static void options(int *argc, char ***argv) { char *ipv4s = NULL; char *adv_ipv4s = NULL; char *ipv6s = NULL; char *adv_ipv6s = NULL; char *listenps = NULL; char *listenudps = NULL; char *listenngs = NULL; char *redisps = NULL; char *log_facility_s = NULL; int version = 0; GOptionEntry e[] = { { "version", 'v', 0, G_OPTION_ARG_NONE, &version, "Print build time and exit", NULL }, { "table", 't', 0, G_OPTION_ARG_INT, &table, "Kernel table to use", "INT" }, { "no-fallback",'F', 0, G_OPTION_ARG_NONE, &no_fallback, "Only start when kernel module is available", NULL }, { "ip", 'i', 0, G_OPTION_ARG_STRING, &ipv4s, "Local IPv4 address for RTP", "IP" }, { "advertised-ip", 'a', 0, G_OPTION_ARG_STRING, &adv_ipv4s, "IPv4 address to advertise", "IP" }, { "ip6", 'I', 0, G_OPTION_ARG_STRING, &ipv6s, "Local IPv6 address for RTP", "IP6" }, { "advertised-ip6",'A',0,G_OPTION_ARG_STRING, &adv_ipv6s, "IPv6 address to advertise", "IP6" }, { "listen-tcp", 'l', 0, G_OPTION_ARG_STRING, &listenps, "TCP port to listen on", "[IP:]PORT" }, { "listen-udp", 'u', 0, G_OPTION_ARG_STRING, &listenudps, "UDP port to listen on", "[IP46:]PORT" }, { "listen-ng", 'n', 0, G_OPTION_ARG_STRING, &listenngs, "UDP port to listen on, NG protocol", "[IP46:]PORT" }, { "tos", 'T', 0, G_OPTION_ARG_INT, &tos, "Default TOS value to set on streams", "INT" }, { "timeout", 'o', 0, G_OPTION_ARG_INT, &timeout, "RTP timeout", "SECS" }, { "silent-timeout",'s',0,G_OPTION_ARG_INT, &silent_timeout,"RTP timeout for muted", "SECS" }, { "pidfile", 'p', 0, G_OPTION_ARG_STRING, &pidfile, "Write PID to file", "FILE" }, { "foreground", 'f', 0, G_OPTION_ARG_NONE, &foreground, "Don't fork to background", NULL }, { "port-min", 'm', 0, G_OPTION_ARG_INT, &port_min, "Lowest port to use for RTP", "INT" }, { "port-max", 'M', 0, G_OPTION_ARG_INT, &port_max, "Highest port to use for RTP", "INT" }, { "redis", 'r', 0, G_OPTION_ARG_STRING, &redisps, "Connect to Redis database", "IP:PORT" }, { "redis-db", 'R', 0, G_OPTION_ARG_INT, &redis_db, "Which Redis DB to use", "INT" }, { "b2b-url", 'b', 0, G_OPTION_ARG_STRING, &b2b_url, "XMLRPC URL of B2B UA" , "STRING" }, { "log-level", 'L', 0, G_OPTION_ARG_INT, (void *)&log_level, "Mask log priorities above this level", "INT" }, { "log-facility", 0, 0, G_OPTION_ARG_STRING, &log_facility_s, "Syslog facility to use for logging", "daemon|local0|...|local7"}, { "log-stderr", 'E', 0, G_OPTION_ARG_NONE, &_log_stderr, "Log on stderr instead of syslog", NULL }, { "xmlrpc-format", 'x', 0, G_OPTION_ARG_INT, &xmlrpc_fmt, "XMLRPC timeout request format to use. 0: SEMS DI, 1: call-id only", "INT" }, { NULL, } }; GOptionContext *c; GError *er = NULL; c = g_option_context_new(" - next-generation media proxy"); g_option_context_add_main_entries(c, e, NULL); if (!g_option_context_parse(c, argc, argv, &er)) die("Bad command line: %s\n", er->message); if (version) die("%s\n", RTPENGINE_VERSION); if (!ipv4s) die("Missing option --ip\n"); if (!listenps && !listenudps && !listenngs) die("Missing option --listen-tcp, --listen-udp or --listen-ng\n"); ipv4 = inet_addr(ipv4s); if (ipv4 == -1) die("Invalid IPv4 address (--ip)\n"); if (adv_ipv4s) { adv_ipv4 = inet_addr(adv_ipv4s); if (adv_ipv4 == -1) die("Invalid IPv4 address (--advertised-ip)\n"); } if (ipv6s) { if (smart_pton(AF_INET6, ipv6s, &ipv6) != 1) die("Invalid IPv6 address (--ip6)\n"); } if (adv_ipv6s) { if (smart_pton(AF_INET6, adv_ipv6s, &adv_ipv6) != 1) die("Invalid IPv6 address (--advertised-ip6)\n"); } if (listenps) { if (parse_ip_port(&listenp, &listenport, listenps)) die("Invalid IP or port (--listen-tcp)\n"); } if (listenudps) { if (parse_ip6_port(&udp_listenp, &udp_listenport, listenudps)) die("Invalid IP or port (--listen-udp)\n"); } if (listenngs) { if (parse_ip6_port(&ng_listenp, &ng_listenport, listenngs)) die("Invalid IP or port (--listen-ng)\n"); } if (tos < 0 || tos > 255) die("Invalid TOS value\n"); if (timeout <= 0) timeout = 60; if (silent_timeout <= 0) silent_timeout = 3600; if (redisps) { if (parse_ip_port(&redis_ip, &redis_port, redisps) || !redis_ip) die("Invalid IP or port (--redis)\n"); if (redis_db < 0) die("Must specify Redis DB number (--redis-db) when using Redis\n"); } if (xmlrpc_fmt < 0 || xmlrpc_fmt > 1) { die("Invalid XMLRPC format\n"); } if ((log_level < LOG_EMERG) || (log_level > LOG_DEBUG)) die("Invalid log level (--log_level)\n"); setlogmask(LOG_UPTO(log_level)); if (log_facility_s) { if (!parse_log_facility(log_facility_s, &_log_facility)) { print_available_log_facilities(); die ("Invalid log facility '%s' (--log-facility)\n", log_facility_s); } } if (_log_stderr) { write_log = log_to_stderr; } }
int main (int argc, char *argv[]) { char *cmd; struct sigaction sa; int fifofd; long int pidslave[3]; // char fifoslave[512]; struct harvester *sh; pthread_t *ht; pthread_attr_t ha; GError *error = NULL; GOptionContext *context; static int use_daemonize = 1; static GOptionEntry entries[] = { {"disable-daemonize", 0, G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &use_daemonize, "do not daemonize", NULL}, {NULL} }; context = g_option_context_new ("launch seed harvester"); g_option_context_add_main_entries (context, entries, NULL); g_option_context_set_summary(context, "xmimsim-harvester: a daemon that gathers seeds from /dev/random..."); if (!g_option_context_parse (context, &argc, &argv, &error)) { g_print ("option parsing failed: %s\n", error->message); exit (1); } if ((cmd = strrchr(argv[0], '/')) == NULL) cmd = argv[0]; else cmd++; if (use_daemonize) daemonize(cmd); else { openlog(cmd, LOG_CONS | LOG_PID, LOG_DAEMON); setlogmask(LOG_UPTO(LOG_DEBUG)); } if (already_running()) { syslog(LOG_ERR, "daemon already running"); exit(1); } sa.sa_handler = sigterm; sigfillset(&sa.sa_mask); //sigaddset(&sa.sa_mask, SIGTERM); sa.sa_flags=0; if (sigaction(SIGTERM, &sa, NULL) < 0) { syslog(LOG_ERR, "can't catch SIGTERM: %s", strerror(errno)); exit(1); } if (sigaction(SIGSEGV, &sa, NULL) < 0) { syslog(LOG_ERR, "can't catch SIGSEGV: %s", strerror(errno)); exit(1); } if (sigaction(SIGBUS, &sa, NULL) < 0) { syslog(LOG_ERR, "can't catch SIGBUS: %s", strerror(errno)); exit(1); } if (sigaction(SIGILL, &sa, NULL) < 0) { syslog(LOG_ERR, "can't catch SIGILL: %s", strerror(errno)); exit(1); } if (sigaction(SIGQUIT, &sa, NULL) < 0) { syslog(LOG_ERR, "can't catch SIGQUIT: %s", strerror(errno)); exit(1); } sa.sa_handler = sighup; sigemptyset(&sa.sa_mask); sigaddset(&sa.sa_mask, SIGHUP); sa.sa_flags=0; if (sigaction(SIGHUP, &sa, NULL) < 0) { syslog(LOG_ERR, "can't catch SIGHUP: %s", strerror(errno)); exit(1); } if (xmi_start_random_acquisition_dev() != 1) { syslog(LOG_ERR,"xmi_start_random_acquisition_dev error"); exit(1); } syslog(LOG_INFO,"daemon running succesfully"); pthread_attr_init(&ha); pthread_attr_setdetachstate(&ha,PTHREAD_CREATE_DETACHED); while (1) { //create fifo if (mkfifo(FIFOMASTER, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH) == -1) { syslog(LOG_ERR,"Could not create named link" FIFOMASTER ": %s",strerror(errno)); exit(1); } if ((fifofd = open(FIFOMASTER,O_RDONLY)) == -1) { syslog(LOG_ERR,"Could not open named link" FIFOMASTER ": %s",strerror(errno)); exit(1); } //read pid from slave if (read(fifofd,pidslave,3*sizeof(long int)) != 3*sizeof(long int)) { syslog(LOG_ERR,"Error reading from " FIFOMASTER ": %s",strerror(errno)); exit(1); } close(fifofd); unlink(FIFOMASTER); #ifdef DEBUG syslog(LOG_INFO,"Daemon -> pid: %li counter: %li number: %li",pidslave[0],pidslave[1],pidslave[2]); #endif //allocate necessary variables sh = (struct harvester *) g_malloc(sizeof(struct harvester)); ht = (pthread_t *) g_malloc(sizeof(pthread_t)); //create slave fifo sh->fifoslave = g_strdup_printf(FIFOSLAVE "%li.%li",pidslave[0],pidslave[1]); sh->nseeds = pidslave[2]; //start thread pthread_create(ht,&ha,harvest_thread,sh); } return 0; }
/* * chat [-esSvV] [-f chat-file] [-r report-file] [-t timeout] * [-T phone-number] [-U phone-number2] [chat-script] * where chat-script has the form: * [...[[expect[-send[-expect...]] send expect[-send[-expect]] ...]]] * * Perform a UUCP-dialer-like chat script on stdin and stdout. */ int main(int argc, char *argv[]) { int option; tzset(); while ((option = getopt(argc, argv, "ef:r:sSt:T:U:vV")) != -1) { switch (option) { case 'e': ++echo; break; case 'f': if (chat_file != NULL) free(chat_file); chat_file = copy_of(optarg); break; case 'r': if (report_fp != NULL) fclose(report_fp); if (report_file != NULL) free(report_file); report_file = copy_of(optarg); report_fp = fopen(report_file, "a"); if (report_fp != NULL) { if (verbose) fprintf(report_fp, "Opening \"%s\"...\n", report_file); } else fatal(2, "cannot open \"%s\" for appending", report_file); break; case 's': ++to_stderr; break; case 'S': to_log = 0; break; case 't': timeout = atoi(optarg); break; case 'T': if (phone_num != NULL) free(phone_num); phone_num = copy_of(optarg); break; case 'U': if (phone_num2 != NULL) free(phone_num2); phone_num2 = copy_of(optarg); break; case 'v': ++verbose; break; case 'V': ++Verbose; break; default: usage(); break; } } argc -= optind; argv += optind; /* * Default the report file to the stderr location */ if (report_fp == NULL) report_fp = stderr; if (to_log) { openlog("chat", LOG_PID | LOG_NDELAY, LOG_LOCAL2); if (verbose) setlogmask(LOG_UPTO(LOG_INFO)); else setlogmask(LOG_UPTO(LOG_WARNING)); } if (chat_file != NULL) { if (*argv != NULL) usage(); else { init(); do_file(chat_file); } } else { init(); while (*argv != NULL && argc > 0) { chat_expect(*argv); argv++; argc--; if (*argv != NULL && argc > 0) { chat_send(*argv); argv++; argc--; } } } terminate(0); return 0; }
void vconsoleLogger(int priority, const char *format, va_list optional_arguments) { /*int n = 0;*/ const int saved_errno = errno; const int LogMask = setlogmask(0); /* no cancellation point is currently used in this function * (according to Advanced Programming in the Unix Environment 2nd ed p411) * so there is no thread cancellation clean-up handlers defined */ /* Check for invalid bits. */ if (unlikely(priority & ~(LOG_PRIMASK | LOG_FACMASK))) { /*syslog(INTERNALLOG, "syslog: unknown facility/priority: %x", pri);*/ WARNING_MSG("unknown facility/priority: %x", priority); priority &= LOG_PRIMASK | LOG_FACMASK; } /* Check priority against setlogmask values. */ if ((LOG_MASK (LOG_PRI (priority)) & LogMask) != 0) { char *buf = 0; size_t bufsize = 1024; /*char logFormat[1024]; char *cursor = logFormat;*/ FILE *f = open_memstream(&buf, &bufsize); if (f != NULL) { struct tm now_tm; time_t now; (void) time(&now); /*cursor += strftime(cursor,sizeof(logFormat),"%h %e %T ",localtime_r(&now, &now_tm));*/ f->_IO_write_ptr += strftime(f->_IO_write_ptr,f->_IO_write_end - f->_IO_write_ptr,"%h %e %T ",localtime_r(&now, &now_tm)); if (LogTag) { //cursor += sprintf (cursor,"%s: ",LogTag); fprintf(f,"%s: ",LogTag); } if (LogStat & LOG_PID) { if (LogStat & LOG_TID) { const pid_t tid = gettid(); /*cursor += sprintf (cursor, "[%d:%d]", (int) getpid (),(int) tid);*/ fprintf(f,"[%d:%d]", (int) getpid (),(int) tid); } else { /*cursor += sprintf (cursor, "[%d]", (int) getpid ());*/ fprintf(f,"[%d]", (int) getpid ()); } } if (LogStat & LOG_RDTSC) { const unsigned long long int t = rdtsc(); /*cursor += sprintf (cursor, "(%llu)",t);*/ fprintf(f,"(%llu)",t); } /* (LogStat & LOG_RDTSC) */ if (LogStat & LOG_CLOCK) { #if HAVE_CLOCK_GETTIME struct timespec timeStamp; if (clock_gettime(CLOCK_MONOTONIC,&timeStamp) == 0) { /*cursor += sprintf (cursor, "(%lu.%.9d)",timeStamp.tv_sec,timeStamp.tv_nsec);*/ fprintf(f,"(%lu.%.9d)",timeStamp.tv_sec,timeStamp.tv_nsec); } else { const int error = errno; ERROR_MSG("clock_gettime CLOCK_MONOTONIC error %d (%m)",error); } #else static unsigned int alreadyPrinted = 0; /* to avoid to print this error msg on each call */ if (unlikely(0 == alreadyPrinted)) { ERROR_MSG("clock_gettime not available on this system"); alreadyPrinted = 1; } #endif } /* (LogStat & LOG_CLOCK) */ if (LogStat & LOG_LEVEL) { switch(LOG_PRI(priority)) { case LOG_EMERG: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Emergency * %s",format);*/ fprintf(f,"[EMERG] %s",format); break; case LOG_ALERT: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Alert * %s",format);*/ fprintf(f,"[ALERT] %s",format); break; case LOG_CRIT: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Critical * %s",format);*/ fprintf(f,"[CRIT] %s",format); break; case LOG_ERR: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Error * %s",format);*/ fprintf(f,"[ERROR] %s",format); break; case LOG_WARNING: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Warning * %s",format);*/ fprintf(f,"[WARNING] %s",format); break; case LOG_NOTICE: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Notice * %s",format); */ fprintf(f,"[NOTICE] %s",format); break; case LOG_INFO: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Info * %s",format);*/ fprintf(f,"[INFO] %s",format); break; case LOG_DEBUG: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Debug * %s",format);*/ fprintf(f,"[DEBUG] %s",format); break; default: /*cursor += sprintf(cursor,"* <%d> * %s",priority,format);*/ fprintf(f,"[<%d>] %s",priority,format); } /* switch(priority) */ } else { /* (LogStat & LOG_LEVEL) */ /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"%s",format);*/ fprintf(f,"%s",format); } /*n =*/ /*vfprintf(stderr,logFormat,optional_arguments);*/ /* Close the memory stream; this will finalize the data into a malloc'd buffer in BUF. */ fclose(f); errno = saved_errno; /* restore errno for %m format */ vfprintf(stderr,buf,optional_arguments); free(buf); } else { /* We cannot get a stream: try to write directly to the console (warning may be splitted by other msg) */ struct tm now_tm; time_t now; char buffer[20]; WARNING_MSG("failed to get stream buffer, using the console without buffering instead"); (void) time(&now); strftime(buffer,sizeof(buffer),"%h %e %T ",localtime_r(&now, &now_tm)); fprintf(stderr,"%s",buffer); if (LogTag) { printf("%s: ",LogTag); } if (LogStat & LOG_PID) { if (LogStat & LOG_TID) { const pid_t tid = gettid(); fprintf(stderr,"[%d:%d]", (int) getpid (),(int) tid); } else { fprintf(stderr,"[%d]", (int) getpid ()); } } if (LogStat & LOG_RDTSC) { const unsigned long long int t = rdtsc(); fprintf(stderr,"(%llu)",t); } /* (LogStat & LOG_RDTSC) */ if (LogStat & LOG_CLOCK) { #if HAVE_CLOCK_GETTIME struct timespec timeStamp; if (clock_gettime(CLOCK_MONOTONIC,&timeStamp) == 0) { fprintf(stderr,"(%lu.%.9d)",timeStamp.tv_sec,timeStamp.tv_nsec); } else { const int error = errno; ERROR_MSG("clock_gettime CLOCK_MONOTONIC error %d (%m)",error); } #else static unsigned int alreadyPrinted = 0; /* to avoid to print this error msg on each call */ if (unlikely(0 == alreadyPrinted)) { ERROR_MSG("clock_gettime not available on this system"); alreadyPrinted = 1; } #endif } /* (LogStat & LOG_CLOCK) */ if (LogStat & LOG_LEVEL) { switch(LOG_PRI(priority)) { case LOG_EMERG: fprintf(stderr,"* Emergency * "); break; case LOG_ALERT: fprintf(stderr,"* Alert * "); break; case LOG_CRIT: fprintf(stderr,"* Critical * "); break; case LOG_ERR: fprintf(stderr,"* Error * "); break; case LOG_WARNING: fprintf(stderr,"* Warning * "); break; case LOG_NOTICE: fprintf(stderr,"* Notice * "); break; case LOG_INFO: fprintf(stderr,"* Info * "); break; case LOG_DEBUG: fprintf(stderr,"* Debug * "); break; default: fprintf(f,"* <%d> * ",priority); } /* switch(priority) */ } vfprintf(stderr,format,optional_arguments); } } /* ((LOG_MASK (LOG_PRI (priority)) & LogMask) != 0) */ /* message has not to be displayed because of the current LogMask and its priority */ /*return n;*/ }
int main(int argc, char **argv) { int n = 0; int use_ssl = 0; struct libwebsocket_context *context; int opts = 0; char interface_name[128] = ""; const char *iface = NULL; #ifndef WIN32 int syslog_options = LOG_PID | LOG_PERROR; #endif unsigned int oldus = 0; struct lws_context_creation_info info; int debug_level = 7; #ifndef LWS_NO_DAEMONIZE int daemonize = 0; #endif memset(&info, 0, sizeof info); info.port = 7681; while (n >= 0) { n = getopt_long(argc, argv, "ci:hsp:d:D", options, NULL); if (n < 0) continue; switch (n) { #ifndef LWS_NO_DAEMONIZE case 'D': daemonize = 1; #ifndef WIN32 syslog_options &= ~LOG_PERROR; #endif break; #endif case 'd': debug_level = atoi(optarg); break; case 's': use_ssl = 1; break; case 'p': info.port = atoi(optarg); break; case 'i': strncpy(interface_name, optarg, sizeof interface_name); interface_name[(sizeof interface_name) - 1] = '\0'; iface = interface_name; break; case 'c': close_testing = 1; fprintf(stderr, " Close testing mode -- closes on " "client after 50 dumb increments" "and suppresses lws_mirror spam\n"); break; case 'h': fprintf(stderr, "Usage: test-server " "[--port=<p>] [--ssl] " "[-d <log bitfield>]\n"); exit(1); } } #if !defined(LWS_NO_DAEMONIZE) && !defined(WIN32) /* * normally lock path would be /var/lock/lwsts or similar, to * simplify getting started without having to take care about * permissions or running as root, set to /tmp/.lwsts-lock */ if (daemonize && lws_daemonize("/tmp/.lwsts-lock")) { fprintf(stderr, "Failed to daemonize\n"); return 1; } #endif signal(SIGINT, sighandler); #ifndef WIN32 /* we will only try to log things according to our debug_level */ setlogmask(LOG_UPTO (LOG_DEBUG)); openlog("lwsts", syslog_options, LOG_DAEMON); #endif /* tell the library what debug level to emit and to send it to syslog */ lws_set_log_level(debug_level, lwsl_emit_syslog); lwsl_notice("libwebsockets test server - " "(C) Copyright 2010-2013 Andy Green <*****@*****.**> - " "licensed under LGPL2.1\n"); #ifdef EXTERNAL_POLL max_poll_elements = getdtablesize(); pollfds = malloc(max_poll_elements * sizeof (struct pollfd)); fd_lookup = malloc(max_poll_elements * sizeof (int)); if (pollfds == NULL || fd_lookup == NULL) { lwsl_err("Out of memory pollfds=%d\n", max_poll_elements); return -1; } #endif info.protocols = protocols; if (!use_ssl) { info.ssl_cert_filepath = NULL; info.ssl_private_key_filepath = NULL; } else { // info.ssl_cert_filepath = LOCAL_RESOURCE_PATH"/libwebsockets-test-server.pem"; // info.ssl_private_key_filepath = LOCAL_RESOURCE_PATH"/libwebsockets-test-server.key.pem"; } info.gid = -1; info.uid = -1; info.options = opts; context = libwebsocket_create_context(&info); if (context == NULL) { lwsl_err("libwebsocket init failed\n"); return -1; } n = 0; while (n >= 0 && !force_exit) { struct timeval tv; gettimeofday(&tv, NULL); n = libwebsocket_service(context, 50); } libwebsocket_context_destroy(context); lwsl_notice("libwebsockets-test-server exited cleanly\n"); closelog(); return 0; }
int main(int argc, char *argv[]) { /* variables used on multiple locations are set at the top of the function */ int status = 0; int daemon = 0; char *customConfigLocation = NULL; setlogmask(LOG_UPTO(LOG_NOTICE)); int option = 0; opterr = 0; while((option = getopt(argc, argv, "v:Vhdi:")) != -1) switch(option) { case 'v': if(strcmp(optarg, "0") == 0) setlogmask(LOG_UPTO(LOG_ERR)); else if(strcmp(optarg, "1") == 0) setlogmask(LOG_UPTO(LOG_INFO)); else if(strcmp(optarg, "2") == 0) setlogmask(LOG_UPTO(LOG_DEBUG)); break; case 'V': fprintf(stdout, "%s %s\n\n%s\n", PROGRAM_NAME, PROGRAM_VERSION, PROGRAM_LEGAL); exit(EXIT_SUCCESS); case 'h': fprintf(stdout, "Usage: %s %s", argv[0], TEXT_USAGE); exit(EXIT_SUCCESS); case 'd': daemon = 1; break; case 'i': customConfigLocation = optarg; break; case '?': if(optopt == 'i') fprintf(stderr, "You forgot to include a path with option '-%c'.\n", optopt); else if(optopt == 'v') setlogmask(LOG_UPTO(LOG_INFO)); else if(isprint(optopt)) fprintf(stderr, "Unknown option `-%c'.\n", optopt); else fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt); exit(EXIT_FAILURE); default: exit(EXIT_FAILURE); } /* All files created without revoked permissions (thus result: 0666) */ umask(0); if(daemon) { if((status = daemonize()) == EXIT_FAILURE) exit(EXIT_FAILURE); } else { /* Setup syslog, print also to stderr, and give notice of execution */ openlog(PROGRAM_NAME, LOG_NDELAY | LOG_PID | LOG_PERROR, LOG_DAEMON); syslog(LOG_NOTICE, "Program started by User %d", getuid()); } /* Lock process and print pid to lock file */ if((lock_file = open(LOCKFILE, O_RDWR|O_CREAT|O_CLOEXEC, LOCKMODE)) < 0) { syslog(LOG_ERR, "Failed to open lock file: %s", strerror(errno)); closelog(); exit(EXIT_FAILURE); } if(lockf(lock_file, F_TLOCK, 0) < 0) { syslog(LOG_WARNING, "Exiting: only one instance of this application can run: %s", strerror(errno)); closelog(); exit(EXIT_SUCCESS); } ftruncate(lock_file, 0); dprintf(lock_file, "%d\n", getpid()); /* Get main thread id and make it the default value for all other threads. * If a thread has been initialized, it changes the default value and the * termination handler knows whether to cancel it or not. */ mainThread = statusQueryThread = watchMixerThread = interfaceListenThread = pthread_self(); common_data.process = NULL; common_data.interface = NULL; common_data.volume = NULL; struct sigaction signal_action; signal_action.sa_handler = terminate; sigfillset(&signal_action.sa_mask); signal_action.sa_flags = 0; if(sigaction(SIGINT, &signal_action, NULL) < 0 || sigaction(SIGTERM, &signal_action, NULL) < 0) { syslog(LOG_ERR, "Failed to ignore signals: %s", strerror(errno)); closelog(); exit(EXIT_FAILURE); } /* Execute synchronatord function, if all goes well, it will never return */ status = synchronatord(customConfigLocation); syslog(LOG_ERR, "Exiting: %i", status); closelog(); exit(status); } /* end main */
/** * @brief benchmark * cbenchmark的入口 * 通过读取参数中的信息 * 开始执行 * * @param param * cbenchmark全局信息 */ void benchmark(void* param) { struct bench * bp = bm_init(param); struct timeval tvStart,tvEnd; float dif = 0; float tps = 0; if(bp->mode & BM_MODE_SHARE && (bp->libs != NULL)){ init_mw(bp); } //参数文件初始化 if(bp->infile != NULL){ init_proc_param(bp); } //日志初始化 openlog(bp->log.name, LOG_PID|LOG_CONS, LOG_USER); setlogmask(LOG_UPTO(bp->log.level)); /* * 为cbenchmark主进程注册信号处理函数 * 之后会对每个子进程也注册类似函数 * 这些信号处理统一由cb_trap管理 */ /* * SIGINT信号处理当用户通过Ctrl+C发送中断信息给主进程后 * 主进程将让子进程停止工作 * 同时自己也逐渐结束 */ if(signal(SIGINT,cb_trap) == SIG_ERR){ fprintf(stderr,"Register signal trap faile."); }; //起始时间 gettimeofday(&tvStart,NULL); dispatch(bp); //如果以定时器模式执行 //则启动定时器 //并设置回掉函数 //让其对子进程发送SIGUSR1信号 if(bp->mode & BM_MODE_TIMER){ timer(&bp->time,cb_kill_children_break,NULL); } //等待所有进程终止 waitall((void *)bp); //终止时间 gettimeofday(&tvEnd,NULL); dif = (tvEnd.tv_sec-tvStart.tv_sec) + (tvEnd.tv_usec-tvStart.tv_usec)/1000000.0; analyse((void *)bp,dif); //关闭日志 closelog(); //关闭动态库 if(bp->mode & BM_MODE_SHARE && (bp->libs != NULL)){ destroy_mw(bp); } }
/* Application Launcher Daemon entrypoint */ int main(int argc, char **argv) { /* return code */ int l_ret; /* logging mechanism */ int log = LOG_MASK (LOG_ERR) | LOG_MASK (LOG_INFO); #ifdef DEBUG log = log | LOG_MASK(LOG_DEBUG); #endif openlog ("AL-DAEMON", 0x0, LOG_USER); setlogmask(log); /* handle signals */ signal(SIGTERM, AlSignalHandler); signal(SIGKILL, AlSignalHandler); /* parse cli options */ AlParseCLIOptions(argc, argv); if (g_stop) { AlDaemonShutdown(); return 0; } if (g_start) { /* daemonize the application launcher */ AlDaemonize(); log_message("Daemon process was started !\n", 0); #ifdef USE_LAST_USER_MODE /* initialise the last user mode */ if(!(l_ret=InitializeLastUserMode())){ log_error_message("Last user mode initialization failed !\n", 0); } else { log_message("Last user mode initialized. Listening for method calls ....\n", 0); } #endif /* initialize SRM Daemon */ if(!initialize_al_dbus()){ log_error_message("Failed to initialize AL Daemon!\n Stopping daemon ...", 0); terminate_al_dbus(); return 1; } /* start the signal dispatching thread */ al_dbus_signal_dispatcher(); /* main loop */ GMainLoop *l_loop = NULL; if(!(l_loop = g_main_loop_new(NULL, FALSE))){ log_error_message("Error creating main loop !\n", 0); exit(1); } /* run the main loop */ g_main_loop_run(l_loop); } log_message("Daemon exited !\n", 0); /* close logging mechanism */ closelog (); /* free res */ terminate_al_dbus(); return 0; }
static int syslog_setlogmask(lua_State *L) { lua_pushinteger(L, setlogmask(luaL_checkint(L, 1))); return 1; }
/* * Initialize the logging * * Called once per process, including forked children. */ void init_logging( const char * name, u_int32 def_syslogmask, int is_daemon ) { static int was_daemon; const char * cp; const char * pname; /* * ntpd defaults to only logging sync-category events, when * NLOG() is used to conditionalize. Other libntp clients * leave it alone so that all NLOG() conditionals will fire. * This presumes all bits lit in ntp_syslogmask can't be * configured via logconfig and all lit is thereby a sentinel * that ntp_syslogmask is still at its default from libntp, * keeping in mind this function is called in forked children * where it has already been called in the parent earlier. * Forked children pass 0 for def_syslogmask. */ if (INIT_NTP_SYSLOGMASK == ntp_syslogmask && 0 != def_syslogmask) ntp_syslogmask = def_syslogmask; /* set more via logconfig */ /* * Logging. This may actually work on the gizmo board. Find a name * to log with by using the basename */ cp = strrchr(name, DIR_SEP); if (NULL == cp) pname = name; else pname = 1 + cp; /* skip DIR_SEP */ progname = estrdup(pname); #ifdef SYS_WINNT /* strip ".exe" */ cp = strrchr(progname, '.'); if (NULL != cp && !strcasecmp(cp, ".exe")) progname[cp - progname] = '\0'; #endif #if !defined(VMS) if (is_daemon) was_daemon = TRUE; # ifndef LOG_DAEMON openlog(progname, LOG_PID); # else /* LOG_DAEMON */ # ifndef LOG_NTP # define LOG_NTP LOG_DAEMON # endif openlog(progname, LOG_PID | LOG_NDELAY, (was_daemon) ? LOG_NTP : 0); # ifdef DEBUG if (debug) setlogmask(LOG_UPTO(LOG_DEBUG)); else # endif /* DEBUG */ setlogmask(LOG_UPTO(LOG_DEBUG)); /* @@@ was INFO */ # endif /* LOG_DAEMON */ #endif /* !VMS */ }
int main(int argc, char **argv) #endif { SOCKET srv_fd; int status; WSADATA wsaData; // options char *srv_host = NULL; int srv_port = 0; char *keyfile = NULL; //"privkeySrv.pem"; char *certfile = NULL; //"certSrv.pem"; int vlevel = 0; char *cpos,*opos; int tmpport; int c; int intarg; #if VXWORKS int argc; char **argv; parseCmdLineArgs(arg1, &argc, &argv); #endif /* VXWORKS */ #if WINCE int argc; char **argv; char args[256]; /* * parseCmdLineArgs expects an ASCII string and CE is unicoded, so convert * the command line. args will get hacked up, so you can't pass in a * static string. */ WideCharToMultiByte(CP_ACP, 0, lpCmdLine, -1, args, 256, NULL, NULL); /* * Parse the command line into an argv array. This allocs memory, so * we have to free argv when we're done. */ parseCmdLineArgs(args, &argc, &argv); #endif /* WINCE */ /* prepare */ #ifndef USE_FORK memset(connections,0,MAXPROXYCOUNT*sizeof(struct proxyConnection)); #endif /* getopt */ /* Gemtek add +++ */ if(argc == 1) usage(1); /* Gemtek add --- */ for (;;) { c = getopt (argc, argv, "VD:P:fo:cd:r:p:A:v:h"); if (c == -1) { break; } switch (c) { case 'c': // client mode isClient=1; break; case 'd': // daemon mode [host:]port cpos = NULL; tmpport = 0; if((cpos = strchr(optarg,':'))) { *cpos = '\0'; if(optarg && optarg[0]) srv_host = optarg; optarg = ++cpos; } if(optarg && optarg[0]) { tmpport = (int)strtol(optarg, (char **)NULL, 0); if(tmpport) srv_port = tmpport; } break; case 'r': // remote [host:]port cpos = NULL; tmpport = 0; if((cpos = strchr(optarg,':'))) { *cpos = '\0'; if(optarg && optarg[0]) dst_host = optarg; optarg = ++cpos; } if(optarg && optarg[0]) { tmpport = (int)strtol(optarg, (char **)NULL, 0); if(tmpport) dst_port = tmpport; } break; case 'p': // pemfile (requred in servermode) keyfile = optarg; break; case 'A': // CA file certfile = optarg; break; case 'v': // veryfication level if(optarg && optarg[0]) { vlevel = (int)strtol(optarg, (char **)NULL, 0); if(vlevel == 1 ) { cervalidator = certChecker; } else if(vlevel > 3 || vlevel < 0) { fprintf(stderr,"-v takes whole numbers between 0 and 3"); exit(2); } } break; case 'P': // create a pidfile pidfile=optarg; break; case 'f': // run in foreground. nofork=1; nosysl=1; break; case 'o': // append logmessages to a file instead of stdout/syslog break; case 'O': // socket options. TODO break; case 'D': // debug level 0...7 intarg=strtol(optarg,NULL,0); if(intarg<0 || intarg>7) { usage(1); } gLogLevel=intarg; break; case 'V': // version break; case '?': case 'h': usage(0); break; default: usage(1); break; } } /* install handlers */ signal( SIGPIPE, SIG_IGN ); signal(SIGCHLD,sigchld_handler); /* ignore child */ signal(SIGHUP,kill_handler); /* catch hangup signal */ signal(SIGTERM,kill_handler); /* catch kill signal */ /* Initialize Windows sockets (no-op on other platforms) */ WSAStartup(MAKEWORD(1,1), &wsaData); if(!nosysl) { openlog("matrixtunnel", LOG_PID, LOG_DAEMON); setlogmask(LOG_UPTO(gLogLevel)); } /* Initialize the MatrixSSL Library, and read in the public key (certificate) and private key. */ if (matrixSslOpen() < 0) { ELOG("matrixSslOpen failed, exiting..."); exit(1); } /* Standard PEM files */ if (matrixSslReadKeys(&keys, certfile, keyfile, NULL, NULL) < 0) { ELOG("Error reading or parsing %s or %s, exiting...", certfile, keyfile); exit(1); } // go to background if(!nofork) { daemonize(); } /* Create the listen socket */ if ((srv_fd = socketListen(srv_port, &status)) == INVALID_SOCKET) { ELOG("Cannot listen on port %d, exiting...", srv_port); exit(1); } /* Set blocking or not on the listen socket */ setSocketBlock(srv_fd); /* Main connection loop */ struct proxyConnection *cp=NULL; struct proxyConnection *ncp; fd_set rs, ws, es, cr; int fdmax; struct timeval tv; int res, dontClose; char buf[4096]; int pc, sc; int ccount; while (!quit) { fdmax=srv_fd; ncp=NULL; FD_ZERO(&rs); FD_ZERO(&ws); FD_ZERO(&es); FD_SET(srv_fd,&rs); FD_SET(srv_fd,&ws); FD_SET(srv_fd,&es); ccount=0; #ifndef USE_FORK DLOG("next select on fds: %d ",srv_fd); for(cp=connections;cp<&connections[MAXPROXYCOUNT];cp++) { if (cp->done) { closeProxyConnection(cp); } if (cp->secure_up) { FD_SET(cp->secure->fd,&rs); FD_SET(cp->secure->fd,&ws); FD_SET(cp->secure->fd,&es); if (fdmax < cp->secure->fd) fdmax = cp->secure->fd; DLOG("fd: %d",cp->secure->fd); ccount++; } if (cp->plain_up) { FD_SET(cp->plain,&rs); FD_SET(cp->plain,&ws); FD_SET(cp->plain,&es); if (fdmax < cp->plain) fdmax = cp->plain; DLOG("fd: %d",cp->plain); ccount++; } if(!ncp && !cp->inuse){ ncp=cp; memset(ncp,0,sizeof(struct proxyConnection)); } } #else struct proxyConnection ncp_s; ncp=&ncp_s; memset(ncp,0,sizeof(struct proxyConnection)); #endif tv.tv_sec=10; tv.tv_usec=0; DLOG("main : select on %d open connections. fdmax: %d", ccount, fdmax); res=select(fdmax+1,&rs,NULL,&es,&tv); DLOG("select returned: %d %s", res , strerror(errno) ); if(res<0) { perror("select"); continue; } if(res==0) continue; #ifndef USE_FORK // handle open connections for(cp=connections;cp<&connections[MAXPROXYCOUNT];cp++) { if (cp->secure_up && cp->plain_up) { if(FD_ISSET(cp->secure->fd,&es) || FD_ISSET(cp->plain,&es)) { closeProxyConnection(cp); continue; } if(secureReady(cp)) { sc=proxyReadwrite(cp,1); if(sc<0) { closeProxyConnection(cp); continue; } } if(plainReady(cp)) { pc=proxyReadwrite(cp,0); if(pc<0) { closeProxyConnection(cp); continue; } } } } #endif // do we have new connections? if(FD_ISSET(srv_fd,&rs)) { proxyAccept(srv_fd,ncp); } } /* Close listening socket, free remaining items */ socketShutdown(srv_fd); #ifndef USE_FORK for(cp=connections;cp<&connections[MAXPROXYCOUNT];cp++) { closeProxyConnection(cp); } #endif if(!nosysl) { closelog(); } matrixSslFreeKeys(keys); matrixSslClose(); WSACleanup(); return 0; }
int main(int argc, char *argv[]) { int s, rtsock, maxfd, ch; int once = 0; struct timeval *timeout; struct fd_set fdset; char *argv0; const char *opts; /* * Initialization */ argv0 = argv[0]; /* get option */ if (argv0 && argv0[strlen(argv0) - 1] != 'd') { fflag = 1; once = 1; opts = "adD"; } else opts = "adDfm1"; while ((ch = getopt(argc, argv, opts)) != -1) { switch (ch) { case 'a': aflag = 1; break; case 'd': dflag = 1; break; case 'D': dflag = 2; break; case 'f': fflag = 1; break; case 'm': mobile_node = 1; break; case '1': once = 1; break; default: usage(argv0); /*NOTREACHED*/ } } argc -= optind; argv += optind; if (aflag) { int i; if (argc != 0) { usage(argv0); /*NOTREACHED*/ } argv = autoifprobe(); if (!argv) { errx(1, "could not autoprobe interface"); /*NOTREACHED*/ } for (i = 0; argv[i]; i++) ; argc = i; } if (argc == 0) { usage(argv0); /*NOTREACHED*/ } /* set log level */ if (dflag == 0) log_upto = LOG_NOTICE; if (!fflag) { char *ident; ident = strrchr(argv0, '/'); if (!ident) ident = argv0; else ident++; openlog(ident, LOG_NDELAY|LOG_PID, LOG_DAEMON); if (log_upto >= 0) setlogmask(LOG_UPTO(log_upto)); } #ifndef HAVE_ARC4RANDOM /* random value initilization */ srandom((u_long)time(NULL)); #endif /* warn if accept_rtadv is down */ if (!getinet6sysctl(IPV6CTL_ACCEPT_RTADV)) warnx("kernel is configured not to accept RAs"); /* warn if forwarding is up */ if (getinet6sysctl(IPV6CTL_FORWARDING)) warnx("kernel is configured as a router, not a host"); /* initialization to dump internal status to a file */ if (signal(SIGUSR1, rtsold_set_dump_file) == SIG_ERR) { errx(1, "failed to set signal for dump status"); /*NOTREACHED*/ } /* * Open a socket for sending RS and receiving RA. * This should be done before calling ifinit(), since the function * uses the socket. */ if ((s = sockopen()) < 0) { errx(1, "failed to open a socket"); /*NOTREACHED*/ } maxfd = s; if ((rtsock = rtsock_open()) < 0) { errx(1, "failed to open a socket"); /*NOTREACHED*/ } if (rtsock > maxfd) maxfd = rtsock; /* configuration per interface */ if (ifinit()) { errx(1, "failed to initilizatoin interfaces"); /*NOTREACHED*/ } while (argc--) { if (ifconfig(*argv)) { errx(1, "failed to initialize %s", *argv); /*NOTREACHED*/ } argv++; } /* setup for probing default routers */ if (probe_init()) { errx(1, "failed to setup for probing routers"); /*NOTREACHED*/ } if (!fflag) daemon(0, 0); /* act as a daemon */ /* dump the current pid */ if (!once) { pid_t pid = getpid(); FILE *fp; if ((fp = fopen(pidfilename, "w")) == NULL) warnmsg(LOG_ERR, __func__, "failed to open a log file(%s): %s", pidfilename, strerror(errno)); else { fprintf(fp, "%d\n", pid); fclose(fp); } } FD_ZERO(&fdset); FD_SET(s, &fdset); FD_SET(rtsock, &fdset); while (1) { /* main loop */ int e; struct fd_set select_fd = fdset; if (do_dump) { /* SIGUSR1 */ do_dump = 0; rtsold_dump_file(dumpfilename); } timeout = rtsol_check_timer(); if (once) { struct ifinfo *ifi; /* if we have no timeout, we are done (or failed) */ if (timeout == NULL) break; /* if all interfaces have got RA packet, we are done */ for (ifi = iflist; ifi; ifi = ifi->next) { if (ifi->state != IFS_DOWN && ifi->racnt == 0) break; } if (ifi == NULL) break; } e = select(maxfd + 1, &select_fd, NULL, NULL, timeout); if (e < 1) { if (e < 0 && errno != EINTR) { warnmsg(LOG_ERR, __func__, "select: %s", strerror(errno)); } continue; } /* packet reception */ if (FD_ISSET(rtsock, &select_fd)) rtsock_input(rtsock); if (FD_ISSET(s, &select_fd)) rtsol_input(s); } /* NOTREACHED */ return 0; }
int main(int argc, char **argv) { char cert_path[1024]; char key_path[1024]; int n = 0; int use_ssl = 0; int opts = 0; char interface_name[128] = ""; const char *iface = NULL; #ifndef WIN32 int syslog_options = LOG_PID | LOG_PERROR; #endif unsigned int ms, oldms = 0; struct lws_context_creation_info info; int debug_level = 7; #ifndef LWS_NO_DAEMONIZE int daemonize = 0; #endif memset(&info, 0, sizeof info); info.port = 7681; while (n >= 0) { n = getopt_long(argc, argv, "eci:hsap:d:Dr:", options, NULL); if (n < 0) continue; switch (n) { case 'e': opts |= LWS_SERVER_OPTION_LIBEV; break; #ifndef LWS_NO_DAEMONIZE case 'D': daemonize = 1; #ifndef WIN32 syslog_options &= ~LOG_PERROR; #endif break; #endif case 'd': debug_level = atoi(optarg); break; case 's': use_ssl = 1; break; case 'a': opts |= LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT; break; case 'p': info.port = atoi(optarg); break; case 'i': strncpy(interface_name, optarg, sizeof interface_name); interface_name[(sizeof interface_name) - 1] = '\0'; iface = interface_name; break; case 'c': close_testing = 1; fprintf(stderr, " Close testing mode -- closes on " "client after 50 dumb increments" "and suppresses lws_mirror spam\n"); break; case 'r': resource_path = optarg; printf("Setting resource path to \"%s\"\n", resource_path); break; case 'h': fprintf(stderr, "Usage: test-server " "[--port=<p>] [--ssl] " "[-d <log bitfield>] " "[--resource_path <path>]\n"); exit(1); } } #if !defined(LWS_NO_DAEMONIZE) && !defined(WIN32) /* * normally lock path would be /var/lock/lwsts or similar, to * simplify getting started without having to take care about * permissions or running as root, set to /tmp/.lwsts-lock */ if (daemonize && lws_daemonize("/tmp/.lwsts-lock")) { fprintf(stderr, "Failed to daemonize\n"); return 1; } #endif signal(SIGINT, sighandler); #ifndef WIN32 /* we will only try to log things according to our debug_level */ setlogmask(LOG_UPTO (LOG_DEBUG)); openlog("lwsts", syslog_options, LOG_DAEMON); #endif /* tell the library what debug level to emit and to send it to syslog */ lws_set_log_level(debug_level, lwsl_emit_syslog); lwsl_notice("libwebsockets test server - " "(C) Copyright 2010-2014 Andy Green <*****@*****.**> - " "licensed under LGPL2.1\n"); #ifdef EXTERNAL_POLL max_poll_elements = getdtablesize(); pollfds = malloc(max_poll_elements * sizeof (struct pollfd)); fd_lookup = malloc(max_poll_elements * sizeof (int)); if (pollfds == NULL || fd_lookup == NULL) { lwsl_err("Out of memory pollfds=%d\n", max_poll_elements); return -1; } #endif info.iface = iface; info.protocols = protocols; #ifndef LWS_NO_EXTENSIONS info.extensions = libwebsocket_get_internal_extensions(); #endif if (!use_ssl) { info.ssl_cert_filepath = NULL; info.ssl_private_key_filepath = NULL; } else { if (strlen(resource_path) > sizeof(cert_path) - 32) { lwsl_err("resource path too long\n"); return -1; } sprintf(cert_path, "%s/libwebsockets-test-server.pem", resource_path); if (strlen(resource_path) > sizeof(key_path) - 32) { lwsl_err("resource path too long\n"); return -1; } sprintf(key_path, "%s/libwebsockets-test-server.key.pem", resource_path); info.ssl_cert_filepath = cert_path; info.ssl_private_key_filepath = key_path; } info.gid = -1; info.uid = -1; info.options = opts; context = libwebsocket_create_context(&info); if (context == NULL) { lwsl_err("libwebsocket init failed\n"); return -1; } n = 0; while (n >= 0 && !force_exit) { struct timeval tv; gettimeofday(&tv, NULL); /* * This provokes the LWS_CALLBACK_SERVER_WRITEABLE for every * live websocket connection using the DUMB_INCREMENT protocol, * as soon as it can take more packets (usually immediately) */ ms = (tv.tv_sec * 1000) + (tv.tv_usec / 1000); if ((ms - oldms) > 50) { libwebsocket_callback_on_writable_all_protocol(&protocols[PROTOCOL_DUMB_INCREMENT]); oldms = ms; } #ifdef EXTERNAL_POLL /* * this represents an existing server's single poll action * which also includes libwebsocket sockets */ n = poll(pollfds, count_pollfds, 50); if (n < 0) continue; if (n) for (n = 0; n < count_pollfds; n++) if (pollfds[n].revents) /* * returns immediately if the fd does not * match anything under libwebsockets * control */ if (libwebsocket_service_fd(context, &pollfds[n]) < 0) goto done; #else /* * If libwebsockets sockets are all we care about, * you can use this api which takes care of the poll() * and looping through finding who needed service. * * If no socket needs service, it'll return anyway after * the number of ms in the second argument. */ n = libwebsocket_service(context, 50); #endif } #ifdef EXTERNAL_POLL done: #endif libwebsocket_context_destroy(context); lwsl_notice("libwebsockets-test-server exited cleanly\n"); #ifndef WIN32 closelog(); #endif return 0; }
int main(int argc, char **argv) { int i; struct sigaction sa, osa; FILE *pf; int r; prog_name= strrchr(argv[0], '/'); if (prog_name == nil) prog_name= argv[0]; else prog_name++; i= 1; while (i < argc && argv[i][0] == '-') { char *opt= argv[i++] + 1; if (opt[0] == '-' && opt[1] == 0) break; /* -- */ while (*opt != 0) switch (*opt++) { case 'd': if (*opt == 0) { debug= 1; } else { debug= strtoul(opt, &opt, 10); if (*opt != 0) usage(); } break; default: usage(); } } if (i != argc) usage(); selectlog(SYSLOG); openlog(prog_name, LOG_PID, LOG_DAEMON); setlogmask(LOG_UPTO(LOG_INFO)); /* Save process id. */ if ((pf= fopen(PIDFILE, "w")) == NULL) { fprintf(stderr, "%s: %s\n", PIDFILE, strerror(errno)); exit(1); } fprintf(pf, "%d\n", getpid()); if (ferror(pf) || fclose(pf) == EOF) { fprintf(stderr, "%s: %s\n", PIDFILE, strerror(errno)); exit(1); } sigemptyset(&sa.sa_mask); sa.sa_flags= 0; sa.sa_handler= handler; /* Hangup: Reload crontab files. */ sigaction(SIGHUP, &sa, nil); /* User signal 1 & 2: Raise or reset debug level. */ sigaction(SIGUSR1, &sa, nil); sigaction(SIGUSR2, &sa, nil); /* Interrupt and Terminate: Cleanup and exit. */ if (sigaction(SIGINT, nil, &osa) == 0 && osa.sa_handler != SIG_IGN) { sigaction(SIGINT, &sa, nil); } if (sigaction(SIGTERM, nil, &osa) == 0 && osa.sa_handler != SIG_IGN) { sigaction(SIGTERM, &sa, nil); } /* Alarm: Wake up and run a job. */ sigaction(SIGALRM, &sa, nil); /* Initialize current time and time next to do something. */ time(&now); next= NEVER; /* Table load required first time. */ need_reload= 1; do { if (need_reload) { need_reload= 0; load_crontabs(); busy= 1; } /* Run jobs whose time has come. */ if (next <= now) { cronjob_t *job; if ((job= tab_nextjob()) != nil) run_job(job); busy= 1; } if (busy) { /* Did a job finish? */ r= waitpid(-1, nil, WNOHANG); busy= 0; } else { /* Sleep until the next job must be started. */ if (next == NEVER) { alarm(0); } else { #if __minix_vmd struct timeval tvnext; tvnext.tv_sec= next; tvnext.tv_usec= 0; sysutime(UTIME_SETALARM, &tvnext); #else alarm((next - now) > INT_MAX ? INT_MAX : (next - now)); #endif } if (debug >= 1) fprintf(stderr, "%s: sleep until %s", prog_name, ctime(&next)); closelog(); /* Don't keep resources open. */ /* Wait for a job to exit or a timeout. */ r= waitpid(-1, nil, 0); if (r == -1 && errno == ECHILD) pause(); alarm(0); time(&now); } if (r > 0) { /* A job has finished, reschedule it. */ if (debug >= 1) fprintf(stderr, "pid %d has exited\n", r); tab_reap_job((pid_t) r); busy= 1; } } while (!need_quit); /* Remove the pid file to signal that cron is gone. */ unlink(PIDFILE); return 0; }
externC void cyg_pppd_main(CYG_ADDRWORD arg) { int i; struct timeval timo; struct protent *protp; int connect_attempts = 0; phase = PHASE_INITIALIZE; cyg_ppp_options_install( ((struct tty *)arg)->options ); for (i = 0; (protp = protocols[i]) != NULL; ++i) (*protp->init)(0); if (!ppp_available()) { option_error(no_ppp_msg); exit(1); } /* * Initialize system-dependent stuff and magic number package. */ sys_init(); magic_init(); if (debug) setlogmask(LOG_UPTO(LOG_DEBUG)); for (;;) { need_holdoff = 1; { Cyg_ErrNo err; while ((err = cyg_io_lookup(devnam, &tty_handle)) < 0) { if (err != 0) syslog(LOG_ERR, "Failed to open %s: %d", devnam,err); } #ifdef CYGOPT_IO_SERIAL_SUPPORT_LINE_STATUS if( modem ) { cyg_uint32 len = sizeof(ppp_tty.serial_callbacks); ppp_tty.serial_callbacks.fn = cyg_ppp_serial_callback; ppp_tty.serial_callbacks.priv = (CYG_ADDRWORD)&ppp_tty; err = cyg_io_set_config( tty_handle, CYG_IO_SET_CONFIG_SERIAL_STATUS_CALLBACK, &ppp_tty.serial_callbacks, &len); if( err != 0 ) { syslog(LOG_ERR, "cyg_io_set_config(serial callbacks): %d",err); die(1); } } #endif } hungup = 0; kill_link = 0; /* set line speed, flow control, etc.; clear CLOCAL if modem option */ set_up_tty(tty_handle, 0); #ifdef CYGPKG_PPP_CHAT if( script != NULL ) { if( !cyg_ppp_chat( devnam, script ) ) { connect_attempts++; goto fail; } } #endif #ifdef CYGOPT_IO_SERIAL_SUPPORT_LINE_STATUS if( modem ) { while( !ppp_tty.carrier_detected ) cyg_thread_delay(100); } #endif connect_attempts = 0; /* we made it through ok */ /* set up the serial device as a ppp interface */ establish_ppp(tty_handle); syslog(LOG_INFO, "Using interface ppp%d", ifunit); (void) sprintf(ifname, "ppp%d", ifunit); /* * Start opening the connection and wait for * incoming events (reply, timeout, etc.). */ syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devnam); stime = time((time_t *) NULL); lcp_lowerup(0); lcp_open(0); /* Start protocol */ for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) { wait_input(timeleft(&timo)); calltimeout(); get_input(); if (kill_link) { lcp_close(0, "User request"); kill_link = 0; } if (open_ccp_flag) { if (phase == PHASE_NETWORK) { ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */ (*ccp_protent.open)(0); } open_ccp_flag = 0; } } clean_check(); disestablish_ppp(tty_handle); #ifdef CYGPKG_PPP_CHAT fail: #endif if (tty_handle != 0) close_tty(); /* limit to retries? */ if (max_con_attempts) if (connect_attempts >= max_con_attempts) break; if (!persist) die(1); #if 0 if (holdoff > 0 && need_holdoff) { phase = PHASE_HOLDOFF; TIMEOUT(holdoff_end, NULL, holdoff); do { wait_time(timeleft(&timo)); calltimeout(); if (kill_link) { if (!persist) die(0); kill_link = 0; phase = PHASE_DORMANT; /* allow signal to end holdoff */ } } while (phase == PHASE_HOLDOFF); } #endif } die(0); }
int main(int argc, char **argv) { struct libwebsocket_context *context; int opts = 0; char interface_name[128] = ""; const char *interface = NULL; int syslog_options = LOG_PID | LOG_PERROR; int listen_port = 7681; struct lws_context_creation_info info; int debug_level = 7; int daemonize = 0; memset(&info, 0, sizeof info); char c; int opt_index = 0; while ((c = getopt_long(argc, argv, "hd:k:p:i:DK:", long_opts, &opt_index)) != -1) { switch (c) { case 'D': daemonize = 1; syslog_options &= ~LOG_PERROR; break; case 'd': debug_level = atoi(optarg); break; case 'p': listen_port = atoi(optarg); break; case 'k': strncpy(keyfile,optarg,sizeof(keyfile)); keyfile[sizeof(keyfile)-1] = 0; break; case 'K': strncpy(knownhostfile,optarg,sizeof(knownhostfile)); knownhostfile[sizeof(knownhostfile)-1] = 0; break; case 'i': strncpy(interface_name, optarg, sizeof interface_name); interface_name[(sizeof interface_name) - 1] = '\0'; interface = interface_name; break; case '?': case 'h': fprintf(stderr, "Usage: %s [OPTIONS]...\n" "Websocket-speaking daemon to acquire authentication tokens\n" "from compatible websites.\n\n" " -p,--port NUM listen on port NUM. (default:%i)\n" " -d,--debug NUM set debug level to NUM.\n" " -k,--keyfile FILE specify IdentityFile for ssh.\n" " -K,--knownhosts FILE specify special ssh known_hosts file\n" " to store host keys acquired by authd\n" " (defaults to %s)\n" " -D,--daemonize run in background.\n" " --help show this message and exit.\n", argv[0],listen_port,knownhostfile); exit(1); } } /* * normally lock path would be /var/lock/lwsts or similar, to * simplify getting started without having to take care about * permissions or running as root, set to /tmp/.lwsts-lock */ if (daemonize && lws_daemonize("/tmp/.lwstecho-lock")) { fprintf(stderr, "Failed to daemonize\n"); return 1; } /* we will only try to log things according to our debug_level */ setlogmask(LOG_UPTO (LOG_DEBUG)); openlog("lwsts", syslog_options, LOG_DAEMON); /* tell the library what debug level to emit and to send it to syslog */ lws_set_log_level(debug_level, lwsl_emit_syslog); info.port = listen_port; info.iface = interface; info.protocols = protocols; #ifndef LWS_NO_EXTENSIONS info.extensions = libwebsocket_get_internal_extensions(); #endif info.gid = -1; info.uid = -1; info.options = opts; context = libwebsocket_create_context(&info); if (context == NULL) { lwsl_err("libwebsocket init failed\n"); return -1; } signal(SIGINT, sighandler); /* setup temp file: */ int fd = mkstemp(tfname); if (fd == -1) { fprintf(stderr, "Couldn't create temp file %s\n",tfname); return 1; } close(fd); /* file created. we'll use it later. */ int n = 0; while (n >= 0 && !force_exit) { /* The timeout parameter can be used to compromise between * responsiveness and CPU usage. We use 2 tenths of a second: */ n = libwebsocket_service(context, 200); } libwebsocket_context_destroy(context); unlink(tfname); /* remove temp file. */ closelog(); return 0; }
/** * Initialize flow-control context and process command-line arguments * * Sets fc->r to zero upon success, a non-zero errno code, otherwise. * * @param fc The flow control context * @param argc The number of command-line arguments * @param argv The command-line arguments * @return Upon success, zero. A non-zero errno code, otherwise. */ static void flow_init( struct flow_context *fc ) { int r; int i; struct sockaddr_in sa; socklen_t sa_len; sighandler_t old_sh; // determine the service name if ( NULL == fc->ident ) { memcpy( flow_progname, fc->argv[ 0 ], MIN( strlen( fc->argv[ 0 ] ), sizeof( flow_progname - 1 ) ) ); fc->ident = basename( flow_progname ); } // use getopt(3), create a usage(), etc // options could include verbosity #ifdef HAVE_SYSLOG // enable logging openlog( fc->ident, 0, LOG_DAEMON ); setlogmask( LOG_UPTO( LOG_INFO ) ); // could be conditional, e.g. if command-line argument exists to enable / disable debug setlogmask( setlogmask( 0 ) | LOG_MASK( LOG_DEBUG ) ); #endif // set the global variable for signal handlers _fc = fc; I( "installing signal handlers.." ); for( i = 0; i < ARRAY_SIZE( signals_to_catch ); i++ ) { old_sh = signal( signals_to_catch[ i ], sighandler ); if ( SIG_ERR == old_sh ) { r = errno; E( "signal(2) failed" ); goto out; } } I( "opening signal pipe.." ); r = pipe( fc->signal_fd ); if ( EXIT_SUCCESS != r ) { r = errno; E( "pipe(2) failed" ); goto out; } D( "opened signal pipe as fd's %d, %d", fc->signal_fd[ 0 ], fc->signal_fd[ 1 ] ); cas( & fc->highest_fd, fc->signal_fd[ 0 ] ); I( "opening server socket.." ); r = socket( AF_INET, SOCK_DGRAM, 0 ); if ( -1 == r ) { r = errno; E( "socket(2) failed" ); goto out; } fc->server_socket = r; D( "opened server socket as fd %d", fc->server_socket ); I( "binding server socket.." ); sa.sin_family = AF_INET; sa.sin_port = htons( fc->server_port ); sa.sin_addr.s_addr = htonl( INADDR_ANY ); sa_len = sizeof( sa ); r = bind( fc->server_socket, (struct sockaddr *) & sa, sa_len ); if ( -1 == r ) { r = errno; E( "bind(2) failed" ); goto out; } D( "bound server socket to port %d", fc->server_port ); cas( & fc->highest_fd, fc->server_socket ); out: fc->r = r; }
int main(int argc, char **argv){ running = true; pthread_mutex_init(&runlock, NULL); pthread_cond_init(&runcond, NULL); const char *www_root = "/www"; const char *listen_socket = "ws://127.0.0.1:5303"; const char *plugin_dir = "/usr/lib/orange/api/"; const char *pw_file = "/etc/orange/shadow"; const char *acl_dir = ""; int num_workers = 10; printf("Orange RPCD v%s\n",VERSION); printf("Lua/JSONRPC server\n"); printf("Copyright (c) 2016 Martin Schröder <*****@*****.**>\n"); setlogmask(LOG_UPTO(LOG_INFO)); openlog("orangerpcd", LOG_CONS | LOG_PID | LOG_NDELAY, LOG_LOCAL1); int c = 0; while((c = getopt(argc, argv, "d:l:p:vx:a:w:")) != -1){ switch(c){ case 'd': www_root = optarg; break; case 'a': acl_dir = optarg; break; case 'l': listen_socket = optarg; break; case 'p': plugin_dir = optarg; break; case 'v': orange_debug_level++; break; case 'x': pw_file = optarg; break; case 'w': num_workers = abs(atoi(optarg)); if(num_workers > 100) printf("WARNING: using more than 100 workers may not make sense!\n"); break; default: break; } } #if !defined(CONFIG_THREADS) num_workers = 0; printf("Note: threading is disabled!\n"); #else printf("Threading is enabled! Running with %d workers.\n", num_workers); #endif orange_server_t server = orange_ws_server_new(www_root); if(orange_server_listen(server, listen_socket) < 0){ fprintf(stderr, "server could not listen on specified socket!\n"); return -1; } signal(SIGINT, handle_sigint); signal(SIGUSR1, handle_sigint); struct orange *app = orange_new(plugin_dir, pw_file, acl_dir); struct orange_rpc rpc; orange_rpc_init(&rpc, server, app, 5000000UL, num_workers); syslog(LOG_INFO, "orangerpcd jsonrpc server started (%d)", getpid()); #if CONFIG_THREADS // wait for abort pthread_mutex_lock(&runlock); pthread_cond_wait(&runcond, &runlock); pthread_mutex_unlock(&runlock); #else while(running){ orange_rpc_process_requests(&rpc); } #endif DEBUG("cleaning up\n"); orange_rpc_deinit(&rpc); orange_server_delete(server); orange_delete(&app); syslog(LOG_INFO, "orangerpcd jsonrpc server exiting (%d)", getpid()); pthread_mutex_destroy(&runlock); pthread_cond_destroy(&runcond); closelog(); return 0; }
int main(int argc, char **argv) { int n = 0; int port = 7681; int use_ssl = 0; struct libwebsocket_context *context; int opts = 0; char interface_name[128] = ""; const char *interface = NULL; char ssl_cert[256] = LOCAL_RESOURCE_PATH"/libwebsockets-test-server.pem"; char ssl_key[256] = LOCAL_RESOURCE_PATH"/libwebsockets-test-server.key.pem"; #ifndef WIN32 int syslog_options = LOG_PID | LOG_PERROR; #endif int client = 0; int listen_port = 80; struct lws_context_creation_info info; char passphrase[256]; char uri[256] = "/"; #ifndef LWS_NO_CLIENT char address[256], ads_port[256 + 30]; int rate_us = 250000; unsigned int oldus = 0; struct libwebsocket *wsi; int disallow_selfsigned = 0; #endif int debug_level = 7; #ifndef LWS_NO_DAEMONIZE int daemonize = 0; #endif memset(&info, 0, sizeof info); #ifndef LWS_NO_CLIENT lwsl_notice("Built to support client operations\n"); #endif #ifndef LWS_NO_SERVER lwsl_notice("Built to support server operations\n"); #endif while (n >= 0) { n = getopt_long(argc, argv, "i:hsp:d:DC:k:P:vu:" #ifndef LWS_NO_CLIENT "c:r:" #endif , options, NULL); if (n < 0) continue; switch (n) { case 'P': strncpy(passphrase, optarg, sizeof(passphrase)); passphrase[sizeof(passphrase) - 1] = '\0'; info.ssl_private_key_password = passphrase; break; case 'C': strncpy(ssl_cert, optarg, sizeof(ssl_cert)); ssl_cert[sizeof(ssl_cert) - 1] = '\0'; disallow_selfsigned = 1; break; case 'k': strncpy(ssl_key, optarg, sizeof(ssl_key)); ssl_key[sizeof(ssl_key) - 1] = '\0'; break; case 'u': strncpy(uri, optarg, sizeof(uri)); uri[sizeof(uri) - 1] = '\0'; break; #ifndef LWS_NO_DAEMONIZE case 'D': daemonize = 1; #ifndef WIN32 syslog_options &= ~LOG_PERROR; #endif break; #endif #ifndef LWS_NO_CLIENT case 'c': client = 1; strncpy(address, optarg, sizeof(address) - 1); address[sizeof(address) - 1] = '\0'; port = 80; break; case 'r': rate_us = atoi(optarg) * 1000; break; #endif case 'd': debug_level = atoi(optarg); break; case 's': use_ssl = 1; /* 1 = take care about cert verification, 2 = allow anything */ break; case 'p': port = atoi(optarg); break; case 'v': versa = 1; break; case 'i': strncpy(interface_name, optarg, sizeof interface_name); interface_name[(sizeof interface_name) - 1] = '\0'; interface = interface_name; break; case '?': case 'h': fprintf(stderr, "Usage: libwebsockets-test-echo\n" " --debug / -d <debug bitfield>\n" " --port / -p <port>\n" " --ssl-cert / -C <cert path>\n" " --ssl-key / -k <key path>\n" #ifndef LWS_NO_CLIENT " --client / -c <server IP>\n" " --ratems / -r <rate in ms>\n" #endif " --ssl / -s\n" " --passphrase / -P <passphrase>\n" " --interface / -i <interface>\n" #ifndef LWS_NO_DAEMONIZE " --daemonize / -D\n" #endif ); exit(1); } } #ifndef LWS_NO_DAEMONIZE /* * normally lock path would be /var/lock/lwsts or similar, to * simplify getting started without having to take care about * permissions or running as root, set to /tmp/.lwsts-lock */ #if defined(WIN32) || defined(_WIN32) #else if (!client && daemonize && lws_daemonize("/tmp/.lwstecho-lock")) { fprintf(stderr, "Failed to daemonize\n"); return 1; } #endif #endif #ifdef WIN32 #else /* we will only try to log things according to our debug_level */ setlogmask(LOG_UPTO (LOG_DEBUG)); openlog("lwsts", syslog_options, LOG_DAEMON); /* tell the library what debug level to emit and to send it to syslog */ lws_set_log_level(debug_level, lwsl_emit_syslog); #endif lwsl_notice("libwebsockets echo test - " "(C) Copyright 2010-2015 Andy Green <*****@*****.**> - " "licensed under LGPL2.1\n"); #ifndef LWS_NO_CLIENT if (client) { lwsl_notice("Running in client mode\n"); listen_port = CONTEXT_PORT_NO_LISTEN; if (use_ssl && !disallow_selfsigned) { lwsl_info("allowing selfsigned\n"); use_ssl = 2; } else { lwsl_info("requiring server cert validation againts %s\n", ssl_cert); info.ssl_ca_filepath = ssl_cert; } } else { #endif #ifndef LWS_NO_SERVER lwsl_notice("Running in server mode\n"); listen_port = port; #endif #ifndef LWS_NO_CLIENT } #endif info.port = listen_port; info.iface = interface; info.protocols = protocols; #ifndef LWS_NO_EXTENSIONS info.extensions = libwebsocket_get_internal_extensions(); #endif if (use_ssl && !client) { info.ssl_cert_filepath = ssl_cert; info.ssl_private_key_filepath = ssl_key; } else if (use_ssl && client) { info.ssl_cert_filepath = NULL; info.ssl_private_key_filepath = NULL; } info.gid = -1; info.uid = -1; info.options = opts; context = libwebsocket_create_context(&info); if (context == NULL) { lwsl_err("libwebsocket init failed\n"); return -1; } signal(SIGINT, sighandler); n = 0; while (n >= 0 && !force_exit) { #ifndef LWS_NO_CLIENT struct timeval tv; if (client && !state) { state = 1; lwsl_notice("Client connecting to %s:%u....\n", address, port); /* we are in client mode */ address[sizeof(address) - 1] = '\0'; sprintf(ads_port, "%s:%u\n", address, port & 65535); wsi = libwebsocket_client_connect(context, address, port, use_ssl, uri, ads_port, "origin", NULL, -1); if (!wsi) { lwsl_err("Client failed to connect to %s:%u\n", address, port); goto bail; } } if (client && !versa) { gettimeofday(&tv, NULL); if (((unsigned int)tv.tv_usec - oldus) > (unsigned int)rate_us) { libwebsocket_callback_on_writable_all_protocol(&protocols[0]); oldus = tv.tv_usec; } } #endif n = libwebsocket_service(context, 10); } #ifndef LWS_NO_CLIENT bail: #endif libwebsocket_context_destroy(context); lwsl_notice("libwebsockets-test-echo exited cleanly\n"); #ifdef WIN32 #else closelog(); #endif return 0; }
extern int pam_sm_setcred(pam_handle_t * pamh, int flags, int argc, const char **argv) { int retcode = PAM_SUCCESS; int errcode = PAM_SUCCESS; int origmask; int logmask = LOG_UPTO(LOG_INFO); int nowarn = 0; int use_first_pass = 1; /* use the password passed in by auth */ int try_first_pass = 0; int ignore_uid = 0; uid_t ignore_uid_id = 0; int refresh_token = 0; int set_expires = 0; /* the default is to not to set the env variable */ int use_klog = 0; int i; PAM_CONST struct pam_conv *pam_convp = NULL; char my_password_buf[256]; char *cell_ptr = NULL; char sbuffer[100]; char *torch_password = NULL; int auth_ok = 0; PAM_CONST char *user = NULL; const char *password = NULL; int password_expires = -1; char *reason = NULL; struct passwd *upwd = NULL; #if !(defined(AFS_LINUX20_ENV) || defined(AFS_FBSD_ENV) || defined(AFS_DFBSD_ENV) || defined(AFS_NBSD_ENV)) char upwd_buf[2048]; /* size is a guess. */ struct passwd unix_pwd; #endif #ifndef AFS_SUN5_ENV openlog(pam_afs_ident, LOG_CONS, LOG_AUTH); #endif origmask = setlogmask(logmask); /* * Parse the user options. Log an error for any unknown options. */ for (i = 0; i < argc; i++) { if (strcasecmp(argv[i], "debug") == 0) { logmask |= LOG_MASK(LOG_DEBUG); (void)setlogmask(logmask); } else if (strcasecmp(argv[i], "nowarn") == 0) { nowarn = 1; } else if (strcasecmp(argv[i], "use_first_pass") == 0) { use_first_pass = 1; /* practically redundant */ } else if (strcasecmp(argv[i], "try_first_pass") == 0) { try_first_pass = 1; } else if (strcasecmp(argv[i], "ignore_root") == 0) { ignore_uid = 1; ignore_uid_id = 0; } else if (strcasecmp(argv[i], "ignore_uid") == 0) { i++; if (i == argc) { pam_afs_syslog(LOG_ERR, PAMAFS_IGNOREUID, "ignore_uid missing argument"); ignore_uid = 0; } else { ignore_uid = 1; ignore_uid_id = (uid_t) strtol(argv[i], (char **)NULL, 10); if (ignore_uid_id > IGNORE_MAX) { ignore_uid = 0; pam_afs_syslog(LOG_ERR, PAMAFS_IGNOREUID, argv[i]); } } } else if (strcasecmp(argv[i], "cell") == 0) { i++; if (i == argc) { pam_afs_syslog(LOG_ERR, PAMAFS_OTHERCELL, "cell missing argument"); } else { cell_ptr = (char *)argv[i]; pam_afs_syslog(LOG_INFO, PAMAFS_OTHERCELL, cell_ptr); } } else if (strcasecmp(argv[i], "no_unlog") == 0) { ; } else if (strcasecmp(argv[i], "refresh_token") == 0) { refresh_token = 1; } else if (strcasecmp(argv[i], "set_token") == 0) { ; } else if (strcasecmp(argv[i], "dont_fork") == 0) { ; } else if (strcasecmp(argv[i], "use_klog") == 0) { use_klog = 1; } else if (strcasecmp(argv[i], "setenv_password_expires") == 0) { set_expires = 1; } else { pam_afs_syslog(LOG_ERR, PAMAFS_UNKNOWNOPT, argv[i]); } } if (use_first_pass) try_first_pass = 0; if (logmask & LOG_MASK(LOG_DEBUG)) pam_afs_syslog(LOG_DEBUG, PAMAFS_OPTIONS, nowarn, use_first_pass, try_first_pass, ignore_uid, ignore_uid_id, 8, 8, 8, 8); /* Try to get the user-interaction info, if available. */ errcode = pam_get_item(pamh, PAM_CONV, (PAM_CONST void **)&pam_convp); if (errcode != PAM_SUCCESS) { if (logmask & LOG_MASK(LOG_DEBUG)) pam_afs_syslog(LOG_DEBUG, PAMAFS_NO_USER_INT); pam_convp = NULL; } /* Who are we trying to authenticate here? */ if ((errcode = pam_get_user(pamh, (PAM_CONST char **)&user, "AFS username:"******"local" (or via nss, possibly nss_dce) pwent, * and its uid==0, and "ignore_root" was given in pam.conf, * ignore the user. */ /* enhanced: use "ignore_uid <number>" to specify the largest uid * which should be ignored by this module */ #if defined(AFS_HPUX_ENV) || defined(AFS_DARWIN100_ENV) || defined(AFS_SUN5_ENV) #if defined(AFS_HPUX110_ENV) || defined(AFS_DARWIN100_ENV) || defined(AFS_SUN5_ENV) i = getpwnam_r(user, &unix_pwd, upwd_buf, sizeof(upwd_buf), &upwd); #else /* AFS_HPUX110_ENV */ i = getpwnam_r(user, &unix_pwd, upwd_buf, sizeof(upwd_buf)); if (i == 0) /* getpwnam_r success */ upwd = &unix_pwd; #endif /* AFS_HPUX110_ENV */ if (ignore_uid && i == 0 && upwd && upwd->pw_uid <= ignore_uid_id) { pam_afs_syslog(LOG_INFO, PAMAFS_IGNORINGROOT, user); RET(PAM_AUTH_ERR); } #else #if defined(AFS_LINUX20_ENV) || defined(AFS_FBSD_ENV) || defined(AFS_DFBSD_ENV) || defined(AFS_NBSD_ENV) upwd = getpwnam(user); #else upwd = getpwnam_r(user, &unix_pwd, upwd_buf, sizeof(upwd_buf)); #endif if (ignore_uid && upwd != NULL && upwd->pw_uid <= ignore_uid_id) { pam_afs_syslog(LOG_INFO, PAMAFS_IGNORINGROOT, user); RET(PAM_AUTH_ERR); } #endif if (flags & PAM_DELETE_CRED) { if (logmask & LOG_MASK(LOG_DEBUG)) pam_afs_syslog(LOG_DEBUG, PAMAFS_DELCRED, user); RET(PAM_SUCCESS); } else if (flags & PAM_REINITIALIZE_CRED) { if (logmask & LOG_MASK(LOG_DEBUG)) pam_afs_syslog(LOG_DEBUG, PAMAFS_REINITCRED, user); RET(PAM_SUCCESS); } else { /* flags are PAM_REFRESH_CRED, PAM_ESTABLISH_CRED, unknown */ if (logmask & LOG_MASK(LOG_DEBUG)) pam_afs_syslog(LOG_DEBUG, PAMAFS_ESTABCRED, user); errcode = pam_get_data(pamh, pam_afs_lh, (const void **)&password); if (errcode != PAM_SUCCESS || password == NULL) { if (use_first_pass) { pam_afs_syslog(LOG_ERR, PAMAFS_PASSWD_REQ, user); RET(PAM_AUTH_ERR); } password = NULL; /* In case it isn't already NULL */ if (logmask & LOG_MASK(LOG_DEBUG)) pam_afs_syslog(LOG_DEBUG, PAMAFS_NOFIRSTPASS, user); } else if (password[0] == '\0') { /* Actually we *did* get one but it was empty. */ /* So don't use it. */ password = NULL; if (use_first_pass) { pam_afs_syslog(LOG_ERR, PAMAFS_PASSWD_REQ, user); RET(PAM_NEW_AUTHTOK_REQD); } if (logmask & LOG_MASK(LOG_DEBUG)) pam_afs_syslog(LOG_DEBUG, PAMAFS_NILPASSWORD, user); } else { if (logmask & LOG_MASK(LOG_DEBUG)) pam_afs_syslog(LOG_DEBUG, PAMAFS_GOTPASS, user); } if (!(use_first_pass || try_first_pass)) { password = NULL; } try_auth: if (password == NULL) { char *prompt_password; if (use_first_pass) RET(PAM_AUTH_ERR); /* shouldn't happen */ if (try_first_pass) try_first_pass = 0; /* we come back if try_first_pass==1 below */ if (pam_convp == NULL || pam_convp->conv == NULL) { pam_afs_syslog(LOG_ERR, PAMAFS_CANNOT_PROMPT); RET(PAM_AUTH_ERR); } errcode = pam_afs_prompt(pam_convp, &prompt_password, 0, PAMAFS_PWD_PROMPT); if (errcode != PAM_SUCCESS || prompt_password == NULL) { pam_afs_syslog(LOG_ERR, PAMAFS_GETPASS_FAILED); RET(PAM_AUTH_ERR); } if (prompt_password[0] == '\0') { if (logmask & LOG_MASK(LOG_DEBUG)) pam_afs_syslog(LOG_DEBUG, PAMAFS_NILPASSWORD); RET(PAM_NEW_AUTHTOK_REQD); } /* * We aren't going to free the password later (we will wipe it, * though), because the storage for it if we get it from other * paths may belong to someone else. Since we do need to free * this storage, copy it to a buffer that won't need to be freed * later, and free this storage now. */ strncpy(my_password_buf, prompt_password, sizeof(my_password_buf)); my_password_buf[sizeof(my_password_buf) - 1] = '\0'; memset(prompt_password, 0, strlen(prompt_password)); free(prompt_password); password = torch_password = my_password_buf; } /* * We only set a PAG here, if we haven't got one before in * pam_sm_authenticate() or if it was destroyed by the application */ if ((!refresh_token) && (getPAG() == -1)) { if (logmask & LOG_MASK(LOG_DEBUG)) syslog(LOG_DEBUG, "New PAG created in pam_setcred()"); setpag(); #ifdef AFS_KERBEROS_ENV ktc_newpag(); #endif } if (flags & PAM_REFRESH_CRED) { if (use_klog) { auth_ok = !do_klog(user, password, "00:00:01", cell_ptr); ktc_ForgetAllTokens(); } else { if (ka_VerifyUserPassword(KA_USERAUTH_VERSION, (char *)user, /* kerberos name */ NULL, /* instance */ cell_ptr, /* realm */ (char*)password, /* password */ 0, /* spare 2 */ &reason /* error string */ )) { pam_afs_syslog(LOG_ERR, PAMAFS_LOGIN_FAILED, user, reason); } else { auth_ok = 1; } } } if (flags & PAM_ESTABLISH_CRED) { if (use_klog) auth_ok = !do_klog(user, password, NULL, cell_ptr); else { if (ka_UserAuthenticateGeneral(KA_USERAUTH_VERSION, (char *)user, /* kerberos name */ NULL, /* instance */ cell_ptr, /* realm */ (char*)password, /* password */ 0, /* default lifetime */ &password_expires, 0, /* spare 2 */ &reason /* error string */ )) { pam_afs_syslog(LOG_ERR, PAMAFS_LOGIN_FAILED, user, reason); } else { auth_ok = 1; } } } if (!auth_ok && try_first_pass) { password = NULL; goto try_auth; } /* pam_sm_authenticate should have set this * if (auth_ok && !got_authtok) { * torch_password = NULL; * (void) pam_set_item(pamh, PAM_AUTHTOK, password); * } */ if (auth_ok) { if (set_expires && !use_klog && (password_expires >= 0)) { strcpy(sbuffer, "PASSWORD_EXPIRES="); strcat(sbuffer, cv2string(&sbuffer[100], password_expires)); errcode = pam_putenv(pamh, sbuffer); if (errcode != PAM_SUCCESS) pam_afs_syslog(LOG_ERR, PAMAFS_PASSEXPFAIL, user); } #if defined(AFS_KERBEROS_ENV) if (upwd) { if (chown(ktc_tkt_string(), upwd->pw_uid, upwd->pw_gid) < 0) pam_afs_syslog(LOG_ERR, PAMAFS_CHOWNKRB, user); sprintf(sbuffer, "KRBTKFILE=%s", ktc_tkt_string()); errcode = pam_putenv(pamh, sbuffer); if (errcode != PAM_SUCCESS) pam_afs_syslog(LOG_ERR, PAMAFS_KRBFAIL, user); } #endif RET(PAM_SUCCESS); } else { RET(PAM_CRED_ERR); } } out: if (password && torch_password) memset(torch_password, 0, strlen(torch_password)); (void)setlogmask(origmask); #ifndef AFS_SUN5_ENV closelog(); #endif return retcode; }
int main (int argc, char *argv[]) { (void)argc; (void)argv; int ret; int dbg = TRUE; struct lapb_callbacks lapb_callbacks; int res; char buffer[2048]; _uchar lapb_equipment_type = LAPB_DCE; _uchar lapb_modulo = LAPB_STANDARD; pthread_t server_thread; struct tcp_server_struct * server_thread_struct = NULL; pthread_t timer_thread; struct timer_thread_struct * timer_thread_struct = NULL; pthread_t logger_thread; printf("*******************************************\n"); printf("****** ******\n"); printf("****** X25 EMULATOR (server side) ******\n"); printf("****** ******\n"); printf("*******************************************\n"); /* Initialize syslog */ setlogmask (LOG_UPTO (LOG_DEBUG)); openlog ("server_app", LOG_CONS | LOG_PID | LOG_NDELAY, LOG_LOCAL1); ret = pthread_create(&logger_thread, NULL, logger_function, NULL); if (ret) { perror("Error - pthread_create()"); closelog(); exit(EXIT_FAILURE); }; printf("Logger thread created(code %d)\n", ret); while (!is_logger_started()) sleep_ms(200); printf("Logger started\n\n"); lapb_debug(0, "Program started by User %d", getuid ()); /* Setup signal handler */ setup_signals_handler(); if (dbg) goto label_1; /* Select program mode */ printf("\nSelect program mode:\n1. Automatic\n2. Manual\n"); write(0, ">", 1); while (read(0, buffer, sizeof(buffer)) <= 1) write(0, ">", 1); if (atoi(buffer) == 2) AutomaticMode = FALSE; else { /* Set up equipment mode: DTE or DCE */ printf("\nSelect equipment type:\n1. DTE\n2. DCE\n"); write(0, ">", 1); while (read(0, buffer, sizeof(buffer)) <= 1) write(0, ">", 1); if (atoi(buffer) == 1) lapb_equipment_type = LAPB_DTE; /* Set up lapb modulo: STANDARD or EXTENDED */ printf("\nSelect modulo value:\n1. STANDARD(8)\n2. EXTENDED(128)\n"); write(0, ">", 1); while (read(0, buffer, sizeof(buffer)) <= 1) write(0, ">", 1); if (atoi(buffer) == 2) lapb_modulo = LAPB_EXTENDED; }; label_1: /* Create TCP server */ server_thread_struct = malloc(sizeof(struct tcp_server_struct)); if (dbg) { server_thread_struct->port = 1234; goto label_2; }; printf("\nEnter server port[1234]: "); fgets(buffer, sizeof(buffer) - 1, stdin); int tmp_len = strlen(buffer); if (tmp_len == 1) server_thread_struct->port = 1234; else { buffer[strlen(buffer) - 1] = 0; server_thread_struct->port = atoi(buffer); }; label_2: /* TCP server callbacks */ server_thread_struct->new_data_received = new_data_received; server_thread_struct->no_active_connection = no_active_connection; ret = pthread_create(&server_thread, NULL, server_function, (void*)server_thread_struct); if (ret) { fprintf(stderr, "Error - pthread_create() return code: %d\n", ret); exit(EXIT_FAILURE); }; printf("TCP server thread created(code %d)\n", ret); while (!is_server_started()) sleep_ms(200); printf("TCP server started\n\n"); // if (!AutomaticMode) // return manual_process(); /* Create timer */ timer_thread_struct = malloc(sizeof(struct timer_thread_struct)); timer_thread_struct->interval = 10; /* milliseconds */ timer_thread_struct->main_lock = main_lock; timer_thread_struct->main_unlock = main_unlock; ret = pthread_create(&timer_thread, NULL, timer_thread_function, (void*)timer_thread_struct); if (ret) { lapb_debug(0, "Error - pthread_create() return code: %d\n", ret); closelog(); exit(EXIT_FAILURE); }; printf("Timer thread created(code %d)\n", ret); while (!is_timer_thread_started()) sleep_ms(200); printf("Timer started\n\n"); /* LAPB init */ bzero(&lapb_callbacks, sizeof(struct lapb_callbacks)); lapb_callbacks.connect_confirmation = lapb_connect_confirmation_cb; lapb_callbacks.connect_indication = lapb_connect_indication_cb; lapb_callbacks.disconnect_confirmation = lapb_disconnect_confirmation_cb; lapb_callbacks.disconnect_indication = lapb_disconnect_indication_cb; lapb_callbacks.data_indication = lapb_data_indication_cb; lapb_callbacks.transmit_data = lapb_transmit_data; lapb_callbacks.add_timer = timer_add; lapb_callbacks.del_timer = timer_del; lapb_callbacks.start_timer = timer_start; lapb_callbacks.stop_timer = timer_stop; lapb_callbacks.debug = lapb_debug; /* Define LAPB values */ struct lapb_params lapb_params; lapb_params.mode = lapb_modulo | LAPB_SLP | lapb_equipment_type; lapb_params.window = LAPB_DEFAULT_SWINDOW; lapb_params.N1 = LAPB_DEFAULT_N1; /* I frame size is 135 bytes */ lapb_params.T201_interval = 1000; /* 1s */ lapb_params.T202_interval = 100; /* 0.1s */ lapb_params.N201 = 10; /* T201 timer will repeat for 10 times */ lapb_params.low_order_bits = FALSE; lapb_params.auto_connecting = TRUE; res = lapb_register(&lapb_callbacks, &lapb_params, &lapb_server); if (res != LAPB_OK) { printf("lapb_register return %d\n", res); exit(EXIT_FAILURE); }; /* X25 init */ struct x25_callbacks x25_callbacks; bzero(&x25_callbacks, sizeof(struct x25_callbacks)); x25_callbacks.link_connect_request = lapb_connect_request; x25_callbacks.link_disconnect_request = lapb_disconnect_request; x25_callbacks.link_send_frame = lapb_data_request; x25_callbacks.call_indication = x25_call_indication_cb; x25_callbacks.call_accepted = x25_call_accepted_cb; x25_callbacks.data_indication = x25_data_indication_cb; x25_callbacks.add_timer = timer_add; x25_callbacks.del_timer = timer_del; x25_callbacks.start_timer = timer_start; x25_callbacks.stop_timer = timer_stop; x25_callbacks.debug = x25_debug; /* Define X25 values */ //struct x25_params x25_params; //res = x25_register(&x25_callbacks, &x25_params, &x25_server); res = x25_register(&x25_callbacks, NULL, &x25_server); if (res != X25_OK) { printf("x25_register return %d\n", res); goto exit; }; x25_server->mode = (lapb_equipment_type & LAPB_DCE ? X25_DCE : X25_DTE) | (lapb_modulo & LAPB_EXTENDED ? X25_EXTENDED : X25_STANDARD); x25_add_link(x25_server, lapb_server); lapb_server->L3_ptr = x25_server; printf("Enter local X25 address[7654321]: "); fgets(x25_server->source_addr.x25_addr, 16, stdin); tmp_len = strlen(x25_server->source_addr.x25_addr); if (tmp_len == 1) sprintf(x25_server->source_addr.x25_addr, "7654321"); else x25_server->source_addr.x25_addr[tmp_len - 1] = 0; struct x25_address dest_addr; sprintf(dest_addr.x25_addr, "1234567"); x25_server->lci = 128; x25_debug(0, "[X25]"); x25_debug(0, "[X25]"); x25_debug(0, "[X25]"); /* Start endless loop */ printf("Run Main loop\n\n"); main_loop(x25_server, &dest_addr); printf("Main loop ended\n"); exit: terminate_tcp_server(); while (is_server_started()) sleep_ms(200); printf("TCP server stopped\n"); int * thread_result; pthread_join(server_thread, (void **)&thread_result); printf("TCP server thread exit(code %d)\n", *thread_result); free(thread_result); if (server_thread_struct != NULL) free(server_thread_struct); terminate_timer_thread(); while (is_timer_thread_started()) sleep_ms(200); printf("Timer stopped\n"); pthread_join(timer_thread, (void **)&thread_result); printf("Timer thread exit(code %d)\n", *thread_result); free(thread_result); if (timer_thread_struct != NULL) free(timer_thread_struct); lapb_unregister(lapb_server); terminate_logger(); while (is_logger_started()) sleep_ms(200); printf("Logger stopped\n"); pthread_join(logger_thread, (void **)&thread_result); printf("Logger thread exit(code %d)\n", *thread_result); free(thread_result); /* Close syslog */ closelog(); printf("Exit application\n\n"); return EXIT_SUCCESS; }
int main(int argc, char *argv[]) { #ifdef DEBUG int daemonize = 0; #else int daemonize = 1; #endif int c; pid_t pid, sid; CURLcode cr = CURLE_WRITE_ERROR; /* Check if this is the best initialization */ time_t delay = 0; signal(SIGHUP, signal_handler); signal(SIGTERM, signal_handler); signal(SIGINT, signal_handler); signal(SIGQUIT, signal_handler); while ((c = getopt(argc, argv, "nh|help")) != -1) { switch (c) { case 'h': PrintUsage (argc, argv); exit (EXIT_SUCCESS); break; case 'n': daemonize = 0; break; default: PrintUsage (argc, argv); exit (EXIT_SUCCESS); break; } } #ifdef DEBUG setlogmask (LOG_UPTO (LOG_DEBUG)); openlog (DAEMON_NAME, LOG_CONS | LOG_NDELAY | LOG_PERROR | LOG_PID, LOG_USER); #else setlogmask (LOG_UPTO (LOG_INFO)); openlog (DAEMON_NAME, LOG_CONS, LOG_USER); #endif /* daemon stuff */ if (daemonize) { syslog (P_INF, "%s daemon starting up", DAEMON_NAME); if ((pid = fork ()) < 0) { syslog (P_ERR, "Could not fork child process: %m"); exit (EXIT_FAILURE); } else if (pid > 0) { syslog (P_NTC, "Child process successfully forked"); exit (EXIT_SUCCESS); } umask(0); sid = setsid(); if (sid < 0) { syslog (P_ERR, "Could not create new session: %m"); exit (EXIT_FAILURE); } if ((chdir ("/")) < 0) { syslog (P_ERR, "Could not change working dir: %m"); exit (EXIT_FAILURE); } close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); } while ((cr == CURLE_WRITE_ERROR) || (cr == CURLE_OK) || (cr == CURLE_HTTP_RETURNED_ERROR)) { time_t uptime = 0, last_tcp_error = time(NULL); cr = curl_connect(); if ((uptime = (time(NULL) - last_tcp_error)) > 240) { syslog(P_INF, "UP for more than 4 minutes, resetting delay"); delay = 0; } if (cr == CURLE_HTTP_RETURNED_ERROR) { if (delay < 10) delay = 10; else delay *= 2; if (delay > 240) delay = 240; syslog(P_INF, "HTTP error - sleeping for %ld seconds", delay); sleep(delay); } else { if (delay < 1) delay = 1; else delay += 1; if (delay > 16) delay = 16; syslog(P_INF, "Connection error (%d) - sleeping for %ld seconds", cr, delay); sleep(delay); } } syslog (P_INF, "CURL ERROR: %d\n", cr); syslog (P_INF, "%s shutting down", DAEMON_NAME); exit (EXIT_SUCCESS); }
int main(int argc, char **argv) { int sigs[] = { SIGINT, SIGKILL, SIGTERM, SIGSEGV, SIGFPE }; struct ev_signal signals[ARRAY_SIZE(sigs)]; struct ev_loop *loop = ev_default_loop(0); struct lws_context_creation_info info; char interface_name[128] = ""; const char *iface = NULL; ev_timer timeout_watcher; char cert_path[1024]; char key_path[1024]; int use_ssl = 0; int opts = 0; int n = 0; #ifndef _WIN32 int syslog_options = LOG_PID | LOG_PERROR; #endif #ifndef LWS_NO_DAEMONIZE int daemonize = 0; #endif /* * take care to zero down the info struct, he contains random garbaage * from the stack otherwise */ memset(&info, 0, sizeof info); info.port = 7681; while (n >= 0) { n = getopt_long(argc, argv, "eci:hsap:d:Dr:", options, NULL); if (n < 0) continue; switch (n) { case 'e': opts |= LWS_SERVER_OPTION_LIBEV; break; #ifndef LWS_NO_DAEMONIZE case 'D': daemonize = 1; #ifndef _WIN32 syslog_options &= ~LOG_PERROR; #endif break; #endif case 'd': debug_level = atoi(optarg); break; case 's': use_ssl = 1; break; case 'a': opts |= LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT; break; case 'p': info.port = atoi(optarg); break; case 'i': strncpy(interface_name, optarg, sizeof interface_name); interface_name[(sizeof interface_name) - 1] = '\0'; iface = interface_name; break; case 'c': close_testing = 1; fprintf(stderr, " Close testing mode -- closes on " "client after 50 dumb increments" "and suppresses lws_mirror spam\n"); break; case 'r': resource_path = optarg; printf("Setting resource path to \"%s\"\n", resource_path); break; case 'h': fprintf(stderr, "Usage: test-server " "[--port=<p>] [--ssl] " "[-d <log bitfield>] " "[--resource_path <path>]\n"); exit(1); } } #if !defined(LWS_NO_DAEMONIZE) && !defined(WIN32) /* * normally lock path would be /var/lock/lwsts or similar, to * simplify getting started without having to take care about * permissions or running as root, set to /tmp/.lwsts-lock */ if (daemonize && lws_daemonize("/tmp/.lwsts-lock")) { fprintf(stderr, "Failed to daemonize\n"); return 1; } #endif for (n = 0; n < ARRAY_SIZE(sigs); n++) { _ev_init(&signals[n], signal_cb); ev_signal_set(&signals[n], sigs[n]); ev_signal_start(loop, &signals[n]); } #ifndef _WIN32 /* we will only try to log things according to our debug_level */ setlogmask(LOG_UPTO (LOG_DEBUG)); openlog("lwsts", syslog_options, LOG_DAEMON); #endif /* tell the library what debug level to emit and to send it to syslog */ lws_set_log_level(debug_level, lwsl_emit_syslog); lwsl_notice("libwebsockets test server libev - license LGPL2.1+SLE\n"); lwsl_notice("(C) Copyright 2010-2016 Andy Green <*****@*****.**>\n"); printf("Using resource path \"%s\"\n", resource_path); info.iface = iface; info.protocols = protocols; info.extensions = exts; info.ssl_cert_filepath = NULL; info.ssl_private_key_filepath = NULL; if (use_ssl) { if (strlen(resource_path) > sizeof(cert_path) - 32) { lwsl_err("resource path too long\n"); return -1; } sprintf(cert_path, "%s/libwebsockets-test-server.pem", resource_path); if (strlen(resource_path) > sizeof(key_path) - 32) { lwsl_err("resource path too long\n"); return -1; } sprintf(key_path, "%s/libwebsockets-test-server.key.pem", resource_path); info.ssl_cert_filepath = cert_path; info.ssl_private_key_filepath = key_path; opts |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT; } info.gid = -1; info.uid = -1; info.max_http_header_pool = 1; info.options = opts | LWS_SERVER_OPTION_LIBEV; context = lws_create_context(&info); if (context == NULL) { lwsl_err("libwebsocket init failed\n"); return -1; } /* * this shows how to override the lws file operations. You don't need * to do any of this unless you have a reason (eg, want to serve * compressed files without decompressing the whole archive) */ /* stash original platform fops */ fops_plat = *(lws_get_fops(context)); /* override the active fops */ lws_get_fops(context)->open = test_server_fops_open; lws_ev_initloop(context, loop, 0); _ev_timer_init(&timeout_watcher, ev_timeout_cb, 0.05, 0.05); ev_timer_start(loop, &timeout_watcher); ev_run(loop, 0); lws_context_destroy(context); lwsl_notice("libwebsockets-test-server exited cleanly\n"); #ifndef _WIN32 closelog(); #endif return 0; }
void openSyslog() { setlogmask(LOG_UPTO (LOG_INFO)); openlog(NULL, 0, LOG_USER); }
bool logger_init(t_configuration_options *opts, const char *ident) { char *level = opts->log_level; char *facility = opts->log_facility; int l; int f; #ifdef HAVE_SYSLOG int syslog_facility = DEFAULT_SYSLOG_FACILITY; #endif #ifdef REPMGR_DEBUG printf("logger initialisation (Level: %s, Facility: %s)\n", level, facility); #endif if (!ident) { ident = DEFAULT_IDENT; } if (level && *level) { l = detect_log_level(level); #ifdef REPMGR_DEBUG printf("assigned level for logger: %d\n", l); #endif if (l >= 0) log_level = l; else stderr_log_warning(_("invalid log level \"%s\" (available values: DEBUG, INFO, NOTICE, WARNING, ERR, ALERT, CRIT or EMERG)\n"), level); } /* * STDERR only logging requested - finish here without setting up any * further logging facility. */ if (logger_output_mode == OM_COMMAND_LINE) return true; if (facility && *facility) { f = detect_log_facility(facility); #ifdef REPMGR_DEBUG printf("assigned facility for logger: %d\n", f); #endif if (f == 0) { /* No syslog requested, just stderr */ #ifdef REPMGR_DEBUG printf(_("using stderr for logging\n")); #endif } else if (f == -1) { stderr_log_warning(_("cannot detect log facility %s (use any of LOCAL0, LOCAL1, ..., LOCAL7, USER or STDERR)\n"), facility); } #ifdef HAVE_SYSLOG else { syslog_facility = f; log_type = REPMGR_SYSLOG; } #endif } #ifdef HAVE_SYSLOG if (log_type == REPMGR_SYSLOG) { setlogmask(LOG_UPTO(log_level)); openlog(ident, LOG_CONS | LOG_PID | LOG_NDELAY, syslog_facility); stderr_log_notice(_("setup syslog (level: %s, facility: %s)\n"), level, facility); } #endif if (*opts->log_file) { FILE *fd; /* * Check if we can write to the specified file before redirecting * stderr - if freopen() fails, stderr output will vanish into the * ether and the user won't know what's going on. */ fd = fopen(opts->log_file, "a"); if (fd == NULL) { stderr_log_error(_("unable to open specified log file \"%s\" for writing: %s\n"), opts->log_file, strerror(errno)); stderr_log_error(_("Terminating\n")); exit(ERR_BAD_CONFIG); } fclose(fd); stderr_log_notice(_("redirecting logging output to \"%s\"\n"), opts->log_file); fd = freopen(opts->log_file, "a", stderr); /* * It's possible freopen() may still fail due to e.g. a race * condition; as it's not feasible to restore stderr after a failed * freopen(), we'll write to stdout as a last resort. */ if (fd == NULL) { printf(_("unable to open specified log file %s for writing: %s\n"), opts->log_file, strerror(errno)); printf(_("terminating\n")); exit(ERR_BAD_CONFIG); } } return true; }
int main(int argc, char **argv) { struct lws_context_creation_info info; char interface_name[128] = ""; uv_timer_t timeout_watcher; const char *iface = NULL; char cert_path[1024]; char key_path[1024]; int use_ssl = 0; int opts = 0; int n = 0; #ifndef _WIN32 int syslog_options = LOG_PID | LOG_PERROR; #endif #ifndef LWS_NO_DAEMONIZE int daemonize = 0; #endif /* * take care to zero down the info struct, he contains random garbaage * from the stack otherwise */ memset(&info, 0, sizeof info); info.port = 7681; while (n >= 0) { n = getopt_long(argc, argv, "eci:hsap:d:Dr:", options, NULL); if (n < 0) continue; switch (n) { case 'e': opts |= LWS_SERVER_OPTION_LIBEV; break; #ifndef LWS_NO_DAEMONIZE case 'D': daemonize = 1; #ifndef _WIN32 syslog_options &= ~LOG_PERROR; #endif break; #endif case 'd': debug_level = atoi(optarg); break; case 's': use_ssl = 1; break; case 'a': opts |= LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT; break; case 'p': info.port = atoi(optarg); break; case 'i': strncpy(interface_name, optarg, sizeof interface_name); interface_name[(sizeof interface_name) - 1] = '\0'; iface = interface_name; break; case 'c': close_testing = 1; fprintf(stderr, " Close testing mode -- closes on " "client after 50 dumb increments" "and suppresses lws_mirror spam\n"); break; case 'r': resource_path = optarg; printf("Setting resource path to \"%s\"\n", resource_path); break; case 'h': fprintf(stderr, "Usage: test-server " "[--port=<p>] [--ssl] " "[-d <log bitfield>] " "[--resource_path <path>]\n"); exit(1); } } #if !defined(WIN32) #if !defined(LWS_NO_DAEMONIZE) /* * normally lock path would be /var/lock/lwsts or similar, to * simplify getting started without having to take care about * permissions or running as root, set to /tmp/.lwsts-lock */ if (daemonize && lws_daemonize("/tmp/.lwsts-lock")) { fprintf(stderr, "Failed to daemonize\n"); return 1; } #endif /* we will only try to log things according to our debug_level */ setlogmask(LOG_UPTO (LOG_DEBUG)); openlog("lwsts", syslog_options, LOG_DAEMON); #endif /* tell the library what debug level to emit and to send it to syslog */ lws_set_log_level(debug_level, lwsl_emit_syslog); lwsl_notice("libwebsockets test server libuv - license LGPL2.1+SLE\n"); lwsl_notice("(C) Copyright 2010-2016 Andy Green <*****@*****.**>\n"); lwsl_info("Using resource path \"%s\"\n", resource_path); info.iface = iface; info.protocols = protocols; info.extensions = exts; info.ssl_cert_filepath = NULL; info.ssl_private_key_filepath = NULL; if (use_ssl) { if (strlen(resource_path) > sizeof(cert_path) - 32) { lwsl_err("resource path too long\n"); return -1; } sprintf(cert_path, "%s/libwebsockets-test-server.pem", resource_path); if (strlen(resource_path) > sizeof(key_path) - 32) { lwsl_err("resource path too long\n"); return -1; } sprintf(key_path, "%s/libwebsockets-test-server.key.pem", resource_path); info.ssl_cert_filepath = cert_path; info.ssl_private_key_filepath = key_path; opts |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT; } info.gid = -1; info.uid = -1; info.max_http_header_pool = 1; info.timeout_secs = 5; info.options = opts | LWS_SERVER_OPTION_LIBUV; context = lws_create_context(&info); if (context == NULL) { lwsl_err("libwebsocket init failed\n"); return -1; } lws_uv_sigint_cfg(context, 1, signal_cb); if (lws_uv_initloop(context, NULL, 0)) { lwsl_err("lws_uv_initloop failed\n"); goto bail; } uv_timer_init(lws_uv_getloop(context, 0), &timeout_watcher); uv_timer_start(&timeout_watcher, uv_timeout_cb_dumb_increment, 50, 50); lws_libuv_run(context, 0); bail: lws_context_destroy(context); lwsl_notice("libwebsockets-test-server exited cleanly\n"); return 0; }
static int psr_set_state(processorid_t cpu, int action, psr_action_t *pac, int mustexist) { int old_state; int err; time_t now; char buf[80]; old_state = p_online(cpu, P_STATUS); if (old_state < 0) { if (errno == EINVAL && !mustexist) return (0); /* no such processor */ err = errno; /* in case sprintf smashes errno */ (void) snprintf(buf, sizeof (buf), "%s: processor %d", cmdname, cpu); errno = err; perror(buf); return (-1); } if (old_state == P_FAULTED && action != P_FAULTED && !force) { (void) printf("%s: processor %d in faulted state; " "add -F option to force change\n", cmdname, cpu); return (-1); } old_state = p_online(cpu, force ? action | P_FORCED : action); if (old_state < 0) { if (errno == EINVAL && !mustexist) return (0); /* no such processor */ err = errno; (void) snprintf(buf, sizeof (buf), "%s: processor %d", cmdname, cpu); errno = err; perror(buf); return (-1); } if (old_state == action) { if (verbose) (void) printf("processor %d already %s.\n", cpu, pac->p_state); return (1); /* no change */ } (void) snprintf(buf, sizeof (buf), "processor %d %s %s.", cpu, pac->p_action, pac->p_state); if (verbose) (void) printf("%s\n", buf); /* * Log the change. */ if (!log_open) { log_open = 1; openlog(cmdname, LOG_CONS, LOG_USER); /* open syslog */ (void) setlogmask(LOG_UPTO(LOG_INFO)); ut.ut_pid = getpid(); ut.ut_type = USER_PROCESS; (void) strncpy(ut.ut_user, "psradm", sizeof (ut.ut_user) - 1); } syslog(LOG_INFO, "%s", buf); /* * Update wtmp. */ (void) snprintf(ut.ut_line, sizeof (ut.ut_line), PSRADM_MSG, cpu, pac->p_wtmp); (void) time(&now); ut.ut_xtime = now; updwtmpx(WTMPX_FILE, &ut); return (1); /* the processor exists and no errors occurred */ }
void log_level(int verbosity) { setlogmask(LOG_UPTO(verbosity)); }
int main(int argc, char **argv) { int result; int log_flags = LOG_PID; struct utsname name; int fd; char pidstr[10]; /* Parse arguments */ result = l2tp_parse_args(argc, argv); if (result < 0) { fprintf(stderr, "Invalid argument\n"); return result; } /* Create a pid file, error if already exists */ fd = open(L2TP_PID_FILENAME, O_WRONLY | O_CREAT | O_EXCL, 0660); if (fd < 0) { if (errno == EEXIST) { fprintf(stderr, "File %s already exists. Is %s already running?\n", L2TP_PID_FILENAME, argv[0]); } else { fprintf(stderr, "File %s: %m", L2TP_PID_FILENAME); } exit(1); } /* Get system kernel info, which is used to build our vendor name */ result = uname(&name); if (result < 0) { fprintf(stderr, "Failed to get system version info: %m"); return result; } l2tp_kernel_version = strdup(name.release); l2tp_cpu_name = strdup(name.machine); if ((l2tp_kernel_version == NULL) || (l2tp_cpu_name == NULL)) { fprintf(stderr, "Out of memory\n"); return -1; } l2tp_firmware_revision = (((L2TP_APP_MAJOR_VERSION & 0x0f) << 4) | ((L2TP_APP_MINOR_VERSION & 0x0f) << 0)); /* Become a daemon */ if (!l2tp_opt_nodaemon) { usl_daemonize(); } /* We write the PID file AFTER the double-fork */ sprintf(&pidstr[0], "%d", getpid()); if (write(fd, &pidstr[0], strlen(pidstr)) < 0) syslog(LOG_WARNING, "Failed to write pid file %s", L2TP_PID_FILENAME); close(fd); /* Open the syslog */ if (l2tp_opt_debug) { log_flags |= LOG_NDELAY; } openlog("openl2tpd", log_flags, l2tp_opt_log_facility); setlogmask(LOG_UPTO(LOG_DEBUG)); l2tp_log(LOG_INFO, "Start, trace_flags=%08x%s", l2tp_opt_trace_flags, l2tp_opt_debug ? " (debug enabled)" : ""); /* Init the app */ l2tp_init(); /* Main loop - USL takes care of it */ usl_main_loop(); return 0; }
int main(int argc, char *argv[]) { int _argc = 0; char *_argv[5]; pid_t pid; int execed = 0; int n, nfd, tflags = 0, ch; struct timeval *tvp, waittime; struct itimerval itval; fd_set ibits; sigset_t sigset, osigset; while ((ch = getopt(argc, argv, "D012bsqtdg")) != EOF) { switch (ch) { case 'D': execed = 1; break; case '0': ripversion = 0; break; case '1': ripversion = 1; break; case '2': ripversion = 2; break; case 'b': multicast = 0; break; case 's': supplier = 1; break; case 'q': supplier = 0; break; case 't': tflags++; break; case 'd': debug++; setlogmask(LOG_UPTO(LOG_DEBUG)); break; case 'g': gateway = 1; break; default: fprintf(stderr, "usage: routed [ -1bsqtdg ]\n"); exit(1); } } // Modified by Mason Yu sleep(2); /* if(!check_pid()) { // Commented by Mason Yu //write_cfg(); exit(1); } */ if (!execed) { if ((pid = vfork()) < 0) { fprintf(stderr, "vfork failed\n"); exit(1); } else if (pid != 0) { exit(0); } for (_argc=0; _argc < argc; _argc++ ) _argv[_argc] = argv[_argc]; _argv[0] = runPath; _argv[argc++] = "-D"; _argv[argc++] = NULL; execv(_argv[0], _argv); /* Not reached */ fprintf(stderr, "Couldn't exec\n"); _exit(1); } else { setsid(); } getkversion(); sock = getsocket(); assert(sock>=0); openlog("routed", LOG_PID | LOG_ODELAY, LOG_DAEMON); #if 0 if (debug == 0 && tflags == 0) { #ifndef EMBED switch (fork()) { case -1: perror("fork"); exit(1); case 0: break; /* child */ default: exit(0); /* parent */ } #endif close(0); close(1); close(2); setsid(); setlogmask(LOG_UPTO(LOG_WARNING)); } else #endif { setlogmask(LOG_UPTO(LOG_DEBUG)); } /* * Any extra argument is considered * a tracing log file. * * Note: because traceon() redirects stderr, anything planning to * crash on startup should do so before this point. */ if (argc > 1) { traceon(argv[argc - 1]); } while (tflags-- > 0) { bumploglevel(); } gettimeofday(&now, NULL); /* * Collect an initial view of the world by * checking the interface configuration and the gateway kludge * file. Then, send a request packet on all * directly connected networks to find out what * everyone else thinks. */ read_cfg(); rtinit(); ifinit(); gwkludge(); if (gateway > 0) { rtdefault(); } if (supplier < 0) { supplier = 0; } signal(SIGALRM, timer); signal(SIGHUP, hup); signal(SIGTERM, hup); signal(SIGTERM, terminate_routed); //RTK WiSOC modify for deleting all route entry signal(SIGINT, rtdeleteall); signal(SIGUSR1, sigtrace); signal(SIGUSR2, sigtrace); itval.it_interval.tv_sec = TIMER_RATE; itval.it_value.tv_sec = TIMER_RATE; itval.it_interval.tv_usec = 0; itval.it_value.tv_usec = 0; srandom(time(NULL) ^ getpid()); if (setitimer(ITIMER_REAL, &itval, (struct itimerval *)NULL) < 0) { syslog(LOG_ERR, "setitimer: %m\n"); } // Kaohj //#ifdef EMBED //WiSOC we use pid file for system init write_pid(); //#endif rip_request_send(); rip_input_init(); DISPLAY_BANNER; FD_ZERO(&ibits); nfd = sock + 1; /* 1 + max(fd's) */ for (;;) { FD_SET(sock, &ibits); /* * If we need a dynamic update that was held off, * needupdate will be set, and nextbcast is the time * by which we want select to return. Compute time * until dynamic update should be sent, and select only * until then. If we have already passed nextbcast, * just poll. */ if (needupdate) { waittime = nextbcast; timevalsub(&waittime, &now); if (waittime.tv_sec < 0) { waittime.tv_sec = 0; waittime.tv_usec = 0; } if (traceactions) fprintf(ftrace, "select until dynamic update %ld/%ld sec/usec\n", (long)waittime.tv_sec, (long)waittime.tv_usec); tvp = &waittime; } else { tvp = (struct timeval *)NULL; } n = select(nfd, &ibits, 0, 0, tvp); if (n <= 0) { /* * Need delayed dynamic update if select returned * nothing and we timed out. Otherwise, ignore * errors (e.g. EINTR). */ if (n < 0) { if (errno == EINTR) continue; syslog(LOG_ERR, "select: %m"); } sigemptyset(&sigset); sigaddset(&sigset, SIGALRM); sigprocmask(SIG_BLOCK, &sigset, &osigset); if (n == 0 && needupdate) { if (traceactions) fprintf(ftrace, "send delayed dynamic update\n"); (void) gettimeofday(&now, (struct timezone *)NULL); toall(supply, RTS_CHANGED, (struct interface *)NULL); lastbcast = now; needupdate = 0; nextbcast.tv_sec = 0; } sigprocmask(SIG_SETMASK, &osigset, NULL); continue; } gettimeofday(&now, (struct timezone *)NULL); sigemptyset(&sigset); sigaddset(&sigset, SIGALRM); sigprocmask(SIG_BLOCK, &sigset, &osigset); if (FD_ISSET(sock, &ibits)) { process(sock); } /* handle ICMP redirects */ sigprocmask(SIG_SETMASK, &osigset, NULL); } }