int main(int argc, char *argv[]) { FILE *fp = stdin; fd_set fdset; struct timeval timeout; int ch, i, maxfd = 0, send_counter = 0; struct flags flags; struct payload_list *pl; #ifdef IPSEC_POLICY_IPSEC char *policy = NULL; #endif memset(&flags, 0, sizeof(flags)); openlog("rrenumd", LOG_PID, LOG_DAEMON); /* get options */ while ((ch = getopt(argc, argv, "c:sdf" #ifdef IPSEC #ifdef IPSEC_POLICY_IPSEC "P:" #else /* IPSEC_POLICY_IPSEC */ "AE" #endif /* IPSEC_POLICY_IPSEC */ #endif /* IPSEC */ )) != -1){ switch (ch) { case 'c': if((fp = fopen(optarg, "r")) == NULL) { syslog(LOG_ERR, "<%s> config file %s open failed", __func__, optarg); exit(1); } break; case 's': fp = stdin; break; case 'd': flags.debug = 1; break; case 'f': flags.fg = 1; break; #ifdef IPSEC #ifdef IPSEC_POLICY_IPSEC case 'P': flags.policy = 1; policy = strdup(optarg); break; #else /* IPSEC_POLICY_IPSEC */ case 'A': flags.auth = 1; break; case 'E': flags.encrypt = 1; break; #endif /* IPSEC_POLICY_IPSEC */ #endif /*IPSEC*/ default: show_usage(); } } argc -= optind; argv += optind; /* set log level */ if (flags.debug == 0) (void)setlogmask(LOG_UPTO(LOG_ERR)); if (flags.debug == 1) (void)setlogmask(LOG_UPTO(LOG_INFO)); /* init global variables */ init_globals(); config(&fp); sock6_open(&flags #ifdef IPSEC_POLICY_IPSEC , policy #endif /* IPSEC_POLICY_IPSEC */ ); sock4_open(&flags #ifdef IPSEC_POLICY_IPSEC , policy #endif /* IPSEC_POLICY_IPSEC */ ); if (!flags.fg) daemon(0, 0); FD_ZERO(&fdset); if (with_v6dest) { FD_SET(s6, &fdset); if (s6 > maxfd) maxfd = s6; } if (with_v4dest) { FD_SET(s4, &fdset); if (s4 > maxfd) maxfd = s4; } /* ADHOC: timeout each 30seconds */ memset(&timeout, 0, sizeof(timeout)); /* init temporary payload_list and send_counter*/ pl = pl_head; send_counter = retry + 1; while (1) { struct fd_set select_fd = fdset; /* reinitialize */ if ((i = select(maxfd + 1, &select_fd, NULL, NULL, &timeout)) < 0){ syslog(LOG_ERR, "<%s> select: %s", __func__, strerror(errno)); continue; } if (i == 0) { /* timeout */ if (pl == NULL) exit(0); rrenum_snd_eachdst(pl); send_counter--; timeout.tv_sec = 30; if (send_counter == 0) { timeout.tv_sec = 0; pl = pl->pl_next; send_counter = retry + 1; } } if (FD_ISSET(s4, &select_fd)) rrenum_input(s4); if (FD_ISSET(s6, &select_fd)) rrenum_input(s6); } }
/* * メインタスク */ void main_task(intptr_t exinf) { char c; ID tskid = TASK1; int_t tskno = 1; ER_UINT ercd; PRI tskpri; #ifndef TASK_LOOP volatile ulong_t i; SYSTIM stime1, stime2; #endif /* TASK_LOOP */ HRTCNT hrtcnt1, hrtcnt2; T_CTSK ctsk; ID TASK3 = -1; T_CALM calm; ID ALMHDR1 = -1; SVC_PERROR(syslog_msk_log(LOG_UPTO(LOG_INFO), LOG_UPTO(LOG_EMERG))); syslog(LOG_NOTICE, "Sample program starts (exinf = %d).", (int_t) exinf); /* * シリアルポートの初期化 * * システムログタスクと同じシリアルポートを使う場合など,シリアル * ポートがオープン済みの場合にはここでE_OBJエラーになるが,支障は * ない. */ ercd = serial_opn_por(TASK_PORTID); if (ercd < 0 && MERCD(ercd) != E_OBJ) { syslog(LOG_ERROR, "%s (%d) reported by `serial_opn_por'.", itron_strerror(ercd), SERCD(ercd)); } SVC_PERROR(serial_ctl_por(TASK_PORTID, (IOCTL_CRLF | IOCTL_FCSND | IOCTL_FCRCV))); /* * ループ回数の設定 * * 並行実行されるタスク内での空ループの回数(task_loop)は,空ルー * プの実行時間が約0.4秒になるように設定する.この設定のために, * LOOP_REF回の空ループの実行時間を,その前後でget_timを呼ぶことで * 測定し,その測定結果から空ループの実行時間が0.4秒になるループ回 * 数を求め,task_loopに設定する. * * LOOP_REFは,デフォルトでは1,000,000に設定しているが,想定したよ * り遅いプロセッサでは,サンプルプログラムの実行開始に時間がかか * りすぎるという問題を生じる.逆に想定したより速いプロセッサでは, * LOOP_REF回の空ループの実行時間が短くなり,task_loopに設定する値 * の誤差が大きくなるという問題がある. * * そこで,そのようなターゲットでは,target_test.hで,LOOP_REFを適 * 切な値に定義するのが望ましい. * * また,task_loopの値を固定したい場合には,その値をTASK_LOOPにマ * クロ定義する.TASK_LOOPがマクロ定義されている場合,上記の測定を * 行わずに,TASK_LOOPに定義された値を空ループの回数とする. * * ターゲットによっては,空ループの実行時間の1回目の測定で,本来よ * りも長めになるものがある.このようなターゲットでは,MEASURE_TWICE * をマクロ定義することで,1回目の測定結果を捨てて,2回目の測定結果 * を使う. */ #ifdef TASK_LOOP task_loop = TASK_LOOP; #else /* TASK_LOOP */ #ifdef MEASURE_TWICE task_loop = LOOP_REF; SVC_PERROR(get_tim(&stime1)); for (i = 0; i < task_loop; i++); SVC_PERROR(get_tim(&stime2)); #endif /* MEASURE_TWICE */ task_loop = LOOP_REF; SVC_PERROR(get_tim(&stime1)); for (i = 0; i < task_loop; i++); SVC_PERROR(get_tim(&stime2)); task_loop = LOOP_REF * 400LU / (ulong_t)(stime2 - stime1) * 1000LU; #endif /* TASK_LOOP */ /* * タスクの起動 */ SVC_PERROR(act_tsk(TASK1)); SVC_PERROR(act_tsk(TASK2)); /* * メインループ */ do { SVC_PERROR(serial_rea_dat(TASK_PORTID, &c, 1)); switch (c) { case 'e': case 's': case 'S': case 'd': case 'y': case 'Y': case 'z': case 'Z': message[tskno-1] = c; break; case '1': tskno = 1; tskid = TASK1; break; case '2': tskno = 2; tskid = TASK2; break; case '3': tskno = 3; tskid = TASK3; break; case 'a': syslog(LOG_INFO, "#act_tsk(%d)", tskno); SVC_PERROR(act_tsk(tskid)); break; case 'A': syslog(LOG_INFO, "#can_act(%d)", tskno); SVC_PERROR(ercd = can_act(tskid)); if (ercd >= 0) { syslog(LOG_NOTICE, "can_act(%d) returns %d", tskno, ercd); } break; case 't': syslog(LOG_INFO, "#ter_tsk(%d)", tskno); SVC_PERROR(ter_tsk(tskid)); break; case '>': syslog(LOG_INFO, "#chg_pri(%d, HIGH_PRIORITY)", tskno); SVC_PERROR(chg_pri(tskid, HIGH_PRIORITY)); break; case '=': syslog(LOG_INFO, "#chg_pri(%d, MID_PRIORITY)", tskno); SVC_PERROR(chg_pri(tskid, MID_PRIORITY)); break; case '<': syslog(LOG_INFO, "#chg_pri(%d, LOW_PRIORITY)", tskno); SVC_PERROR(chg_pri(tskid, LOW_PRIORITY)); break; case 'G': syslog(LOG_INFO, "#get_pri(%d, &tskpri)", tskno); SVC_PERROR(ercd = get_pri(tskid, &tskpri)); if (ercd >= 0) { syslog(LOG_NOTICE, "priority of task %d is %d", tskno, tskpri); } break; case 'w': syslog(LOG_INFO, "#wup_tsk(%d)", tskno); SVC_PERROR(wup_tsk(tskid)); break; case 'W': syslog(LOG_INFO, "#can_wup(%d)", tskno); SVC_PERROR(ercd = can_wup(tskid)); if (ercd >= 0) { syslog(LOG_NOTICE, "can_wup(%d) returns %d", tskno, ercd); } break; case 'l': syslog(LOG_INFO, "#rel_wai(%d)", tskno); SVC_PERROR(rel_wai(tskid)); break; case 'u': syslog(LOG_INFO, "#sus_tsk(%d)", tskno); SVC_PERROR(sus_tsk(tskid)); break; case 'm': syslog(LOG_INFO, "#rsm_tsk(%d)", tskno); SVC_PERROR(rsm_tsk(tskid)); break; case 'x': syslog(LOG_INFO, "#ras_ter(%d)", tskno); SVC_PERROR(ras_ter(tskid)); break; case 'r': syslog(LOG_INFO, "#rot_rdq(three priorities)"); SVC_PERROR(rot_rdq(HIGH_PRIORITY)); SVC_PERROR(rot_rdq(MID_PRIORITY)); SVC_PERROR(rot_rdq(LOW_PRIORITY)); break; case 'c': syslog(LOG_INFO, "#sta_cyc(1)"); SVC_PERROR(sta_cyc(CYCHDR1)); break; case 'C': syslog(LOG_INFO, "#stp_cyc(1)"); SVC_PERROR(stp_cyc(CYCHDR1)); break; case 'b': syslog(LOG_INFO, "#sta_alm(1, 5000000)"); SVC_PERROR(sta_alm(ALMHDR1, 5000000)); break; case 'B': syslog(LOG_INFO, "#stp_alm(1)"); SVC_PERROR(stp_alm(ALMHDR1)); break; case '@': ctsk.tskatr = TA_NULL; ctsk.exinf = 3; ctsk.task = task; ctsk.itskpri = MID_PRIORITY; ctsk.stksz = STACK_SIZE; ctsk.stk = NULL; SVC_PERROR(TASK3 = acre_tsk(&ctsk)); syslog(LOG_NOTICE, "task3 is created with tskid = %d.", (int_t) TASK3); break; case '!': syslog(LOG_INFO, "#del_tsk(%d)", tskno); SVC_PERROR(del_tsk(tskid)); break; case '$': calm.almatr = TA_NULL; calm.nfyinfo.nfymode = TNFY_HANDLER; calm.nfyinfo.nfy.handler.exinf = (intptr_t) 0; calm.nfyinfo.nfy.handler.tmehdr = (TMEHDR) alarm_handler; SVC_PERROR(ALMHDR1 = acre_alm(&calm)); syslog(LOG_NOTICE, "alarm handler is created with almid = %d.", (int_t) ALMHDR1); break; case '#': syslog(LOG_INFO, "#del_alm(1)"); SVC_PERROR(del_alm(ALMHDR1)); break; case 'V': hrtcnt1 = fch_hrt(); hrtcnt2 = fch_hrt(); syslog(LOG_NOTICE, "hrtcnt1 = %tu, hrtcnt2 = %tu", hrtcnt1, hrtcnt2); break; case 'v': SVC_PERROR(syslog_msk_log(LOG_UPTO(LOG_INFO), LOG_UPTO(LOG_EMERG))); break; case 'q': SVC_PERROR(syslog_msk_log(LOG_UPTO(LOG_NOTICE), LOG_UPTO(LOG_EMERG))); break; #ifdef BIT_KERNEL case ' ': SVC_PERROR(loc_cpu()); { extern ER bit_kernel(void); SVC_PERROR(ercd = bit_kernel()); if (ercd >= 0) { syslog(LOG_NOTICE, "bit_kernel passed."); } } SVC_PERROR(unl_cpu()); break; #endif /* BIT_KERNEL */ default: break; } } while (c != '\003' && c != 'Q'); syslog(LOG_NOTICE, "Sample program ends."); SVC_PERROR(ext_ker()); assert(0); }
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; }
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; }
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; }
void log_level(int verbosity) { setlogmask(LOG_UPTO(verbosity)); }
/** * 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; }
* License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * This file is part of the Arduino Che Cosa project. */ #include "Cosa/Trace.hh" Trace trace; uint8_t trace_log_mask = LOG_UPTO(LOG_INFO); bool Trace::begin(IOStream::Device* dev, const char* banner) { set_device(dev); if (banner != NULL) { print_P(banner); println(); } return (true); } void Trace::fatal_P(const char* file, int line, const char* expr) {
/* * 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) { 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 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) { 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; }
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[]) { 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); } }
void openSyslog() { setlogmask(LOG_UPTO (LOG_INFO)); openlog(NULL, 0, LOG_USER); }
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) { 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; }
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; }
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); }
/** * Reports statistics. */ static void reportStats(void) { struct timeval now; double interval; double rate; char buf[80]; int logmask; unsigned long byteCount; unsigned long packetCount, missedPacketCount, prodCount; static unsigned long totalPacketCount; static unsigned long totalMissedPacketCount; static unsigned long totalProdCount; static unsigned long totalByteCount; (void)gettimeofday(&now, NULL); readerGetStatistics(reader, &byteCount); pmGetStatistics(productMaker, &packetCount, &missedPacketCount, &prodCount); totalByteCount += byteCount; totalPacketCount += packetCount; totalMissedPacketCount += missedPacketCount; totalProdCount += prodCount; logmask = setulogmask(LOG_UPTO(LOG_NOTICE)); nplStart("----------------------------------------"); nplAdd("Ingestion Statistics:"); nplAdd(" Since Previous Report (or Start):"); interval = duration(&now, &reportTime); encodeDuration(buf, sizeof(buf), interval); nplAdd(" Duration %s", buf); nplAdd(" Raw Data:"); nplAdd(" Octets %lu", CHAR_BIT*byteCount/8); nplAdd(" Mean Rate:"); rate = (byteCount/interval)*(CHAR_BIT/8.0); nplAdd(" Octets %g/s", rate); nplAdd(" Bits %g/s", 8*rate); nplAdd(" Received packets:"); nplAdd(" Number %lu", packetCount); nplAdd(" Mean Rate %g/s", packetCount/interval); nplAdd(" Missed packets:"); nplAdd(" Number %lu", missedPacketCount); nplAdd(" %% %g", 100.0 * missedPacketCount / (missedPacketCount + packetCount)); nplAdd(" Products:"); nplAdd(" Inserted %lu", prodCount); nplAdd(" Mean Rate %g/s", prodCount/interval); nplAdd(" Since Start:"); interval = duration(&now, &startTime); encodeDuration(buf, sizeof(buf), interval); nplAdd(" Duration %s", buf); nplAdd(" Raw Data:"); nplAdd(" Octets %lu", CHAR_BIT*totalByteCount/8); nplAdd(" Mean Rate:"); rate = (totalByteCount/interval)*(CHAR_BIT/8.0); nplAdd(" Octets %g/s", rate); nplAdd(" Bits %g/s", 8*rate); nplAdd(" Received packets:"); nplAdd(" Number %lu", totalPacketCount); nplAdd(" Mean Rate %g/s", totalPacketCount/interval); nplAdd(" Missed packets:"); nplAdd(" Number %lu", totalMissedPacketCount); nplAdd(" %% %g", 100.0 * totalMissedPacketCount / (totalMissedPacketCount + totalPacketCount)); nplAdd(" Products:"); nplAdd(" Inserted %lu", totalProdCount); nplAdd(" Mean Rate %g/s", totalProdCount/interval); nplAdd("----------------------------------------"); nplLog(LOG_NOTICE); (void)setulogmask(logmask); reportTime = now; }
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 */
/** * Reads a NOAAPORT data stream, creates LDM data-products from the stream, and * inserts the data-products into an LDM product-queue. The NOAAPORT data * stream can take the form of multicast UDP packets from (for example) a * Novra S300 DVB-S2 receiver or the standard input stream. * * Usage: * noaaportIngester [-l <em>log</em>] [-n|-v|-x] [-q <em>queue</em>] [-u <em>n</em>] [-m <em>mcastAddr</em>] [-I <em>iface</em>] [-b <em>npages</em>]\n * * Where: * <dl> * <dt>-b <em>npages</em></dt> * <dd>Allocate \e npages pages of memory for the internal buffer.</dd> * * <dt>-I <em>iface</em></dt> * <dd>Listen for multicast packets on interface \e iface.</dd> * * <dt>-l <em>log</em></dt> * <dd>Log to file \e log. The default is to use the system logging daemon * if the current process is a daemon; otherwise, the standard error * stream is used.</dd> * * <dt>-m <em>mcastAddr</em></dt> * <dd>Use the multicast address \e mcastAddr. The default is to * read from the standard input stream.</dd> * * <dt>-n</dt> * <dd>Log messages of level NOTE and higher priority. Each data-product * will generate a log message.</dd> * * <dt>-q <em>queue</em></dt> * <dd>Use \e queue as the pathname of the LDM product-queue. The default * is to use the default LDM pathname of the product-queue.</dd> * * <dt>-u <em>n</em></dt> * <dd>If logging is to the system logging daemon, then use facility * <b>local</b><em>n</em>. The default is to use the LDM facility.</dd> * * <dt>-v</dt> * <dd>Log messages of level INFO and higher priority.</dd> * * <dt>-x</dt> * <dd>Log messages of level DEBUG and higher priority.</dd> * </dl> * * If neither -n, -v, nor -x is specified, then logging will be restricted to * levels ERROR and WARN only. * * @retval 0 if successful. * @retval 1 if an error occurred. At least one error-message will be logged. */ int main( const int argc, /**< [in] Number of arguments */ char* const argv[]) /**< [in] Arguments */ { int status = 0; /* default success */ extern int optind; extern int opterr; int ch; const char* const progName = ubasename(argv[0]); const char* interface = NULL; int logmask = LOG_UPTO(LOG_WARNING); const unsigned logOptions = LOG_CONS | LOG_PID; const char* mcastSpec = NULL; const char* prodQueuePath = NULL; size_t npages = DEFAULT_NPAGES; Fifo* fifo; int ttyFd = open("/dev/tty", O_RDONLY); int processPriority = 0; const char* logPath = (-1 == ttyFd) ? NULL /* log to system logging daemon */ : "-"; /* log to standard error stream */ (void)close(ttyFd); (void)setulogmask(logmask); status = initLogging(progName, logOptions, logFacility, logPath); opterr = 0; /* no error messages from getopt(3) */ while (0 == status && (ch = getopt(argc, argv, "b:I:l:m:np:q:u:vx")) != -1) { switch (ch) { extern char* optarg; extern int optopt; case 'b': { unsigned long n; if (sscanf(optarg, "%lu", &n) != 1) { NPL_SERROR1("Couldn't decode FIFO size in pages: \"%s\"", optarg); status = 1; } else { npages = n; } } case 'I': interface = optarg; break; case 'l': logPath = optarg; status = initLogging(progName, logOptions, logFacility, logPath); break; case 'm': mcastSpec = optarg; break; case 'n': logmask |= LOG_MASK(LOG_NOTICE); (void)setulogmask(logmask); break; case 'p': { char* cp; errno = 0; processPriority = (int)strtol(optarg, &cp, 0); if (0 != errno) { NPL_SERROR1("Couldn't decode priority \"%s\"", optarg); nplLog(LOG_ERR); } else { if (processPriority < -20) processPriority = -20; else if (processPriority > 20) processPriority = 20; } break; } case 'q': prodQueuePath = optarg; break; case 'u': { int i = atoi(optarg); if (0 > i || 7 < i) { NPL_START1("Invalid logging facility number: %d", i); status = 1; } else { static int logFacilities[] = {LOG_LOCAL0, LOG_LOCAL1, LOG_LOCAL2, LOG_LOCAL3, LOG_LOCAL4, LOG_LOCAL5, LOG_LOCAL6, LOG_LOCAL7}; logFacility = logFacilities[i]; status = initLogging(progName, logOptions, logFacility, logPath); } break; } case 'v': logmask |= LOG_MASK(LOG_INFO); (void)setulogmask(logmask); break; case 'x': logmask |= LOG_MASK(LOG_DEBUG); (void)setulogmask(logmask); break; default: optopt = ch; /*FALLTHROUGH*/ case '?': { nplError("Unknown option: \"%c\"", optopt); status = 1; } } /* option character switch */ } /* getopt() loop */ if (0 == status) { if (optind < argc) { nplError("Extraneous command-line argument: \"%s\"", argv[optind]); status = 1; } } if (0 != status) { nplError("Error decoding command-line"); usage(progName); } else { nplNotice("Starting Up %s", PACKAGE_VERSION); nplNotice("%s", COPYRIGHT_NOTICE); if ((status = fifoNew(npages, &fifo)) != 0) { NPL_ADD0("Couldn't create FIFO"); nplLog(LOG_ERR); } else { LdmProductQueue* prodQueue; if ((status = lpqGet(prodQueuePath, &prodQueue)) != 0) { NPL_ADD0("Couldn't open LDM product-queue"); nplLog(LOG_ERR); } else { if (NULL == mcastSpec) { if (0 == (status = spawnProductMaker(NULL, fifo, prodQueue, &productMaker, &productMakerThread))) { status = spawnFileReader(NULL, NULL, fifo, &reader, &readerThread); } } /* reading file */ else { pthread_attr_t attr; if (0 != (status = pthread_attr_init(&attr))) { NPL_ERRNUM0(status, "Couldn't initialize thread attribute"); } else { #ifndef _POSIX_THREAD_PRIORITY_SCHEDULING nplWarn("Can't adjust thread priorities due to lack of " "necessary support from environment"); #else /* * In order to not miss any data, the reader thread * should preempt the product-maker thread as soon as * data is available and run as long as data is * available. */ const int SCHED_POLICY = SCHED_FIFO; struct sched_param param; param.sched_priority = sched_get_priority_max(SCHED_POLICY) - 1; (void)pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED); (void)pthread_attr_setschedpolicy(&attr, SCHED_POLICY); (void)pthread_attr_setschedparam(&attr, ¶m); (void)pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); #endif if (0 == (status = spawnProductMaker(&attr, fifo, prodQueue, &productMaker, &productMakerThread))) { #ifdef _POSIX_THREAD_PRIORITY_SCHEDULING param.sched_priority++; (void)pthread_attr_setschedparam(&attr, ¶m); #endif status = spawnMulticastReader(&attr, mcastSpec, interface, fifo, &reader, &readerThread); } /* product-maker spawned */ } /* "attr" initialized */ } /* reading multicast packets */ if (0 != status) { nplLog(LOG_ERR); status = 1; } else { pthread_t statThread; (void)gettimeofday(&startTime, NULL); reportTime = startTime; (void)pthread_create(&statThread, NULL, reportStatsWhenSignaled, NULL); set_sigactions(); (void)pthread_join(readerThread, NULL); status = readerStatus(reader); (void)pthread_cancel(statThread); (void)pthread_join(statThread, NULL); (void)fifoCloseWhenEmpty(fifo); (void)pthread_join(productMakerThread, NULL); if (0 != status) status = pmStatus(productMaker); reportStats(); readerFree(reader); } /* "reader" spawned */ (void)lpqClose(prodQueue); } /* "prodQueue" open */ } /* "fifo" created */ } /* command line decoded */ return status; }
/** * @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); } }
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; }
/* * メインタスク */ void main_task(VP_INT exinf) { char c; ID tskid = TASK1; volatile UW i; INT tskno = 1; ER_UINT ercd; PRI tskpri; SYSTIM stime1, stime2; #ifndef OMIT_VGET_TIM SYSUTIM utime1, utime2; #endif /* OMIT_VGET_TIM */ vmsk_log(LOG_UPTO(LOG_INFO), LOG_UPTO(LOG_EMERG)); syslog(LOG_NOTICE, "Sample program starts (exinf = %d).", (INT) exinf); syscall(serial_ctl_por(TASK_PORTID, (IOCTL_CRLF | IOCTL_FCSND | IOCTL_FCRCV))); /* * ループ回数の設定 */ task_loop = LOOP_REF; get_tim(&stime1); for (i = 0; i < task_loop; i++); get_tim(&stime2); task_loop = LOOP_REF * 400 / (stime2 - stime1); tex_loop = task_loop / 5; /* * タスクの起動 */ act_tsk(TASK1); act_tsk(TASK2); act_tsk(TASK3); /* * メインループ */ do { syscall(serial_rea_dat(TASK_PORTID, &c, 1)); switch (c) { case 'e': case 's': case 'S': case 'd': case 'y': case 'Y': case 'z': case 'Z': message[tskno-1] = c; break; case '1': tskno = 1; tskid = TASK1; break; case '2': tskno = 2; tskid = TASK2; break; case '3': tskno = 3; tskid = TASK3; break; case 'a': syslog(LOG_INFO, "#act_tsk(%d)", tskno); syscall(act_tsk(tskid)); break; case 'A': syslog(LOG_INFO, "#can_act(%d)", tskno); syscall(ercd = can_act(tskid)); if (ercd >= 0) { syslog(LOG_NOTICE, "can_act(%d) returns %d", tskno, ercd); } break; case 't': syslog(LOG_INFO, "#ter_tsk(%d)", tskno); syscall(ter_tsk(tskid)); break; case '>': syslog(LOG_INFO, "#chg_pri(%d, HIGH_PRIORITY)", tskno); chg_pri(tskid, HIGH_PRIORITY); break; case '=': syslog(LOG_INFO, "#chg_pri(%d, MID_PRIORITY)", tskno); chg_pri(tskid, MID_PRIORITY); break; case '<': syslog(LOG_INFO, "#chg_pri(%d, LOW_PRIORITY)", tskno); chg_pri(tskid, LOW_PRIORITY); break; case 'G': syslog(LOG_INFO, "#get_pri(%d, &tskpri)", tskno); syscall(ercd = get_pri(tskid, &tskpri)); if (ercd >= 0) { syslog(LOG_NOTICE, "priority of task %d is %d", tskno, tskpri); } break; case 'w': syslog(LOG_INFO, "#wup_tsk(%d)", tskno); syscall(wup_tsk(tskid)); break; case 'W': syslog(LOG_INFO, "#can_wup(%d)", tskno); syscall(ercd = can_wup(tskid)); if (ercd >= 0) { syslog(LOG_NOTICE, "can_wup(%d) returns %d", tskno, ercd); } break; case 'l': syslog(LOG_INFO, "#rel_wai(%d)", tskno); syscall(rel_wai(tskid)); break; case 'u': syslog(LOG_INFO, "#sus_tsk(%d)", tskno); syscall(sus_tsk(tskid)); break; case 'm': syslog(LOG_INFO, "#rsm_tsk(%d)", tskno); syscall(rsm_tsk(tskid)); break; case 'M': syslog(LOG_INFO, "#frsm_tsk(%d)", tskno); syscall(frsm_tsk(tskid)); break; case 'x': syslog(LOG_INFO, "#ras_tex(%d, 0x0001)", tskno); syscall(ras_tex(tskid, 0x0001)); break; case 'X': syslog(LOG_INFO, "#ras_tex(%d, 0x0002)", tskno); syscall(ras_tex(tskid, 0x0002)); break; case 'r': syslog(LOG_INFO, "#rot_rdq(three priorities)"); rot_rdq(HIGH_PRIORITY); rot_rdq(MID_PRIORITY); rot_rdq(LOW_PRIORITY); break; case 'c': sta_cyc(CYCHDR1); break; case 'C': stp_cyc(CYCHDR1); break; #ifndef OMIT_VGET_TIM case 'V': syscall(vxget_tim(&utime1)); syscall(vxget_tim(&utime2)); syslog(LOG_NOTICE, "utime1 = %d, utime2 = %d", (UINT) utime1, (UINT) utime2); break; #endif /* OMIT_VGET_TIM */ case 'v': vmsk_log(LOG_UPTO(LOG_INFO), LOG_UPTO(LOG_EMERG)); break; case 'q': vmsk_log(LOG_UPTO(LOG_NOTICE), LOG_UPTO(LOG_EMERG)); break; default: break; } } while (c != '\003' && c != 'Q'); syslog(LOG_NOTICE, "Sample program ends."); kernel_exit(); }
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; }
/* call-seq: * LOG_UPTO(priority_level) => priority_mask * * Generates a mask value for priority levels at or below the level specified. * See #mask= */ static VALUE mSyslogConstants_LOG_UPTO(VALUE klass, VALUE pri) { return INT2FIX(LOG_UPTO(NUM2INT(pri))); }
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 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* const argv[]) { memset(&config, 0, sizeof(config)); const char *pidfile = "/var/run/6relayd.pid"; bool daemonize = false; int verbosity = 0; int c; while ((c = getopt(argc, argv, "ASR:D:Nsucn::l:a:rt:m:oi:p:dvh")) != -1) { switch (c) { case 'A': config.enable_router_discovery_relay = true; config.enable_dhcpv6_relay = true; config.enable_ndp_relay = true; config.send_router_solicitation = true; config.enable_route_learning = true; break; case 'S': config.enable_router_discovery_relay = true; config.enable_router_discovery_server = true; config.enable_dhcpv6_relay = true; config.enable_dhcpv6_server = true; break; case 'R': config.enable_router_discovery_relay = true; if (!strcmp(optarg, "server")) config.enable_router_discovery_server = true; else if (strcmp(optarg, "relay")) return print_usage(argv[0]); break; case 'D': config.enable_dhcpv6_relay = true; if (!strcmp(optarg, "server")) config.enable_dhcpv6_server = true; else if (strcmp(optarg, "relay")) return print_usage(argv[0]); break; case 'N': config.enable_ndp_relay = true; break; case 's': config.send_router_solicitation = true; break; case 'u': config.always_announce_default_router = true; break; case 'c': config.deprecate_ula_if_public_avail = true; break; case 'n': config.always_rewrite_dns = true; if (optarg) inet_pton(AF_INET6, optarg, &config.dnsaddr); break; case 'l': config.dhcpv6_statefile = strtok(optarg, ","); if (config.dhcpv6_statefile) config.dhcpv6_cb = strtok(NULL, ","); break; case 'a': config.dhcpv6_lease = realloc(config.dhcpv6_lease, sizeof(char*) * ++config.dhcpv6_lease_len); config.dhcpv6_lease[config.dhcpv6_lease_len - 1] = optarg; break; case 'r': config.enable_route_learning = true; break; case 't': config.static_ndp = realloc(config.static_ndp, sizeof(char*) * ++config.static_ndp_len); config.static_ndp[config.static_ndp_len - 1] = optarg; break; case 'm': config.ra_managed_mode = atoi(optarg); break; case 'o': config.ra_not_onlink = true; break; case 'i': if (!strcmp(optarg, "low")) config.ra_preference = -1; else if (!strcmp(optarg, "high")) config.ra_preference = 1; break; case 'p': pidfile = optarg; break; case 'd': daemonize = true; break; case 'v': verbosity++; break; default: return print_usage(argv[0]); } } openlog("6relayd", LOG_PERROR | LOG_PID, LOG_DAEMON); if (verbosity == 0) setlogmask(LOG_UPTO(LOG_WARNING)); else if (verbosity == 1) setlogmask(LOG_UPTO(LOG_INFO)); if (argc - optind < 1) return print_usage(argv[0]); if (getuid() != 0) { syslog(LOG_ERR, "Must be run as root. stopped."); return 2; } #if defined(__NR_epoll_create1) && defined(EPOLL_CLOEXEC) epoll = epoll_create1(EPOLL_CLOEXEC); #else epoll = epoll_create(32); epoll = fflags(epoll, O_CLOEXEC); #endif if (epoll < 0) { syslog(LOG_ERR, "Unable to open epoll: %s", strerror(errno)); return 2; } #ifdef SOCK_CLOEXEC ioctl_sock = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0); #else ioctl_sock = socket(AF_INET6, SOCK_DGRAM, 0); ioctl_sock = fflags(ioctl_sock, O_CLOEXEC); #endif if ((rtnl_socket = relayd_open_rtnl_socket()) < 0) { syslog(LOG_ERR, "Unable to open socket: %s", strerror(errno)); return 2; } if (open_interface(&config.master, argv[optind++], false)) return 3; config.slavecount = argc - optind; config.slaves = calloc(config.slavecount, sizeof(*config.slaves)); for (size_t i = 0; i < config.slavecount; ++i) { const char *name = argv[optind + i]; bool external = (name[0] == '~'); if (external) ++name; if (open_interface(&config.slaves[i], name, external)) return 3; } if ((urandom_fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC)) < 0) return 4; struct sigaction sa = {.sa_handler = SIG_IGN}; sigaction(SIGUSR1, &sa, NULL); if (init_router_discovery_relay(&config)) return 4; if (init_dhcpv6_relay(&config)) return 4; if (init_ndp_proxy(&config)) return 4; if (epoll_registered == 0) { syslog(LOG_WARNING, "No relays enabled or no slave " "interfaces specified. stopped."); return 5; } if (daemonize) { openlog("6relayd", LOG_PID, LOG_DAEMON); // Disable LOG_PERROR if (daemon(0, 0)) { syslog(LOG_ERR, "Failed to daemonize: %s", strerror(errno)); return 6; } FILE *fp = fopen(pidfile, "w"); if (fp) { fprintf(fp, "%i\n", getpid()); fclose(fp); } } signal(SIGTERM, set_stop); signal(SIGHUP, set_stop); signal(SIGINT, set_stop); signal(SIGCHLD, wait_child); // Main loop while (!do_stop) { struct epoll_event ev[16]; int len = epoll_wait(epoll, ev, 16, -1); for (int i = 0; i < len; ++i) { struct relayd_event *event = ev[i].data.ptr; if (event->handle_event) event->handle_event(event); else if (event->handle_dgram) relayd_receive_packets(event); } } syslog(LOG_WARNING, "Termination requested by signal."); deinit_ndp_proxy(); deinit_router_discovery_relay(); free(config.slaves); close(urandom_fd); return 0; }