int main(int argc, char **argv) { mStatus status; int result; // Parse our command line arguments. This won't come back if there's an error. ParseArguments(argc, argv); // If we're told to run as a daemon, then do that straight away. // Note that we don't treat the inability to create our PID // file as an error. Also note that we assign getpid to a long // because printf has no format specified for pid_t. if (gDaemon) { if (gMDNSPlatformPosixVerboseLevel > 0) { fprintf(stderr, "%s: Starting in daemon mode\n", gProgramName); } daemon(0,0); { FILE *fp; int junk; fp = fopen(gPIDFile, "w"); if (fp != NULL) { fprintf(fp, "%ld\n", (long) getpid()); junk = fclose(fp); assert(junk == 0); } } } else { if (gMDNSPlatformPosixVerboseLevel > 0) { fprintf(stderr, "%s: Starting in foreground mode, PID %ld\n", gProgramName, (long) getpid()); } } status = mDNS_Init(&mDNSStorage, &PlatformStorage, mDNS_Init_NoCache, mDNS_Init_ZeroCacheSize, mDNS_Init_AdvertiseLocalAddresses, mDNS_Init_NoInitCallback, mDNS_Init_NoInitCallbackContext); if (status != mStatus_NoError) return(2); status = RegisterOurServices(); if (status != mStatus_NoError) return(2); signal(SIGHUP, HandleSigHup); // SIGHUP has to be sent by kill -HUP <pid> signal(SIGINT, HandleSigInt); // SIGINT is what you get for a Ctrl-C signal(SIGQUIT, HandleSigQuit); // SIGQUIT is what you get for a Ctrl-\ (indeed) signal(SIGUSR1, HandleSigUsr1); // SIGUSR1 has to be sent by kill -USR1 <pid> while (!gStopNow) { int nfds = 0; fd_set readfds; struct timeval timeout; int result; // 1. Set up the fd_set as usual here. // This example client has no file descriptors of its own, // but a real application would call FD_SET to add them to the set here FD_ZERO(&readfds); // 2. Set up the timeout. // This example client has no other work it needs to be doing, // so we set an effectively infinite timeout timeout.tv_sec = 0x3FFFFFFF; timeout.tv_usec = 0; // 3. Give the mDNSPosix layer a chance to add its information to the fd_set and timeout mDNSPosixGetFDSet(&mDNSStorage, &nfds, &readfds, &timeout); // 4. Call select as normal verbosedebugf("select(%d, %d.%06d)", nfds, timeout.tv_sec, timeout.tv_usec); result = select(nfds, &readfds, NULL, NULL, &timeout); if (result < 0) { verbosedebugf("select() returned %d errno %d", result, errno); if (errno != EINTR) gStopNow = mDNStrue; else { if (gReceivedSigUsr1) { gReceivedSigUsr1 = mDNSfalse; gMDNSPlatformPosixVerboseLevel += 1; if (gMDNSPlatformPosixVerboseLevel > 2) gMDNSPlatformPosixVerboseLevel = 0; if ( gMDNSPlatformPosixVerboseLevel > 0 ) fprintf(stderr, "\nVerbose level %d\n", gMDNSPlatformPosixVerboseLevel); } if (gReceivedSigHup) { if (gMDNSPlatformPosixVerboseLevel > 0) fprintf(stderr, "\nSIGHUP\n"); gReceivedSigHup = mDNSfalse; DeregisterOurServices(); status = mDNSPlatformPosixRefreshInterfaceList(&mDNSStorage); if (status != mStatus_NoError) break; status = RegisterOurServices(); if (status != mStatus_NoError) break; } } } else { // 5. Call mDNSPosixProcessFDSet to let the mDNSPosix layer do its work mDNSPosixProcessFDSet(&mDNSStorage, &readfds); // 6. This example client has no other work it needs to be doing, // but a real client would do its work here // ... (do work) ... } } debugf("Exiting"); DeregisterOurServices(); mDNS_Close(&mDNSStorage); if (status == mStatus_NoError) { result = 0; } else { result = 2; } if ( (result != 0) || (gMDNSPlatformPosixVerboseLevel > 0) ) { fprintf(stderr, "%s: Finished with status %d, result %d\n", gProgramName, (int)status, result); } return result; }
int main(int argc, char * argv[]) { struct timeval timeout; fd_set fdset; int nfds; struct pidfh *pfh = NULL; const char *pidfile = NULL; int freq, curfreq, initfreq, *freqs, i, j, *mwatts, numfreqs, load; int minfreq = -1, maxfreq = -1; int ch, mode, mode_ac, mode_battery, mode_none, idle, to; uint64_t mjoules_used; size_t len; /* Default mode for all AC states is adaptive. */ mode_ac = mode_none = MODE_HIADAPTIVE; mode_battery = MODE_ADAPTIVE; cpu_running_mark = DEFAULT_ACTIVE_PERCENT; cpu_idle_mark = DEFAULT_IDLE_PERCENT; poll_ival = DEFAULT_POLL_INTERVAL; mjoules_used = 0; vflag = 0; /* User must be root to control frequencies. */ if (geteuid() != 0) errx(1, "must be root to run"); while ((ch = getopt(argc, argv, "a:b:i:m:M:n:p:P:r:v")) != -1) switch (ch) { case 'a': parse_mode(optarg, &mode_ac, ch); break; case 'b': parse_mode(optarg, &mode_battery, ch); break; case 'i': cpu_idle_mark = atoi(optarg); if (cpu_idle_mark < 0 || cpu_idle_mark > 100) { warnx("%d is not a valid percent", cpu_idle_mark); usage(); } break; case 'm': minfreq = atoi(optarg); if (minfreq < 0) { warnx("%d is not a valid CPU frequency", minfreq); usage(); } break; case 'M': maxfreq = atoi(optarg); if (maxfreq < 0) { warnx("%d is not a valid CPU frequency", maxfreq); usage(); } break; case 'n': parse_mode(optarg, &mode_none, ch); break; case 'p': poll_ival = atoi(optarg); if (poll_ival < 5) { warnx("poll interval is in units of ms"); usage(); } break; case 'P': pidfile = optarg; break; case 'r': cpu_running_mark = atoi(optarg); if (cpu_running_mark <= 0 || cpu_running_mark > 100) { warnx("%d is not a valid percent", cpu_running_mark); usage(); } break; case 'v': vflag = 1; break; default: usage(); } mode = mode_none; /* Poll interval is in units of ms. */ poll_ival *= 1000; /* Look up various sysctl MIBs. */ len = 2; if (sysctlnametomib("kern.cp_times", cp_times_mib, &len)) err(1, "lookup kern.cp_times"); len = 4; if (sysctlnametomib("dev.cpu.0.freq", freq_mib, &len)) err(EX_UNAVAILABLE, "no cpufreq(4) support -- aborting"); len = 4; if (sysctlnametomib("dev.cpu.0.freq_levels", levels_mib, &len)) err(1, "lookup freq_levels"); /* Check if we can read the load and supported freqs. */ if (read_usage_times(NULL)) err(1, "read_usage_times"); if (read_freqs(&numfreqs, &freqs, &mwatts, minfreq, maxfreq)) err(1, "error reading supported CPU frequencies"); if (numfreqs == 0) errx(1, "no CPU frequencies in user-specified range"); /* Run in the background unless in verbose mode. */ if (!vflag) { pid_t otherpid; pfh = pidfile_open(pidfile, 0600, &otherpid); if (pfh == NULL) { if (errno == EEXIST) { errx(1, "powerd already running, pid: %d", otherpid); } warn("cannot open pid file"); } if (daemon(0, 0) != 0) { warn("cannot enter daemon mode, exiting"); pidfile_remove(pfh); exit(EXIT_FAILURE); } pidfile_write(pfh); } /* Decide whether to use ACPI or APM to read the AC line status. */ acline_init(); /* * Exit cleanly on signals. */ signal(SIGINT, handle_sigs); signal(SIGTERM, handle_sigs); freq = initfreq = curfreq = get_freq(); i = get_freq_id(curfreq, freqs, numfreqs); if (freq < 1) freq = 1; /* * If we are in adaptive mode and the current frequency is outside the * user-defined range, adjust it to be within the user-defined range. */ acline_read(); if (acline_status > SRC_UNKNOWN) errx(1, "invalid AC line status %d", acline_status); if ((acline_status == SRC_AC && (mode_ac == MODE_ADAPTIVE || mode_ac == MODE_HIADAPTIVE)) || (acline_status == SRC_BATTERY && (mode_battery == MODE_ADAPTIVE || mode_battery == MODE_HIADAPTIVE)) || (acline_status == SRC_UNKNOWN && (mode_none == MODE_ADAPTIVE || mode_none == MODE_HIADAPTIVE))) { /* Read the current frequency. */ len = sizeof(curfreq); if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) { if (vflag) warn("error reading current CPU frequency"); } if (curfreq < freqs[numfreqs - 1]) { if (vflag) { printf("CPU frequency is below user-defined " "minimum; changing frequency to %d " "MHz\n", freqs[numfreqs - 1]); } if (set_freq(freqs[numfreqs - 1]) != 0) { warn("error setting CPU freq %d", freqs[numfreqs - 1]); } } else if (curfreq > freqs[0]) { if (vflag) { printf("CPU frequency is above user-defined " "maximum; changing frequency to %d " "MHz\n", freqs[0]); } if (set_freq(freqs[0]) != 0) { warn("error setting CPU freq %d", freqs[0]); } } } idle = 0; /* Main loop. */ for (;;) { FD_ZERO(&fdset); if (devd_pipe >= 0) { FD_SET(devd_pipe, &fdset); nfds = devd_pipe + 1; } else { nfds = 0; } if (mode == MODE_HIADAPTIVE || idle < 120) to = poll_ival; else if (idle < 360) to = poll_ival * 2; else to = poll_ival * 4; timeout.tv_sec = to / 1000000; timeout.tv_usec = to % 1000000; select(nfds, &fdset, NULL, &fdset, &timeout); /* If the user requested we quit, print some statistics. */ if (exit_requested) { if (vflag && mjoules_used != 0) printf("total joules used: %u.%03u\n", (u_int)(mjoules_used / 1000), (int)mjoules_used % 1000); break; } /* Read the current AC status and record the mode. */ acline_read(); switch (acline_status) { case SRC_AC: mode = mode_ac; break; case SRC_BATTERY: mode = mode_battery; break; case SRC_UNKNOWN: mode = mode_none; break; default: errx(1, "invalid AC line status %d", acline_status); } /* Read the current frequency. */ if (idle % 32 == 0) { if ((curfreq = get_freq()) == 0) continue; i = get_freq_id(curfreq, freqs, numfreqs); } idle++; if (vflag) { /* Keep a sum of all power actually used. */ if (mwatts[i] != -1) mjoules_used += (mwatts[i] * (poll_ival / 1000)) / 1000; } /* Always switch to the lowest frequency in min mode. */ if (mode == MODE_MIN) { freq = freqs[numfreqs - 1]; if (curfreq != freq) { if (vflag) { printf("now operating on %s power; " "changing frequency to %d MHz\n", modes[acline_status], freq); } idle = 0; if (set_freq(freq) != 0) { warn("error setting CPU freq %d", freq); continue; } } continue; } /* Always switch to the highest frequency in max mode. */ if (mode == MODE_MAX) { freq = freqs[0]; if (curfreq != freq) { if (vflag) { printf("now operating on %s power; " "changing frequency to %d MHz\n", modes[acline_status], freq); } idle = 0; if (set_freq(freq) != 0) { warn("error setting CPU freq %d", freq); continue; } } continue; } /* Adaptive mode; get the current CPU usage times. */ if (read_usage_times(&load)) { if (vflag) warn("read_usage_times() failed"); continue; } if (mode == MODE_ADAPTIVE) { if (load > cpu_running_mark) { if (load > 95 || load > cpu_running_mark * 2) freq *= 2; else freq = freq * load / cpu_running_mark; if (freq > freqs[0]) freq = freqs[0]; } else if (load < cpu_idle_mark && curfreq * load < freqs[get_freq_id( freq * 7 / 8, freqs, numfreqs)] * cpu_running_mark) { freq = freq * 7 / 8; if (freq < freqs[numfreqs - 1]) freq = freqs[numfreqs - 1]; } } else { /* MODE_HIADAPTIVE */ if (load > cpu_running_mark / 2) { if (load > 95 || load > cpu_running_mark) freq *= 4; else freq = freq * load * 2 / cpu_running_mark; if (freq > freqs[0] * 2) freq = freqs[0] * 2; } else if (load < cpu_idle_mark / 2 && curfreq * load < freqs[get_freq_id( freq * 31 / 32, freqs, numfreqs)] * cpu_running_mark / 2) { freq = freq * 31 / 32; if (freq < freqs[numfreqs - 1]) freq = freqs[numfreqs - 1]; } } if (vflag) { printf("load %3d%%, current freq %4d MHz (%2d), wanted freq %4d MHz\n", load, curfreq, i, freq); } j = get_freq_id(freq, freqs, numfreqs); if (i != j) { if (vflag) { printf("changing clock" " speed from %d MHz to %d MHz\n", freqs[i], freqs[j]); } idle = 0; if (set_freq(freqs[j])) warn("error setting CPU frequency %d", freqs[j]); } } if (set_freq(initfreq)) warn("error setting CPU frequency %d", initfreq); free(freqs); free(mwatts); devd_close(); if (!vflag) pidfile_remove(pfh); exit(0); }
int main(int argc, char *argv[]) { char *buf; struct disk *disks, *dp; int ch, ok; long long minwait, nextwait; struct sigaction sa; long long counter; int initial_debug; const char *conf_file, *save_file; conf_file = _PATH_CONF; save_file = _PATH_SAVE; debug = 0; while ((ch = getopt(argc, argv, "df:o:")) != -1) switch (ch) { case 'd': if (debug) debug *= 2; else debug = 1; break; case 'f': conf_file = optarg; break; case 'o': save_file = optarg; break; default: usage(); /* NOTREACHED */ } argv += optind; argc -= optind; if (argc != 0) usage(); initial_debug = debug; openlog("diskcheckd", LOG_CONS|LOG_PID|(debug?LOG_PERROR:0), LOG_DAEMON); if (!debug && daemon(0, 0) < 0) { syslog(LOG_NOTICE, "daemon() failure: %m"); exit(EXIT_FAILURE); } sa.sa_handler = sigterm; sa.sa_flags = SA_RESTART; sigemptyset(&sa.sa_mask); sigaction(SIGTERM, &sa, NULL); sigaction(SIGINT, &sa, NULL); sa.sa_handler = sighup; sigaction(SIGHUP, &sa, NULL); /* Read the configuration file and the saved offsets */ disks = readconf(conf_file); readoffsets(disks, save_file); if ((buf = malloc(READ_SIZE)) == NULL) { syslog(LOG_NOTICE, "malloc failure: %m"); exit(EXIT_FAILURE); } /* The main disk checking loop. * * We wait the shortest amount of time we need to before * another disk is due for a read -- this time is updated * in the 'nextwait' variable, which is then copied to * 'minwait'. After a sleep, 'minwait' is subtracted from * each disk's 'next' field, and when that reaches zero, * that disk is read again. */ counter = 0LL; minwait = 0LL; while (!got_sigterm) { ok = 0; nextwait = LLONG_MAX; for (dp = disks; dp->device != NULL; dp++) if (dp->fd != -1) { if (debug > 1) fprintf(stderr, "%s: next(%qd) -= %qd\n", dp->device, dp->next, minwait); if ((dp->next -= minwait) == 0) { ok = 1; readchunk(dp, buf); } /* XXX debugging */ if (dp->next < 0LL) { syslog(LOG_NOTICE, "dp->next < 0 for %s", dp->device); abort(); } if (dp->next < nextwait) nextwait = dp->next; } if (!ok) { syslog(LOG_EMERG, "all disks had read errors"); exit(EXIT_FAILURE); } /* 300 seconds => 5 minutes */ if (counter >= 300000000LL) { if (debug) fprintf(stderr, "counter rollover %qd => 0\n", counter); updateproctitle(disks); writeoffsets(disks, save_file); counter = 0LL; } minwait = nextwait; if (debug > 1) { --debug; fprintf(stderr, "sleep %qd, counter %qd\n", minwait, counter); } /* * Handle whole seconds and usec separately to avoid overflow * when calling usleep -- useconds_t is only 32 bits on at * least some architectures, and minwait (being long long) * may exceed INT_MAX. */ if (minwait > 1000000LL) sleep((unsigned int)(minwait / 1000000)); if ((minwait % 1000000) > 0) usleep((useconds_t)(minwait % 1000000)); counter += minwait; if (got_sighup) { /* * Got a SIGHUP, so save the offsets, free the * memory used for the disk structures, and then * re-read the config file and the disk offsets. */ if (debug) { fprintf(stderr, "got SIGHUP, counter == %qd\n", counter); debug = initial_debug; } writeoffsets(disks, save_file); for (dp = disks; dp->device != NULL; dp++) { free(dp->device); close(dp->fd); } free(disks); disks = readconf(conf_file); readoffsets(disks, save_file); minwait = 0LL; got_sighup = 0; } } if (debug) fprintf(stderr, "got %s, counter == %qd\n", got_sigterm==SIGTERM?"SIGTERM":"SIGINT", counter); writeoffsets(disks, save_file); return (EXIT_SUCCESS); }
// Setup dbus server static int thd_dbus_server_proc(gboolean no_daemon) { DBusGConnection *bus; DBusGProxy *bus_proxy; GMainLoop *main_loop; GError *error = NULL; guint result; PrefObject *value_obj; // Initialize the GType/GObject system g_type_init(); // Create a main loop that will dispatch callbacks main_loop = g_main_loop_new(NULL, FALSE); if(main_loop == NULL) { thd_log_error("Couldn't create GMainLoop:"); return THD_FATAL_ERROR; } if(dbus_enable) { bus = dbus_g_bus_get(DBUS_BUS_SYSTEM, &error); if(error != NULL) { thd_log_error("Couldn't connect to session bus: %s:", error->message); return THD_FATAL_ERROR; } // Get a bus proxy instance bus_proxy = dbus_g_proxy_new_for_name(bus, DBUS_SERVICE_DBUS, DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS); if(bus_proxy == NULL) { thd_log_error("Failed to get a proxy for D-Bus:"); return THD_FATAL_ERROR; } thd_log_debug("Registering the well-known name (%s)\n", THD_SERVICE_NAME); // register the well-known name if(!dbus_g_proxy_call(bus_proxy, "RequestName", &error, G_TYPE_STRING, THD_SERVICE_NAME, G_TYPE_UINT, 0, G_TYPE_INVALID, G_TYPE_UINT, &result, G_TYPE_INVALID)) { thd_log_error("D-Bus.RequestName RPC failed: %s\n", error->message); return THD_FATAL_ERROR; } thd_log_debug("RequestName returned %d.\n", result); if(result != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) { thd_log_error("Failed to get the primary well-known name:"); return THD_FATAL_ERROR; } value_obj = (PrefObject*)g_object_new(PREF_TYPE_OBJECT, NULL); if(value_obj == NULL) { thd_log_error("Failed to create one Value instance:"); return THD_FATAL_ERROR; } thd_log_debug("Registering it on the D-Bus.\n"); dbus_g_connection_register_g_object(bus, THD_SERVICE_OBJECT_PATH, G_OBJECT (value_obj)); } if(!no_daemon) { printf("Ready to serve requests: Daemonizing.. %d\n", thd_daemonize); thd_log_info("thermald ver %s: Ready to serve requests: Daemonizing..\n", TD_DIST_VERSION); if(daemon(0, 1) != 0) { thd_log_error("Failed to daemonize.\n"); return THD_FATAL_ERROR; } } if(use_thermal_sys_fs) thd_engine = new cthd_engine_therm_sysfs(); else { cthd_parse parser; bool matched = false; // if there is XML config for this platform // Use this instead of default DTS sensor and associated cdevs if(parser.parser_init() == THD_SUCCESS) { if(parser.start_parse() == THD_SUCCESS) { matched = parser.platform_matched(); } } if (matched) { thd_log_warn("UUID matched, so will load zones and cdevs from thermal-conf.xml\n"); thd_engine = new cthd_engine_therm_sysfs(); } else thd_engine = new cthd_engine_dts(); } // Initialize thermald objects if(thd_engine->thd_engine_start() != THD_SUCCESS) { thd_log_error("THD engine start failed: "); closelog(); exit(1); } // Start service requests on the D-Bus thd_log_debug("Start main loop\n"); g_main_loop_run(main_loop); thd_log_warn("Oops g main loop exit..\n"); return THD_SUCCESS; }
int main(int argc, char **argv) { krb5_error_code ret; krb5_context context; krb5_kdc_configuration *config; setprogname(argv[0]); ret = krb5_init_context(&context); if (ret == KRB5_CONFIG_BADFORMAT) errx (1, "krb5_init_context failed to parse configuration file"); else if (ret) errx (1, "krb5_init_context failed: %d", ret); ret = krb5_kt_register(context, &hdb_kt_ops); if (ret) errx (1, "krb5_kt_register(HDB) failed: %d", ret); config = configure(context, argc, argv); #ifdef HAVE_SIGACTION { struct sigaction sa; sa.sa_flags = 0; sa.sa_handler = sigterm; sigemptyset(&sa.sa_mask); sigaction(SIGINT, &sa, NULL); sigaction(SIGTERM, &sa, NULL); #ifdef SIGXCPU sigaction(SIGXCPU, &sa, NULL); #endif sa.sa_handler = SIG_IGN; #ifdef SIGPIPE sigaction(SIGPIPE, &sa, NULL); #endif } #else signal(SIGINT, sigterm); signal(SIGTERM, sigterm); #ifdef SIGXCPU signal(SIGXCPU, sigterm); #endif #ifdef SIGPIPE signal(SIGPIPE, SIG_IGN); #endif #endif #ifdef SUPPORT_DETACH if (detach_from_console) daemon(0, 0); #endif #ifdef __APPLE__ bonjour_announce(context, config); #endif pidfile(NULL); switch_environment(); loop(context, config); krb5_free_context(context); return 0; }
/** * Initialize a libvlc instance * This function initializes a previously allocated libvlc instance: * - CPU detection * - gettext initialization * - message queue, module bank and playlist initialization * - configuration and commandline parsing */ int libvlc_InternalInit( libvlc_int_t *p_libvlc, int i_argc, const char *ppsz_argv[] ) { libvlc_priv_t *priv = libvlc_priv (p_libvlc); char * psz_modules = NULL; char * psz_parser = NULL; char * psz_control = NULL; char *psz_val; /* System specific initialization code */ system_Init(); vlc_LogPreinit(p_libvlc); /* Initialize the module bank and load the configuration of the * core module. We need to do this at this stage to be able to display * a short help if required by the user. (short help == core module * options) */ module_InitBank (); /* Get command line options that affect module loading. */ if( config_LoadCmdLine( p_libvlc, i_argc, ppsz_argv, NULL ) ) { module_EndBank (false); return VLC_EGENERIC; } vlc_threads_setup (p_libvlc); /* Load the builtins and plugins into the module_bank. * We have to do it before config_Load*() because this also gets the * list of configuration options exported by each module and loads their * default values. */ size_t module_count = module_LoadPlugins (p_libvlc); /* * Override default configuration with config file settings */ if( !var_InheritBool( p_libvlc, "ignore-config" ) ) { if( var_InheritBool( p_libvlc, "reset-config" ) ) config_SaveConfigFile( p_libvlc ); /* Save default config */ else config_LoadConfigFile( p_libvlc ); } /* * Override configuration with command line settings */ int vlc_optind; if( config_LoadCmdLine( p_libvlc, i_argc, ppsz_argv, &vlc_optind ) ) { vlc_LogDeinit (p_libvlc); module_EndBank (true); return VLC_EGENERIC; } vlc_LogInit(p_libvlc); /* * Support for gettext */ #if defined( ENABLE_NLS ) \ && ( defined( HAVE_GETTEXT ) || defined( HAVE_INCLUDED_GETTEXT ) ) vlc_bindtextdomain (PACKAGE_NAME); #endif /*xgettext: Translate "C" to the language code: "fr", "en_GB", "nl", "ru"... */ msg_Dbg( p_libvlc, "translation test: code is \"%s\"", _("C") ); if (config_PrintHelp (VLC_OBJECT(p_libvlc))) { module_EndBank (true); exit(0); } if( module_count <= 1 ) { msg_Err( p_libvlc, "No plugins found! Check your VLC installation."); vlc_LogDeinit (p_libvlc); module_EndBank (true); return VLC_ENOMOD; } #ifdef HAVE_DAEMON /* Check for daemon mode */ if( var_InheritBool( p_libvlc, "daemon" ) ) { if( daemon( 1, 0) != 0 ) { msg_Err( p_libvlc, "Unable to fork vlc to daemon mode" ); vlc_LogDeinit (p_libvlc); module_EndBank (true); return VLC_ENOMEM; } /* lets check if we need to write the pidfile */ char *pidfile = var_InheritString( p_libvlc, "pidfile" ); if( pidfile != NULL ) { FILE *stream = vlc_fopen( pidfile, "w" ); if( stream != NULL ) { fprintf( stream, "%d", (int)getpid() ); fclose( stream ); msg_Dbg( p_libvlc, "written PID file %s", pidfile ); } else msg_Err( p_libvlc, "cannot write PID file %s: %s", pidfile, vlc_strerror_c(errno) ); free( pidfile ); } } else { var_Create( p_libvlc, "pidfile", VLC_VAR_STRING ); var_SetString( p_libvlc, "pidfile", "" ); } #endif if( libvlc_InternalDialogInit( p_libvlc ) != VLC_SUCCESS ) { vlc_LogDeinit (p_libvlc); module_EndBank (true); return VLC_ENOMEM; } if( libvlc_InternalKeystoreInit( p_libvlc ) != VLC_SUCCESS ) msg_Warn( p_libvlc, "memory keystore init failed" ); /* FIXME: could be replaced by using Unix sockets */ #ifdef HAVE_DBUS #define MPRIS_APPEND "/org/mpris/MediaPlayer2/TrackList/Append" #define MPRIS_BUS_NAME "org.mpris.MediaPlayer2.vlc" #define MPRIS_OBJECT_PATH "/org/mpris/MediaPlayer2" #define MPRIS_TRACKLIST_INTERFACE "org.mpris.MediaPlayer2.TrackList" if( var_InheritBool( p_libvlc, "one-instance" ) || ( var_InheritBool( p_libvlc, "one-instance-when-started-from-file" ) && var_InheritBool( p_libvlc, "started-from-file" ) ) ) { for( int i = vlc_optind; i < i_argc; i++ ) if( ppsz_argv[i][0] == ':' ) { msg_Err( p_libvlc, "item option %s incompatible with single instance", ppsz_argv[i] ); goto dbus_out; } /* Initialise D-Bus interface, check for other instances */ dbus_threads_init_default(); DBusError err; dbus_error_init( &err ); /* connect to the session bus */ DBusConnection *conn = dbus_bus_get( DBUS_BUS_SESSION, &err ); if( conn == NULL ) { msg_Err( p_libvlc, "Failed to connect to D-Bus session daemon: %s", err.message ); dbus_error_free( &err ); goto dbus_out; } /* check if VLC is available on the bus * if not: D-Bus control is not enabled on the other * instance and we can't pass MRLs to it */ /* FIXME: This check is totally brain-dead and buggy. */ if( !dbus_bus_name_has_owner( conn, MPRIS_BUS_NAME, &err ) ) { dbus_connection_unref( conn ); if( dbus_error_is_set( &err ) ) { msg_Err( p_libvlc, "D-Bus error: %s", err.message ); } else msg_Dbg( p_libvlc, "No media player running. Continuing normally." ); dbus_error_free( &err ); goto dbus_out; } const dbus_bool_t play = !var_InheritBool( p_libvlc, "playlist-enqueue" ); msg_Warn( p_libvlc, "media player running. Exiting..."); for( int i = vlc_optind; i < i_argc; i++ ) { DBusMessage *msg = dbus_message_new_method_call( MPRIS_BUS_NAME, MPRIS_OBJECT_PATH, MPRIS_TRACKLIST_INTERFACE, "AddTrack" ); if( unlikely(msg == NULL) ) continue; /* We need to resolve relative paths in this instance */ char *mrl; if( strstr( ppsz_argv[i], "://" ) ) mrl = strdup( ppsz_argv[i] ); else mrl = vlc_path2uri( ppsz_argv[i], NULL ); if( mrl == NULL ) { dbus_message_unref( msg ); continue; } const char *after_track = MPRIS_APPEND; /* append MRLs */ if( !dbus_message_append_args( msg, DBUS_TYPE_STRING, &mrl, DBUS_TYPE_OBJECT_PATH, &after_track, DBUS_TYPE_BOOLEAN, &play, DBUS_TYPE_INVALID ) ) { dbus_message_unref( msg ); msg = NULL; free( mrl ); continue; } msg_Dbg( p_libvlc, "Adds %s to the running media player", mrl ); free( mrl ); /* send message and get a handle for a reply */ DBusMessage *reply = dbus_connection_send_with_reply_and_block( conn, msg, -1, &err ); dbus_message_unref( msg ); if( reply == NULL ) { msg_Err( p_libvlc, "D-Bus error: %s", err.message ); continue; } dbus_message_unref( reply ); } /* we unreference the connection when we've finished with it */ dbus_connection_unref( conn ); exit( 0 ); } #undef MPRIS_APPEND #undef MPRIS_BUS_NAME #undef MPRIS_OBJECT_PATH #undef MPRIS_TRACKLIST_INTERFACE dbus_out: #endif // HAVE_DBUS vlc_CPU_dump( VLC_OBJECT(p_libvlc) ); priv->b_stats = var_InheritBool( p_libvlc, "stats" ); /* * Initialize hotkey handling */ priv->actions = vlc_InitActions( p_libvlc ); /* * Meta data handling */ priv->parser = playlist_preparser_New(VLC_OBJECT(p_libvlc)); /* Create a variable for showing the fullscreen interface */ var_Create( p_libvlc, "intf-toggle-fscontrol", VLC_VAR_BOOL ); var_SetBool( p_libvlc, "intf-toggle-fscontrol", true ); /* Create a variable for the Boss Key */ var_Create( p_libvlc, "intf-boss", VLC_VAR_VOID ); /* Create a variable for showing the main interface */ var_Create( p_libvlc, "intf-show", VLC_VAR_BOOL ); /* Create a variable for showing the right click menu */ var_Create( p_libvlc, "intf-popupmenu", VLC_VAR_BOOL ); /* variables for signalling creation of new files */ var_Create( p_libvlc, "snapshot-file", VLC_VAR_STRING ); var_Create( p_libvlc, "record-file", VLC_VAR_STRING ); /* some default internal settings */ var_Create( p_libvlc, "window", VLC_VAR_STRING ); /* NOTE: Because the playlist and interfaces start before this function * returns control to the application (DESIGN BUG!), all these variables * must be created (in place of libvlc_new()) and set to VLC defaults * (in place of VLC main()) *here*. */ var_Create( p_libvlc, "user-agent", VLC_VAR_STRING ); var_SetString( p_libvlc, "user-agent", "VLC media player (LibVLC "VERSION")" ); var_Create( p_libvlc, "http-user-agent", VLC_VAR_STRING ); var_SetString( p_libvlc, "http-user-agent", "VLC/"PACKAGE_VERSION" LibVLC/"PACKAGE_VERSION ); var_Create( p_libvlc, "app-icon-name", VLC_VAR_STRING ); var_SetString( p_libvlc, "app-icon-name", PACKAGE_NAME ); var_Create( p_libvlc, "app-id", VLC_VAR_STRING ); var_SetString( p_libvlc, "app-id", "org.VideoLAN.VLC" ); var_Create( p_libvlc, "app-version", VLC_VAR_STRING ); var_SetString( p_libvlc, "app-version", PACKAGE_VERSION ); /* System specific configuration */ system_Configure( p_libvlc, i_argc - vlc_optind, ppsz_argv + vlc_optind ); #ifdef ENABLE_VLM /* Initialize VLM if vlm-conf is specified */ psz_parser = var_CreateGetNonEmptyString( p_libvlc, "vlm-conf" ); if( psz_parser ) { priv->p_vlm = vlm_New( p_libvlc ); if( !priv->p_vlm ) msg_Err( p_libvlc, "VLM initialization failed" ); } free( psz_parser ); #endif /* * Load background interfaces */ psz_modules = var_CreateGetNonEmptyString( p_libvlc, "extraintf" ); psz_control = var_CreateGetNonEmptyString( p_libvlc, "control" ); if( psz_modules && psz_control ) { char* psz_tmp; if( asprintf( &psz_tmp, "%s:%s", psz_modules, psz_control ) != -1 ) { free( psz_modules ); psz_modules = psz_tmp; } } else if( psz_control ) { free( psz_modules ); psz_modules = strdup( psz_control ); } psz_parser = psz_modules; while ( psz_parser && *psz_parser ) { char *psz_module, *psz_temp; psz_module = psz_parser; psz_parser = strchr( psz_module, ':' ); if ( psz_parser ) { *psz_parser = '\0'; psz_parser++; } if( asprintf( &psz_temp, "%s,none", psz_module ) != -1) { libvlc_InternalAddIntf( p_libvlc, psz_temp ); free( psz_temp ); } } free( psz_modules ); free( psz_control ); if( var_InheritBool( p_libvlc, "network-synchronisation") ) libvlc_InternalAddIntf( p_libvlc, "netsync,none" ); #ifdef __APPLE__ var_Create( p_libvlc, "drawable-view-top", VLC_VAR_INTEGER ); var_Create( p_libvlc, "drawable-view-left", VLC_VAR_INTEGER ); var_Create( p_libvlc, "drawable-view-bottom", VLC_VAR_INTEGER ); var_Create( p_libvlc, "drawable-view-right", VLC_VAR_INTEGER ); var_Create( p_libvlc, "drawable-clip-top", VLC_VAR_INTEGER ); var_Create( p_libvlc, "drawable-clip-left", VLC_VAR_INTEGER ); var_Create( p_libvlc, "drawable-clip-bottom", VLC_VAR_INTEGER ); var_Create( p_libvlc, "drawable-clip-right", VLC_VAR_INTEGER ); var_Create( p_libvlc, "drawable-nsobject", VLC_VAR_ADDRESS ); #endif /* * Get input filenames given as commandline arguments. * We assume that the remaining parameters are filenames * and their input options. */ GetFilenames( p_libvlc, i_argc - vlc_optind, ppsz_argv + vlc_optind ); /* * Get --open argument */ psz_val = var_InheritString( p_libvlc, "open" ); if ( psz_val != NULL ) { intf_InsertItem( p_libvlc, psz_val, 0, NULL, 0 ); free( psz_val ); } return VLC_SUCCESS; }
int main(int argc, char **argv) { struct sigaction sa; if (parse_argv(argc, argv) < 0) _exit(100); snprintf(status_files[0], 1024, "%s/lock", status_dir); snprintf(status_files[1], 1024, "%s/control", status_dir); snprintf(status_files[2], 1024, "%s/ok", status_dir); snprintf(status_files[3], 1024, "%s/status", status_dir); snprintf(status_files[4], 1024, "%s/status.new", status_dir); snprintf(status_files[5], 1024, "%s/supervise.log", status_dir); snprintf(status_files[6], 1024, "%s/supervise.log.wf", status_dir); sa.sa_handler = SIG_IGN; sigemptyset(&sa.sa_mask); if (sigaction(SIGHUP, &sa, NULL) < 0) { printf("unable to ignore SIGHUP for %s\n", service); _exit(110); } if (mkdir(status_dir, 0700) < 0 && errno != EEXIST) { printf("unable to create dir: %s\n", status_dir); _exit(110); } fdlog = open_append(status_files[5]); if (fdlog == -1) { printf("unable to open %s%s", status_dir, "/supervise.log"); _exit(111); } coe(fdlog); fdlogwf = open_append(status_files[6]); if (fdlogwf == -1) { printf("unable to open %s%s", status_dir, "/supervise.log.wf"); _exit(1); } coe(fdlogwf); if (daemon(1, 0) < 0) { printf("failed to daemonize supervise!\n"); _exit(111); } if (pipe(selfpipe) == -1) { write_log(fdlogwf, FATAL, "unable to create pipe for ", service, "\n"); _exit(111); } coe(selfpipe[0]); coe(selfpipe[1]); ndelay_on(selfpipe[0]); ndelay_on(selfpipe[1]); sig_block(sig_child); sig_catch(sig_child, trigger); sig_block(sig_alarm); sig_catch(sig_alarm, timer_handler); sig_unblock(sig_alarm); fdlock = open_append(status_files[0]); if ((fdlock == -1) || (lock_exnb(fdlock) == -1)) { write_log(fdlogwf, FATAL, "Unable to acquier ", status_dir, "/lock\n"); _exit(111); } coe(fdlock); fifo_make(status_files[1], 0600); fdcontrol = open_read(status_files[1]); if (fdcontrol == -1) { write_log(fdlogwf, FATAL, "unable to read ", status_dir, "/control\n"); _exit(1); } coe(fdcontrol); ndelay_on(fdcontrol); fdcontrolwrite = open_write(status_files[1]); if (fdcontrolwrite == -1) { write_log(fdlogwf, FATAL, "unable to write ", status_dir, "/control\n"); _exit(1); } coe(fdcontrolwrite); fifo_make(status_files[2], 0600); fdok = open_read(status_files[2]); if (fdok == -1) { write_log(fdlogwf, FATAL, "unable to read ", status_dir, "/ok\n"); _exit(1); } coe(fdok); if (!restart_sh[0]) { parse_conf(); } pidchange(); announce(); if (!flagwant || flagwantup) trystart(); doit(); announce(); _exit(0); }
int main (int ac, char *av[]) { int ret,ch,daemonize=0; char *logfile=NULL; struct destination *destination; struct listener *listener; signal(SIGPIPE ,SIG_IGN); if (ac==1) { usage(); } /* destination is global variable a pointer to struct destination * struct destination forms a linked list * first_destination is pointer to first struct * * struct listener is the same */ first_destination=destination=malloc(sizeof(struct destination)); listener=NULL; while ((ch = getopt(ac, av, "bd:s:m:l:M:")) != -1) { switch (ch) { case 'b': daemonize=1; break; case 's': case 'm': if (listener==NULL) { first_listener = listener = malloc(sizeof(struct listener)); } else { listener->next = malloc(sizeof(struct listener)); listener = listener->next; } listener->s=strdup(optarg); listener->fd=create_listen_socket(optarg); listener->next=NULL; /* vynulujeme statistiky */ listener->nr_conn=0; listener->nr_allconn=0; listener->input_bytes=0; listener->output_bytes=0; if (ch=='s') { listener->type=LISTENER_DEFAULT; } else if (ch=='m') { listener->type=LISTENER_STATS; } break; case 'M': /* enable mysql module */ mysql_cdb_file=strdup(optarg); break; case 'd': prepareclient(optarg, destination); break; case 'l': logfile=strdup(optarg); break; } } event_base=event_base_new(); /* if mysql module is enabled, open cdb file and create EV_SIGNAL event which call repoen_cdb(). * if someone send SIGUSR1 cdb file is reopened, but this is automatically triggered by timeout with * CDB_RELOAD_TIME seconds (default 2s) * * reopen_cdb is called from main event loop, it is not called directly by signal, * so it is race condition free (safe to free and init global cdb variable) */ if (mysql_cdb_file) { init_mysql_cdb_file(); } if (daemonize) { if (logfile) { if (daemon(0,1)<0) { perror("daemon()"); exit(0); } close(0); close(1); close(2); ret=open(logfile, O_WRONLY|O_CREAT|O_APPEND, S_IRUSR|S_IWUSR); if (ret!=-1) { dup2(ret,1); dup2(ret,2); } } else { if (daemon(0,0)<0) { perror("daemon()"); exit(0); } } } /* add all listen (-s -m) ports to event_base, if someone connect: accept_connect is executed with struct listener argument */ for (listener=first_listener; listener; listener=listener->next) { struct event *ev; ev=event_new(event_base, listener->fd, EV_READ|EV_PERSIST, accept_connect, listener); event_add(ev,NULL); } /* main libevent loop */ event_base_loop(event_base,0); usage(); exit(0); }
/** * Initialize with AMF * @param amf_sel_obj [out] * * @return SaAisErrorT */ static SaAisErrorT amf_initialize(SaSelectionObjectT *amf_sel_obj) { SaAisErrorT rc; SaAmfCallbacksT amf_callbacks = {0}; SaVersionT api_ver = {.releaseCode = 'B', api_ver.majorVersion = 0x01, api_ver.minorVersion = 0x01}; /* Initialize our callbacks */ amf_callbacks.saAmfCSISetCallback = amf_csi_set_callback; amf_callbacks.saAmfCSIRemoveCallback = amf_csi_remove_callback; amf_callbacks.saAmfHealthcheckCallback = amf_healthcheck_callback; amf_callbacks.saAmfComponentTerminateCallback = amf_comp_terminate_callback; rc = saAmfInitialize(&my_amf_hdl, &amf_callbacks, &api_ver); if (rc != SA_AIS_OK) { syslog(LOG_ERR, " saAmfInitialize FAILED %u", rc); goto done; } rc = saAmfSelectionObjectGet(my_amf_hdl, amf_sel_obj); if (rc != SA_AIS_OK) { syslog(LOG_ERR, "saAmfSelectionObjectGet FAILED %u", rc); goto done; } rc = saAmfComponentNameGet(my_amf_hdl, &my_comp_name); if (rc != SA_AIS_OK) { syslog(LOG_ERR, "saAmfComponentNameGet FAILED %u", rc); goto done; } rc = saAmfComponentRegister(my_amf_hdl, &my_comp_name, 0); if (rc != SA_AIS_OK) { syslog(LOG_ERR, "saAmfComponentRegister FAILED %u", rc); goto done; } rc = saAmfHealthcheckStart(my_amf_hdl, &my_comp_name, &my_healthcheck_key, SA_AMF_HEALTHCHECK_AMF_INVOKED, SA_AMF_COMPONENT_RESTART); if (rc != SA_AIS_OK) { syslog(LOG_ERR, "saAmfHealthcheckStart FAILED - %u", rc); goto done; } done: return rc; } int main(int argc, char **argv) { SaAisErrorT rc; SaSelectionObjectT amf_sel_obj; struct pollfd fds[1]; char *env_comp_name; /* Environment variable "SA_AMF_COMPONENT_NAME" exist when started by AMF */ if ((env_comp_name = getenv("SA_AMF_COMPONENT_NAME")) == NULL) { fprintf(stderr, "not started by AMF exiting...\n"); exit(EXIT_FAILURE); } /* Daemonize ourselves and detach from terminal. ** This important since our start script will hang forever otherwise. ** Note daemon() is not LSB but impl by libc so fairly portable... */ if (daemon(0, 0) == -1) { syslog(LOG_ERR, "daemon failed: %s", strerror(errno)); goto done; } /* Install a TERM handler just to log and visualize when cleanup is called */ if ((signal(SIGTERM, sigterm_handler)) == SIG_ERR) { syslog(LOG_ERR, "signal TERM failed: %s", strerror(errno)); goto done; } /* Create a PID file which is needed by our CLC-CLI script. ** Use AMF component name as file name so multiple instances of this ** component can be managed by the same script. */ create_pid_file("/tmp", env_comp_name); /* Use syslog for logging */ openlog(basename(argv[0]), LOG_PID, LOG_USER); /* Make a log to associate component name with PID */ syslog(LOG_INFO, "'%s' started", env_comp_name); if (amf_initialize(&amf_sel_obj) != SA_AIS_OK) goto done; syslog(LOG_INFO, "Registered with AMF and HC started"); fds[0].fd = amf_sel_obj; fds[0].events = POLLIN; /* Loop forever waiting for events on watched file descriptors */ while (1) { int res = poll(fds, 1, -1); if (res == -1) { if (errno == EINTR) continue; else { syslog(LOG_ERR, "poll FAILED - %s", strerror(errno)); goto done; } } if (fds[0].revents & POLLIN) { /* An AMF event is received, call AMF dispatch which in turn will * call our installed callbacks. In context of this main thread. */ rc = saAmfDispatch(my_amf_hdl, SA_DISPATCH_ONE); if (rc != SA_AIS_OK) { syslog(LOG_ERR, "saAmfDispatch FAILED %u", rc); goto done; } } } done: return EXIT_FAILURE; }
int main(int argc, char *argv[]) { struct if_config_options *default_ifcnf; char conf_file_name[FILENAME_MAX]; struct ipaddr_str buf; bool loadedConfig = false; int i; #ifdef LINUX_NETLINK_ROUTING struct interface *ifn; #endif #ifdef WIN32 WSADATA WsaData; size_t len; #endif /* paranoia checks */ assert(sizeof(uint8_t) == 1); assert(sizeof(uint16_t) == 2); assert(sizeof(uint32_t) == 4); assert(sizeof(int8_t) == 1); assert(sizeof(int16_t) == 2); assert(sizeof(int32_t) == 4); printf("\n *** %s ***\n Build date: %s on %s\n http://www.olsr.org\n\n", olsrd_version, build_date, build_host); if (argc == 2) { if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "/?") == 0) { print_usage(false); exit(0); } if (strcmp(argv[1], "-v") == 0) { exit(0); } } debug_handle = stdout; #ifndef WIN32 olsr_argv = argv; #endif setbuf(stdout, NULL); setbuf(stderr, NULL); #ifndef WIN32 /* Check if user is root */ if (geteuid()) { fprintf(stderr, "You must be root(uid = 0) to run olsrd!\nExiting\n\n"); exit(EXIT_FAILURE); } #else DisableIcmpRedirects(); if (WSAStartup(0x0202, &WsaData)) { fprintf(stderr, "Could not initialize WinSock.\n"); olsr_exit(__func__, EXIT_FAILURE); } #endif /* Open syslog */ olsr_openlog("olsrd"); /* Using PID as random seed */ srandom(getpid()); /* Init widely used statics */ memset(&all_zero, 0, sizeof(union olsr_ip_addr)); /* * Set configfile name and * check if a configfile name was given as parameter */ #ifdef WIN32 #ifndef WINCE GetWindowsDirectory(conf_file_name, FILENAME_MAX - 11); #else conf_file_name[0] = 0; #endif len = strlen(conf_file_name); if (len == 0 || conf_file_name[len - 1] != '\\') conf_file_name[len++] = '\\'; strscpy(conf_file_name + len, "olsrd.conf", sizeof(conf_file_name) - len); #else strscpy(conf_file_name, OLSRD_GLOBAL_CONF_FILE, sizeof(conf_file_name)); #endif olsr_cnf = olsrd_get_default_cnf(); for (i=1; i < argc-1;) { if (strcmp(argv[i], "-f") == 0) { loadedConfig = true; if (olsrmain_load_config(argv[i+1]) < 0) { exit(EXIT_FAILURE); } if (i+2 < argc) { memmove(&argv[i], &argv[i+2], sizeof(*argv) * (argc-i-1)); } argc -= 2; } else { i++; } } /* * set up configuration prior to processing commandline options */ if (!loadedConfig && olsrmain_load_config(conf_file_name) == 0) { loadedConfig = true; } if (!loadedConfig) { olsrd_free_cnf(olsr_cnf); olsr_cnf = olsrd_get_default_cnf(); } default_ifcnf = get_default_if_config(); if (default_ifcnf == NULL) { fprintf(stderr, "No default ifconfig found!\n"); exit(EXIT_FAILURE); } /* Initialize timers */ olsr_init_timers(); /* * Process olsrd options. */ if (olsr_process_arguments(argc, argv, olsr_cnf, default_ifcnf) < 0) { print_usage(true); olsr_exit(__func__, EXIT_FAILURE); } /* * Set configuration for command-line specified interfaces */ set_default_ifcnfs(olsr_cnf->interfaces, default_ifcnf); /* free the default ifcnf */ free(default_ifcnf); /* Sanity check configuration */ if (olsrd_sanity_check_cnf(olsr_cnf) < 0) { fprintf(stderr, "Bad configuration!\n"); olsr_exit(__func__, EXIT_FAILURE); } /* * Establish file lock to prevent multiple instances */ if (olsr_cnf->lock_file) { strscpy(lock_file_name, olsr_cnf->lock_file, sizeof(lock_file_name)); } else { size_t l; #ifdef DEFAULT_LOCKFILE_PREFIX strscpy(lock_file_name, DEFAULT_LOCKFILE_PREFIX, sizeof(lock_file_name)); #else strscpy(lock_file_name, conf_file_name, sizeof(lock_file_name)); #endif l = strlen(lock_file_name); snprintf(&lock_file_name[l], sizeof(lock_file_name) - l, "-ipv%d.lock", olsr_cnf->ip_version == AF_INET ? 4 : 6); } /* * Print configuration */ if (olsr_cnf->debug_level > 1) { olsrd_print_cnf(olsr_cnf); } def_timer_ci = olsr_alloc_cookie("Default Timer Cookie", OLSR_COOKIE_TYPE_TIMER); /* * socket for ioctl calls */ olsr_cnf->ioctl_s = socket(olsr_cnf->ip_version, SOCK_DGRAM, 0); if (olsr_cnf->ioctl_s < 0) { #ifndef WIN32 olsr_syslog(OLSR_LOG_ERR, "ioctl socket: %m"); #endif olsr_exit(__func__, 0); } #ifdef LINUX_NETLINK_ROUTING olsr_cnf->rtnl_s = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE); if (olsr_cnf->rtnl_s < 0) { olsr_syslog(OLSR_LOG_ERR, "rtnetlink socket: %m"); olsr_exit(__func__, 0); } fcntl(olsr_cnf->rtnl_s, F_SETFL, O_NONBLOCK); if ((olsr_cnf->rt_monitor_socket = rtnetlink_register_socket(RTMGRP_LINK)) < 0) { olsr_syslog(OLSR_LOG_ERR, "rtmonitor socket: %m"); olsr_exit(__func__, 0); } #endif /* * create routing socket */ #if defined __FreeBSD__ || __FreeBSD_kernel__ || defined __MacOSX__ || defined __NetBSD__ || defined __OpenBSD__ olsr_cnf->rts = socket(PF_ROUTE, SOCK_RAW, 0); if (olsr_cnf->rts < 0) { olsr_syslog(OLSR_LOG_ERR, "routing socket: %m"); olsr_exit(__func__, 0); } #endif #ifdef LINUX_NETLINK_ROUTING /* initialize gateway system */ if (olsr_cnf->smart_gw_active) { if (olsr_init_gateways()) { olsr_exit("Cannot initialize gateway tunnels", 1); } } /* initialize niit if index */ if (olsr_cnf->use_niit) { olsr_init_niit(); } #endif /* Init empty TC timer */ set_empty_tc_timer(GET_TIMESTAMP(0)); /* enable ip forwarding on host */ /* Disable redirects globally */ #ifndef WIN32 net_os_set_global_ifoptions(); #endif /* Initialize parser */ olsr_init_parser(); /* Initialize route-exporter */ olsr_init_export_route(); /* Initialize message sequencnumber */ init_msg_seqno(); /* Initialize dynamic willingness calculation */ olsr_init_willingness(); /* *Set up willingness/APM */ if (olsr_cnf->willingness_auto) { if (apm_init() < 0) { OLSR_PRINTF(1, "Could not read APM info - setting default willingness(%d)\n", WILL_DEFAULT); olsr_syslog(OLSR_LOG_ERR, "Could not read APM info - setting default willingness(%d)\n", WILL_DEFAULT); olsr_cnf->willingness_auto = 0; olsr_cnf->willingness = WILL_DEFAULT; } else { olsr_cnf->willingness = olsr_calculate_willingness(); OLSR_PRINTF(1, "Willingness set to %d - next update in %.1f secs\n", olsr_cnf->willingness, olsr_cnf->will_int); } } /* Initialize net */ init_net(); /* Initializing networkinterfaces */ if (!olsr_init_interfacedb()) { if (olsr_cnf->allow_no_interfaces) { fprintf( stderr, "No interfaces detected! This might be intentional, but it also might mean that your configuration is fubar.\nI will continue after 5 seconds...\n"); olsr_startup_sleep(5); } else { fprintf(stderr, "No interfaces detected!\nBailing out!\n"); olsr_exit(__func__, EXIT_FAILURE); } } olsr_do_startup_sleep(); /* Print heartbeat to stdout */ #if !defined WINCE if (olsr_cnf->debug_level > 0 && isatty(STDOUT_FILENO)) { olsr_start_timer(STDOUT_PULSE_INT, 0, OLSR_TIMER_PERIODIC, &generate_stdout_pulse, NULL, 0); } #endif /* Initialize the IPC socket */ if (olsr_cnf->ipc_connections > 0) { ipc_init(); } /* Initialisation of different tables to be used. */ olsr_init_tables(); /* daemon mode */ #ifndef WIN32 if (olsr_cnf->debug_level == 0 && !olsr_cnf->no_fork) { printf("%s detaching from the current process...\n", olsrd_version); if (daemon(0, 0) < 0) { printf("daemon(3) failed: %s\n", strerror(errno)); exit(EXIT_FAILURE); } } #endif /* * Create locking file for olsrd, will be cleared after olsrd exits */ olsr_create_lock_file(); /* Load plugins */ olsr_load_plugins(); OLSR_PRINTF(1, "Main address: %s\n\n", olsr_ip_to_string(&buf, &olsr_cnf->main_addr)); #ifdef LINUX_NETLINK_ROUTING /* create policy routing priorities if necessary */ if (DEF_RT_NONE != olsr_cnf->rt_table_pri) { olsr_os_policy_rule(olsr_cnf->ip_version, olsr_cnf->rt_table, olsr_cnf->rt_table_pri, NULL, true); } if (DEF_RT_NONE != olsr_cnf->rt_table_tunnel_pri) { olsr_os_policy_rule(olsr_cnf->ip_version, olsr_cnf->rt_table_tunnel, olsr_cnf->rt_table_tunnel_pri, NULL, true); } if (DEF_RT_NONE != olsr_cnf->rt_table_default_pri) { olsr_os_policy_rule(olsr_cnf->ip_version, olsr_cnf->rt_table_default, olsr_cnf->rt_table_default_pri, NULL, true); } /* OLSR sockets */ if (DEF_RT_NONE != olsr_cnf->rt_table_defaultolsr_pri) { for (ifn = ifnet; ifn; ifn = ifn->int_next) { olsr_os_policy_rule(olsr_cnf->ip_version, olsr_cnf->rt_table_default, olsr_cnf->rt_table_defaultolsr_pri, ifn->int_name, true); } } /* trigger gateway selection */ if (olsr_cnf->smart_gw_active) { olsr_trigger_inetgw_startup(); } /* trigger niit static route setup */ if (olsr_cnf->use_niit) { olsr_setup_niit_routes(); } /* create lo:olsr interface */ if (olsr_cnf->use_src_ip_routes) { olsr_os_localhost_if(&olsr_cnf->main_addr, true); } #endif /* Start syslog entry */ olsr_syslog(OLSR_LOG_INFO, "%s successfully started", olsrd_version); /* *signal-handlers */ /* ctrl-C and friends */ #ifdef WIN32 #ifndef WINCE SetConsoleCtrlHandler(SignalHandler, true); #endif #else signal(SIGHUP, olsr_reconfigure); signal(SIGINT, olsr_shutdown); signal(SIGQUIT, olsr_shutdown); signal(SIGILL, olsr_shutdown); signal(SIGABRT, olsr_shutdown); // signal(SIGSEGV, olsr_shutdown); signal(SIGTERM, olsr_shutdown); signal(SIGPIPE, SIG_IGN); // Ignoring SIGUSR1 and SIGUSR1 by default to be able to use them in plugins signal(SIGUSR1, SIG_IGN); signal(SIGUSR2, SIG_IGN); #endif link_changes = false; /* Starting scheduler */ olsr_scheduler(); /* Like we're ever going to reach this ;-) */ return 1; } /* main */
int main(int argc, char *argv[]) { base::CommandLine::Init(argc, argv); base::CommandLine* cl = base::CommandLine::ForCurrentProcess(); int32_t port = kDefaultPort; if (cl->HasSwitch(kPort)) { std::string value = cl->GetSwitchValueASCII(kPort); base::StringToInt(value, &port); } // Puch a TCP hole to accept connection FwDaemon daemon(std::unique_ptr<FirewallInterface>{new FirewalldFirewall()}, (uint16_t)port); daemon.Run(); std::unique_ptr<Socket> server = Socket::NewServer(Socket::Protocol::kTcp, port); if (server == nullptr) { ALOGE("Failed to create fastbootd service."); return 1; } int fastbootd_reboot = 0; if (property_get_bool("persist.sys.fastbootd.reboot", 1)) { pthread_t hreboot; pthread_create(&hreboot, NULL, thread_reboot, &fastbootd_reboot); fastbootd_reboot = 1; } // Check if in demo mode if (fastbootd_reboot == 1) { struct stat st; int result = stat("/boot/DEMO", &st); if (result == 0 && S_ISREG(st.st_mode)) { fastbootd_reboot = 0; } } std::string handshake_message(android::base::StringPrintf("FB%02d", kProtocolVersion)); while (true) { std::unique_ptr<Socket> client = server->Accept(); if (client == nullptr) { ALOGE("Failed to accept client connection."); continue; } char buffer[4]; ssize_t bytes = client->Receive(buffer, sizeof(buffer), 500); if (bytes != 4) { ALOGE("Failed to get client version."); continue; } if (memcmp(buffer, "FB01", 4) != 0) { ALOGE("Unsupported client: %c%c%c%c", buffer[0], buffer[1], buffer[2], buffer[3]); continue; } if (fastbootd_reboot) { fastbootd_reboot = 0; property_set("persist.sys.fastbootd.reboot", "0"); } if (!client->Send(handshake_message.c_str(), kHandshakeLength)) { ALOGE("Failed to send handshake."); continue; } command_loop(client.get()); } return 0; }
int main(int argc, char *argv[]) { int i, j; int error, fnd_dup, len, mustfreeai = 0, start_uidpos; struct nfsd_idargs nid; struct passwd *pwd; struct group *grp; int sock, one = 1; SVCXPRT *udptransp; u_short portnum; sigset_t signew; char hostname[MAXHOSTNAMELEN + 1], *cp; struct addrinfo *aip, hints; static uid_t check_dups[MAXUSERMAX]; if (modfind("nfscommon") < 0) { /* Not present in kernel, try loading it */ if (kldload("nfscommon") < 0 || modfind("nfscommon") < 0) errx(1, "Experimental nfs subsystem is not available"); } /* * First, figure out what our domain name and Kerberos Realm * seem to be. Command line args may override these later. */ if (gethostname(hostname, MAXHOSTNAMELEN) == 0) { if ((cp = strchr(hostname, '.')) != NULL && *(cp + 1) != '\0') { dnsname = cp + 1; } else { memset((void *)&hints, 0, sizeof (hints)); hints.ai_flags = AI_CANONNAME; error = getaddrinfo(hostname, NULL, &hints, &aip); if (error == 0) { if (aip->ai_canonname != NULL && (cp = strchr(aip->ai_canonname, '.')) != NULL && *(cp + 1) != '\0') { dnsname = cp + 1; mustfreeai = 1; } else { freeaddrinfo(aip); } } } } nid.nid_usermax = DEFUSERMAX; nid.nid_usertimeout = defusertimeout; argc--; argv++; while (argc >= 1) { if (!strcmp(*argv, "-domain")) { if (argc == 1) usage(); argc--; argv++; strncpy(hostname, *argv, MAXHOSTNAMELEN); hostname[MAXHOSTNAMELEN] = '\0'; dnsname = hostname; } else if (!strcmp(*argv, "-verbose")) { verbose = 1; } else if (!strcmp(*argv, "-force")) { forcestart = 1; } else if (!strcmp(*argv, "-usermax")) { if (argc == 1) usage(); argc--; argv++; i = atoi(*argv); if (i < MINUSERMAX || i > MAXUSERMAX) { fprintf(stderr, "usermax %d out of range %d<->%d\n", i, MINUSERMAX, MAXUSERMAX); usage(); } nid.nid_usermax = i; } else if (!strcmp(*argv, "-usertimeout")) { if (argc == 1) usage(); argc--; argv++; i = atoi(*argv); if (i < 0 || i > 100000) { fprintf(stderr, "usertimeout %d out of range 0<->100000\n", i); usage(); } nid.nid_usertimeout = defusertimeout = i * 60; } else if (nfsuserdcnt == -1) { nfsuserdcnt = atoi(*argv); if (nfsuserdcnt < 1) usage(); if (nfsuserdcnt > MAXNFSUSERD) { warnx("nfsuserd count %d; reset to %d", nfsuserdcnt, DEFNFSUSERD); nfsuserdcnt = DEFNFSUSERD; } } else { usage(); } argc--; argv++; } if (nfsuserdcnt < 1) nfsuserdcnt = DEFNFSUSERD; /* * Strip off leading and trailing '.'s in domain name and map * alphabetics to lower case. */ while (*dnsname == '.') dnsname++; if (*dnsname == '\0') errx(1, "Domain name all '.'"); len = strlen(dnsname); cp = dnsname + len - 1; while (*cp == '.') { *cp = '\0'; len--; cp--; } for (i = 0; i < len; i++) { if (!isascii(dnsname[i])) errx(1, "Domain name has non-ascii char"); if (isupper(dnsname[i])) dnsname[i] = tolower(dnsname[i]); } /* * If the nfsuserd died off ungracefully, this is necessary to * get them to start again. */ if (forcestart && nfssvc(NFSSVC_NFSUSERDDELPORT, NULL) < 0) errx(1, "Can't do nfssvc() to delete the port"); if (verbose) fprintf(stderr, "nfsuserd: domain=%s usermax=%d usertimeout=%d\n", dnsname, nid.nid_usermax, nid.nid_usertimeout); for (i = 0; i < nfsuserdcnt; i++) slaves[i] = (pid_t)-1; /* * Set up the service port to accept requests via UDP from * localhost (127.0.0.1). */ if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) err(1, "cannot create udp socket"); /* * Not sure what this does, so I'll leave it here for now. */ setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)); if ((udptransp = svcudp_create(sock)) == NULL) err(1, "Can't set up socket"); /* * By not specifying a protocol, it is linked into the * dispatch queue, but not registered with portmapper, * which is just what I want. */ if (!svc_register(udptransp, RPCPROG_NFSUSERD, RPCNFSUSERD_VERS, nfsuserdsrv, 0)) err(1, "Can't register nfsuserd"); /* * Tell the kernel what my port# is. */ portnum = htons(udptransp->xp_port); #ifdef DEBUG printf("portnum=0x%x\n", portnum); #else if (nfssvc(NFSSVC_NFSUSERDPORT, (caddr_t)&portnum) < 0) { if (errno == EPERM) { fprintf(stderr, "Can't start nfsuserd when already running"); fprintf(stderr, " If not running, use the -force option.\n"); } else { fprintf(stderr, "Can't do nfssvc() to add port\n"); } exit(1); } #endif pwd = getpwnam(defaultuser); if (pwd) nid.nid_uid = pwd->pw_uid; else nid.nid_uid = defaultuid; grp = getgrnam(defaultgroup); if (grp) nid.nid_gid = grp->gr_gid; else nid.nid_gid = defaultgid; nid.nid_name = dnsname; nid.nid_namelen = strlen(nid.nid_name); nid.nid_flag = NFSID_INITIALIZE; #ifdef DEBUG printf("Initialize uid=%d gid=%d dns=%s\n", nid.nid_uid, nid.nid_gid, nid.nid_name); #else error = nfssvc(NFSSVC_IDNAME, &nid); if (error) errx(1, "Can't initialize nfs user/groups"); #endif i = 0; /* * Loop around adding all groups. */ setgrent(); while (i < nid.nid_usermax && (grp = getgrent())) { nid.nid_gid = grp->gr_gid; nid.nid_name = grp->gr_name; nid.nid_namelen = strlen(grp->gr_name); nid.nid_flag = NFSID_ADDGID; #ifdef DEBUG printf("add gid=%d name=%s\n", nid.nid_gid, nid.nid_name); #else error = nfssvc(NFSSVC_IDNAME, &nid); if (error) errx(1, "Can't add group %s", grp->gr_name); #endif i++; } /* * Loop around adding all users. */ start_uidpos = i; setpwent(); while (i < nid.nid_usermax && (pwd = getpwent())) { fnd_dup = 0; /* * Yes, this is inefficient, but it is only done once when * the daemon is started and will run in a fraction of a second * for nid_usermax at 10000. If nid_usermax is cranked up to * 100000, it will take several seconds, depending on the CPU. */ for (j = 0; j < (i - start_uidpos); j++) if (check_dups[j] == pwd->pw_uid) { /* Found another entry for uid, so skip it */ fnd_dup = 1; break; } if (fnd_dup != 0) continue; check_dups[i - start_uidpos] = pwd->pw_uid; nid.nid_uid = pwd->pw_uid; nid.nid_name = pwd->pw_name; nid.nid_namelen = strlen(pwd->pw_name); nid.nid_flag = NFSID_ADDUID; #ifdef DEBUG printf("add uid=%d name=%s\n", nid.nid_uid, nid.nid_name); #else error = nfssvc(NFSSVC_IDNAME, &nid); if (error) errx(1, "Can't add user %s", pwd->pw_name); #endif i++; } /* * I should feel guilty for not calling this for all the above exit() * upon error cases, but I don't. */ if (mustfreeai) freeaddrinfo(aip); #ifdef DEBUG exit(0); #endif /* * Temporarily block SIGUSR1 and SIGCHLD, so slaves[] can't * end up bogus. */ sigemptyset(&signew); sigaddset(&signew, SIGUSR1); sigaddset(&signew, SIGCHLD); sigprocmask(SIG_BLOCK, &signew, NULL); daemon(0, 0); (void)signal(SIGHUP, SIG_IGN); (void)signal(SIGINT, SIG_IGN); (void)signal(SIGQUIT, SIG_IGN); (void)signal(SIGTERM, SIG_IGN); (void)signal(SIGUSR1, cleanup_term); (void)signal(SIGCHLD, cleanup_term); openlog("nfsuserd:", LOG_PID, LOG_DAEMON); /* * Fork off the slave daemons that do the work. All the master * does is kill them off and cleanup. */ for (i = 0; i < nfsuserdcnt; i++) { slaves[i] = fork(); if (slaves[i] == 0) { im_a_slave = 1; setproctitle("slave"); sigemptyset(&signew); sigaddset(&signew, SIGUSR1); sigprocmask(SIG_UNBLOCK, &signew, NULL); /* * and away we go. */ svc_run(); syslog(LOG_ERR, "nfsuserd died: %m"); exit(1); } else if (slaves[i] < 0) { syslog(LOG_ERR, "fork: %m"); } } /* * Just wait for SIGUSR1 or a child to die and then... * As the Governor of California would say, "Terminate them". */ setproctitle("master"); sigemptyset(&signew); while (1) sigsuspend(&signew); }
int main (int argc, char **argv) { FILE *f; parse_command_line(argc, argv); /* Log to the console if not daemonizing. */ openlog("sleepd", LOG_PID | (daemonize ? 0 : LOG_PERROR), LOG_DAEMON); /* Set up a signal handler for SIGTERM to clean up things. */ signal(SIGTERM, cleanup); /* And a handler for SIGHUP, to reaload control file. */ signal(SIGHUP, loadcontrol); loadcontrol(0); if (! use_events) { if (! have_irqs && ! autoprobe) { fprintf(stderr, "No irqs specified.\n"); exit(1); } } if (daemonize) { if (daemon(0,0) == -1) { perror("daemon"); exit(1); } if ((f=fopen(PID_FILE, "w")) == NULL) { syslog(LOG_ERR, "unable to write %s", PID_FILE); exit(1); } else { fprintf(f, "%i\n", getpid()); fclose(f); } } if (apm_exists() != 0) { if (! sleep_command) sleep_command=acpi_sleep_command; /* Chosing between hal and acpi backends is tricky, * because acpi may report no batteries due to the battery * being absent (but inserted later), or due to battery * info no longer being available by acpi in new kernels. * Meanwhile, hal may fail if hald is not yet * running, but might work later. * * The strategy used is to check if acpi reports an AC * adapter, or a battery. If it reports neither, we assume * that the kernel no longer supports acpi power info, and * use hal. */ if (acpi_supported() && (acpi_ac_count > 0 || acpi_batt_count > 0)) { use_acpi=1; } #ifdef HAL else if (simplehal_supported()) { use_simplehal=1; } else { syslog(LOG_NOTICE, "failed to connect to hal on startup, but will try to use it anyway"); use_simplehal=1; } #else else { fprintf(stderr, "sleepd: no APM or ACPI support detected\n"); exit(1); } #endif }
/* Main startup routine. */ int zebra_main_entry (int argc, char **argv) { char *p; #undef vty_addr char *vty_addr = NULL; #undef vty_port int vty_port = ZEBRA_VTY_PORT; int batch_mode = 0; int daemon_mode = 0; #undef config_file char *config_file = NULL; char *progname; struct thread thread; void rib_weed_tables (); void zebra_vty_init (); /* Set umask before anything for security */ umask (0027); /* preserve my name */ progname = ((p = strrchr (argv[0], '/')) ? ++p : argv[0]); zlog_default = openzlog (progname, ZLOG_ZEBRA, LOG_CONS|LOG_NDELAY|LOG_PID, LOG_DAEMON); while (1) { int opt; #ifdef HAVE_NETLINK opt = getopt_long (argc, argv, "bdklf:i:hA:P:ru:g:vs:", longopts, 0); #else opt = getopt_long (argc, argv, "bdklf:i:hA:P:ru:g:v", longopts, 0); #endif /* HAVE_NETLINK */ if (opt == EOF) break; switch (opt) { case 0: break; case 'b': batch_mode = 1; case 'd': daemon_mode = 1; break; case 'k': keep_kernel_mode = 1; break; case 'l': /* log_mode = 1; */ break; case 'f': config_file = optarg; break; case 'A': vty_addr = optarg; break; case 'i': pid_file = optarg; break; case 'P': /* Deal with atoi() returning 0 on failure, and zebra not listening on zebra port... */ if (strcmp(optarg, "0") == 0) { vty_port = 0; break; } vty_port = atoi (optarg); vty_port = (vty_port ? vty_port : ZEBRA_VTY_PORT); break; case 'r': retain_mode = 1; break; #ifdef HAVE_NETLINK case 's': nl_rcvbufsize = atoi (optarg); break; #endif /* HAVE_NETLINK */ case 'u': zserv_privs.user = optarg; break; case 'g': zserv_privs.group = optarg; break; case 'v': print_version (progname); exit (0); break; case 'h': usage (progname, 0); break; default: usage (progname, 1); break; } } /* Make master thread emulator. */ zebrad.master__item = thread_master_create (); /* privs initialise */ zprivs_init (&zserv_privs); /* Vty related initialize. */ signal_init (zebrad.master__item, Q_SIGC(zebra_signals), zebra_signals); cmd_init (1); vty_init (zebrad.master__item); memory_init (); /* Zebra related initialize. */ zebra_init (); rib_init (); zebra_if_init (); zebra_debug_init (); router_id_init(); zebra_vty_init (); access_list_init (); rtadv_init (); #ifdef HAVE_IRDP irdp_init(); #endif /* For debug purpose. */ /* SET_FLAG (zebra_debug_event, ZEBRA_DEBUG_EVENT); */ /* Make kernel routing socket. */ kernel_init (); interface_list (); route_read (); /* Sort VTY commands. */ sort_node (); #ifdef HAVE_SNMP zebra_snmp_init (); #endif /* HAVE_SNMP */ /* Clean up self inserted route. */ if (! keep_kernel_mode) rib_sweep_route (); /* Configuration file read*/ vty_read_config (config_file, config_default); /* Clean up rib. */ rib_weed_tables (); /* Exit when zebra is working in batch mode. */ if (batch_mode) exit (0); /* Needed for BSD routing socket. */ old_pid = getpid (); /* Daemonize. */ if (daemon_mode) daemon (0, 0); /* Output pid of zebra. */ pid_output (pid_file); /* Needed for BSD routing socket. */ pid = getpid (); /* Make vty server socket. */ vty_serv_sock (vty_addr, vty_port, ZEBRA_VTYSH_PATH); /* Print banner. */ zlog_notice ("Zebra %s starting: vty@%d", QUAGGA_VERSION, vty_port); while (thread_fetch (zebrad.master__item, &thread)) thread_call (&thread); /* Not reached... */ exit (0); }
int main(int argc, char *argv[]) #endif { fd_set rfds; struct timeval tv; int server_socket = -1; int bytes, retval; struct dhcpMessage packet; unsigned char *state; unsigned char *server_id, *requested, *hostname; u_int32_t server_id_align, requested_align; unsigned long timeout_end; struct option_set *option; struct dhcpOfferedAddr *lease; int pid_fd; int max_sock; int sig; OPEN_LOG("udhcpd"); LOG(LOG_INFO, "udhcp server (v%s) started", VERSION); memset(&server_config, 0, sizeof(struct server_config_t)); if (argc < 2) read_config(DHCPD_CONF_FILE); else read_config(argv[1]); pid_fd = pidfile_acquire(server_config.pidfile); pidfile_write_release(pid_fd); if ((option = find_option(server_config.options, DHCP_LEASE_TIME))) { memcpy(&server_config.lease, option->data + 2, 4); server_config.lease = ntohl(server_config.lease); } else server_config.lease = LEASE_TIME; leases = malloc(sizeof(struct dhcpOfferedAddr) * server_config.max_leases); memset(leases, 0, sizeof(struct dhcpOfferedAddr) * server_config.max_leases); // Added by Joey to load static lease if (argc>=3) { load_leases(argv[2]); } read_leases(server_config.lease_file); if (read_interface(server_config.interface, &server_config.ifindex, &server_config.server, server_config.arp) < 0) exit_server(1); #ifndef DEBUGGING pid_fd = pidfile_acquire(server_config.pidfile); /* hold lock during fork. */ if (daemon(0, 0) == -1) { perror("fork"); exit_server(1); } pidfile_write_release(pid_fd); #endif /* ensure that stdin/stdout/stderr are never returned by pipe() */ if (fcntl(STDIN_FILENO, F_GETFL) == -1) (void) open("/dev/null", O_RDONLY); if (fcntl(STDOUT_FILENO, F_GETFL) == -1) (void) open("/dev/null", O_WRONLY); if (fcntl(STDERR_FILENO, F_GETFL) == -1) (void) open("/dev/null", O_WRONLY); /* setup signal handlers */ pipe(signal_pipe); signal(SIGUSR1, signal_handler); signal(SIGTERM, signal_handler); timeout_end = uptime() + server_config.auto_time; while(1) { /* loop until universe collapses */ if (server_socket < 0) if ((server_socket = listen_socket(INADDR_ANY, SERVER_PORT, server_config.interface)) < 0) { LOG(LOG_ERR, "FATAL: couldn't create server socket, %s", strerror(errno)); exit_server(0); } FD_ZERO(&rfds); FD_SET(server_socket, &rfds); FD_SET(signal_pipe[0], &rfds); if (server_config.auto_time) { tv.tv_sec = timeout_end - uptime(); tv.tv_usec = 0; } if (!server_config.auto_time || tv.tv_sec > 0) { max_sock = server_socket > signal_pipe[0] ? server_socket : signal_pipe[0]; retval = select(max_sock + 1, &rfds, NULL, NULL, server_config.auto_time ? &tv : NULL); } else retval = 0; /* If we already timed out, fall through */ if (retval == 0) { write_leases(); timeout_end = uptime() + server_config.auto_time; continue; } else if (retval < 0 && errno != EINTR) { DEBUG(LOG_INFO, "error on select"); continue; } if (FD_ISSET(signal_pipe[0], &rfds)) { if (read(signal_pipe[0], &sig, sizeof(sig)) < 0) continue; /* probably just EINTR */ switch (sig) { case SIGUSR1: LOG(LOG_INFO, "Received a SIGUSR1"); write_leases(); /* why not just reset the timeout, eh */ timeout_end = uptime() + server_config.auto_time; continue; case SIGTERM: LOG(LOG_INFO, "Received a SIGTERM"); exit_server(0); } } if ((bytes = get_packet(&packet, server_socket)) < 0) { /* this waits for a packet - idle */ if (bytes == -1 && errno != EINTR) { DEBUG(LOG_INFO, "error on read, %s, reopening socket", strerror(errno)); close(server_socket); server_socket = -1; } continue; } if ((state = get_option(&packet, DHCP_MESSAGE_TYPE)) == NULL) { DEBUG(LOG_ERR, "couldn't get option from packet, ignoring"); continue; } server_id = get_option(&packet, DHCP_SERVER_ID); if (server_id) { memcpy(&server_id_align, server_id, 4); if (server_id_align != server_config.server) { /* client talks to somebody else */ DEBUG(LOG_INFO,"server ID %08x doesn't match, ignoring", ntohl(server_id_align)); continue; } } /* ADDME: look for a static lease */ lease = find_lease_by_chaddr(packet.chaddr); switch (state[0]) { case DHCPDISCOVER: DEBUG(LOG_INFO,"received DISCOVER"); if (sendOffer(&packet) < 0) { LOG(LOG_ERR, "send OFFER failed"); } break; case DHCPREQUEST: DEBUG(LOG_INFO, "received REQUEST"); requested = get_option(&packet, DHCP_REQUESTED_IP); hostname = get_option(&packet, DHCP_HOST_NAME); if (requested) memcpy(&requested_align, requested, 4); if (lease) { /*ADDME: or static lease */ if (server_id) { /* SELECTING State */ if (requested && requested_align == lease->yiaddr) { sendACK(&packet, lease->yiaddr); } } else { if (requested) { /* INIT-REBOOT State */ if (lease->yiaddr == requested_align) sendACK(&packet, lease->yiaddr); else sendNAK(&packet); } else { /* RENEWING or REBINDING State */ if (lease->yiaddr == packet.ciaddr) sendACK(&packet, lease->yiaddr); else { /* don't know what to do!!!! */ sendNAK(&packet); } } } if (hostname) { bytes = hostname[-1]; if (bytes >= (int) sizeof(lease->hostname)) bytes = sizeof(lease->hostname) - 1; strncpy(lease->hostname, hostname, bytes); lease->hostname[bytes] = '\0'; if (!is_valid_hostname(lease->hostname)) lease->hostname[0] = '\0'; } else lease->hostname[0] = '\0'; /* what to do if we have no record of the client */ } else if (server_id) { /* SELECTING State */ if (requested) sendNAK(&packet); } else if (requested) { /* INIT-REBOOT State */ if ((lease = find_lease_by_yiaddr(requested_align))) { if (lease_expired(lease)) { /* probably best if we drop this lease */ memset(lease->chaddr, 0, 16); /* make some contention for this address */ } else sendNAK(&packet); } else if (requested_align < server_config.start || requested_align > server_config.end) { sendNAK(&packet); } else { sendNAK(&packet); } } else if (packet.ciaddr) { /* RENEWING or REBINDING State */ sendNAK(&packet); } break; case DHCPDECLINE: DEBUG(LOG_INFO,"received DECLINE"); if (lease) { memset(lease->chaddr, 0, 16); lease->expires = uptime() + server_config.decline_time; } break; case DHCPRELEASE: DEBUG(LOG_INFO,"received RELEASE"); if (lease) lease->expires = uptime(); break; case DHCPINFORM: DEBUG(LOG_INFO,"received INFORM"); send_inform(&packet); break; default: LOG(LOG_WARNING, "unsupported DHCP message (%02x) -- ignoring", state[0]); } } return 0; }
int qemu_daemon(int nochdir, int noclose) { return daemon(nochdir, noclose); }
int main(int argc, char **argv) { int u_flag; int s_flag; int d_flag; int W_flag; int w_flag; int l_flag; int ret; char *user; char *socket; char *ep; int uid; struct passwd *pwd; pid_t pid; int fd; u_flag = s_flag = d_flag = l_flag = w_flag = W_flag = 0; dnsbls = dnswls = wl_domains = NULL; while ((ret = getopt(argc, argv, "hdu:s:l:w:W:")) != -1) { switch(ret) { case 'd': d_flag++; break; case 'u': u_flag++; user = optarg; break; case 's': s_flag++; socket = optarg; break; case 'l': dnsbls = add_list(dnsbls, optarg); l_flag++; break; case 'w': dnswls = add_list(dnswls, optarg); w_flag++; break; case 'W': wl_domains = add_list(wl_domains, optarg); W_flag++; break; case 'h': default: usage(_progname); } } argc -= optind; argv += optind; if (!u_flag) { fprintf(stderr, "You must specify a user!\n"); usage(_progname); } if (!s_flag) { fprintf(stderr, "You must specify a socket!\n"); usage(_progname); } if (w_flag) { printf("Using whitelists:\n"); print_list(dnswls); } if (W_flag) { printf("Whitelisting domains:\n"); print_list(wl_domains); } if (!l_flag) { fprintf(stderr, "You must specify at least one DNSBL!\n"); usage(_progname); } else { printf("Using blacklists:\n"); print_list(dnsbls); } if (getuid() != 0) { fprintf(stderr, "%s: cannot switch to user %s if not started as root!\n", _progname, user); exit(EX_USAGE); } /* OK running as root, now switch to user */ uid = strtol(user, &ep, 0); if (*ep == '\0') { pwd = getpwuid(uid); } else { pwd = getpwnam(user); } if (pwd == NULL) { fprintf(stderr, "%s: unknown user: %s\n", _progname, user); exit(EX_NOUSER); } if (setgroups(0, NULL) < 0) { perror("setgroups()"); exit(1); } if (setgid(pwd->pw_gid) < 0) { perror("setgid()"); exit(1); } if (initgroups(user, pwd->pw_gid) < 0) { perror("initgroups()"); /* not a critical failure */ } if (setuid(pwd->pw_uid) < 0) { perror("setuid()"); exit(1); } openlog(_progname, 0, LOG_MAIL); if (smfi_register(smfilter) == MI_FAILURE) { fprintf(stderr, "smfi_register() failed.\n"); exit(EX_UNAVAILABLE); } if (smfi_setconn(socket) == MI_FAILURE) { fprintf(stderr, "smfi_setconn() %s\n", strerror(errno)); exit(EX_SOFTWARE); } if (smfi_opensocket(1) == MI_FAILURE) { fprintf(stderr, "smfi_opensocket() %s\n", strerror(errno)); exit(EX_SOFTWARE); } (void) smfi_settimeout(7200); if (!d_flag) { fprintf(stderr, "Warning: not starting as daemon"); } else { if (daemon(0, 0) < 0) { perror("daemon()"); exit(1); } } syslog(LOG_INFO, "%s started successfuly!", _progname); return(smfi_main()); /* start doing business */ }
/* Main */ int main(int argc, char *argv[]) { struct sockaddr_rfcomm sock_addr; char *label = NULL, *unit = NULL, *ep = NULL; bdaddr_t addr; int s, channel, detach, server, service, regdun, regsp; pid_t pid; memcpy(&addr, NG_HCI_BDADDR_ANY, sizeof(addr)); channel = 0; detach = 1; server = 0; service = 0; regdun = 0; regsp = 0; /* Parse command line arguments */ while ((s = getopt(argc, argv, "a:cC:dDhl:sSu:")) != -1) { switch (s) { case 'a': /* BDADDR */ if (!bt_aton(optarg, &addr)) { struct hostent *he = NULL; if ((he = bt_gethostbyname(optarg)) == NULL) errx(1, "%s: %s", optarg, hstrerror(h_errno)); memcpy(&addr, he->h_addr, sizeof(addr)); } break; case 'c': /* client */ server = 0; break; case 'C': /* RFCOMM channel */ channel = strtoul(optarg, &ep, 10); if (*ep != '\0') { channel = 0; switch (tolower(optarg[0])) { case 'd': /* DialUp Networking */ service = SDP_SERVICE_CLASS_DIALUP_NETWORKING; break; case 'l': /* LAN Access Using PPP */ service = SDP_SERVICE_CLASS_LAN_ACCESS_USING_PPP; break; } } break; case 'd': /* do not detach */ detach = 0; break; case 'D': /* Register DUN service as well as LAN service */ regdun = 1; break; case 'l': /* PPP label */ label = optarg; break; case 's': /* server */ server = 1; break; case 'S': /* Register SP service as well as LAN service */ regsp = 1; break; case 'u': /* PPP -unit option */ strtoul(optarg, &ep, 10); if (*ep != '\0') usage(); /* NOT REACHED */ unit = optarg; break; case 'h': default: usage(); /* NOT REACHED */ } } /* Check if we got everything we wanted */ if (label == NULL) errx(1, "Must specify PPP label"); if (!server) { if (memcmp(&addr, NG_HCI_BDADDR_ANY, sizeof(addr)) == 0) errx(1, "Must specify server BD_ADDR"); /* Check channel, if was not set then obtain it via SDP */ if (channel == 0 && service != 0) if (rfcomm_channel_lookup(NULL, &addr, service, &channel, &s) != 0) errc(1, s, "Could not obtain RFCOMM channel"); } if (channel <= 0 || channel > 30) errx(1, "Invalid RFCOMM channel number %d", channel); openlog(RFCOMM_PPPD, LOG_PID | LOG_PERROR | LOG_NDELAY, LOG_USER); if (detach && daemon(0, 0) < 0) { syslog(LOG_ERR, "Could not daemon(0, 0). %s (%d)", strerror(errno), errno); exit(1); } s = socket(PF_BLUETOOTH, SOCK_STREAM, BLUETOOTH_PROTO_RFCOMM); if (s < 0) { syslog(LOG_ERR, "Could not create socket. %s (%d)", strerror(errno), errno); exit(1); } if (server) { struct sigaction sa; void *ss = NULL; sdp_lan_profile_t lan; /* Install signal handler */ memset(&sa, 0, sizeof(sa)); sa.sa_handler = sighandler; if (sigaction(SIGTERM, &sa, NULL) < 0) { syslog(LOG_ERR, "Could not sigaction(SIGTERM). %s (%d)", strerror(errno), errno); exit(1); } if (sigaction(SIGHUP, &sa, NULL) < 0) { syslog(LOG_ERR, "Could not sigaction(SIGHUP). %s (%d)", strerror(errno), errno); exit(1); } if (sigaction(SIGINT, &sa, NULL) < 0) { syslog(LOG_ERR, "Could not sigaction(SIGINT). %s (%d)", strerror(errno), errno); exit(1); } sa.sa_handler = SIG_IGN; sa.sa_flags = SA_NOCLDWAIT; if (sigaction(SIGCHLD, &sa, NULL) < 0) { syslog(LOG_ERR, "Could not sigaction(SIGCHLD). %s (%d)", strerror(errno), errno); exit(1); } /* bind socket and listen for incoming connections */ sock_addr.rfcomm_len = sizeof(sock_addr); sock_addr.rfcomm_family = AF_BLUETOOTH; memcpy(&sock_addr.rfcomm_bdaddr, &addr, sizeof(sock_addr.rfcomm_bdaddr)); sock_addr.rfcomm_channel = channel; if (bind(s, (struct sockaddr *) &sock_addr, sizeof(sock_addr)) < 0) { syslog(LOG_ERR, "Could not bind socket. %s (%d)", strerror(errno), errno); exit(1); } if (listen(s, 10) < 0) { syslog(LOG_ERR, "Could not listen on socket. %s (%d)", strerror(errno), errno); exit(1); } ss = sdp_open_local(NULL); if (ss == NULL) { syslog(LOG_ERR, "Unable to create local SDP session"); exit(1); } if (sdp_error(ss) != 0) { syslog(LOG_ERR, "Unable to open local SDP session. " \ "%s (%d)", strerror(sdp_error(ss)), sdp_error(ss)); exit(1); } memset(&lan, 0, sizeof(lan)); lan.server_channel = channel; if (sdp_register_service(ss, SDP_SERVICE_CLASS_LAN_ACCESS_USING_PPP, &addr, (void *) &lan, sizeof(lan), NULL) != 0) { syslog(LOG_ERR, "Unable to register LAN service with " \ "local SDP daemon. %s (%d)", strerror(sdp_error(ss)), sdp_error(ss)); exit(1); } /* * Register DUN (Dial-Up Networking) service on the same * RFCOMM channel if requested. There is really no good reason * to not to support this. AT-command exchange can be faked * with chat script in ppp.conf */ if (regdun) { sdp_dun_profile_t dun; memset(&dun, 0, sizeof(dun)); dun.server_channel = channel; if (sdp_register_service(ss, SDP_SERVICE_CLASS_DIALUP_NETWORKING, &addr, (void *) &dun, sizeof(dun), NULL) != 0) { syslog(LOG_ERR, "Unable to register DUN " \ "service with local SDP daemon. " \ "%s (%d)", strerror(sdp_error(ss)), sdp_error(ss)); exit(1); } } /* * Register SP (Serial Port) service on the same RFCOMM channel * if requested. It appears that some cell phones are using so * called "callback mechanism". In this scenario user is trying * to connect his cell phone to the Internet, and, user's host * computer is acting as the gateway server. It seems that it * is not possible to tell the phone to just connect and start * using the LAN service. Instead the user's host computer must * "jump start" the phone by connecting to the phone's SP * service. What happens next is the phone kills the existing * connection and opens another connection back to the user's * host computer. The phone really wants to use LAN service, * but for whatever reason it looks for SP service on the * user's host computer. This brain damaged behavior was * reported for Nokia 6600 and Sony/Ericsson P900. Both phones * are Symbian-based phones. Perhaps this is a Symbian problem? */ if (regsp) { sdp_sp_profile_t sp; memset(&sp, 0, sizeof(sp)); sp.server_channel = channel; if (sdp_register_service(ss, SDP_SERVICE_CLASS_SERIAL_PORT, &addr, (void *) &sp, sizeof(sp), NULL) != 0) { syslog(LOG_ERR, "Unable to register SP " \ "service with local SDP daemon. " \ "%s (%d)", strerror(sdp_error(ss)), sdp_error(ss)); exit(1); } } for (done = 0; !done; ) { socklen_t len = sizeof(sock_addr); int s1 = accept(s, (struct sockaddr *) &sock_addr, &len); if (s1 < 0) { syslog(LOG_ERR, "Could not accept connection " \ "on socket. %s (%d)", strerror(errno), errno); exit(1); } pid = fork(); if (pid == (pid_t) -1) { syslog(LOG_ERR, "Could not fork(). %s (%d)", strerror(errno), errno); exit(1); } if (pid == 0) { sdp_close(ss); close(s); /* Reset signal handler */ memset(&sa, 0, sizeof(sa)); sa.sa_handler = SIG_DFL; sigaction(SIGTERM, &sa, NULL); sigaction(SIGHUP, &sa, NULL); sigaction(SIGINT, &sa, NULL); sigaction(SIGCHLD, &sa, NULL); /* Become daemon */ daemon(0, 0); /* * XXX Make sure user does not shoot himself * in the foot. Do not pass unit option to the * PPP when operating in the server mode. */ exec_ppp(s1, NULL, label); } else close(s1); } } else { sock_addr.rfcomm_len = sizeof(sock_addr); sock_addr.rfcomm_family = AF_BLUETOOTH; memcpy(&sock_addr.rfcomm_bdaddr, NG_HCI_BDADDR_ANY, sizeof(sock_addr.rfcomm_bdaddr)); sock_addr.rfcomm_channel = 0; if (bind(s, (struct sockaddr *) &sock_addr, sizeof(sock_addr)) < 0) { syslog(LOG_ERR, "Could not bind socket. %s (%d)", strerror(errno), errno); exit(1); } memcpy(&sock_addr.rfcomm_bdaddr, &addr, sizeof(sock_addr.rfcomm_bdaddr)); sock_addr.rfcomm_channel = channel; if (connect(s, (struct sockaddr *) &sock_addr, sizeof(sock_addr)) < 0) { syslog(LOG_ERR, "Could not connect socket. %s (%d)", strerror(errno), errno); exit(1); } exec_ppp(s, unit, label); } exit(0); } /* main */
static int sys_daemon(int nocd, int nocl) { return daemon(nocd, nocl); }
/* * Main program. Initialize us, disconnect us from the tty if necessary, * and loop waiting for I/O and/or timer expiries. */ int ntpdmain( int argc, char *argv[] ) { l_fp now; struct recvbuf *rbuf; #ifdef _AIX /* HMS: ifdef SIGDANGER? */ struct sigaction sa; #endif progname = argv[0]; initializing = 1; /* mark that we are initializing */ process_commandline_opts(&argc, &argv); init_logging(progname, 1); /* Open the log file */ #ifdef HAVE_UMASK { mode_t uv; uv = umask(0); if(uv) (void) umask(uv); else (void) umask(022); } #endif #if defined(HAVE_GETUID) && !defined(MPE) /* MPE lacks the concept of root */ { uid_t uid; uid = getuid(); if (uid && !HAVE_OPT( SAVECONFIGQUIT )) { msyslog(LOG_ERR, "ntpd: must be run as root, not uid %ld", (long)uid); printf("must be run as root, not uid %ld\n", (long)uid); exit(1); } } #endif /* getstartup(argc, argv); / * startup configuration, may set debug */ #ifdef DEBUG debug = DESC(DEBUG_LEVEL).optOccCt; DPRINTF(1, ("%s\n", Version)); #endif /* honor -l/--logfile option to log to a file */ setup_logfile(); /* * Enable the Multi-Media Timer for Windows? */ #ifdef SYS_WINNT if (HAVE_OPT( MODIFYMMTIMER )) set_mm_timer(MM_TIMER_HIRES); #endif if (HAVE_OPT( NOFORK ) || HAVE_OPT( QUIT ) #ifdef DEBUG || debug #endif || HAVE_OPT( SAVECONFIGQUIT )) nofork = 1; if (HAVE_OPT( NOVIRTUALIPS )) listen_to_virtual_ips = 0; /* * --interface, listen on specified interfaces */ if (HAVE_OPT( INTERFACE )) { int ifacect = STACKCT_OPT( INTERFACE ); const char** ifaces = STACKLST_OPT( INTERFACE ); sockaddr_u addr; while (ifacect-- > 0) { add_nic_rule( is_ip_address(*ifaces, &addr) ? MATCH_IFADDR : MATCH_IFNAME, *ifaces, -1, ACTION_LISTEN); ifaces++; } } if (HAVE_OPT( NICE )) priority_done = 0; #if defined(HAVE_SCHED_SETSCHEDULER) if (HAVE_OPT( PRIORITY )) { config_priority = OPT_VALUE_PRIORITY; config_priority_override = 1; priority_done = 0; } #endif #ifdef SYS_WINNT /* * Start interpolation thread, must occur before first * get_systime() */ init_winnt_time(); #endif /* * Initialize random generator and public key pair */ get_systime(&now); ntp_srandom((int)(now.l_i * now.l_uf)); #if !defined(VMS) # ifndef NODETACH /* * Detach us from the terminal. May need an #ifndef GIZMO. */ if (!nofork) { /* * Install trap handlers to log errors and assertion * failures. Default handlers print to stderr which * doesn't work if detached. */ isc_assertion_setcallback(assertion_failed); isc_error_setfatal(library_fatal_error); isc_error_setunexpected(library_unexpected_error); # ifndef SYS_WINNT # ifdef HAVE_DAEMON daemon(0, 0); # else /* not HAVE_DAEMON */ if (fork()) /* HMS: What about a -1? */ exit(0); { #if !defined(F_CLOSEM) u_long s; int max_fd; #endif /* !FCLOSEM */ if (syslog_file != NULL) { fclose(syslog_file); syslog_file = NULL; } #if defined(F_CLOSEM) /* * From 'Writing Reliable AIX Daemons,' SG24-4946-00, * by Eric Agar (saves us from doing 32767 system * calls) */ if (fcntl(0, F_CLOSEM, 0) == -1) msyslog(LOG_ERR, "ntpd: failed to close open files(): %m"); #else /* not F_CLOSEM */ # if defined(HAVE_SYSCONF) && defined(_SC_OPEN_MAX) max_fd = sysconf(_SC_OPEN_MAX); # else /* HAVE_SYSCONF && _SC_OPEN_MAX */ max_fd = getdtablesize(); # endif /* HAVE_SYSCONF && _SC_OPEN_MAX */ for (s = 0; s < max_fd; s++) (void) close((int)s); #endif /* not F_CLOSEM */ (void) open("/", 0); (void) dup2(0, 1); (void) dup2(0, 2); init_logging(progname, 0); /* we lost our logfile (if any) daemonizing */ setup_logfile(); #ifdef SYS_DOMAINOS { uid_$t puid; status_$t st; proc2_$who_am_i(&puid); proc2_$make_server(&puid, &st); } #endif /* SYS_DOMAINOS */ #if defined(HAVE_SETPGID) || defined(HAVE_SETSID) # ifdef HAVE_SETSID if (setsid() == (pid_t)-1) msyslog(LOG_ERR, "ntpd: setsid(): %m"); # else if (setpgid(0, 0) == -1) msyslog(LOG_ERR, "ntpd: setpgid(): %m"); # endif #else /* HAVE_SETPGID || HAVE_SETSID */ { # if defined(TIOCNOTTY) int fid; fid = open("/dev/tty", 2); if (fid >= 0) { (void) ioctl(fid, (u_long) TIOCNOTTY, (char *) 0); (void) close(fid); } # endif /* defined(TIOCNOTTY) */ # ifdef HAVE_SETPGRP_0 (void) setpgrp(); # else /* HAVE_SETPGRP_0 */ (void) setpgrp(0, getpid()); # endif /* HAVE_SETPGRP_0 */ } #endif /* HAVE_SETPGID || HAVE_SETSID */ #ifdef _AIX /* Don't get killed by low-on-memory signal. */ sa.sa_handler = catch_danger; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; (void) sigaction(SIGDANGER, &sa, NULL); #endif /* _AIX */ } # endif /* not HAVE_DAEMON */ # endif /* SYS_WINNT */ } # endif /* NODETACH */ #endif /* VMS */ #ifdef SCO5_CLOCK /* * SCO OpenServer's system clock offers much more precise timekeeping * on the base CPU than the other CPUs (for multiprocessor systems), * so we must lock to the base CPU. */ { int fd = open("/dev/at1", O_RDONLY); if (fd >= 0) { int zero = 0; if (ioctl(fd, ACPU_LOCK, &zero) < 0) msyslog(LOG_ERR, "cannot lock to base CPU: %m"); close( fd ); } /* else ... * If we can't open the device, this probably just isn't * a multiprocessor system, so we're A-OK. */ } #endif #if defined(HAVE_MLOCKALL) && defined(MCL_CURRENT) && defined(MCL_FUTURE) # ifdef HAVE_SETRLIMIT /* * Set the stack limit to something smaller, so that we don't lock a lot * of unused stack memory. */ { struct rlimit rl; /* HMS: must make the rlim_cur amount configurable */ if (getrlimit(RLIMIT_STACK, &rl) != -1 && (rl.rlim_cur = 50 * 4096) < rl.rlim_max) { if (setrlimit(RLIMIT_STACK, &rl) == -1) { msyslog(LOG_ERR, "Cannot adjust stack limit for mlockall: %m"); } } # ifdef RLIMIT_MEMLOCK /* * The default RLIMIT_MEMLOCK is very low on Linux systems. * Unless we increase this limit malloc calls are likely to * fail if we drop root privlege. To be useful the value * has to be larger than the largest ntpd resident set size. */ rl.rlim_cur = rl.rlim_max = 32*1024*1024; if (setrlimit(RLIMIT_MEMLOCK, &rl) == -1) { msyslog(LOG_ERR, "Cannot set RLIMIT_MEMLOCK: %m"); } # endif /* RLIMIT_MEMLOCK */ } # endif /* HAVE_SETRLIMIT */ /* * lock the process into memory */ if (mlockall(MCL_CURRENT|MCL_FUTURE) < 0) msyslog(LOG_ERR, "mlockall(): %m"); #else /* not (HAVE_MLOCKALL && MCL_CURRENT && MCL_FUTURE) */ # ifdef HAVE_PLOCK # ifdef PROCLOCK # ifdef _AIX /* * set the stack limit for AIX for plock(). * see get_aix_stack() for more info. */ if (ulimit(SET_STACKLIM, (get_aix_stack() - 8*4096)) < 0) { msyslog(LOG_ERR,"Cannot adjust stack limit for plock on AIX: %m"); } # endif /* _AIX */ /* * lock the process into memory */ if (plock(PROCLOCK) < 0) msyslog(LOG_ERR, "plock(PROCLOCK): %m"); # else /* not PROCLOCK */ # ifdef TXTLOCK /* * Lock text into ram */ if (plock(TXTLOCK) < 0) msyslog(LOG_ERR, "plock(TXTLOCK) error: %m"); # else /* not TXTLOCK */ msyslog(LOG_ERR, "plock() - don't know what to lock!"); # endif /* not TXTLOCK */ # endif /* not PROCLOCK */ # endif /* HAVE_PLOCK */ #endif /* not (HAVE_MLOCKALL && MCL_CURRENT && MCL_FUTURE) */ /* * Set up signals we pay attention to locally. */ #ifdef SIGDIE1 (void) signal_no_reset(SIGDIE1, finish); #endif /* SIGDIE1 */ #ifdef SIGDIE2 (void) signal_no_reset(SIGDIE2, finish); #endif /* SIGDIE2 */ #ifdef SIGDIE3 (void) signal_no_reset(SIGDIE3, finish); #endif /* SIGDIE3 */ #ifdef SIGDIE4 (void) signal_no_reset(SIGDIE4, finish); #endif /* SIGDIE4 */ #ifdef SIGBUS (void) signal_no_reset(SIGBUS, finish); #endif /* SIGBUS */ #if !defined(SYS_WINNT) && !defined(VMS) # ifdef DEBUG (void) signal_no_reset(MOREDEBUGSIG, moredebug); (void) signal_no_reset(LESSDEBUGSIG, lessdebug); # else (void) signal_no_reset(MOREDEBUGSIG, no_debug); (void) signal_no_reset(LESSDEBUGSIG, no_debug); # endif /* DEBUG */ #endif /* !SYS_WINNT && !VMS */ /* * Set up signals we should never pay attention to. */ #if defined SIGPIPE (void) signal_no_reset(SIGPIPE, SIG_IGN); #endif /* SIGPIPE */ /* * Call the init_ routines to initialize the data structures. * * Exactly what command-line options are we expecting here? */ init_auth(); init_util(); init_restrict(); init_mon(); init_timer(); init_lib(); init_request(); init_control(); init_peer(); #ifdef REFCLOCK init_refclock(); #endif set_process_priority(); init_proto(); /* Call at high priority */ init_io(); init_loopfilter(); mon_start(MON_ON); /* monitor on by default now */ /* turn off in config if unwanted */ /* * Get the configuration. This is done in a separate module * since this will definitely be different for the gizmo board. */ getconfig(argc, argv); report_event(EVNT_SYSRESTART, NULL, NULL); loop_config(LOOP_DRIFTCOMP, old_drift); initializing = 0; #ifdef HAVE_DROPROOT if( droproot ) { /* Drop super-user privileges and chroot now if the OS supports this */ #ifdef HAVE_LINUX_CAPABILITIES /* set flag: keep privileges accross setuid() call (we only really need cap_sys_time): */ if (prctl( PR_SET_KEEPCAPS, 1L, 0L, 0L, 0L ) == -1) { msyslog( LOG_ERR, "prctl( PR_SET_KEEPCAPS, 1L ) failed: %m" ); exit(-1); } #else /* we need a user to switch to */ if (user == NULL) { msyslog(LOG_ERR, "Need user name to drop root privileges (see -u flag!)" ); exit(-1); } #endif /* HAVE_LINUX_CAPABILITIES */ if (user != NULL) { if (isdigit((unsigned char)*user)) { sw_uid = (uid_t)strtoul(user, &endp, 0); if (*endp != '\0') goto getuser; if ((pw = getpwuid(sw_uid)) != NULL) { user = strdup(pw->pw_name); if (NULL == user) { msyslog(LOG_ERR, "strdup() failed: %m"); exit (-1); } sw_gid = pw->pw_gid; } else { errno = 0; msyslog(LOG_ERR, "Cannot find user ID %s", user); exit (-1); } } else { getuser: errno = 0; if ((pw = getpwnam(user)) != NULL) { sw_uid = pw->pw_uid; sw_gid = pw->pw_gid; } else { if (errno) msyslog(LOG_ERR, "getpwnam(%s) failed: %m", user); else msyslog(LOG_ERR, "Cannot find user `%s'", user); exit (-1); } } } if (group != NULL) { if (isdigit((unsigned char)*group)) { sw_gid = (gid_t)strtoul(group, &endp, 0); if (*endp != '\0') goto getgroup; } else { getgroup: if ((gr = getgrnam(group)) != NULL) { sw_gid = gr->gr_gid; } else { errno = 0; msyslog(LOG_ERR, "Cannot find group `%s'", group); exit (-1); } } } if (chrootdir ) { /* make sure cwd is inside the jail: */ if (chdir(chrootdir)) { msyslog(LOG_ERR, "Cannot chdir() to `%s': %m", chrootdir); exit (-1); } if (chroot(chrootdir)) { msyslog(LOG_ERR, "Cannot chroot() to `%s': %m", chrootdir); exit (-1); } if (chdir("/")) { msyslog(LOG_ERR, "Cannot chdir() to`root after chroot(): %m"); exit (-1); } } if (user && initgroups(user, sw_gid)) { msyslog(LOG_ERR, "Cannot initgroups() to user `%s': %m", user); exit (-1); } if (group && setgid(sw_gid)) { msyslog(LOG_ERR, "Cannot setgid() to group `%s': %m", group); exit (-1); } if (group && setegid(sw_gid)) { msyslog(LOG_ERR, "Cannot setegid() to group `%s': %m", group); exit (-1); } if (group) setgroups(1, &sw_gid); else initgroups(pw->pw_name, pw->pw_gid); if (user && setuid(sw_uid)) { msyslog(LOG_ERR, "Cannot setuid() to user `%s': %m", user); exit (-1); } if (user && seteuid(sw_uid)) { msyslog(LOG_ERR, "Cannot seteuid() to user `%s': %m", user); exit (-1); } #ifndef HAVE_LINUX_CAPABILITIES /* * for now assume that the privilege to bind to privileged ports * is associated with running with uid 0 - should be refined on * ports that allow binding to NTP_PORT with uid != 0 */ disable_dynamic_updates |= (sw_uid != 0); /* also notifies routing message listener */ #endif if (disable_dynamic_updates && interface_interval) { interface_interval = 0; msyslog(LOG_INFO, "running in unprivileged mode disables dynamic interface tracking"); } #ifdef HAVE_LINUX_CAPABILITIES do { /* * We may be running under non-root uid now, but we still hold full root privileges! * We drop all of them, except for the crucial one or two: cap_sys_time and * cap_net_bind_service if doing dynamic interface tracking. */ cap_t caps; char *captext = (interface_interval) ? "cap_sys_time,cap_net_bind_service=ipe" : "cap_sys_time=ipe"; if( ! ( caps = cap_from_text( captext ) ) ) { msyslog( LOG_ERR, "cap_from_text() failed: %m" ); exit(-1); } if( cap_set_proc( caps ) == -1 ) { msyslog( LOG_ERR, "cap_set_proc() failed to drop root privileges: %m" ); exit(-1); } cap_free( caps ); } while(0); #endif /* HAVE_LINUX_CAPABILITIES */ } /* if( droproot ) */ #endif /* HAVE_DROPROOT */ /* * Use select() on all on all input fd's for unlimited * time. select() will terminate on SIGALARM or on the * reception of input. Using select() means we can't do * robust signal handling and we get a potential race * between checking for alarms and doing the select(). * Mostly harmless, I think. */ /* On VMS, I suspect that select() can't be interrupted * by a "signal" either, so I take the easy way out and * have select() time out after one second. * System clock updates really aren't time-critical, * and - lacking a hardware reference clock - I have * yet to learn about anything else that is. */ #if defined(HAVE_IO_COMPLETION_PORT) for (;;) { GetReceivedBuffers(); #else /* normal I/O */ BLOCK_IO_AND_ALARM(); was_alarmed = 0; for (;;) { # if !defined(HAVE_SIGNALED_IO) extern fd_set activefds; extern int maxactivefd; fd_set rdfdes; int nfound; # endif if (alarm_flag) /* alarmed? */ { was_alarmed = 1; alarm_flag = 0; } if (!was_alarmed && has_full_recv_buffer() == ISC_FALSE) { /* * Nothing to do. Wait for something. */ # ifndef HAVE_SIGNALED_IO rdfdes = activefds; # if defined(VMS) || defined(SYS_VXWORKS) /* make select() wake up after one second */ { struct timeval t1; t1.tv_sec = 1; t1.tv_usec = 0; nfound = select(maxactivefd+1, &rdfdes, (fd_set *)0, (fd_set *)0, &t1); } # else nfound = select(maxactivefd+1, &rdfdes, (fd_set *)0, (fd_set *)0, (struct timeval *)0); # endif /* VMS */ if (nfound > 0) { l_fp ts; get_systime(&ts); (void)input_handler(&ts); } else if (nfound == -1 && errno != EINTR) msyslog(LOG_ERR, "select() error: %m"); # ifdef DEBUG else if (debug > 5) msyslog(LOG_DEBUG, "select(): nfound=%d, error: %m", nfound); # endif /* DEBUG */ # else /* HAVE_SIGNALED_IO */ wait_for_signal(); # endif /* HAVE_SIGNALED_IO */ if (alarm_flag) /* alarmed? */ { was_alarmed = 1; alarm_flag = 0; } } if (was_alarmed) { UNBLOCK_IO_AND_ALARM(); /* * Out here, signals are unblocked. Call timer routine * to process expiry. */ timer(); was_alarmed = 0; BLOCK_IO_AND_ALARM(); } #endif /* ! HAVE_IO_COMPLETION_PORT */ #ifdef DEBUG_TIMING { l_fp pts; l_fp tsa, tsb; int bufcount = 0; get_systime(&pts); tsa = pts; #endif rbuf = get_full_recv_buffer(); while (rbuf != NULL) { if (alarm_flag) { was_alarmed = 1; alarm_flag = 0; } UNBLOCK_IO_AND_ALARM(); if (was_alarmed) { /* avoid timer starvation during lengthy I/O handling */ timer(); was_alarmed = 0; } /* * Call the data procedure to handle each received * packet. */ if (rbuf->receiver != NULL) /* This should always be true */ { #ifdef DEBUG_TIMING l_fp dts = pts; L_SUB(&dts, &rbuf->recv_time); DPRINTF(2, ("processing timestamp delta %s (with prec. fuzz)\n", lfptoa(&dts, 9))); collect_timing(rbuf, "buffer processing delay", 1, &dts); bufcount++; #endif (rbuf->receiver)(rbuf); } else { msyslog(LOG_ERR, "receive buffer corruption - receiver found to be NULL - ABORTING"); abort(); } BLOCK_IO_AND_ALARM(); freerecvbuf(rbuf); rbuf = get_full_recv_buffer(); } #ifdef DEBUG_TIMING get_systime(&tsb); L_SUB(&tsb, &tsa); if (bufcount) { collect_timing(NULL, "processing", bufcount, &tsb); DPRINTF(2, ("processing time for %d buffers %s\n", bufcount, lfptoa(&tsb, 9))); } } #endif /* * Go around again */ #ifdef HAVE_DNSREGISTRATION if (mdnsreg && (current_time - mdnsreg ) > 60 && mdnstries && sys_leap != LEAP_NOTINSYNC) { mdnsreg = current_time; msyslog(LOG_INFO, "Attempting to register mDNS"); if ( DNSServiceRegister (&mdns, 0, 0, NULL, "_ntp._udp", NULL, NULL, htons(NTP_PORT), 0, NULL, NULL, NULL) != kDNSServiceErr_NoError ) { if (!--mdnstries) { msyslog(LOG_ERR, "Unable to register mDNS, giving up."); } else { msyslog(LOG_INFO, "Unable to register mDNS, will try later."); } } else { msyslog(LOG_INFO, "mDNS service registered."); mdnsreg = 0; } } #endif /* HAVE_DNSREGISTRATION */ } UNBLOCK_IO_AND_ALARM(); return 1; } #ifdef SIGDIE2 /* * finish - exit gracefully */ static RETSIGTYPE finish( int sig ) { msyslog(LOG_NOTICE, "ntpd exiting on signal %d", sig); #ifdef HAVE_DNSREGISTRATION if (mdns != NULL) DNSServiceRefDeallocate(mdns); #endif switch (sig) { # ifdef SIGBUS case SIGBUS: printf("\nfinish(SIGBUS)\n"); exit(0); # endif case 0: /* Should never happen... */ return; default: exit(0); } }
int main(int argc, char *argv[]) { QtSingleApplication instance(argc, argv, QApplication::GuiServer); instance.setApplicationName(APPNAME); instance.setOrganizationName(ORGANISATION); QStringList argsList = instance.arguments(); QString argsString = argsList.join(ARGS_SPLIT_TOKEN); //Hide mouse cursor by default #ifdef ENABLE_QWS_STUFF QWSServer *qserver = QWSServer::instance(); qserver->setCursorVisible(false); #endif // Show help message if (argsList.contains("-h") || argsList.contains("--help")) { printf("\tUsage: %s [-d] -qws -nomouse [SetUrl http://example.com/]\n" "\tIf -d is specified, this program will run as a daemon.\n" "\tFor more info, see http://wiki.chumby.com/index.php/NeTV_local_UI\n", argv[0]); return 0; } //Check if another instance is already running & attempt to send arguments to it if (instance.sendMessage(argsString)) { printf("Sending arguments to running %s instance: %s\n", TAG, argsString.toLatin1().constData()); return 0; } //Give it another go if (instance.sendMessage(argsString)) { printf("Sending arguments to running %s instance: %s\n", TAG, argsString.toLatin1().constData()); return 0; } bool running = isRunning(); if (running) { // For some reason, the local socket in previous instance doesn't accept command. We give up. printf("Failed to send arguments to running %s instance: %s\n", TAG, argsString.toLatin1().constData()); return 1; } // If the args list contains "-d", then daemonize it int temp = 0; if (argsList.contains("-d") || argsList.contains("--daemon")) temp = daemon(0, 0); printf("Starting new %s with args:", TAG); printf("%s", argsString.toLatin1().constData()); //Pink background for the entire QWS environment #ifdef ENABLE_QWS_STUFF qserver->setBackground(QBrush(QColor(240,0,240))); #endif MainWindow w; w.receiveArgs(argsString); #ifdef Q_WS_QWS w.showFullScreen(); #else w.show(); #endif instance.setActivationWindow(&w); QObject::connect(&instance, SIGNAL(messageReceived(const QString&)), &w, SLOT(receiveArgs(const QString&))); return instance.exec(); }
/* The beginning of everything */ int main(int argc, char **argv) { struct user_options user_ops; /* holds user configuration data */ struct rand_pool_info *rand = NULL; /* structure to pass entropy (IOCTL) */ int random_fd = 0; /* output file descriptor */ int random_hw_fd = 0; /* input file descriptor */ int ent_count; /* current system entropy */ int write_size; /* max entropy data to pass */ struct pollfd fds[1]; /* used for polling file descriptor */ int ret; int exitval = 0; /*Hold minimal permissions, just enough to get IOCTL working*/ if(0 != qrng_update_cap()){ log_print(ERROR, "qrngd permission reset failed, exiting\n"); exitval = 1; goto exit; } /* set default parameters */ user_ops.run_as_daemon = TRUE; strcpy(user_ops.input_device_name, RANDOM_DEVICE_HW); strcpy(user_ops.output_device_name, RANDOM_DEVICE); /* display application header */ title(); /* get user preferences */ ret = get_user_options(&user_ops, argc, argv); if (ret < 0) { usage(); exitval = 1; goto exit; } /* open hardware random device */ random_hw_fd = open(user_ops.input_device_name, O_RDONLY); if (random_hw_fd < 0) { fprintf(stderr, "Can't open hardware random device file %s\n", user_ops.input_device_name); exitval = 1; goto exit; } /* open random device */ random_fd = open(user_ops.output_device_name, O_RDWR); if (random_fd < 0) { fprintf(stderr, "Can't open random device file %s\n", user_ops.output_device_name); exitval = 1; goto exit; } /* allocate memory for ioctl data struct and buffer */ rand = malloc(sizeof(struct rand_pool_info) + MAX_ENT_POOL_WRITES); if (!rand) { fprintf(stderr, "Can't allocate memory\n"); exitval = 1; goto exit; } /* setup poll() data */ memset(fds, 0 , sizeof(fds)); fds[0].fd = random_fd; fds[0].events = POLLOUT; /* run as daemon if requested to do so */ if (user_ops.run_as_daemon) { fprintf(stderr, "Starting daemon.\n"); if (daemon(0, 0) < 0) { fprintf(stderr, "can't daemonize: %s\n", strerror(errno)); exitval = 1; goto exit; } #ifndef ANDROID_CHANGES openlog(APP_NAME, 0, LOG_DAEMON); #endif } /* log message */ log_print(INFO, APP_NAME " has started:\n" "Reading device:'%s' updating entropy for device:'%s'", user_ops.input_device_name, user_ops.output_device_name); /* main loop to get data from hardware and feed RNG entropy pool */ while (1) { /* Check for empty buffer and fill with hardware random generated numbers */ if (buffsize == 0) { /* fill buffer with random data from hardware */ ret = read_src(random_hw_fd, databuf, MAX_BUFFER); if (ret < 0) { log_print(ERROR, "ERROR: Can't read from hardware source."); exitval = 1; goto exit; } /* run FIPS test on buffer, if buffer fails then ditch it and get new data */ ret = fips_test(databuf, MAX_BUFFER); if (ret < 0) { buffsize = 0; log_print(INFO, "ERROR: Failed FIPS test."); } /* everything good, reset buffer variables to indicate full buffer */ else { buffsize = MAX_BUFFER; curridx = 0; } } /* We should have data here, if not then something bad happened above and we should wait and try again */ if (buffsize == 0) { log_print(ERROR, "ERROR: Timeout getting valid random data from hardware."); usleep(100000); /* 100ms */ continue; } /* Get current entropy pool size in bits and convert to bytes */ if (ioctl(random_fd, RNDGETENTCNT, &ent_count) != 0) { log_print(ERROR, "ERROR: Can't read entropy count."); exitval = 1; goto exit; } /* convert entropy bits to bytes */ ent_count >>= 3; /* fill entropy pool */ write_size = min(buffsize, MAX_ENT_POOL_WRITES); /* Write some data to the device */ rand->entropy_count = write_size * 8; rand->buf_size = write_size; memcpy(rand->buf, &databuf[curridx], write_size); curridx += write_size; buffsize -= write_size; /* Issue the ioctl to increase the entropy count */ if (ioctl(random_fd, RNDADDENTROPY, rand) < 0) { log_print(ERROR,"ERROR: RNDADDENTROPY ioctl() failed."); exitval = 1; goto exit; } /* Wait if entropy pool is full */ ret = poll(fds, 1, -1); if (ret < 0) { log_print(ERROR,"ERROR: poll call failed."); /* wait if error */ usleep(100000); } } exit: /* free other resources */ if (rand) free(rand); if (random_fd) close(random_fd); if (random_hw_fd) close(random_hw_fd); return exitval; }
// Main int main(int argc, char *argv[]) { //Initialize logger singleton here to avoid threading issues Logger::instance()->addMessage(QObject::tr("qBittorrent %1 started", "qBittorrent v3.2.0alpha started").arg(VERSION)); // We must save it here because QApplication constructor may change it bool isOneArg = (argc == 2); // Create Application QString appId = QLatin1String("qBittorrent-") + misc::getUserIDString(); QScopedPointer<Application> app(new Application(appId, argc, argv)); const QBtCommandLineParameters params = parseCommandLine(); if (!params.unknownParameter.isEmpty()) { displayBadArgMessage(QObject::tr("%1 is an unknown command line parameter.", "--random-parameter is an unknown command line parameter.") .arg(params.unknownParameter)); return EXIT_FAILURE; } #ifndef Q_OS_WIN if (params.showVersion) { if (isOneArg) { displayVersion(); return EXIT_SUCCESS; } else { displayBadArgMessage(QObject::tr("%1 must be the single command line parameter.") .arg(QLatin1String("-v (or --version)"))); return EXIT_FAILURE; } } #endif if (params.showHelp) { if (isOneArg) { displayUsage(argv[0]); return EXIT_SUCCESS; } else { displayBadArgMessage(QObject::tr("%1 must be the single command line parameter.") .arg(QLatin1String("-h (or --help)"))); return EXIT_FAILURE; } } if ((params.webUiPort > 0) && (params.webUiPort <= 65535)) { Preferences::instance()->setWebUiPort(params.webUiPort); } else { displayBadArgMessage(QObject::tr("%1 must specify the correct port (1 to 65535).") .arg(QLatin1String("--webui-port"))); return EXIT_FAILURE; } // Set environment variable if (!qputenv("QBITTORRENT", QByteArray(VERSION))) std::cerr << "Couldn't set environment variable...\n"; if (!userAgreesWithLegalNotice()) return EXIT_SUCCESS; // Check if qBittorrent is already running for this user if (app->isRunning()) { #ifdef DISABLE_GUI if (params.shouldDaemonize) { displayBadArgMessage(QObject::tr("You cannot use %1: qBittorrent is already running for this user.") .arg(QLatin1String("-d (or --daemon)"))); return EXIT_FAILURE; } else #endif qDebug("qBittorrent is already running for this user."); misc::msleep(300); app->sendParams(params.torrents); return EXIT_SUCCESS; } srand(time(0)); #ifdef DISABLE_GUI if (params.shouldDaemonize) { app.reset(); // Destroy current application if ((daemon(1, 0) == 0)) { app.reset(new Application(appId, argc, argv)); if (app->isRunning()) { // Another instance had time to start. return EXIT_FAILURE; } } else { qCritical("Something went wrong while daemonizing, exiting..."); return EXIT_FAILURE; } } #else if (!params.noSplash) showSplashScreen(); #endif #if defined(Q_OS_UNIX) || defined(STACKTRACE_WIN) signal(SIGABRT, sigabrtHandler); signal(SIGTERM, sigtermHandler); signal(SIGINT, sigintHandler); signal(SIGSEGV, sigsegvHandler); #endif return app->exec(params.torrents); }
int main (int argc, char **argv) { int c; char *config_dir = DEFAULT_CONFIG_DIR; char *seafile_dir = NULL; char *worktree_dir = NULL; char *logfile = NULL; const char *debug_str = NULL; int daemon_mode = 0; CcnetClient *client; char *ccnet_debug_level_str = "info"; char *seafile_debug_level_str = "debug"; #ifdef WIN32 argv = get_argv_utf8 (&argc); #endif while ((c = getopt_long (argc, argv, short_options, long_options, NULL)) != EOF) { switch (c) { case 'h': exit (1); break; case 'v': exit (1); break; case 'c': config_dir = optarg; break; case 'd': seafile_dir = g_strdup(optarg); break; case 'b': daemon_mode = 1; break; case 'D': debug_str = optarg; break; case 'w': worktree_dir = g_strdup(optarg); break; case 'l': logfile = g_strdup(optarg); break; case 'g': ccnet_debug_level_str = optarg; break; case 'G': seafile_debug_level_str = optarg; break; default: usage (); exit (1); } } argc -= optind; argv += optind; #ifndef WIN32 #ifndef __APPLE__ if (daemon_mode) daemon (1, 0); #endif #endif g_type_init (); #if !GLIB_CHECK_VERSION(2,32,0) g_thread_init (NULL); #endif if (!debug_str) debug_str = g_getenv("SEAFILE_DEBUG"); seafile_debug_set_flags_string (debug_str); /* init ccnet */ client = ccnet_init (config_dir); if (!client) exit (1); register_processors (client); start_rpc_service (client); create_sync_rpc_clients (config_dir); appletrpc_client = ccnet_create_async_rpc_client (client, NULL, "applet-rpcserver"); /* init seafile */ if (seafile_dir == NULL) seafile_dir = g_build_filename (config_dir, "seafile-data", NULL); if (worktree_dir == NULL) worktree_dir = g_build_filename (g_get_home_dir(), "seafile", NULL); if (logfile == NULL) logfile = g_build_filename (config_dir, "logs", "seafile.log", NULL); seaf = seafile_session_new (seafile_dir, worktree_dir, client); if (!seaf) { fprintf (stderr, "Failed to create seafile session.\n"); exit (1); } seaf->ccnetrpc_client = ccnetrpc_client; seaf->appletrpc_client = appletrpc_client; if (seafile_log_init (logfile, ccnet_debug_level_str, seafile_debug_level_str) < 0) { fprintf (stderr, "Failed to init log.\n"); exit (1); } seaf_message ("starting seaf-daemon "PACKAGE_VERSION"\n"); g_free (seafile_dir); g_free (worktree_dir); g_free (logfile); set_signal_handlers (seaf); seafile_session_prepare (seaf); seafile_session_start (seaf); seafile_session_config_set_string (seaf, "wktree", seaf->worktree_dir); ccnet_main (client); return 0; }
int main(int argc, char* argv[]) { int result = 0; int rd, ctr, combo = 0; char keyStates[256]; int detach = 0; int opt; while ((opt = getopt(argc, argv, "+ds")) != -1) { switch (opt) { case 'd': detach = 1; break; case 's': use_syslog = 1; break; default: fprintf(stderr, "Usage: %s [-d] [-s]\n", argv[0]); exit(EXIT_FAILURE); break; } } SYSLOG(LOG_NOTICE, "Starting."); printf("[Xarcade2Joystick] Getting exclusive access: "); result = input_xarcade_open(&xarcdev, INPUT_XARC_TYPE_TANKSTICK); if (result != 0) { if (errno == 0) { printf("Not found.\n"); SYSLOG(LOG_ERR, "Xarcade not found, exiting."); } else { printf("Failed to get exclusive access to Xarcade: %d (%s)\n", errno, strerror(errno)); SYSLOG(LOG_ERR, "Failed to get exclusive access to Xarcade, exiting: %d (%s)", errno, strerror(errno)); } exit(EXIT_FAILURE); } SYSLOG(LOG_NOTICE, "Got exclusive access to Xarcade."); uinput_gpad_open(&uinp_gpads[0], UINPUT_GPAD_TYPE_XARCADE); uinput_gpad_open(&uinp_gpads[1], UINPUT_GPAD_TYPE_XARCADE); uinput_kbd_open(&uinp_kbd); if (detach) { if (daemon(0, 1)) { perror("daemon"); return 1; } } signal(SIGINT, signal_handler); signal(SIGTERM, signal_handler); SYSLOG(LOG_NOTICE, "Running."); while (1) { rd = input_xarcade_read(&xarcdev); if (rd < 0) { break; } for (ctr = 0; ctr < rd; ctr++) { if (xarcdev.ev[ctr].type == 0) continue; if (xarcdev.ev[ctr].type == EV_MSC) continue; if (EV_KEY == xarcdev.ev[ctr].type) { keyStates[xarcdev.ev[ctr].code] = xarcdev.ev[ctr].value; switch (xarcdev.ev[ctr].code) { /* ---------------- Player 1 controls ------------------- */ /* buttons */ case KEY_LEFTCTRL: uinput_gpad_write(&uinp_gpads[0], BTN_A, xarcdev.ev[ctr].value > 0, EV_KEY); break; case KEY_LEFTALT: uinput_gpad_write(&uinp_gpads[0], BTN_B, xarcdev.ev[ctr].value > 0, EV_KEY); break; case KEY_SPACE: uinput_gpad_write(&uinp_gpads[0], BTN_C, xarcdev.ev[ctr].value > 0, EV_KEY); break; case KEY_LEFTSHIFT: uinput_gpad_write(&uinp_gpads[0], BTN_X, xarcdev.ev[ctr].value > 0, EV_KEY); break; case KEY_Z: uinput_gpad_write(&uinp_gpads[0], BTN_Y, xarcdev.ev[ctr].value > 0, EV_KEY); break; case KEY_X: uinput_gpad_write(&uinp_gpads[0], BTN_Z, xarcdev.ev[ctr].value > 0, EV_KEY); break; case KEY_C: uinput_gpad_write(&uinp_gpads[0], BTN_TL, xarcdev.ev[ctr].value > 0, EV_KEY); break; case KEY_5: uinput_gpad_write(&uinp_gpads[0], BTN_TR, xarcdev.ev[ctr].value > 0, EV_KEY); break; case KEY_1: /* handle combination */ if (keyStates[KEY_3] && xarcdev.ev[ctr].value) { uinput_kbd_write(&uinp_kbd, KEY_TAB, 1, EV_KEY); uinput_kbd_sleep(); uinput_kbd_write(&uinp_kbd, KEY_TAB, 0, EV_KEY); combo = 2; continue; } /* it's a key down, ignore */ if (xarcdev.ev[ctr].value) continue; if (!combo) { uinput_gpad_write(&uinp_gpads[0], BTN_START, 1, EV_KEY); uinput_gpad_sleep(); uinput_gpad_write(&uinp_gpads[0], BTN_START, 0, EV_KEY); } else combo--; break; case KEY_3: /* it's a key down, ignore */ if (xarcdev.ev[ctr].value) continue; if (!combo) { uinput_gpad_write(&uinp_gpads[0], BTN_SELECT, 1, EV_KEY); uinput_gpad_sleep(); uinput_gpad_write(&uinp_gpads[0], BTN_SELECT, 0, EV_KEY); } else combo--; break; /* joystick */ case KEY_KP4: case KEY_LEFT: uinput_gpad_write(&uinp_gpads[0], ABS_X, xarcdev.ev[ctr].value == 0 ? 2 : 0, EV_ABS); // center or left break; case KEY_KP6: case KEY_RIGHT: uinput_gpad_write(&uinp_gpads[0], ABS_X, xarcdev.ev[ctr].value == 0 ? 2 : 4, EV_ABS); // center or right break; case KEY_KP8: case KEY_UP: uinput_gpad_write(&uinp_gpads[0], ABS_Y, xarcdev.ev[ctr].value == 0 ? 2 : 0, EV_ABS); // center or up break; case KEY_KP2: case KEY_DOWN: uinput_gpad_write(&uinp_gpads[0], ABS_Y, xarcdev.ev[ctr].value == 0 ? 2 : 4, EV_ABS); // center or down break; /* ---------------- Player 2 controls ------------------- */ /* buttons */ case KEY_A: uinput_gpad_write(&uinp_gpads[1], BTN_A, xarcdev.ev[ctr].value > 0, EV_KEY); break; case KEY_S: uinput_gpad_write(&uinp_gpads[1], BTN_B, xarcdev.ev[ctr].value > 0, EV_KEY); break; case KEY_Q: uinput_gpad_write(&uinp_gpads[1], BTN_C, xarcdev.ev[ctr].value > 0, EV_KEY); break; case KEY_W: uinput_gpad_write(&uinp_gpads[1], BTN_X, xarcdev.ev[ctr].value > 0, EV_KEY); break; case KEY_E: uinput_gpad_write(&uinp_gpads[1], BTN_Y, xarcdev.ev[ctr].value > 0, EV_KEY); break; case KEY_LEFTBRACE: uinput_gpad_write(&uinp_gpads[1], BTN_Z, xarcdev.ev[ctr].value > 0, EV_KEY); break; case KEY_RIGHTBRACE: uinput_gpad_write(&uinp_gpads[1], BTN_TL, xarcdev.ev[ctr].value > 0, EV_KEY); break; case KEY_6: uinput_gpad_write(&uinp_gpads[1], BTN_TR, xarcdev.ev[ctr].value > 0, EV_KEY); break; case KEY_2: /* handle combination */ if (keyStates[KEY_4] && xarcdev.ev[ctr].value) { uinput_kbd_write(&uinp_kbd, KEY_ESC, 1, EV_KEY); uinput_kbd_sleep(); uinput_kbd_write(&uinp_kbd, KEY_ESC, 0, EV_KEY); combo = 2; continue; } /* it's a key down, ignore */ if (xarcdev.ev[ctr].value) continue; if (!combo) { uinput_gpad_write(&uinp_gpads[1], BTN_START, 1, EV_KEY); uinput_gpad_sleep(); uinput_gpad_write(&uinp_gpads[1], BTN_START, 0, EV_KEY); } else combo--; break; case KEY_4: /* it's a key down, ignore */ if (xarcdev.ev[ctr].value) continue; if (!combo) { uinput_gpad_write(&uinp_gpads[1], BTN_SELECT, 1, EV_KEY); uinput_gpad_sleep(); uinput_gpad_write(&uinp_gpads[1], BTN_SELECT, 0, EV_KEY); } else combo--; break; /* joystick */ case KEY_D: uinput_gpad_write(&uinp_gpads[1], ABS_X, xarcdev.ev[ctr].value == 0 ? 2 : 0, EV_ABS); // center or left break; case KEY_G: uinput_gpad_write(&uinp_gpads[1], ABS_X, xarcdev.ev[ctr].value == 0 ? 2 : 4, EV_ABS); // center or right break; case KEY_R: uinput_gpad_write(&uinp_gpads[1], ABS_Y, xarcdev.ev[ctr].value == 0 ? 2 : 0, EV_ABS); // center or up break; case KEY_F: uinput_gpad_write(&uinp_gpads[1], ABS_Y, xarcdev.ev[ctr].value == 0 ? 2 : 4, EV_ABS); // center or down break; default: break; } } } } teardown(); return EXIT_SUCCESS; }
int main(int argc,char **argv) { static struct option longopts[] = { {"help",no_argument,NULL,'h'}, {"version",no_argument,NULL,'V'}, {"verbose",no_argument,NULL,'v'}, {"foreground",no_argument,NULL,'f'}, {"evmap",required_argument,NULL,'e'}, {"socket",required_argument,NULL,'s'}, {"mode",required_argument,NULL,'m'}, {"process",required_argument,NULL,'p'}, {"repeat-filter",no_argument,NULL,'R'}, {"release",required_argument,NULL,'r'}, {0, 0, 0, 0} }; const char *progname = NULL; int verbose = 0; bool foreground = false; const char *input_device_evmap_dir = EVMAP_DIR; const char *lircd_socket_path = LIRCD_SOCKET; mode_t lircd_socket_mode = S_IWUSR | S_IRUSR | S_IWGRP | S_IRGRP | S_IWOTH | S_IROTH; bool input_repeat_filter = false; const char *lircd_release_suffix = NULL; int opt; for (progname = argv[0] ; strchr(progname, '/') != NULL ; progname = strchr(progname, '/') + 1); openlog(progname, LOG_CONS | LOG_PERROR | LOG_PID, LOG_DAEMON); while((opt = getopt_long(argc, argv, "hVvfe:s:m:r:", longopts, NULL)) != -1) { switch(opt) { case 'h': fprintf(stdout, "Usage: %s [options]\n", progname); fprintf(stdout, " -h --help print this help message and exit\n"); fprintf(stdout, " -V --version print the program version and exit\n"); fprintf(stdout, " -v --verbose increase the output message verbosity (-v, -vv or -vvv)\n"); fprintf(stdout, " -f --foreground run in the foreground\n"); fprintf(stdout, " -e --evmap=<dir> directory containing input device event map files (default is '%s')\n", input_device_evmap_dir); fprintf(stdout, " -s --socket=<socket> lircd socket (default is '%s')\n", lircd_socket_path); fprintf(stdout, " -m --mode=<mode> lircd socket mode (default is '%04o')\n", lircd_socket_mode); fprintf(stdout, " -R --repeat-filter enable repeat filtering (default is '%s')\n", input_repeat_filter ? "false" : "true"); fprintf(stdout, " -r --release=<suffix> generate key release events suffixed with <suffix>\n"); exit(EX_OK); break; case 'V': fprintf(stdout, PACKAGE_STRING "\n"); break; case 'v': if (verbose < 3) { verbose++; } else { syslog(LOG_WARNING, "the highest verbosity level is -vvv\n"); } case 'f': foreground = true; break; case 'e': input_device_evmap_dir = optarg; break; case 's': lircd_socket_path = optarg; break; case 'm': lircd_socket_mode = (mode_t)atol(optarg); break; case 'R': input_repeat_filter = true; break; case 'r': lircd_release_suffix = optarg; break; default: fprintf(stderr, "error: unknown option: %c\n", opt); exit(EX_USAGE); } } if (verbose == 0) { setlogmask(0 | LOG_DEBUG | LOG_INFO | LOG_NOTICE); } else if (verbose == 1) { setlogmask(0 | LOG_DEBUG | LOG_INFO); } else if (verbose == 2) { setlogmask(0 | LOG_DEBUG); } else { setlogmask(0); } signal(SIGPIPE, SIG_IGN); if (monitor_init() != 0) { exit(EXIT_FAILURE); } /* Initialize the lircd socket before daemonizing in order to ensure that programs started after it damonizes will have an lircd socket with which to connect. */ if (lircd_init(lircd_socket_path, lircd_socket_mode, lircd_release_suffix) != 0) { monitor_exit(); exit(EXIT_FAILURE); } if (foreground != true) { daemon(0, 0); } if (input_init(input_device_evmap_dir, input_repeat_filter) != 0) { monitor_exit(); lircd_exit(); exit(EXIT_FAILURE); } monitor_run(); if (input_exit() != 0) { monitor_exit(); lircd_exit(); exit(EXIT_FAILURE); } if (lircd_exit() != 0) { monitor_exit(); exit(EXIT_FAILURE); } if (monitor_exit() != 0) { exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { char hist_name[128]; struct sockaddr_un sun; FILE *hist_fp = NULL; int ch; int fd; while ((ch = getopt_long(argc, argv, "hvVzrnasd:t:eK", longopts, NULL)) != EOF) { switch(ch) { case 'z': dump_zeros = 1; break; case 'r': reset_history = 1; break; case 'a': ignore_history = 1; break; case 's': no_update = 1; break; case 'n': no_output = 1; break; case 'e': show_errors = 1; break; case 'd': scan_interval = atoi(optarg) * 1000; if (scan_interval <= 0) { fprintf(stderr, "ifstat: invalid scan interval\n"); exit(-1); } break; case 't': time_constant = atoi(optarg); if (time_constant <= 0) { fprintf(stderr, "ifstat: invalid time constant divisor\n"); exit(-1); } break; case 'v': case 'V': printf("ifstat utility, iproute2-ss%s\n", SNAPSHOT); exit(0); case 'h': case '?': default: usage(); } } argc -= optind; argv += optind; sun.sun_family = AF_UNIX; sun.sun_path[0] = 0; sprintf(sun.sun_path+1, "ifstat%d", getuid()); if (scan_interval > 0) { if (time_constant == 0) time_constant = 60; time_constant *= 1000; W = 1 - 1/exp(log(10)*(double)scan_interval/time_constant); if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) { perror("ifstat: socket"); exit(-1); } if (bind(fd, (struct sockaddr*)&sun, 2+1+strlen(sun.sun_path+1)) < 0) { perror("ifstat: bind"); exit(-1); } if (listen(fd, 5) < 0) { perror("ifstat: listen"); exit(-1); } if (daemon(0, 0)) { perror("ifstat: daemon"); exit(-1); } signal(SIGPIPE, SIG_IGN); signal(SIGCHLD, sigchild); server_loop(fd); exit(0); } patterns = argv; npatterns = argc; if (getenv("IFSTAT_HISTORY")) snprintf(hist_name, sizeof(hist_name), "%s", getenv("IFSTAT_HISTORY")); else snprintf(hist_name, sizeof(hist_name), "%s/.ifstat.u%d", P_tmpdir, getuid()); if (reset_history) unlink(hist_name); if (!ignore_history || !no_update) { struct stat stb; fd = open(hist_name, O_RDWR|O_CREAT|O_NOFOLLOW, 0600); if (fd < 0) { perror("ifstat: open history file"); exit(-1); } if ((hist_fp = fdopen(fd, "r+")) == NULL) { perror("ifstat: fdopen history file"); exit(-1); } if (flock(fileno(hist_fp), LOCK_EX)) { perror("ifstat: flock history file"); exit(-1); } if (fstat(fileno(hist_fp), &stb) != 0) { perror("ifstat: fstat history file"); exit(-1); } if (stb.st_nlink != 1 || stb.st_uid != getuid()) { fprintf(stderr, "ifstat: something is so wrong with history file, that I prefer not to proceed.\n"); exit(-1); } if (!ignore_history) { FILE *tfp; long uptime = -1; if ((tfp = fopen("/proc/uptime", "r")) != NULL) { if (fscanf(tfp, "%ld", &uptime) != 1) uptime = -1; fclose(tfp); } if (uptime >= 0 && time(NULL) >= stb.st_mtime+uptime) { fprintf(stderr, "ifstat: history is aged out, resetting\n"); ftruncate(fileno(hist_fp), 0); } } load_raw_table(hist_fp); hist_db = kern_db; kern_db = NULL; } if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) >= 0 && (connect(fd, (struct sockaddr*)&sun, 2+1+strlen(sun.sun_path+1)) == 0 || (strcpy(sun.sun_path+1, "ifstat0"), connect(fd, (struct sockaddr*)&sun, 2+1+strlen(sun.sun_path+1)) == 0)) && verify_forging(fd) == 0) { FILE *sfp = fdopen(fd, "r"); load_raw_table(sfp); if (hist_db && source_mismatch) { fprintf(stderr, "ifstat: history is stale, ignoring it.\n"); hist_db = NULL; } fclose(sfp); } else { if (fd >= 0) close(fd); if (hist_db && info_source[0] && strcmp(info_source, "kernel")) { fprintf(stderr, "ifstat: history is stale, ignoring it.\n"); hist_db = NULL; info_source[0] = 0; } load_info(); if (info_source[0] == 0) strcpy(info_source, "kernel"); } if (!no_output) { if (ignore_history || hist_db == NULL) dump_kern_db(stdout); else dump_incr_db(stdout); } if (!no_update) { ftruncate(fileno(hist_fp), 0); rewind(hist_fp); dump_raw_db(hist_fp, 1); fflush(hist_fp); } exit(0); }
int main(int argc, char ** argv) { pid_t pid; char log_prefix[50] = {0}; now = time(NULL); L = lua_open(); /* initialize Lua */ luaL_openlibs(L); /* load Lua base libraries */ tolua_interface_open(L); luaL_dofile (L, "script/server.lua"); /* load the script */ // 创建一个新的表 lua_newtable(L); int result; char* option = "a:b:c:de:f:g:h:i:j:k:l:m:n:o:p:q:r:s:t:u:v:w:x:y:z:"; while((result = getopt(argc, argv, option)) != -1) { if(result >= 'a' && result <= 'z') { if(result == 'd') { is_daemon = true; } else { char s[2]={0}; sprintf(s, "%c", result); lua_pushstring(L, s); lua_pushstring(L, optarg); lua_rawset(L, -3); } } } lua_setglobal(L, COMMAND_ARGS); //初始化日志文件 //log_info("Initing\n"); if (is_daemon) { if ( -1 == daemon(1, 0)) { fprintf(stdout, "%s\n", "daemon error."); } } pid = getpid(); snprintf(log_prefix, sizeof(log_prefix), "Log_%d", pid); init_log(log_prefix, "./"); init_timer(); __binding_cpu(); __signal_binding(); __pidfile(); __version(); CProtocal::init(); if(!net.init()) { log_error("init server failed"); return -1; } int ret = -1; if(call_lua("handle_init", ">d", &ret)) { return -1; } if(ret < 0) { log_error("call lua function handle_init failed"); return -1; } if(!net.start_server()) { log_error("start server failed"); return -1; } return 0; }
void listen_loop(int do_init) { struct client_struct* new_client; struct np_sock npsock = {.count = 0}; pthread_t client_tid; int ret; #ifdef NP_SSH ssh_bind sshbind = NULL; #endif #ifdef NP_TLS SSL_CTX* tlsctx = NULL; #endif /* Init */ if (do_init) { #ifdef NP_SSH np_ssh_init(); #endif #ifdef NP_TLS np_tls_init(); #endif } /* Main accept loop */ do { new_client = NULL; /* Binds change check */ if (netopeer_options.binds_change_flag) { /* BINDS LOCK */ pthread_mutex_lock(&netopeer_options.binds_lock); sock_cleanup(&npsock); sock_listen(netopeer_options.binds, &npsock); netopeer_options.binds_change_flag = 0; /* BINDS UNLOCK */ pthread_mutex_unlock(&netopeer_options.binds_lock); if (npsock.count == 0) { nc_verb_warning("Server is not listening on any address!"); } } #ifdef NP_SSH sshbind = np_ssh_server_id_check(sshbind); #endif #ifdef NP_TLS tlsctx = np_tls_server_id_check(tlsctx); #endif /* Callhome client check */ if (callhome_client != NULL) { /* CALLHOME LOCK */ pthread_mutex_lock(&callhome_lock); new_client = callhome_client; callhome_client = NULL; /* CALLHOME UNLOCK */ pthread_mutex_unlock(&callhome_lock); } /* Listen client check */ if (new_client == NULL) { new_client = sock_accept(&npsock); } /* New client full structure creation */ if (new_client != NULL) { /* Maximum number of sessions check */ if (netopeer_options.max_sessions > 0) { ret = 0; #ifdef NP_SSH ret += np_ssh_session_count(); #endif #ifdef NP_TLS ret += np_tls_session_count(); #endif if (ret >= netopeer_options.max_sessions) { nc_verb_error("Maximum number of sessions reached, droppping the new client."); new_client->to_free = 1; switch (new_client->transport) { #ifdef NP_SSH case NC_TRANSPORT_SSH: client_free_ssh((struct client_struct_ssh*)new_client); break; #endif #ifdef NP_TLS case NC_TRANSPORT_TLS: client_free_tls((struct client_struct_tls*)new_client); break; #endif default: free(new_client); nc_verb_error("%s: internal error (%s:%d)", __func__, __FILE__, __LINE__); } /* sleep to prevent clients from immediate connection retry */ usleep(netopeer_options.response_time*1000); continue; } } switch (new_client->transport) { #ifdef NP_SSH case NC_TRANSPORT_SSH: ret = np_ssh_create_client((struct client_struct_ssh*)new_client, sshbind); if (ret != 0) { new_client->to_free = 1; client_free_ssh((struct client_struct_ssh*)new_client); } break; #endif #ifdef NP_TLS case NC_TRANSPORT_TLS: ret = np_tls_create_client((struct client_struct_tls*)new_client, tlsctx); if (ret != 0) { new_client->to_free = 1; client_free_tls((struct client_struct_tls*)new_client); } break; #endif default: nc_verb_error("Client with an unknown transport protocol, dropping it."); free(new_client); ret = 1; } /* client is not valid, some error occured */ if (ret != 0) { continue; } /* add the client into the global clients structure */ /* GLOBAL WRITE LOCK */ pthread_rwlock_wrlock(&netopeer_state.global_lock); client_append(&netopeer_state.clients, new_client); /* GLOBAL WRITE UNLOCK */ pthread_rwlock_unlock(&netopeer_state.global_lock); /* start the client thread */ if ((ret = pthread_create((pthread_t*)&new_client->tid, NULL, client_main_thread, (void*)new_client)) != 0) { nc_verb_error("%s: failed to create a thread (%s)", __func__, strerror(ret)); np_client_detach(&netopeer_state.clients, new_client); new_client->tid = 0; new_client->to_free = 1; switch (new_client->transport) { #ifdef NP_SSH case NC_TRANSPORT_SSH: client_free_ssh((struct client_struct_ssh*)new_client); break; #endif #ifdef NP_TLS case NC_TRANSPORT_TLS: client_free_tls((struct client_struct_tls*)new_client); break; #endif default: free(new_client); break; } continue; } } } while (!quit && !restart_soft); /* Cleanup */ sock_cleanup(&npsock); #ifdef NP_SSH ssh_bind_free(sshbind); #endif #ifdef NP_TLS SSL_CTX_free(tlsctx); #endif if (!restart_soft) { /* wait for all the clients to exit nicely themselves */ while (1) { /* GLOBAL READ LOCK */ pthread_rwlock_rdlock(&netopeer_state.global_lock); if (netopeer_state.clients == NULL) { /* GLOBAL READ UNLOCK */ pthread_rwlock_unlock(&netopeer_state.global_lock); break; } client_tid = netopeer_state.clients->tid; /* GLOBAL READ UNLOCK */ pthread_rwlock_unlock(&netopeer_state.global_lock); ret = pthread_join(client_tid, NULL); if (ret != 0 && errno != EINTR) { nc_verb_error("Failed to join client thread (%s).", strerror(errno)); } } #ifdef NP_SSH np_ssh_cleanup(); #endif #ifdef NP_TLS np_tls_cleanup(); #endif } } int main(int argc, char** argv) { struct sigaction action; sigset_t block_mask; char *aux_string = NULL, path[PATH_MAX+1]; int next_option; int daemonize = 0, len; int listen_init = 1; struct np_module* netopeer_module = NULL, *server_module = NULL; /* initialize message system and set verbose and debug variables */ if ((aux_string = getenv(ENVIRONMENT_VERBOSE)) == NULL) { netopeer_options.verbose = NC_VERB_ERROR; } else { netopeer_options.verbose = atoi(aux_string); } aux_string = NULL; /* for sure to avoid unwanted changes in environment */ /* parse given options */ while ((next_option = getopt(argc, argv, OPTSTRING)) != -1) { switch (next_option) { case 'd': daemonize = 1; break; case 'h': print_usage(argv[0]); break; case 'v': netopeer_options.verbose = atoi(optarg); break; case 'V': print_version(argv[0]); break; default: print_usage(argv[0]); break; } } /* set signal handler */ sigfillset (&block_mask); action.sa_handler = signal_handler; action.sa_mask = block_mask; action.sa_flags = 0; sigaction(SIGINT, &action, NULL); sigaction(SIGQUIT, &action, NULL); sigaction(SIGABRT, &action, NULL); sigaction(SIGTERM, &action, NULL); sigaction(SIGHUP, &action, NULL); nc_callback_print(clb_print); /* normalize value if not from the enum */ if (netopeer_options.verbose > NC_VERB_DEBUG) { netopeer_options.verbose = NC_VERB_DEBUG; } nc_verbosity(netopeer_options.verbose); /* go to the background as a daemon */ if (daemonize == 1) { if (daemon(0, 0) != 0) { nc_verb_error("Going to background failed (%s)", strerror(errno)); return EXIT_FAILURE; } openlog("netopeer-server", LOG_PID, LOG_DAEMON); } else { openlog("netopeer-server", LOG_PID|LOG_PERROR, LOG_DAEMON); } /* make sure we were executed by root */ if (geteuid() != 0) { nc_verb_error("Failed to start, must have root privileges."); return EXIT_FAILURE; } /* * this initialize the library and check potential ABI mismatches * between the version it was compiled for and the actual shared * library used. */ LIBXML_TEST_VERSION /* initialize library including internal datastores and maybee something more */ if (nc_init(NC_INIT_ALL | NC_INIT_MULTILAYER) < 0) { nc_verb_error("Library initialization failed."); return EXIT_FAILURE; } server_start = 1; restart: /* start NETCONF server module */ if ((server_module = calloc(1, sizeof(struct np_module))) == NULL) { nc_verb_error("Creating necessary NETCONF server plugin failed!"); return EXIT_FAILURE; } server_module->name = strdup(NCSERVER_MODULE_NAME); if (module_enable(server_module, 0)) { nc_verb_error("Starting necessary NETCONF server plugin failed!"); free(server_module->name); free(server_module); return EXIT_FAILURE; } /* start netopeer device module - it will start all modules that are * in its configuration and in server configuration */ if ((netopeer_module = calloc(1, sizeof(struct np_module))) == NULL) { nc_verb_error("Creating necessary Netopeer plugin failed!"); module_disable(server_module, 1); return EXIT_FAILURE; } netopeer_module->name = strdup(NETOPEER_MODULE_NAME); if (module_enable(netopeer_module, 0)) { nc_verb_error("Starting necessary Netopeer plugin failed!"); module_disable(server_module, 1); free(netopeer_module->name); free(netopeer_module); return EXIT_FAILURE; } server_start = 0; nc_verb_verbose("Netopeer server successfully initialized."); listen_loop(listen_init); /* unload Netopeer module -> unload all modules */ module_disable(server_module, 1); module_disable(netopeer_module, 1); /* main cleanup */ if (!restart_soft) { /* close libnetconf only when shutting down or hard restarting the server */ nc_close(); } if (restart_soft) { nc_verb_verbose("Server is going to soft restart."); restart_soft = 0; listen_init = 0; goto restart; } else if (restart_hard) { nc_verb_verbose("Server is going to hard restart."); len = readlink("/proc/self/exe", path, PATH_MAX); if (len > 0) { path[len] = 0; xmlCleanupParser(); execv(path, argv); } nc_verb_error("Failed to get the path to self."); xmlCleanupParser(); return EXIT_FAILURE; } /* *Free the global variables that may *have been allocated by the parser. */ xmlCleanupParser(); return EXIT_SUCCESS; }
/* Main */ int main(int argc, char *argv[]) { struct sigaction sa; struct sockaddr_rfcomm ra; bdaddr_t addr; int n, background, channel, service, s, amaster, aslave, fd, doserver, dopty; fd_set rfd; char *tty = NULL, *ep = NULL, buf[SPPD_BUFFER_SIZE]; memcpy(&addr, NG_HCI_BDADDR_ANY, sizeof(addr)); background = channel = 0; service = SDP_SERVICE_CLASS_SERIAL_PORT; doserver = 0; dopty = 0; /* Parse command line options */ while ((n = getopt(argc, argv, "a:bc:thS")) != -1) { switch (n) { case 'a': /* BDADDR */ if (!bt_aton(optarg, &addr)) { struct hostent *he = NULL; if ((he = bt_gethostbyname(optarg)) == NULL) errx(1, "%s: %s", optarg, hstrerror(h_errno)); memcpy(&addr, he->h_addr, sizeof(addr)); } break; case 'c': /* RFCOMM channel */ channel = strtoul(optarg, &ep, 10); if (*ep != '\0') { channel = 0; switch (tolower(optarg[0])) { case 'd': /* DialUp Networking */ service = SDP_SERVICE_CLASS_DIALUP_NETWORKING; break; case 'f': /* Fax */ service = SDP_SERVICE_CLASS_FAX; break; case 'l': /* LAN */ service = SDP_SERVICE_CLASS_LAN_ACCESS_USING_PPP; break; case 's': /* Serial Port */ service = SDP_SERVICE_CLASS_SERIAL_PORT; break; default: errx(1, "Unknown service name: %s", optarg); /* NOT REACHED */ } } break; case 'b': /* Run in background */ background = 1; break; case 't': /* Open pseudo TTY */ dopty = 1; break; case 'S': doserver = 1; break; case 'h': default: usage(); /* NOT REACHED */ } } /* Check if we have everything we need */ if (!doserver && memcmp(&addr, NG_HCI_BDADDR_ANY, sizeof(addr)) == 0) usage(); /* NOT REACHED */ /* Set signal handlers */ memset(&sa, 0, sizeof(sa)); sa.sa_handler = sppd_sighandler; if (sigaction(SIGTERM, &sa, NULL) < 0) err(1, "Could not sigaction(SIGTERM)"); if (sigaction(SIGHUP, &sa, NULL) < 0) err(1, "Could not sigaction(SIGHUP)"); if (sigaction(SIGINT, &sa, NULL) < 0) err(1, "Could not sigaction(SIGINT)"); sa.sa_handler = SIG_IGN; sa.sa_flags = SA_NOCLDWAIT; if (sigaction(SIGCHLD, &sa, NULL) < 0) err(1, "Could not sigaction(SIGCHLD)"); /* Open TTYs */ if (dopty) { if (sppd_ttys_open(&tty, &amaster, &aslave) < 0) exit(1); fd = amaster; } else { if (background) usage(); amaster = STDIN_FILENO; fd = STDOUT_FILENO; } /* Open RFCOMM connection */ if (doserver) { struct sockaddr_rfcomm ma; bdaddr_t bt_addr_any; sdp_sp_profile_t sp; void *ss; uint32_t sdp_handle; int acceptsock, aaddrlen; acceptsock = socket(PF_BLUETOOTH, SOCK_STREAM, BLUETOOTH_PROTO_RFCOMM); if (acceptsock < 0) err(1, "Could not create socket"); memcpy(&bt_addr_any, NG_HCI_BDADDR_ANY, sizeof(bt_addr_any)); memset(&ma, 0, sizeof(ma)); ma.rfcomm_len = sizeof(ma); ma.rfcomm_family = AF_BLUETOOTH; memcpy(&ma.rfcomm_bdaddr, &bt_addr_any, sizeof(bt_addr_any)); ma.rfcomm_channel = channel; if (bind(acceptsock, (struct sockaddr *)&ma, sizeof(ma)) < 0) err(1, "Could not bind socket on channel %d", channel); if (listen(acceptsock, 10) != 0) err(1, "Could not listen on socket"); aaddrlen = sizeof(ma); if (getsockname(acceptsock, (struct sockaddr *)&ma, &aaddrlen) < 0) err(1, "Could not get socket name"); channel = ma.rfcomm_channel; ss = sdp_open_local(NULL); if (ss == NULL) errx(1, "Unable to create local SDP session"); if (sdp_error(ss) != 0) errx(1, "Unable to open local SDP session. %s (%d)", strerror(sdp_error(ss)), sdp_error(ss)); memset(&sp, 0, sizeof(sp)); sp.server_channel = channel; if (sdp_register_service(ss, SDP_SERVICE_CLASS_SERIAL_PORT, &bt_addr_any, (void *)&sp, sizeof(sp), &sdp_handle) != 0) { errx(1, "Unable to register LAN service with " "local SDP daemon. %s (%d)", strerror(sdp_error(ss)), sdp_error(ss)); } s = -1; while (s < 0) { aaddrlen = sizeof(ra); s = accept(acceptsock, (struct sockaddr *)&ra, &aaddrlen); if (s < 0) err(1, "Unable to accept()"); if (memcmp(&addr, NG_HCI_BDADDR_ANY, sizeof(addr)) && memcmp(&addr, &ra.rfcomm_bdaddr, sizeof(addr))) { warnx("Connect from wrong client"); close(s); s = -1; } } sdp_unregister_service(ss, sdp_handle); sdp_close(ss); close(acceptsock); } else { /* Check channel, if was not set then obtain it via SDP */ if (channel == 0 && service != 0) if (rfcomm_channel_lookup(NULL, &addr, service, &channel, &n) != 0) errc(1, n, "Could not obtain RFCOMM channel"); if (channel <= 0 || channel > 30) errx(1, "Invalid RFCOMM channel number %d", channel); s = socket(PF_BLUETOOTH, SOCK_STREAM, BLUETOOTH_PROTO_RFCOMM); if (s < 0) err(1, "Could not create socket"); memset(&ra, 0, sizeof(ra)); ra.rfcomm_len = sizeof(ra); ra.rfcomm_family = AF_BLUETOOTH; if (bind(s, (struct sockaddr *) &ra, sizeof(ra)) < 0) err(1, "Could not bind socket"); memcpy(&ra.rfcomm_bdaddr, &addr, sizeof(ra.rfcomm_bdaddr)); ra.rfcomm_channel = channel; if (connect(s, (struct sockaddr *) &ra, sizeof(ra)) < 0) err(1, "Could not connect socket"); } /* Became daemon if required */ if (background && daemon(0, 0) < 0) err(1, "Could not daemon()"); openlog(SPPD_IDENT, LOG_NDELAY|LOG_PERROR|LOG_PID, LOG_DAEMON); syslog(LOG_INFO, "Starting on %s...", (tty != NULL)? tty : "stdin/stdout"); /* Print used tty on stdout for wrappers to pick up */ if (!background) fprintf(stdout, "%s\n", tty); for (done = 0; !done; ) { FD_ZERO(&rfd); FD_SET(amaster, &rfd); FD_SET(s, &rfd); n = select(max(amaster, s) + 1, &rfd, NULL, NULL, NULL); if (n < 0) { if (errno == EINTR) continue; syslog(LOG_ERR, "Could not select(). %s", strerror(errno)); exit(1); } if (n == 0) continue; if (FD_ISSET(amaster, &rfd)) { n = sppd_read(amaster, buf, sizeof(buf)); if (n < 0) { syslog(LOG_ERR, "Could not read master pty, " \ "fd=%d. %s", amaster, strerror(errno)); exit(1); } if (n == 0) break; /* XXX */ if (sppd_write(s, buf, n) < 0) { syslog(LOG_ERR, "Could not write to socket, " \ "fd=%d, size=%d. %s", s, n, strerror(errno)); exit(1); } } if (FD_ISSET(s, &rfd)) { n = sppd_read(s, buf, sizeof(buf)); if (n < 0) { syslog(LOG_ERR, "Could not read socket, " \ "fd=%d. %s", s, strerror(errno)); exit(1); } if (n == 0) break; if (sppd_write(fd, buf, n) < 0) { syslog(LOG_ERR, "Could not write to master " \ "pty, fd=%d, size=%d. %s", fd, n, strerror(errno)); exit(1); } } } syslog(LOG_INFO, "Completed on %s", (tty != NULL)? tty : "stdin/stdout"); closelog(); close(s); if (tty != NULL) { close(aslave); close(amaster); } return (0); }