static int rtasd(void *unused) { unsigned int err_type; int cpu = 0; int event_scan = rtas_token("event-scan"); cpumask_t all = CPU_MASK_ALL; int rc; daemonize("rtasd"); if (event_scan == RTAS_UNKNOWN_SERVICE || get_eventscan_parms() == -1) goto error; rtas_log_buf = vmalloc(rtas_error_log_buffer_max*LOG_NUMBER); if (!rtas_log_buf) { printk(KERN_ERR "rtasd: no memory\n"); goto error; } /* We can use rtas_log_buf now */ no_more_logging = 0; printk(KERN_ERR "RTAS daemon started\n"); DEBUG("will sleep for %d jiffies\n", (HZ*60/rtas_event_scan_rate) / 2); /* See if we have any error stored in NVRAM */ memset(logdata, 0, rtas_error_log_max); rc = nvram_read_error_log(logdata, rtas_error_log_max, &err_type); if (!rc) { if (err_type != ERR_FLAG_ALREADY_LOGGED) { pSeries_log_error(logdata, err_type | ERR_FLAG_BOOT, 0); } } /* First pass. */ lock_cpu_hotplug(); for_each_online_cpu(cpu) { DEBUG("scheduling on %d\n", cpu); set_cpus_allowed(current, cpumask_of_cpu(cpu)); DEBUG("watchdog scheduled on cpu %d\n", smp_processor_id()); do_event_scan(event_scan); set_current_state(TASK_INTERRUPTIBLE); schedule_timeout(HZ); } unlock_cpu_hotplug(); if (surveillance_timeout != -1) { DEBUG("enabling surveillance\n"); enable_surveillance(surveillance_timeout); DEBUG("surveillance enabled\n"); } lock_cpu_hotplug(); cpu = first_cpu_const(mk_cpumask_const(cpu_online_map)); for (;;) { set_cpus_allowed(current, cpumask_of_cpu(cpu)); do_event_scan(event_scan); set_cpus_allowed(current, all); /* Drop hotplug lock, and sleep for a bit (at least * one second since some machines have problems if we * call event-scan too quickly). */ unlock_cpu_hotplug(); set_current_state(TASK_INTERRUPTIBLE); schedule_timeout((HZ*60/rtas_event_scan_rate) / 2); lock_cpu_hotplug(); cpu = next_cpu_const(cpu, mk_cpumask_const(cpu_online_map)); if (cpu == NR_CPUS) cpu = first_cpu_const(mk_cpumask_const(cpu_online_map)); } error: /* Should delete proc entries */ return -EINVAL; }
/* * This is the NFS server kernel thread */ static void nfsd(struct svc_rqst *rqstp) { struct svc_serv *serv = rqstp->rq_server; struct fs_struct *fsp; int err; struct nfsd_list me; sigset_t shutdown_mask, allowed_mask; /* Lock module and set up kernel thread */ lock_kernel(); daemonize("nfsd"); current->rlim[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY; /* After daemonize() this kernel thread shares current->fs * with the init process. We need to create files with a * umask of 0 instead of init's umask. */ fsp = copy_fs_struct(current->fs); if (!fsp) { printk("Unable to start nfsd thread: out of memory\n"); goto out; } exit_fs(current); current->fs = fsp; current->fs->umask = 0; siginitsetinv(&shutdown_mask, SHUTDOWN_SIGS); siginitsetinv(&allowed_mask, ALLOWED_SIGS); nfsdstats.th_cnt++; lockd_up(); /* start lockd */ me.task = current; list_add(&me.list, &nfsd_list); unlock_kernel(); /* * We want less throttling in balance_dirty_pages() so that nfs to * localhost doesn't cause nfsd to lock up due to all the client's * dirty pages. */ current->flags |= PF_LESS_THROTTLE; /* * The main request loop */ for (;;) { /* Block all but the shutdown signals */ sigprocmask(SIG_SETMASK, &shutdown_mask, NULL); /* * Find a socket with data available and call its * recvfrom routine. */ while ((err = svc_recv(serv, rqstp, 60*60*HZ)) == -EAGAIN) ; if (err < 0) break; update_thread_usage(atomic_read(&nfsd_busy)); atomic_inc(&nfsd_busy); /* Lock the export hash tables for reading. */ exp_readlock(); /* Process request with signals blocked. */ sigprocmask(SIG_SETMASK, &allowed_mask, NULL); svc_process(serv, rqstp); /* Unlock export hash tables */ exp_readunlock(); update_thread_usage(atomic_read(&nfsd_busy)); atomic_dec(&nfsd_busy); } if (err != -EINTR) { printk(KERN_WARNING "nfsd: terminating on error %d\n", -err); } else { unsigned int signo; for (signo = 1; signo <= _NSIG; signo++) if (sigismember(¤t->pending.signal, signo) && !sigismember(¤t->blocked, signo)) break; err = signo; } lock_kernel(); /* Release lockd */ lockd_down(); /* Check if this is last thread */ if (serv->sv_nrthreads==1) { printk(KERN_WARNING "nfsd: last server has exited\n"); if (err != SIG_NOCLEAN) { printk(KERN_WARNING "nfsd: unexporting all filesystems\n"); nfsd_export_flush(); } nfsd_serv = NULL; nfsd_racache_shutdown(); /* release read-ahead cache */ nfs4_state_shutdown(); } list_del(&me.list); nfsdstats.th_cnt --; out: /* Release the thread */ svc_exit_thread(rqstp); /* Release module */ module_put_and_exit(0); }
static int set_details() { #if (!TCPCOPY_PCAP) int rand_port; #else int len, rand_port; #endif unsigned int seed; struct timeval tp; /* generate a random port number for avoiding port conflicts */ gettimeofday(&tp, NULL); seed = tp.tv_usec; rand_port = (int) ((rand_r(&seed) / (RAND_MAX + 1.0)) * 512); clt_settings.rand_port_shifted = rand_port; if (clt_settings.session_timeout < 0) { clt_settings.session_timeout = DEFAULT_SESSION_TIMEOUT; } tc_log_info(LOG_NOTICE, 0, "session timeout:%d", clt_settings.session_timeout); if (clt_settings.session_keepalive_timeout <= 0) { clt_settings.session_keepalive_timeout = clt_settings.session_timeout + SESS_KEEPLIVE_ADD; } tc_log_info(LOG_NOTICE, 0, "keepalive timeout:%d", clt_settings.session_keepalive_timeout); if (clt_settings.raw_clt_tf_ip != NULL) { /* print out raw_clt_tf_ip */ tc_log_info(LOG_NOTICE, 0, "raw_clt_tf_ip:%s", clt_settings.raw_clt_tf_ip); retrieve_clt_tf_ips(); } /* set the ip port pair mapping according to settings */ if (retrieve_target_addresses(clt_settings.raw_transfer, &clt_settings.transfer) == -1) { return -1; } if (clt_settings.percentage < 0 || clt_settings.percentage > 99) { clt_settings.percentage = 0; } if (clt_settings.par_connections <= 0) { clt_settings.par_connections = 1; } else if (clt_settings.par_connections > MAX_CONNECTION_NUM) { clt_settings.par_connections = MAX_CONNECTION_NUM; } tc_log_info(LOG_NOTICE, 0, "parallel connections per target:%d", clt_settings.par_connections); if(isOfflineMode()) { if (clt_settings.pcap_file == NULL) { tc_log_info(LOG_ERR, 0, "it must have -i argument for offline"); fprintf(stderr, "no -i argument\n"); return -1; } if (clt_settings.accelerated_times < 1) { clt_settings.accelerated_times = 1; } tc_log_info(LOG_NOTICE, 0, "accelerated %d times,interval:%llu ms", clt_settings.accelerated_times, clt_settings.interval); if (clt_settings.interval > 0) { clt_settings.interval = clt_settings.interval * 1000; } } #if (TCPCOPY_PCAP_SEND) if (clt_settings.output_if_name != NULL) { tc_log_info(LOG_NOTICE, 0, "output device:%s", clt_settings.output_if_name); } else { tc_log_info(LOG_ERR, 0, "output device is null"); return -1; } #endif #if (TCPCOPY_PCAP) if (clt_settings.raw_device != NULL) { tc_log_info(LOG_NOTICE, 0, "device:%s", clt_settings.raw_device); if (strcmp(clt_settings.raw_device, DEFAULT_DEVICE) == 0) { clt_settings.raw_device = NULL; } else { retrieve_devices(clt_settings.raw_device, &(clt_settings.devices)); } } if (clt_settings.user_filter != NULL) { tc_log_info(LOG_NOTICE, 0, "user filter:%s", clt_settings.user_filter); len = strlen(clt_settings.user_filter); if (len >= MAX_FILTER_LENGH) { tc_log_info(LOG_ERR, 0, "user filter is too long"); return -1; } memcpy(clt_settings.filter, clt_settings.user_filter, len); } else { extract_filter(); } #endif #if (TCPCOPY_MYSQL_ADVANCED) if (clt_settings.user_pwd != NULL) { tc_log_info(LOG_NOTICE, 0, "-u argument:%s",clt_settings.user_pwd); if (retrieve_mysql_user_pwd_info(clt_settings.user_pwd) == -1) { tc_log_info(LOG_ERR, 0, "wrong -u argument"); return -1; } } else { tc_log_info(LOG_ERR, 0, "it must have -u argument"); fprintf(stderr, "no -u argument\n"); return -1; } #endif #if (TCPCOPY_DR) /* retrieve real server ip addresses */ if (clt_settings.raw_rs_list != NULL) { tc_log_info(LOG_NOTICE, 0, "s parameter:%s", clt_settings.raw_rs_list); retrieve_real_servers(); } else { tc_log_info(LOG_WARN, 0, "no real server ip addresses"); return -1; } #endif /* daemonize */ if (clt_settings.do_daemonize) { if (sigignore(SIGHUP) == -1) { tc_log_info(LOG_ERR, errno, "Failed to ignore SIGHUP"); } if (daemonize() == -1) { fprintf(stderr, "failed to daemonize() in order to daemonize\n"); return -1; } } return 0; }
int MODULEMAINFUNC (int argc, char** argv){ SOCKET sock = INVALID_SOCKET; int i=0; SASIZETYPE size; pthread_t thread; struct clientparam defparam; int demon=0; struct clientparam * newparam; char *s; int error = 0; unsigned sleeptime; struct extparam myconf; unsigned char buf[256]; struct pollfd fds; int opt = 1; PROXYFUNC pf; FILE *fp = NULL; int maxchild; int silent = 0; int nlog = 5000; char loghelp[] = #ifdef STDMAIN " -d go to background (daemon)\n" #endif " -fFORMAT logging format (see documentation)\n" " -l log to stderr\n" " -lFILENAME log to FILENAME\n" " -bBUFSIZE size of network buffer (default 4096 for TCP, 16384 for UDP)\n" #ifndef _WIN32 " -l@IDENT log to syslog IDENT\n" #endif " -t be silenT (do not log service start/stop)\n" " -iIP ip address or internal interface (clients are expected to connect)\n" " -eIP ip address or external interface (outgoing connection will have this)\n"; int childcount=0; pthread_mutex_t counter_mutex; #ifdef _WIN32 unsigned long ul; #endif #ifndef UDP int new_sock = INVALID_SOCKET; struct linger lg; #endif #ifdef _WIN32 HANDLE h; #endif #ifdef STDMAIN #ifdef _WIN32 WSADATA wd; WSAStartup(MAKEWORD( 1, 1 ), &wd); #else signal(SIGPIPE, SIG_IGN); pthread_attr_init(&pa); pthread_attr_setstacksize(&pa,PTHREAD_STACK_MIN + 16384); pthread_attr_setdetachstate(&pa,PTHREAD_CREATE_DETACHED); #endif #endif pf = childdef.pf; memcpy(&myconf, &conf, sizeof(myconf)); memset(&defparam, 0, sizeof(struct clientparam)); defparam.version = paused; defparam.childcount = &childcount; defparam.logfunc = myconf.logfunc; defparam.authfunc = myconf.authfunc; defparam.aclnum = myconf.aclnum; defparam.service = childdef.service; defparam.usentlm = 1; defparam.stdlog = NULL; defparam.time_start = time(NULL); maxchild = myconf.maxchild; #ifndef STDMAIN if(!conf.services){ conf.services = &defparam; } else { defparam.next = conf.services; conf.services = conf.services->prev = &defparam; } #endif pthread_mutex_init(defparam.counter_mutex = &counter_mutex, NULL); for (i=1; i<argc; i++) { if(*argv[i]=='-') { switch(argv[i][1]) { case 'd': if(!demon)daemonize(); demon = 1; break; case 'l': defparam.logfunc = logstdout; defparam.logtarget = (unsigned char*)mystrdup(argv[i]); if(argv[i][2]) { #ifdef STDMAIN if(argv[i][2]=='@'){ #ifndef _WIN32 openlog(argv[i]+3, LOG_PID, LOG_DAEMON); defparam.logfunc = logsyslog; #endif } else #endif { fp = fopen(argv[i] + 2, "a"); if (fp) { defparam.stdlog = fp; fseek(fp, 0L, SEEK_END); } } } break; case 'i': myconf.intip = getip((unsigned char *)argv[i]+2); break; case 'e': myconf.extip = getip((unsigned char *)argv[i]+2); break; case 'p': myconf.intport = atoi(argv[i]+2); break; case 'b': myconf.bufsize = atoi(argv[i]+2); break; case 'n': defparam.usentlm = 0; break; case 'f': defparam.logformat = (unsigned char *)argv[i] + 2; break; case 't': silent = 1; break; case 's': case 'a': myconf.singlepacket = 1 + atoi(argv[i]+2); break; default: error = 1; break; } } else break; } #ifndef STDMAIN if(childdef.port) { #endif #ifndef PORTMAP if (error || i!=argc) { #ifndef STDMAIN haveerror = 1; conf.threadinit = 0; #endif fprintf(stderr, "Usage: %s options\n" "Available options are:\n" "%s" " -pPORT - service port to accept connections\n" "%s" "\tExample: %s -i127.0.0.1\n\n" "%s", argv[0], loghelp, childdef.helpmessage, argv[0], #ifdef STDMAIN copyright #else "" #endif ); return (1); } #endif #ifndef STDMAIN } else { #endif #ifndef NOPORTMAP if (error || argc != i+3 || *argv[i]=='-'|| (myconf.intport = atoi(argv[i]))==0 || (defparam.targetport = htons((unsigned short)atoi(argv[i+2])))==0) { #ifndef STDMAIN haveerror = 1; conf.threadinit = 0; #endif fprintf(stderr, "Usage: %s options" " [-e<external_ip>] <port_to_bind>" " <target_hostname> <target_port>\n" "Available options are:\n" "%s" "%s" "\tExample: %s -d -i127.0.0.1 6666 serv.somehost.ru 6666\n\n" "%s", argv[0], loghelp, childdef.helpmessage, argv[0], #ifdef STDMAIN copyright #else "" #endif ); return (1); } defparam.target = (unsigned char *)mystrdup(argv[i+1]); #endif #ifndef STDMAIN } #endif if(!defparam.logformat){ defparam.logformat = myconf.logformat; } if(defparam.logformat){ if(*defparam.logformat == '-' && (s = strchr((char *)defparam.logformat + 1, '+')) && s[1]){ *s = 0; defparam.nonprintable = (unsigned char *)mystrdup((char *)defparam.logformat + 1); defparam.replace = s[1]; defparam.logformat = (unsigned char *)mystrdup(s + 2); *s = '+'; } else defparam.logformat = (unsigned char *)mystrdup((char *)defparam.logformat); } defparam.sinc.sin_addr.s_addr = defparam.intip = myconf.intip; if(!myconf.intport)myconf.intport = childdef.port; defparam.sinc.sin_port = defparam.intport = htons(myconf.intport); defparam.sins.sin_addr.s_addr = defparam.extip = myconf.extip; defparam.sins.sin_port = defparam.extport = htons(myconf.extport); defparam.remsock = defparam.clisock = defparam.ctrlsock = INVALID_SOCKET; defparam.sins.sin_family = defparam.sinc.sin_family = AF_INET; defparam.singlepacket = myconf.singlepacket; defparam.bufsize = myconf.bufsize; #ifndef STDMAIN conf.threadinit = 0; #endif #ifndef UDP lg.l_onoff = 1; lg.l_linger = conf.timeouts[STRING_L]; if( (sock=socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) { #else if( (sock=socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET) { #endif perror("socket()"); return -2; } #ifdef _WIN32 ioctlsocket(sock, FIONBIO, &ul); #else fcntl(sock,F_SETFL,O_NONBLOCK); #endif defparam.srvsock = sock; if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (unsigned char *)&opt, sizeof(int)))perror("setsockopt()"); size = sizeof(defparam.sinc); for(sleeptime = SLEEPTIME * 100; bind(sock, (struct sockaddr*)&defparam.sinc, size)==-1; usleep(sleeptime)) { sprintf((char *)buf, "bind(): %s", strerror(errno)); (*defparam.logfunc)(&defparam, buf); sleeptime = (sleeptime<<1); if(!sleeptime) { closesocket(sock); return -3; } } #ifndef UDP if(listen (sock, 1 + (maxchild>>4))==-1) { sprintf((char *)buf, "listen(): %s", strerror(errno)); (*defparam.logfunc)(&defparam, buf); return -4; } #else defparam.srvfds = &fds; defparam.clisock = sock; #endif defparam.threadid = (unsigned)pthread_self(); if(!silent){ sprintf((char *)buf, "Accepting connections [%u/%u]", (unsigned)getpid(), (unsigned)pthread_self()); (*defparam.logfunc)(&defparam, buf); } defparam.sinc.sin_addr.s_addr = defparam.sins.sin_addr.s_addr = 0; defparam.sinc.sin_port = defparam.sins.sin_port = 0; fds.fd = sock; fds.events = POLLIN; for (;;) { for(;;){ while((paused == defparam.version && childcount >= myconf.maxchild)){ nlog++; if(nlog > 5000) { sprintf((char *)buf, "Warning: too many connected clients (%d/%d)", childcount, myconf.maxchild); (*defparam.logfunc)(&defparam, buf); nlog = 0; } usleep(SLEEPTIME); } if (paused != defparam.version) break; if (fds.events & POLLIN) { error = poll(&fds, 1, 1000); } else { usleep(SLEEPTIME); continue; } if (error >= 1) break; if (error == 0) continue; sprintf((char *)buf, "poll(): %s/%d", strerror(errno), errno); (*defparam.logfunc)(&defparam, buf); if(errno != EAGAIN) break; continue; } if(paused != defparam.version) break; #ifndef UDP size = sizeof(defparam.sinc); new_sock = accept(sock, (struct sockaddr*)&defparam.sinc, &size); if(new_sock == INVALID_SOCKET){ sprintf((char *)buf, "accept(): %s", strerror(errno)); (*defparam.logfunc)(&defparam, buf); continue; } #ifdef _WIN32 ioctlsocket(new_sock, FIONBIO, &ul); #else fcntl(new_sock,F_SETFL,O_NONBLOCK); #endif setsockopt(new_sock, SOL_SOCKET, SO_LINGER, (unsigned char *)&lg, sizeof(lg)); setsockopt(new_sock, SOL_SOCKET, SO_OOBINLINE, (unsigned char *)&opt, sizeof(int)); #else fds.events = 0; #endif if(! (newparam = myalloc (sizeof(defparam)))){ #ifndef UDP closesocket(new_sock); #endif defparam.res = 21; (*defparam.logfunc)(&defparam, (unsigned char *)"Memory Allocation Failed"); usleep(SLEEPTIME); continue; }; memcpy(newparam, &defparam, sizeof(defparam)); clearstat(newparam); #ifndef UDP newparam->clisock = new_sock; #endif newparam->child = newparam->prev = newparam->next = NULL; newparam->parent = &defparam; pthread_mutex_lock(&counter_mutex); if(!defparam.child)defparam.child = newparam; else { newparam->next = defparam.child; defparam.child = defparam.child->prev = newparam; } #ifdef _WIN32 h = CreateThread((LPSECURITY_ATTRIBUTES )NULL, 16384, (LPTHREAD_START_ROUTINE)pf, (void *) newparam, (DWORD)0, &thread); newparam->threadid = (unsigned)thread; if (h) { childcount++; CloseHandle(h); } else { myfree(newparam); } #else if((error = pthread_create(&thread, &pa, pf, (void *)newparam))){ sprintf((char *)buf, "pthread_create(): %s", strerror(error)); (*defparam.logfunc)(&defparam, buf); freeparam(newparam); } else { childcount++; newparam->threadid = (unsigned)thread; } #endif pthread_mutex_unlock(&counter_mutex); memset(&defparam.sinc, 0, sizeof(defparam.sinc)); #ifdef UDP while(!fds.events)usleep(SLEEPTIME); #endif } if(defparam.srvsock != INVALID_SOCKET) closesocket(defparam.srvsock); if(!silent) defparam.logfunc(&defparam, (unsigned char *)"Exiting thread"); defparam.service = S_ZOMBIE; while(defparam.child) usleep(SLEEPTIME * 100); defparam.threadid = 0; if(fp) fclose(fp); if(defparam.target) myfree(defparam.target); if(defparam.logtarget) myfree(defparam.logtarget); if(defparam.logformat) myfree(defparam.logformat); if(defparam.nonprintable) myfree(defparam.nonprintable); #ifndef STDMAIN if(defparam.next)defparam.next->prev = defparam.prev; if(defparam.prev)defparam.prev->next = defparam.next; else conf.services = defparam.next; #endif pthread_mutex_destroy(&counter_mutex); return 0; }
int main(int argc, char *argv[]) { struct link *link, *query_port = 0; signed char ch; time_t current; int is_daemon = 0; char *pidfile = NULL; char *interface = NULL; char raddr[LINK_ADDRESS_MAX]; int rport; outgoing_host_list = list_create(); change_process_title_init(argv); debug_config(argv[0]); static const struct option long_options[] = { {"background", no_argument, 0, 'b'}, {"pid-file", required_argument, 0, 'B'}, {"debug", required_argument, 0, 'd'}, {"help", no_argument, 0, 'h'}, {"history", required_argument, 0, 'H'}, {"lifetime", required_argument, 0, 'l'}, {"update-log", required_argument, 0, 'L'}, {"max-jobs", required_argument, 0, 'm'}, {"server-size", required_argument, 0, 'M'}, {"name", required_argument, 0, 'n'}, {"interface", required_argument, 0, 'I'}, {"debug-file", required_argument, 0, 'o'}, {"debug-rotate-max", required_argument, 0, 'O'}, {"port", required_argument, 0, 'p'}, {"single", no_argument, 0, 'S'}, {"timeout", required_argument, 0, 'T'}, {"update-host", required_argument, 0, 'u'}, {"update-interval", required_argument, 0, 'U'}, {"version", no_argument, 0, 'v'}, {"port-file", required_argument, 0, 'Z'}, {0,0,0,0}}; while((ch = getopt_long(argc, argv, "bB:d:hH:I:l:L:m:M:n:o:O:p:ST:u:U:vZ:", long_options, NULL)) > -1) { switch (ch) { case 'b': is_daemon = 1; break; case 'B': free(pidfile); pidfile = strdup(optarg); break; case 'd': debug_flags_set(optarg); break; case 'h': default: show_help(argv[0]); return 1; case 'l': lifetime = string_time_parse(optarg); break; case 'L': logfilename = strdup(optarg); break; case 'H': history_dir = strdup(optarg); break; case 'I': free(interface); interface = strdup(optarg); break; case 'm': child_procs_max = atoi(optarg); break; case 'M': max_server_size = string_metric_parse(optarg); break; case 'n': preferred_hostname = optarg; break; case 'o': debug_config_file(optarg); break; case 'O': debug_config_file_size(string_metric_parse(optarg)); break; case 'p': port = atoi(optarg); break; case 'S': fork_mode = 0; break; case 'T': child_procs_timeout = string_time_parse(optarg); break; case 'u': list_push_head(outgoing_host_list, xxstrdup(optarg)); break; case 'U': outgoing_timeout = string_time_parse(optarg); break; case 'v': cctools_version_print(stdout, argv[0]); return 0; case 'Z': port_file = optarg; port = 0; break; } } if (is_daemon) daemonize(0, pidfile); cctools_version_debug(D_DEBUG, argv[0]); if(logfilename) { logfile = fopen(logfilename,"a"); if(!logfile) fatal("couldn't open %s: %s\n",optarg,strerror(errno)); } current = time(0); debug(D_NOTICE, "*** %s starting at %s", argv[0], ctime(¤t)); if(!list_size(outgoing_host_list)) { list_push_head(outgoing_host_list, CATALOG_HOST_DEFAULT); } install_handler(SIGPIPE, ignore_signal); install_handler(SIGHUP, ignore_signal); install_handler(SIGCHLD, ignore_signal); install_handler(SIGINT, shutdown_clean); install_handler(SIGTERM, shutdown_clean); install_handler(SIGQUIT, shutdown_clean); install_handler(SIGALRM, shutdown_clean); if(!preferred_hostname) { domain_name_cache_guess(hostname); preferred_hostname = hostname; } username_get(owner); starttime = time(0); table = jx_database_create(history_dir); if(!table) fatal("couldn't create directory %s: %s\n",history_dir,strerror(errno)); query_port = link_serve_address(interface, port); if(query_port) { /* If a port was chosen automatically, read it back so that the same one can be used for the update port. There is the possibility that the UDP listen will fail because that port is in use. */ if(port==0) { char addr[LINK_ADDRESS_MAX]; link_address_local(query_port,addr,&port); } } else { if(interface) fatal("couldn't listen on TCP address %s port %d", interface, port); else fatal("couldn't listen on TCP port %d", port); } update_dgram = datagram_create_address(interface, port); if(!update_dgram) { if(interface) fatal("couldn't listen on UDP address %s port %d", interface, port); else fatal("couldn't listen on UDP port %d", port); } update_port = link_serve_address(interface,port+1); if(!update_port) { if(interface) fatal("couldn't listen on TCP address %s port %d", interface, port+1); else fatal("couldn't listen on TCP port %d", port+1); } opts_write_port_file(port_file,port); while(1) { fd_set rfds; int dfd = datagram_fd(update_dgram); int lfd = link_fd(query_port); int ufd = link_fd(update_port); int result, maxfd; struct timeval timeout; remove_expired_records(); if(time(0) > outgoing_alarm) { update_all_catalogs(); outgoing_alarm = time(0) + outgoing_timeout; } while(1) { int status; pid_t pid = waitpid(-1, &status, WNOHANG); if(pid>0) { child_procs_count--; continue; } else { break; } } FD_ZERO(&rfds); FD_SET(dfd, &rfds); FD_SET(ufd, &rfds); if(child_procs_count < child_procs_max) { FD_SET(lfd, &rfds); } maxfd = MAX(ufd,MAX(dfd, lfd)) + 1; timeout.tv_sec = 5; timeout.tv_usec = 0; result = select(maxfd, &rfds, 0, 0, &timeout); if(result <= 0) continue; if(FD_ISSET(dfd, &rfds)) { handle_udp_updates(update_dgram); } if(FD_ISSET(ufd, &rfds)) { handle_tcp_update(update_port); } if(FD_ISSET(lfd, &rfds)) { link = link_accept(query_port, time(0) + 5); if(link) { if(fork_mode) { pid_t pid = fork(); if(pid == 0) { link_address_remote(link, raddr, &rport); change_process_title("catalog_server [%s]", raddr); alarm(child_procs_timeout); handle_query(link); _exit(0); } else if (pid>0) { child_procs_count++; } } else { handle_query(link); } link_close(link); } } } return 1; }
OPENVPN_EXPORT openvpn_plugin_handle_t openvpn_plugin_open_v1 (unsigned int *type_mask, const char *argv[], const char *envp[]) { pid_t pid; int fd[2]; struct auth_pam_context *context; struct name_value_list name_value_list; const int base_parms = 2; /* * Allocate our context */ context = (struct auth_pam_context *) calloc (1, sizeof (struct auth_pam_context)); if (!context) goto error; context->foreground_fd = -1; /* * Intercept the --auth-user-pass-verify callback. */ *type_mask = OPENVPN_PLUGIN_MASK (OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY); /* * Make sure we have two string arguments: the first is the .so name, * the second is the PAM service type. */ if (string_array_len (argv) < base_parms) { fprintf (stderr, "AUTH-PAM: need PAM service parameter\n"); goto error; } /* * See if we have optional name/value pairs to match against * PAM module queried fields in the conversation function. */ name_value_list.len = 0; if (string_array_len (argv) > base_parms) { const int nv_len = string_array_len (argv) - base_parms; int i; if ((nv_len & 1) == 1 || (nv_len / 2) > N_NAME_VALUE) { fprintf (stderr, "AUTH-PAM: bad name/value list length\n"); goto error; } name_value_list.len = nv_len / 2; for (i = 0; i < name_value_list.len; ++i) { const int base = base_parms + i * 2; name_value_list.data[i].name = argv[base]; name_value_list.data[i].value = argv[base+1]; } } /* * Get verbosity level from environment */ { const char *verb_string = get_env ("verb", envp); if (verb_string) context->verb = atoi (verb_string); } /* * Make a socket for foreground and background processes * to communicate. */ if (socketpair (PF_UNIX, SOCK_DGRAM, 0, fd) == -1) { fprintf (stderr, "AUTH-PAM: socketpair call failed\n"); goto error; } /* * Fork off the privileged process. It will remain privileged * even after the foreground process drops its privileges. */ pid = fork (); if (pid) { int status; /* * Foreground Process */ context->background_pid = pid; /* close our copy of child's socket */ close (fd[1]); /* don't let future subprocesses inherit child socket */ if (fcntl (fd[0], F_SETFD, FD_CLOEXEC) < 0) fprintf (stderr, "AUTH-PAM: Set FD_CLOEXEC flag on socket file descriptor failed\n"); /* wait for background child process to initialize */ status = recv_control (fd[0]); if (status == RESPONSE_INIT_SUCCEEDED) { context->foreground_fd = fd[0]; return (openvpn_plugin_handle_t) context; } } else { /* * Background Process */ /* close all parent fds except our socket back to parent */ close_fds_except (fd[1]); /* Ignore most signals (the parent will receive them) */ set_signals (); #ifdef DO_DAEMONIZE /* Daemonize if --daemon option is set. */ daemonize (envp); #endif /* execute the event loop */ pam_server (fd[1], argv[1], context->verb, &name_value_list); close (fd[1]); exit (0); return 0; /* NOTREACHED */ } error: if (context) free (context); return NULL; }
int main (int argc, char **argv) { int i, c; int pid_flags = 0; char *user = NULL; char *password = NULL; char *timeout = NULL; char *method = NULL; char *pid_path = NULL; char *conf_path = NULL; char *iface = NULL; int server_num = 0; const char *server_host[MAX_REMOTE_NUM]; const char *server_port = NULL; int dns_thread_num = DNS_THREAD_NUM; int option_index = 0; static struct option long_options[] = { {"fast-open", no_argument, 0, 0 }, {"port-start", required_argument, 0, 0 }, {"port-end", required_argument, 0, 0 }, {0, 0, 0, 0 } }; opterr = 0; while ((c = getopt_long(argc, argv, "f:s:p:l:k:t:m:c:i:d:a:uv", long_options, &option_index)) != -1) { printf("option_index %d\n", option_index); switch (c) { case 0: if (option_index == 0) { #ifdef TCP_FASTOPEN fast_open = 1; LOGD("using tcp fast open"); #else LOGE("tcp fast open is not supported by this environment"); #endif } else if (option_index == 1) { start_port = atoi(optarg); } else if (option_index == 2) { end_port = atoi(optarg); } break; case 's': server_host[server_num++] = optarg; break; case 'p': server_port = optarg; break; case 'k': password = optarg; break; case 'f': pid_flags = 1; pid_path = optarg; break; case 't': timeout = optarg; break; case 'm': method = optarg; break; case 'c': conf_path = optarg; break; case 'i': iface = optarg; break; case 'd': dns_thread_num = atoi(optarg); if (!dns_thread_num) FATAL("Invalid DNS thread number"); break; case 'a': user = optarg; break; case 'u': udprelay = 1; break; case 'v': verbose = 1; break; } } printf("start %d end %d\n", start_port, end_port); if (opterr) { usage(); exit(EXIT_FAILURE); } if (conf_path != NULL) { jconf_t *conf = read_jconf(conf_path); if (server_num == 0) { server_num = conf->remote_num; for (i = 0; i < server_num; i++) { server_host[i] = conf->remote_addr[i].host; } } if (server_port == NULL) server_port = conf->remote_port; if (password == NULL) password = conf->password; if (method == NULL) method = conf->method; if (timeout == NULL) timeout = conf->timeout; #ifdef TCP_FASTOPEN if (fast_open == 0) fast_open = conf->fast_open; #endif #ifdef HAVE_SETRLIMIT if (nofile == 0) nofile = conf->nofile; /* * no need to check the return value here since we will show * the user an error message if setrlimit(2) fails */ if (nofile) { if (verbose) { LOGD("setting NOFILE to %d", nofile); } set_nofile(nofile); } #endif } if ((start_port > 0 && end_port <= 0) || (start_port <= 0 && end_port > 0)) { printf("Both start_prot and end_port needs to be specified\n"); usage(); exit(EXIT_FAILURE); } if (server_port != NULL && start_port > 0) { printf("server port can't be set if you want to use a port range\n"); usage(); exit(EXIT_FAILURE); } if (server_num == 0 || (server_port == NULL && start_port <= 0) || password == NULL) { usage(); exit(EXIT_FAILURE); } if (timeout == NULL) timeout = "60"; if (pid_flags) { USE_SYSLOG(argv[0]); daemonize(pid_path); } // ignore SIGPIPE signal(SIGPIPE, SIG_IGN); signal(SIGCHLD, SIG_IGN); signal(SIGABRT, SIG_IGN); // setup asyncns asyncns_t *asyncns; if (!(asyncns = asyncns_new(dns_thread_num))) { FATAL("asyncns failed"); } // setup keys LOGD("initialize ciphers... %s", method); int m = enc_init(password, method); // inilitialize ev loop struct ev_loop *loop = EV_DEFAULT; // inilitialize listen context struct listen_ctx listen_ctx_list[server_num + 1]; // bind to each interface while (server_num > 0) { int index = --server_num; const char* host = server_host[index]; int success = 1; int listenfd; if (start_port > 0) { server_port = itoa(start_port); } do { // Bind to port listenfd = create_and_bind(host, server_port); success = 1; if (listenfd < 0) { success = 0; } if (listen(listenfd, SOMAXCONN) == -1) { success = 0; } if (!success) { if (start_port < end_port) { start_port++; server_port = itoa(start_port); } else { FATAL("Out of listen ports!"); exit(1); } } } while (!success); setnonblocking(listenfd); LOGD("server listening at port %s.", server_port); struct listen_ctx *listen_ctx = &listen_ctx_list[index + 1]; // Setup proxy context listen_ctx->timeout = atoi(timeout); listen_ctx->asyncns = asyncns; listen_ctx->fd = listenfd; listen_ctx->method = m; listen_ctx->iface = iface; ev_io_init (&listen_ctx->io, accept_cb, listenfd, EV_READ); ev_io_start (loop, &listen_ctx->io); } // initialize the DNS struct listen_ctx *listen_ctx = &listen_ctx_list[0]; int asyncnsfd = asyncns_fd(asyncns); listen_ctx->timeout = atoi(timeout); listen_ctx->asyncns = asyncns; listen_ctx->fd = asyncnsfd; listen_ctx->method = m; listen_ctx->iface = iface; ev_io_init (&listen_ctx->io, server_resolve_cb, asyncnsfd, EV_READ); ev_io_start (loop, &listen_ctx->io); // Setup UDP if (udprelay) { LOGD("udprelay enabled."); udprelay_init(server_host[0], server_port, dns_thread_num, m, listen_ctx->timeout, iface); } // setuid if (user != NULL) run_as(user); // start ev loop ev_run (loop, 0); return 0; }
static int dpram_thread(void *data) { int ret = 0; //unsigned long flags; struct file *filp; dpram_task = current; daemonize("dpram_thread"); //reparent_to_init(); // for 2.6 kernel porting : this seems not to be used in driver // current->tty = NULL; // for 2.6 kernel porting strcpy(current->comm, "multipdp"); /* set signals to accept */ //spin_lock_irqsave(¤t->sigmask_lock, flags); // for 2.6 kernel proting siginitsetinv(¤t->blocked, sigmask(SIGUSR1)); //recalc_sigpending(current); recalc_sigpending(); //spin_unlock_irqrestore(¤t->sigmask_lock, flags); // for 2.6 kernel proting filp = dpram_open(); if (filp == NULL) { goto out; } dpram_filp = filp; /* send start signal */ complete(&dpram_complete); while (1) { ret = dpram_poll(filp); if (ret == -ERESTARTSYS) { if (sigismember(¤t->pending.signal, SIGUSR1)) { printk(KERN_ERR "MULTIPDP (%s) DPRAM device communication interrupted\n",__func__); sigdelset(¤t->pending.signal, SIGUSR1); recalc_sigpending(); ret = 0; break; } } else if (ret < 0) { EPRINTK("dpram_poll() failed\n"); break; } else { char ch; dpram_read(dpram_filp, &ch, sizeof(ch)); if (ch == 0x7f) { pdp_demux(); } } try_to_freeze(); } dpram_close(filp); dpram_filp = NULL; out: dpram_task = NULL; /* send finish signal and exit */ complete_and_exit(&dpram_complete, ret); }
//-----main function------------------------------------------------------------------------------------------------------------ int main( int argc, char *argv[] ) { if (argc == 2) //shortcut to daemonize or not { if (strcmp(argv[1],"1") == 0) {daemonize();} } struct clientParams controlClient[MAXTHREADS]; //array of struct which control the threads pthread_t clientThreads[MAXTHREADS]; //array of threads int clientSocket[MAXTHREADS]; int yes = 1; //used in setsockopt function int sockfd, new_fd; // listen on sock_fd, new connection on new_fd struct sockaddr_in my_addr; // my address information struct sockaddr_in their_addr; // connector's address information socklen_t sin_size; int i=0; FILE *fUser; //the users present in the file are copied to the array if(fUser=fopen("user.txt","r")) { while(fscanf(fUser,"%s %s",userInfo[numUsers].user, userInfo[numUsers].pass)==2) { numUsers++;} fclose(fUser); } if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); } if (setsockopt(sockfd,SOL_SOCKET, SO_REUSEADDR, &yes,sizeof(int)) == -1) { perror("setsockopt"); exit(1); } my_addr.sin_family = AF_INET; // host byte order my_addr.sin_port = htons(MYPORT); // short, network byte order my_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IP memset(my_addr.sin_zero, '\0', sizeof my_addr.sin_zero); if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof my_addr) == -1) { perror("bind"); exit(1); } if (listen(sockfd, BACKLOG) == -1) { perror("listen"); exit(1); } int reset = 0; //checks if all the threads are used struct timeval timeout; //used for creating the timeout timeout.tv_usec = 0; //needed as parameter, else timeout doesnt work since it takes any random value char recvCheck[DATASIZE]; //recieve the message during timeout, control for setsockopt for(;;) { printf("id: %d Waiting for a connection...\n", getpid()); //since we use 2 threads for each client, other connections with 1 socket are denied if ((clientSocket[i] = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1) { perror("accept");} //1st connection timeout.tv_sec = 1; //timeout is set to 1 sec if(setsockopt(clientSocket[i], SOL_SOCKET, SO_RCVTIMEO, (struct timeout *)&timeout, sizeof(timeout)) < 0) {perror("setsockopt failed");} recv(clientSocket[i], recvCheck, DATASIZE, 0); //recv is active for 1 sec timeout.tv_sec = 0; //timeout is disabled if(setsockopt(clientSocket[i], SOL_SOCKET, SO_RCVTIMEO, (struct timeout *)&timeout, sizeof(timeout)) < 0) {perror("setsockopt failed");} if (strcmp(recvCheck, "thing") == 0) //if the right string was recieved during 1 sec, accept the connection from next socket, run the program { printf("I got the right thing.\n"); if ((clientSocket[i+1] = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1) { perror("accept");} printf("Accepted Connections\n"); if (reset) //if reset=1, join present i and i+1 threads before creating new threads { pthread_tryjoin_np(clientThreads[i], NULL); pthread_tryjoin_np(clientThreads[i+1], NULL); } printf("Creating thread %d\n", i); //Thread 1: listener function controlClient[i].threadId=i; controlClient[i].clientSocket=clientSocket[i]; controlClient[i].recvError = 0; pthread_create(&clientThreads[i], NULL, &serverListener, &controlClient[i]); printf("Creating thread %d\n", i+1); //Thread 2: sender function controlClient[i+1].threadId=(i+1); controlClient[i+1].clientSocket=clientSocket[i+1]; controlClient[i+1].recvError = 0; pthread_create(&clientThreads[i+1], NULL, &serverSender, &controlClient[i+1]); i+=2; //increased by 2 since threads work in pairs if (i == MAXTHREADS) //if all threads are used, start over from 0 { i = 0; reset = 1; } strcpy(recvCheck, " "); //reset the recvCheck to check further incoming connections } else //if nothing or something wrong with one socket was recieved, close the current socket and restart the loop { printf("I didnt get the right thing. Closing socket.\n"); close(clientSocket[i]); } } return 0; }
/* init phase : * 1) read configuration file * 2) read command line arguments * 3) daemonize * 4) check and write pid file * 5) set startup time stamp * 6) compute presentation URL * 7) set signal handlers */ static int init(int argc, char **argv) { int i; int pid; int debug_flag = 0; int verbose_flag = 0; int options_flag = 0; struct sigaction sa; const char * presurl = NULL; const char * optionsfile = "/etc/minidlna.conf"; char mac_str[13]; char *string, *word; char *path; char buf[PATH_MAX]; char ip_addr[INET_ADDRSTRLEN + 3] = {'\0'}; char log_str[75] = "general,artwork,database,inotify,scanner,metadata,http,ssdp,tivo=warn"; char *log_level = NULL; struct media_dir_s *media_dir; media_types types; uid_t uid = -1; /* first check if "-f" option is used */ for (i=2; i<argc; i++) { if (strcmp(argv[i-1], "-f") == 0) { optionsfile = argv[i]; options_flag = 1; break; } } /* set up uuid based on mac address */ if (getsyshwaddr(mac_str, sizeof(mac_str)) < 0) { DPRINTF(E_OFF, L_GENERAL, "No MAC address found. Falling back to generic UUID.\n"); strcpy(mac_str, "554e4b4e4f57"); } strcpy(uuidvalue+5, "4d696e69-444c-164e-9d41-"); strncat(uuidvalue, mac_str, 12); getfriendlyname(friendly_name, FRIENDLYNAME_MAX_LEN); runtime_vars.port = -1; runtime_vars.notify_interval = 895; /* seconds between SSDP announces */ runtime_vars.root_container = NULL; /* read options file first since * command line arguments have final say */ if (readoptionsfile(optionsfile) < 0) { /* only error if file exists or using -f */ if(access(optionsfile, F_OK) == 0 || options_flag) DPRINTF(E_FATAL, L_GENERAL, "Error reading configuration file %s\n", optionsfile); } for (i=0; i<num_options; i++) { switch (ary_options[i].id) { case UPNPIFNAME: for (string = ary_options[i].value; (word = strtok(string, ",")); string = NULL) { if (n_lan_addr < MAX_LAN_ADDR) { if (getifaddr(word, ip_addr, sizeof(ip_addr)) >= 0) { if (*ip_addr && parselanaddr(&lan_addr[n_lan_addr], ip_addr) == 0) if (n_lan_addr < MAX_LAN_ADDR) n_lan_addr++; } } else DPRINTF(E_ERROR, L_GENERAL, "Too many listening ips (max: %d), ignoring %s\n", MAX_LAN_ADDR, word); } break; case UPNPLISTENING_IP: if (n_lan_addr < MAX_LAN_ADDR) { if (parselanaddr(&lan_addr[n_lan_addr], ary_options[i].value) == 0) n_lan_addr++; } else DPRINTF(E_ERROR, L_GENERAL, "Too many listening ips (max: %d), ignoring %s\n", MAX_LAN_ADDR, ary_options[i].value); break; case UPNPPORT: runtime_vars.port = atoi(ary_options[i].value); break; case UPNPPRESENTATIONURL: presurl = ary_options[i].value; break; case UPNPNOTIFY_INTERVAL: runtime_vars.notify_interval = atoi(ary_options[i].value); break; case UPNPSERIAL: strncpyt(serialnumber, ary_options[i].value, SERIALNUMBER_MAX_LEN); break; case UPNPMODEL_NAME: strncpyt(modelname, ary_options[i].value, MODELNAME_MAX_LEN); break; case UPNPMODEL_NUMBER: strncpyt(modelnumber, ary_options[i].value, MODELNUMBER_MAX_LEN); break; case UPNPFRIENDLYNAME: strncpyt(friendly_name, ary_options[i].value, FRIENDLYNAME_MAX_LEN); break; case UPNPMEDIADIR: types = ALL_MEDIA; path = ary_options[i].value; word = strchr(path, ','); if (word && (access(path, F_OK) != 0)) { types = 0; while (*path) { if (*path == ',') { path++; break; } else if (*path == 'A' || *path == 'a') types |= TYPE_AUDIO; else if (*path == 'V' || *path == 'v') types |= TYPE_VIDEO; else if (*path == 'P' || *path == 'p') types |= TYPE_IMAGES; else DPRINTF(E_FATAL, L_GENERAL, "Media directory entry not understood [%s]\n", ary_options[i].value); path++; } } path = realpath(path, buf); if (!path || access(path, F_OK) != 0) { DPRINTF(E_ERROR, L_GENERAL, "Media directory \"%s\" not accessible [%s]\n", ary_options[i].value, strerror(errno)); break; } media_dir = calloc(1, sizeof(struct media_dir_s)); media_dir->path = strdup(path); media_dir->types = types; if (media_dirs) { struct media_dir_s *all_dirs = media_dirs; while( all_dirs->next ) all_dirs = all_dirs->next; all_dirs->next = media_dir; } else media_dirs = media_dir; break; case UPNPALBUMART_NAMES: for (string = ary_options[i].value; (word = strtok(string, "/")); string = NULL) { struct album_art_name_s * this_name = calloc(1, sizeof(struct album_art_name_s)); int len = strlen(word); if (word[len-1] == '*') { word[len-1] = '\0'; this_name->wildcard = 1; } this_name->name = strdup(word); if (album_art_names) { struct album_art_name_s * all_names = album_art_names; while( all_names->next ) all_names = all_names->next; all_names->next = this_name; } else album_art_names = this_name; } break; case UPNPDBDIR: path = realpath(ary_options[i].value, buf); if (!path) path = (ary_options[i].value); make_dir(path, S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO); if (access(path, F_OK) != 0) DPRINTF(E_FATAL, L_GENERAL, "Database path not accessible! [%s]\n", path); strncpyt(db_path, path, PATH_MAX); break; case UPNPLOGDIR: path = realpath(ary_options[i].value, buf); if (!path) path = (ary_options[i].value); make_dir(path, S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO); if (access(path, F_OK) != 0) DPRINTF(E_FATAL, L_GENERAL, "Log path not accessible! [%s]\n", path); strncpyt(log_path, path, PATH_MAX); break; case UPNPLOGLEVEL: log_level = ary_options[i].value; break; case UPNPINOTIFY: if ((strcmp(ary_options[i].value, "yes") != 0) && !atoi(ary_options[i].value)) CLEARFLAG(INOTIFY_MASK); break; case ENABLE_TIVO: if ((strcmp(ary_options[i].value, "yes") == 0) || atoi(ary_options[i].value)) SETFLAG(TIVO_MASK); break; case ENABLE_DLNA_STRICT: if ((strcmp(ary_options[i].value, "yes") == 0) || atoi(ary_options[i].value)) SETFLAG(DLNA_STRICT_MASK); break; case ROOT_CONTAINER: switch (ary_options[i].value[0]) { case '.': runtime_vars.root_container = NULL; break; case 'B': case 'b': runtime_vars.root_container = BROWSEDIR_ID; break; case 'M': case 'm': runtime_vars.root_container = MUSIC_ID; break; case 'V': case 'v': runtime_vars.root_container = VIDEO_ID; break; case 'P': case 'p': runtime_vars.root_container = IMAGE_ID; break; default: DPRINTF(E_ERROR, L_GENERAL, "Invalid root container! [%s]\n", ary_options[i].value); break; } break; case UPNPMINISSDPDSOCKET: minissdpdsocketpath = ary_options[i].value; break; case UPNPUUID: strcpy(uuidvalue+5, ary_options[i].value); break; case USER_ACCOUNT: uid = strtol(ary_options[i].value, &string, 0); if (*string) { /* Symbolic username given, not UID. */ struct passwd *entry = getpwnam(ary_options[i].value); if (!entry) DPRINTF(E_FATAL, L_GENERAL, "Bad user '%s'.\n", argv[i]); uid = entry->pw_uid; } break; default: DPRINTF(E_ERROR, L_GENERAL, "Unknown option in file %s\n", optionsfile); } } if (log_path[0] == '\0') { if (db_path[0] == '\0') strncpyt(log_path, DEFAULT_LOG_PATH, PATH_MAX); else strncpyt(log_path, db_path, PATH_MAX); } if (db_path[0] == '\0') strncpyt(db_path, DEFAULT_DB_PATH, PATH_MAX); /* command line arguments processing */ for (i=1; i<argc; i++) { if (argv[i][0] != '-') { DPRINTF(E_FATAL, L_GENERAL, "Unknown option: %s\n", argv[i]); } else if (strcmp(argv[i], "--help") == 0) { runtime_vars.port = 0; break; } else switch(argv[i][1]) { case 't': if (i+1 < argc) runtime_vars.notify_interval = atoi(argv[++i]); else DPRINTF(E_FATAL, L_GENERAL, "Option -%c takes one argument.\n", argv[i][1]); break; case 's': if (i+1 < argc) strncpyt(serialnumber, argv[++i], SERIALNUMBER_MAX_LEN); else DPRINTF(E_FATAL, L_GENERAL, "Option -%c takes one argument.\n", argv[i][1]); break; case 'm': if (i+1 < argc) strncpyt(modelnumber, argv[++i], MODELNUMBER_MAX_LEN); else DPRINTF(E_FATAL, L_GENERAL, "Option -%c takes one argument.\n", argv[i][1]); break; case 'p': if (i+1 < argc) runtime_vars.port = atoi(argv[++i]); else DPRINTF(E_FATAL, L_GENERAL, "Option -%c takes one argument.\n", argv[i][1]); break; case 'P': if (i+1 < argc) { if (argv[++i][0] != '/') DPRINTF(E_FATAL, L_GENERAL, "Option -%c requires an absolute filename.\n", argv[i-1][1]); else pidfilename = argv[i]; } else DPRINTF(E_FATAL, L_GENERAL, "Option -%c takes one argument.\n", argv[i][1]); break; case 'd': debug_flag = 1; case 'v': verbose_flag = 1; break; case 'L': SETFLAG(NO_PLAYLIST_MASK); break; case 'w': if (i+1 < argc) presurl = argv[++i]; else DPRINTF(E_FATAL, L_GENERAL, "Option -%c takes one argument.\n", argv[i][1]); break; case 'a': if (i+1 < argc) { int address_already_there = 0; int j; i++; for (j=0; j<n_lan_addr; j++) { struct lan_addr_s tmpaddr; parselanaddr(&tmpaddr, argv[i]); if(0 == strcmp(lan_addr[j].str, tmpaddr.str)) address_already_there = 1; } if (address_already_there) break; if (n_lan_addr < MAX_LAN_ADDR) { if (parselanaddr(&lan_addr[n_lan_addr], argv[i]) == 0) n_lan_addr++; } else DPRINTF(E_ERROR, L_GENERAL, "Too many listening ips (max: %d), ignoring %s\n", MAX_LAN_ADDR, argv[i]); } else DPRINTF(E_FATAL, L_GENERAL, "Option -%c takes one argument.\n", argv[i][1]); break; case 'i': if (i+1 < argc) { int address_already_there = 0; int j; i++; if (getifaddr(argv[i], ip_addr, sizeof(ip_addr)) < 0) DPRINTF(E_FATAL, L_GENERAL, "Required network interface '%s' not found.\n", argv[i]); for (j=0; j<n_lan_addr; j++) { struct lan_addr_s tmpaddr; parselanaddr(&tmpaddr, ip_addr); if(strcmp(lan_addr[j].str, tmpaddr.str) == 0) address_already_there = 1; } if (address_already_there) break; if (n_lan_addr < MAX_LAN_ADDR) { if(parselanaddr(&lan_addr[n_lan_addr], ip_addr) == 0) n_lan_addr++; } else DPRINTF(E_ERROR, L_GENERAL, "Too many listening ips (max: %d), ignoring %s\n", MAX_LAN_ADDR, argv[i]); } else DPRINTF(E_FATAL, L_GENERAL, "Option -%c takes one argument.\n", argv[i][1]); break; case 'f': i++; /* discarding, the config file is already read */ break; case 'h': runtime_vars.port = 0; // triggers help display break; case 'R': snprintf(buf, sizeof(buf), "rm -rf %s/files.db %s/art_cache", db_path, db_path); if (system(buf) != 0) DPRINTF(E_FATAL, L_GENERAL, "Failed to clean old file cache. EXITING\n"); break; case 'u': if (i+1 != argc) { i++; uid = strtol(argv[i], &string, 0); if (*string) { /* Symbolic username given, not UID. */ struct passwd *entry = getpwnam(argv[i]); if (!entry) DPRINTF(E_FATAL, L_GENERAL, "Bad user '%s'.\n", argv[i]); uid = entry->pw_uid; } } else DPRINTF(E_FATAL, L_GENERAL, "Option -%c takes one argument.\n", argv[i][1]); break; break; #ifdef __linux__ case 'S': SETFLAG(SYSTEMD_MASK); break; #endif case 'V': printf("Version " MINIDLNA_VERSION "\n"); exit(0); break; default: DPRINTF(E_ERROR, L_GENERAL, "Unknown option: %s\n", argv[i]); } } /* If no IP was specified, try to detect one */ if (n_lan_addr < 1) { if (getsysaddrs() <= 0) DPRINTF(E_FATAL, L_GENERAL, "No IP address automatically detected!\n"); } if (!n_lan_addr || runtime_vars.port <= 0) { DPRINTF(E_ERROR, L_GENERAL, "Usage:\n\t" "%s [-d] [-v] [-f config_file]\n" "\t\t[-a listening_ip] [-p port]\n" /*"[-l logfile] " not functionnal */ "\t\t[-s serial] [-m model_number] \n" "\t\t[-t notify_interval] [-P pid_filename]\n" "\t\t[-u uid_to_run_as]\n" "\t\t[-w url] [-R] [-V] [-h]\n" "\nNotes:\n\tNotify interval is in seconds. Default is 895 seconds.\n" "\tDefault pid file is %s.\n" "\tWith -d minidlna will run in debug mode (not daemonize).\n" "\t-w sets the presentation url. Default is http address on port 80\n" "\t-h displays this text\n" "\t-R forces a full rescan\n" "\t-L do note create playlists\n" #ifdef __linux__ "\t-S changes behaviour for systemd\n" #endif "\t-V print the version number\n", argv[0], pidfilename); return 1; } if (verbose_flag) { strcpy(log_str+65, "debug"); log_level = log_str; } else if (!log_level) log_level = log_str; /* Set the default log file path to NULL (stdout) */ path = NULL; if (debug_flag) { pid = getpid(); strcpy(log_str+65, "maxdebug"); log_level = log_str; } else if (GETFLAG(SYSTEMD_MASK)) { pid = getpid(); } else { pid = daemonize(); #ifdef READYNAS unlink("/ramfs/.upnp-av_scan"); path = "/var/log/upnp-av.log"; #else if (access(db_path, F_OK) != 0) make_dir(db_path, S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO); snprintf(buf, sizeof(buf), "%s/minidlna.log", log_path); path = buf; #endif } log_init(path, log_level); if (checkforrunning(pidfilename) < 0) { DPRINTF(E_ERROR, L_GENERAL, "MiniDLNA is already running. EXITING.\n"); return 1; } set_startup_time(); /* presentation url */ if (presurl) strncpyt(presentationurl, presurl, PRESENTATIONURL_MAX_LEN); else strcpy(presentationurl, "/"); /* set signal handlers */ memset(&sa, 0, sizeof(struct sigaction)); sa.sa_handler = sigterm; if (sigaction(SIGTERM, &sa, NULL)) DPRINTF(E_FATAL, L_GENERAL, "Failed to set %s handler. EXITING.\n", SIGTERM); if (sigaction(SIGINT, &sa, NULL)) DPRINTF(E_FATAL, L_GENERAL, "Failed to set %s handler. EXITING.\n", SIGINT); if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) DPRINTF(E_FATAL, L_GENERAL, "Failed to set %s handler. EXITING.\n", SIGPIPE); if (writepidfile(pidfilename, pid, uid) != 0) pidfilename = NULL; if (uid != -1 && setuid(uid) == -1) DPRINTF(E_FATAL, L_GENERAL, "Failed to switch to uid '%d'. [%s] EXITING.\n", uid, strerror(errno)); return 0; }
int main(int argc, char **argv) { void *mod_routing = NULL; char *conffile = NULL; FILE *file = NULL; int nofork = 1; char str[100]; int c = 0; char b_log = 1; char b_fork = 1; memset(&str, 0, 100*sizeof(char)); log_init("logFile",NULL); log2display(LOG_ALERT); p_threadpool = threadpool_create(5, 8096, 0); init_maps(); init_call_id(NULL); while((c=getopt(argc, argv, "c:vP:fhD:"))!=-1) { switch(c) { case 'c': conffile = optarg; break; case 'v': printf("sip2smpp version: %s\n", VERSION); exit(0); break; case 'P': pid_file = optarg; break; case 'f': nofork = 0; b_fork = 0; break; case 'h': usage(0); break; case 'D': { char log = atoi(optarg); if(log >= 0 && log <= 8) { log2display((Loglevel)log); b_log = 0; } break; } default: abort(); } } if(!conffile) { conffile = (char*)malloc(sizeof(char)*strlen(DEFAULT_CONFIG)+1); strcpy(conffile,DEFAULT_CONFIG); } if((file = fopen(conffile,"r")) != NULL) { fclose(file); } else { ERROR(LOG_FILE | LOG_SCREEN,"The INI file isn't found!"); handler(-1); } if(load_config_file((uint8_t*)conffile, CONFIG_ALL, NULL) == -1) { ERROR(LOG_FILE | LOG_SCREEN,"There are errors in the INI file!"); free_config_file(CONFIG_ALL, NULL); handler(-1); } if(b_log) { log2display((Loglevel)cfg_main->log_level); } if(b_fork) { nofork = !cfg_main->fork; } if(daemonize(nofork) != 0) { ERROR(LOG_FILE | LOG_SCREEN,"Daemoniize failed"); exit(-1); } //Load routing module void* functions[2] = { send_sms_to_smpp, send_sms_to_sip }; void* cfgs[2] = { cfg_smpp, cfg_sip }; if(cfg_main->routing_module) { mod_routing = dlopen(cfg_main->routing_module, RTLD_NOW | RTLD_GLOBAL); if(!mod_routing) { ERROR(LOG_SCREEN | LOG_FILE, "%s", dlerror()); handler(-1); } f_start_routing = dlsym(mod_routing, "start_routing"); f_routing = dlsym(mod_routing, "routing"); f_close_routing = dlsym(mod_routing, "close_routing"); } else { f_start_routing = default_start_routing; f_routing = default_routing; f_close_routing = default_close_routing; } if(db_init() == -1) { ERROR(LOG_FILE | LOG_SCREEN,"There are errors when the DB connection!"); handler(-1); } else { //TODO: send sms saved in db } if(f_start_routing(functions, cfgs) != 0) { ERROR(LOG_FILE | LOG_SCREEN, "Routing loading failed"); handler(-1); } if(cfg_main && cfg_main->launch_msg) { printf("\033[0;36m%s\033[0m\n", cfg_main->launch_msg); } printf("SIP 2 SMPP Version [%s]\n", VERSION); printf("Pid file [%s]\n", pid_file); printf("Config File [%s]\n", conffile); display_config_file(CONFIG_ALL, NULL); start_all_threads_interfaces(); join_all_threads(); threadpool_destroy(p_threadpool, threadpool_graceful); f_close_routing(); if(cfg_main->routing_module) { dlclose(mod_routing); } free_config_file(CONFIG_ALL, NULL); handler(0); return 0; }
static void create_everything(struct main_context *ctx) { struct callmaster_config mc; struct control_tcp *ct; struct control_udp *cu; struct control_ng *cn; struct cli *cl; int kfd = -1; struct timeval tmp_tv; struct timeval redis_start, redis_stop; double redis_diff = 0; if (table < 0) goto no_kernel; if (kernel_create_table(table)) { fprintf(stderr, "FAILED TO CREATE KERNEL TABLE %i, KERNEL FORWARDING DISABLED\n", table); ilog(LOG_CRIT, "FAILED TO CREATE KERNEL TABLE %i, KERNEL FORWARDING DISABLED\n", table); if (no_fallback) exit(-1); goto no_kernel; } kfd = kernel_open_table(table); if (kfd == -1) { fprintf(stderr, "FAILED TO OPEN KERNEL TABLE %i, KERNEL FORWARDING DISABLED\n", table); ilog(LOG_CRIT, "FAILED TO OPEN KERNEL TABLE %i, KERNEL FORWARDING DISABLED\n", table); if (no_fallback) exit(-1); goto no_kernel; } no_kernel: ctx->p = poller_new(); if (!ctx->p) die("poller creation failed"); ctx->m = callmaster_new(ctx->p); if (!ctx->m) die("callmaster creation failed"); dtls_timer(ctx->p); ZERO(mc); rwlock_init(&mc.config_lock); mc.kernelfd = kfd; mc.kernelid = table; if (max_sessions < -1) { max_sessions = -1; } mc.max_sessions = max_sessions; mc.timeout = timeout; mc.silent_timeout = silent_timeout; mc.final_timeout = final_timeout; mc.delete_delay = delete_delay; mc.default_tos = tos; mc.b2b_url = b2b_url; mc.fmt = xmlrpc_fmt; mc.graphite_ep = graphite_ep; mc.graphite_interval = graphite_interval; mc.redis_subscribed_keyspaces = g_queue_copy(&keyspaces); if (redis_num_threads < 1) { #ifdef _SC_NPROCESSORS_ONLN redis_num_threads = sysconf( _SC_NPROCESSORS_ONLN ); #endif if (redis_num_threads < 1) { redis_num_threads = REDIS_RESTORE_NUM_THREADS; } } mc.redis_num_threads = redis_num_threads; ct = NULL; if (tcp_listen_ep.port) { ct = control_tcp_new(ctx->p, &tcp_listen_ep, ctx->m); if (!ct) die("Failed to open TCP control connection port"); } cu = NULL; if (udp_listen_ep.port) { interfaces_exclude_port(udp_listen_ep.port); cu = control_udp_new(ctx->p, &udp_listen_ep, ctx->m); if (!cu) die("Failed to open UDP control connection port"); } cn = NULL; if (ng_listen_ep.port) { interfaces_exclude_port(ng_listen_ep.port); cn = control_ng_new(ctx->p, &ng_listen_ep, ctx->m); if (!cn) die("Failed to open UDP control connection port"); } cl = NULL; if (cli_listen_ep.port) { interfaces_exclude_port(cli_listen_ep.port); cl = cli_new(ctx->p, &cli_listen_ep, ctx->m); if (!cl) die("Failed to open UDP CLI connection port"); } if (!is_addr_unspecified(&redis_write_ep.address)) { mc.redis_write = redis_new(&redis_write_ep, redis_write_db, redis_write_auth, ANY_REDIS_ROLE, no_redis_required); if (!mc.redis_write) die("Cannot start up without running Redis %s write database! See also NO_REDIS_REQUIRED paramter.", endpoint_print_buf(&redis_write_ep)); } if (!is_addr_unspecified(&redis_ep.address)) { mc.redis = redis_new(&redis_ep, redis_db, redis_auth, mc.redis_write ? ANY_REDIS_ROLE : MASTER_REDIS_ROLE, no_redis_required); mc.redis_notify = redis_new(&redis_ep, redis_db, redis_auth, mc.redis_write ? ANY_REDIS_ROLE : MASTER_REDIS_ROLE, no_redis_required); if (!mc.redis || !mc.redis_notify) die("Cannot start up without running Redis %s database! See also NO_REDIS_REQUIRED paramter.", endpoint_print_buf(&redis_ep)); if (!mc.redis_write) mc.redis_write = mc.redis; } mc.redis_expires_secs = redis_expires; ctx->m->conf = mc; if (!foreground) daemonize(); wpidfile(); ctx->m->homer = homer_sender_new(&homer_ep, homer_protocol, homer_id); if (mc.redis) { // start redis restore timer gettimeofday(&redis_start, NULL); // restore if (redis_restore(ctx->m, mc.redis)) die("Refusing to continue without working Redis database"); // stop redis restore timer gettimeofday(&redis_stop, NULL); // print redis restore duration redis_diff += timeval_diff(&redis_stop, &redis_start) / 1000.0; ilog(LOG_INFO, "Redis restore time = %.0lf ms", redis_diff); } gettimeofday(&ctx->m->latest_graphite_interval_start, NULL); timeval_from_us(&tmp_tv, graphite_interval*1000000); set_graphite_interval_tv(&tmp_tv); }
/* init phase : * 1) read configuration file * 2) read command line arguments * 3) daemonize * 4) check and write pid file * 5) set startup time stamp * 6) set signal handlers */ static int init(int argc, char * * argv) { int i; int pid; int debug_flag = 0; int options_flag = 0; struct sigaction sa; /*const char * logfilename = 0;*/ const char * presurl = 0; const char * optionsfile = "/etc/dlnaproxy.conf"; char mac_str[13]; char * string, * word; char * path; char real_path[PATH_MAX]; char ip_addr[INET_ADDRSTRLEN + 3] = {'\0'}; /* first check if "-f" option is used */ for(i=2; i<argc; i++) { if(0 == strcmp(argv[i-1], "-f")) { optionsfile = argv[i]; options_flag = 1; break; } } /* set up uuid based on mac address */ if( getsyshwaddr(mac_str, sizeof(mac_str)) < 0 ) { DPRINTF(E_OFF, L_GENERAL, "No MAC address found. Falling back to generic UUID.\n"); strcpy(mac_str, "554e4b4e4f57"); } strcpy(uuidvalue+5, "4d696e69-444c-164e-9d41-"); strncat(uuidvalue, mac_str, 12); getfriendlyname(friendly_name, FRIENDLYNAME_MAX_LEN); runtime_vars.port = -1; runtime_vars.notify_interval = 895; /* seconds between SSDP announces */ runtime_vars.rport = 50001; runtime_vars.rhost = "192.168.1.1"; /* read options file first since * command line arguments have final say */ if(readoptionsfile(optionsfile) < 0) { /* only error if file exists or using -f */ if(access(optionsfile, F_OK) == 0 || options_flag) fprintf(stderr, "Error reading configuration file %s\n", optionsfile); } else { for(i=0; i<num_options; i++) { switch(ary_options[i].id) { case UPNPIFNAME: for( string = ary_options[i].value; (word = strtok(string, ",")); string = NULL ) { if(n_lan_addr < MAX_LAN_ADDR) { if(getifaddr(word, ip_addr, sizeof(ip_addr)) >= 0) { if( *ip_addr && parselanaddr(&lan_addr[n_lan_addr], ip_addr) == 0 ) if(n_lan_addr < MAX_LAN_ADDR) n_lan_addr++; } else fprintf(stderr, "Interface %s not found, ignoring.\n", word); } else { fprintf(stderr, "Too many listening ips (max: %d), ignoring %s\n", MAX_LAN_ADDR, word); } } break; case UPNPLISTENING_IP: if(n_lan_addr < MAX_LAN_ADDR) { if(parselanaddr(&lan_addr[n_lan_addr], ary_options[i].value) == 0) n_lan_addr++; } else { fprintf(stderr, "Too many listening ips (max: %d), ignoring %s\n", MAX_LAN_ADDR, ary_options[i].value); } break; case UPNPPORT: runtime_vars.port = atoi(ary_options[i].value); break; case UPNPNOTIFY_INTERVAL: runtime_vars.notify_interval = atoi(ary_options[i].value); break; case UPNPSERIAL: strncpy(serialnumber, ary_options[i].value, SERIALNUMBER_MAX_LEN); serialnumber[SERIALNUMBER_MAX_LEN-1] = '\0'; break; case UPNPMODEL_NAME: strncpy(modelname, ary_options[i].value, MODELNAME_MAX_LEN); modelname[MODELNAME_MAX_LEN-1] = '\0'; break; case UPNPMODEL_NUMBER: strncpy(modelnumber, ary_options[i].value, MODELNUMBER_MAX_LEN); modelnumber[MODELNUMBER_MAX_LEN-1] = '\0'; break; case UPNPLOGDIR: path = realpath(ary_options[i].value, real_path); if( !path ) path = (ary_options[i].value); make_dir(path, S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO); if( access(path, F_OK) != 0 ) { DPRINTF(E_FATAL, L_GENERAL, "Log path not accessible! [%s]\n", path); break; } strncpy(log_path, path, PATH_MAX); break; case UPNPMINISSDPDSOCKET: minissdpdsocketpath = ary_options[i].value; break; case UPNPREMOTEUUID: runtime_vars.ruuid = ary_options[i].value; strcpy(uuidvalue+5, runtime_vars.ruuid); break; case UPNPREMOTEPORT: runtime_vars.rport = atoi(ary_options[i].value); break; case UPNPREMOTEHOST: runtime_vars.rhost = ary_options[i].value; break; case UPNPDESCPATH: runtime_vars.path = ary_options[i].value; break; default: fprintf(stderr, "Unknown option with value %s in file %s\n", ary_options[i].value, optionsfile); } } } if( log_path[0] == '\0' ) { strncpy(log_path, DEFAULT_LOG_PATH, PATH_MAX); } /* command line arguments processing */ for(i=1; i<argc; i++) { if(argv[i][0]!='-') { fprintf(stderr, "Unknown option: %s\n", argv[i]); } else if(strcmp(argv[i], "--help")==0) { runtime_vars.port = 0; break; } else switch(argv[i][1]) { case 't': if(i+1 < argc) runtime_vars.notify_interval = atoi(argv[++i]); else fprintf(stderr, "Option -%c takes one argument.\n", argv[i][1]); break; /*case 'l': logfilename = argv[++i]; break;*/ case 'p': if(i+1 < argc) runtime_vars.port = atoi(argv[++i]); else fprintf(stderr, "Option -%c takes one argument.\n", argv[i][1]); break; case 'P': if(i+1 < argc) pidfilename = argv[++i]; else fprintf(stderr, "Option -%c takes one argument.\n", argv[i][1]); break; case 'd': debug_flag = 1; break; case 'a': if(i+1 < argc) { int address_already_there = 0; int j; i++; for(j=0; j<n_lan_addr; j++) { struct lan_addr_s tmpaddr; parselanaddr(&tmpaddr, argv[i]); if(0 == strcmp(lan_addr[j].str, tmpaddr.str)) address_already_there = 1; } if(address_already_there) break; if(n_lan_addr < MAX_LAN_ADDR) { if(parselanaddr(&lan_addr[n_lan_addr], argv[i]) == 0) n_lan_addr++; } else { fprintf(stderr, "Too many listening ips (max: %d), ignoring %s\n", MAX_LAN_ADDR, argv[i]); } } else fprintf(stderr, "Option -%c takes one argument.\n", argv[i][1]); break; case 'i': if(i+1 < argc) { int address_already_there = 0; int j; i++; if( getifaddr(argv[i], ip_addr, sizeof(ip_addr)) < 0 ) { fprintf(stderr, "Network interface '%s' not found.\n", argv[i]); exit(-1); } for(j=0; j<n_lan_addr; j++) { struct lan_addr_s tmpaddr; parselanaddr(&tmpaddr, ip_addr); if(0 == strcmp(lan_addr[j].str, tmpaddr.str)) address_already_there = 1; } if(address_already_there) break; if(n_lan_addr < MAX_LAN_ADDR) { if(parselanaddr(&lan_addr[n_lan_addr], ip_addr) == 0) n_lan_addr++; } else { fprintf(stderr, "Too many listening ips (max: %d), ignoring %s\n", MAX_LAN_ADDR, argv[i]); } } else fprintf(stderr, "Option -%c takes one argument.\n", argv[i][1]); break; case 'f': i++; /* discarding, the config file is already read */ break; case 'h': runtime_vars.port = 0; // triggers help display break; case 'V': printf("Version " DLNAPROXY_VERSION "\n"); exit(0); break; default: fprintf(stderr, "Unknown option: %s\n", argv[i]); } } /* If no IP was specified, try to detect one */ if( n_lan_addr < 1 ) { if( (getsysaddr(ip_addr, sizeof(ip_addr)) < 0) && (getifaddr("eth0", ip_addr, sizeof(ip_addr)) < 0) && (getifaddr("eth1", ip_addr, sizeof(ip_addr)) < 0) ) { DPRINTF(E_OFF, L_GENERAL, "No IP address automatically detected!\n"); } if( *ip_addr && parselanaddr(&lan_addr[n_lan_addr], ip_addr) == 0 ) { n_lan_addr++; } } if( (n_lan_addr==0) || (runtime_vars.port<=0) ) { fprintf(stderr, "Usage:\n\t" "%s [-d] [-f config_file]\n" "\t\t[-a listening_ip] [-p port]\n" /*"[-l logfile] " not functionnal */ "\t\t[-t notify_interval] [-P pid_filename]\n" "\t\t[-V] [-h]\n" "\nNotes:\n\tNotify interval is in seconds. Default is 895 seconds.\n" "\tDefault pid file is %s.\n" "\tWith -d dlnaproxy will run in debug mode (not daemonize).\n" "\t-h displays this text\n" "\t-V print the version number\n", argv[0], pidfilename); return 1; } if(debug_flag) { pid = getpid(); log_init(NULL, "general,inotify,http,ssdp=debug"); } else { #ifdef USE_DAEMON if(daemon(0, 0)<0) { perror("daemon()"); } pid = getpid(); #else pid = daemonize(); #endif if( access(log_path, F_OK) != 0 ) make_dir(log_path, S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO); sprintf(real_path, "%s/dlnaproxy.log", log_path); log_init(real_path, "general,inotify,http,ssdp=warn"); } if(checkforrunning(pidfilename) < 0) { DPRINTF(E_ERROR, L_GENERAL, "DLNAProxy is already running. EXITING.\n"); return 1; } set_startup_time(); /* presentation url */ if(presurl) { strncpy(presentationurl, presurl, PRESENTATIONURL_MAX_LEN); presentationurl[PRESENTATIONURL_MAX_LEN-1] = '\0'; } else { snprintf(presentationurl, PRESENTATIONURL_MAX_LEN, "http://%s:%d/", lan_addr[0].str, runtime_vars.port); } /* set signal handler */ signal(SIGCLD, SIG_IGN); memset(&sa, 0, sizeof(struct sigaction)); sa.sa_handler = sigterm; if (sigaction(SIGTERM, &sa, NULL)) { DPRINTF(E_FATAL, L_GENERAL, "Failed to set SIGTERM handler. EXITING.\n"); } if (sigaction(SIGINT, &sa, NULL)) { DPRINTF(E_FATAL, L_GENERAL, "Failed to set SIGINT handler. EXITING.\n"); } if(signal(SIGPIPE, SIG_IGN) == SIG_ERR) { DPRINTF(E_FATAL, L_GENERAL, "Failed to ignore SIGPIPE signals. EXITING.\n"); } writepidfile(pidfilename, pid); return 0; }
int main(int argc, char **argv) { struct sigaction sa; char *cmdline_str; char **argv_array; GMainLoop *loop; argv_array = argv_to_array(argc, argv); cmdline_str = get_command_line(argv_array); set_argv_for_child_process(argv_array); cps_config_init(argc, argv); if(global_config.daemonize) { /* When daemonizing, a child process will be launched with daemonization disabled */ daemonize(); run_watchdog(argv_array); /* Watchdog should never stop ! */ exit(EXIT_FAILURE); } /* The child (or not daemonized process) will continue here. */ L (LOGLEVEL_WARNING, PACKAGE_NAME "-" PACKAGE_VERSION " starting"); L (LOGLEVEL_DEBUG, "Command line : %s", cmdline_str); g_free(cmdline_str); /* Signals initialization {{{ */ memset (&sa, 0, sizeof (sa)); sa.sa_sigaction = signal_handler_for_stop; sa.sa_flags = SA_SIGINFO; sigemptyset(&(sa.sa_mask)); if(0 != sigaction(SIGTERM, &sa, NULL)) { L (LOGLEVEL_CRITICAL, "Could not set signal handler for TERM"); exit(EXIT_FAILURE); } if(0 != sigaction(SIGINT, &sa, NULL)) { L (LOGLEVEL_CRITICAL, "Could not set signal handler for INT"); close_all_and_exit(EXIT_FAILURE); } if(0 != sigaction(SIGQUIT, &sa, NULL)) { L (LOGLEVEL_CRITICAL, "Could not set signal handler for QUIT"); close_all_and_exit(EXIT_FAILURE); } memset (&sa, 0, sizeof (sa)); sa.sa_handler = SIG_IGN; sa.sa_flags = SA_RESTART; sigemptyset(&(sa.sa_mask)); if(0 != sigaction(SIGPIPE, &sa, NULL)) { L (LOGLEVEL_CRITICAL, "Could not set signal handler for PIPE"); exit(EXIT_FAILURE); } /* }}} */ cpsa_init(); loop = g_main_new(TRUE); g_timeout_add_seconds(global_config.agent__interval, cpsa_get_process, NULL); g_main_run( loop ); L (LOGLEVEL_WARNING, PACKAGE_NAME "-" PACKAGE_VERSION " ending"); exit(EXIT_SUCCESS); }
static int dvb_frontend_thread(void *data) { struct dvb_frontend *fe = data; struct dvb_frontend_private *fepriv = fe->frontend_priv; unsigned long timeout; char name [15]; fe_status_t s; struct dvb_frontend_parameters *params; dprintk("%s\n", __FUNCTION__); snprintf (name, sizeof(name), "kdvb-fe-%i", fe->dvb->num); lock_kernel(); daemonize(name); sigfillset(¤t->blocked); unlock_kernel(); fepriv->check_wrapped = 0; fepriv->quality = 0; fepriv->delay = 3*HZ; fepriv->status = 0; fepriv->wakeup = 0; fepriv->reinitialise = 0; dvb_frontend_init(fe); while (1) { up(&fepriv->sem); /* is locked when we enter the thread... */ timeout = wait_event_interruptible_timeout(fepriv->wait_queue, dvb_frontend_should_wakeup(fe), fepriv->delay); if (0 != dvb_frontend_is_exiting(fe)) { /* got signal or quitting */ break; } try_to_freeze(); if (down_interruptible(&fepriv->sem)) break; if (fepriv->reinitialise) { dvb_frontend_init(fe); if (fepriv->tone != -1) { fe->ops.set_tone(fe, fepriv->tone); } if (fepriv->voltage != -1) { fe->ops.set_voltage(fe, fepriv->voltage); } fepriv->reinitialise = 0; } /* do an iteration of the tuning loop */ if (fe->ops.get_frontend_algo) { if (fe->ops.get_frontend_algo(fe) == FE_ALGO_HW) { /* have we been asked to retune? */ params = NULL; if (fepriv->state & FESTATE_RETUNE) { params = &fepriv->parameters; fepriv->state = FESTATE_TUNED; } fe->ops.tune(fe, params, fepriv->tune_mode_flags, &fepriv->delay, &s); if (s != fepriv->status) { dvb_frontend_add_event(fe, s); fepriv->status = s; } } else dvb_frontend_swzigzag(fe); } else dvb_frontend_swzigzag(fe); } if (dvb_shutdown_timeout) { if (dvb_powerdown_on_sleep) if (fe->ops.set_voltage) fe->ops.set_voltage(fe, SEC_VOLTAGE_OFF); if (fe->ops.tuner_ops.sleep) { fe->ops.tuner_ops.sleep(fe); if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 0); } if (fe->ops.sleep) fe->ops.sleep(fe); } fepriv->thread_pid = 0; mb(); dvb_frontend_wakeup(fe); return 0; }
int execute_arguments(char *program_name, struct hash_map_t *arguments) { /* allocates space for the possible argument to be executed from the arguments map */ void *value; /* allocates the value to be used to verify the exitence of error from the function */ ERROR_CODE return_value; /* sets space for the flag that will control if the service should be run or not, this is used for certain situations (mostyle test) where the service is not meant to be run */ char run_service = TRUE; /* tries to retrieve the help argument from the arguments map in case the value exists prints the help value and then exits the current system */ get_value_string_hash_map(arguments, (unsigned char *) "help", &value); if(value != NULL) { return help(); } /* tries to retrieve the version argument from the arguments map in case the value exists prints the version value and then exits the current system */ get_value_string_hash_map(arguments, (unsigned char *) "version", &value); if(value != NULL) { return version(); } /* retrieves the test argument value from the arguments map and in case it's set starts the test process runing a series of test functions in sequence */ get_value_string_hash_map(arguments, (unsigned char *) "test", &value); if(value != NULL) { return test(); } /* retrieves the speed argument value from the arguments map and in case it's set starts the speed measuring and disables the runnig of the service */ get_value_string_hash_map(arguments, (unsigned char *) "speed", &value); if(value != NULL) { return speed(); } /* tries to retrieve the daemon argument from the arguments map in case the value is set daemonizes the current process so that it remains in background and returns to the caller process immediately, otherwise prints the viriatum information into the standard output "file", the label should be standard */ get_value_string_hash_map(arguments, (unsigned char *) "daemon", &value); if(value != NULL) { daemonize(); } else { print_information(); } /* tries to retrieve the local argument from the arguments map in case the value exists localizes the current service so that any file read is read from the current directory */ get_value_string_hash_map(arguments, (unsigned char *) "local", &value); if(value != NULL) { localize(); } /* in cas the flag that control if the service must be run is unset the control flow must be returned immediately (avoids running service) */ if(run_service == FALSE) { RAISE_NO_ERROR; } /* runs the service, with the given arguments, this call should block the program control flow until an event stop the running of the main loop */ return_value = run_service_s(program_name, arguments); /* tests the error code for error in case it exists prints a message indicating the problem that occurred */ if(IS_ERROR_CODE(return_value)) { V_ERROR_F("Problem running service (%s)\n", (char *) GET_ERROR()); RAISE_AGAIN(return_value); } /* returns the normal result value as no problems has occured during the execution of the command */ RAISE_NO_ERROR; }
static int set_details() { int mtu_list[] = {576, 1492, 1500, 0}; int i, len, index, offset, rand_port; unsigned int seed; unsigned char value; struct timeval tp; for (i = tc_pagesize; i >>= 1; tc_pagesize_shift++) { /* void */ } /* generate a random port number for avoiding port conflicts */ gettimeofday(&tp, NULL); seed = tp.tv_usec; rand_port = (int) ((rand_r(&seed) / (RAND_MAX + 1.0)) * 512); clt_settings.rand_port_shifted = rand_port; if (clt_settings.sess_timeout < 0) { clt_settings.sess_timeout = DEFAULT_SESS_TIMEOUT; } tc_log_info(LOG_NOTICE, 0, "session timeout:%d", clt_settings.sess_timeout); if (clt_settings.sess_keepalive_timeout <= 0) { clt_settings.sess_keepalive_timeout = clt_settings.sess_timeout + SESS_KEEPLIVE_ADD; } tc_log_info(LOG_NOTICE, 0, "keepalive timeout:%d", clt_settings.sess_keepalive_timeout); #if (!TC_UDP) if (clt_settings.s_pool_size == 0) { clt_settings.s_pool_size = TC_DEFAULT_UPOOL_SIZE; } tc_log_info(LOG_NOTICE, 0, "min sess pool size:%d", TC_MIN_SESS_POOL_SIZE); tc_log_info(LOG_NOTICE, 0, "sess pool size:%d", clt_settings.s_pool_size); if (clt_settings.s_pool_size < TC_MIN_SESS_POOL_SIZE) { tc_log_info(LOG_NOTICE, 0, "sess pool size is too small"); } #endif if (clt_settings.replica_num > 1) { tc_log_info(LOG_NOTICE, 0, "repl num:%d", clt_settings.replica_num); } if (clt_settings.gradully) { tc_log_info(LOG_NOTICE, 0, "gradully replay"); } /* set the ip port pair mapping according to settings */ if (retr_target_addrs(clt_settings.raw_tf, &clt_settings.transfer) == -1) { return -1; } if (clt_settings.raw_clt_tf_ip != NULL) { /* print out raw_clt_tf_ip */ tc_log_info(LOG_NOTICE, 0, "raw_clt_tf_ip:%s", clt_settings.raw_clt_tf_ip); retrieve_clt_tf_ips(); } if (clt_settings.percentage > 99) { clt_settings.percentage = 0; } #if (!TC_UDP) if (sizeof(tc_sess_t) > TC_UPOOL_MAXV) { tc_log_info(LOG_NOTICE, 0, "TC_UPOOL_MAXV is too small"); } #endif if (clt_settings.par_conns <= 0) { clt_settings.par_conns = 1; } else if (clt_settings.par_conns > MAX_CONN_NUM) { clt_settings.par_conns = MAX_CONN_NUM; } tc_log_info(LOG_NOTICE, 0, "parallel connections per target:%d", clt_settings.par_conns); len = sizeof(mtu_list) / sizeof(int) - 1; for (i = 0; i < len; i++) { if (mtu_list[i] == clt_settings.mtu) { break; } } if (i == len) { mtu_list[len++] = clt_settings.mtu; } for (i = 0; i < len; i++) { index = mtu_list[i] >> 3; offset = mtu_list[i] - (index << 3); value = clt_settings.candidate_mtu[index]; value = value | (1 << offset); clt_settings.candidate_mtu[index] = value; } #if (TC_OFFLINE) if (clt_settings.pcap_file == NULL) { tc_log_info(LOG_ERR, 0, "it must have -i argument for offline"); fprintf(stderr, "no -i argument\n"); return -1; } if (clt_settings.accelerated_times < 1) { clt_settings.accelerated_times = 1; } tc_log_info(LOG_NOTICE, 0, "accelerated %d times,interval:%llu ms", clt_settings.accelerated_times, clt_settings.interval); if (clt_settings.interval > 0) { clt_settings.interval = clt_settings.interval * 1000; } #endif #if (TC_PCAP_SND) if (clt_settings.output_if_name != NULL) { tc_log_info(LOG_NOTICE, 0, "output device:%s", clt_settings.output_if_name); } else { tc_log_info(LOG_ERR, 0, "no -o argument"); fprintf(stderr, "no -o argument\n"); return -1; } #endif #if (TC_PCAP) if (clt_settings.raw_device != NULL) { tc_log_info(LOG_NOTICE, 0, "device:%s", clt_settings.raw_device); if (strcmp(clt_settings.raw_device, DEFAULT_DEVICE) == 0) { clt_settings.raw_device = NULL; } else { retrieve_devices(clt_settings.raw_device, &(clt_settings.devices)); } } if (clt_settings.user_filter != NULL) { tc_log_info(LOG_NOTICE, 0, "user filter:%s", clt_settings.user_filter); len = strlen(clt_settings.user_filter); if (len >= MAX_FILTER_LENGH) { tc_log_info(LOG_ERR, 0, "user filter is too long"); return -1; } memcpy(clt_settings.filter, clt_settings.user_filter, len); } else { extract_filter(); } if (clt_settings.snaplen > PCAP_RCV_BUF_SIZE) { clt_settings.snaplen = PCAP_RCV_BUF_SIZE; } #endif /* retrieve real server ip addresses */ if (clt_settings.raw_rs_list != NULL) { tc_log_info(LOG_NOTICE, 0, "s parameter:%s", clt_settings.raw_rs_list); retrieve_real_servers(); } else { tc_log_info(LOG_WARN, 0, "no -s parameter(intercept addresses)"); fprintf(stderr, "tcpcopy needs -s paramter(intercept addresses)\n"); return -1; } #if (TC_PLUGIN) /* support only one additional module*/ clt_settings.plugin = tc_modules[0]; #endif if (read_conf_file() != TC_OK) { return -1; } /* daemonize */ if (clt_settings.do_daemonize) { if (sigignore(SIGHUP) == -1) { tc_log_info(LOG_ERR, errno, "Failed to ignore SIGHUP"); } if (daemonize() == -1) { fprintf(stderr, "failed to daemonize() in order to daemonize\n"); return -1; } } return 0; }
/** * Main * * @param argc Number of command line arguments * @param argv Array with command line arguments * @return 0 on success, non-zero on failure */ int main(int argc, char **argv) { int status = EXIT_FAILURE; /* Set the program-name */ progname = PRG_NAME; /* Parse the command-line options */ if( !mce_command_line_parse(options, argc, argv) ) goto EXIT; /* We don't take any non-flag arguments */ if ((argc - optind) > 0) { fprintf(stderr, "%s: Too many arguments\n" "Try: `%s --help' for more information.\n", progname, progname); exit(EXIT_FAILURE); } mce_log_open(PRG_NAME, LOG_DAEMON, mce_args.logtype); mce_log_set_verbosity(mce_args.verbosity); #ifdef ENABLE_WAKELOCKS /* Since mce enables automatic suspend, we must try to * disable it when mce process exits */ atexit(mce_cleanup_wakelocks); #endif /* Identify mce version & flavor on start up */ mce_log(LL_WARN, "MCE %s (%s) starting up", G_STRINGIFY(PRG_VERSION), (LL_DEVEL == LL_EXTRA) ? "devel" : "release"); /* Daemonize if requested */ if( mce_args.daemonflag ) daemonize(); /* Register a mainloop */ mainloop = g_main_loop_new(NULL, FALSE); /* Signal handlers can be installed once we have a mainloop */ if( !mce_init_signal_pipe() ) { mce_log(LL_CRIT, "Failed to initialise signal pipe"); exit(EXIT_FAILURE); } mce_signal_handlers_install(); /* Initialise subsystems */ /* Open fbdev as early as possible */ mce_fbdev_init(); /* Get configuration options */ if( !mce_conf_init() ) { mce_log(LL_CRIT, "Failed to initialise configuration options"); exit(EXIT_FAILURE); } /* Initialise D-Bus */ if( !mce_dbus_init(mce_args.systembus) ) { mce_log(LL_CRIT, "Failed to initialise D-Bus"); exit(EXIT_FAILURE); } /* Initialise GConf * pre-requisite: g_type_init() */ if (mce_gconf_init() == FALSE) { mce_log(LL_CRIT, "Cannot connect to default GConf engine"); exit(EXIT_FAILURE); } /* Setup all datapipes */ mce_datapipe_init(); /* Allow registering of suspend proof timers */ mce_hbtimer_init(); /* Initialise mode management * pre-requisite: mce_gconf_init() * pre-requisite: mce_dbus_init() */ if (mce_mode_init() == FALSE) { goto EXIT; } /* Initialise DSME * pre-requisite: mce_gconf_init() * pre-requisite: mce_dbus_init() * pre-requisite: mce_mce_init() */ if( !mce_dsme_init() ) goto EXIT; /* Initialise powerkey driver */ if (mce_powerkey_init() == FALSE) { goto EXIT; } /* Initialise /dev/input driver * pre-requisite: g_type_init() */ if (mce_input_init() == FALSE) { goto EXIT; } /* Initialise switch driver */ if (mce_switches_init() == FALSE) { goto EXIT; } /* Initialise tklock driver */ if (mce_tklock_init() == FALSE) { goto EXIT; } if( !mce_sensorfw_init() ) { goto EXIT; } /* Load all modules */ if (mce_modules_init() == FALSE) { goto EXIT; } if( mce_args.show_module_info ) { mce_modules_dump_info(); goto EXIT; } /* MCE startup succeeded */ status = EXIT_SUCCESS; /* Tell systemd that we have started up */ if( mce_args.systemd_notify ) { mce_log(LL_NOTICE, "notifying systemd"); sd_notify(0, "READY=1"); } /* Debug feature: exit after startup is finished */ if( mce_args.auto_exit >= 0 ) { mce_log(LL_WARN, "auto-exit scheduled"); g_idle_add(mce_auto_exit_cb, 0); } /* Run the main loop */ g_main_loop_run(mainloop); /* If we get here, the main loop has terminated; * either because we requested or because of an error */ EXIT: /* Unload all modules */ mce_modules_exit(); /* Call the exit function for all components */ mce_sensorfw_quit(); mce_tklock_exit(); mce_switches_exit(); mce_input_exit(); mce_powerkey_exit(); mce_dsme_exit(); mce_mode_exit(); mce_hbtimer_quit(); /* Free all datapipes */ mce_datapipe_quit(); /* Call the exit function for all subsystems */ mce_gconf_exit(); mce_dbus_exit(); mce_conf_exit(); mce_fbdev_quit(); /* If the mainloop is initialised, unreference it */ if (mainloop != NULL) { g_main_loop_unref(mainloop); mainloop = 0; } /* Close signal pipe & remove io watch for it */ mce_quit_signal_pipe(); /* Log a farewell message and close the log */ mce_log(LL_INFO, "Exiting..."); /* No more logging expected */ mce_log_close(); return status; }
int main(int argc, char **argv) { int listen_port = 0; struct string_list listen_addr = STRING_LIST_INIT_NODUP; int serve_mode = 0, inetd_mode = 0; const char *pid_file = NULL, *user_name = NULL, *group_name = NULL; int detach = 0; struct credentials *cred = NULL; int i; git_setup_gettext(); git_extract_argv0_path(argv[0]); for (i = 1; i < argc; i++) { char *arg = argv[i]; const char *v; if (skip_prefix(arg, "--listen=", &v)) { string_list_append(&listen_addr, xstrdup_tolower(v)); continue; } if (skip_prefix(arg, "--port=", &v)) { char *end; unsigned long n; n = strtoul(v, &end, 0); if (*v && !*end) { listen_port = n; continue; } } if (!strcmp(arg, "--serve")) { serve_mode = 1; continue; } if (!strcmp(arg, "--inetd")) { inetd_mode = 1; log_syslog = 1; continue; } if (!strcmp(arg, "--verbose")) { verbose = 1; continue; } if (!strcmp(arg, "--syslog")) { log_syslog = 1; continue; } if (!strcmp(arg, "--export-all")) { export_all_trees = 1; continue; } if (skip_prefix(arg, "--access-hook=", &v)) { access_hook = v; continue; } if (skip_prefix(arg, "--timeout=", &v)) { timeout = atoi(v); continue; } if (skip_prefix(arg, "--init-timeout=", &v)) { init_timeout = atoi(v); continue; } if (skip_prefix(arg, "--max-connections=", &v)) { max_connections = atoi(v); if (max_connections < 0) max_connections = 0; /* unlimited */ continue; } if (!strcmp(arg, "--strict-paths")) { strict_paths = 1; continue; } if (skip_prefix(arg, "--base-path=", &v)) { base_path = v; continue; } if (!strcmp(arg, "--base-path-relaxed")) { base_path_relaxed = 1; continue; } if (skip_prefix(arg, "--interpolated-path=", &v)) { interpolated_path = v; continue; } if (!strcmp(arg, "--reuseaddr")) { reuseaddr = 1; continue; } if (!strcmp(arg, "--user-path")) { user_path = ""; continue; } if (skip_prefix(arg, "--user-path=", &v)) { user_path = v; continue; } if (skip_prefix(arg, "--pid-file=", &v)) { pid_file = v; continue; } if (!strcmp(arg, "--detach")) { detach = 1; log_syslog = 1; continue; } if (skip_prefix(arg, "--user="******"--group=", &v)) { group_name = v; continue; } if (skip_prefix(arg, "--enable=", &v)) { enable_service(v, 1); continue; } if (skip_prefix(arg, "--disable=", &v)) { enable_service(v, 0); continue; } if (skip_prefix(arg, "--allow-override=", &v)) { make_service_overridable(v, 1); continue; } if (skip_prefix(arg, "--forbid-override=", &v)) { make_service_overridable(v, 0); continue; } if (!strcmp(arg, "--informative-errors")) { informative_errors = 1; continue; } if (!strcmp(arg, "--no-informative-errors")) { informative_errors = 0; continue; } if (!strcmp(arg, "--")) { ok_paths = &argv[i+1]; break; } else if (arg[0] != '-') { ok_paths = &argv[i]; break; } usage(daemon_usage); } if (log_syslog) { openlog("git-daemon", LOG_PID, LOG_DAEMON); set_die_routine(daemon_die); } else /* avoid splitting a message in the middle */ setvbuf(stderr, NULL, _IOFBF, 4096); if (inetd_mode && (detach || group_name || user_name)) die("--detach, --user and --group are incompatible with --inetd"); if (inetd_mode && (listen_port || (listen_addr.nr > 0))) die("--listen= and --port= are incompatible with --inetd"); else if (listen_port == 0) listen_port = DEFAULT_GIT_PORT; if (group_name && !user_name) die("--group supplied without --user"); if (user_name) cred = prepare_credentials(user_name, group_name); if (strict_paths && (!ok_paths || !*ok_paths)) die("option --strict-paths requires a whitelist"); if (base_path && !is_directory(base_path)) die("base-path '%s' does not exist or is not a directory", base_path); if (inetd_mode) { if (!freopen("/dev/null", "w", stderr)) die_errno("failed to redirect stderr to /dev/null"); } if (inetd_mode || serve_mode) return execute(); if (detach) { if (daemonize()) die("--detach not supported on this platform"); } else sanitize_stdfds(); if (pid_file) write_file(pid_file, "%"PRIuMAX, (uintmax_t) getpid()); /* prepare argv for serving-processes */ argv_array_push(&cld_argv, argv[0]); /* git-daemon */ argv_array_push(&cld_argv, "--serve"); for (i = 1; i < argc; ++i) argv_array_push(&cld_argv, argv[i]); return serve(&listen_addr, listen_port, cred); }
int udatapath_cmd(int argc, char *argv[]) { int n_listeners; int error; int i; set_program_name(argv[0]); register_fault_handlers(); time_init(); vlog_init(); dp = dp_new(); parse_options(dp, argc, argv); signal(SIGPIPE, SIG_IGN); if (argc - optind < 1) { OFP_FATAL(0, "at least one listener argument is required; " "use --help for usage"); } if (use_multiple_connections && (argc - optind) % 2 != 0) OFP_FATAL(0, "when using multiple connections, you must specify an even number of listeners"); n_listeners = 0; for (i = optind; i < argc; i += 2) { const char *pvconn_name = argv[i]; const char *pvconn_name_aux = NULL; if (use_multiple_connections) pvconn_name_aux = argv[i + 1]; struct pvconn *pvconn, *pvconn_aux = NULL; int retval, retval_aux; retval = pvconn_open(pvconn_name, &pvconn); if (!retval || retval == EAGAIN) { // Get another listener if we are using auxiliary connections if (use_multiple_connections) { retval_aux = pvconn_open(pvconn_name_aux, &pvconn_aux); if (retval_aux && retval_aux != EAGAIN) { ofp_error(retval_aux, "opening auxiliary %s", pvconn_name_aux); pvconn_aux = NULL; } } dp_add_pvconn(dp, pvconn, pvconn_aux); n_listeners++; } else { ofp_error(retval, "opening %s", pvconn_name); } } if (n_listeners == 0) { OFP_FATAL(0, "could not listen for any connections"); } if (port_list != NULL) { add_ports(dp, port_list); } if (local_port != NULL) { error = dp_ports_add_local(dp, local_port); if (error) { OFP_FATAL(error, "failed to add local port %s", local_port); } } error = vlog_server_listen(NULL, NULL); if (error) { OFP_FATAL(error, "could not listen for vlog connections"); } die_if_already_running(); daemonize(); for (;;) { dp_run(dp); dp_wait(dp); poll_block(); #ifdef OTN_SUPPORT port_status_check(dp); #endif } return 0; }
int mpd_main(int argc, char *argv[]) { struct options options; clock_t start; bool create_db; GError *error = NULL; bool success; daemonize_close_stdin(); #ifdef HAVE_LOCALE_H /* initialize locale */ setlocale(LC_CTYPE,""); #endif g_set_application_name("Music Player Daemon"); /* enable GLib's thread safety code */ g_thread_init(NULL); io_thread_init(); winsock_init(); idle_init(); tag_pool_init(); config_global_init(); success = parse_cmdline(argc, argv, &options, &error); if (!success) { g_warning("%s", error->message); g_error_free(error); return EXIT_FAILURE; } if (!glue_daemonize_init(&options, &error)) { g_warning("%s", error->message); g_error_free(error); return EXIT_FAILURE; } stats_global_init(); tag_lib_init(); if (!log_init(options.verbose, options.log_stderr, &error)) { g_warning("%s", error->message); g_error_free(error); return EXIT_FAILURE; } success = listen_global_init(&error); if (!success) { g_warning("%s", error->message); g_error_free(error); return EXIT_FAILURE; } daemonize_set_user(); main_task = g_thread_self(); main_loop = g_main_loop_new(NULL, FALSE); main_cond = g_cond_new(); event_pipe_init(); event_pipe_register(PIPE_EVENT_IDLE, idle_event_emitted); event_pipe_register(PIPE_EVENT_SHUTDOWN, shutdown_event_emitted); path_global_init(); if (!glue_mapper_init(&error)) { g_warning("%s", error->message); g_error_free(error); return EXIT_FAILURE; } initPermissions(); playlist_global_init(); spl_global_init(); #ifdef ENABLE_ARCHIVE archive_plugin_init_all(); #endif if (!pcm_resample_global_init(&error)) { g_warning("%s", error->message); g_error_free(error); return EXIT_FAILURE; } decoder_plugin_init_all(); update_global_init(); create_db = !glue_db_init_and_load(); glue_sticker_init(); command_init(); initialize_decoder_and_player(); volume_init(); initAudioConfig(); audio_output_all_init(global_player_control); client_manager_init(); replay_gain_global_init(); if (!input_stream_global_init(&error)) { g_warning("%s", error->message); g_error_free(error); return EXIT_FAILURE; } playlist_list_global_init(); daemonize(options.daemon); setup_log_output(options.log_stderr); initSigHandlers(); if (!io_thread_start(&error)) { g_warning("%s", error->message); g_error_free(error); return EXIT_FAILURE; } initZeroconf(); player_create(global_player_control); if (create_db) { /* the database failed to load: recreate the database */ unsigned job = update_enqueue(NULL, true); if (job == 0) MPD_ERROR("directory update failed"); } if (!glue_state_file_init(&error)) { g_warning("%s", error->message); g_error_free(error); return EXIT_FAILURE; } success = config_get_bool(CONF_AUTO_UPDATE, false); #ifdef ENABLE_INOTIFY if (success && mapper_has_music_directory()) mpd_inotify_init(config_get_unsigned(CONF_AUTO_UPDATE_DEPTH, G_MAXUINT)); #else if (success) g_warning("inotify: auto_update was disabled. enable during compilation phase"); #endif config_global_check(); /* enable all audio outputs (if not already done by playlist_state_restore() */ pc_update_audio(global_player_control); #ifdef WIN32 win32_app_started(); #endif /* run the main loop */ g_main_loop_run(main_loop); #ifdef WIN32 win32_app_stopping(); #endif /* cleanup */ g_main_loop_unref(main_loop); #ifdef ENABLE_INOTIFY mpd_inotify_finish(); #endif state_file_finish(global_player_control); pc_kill(global_player_control); finishZeroconf(); client_manager_deinit(); listen_global_finish(); playlist_global_finish(); start = clock(); db_finish(); g_debug("db_finish took %f seconds", ((float)(clock()-start))/CLOCKS_PER_SEC); #ifdef ENABLE_SQLITE sticker_global_finish(); #endif g_cond_free(main_cond); event_pipe_deinit(); playlist_list_global_finish(); input_stream_global_finish(); audio_output_all_finish(); volume_finish(); mapper_finish(); path_global_finish(); finishPermissions(); pc_free(global_player_control); command_finish(); update_global_finish(); decoder_plugin_deinit_all(); #ifdef ENABLE_ARCHIVE archive_plugin_deinit_all(); #endif config_global_finish(); tag_pool_deinit(); idle_deinit(); stats_global_finish(); io_thread_deinit(); daemonize_finish(); #ifdef WIN32 WSACleanup(); #endif close_log_files(); return EXIT_SUCCESS; }
int main(int argc, char* const argv[]) { char* jail_base; char* jail_src_base; char* jail_system; char* jailpath; char* work_dir; char* prog; char* const * args; int uid; gid_t groups[1]; int arg_num = 1; int daemon_mode = 0; int unlimited = 0; char canonical_jailpath[PATH_MAX]; /* Disallow execution from all users but the whitelisted ones, and root */ if (!uid_allowed(getuid())) { fprintf(stderr, "only the web server may execute trampoline\n"); exit(1); } /* Args check and usage */ if (argc < 5) { usage(argv[0]); } if (strcmp(argv[arg_num], "-d") == 0) { if (argc < 6) { usage(argv[0]); } daemon_mode = 1; arg_num++; } if (strcmp(argv[arg_num], "-u") == 0) { if (argc < 6) { usage(argv[0]); } unlimited = 1; arg_num++; } uid = atoi(argv[arg_num++]); jail_base = argv[arg_num++]; jail_src_base = argv[arg_num++]; jail_system = argv[arg_num++]; jailpath = argv[arg_num++]; work_dir = argv[arg_num++]; prog = argv[arg_num]; args = argv + arg_num; /* Disallow suiding to the root user */ if (uid == 0) { fprintf(stderr, "cannot set up a jail as root\n"); exit(1); } /* Jail path must be an absolute path, * and it must begin with jail_base. */ if (norm(canonical_jailpath, PATH_MAX, jailpath) != 0) { fprintf(stderr, "bad jail path: %s\n", jailpath); exit(1); } if (strncmp(canonical_jailpath, jail_base, strlen(jail_base))) { fprintf(stderr, "bad jail path: %s\n", jailpath); exit(1); } openlog("trampoline", LOG_CONS | LOG_PID | LOG_NDELAY, LOG_USER); #ifdef IVLE_AUFS_JAILS mount_if_needed(jail_src_base, jail_base, jail_system, canonical_jailpath); #endif /* IVLE_AUFS_JAILS */ /* chroot into the jail. * Henceforth this process, and its children, cannot see anything above * canoncial_jailpath. */ if (chroot(canonical_jailpath)) { syslog(LOG_ERR, "chroot to %s failed\n", canonical_jailpath); perror("could not chroot"); exit(1); } /* chdir into the specified working directory */ if (chdir(work_dir)) { perror("could not chdir"); exit(1); } /* setuid to the given user ID. * Henceforth we will be running as this user instead of root. */ if (setgid(uid)) { perror("could not setgid"); exit(1); } groups[0] = uid; if (setgroups(1, groups)) { perror("could not setgroups"); exit(1); } if (setuid(uid)) { perror("could not setuid"); exit(1); } /* set user resource limits */ if (!unlimited) { struct rlimit l; /* Process adress space in memory */ l.rlim_cur = 448 * 1024 * 1024; /* 512MiB - 64MiB */ l.rlim_max = 512 * 1024 * 1024; /* 512MiB */ if (setrlimit(RLIMIT_AS, &l)) { perror("could not setrlimit/RLIMIT_AS"); exit(1); } /* Process data segment in memory * Note: This requires a kernel patch to work correctly otherwise it is * ineffective (thus you are only limited by RLIMIT_AS) */ l.rlim_cur = 448 * 1024 * 1024; /* 512MiB - 64MiB */ l.rlim_max = 512 * 1024 * 1024; /* 512MiB */ if (setrlimit(RLIMIT_DATA, &l)) { perror("could not setrlimit/RLIMIT_DATA"); exit(1); } /* Core */ l.rlim_cur = 0; /* No core files */ l.rlim_max = 0; /* No core files */ if (setrlimit(RLIMIT_CORE, &l)) { perror("could not setrlimit/RLIMIT_CORE"); exit(1); } /* CPU */ l.rlim_cur = 25; /* 25 Seconds */ l.rlim_max = 30; /* 30 Seconds */ if (setrlimit(RLIMIT_CPU, &l)) { perror("could not setrlimit/RLIMIT_CPU"); exit(1); } /* File Size */ l.rlim_cur = 64 * 1024 * 1024; /* 64MiB */ l.rlim_max = 72 * 1024 * 1024; /* 72MiB */ if (setrlimit(RLIMIT_FSIZE, &l)) { perror("could not setrlimit/RLIMIT_FSIZE"); exit(1); } /* Number of Processes */ l.rlim_cur = 50; l.rlim_max = 50; if (setrlimit(RLIMIT_NPROC, &l)) { perror("could not setrlimit/RLIMIT_NPROC"); exit(1); } } /* Remove any signal handler masks so we can send signals to the child */ if(unmask_signals()) { perror("could not unmask signals"); exit(1); } /* If everything was OK daemonize (if required) */ if (daemon_mode) { daemonize(); } /* exec (replace this process with the a new instance of the target * program). Pass along all the arguments. * Note that for script execution, the "program" will be the interpreter, * and the first argument will be the script. */ execv(prog, args); /* nb exec won't return unless there was an error */ syslog(LOG_ERR, "exec of %s in %s failed", prog, canonical_jailpath); perror("could not exec"); closelog(); return 1; }
int main(int argc, char **argv) { int i, c; int pid_flags = 0; char *user = NULL; char *local_port = NULL; char *local_addr = NULL; char *password = NULL; char *timeout = NULL; char *method = NULL; char *pid_path = NULL; char *conf_path = NULL; char *iface = NULL; srand(time(NULL)); int remote_num = 0; ss_addr_t remote_addr[MAX_REMOTE_NUM]; char *remote_port = NULL; int option_index = 0; static struct option long_options[] = { { "fast-open", no_argument, 0, 0 }, { "acl", required_argument, 0, 0 }, { 0, 0, 0, 0 } }; opterr = 0; while ((c = getopt_long(argc, argv, "f:s:p:l:k:t:m:i:c:b:a:uv", long_options, &option_index)) != -1) { switch (c) { case 0: if (option_index == 0) { fast_open = 1; } else if (option_index == 1) { LOGI("initialize acl..."); acl = !init_acl(optarg); } break; case 's': if (remote_num < MAX_REMOTE_NUM) { remote_addr[remote_num].host = optarg; remote_addr[remote_num++].port = NULL; } break; case 'p': remote_port = optarg; break; case 'l': local_port = optarg; break; case 'k': password = optarg; break; case 'f': pid_flags = 1; pid_path = optarg; break; case 't': timeout = optarg; break; case 'm': method = optarg; break; case 'c': conf_path = optarg; break; case 'i': iface = optarg; break; case 'b': local_addr = optarg; break; case 'a': user = optarg; break; case 'u': udprelay = 1; break; case 'v': verbose = 1; break; } } if (opterr) { usage(); exit(EXIT_FAILURE); } if (conf_path != NULL) { jconf_t *conf = read_jconf(conf_path); if (remote_num == 0) { remote_num = conf->remote_num; for (i = 0; i < remote_num; i++) { remote_addr[i] = conf->remote_addr[i]; } } if (remote_port == NULL) { remote_port = conf->remote_port; } if (local_addr == NULL) { local_addr = conf->local_addr; } if (local_port == NULL) { local_port = conf->local_port; } if (password == NULL) { password = conf->password; } if (method == NULL) { method = conf->method; } if (timeout == NULL) { timeout = conf->timeout; } if (fast_open == 0) { fast_open = conf->fast_open; } #ifdef HAVE_SETRLIMIT if (nofile == 0) { nofile = conf->nofile; } /* * no need to check the return value here since we will show * the user an error message if setrlimit(2) fails */ if (nofile) { if (verbose) { LOGI("setting NOFILE to %d", nofile); } set_nofile(nofile); } #endif } if (remote_num == 0 || remote_port == NULL || local_port == NULL || password == NULL) { usage(); exit(EXIT_FAILURE); } if (timeout == NULL) { timeout = "10"; } if (local_addr == NULL) { local_addr = "127.0.0.1"; } if (pid_flags) { USE_SYSLOG(argv[0]); daemonize(pid_path); } if (fast_open == 1) { #ifdef TCP_FASTOPEN LOGI("using tcp fast open"); #else LOGE("tcp fast open is not supported by this environment"); #endif } #ifdef __MINGW32__ winsock_init(); #else // ignore SIGPIPE signal(SIGPIPE, SIG_IGN); signal(SIGABRT, SIG_IGN); #endif struct ev_signal sigint_watcher; struct ev_signal sigterm_watcher; ev_signal_init(&sigint_watcher, signal_cb, SIGINT); ev_signal_init(&sigterm_watcher, signal_cb, SIGTERM); ev_signal_start(EV_DEFAULT, &sigint_watcher); ev_signal_start(EV_DEFAULT, &sigterm_watcher); // Setup keys LOGI("initialize ciphers... %s", method); int m = enc_init(password, method); // Setup socket int listenfd; listenfd = create_and_bind(local_addr, local_port); if (listenfd < 0) { FATAL("bind() error"); } if (listen(listenfd, SOMAXCONN) == -1) { FATAL("listen() error"); } setnonblocking(listenfd); LOGI("listening at %s:%s", local_addr, local_port); // Setup proxy context struct listen_ctx listen_ctx; listen_ctx.remote_num = remote_num; listen_ctx.remote_addr = malloc(sizeof(struct sockaddr *) * remote_num); for (i = 0; i < remote_num; i++) { char *host = remote_addr[i].host; char *port = remote_addr[i].port == NULL ? remote_port : remote_addr[i].port; struct sockaddr_storage *storage = malloc(sizeof(struct sockaddr_storage)); memset(storage, 0, sizeof(struct sockaddr_storage)); if (get_sockaddr(host, port, storage) == -1) { FATAL("failed to resolve the provided hostname"); } listen_ctx.remote_addr[i] = (struct sockaddr *)storage; } listen_ctx.timeout = atoi(timeout); listen_ctx.fd = listenfd; listen_ctx.iface = iface; listen_ctx.method = m; struct ev_loop *loop = EV_DEFAULT; ev_io_init(&listen_ctx.io, accept_cb, listenfd, EV_READ); ev_io_start(loop, &listen_ctx.io); // Setup UDP if (udprelay) { LOGI("udprelay enabled"); init_udprelay(local_addr, local_port, listen_ctx.remote_addr[0], get_sockaddr_len(listen_ctx.remote_addr[0]), m, listen_ctx.timeout, iface); } // setuid if (user != NULL) { run_as(user); } // Init connections cork_dllist_init(&connections); // Enter the loop ev_run(loop, 0); if (verbose) { LOGI("closed gracefully"); } // Clean up free_connections(loop); free_udprelay(); ev_io_stop(loop, &listen_ctx.io); for (i = 0; i < remote_num; i++) { free(listen_ctx.remote_addr[i]); } free(listen_ctx.remote_addr); #ifdef __MINGW32__ winsock_cleanup(); #endif ev_signal_stop(EV_DEFAULT, &sigint_watcher); ev_signal_stop(EV_DEFAULT, &sigterm_watcher); return 0; }
int main(int argc, char *argv[]){ FILE *fd; job_registry_entry *en; time_t now; time_t purge_time=0; time_t last_consistency_check=0; char *pidfile=NULL; char *first_duplicate=NULL; struct pollfd *remupd_pollset = NULL; int remupd_nfds; int version=0; int first=TRUE; int tmptim; time_t finalquery_start_date; int loop_interval=DEFAULT_LOOP_INTERVAL; int rc; int c; pthread_t RecUpdNetThd; int confirm_time=0; static int help; static int short_help; bact.njobs = 0; bact.jobs = NULL; while (1) { static struct option long_options[] = { {"help", no_argument, &help, 1}, {"usage", no_argument, &short_help, 1}, {"nodaemon", no_argument, 0, 'o'}, {"version", no_argument, 0, 'v'}, {"prefix", required_argument, 0, 'p'}, {0, 0, 0, 0} }; int option_index = 0; c = getopt_long (argc, argv, "vop:",long_options, &option_index); if (c == -1){ break; } switch (c) { case 0: if (long_options[option_index].flag != 0){ break; } case 'v': version=1; break; case 'o': nodmn=1; break; case 'p': break; case '?': break; default: abort (); } } if(help){ usage(); } if(short_help){ short_usage(); } argv0 = argv[0]; signal(SIGHUP,sighup); if(version) { printf("%s Version: %s\n",progname,VERSION); exit(EXIT_SUCCESS); } /* Checking configuration */ check_config_file("UPDATER"); cha = config_read(NULL); if (cha == NULL) { fprintf(stderr,"Error reading config: "); perror(""); return -1; } config_setenv(NULL); ret = config_get("bupdater_child_poll_timeout",cha); if (ret != NULL){ tmptim=atoi(ret->value); if (tmptim > 0) bfunctions_poll_timeout = tmptim*1000; } ret = config_get("bupdater_debug_level",cha); if (ret != NULL){ debug=atoi(ret->value); } ret = config_get("bupdater_debug_logfile",cha); if (ret != NULL){ debuglogname=strdup(ret->value); if(debuglogname == NULL){ sysfatal("strdup failed for debuglogname in main: %r"); } } if(debug <=0){ debug=0; } if(debuglogname){ if((debuglogfile = fopen(debuglogname, "a+"))==0){ debug = 0; } } else { debug = 0; } ret = config_get("slurm_binpath",cha); if (ret == NULL){ do_log(debuglogfile, debug, 1, "%s: key slurm_binpath not found\n",argv0); } else { slurm_binpath=strdup(ret->value); if(slurm_binpath == NULL){ sysfatal("strdup failed for slurm_binpath in main: %r"); } } ret = config_get("job_registry",cha); if (ret == NULL){ do_log(debuglogfile, debug, 1, "%s: key job_registry not found\n",argv0); sysfatal("job_registry not defined. Exiting"); } else { registry_file=strdup(ret->value); if(registry_file == NULL){ sysfatal("strdup failed for registry_file in main: %r"); } } ret = config_get("purge_interval",cha); if (ret == NULL){ do_log(debuglogfile, debug, 1, "%s: key purge_interval not found using the default:%d\n",argv0,purge_interval); } else { purge_interval=atoi(ret->value); } ret = config_get("finalstate_query_interval",cha); if (ret == NULL){ do_log(debuglogfile, debug, 1, "%s: key finalstate_query_interval not found using the default:%d\n",argv0,finalstate_query_interval); } else { finalstate_query_interval=atoi(ret->value); } ret = config_get("alldone_interval",cha); if (ret == NULL){ do_log(debuglogfile, debug, 1, "%s: key alldone_interval not found using the default:%d\n",argv0,alldone_interval); } else { alldone_interval=atoi(ret->value); } ret = config_get("bupdater_consistency_check_interval",cha); if (ret == NULL){ do_log(debuglogfile, debug, 1, "%s: key bupdater_consistency_check_interval not found using the default:%d\n",argv0,bupdater_consistency_check_interval); } else { bupdater_consistency_check_interval=atoi(ret->value); } ret = config_get("bupdater_pidfile",cha); if (ret == NULL){ do_log(debuglogfile, debug, 1, "%s: key bupdater_pidfile not found\n",argv0); } else { pidfile=strdup(ret->value); if(pidfile == NULL){ sysfatal("strdup failed for pidfile in main: %r"); } } ret = config_get("bupdater_loop_interval",cha); if (ret == NULL){ do_log(debuglogfile, debug, 1, "%s: key bupdater_loop_interval not found - using the default:%d\n",argv0,loop_interval); } else { loop_interval=atoi(ret->value); } ret = config_get("job_registry_use_mmap",cha); if (ret == NULL){ do_log(debuglogfile, debug, 1, "%s: key job_registry_use_mmap not found. Default is NO\n",argv0); } else { do_log(debuglogfile, debug, 1, "%s: key job_registry_use_mmap is set to %s\n",argv0,ret->value); } remupd_conf = config_get("job_registry_add_remote",cha); if (remupd_conf == NULL){ do_log(debuglogfile, debug, 1, "%s: key job_registry_add_remote not found\n",argv0); }else{ if (job_registry_updater_setup_receiver(remupd_conf->values,remupd_conf->n_values,&remupd_head) < 0){ do_log(debuglogfile, debug, 1, "%s: Cannot set network receiver(s) up for remote update\n",argv0); fprintf(stderr,"%s: Cannot set network receiver(s) up for remote update \n",argv0); } if (remupd_head == NULL){ do_log(debuglogfile, debug, 1, "%s: Cannot find values for network endpoints in configuration file (attribute 'job_registry_add_remote').\n",argv0); fprintf(stderr,"%s: Cannot find values for network endpoints in configuration file (attribute 'job_registry_add_remote').\n", argv0); } if ((remupd_nfds = job_registry_updater_get_pollfd(remupd_head, &remupd_pollset)) < 0){ do_log(debuglogfile, debug, 1, "%s: Cannot setup poll set for receiving data.\n",argv0); fprintf(stderr,"%s: Cannot setup poll set for receiving data.\n", argv0); } if (remupd_pollset == NULL || remupd_nfds == 0){ do_log(debuglogfile, debug, 1, "%s: No poll set available for receiving data.\n",argv0); fprintf(stderr,"%s: No poll set available for receiving data.\n",argv0); } } if( !nodmn ) daemonize(); if( pidfile ){ writepid(pidfile); free(pidfile); } rha=job_registry_init(registry_file, BY_BATCH_ID); if (rha == NULL){ do_log(debuglogfile, debug, 1, "%s: Error initialising job registry %s\n",argv0,registry_file); fprintf(stderr,"%s: Error initialising job registry %s :",argv0,registry_file); perror(""); } if (remupd_conf != NULL){ pthread_create(&RecUpdNetThd, NULL, (void *(*)(void *))ReceiveUpdateFromNetwork, (void *)NULL); if (job_registry_updater_setup_sender(remupd_conf->values,remupd_conf->n_values,0,&remupd_head_send) < 0){ do_log(debuglogfile, debug, 1, "%s: Cannot set network sender(s) up for remote update\n",argv0); fprintf(stderr,"%s: Cannot set network sender(s) up for remote update \n",argv0); } if (remupd_head_send == NULL){ do_log(debuglogfile, debug, 1, "%s: Cannot find values for network endpoints in configuration file (attribute 'job_registry_add_remote').\n",argv0); fprintf(stderr,"%s: Cannot find values for network endpoints in configuration file (attribute 'job_registry_add_remote').\n", argv0); } } config_free(cha); for(;;){ /* Purge old entries from registry */ now=time(0); if(now - purge_time > 86400){ if((rc=job_registry_purge(registry_file, now-purge_interval,0))<0){ do_log(debuglogfile, debug, 1, "%s: Error purging job registry %s:%d\n",argv0,registry_file,rc); fprintf(stderr,"%s: Error purging job registry %s :",argv0,registry_file); perror(""); } purge_time=time(0); } now=time(0); if(now - last_consistency_check > bupdater_consistency_check_interval){ if(job_registry_check_index_key_uniqueness(rha,&first_duplicate)==JOB_REGISTRY_FAIL){ do_log(debuglogfile, debug, 1, "%s: Found job registry duplicate entry. The first one is:%s.\nJobid should be removed or registry directory should be removed.\n",argv0,first_duplicate); fprintf(stderr,"%s: Found job registry duplicate entry. The first one is:%s.\nJobid should be removed or registry directory should be removed.",argv0,first_duplicate); } last_consistency_check=time(0); } IntStateQuery(); fd = job_registry_open(rha, "r"); if (fd == NULL){ do_log(debuglogfile, debug, 1, "%s: Error opening job registry %s\n",argv0,registry_file); fprintf(stderr,"%s: Error opening job registry %s :",argv0,registry_file); perror(""); sleep(loop_interval); continue; } if (job_registry_rdlock(rha, fd) < 0){ do_log(debuglogfile, debug, 1, "%s: Error read locking job registry %s\n",argv0,registry_file); fprintf(stderr,"%s: Error read locking job registry %s :",argv0,registry_file); perror(""); sleep(loop_interval); continue; } job_registry_firstrec(rha,fd); fseek(fd,0L,SEEK_SET); first=TRUE; finalquery_start_date = time(0); while ((en = job_registry_get_next(rha, fd)) != NULL){ if((bupdater_lookup_active_jobs(&bact,en->batch_id) != BUPDATER_ACTIVE_JOBS_SUCCESS) && en->status!=REMOVED && en->status!=COMPLETED){ do_log(debuglogfile, debug, 3, "%s: bupdater_lookup_active_jobs returned: %d for jobid: %s\n",argv0,bupdater_lookup_active_jobs(&bact,en->batch_id),en->batch_id); confirm_time=atoi(en->updater_info); if(confirm_time==0){ confirm_time=en->mdate; } /* Assign Status=4 and ExitStatus=999 to all entries that after alldone_interval are still not in a final state(3 or 4)*/ if(now-confirm_time>alldone_interval){ AssignFinalState(en->batch_id); free(en); continue; } if(en->status==IDLE && strlen(en->updater_info)>0){ if (en->mdate < finalquery_start_date){ finalquery_start_date=en->mdate; } do_log(debuglogfile, debug, 2, "%s: FinalStateQuery needed for jobid=%s with status=%d\n",argv0,en->batch_id,en->status); runfinal=TRUE; }else if((now-confirm_time>finalstate_query_interval) && (now > next_finalstatequery)){ if (en->mdate < finalquery_start_date){ finalquery_start_date=en->mdate; } do_log(debuglogfile, debug, 2, "%s: FinalStateQuery needed for jobid=%s with status=%d\n",argv0,en->batch_id,en->status); runfinal=TRUE; } } free(en); } if(runfinal_oldlogs){ FinalStateQuery(0,1); runfinal_oldlogs=FALSE; runfinal=FALSE; }else if(runfinal){ FinalStateQuery(finalquery_start_date,1); runfinal=FALSE; } fclose(fd); sleep(loop_interval); } job_registry_destroy(rha); return 0; }
int main(int argc, char **argv){ int err, c, i; signal(SIGTERM, daemon_exit); signal(SIGINT, daemon_exit); signal(SIGQUIT, daemon_exit); openlog("netradio", LOG_PID|LOG_PERROR, LOG_DAEMON); while(1){ c = getopt(argc, argv, "P:M:D:I:FH"); if( c < 0){ break; } switch(c){ case 'P': server_conf.rcvport = optarg; break; case 'M': server_conf.mgroup = optarg; break; case 'D': server_conf.media_dir = optarg; break; case 'I': server_conf.ifname = optarg; break; case 'F': server_conf.runmode = run_foreground; break; case 'H': printhelp(); exit(0); default: abort(); } } if(server_conf.runmode == run_daemon){ daemonize(); } socket_init(); err = mlib_getchnlist(&list, &list_size); if(err){ syslog(LOG_ERR, "mlib_getchnlist() : %s", strerror(err)); exit(1); } syslog(LOG_DEBUG, "mlib_getchnlist() %d", list_size); #if 0 for(i = 0; i < list_size; i++){ printf("CHN: %d %s\n", list[i].id, list[i].desc); } #endif thr_list_create(list, list_size); // for(i = 0; i < list_size; ++i){ // thr_channel_create(list + i); // syslog(LOG_DEBUG, "thr_channel_create() %d", i); // } while(1) pause(); exit(0); }
int main(int argc, char **argv) { int option; char *configfile; int background; int mdns_no_rsp; int mdns_no_daap; int loglevel; char *logdomains; char *logfile; char *ffid; char *pidfile; const char *gcry_version; sigset_t sigs; int sigfd; #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) struct kevent ke_sigs[4]; #endif int ret; struct option option_map[] = { { "ffid", 1, NULL, 'b' }, { "debug", 1, NULL, 'd' }, { "logdomains", 1, NULL, 'D' }, { "foreground", 0, NULL, 'f' }, { "config", 1, NULL, 'c' }, { "pidfile", 1, NULL, 'P' }, { "version", 0, NULL, 'v' }, { "mdns-no-rsp", 0, NULL, 512 }, { "mdns-no-daap", 0, NULL, 513 }, { NULL, 0, NULL, 0 } }; configfile = CONFFILE; pidfile = PIDFILE; loglevel = -1; logdomains = NULL; logfile = NULL; background = 1; ffid = NULL; mdns_no_rsp = 0; mdns_no_daap = 0; while ((option = getopt_long(argc, argv, "D:d:c:P:fb:v", option_map, NULL)) != -1) { switch (option) { case 512: mdns_no_rsp = 1; break; case 513: mdns_no_daap = 1; break; case 'b': ffid = optarg; break; case 'd': ret = safe_atoi32(optarg, &option); if (ret < 0) fprintf(stderr, "Error: loglevel must be an integer in '-d %s'\n", optarg); else loglevel = option; break; case 'D': logdomains = optarg; break; case 'f': background = 0; break; case 'c': configfile = optarg; break; case 'P': pidfile = optarg; break; case 'v': version(); return EXIT_SUCCESS; break; default: usage(argv[0]); return EXIT_FAILURE; break; } } ret = logger_init(NULL, NULL, (loglevel < 0) ? E_LOG : loglevel); if (ret != 0) { fprintf(stderr, "Could not initialize log facility\n"); return EXIT_FAILURE; } ret = conffile_load(configfile); if (ret != 0) { DPRINTF(E_FATAL, L_MAIN, "Config file errors; please fix your config\n"); logger_deinit(); return EXIT_FAILURE; } logger_deinit(); /* Reinit log facility with configfile values */ if (loglevel < 0) loglevel = cfg_getint(cfg_getsec(cfg, "general"), "loglevel"); logfile = cfg_getstr(cfg_getsec(cfg, "general"), "logfile"); ret = logger_init(logfile, logdomains, loglevel); if (ret != 0) { fprintf(stderr, "Could not reinitialize log facility with config file settings\n"); conffile_unload(); return EXIT_FAILURE; } /* Set up libevent logging callback */ event_set_log_callback(logger_libevent); DPRINTF(E_LOG, L_MAIN, "Forked Media Server Version %s taking off\n", VERSION); /* Initialize ffmpeg */ avcodec_init(); ret = av_lockmgr_register(ffmpeg_lockmgr); if (ret < 0) { DPRINTF(E_FATAL, L_MAIN, "Could not register ffmpeg lock manager callback\n"); ret = EXIT_FAILURE; goto ffmpeg_init_fail; } av_register_all(); av_log_set_callback(logger_ffmpeg); #if LIBAVFORMAT_VERSION_MAJOR < 53 register_ffmpeg_evbuffer_url_protocol(); #endif /* Initialize libgcrypt */ gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread); gcry_version = gcry_check_version(GCRYPT_VERSION); if (!gcry_version) { DPRINTF(E_FATAL, L_MAIN, "libgcrypt version mismatch\n"); ret = EXIT_FAILURE; goto gcrypt_init_fail; } /* We aren't handling anything sensitive, so give up on secure * memory, which is a scarce system resource. */ gcry_control(GCRYCTL_DISABLE_SECMEM, 0); gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0); DPRINTF(E_DBG, L_MAIN, "Initialized with gcrypt %s\n", gcry_version); /* Block signals for all threads except the main one */ sigemptyset(&sigs); sigaddset(&sigs, SIGINT); sigaddset(&sigs, SIGHUP); sigaddset(&sigs, SIGCHLD); sigaddset(&sigs, SIGTERM); sigaddset(&sigs, SIGPIPE); ret = pthread_sigmask(SIG_BLOCK, &sigs, NULL); if (ret != 0) { DPRINTF(E_LOG, L_MAIN, "Error setting signal set\n"); ret = EXIT_FAILURE; goto signal_block_fail; } /* Daemonize and drop privileges */ ret = daemonize(background, pidfile); if (ret < 0) { DPRINTF(E_LOG, L_MAIN, "Could not initialize server\n"); ret = EXIT_FAILURE; goto daemon_fail; } /* Initialize libevent (after forking) */ evbase_main = event_init(); DPRINTF(E_LOG, L_MAIN, "mDNS init\n"); ret = mdns_init(); if (ret != 0) { DPRINTF(E_FATAL, L_MAIN, "mDNS init failed\n"); ret = EXIT_FAILURE; goto mdns_fail; } /* Initialize the database before starting */ DPRINTF(E_INFO, L_MAIN, "Initializing database\n"); ret = db_init(); if (ret < 0) { DPRINTF(E_FATAL, L_MAIN, "Database init failed\n"); ret = EXIT_FAILURE; goto db_fail; } /* Open a DB connection for the main thread */ ret = db_perthread_init(); if (ret < 0) { DPRINTF(E_FATAL, L_MAIN, "Could not perform perthread DB init for main\n"); ret = EXIT_FAILURE; goto db_fail; } /* Spawn file scanner thread */ ret = filescanner_init(); if (ret != 0) { DPRINTF(E_FATAL, L_MAIN, "File scanner thread failed to start\n"); ret = EXIT_FAILURE; goto filescanner_fail; } /* Spawn player thread */ ret = player_init(); if (ret != 0) { DPRINTF(E_FATAL, L_MAIN, "Player thread failed to start\n"); ret = EXIT_FAILURE; goto player_fail; } /* Spawn HTTPd thread */ ret = httpd_init(); if (ret != 0) { DPRINTF(E_FATAL, L_MAIN, "HTTPd thread failed to start\n"); ret = EXIT_FAILURE; goto httpd_fail; } /* Start Remote pairing service */ ret = remote_pairing_init(); if (ret != 0) { DPRINTF(E_FATAL, L_MAIN, "Remote pairing service failed to start\n"); ret = EXIT_FAILURE; goto remote_fail; } /* Register mDNS services */ ret = register_services(ffid, mdns_no_rsp, mdns_no_daap); if (ret < 0) { ret = EXIT_FAILURE; goto mdns_reg_fail; } #if defined(__linux__) /* Set up signal fd */ sigfd = signalfd(-1, &sigs, SFD_NONBLOCK | SFD_CLOEXEC); if (sigfd < 0) { DPRINTF(E_FATAL, L_MAIN, "Could not setup signalfd: %s\n", strerror(errno)); ret = EXIT_FAILURE; goto signalfd_fail; } event_set(&sig_event, sigfd, EV_READ, signal_signalfd_cb, NULL); #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) sigfd = kqueue(); if (sigfd < 0) { DPRINTF(E_FATAL, L_MAIN, "Could not setup kqueue: %s\n", strerror(errno)); ret = EXIT_FAILURE; goto signalfd_fail; } EV_SET(&ke_sigs[0], SIGINT, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL); EV_SET(&ke_sigs[1], SIGTERM, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL); EV_SET(&ke_sigs[2], SIGHUP, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL); EV_SET(&ke_sigs[3], SIGCHLD, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL); ret = kevent(sigfd, ke_sigs, 4, NULL, 0, NULL); if (ret < 0) { DPRINTF(E_FATAL, L_MAIN, "Could not register signal events: %s\n", strerror(errno)); ret = EXIT_FAILURE; goto signalfd_fail; } event_set(&sig_event, sigfd, EV_READ, signal_kqueue_cb, NULL); #endif event_base_set(evbase_main, &sig_event); event_add(&sig_event, NULL); /* Run the loop */ event_base_dispatch(evbase_main); DPRINTF(E_LOG, L_MAIN, "Stopping gracefully\n"); ret = EXIT_SUCCESS; /* * On a clean shutdown, bring mDNS down first to give a chance * to the clients to perform a clean shutdown on their end */ DPRINTF(E_LOG, L_MAIN, "mDNS deinit\n"); mdns_deinit(); signalfd_fail: mdns_reg_fail: DPRINTF(E_LOG, L_MAIN, "Remote pairing deinit\n"); remote_pairing_deinit(); remote_fail: DPRINTF(E_LOG, L_MAIN, "HTTPd deinit\n"); httpd_deinit(); httpd_fail: DPRINTF(E_LOG, L_MAIN, "Player deinit\n"); player_deinit(); player_fail: DPRINTF(E_LOG, L_MAIN, "File scanner deinit\n"); filescanner_deinit(); filescanner_fail: DPRINTF(E_LOG, L_MAIN, "Database deinit\n"); db_perthread_deinit(); db_deinit(); db_fail: if (ret == EXIT_FAILURE) { DPRINTF(E_LOG, L_MAIN, "mDNS deinit\n"); mdns_deinit(); } mdns_fail: daemon_fail: if (background) { ret = seteuid(0); if (ret < 0) DPRINTF(E_LOG, L_MAIN, "seteuid() failed: %s\n", strerror(errno)); else { ret = unlink(pidfile); if (ret < 0) DPRINTF(E_LOG, L_MAIN, "Could not unlink PID file %s: %s\n", pidfile, strerror(errno)); } } signal_block_fail: gcrypt_init_fail: av_lockmgr_register(NULL); ffmpeg_init_fail: DPRINTF(E_LOG, L_MAIN, "Exiting.\n"); conffile_unload(); logger_deinit(); return ret; }
int main(int argc, char *argv[]) { int c; int option_index = 0; bool no_daemon = false; bool exclusive_control = false; bool dbus_enable = false; bool test_mode = false; const char* const short_options = "hvnp:de"; static struct option long_options[] = { { "help", no_argument, 0, 'h' }, { "version", no_argument, 0, 'v' }, { "no-daemon", no_argument, 0, 'n' }, { "poll-interval", required_argument, 0, 'p' }, { "dbus-enable", no_argument, 0, 'd' }, { "exclusive_control", no_argument, 0, 'e' }, { "test-mode", no_argument, 0, 't' }, { NULL, 0, NULL, 0 } }; if (argc > 1) { while ((c = getopt_long(argc, argv, short_options, long_options, &option_index)) != -1) { int this_option_optind = optind ? optind : 1; switch (c) { case 'h': print_usage(stdout, 0); break; case 'v': fprintf(stdout, "1.03-01\n"); exit(0); break; case 'n': no_daemon = true; break; case 'd': dbus_enable = true; break; case 'p': thd_poll_interval = atoi(optarg); break; case 'e': exclusive_control = true; break; case 't': test_mode = true; break; case -1: case 0: break; default: break; } } } if (getuid() != 0 && !test_mode) { fprintf(stderr, "You must be root to run thermal daemon!\n"); exit(1); } if ((c = mkdir(TDRUNDIR, 0755)) != 0) { if (errno != EEXIST) { fprintf(stderr, "Cannot create '%s': %s\n", TDRUNDIR, strerror(errno)); exit(1); } } mkdir(TDCONFDIR, 0755); // Don't care return value as directory if (!no_daemon) { daemonize((char *) "/tmp/", (char *) "/tmp/thermald.pid"); } else signal(SIGINT, signal_handler); thd_log_info( "Linux Thermal Daemon is starting mode %d : poll_interval %d :ex_control %d\n", no_daemon, thd_poll_interval, exclusive_control); thd_engine = new cthd_engine_default(); if (exclusive_control) thd_engine->set_control_mode(EXCLUSIVE); thd_engine->set_poll_interval(thd_poll_interval); // Initialize thermald objects if (thd_engine->thd_engine_start(false) != THD_SUCCESS) { thd_log_error("thermald engine start failed: "); exit(1); } #ifdef VALGRIND_TEST // lots of STL lib function don't free memory // when called with exit(). // Here just run for some time and gracefully return. sleep(10); if (pid_file_handle) close(pid_file_handle); thd_engine->thd_engine_terminate(); sleep(1); delete thd_engine; #else for (;;) sleep(0xffff); thd_log_info("Linux Thermal Daemon is exiting \n"); #endif return 0; }
int main(int argc, char **argv) { int i, c; int pid_flags = 0; char *user = NULL; char *local_port = NULL; char *local_addr = NULL; char *password = NULL; char *timeout = NULL; char *method = NULL; char *pid_path = NULL; char *conf_path = NULL; char *iface = NULL; int remote_num = 0; ss_addr_t remote_addr[MAX_REMOTE_NUM]; char *remote_port = NULL; ss_addr_t tunnel_addr = { .host = NULL, .port = NULL }; char *tunnel_addr_str = NULL; opterr = 0; USE_TTY(); #ifdef ANDROID while ((c = getopt(argc, argv, "f:s:p:l:k:t:m:i:c:b:L:a:uUvVA")) != -1) { #else while ((c = getopt(argc, argv, "f:s:p:l:k:t:m:i:c:b:L:a:uUvA")) != -1) { #endif switch (c) { case 's': if (remote_num < MAX_REMOTE_NUM) { remote_addr[remote_num].host = optarg; remote_addr[remote_num++].port = NULL; } break; case 'p': remote_port = optarg; break; case 'l': local_port = optarg; break; case 'k': password = optarg; break; case 'f': pid_flags = 1; pid_path = optarg; break; case 't': timeout = optarg; break; case 'm': method = optarg; break; case 'c': conf_path = optarg; break; case 'i': iface = optarg; break; case 'b': local_addr = optarg; break; case 'u': mode = TCP_AND_UDP; break; case 'U': mode = UDP_ONLY; break; case 'L': tunnel_addr_str = optarg; break; case 'a': user = optarg; break; case 'v': verbose = 1; break; case 'A': auth = 1; break; #ifdef ANDROID case 'V': vpn = 1; break; #endif } } if (opterr) { usage(); exit(EXIT_FAILURE); } if (argc == 1) { if (conf_path == NULL) { conf_path = DEFAULT_CONF_PATH; } } if (conf_path != NULL) { jconf_t *conf = read_jconf(conf_path); if (remote_num == 0) { remote_num = conf->remote_num; for (i = 0; i < remote_num; i++) { remote_addr[i] = conf->remote_addr[i]; } } if (remote_port == NULL) { remote_port = conf->remote_port; } if (local_addr == NULL) { local_addr = conf->local_addr; } if (local_port == NULL) { local_port = conf->local_port; } if (password == NULL) { password = conf->password; } if (method == NULL) { method = conf->method; } if (timeout == NULL) { timeout = conf->timeout; } } if (remote_num == 0 || remote_port == NULL || tunnel_addr_str == NULL || local_port == NULL || password == NULL) { usage(); exit(EXIT_FAILURE); } if (timeout == NULL) { timeout = "60"; } if (local_addr == NULL) { local_addr = "127.0.0.1"; } if (pid_flags) { USE_SYSLOG(argv[0]); daemonize(pid_path); } // parse tunnel addr parse_addr(tunnel_addr_str, &tunnel_addr); if (tunnel_addr.port == NULL) { FATAL("tunnel port is not defined"); } #ifdef __MINGW32__ winsock_init(); #else // ignore SIGPIPE signal(SIGPIPE, SIG_IGN); signal(SIGABRT, SIG_IGN); #endif // Setup keys LOGI("initialize ciphers... %s", method); int m = enc_init(password, method); // Setup proxy context struct listen_ctx listen_ctx; listen_ctx.tunnel_addr = tunnel_addr; listen_ctx.remote_num = remote_num; listen_ctx.remote_addr = malloc(sizeof(struct sockaddr *) * remote_num); for (i = 0; i < remote_num; i++) { char *host = remote_addr[i].host; char *port = remote_addr[i].port == NULL ? remote_port : remote_addr[i].port; struct sockaddr_storage *storage = malloc(sizeof(struct sockaddr_storage)); memset(storage, 0, sizeof(struct sockaddr_storage)); if (get_sockaddr(host, port, storage, 1) == -1) { FATAL("failed to resolve the provided hostname"); } listen_ctx.remote_addr[i] = (struct sockaddr *)storage; } listen_ctx.timeout = atoi(timeout); listen_ctx.iface = iface; listen_ctx.method = m; struct ev_loop *loop = EV_DEFAULT; if (mode != UDP_ONLY) { // Setup socket int listenfd; listenfd = create_and_bind(local_addr, local_port); if (listenfd < 0) { FATAL("bind() error:"); } if (listen(listenfd, SOMAXCONN) == -1) { FATAL("listen() error:"); } setnonblocking(listenfd); listen_ctx.fd = listenfd; ev_io_init(&listen_ctx.io, accept_cb, listenfd, EV_READ); ev_io_start(loop, &listen_ctx.io); } if (auth) { LOGI("onetime authentication enabled"); } // Setup UDP if (mode != TCP_ONLY) { LOGI("UDP relay enabled"); init_udprelay(local_addr, local_port, listen_ctx.remote_addr[0], get_sockaddr_len(listen_ctx.remote_addr[0]), tunnel_addr, m, listen_ctx.timeout, iface); } if (mode == UDP_ONLY) { LOGI("TCP relay disabled"); } LOGI("listening at %s:%s", local_addr, local_port); // setuid if (user != NULL) { run_as(user); } ev_run(loop, 0); #ifdef __MINGW32__ winsock_cleanup(); #endif return 0; }
int main(int argc, char **argv) { struct timespec timeout = {SELECT_TIMEOUT_SECONDS, 0}; struct sigaction sigact; sigset_t select_sigset; int exitval = EXIT_FAILURE; int syslog_options = LOG_ODELAY | LOG_PERROR; int settings_retval; parse_args(argc, argv); openlog(program_invocation_short_name, syslog_options, LOG_DAEMON); syslog(LOG_INFO, "starting"); memset(&sigact, 0, sizeof(struct sigaction)); sigact.sa_handler = &sigterm_handler; if (sigfillset(&sigact.sa_mask) == -1) { syslog(LOG_ERR, "sigfillset: %s", strerror(errno)); goto out; } if (sigaction(SIGTERM, &sigact, NULL) == -1) { syslog(LOG_ERR, "sigaction SIGTERM: %s", strerror(errno)); goto out; } if (!is_daemon && sigaction(SIGINT, &sigact, NULL) == -1) { syslog(LOG_ERR, "sigaction SIGINT: %s", strerror(errno)); goto out; } if (sigemptyset(&select_sigset) == -1) { syslog(LOG_ERR, "sigemptyset: %s", strerror(errno)); goto out; } if (sigaddset(&select_sigset, SIGTERM) == -1) { syslog(LOG_ERR, "sigaddset SIGTERM: %s", strerror(errno)); goto out; } if (!is_daemon && sigaddset(&select_sigset, SIGINT) == -1) { syslog(LOG_ERR, "sigaddset SIGINT: %s", strerror(errno)); goto out; } settings_retval = settings_read(&settings); switch (settings_retval) { case 0: break; case -1: syslog(LOG_ERR, "settings_read: %s", strerror(errno)); goto out; default: syslog(LOG_ERR, "settings_read: %s", settings_strerror(settings_retval)); goto out; } if ((monitor_fd = open_evdev_by_name(settings.monitor_name)) == -1) { syslog(LOG_ERR, "open monitor %s: %s", settings.monitor_name, strerror(errno)); goto out; } if ((filter_fd = open_evdev_by_name(settings.filter_name)) == -1) { syslog(LOG_ERR, "open filter %s: %s", settings.filter_name, strerror(errno)); goto out; } if (ioctl(filter_fd, EVIOCGRAB, 1) == -1) { syslog(LOG_ERR, "grab filter: %s", strerror(errno)); goto out; } if ((clone_fd = clone_evdev(filter_fd, &settings.clone_id, settings.clone_name)) == -1) { syslog(LOG_ERR, "clone_evdev: %s", strerror(errno)); goto out; } if (is_daemon && daemonize() == -1) { syslog(LOG_ERR, "daemonize: %s", strerror(errno)); goto out; } syslog(LOG_INFO, "started"); while (is_running) { fd_set rfds; FD_ZERO(&rfds); FD_SET(monitor_fd, &rfds); FD_SET(filter_fd, &rfds); switch (pselect(filter_fd + 1, &rfds, NULL, NULL, &timeout, &select_sigset)) { case 0: break; case -1: syslog(LOG_ERR, "select: %s", strerror(errno)); goto out; default: if (FD_ISSET(filter_fd, &rfds)) { if (handle_filter() == -1) { goto out; } } else if (FD_ISSET(monitor_fd, &rfds)) { if (handle_monitor() == -1) { goto out; } } break; } } syslog(LOG_INFO, "stopped"); syslog(LOG_INFO, "terminating"); exitval = EXIT_SUCCESS; out: settings_free(&settings); if (clone_fd != -1) { if (ioctl(clone_fd, UI_DEV_DESTROY) == -1) { syslog(LOG_ERR, "destroy clone: %s", strerror(errno)); exitval = EXIT_FAILURE; } if (close(clone_fd) == -1) { syslog(LOG_ERR, "close clone: %s", strerror(errno)); exitval = EXIT_FAILURE; } } if (filter_fd != -1) { if (ioctl(filter_fd, EVIOCGRAB, 0) == -1) { syslog(LOG_ERR, "release filter: %s", strerror(errno)); exitval = EXIT_FAILURE; } if (close(filter_fd) == -1) { syslog(LOG_ERR, "close filter: %s", strerror(errno)); exitval = EXIT_FAILURE; } } if (monitor_fd != -1) { if (close(monitor_fd) == -1) { syslog(LOG_ERR, "close monitor: %s", strerror(errno)); exitval = EXIT_FAILURE; } } syslog(LOG_INFO, "terminated"); return exitval; }
void init(int argc, char **argv){ if(argc < 2){ usage(argc, argv); exit(0); } signal(SIGPIPE, SIG_IGN); { struct timeval tv; if(gettimeofday(&tv, NULL) == -1){ srand(time(NULL) + getpid()); }else{ srand(tv.tv_sec + tv.tv_usec + getpid()); } } bool is_daemon = false; const char *conf_file = NULL; for(int i=1; i<argc; i++){ if(strcmp(argv[i], "-d") == 0){ is_daemon = true; }else{ conf_file = argv[i]; } } if(conf_file == NULL){ usage(argc, argv); exit(0); } if(!is_file(conf_file)){ fprintf(stderr, "'%s' is not a file or not exists!\n", conf_file); exit(0); } conf = Config::load(conf_file); if(!conf){ fprintf(stderr, "error loading conf file: '%s'\n", conf_file); exit(0); } { std::string conf_dir = real_dirname(conf_file); if(chdir(conf_dir.c_str()) == -1){ fprintf(stderr, "error chdir: %s\n", conf_dir.c_str()); exit(0); } } std::string log_output; int log_rotate_size = 0; { // logger int log_level = Logger::get_level(conf->get_str("logger.level")); log_rotate_size = conf->get_num("logger.rotate.size"); if(log_rotate_size < 1024 * 1024){ log_rotate_size = 1024 * 1024; } log_output = conf->get_str("logger.output"); if(log_output == ""){ log_output = "stdout"; } if(log_open(log_output.c_str(), log_level, true, log_rotate_size) == -1){ fprintf(stderr, "error open log file: %s\n", log_output.c_str()); exit(0); } } check_pidfile(); if(is_daemon){ daemonize(); } log_info("starting icomet %s...", ICOMET_VERSION); log_info("config file: %s", conf_file); log_info("log_level : %s", conf->get_str("logger.level")); log_info("log_output : %s", log_output.c_str()); log_info("log_rotate_size : %d", log_rotate_size); evbase = event_base_new(); if(!evbase){ fprintf(stderr, "create evbase error!\n"); exit(0); } admin_http = evhttp_new(evbase); if(!admin_http){ fprintf(stderr, "create admin_http error!\n"); exit(0); } front_http = evhttp_new(evbase); if(!front_http){ fprintf(stderr, "create front_http error!\n"); exit(0); } sigint_event = evsignal_new(evbase, SIGINT, signal_cb, NULL); if(!sigint_event || event_add(sigint_event, NULL)<0){ fprintf(stderr, "Could not create/add a signal event!\n"); exit(0); } sigterm_event = evsignal_new(evbase, SIGTERM, signal_cb, NULL); if(!sigterm_event || event_add(sigterm_event, NULL)<0){ fprintf(stderr, "Could not create/add a signal event!\n"); exit(0); } timer_event = event_new(evbase, -1, EV_PERSIST, timer_cb, NULL); { struct timeval tv; tv.tv_sec = CHANNEL_CHECK_INTERVAL; tv.tv_usec = 0; if(!timer_event || evtimer_add(timer_event, &tv)<0){ fprintf(stderr, "Could not create/add a timer event!\n"); exit(0); } } }