int main(int argc, char *argv[]) { int i, foreground, port; void (*timeseal_init)(const char * ) = chessd_function("timeseal_init"); int (*net_init)(int ) = chessd_function("net_init"); void (*initial_load)(void ) = chessd_function("initial_load"); void (*db_connect)(void ) = chessd_function("db_connect"); void (*db_disconnect)(void ) = chessd_function("db_disconnect"); port = DEFAULT_PORT; foreground = 0; /* enable malloc checking in libc */ setenv("MALLOC_CHECK_", "2", 1); while((i = getopt(argc, argv, "p:fR:T:")) != -1) { switch(i) { case 'p': port = atoi(optarg); break; case 'f': foreground = 1; break; case 'T': timeseal_init(optarg); break; case 'R': do_chroot(optarg); break; default: usage(); } } if (!foreground && daemonize()){ printf("Problem with Daemonization - Aborting\n"); exit(1); } signal(SIGTERM, TerminateServer); signal(SIGSEGV, segv_handler); signal(SIGBUS, segv_handler); signal(SIGINT, TerminateServer); signal(SIGPIPE, BrokenPipe); if (net_init(port)) { fprintf(stderr, "CHESSD: Network initialize failed on port %d.\n", port); exit(1); } fprintf(stderr, "CHESSD: Initialized on port %d\n", port); initial_load(); db_connect(); main_event_loop(); db_disconnect(); /* will never get here - uses TerminateServer */ return 0; }
int main (int argc, char**argv) { int ret = 0; int heartbeat_usec = 50000; //20Hz is ok by default uint64_t last_beat = 0; Log_info ("cloudvpn starting"); Log (0, "You are using CloudVPN, which is Free software."); Log (0, "For more information please see the GNU GPL license,"); Log (0, "which you should have received along with this program."); setup_sighandler (kill_cloudvpn); /* * initialization */ if (!config_parse (argc, argv) ) { Log_error ("failed to parse config, terminating."); ret = 1; goto failed_config; } if (!config_get_int ("heartbeat", heartbeat_usec) ) heartbeat_usec = 50000; Log_info ("heartbeat is set to %d usec", heartbeat_usec); timestamp_update(); //get initial timestamp status_init(); route_init(); squeue_init(); network_init(); if (poll_init() ) { Log_fatal ("poll initialization failed"); ret = 2; goto failed_poll; } if (do_memlock() ) { Log_fatal ("locking process to memory failed"); ret = 3; goto failed_poll; } if (comm_load() ) { Log_fatal ("failed to load comm data"); ret = 4; goto failed_poll; } if (comm_init() ) { Log_fatal ("communication initialization failed"); ret = 5; goto failed_comm; } if (gate_init() ) { Log_fatal ("gate initialization failed"); ret = 6; goto failed_gate; } if (do_chroot() ) { Log_fatal ("chrooting failed"); ret = 7; goto failed_sec; } if (do_switch_user() ) { Log_fatal ("user switch failed"); ret = 8; goto failed_sec; } /* * main loop */ Log_info ("initialization complete, entering main loop"); last_beat = 0; //update immediately. while (!g_terminate) { timestamp_update(); if ( (timestamp() - last_beat) < (unsigned int) heartbeat_usec) { //poll more stuff poll_wait_for_event (heartbeat_usec - timestamp() + last_beat); //send the results comm_flush_data(); gate_flush_data(); continue; } last_beat = timestamp(); gate_periodic_update(); comm_periodic_update(); route_periodic_update(); status_try_export(); } /* * deinitialization */ Log_info ("shutting down"); failed_sec: gate_shutdown(); failed_gate: comm_shutdown(); failed_comm: if (poll_deinit() ) Log_warn ("poll_deinit somehow failed!"); failed_poll: failed_config: if (!ret) Log_info ("cloudvpn exiting gracefully"); else Log_error ("cloudvpn exiting with code %d", ret); return ret; }
int bootup_main(int argc, char **argv) { FILE *fp; DIR *dp; struct dirent *dt; int t=0, rc; char cmd[1024], buf[1024], name[1024]; time_t curtime; struct tm *loctime; signal(SIGINT,SIG_IGN); putenv("PATH=/bin"); putenv("TERM=linux"); umask(0770); chdir("/"); putchar('\n'); print_banner(); putchar('\n'); xsystem("mount -t proc -o ro virtual /proc"); xsystem("mount -t sysfs -o ro virtual /sys"); // STAGE 1 calculate_mem(); fprintf_stdout("* Creating Mybox filesystem (%d kB) on shared memory...\n",RAMSIZE); xsystem("mount -t tmpfs -o \"rw,size=%dk\" virtual /ramd",RAMSIZE); chmod("/ramd",S_IREAD | S_IWRITE | S_IEXEC); chdir("/ramd"); if((dp=opendir("/")) == NULL) { perror("opendir"); exit(1); } while((dt=readdir(dp))!=NULL) { if(!strcmp(dt->d_name,".") || !strcmp(dt->d_name,"..") || !strcmp(dt->d_name,"lost+found") || !strcmp(dt->d_name,"ramd") || !strcmp(dt->d_name,"proc") || !strcmp(dt->d_name,"dev") || !strcmp(dt->d_name,"sys")) continue; xsystem("cp -dpR /%s /ramd/",dt->d_name); } closedir(dp); xmkdir("dev/pts"); xmkdir("initrd"); umount("/proc"); umount("/sys"); // STAGE 2 rc=pivot_root(".","initrd"); if(rc==-1) { fprintf_stdout("#### ERROR: Change root file system failed!\n"); exit(1); } chdir("/"); xmkdir("proc"); xmkdir("sys"); xsystem("mount -t proc -o rw virtual /proc"); xsystem("mount -t sysfs -o rw virtual /sys"); save_to_file("/proc/sys/kernel/printk","0 0 0 0\n"); if((dp=opendir("/tmp")) == NULL) { perror("opendir"); exit(1); } fprintf_stdout("-> Extracting base tools: "); while((dt=readdir(dp))!=NULL) { if(!strcmp(dt->d_name,".") || !strcmp(dt->d_name,"..")) continue; if(strstr(dt->d_name,".mpk")) { fprintf_stdout("#"); xsystem("tar -C / -axf /tmp/%s",dt->d_name); } } free(dt); closedir(dp); fprintf_stdout("\r* Extracting base tools. Done.%s\n",SPACE); save_to_file("/proc/sys/kernel/modprobe","/bin/modprobe\n"); xsystem("depmod -a"); // STAGE 3 chdir("/"); xsystem("mdev -s"); xsystem("mount -t devpts /dev/devpts /dev/pts -o \"rw,gid=0,mode=620\""); rename("/dev/random","/dev/random-block"); symlink("/dev/urandom","/dev/random"); xsystem("chmod 700 *"); if((fp=fopen("/etc/inittab","w"))!=NULL) { fprintf(fp,"::sysinit:/etc/init.boot/rc.init\n"); fprintf(fp,"tty1::respawn:/bin/getty -h -n -L tty1 115200 linux\n"); fprintf(fp,"ttyS0::respawn:/bin/getty -h -n -L ttyS0 115200 vt100\n"); fprintf(fp,"tty7::respawn:/bin/chkprog\n"); fprintf(fp,"tty8::respawn:/bin/trafficd\n"); fprintf(fp,"::restart:/bin/init\n"); fprintf(fp,"::ctrlaltdel:/bin/bootdown\n"); fprintf(fp,"::ctrlaltdel:/bin/reset\n"); fprintf(fp,"::ctrlaltdel:/bin/reboot\n"); fprintf(fp,"::shutdown:/bin/bootdown\n"); fclose(fp); } curtime=time(NULL); loctime=localtime(&curtime); strftime(cmd, sizeof(cmd), "[%d/%m/%Y %T] TYPE=INFO MSG=****** SYSTEM LOADING ******\n",loctime); append_to_file("/tmp/bootup",cmd); if(file_exists("/bin/getkey")) { if(system("getkey -c 3 -m \"-> Starting Init: %d\" R")==0) { fprintf_stdout("\r#### WARNING: LOGIN DISABLED\n"); xtouch("/etc/noconsole"); } else { fprintf_stdout("\r* Starting Init. Done.\n"); } } memset(buf,0x0,sizeof(buf)); snprintf(buf,sizeof(buf),"%s\n","/bin/mdev"); save_to_file("/proc/sys/kernel/hotplug",buf); do_chroot(); signal(SIGINT,SIG_DFL); fprintf_stdout("#### ERROR: Failed to boot file system!\n"); fprintf_stdout("#### ERROR: Press Ctrl+Alt+Del or switch off/on for reboot.\n"); while(1); exit(0); }
int main(int argc, char **argv) { char *nameserv_host; char *topdomain; char *errormsg; #ifndef WINDOWS32 struct passwd *pw; #endif char *username; char password[33]; int foreground; char *newroot; char *context; char *device; char *pidfile; int choice; int tun_fd; int dns_fd; int max_downstream_frag_size; int autodetect_frag_size; int retval; int raw_mode; int lazymode; int selecttimeout; int hostname_maxlen; #ifdef OPENBSD int rtable = 0; #endif struct sockaddr_storage nameservaddr; int nameservaddr_len; int nameserv_family; nameserv_host = NULL; topdomain = NULL; errormsg = NULL; #ifndef WINDOWS32 pw = NULL; #endif username = NULL; memset(password, 0, 33); srand(time(NULL)); foreground = 0; newroot = NULL; context = NULL; device = NULL; pidfile = NULL; autodetect_frag_size = 1; max_downstream_frag_size = 3072; retval = 0; raw_mode = 1; lazymode = 1; selecttimeout = 4; hostname_maxlen = 0xFF; nameserv_family = AF_UNSPEC; #ifdef WINDOWS32 WSAStartup(req_version, &wsa_data); #endif srand((unsigned) time(NULL)); client_init(); #if !defined(BSD) && !defined(__GLIBC__) __progname = strrchr(argv[0], '/'); if (__progname == NULL) __progname = argv[0]; else __progname++; #endif while ((choice = getopt(argc, argv, "46vfhru:t:d:R:P:m:M:F:T:O:L:I:")) != -1) { switch(choice) { case '4': nameserv_family = AF_INET; break; case '6': nameserv_family = AF_INET6; break; case 'v': version(); /* NOTREACHED */ break; case 'f': foreground = 1; break; case 'h': help(); /* NOTREACHED */ break; case 'r': raw_mode = 0; break; case 'u': username = optarg; break; case 't': newroot = optarg; break; case 'd': device = optarg; break; #ifdef OPENBSD case 'R': rtable = atoi(optarg); break; #endif case 'P': strncpy(password, optarg, sizeof(password)); password[sizeof(password)-1] = 0; /* XXX: find better way of cleaning up ps(1) */ memset(optarg, 0, strlen(optarg)); break; case 'm': autodetect_frag_size = 0; max_downstream_frag_size = atoi(optarg); break; case 'M': hostname_maxlen = atoi(optarg); if (hostname_maxlen > 255) hostname_maxlen = 255; if (hostname_maxlen < 10) hostname_maxlen = 10; break; case 'z': context = optarg; break; case 'F': pidfile = optarg; break; case 'T': if (client_set_qtype(optarg)) errx(5, "Invalid query type '%s'", optarg); break; case 'O': /* not -D, is Debug in server */ client_set_downenc(optarg); break; case 'L': lazymode = atoi(optarg); if (lazymode > 1) lazymode = 1; if (lazymode < 0) lazymode = 0; if (!lazymode) selecttimeout = 1; break; case 'I': selecttimeout = atoi(optarg); if (selecttimeout < 1) selecttimeout = 1; break; default: usage(); /* NOTREACHED */ } } check_superuser(usage); argc -= optind; argv += optind; switch (argc) { case 1: nameserv_host = get_resolvconf_addr(); topdomain = strdup(argv[0]); break; case 2: nameserv_host = argv[0]; topdomain = strdup(argv[1]); break; default: usage(); /* NOTREACHED */ } if (max_downstream_frag_size < 1 || max_downstream_frag_size > 0xffff) { warnx("Use a max frag size between 1 and 65535 bytes.\n"); usage(); /* NOTREACHED */ } if (nameserv_host) { nameservaddr_len = get_addr(nameserv_host, DNS_PORT, nameserv_family, 0, &nameservaddr); if (nameservaddr_len < 0) { errx(1, "Cannot lookup nameserver '%s': %s ", nameserv_host, gai_strerror(nameservaddr_len)); } client_set_nameserver(&nameservaddr, nameservaddr_len); } else { warnx("No nameserver found - not connected to any network?\n"); usage(); /* NOTREACHED */ } if(check_topdomain(topdomain, &errormsg)) { warnx("Invalid topdomain: %s", errormsg); usage(); /* NOTREACHED */ } client_set_selecttimeout(selecttimeout); client_set_lazymode(lazymode); client_set_topdomain(topdomain); client_set_hostname_maxlen(hostname_maxlen); if (username != NULL) { #ifndef WINDOWS32 if ((pw = getpwnam(username)) == NULL) { warnx("User %s does not exist!\n", username); usage(); /* NOTREACHED */ } #endif } if (strlen(password) == 0) { if (NULL != getenv(PASSWORD_ENV_VAR)) snprintf(password, sizeof(password), "%s", getenv(PASSWORD_ENV_VAR)); else read_password(password, sizeof(password)); } client_set_password(password); if ((tun_fd = open_tun(device)) == -1) { retval = 1; goto cleanup1; } if ((dns_fd = open_dns_from_host(NULL, 0, nameservaddr.ss_family, AI_PASSIVE)) < 0) { retval = 1; goto cleanup2; } #ifdef OPENBSD if (rtable > 0) socket_setrtable(dns_fd, rtable); #endif signal(SIGINT, sighandler); signal(SIGTERM, sighandler); fprintf(stderr, "Sending DNS queries for %s to %s\n", topdomain, format_addr(&nameservaddr, nameservaddr_len)); if (client_handshake(dns_fd, raw_mode, autodetect_frag_size, max_downstream_frag_size)) { retval = 1; goto cleanup2; } if (client_get_conn() == CONN_RAW_UDP) { fprintf(stderr, "Sending raw traffic directly to %s\n", client_get_raw_addr()); } fprintf(stderr, "Connection setup complete, transmitting data.\n"); if (foreground == 0) do_detach(); if (pidfile != NULL) do_pidfile(pidfile); if (newroot != NULL) do_chroot(newroot); if (username != NULL) { #ifndef WINDOWS32 gid_t gids[1]; gids[0] = pw->pw_gid; if (setgroups(1, gids) < 0 || setgid(pw->pw_gid) < 0 || setuid(pw->pw_uid) < 0) { warnx("Could not switch to user %s!\n", username); usage(); /* NOTREACHED */ } #endif } if (context != NULL) do_setcon(context); client_tunnel(tun_fd, dns_fd); cleanup2: close_dns(dns_fd); close_tun(tun_fd); cleanup1: return retval; }
int main(int argc, char **argv) { extern char *__progname; char *listen_ip4; char *listen_ip6; char *errormsg; #ifndef WINDOWS32 struct passwd *pw = NULL; #endif int foreground; char *username; char *newroot; char *context; char *device; char *pidfile; int choice; int skipipconfig; char *netsize; int ns_get_externalip; int retval; #ifdef HAVE_SYSTEMD int nb_fds; #endif errormsg = NULL; username = NULL; newroot = NULL; context = NULL; device = NULL; foreground = 0; listen_ip4 = NULL; listen_ip6 = NULL; ns_get_externalip = 0; skipipconfig = 0; pidfile = NULL; srand(time(NULL)); retval = 0; #ifdef WINDOWS32 WSAStartup(req_version, &wsa_data); #endif #if !defined(BSD) && !defined(__GLIBC__) __progname = strrchr(argv[0], '/'); if (__progname == NULL) __progname = argv[0]; else __progname++; #endif // Load default values from preset memcpy(&server, &preset_default, sizeof(struct server_instance)); /* each option has format: char *name, int has_arg, int *flag, int val */ static struct option iodined_args[] = { {"version", no_argument, 0, 'v'}, {"noipcheck", no_argument, 0, 'c'}, {"notun", no_argument, 0, 's'}, {"user", required_argument, 0, 'u'}, {"listen4", required_argument, 0, 'l'}, {"listen6", required_argument, 0, 'L'}, {"nsip", required_argument, 0, 'n'}, {"mtu", required_argument, 0, 'm'}, {"idlequit", required_argument, 0, 'i'}, {"forwardto", required_argument, 0, 'b'}, {"localforward", no_argument, 0, 'A'}, {"remoteforward", no_argument, 0, 'R'}, {"help", no_argument, 0, 'h'}, {"context", required_argument, 0, 'z'}, {"chrootdir", required_argument, 0, 't'}, {"pidfile", required_argument, 0, 'F'}, {NULL, 0, 0, 0} }; static char *iodined_args_short = "46vcsfhDARu:t:d:m:l:L:p:n:b:P:z:F:i:"; server.running = 1; while ((choice = getopt_long(argc, argv, iodined_args_short, iodined_args, NULL)) != -1) { switch(choice) { case '4': server.addrfamily = AF_INET; break; case '6': server.addrfamily = AF_INET6; break; case 'v': version(); break; case 'c': server.check_ip = 0; break; case 's': skipipconfig = 1; break; case 'f': foreground = 1; break; case 'h': help(); break; case 'D': server.debug++; break; case 'u': username = optarg; break; case 't': newroot = optarg; break; case 'd': device = optarg; break; case 'm': server.mtu = atoi(optarg); break; case 'l': listen_ip4 = optarg; break; case 'L': listen_ip6 = optarg; break; case 'p': server.port = atoi(optarg); break; case 'n': if (optarg && strcmp("auto", optarg) == 0) { ns_get_externalip = 1; } else { server.ns_ip = inet_addr(optarg); } break; case 'b': server.bind_enable = 1; server.bind_port = atoi(optarg); break; case 'A': server.allow_forward_local_port = 1; break; case 'R': server.allow_forward_local_port = 1; server.allow_forward_remote = 1; break; case 'F': pidfile = optarg; break; case 'i': server.max_idle_time = atoi(optarg); break; case 'P': strncpy(server.password, optarg, sizeof(server.password)); server.password[sizeof(server.password)-1] = 0; /* XXX: find better way of cleaning up ps(1) */ memset(optarg, 0, strlen(optarg)); break; case 'z': context = optarg; break; default: usage(); break; } } argc -= optind; argv += optind; check_superuser(usage); if (argc != 2) usage(); netsize = strchr(argv[0], '/'); if (netsize) { *netsize = 0; netsize++; server.netmask = atoi(netsize); } server.my_ip = inet_addr(argv[0]); if (server.my_ip == INADDR_NONE) { warnx("Bad IP address to use inside tunnel."); usage(); } server.topdomain = strdup(argv[1]); if(check_topdomain(server.topdomain, &errormsg)) { warnx("Invalid topdomain: %s", errormsg); usage(); /* NOTREACHED */ } if (username != NULL) { #ifndef WINDOWS32 if ((pw = getpwnam(username)) == NULL) { warnx("User %s does not exist!", username); usage(); } #endif } if (server.mtu <= 0) { warnx("Bad MTU given."); usage(); } if(server.port < 1 || server.port > 65535) { warnx("Bad port number given."); usage(); } if (server.port != 53) { fprintf(stderr, "ALERT! Other dns servers expect you to run on port 53.\n"); fprintf(stderr, "You must manually forward port 53 to port %d for things to work.\n", server.port); } if (server.debug) { fprintf(stderr, "Debug level %d enabled, will stay in foreground.\n", server.debug); fprintf(stderr, "Add more -D switches to set higher debug level.\n"); foreground = 1; } if (server.addrfamily == AF_UNSPEC || server.addrfamily == AF_INET) { server.dns4addr_len = get_addr(listen_ip4, server.port, AF_INET, AI_PASSIVE | AI_NUMERICHOST, &server.dns4addr); if (server.dns4addr_len < 0) { warnx("Bad IPv4 address to listen on."); usage(); } } if (server.addrfamily == AF_UNSPEC || server.addrfamily == AF_INET6) { server.dns6addr_len = get_addr(listen_ip6, server.port, AF_INET6, AI_PASSIVE | AI_NUMERICHOST, &server.dns6addr); if (server.dns6addr_len < 0) { warnx("Bad IPv6 address to listen on."); usage(); } } if (server.bind_enable) { in_addr_t dns_ip = ((struct sockaddr_in *) &server.dns4addr)->sin_addr.s_addr; if (server.bind_port < 1 || server.bind_port > 65535) { warnx("Bad DNS server port number given."); usage(); /* NOTREACHED */ } /* Avoid forwarding loops */ if (server.bind_port == server.port && (dns_ip == INADDR_ANY || dns_ip == INADDR_LOOPBACK)) { warnx("Forward port is same as listen port (%d), will create a loop!", server.bind_port); fprintf(stderr, "Use -l to set listen ip to avoid this.\n"); usage(); /* NOTREACHED */ } fprintf(stderr, "Requests for domains outside of %s will be forwarded to port %d\n", server.topdomain, server.bind_port); } if (ns_get_externalip) { struct in_addr extip; int res = get_external_ip(&extip); if (res) { fprintf(stderr, "Failed to get external IP via web service.\n"); exit(3); } server.ns_ip = extip.s_addr; fprintf(stderr, "Using %s as external IP.\n", inet_ntoa(extip)); } if (server.ns_ip == INADDR_NONE) { warnx("Bad IP address to return as nameserver."); usage(); } if (server.netmask > 30 || server.netmask < 8) { warnx("Bad netmask (%d bits). Use 8-30 bits.", server.netmask); usage(); } if (strlen(server.password) == 0) { if (NULL != getenv(PASSWORD_ENV_VAR)) snprintf(server.password, sizeof(server.password), "%s", getenv(PASSWORD_ENV_VAR)); else read_password(server.password, sizeof(server.password)); } created_users = init_users(server.my_ip, server.netmask); if ((server.tun_fd = open_tun(device)) == -1) { /* nothing to clean up, just return */ return 1; } if (!skipipconfig) { const char *other_ip = users_get_first_ip(); if (tun_setip(argv[0], other_ip, server.netmask) != 0 || tun_setmtu(server.mtu) != 0) { retval = 1; free((void*) other_ip); goto cleanup; } free((void*) other_ip); } #ifdef HAVE_SYSTEMD nb_fds = sd_listen_fds(0); if (nb_fds > 1) { retval = 1; warnx("Too many file descriptors received!\n"); goto cleanup; } else if (nb_fds == 1) { /* XXX: assume we get IPv4 socket */ server.dns_fds.v4fd = SD_LISTEN_FDS_START; } else { #endif if ((server.addrfamily == AF_UNSPEC || server.addrfamily == AF_INET) && (server.dns_fds.v4fd = open_dns(&server.dns4addr, server.dns4addr_len)) < 0) { retval = 1; goto cleanup; } if ((server.addrfamily == AF_UNSPEC || server.addrfamily == AF_INET6) && /* Set IPv6 socket to V6ONLY */ (server.dns_fds.v6fd = open_dns_opt(&server.dns6addr, server.dns6addr_len, 1)) < 0) { retval = 1; goto cleanup; } #ifdef HAVE_SYSTEMD } #endif /* Setup dns file descriptors to get destination IP address */ if (server.dns_fds.v4fd >= 0) prepare_dns_fd(server.dns_fds.v4fd); if (server.dns_fds.v6fd >= 0) prepare_dns_fd(server.dns_fds.v6fd); if (server.bind_enable) { if ((server.bind_fd = open_dns_from_host(NULL, 0, AF_INET, 0)) < 0) { retval = 1; goto cleanup; } } if (created_users < USERS) { fprintf(stderr, "Limiting to %d simultaneous users because of netmask /%d\n", created_users, server.netmask); } fprintf(stderr, "Listening to dns for domain %s\n", server.topdomain); if (foreground == 0) do_detach(); if (pidfile != NULL) do_pidfile(pidfile); #ifdef FREEBSD tzsetwall(); #endif #ifndef WINDOWS32 openlog( __progname, LOG_NDELAY, LOG_DAEMON ); #endif if (newroot != NULL) do_chroot(newroot); signal(SIGINT, sigint); if (username != NULL) { #ifndef WINDOWS32 gid_t gids[1]; gids[0] = pw->pw_gid; if (setgroups(1, gids) < 0 || setgid(pw->pw_gid) < 0 || setuid(pw->pw_uid) < 0) { warnx("Could not switch to user %s!\n", username); usage(); } #endif } if (context != NULL) do_setcon(context); syslog(LOG_INFO, "started, listening on port %d", server.port); server_tunnel(); syslog(LOG_INFO, "stopping"); close_socket(server.bind_fd); cleanup: close_socket(server.dns_fds.v6fd); close_socket(server.dns_fds.v4fd); close_socket(server.tun_fd); #ifdef WINDOWS32 WSACleanup(); #endif /* TODO close user TCP forward sockets */ return retval; }
int bootup_main(int argc, char **argv) { FILE *fp; int t=0; char cmd[1024], buf[1024], name[1024]; time_t curtime; struct tm *loctime; signal(SIGINT,SIG_IGN); putenv("PATH=/bin"); putenv("TERM=linux"); umask(0770); chdir("/"); print_file("/etc/banner"); xsystem("mount -t proc -o ro virtual /proc"); xsystem("mount -t sysfs -o ro virtual /sys"); stage1(); stage2(); // STAGE 3 chdir("/"); read_cmdline(); xsystem("mdev -s"); xsystem("mount -t devpts -o \"rw,gid=0,mode=620\""); mk_dev("/dev/ppp",108,0); if(LCD_PROG==1 && file_exists("/tmp/tools/lcd/lcd.bz2")) { mk_dev("/dev/parport0",99,0); mk_dev("/dev/lp0",6,0); xsystem("tar -C / -jxf /tmp/tools/lcd/lcd.bz2"); } else { LCD_PROG=0; } rename("/dev/random","/dev/random-block"); symlink("/dev/urandom","/dev/random"); xmkdir("/strg"); if(LCD_DEV[0]!='\0') { snprintf(buf,sizeof(buf),"/dev/%s",LCD_DEV); if(file_exists(buf)) { save_to_file("/var/sys/lcd_dev",buf); if(LCD_PROG==1) save_to_file("/var/sys/lcd_proc","%d",LCD_PROG); symlink(buf,"/dev/lcd"); lcd_msg(LCD_PROG,"SYSTEM LOADING..","-> STORAGE ON"); } } memset(buf,0x0,sizeof(buf)); snprintf(buf,sizeof(buf),"mount -t %s -o \"rw,noatime\" %s /strg",STRG_FS,STRG_DEV); if(xsystem("mount -t %s -o \"rw,noatime\" %s /strg",STRG_FS,STRG_DEV)==0) { if(file_exists("/strg/.mount_strg")) { unlink("/strg/.mount_strg"); if(xsystem("umount /strg")==0) { fprintf_stdout("**** MYBOX SYSTEM APPEARS TO HAVE SHUT DOWN UNCLEANLY ****\n"); lcd_msg(LCD_PROG,"SYSTEM LOADING..","-> FIX STORAGE"); xsystem("e2fsck -y %s",STRG_DEV); t=1; } } if(t==0) xsystem("umount /strg"); } else { fprintf_stdout("**** MOUNTING STORAGE DISK FAILED! ****\n"); lcd_msg(LCD_PROG,"SYSTEM LOADING..","STORAGE FAILED !"); xtouch("/strg/.nostrg"); xtouch("/var/sys/nolog"); } if(!file_exists("/strg/.nostrg")) { if(xsystem("mount -t %s -o \"rw,noatime\" %s /strg",STRG_FS,STRG_DEV)==0) { memset(buf,0x0,sizeof(buf)); snprintf(buf,sizeof(buf),"%s:%s\n",STRG_DEV,STRG_FS); save_to_file("/strg/.mount_strg",buf); save_to_file("/var/sys/.mount_strg",buf); save_to_file("/var/sys/.mount_strg","%s:%s\n",BOOT_DEV,BOOT_FS); } } if(xsystem("swapon %s",SWAP_DEV)==0) { memset(buf,0x0,sizeof(buf)); snprintf(buf,sizeof(buf),"%s:swap\n",SWAP_DEV); save_to_file("/var/sys/.mount_swap",buf); } xsystem("chmod 700 *"); if((fp=fopen("/etc/inittab","w"))!=NULL) { fprintf(fp,"::sysinit:/bin/initrc\n"); fprintf(fp,"tty1::respawn:/bin/getty -h -n -L tty1 9600 linux\n"); fprintf(fp,"ttyS0::respawn:/bin/getty -h -n -L ttyS0 9600 vt100\n"); fprintf(fp,"null::respawn:/bin/chkprog\n"); fprintf(fp,"::restart:/bin/init\n"); fprintf(fp,"::ctrlaltdel:/bin/bootdown\n"); fprintf(fp,"::ctrlaltdel:/bin/reset\n"); fprintf(fp,"::ctrlaltdel:/bin/reboot\n"); fprintf(fp,"::shutdown:/bin/bootdown\n"); fclose(fp); } if((fp=fopen("/etc/profile","a"))!=NULL) { fprintf(fp,"xexit() {\n"); fprintf(fp," if [ \"$PPID\" = \"1\" ]; then\n"); fprintf(fp," local logname=\"/strg/mybox/logs/auth-$(date \"+%s\").log\"\n","%Y%m%d"); fprintf(fp," local msg=\"[$(date \"+%s\")] TYPE=console USER=console IP=$(basename $(tty)) MSG=Session logout.\"\n","%d/%m/%Y %H:%M:%S"); fprintf(fp," echo \"$msg\" >> $logname\n"); fprintf(fp," [ ! -z \"$ME\" -a -f \"$ME\" ] && rm -f /tmp/console.session/console_*\n"); fprintf(fp," fi\n"); fprintf(fp," exit\n"); fprintf(fp,"}\n"); fprintf(fp,"alias exit='xexit'\n"); fprintf(fp,"export HISTFILE=/.consolehistory\n"); fprintf(fp,"lcdd_msg() {\n"); fprintf(fp," if [ -f \"/bin/lcdd\" -a -c \"/dev/lcd\" ]; then\n"); fprintf(fp," if [ -f \"/var/sys/lcd_proc\" ]; then\n"); fprintf(fp," echo \"$2\" > /var/sys/lcd_msg\n"); fprintf(fp," else\n"); fprintf(fp," /bin/lcdd \"$1\" \"$2\"\n"); fprintf(fp," fi\n"); fprintf(fp," fi\n"); fprintf(fp,"}\n"); fprintf(fp,"if [ -z $DO_SINGLE ]; then\n"); fprintf(fp," if [ -f \"/bin/iosh\" ]; then\n"); fprintf(fp," XTTY=\"SSL\";\n"); fprintf(fp," if [ -f \"/var/sys/init_start\" ]; then\n"); fprintf(fp," trap : 1 2 3 15\n"); fprintf(fp," echo \"System loading in progress..please wait or login back in a minute\"\n"); fprintf(fp," while [ -f \"/var/sys/init_start\" ]; do sleep 1;done\n"); fprintf(fp," trap 1 2 3 15\n"); fprintf(fp," fi\n"); fprintf(fp," if [ \"$PPID\" = \"1\" ]; then\n"); fprintf(fp," export ME=\"/tmp/console.session/console_${PPID}_$(basename $(tty))_$(date \"+%s\")\";\n","%d:%m:%Y_%H:%M:%S"); fprintf(fp," touch $ME\n"); fprintf(fp," XTTY=\"console\";\n"); fprintf(fp," fi\n"); fprintf(fp," /bin/iosh $XTTY\n"); fprintf(fp," if [ $? != 5 ]; then\n"); fprintf(fp," clear;reset\n"); fprintf(fp," exit\n"); fprintf(fp," fi\n"); fprintf(fp," else\n"); fprintf(fp," echo \"** FAILED TO RUN IO SHELL **\"\n"); fprintf(fp," read io\n"); fprintf(fp," exit\n"); fprintf(fp," fi\n"); fprintf(fp,"else \n"); fprintf(fp," echo \"** MAINTENANCE MODE **\"\n"); fprintf(fp," lcdd_msg \"SYSTEM LOADING.." "-> MAINTENANCE\"\n"); fprintf(fp," read io\n"); fprintf(fp,"fi\n"); fclose(fp); } unlink("/strg/mybox/debug.log"); curtime=time(NULL); loctime=localtime(&curtime); memset(name,0x0,sizeof(name)); strftime(name, sizeof(name),"system-%Y%m%d.log",loctime); memset(buf,0x0,sizeof(buf)); snprintf(buf,sizeof(buf),"%s/%s",LOGPATH,name); memset(cmd,0x0,sizeof(cmd)); strftime(cmd, sizeof(cmd), "[%d/%m/%Y %T] TYPE=INFO MSG=****** SYSTEM LOADING ******\n",loctime); append_to_file(buf,cmd); if(file_exists("/bin/getkey")) { if(system("getkey -c 3 -m \"-> Starting Init: %d\" R")==0) { fprintf_stdout("\r*** BYPASS CONSOLE LOGIN ***\n"); lcd_msg(LCD_PROG,"SYSTEM LOADING..","BYPASS CONSOLE !"); xtouch("/etc/noconsole"); } else { fprintf_stdout("\r* Starting Init. Done.\n"); } } memset(buf,0x0,sizeof(buf)); snprintf(buf,sizeof(buf),"%s\n","/bin/mdev"); save_to_file("/proc/sys/kernel/hotplug",buf); if(NUM_NET!=0) save_to_file("/var/sys/numnet_veto","%d",NUM_NET); do_chroot(); signal(SIGINT,SIG_DFL); lcd_msg(LCD_PROG,"SYSTEM LOADING..","ERROR !"); fprintf_stdout("You are not supposed to be here, something went wrong!\n"); fprintf_stdout("Press Ctrl+Alt+Del or switch off/on for reboot.\n"); while(1); exit(0); }
int main(int argc, char **argv) { char *errormsg = NULL; #ifndef WINDOWS32 struct passwd *pw = NULL; #endif int choice = -1; int retval = 0; char *username = NULL; char *newroot = NULL; char *context = NULL; char *device = NULL; char *pidfile = NULL; int remote_forward_port = 0; char *nameserv_host = NULL; struct sockaddr_storage nameservaddr; int nameservaddr_len = 0; int nameserv_family = AF_UNSPEC; #ifdef WINDOWS32 WSAStartup(req_version, &wsa_data); #endif #if !defined(BSD) && !defined(__GLIBC__) __progname = strrchr(argv[0], '/'); if (__progname == NULL) __progname = argv[0]; else __progname++; #endif #define OPT_RDOMAIN 0x80 #define OPT_NODROP 0x81 /* each option has format: * char *name, int has_arg, int *flag, int val */ static struct option iodine_args[] = { {"version", no_argument, 0, 'v'}, {"help", no_argument, 0, 'h'}, {"stats", optional_argument, 0, 'V'}, {"context", required_argument, 0, 'z'}, {"rdomain", required_argument, 0, OPT_RDOMAIN}, {"chrootdir", required_argument, 0, 't'}, {"preset", required_argument, 0, 'Y'}, {"proxycommand", no_argument, 0, 'R'}, // {"nodrop", no_argument, 0, OPT_NODROP}, {"remote", required_argument, 0, 'R'}, {NULL, 0, 0, 0} }; /* Pre-parse command line to get preset * This is so that all options override preset values regardless of order in command line */ int optind_orig = optind, preset_id = -1; static char *iodine_args_short = "46vfDhrY:s:V:c:C:i:j:u:t:d:R:P:w:W:m:M:F:T:O:L:I:"; while ((choice = getopt_long(argc, argv, iodine_args_short, iodine_args, NULL))) { /* Check if preset has been found yet so we don't process any other options */ if (preset_id < 0) { if (choice == -1) { /* reached end of command line and no preset specified - use default */ preset_id = 0; } else if (choice == 'Y') { /* find index of preset */ if (optarg) { for (int i = 0; i < NUM_CLIENT_PRESETS; i++) { if (toupper(optarg[0]) == client_presets[i].short_name) { preset_id = i; break; } } } } else if (choice == '?') { usage(); /* Not reached */ } else { /* skip all other options until we find preset */ continue; } if (preset_id < 0) { /* invalid preset or none specified */ fprintf(stderr, "Invalid preset or none specified with -Y or --preset!\n"); print_presets(2); usage(); /* not reached */ } memcpy(&this, client_presets[preset_id].preset_data, sizeof(struct client_instance)); /* Reset optind to reparse command line */ optind = optind_orig; continue; } else if (choice == -1) { break; } /* Once a preset is used, it is copied into memory. This way other * options can override preset values regardless of order in command line */ switch (choice) { case '4': nameserv_family = AF_INET; break; case '6': nameserv_family = AF_INET6; break; case 'v': version(); /* NOTREACHED */ break; case 'V': this.stats = atoi(optarg); if (this.stats < 0) this.stats = 0; break; case 'f': this.foreground = 1; break; case 'D': this.debug++; break; case 'h': help(); /* NOTREACHED */ break; case 'r': this.raw_mode = 0; break; case 'u': username = optarg; break; case 't': newroot = optarg; break; case 'd': device = optarg; break; #ifdef OPENBSD case OPT_RDOMAIN: rtable = atoi(optarg); break; #endif case 'R': /* Argument format: [host:]port */ if (!optarg) break; this.use_remote_forward = 1; remote_forward_port = parse_tcp_forward_option(optarg); break; case OPT_NODROP: // TODO implement TCP-over-tun optimisations break; case 'P': strncpy(this.password, optarg, sizeof(this.password)); this.password[sizeof(this.password)-1] = 0; /* XXX: find better way of cleaning up ps(1) */ memset(optarg, 0, strlen(optarg)); break; case 'm': this.autodetect_frag_size = 0; this.max_downstream_frag_size = atoi(optarg); break; case 'M': this.hostname_maxlen = atoi(optarg); if (this.hostname_maxlen > 255) this.hostname_maxlen = 255; if (this.hostname_maxlen < 10) this.hostname_maxlen = 10; break; case 'z': context = optarg; break; case 'F': pidfile = optarg; break; case 'T': if (client_set_qtype(optarg)) errx(5, "Invalid query type '%s'", optarg); break; case 'O': if ((this.downenc = parse_encoding(optarg)) == 0) errx(6, "Invalid encoding type '%s'", optarg); break; case 'L': this.lazymode = atoi(optarg); if (this.lazymode > 1) this.lazymode = 1; if (this.lazymode < 0) this.lazymode = 0; break; case 'I': this.max_timeout_ms = strtod(optarg, NULL) * 1000; if (this.autodetect_server_timeout) { this.server_timeout_ms = this.max_timeout_ms / 2; } break; case 'i': this.server_timeout_ms = strtod(optarg, NULL) * 1000; this.autodetect_server_timeout = 0; break; case 'j': this.downstream_timeout_ms = strtod(optarg, NULL) * 1000; if (this.autodetect_server_timeout) { this.autodetect_server_timeout = 0; this.server_timeout_ms = 4000; } break; case 's': this.send_interval_ms = atoi(optarg); if (this.send_interval_ms < 0) this.send_interval_ms = 0; case 'w': this.windowsize_down = atoi(optarg); break; case 'W': this.windowsize_up = atoi(optarg); break; case 'c': this.compression_down = atoi(optarg) & 1; break; case 'C': this.compression_up = atoi(optarg) & 1; break; case 'Y': /* Already processed preset: ignore */ continue; default: usage(); /* NOTREACHED */ } } srand((unsigned) time(NULL)); this.rand_seed = (uint16_t) rand(); this.chunkid = (uint16_t) rand(); this.running = 1; check_superuser(usage); argc -= optind; argv += optind; if (this.debug) { fprintf(stderr, "Debug level %d enabled, will stay in foreground.\n", this.debug); fprintf(stderr, "Add more -D switches to set higher debug level.\n"); this.foreground = 1; } this.nameserv_hosts_len = argc - 1; if (this.nameserv_hosts_len <= 0) /* if no hosts specified, use resolv.conf */ this.nameserv_hosts_len = 1; // Preallocate memory with expected number of hosts this.nameserv_hosts = malloc(sizeof(char *) * this.nameserv_hosts_len); this.nameserv_addrs = malloc(sizeof(struct sockaddr_storage) * this.nameserv_hosts_len); if (argc == 0) { usage(); /* NOT REACHED */ } else if (argc == 1) { this.nameserv_hosts[0] = get_resolvconf_addr(); } else if (argc > 1) for (int h = 0; h < this.nameserv_hosts_len; h++) this.nameserv_hosts[h] = strdup(argv[h + 1]); this.topdomain = strdup(argv[0]); for (int n = 0; n < this.nameserv_hosts_len; n++) { nameserv_host = this.nameserv_hosts[n]; if (!nameserv_host) { errx(1, "Error processing nameserver hostnames!"); } nameservaddr_len = get_addr(nameserv_host, DNS_PORT, nameserv_family, 0, &nameservaddr); if (nameservaddr_len < 0) { errx(1, "Cannot lookup nameserver '%s': %s ", nameserv_host, gai_strerror(nameservaddr_len)); } memcpy(&this.nameserv_addrs[n], &nameservaddr, sizeof(struct sockaddr_storage)); this.nameserv_addrs_len ++; nameserv_host = NULL; } if (this.nameserv_addrs_len <= 0 || !this.nameserv_hosts[0]) { warnx("No nameservers found - not connected to any network?"); usage(); } if (this.max_downstream_frag_size < 10 || this.max_downstream_frag_size > MAX_FRAGSIZE) { warnx("Use a max frag size between 10 and %d bytes.", MAX_FRAGSIZE); usage(); /* NOTREACHED */ } if(check_topdomain(this.topdomain, &errormsg)) { warnx("Invalid topdomain: %s", errormsg); usage(); /* NOTREACHED */ } int max_ws = MAX_SEQ_ID / 2; if (this.windowsize_up < 1 || this.windowsize_down < 1 || this.windowsize_up > max_ws || this.windowsize_down > max_ws) { warnx("Window sizes (-w or -W) must be between 0 and %d!", max_ws); usage(); } if (this.max_timeout_ms < 100) { warnx("Target interval (-I) must be greater than 0.1 seconds!"); usage(); } if ((this.server_timeout_ms < 100 || this.server_timeout_ms >= this.max_timeout_ms) && !this.autodetect_server_timeout) { warnx("Server timeout (-i) must be greater than 0.1 sec and less than target interval!"); usage(); } if (this.downstream_timeout_ms < 100) { warnx("Downstream fragment timeout must be more than 0.1 sec to prevent excessive retransmits."); usage(); } if (!this.lazymode && this.max_timeout_ms > 1000) { fprintf(stderr, "Warning: Target interval of >1 second in immediate mode will cause high latency.\n"); } if (username != NULL) { #ifndef WINDOWS32 if ((pw = getpwnam(username)) == NULL) { warnx("User %s does not exist!", username); usage(); /* NOTREACHED */ } #else warnx("Warning: Cannot switch user on Windows systems."); #endif } if (strlen(this.password) == 0) { if (NULL != getenv(PASSWORD_ENV_VAR)) snprintf(this.password, sizeof(this.password), "%s", getenv(PASSWORD_ENV_VAR)); else read_password(this.password, sizeof(this.password)); } if (!this.use_remote_forward) { if ((this.tun_fd = open_tun(device)) == -1) { retval = 1; goto cleanup; } } if ((this.dns_fd = open_dns_from_host(NULL, 0, nameservaddr.ss_family, AI_PASSIVE)) < 0) { retval = 1; goto cleanup; } #ifdef OPENBSD if (rtable > 0) socket_setrtable(dns_fd, rtable); #endif signal(SIGINT, sighandler); signal(SIGTERM, sighandler); fprintf(stderr, "Sending DNS queries for %s to ", this.topdomain); for (int a = 0; a < this.nameserv_addrs_len; a++) fprintf(stderr, "%s%s", format_addr(&this.nameserv_addrs[a], sizeof(struct sockaddr_storage)), (a != this.nameserv_addrs_len - 1) ? ", " : ""); fprintf(stderr, "\n"); if (this.remote_forward_addr.ss_family != AF_UNSPEC) fprintf(stderr, "Requesting TCP data forwarding from server to %s:%d\n", format_addr(&this.remote_forward_addr, sizeof(struct sockaddr_storage)), remote_forward_port); if (client_handshake()) { retval = 1; goto cleanup; } if (this.conn == CONN_RAW_UDP) { fprintf(stderr, "Sending raw UDP traffic directly to %s\n", client_get_raw_addr()); } fprintf(stderr, "Connection setup complete, transmitting data.\n"); if (this.foreground == 0) do_detach(); if (pidfile != NULL) do_pidfile(pidfile); if (newroot != NULL) do_chroot(newroot); if (username != NULL) { #ifndef WINDOWS32 gid_t gids[1]; gids[0] = pw->pw_gid; if (setgroups(1, gids) < 0 || setgid(pw->pw_gid) < 0 || setuid(pw->pw_uid) < 0) { warnx("Could not switch to user %s!\n", username); usage(); /* NOTREACHED */ } #endif } if (context != NULL) do_setcon(context); client_tunnel(); cleanup: if (this.use_remote_forward) close(STDOUT_FILENO); close_socket(this.dns_fd); close_socket(this.tun_fd); #ifdef WINDOWS32 WSACleanup(); #endif return retval; }
int main(int argc, char **argv) { char buffer[MAX_INPUT_BUFFER]; int result; uid_t uid = -1; gid_t gid = -1; /* process command-line arguments */ result = process_arguments(argc, argv); if (result != OK || show_help == TRUE || show_license == TRUE || show_version == TRUE) { if (result != OK) printf("Incorrect command line arguments supplied\n"); printf("\n"); printf("NSCA - Nagios Service Check Acceptor for Icinga\n"); printf("Copyright (c) 2010-2012 Icinga Development Team and Community Contributors (http://www.icinga.org)\n"); printf("Copyright (c) 2009-2012 Nagios Core Development Team and Community Contributors\n"); printf("Copyright (c) 2000-2009 Ethan Galstad\n"); printf("Version: %s\n", PROGRAM_VERSION); printf("Last Modified: %s\n", MODIFICATION_DATE); printf("License: GPL v2\n"); printf("Encryption Routines: "); #ifdef HAVE_LIBMCRYPT printf("AVAILABLE"); #else printf("NOT AVAILABLE"); #endif printf("\n"); #ifdef HAVE_LIBWRAP printf("TCP Wrappers Available\n"); #endif printf("\n"); } if (result != OK || show_help == TRUE) { printf("Usage: %s -c <config_file> [mode]\n", argv[0]); printf("\n"); printf("Options:\n"); printf(" <config_file> = Name of config file to use\n"); printf(" [mode] = Determines how NSCA should run. Valid modes:\n"); printf(" --inetd = Run as a service under inetd or xinetd\n"); printf(" --daemon = Run as a standalone multi-process daemon\n"); printf(" --single = Run as a standalone single-process daemon (default)\n"); printf("\n"); printf("Notes:\n"); printf("This program is designed to accept passive check results from\n"); printf("remote hosts that use the send_nsca utility. Can run as a service\n"); printf("under inetd or xinetd (read the docs for info on this), or as a\n"); printf("standalone daemon.\n"); printf("\n"); } if (show_license == TRUE) display_license(); if (result != OK || show_help == TRUE || show_license == TRUE || show_version == TRUE) do_exit(STATE_UNKNOWN); /* open a connection to the syslog facility */ /* facility may be overridden later */ get_log_facility(NSCA_LOG_FACILITY); openlog("nsca", LOG_PID | LOG_NDELAY, log_facility); /* make sure the config file uses an absolute path */ if (config_file[0] != '/') { /* save the name of the config file */ strncpy(buffer, config_file, sizeof(buffer)); buffer[sizeof(buffer) - 1] = '\0'; /* get absolute path of current working directory */ strcpy(config_file, ""); getcwd(config_file, sizeof(config_file)); /* append a forward slash */ strncat(config_file, "/", sizeof(config_file) - 2); config_file[sizeof(config_file) - 1] = '\0'; /* append the config file to the path */ strncat(config_file, buffer, sizeof(config_file) - strlen(config_file) - 1); config_file[sizeof(config_file) - 1] = '\0'; } /* read the config file */ result = read_config_file(config_file); /* exit if there are errors... */ if (result == ERROR) do_exit(STATE_CRITICAL); /* generate the CRC 32 table */ generate_crc32_table(); /* how should we handle client connections? */ switch (mode) { case INETD: /* chroot if configured */ do_chroot(); /* if we're running under inetd, handle one connection and get out */ handle_connection(0, NULL); break; case MULTI_PROCESS_DAEMON: /* older style, mult-process daemon */ /* execution cascades below... */ install_child_handler(); /* | | | */ case SINGLE_PROCESS_DAEMON: /* | | V */ /* daemonize and start listening for requests... */ if (fork() == 0) { /* we're a daemon - set up a new process group */ setsid(); /* handle signals */ signal(SIGQUIT, sighandler); signal(SIGTERM, sighandler); signal(SIGHUP, sighandler); signal(SIGPIPE, SIG_IGN); /* close standard file descriptors */ close(0); close(1); close(2); /* redirect standard descriptors to /dev/null */ open("/dev/null", O_RDONLY); open("/dev/null", O_WRONLY); open("/dev/null", O_WRONLY); /* get group information before chrooting */ get_user_info(nsca_user, &uid); get_group_info(nsca_group, &gid); /* write pid file */ if (write_pid_file(uid, gid) == ERROR) return STATE_CRITICAL; /* chroot if configured */ do_chroot(); /* drop privileges */ if (drop_privileges(nsca_user, uid, gid) == ERROR) do_exit(STATE_CRITICAL); do { /* reset flags */ sigrestart = FALSE; sigshutdown = FALSE; /* wait for connections */ wait_for_connections(); if (sigrestart == TRUE) { /* free memory */ free_memory(); /* re-read the config file */ result = read_config_file(config_file); /* exit if there are errors... */ if (result == ERROR) { syslog(LOG_ERR, "Config file '%s' contained errors, bailing out...", config_file); break; } } } while (sigrestart == TRUE && sigshutdown == FALSE); /* remove pid file */ remove_pid_file(); syslog(LOG_NOTICE, "Daemon shutdown\n"); } break; default: break; } /* we are now running in daemon mode, or the connection handed over by inetd has been completed, so the parent process exits */ do_exit(STATE_OK); /* keep the compilers happy... */ return STATE_OK; }
int main(int argc, char *argv[]) { int rc, sync[2]; pid_t pid = -1; siginfo_t status; struct mount *mounts = NULL; struct netif *netifs = NULL; struct cgroup *cgroups = NULL; struct user *users = NULL; #if HAVE_LIBCAP_NG struct capability *caps = NULL; #endif char *master; _close_ int master_fd = -1; char ephemeral_dir[] = "/tmp/pflask-ephemeral-XXXXXX"; int clone_flags = CLONE_NEWNS | CLONE_NEWIPC | CLONE_NEWPID | #ifdef CLONE_NEWCGROUP CLONE_NEWCGROUP | #endif CLONE_NEWUTS; struct gengetopt_args_info args; if (cmdline_parser(argc, argv, &args) != 0) return 1; for (unsigned int i = 0; i < args.mount_given; i++) { validate_optlist("--mount", args.mount_arg[i]); mount_add_from_spec(&mounts, args.mount_arg[i]); } for (unsigned int i = 0; i < args.netif_given; i++) { clone_flags |= CLONE_NEWNET; if (args.netif_arg != NULL) { validate_optlist("--netif", args.netif_arg[i]); netif_add_from_spec(&netifs, args.netif_arg[i]); } } if (args.user_given && !args.user_map_given) { uid_t uid; gid_t gid; clone_flags |= CLONE_NEWUSER; if (user_get_uid_gid(args.user_arg, &uid, &gid)) { user_add_map(&users, 'u', uid, uid, 1); user_add_map(&users, 'g', gid, gid, 1); } } for (unsigned int i = 0; i < args.user_map_given; i++) { size_t count; uid_t id, host_id; char *start = args.user_map_arg[i], *end = NULL; validate_optlist("--user-map", args.user_map_arg[i]); clone_flags |= CLONE_NEWUSER; id = strtoul(start, &end, 10); if (*end != ':') fail_printf("Invalid value '%s' for --user-map", args.user_map_arg[i]); start = end + 1; host_id = strtoul(start, &end, 10); if (*end != ':') fail_printf("Invalid value '%s' for --user-map", args.user_map_arg[i]); start = end + 1; count = strtoul(start, &end, 10); if (*end != '\0') fail_printf("Invalid value '%s' for --user-map", args.user_map_arg[i]); user_add_map(&users, 'u', id, host_id, count); user_add_map(&users, 'g', id, host_id, count); } for (unsigned int i = 0; i < args.cgroup_given; i++) cgroup_add(&cgroups, args.cgroup_arg[i]); #if HAVE_LIBCAP_NG for (unsigned int i = 0; i < args.caps_given; i++) capability_add(&caps, args.caps_arg[i]); #endif if (args.no_userns_flag) clone_flags &= ~(CLONE_NEWUSER); if (args.no_mountns_flag) clone_flags &= ~(CLONE_NEWNS); if (args.no_netns_flag) clone_flags &= ~(CLONE_NEWNET); if (args.no_ipcns_flag) clone_flags &= ~(CLONE_NEWIPC); if (args.no_utsns_flag) clone_flags &= ~(CLONE_NEWUTS); if (args.no_pidns_flag) clone_flags &= ~(CLONE_NEWPID); if (args.attach_given) { master_fd = recv_pty(args.attach_arg); fail_if(master_fd < 0, "Invalid PID '%u'", args.attach_arg); process_pty(master_fd); return 0; } open_master_pty(&master_fd, &master); if (args.detach_flag) do_daemonize(); sync_init(sync); if (args.ephemeral_flag) { if (!mkdtemp(ephemeral_dir)) sysf_printf("mkdtemp()"); } pid = do_clone(&clone_flags); if (!pid) { closep(&master_fd); rc = prctl(PR_SET_PDEATHSIG, SIGKILL); sys_fail_if(rc < 0, "prctl(PR_SET_PDEATHSIG)"); rc = setsid(); sys_fail_if(rc < 0, "setsid()"); sync_barrier_parent(sync, SYNC_START); sync_close(sync); open_slave_pty(master); setup_user(args.user_arg); if (args.hostname_given) { rc = sethostname(args.hostname_arg, strlen(args.hostname_arg)); sys_fail_if(rc < 0, "Error setting hostname"); } setup_mount(mounts, args.chroot_arg, args.ephemeral_flag ? ephemeral_dir : NULL); if (args.chroot_given) { setup_nodes(args.chroot_arg); setup_ptmx(args.chroot_arg); setup_symlinks(args.chroot_arg); setup_console(args.chroot_arg, master); do_chroot(args.chroot_arg); } if (clone_flags & CLONE_NEWNET) config_netif(); umask(0022); #if HAVE_LIBCAP_NG setup_capabilities(caps); #endif if (args.chdir_given) { rc = chdir(args.chdir_arg); sys_fail_if(rc < 0, "Error changing cwd"); } if (args.chroot_given) { char *term = getenv("TERM"); if (!args.keepenv_flag) clearenv(); setenv("PATH", "/usr/sbin:/usr/bin:/sbin:/bin", 1); setenv("USER", args.user_arg, 1); setenv("LOGNAME", args.user_arg, 1); if (term) setenv("TERM", term, 1); } for (unsigned int i = 0; i < args.setenv_given; i++) { rc = putenv(strdup(args.setenv_arg[i])); sys_fail_if(rc != 0, "Error setting environment"); } setenv("container", "pflask", 1); if (argc > optind) rc = execvpe(argv[optind], argv + optind, environ); else rc = execle("/bin/bash", "-bash", NULL, environ); sys_fail_if(rc < 0, "Error executing command"); } sync_wait_child(sync, SYNC_START); if (args.chroot_given && (clone_flags & CLONE_NEWUSER)) setup_console_owner(master, users); setup_cgroup(cgroups, pid); setup_netif(netifs, pid); #ifdef HAVE_DBUS register_machine(pid, args.chroot_given ? args.chroot_arg : ""); #endif if (clone_flags & CLONE_NEWUSER) setup_user_map(users, pid); sync_wake_child(sync, SYNC_DONE); sync_close(sync); if (args.detach_flag) serve_pty(master_fd); else process_pty(master_fd); kill(pid, SIGKILL); rc = waitid(P_PID, pid, &status, WEXITED); sys_fail_if(rc < 0, "Error waiting for child"); switch (status.si_code) { case CLD_EXITED: if (status.si_status != 0) err_printf("Child failed with code '%d'", status.si_status); else ok_printf("Child exited"); break; case CLD_KILLED: err_printf("Child was terminated by signal '%d'", status.si_status); break; default: err_printf("Child failed"); break; } sync_close(sync); clean_cgroup(cgroups); if (args.ephemeral_flag) { rc = rmdir(ephemeral_dir); sys_fail_if(rc != 0, "Error deleting ephemeral directory: %s", ephemeral_dir); } cmdline_parser_free(&args); return status.si_status; }
int main(int argc, char *argv[]) { int rc, i; pid_t pid = -1; pid_t ppid = getpid(); uid_t uid = -1; gid_t gid = -1; _free_ char *user = NULL; _free_ char *dest = NULL; _free_ char *change = NULL; _free_ char *env = NULL; _free_ char *cgroup = NULL; _close_ int master_fd = -1; char *master_name; int detach = 0; int keepenv = 0; siginfo_t status; while ((rc = getopt_long(argc, argv, short_opts, long_opts, &i)) !=-1) { switch (rc) { case 'm': validate_optlist("--mount", optarg); add_mount_from_spec(optarg); break; case 'n': clone_flags |= CLONE_NEWNET; if (optarg != NULL) { validate_optlist("--netif", optarg); add_netif_from_spec(optarg); } break; case 'u': clone_flags |= CLONE_NEWUSER; freep(&user); user = strdup(optarg); break; case 'r': freep(&dest); dest = realpath(optarg, NULL); if (dest == NULL) sysf_printf("realpath()"); break; case 'c': freep(&change); change = strdup(optarg); break; case 'g': validate_optlist("--cgroup", optarg); validate_cgroup_spec(optarg); freep(&change); cgroup = strdup(optarg); break; case 'd': detach = 1; break; case 'a': { char *end = NULL; pid = strtol(optarg, &end, 10); if (*end != '\0') fail_printf("Invalid value '%s' for --attach", optarg); break; } case 's': { validate_optlist("--setenv", optarg); if (env != NULL) { char *tmp = env; rc = asprintf(&env, "%s,%s", env, optarg); if (rc < 0) fail_printf("OOM"); freep(&tmp); } else { env = strdup(optarg); } break; } case 'k': keepenv = 1; break; case 'U': clone_flags &= ~(CLONE_NEWUSER); break; case 'M': clone_flags &= ~(CLONE_NEWNS); break; case 'N': clone_flags &= ~(CLONE_NEWNET); break; case 'I': clone_flags &= ~(CLONE_NEWIPC); break; case 'H': clone_flags &= ~(CLONE_NEWUTS); break; case 'P': clone_flags &= ~(CLONE_NEWPID); break; case '?': case 'h': help(); return 0; } } if (pid != -1) { master_fd = recv_pty(pid); if (master_fd < 0) fail_printf("Invalid PID '%u'", pid); pid = -1; goto process_fd; } if (user == NULL) { user = strdup("root"); if (user == NULL) fail_printf("OOM"); } open_master_pty(&master_fd, &master_name); uid = getuid(); gid = getgid(); if (detach == 1) do_daemonize(); pid = do_clone(); if (pid == 0) { closep(&master_fd); open_slave_pty(master_name); rc = setsid(); if (rc < 0) sysf_printf("setsid()"); rc = prctl(PR_SET_PDEATHSIG, SIGKILL); if (rc < 0) sysf_printf("prctl(PR_SET_PDEATHSIG)"); if (clone_flags & CLONE_NEWUSER) map_user_to_user(uid, gid, user); do_cgroup(cgroup, ppid); do_mount(dest); if (dest != NULL) { copy_nodes(dest); make_ptmx(dest); make_symlinks(dest); make_console(dest, master_name); do_chroot(dest); } if (clone_flags & CLONE_NEWNET) setup_loopback(); umask(0022); /* TODO: drop capabilities */ do_user(user); if (change != NULL) { rc = chdir(change); if (rc < 0) sysf_printf("chdir()"); } if (dest != NULL) { char *term = getenv("TERM"); if (keepenv == 0) clearenv(); setenv("PATH", "/usr/sbin:/usr/bin:/sbin:/bin", 1); setenv("USER", user, 1); setenv("LOGNAME", user, 1); setenv("TERM", term, 1); } if (env != NULL) { size_t i, c; _free_ char **vars = NULL; _free_ char *tmp = strdup(env); if (tmp == NULL) fail_printf("OOM"); c = split_str(tmp, &vars, ","); for (i = 0; i < c; i++) { rc = putenv(strdup(vars[i])); if (rc != 0) sysf_printf("putenv()"); } } setenv("container", "pflask", 1); if (argc > optind) rc = execvpe(argv[optind], argv + optind, environ); else rc = execle("/bin/bash", "-bash", NULL, environ); if (rc < 0) sysf_printf("exec()"); } do_netif(pid); process_fd: if (detach == 1) serve_pty(master_fd); else process_pty(master_fd); if (pid == -1) return 0; kill(pid, SIGKILL); rc = waitid(P_PID, pid, &status, WEXITED); if (rc < 0) sysf_printf("waitid()"); switch (status.si_code) { case CLD_EXITED: if (status.si_status != 0) err_printf("Child failed with code '%d'", status.si_status); else ok_printf("Child exited"); break; case CLD_KILLED: err_printf("Child was terminated"); break; default: err_printf("Child failed"); break; } undo_cgroup(cgroup, ppid); return status.si_status; }