int main (int argc, char *argv[]) { struct libusb_context *ctx; struct libusb_device_handle *handle; int err; if ((err = libusb_init (&ctx)) != 0) { printf ("libusb_init failed with clode %d\n", err); return 1; } // libusb_set_debug (ctx, 3); while (1) { handle = libusb_open_device_with_vid_pid (ctx, BOAT_VENDOR, BOAT_PRODUCT); if (!handle) { printf ("Boat USB device not found, sleep for 10 seconds and try again\n"); sleep (10); } else { printf ("Boat device found, open master socket\n"); libusb_claim_interface (handle, 0); run_daemon (handle); libusb_close (handle); break; } } libusb_exit (ctx); return 0; }
static void run_check(void) { int i; time_t curtime; struct tm *loctime; char fname[150]; char info[150]; if(taskq==0 && file_exists("/bin/taskq-check")) { run_daemon("taskq-check","/bin/taskq-check"); } if(!file_exists(DIRQUE)) xmkdir(DIRQUE); for(i=0; i < listcnt;i++) { if(listq[i].cmd && listq[i].status==0) { curtime=time(NULL); loctime=localtime(&curtime); memset(fname,0x0,sizeof(fname)); snprintf(fname,sizeof(fname),"%s/%s",DIRQUE,listq[i].cmd); if(file_exists(fname)) continue; strftime(info, sizeof(info), "%d/%m/%Y %T",loctime); save_to_file(fname,"%s",info); //printf("[%s] Service %s down\n",info,listq[i].prog); memset(info,0x0,sizeof(info)); __log(listq[i].prog); } } }
int main(int argc, char **argv) { if (argc >= 2 && strcmp(argv[1], "--handle") == 0) { return handle_crash(argc, argv); } else { return run_daemon(argc, argv); } }
int main(int argc, char *argv[]) { if (argc == 2 && strcmp(argv[1], "--daemon") == 0) { //Everything we'll exec will be in su, not su_daemon setexeccon("u:r:su:s0"); return run_daemon(); } return su_main(argc, argv); }
// called when daemon auto-started by client. int spawn_daemon(void) { int r = daemonize(); if (r < 0) return r; if (r > 0) return 0; main_thread = pthread_self(); run_daemon(NULL); }
int test_run() { int retval; printf("[+] run_daemon():\n"); retval = run_daemon(); printf("\trun retval: %d\n\n", retval); return retval; }
// called when daemon explicitly started. int start_daemon(bool debug, const char *fwsim) { debug_daemon = debug; use_fwsim = fwsim != NULL; int r = daemonize(); if (r < 0) return r; if (r > 0) return 0; // nonzero PID => success main_thread = pthread_self(); run_daemon(fwsim); }
static void run_daemon_fork(void) { pid_t pid = fork(); if (pid < 0) { LOGE("Failed to fork: %s", strerror(errno)); _exit(EXIT_FAILURE); } else if (pid > 0) { _exit(EXIT_SUCCESS); } if (setsid() < 0) { LOGE("Failed to become session leader: %s", strerror(errno)); _exit(EXIT_FAILURE); } signal(SIGHUP, SIG_IGN); pid = fork(); if (pid < 0) { LOGE("Failed to fork: %s", strerror(errno)); _exit(EXIT_FAILURE); } else if (pid > 0) { _exit(EXIT_SUCCESS); } if (chdir("/") < 0) { LOGE("Failed to change cwd to /: %s", strerror(errno)); _exit(EXIT_FAILURE); } umask(0); LOGD("Started daemon in background"); close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); if (open("/dev/null", O_RDONLY) < 0) { LOGE("Failed to reopen stdin: %s", strerror(errno)); _exit(EXIT_FAILURE); } if (open("/dev/null", O_WRONLY) < 0) { LOGE("Failed to reopen stdout: %s", strerror(errno)); _exit(EXIT_FAILURE); } if (open("/dev/null", O_RDWR) < 0) { LOGE("Failed to reopen stderr: %s", strerror(errno)); _exit(EXIT_FAILURE); } run_daemon(); _exit(EXIT_SUCCESS); }
int main(int argc, char **argv) { int c; int opt_index = 0; TelemPostDaemon daemon; struct option opts[] = { { "config_file", 1, NULL, 'f' }, { "help", 0, NULL, 'h' }, { "version", 0, NULL, 'V' }, { NULL, 0, NULL, 0 } }; while ((c = getopt_long(argc, argv, "f:hV", opts, &opt_index)) != -1) { switch (c) { case 'f': if (tm_set_config_file(optarg) != 0) { telem_log(LOG_ERR, "Configuration file" " path not valid\n"); exit(EXIT_FAILURE); } break; case 'V': printf(PACKAGE_VERSION "\n"); exit(EXIT_SUCCESS); case 'h': print_usage(argv[0]); exit(EXIT_SUCCESS); case '?': print_usage(argv[0]); exit(EXIT_FAILURE); } } initialize_daemon(&daemon); daemon.current_spool_size = get_spool_dir_size(); /* When path activated this will process * the activating message or previously * spooled data */ staging_records_loop(&daemon); /* This function is blocking, it will * block until a signal is received */ run_daemon(&daemon); close_daemon(&daemon); return 0; }
int main() { signal(SIGINT, signal_handler); pid_t pid = fork(); if (pid < 0) { std::cerr << "Failed to fork" << std::endl; return 1; } else if (pid == 0) { // child code only run_client(); } else { // parent code only run_daemon(); } return 0; }
int main (int argc, char *argv[]) { LOG_INIT(LOG_ALL); LOG_GMT_ZONE; LOG_BEGIN; settings = bp_hashtab_new_ext(czstr_hash, czstr_equal, free, free); if (!preload_settings()){ LOG_END_RC(1); //return 1; } chain_set(); LOG("chain-set"); RAND_bytes((unsigned char *)&instance_nonce, sizeof(instance_nonce)); unsigned int arg; for (arg = 1; arg < argc; arg++) { const char *argstr = argv[arg]; if (!do_setting(argstr)){ LOG_END_RC(1); //return 1; } } LOG("arguments processed"); /* * properly capture TERM and other signals */ signal(SIGHUP, SIG_IGN); signal(SIGPIPE, SIG_IGN); signal(SIGINT, term_signal); signal(SIGTERM, term_signal); LOG("signals set"); init_daemon(&global_nci); run_daemon(&global_nci); fprintf(plog, "daemon exiting\n"); shutdown_daemon(&global_nci); LOG_END_RC(0); //return 0; }
int main(int argc, char* argv[]) { int result = 0; int custom_addr = 0; int daemon_mode = 0; if (argc > 1) { if (strcmp(argv[1], "-d") == 0) { daemon_mode = 1; } else { if (_psmove_btaddr_from_string(argv[1], NULL)) { printf("Using user-supplied host address: %s\n", argv[1]); } else { printf("Cannot convert host address: %s\n", argv[1]); return 1; } custom_addr = 1; } } #ifdef __linux /** * In order to be able to start/stop bluetoothd and to * add new entries to the Bluez configuration files, we * need to run as root (platform/psmove_linuxsupport.c) **/ if (geteuid() != 0) { printf("This program must be run as root (or use sudo).\n"); return 1; } #endif if (daemon_mode == 0) { if (custom_addr != 0) { result = pair(argv[1]); } else { result = pair(NULL); } } else { result = run_daemon(); } return result; }
DWORD WINAPI ServiceWorkerThread(LPVOID lpParam) { OutputDebugString(_T("GDaemon: ServiceWorkerThread: Entry")); bool started = false; // Periodically check if the service has been requested to stop while (WaitForSingleObject(g_ServiceStopEvent, 0) != WAIT_OBJECT_0) { Sleep(1000); if (!started) { run_daemon(); started = true; } } OutputDebugString(_T("GDaemon: ServiceWorkerThread: Exit")); return ERROR_SUCCESS; }
int main (int argc, char *argv[]) { syslog_open("nntpswitchd", LOG_PID, LOG_NEWS); init_options(argc, argv); init_sighandlers(); initproctitle(argc, argv); if ((master = memmap(sizeof (MASTER))) == NULL) die("Can't allocate master memory"); info("Server starting up.."); run_daemon(); syslog_close(); return 0; }
int main (int argc, char *argv[]) { int kvm_fd; int ret; volatile int loop=1; bool flag; flag = check_if_daemon(argc, argv); if (flag == true) { printf("Its a daemon invocation\n"); run_daemon(); printf("daemon invocation should not come here\n"); exit(1); } else { printf("its a client invocation\n"); run_client(argc, argv); exit(0); } return 0; }
static void check_daemon(void) { int pid; if ((pid = readpid()) < 0 || kill(pid, 0) < 0) { /* daemon ping failed, try to start it up */ if (run_daemon()) { fprintf(stderr, "Failed to ping daemon and unable to start it up: %s\n", strerror(errno)); exit(1); } } else if (kill(pid, SIGUSR1)) { fprintf(stderr, "Failed to send signal: %s\n", strerror(errno)); exit(2); } }
int CL_Service_Unix::main(int argc, char **argv) { std::vector<CL_String> args; for (int i=0; i<argc; i++) args.push_back(argv[i]); if (argc >= 3 && args[1] == "-daemon") { return run_daemon(args); } else if (argc == 2 && args[1] == "-debug") { return run_debug(args); } else { std::cout << "Service parameters:" << std::endl; std::cout << " -daemon <pidfile> - Start service as a unix daemon" << std::endl; std::cout << " -debug - Debug service" << std::endl; return 0; } }
int main(int argc, char* argv[]) { int result = 0; int custom_addr = 0; int daemon_mode = 0; if (argc > 1) { if (strcmp(argv[1], "-d") == 0) { daemon_mode = 1; } else { if (_psmove_btaddr_from_string(argv[1], NULL)) { printf("Using user-supplied host address: %s\n", argv[1]); } else { printf("Cannot convert host address: %s\n", argv[1]); return 1; } custom_addr = 1; } } if (!psmove_port_check_pairing_permissions()) { return 1; } if (daemon_mode == 0) { if (custom_addr != 0) { result = pair(argv[1]); } else { result = pair(NULL); } } else { result = run_daemon(); } return result; }
/** * Entry point */ int main(int argc, char **argv) { static const char* cmds[] = { "b", "buffer", "1", SETTINGR("Buffer size [KW], default: ",COLLECT_BUFSIZE), "d", "data", "1", SETTINGR("Data cache size [KB], with fallback to: ", GENERIC_DCACHE ), "i", "inst", "1", SETTINGR("Instruction cache size [KB], with fallback to: ", GENERIC_ICACHE), "f", "file", "1", "Sample output file, default: '" OUTPUT_DEFAULT "', '-' for stdout", "F", "Foreground", "0", "Run daemon in foreground", "r", "run", "1", "0=daemon, 1=config info, >1=<r>KB sample", "n", "number", "1", "Output size in [k|m|g|t] bytes, 0 = unlimited to stdout", "o", "onlinetest", "1", "[t<x>][c<x>] x=[a[n][w]][b[w]] 't'ot, 'c'ontinuous, default: ta8b", "p", "pidfile", "1", "daemon pidfile, default: " PID_DEFAULT , "s", "source", "1", "Injection source file, default: '" INPUT_DEFAULT "', '-' for stdin", "t", "threads", "1", "Number of threads", "v", "verbose", "1", "Verbose mask 0=none,1=summary,2=retries,4=timing,8=loop,16=code,32=test", "w", "write", "1", "Set write_wakeup_threshold [bits]", "h", "help", "0", "This help" }; static int nopts = sizeof(cmds)/(4*sizeof(char *)); struct option long_options[nopts+1]; char short_options[1+nopts*2]; int c,i,j; H_UINT bufct, bufrem, ierr; H_PARAMS cmd; if (havege_version(HAVEGE_PREP_VERSION)==NULL) error_exit("version conflict %s!=%s", HAVEGE_PREP_VERSION, havege_version(NULL)); #if NO_DAEMON==1 params->setup |= RUN_AS_APP; #endif #ifdef RAW_IN_ENABLE #define DIAG_USAGE2 SETTINGL("=inject ticks,", DIAG_RUN_INJECT)\ SETTINGL("=inject data", DIAG_RUN_TEST) params->setup |= INJECT | RUN_AS_APP; #else #define DIAG_USAGE2 "" #endif #ifdef RAW_OUT_ENABLE #define DIAG_USAGE1 SETTINGL("=capture,", DIAG_RUN_CAPTURE) params->setup |= CAPTURE | RUN_AS_APP; #else #define DIAG_USAGE1 "" #endif #if NUMBER_CORES>1 params->setup |= MULTI_CORE; #endif #ifdef SIGHUP signal(SIGHUP, tidy_exit); #endif signal(SIGINT, tidy_exit); signal(SIGTERM, tidy_exit); strcpy(short_options,""); bufct = bufrem = 0; /** * Build options */ for(i=j=0;j<(nopts*4);j+=4) { switch(cmds[j][0]) { case 'o': #ifdef ONLINE_TESTS_ENABLE break; #else continue; #endif case 'r': #if defined(RAW_IN_ENABLE) || defined (RAW_OUT_ENABLE) if (0!=(params->setup & (INJECT|CAPTURE))) { params->daemon = "havege_diagnostic"; cmds[j+3] = "run level, 0=diagnostic off,1=config info," DIAG_USAGE1 DIAG_USAGE2 ; } else #endif if (0!=(params->setup & RUN_AS_APP)) continue; break; case 's': if (0 == (params->setup & INJECT)) continue; break; case 't': if (0 == (params->setup & MULTI_CORE)) continue; break; case 'p': case 'w': case 'F': if (0 !=(params->setup & RUN_AS_APP)) continue; break; } long_options[i].name = cmds[j+1]; long_options[i].has_arg = atoi(cmds[j+2]); long_options[i].flag = NULL; long_options[i].val = cmds[j][0]; strcat(short_options,cmds[j]); if (long_options[i].has_arg!=0) strcat(short_options,":"); i += 1; } memset(&long_options[i], 0, sizeof(struct option)); do { c = getopt_long (argc, argv, short_options, long_options, NULL); switch(c) { case 'F': params->setup |= RUN_IN_FG; params->foreground = 1; break; case 'b': params->buffersz = ATOU(optarg) * 1024; if (params->buffersz<4) error_exit("invalid size %s", optarg); break; case 'd': params->d_cache = ATOU(optarg); break; case 'i': params->i_cache = ATOU(optarg); break; case 'f': params->sample_out = optarg; if (strcmp(optarg,"-") == 0 ) params->setup |= USE_STDOUT; break; case 'n': if (get_runsize(&bufct, &bufrem, optarg)) error_exit("invalid count: %s", optarg); params->setup |= RUN_AS_APP|RANGE_SPEC; if (bufct==0 && bufrem==0) params->setup |= USE_STDOUT; /* ugly but documented behavior! */ break; case 'o': params->tests_config = optarg; break; case 'p': params->pid_file = optarg; break; case 'r': params->run_level = ATOU(optarg); if (params->run_level != 0) params->setup |= RUN_AS_APP; break; case 's': params->sample_in = optarg; break; case 't': params->ncores = ATOU(optarg); if (params->ncores > NUMBER_CORES) error_exit("invalid thread count: %s", optarg); break; case 'v': params->verbose = ATOU(optarg); break; case 'w': params->setup |= SET_LWM; params->low_water = ATOU(optarg); break; case '?': case 'h': usage(0, nopts, long_options, cmds); case -1: break; } } while (c!=-1); if (params->tests_config == 0) params->tests_config = (0 != (params->setup & RUN_AS_APP))? TESTS_DEFAULT_APP : TESTS_DEFAULT_RUN; memset(&cmd, 0, sizeof(H_PARAMS)); cmd.collectSize = params->buffersz; cmd.icacheSize = params->i_cache; cmd.dcacheSize = params->d_cache; cmd.options = params->verbose & 0xff; cmd.nCores = params->ncores; cmd.testSpec = params->tests_config; cmd.msg_out = print_msg; if (0 != (params->setup & RUN_AS_APP)) { cmd.ioSz = APP_BUFF_SIZE * sizeof(H_UINT); if (params->verbose!=0 && 0==(params->setup & RANGE_SPEC)) params->run_level = 1; } #ifndef NO_DAEMON else { poolSize = get_poolsize(); i = (poolSize + 7)/8 * sizeof(H_UINT); cmd.ioSz = sizeof(struct rand_pool_info) + i *sizeof(H_UINT); } #endif if (0 != (params->verbose & H_DEBUG_TIME)) cmd.metering = show_meterInfo; if (0 !=(params->setup & CAPTURE) && 0 != (params->run_level == DIAG_RUN_CAPTURE)) cmd.options |= H_DEBUG_RAW_OUT; #ifdef RAW_IN_ENABLE if (0 !=(params->setup & INJECT) && 0 != (params->run_level & (DIAG_RUN_INJECT|DIAG_RUN_TEST))) { if (strcmp(params->sample_in,"-") == 0 ) fd_in = stdin; else fd_in = fopen(params->sample_in, "rb"); if (NULL == fd_in) error_exit("Unable to open: %s", params->sample_in); cmd.injection = injectFile; if (params->run_level==DIAG_RUN_INJECT) cmd.options |= H_DEBUG_RAW_IN; else if (params->run_level==DIAG_RUN_TEST) cmd.options |= H_DEBUG_TEST_IN; else usage(1, nopts, long_options, cmds); } #endif handle = havege_create(&cmd); ierr = handle==NULL? H_NOHANDLE : handle->error; switch(ierr) { case H_NOERR: break; case H_NOTESTSPEC: error_exit("unrecognized test setup: %s", cmd.testSpec); break; default: error_exit("Couldn't initialize haveged (%d)", ierr); } if (0 != (params->setup & RUN_AS_APP)) { if (params->run_level==1) anchor_info(handle); else if (0==(params->setup&(INJECT|CAPTURE))) { /* must specify range with --nunber or --run > 1 but not both */ if (params->run_level>1) { if (0==(params->setup&RANGE_SPEC)) { /* --run specified */ bufct = params->run_level/sizeof(H_UINT); bufrem = (params->run_level%sizeof(H_UINT))*1024; } else usage(2, nopts, long_options, cmds); /* both specified */ } else if (0==(params->setup&RANGE_SPEC)) usage(3,nopts, long_options, cmds); /* neither specified */ else if (0==(params->setup&USE_STDOUT)&&(bufct+bufrem)==0) usage(4, nopts, long_options, cmds); /* only with stdout */ run_app(handle, bufct, bufrem); } else if (0==(params->setup&USE_STDOUT)&&(bufct+bufrem)==0) usage(5, nopts, long_options, cmds); /* only with stdout */ else run_app(handle, bufct, bufrem); } #ifndef NO_DAEMON else run_daemon(handle); #endif havege_destroy(handle); exit(0); }
/** * main program. Set options given commandline arguments. * @param argc: number of commandline arguments. * @param argv: array of commandline arguments. * @return: exit status of the program. */ int main(int argc, char* argv[]) { int c; const char* cfgfile = CONFIGFILE; const char* winopt = NULL; const char* log_ident_default; int cmdline_verbose = 0; int debug_mode = 0; int need_pidfile = 1; #ifdef UB_ON_WINDOWS int cmdline_cfg = 0; #endif log_init(NULL, 0, NULL); log_ident_default = strrchr(argv[0],'/')?strrchr(argv[0],'/')+1:argv[0]; log_ident_set(log_ident_default); /* parse the options */ while( (c=getopt(argc, argv, "c:dhpvw:")) != -1) { switch(c) { case 'c': cfgfile = optarg; #ifdef UB_ON_WINDOWS cmdline_cfg = 1; #endif break; case 'v': cmdline_verbose++; verbosity++; break; case 'p': need_pidfile = 0; break; case 'd': debug_mode++; break; case 'w': winopt = optarg; break; case '?': case 'h': default: usage(); return 1; } } argc -= optind; /* argv += optind; not using further arguments */ if(winopt) { #ifdef UB_ON_WINDOWS wsvc_command_option(winopt, cfgfile, cmdline_verbose, cmdline_cfg); #else fatal_exit("option not supported"); #endif } if(argc != 0) { usage(); return 1; } run_daemon(cfgfile, cmdline_verbose, debug_mode, log_ident_default, need_pidfile); log_init(NULL, 0, NULL); /* close logfile */ #ifndef unbound_testbound if(log_get_lock()) { lock_quick_destroy((lock_quick_type*)log_get_lock()); } #endif return 0; }
int Xboxdrv::main(int argc, char** argv) { try { Options opts; CommandLineParser cmd_parser; cmd_parser.parse_args(argc, argv, &opts); set_scheduling(opts); switch(opts.mode) { case Options::PRINT_HELP_DEVICES: run_help_devices(); break; case Options::RUN_LIST_SUPPORTED_DEVICES: run_list_supported_devices(); break; case Options::RUN_LIST_SUPPORTED_DEVICES_XPAD: run_list_supported_devices_xpad(); break; case Options::PRINT_VERSION: cmd_parser.print_version(); break; case Options::PRINT_HELP: cmd_parser.print_help(); break; case Options::PRINT_LED_HELP: cmd_parser.print_led_help(); break; case Options::RUN_DEFAULT: run_main(opts); break; case Options::PRINT_ENUMS: run_list_enums(opts.list_enums); break; case Options::RUN_DAEMON: run_daemon(opts); break; case Options::RUN_LIST_CONTROLLER: run_list_controller(); break; } } catch(const std::exception& err) { std::cout << "\n-- [ ERROR ] ------------------------------------------------------\n" << err.what() << std::endl; } return 0; }
int _tmain (int argc, TCHAR *argv[]) { fs::path exe_path( fs::initial_path<fs::path>() ); exe_path = fs::system_complete( fs::path(argv[0]) ); fs::current_path(exe_path.parent_path()); Config& config = Config::getInstance(); config.cfg_file = fs::current_path().string() + "\\daemon.cfg"; config.output_log = fs::current_path().string() + "\\" + std::string(LOG_DIRECTORY) + std::string(LOG_MAIN_FILE); config.error_log = fs::current_path().string() + "\\" + std::string(LOG_DIRECTORY) + std::string(LOG_ERROR_FILE); if (!fs::exists(LOG_DIRECTORY)) { fs::create_directory(LOG_DIRECTORY); } time_t now = time(nullptr); tm *ltm = localtime(&now); char buffer_time[256]; strftime(buffer_time, sizeof(buffer_time), "%Y%m%d_%H%M", ltm); if (fs::exists(config.output_log) && fs::file_size(config.output_log) > 0) { fs::rename( config.output_log, boost::str(boost::format("%1%main_%2%.log") % LOG_DIRECTORY % buffer_time) ); } if (fs::exists(config.error_log) && fs::file_size(config.error_log) > 0) { fs::rename( config.error_log, boost::str(boost::format("%1%error_%2%.log") % LOG_DIRECTORY % buffer_time) ); } #ifndef NON_DAEMON freopen(config.output_log.c_str(), "w", stdout); freopen(config.error_log.c_str(), "w", stderr); #endif // Info std::cout << "CurrentPath: " << fs::current_path() << std::endl; std::cout << "Config: " << config.cfg_file << std::endl; std::cout << "OutputLog: " << config.output_log << std::endl; std::cout << "ErrorLog: " << config.error_log << std::endl; #ifdef NON_DAEMON run_daemon(); #else SERVICE_TABLE_ENTRY ServiceTable[] = { {SERVICE_NAME, (LPSERVICE_MAIN_FUNCTION) ServiceMain}, {NULL, NULL} }; if (StartServiceCtrlDispatcher (ServiceTable) == FALSE) { return GetLastError (); } #endif }
int daemon_main(int argc, char *argv[]) { int opt; bool fork_flag = false; bool replace_flag = false; static struct option long_options[] = { {"daemonize", no_argument, 0, 'd'}, {"replace", no_argument, 0, 'r'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0} }; int long_index = 0; while ((opt = getopt_long(argc, argv, "drh", long_options, &long_index)) != -1) { switch (opt) { case 'd': fork_flag = true; break; case 'r': replace_flag = true; break; case 'h': daemon_usage(0); return EXIT_SUCCESS; default: daemon_usage(1); return EXIT_FAILURE; } } // There should be no other arguments if (argc - optind != 0) { daemon_usage(1); return EXIT_FAILURE; } // Patch SELinux policy to make init permissive patch_loaded_sepolicy(); // Allow untrusted_app to connect to our daemon patch_sepolicy_daemon(); // Set version property if we're the system mbtool (i.e. launched by init) // Possible to override this with another program by double forking, letting // 2nd child reparent to init, and then calling execve("/mbtool", ...), but // meh ... if (getppid() == 1) { if (!util::set_property("ro.multiboot.version", get_mbtool_version())) { std::printf("Failed to set 'ro.multiboot.version' to '%s'\n", get_mbtool_version()); } } if (replace_flag) { PROCTAB *proc = openproc(PROC_FILLCOM | PROC_FILLSTAT); if (proc) { pid_t curpid = getpid(); while (proc_t *info = readproc(proc, nullptr)) { if (strcmp(info->cmd, "mbtool") == 0 // This is mbtool && info->cmdline // And we can see the command line && info->cmdline[1] // And argc > 1 && strstr(info->cmdline[1], "daemon") // And it's a daemon process && info->tid != curpid) { // And we're not killing ourself // Kill the daemon process std::printf("Killing PID %d\n", info->tid); kill(info->tid, SIGTERM); } freeproc(info); } closeproc(proc); } // Give processes a chance to exit usleep(500000); } // Set up logging if (!util::mkdir_parent(MULTIBOOT_LOG_DAEMON, 0775) && errno != EEXIST) { fprintf(stderr, "Failed to create parent directory of %s: %s\n", MULTIBOOT_LOG_DAEMON, strerror(errno)); return EXIT_FAILURE; } autoclose::file fp(autoclose::fopen(MULTIBOOT_LOG_DAEMON, "w")); if (!fp) { fprintf(stderr, "Failed to open log file %s: %s\n", MULTIBOOT_LOG_DAEMON, strerror(errno)); return EXIT_FAILURE; } fix_multiboot_permissions(); // mbtool logging log::log_set_logger(std::make_shared<log::StdioLogger>(fp.get(), true)); if (fork_flag) { run_daemon_fork(); } else { return run_daemon() ? EXIT_SUCCESS : EXIT_FAILURE; } }
int daemon_main(int argc, char *argv[]) { int opt; bool fork_flag = false; bool replace_flag = false; bool patch_sepolicy = true; enum { OPT_ALLOW_ROOT_CLIENT = 1000, OPT_NO_PATCH_SEPOLICY = 1001, OPT_SIGSTOP_WHEN_READY = 1002, OPT_LOG_TO_KMSG = 1003, OPT_LOG_TO_STDIO = 1004, OPT_NO_UNSHARE = 1005, }; static struct option long_options[] = { {"daemonize", no_argument, 0, 'd'}, {"replace", no_argument, 0, 'r'}, {"help", no_argument, 0, 'h'}, {"allow-root-client", no_argument, 0, OPT_ALLOW_ROOT_CLIENT}, {"no-patch-sepolicy", no_argument, 0, OPT_NO_PATCH_SEPOLICY}, {"sigstop-when-ready", no_argument, 0, OPT_SIGSTOP_WHEN_READY}, {"log-to-kmsg", no_argument, 0, OPT_LOG_TO_KMSG}, {"log-to-stdio", no_argument, 0, OPT_LOG_TO_STDIO}, {"no-unshare", no_argument, 0, OPT_NO_UNSHARE}, {0, 0, 0, 0} }; int long_index = 0; while ((opt = getopt_long(argc, argv, "drh", long_options, &long_index)) != -1) { switch (opt) { case 'd': fork_flag = true; break; case 'r': replace_flag = true; break; case 'h': daemon_usage(0); return EXIT_SUCCESS; case OPT_ALLOW_ROOT_CLIENT: allow_root_client = true; break; case OPT_NO_PATCH_SEPOLICY: patch_sepolicy = false; break; case OPT_SIGSTOP_WHEN_READY: sigstop_when_ready = true; break; case OPT_LOG_TO_KMSG: log_to_kmsg = true; break; case OPT_LOG_TO_STDIO: log_to_stdio = true; break; case OPT_NO_UNSHARE: no_unshare = true; break; default: daemon_usage(1); return EXIT_FAILURE; } } // There should be no other arguments if (argc - optind != 0) { daemon_usage(1); return EXIT_FAILURE; } if (!no_unshare && unshare(CLONE_NEWNS) < 0) { fprintf(stderr, "unshare() failed: %s\n", strerror(errno)); return EXIT_FAILURE; } if (patch_sepolicy) { patch_loaded_sepolicy(SELinuxPatch::MAIN); } if (!switch_context(MB_EXEC_CONTEXT)) { fprintf(stderr, "Failed to switch context; %s may not run properly", argv[0]); } if (replace_flag) { PROCTAB *proc = openproc(PROC_FILLCOM | PROC_FILLSTAT); if (proc) { pid_t curpid = getpid(); while (proc_t *info = readproc(proc, nullptr)) { // NOTE: Can't check 'strcmp(info->cmd, "mbtool") == 0' (which // is the basename of /proc/<pid>/cmd) because the binary is not // always called "mbtool". For example, when run via SignedExec, // it's just called "binary". // If we can read the cmdline and argc >= 2 if (info->cmdline && info->cmdline[0] && info->cmdline[1]) { const char *name = strrchr(info->cmdline[0], '/'); if (name) { ++name; } else { name = info->cmdline[0]; } if (strcmp(name, "mbtool") == 0 // This is mbtool && strstr(info->cmdline[1], "daemon") // And it's a daemon process && info->tid != curpid) { // And we're not killing ourself // Kill the daemon process LOGV("Killing PID %d", info->tid); kill(info->tid, SIGTERM); } } freeproc(info); } closeproc(proc); } // Give processes a chance to exit usleep(500000); } if (fork_flag) { run_daemon_fork(); } else { return (daemon_init() && run_daemon()) ? EXIT_SUCCESS : EXIT_FAILURE; } }
static void run_daemon_fork() { pid_t pid = fork(); if (pid < 0) { fprintf(stderr, "Failed to fork: %s\n", strerror(errno)); _exit(EXIT_FAILURE); } else if (pid > 0) { int status; do { if (waitpid(pid, &status, 0) < 0) { fprintf(stderr, "Failed to waitpid(): %s\n", strerror(errno)); _exit(EXIT_FAILURE); } } while (!WIFEXITED(status) && !WIFSIGNALED(status)); _exit(EXIT_SUCCESS); } // Become session and process group leader if (setsid() < 0) { fprintf(stderr, "Failed to become session leader: %s\n", strerror(errno)); _exit(EXIT_FAILURE); } // Ignore hangup signal signal(SIGHUP, SIG_IGN); // Create pipe for the daemon to tell us it is listening for connections send_ok_to_pipe = true; if (pipe(pipe_fds) < 0) { fprintf(stderr, "Failed to create pipe: %s\n", strerror(errno)); _exit(EXIT_FAILURE); } pid = fork(); if (pid < 0) { fprintf(stderr, "Failed to fork: %s\n", strerror(errno)); _exit(EXIT_FAILURE); } else if (pid > 0) { // Close write end of pipe close(pipe_fds[1]); fprintf(stderr, "Waiting for daemon to start..."); // Wait for OK from child char dummy; ssize_t n = read(pipe_fds[0], &dummy, 1); // Close read end of pipe close(pipe_fds[0]); if (n < 0) { fprintf(stderr, " Failed: %s\n", strerror(errno)); _exit(EXIT_FAILURE); } else if (n != 1) { fprintf(stderr, " Failed\n"); _exit(EXIT_FAILURE); } fprintf(stderr, " OK\n"); _exit(EXIT_SUCCESS); } // Close read end of the pipe close(pipe_fds[0]); _exit((daemon_init() && run_daemon()) ? EXIT_SUCCESS : EXIT_FAILURE); }
int main(int argc, char *argv[]) { // start up in daemon mode if prompted if (argc == 2 && strcmp(argv[1], "--daemon") == 0) { return run_daemon(); } // attempt to use the daemon client if not root, // or this is api 18 and adb shell (/data is not readable even as root) if (is_api_18()) { if (geteuid() != AID_ROOT || getuid() != AID_ROOT) { // attempt to connect to daemon... LOGD("starting daemon client %d %d", getuid(), geteuid()); return connect_daemon(argc, argv); } } LOGD("skipping daemon client %d %d", getuid(), geteuid()); // Sanitize all secure environment variables (from linker_environ.c in AOSP linker). /* The same list than GLibc at this point */ static const char* const unsec_vars[] = { "GCONV_PATH", "GETCONF_DIR", "HOSTALIASES", "LD_AUDIT", "LD_DEBUG", "LD_DEBUG_OUTPUT", "LD_DYNAMIC_WEAK", "LD_LIBRARY_PATH", "LD_ORIGIN_PATH", "LD_PRELOAD", "LD_PROFILE", "LD_SHOW_AUXV", "LD_USE_LOAD_BIAS", "LOCALDOMAIN", "LOCPATH", "MALLOC_TRACE", "MALLOC_CHECK_", "NIS_PATH", "NLSPATH", "RESOLV_HOST_CONF", "RES_OPTIONS", "TMPDIR", "TZDIR", "LD_AOUT_LIBRARY_PATH", "LD_AOUT_PRELOAD", // not listed in linker, used due to system() call "IFS", }; const char* const* cp = unsec_vars; const char* const* endp = cp + sizeof(unsec_vars)/sizeof(unsec_vars[0]); while (cp < endp) { unsetenv(*cp); cp++; } /* * set LD_LIBRARY_PATH if the linker has wiped out it due to we're suid. * This occurs on Android 4.0+ */ setenv("LD_LIBRARY_PATH", "/vendor/lib:/system/lib", 0); LOGD("su invoked."); struct su_context ctx = { .from = { .pid = -1, .uid = 0, .bin = "", .args = "", .name = "", }, .to = { .uid = AID_ROOT, .login = 0, .keepenv = 0, .shell = NULL, .command = NULL, .argv = argv, .argc = argc, .optind = 0, .name = "", }, .user = {
int parse_para(int argc, char **argv) { // parse the monitor agent parameters int c, index; char *optstring = "i:l:m:n:s:p:dtvh"; char *version, *help; char *disk, *cpu_seq, *interface, *loadlevel, *processid; char *mproc, *mused, *mpri, *mvir, *mpri_ipcs; char *mswap_used, *mswap_total, *pgpgin; char *pgpgout, *pswpin, *pswpout, *svctm, *await, *aveq, *avgrq_sz, *util; char *net_byte_in, *net_byte_out, *net_pack_in, *net_pack_out; char *passiveopens, *currestab, *indatagrams, *outdatagrams; char *hard_proc, *hard_mem, *hard_temp, *hard_disk, *hard_pwr, *hard_batt, *hard_nics, *hard_fans; char * para[40] ; int i = 0; for ( i = 0; i<40; i++ ) { para[i] = NULL; } struct option longopts[] = { /* 0 */ {"help", no_argument, NULL, 'h'}, /* 1 */ {"version", no_argument, NULL, 'v'}, /* 2 */ {"daemon", no_argument, NULL, 'd'}, /* 3 */ {"url_post", required_argument, NULL, 'd'}, /* 4 */ {"rul_server", required_argument, NULL, 0}, /* 5 */ {"url_config", required_argument, NULL, 0}, /* 6 */ {"url_report", required_argument, NULL, 0}, /* 7 */ {"processid", required_argument, NULL, 0}, /* 8 */ {"mproc", no_argument, NULL, 0}, /* 9 */ {"mused", no_argument, NULL, 0}, /* 10 */ {"mpri", no_argument, NULL, 0}, /* 11 */ {"mvir", no_argument, NULL, 0}, /* 12 */ {"mpri_ipcs", no_argument, NULL, 0}, /* 13 */ {"mswap_used", no_argument, NULL, 0}, /* 14 */ {"mswap_total", no_argument, NULL, 0}, /* 15 */ {"pgpgin", no_argument, NULL, 0}, /* 16 */ {"pgpgout", no_argument, NULL, 0}, /* 17 */ {"pswpin", no_argument, NULL, 0}, /* 18 */ {"pswpout", no_argument, NULL, 0}, /* 19 */ {"svctm", no_argument, NULL, 0}, /* 20 */ {"await", no_argument, NULL, 0}, /* 21 */ {"aveq", no_argument, NULL, 0}, /* 22 */ {"avgrq_sz", no_argument, NULL, 0}, /* 23 */ {"util", no_argument, NULL, 0}, /* 24 */ {"net_byte_in", no_argument, NULL, 0}, /* 25 */ {"net_byte_out", no_argument, NULL, 0}, /* 26 */ {"net_pack_in", no_argument, NULL, 0}, /* 27 */ {"net_pack_out", no_argument, NULL, 0}, /* 28 */ {"passiveopens", no_argument, NULL, 0}, /* 29 */ {"currestab", no_argument, NULL, 0}, /* 30 */ {"indatagrams", no_argument, NULL, 0}, /* 31 */ {"outdatagrams", no_argument, NULL, 0}, /* 32 */ {"hard_proc", no_argument, NULL, 0}, /* 33 */ {"hard_mem", no_argument, NULL, 0}, /* 34 */ {"hard_temps", no_argument, NULL, 0}, /* 35 */ {"hard_disk", no_argument, NULL, 0}, /* 36 */ {"hard_pwr", no_argument, NULL, 0}, /* 37 */ {"hard_batt", no_argument, NULL, 0}, /* 38 */ {"hard_nics", no_argument, NULL, 0}, /* 39 */ {"hard_fans", no_argument, NULL, 0}, /* end */ {NULL, no_argument, NULL, 0}, }; while ((c = getopt_long(argc, argv, optstring, longopts, &index)) != -1) { switch (c) { case 'h': para[0]=""; break; case 'v': para[1]=""; break; case 'd': para[2]=""; break; case 'i': para[5]=optarg; break; case 'l': loadlevel = optarg; break; case '?': c = (char)optopt; printf("parameters is not correct! \n"); break; case ':': printf("1111111111111111111\n"); break; } switch(index){ case 0: para[0] = ""; break; case 1: para[1] = ""; break; case 2: para[2] = ""; break; case 3: para[3] = optarg; break; case 4: para[4] = optarg; break; case 5: para[5] = optarg; break; case 6: para[6] = optarg; break; case 7: para[7] = optarg; break; case 8: para[8] = ""; break; case 9: para[9] = ""; break; case 10: para[10] = ""; break; case 11: para[11] = ""; break; case 12: para[12] = ""; break; case 13: para[13] = ""; break; case 14: para[14] = ""; break; case 15: para[15] = ""; break; case 16: para[16] = ""; break; case 17: para[17] = ""; break; case 18: para[18] = ""; break; case 19: para[19] = ""; break; case 20: para[20] = ""; break; case 21: para[21] = ""; break; case 22: para[22] = ""; break; case 23: para[23] = ""; break; case 24: para[24] = ""; break; case 25: para[25] = ""; break; case 26: para[26] = ""; break; case 27: para[27] = ""; break; case 28: para[28] = ""; break; case 29: para[29] = ""; break; case 30: para[30] = ""; break; case 31: para[31] = ""; break; case 32: para[32] = ""; break; case 33: para[33] = ""; break; case 34: para[34] = ""; break; case 35: para[35] = ""; break; case 36: para[36] = ""; break; case 37: para[37] = ""; break; case 38: para[38] = ""; break; case 39: para[39] = ""; break; case 40: para[40] = ""; break; } // printf("the swich finished!\n"); } /* 0 */ if( para[0] != NULL ) { print_help(); } /* 1 */ if( para[1] != NULL ) { print_version(); } /* 2 */ if( para[2] != NULL ) { run_daemon(); } /* 3 */ if( para[3] != NULL ) { disk = para[3]; } /* 4 */ if( para[4] != NULL ) { cpu_seq = para[4]; collect_cpu(cpu_seq); } /* 5 */ if( para[5] != NULL ) { interface = para[5]; } /* 6 */ if( para[6] != NULL ) { loadlevel = para[6]; cpu_load(loadlevel); } /* 7 */ if( para[7] != NULL ) { processid = para[7]; } /* 8 */ if( para[8] != NULL ) { collect_mem_proc( "mem_proc" ); } /* 9 */ if( para[9] != NULL ) { collect_mem_proc( "mem_used" ); } /* 10 */ if( para[10] != NULL ) { collect_mem_pri(); } /* 11 */ if( para[11] != NULL ) { collect_mem_vir(); } /* 12 */ if( para[12] != NULL ) { collect_mem_pri_ipcs(); } /* 13 */ if( para[13] != NULL ) { collect_mem_proc( "mswap_used" ); } /* 14 */ if( para[14] != NULL ) { collect_mem_proc( "mswap_total" ); } /* 15 */ if( para[15] != NULL ) { collect_disk_vmstat( "pgpgin"); } /* 16 */ if( para[16] != NULL ) { collect_disk_vmstat( "pgpgout"); } /* 17 */ if( para[17] != NULL ) { collect_disk_vmstat( "pswpin"); } /* 18 */ if( para[18] != NULL ) { collect_disk_vmstat( "pswpout"); } /* 19 */ if( para[19] != NULL ) { collect_diskstats( disk, "svctm" ); } /* 20 */ if( para[20] != NULL ) { collect_diskstats( disk, "await" ); } /* 21 */ if( para[21] != NULL ) { collect_diskstats( disk, "aveq" ); } /* 22 */ if( para[22] != NULL ) { collect_diskstats( disk, "avgrq_sz" ); } /* 23 */ if( para[23] != NULL ) { collect_diskstats( disk, "util" ); } /* 24 */ if( para[24] != NULL ) { collect_net_dev ( interface, "net_byte_in" ); } /* 25 */ if( para[25] != NULL ) { collect_net_dev ( interface, "net_byte_out" ); } /* 26 */ if( para[26] != NULL ) { collect_net_dev ( interface, "net_pack_in" ); } /* 27 */ if( para[27] != NULL ) { collect_net_dev ( interface, "net_pack_out" ); } /* 28 */ if( para[28] != NULL ) { collect_net_snmp( "passiveopens" ); } /* 29 */ if( para[29] != NULL ) { collect_net_snmp( "currestab" ); } /* 30 */ if( para[30] != NULL ) { collect_net_snmp( "indatagrams" ); } /* 31 */ if( para[31] != NULL ) { collect_net_snmp( "outdatagrams" ); } /* 32 */ if( para[32] != NULL ) { collect_hardinfo ( "hard_proc" ); } /* 33 */ if( para[33] != NULL ) { collect_hardinfo ( "hard_mem" ); } /* 34 */ if( para[34] != NULL ) { collect_hardinfo ( "hard_temp" ); } /* 35 */ if( para[35] != NULL ) { collect_hardinfo ( "hard_disk" ); } /* 36 */ if( para[36] != NULL ) { collect_hardinfo ( "hard_pwr" ); } /* 37 */ if( para[37] != NULL ) { collect_hardinfo ( "hard_batt" ); } /* 38 */ if( para[38] != NULL ) { collect_hardinfo ( "hard_nics" ); } /* 39 */ if( para[39] != NULL ) { collect_hardinfo ( "hard_fans" ); } // printf("the while loop finished\n"); return 0; }
/** * main program. Set options given commandline arguments. * @param argc: number of commandline arguments. * @param argv: array of commandline arguments. * @return: exit status of the program. */ int main(int argc, char* argv[]) { int c; const char* cfgfile = CONFIGFILE; const char* winopt = NULL; const char* log_ident_default; int cmdline_verbose = 0; int debug_mode = 0; #ifdef UB_ON_WINDOWS int cmdline_cfg = 0; #endif log_init(NULL, 0, NULL); log_ident_default = strrchr(argv[0],'/')?strrchr(argv[0],'/')+1:argv[0]; log_ident_set(log_ident_default); /* parse the options */ while( (c=getopt(argc, argv, "c:dhvw:")) != -1) { switch(c) { case 'c': cfgfile = optarg; #ifdef UB_ON_WINDOWS cmdline_cfg = 1; #endif break; case 'v': cmdline_verbose++; verbosity++; break; case 'd': debug_mode++; break; case 'w': winopt = optarg; break; case '?': case 'h': default: usage(); return 1; } } argc -= optind; argv += optind; if(winopt) { #ifdef UB_ON_WINDOWS wsvc_command_option(winopt, cfgfile, cmdline_verbose, cmdline_cfg); #else fatal_exit("option not supported"); #endif } if(argc != 0) { usage(); return 1; } run_daemon(cfgfile, cmdline_verbose, debug_mode, log_ident_default); log_init(NULL, 0, NULL); /* close logfile */ return 0; }
/** * main program. Set options given commandline arguments. * @param argc: number of commandline arguments. * @param argv: array of commandline arguments. * @return: exit status of the program. */ int main(int argc, char* argv[]) { int c; const char* cfgfile = CONFIGFILE; const char* winopt = NULL; int cmdline_verbose = 0; int debug_mode = 0; #ifdef UB_ON_WINDOWS int cmdline_cfg = 0; #endif #ifdef HAVE_SBRK /* take debug snapshot of heap */ unbound_start_brk = sbrk(0); #endif log_init(NULL, 0, NULL); /* parse the options */ while( (c=getopt(argc, argv, "c:dhvw:")) != -1) { switch(c) { case 'c': cfgfile = optarg; #ifdef UB_ON_WINDOWS cmdline_cfg = 1; #endif break; case 'v': cmdline_verbose ++; verbosity++; break; case 'd': debug_mode = 1; break; case 'w': winopt = optarg; break; case '?': case 'h': default: usage(); return 1; } } argc -= optind; argv += optind; if(winopt) { #ifdef UB_ON_WINDOWS wsvc_command_option(winopt, cfgfile, cmdline_verbose, cmdline_cfg); #else fatal_exit("option not supported"); #endif } if(argc != 0) { usage(); return 1; } run_daemon(cfgfile, cmdline_verbose, debug_mode); log_init(NULL, 0, NULL); /* close logfile */ return 0; }