int main(int argc, const char *argv[]) { if (argc != 3) { print_usage(); return 1; } setup_signal_handlers(); server *s = server_create((uint16_t)atoi(argv[1]), argv[2]); server_listen(s); printf("Listening...\n"); fflush(stdout); while (running) { server_wait(s); } printf("Shutting down...\n"); fflush(stdout); server_close(s); server_destroy(s); return 0; }
int main(int argc, char *argv[]) { int type, chans; RadioDevice *usrp; RadioInterface *radio = NULL; Transceiver *trx = NULL; struct trx_config config; handle_options(argc, argv, &config); setup_signal_handlers(); /* Check database sanity */ if (!trx_setup_config(&config)) { std::cerr << "Config: Database failure - exiting" << std::endl; return EXIT_FAILURE; } gLogInit("transceiver", config.log_level.c_str(), LOG_LOCAL7); srandom(time(NULL)); /* Create the low level device object */ usrp = RadioDevice::make(config.sps, config.chans, config.diversity, config.offset); type = usrp->open(config.dev_args, config.extref, config.swap_channels); if (type < 0) { LOG(ALERT) << "Failed to create radio device" << std::endl; goto shutdown; } /* Setup the appropriate device interface */ radio = makeRadioInterface(&config, usrp, type); if (!radio) goto shutdown; /* Create the transceiver core */ trx = makeTransceiver(&config, radio); if (!trx) goto shutdown; chans = trx->numChans(); std::cout << "-- Transceiver active with " << chans << " channel(s)" << std::endl; while (!gshutdown) sleep(1); shutdown: std::cout << "Shutting down transceiver..." << std::endl; delete trx; delete radio; delete usrp; return 0; }
int main(int argc, char **argv) { int cf_index; Octstr *filename, *version; gwlib_init(); list_dict = dict_create(32, msg_list_destroy_item); cf_index = get_and_set_debugs(argc, argv, check_args); setup_signal_handlers(); if (argv[cf_index] == NULL) filename = octstr_create("httpClient.conf"); else filename = octstr_create(argv[cf_index]); cfg = cfg_create(filename); /* Adding cfg-checks to core */ cfg_add_hooks(smppbox_is_allowed_in_group, smppbox_is_single_group); if (cfg_read(cfg) == -1) panic(0, "Couldn't read configuration from `%s'.", octstr_get_cstr(filename)); octstr_destroy(filename); version = octstr_format("httpClient version %s gwlib", GW_VERSION); report_versions(octstr_get_cstr(version)); octstr_destroy(version); struct server_type *res = NULL; res = sqlbox_init_mysql(cfg); sqlbox_configure_mysql(cfg); init_smpp_server_box(cfg); http_client_box_run(); //gwthread_join_every(sql_to_smpp); //gwthread_join_every(smpp_to_sql); smpp_server_box_shutdown(); dict_destroy(list_dict); list_dict = NULL; cfg_destroy(cfg); if (restart_httpbox) { gwthread_sleep(1.0); } gw_smpp_leave(); gwlib_shutdown(); if (restart_httpbox) execvp(argv[0], argv); return 0; }
/*---------------------------------------------------------------------+ | setup () | | ==================================================================== | | | | Function: Parse the command line arguments & initialize global | | variables. | | | | Updates: (command line options) | | | | [-n] non_blocking_flag: prevents read & write calls from | | from blocking if the resource is not available. | | | | [-p] num_packets: number of packets ... | | | | [-c] num_children: number of child processes to spawn ... | | | +---------------------------------------------------------------------*/ void setup (int argc, char **argv) { int i; int errflag = 0; int bytes = 0, megabytes = 0; char *program_name = *argv; extern char *optarg; /* Command line option */ while ((i = getopt(argc, argv, "nm:b:p:?")) != EOF) { switch (i) { case 'n': /* NON-BLOCKING flag */ non_blocking_flag++; break; case 'm': /* MB */ mflg++; megabytes = atoi (optarg); break; case 'b': /* bytes */ bflg++; bytes = atoi (optarg); break; case 'p': /* number of child procs */ num_children = atoi (optarg); break; case '?': errflag++; break; } } if (mflg) { num_packets = megabytes * MB / sizeof (struct data_packet); } else if (bflg) { num_packets = bytes / sizeof (struct data_packet); } if (num_packets == 0 || num_children == 0 || num_children > MAXCHILD) errflag++; if (errflag) { fprintf (stderr, USAGE, program_name, MAXCHILD); exit (2); } /* * Setup signal catching function for SIGPIPE & SIGINT, record * the process id of the parent and initialize the child process * id array. */ setup_signal_handlers (); parent_pid = getpid (); for (i=0; i<num_children; i++) { pid [i] = (pid_t)0; } }
void Terminal::Initialize(){ if(init){ return; } original = std::cout.rdbuf(); // Back-up cout's streambuf pbuf = stream.rdbuf(); // Get stream's streambuf std::cout.flush(); std::cout.rdbuf(pbuf); // Assign streambuf to cout main = initscr(); if(main == NULL ){ // Attempt to initialize ncurses std::cout.rdbuf(original); // Restore cout's original streambuf fprintf(stderr, " Error: failed to initialize ncurses!\n"); } else{ getmaxyx(stdscr, _winSizeY, _winSizeX); output_window = newpad(_scrollbackBufferSize, _winSizeX); input_window = newpad(1, _winSizeX); wmove(output_window, _scrollbackBufferSize-1, 0); // Set the output cursor at the bottom so that new text will scroll up if (halfdelay(5) == ERR) { // Timeout after 5/10 of a second std::cout << "WARNING: Unable to set terminal blocking half delay to 0.5s!\n"; std::cout << "\tThis will increase CPU usage in the command thread.\n"; if (nodelay(input_window, true) == ERR) { //Disable the blocking timeout. std::cout << "ERROR: Unable to remove terminal blocking!\n"; std::cout << "\tThe command thread will be locked until a character is entered. This will reduce functionality of terminal status bar and timeout.\n"; } } keypad(input_window, true); // Capture special keys noecho(); // Turn key echoing off scrollok(output_window, true); scrollok(input_window, true); if (NCURSES_MOUSE_VERSION > 0) { mousemask(ALL_MOUSE_EVENTS,NULL); mouseinterval(0); } init = true; offset = 0; // Set the position of the physical cursor cursX = 0; cursY = _winSizeY-1; update_cursor_(); refresh_(); init_colors_(); } setup_signal_handlers(); }
int main(int argc, char **argv) { struct timeval timeout; fd_set readfds; handle_cmd_line(argc, argv); in = dup(0); out = dup(1); terminal = open(terminal_device, O_RDWR | O_NOCTTY | O_NONBLOCK); if (terminal == -1) { perror("Failed to open terminal"); exit(3); } configure_terminal(speed); configure_input(); setup_signal_handlers(); escape_state = 0; for (;;) { FD_ZERO(&readfds); FD_SET(terminal, &readfds); FD_SET(in, &readfds); timeout.tv_sec = 0; timeout.tv_usec = 500000; if (select(FD_SETSIZE, &readfds, NULL, NULL, &timeout) == -1) { break; } else { if (FD_ISSET(terminal, &readfds) && transfer_from_terminal() == false) break; if (FD_ISSET(in, &readfds) && transfer_to_terminal() == false) break; } } unconfigure_input(); if (opt_reset) write(out, RESET_SEQUENCE, sizeof(RESET_SEQUENCE)); close(terminal); close(in); close(out); return 0; }
void Terminal::Initialize(){ if(init){ return; } original = std::cout.rdbuf(); // Back-up cout's streambuf pbuf = stream.rdbuf(); // Get stream's streambuf std::cout.flush(); std::cout.rdbuf(pbuf); // Assign streambuf to cout main = initscr(); if(main == NULL ){ // Attempt to initialize ncurses std::cout.rdbuf(original); // Restore cout's original streambuf fprintf(stderr, " Error: failed to initialize ncurses!\n"); } else{ getmaxyx(stdscr, _winSizeY, _winSizeX); output_window = newpad(_scrollbackBufferSize, _winSizeX); input_window = newpad(1, _winSizeX); wmove(output_window, _scrollbackBufferSize-1, 0); // Set the output cursor at the bottom so that new text will scroll up halfdelay(5); // Timeout after 5/10 of a second keypad(input_window, true); // Capture special keys noecho(); // Turn key echoing off scrollok(output_window, true); scrollok(input_window, true); if (NCURSES_MOUSE_VERSION > 0) { mousemask(ALL_MOUSE_EVENTS,NULL); mouseinterval(0); } init = true; text_length = 0; offset = 0; // Set the position of the physical cursor cursX = 0; cursY = _winSizeY-1; update_cursor_(); refresh_(); init_colors_(); } setup_signal_handlers(); }
static void initial_setup() { #ifdef OPENWRT OOR_LOG(LINF,"Open Overlay Router %s compiled for openWRT\n", OOR_VERSION); #else #ifdef ANDROID #ifdef VPNAPI OOR_LOG(LINF,"Open Overlay Router %s compiled for not rooted Android\n", OOR_VERSION); #else OOR_LOG(LINF,"Open Overlay Router %s compiled for rooted Android\n", OOR_VERSION); #endif #else OOR_LOG(LINF,"Open Overlay Router %s compiled for Linux\n", OOR_VERSION); #endif #endif #if UINTPTR_MAX == 0xffffffff OOR_LOG(LDBG_1,"x32 system"); #elif UINTPTR_MAX == 0xffffffffffffffff OOR_LOG(LDBG_1,"x64 system"); #else OOR_LOG(LERR,"Unknow system. Please contact the Open Overlay Router team providing your hardware"); #endif #ifndef VPNAPI if (check_capabilities() != GOOD){ exit(EXIT_SUCCESS); } if(pid_file_check_not_exist() == BAD){ exit(EXIT_SUCCESS); } pid_file_create(); #endif /* Initialize the random number generator */ iseed = (unsigned int) time(NULL); srandom(iseed); setup_signal_handlers(); /* Initialize hash table that control timers */ nonces_ht = htable_nonces_new(); ptrs_to_timers_ht = htable_ptrs_new(); }
int main(int argc, char **argv) { int cf_index; Octstr *filename; gwlib_init(); cf_index = get_and_set_debugs(argc, argv, check_args); setup_signal_handlers(); if (argv[cf_index] == NULL) { filename = octstr_create("sqlbox.conf"); } else { filename = octstr_create(argv[cf_index]); } cfg = cfg_create(filename); /* Adding cfg-checks to core */ cfg_add_hooks(sqlbox_is_allowed_in_group, sqlbox_is_single_group); if (cfg_read(cfg) == -1) panic(0, "Couldn't read configuration from `%s'.", octstr_get_cstr(filename)); octstr_destroy(filename); report_versions("sqlbox"); init_sqlbox(cfg); sqlboxc_run((void *)sqlbox_port); cfg_destroy(cfg); if (restart_sqlbox) { gwthread_sleep(1.0); } gw_sql_leave(); gwlib_shutdown(); if (restart_sqlbox) execvp(argv[0], argv); return 0; }
int start_sandbox() { install_sandbox_configuration(); DPRINT(DEBUG_INFO, "Start the sandbox enviroment of the %s process\n", sandbox.visibility==PUBLIC ? PUBLIC_STRING : PRIVATE_STRING ); setup_signal_handlers(); DPRINT(DEBUG_INFO, "Signal handler installed\n"); /* Initialize the sytem call table containing the * handler for each function */ initialize_syscall_table(); DPRINT(DEBUG_INFO, "System call table initialized \n"); /*TODO Rewrite VSDO and vsyscall */ // close all file descriptors open so far close_file_descriptors(); // This may be moved to another position, only the trusted // process uses it. /*Get the file descriptor of the mapins */ sandbox.self_maps = open("/proc/self/maps", O_RDONLY, 0); if (sandbox.self_maps < 0) die("Cannot access \"/proc/self/maps\""); /* Create the trusted thread and enter seccomp mode */ if (create_trusted_thread() < 0 ) die("Create trusted thread"); sandbox.status = ENABLE; wait_for_remote_process(); DPRINT(DEBUG_INFO, "Ends Sandbox\n"); return 0; }
static clib_error_t * unix_config (vlib_main_t * vm, unformat_input_t * input) { unix_main_t *um = &unix_main; clib_error_t *error = 0; gid_t gid; int pidfd = -1; /* Defaults */ um->cli_pager_buffer_limit = UNIX_CLI_DEFAULT_PAGER_LIMIT; um->cli_history_limit = UNIX_CLI_DEFAULT_HISTORY; while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT) { char *cli_prompt; if (unformat (input, "interactive")) um->flags |= UNIX_FLAG_INTERACTIVE; else if (unformat (input, "nodaemon")) um->flags |= UNIX_FLAG_NODAEMON; else if (unformat (input, "cli-prompt %s", &cli_prompt)) vlib_unix_cli_set_prompt (cli_prompt); else if (unformat (input, "cli-listen %s", &um->cli_listen_socket.config)) ; else if (unformat (input, "runtime-dir %s", &um->runtime_dir)) ; else if (unformat (input, "cli-line-mode")) um->cli_line_mode = 1; else if (unformat (input, "cli-no-banner")) um->cli_no_banner = 1; else if (unformat (input, "cli-no-pager")) um->cli_no_pager = 1; else if (unformat (input, "poll-sleep-usec %d", &um->poll_sleep_usec)) ; else if (unformat (input, "cli-pager-buffer-limit %d", &um->cli_pager_buffer_limit)) ; else if (unformat (input, "cli-history-limit %d", &um->cli_history_limit)) ; else if (unformat (input, "coredump-size")) { uword coredump_size = 0; if (unformat (input, "unlimited")) { coredump_size = RLIM_INFINITY; } else if (!unformat (input, "%U", unformat_memory_size, &coredump_size)) { return clib_error_return (0, "invalid coredump-size parameter `%U'", format_unformat_error, input); } const struct rlimit new_limit = { coredump_size, coredump_size }; if (0 != setrlimit (RLIMIT_CORE, &new_limit)) { clib_unix_warning ("prlimit() failed"); } } else if (unformat (input, "full-coredump")) { int fd; fd = open ("/proc/self/coredump_filter", O_WRONLY); if (fd >= 0) { if (write (fd, "0x6f\n", 5) != 5) clib_unix_warning ("coredump filter write failed!"); close (fd); } else clib_unix_warning ("couldn't open /proc/self/coredump_filter"); } else if (unformat (input, "startup-config %s", &um->startup_config_filename)) ; else if (unformat (input, "exec %s", &um->startup_config_filename)) ; else if (unformat (input, "log %s", &um->log_filename)) { um->log_fd = open ((char *) um->log_filename, O_CREAT | O_WRONLY | O_APPEND, 0644); if (um->log_fd < 0) { clib_warning ("couldn't open log '%s'\n", um->log_filename); um->log_fd = 0; } else { u8 *lv = 0; lv = format (0, "%U: ***** Start: PID %d *****\n", format_timeval, 0 /* current bat-time */ , 0 /* current bat-format */ , getpid ()); { int rv __attribute__ ((unused)) = write (um->log_fd, lv, vec_len (lv)); } vec_free (lv); } } else if (unformat (input, "gid %U", unformat_unix_gid, &gid)) { if (setegid (gid) == -1) return clib_error_return_unix (0, "setegid"); } else if (unformat (input, "pidfile %s", &um->pidfile)) ; else return clib_error_return (0, "unknown input `%U'", format_unformat_error, input); } if (um->runtime_dir == 0) { uid_t uid = geteuid (); if (uid == 00) um->runtime_dir = format (0, "/run/%s%c", vlib_default_runtime_dir, 0); else um->runtime_dir = format (0, "/run/user/%u/%s%c", uid, vlib_default_runtime_dir, 0); } error = setup_signal_handlers (um); if (error) return error; if (um->pidfile) { if ((error = vlib_unix_validate_runtime_file (um, (char *) um->pidfile, &um->pidfile))) return error; if (((pidfd = open ((char *) um->pidfile, O_CREAT | O_WRONLY | O_TRUNC, 0644)) < 0)) { return clib_error_return_unix (0, "open"); } } if (!(um->flags & UNIX_FLAG_INTERACTIVE)) { openlog (vm->name, LOG_CONS | LOG_PERROR | LOG_PID, LOG_DAEMON); clib_error_register_handler (unix_error_handler, um); if (!(um->flags & UNIX_FLAG_NODAEMON) && daemon ( /* chdir to / */ 0, /* stdin/stdout/stderr -> /dev/null */ 0) < 0) clib_error_return (0, "daemon () fails"); } if (pidfd >= 0) { u8 *lv = format (0, "%d", getpid ()); if (write (pidfd, (char *) lv, vec_len (lv)) != vec_len (lv)) { vec_free (lv); close (pidfd); return clib_error_return_unix (0, "write"); } vec_free (lv); close (pidfd); } um->unix_config_complete = 1; return 0; }
int main(int argc, char* argv[]) { fd_set sel, sel0; int status; int pty_alloc_only = FALSE; char* newarg0; /* SIGINT and SIGBREAK are indistinctive under cygwin environment. */ /* Using Win32API to handle SIGINT. */ SetConsoleCtrlHandler(ctrl_handler, TRUE); if (argc < 1) { fputs("Unable to get arg[0].", stderr); exit(EXIT_FAILURE); } newarg0 = real_command_name(argv[0]); if (newarg0) argv[0] = newarg0; else if (argc >=2) argv++; else pty_alloc_only = TRUE; if (isatty(STDIN_FILENO) && !pty_alloc_only) { execvp(argv[0], argv); fprintf(stderr, "Failed to execute \"%s\": %s\n", argv[0], strerror(errno)); exit(EXIT_FAILURE); } master_fd = open_master_pty(); child_pid = exec_target(master_fd, argv, pty_alloc_only); setup_signal_handlers(); FD_ZERO(&sel0); FD_SET(master_fd, &sel0); FD_SET(STDIN_FILENO, &sel0); /* communication loop */ while (1) { char buf[BUFSIZE]; int ret; if (sig_winch_caught == TRUE) { sig_winch_caught = FALSE; if (child_pid != -1 && resize_tty_window(master_fd, sig_window_size) == 0) kill(child_pid, SIGWINCH); } sel = sel0; if (select (FD_SETSIZE, &sel, NULL, NULL, NULL) <= 0) { if(errno == EINTR) continue; else break; } if (FD_ISSET(master_fd, &sel)) { ret = safe_read(master_fd, buf, BUFSIZE); if (ret > 0) { if (safe_write_full(STDOUT_FILENO, buf, ret) < 0) break; } else break; } else if (FD_ISSET(STDIN_FILENO, &sel)) { ret = safe_read(STDIN_FILENO, buf, BUFSIZE); if (ret > 0) { if (safe_write_full_checking_eof(master_fd, buf, ret) < 0) break; } else { FD_CLR(STDIN_FILENO, &sel0); close(master_fd); } } } if (pty_alloc_only) { kill(child_pid, SIGKILL); status = 0; } else { while(waitpid(child_pid, &status, 0) < 0 && errno == EINTR) ; if (WIFEXITED(status)) status = WEXITSTATUS(status); else if(WIFSIGNALED(status)) /* ntemacs cannot distinct killed by signal */ status = 0x80 + WTERMSIG(status); } return status; }
int driver_to_pipe_main (char* command, ErlDrvEntry* entry) { ErlDrvData d; PollInfo info; char buf[1 << 20]; setup_signal_handlers (); info.fds = driver_alloc (sizeof (struct pollfd)); info.fds[0].fd = 3; info.fds[0].events = POLLIN; info.fds[0].revents = 0; info.nfds = 1; if (entry->init) { entry->init (); } d = entry->start ((void *) &info, command); while (! signalled) { nfds_t i; nfds_t nfds; nfds = info.nfds; for (i = 0; i < nfds; ++i) { info.fds[i].revents = 0; } if (poll (info.fds, nfds, 1000) < 0) { if (errno != EINTR) { const char msg[] = "driver2pipe: bad poll\n"; write (2, msg, sizeof (msg)); goto STOP; } } if (info.fds[0].revents) { ssize_t size; size = read_packet (3, 4, buf, sizeof (buf)); if (size < 0) { goto STOP; } entry->output (d, buf, size); } for (i = 1; i < nfds; ++i) { if (info.fds[i].revents & POLLNVAL) { fprintf (stderr, "fatal: poll got nval (%d) for file descriptor %d " "wanted: %d\n", info.fds[i].revents, info.fds[i].fd, info.fds[i].events); goto STOP; } if (info.fds[i].revents & POLLERR) { fprintf (stderr, "fatal: poll got err (%d) for file descriptor %d " "wanted: %d\n", info.fds[i].revents, info.fds[i].fd, info.fds[i].events); goto STOP; } if (info.fds[i].revents & POLLIN) { entry->ready_input (d, (ErlDrvEvent) (intptr_t) info.fds[i].fd); } if (info.fds[i].revents & POLLOUT) { entry->ready_output (d, (ErlDrvEvent) (intptr_t) info.fds[i].fd); } } } STOP: entry->stop (d); if (entry->finish) { entry->finish (); } driver_free (info.fds); return signalled; }
/*---------------------------------------------------------------------+ | main | | ==================================================================== | | | | Function: Main program (see prolog for more details) | | | | Returns: (0) Successful completion | | (-1) Error occurred | | | +---------------------------------------------------------------------*/ int main(int argc, char **argv) { int fd; /* Misc file descriptor */ int i; /* Misc loop index */ int shmem_size; /* Size (in bytes) of shared memory segment */ int status; /* Child processes exit status */ unsigned char *ptr; /* Misc pointer */ unsigned char data = 0; /* Value written into shared memory segment */ unsigned char *shmptr; /* Shared memory segment address */ unsigned long cksum; /* Shared memory segment checksum */ /* * Parse command line arguments and print out program header */ parse_args(argc, argv); printf("%s: IPC Shared Memory TestSuite program\n", *argv); /* * Setup the signal handlers (in case user aborts program). * * Create the semaphores to insure exclusive writes to the * shared memory segment. * * Save the parent process id and initialize the array of child * process ids. */ setup_signal_handlers(); create_semaphores(); parent_pid = getpid(); for (i = 0; i < num_children; i++) pid[i] = (pid_t) 0; /* * Create a shared memory segment for storing the read count * (number of child processes reading shared data) * After creating the shared memory segment, initialize it. */ if ((fd = open("/dev/zero", O_RDWR)) < 0) sys_error("open failed", __LINE__); if ((read_count = (int *) mmap(0, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)) < 0) sys_error("mmap failed", __LINE__); close(fd); *read_count = 0; /* * Create a shared memory segment for storing the child * processes checksums by memory mapping /dev/zero. * After creating the shared memory segment, initialize it. */ if ((fd = open("/dev/zero", O_RDWR)) < 0) sys_error("open failed", __LINE__); shmem_size = sizeof(unsigned long) * num_children; if ((checksum = (unsigned long *) mmap(0, shmem_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)) < 0) sys_error("mmap failed", __LINE__); close(fd); for (i = 0; i < num_children; i++) *(checksum + (sizeof(unsigned long) * i)) = 0; /* * Create the "scratch" shared memory segment for storing * a series of values by memory mapping /dev/zero. */ if ((fd = open("/dev/zero", O_RDWR)) < 0) sys_error("open failed", __LINE__); printf("\n\tGet shared memory segment (%d bytes)\n", buffer_size); if ((shmptr = mmap(0, buffer_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)) < 0) sys_error("mmap failed", __LINE__); close(fd); /* * Obtain an exclusive "write" lock on the shared memory data * segment -- get lock now to insure the parent process gets * first access to the segment. */ lock_resource(WRITE); /* * Spawn all N child processes. Each child process will compute * the checksum of the shared memory segment and will store * the results in the other shared memory segment accessible * by the parent. */ printf("\n\tSpawning %d child processes ... \n", num_children); for (i = 0; i < num_children; i++) { if ((pid[i] = fork()) == (pid_t) 0) { child(i, shmptr); exit(0); } else if (pid[i] < (pid_t) 0) sys_error("fork failed", __LINE__); } /* * Fill the "scratch" shared memory segment up with data and * compute the segments checksum. Release "write" lock after * completing so that the child processes may begin to read the * data. */ printf("\n\tParent: calculate shared memory segment checksum\n"); cksum = data = 0; for (ptr = shmptr; ptr < (shmptr + buffer_size); ptr++) { *ptr = (data++) % (UCHAR_MAX + 1); cksum += *ptr; } printf("\t shared memory checksum %08lx\n", cksum); unlock_resource(WRITE); /* * Wait for the child processes to compute the checksums and complete. * After the processes complete, check their exit status to insure * that they ran to completion and then verify the corresponding * checksum. */ for (i = 0; i < num_children; i++) { waitpid(pid[i], &status, 0); if (!WIFEXITED(status)) sys_error("child process terminated abnormally", __LINE__); if (cksum != *(checksum + (sizeof(unsigned long) * i))) { printf("checksum [%d] = %08lx\n", i, checksum[i]); error("checksums do not match", __LINE__); } } printf("\n\tParent: children calculated segment successfully\n"); /* * Program completed successfully, cleanup semaphores and exit. */ delete_semaphores(); printf("\nsuccessful!\n"); return (0); }
/*---------------------------------------------------------------------+ | main | | ==================================================================== | | | | Function: Main program (see prolog for more details) | | | | Returns: (0) Successful completion | | (-1) Error occurred | | | +---------------------------------------------------------------------*/ int main (int argc, char **argv) { char *shmptr, /* Shared memory segment address */ value = 0; /* Value written into shared memory segment */ int i; char *ptr; int status; int shmem_size; unsigned long cksum; lockfd = create_lock_file (LOCK_FILE); setup_signal_handlers (); /* * Parse command line arguments and print out program header */ parse_args (argc, argv); printf ("%s: IPC Shared Memory TestSuite program\n", *argv); parent_pid = getpid (); for (i=0; i<num_children; i++) pid [i] = (pid_t)0; /* * Get chunk of shared memory for storing num_children checksum */ shmem_size = sizeof (unsigned long); if ((long)(checksum = (unsigned long *) mmap (0, shmem_size, PROT_READ | PROT_WRITE, MAP_ANON | MAP_SHARED, -1, 0)) < 0) sys_error ("mmap failed", __LINE__); for (i=0; i < num_children; i++) *(checksum + (sizeof (unsigned long) * i)) = 0; /* * Get chunk of memory for writing scratch data */ printf ("\n\tGet shared memory segment (%d bytes)\n", buffer_size); if ((shmptr = mmap (0, buffer_size, PROT_READ | PROT_WRITE, MAP_ANON | MAP_SHARED, -1, 0)) == MAP_FAILED) sys_error ("mmap failed", __LINE__); /* * Parent: * * Fill buffer with data.. */ cksum = value = 0; printf ("\n\tParent: calculate shared memory segment checksum\n"); write_lock (lockfd); for (ptr=shmptr; ptr < (shmptr+buffer_size); ptr++) { *ptr = value++; cksum += *ptr; } unlock_file (lockfd); printf ("\t shared memory checksum %08lx\n", cksum); printf ("\n\tSpawning %d child processes ... \n", num_children); for (i=0; i<num_children; i++) { if ((pid [i] = fork()) == (pid_t)0) { child (i, shmptr); exit (0); } else if (pid [i] < (pid_t)0) sys_error ("fork failed", __LINE__); } /* * Wait for child processes to compute checksum and complete... */ for (i=0; i<num_children; i++) { waitpid (pid [i], &status, 0); if (!WIFEXITED (status)) sys_error ("child process terminated abnormally", __LINE__); if (cksum != *(checksum + (sizeof (unsigned long) * i))) { printf ("checksum [%d] = %08lx\n", i, checksum [i]); error ("checksums do not match", __LINE__); } } printf ("\n\tParent: children calculated segment successfully\n"); /* * Program completed successfully -- exit */ printf ("\nsuccessful!\n"); return (0); }
int main (int argc, char **argv) { int quit = 0; #if defined(__GLIBC__) setup_signal_handlers (); #endif /* command line/config options */ verify_global_config (argc, argv); parse_conf_file (&argc, &argv); parse_cmd_line (argc, argv); /* initialize storage */ init_storage (); /* setup to use the current locale */ set_locale (); #ifdef HAVE_LIBGEOIP init_geoip (); #endif /* init logger */ logger = init_log (); set_signal_data (logger); /* init parsing spinner */ parsing_spinner = new_gspinner (); parsing_spinner->process = &logger->process; /* outputting to stdout */ if (conf.output_html) { ui_spinner_create (parsing_spinner); goto out; } /* init curses */ set_input_opts (); if (conf.no_color || has_colors () == FALSE) { conf.color_scheme = NO_COLOR; conf.no_color = 1; } else { start_color (); } init_colors (); init_windows (&header_win, &main_win); set_curses_spinner (parsing_spinner); /* configuration dialog */ if (isatty (STDIN_FILENO) && (conf.log_format == NULL || conf.load_conf_dlg)) { refresh (); quit = render_confdlg (logger, parsing_spinner); } /* straight parsing */ else { ui_spinner_create (parsing_spinner); } out: /* main processing event */ time (&start_proc); if (conf.load_from_disk) set_general_stats (); else if (!quit && parse_log (&logger, NULL, -1)) FATAL ("Error while processing file"); logger->offset = logger->process; /* no valid entries to process from the log */ if (logger->process == 0) FATAL ("Nothing valid to process."); /* init reverse lookup thread */ gdns_init (); parse_initial_sort (); allocate_holder (); end_spinner (); time (&end_proc); /* stdout */ if (conf.output_html) standard_output (); /* curses */ else curses_output (); /* clean */ house_keeping (); return EXIT_SUCCESS; }
int main(int argc, char **argv) { krb5_error_code retval; krb5_context kcontext; int errout = 0; krb5_boolean log_stderr_set; (void) setlocale(LC_ALL, ""); #if !defined(TEXT_DOMAIN) /* Should be defined by cc -D */ #define TEXT_DOMAIN "KRB5KDC_TEST" /* Use this only if it weren't */ #endif (void) textdomain(TEXT_DOMAIN); if (strrchr(argv[0], '/')) argv[0] = strrchr(argv[0], '/')+1; if (!(kdc_realmlist = (kdc_realm_t **) malloc(sizeof(kdc_realm_t *) * KRB5_KDC_MAX_REALMS))) { fprintf(stderr, gettext("%s: cannot get memory for realm list\n"), argv[0]); exit(1); } memset((char *) kdc_realmlist, 0, (size_t) (sizeof(kdc_realm_t *) * KRB5_KDC_MAX_REALMS)); /* * A note about Kerberos contexts: This context, "kcontext", is used * for the KDC operations, i.e. setup, network connection and error * reporting. The per-realm operations use the "realm_context" * associated with each realm. */ retval = krb5int_init_context_kdc(&kcontext); if (retval) { com_err(argv[0], retval, gettext("while initializing krb5")); exit(1); } krb5_klog_init(kcontext, "kdc", argv[0], 1); /* * Solaris Kerberos: * In the early stages of krb5kdc it is desirable to log error messages * to stderr as well as any other logging locations specified in config * files. */ log_stderr_set = krb5_klog_logging_to_stderr(); if (log_stderr_set != TRUE) { krb5_klog_add_stderr(); } /* initialize_kdc5_error_table(); SUNWresync121 XXX */ /* * Scan through the argument list */ initialize_realms(kcontext, argc, argv); setup_signal_handlers(); load_preauth_plugins(kcontext); retval = setup_sam(); if (retval) { com_err(argv[0], retval, gettext("while initializing SAM")); finish_realms(argv[0]); return 1; } if ((retval = setup_network(argv[0]))) { com_err(argv[0], retval, gettext("while initializing network")); finish_realms(argv[0]); return 1; } /* Solaris Kerberos: Remove the extra stderr logging */ if (log_stderr_set != TRUE) krb5_klog_remove_stderr(); /* * Solaris Kerberos: * List the logs (FILE, STDERR, etc) which are currently being * logged to and print that to stderr. Useful when trying to * track down a failure via SMF. */ if (retval = krb5_klog_list_logs(argv[0])) { com_err(argv[0], retval, gettext("while listing logs")); if (log_stderr_set != TRUE) { fprintf(stderr, gettext("%s: %s while listing logs\n"), argv[0], error_message(retval)); } } if (!nofork && daemon(0, 0)) { com_err(argv[0], errno, gettext("while detaching from tty")); if (log_stderr_set != TRUE) { fprintf(stderr, gettext("%s: %s while detaching from tty\n"), argv[0], strerror(errno)); } finish_realms(argv[0]); return 1; } if (retval = krb5_klog_syslog(LOG_INFO, "commencing operation")) { com_err(argv[0], retval, gettext("while logging message")); errout++; }; if ((retval = listen_and_process(argv[0]))) { com_err(argv[0], retval, gettext("while processing network requests")); errout++; } if ((retval = closedown_network(argv[0]))) { com_err(argv[0], retval, gettext("while shutting down network")); errout++; } krb5_klog_syslog(LOG_INFO, "shutting down"); unload_preauth_plugins(kcontext); krb5_klog_close(kdc_context); finish_realms(argv[0]); if (kdc_realmlist) free(kdc_realmlist); #ifdef USE_RCACHE (void) krb5_rc_close(kcontext, kdc_rcache); #endif #ifndef NOCACHE kdc_free_lookaside(kcontext); #endif krb5_free_context(kcontext); return errout; }
static Cfg *init_bearerbox(Cfg *cfg) { CfgGroup *grp; Octstr *log, *val; long loglevel, store_dump_freq, value; int lf, m; #ifdef HAVE_LIBSSL Octstr *ssl_server_cert_file; Octstr *ssl_server_key_file; int ssl_enabled = 0; #endif /* HAVE_LIBSSL */ Octstr *http_proxy_host = NULL; long http_proxy_port = -1; int http_proxy_ssl = 0; List *http_proxy_exceptions = NULL; Octstr *http_proxy_username = NULL; Octstr *http_proxy_password = NULL; Octstr *http_proxy_exceptions_regex = NULL; /* defaults: use localtime and markers for access-log */ lf = m = 1; grp = cfg_get_single_group(cfg, octstr_imm("core")); log = cfg_get(grp, octstr_imm("log-file")); if (log != NULL) { if (cfg_get_integer(&loglevel, grp, octstr_imm("log-level")) == -1) loglevel = 0; log_open(octstr_get_cstr(log), loglevel, GW_NON_EXCL); octstr_destroy(log); } if ((val = cfg_get(grp, octstr_imm("syslog-level"))) != NULL) { long level; Octstr *facility; if ((facility = cfg_get(grp, octstr_imm("syslog-facility"))) != NULL) { log_set_syslog_facility(octstr_get_cstr(facility)); octstr_destroy(facility); } if (octstr_compare(val, octstr_imm("none")) == 0) { log_set_syslog(NULL, 0); } else if (octstr_parse_long(&level, val, 0, 10) > 0) { log_set_syslog("bearerbox", level); } octstr_destroy(val); } else { log_set_syslog(NULL, 0); } if (check_config(cfg) == -1) panic(0, "Cannot start with corrupted configuration"); /* determine which timezone we use for access logging */ if ((log = cfg_get(grp, octstr_imm("access-log-time"))) != NULL) { lf = (octstr_case_compare(log, octstr_imm("gmt")) == 0) ? 0 : 1; octstr_destroy(log); } /* should predefined markers be used, ie. prefixing timestamp */ cfg_get_bool(&m, grp, octstr_imm("access-log-clean")); /* custom access-log format */ if ((log = cfg_get(grp, octstr_imm("access-log-format"))) != NULL) { bb_alog_init(log); octstr_destroy(log); } /* open access-log file */ if ((log = cfg_get(grp, octstr_imm("access-log"))) != NULL) { alog_open(octstr_get_cstr(log), lf, m ? 0 : 1); octstr_destroy(log); } if (cfg_get_integer(&store_dump_freq, grp, octstr_imm("store-dump-freq")) == -1) store_dump_freq = -1; log = cfg_get(grp, octstr_imm("store-file")); /* initialize the store file */ if (log != NULL) { warning(0, "'store-file' option deprecated, please use 'store-location' and 'store-type' instead."); val = octstr_create("file"); } else { log = cfg_get(grp, octstr_imm("store-location")); val = cfg_get(grp, octstr_imm("store-type")); } if (store_init(val, log, store_dump_freq, msg_pack, msg_unpack_wrapper) == -1) panic(0, "Could not start with store init failed."); octstr_destroy(val); octstr_destroy(log); cfg_get_integer(&http_proxy_port, grp, octstr_imm("http-proxy-port")); #ifdef HAVE_LIBSSL cfg_get_bool(&http_proxy_ssl, grp, octstr_imm("http-proxy-ssl")); #endif /* HAVE_LIBSSL */ http_proxy_host = cfg_get(grp, octstr_imm("http-proxy-host")); http_proxy_username = cfg_get(grp, octstr_imm("http-proxy-username")); http_proxy_password = cfg_get(grp, octstr_imm("http-proxy-password")); http_proxy_exceptions = cfg_get_list(grp, octstr_imm("http-proxy-exceptions")); http_proxy_exceptions_regex = cfg_get(grp, octstr_imm("http-proxy-exceptions-regex")); conn_config_ssl (grp); /* * Make sure we have "ssl-server-cert-file" and "ssl-server-key-file" specified * in the core group since we need it to run SSL-enabled internal box * connections configured via "smsbox-port-ssl = yes" and "wapbox-port-ssl = yes". * Check only these, because for "admin-port-ssl" and "sendsms-port-ssl" for the * SSL-enabled HTTP servers are probed within gw/bb_http.c:httpadmin_start() */ #ifdef HAVE_LIBSSL ssl_server_cert_file = cfg_get(grp, octstr_imm("ssl-server-cert-file")); ssl_server_key_file = cfg_get(grp, octstr_imm("ssl-server-key-file")); if (ssl_server_cert_file != NULL && ssl_server_key_file != NULL) { /* we are fine, at least files are specified in the configuration */ } else { cfg_get_bool(&ssl_enabled, grp, octstr_imm("smsbox-port-ssl")); cfg_get_bool(&ssl_enabled, grp, octstr_imm("wapbox-port-ssl")); if (ssl_enabled) { panic(0, "You MUST specify cert and key files within core group for SSL-enabled inter-box connections!"); } } octstr_destroy(ssl_server_cert_file); octstr_destroy(ssl_server_key_file); #endif /* HAVE_LIBSSL */ /* if all seems to be OK by the first glimpse, real start-up */ outgoing_sms = gwlist_create(); incoming_sms = gwlist_create(); outgoing_wdp = gwlist_create(); incoming_wdp = gwlist_create(); outgoing_sms_counter = counter_create(); incoming_sms_counter = counter_create(); incoming_dlr_counter = counter_create(); outgoing_dlr_counter = counter_create(); outgoing_wdp_counter = counter_create(); incoming_wdp_counter = counter_create(); status_mutex = mutex_create(); outgoing_sms_load = load_create(); /* add 60,300,-1 entries */ load_add_interval(outgoing_sms_load, 60); load_add_interval(outgoing_sms_load, 300); load_add_interval(outgoing_sms_load, -1); incoming_sms_load = load_create(); /* add 60,300,-1 entries */ load_add_interval(incoming_sms_load, 60); load_add_interval(incoming_sms_load, 300); load_add_interval(incoming_sms_load, -1); incoming_dlr_load = load_create(); /* add 60,300,-1 entries to dlr */ load_add_interval(incoming_dlr_load, 60); load_add_interval(incoming_dlr_load, 300); load_add_interval(incoming_dlr_load, -1); outgoing_dlr_load = load_create(); /* add 60,300,-1 entries to dlr */ load_add_interval(outgoing_dlr_load, 60); load_add_interval(outgoing_dlr_load, 300); load_add_interval(outgoing_dlr_load, -1); setup_signal_handlers(); /* http-admin is REQUIRED */ httpadmin_start(cfg); if (cfg_get_integer(&max_incoming_sms_qlength, grp, octstr_imm("maximum-queue-length")) == -1) max_incoming_sms_qlength = -1; else { warning(0, "Option 'maximum-queue-length' is deprecated! Please use" " 'sms-incoming-queue-limit' instead!"); } if (max_incoming_sms_qlength == -1 && cfg_get_integer(&max_incoming_sms_qlength, grp, octstr_imm("sms-incoming-queue-limit")) == -1) max_incoming_sms_qlength = -1; if (cfg_get_integer(&max_outgoing_sms_qlength, grp, octstr_imm("sms-outgoing-queue-limit")) == -1) max_outgoing_sms_qlength = -1; if (max_outgoing_sms_qlength < 0) max_outgoing_sms_qlength = DEFAULT_OUTGOING_SMS_QLENGTH; if (cfg_get_integer(&value, grp, octstr_imm("http-timeout")) == 0) http_set_client_timeout(value); #ifndef NO_SMS { List *list; list = cfg_get_multi_group(cfg, octstr_imm("smsc")); if (list != NULL) { gwlist_destroy(list, NULL); if (start_smsc(cfg) == -1) { panic(0, "Unable to start SMSCs."); return NULL; } } } #endif #ifndef NO_WAP grp = cfg_get_single_group(cfg, octstr_imm("core")); val = cfg_get(grp, octstr_imm("wdp-interface-name")); if (val != NULL && octstr_len(val) > 0) start_udp(cfg); octstr_destroy(val); if (cfg_get_single_group(cfg, octstr_imm("wapbox")) != NULL) start_wap(cfg); #endif if (http_proxy_host != NULL && http_proxy_port > 0) { http_use_proxy(http_proxy_host, http_proxy_port, http_proxy_ssl, http_proxy_exceptions, http_proxy_username, http_proxy_password, http_proxy_exceptions_regex); } octstr_destroy(http_proxy_host); octstr_destroy(http_proxy_username); octstr_destroy(http_proxy_password); octstr_destroy(http_proxy_exceptions_regex); gwlist_destroy(http_proxy_exceptions, octstr_destroy_item); return cfg; }
int main_loop() { struct hub_config configuration; struct acl_handle acl; struct hub_info* hub = 0; if (net_initialize() == -1) return -1; do { if (hub) { LOG_INFO("Reloading configuration files..."); LOG_DEBUG("Hub status: %d", (int) hub->status); /* Reinitialize logs */ hub_log_shutdown(); hub_log_initialize(arg_log, arg_log_syslog); hub_set_log_verbosity(arg_verbose); } if (read_config(arg_config, &configuration, !arg_have_config) == -1) return -1; if (acl_initialize(&configuration, &acl) == -1) return -1; /* * Don't restart networking when re-reading configuration. * This might not be possible either, since we might have * dropped our privileges to do so. */ if (!hub) { hub = hub_start_service(&configuration); if (!hub) { acl_shutdown(&acl); free_config(&configuration); net_destroy(); hub_log_shutdown(); return -1; } #if !defined(WIN32) setup_signal_handlers(hub); #ifdef SYSTEMD /* Notify the service manager that this daemon has * been successfully initalized and shall enter the * main loop. */ sd_notifyf(0, "READY=1\n" "MAINPID=%lu", (unsigned long) getpid()); #endif /* SYSTEMD */ #endif /* ! WIN32 */ } hub_set_variables(hub, &acl); hub_event_loop(hub); hub_free_variables(hub); acl_shutdown(&acl); free_config(&configuration); } while (hub->status == hub_status_restart); #if !defined(WIN32) shutdown_signal_handlers(hub); #endif if (hub) { hub_shutdown_service(hub); } net_destroy(); hub_log_shutdown(); return 0; }
int main(int argc, char **argv) { int result = 0; int i; userui_ops[0] = &userui_text_ops; userui_ops[1] = FBSPLASH_OPS; userui_ops[2] = USPLASH_OPS; active_ops = &userui_text_ops; handle_params(argc, argv); setup_signal_handlers(); open_console(); open_misc(); if (!test_run) { open_netlink(); get_nofreeze(); get_info(); } lock_memory(); prepare_console(); /* Initialise all that we can, use the first */ // active_ops = NULL; for (i = 0; i < NUM_UIS; i++) { if (userui_ops[i] && userui_ops[i]->load) { result = userui_ops[i]->load(); if (result) { if (test_run) fprintf(stderr, "Failed to initialise %s module.\n", userui_ops[i]->name); else printk("Failed to initialise %s module.\n", userui_ops[i]->name); } else if (!active_ops) active_ops = userui_ops[i]; } } if (active_ops->prepare) active_ops->prepare(); register_keypress_handler(); need_cleanup = 1; running = 1; result = nice(1); if (active_ops->memory_required) reserve_memory(active_ops->memory_required()); else reserve_memory(4*1024*1024); /* say 4MB */ enforce_lifesavers(); if (test_run) { safe_to_exit = 0; do_test_run(); return 0; } if (send_ready()) message_loop(); /* The only point we ever reach here is if message_loop crashed out. * If this is the case, we should spin for a few hours before exiting to * ensure that we don't corrupt stuff on disk (if we're past the atomic * copy). */ sleep(60*60*1); /* 1 hours */ _exit(1); }
int main(int argc, char **argv) { int cf_index; int restart = 0; Msg *msg; Cfg *cfg; double heartbeat_freq = DEFAULT_HEARTBEAT; gwlib_init(); cf_index = get_and_set_debugs(argc, argv, NULL); setup_signal_handlers(); if (argv[cf_index] == NULL) config_filename = octstr_create("kannel.conf"); else config_filename = octstr_create(argv[cf_index]); cfg = cfg_create(config_filename); if (cfg_read(cfg) == -1) panic(0, "Couldn't read configuration from `%s'.", octstr_get_cstr(config_filename)); report_versions("wapbox"); cfg = init_wapbox(cfg); info(0, "------------------------------------------------------------"); info(0, GW_NAME " wapbox version %s starting up.", GW_VERSION); sequence_counter = counter_create(); wsp_session_init(&wtp_resp_dispatch_event, &wtp_initiator_dispatch_event, &wap_appl_dispatch, &wap_push_ppg_dispatch_event); wsp_unit_init(&dispatch_datagram, &wap_appl_dispatch); wsp_push_client_init(&wsp_push_client_dispatch_event, &wtp_resp_dispatch_event); if (cfg) wtp_initiator_init(&dispatch_datagram, &wsp_session_dispatch_event, timer_freq); wtp_resp_init(&dispatch_datagram, &wsp_session_dispatch_event, &wsp_push_client_dispatch_event, timer_freq); wap_appl_init(cfg); #if (HAVE_WTLS_OPENSSL) wtls_secmgr_init(); wtls_init(&write_to_bearerbox); #endif if (cfg) { wap_push_ota_init(&wsp_session_dispatch_event, &wsp_unit_dispatch_event); wap_push_ppg_init(&wap_push_ota_dispatch_event, &wap_appl_dispatch, cfg); } wml_init(wml_xml_strict); if (bearerbox_host == NULL) bearerbox_host = octstr_create(BB_DEFAULT_HOST); connect_to_bearerbox(bearerbox_host, bearerbox_port, bearerbox_ssl, NULL /* bearerbox_our_port */); if (cfg) wap_push_ota_bb_address_set(bearerbox_host); program_status = running; if (0 > heartbeat_start(write_to_bearerbox, heartbeat_freq, wap_appl_get_load)) { info(0, GW_NAME "Could not start heartbeat."); } while (program_status != shutting_down) { WAPEvent *dgram; int ret; /* block infinite for reading messages */ ret = read_from_bearerbox(&msg, INFINITE_TIME); if (ret == -1) { error(0, "Bearerbox is gone, restarting"); program_status = shutting_down; restart = 1; break; } else if (ret == 1) /* timeout */ continue; else if (msg == NULL) /* just to be sure, may not happens */ break; if (msg_type(msg) == admin) { if (msg->admin.command == cmd_shutdown) { info(0, "Bearerbox told us to die"); program_status = shutting_down; } else if (msg->admin.command == cmd_restart) { info(0, "Bearerbox told us to restart"); restart = 1; program_status = shutting_down; } /* * XXXX here should be suspend/resume, add RSN */ } else if (msg_type(msg) == wdp_datagram) { switch (msg->wdp_datagram.destination_port) { case CONNECTIONLESS_PORT: case CONNECTION_ORIENTED_PORT: dgram = wap_event_create(T_DUnitdata_Ind); dgram->u.T_DUnitdata_Ind.addr_tuple = wap_addr_tuple_create( msg->wdp_datagram.source_address, msg->wdp_datagram.source_port, msg->wdp_datagram.destination_address, msg->wdp_datagram.destination_port); dgram->u.T_DUnitdata_Ind.user_data = msg->wdp_datagram.user_data; msg->wdp_datagram.user_data = NULL; wap_dispatch_datagram(dgram); break; case WTLS_CONNECTIONLESS_PORT: case WTLS_CONNECTION_ORIENTED_PORT: #if (HAVE_WTLS_OPENSSL) dgram = wtls_unpack_wdp_datagram(msg); if (dgram != NULL) wtls_dispatch_event(dgram); #endif break; default: panic(0,"Bad packet received! This shouldn't happen!"); break; } } else { warning(0, "Received other message than wdp/admin, ignoring!"); } msg_destroy(msg); } info(0, GW_NAME " wapbox terminating."); program_status = shutting_down; heartbeat_stop(ALL_HEARTBEATS); counter_destroy(sequence_counter); if (cfg) wtp_initiator_shutdown(); wtp_resp_shutdown(); wsp_push_client_shutdown(); wsp_unit_shutdown(); wsp_session_shutdown(); wap_appl_shutdown(); radius_acct_shutdown(); if (cfg) { wap_push_ota_shutdown(); wap_push_ppg_shutdown(); } wml_shutdown(); close_connection_to_bearerbox(); alog_close(); wap_map_destroy(); wap_map_user_destroy(); octstr_destroy(device_home); octstr_destroy(bearerbox_host); octstr_destroy(config_filename); /* * Just sleep for a while to get bearerbox chance to restart. * Otherwise we will fail while trying to connect to bearerbox! */ if (restart) { gwthread_sleep(10.0); /* now really restart */ restart_box(argv); } log_close_all(); gwlib_shutdown(); return 0; }
/* The main program. */ int main(int argc, char **argv) { Connection *server; Octstr *line; Octstr **msgs; int i; int mptr, num_msgs; long num_received, num_sent; double first_received_at, last_received_at; double first_sent_at, last_sent_at; double start_time, end_time; double delta; int interactive, maxfd; char *cptr; char buffer[IN_BUFSIZE]; fd_set rset; struct timeval alarm; FILE *fp; gwlib_init(); setup_signal_handlers(); host = octstr_create("localhost"); start_time = get_current_time(); mptr = get_and_set_debugs(argc, argv, check_args); num_msgs = argc - mptr; interactive = 0; msgs = NULL; fp = NULL; if (num_msgs <= 0) { interactive = 1; num_msgs = 0; info(0, "Entering interactive mode. Type your message on the command line"); /* set up file pointer to stdin */ fp = stdin; /* initialize set for select */ FD_ZERO(&rset); } else { msgs = gw_malloc(sizeof(Octstr *) * num_msgs); for (i = 0; i < num_msgs; i ++) { msgs[i] = octstr_create(argv[mptr + i]); octstr_append_char(msgs[i], 10); /* End of line */ } info(0, "Host %s Port %d interval %.3f max-messages %ld", octstr_get_cstr(host), port, interval, max_send); srand((unsigned int) time(NULL)); } info(0, "fakesmsc starting"); server = conn_open_tcp(host, port, NULL); if (server == NULL) panic(0, "Failed to open connection"); num_sent = 0; num_received = 0; first_received_at = 0; first_sent_at = 0; last_received_at = 0; last_sent_at = 0; /* infinitely loop */ while (1) { /* Are we on interactive mode? */ if (interactive == 1) { /* Check if we need to clean things up beforehand */ if ( num_msgs > 0 ) { for (i = 0; i < num_msgs; i ++) octstr_destroy(msgs[i]); gw_free(msgs); num_msgs = 0; } /* we want either the file pointer or timer */ FD_SET(fileno(fp), &rset); /* get the largest file descriptor */ maxfd = fileno(fp) + 1; /* set timer to go off in 3 seconds */ alarm.tv_sec = IN_TIMEOUT; alarm.tv_usec = 0; if (select(maxfd, &rset, NULL, NULL, &alarm) == -1) goto over; /* something went off, let's see if it's stdin */ if (FD_ISSET(fileno(fp), &rset)) { /* stdin is readable */ cptr = fgets(buffer, IN_BUFSIZE, stdin); if( strlen( cptr ) < 2 ) goto rcv; } else { /* timer kicked in */ goto rcv; } num_msgs = 1; msgs = gw_malloc(sizeof(Octstr*)); msgs[0] = octstr_create(cptr); } /* if we still have something to send as MO message */ if (num_sent < max_send) { Octstr *os = choose_message(msgs, num_msgs); Octstr *msg = rnd > 0 ? randomize(os) : os; if (conn_write(server, msg) == -1) panic(0, "write failed"); ++num_sent; if (num_sent == max_send) info(0, "fakesmsc: sent message %ld", num_sent); else debug("send", 0, "fakesmsc: sent message %ld", num_sent); if (rnd > 0) octstr_destroy(msg); last_sent_at = get_current_time(); if (first_sent_at == 0) first_sent_at = last_sent_at; } rcv: do { delta = interval * num_sent - (get_current_time() - first_sent_at); if (delta < 0) delta = 0; if (num_sent >= max_send) delta = -1; conn_wait(server, delta); if (conn_error(server) || conn_eof(server) || sigint_received) goto over; /* read as much as the smsc module provides us */ while ((line = conn_read_line(server))) { last_received_at = get_current_time(); if (first_received_at == 0) first_received_at = last_received_at; ++num_received; if (num_received == max_send) { info(0, "Got message %ld: <%s>", num_received, octstr_get_cstr(line)); } else { debug("receive", 0, "Got message %ld: <%s>", num_received, octstr_get_cstr(line)); } octstr_destroy(line); } } while (delta > 0 || num_sent >= max_send); } over: conn_destroy(server); /* destroy the MO messages */ for (i = 0; i < num_msgs; i ++) octstr_destroy(msgs[i]); gw_free(msgs); end_time = get_current_time(); info(0, "fakesmsc: %ld messages sent and %ld received", num_sent, num_received); info(0, "fakesmsc: total running time %.1f seconds", end_time - start_time); delta = last_sent_at - first_sent_at; if (delta == 0) delta = .01; if (num_sent > 1) info(0, "fakesmsc: from first to last sent message %.1f s, " "%.1f msgs/s", delta, (num_sent - 1) / delta); delta = last_received_at - first_received_at; if (delta == 0) delta = .01; if (num_received > 1) info(0, "fakesmsc: from first to last received message %.1f s, " "%.1f msgs/s", delta, (num_received - 1) / delta); info(0, "fakesmsc: terminating"); return 0; }
int main(int argc, char *argv[]) { if(getuid() != 0 || geteuid() != 0) { fprintf(stderr, "\n[!] You need root to run this tool\n"); /*return ERR; */ } #ifdef __linux__ /* QueMod is Linux only anyway */ setup_signal_handlers(); #endif int opt; int ret = 0; FILE *configuration_fd; char *conf_fd = "/opt/quemod/quemod.conf"; fprintf(stdout,"\n[ QueMod Framework ]\n"); if((configuration_fd = fopen(conf_fd, "r")) == NULL) { error("[!] Could not open the configuration file"); return ERR; } if((parse_configuration_file(configuration_fd)) == 0) { #ifdef DEBUG fprintf(stdout, "Parsed 0 lines in configuration file\n"); #endif } if(configuration_fd) { fclose(configuration_fd); } while((opt = getopt(argc, argv,"u:p:v:wd")) != ERR) { switch(opt) { case 'u': options.load_plugins = optarg; break; case 'p': options.plugin_dir = optarg; break; case 'v': options.ip_version = atol(optarg); break; case 'w': options.write_packets = YES; break; case 'd': options.write_packet_hdrs = YES; break; case '?': help(); break; } } ret = init_plugins(); if(ret == ERR) return ERR; memset(&stats, 0x0, sizeof(struct _stats)); ret = setup_nfq(); cleanup(); printf("\n"); return ret; }
int main(int argc, char *argv[]) { if (1 >= argc) { background = true; } else { background = false; } if ( background ) { pid_t pid = fork(); if (pid < 0) { cerr << "fork: unable to fork" << endl; return -1; } if (pid ) //parent { exit(0); } } checkLogFile(); setup_signal_handlers(); pid_t pidt = getpid(); gOsLog<<"main thread pid="<<(int)pidt<<endl; printSysTime (); // bSysStop = false; pthread_t tidListen = 0; if (pthread_create(&tidListen, 0, (void *(*)(void*))&listenThread, 0)) { gOsLog<<"create gk thread fail!"<<endl; exit(0); } // //signal(SIGINT, signal_handler); signal(SIGTERM, signal_handler); // main loop for dialogic SR event while(!bSysStop) { sleep(10); if (1 >= argc) { checkLogFile(); } } pthread_join(tidListen, NULL); //closeSys(); printSysTime (); gOsLog<<"exit from the main thread!"<<endl; return 0; }
int main(int argc, char **argv) { static struct option longopts[] = { { "conf", required_argument, NULL, 'c' }, { "help", no_argument, NULL, 'h' }, { NULL, 0, NULL, 0 } }; static struct config_t config = { {}, /* global_config */ NULL, /* listeners */ 0, /* num_listeners */ 1024, /* max_connections */ 1, /* num_threads */ NULL, /* thread_ids */ {}, /* state */ }; const char *config_file = "h2o.conf"; int opt_ch; yoml_t *config_yoml; h2o_config_init(&config.global_config); config.global_config.close_cb = on_close; { h2o_configurator_t *c = h2o_config_create_configurator(&config.global_config, sizeof(*c)); c->exit = on_config_listen_exit; h2o_config_define_command( c, "listen", H2O_CONFIGURATOR_FLAG_GLOBAL, on_config_listen, "port at which the server should listen for incoming requests (mandatory)", " - if the value is a scalar, it is treated as the port number (or as the", " service name)", " - if the value is a mapping, following properties are recognized:", " port: incoming port number or service name (mandatory)", " host: incoming address (default: any address)", " ssl: if using SSL (default: none)", " certificate-file: path of the certificate file", " key-file: path of the key file"); h2o_config_define_command( c, "max-connections", H2O_CONFIGURATOR_FLAG_GLOBAL, on_config_max_connections, "max connections (default: 1024)"); h2o_config_define_command( c, "num-threads", H2O_CONFIGURATOR_FLAG_GLOBAL, on_config_num_threads, "number of worker threads (default: 1)"); } h2o_access_log_register_configurator(&config.global_config); h2o_file_register_configurator(&config.global_config); h2o_proxy_register_configurator(&config.global_config); /* parse options */ while ((opt_ch = getopt_long(argc, argv, "c:h", longopts, NULL)) != -1) { switch (opt_ch) { case 'c': config_file = optarg; break; case 'h': usage(&config.global_config); exit(0); break; default: assert(0); break; } } argc -= optind; argv += optind; /* configure */ if ((config_yoml = load_config(config_file)) == NULL) exit(EX_CONFIG); if (h2o_config_configure(&config.global_config, config_file, config_yoml) != 0) exit(EX_CONFIG); yoml_free(config_yoml); setup_signal_handlers(); if (config.num_threads <= 1) { run_loop(&config); } else { config.thread_ids = alloca(sizeof(pthread_t) * config.num_threads); unsigned i; for (i = 0; i != config.num_threads; ++i) { pthread_create(config.thread_ids + i, NULL, run_loop, &config); } for (i = 0; i < config.num_threads; ++i) { pthread_join(config.thread_ids[i], NULL); } } return 0; }
int main (int argc, char **argv) { int quit = 0; #if defined(__GLIBC__) setup_signal_handlers (); #endif /* command line/config options */ verify_global_config (argc, argv); parse_conf_file (&argc, &argv); parse_cmd_line (argc, argv); /* initialize storage */ init_storage (); /* setup to use the current locale */ set_locale (); #ifdef HAVE_LIBGEOIP init_geoip (); #endif /* init logger */ logger = init_log (); /* init parsing spinner */ parsing_spinner = new_gspinner (); parsing_spinner->process = &logger->process; /* outputting to stdout */ if (conf.output_html) { ui_spinner_create (parsing_spinner); goto out; } /* init curses */ set_input_opts (); if (conf.no_color || has_colors () == FALSE) { conf.color_scheme = NO_COLOR; conf.no_color = 1; } else { start_color (); } init_colors (); init_windows (&header_win, &main_win); set_curses_spinner (parsing_spinner); /* configuration dialog */ if (isatty (STDIN_FILENO) && (conf.log_format == NULL || conf.load_conf_dlg)) { refresh (); quit = verify_format (logger, parsing_spinner); } /* straight parsing */ else { ui_spinner_create (parsing_spinner); } out: /* main processing event */ time (&start_proc); if (conf.load_from_disk) set_general_stats (); else if (!quit && parse_log (&logger, NULL, -1)) FATAL ("Error while processing file"); logger->offset = logger->process; /* no valid entries to process from the log */ if ((logger->process == 0) || (logger->process == logger->invalid)) FATAL ("Nothing valid to process."); /* init reverse lookup thread */ gdns_init (); parse_initial_sort (); allocate_holder (); end_spinner (); time (&end_proc); /* stdout */ if (conf.output_html) { /* CSV */ if (conf.output_format && strcmp ("csv", conf.output_format) == 0) output_csv (logger, holder); /* JSON */ else if (conf.output_format && strcmp ("json", conf.output_format) == 0) output_json (logger, holder); /* HTML */ else output_html (logger, holder); } /* curses */ else { allocate_data (); if (!conf.skip_term_resolver) gdns_thread_create (); render_screens (); get_keys (); attroff (COLOR_PAIR (COL_WHITE)); /* restore tty modes and reset * terminal into non-visual mode */ endwin (); } /* clean */ house_keeping (); return EXIT_SUCCESS; }
int main(int argc, char **argv) { int ncmds, i; const char *tmp; pgm_error_t *pgm_err = NULL; /* FIXME */ signal(SIGPIPE, SIG_IGN); setup_signal_handlers(); cmds = table_new(cmpstr, hashmurmur2, NULL, NULL); ncmds = sizeof commands / sizeof (struct cmd); for (i = 0; i < ncmds; ++i) { struct cmd *cmd = commands + i; table_insert(cmds, cmd->name, cmd); } if (argc != 2 && argc != 3) usage(); else if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) usage(); else if (argc == 3 && strcmp(argv[1], "-f")) usage(); if (argc == 2 && daemon(1, 0) == -1) fprintf(stderr, "Error daemonizing: %s\n", strerror(errno)); /* FIXME */ if (init_logger("/var/log/xcb/xcb-dp2.log", __LOG_DEBUG) == -1) { fprintf(stderr, "Error initializing logger\n"); exit(1); } cfg_path = argc == 2 ? argv[1] : argv[2]; if ((cfg = config_load(cfg_path)) == NULL) exit(1); if ((tmp = variable_retrieve(cfg, "general", "log_level"))) { if (!strcasecmp(tmp, "info")) set_logger_level(__LOG_INFO); else if (!strcasecmp(tmp, "notice")) set_logger_level(__LOG_NOTICE); else if (!strcasecmp(tmp, "warning")) set_logger_level(__LOG_WARNING); } /* FIXME */ if (addms) times = table_new(cmpstr, hashmurmur2, kfree, vfree); clients_to_close = dlist_new(NULL, NULL); clients = dlist_new(NULL, NULL); monitors = dlist_new(NULL, NULL); tp = thrpool_new(16, 512, 200, NULL); if (!pgm_init(&pgm_err)) { xcb_log(XCB_LOG_ERROR, "Error starting PGM engine: %s", pgm_err->message); pgm_error_free(pgm_err); goto err; } /* FIXME */ if (NEW(pgm_send_cfg) == NULL) { xcb_log(XCB_LOG_ERROR, "Error allocating memory for PGM cfg"); goto err; } pgm_send_cfg->network = NULL; pgm_send_cfg->port = 0; init_pgm_send_cfg(pgm_send_cfg); if (pgm_send_cfg->network == NULL) { xcb_log(XCB_LOG_ERROR, "PGM network can't be NULL"); goto err; } if (pgm_send_cfg->port == 0) { xcb_log(XCB_LOG_ERROR, "PGM port can't be zero"); goto err; } if ((pgm_sender = pgmsock_create(pgm_send_cfg->network, pgm_send_cfg->port, PGMSOCK_SENDER)) == NULL) goto err; /* FIXME */ if ((el = create_event_loop(1024 + 1000)) == NULL) { xcb_log(XCB_LOG_ERROR, "Error creating event loop"); goto err; } create_time_event(el, 1, server_cron, NULL, NULL); if ((tmp = variable_retrieve(cfg, "general", "udp_port")) && strcmp(tmp, "")) { if ((udpsock = net_udp_server(NULL, atoi(tmp), neterr, sizeof neterr)) == -1) { xcb_log(XCB_LOG_ERROR, "Opening port '%s': %s", tmp, neterr); goto err; } if (net_nonblock(udpsock, neterr, sizeof neterr) == -1) { xcb_log(XCB_LOG_ERROR, "Setting port '%s' nonblocking: %s", tmp, neterr); goto err; } } if ((tmp = variable_retrieve(cfg, "general", "tcp_port")) && strcmp(tmp, "")) if ((tcpsock = net_tcp_server(NULL, atoi(tmp), neterr, sizeof neterr)) == -1) { xcb_log(XCB_LOG_ERROR, "Opening port '%s': %s", tmp, neterr); goto err; } if (udpsock > 0 && create_file_event(el, udpsock, EVENT_READABLE, read_quote, NULL) == -1) { xcb_log(XCB_LOG_ERROR, "Unrecoverable error creating udpsock '%d' file event", udpsock); goto err; } if (tcpsock > 0 && create_file_event(el, tcpsock, EVENT_READABLE, tcp_accept_handler, NULL) == -1) { xcb_log(XCB_LOG_ERROR, "Unrecoverable error creating tcpsock '%d' file event", tcpsock); goto err; } xcb_log(XCB_LOG_NOTICE, "Server dispatcher started"); start_event_loop(el, ALL_EVENTS); delete_event_loop(el); pgm_shutdown(); return 0; err: close_logger(); exit(1); }
int main (int argc, char **argv) { unformat_input_t input; char *chroot_path = 0; u8 *chroot_path_u8; int interval = 0; f64 *vector_ratep, *rx_ratep, *sig_error_ratep; pid_t *vpp_pidp; svmdb_map_args_t _ma, *ma = &_ma; int uid, gid, rv; struct passwd _pw, *pw; struct group _grp, *grp; char *s, buf[128]; unformat_init_command_line (&input, argv); uid = geteuid (); gid = getegid (); while (unformat_check_input (&input) != UNFORMAT_END_OF_INPUT) { if (unformat (&input, "chroot %s", &chroot_path_u8)) { chroot_path = (char *) chroot_path_u8; } else if (unformat (&input, "interval %d", &interval)) ; else if (unformat (&input, "uid %d", &uid)) ; else if (unformat (&input, "gid %d", &gid)) ; else if (unformat (&input, "uid %s", &s)) { /* lookup the username */ pw = NULL; rv = getpwnam_r (s, &_pw, buf, sizeof (buf), &pw); if (rv < 0) { fformat (stderr, "cannot fetch username %s", s); exit (1); } if (pw == NULL) { fformat (stderr, "username %s does not exist", s); exit (1); } vec_free (s); uid = pw->pw_uid; } else if (unformat (&input, "gid %s", &s)) { /* lookup the group name */ grp = NULL; rv = getgrnam_r (s, &_grp, buf, sizeof (buf), &grp); if (rv != 0) { fformat (stderr, "cannot fetch group %s", s); exit (1); } if (grp == NULL) { fformat (stderr, "group %s does not exist", s); exit (1); } vec_free (s); gid = grp->gr_gid; } else { fformat (stderr, "usage: vpp_get_metrics [chroot <path>] [interval <nn>]\n"); exit (1); } } setup_signal_handlers (); clib_memset (ma, 0, sizeof (*ma)); ma->root_path = chroot_path; ma->uid = uid; ma->gid = gid; c = svmdb_map (ma); vpp_pidp = svmdb_local_get_variable_reference (c, SVMDB_NAMESPACE_VEC, "vpp_pid"); vector_ratep = svmdb_local_get_variable_reference (c, SVMDB_NAMESPACE_VEC, "vpp_vector_rate"); rx_ratep = svmdb_local_get_variable_reference (c, SVMDB_NAMESPACE_VEC, "vpp_input_rate"); sig_error_ratep = svmdb_local_get_variable_reference (c, SVMDB_NAMESPACE_VEC, "vpp_sig_error_rate"); /* * Make sure vpp is actually running. Otherwise, there's every * chance that the database region will be wiped out by the * process monitor script */ if (vpp_pidp == 0 || vector_ratep == 0 || rx_ratep == 0 || sig_error_ratep == 0) { fformat (stdout, "vpp not running\n"); exit (1); } do { /* * Once vpp exits, the svm db region will be recreated... * Can't use kill (*vpp_pidp, 0) if running as non-root / * accessing the shared-VM database via group perms. */ if (*vpp_pidp == 0) { fformat (stdout, "vpp not running\n"); exit (1); } fformat (stdout, "%d: vpp_vector_rate=%.2f, vpp_input_rate=%f, vpp_sig_error_rate=%f\n", *vpp_pidp, *vector_ratep, *rx_ratep, *sig_error_ratep); if (interval) sleep (interval); if (signal_received) break; } while (interval); svmdb_unmap (c); exit (0); }
void install_signal_handlers() { std::unordered_map<int, signal_handler_t> handlers = {{SIGINT, sigint_handler}, {SIGQUIT, sigquit_handler}, {SIGWINCH, sigwinch_handler}, {SIGTSTP, sigtstp_handler}}; setup_signal_handlers(handlers); }
int main(int argc, char** argv) { s32 opt; u8 mem_limit_given = 0, timeout_given = 0, qemu_mode = 0; u32 tcnt; char** use_argv; doc_path = access(DOC_PATH, F_OK) ? "docs" : DOC_PATH; while ((opt = getopt(argc,argv,"+o:m:t:A:eqZQ")) > 0) switch (opt) { case 'o': if (out_file) FATAL("Multiple -o options not supported"); out_file = optarg; break; case 'm': { u8 suffix = 'M'; if (mem_limit_given) FATAL("Multiple -m options not supported"); mem_limit_given = 1; if (!strcmp(optarg, "none")) { mem_limit = 0; break; } if (sscanf(optarg, "%llu%c", &mem_limit, &suffix) < 1 || optarg[0] == '-') FATAL("Bad syntax used for -m"); switch (suffix) { case 'T': mem_limit *= 1024 * 1024; break; case 'G': mem_limit *= 1024; break; case 'k': mem_limit /= 1024; break; case 'M': break; default: FATAL("Unsupported suffix or bad syntax for -m"); } if (mem_limit < 5) FATAL("Dangerously low value of -m"); if (sizeof(rlim_t) == 4 && mem_limit > 2000) FATAL("Value of -m out of range on 32-bit systems"); } break; case 't': if (timeout_given) FATAL("Multiple -t options not supported"); timeout_given = 1; if (strcmp(optarg, "none")) { exec_tmout = atoi(optarg); if (exec_tmout < 20 || optarg[0] == '-') FATAL("Dangerously low value of -t"); } break; case 'e': if (edges_only) FATAL("Multiple -e options not supported"); edges_only = 1; break; case 'q': if (quiet_mode) FATAL("Multiple -q options not supported"); quiet_mode = 1; break; case 'Z': /* This is an undocumented option to write data in the syntax expected by afl-cmin. Nobody else should have any use for this. */ cmin_mode = 1; quiet_mode = 1; break; case 'A': /* Another afl-cmin specific feature. */ at_file = optarg; break; case 'Q': if (qemu_mode) FATAL("Multiple -Q options not supported"); if (!mem_limit_given) mem_limit = MEM_LIMIT_QEMU; qemu_mode = 1; break; default: usage(argv[0]); } if (optind == argc || !out_file) usage(argv[0]); setup_shm(); setup_signal_handlers(); set_up_environment(); find_binary(argv[optind]); if (!quiet_mode) { show_banner(); ACTF("Executing '%s'...\n", target_path); } detect_file_args(argv + optind); if (qemu_mode) use_argv = get_qemu_argv(argv[0], argv + optind, argc - optind); else use_argv = argv + optind; run_target(use_argv); tcnt = write_results(); if (!quiet_mode) { if (!tcnt) FATAL("No instrumentation detected" cRST); OKF("Captured %u tuples in '%s'." cRST, tcnt, out_file); } exit(child_crashed * 2 + child_timed_out); }