Files
mars_nwe_pcab/native/main.c

235 lines
32 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/* SPDX-License-Identifier: GPL-2.0-or-later */
#define _GNU_SOURCE
#include "core.h"
#include "supervisor.h"
#include "admin.h"
#include "directory.h"
#include "identity_api.h"
#include "../src/gateway.h"
#include "../src/ncp_ip.h"
#include "gateway_auto.h"
#include <civetweb.h>
#include <pthread.h>
#include <openssl/crypto.h>
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <netinet/in.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/time.h>
#include <spawn.h>
extern char **environ;
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <errno.h>
#define SESSIONS 128
#define MAX_BODY (MAX_CONF*6)
static pthread_mutex_t api_lock=PTHREAD_MUTEX_INITIALIZER;
static char assets[PATH_MAX]="/usr/local/share/mars-vme/www",port[8]="8787",bind_ip[64]="0.0.0.0",pem[PATH_MAX],extra_host[256];
static int tls,initial_start=1;
static volatile sig_atomic_t quitting;
struct session {char token[65],csrf[65];time_t until,absolute;};
struct attempt {char ip[48];int count;time_t until;};
static struct session sessions[SESSIONS];static struct attempt attempts[256];
static time_t mono(void){struct timespec t;clock_gettime(CLOCK_MONOTONIC,&t);return t.tv_sec;}
static const char *reason(int code){switch(code){case 200:return "OK";case 303:return "See Other";case 400:return "Bad Request";case 401:return "Unauthorized";case 403:return "Forbidden";case 404:return "Not Found";case 405:return "Method Not Allowed";case 409:return "Conflict";case 429:return "Too Many Requests";default:return "Internal Server Error";}}
static int send_data(struct mg_connection*c,int code,const char*type,const char*s,size_t n,const char*cookie,const char*location){mg_printf(c,"HTTP/1.1 %d %s\r\nContent-Type: %s\r\nContent-Length: %zu\r\nConnection: close\r\nCache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\nX-Frame-Options: DENY\r\nReferrer-Policy: no-referrer\r\nContent-Security-Policy: default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'\r\n",code,reason(code),type,n);if(cookie)mg_printf(c,"Set-Cookie: %s\r\n",cookie);if(location)mg_printf(c,"Location: %s\r\n",location);mg_printf(c,"\r\n");if(n)mg_write(c,s,n);return code;}
static int reply(struct mg_connection*c,int code,json_object*o,const char*cookie){const char*s=json_object_to_json_string_ext(o,JSON_C_TO_STRING_PLAIN);int r=send_data(c,code,"application/json; charset=utf-8",s,strlen(s),cookie,NULL);json_object_put(o);return r;}
static int error(struct mg_connection*c,int code,const char*s){json_object*o=json_object_new_object();addstr(o,"error",s);return reply(c,code,o,NULL);}
static int ok(struct mg_connection*c,const char*cookie){json_object*o=json_object_new_object();json_object_object_add(o,"ok",json_object_new_boolean(1));return reply(c,200,o,cookie);}
static int private_ip(const char*s){struct in_addr a;if(inet_pton(AF_INET,s,&a)!=1)return 0;uint32_t x=ntohl(a.s_addr);return (x>>24)==127||(x>>24)==10||(x>>20)==0xac1||(x>>16)==0xc0a8||(x>>16)==0xa9fe;}
static int allowed_host(const char*h){if(!h)return 0;char b[256];if(*extra_host&&!strcmp(h,extra_host))return 1;snprintf(b,sizeof b,"localhost:%s",port);if(!strcmp(h,b))return 1;struct ifaddrs*ifs;if(getifaddrs(&ifs))return 0;int ok=0;for(struct ifaddrs*p=ifs;p;p=p->ifa_next){if(!p->ifa_addr||p->ifa_addr->sa_family!=AF_INET)continue;char ip[INET_ADDRSTRLEN];if(!inet_ntop(AF_INET,&((struct sockaddr_in*)p->ifa_addr)->sin_addr,ip,sizeof ip))continue;snprintf(b,sizeof b,"%s:%s",ip,port);if(!strcmp(h,b))ok=1;}freeifaddrs(ifs);return ok;}
static void cookie_str(char out[256],const char*token){snprintf(out,256,"mars_session=%s; Path=/; HttpOnly; SameSite=Strict; Max-Age=%d%s",token,*token?28800:0,tls?"; Secure":"");}
static struct session* session_get(struct mg_connection*c){const char*h=mg_get_header(c,"Cookie");if(!h)return NULL;char token[65];if(mg_get_cookie(h,"mars_session",token,sizeof token)!=64)return NULL;time_t t=mono();for(int i=0;i<SESSIONS;i++){struct session*s=&sessions[i];if(s->until<=t||s->absolute<=t){memset(s,0,sizeof *s);continue;}if(!CRYPTO_memcmp(s->token,token,64)){s->until=t+1800;return s;}}return NULL;}
static struct session* new_session(void){time_t t=mono();int slot=-1;for(int i=0;i<SESSIONS;i++){if(sessions[i].until<=t||sessions[i].absolute<=t){slot=i;break;}}if(slot<0)return NULL;struct session*s=&sessions[slot];memset(s,0,sizeof *s);if(random_hex(s->token,32)||random_hex(s->csrf,32)){memset(s,0,sizeof *s);return NULL;}s->until=t+1800;s->absolute=t+28800;return s;}
static struct attempt* rate(const char*ip){time_t t=mono();int slot=-1;for(int i=0;i<256;i++){if(attempts[i].until<=t){if(slot<0)slot=i;}else if(!strcmp(attempts[i].ip,ip))return &attempts[i];}if(slot<0)return NULL;struct attempt*a=&attempts[slot];memset(a,0,sizeof *a);snprintf(a->ip,sizeof a->ip,"%s",ip);a->until=t+60;return a;}
static json_object *read_json(struct mg_connection*c,long long n){if(n<=0||n>MAX_BODY)return NULL;const char*ct=mg_get_header(c,"Content-Type");if(!ct||strncmp(ct,"application/json",16)||(ct[16]&&ct[16]!=';'))return NULL;char*b=malloc((size_t)n+1);if(!b)return NULL;size_t off=0;while(off<(size_t)n){int k=mg_read(c,b+off,(size_t)n-off);if(k<=0){free(b);return NULL;}off+=k;}b[n]=0;struct json_tokener*t=json_tokener_new();if(!t){free(b);return NULL;}json_tokener_set_flags(t,JSON_TOKENER_STRICT|JSON_TOKENER_VALIDATE_UTF8);json_object*o=json_tokener_parse_ex(t,b,(int)n);if(json_tokener_get_error(t)!=json_tokener_success||json_tokener_get_parse_end(t)!=(size_t)n||!json_object_is_type(o,json_type_object)){json_object_put(o);o=NULL;}json_tokener_free(t);OPENSSL_cleanse(b,(size_t)n);free(b);return o;}
static json_object *state(struct session*s,const char*current){json_object*o=json_object_new_object();int initial=auth_default();char h[65];sha(current,h);addstr(o,"text",initial?"":current);addstr(o,"revision",h);json_object_object_add(o,"groups",groups(initial?"":current));json_object_object_add(o,"devices",devices());json_object_object_add(o,"validation",validate(initial?"":current));json_object_object_add(o,"backups",initial?json_object_new_array():backups());addstr(o,"path",config_path);json_object_object_add(o,"services",json_object_new_boolean(!no_services&&!initial));addstr(o,"csrf",s->csrf);json_object_object_add(o,"defaultPassword",json_object_new_boolean(initial));return o;}
/* Full before/after comparison. No external shell command or temporary cleartext diff file. */
static char *comparison(const char*a,const char*b){if(!strcmp(a,b))return strdup("");char*s=NULL;if(asprintf(&s,"--- Aktuell (vollständig) ---\n%s\n+++ Entwurf (vollständig) +++\n%s",a,b)<0)return NULL;return s;}
static int confirm(json_object*r){json_object*v=get(r,"confirm");return json_object_is_type(v,json_type_boolean)&&json_object_get_boolean(v);}
static int config_valid(const char*s){json_object*v=validate(s);int ok=json_object_array_length(get(v,"errors"))==0;json_object_put(v);return ok;}
/* Gateway configuration is independent of nwserv.conf, but references its saved IPX network. */
/* NCP/IP settings are separate from the IPX gateway; only admin may change them. */
static int ncp_ip_api(struct mg_connection*c,int post,json_object*req){
if(auth_default()||no_services)return error(c,403,"Zuerst MARS einrichten und Web-Kennwort ändern.");
char *old=read_file(NCP_IP_CONFIG,4096,1);int missing=!old&&errno==ENOENT;
if(missing)old=strdup("{\"enabled\":false,\"address\":\"\"}");
if(!old)return error(c,500,"TCP/IP-Konfiguration nicht lesbar. Dateirechte prüfen.");
char rev[65];sha(old,rev);struct json_tokener *tok=json_tokener_new();json_object *cfg=NULL;size_t oldlen=strlen(old);if(tok){json_tokener_set_flags(tok,JSON_TOKENER_STRICT);cfg=json_tokener_parse_ex(tok,old,(int)oldlen);if(json_tokener_get_error(tok)!=json_tokener_success||json_tokener_get_parse_end(tok)!=oldlen){json_object_put(cfg);cfg=NULL;}json_tokener_free(tok);}free(old);
uint32_t addr,mask;int valid=ncp_ip_config(cfg,&addr,&mask);
if(post){const char *r=js(req,"revision");if(!r||strcmp(r,rev)){json_object_put(cfg);return error(c,409,"Konfiguration wurde geändert. Neu laden.");}
json_object *next=get(req,"config");if(!confirm(req)||ncp_ip_config(next,&addr,&mask)<0){json_object_put(cfg);return error(c,400,"Eine vorhandene private IPv4-Adresse auswählen und bestätigen.");}
json_object *save=json_object_new_object();json_object_object_add(save,"enabled",json_object_new_boolean(json_object_get_boolean(get(next,"enabled"))));addstr(save,"address",js(next,"address")?js(next,"address"):"");json_object_object_add(save,"slp",json_object_new_boolean(json_object_get_boolean(get(next,"slp"))));
const char *str=json_object_to_json_string_ext(save,JSON_C_TO_STRING_PLAIN);int rc=atomic_write(NCP_IP_CONFIG,str,strlen(str),0600);json_object_put(save);json_object_put(cfg);if(rc)return error(c,500,"TCP/IP-Einstellung konnte nicht gespeichert werden.");return ok(c,NULL);
}
json_object *out=json_object_new_object();json_object_object_add(out,"config",cfg?cfg:json_object_new_object());addstr(out,"revision",rev);json_object_object_add(out,"valid",json_object_new_boolean(valid>=0));json_object_object_add(out,"addresses",ncp_ip_addresses());json_object_object_add(out,"port",json_object_new_int(NCP_TCP_PORT));json_object_object_add(out,"nativeNds",json_object_new_boolean(0));char *runtime=read_file(NCP_IP_STATUS,1024,1);struct stat rst;int fresh=runtime&&!stat(NCP_IP_STATUS,&rst)&&time(NULL)>=rst.st_mtime&&time(NULL)-rst.st_mtime<5;addstr(out,"runtime",fresh?runtime:"Kein aktueller TCP/IP-Status. NetWare starten bzw. neu starten.");free(runtime);return reply(c,200,out,NULL);
}
static int gateway_network_exists(uint32_t net){char*conf=read_file(config_path,MAX_CONF,0);if(!conf)return 0;json_object*g=groups(conf);free(conf);json_object*a=get(g,"4");int found=0;for(size_t i=0;i<json_object_array_length(a);i++){const char*s=json_object_get_string(json_object_array_get_idx(a,i));char *end;unsigned long n=strtoul(s,&end,0);if(end!=s&&(*end==' '||*end=='\t')&&n==ntohl(net)){found=1;break;}}json_object_put(g);return found;}
static int gateway_api(struct mg_connection*c,int post,json_object*req,int detect){
if(auth_default()||no_services)return error(c,403,"Gateway nur im eingerichteten Dienstmodus verfügbar.");
char *old=read_file(GW_CONFIG,16384,1);int configured=old!=NULL;json_object*current=NULL;
if(!old){if(errno!=ENOENT)return error(c,500,"Gateway-Konfiguration nicht lesbar; Linux-Konsole prüfen.");current=gw_default();old=strdup(json_object_to_json_string_ext(current,JSON_C_TO_STRING_PLAIN));}else current=json_tokener_parse(old);
if(!old||!current){free(old);json_object_put(current);return error(c,500,"Gateway-Konfiguration ungültig.");}
char rev[65];sha(old,rev);
if(detect){char err[512];char*conf=read_file(config_path,MAX_CONF,0);if(!conf)snprintf(err,sizeof err,"NetWare-Konfiguration nicht lesbar.");json_object*out=conf?ga_detect(conf,current,err,sizeof err):NULL;free(conf);free(old);json_object_put(current);if(!out)return error(c,400,err);return reply(c,200,out,NULL);}
if(post){const char*given=js(req,"revision");json_object*next=get(req,"config");struct gw_config cfg;char msg[256];int code=0;
if(!given||strcmp(given,rev)){snprintf(msg,sizeof msg,"Gateway-Konfiguration inzwischen geändert.");code=409;}
else if(!confirm(req)){snprintf(msg,sizeof msg,"Änderung bestätigen.");code=400;}
else if(gw_parse(next,&cfg,msg,sizeof msg))code=400;
else if(cfg.enabled&&(!gateway_network_exists(cfg.net)||!if_nametoindex(cfg.uplink))){snprintf(msg,sizeof msg,"Gespeichertes externes IPX-Netz und vorhandenen Uplink wählen.");code=400;}
else{const char*text=json_object_to_json_string_ext(next,JSON_C_TO_STRING_PLAIN);if(strlen(text)>16384){snprintf(msg,sizeof msg,"Konfiguration zu groß.");code=400;}else if(atomic_write(GW_CONFIG ".previous",old,strlen(old),0600)||atomic_write(GW_CONFIG,text,strlen(text),0600)){snprintf(msg,sizeof msg,"Gateway-Konfiguration konnte nicht gesichert/geschrieben werden.");code=500;}}
free(old);json_object_put(current);if(code)return error(c,code,msg);return ok(c,NULL);
}
json_object*result=json_object_new_object();json_object_object_add(result,"config",current);json_object_object_add(result,"configured",json_object_new_boolean(configured));addstr(result,"revision",rev);free(old);
char *snapshot=read_file(GW_STATUS,16384,1);struct stat st;int fresh=snapshot&&!stat(GW_STATUS,&st)&&time(NULL)-st.st_mtime>=0&&time(NULL)-st.st_mtime<4;
char *seen=read_file(GW_DISCOVERY,16384,1);struct stat ds;json_object*peers=seen&&!stat(GW_DISCOVERY,&ds)&&time(NULL)-ds.st_mtime>=0&&time(NULL)-ds.st_mtime<4?json_tokener_parse(seen):NULL;free(seen);if(!json_object_is_type(peers,json_type_array)){json_object_put(peers);peers=json_object_new_array();}json_object_object_add(result,"observed",peers);
addstr(result,"status",fresh?snapshot:"Kein aktueller Gateway-Status. Dateiserver/Dispatcher starten oder Journal prüfen.");free(snapshot);
return reply(c,200,result,NULL);
}
/* Browser administration through a local, owner-only Unix socket. */
static int browser_api(struct mg_connection*c,int post,json_object*req){
if(auth_default()||no_services)return error(c,403,"Kennwort ändern oder Dienstmodus verwenden.");
if(post&&!confirm(req))return error(c,400,"Aktion bestätigen.");
if(post&&js(req,"op")&&!strcmp(js(req,"op"),"update")){
pid_t pid;char *args[]={"/usr/bin/systemctl","start","--no-block","mars-browser-update-now.service",NULL};int status;
if(posix_spawn(&pid,args[0],NULL,NULL,args,environ)||waitpid(pid,&status,0)<0||!WIFEXITED(status)||WEXITSTATUS(status))return error(c,500,"Update-Dienst konnte nicht gestartet werden.");
return ok(c,NULL);
}
int fd=socket(AF_UNIX,SOCK_STREAM|SOCK_CLOEXEC,0);if(fd<0)return error(c,500,"Browser-Socket fehlt.");
struct timeval timeout={15,0};setsockopt(fd,SOL_SOCKET,SO_RCVTIMEO,&timeout,sizeof timeout);setsockopt(fd,SOL_SOCKET,SO_SNDTIMEO,&timeout,sizeof timeout);
struct sockaddr_un a={.sun_family=AF_UNIX,.sun_path="/run/mars-browser/admin.sock"};
if(connect(fd,(struct sockaddr*)&a,sizeof a)){close(fd);return error(c,500,"Browsermodul nicht installiert, wird gestartet oder ist ausgefallen. mars_vme-Journal prüfen.");}
const char*body=post?json_object_to_json_string_ext(req,JSON_C_TO_STRING_PLAIN):"{\"op\":\"get\"}";
size_t n=strlen(body),off=0;if(n>16000){close(fd);return error(c,400,"Anfrage zu groß.");}
while(off<n){ssize_t k=send(fd,body+off,n-off,MSG_NOSIGNAL);if(k<=0)break;off+=(size_t)k;}
if(off!=n||send(fd,"\n",1,MSG_NOSIGNAL)!=1){close(fd);return error(c,500,"Browserdienst nicht erreichbar.");}
char *b=malloc(65536);if(!b){close(fd);return error(c,500,"Speicher fehlt.");}off=0;while(off<65535){ssize_t k=recv(fd,b+off,65535-off,0);if(k<=0)break;off+=(size_t)k;if(memchr(b,'\n',off))break;}close(fd);b[off]=0;
if(!memchr(b,'\n',off)){free(b);return error(c,500,"Browserdienst: unvollständige Antwort.");}
json_object *res=json_tokener_parse(b);free(b);if(!res||!json_object_is_type(res,json_type_object)){json_object_put(res);return error(c,500,"Browserdienst: ungültige Antwort.");}
return reply(c,get(res,"error")?400:200,res,NULL);
}
static int process(struct mg_connection*c,const struct mg_request_info*r,json_object*req){const char*u=r->local_uri;int post=!strcmp(r->request_method,"POST");struct session*s=session_get(c);char cookie[256];if(post&&!strcmp(u,"/api/login")){struct attempt*a=rate(r->remote_addr);if(!a||a->count>=5)return error(c,429,"Zu viele Versuche. Eine Minute warten.");const char*user=js(req,"user");if(!user||strcmp(user,"admin")||!auth_verify(js(req,"password"))){a->count++;return error(c,401,"Anmeldung fehlgeschlagen.");}a->count=0;if(!(s=new_session()))return error(c,429,"Zu viele aktive Sitzungen.");cookie_str(cookie,s->token);return ok(c,cookie);}
const char*file=NULL,*type=NULL;if(!post){if(!strcmp(u,"/login")){file="login.html";type="text/html";}else if(!strcmp(u,"/login.js")){file="login.js";type="text/javascript";}else if(!strcmp(u,"/style.css")){file="style.css";type="text/css";}}
if(!file&&!s){if(!strcmp(u,"/"))return send_data(c,303,"text/plain","",0,NULL,"/login");return error(c,401,"Anmeldung erforderlich.");}
if(post){const char*csrf=mg_get_header(c,"X-Mars-CSRF");if(!csrf||strlen(csrf)!=64||CRYPTO_memcmp(csrf,s->csrf,64))return error(c,403,"CSRF-Prüfung fehlgeschlagen.");if(!strcmp(u,"/api/logout")){memset(s,0,sizeof *s);cookie_str(cookie,"");return ok(c,cookie);}if(!strcmp(u,"/api/password")){const char*next=js(req,"new"),*rep=js(req,"repeat");if(!auth_verify(js(req,"current"))||!next||!rep||strcmp(next,rep)||auth_set(next,0))return error(c,400,"Aktuelles Kennwort prüfen; neues Kennwort 10–256 Zeichen, zweimal identisch.");memset(sessions,0,sizeof sessions);cookie_str(cookie,"");return ok(c,cookie);}if(auth_default())return error(c,403,"Zuerst das Web-Standardkennwort ändern.");}
if(!post&&!file){if(!strcmp(u,"/")){file="index.html";type="text/html";}else if(!strcmp(u,"/app.js")){file="app.js";type="text/javascript";}}
if(file){char*p=NULL;asprintf(&p,"%s/%s",assets,file);char*d=p?read_file(p,MAX_CONF,0):NULL;free(p);if(!d)return error(c,404,"Datei fehlt.");char mime[64];snprintf(mime,sizeof mime,"%s; charset=utf-8",type);int code=send_data(c,200,mime,d,strlen(d),NULL,NULL);free(d);return code;}
if(post&&!strcmp(u,"/api/drivers/activate")){
if(no_services||!confirm(req))return error(c,400,"Dienstmodus und Bestätigung erforderlich.");
json_object *platforms=get(req,"platforms");
if(!json_object_is_type(platforms,json_type_array)||json_object_array_length(platforms)<1||json_object_array_length(platforms)>6)return error(c,400,"Mindestens ein Betriebssystem wählen.");
pid_t pid;int status;char *args[18]={"/usr/local/libexec/mars-install-drivers","--packages","/usr/local/share/mars-vme/driver-packages"};int ac=3;
for(size_t i=0;i<json_object_array_length(platforms);i++){
const char *os=json_object_get_string(json_object_array_get_idx(platforms,i));
if(!os||(strcmp(os,"WIN95")&&strcmp(os,"WIN98")&&strcmp(os,"WINME")&&strcmp(os,"WINNT40")&&strcmp(os,"WIN2000")&&strcmp(os,"WINXP")))return error(c,400,"Unbekanntes Betriebssystem.");
args[ac++]="--os";args[ac++]=(char*)os;
}
args[ac]=NULL;
if(posix_spawn(&pid,args[0],NULL,NULL,args,environ))return error(c,500,"Treiber-Installer fehlt. DEB oder install.sh aktualisieren.");
pid_t done;do{done=waitpid(pid,&status,0);}while(done<0&&errno==EINTR);
if(done!=pid||!WIFEXITED(status)||WEXITSTATUS(status))return error(c,500,"Bereitstellung fehlgeschlagen: SYS/PUBLIC einrichten; Details im Dienstjournal.");
return ok(c,NULL);
}
if(!post&&!strcmp(u,"/api/drivers")){
char path[PATH_MAX];snprintf(path,sizeof path,"%s/drivers/enabled.json",assets);char *data=read_file(path,4096,0);
json_object *result=data?json_tokener_parse(data):NULL;free(data);
if(!result)result=json_tokener_parse("{\"platforms\":[],\"map\":\"\"}");
return reply(c,200,result,NULL);
}
/* DOS helpers: fixed profile combinations, authenticated like the UI. */
if(!post&&!strncmp(u,"/dos/",5)){
if(auth_default())return error(c,403,"Kennwort ändern.");
const char *oses[]={"ms5","ms6","ms7","pc","dr","free",NULL};
const char *clients[]={"netx","vlm","client32",NULL};
for(int i=0;oses[i];i++)for(int j=0;clients[j];j++){
char name[48];snprintf(name,sizeof name,"%s-%s.zip",oses[i],clients[j]);
if(!strcmp(u+5,name)){char path[PATH_MAX];struct stat st;
if(snprintf(path,sizeof path,"%s/dos/%s",assets,name)>=(int)sizeof path||lstat(path,&st)||!S_ISREG(st.st_mode))return error(c,404,"Installationshilfe nicht installiert.");
mg_send_file(c,path);return 200;
}
}
return error(c,404,"Unbekanntes Clientprofil.");
}
/* Fixed allowlist only; never interpolate a request path into the filesystem. */
if(!post&&!strncmp(u,"/drivers/",9)){
if(auth_default())return error(c,403,"Kennwort ändern.");
static const char *names[]={"WIN95.zip","WIN98.zip","WINME.zip","WINNT40.zip","WIN2000.zip","WINXP.zip",NULL};
for(int i=0;names[i];i++)if(!strcmp(u+9,names[i])){
char settings[PATH_MAX];snprintf(settings,sizeof settings,"%s/drivers/enabled.json",assets);
char *data=read_file(settings,4096,0);json_object *enabled=data?json_tokener_parse(data):NULL;free(data);int allowed=0;
json_object *list=get(enabled,"platforms");
if(json_object_is_type(list,json_type_array))for(size_t j=0;j<json_object_array_length(list);j++){
const char *os=json_object_get_string(json_object_array_get_idx(list,j));char name[32];snprintf(name,sizeof name,"%s.zip",os?os:"");if(!strcmp(name,names[i]))allowed=1;
}
json_object_put(enabled);if(!allowed)return error(c,404,"Treiberpaket nicht freigegeben.");
char path[PATH_MAX];struct stat st;
if(snprintf(path,sizeof path,"%s/drivers/%s",assets,names[i])>=(int)sizeof path||lstat(path,&st)||!S_ISREG(st.st_mode))return error(c,404,"Treiberpaket nicht installiert.");
mg_send_file(c,path);return 200;
}
return error(c,404,"Unbekanntes Treiberpaket.");
}
if(!post){
const char *routes[]={"/api/browser/client-windows","/api/browser/client-linux","/api/browser/client-macclassic","/api/browser/client-macclassic-source","/api/browser/mac-opentransport"};
const char *files[]={"windows-x86.zip","linux-x11.zip","macclassic-powerpc.zip","macclassic-powerpc-source.zip","Open-Transport-1-3-1.iso.zip"};
for(size_t i=0;i<sizeof(routes)/sizeof(routes[0]);i++)if(!strcmp(u,routes[i])){
if(auth_default())return error(c,403,"Kennwort ändern.");
char path[512];snprintf(path,sizeof path,"/usr/local/share/mars-vme/browser/%s",files[i]);
if(access(path,R_OK))return error(c,404,"Browser-Paket nicht installiert.");
mg_send_file(c,path);return 200;
}
}
if(!post&&!strcmp(u,"/api/browser/client-source")){
if(auth_default())return error(c,403,"Kennwort ändern.");
const char *p="/usr/local/share/mars-vme/browser-client-source.zip";
if(access(p,R_OK))return error(c,404,"Browser-Quellpaket noch nicht installiert.");
mg_send_file(c,p);return 200;
}
if(!strcmp(u,"/api/identities")){
if(auth_default()||no_services)return error(c,403,"Eingerichteter Dienstmodus erforderlich.");
if(!post)return reply(c,200,identity_status(),NULL);
if(!confirm(req)||!js(req,"op")||strcmp(js(req,"op"),"create"))return error(c,400,"Bestätigte Benutzeranlage erforderlich.");
json_object *out=identity_create(req);return reply(c,get(out,"error")?400:200,out,NULL);
}
if(!strcmp(u,"/api/directory")){
if(auth_default())return error(c,403,"Zuerst das Web-Kennwort ändern.");
char path[PATH_MAX],rev[65];int configured;
if(snprintf(path,sizeof path,"%s.directory.json",config_path)>=(int)sizeof path)return error(c,500,"Verzeichnispfad zu lang.");
json_object *dir=directory_read(path,rev,&configured);if(!dir)return error(c,500,"Verzeichnisdatei ungültig oder nicht lesbar. Sicherung prüfen.");
if(post){json_object *next=get(req,"config");json_object *errs=directory_validate(next);if(json_object_array_length(errs)){json_object *o=json_object_new_object();addstr(o,"error","Verzeichnisentwurf ungültig.");json_object_object_add(o,"errors",errs);json_object_put(dir);return reply(c,400,o,NULL);}json_object_put(errs);
int rc=confirm(req)?directory_save(path,next,js(req,"revision")):-3;json_object_put(dir);if(rc)return error(c,rc==-2?409:rc==-3?400:500,rc==-2?"Verzeichnis wurde inzwischen geändert. Neu laden.":"Verzeichnis konnte nicht gespeichert werden; Entwurf und Bestätigung prüfen.");return ok(c,NULL);}
char *conf=read_file(config_path,MAX_CONF,0);if(!conf){json_object_put(dir);return error(c,500,"nwserv.conf nicht lesbar.");}json_object *query=json_object_new_object();addstr(query,"op","objects");json_object *live=no_services?NULL:bindery_call(query);json_object_put(query);json_object *o=directory_report(conf,dir,live,!no_services&&supervisor_config_matches());free(conf);json_object_put(live);json_object_object_add(o,"config",dir);addstr(o,"revision",rev);json_object_object_add(o,"configured",json_object_new_boolean(configured));json_object_object_add(o,"status",supervisor_status());return reply(c,200,o,NULL);
}
if(!strcmp(u,"/api/browser"))return browser_api(c,post,req);
if(!strcmp(u,"/api/ncp-ip"))return ncp_ip_api(c,post,req);
if(!strcmp(u,"/api/gateway"))return gateway_api(c,post,req,0);
if(!post&&!strcmp(u,"/api/gateway/detect"))return gateway_api(c,0,NULL,1);
if(!post&&!strcmp(u,"/api/status"))return reply(c,200,supervisor_status(),NULL);
if(!post&&!strcmp(u,"/api/monitor")){if(auth_default())return error(c,403,"Kennwort ändern.");return reply(c,200,monitor_data(),NULL);}
if(!strcmp(u,"/api/bindery")||!strcmp(u,"/api/print")){if(auth_default()||no_services)return error(c,403,"Kennwort ändern oder Dienstmodus verwenden.");if(!post)return error(c,405,"POST erforderlich.");const char *op=js(req,"op");if(!op)return error(c,400,"Aktion fehlt.");const char *unixname=js(req,"unix");if(!strcmp(u,"/api/bindery")&&unixname&&!strncmp(unixname,"marsv",5)&&(!strcmp(op,"create-user")||!strcmp(op,"map-user")))return error(c,400,"Reservierte SQLite-Identitäten nur über die geführte Benutzeranlage verwenden.");if(!strncmp(op,"trustee-",8)&&!supervisor_config_matches())return error(c,409,"Konfiguration seit Serverstart geändert. Dateiserver neu starten.");int readonly=!strcmp(op,"sessions")||!strcmp(op,"objects")||!strcmp(op,"properties")||!strcmp(op,"list")||!strcmp(op,"script-get")||!strcmp(op,"trustee-get")||!strcmp(op,"group-members");if(!readonly&&!confirm(req))return error(c,400,"Aktion bestätigen.");json_object *res=!strcmp(u,"/api/bindery")?bindery_call(req):print_call(req);return reply(c,get(res,"error")?400:200,res,NULL);}
char*current=read_file(config_path,MAX_CONF,0);if(!current)return error(c,500,"nwserv.conf nicht lesbar.");char rev[65];sha(current,rev);int ret=404;
if(!post&&!strcmp(u,"/api/state")){ret=reply(c,200,state(s,current),NULL);goto done;}if(!post&&!strcmp(u,"/api/download")){if(auth_default())ret=error(c,403,"Kennwort ändern.");else ret=send_data(c,200,"text/plain; charset=utf-8",current,strlen(current),NULL,NULL);goto done;}
if(!post){ret=error(c,404,"Nicht gefunden.");goto done;}const char*given=js(req,"revision");if(!given||strcmp(given,rev)){ret=error(c,409,"Konfiguration geändert. Bitte neu laden.");goto done;}
if(!strcmp(u,"/api/service")){const char*a=js(req,"action");if(!confirm(req)||!a||no_services||((!strcmp(a,"start")||!strcmp(a,"restart"))&&!config_valid(current))||supervisor_request(a)){ret=error(c,400,"Aktion nicht erlaubt oder Konfiguration ungültig.");goto done;}ret=reply(c,200,supervisor_status(),NULL);goto done;}
if(strcmp(u,"/api/preview")&&strcmp(u,"/api/save")){ret=error(c,404,"Nicht gefunden.");goto done;}const char*mode=js(req,"mode");char*candidate=NULL;if(mode&&!strcmp(mode,"guided"))candidate=merge(current,get(req,"groups"));else if(mode&&!strcmp(mode,"raw")){const char*t=js(req,"text");if(t&&strlen(t)<=MAX_CONF)candidate=strdup(t);}else if(mode&&!strcmp(mode,"backup"))candidate=backup_read(js(req,"name"));if(!candidate){ret=error(c,400,"Ungültiger Entwurf oder Backup.");goto done;}
json_object*v=validate(candidate);char hash[65];sha(candidate,hash);if(!strcmp(u,"/api/preview")){char*d=comparison(current,candidate);if(!d){json_object_put(v);ret=error(c,500,"Vorschau fehlgeschlagen.");}else{addstr(v,"candidate",candidate);addstr(v,"candidateHash",hash);addstr(v,"diff",d);free(d);ret=reply(c,200,v,NULL);}}else{const char*h=js(req,"candidateHash");if(json_object_array_length(get(v,"errors"))||!confirm(req)||!h||strcmp(h,hash)){ret=error(c,400,"Entwurf zuerst prüfen und bestätigen.");}else{char name[64];int rc=save_conf(current,rev,candidate,name);if(rc)ret=error(c,rc==-2?409:500,"Speichern fehlgeschlagen; Datei oder Backup prüfen.");else{json_object*o=json_object_new_object();addstr(o,"backup",name);json_object_object_add(o,"state",state(s,candidate));ret=reply(c,200,o,NULL);}}json_object_put(v);}free(candidate);
done:free(current);return ret;}
static int handle(struct mg_connection*c,void*data){(void)data;const struct mg_request_info*r=mg_get_request_info(c);const char*h=mg_get_header(c,"Host");if(!r||!r->local_uri||!private_ip(r->remote_addr)||!allowed_host(h))return error(c,403,"Host oder Clientnetz nicht erlaubt.");int post=!strcmp(r->request_method,"POST");if(!post&&strcmp(r->request_method,"GET"))return error(c,405,"Methode nicht erlaubt.");json_object*req=NULL;if(post){char expected[300];snprintf(expected,sizeof expected,"%s://%s",tls?"https":"http",h);const char*origin=mg_get_header(c,"Origin");if(!origin||strcmp(origin,expected))return error(c,403,"Origin-Prüfung fehlgeschlagen.");req=read_json(c,r->content_length);if(!req)return error(c,400,"Ungültiges JSON oder Anfragegröße.");}pthread_mutex_lock(&api_lock);int result=process(c,r,req);pthread_mutex_unlock(&api_lock);json_object_put(req);return result;}
static int begin_request(struct mg_connection*c){return handle(c,NULL);}
static void on_signal(int s){(void)s;quitting=1;}
static int set_path(char*d,size_t cap,const char*s){if(!s||strlen(s)>=cap)return -1;strcpy(d,s);return 0;}
static void usage(void){fprintf(stderr,"mars_vme [--config PATH] [--www PATH] [--bind IPv4] [--port N] [--pem PATH] [--host HOST:PORT] [--no-autostart] [--no-services] [--reset-password]\n");}
int main(int argc,char**argv){strcpy(config_path,"/usr/local/etc/mars_nwe/nwserv.conf");int reset=0;for(int i=1;i<argc;i++){char *a=argv[i],*v=i+1<argc?argv[i+1]:NULL;int bad=0;if(!strcmp(a,"--no-autostart"))initial_start=0;else if(!strcmp(a,"--no-services")){no_services=1;initial_start=0;}else if(!strcmp(a,"--reset-password"))reset=1;else if(!strcmp(a,"--config")){bad=set_path(config_path,sizeof config_path,v);i++;}else if(!strcmp(a,"--www")){bad=set_path(assets,sizeof assets,v);i++;}else if(!strcmp(a,"--bind")){bad=set_path(bind_ip,sizeof bind_ip,v);i++;}else if(!strcmp(a,"--port")){bad=set_path(port,sizeof port,v);i++;}else if(!strcmp(a,"--pem")){bad=set_path(pem,sizeof pem,v);i++;}else if(!strcmp(a,"--host")){bad=set_path(extra_host,sizeof extra_host,v);i++;}else{usage();return 2;}if(bad){usage();return 2;}}
struct in_addr addr;char*end;long pn=strtol(port,&end,10);if(*end||pn<1024||pn>65535||inet_pton(AF_INET,bind_ip,&addr)!=1||config_path[0]!='/'||assets[0]!='/'){usage();return 2;}if(!no_services&&(geteuid()!=0||strcmp(config_path,"/usr/local/etc/mars_nwe/nwserv.conf"))){fprintf(stderr,"NetWare-Dienststeuerung benötigt root und Standard-Konfigurationspfad. Für Tests --no-services.\n");return 1;}umask(0077);char*parent=strdup(config_path);char*slash=strrchr(parent,'/');*slash=0;if(snprintf(auth_path,sizeof auth_path,"%s/.mars-web-auth.json",parent)>=(int)sizeof auth_path||snprintf(backup_dir,sizeof backup_dir,"%s/.mars-web-backups",parent)>=(int)sizeof backup_dir){free(parent);return 2;}char*lockname=NULL;asprintf(&lockname,"%s/.mars-vme.lock",parent);free(parent);int lockfd=open(lockname,O_CREAT|O_RDWR|O_CLOEXEC|O_NOFOLLOW,0600);free(lockname);if(lockfd<0||flock(lockfd,LOCK_EX|LOCK_NB)){fprintf(stderr,"Andere mars_vme-Instanz aktiv oder Lock nicht zugänglich.\n");return 1;}char*conf=read_file(config_path,MAX_CONF,0);if(!conf||auth_init()){fprintf(stderr,"Konfiguration oder Kennwortdatei nicht lesbar.\n");free(conf);return 1;}
if(reset){char*pw=getpass("Neues Web-Kennwort: ");char*first=pw?strdup(pw):NULL;pw=getpass("Wiederholen: ");int rc=!first||!pw||strcmp(first,pw)||auth_set(first,0);if(first){OPENSSL_cleanse(first,strlen(first));free(first);}free(conf);return rc?1:0;}
tls=*pem!=0;char listen[128];snprintf(listen,sizeof listen,"%s:%s%s",bind_ip,port,tls?"s":"");const char*options[24];int k=0;options[k++]="listening_ports";options[k++]=listen;options[k++]="num_threads";options[k++]="4";options[k++]="request_timeout_ms";options[k++]="10000";options[k++]="enable_keep_alive";options[k++]="no";options[k++]="enable_directory_listing";options[k++]="no";/* no document_root: only explicitly mapped assets */if(tls){options[k++]="ssl_certificate";options[k++]=pem;options[k++]="ssl_protocol_version";options[k++]="4";}options[k]=NULL;signal(SIGINT,on_signal);signal(SIGTERM,on_signal);signal(SIGPIPE,SIG_IGN);if(tls&&!(mg_init_library(MG_FEATURES_TLS)&MG_FEATURES_TLS)){fprintf(stderr,"CivetWeb TLS nicht verfügbar.\n");free(conf);return 1;}if(!tls)mg_init_library(0);struct mg_callbacks cb={0};cb.begin_request=begin_request;struct mg_context*ctx=mg_start(&cb,NULL,options);if(!ctx){fprintf(stderr,"CivetWeb Start fehlgeschlagen.\n");free(conf);mg_exit_library();return 1;}fprintf(stderr,"mars_vme: %s://%s:%s (CivetWeb); %s\n",tls?"https":"http",bind_ip,port,auth_default()?"Initialkennwort aktiv":"Kennwort eingerichtet");if(initial_start&&config_valid(conf))supervisor_request("start");else if(initial_start)fprintf(stderr,"NetWare wartet auf gültige Einrichtung.\n");free(conf);while(!quitting){supervisor_tick();usleep(100000);}mg_stop(ctx);supervisor_shutdown();mg_exit_library();close(lockfd);return 0;}