/** * @brief Main function of whole server. * * @return EXIT_SUCCESS - when forked properly * @return EXIT_FAILURE - on error during server initialization * @return 0 - on application exit */ int main(void) { pid_t pid, sid; int fd; int ret = 0; struct sigaction sa; char buff[16] = {0}; sa.sa_handler = server_sig_handler; sigemptyset(&sa.sa_mask); sigaction(SIGTERM, &sa, NULL); openlog("ScopeServer", LOG_PID | LOG_LOCAL0, LOG_LOCAL0); pid = fork(); if(pid < 0) { syslog(LOG_ERR, "Fork failed, daemon couldn't start! (errno = %d)\n", -errno); return EXIT_FAILURE; } else if(pid > 0){ return EXIT_SUCCESS; } openlog("ScopeServer", LOG_PID | LOG_LOCAL0, LOG_LOCAL0); umask(0); syslog(LOG_INFO, "[ScopeServer]: Daemon started!\n"); sid = setsid(); if(sid < 0) { syslog(LOG_ERR, "Setsid failed, couldn't create new sid! (errno = %d)\n", -errno); return EXIT_FAILURE; } sprintf(buff, "%ld", (long)getpid()); fd = open(SCOPE_FILE_PID, O_CREAT | O_WRONLY); if(fd <0) { syslog(LOG_ERR, "Couldn't create pid file! (errno = %d)\n", -errno); ret = EXIT_FAILURE; goto init_fail; } if(write(fd, buff, strlen(buff)+1) < 0) { syslog(LOG_ERR, "Couldn't save pid file for ScopeServer! (errno = %d)\n", -errno); close(fd); ret = EXIT_FAILURE; goto init_fail; } close(fd); if(mkfifo(SCOPE_FILE_FIFO, O_RDWR) < 0) { syslog(LOG_ERR, "Couldn't create fifo file: %s! (errno = %d)\n", SCOPE_FILE_FIFO, -errno); ret = EXIT_FAILURE; goto init_fail; } if(chdir("/") < 0) { syslog(LOG_ERR, "Chdir failed! (errno = %d)\n", -errno); ret = EXIT_FAILURE; goto init_fail; } close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); if(server_init() < 0) { syslog(LOG_ERR, "Unable to initizalize the server! (errno = %d)\n", -errno); ret = EXIT_FAILURE; goto init_fail; } server_start(); init_fail: unlink(SCOPE_FILE_FIFO); unlink(SCOPE_FILE_PID); closelog(); return ret; }
void log_Open(const char *Name) { openlog(Name, LOG_PID, LOG_DAEMON); }
void log_init() { return openlog("yasnd", LOG_PID|LOG_CONS, LOG_USER); }
void startsyslog() { openlog(PROGNAME, LOG_PID, LOG_AUTHPRIV); }
/* * main() - loop forever, reading the hdaps values and * parking/unparking as necessary */ int main (int argc, char** argv) { struct utsname sysinfo; struct list *p = NULL; int c, park_now, protect_factor; int x = 0, y = 0, z = 0; int fd, i, ret, threshold = 15, adaptive = 0, pidfile = 0, parked = 0, forceadd = 0; double unow = 0, parked_utime = 0; struct option longopts[] = { {"device", required_argument, NULL, 'd'}, {"sensitivity", required_argument, NULL, 's'}, {"adaptive", no_argument, NULL, 'a'}, {"verbose", no_argument, NULL, 'v'}, {"background", no_argument, NULL, 'b'}, {"pidfile", optional_argument, NULL, 'p'}, {"dry-run", no_argument, NULL, 't'}, {"poll-sysfs", no_argument, NULL, 'y'}, {"hardware-logic", no_argument, NULL, 'H'}, {"software-logic", no_argument, NULL, 'S'}, {"version", no_argument, NULL, 'V'}, {"help", no_argument, NULL, 'h'}, {"no-leds", no_argument, NULL, 'L'}, {"syslog", no_argument, NULL, 'l'}, {"force", no_argument, NULL, 'f'}, {"force-rotational", no_argument, NULL, 'r'}, {NULL, 0, NULL, 0} }; if (uname(&sysinfo) < 0 || strcmp("2.6.27", sysinfo.release) <= 0) { protect_factor = 1000; kernel_interface = UNLOAD_HEADS; } else { protect_factor = 1; kernel_interface = PROTECT; } openlog(PACKAGE_NAME, LOG_PID, LOG_DAEMON); while ((c = getopt_long(argc, argv, "d:s:vbap::tyHSVhLlfr", longopts, NULL)) != -1) { switch (c) { case 'd': add_disk(optarg); break; case 's': threshold = atoi(optarg); break; case 'b': background = 1; break; case 'a': adaptive = 1; break; case 'v': verbose = 1; break; case 'p': pidfile = 1; if (optarg == NULL) { snprintf(pid_file, sizeof(pid_file), "%s", PID_FILE); } else { snprintf(pid_file, sizeof(pid_file), "%s", optarg); } break; case 't': printlog(stdout, "Dry run, will not actually park heads or freeze queue."); dry_run = 1; break; case 'y': poll_sysfs = 1; break; case 'H': hardware_logic = 1; position_interface = INTERFACE_FREEFALL; break; case 'S': force_software_logic = 1; break; case 'V': version(); break; case 'l': dosyslog = 1; break; case 'L': use_leds = 0; break; case 'f': forceadd = 1; break; case 'r': forcerotational = 1; break; case 'h': default: usage(); break; } } printlog(stdout, "Starting "PACKAGE_NAME); if (disklist && forceadd) { char protect_method[FILENAME_MAX] = ""; p = disklist; while (p != NULL) { snprintf(protect_method, sizeof(protect_method), QUEUE_METHOD_FMT, p->name); if (kernel_interface == UNLOAD_HEADS) fd = open (p->protect_file, O_RDWR); else fd = open (protect_method, O_RDWR); if (fd > 0) { if (kernel_interface == UNLOAD_HEADS) ret = write(fd, FORCE_UNLOAD_HEADS, strlen(FORCE_UNLOAD_HEADS)); else ret = write(fd, FORCE_PROTECT_METHOD, strlen(FORCE_PROTECT_METHOD)); if (ret == -1) printlog(stderr, "Could not forcely enable UNLOAD feature for %s", p->name); else printlog(stdout, "Forcely enabled UNLOAD for %s", p->name); close(fd); } else printlog(stderr, "Could not open %s for forcely enabling UNLOAD feature", p->protect_file); p = p->next; } } if (disklist == NULL) { printlog(stdout, "WARNING: You did not supply any devices to protect, trying autodetection."); if (autodetect_devices() < 1) printlog(stderr, "Could not detect any devices."); } if (disklist == NULL) usage(argv); /* Let's see if we're on a ThinkPad or on an *Book */ if (!position_interface) select_interface(0); if (!position_interface) select_interface(1); if (!position_interface && !hardware_logic) { printlog(stdout, "Could not find a suitable interface"); return -1; } else printlog(stdout, "Selected interface: %s", interface_names[position_interface]); if (hardware_logic) { /* Open the file representing the hardware decision */ freefall_fd = open (FREEFALL_FILE, FREEFALL_FD_FLAGS); if (freefall_fd < 0) { printlog(stdout, "ERROR: Failed openning the hardware logic file (%s). " "It is probably not supported on your system.", strerror(errno)); return errno; } else { printlog (stdout, "Uses hardware logic from " FREEFALL_FILE); } } if (!poll_sysfs && !hardware_logic) { if (position_interface == INTERFACE_HDAPS) { hdaps_input_nr = device_find_byphys("hdaps/input1"); hdaps_input_fd = device_open(hdaps_input_nr); if (hdaps_input_fd < 0) { printlog(stdout, "WARNING: Could not find hdaps input device (%s). " "You may be using an incompatible version of the hdaps module. " "Falling back to reading the position from sysfs (uses more power).\n" "Use '-y' to silence this warning.", strerror(errno)); poll_sysfs = 1; } else { printlog(stdout, "Selected HDAPS input device: /dev/input/event%d", hdaps_input_nr); } } else if (position_interface == INTERFACE_AMS) { hdaps_input_nr = device_find_byname("Apple Motion Sensor"); hdaps_input_fd = device_open(hdaps_input_nr); if (hdaps_input_fd < 0) { printlog(stdout, "WARNING: Could not find AMS input device, do you need to set joystick=1?"); poll_sysfs = 1; } else { printlog(stdout, "Selected AMS input device /dev/input/event%d", hdaps_input_nr); } } else if (position_interface == INTERFACE_HP3D) { hdaps_input_nr = device_find_byname("ST LIS3LV02DL Accelerometer"); hdaps_input_fd = device_open(hdaps_input_nr); if (hdaps_input_fd < 0) { printlog(stdout, "WARNING: Could not find HP3D input device"); poll_sysfs = 1; } else { printlog(stdout, "Selected HP3D input device /dev/input/event%d", hdaps_input_nr); } } else if (position_interface == INTERFACE_APPLESMC) { hdaps_input_nr = device_find_byname("applesmc"); hdaps_input_fd = device_open(hdaps_input_nr); if (hdaps_input_fd < 0) { printlog(stdout, "WARNING: Could not find APPLESMC input device"); poll_sysfs = 1; } else { printlog(stdout, "Selected APPLESMC input device /dev/input/event%d", hdaps_input_nr); } } } if (position_interface != INTERFACE_HP3D && position_interface != INTERFACE_FREEFALL) { /* LEDs are not supported yet on other systems */ use_leds = 0; } if (use_leds) { fd = open(HP3D_LED_FILE, O_WRONLY); if (fd < 0) use_leds = 0; else close(fd); } if (background) { verbose = 0; if (pidfile) { fd = open (pid_file, O_WRONLY | O_CREAT, 0644); if (fd < 0) { printlog (stderr, "Could not create pidfile: %s", pid_file); return 1; } } daemon(0,0); if (pidfile) { char buf[BUF_LEN]; snprintf (buf, sizeof(buf), "%d\n", getpid()); ret = write (fd, buf, strlen(buf)); if (ret < 0) { printlog (stderr, "Could not write to pidfile %s", pid_file); return 1; } if (close (fd)) { printlog (stderr, "Could not close pidfile %s", pid_file); return 1; } } } mlockall(MCL_FUTURE); if (verbose) { p = disklist; while (p != NULL) { printf("disk: %s\n", p->name); p = p->next; } printf("threshold: %i\n", threshold); printf("read_method: %s\n", poll_sysfs ? "poll-sysfs" : (hardware_logic ? "hardware-logic" : "input-dev")); } /* check the protect attribute exists */ /* wait for it if it's not there (in case the attribute hasn't been created yet) */ p = disklist; while (p != NULL && !dry_run) { fd = open (p->protect_file, O_RDWR); if (background) for (i = 0; fd < 0 && i < 100; ++i) { usleep (100000); /* 10 Hz */ fd = open (p->protect_file, O_RDWR); } if (fd < 0) { printlog (stderr, "Could not open %s\nDoes your kernel/drive support IDLE_IMMEDIATE with UNLOAD?", p->protect_file); free_disk(disklist); return 1; } close (fd); p = p->next; } /* see if we can read the sensor */ /* wait for it if it's not there (in case the attribute hasn't been created yet) */ if (!hardware_logic) { ret = read_position_from_sysfs (&x, &y, &z); if (background) for (i = 0; ret && i < 100; ++i) { usleep (100000); /* 10 Hz */ ret = read_position_from_sysfs (&x, &y, &z); } if (ret) { printlog(stderr, "Could not read position from sysfs."); return 1; } } /* adapt to the driver's sampling rate */ if (position_interface == INTERFACE_HDAPS) sampling_rate = read_int(HDAPS_SAMPLING_RATE_FILE); else if (position_interface == INTERFACE_HP3D) sampling_rate = read_int(HP3D_SAMPLING_RATE_FILE); if (sampling_rate <= 0) sampling_rate = DEFAULT_SAMPLING_RATE; if (verbose) printf("sampling_rate: %d\n", sampling_rate); signal(SIGUSR1, SIGUSR1_handler); signal(SIGTERM, SIGTERM_handler); while (running) { if (!hardware_logic) { /* The decision is made by the software */ /* Get statistics and decide what to do */ if (poll_sysfs) { usleep (1000000/sampling_rate); ret = read_position_from_sysfs (&x, &y, &z); unow = get_utime(); /* microsec */ } else { double oldunow = unow; int oldx = x, oldy = y, oldz = z; ret = read_position_from_inputdev (&x, &y, &z, &unow); /* * The input device issues events only when the position changed. * The analysis state needs to know how long the position remained * unchanged, so send analyze() a fake retroactive update before sending * the new one. */ if (!ret && oldunow && unow-oldunow > 1.5/sampling_rate) analyze(oldx, oldy, unow-1.0/sampling_rate, threshold, adaptive, parked); } if (ret) { if (verbose) printf("readout error (%d)\n", ret); continue; } park_now = analyze(x, y, unow, threshold, adaptive, parked); } else /* if (hardware_logic) */ { unsigned char count; /* Number of fall events */ if (!parked) { /* Wait for the hardware to notify a fall */ ret = read(freefall_fd, &count, sizeof(count)); } else { /* * Poll to check if we no longer are falling * (hardware_logic polls only when parked) */ usleep (1000000/sampling_rate); fcntl (freefall_fd, F_SETFL, FREEFALL_FD_FLAGS|O_NONBLOCK); ret = read(freefall_fd, &count, sizeof(count)); fcntl (freefall_fd, F_SETFL, FREEFALL_FD_FLAGS); /* * If the error is EAGAIN then it is not a real error but * a sign that the fall has ended */ if (ret != sizeof(count) && errno == EAGAIN) { count = 0; /* set fall events count to 0 */ ret = sizeof(count); /* Validate count */ } } /* handle read errors */ if (ret != sizeof(count)) { if (verbose) printf("readout error (%d)\n", ret); continue; } /* Display the read values in verbose mode */ if (verbose) printf ("HW=%u\n", (unsigned) count); unow = get_utime(); /* microsec */ park_now = (count > 0); } if (park_now && !pause_now) { if (!parked || unow>parked_utime+REFREEZE_SECONDS) { /* Not frozen or freeze about to expire */ p = disklist; while (p != NULL) { write_protect(p->protect_file, (FREEZE_SECONDS+FREEZE_EXTRA_SECONDS) * protect_factor); p = p->next; } /* * Write protect before any output (xterm, or * whatever else is handling our stdout, may be * swapped out). */ if (!parked) { printlog(stdout, "parking"); if (use_leds) write_int (HP3D_LED_FILE, 1); } parked = 1; parked_utime = unow; } } else { if (parked && (pause_now || unow>parked_utime+FREEZE_SECONDS)) { /* Sanity check */ p = disklist; while (p != NULL) { if (!dry_run && !read_int(p->protect_file)) printlog(stderr, "Error! Not parked when we " "thought we were... (paged out " "and timer expired?)"); /* Freeze has expired */ write_protect(p->protect_file, 0); /* unprotect */ if (use_leds) write_int (HP3D_LED_FILE, 0); p = p->next; } parked = 0; printlog(stdout, "un-parking"); } while (pause_now) { pause_now = 0; printlog(stdout, "pausing for %d seconds", SIGUSR1_SLEEP_SEC); sleep(SIGUSR1_SLEEP_SEC); } } } free_disk(disklist); printlog(stdout, "Terminating "PACKAGE_NAME); closelog(); if (pidfile) unlink(pid_file); munlockall(); return ret; }
int app_proxy( int argc, char const * const * argv, const char * copyright_notice , CryptoContext & cctx , ExtraOptions const & extrax_options, ExtracOptionChecker extrac_options_checker , PreLoopFn pre_loop_fn = PreLoopFn() ) { setlocale(LC_CTYPE, "C"); const unsigned uid = getuid(); const unsigned gid = getgid(); unsigned euid = uid; unsigned egid = gid; std::string config_filename = CFG_PATH "/" RDPPROXY_INI; program_options::options_description desc({ {'h', "help", "produce help message"}, {'v', "version", "show software version"}, {'k', "kill", "shut down rdpproxy"}, {'n', "nodaemon", "don't fork into background"}, {'u', "uid", &euid, "run with given uid"}, {'g', "gid", &egid, "run with given gid"}, //{'t', "trace", "trace behaviour"}, {'c', "check", "check installation files"}, {'f', "force", "remove application lock file"}, {'i', "inetd", "launch redemption with inetd like launcher"}, {"config-file", &config_filename, "used an another ini file"}, //{"test", "check Inifile syntax"} }); for (extra_option const & extra : extrax_options) { desc.add({extra.option_long, extra.description}); } auto options = program_options::parse_command_line(argc, const_cast<char**>(argv), desc); if (options.count("kill")) { int status = shutdown(PID_PATH "/redemption/" LOCKFILE); if (status){ // TODO check the real error that occured std::clog << "problem opening " << PID_PATH "/redemption/" LOCKFILE << "." " Maybe rdpproxy is not running\n"; } return status; } if (options.count("help")) { std::cout << copyright_notice << "\n\n"; std::cout << "Usage: rdpproxy [options]\n\n"; std::cout << desc << std::endl; return 0; } if (options.count("version")) { std::cout << copyright_notice << std::endl; return 0; } { bool quit = false; if (int status = extrac_options_checker(options, &quit)) { return status; } else if (quit) { return 0; } } openlog("rdpproxy", LOG_CONS | LOG_PERROR, LOG_USER); if (options.count("check")) { bool user_check_file_result = ((uid != euid) || (gid != egid)) ? CheckFile::check(user_check_file_list) : true; /* setgid(egid); setuid(euid); */ bool euser_check_file_result = CheckFile::check(euser_check_file_list); /* setgid(gid); setuid(uid); */ if ((uid != euid) || (gid != egid)) { CheckFile::ShowAll(user_check_file_list, uid, gid); } CheckFile::ShowAll(euser_check_file_list, euid, egid); if (!user_check_file_result || !euser_check_file_result) { if ((uid != euid) || (gid != egid)) { CheckFile::ShowErrors(user_check_file_list, uid, gid); } CheckFile::ShowErrors(euser_check_file_list, euid, egid); LOG(LOG_INFO, "%s", "Please verify that all tests passed. If not, " "you may need to remove " PID_PATH "/redemption/" LOCKFILE " or reinstall rdpproxy if some configuration " "files are missing."); } return 0; } if (options.count("inetd")) { redemption_new_session(cctx, config_filename.c_str()); return 0; } // if -f (force option) is set // force kill running rdpproxy // force remove pid file // don't check if it fails (proxy may be allready stopped) // and try to continue normal start process afterward if (mkdir(PID_PATH "/redemption", 0700) < 0){ // TODO check only for relevant errors (exists with expected permissions is OK) } if (chown(PID_PATH "/redemption", euid, egid) < 0){ LOG(LOG_INFO, "Failed to set owner %u.%u to " PID_PATH "/redemption", euid, egid); return 1; } if (options.count("force")){ shutdown(PID_PATH "/redemption/" LOCKFILE); } if (0 == access(PID_PATH "/redemption/" LOCKFILE, F_OK)) { std::clog << "File " << PID_PATH "/redemption/" LOCKFILE << " already exists. " "It looks like rdpproxy is already running, " "if not, try again with -f (force) option or delete the " PID_PATH "/redemption/" LOCKFILE " file and try again\n"; return 1; } /* write the pid to file */ int fd = open(PID_PATH "/redemption/" LOCKFILE, O_WRONLY | O_CREAT, S_IRWXU); if (fd == -1) { std::clog << "Writing process id to " PID_PATH "/redemption/" LOCKFILE " failed. Maybe no rights ?" << " : " << errno << ":'" << strerror(errno) << "'\n"; return 1; } { io::posix::fdbuf file(fd); const int pid = getpid(); char text[256]; size_t lg = snprintf(text, 255, "%d", pid); if (file.write(text, lg) == -1) { LOG(LOG_ERR, "Couldn't write pid to %s: %s", PID_PATH "/redemption/" LOCKFILE, strerror(errno)); return 1; } } if (!options.count("nodaemon")) { daemonize(PID_PATH "/redemption/" LOCKFILE); } Inifile ini; { ConfigurationLoader cfg_loader(ini.configuration_holder(), config_filename.c_str()); } OpenSSL_add_all_digests(); if (!ini.get<cfg::globals::enable_ip_transparent>()) { if (setgid(egid) != 0){ LOG(LOG_ERR, "Changing process group to %u failed with error: %s\n", egid, strerror(errno)); return 1; } if (setuid(euid) != 0){ LOG(LOG_ERR, "Changing process user to %u failed with error: %s\n", euid, strerror(errno)); return 1; } } pre_loop_fn(ini); LOG(LOG_INFO, "ReDemPtion " VERSION " starting"); redemption_main_loop(ini, cctx, euid, egid, std::move(config_filename)); /* delete the .pid file if it exists */ /* don't care about errors. */ /* If we are not in daemon mode this file will not exists, */ /* hence some errors are expected */ unlink(PID_PATH "/redemption/" LOCKFILE); return 0; }
int main (int argc, char *argv[]) { Daemon *daemon; DBusGConnection *bus; DBusGProxy *system_bus_proxy; GError *error; gint ret; GOptionContext *context; static gboolean replace; static gboolean show_version; static GOptionEntry entries[] = { { "version", 0, 0, G_OPTION_ARG_NONE, &show_version, N_("Output version information and exit"), NULL }, { "replace", 0, 0, G_OPTION_ARG_NONE, &replace, N_("Replace existing instance"), NULL }, { "debug", 0, 0, G_OPTION_ARG_NONE, &debug, N_("Enable debugging code"), NULL }, { NULL } }; ret = 1; error = NULL; setlocale (LC_ALL, ""); bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8"); g_type_init (); if (!g_setenv ("GIO_USE_VFS", "local", TRUE)) { g_warning ("Couldn't set GIO_USE_GVFS"); goto out; } context = g_option_context_new (""); g_option_context_set_translation_domain (context, GETTEXT_PACKAGE); g_option_context_set_summary (context, _("Provides D-Bus interfaces for querying and manipulating\nuser account information.")); g_option_context_add_main_entries (context, entries, NULL); error = NULL; if (!g_option_context_parse (context, &argc, &argv, &error)) { g_warning ("%s", error->message); g_error_free (error); goto out; } g_option_context_free (context); if (show_version) { g_print ("mateaccounts-daemon " VERSION "\n"); ret = 0; goto out; } g_log_set_default_handler (log_handler, NULL); bus = dbus_g_bus_get (DBUS_BUS_SYSTEM, &error); if (bus == NULL) { g_warning ("Could not connect to system bus: %s", error->message); g_error_free (error); goto out; } system_bus_proxy = dbus_g_proxy_new_for_name (bus, DBUS_SERVICE_DBUS, DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS); if (system_bus_proxy == NULL) { g_warning ("Could not construct system_bus_proxy object"); goto out; } if (!acquire_name_on_proxy (system_bus_proxy, replace)) { g_warning ("Could not acquire name"); goto out; } daemon = daemon_new (); if (daemon == NULL) goto out; openlog ("mateaccounts-daemon", LOG_PID, LOG_DAEMON); syslog (LOG_INFO, "started daemon version %s", VERSION); closelog (); openlog ("mateaccounts-daemon", 0, LOG_AUTHPRIV); loop = g_main_loop_new (NULL, FALSE); g_debug ("entering main loop\n"); g_main_loop_run (loop); g_main_loop_unref (loop); ret = 0; out: return ret; }
/* Open the error log for the given server_rec. If IS_MAIN is * non-zero, s is the main server. */ static int open_error_log(server_rec *s, int is_main, apr_pool_t *p) { const char *fname; int rc; if (*s->error_fname == '|') { apr_file_t *dummy = NULL; /* Spawn a new child logger. If this is the main server_rec, * the new child must use a dummy stderr since the current * stderr might be a pipe to the old logger. Otherwise, the * child inherits the parents stderr. */ rc = log_child(p, s->error_fname + 1, &dummy, is_main); if (rc != APR_SUCCESS) { ap_log_error(APLOG_MARK, APLOG_STARTUP, rc, NULL, "Couldn't start ErrorLog process"); return DONE; } s->error_log = dummy; } #ifdef HAVE_SYSLOG else if (!strncasecmp(s->error_fname, "syslog", 6)) { if ((fname = strchr(s->error_fname, ':'))) { const TRANS *fac; fname++; for (fac = facilities; fac->t_name; fac++) { if (!strcasecmp(fname, fac->t_name)) { openlog(ap_server_argv0, LOG_NDELAY|LOG_CONS|LOG_PID, fac->t_val); s->error_log = NULL; return OK; } } } else { openlog(ap_server_argv0, LOG_NDELAY|LOG_CONS|LOG_PID, LOG_LOCAL7); } s->error_log = NULL; } #endif else { fname = ap_server_root_relative(p, s->error_fname); if (!fname) { ap_log_error(APLOG_MARK, APLOG_STARTUP, APR_EBADPATH, NULL, "%s: Invalid error log path %s.", ap_server_argv0, s->error_fname); return DONE; } if ((rc = apr_file_open(&s->error_log, fname, APR_APPEND | APR_WRITE | APR_CREATE | APR_LARGEFILE, APR_OS_DEFAULT, p)) != APR_SUCCESS) { ap_log_error(APLOG_MARK, APLOG_STARTUP, rc, NULL, "%s: could not open error log file %s.", ap_server_argv0, fname); return DONE; } } return OK; }
int main(int argc, char **argv) { struct stat statbuf; uid_t uid = getuid(); uid_t gid = getgid(); uid_t euid = geteuid(); uid_t egid = getegid(); struct passwd *pwd = getpwuid(uid); struct group *grp = getgrgid(gid); if (argc < 3) usage(argv[0]); options_init(); openlog(PACKAGE, LOG_PID, LOG_DAEMON); memset(&statbuf, 0, sizeof(statbuf)); if (!options_binload(argv[1])) { log_err(0, "invalid binary config file %s", argv[1]); usage(argv[0]); } if (uid != 0) { if (strcmp(pwd->pw_name, CHILLI_USER)) { log_err(0, "has to run as user %s or root", CHILLI_USER); usage(argv[0]); } if (strcmp(grp->gr_name, CHILLI_GROUP)) { log_err(0, "has to run as group %s or root", CHILLI_GROUP); usage(argv[0]); } } log_dbg("USER %s(%d/%d), GROUP %s(%d/%d) CHILLI[UID %d, GID %d]", pwd->pw_name, uid, euid, grp->gr_name, gid, egid, _options.uid, _options.gid); if (stat(argv[2], &statbuf)) { log_err(errno, "%s does not exist", argv[2]); usage(argv[0]); } if (_options.uid && /* chilli is running as non-root */ _options.uid == euid && /* current euid same as chilli uid */ _options.gid == egid && /* current egid same as chilli gid */ statbuf.st_uid == 0 && /* script owned by root */ statbuf.st_gid == _options.gid && /* script group same as chilli gid */ (statbuf.st_mode & 0400) == 0400) { if (setuid(0)) log_err(errno, "setuid %s", argv[0]); } log_info("Running %s (%d/%d)", argv[2], getuid(), geteuid()); if (execv(argv[2], &argv[2])) { log_err(errno, "exec %s", argv[2]); usage(argv[0]); } return 0; }
void log_ext( int errnum, /* I (errno or PBSErrno) */ const char *routine, /* I */ const char *text, /* I */ int severity) /* I */ { char buf[LOG_BUF_SIZE]; char *EPtr = NULL; char EBuf[1024]; char tmpLine[2048]; const char *SeverityText = NULL; tmpLine[0] = '\0'; EBuf[0] = '\0'; if (errnum == -1) { buf[0] = '\0'; } else { /* NOTE: some strerror() routines return "Unknown error X" w/bad errno */ if (errnum >= 15000) { EPtr = pbse_to_txt(errnum); } else { EPtr = strerror(errnum); } if (EPtr == NULL) { sprintf(EBuf, "unexpected error %d", errnum); EPtr = EBuf; } sprintf(tmpLine,"%s (%d) in ", EPtr, errnum); } SeverityText = log_get_severity_string(severity); snprintf(buf,sizeof(buf),"%s::%s%s, %s", SeverityText, tmpLine, routine, text); buf[LOG_BUF_SIZE - 1] = '\0'; if (!log_mutex) { if (isatty(2)) { fprintf(stderr, "%s: %s\n", msg_daemonname, buf); } #if SYSLOG if (syslogopen == 0) { openlog(msg_daemonname, LOG_NOWAIT, LOG_DAEMON); syslogopen = 1; } syslog(severity|LOG_DAEMON,"%s",buf); #endif /* SYSLOG */ return; } pthread_mutex_lock(log_mutex); if (log_opened == 0) { #if !SYSLOG log_open("/dev/console", log_directory); #endif /* not SYSLOG */ } if (isatty(2)) { fprintf(stderr, "%s: %s\n", msg_daemonname, buf); } if (log_opened > 0) { pthread_mutex_unlock(log_mutex); log_record( PBSEVENT_ERROR | PBSEVENT_FORCE, PBS_EVENTCLASS_SERVER, msg_daemonname, buf); } else pthread_mutex_unlock(log_mutex); #if SYSLOG if (syslogopen == 0) { openlog(msg_daemonname, LOG_NOWAIT, LOG_DAEMON); syslogopen = 1; } syslog(severity|LOG_DAEMON,"%s",buf); #endif /* SYSLOG */ return; } /* END log_ext() */
int nameif_main(int argc, char **argv) { ethtable_t *clist = NULL; FILE *ifh; const char *fname = "/etc/mactab"; char *line; char *line_ptr; int linenum; int ctl_sk; ethtable_t *ch; if (1 & getopt32(argv, "sc:", &fname)) { openlog(applet_name, 0, LOG_LOCAL0); logmode = LOGMODE_SYSLOG; } argc -= optind; argv += optind; if (argc & 1) bb_show_usage(); if (argc) { while (*argv) { char *ifname = xstrdup(*argv++); prepend_new_eth_table(&clist, ifname, *argv++); } } else { ifh = xfopen(fname, "r"); while ((line = xmalloc_fgets(ifh)) != NULL) { char *next; line_ptr = skip_whitespace(line); if ((line_ptr[0] == '#') || (line_ptr[0] == '\n')) goto read_next_line; next = skip_non_whitespace(line_ptr); if (*next) *next++ = '\0'; prepend_new_eth_table(&clist, line_ptr, next); read_next_line: free(line); } fclose(ifh); } ctl_sk = xsocket(PF_INET, SOCK_DGRAM, 0); ifh = xfopen("/proc/net/dev", "r"); linenum = 0; while (clist) { struct ifreq ifr; #if ENABLE_FEATURE_NAMEIF_EXTENDED struct ethtool_drvinfo drvinfo; #endif line = xmalloc_fgets(ifh); if (line == NULL) break; /* Seems like we're done */ if (linenum++ < 2 ) goto next_line; /* Skip the first two lines */ /* Find the current interface name and copy it to ifr.ifr_name */ line_ptr = skip_whitespace(line); *strpbrk(line_ptr, " \t\n:") = '\0'; memset(&ifr, 0, sizeof(struct ifreq)); strncpy(ifr.ifr_name, line_ptr, sizeof(ifr.ifr_name)); #if ENABLE_FEATURE_NAMEIF_EXTENDED /* Check for driver etc. */ memset(&drvinfo, 0, sizeof(struct ethtool_drvinfo)); drvinfo.cmd = ETHTOOL_GDRVINFO; ifr.ifr_data = (caddr_t) &drvinfo; /* Get driver and businfo first, so we have it in drvinfo */ ioctl(ctl_sk, SIOCETHTOOL, &ifr); #endif ioctl(ctl_sk, SIOCGIFHWADDR, &ifr); /* Search the list for a matching device */ for (ch = clist; ch; ch = ch->next) { #if ENABLE_FEATURE_NAMEIF_EXTENDED if (ch->bus_info && strcmp(ch->bus_info, drvinfo.bus_info) != 0) continue; if (ch->driver && strcmp(ch->driver, drvinfo.driver) != 0) continue; #endif if (ch->mac && memcmp(ch->mac, ifr.ifr_hwaddr.sa_data, ETH_ALEN) != 0) continue; /* if we came here, all selectors have matched */ goto found; } /* Nothing found for current interface */ goto next_line; found: if (strcmp(ifr.ifr_name, ch->ifname) != 0) { strcpy(ifr.ifr_newname, ch->ifname); ioctl_or_perror_and_die(ctl_sk, SIOCSIFNAME, &ifr, "cannot change ifname %s to %s", ifr.ifr_name, ch->ifname); } /* Remove list entry of renamed interface */ if (ch->prev != NULL) ch->prev->next = ch->next; else clist = ch->next; if (ch->next != NULL) ch->next->prev = ch->prev; if (ENABLE_FEATURE_CLEAN_UP) delete_eth_table(ch); next_line: free(line); } if (ENABLE_FEATURE_CLEAN_UP) { for (ch = clist; ch; ch = ch->next) delete_eth_table(ch); fclose(ifh); }; return 0; }
int main(_unused int argc, char* const argv[]) { // Allocate ressources const char *pidfile = NULL; const char *script = "/usr/sbin/odhcp6c-update"; ssize_t l; uint8_t buf[134]; char *optpos; uint16_t opttype; uint16_t optlen; enum odhcp6c_ia_mode ia_na_mode = IA_MODE_TRY; enum odhcp6c_ia_mode ia_pd_mode = IA_MODE_NONE; int ia_pd_iaid_index = 0; static struct in6_addr ifid = IN6ADDR_ANY_INIT; int sol_timeout = DHCPV6_SOL_MAX_RT; int verbosity = 0; bool help = false, daemonize = false; int logopt = LOG_PID; int c; unsigned int client_options = DHCPV6_CLIENT_FQDN | DHCPV6_ACCEPT_RECONFIGURE; while ((c = getopt(argc, argv, "S::N:V:P:FB:c:i:r:Ru:s:kt:m:hedp:fav")) != -1) { switch (c) { case 'S': allow_slaac_only = (optarg) ? atoi(optarg) : -1; break; case 'N': if (!strcmp(optarg, "force")) { ia_na_mode = IA_MODE_FORCE; allow_slaac_only = -1; } else if (!strcmp(optarg, "none")) { ia_na_mode = IA_MODE_NONE; } else if (!strcmp(optarg, "try")) { ia_na_mode = IA_MODE_TRY; } else { help = true; } break; case 'V': l = script_unhexlify(buf, sizeof(buf), optarg); if (!l) help=true; odhcp6c_add_state(STATE_VENDORCLASS, buf, l); break; case 'P': if (ia_pd_mode == IA_MODE_NONE) ia_pd_mode = IA_MODE_TRY; if (allow_slaac_only >= 0 && allow_slaac_only < 10) allow_slaac_only = 10; char *iaid_begin; int iaid_len = 0; int prefix_length = strtoul(optarg, &iaid_begin, 10); if (*iaid_begin != '\0' && *iaid_begin != ',' && *iaid_begin != ':') { syslog(LOG_ERR, "invalid argument: '%s'", optarg); return 1; } struct odhcp6c_request_prefix prefix = { 0, prefix_length }; if (*iaid_begin == ',' && (iaid_len = strlen(iaid_begin)) > 1) memcpy(&prefix.iaid, iaid_begin + 1, iaid_len > 4 ? 4 : iaid_len); else if (*iaid_begin == ':') prefix.iaid = htonl((uint32_t)strtoul(&iaid_begin[1], NULL, 16)); else prefix.iaid = htonl(++ia_pd_iaid_index); odhcp6c_add_state(STATE_IA_PD_INIT, &prefix, sizeof(prefix)); break; case 'F': allow_slaac_only = -1; ia_pd_mode = IA_MODE_FORCE; break; case 'c': l = script_unhexlify(&buf[4], sizeof(buf) - 4, optarg); if (l > 0) { buf[0] = 0; buf[1] = DHCPV6_OPT_CLIENTID; buf[2] = 0; buf[3] = l; odhcp6c_add_state(STATE_CLIENT_ID, buf, l + 4); } else { help = true; } break; case 'i': if (inet_pton(AF_INET6, optarg, &ifid) != 1) help = true; break; case 'r': optpos = optarg; while (optpos[0]) { opttype = htons(strtoul(optarg, &optpos, 10)); if (optpos == optarg) break; else if (optpos[0]) optarg = &optpos[1]; odhcp6c_add_state(STATE_ORO, &opttype, 2); } break; case 'R': client_options |= DHCPV6_STRICT_OPTIONS; break; case 'u': optlen = htons(strlen(optarg)); odhcp6c_add_state(STATE_USERCLASS, &optlen, 2); odhcp6c_add_state(STATE_USERCLASS, optarg, strlen(optarg)); break; case 's': script = optarg; break; case 'k': release = false; break; case 't': sol_timeout = atoi(optarg); break; case 'm': min_update_interval = atoi(optarg); break; case 'e': logopt |= LOG_PERROR; break; case 'd': daemonize = true; break; case 'p': pidfile = optarg; break; case 'f': client_options &= ~DHCPV6_CLIENT_FQDN; break; case 'a': client_options &= ~DHCPV6_ACCEPT_RECONFIGURE; break; case 'v': ++verbosity; break; default: help = true; break; } } if (allow_slaac_only > 0) script_sync_delay = allow_slaac_only; openlog("odhcp6c", logopt, LOG_DAEMON); if (!verbosity) setlogmask(LOG_UPTO(LOG_WARNING)); const char *ifname = argv[optind]; if (help || !ifname) return usage(); signal(SIGIO, sighandler); signal(SIGHUP, sighandler); signal(SIGINT, sighandler); signal(SIGTERM, sighandler); signal(SIGUSR1, sighandler); signal(SIGUSR2, sighandler); if ((urandom_fd = open("/dev/urandom", O_CLOEXEC | O_RDONLY)) < 0 || init_dhcpv6(ifname, client_options, sol_timeout) || ra_init(ifname, &ifid) || script_init(script, ifname)) { syslog(LOG_ERR, "failed to initialize: %s", strerror(errno)); return 3; } if (daemonize) { openlog("odhcp6c", LOG_PID, LOG_DAEMON); // Disable LOG_PERROR if (daemon(0, 0)) { syslog(LOG_ERR, "Failed to daemonize: %s", strerror(errno)); return 4; } if (!pidfile) { snprintf((char*)buf, sizeof(buf), "/var/run/odhcp6c.%s.pid", ifname); pidfile = (char*)buf; } FILE *fp = fopen(pidfile, "w"); if (fp) { fprintf(fp, "%i\n", getpid()); fclose(fp); } } script_call("started", 0, false); while (!signal_term) { // Main logic odhcp6c_clear_state(STATE_SERVER_ID); odhcp6c_clear_state(STATE_SERVER_ADDR); odhcp6c_clear_state(STATE_IA_NA); odhcp6c_clear_state(STATE_IA_PD); odhcp6c_clear_state(STATE_SNTP_IP); odhcp6c_clear_state(STATE_NTP_IP); odhcp6c_clear_state(STATE_NTP_FQDN); odhcp6c_clear_state(STATE_SIP_IP); odhcp6c_clear_state(STATE_SIP_FQDN); bound = false; syslog(LOG_NOTICE, "(re)starting transaction on %s", ifname); signal_usr1 = signal_usr2 = false; int mode = dhcpv6_set_ia_mode(ia_na_mode, ia_pd_mode); if (mode != DHCPV6_STATELESS) mode = dhcpv6_request(DHCPV6_MSG_SOLICIT); odhcp6c_signal_process(); if (mode < 0) continue; do { int res = dhcpv6_request(mode == DHCPV6_STATELESS ? DHCPV6_MSG_INFO_REQ : DHCPV6_MSG_REQUEST); bool signalled = odhcp6c_signal_process(); if (res > 0) break; else if (signalled) { mode = -1; break; } mode = dhcpv6_promote_server_cand(); } while (mode > DHCPV6_UNKNOWN); if (mode < 0) continue; switch (mode) { case DHCPV6_STATELESS: bound = true; syslog(LOG_NOTICE, "entering stateless-mode on %s", ifname); while (!signal_usr2 && !signal_term) { signal_usr1 = false; script_call("informed", script_sync_delay, true); int res = dhcpv6_poll_reconfigure(); odhcp6c_signal_process(); if (res > 0) continue; if (signal_usr1) { signal_usr1 = false; // Acknowledged continue; } if (signal_usr2 || signal_term) break; res = dhcpv6_request(DHCPV6_MSG_INFO_REQ); odhcp6c_signal_process(); if (signal_usr1) continue; else if (res < 0) break; } break; case DHCPV6_STATEFUL: bound = true; script_call("bound", script_sync_delay, true); syslog(LOG_NOTICE, "entering stateful-mode on %s", ifname); while (!signal_usr2 && !signal_term) { // Renew Cycle // Wait for T1 to expire or until we get a reconfigure int res = dhcpv6_poll_reconfigure(); odhcp6c_signal_process(); if (res > 0) { script_call("updated", 0, false); continue; } // Handle signal, if necessary if (signal_usr1) signal_usr1 = false; // Acknowledged if (signal_usr2 || signal_term) break; // Other signal type // Send renew as T1 expired res = dhcpv6_request(DHCPV6_MSG_RENEW); odhcp6c_signal_process(); if (res > 0) { // Renew was succesfull // Publish updates script_call("updated", 0, false); continue; // Renew was successful } odhcp6c_clear_state(STATE_SERVER_ID); // Remove binding odhcp6c_clear_state(STATE_SERVER_ADDR); size_t ia_pd_len, ia_na_len; odhcp6c_get_state(STATE_IA_PD, &ia_pd_len); odhcp6c_get_state(STATE_IA_NA, &ia_na_len); if (ia_pd_len == 0 && ia_na_len == 0) break; // If we have IAs, try rebind otherwise restart res = dhcpv6_request(DHCPV6_MSG_REBIND); odhcp6c_signal_process(); if (res > 0) script_call("rebound", 0, true); else { break; } } break; default: break; } odhcp6c_expire(); size_t ia_pd_len, ia_na_len, server_id_len; odhcp6c_get_state(STATE_IA_PD, &ia_pd_len); odhcp6c_get_state(STATE_IA_NA, &ia_na_len); odhcp6c_get_state(STATE_SERVER_ID, &server_id_len); // Add all prefixes to lost prefixes bound = false; script_call("unbound", 0, true); if (server_id_len > 0 && (ia_pd_len > 0 || ia_na_len > 0) && release) dhcpv6_request(DHCPV6_MSG_RELEASE); odhcp6c_clear_state(STATE_IA_NA); odhcp6c_clear_state(STATE_IA_PD); } script_call("stopped", 0, true); return 0; }
int main(void) { int fd, len, sock_opt; int error; struct cn_msg *message; struct pollfd pfd; struct nlmsghdr *incoming_msg; struct cn_msg *incoming_cn_msg; struct hv_kvp_msg *hv_msg; char *p; char *key_value; char *key_name; daemon(1, 0); openlog("KVP", 0, LOG_USER); syslog(LOG_INFO, "KVP starting; pid is:%d", getpid()); kvp_get_os_info(); if (kvp_file_init()) { syslog(LOG_ERR, "Failed to initialize the pools"); exit(EXIT_FAILURE); } fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_CONNECTOR); if (fd < 0) { syslog(LOG_ERR, "netlink socket creation failed; error:%d", fd); exit(EXIT_FAILURE); } addr.nl_family = AF_NETLINK; addr.nl_pad = 0; addr.nl_pid = 0; addr.nl_groups = CN_KVP_IDX; error = bind(fd, (struct sockaddr *)&addr, sizeof(addr)); if (error < 0) { syslog(LOG_ERR, "bind failed; error:%d", error); close(fd); exit(EXIT_FAILURE); } sock_opt = addr.nl_groups; setsockopt(fd, 270, 1, &sock_opt, sizeof(sock_opt)); message = (struct cn_msg *)kvp_send_buffer; message->id.idx = CN_KVP_IDX; message->id.val = CN_KVP_VAL; hv_msg = (struct hv_kvp_msg *)message->data; hv_msg->kvp_hdr.operation = KVP_OP_REGISTER; message->ack = 0; message->len = sizeof(struct hv_kvp_msg); len = netlink_send(fd, message); if (len < 0) { syslog(LOG_ERR, "netlink_send failed; error:%d", len); close(fd); exit(EXIT_FAILURE); } pfd.fd = fd; while (1) { struct sockaddr *addr_p = (struct sockaddr *) &addr; socklen_t addr_l = sizeof(addr); pfd.events = POLLIN; pfd.revents = 0; poll(&pfd, 1, -1); len = recvfrom(fd, kvp_recv_buffer, sizeof(kvp_recv_buffer), 0, addr_p, &addr_l); if (len < 0 || addr.nl_pid) { syslog(LOG_ERR, "recvfrom failed; pid:%u error:%d %s", addr.nl_pid, errno, strerror(errno)); close(fd); return -1; } incoming_msg = (struct nlmsghdr *)kvp_recv_buffer; incoming_cn_msg = (struct cn_msg *)NLMSG_DATA(incoming_msg); hv_msg = (struct hv_kvp_msg *)incoming_cn_msg->data; switch (hv_msg->kvp_hdr.operation) { case KVP_OP_REGISTER: p = (char *)hv_msg->body.kvp_register.version; lic_version = malloc(strlen(p) + 1); if (lic_version) { strcpy(lic_version, p); syslog(LOG_INFO, "KVP LIC Version: %s", lic_version); } else { syslog(LOG_ERR, "malloc failed"); } continue; case KVP_OP_SET: if (kvp_key_add_or_modify(hv_msg->kvp_hdr.pool, hv_msg->body.kvp_set.data.key, hv_msg->body.kvp_set.data.key_size, hv_msg->body.kvp_set.data.value, hv_msg->body.kvp_set.data.value_size)) strcpy(hv_msg->body.kvp_set.data.key, ""); break; case KVP_OP_GET: if (kvp_get_value(hv_msg->kvp_hdr.pool, hv_msg->body.kvp_set.data.key, hv_msg->body.kvp_set.data.key_size, hv_msg->body.kvp_set.data.value, hv_msg->body.kvp_set.data.value_size)) strcpy(hv_msg->body.kvp_set.data.key, ""); break; case KVP_OP_DELETE: if (kvp_key_delete(hv_msg->kvp_hdr.pool, hv_msg->body.kvp_delete.key, hv_msg->body.kvp_delete.key_size)) strcpy(hv_msg->body.kvp_delete.key, ""); break; default: break; } if (hv_msg->kvp_hdr.operation != KVP_OP_ENUMERATE) goto kvp_done; if (hv_msg->kvp_hdr.pool != KVP_POOL_AUTO) { kvp_pool_enumerate(hv_msg->kvp_hdr.pool, hv_msg->body.kvp_enum_data.index, hv_msg->body.kvp_enum_data.data.key, HV_KVP_EXCHANGE_MAX_KEY_SIZE, hv_msg->body.kvp_enum_data.data.value, HV_KVP_EXCHANGE_MAX_VALUE_SIZE); goto kvp_done; } hv_msg = (struct hv_kvp_msg *)incoming_cn_msg->data; key_name = (char *)hv_msg->body.kvp_enum_data.data.key; key_value = (char *)hv_msg->body.kvp_enum_data.data.value; switch (hv_msg->body.kvp_enum_data.index) { case FullyQualifiedDomainName: kvp_get_domain_name(key_value, HV_KVP_EXCHANGE_MAX_VALUE_SIZE); strcpy(key_name, "FullyQualifiedDomainName"); break; case IntegrationServicesVersion: strcpy(key_name, "IntegrationServicesVersion"); strcpy(key_value, lic_version); break; case NetworkAddressIPv4: kvp_get_ip_address(AF_INET, key_value, HV_KVP_EXCHANGE_MAX_VALUE_SIZE); strcpy(key_name, "NetworkAddressIPv4"); break; case NetworkAddressIPv6: kvp_get_ip_address(AF_INET6, key_value, HV_KVP_EXCHANGE_MAX_VALUE_SIZE); strcpy(key_name, "NetworkAddressIPv6"); break; case OSBuildNumber: strcpy(key_value, os_build); strcpy(key_name, "OSBuildNumber"); break; case OSName: strcpy(key_value, os_name); strcpy(key_name, "OSName"); break; case OSMajorVersion: strcpy(key_value, os_major); strcpy(key_name, "OSMajorVersion"); break; case OSMinorVersion: strcpy(key_value, os_minor); strcpy(key_name, "OSMinorVersion"); break; case OSVersion: strcpy(key_value, os_build); strcpy(key_name, "OSVersion"); break; case ProcessorArchitecture: strcpy(key_value, processor_arch); strcpy(key_name, "ProcessorArchitecture"); break; default: strcpy(key_value, "Unknown Key"); strcpy(key_name, ""); break; } kvp_done: incoming_cn_msg->id.idx = CN_KVP_IDX; incoming_cn_msg->id.val = CN_KVP_VAL; incoming_cn_msg->ack = 0; incoming_cn_msg->len = sizeof(struct hv_kvp_msg); len = netlink_send(fd, incoming_cn_msg); if (len < 0) { syslog(LOG_ERR, "net_link send failed; error:%d", len); exit(EXIT_FAILURE); } } }
int main(int argc, char *argv[]) { struct rlimit rlp; struct addrinfo hints, *res; struct event ev, ev_sighup, ev_sigint, ev_sigterm; int ch, error, listenfd, on; const char *errstr = NULL; /* XXX gcc */ /* Defaults. */ anonymous_only = 0; daemonize = 1; fixed_proxy = NULL; fixed_server = NULL; fixed_server_port = "21"; ipv6_mode = 0; listen_ip = NULL; listen_port = "8021"; loglevel = LOG_NOTICE; max_sessions = 100; qname = NULL; rfc_mode = 0; tagname = NULL; timeout = 24 * 3600; verbose = 0; /* Other initialization. */ id_count = 1; session_count = 0; #if defined(__NetBSD__) /* Note: both for IPFilter and NPF. */ #define NBSD_OPTS "i:N:" #endif while ((ch = getopt(argc, argv, "6Aa:b:D:d" NBSD_OPTS "m:P:p:q:R:rT:t:v")) != -1) { switch (ch) { case '6': ipv6_mode = 1; break; case 'A': anonymous_only = 1; break; case 'a': fixed_proxy = optarg; break; case 'b': listen_ip = optarg; break; case 'D': loglevel = strtonum(optarg, LOG_EMERG, LOG_DEBUG, &errstr); if (errstr) errx(1, "loglevel %s", errstr); break; case 'd': daemonize = 0; break; case 'i': #if defined(__NetBSD__) && defined(WITH_IPF) fops = &ipf_fprx_ops; netif = optarg; #endif break; case 'm': max_sessions = strtonum(optarg, 1, 500, &errstr); if (errstr) errx(1, "max sessions %s", errstr); break; case 'N': #if defined(__NetBSD__) && defined(WITH_NPF) fops = &npf_fprx_ops; npfopts = optarg; #endif break; case 'P': fixed_server_port = optarg; break; case 'p': listen_port = optarg; break; case 'q': if (strlen(optarg) >= PF_QNAME_SIZE) errx(1, "queuename too long"); qname = optarg; break; case 'R': fixed_server = optarg; break; case 'r': rfc_mode = 1; break; case 'T': if (strlen(optarg) >= PF_TAG_NAME_SIZE) errx(1, "tagname too long"); tagname = optarg; break; case 't': timeout = strtonum(optarg, 0, 86400, &errstr); if (errstr) errx(1, "timeout %s", errstr); break; case 'v': verbose++; if (verbose > 2) usage(); break; default: usage(); } } if (listen_ip == NULL) listen_ip = ipv6_mode ? "::1" : "127.0.0.1"; /* Check for root to save the user from cryptic failure messages. */ if (getuid() != 0) errx(1, "needs to start as root"); /* Raise max. open files limit to satisfy max. sessions. */ rlp.rlim_cur = rlp.rlim_max = (2 * max_sessions) + 10; if (setrlimit(RLIMIT_NOFILE, &rlp) == -1) err(1, "setrlimit"); if (fixed_proxy) { memset(&hints, 0, sizeof hints); hints.ai_flags = AI_NUMERICHOST; hints.ai_family = ipv6_mode ? AF_INET6 : AF_INET; hints.ai_socktype = SOCK_STREAM; error = getaddrinfo(fixed_proxy, NULL, &hints, &res); if (error) errx(1, "getaddrinfo fixed proxy address failed: %s", gai_strerror(error)); memcpy(&fixed_proxy_ss, res->ai_addr, res->ai_addrlen); logmsg(LOG_INFO, "using %s to connect to servers", sock_ntop(sstosa(&fixed_proxy_ss))); freeaddrinfo(res); } if (fixed_server) { memset(&hints, 0, sizeof hints); hints.ai_family = ipv6_mode ? AF_INET6 : AF_INET; hints.ai_socktype = SOCK_STREAM; error = getaddrinfo(fixed_server, fixed_server_port, &hints, &res); if (error) errx(1, "getaddrinfo fixed server address failed: %s", gai_strerror(error)); memcpy(&fixed_server_ss, res->ai_addr, res->ai_addrlen); logmsg(LOG_INFO, "using fixed server %s", sock_ntop(sstosa(&fixed_server_ss))); freeaddrinfo(res); } /* Setup listener. */ memset(&hints, 0, sizeof hints); hints.ai_flags = AI_NUMERICHOST | AI_PASSIVE; hints.ai_family = ipv6_mode ? AF_INET6 : AF_INET; hints.ai_socktype = SOCK_STREAM; error = getaddrinfo(listen_ip, listen_port, &hints, &res); if (error) errx(1, "getaddrinfo listen address failed: %s", gai_strerror(error)); if ((listenfd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP)) == -1) errx(1, "socket failed"); on = 1; if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof on) != 0) err(1, "setsockopt failed"); if (bind(listenfd, (struct sockaddr *)res->ai_addr, (socklen_t)res->ai_addrlen) != 0) err(1, "bind failed"); if (listen(listenfd, TCP_BACKLOG) != 0) err(1, "listen failed"); freeaddrinfo(res); /* Initialize pf. */ fops->init_filter(qname, tagname, verbose); if (daemonize) { if (daemon(0, 0) == -1) err(1, "cannot daemonize"); openlog(__progname, LOG_PID | LOG_NDELAY, LOG_DAEMON); } /* Use logmsg for output from here on. */ if (!drop_privs()) { logmsg(LOG_ERR, "cannot drop privileges: %s", strerror(errno)); exit(1); } event_init(); /* Setup signal handler. */ signal(SIGPIPE, SIG_IGN); signal_set(&ev_sighup, SIGHUP, handle_signal, NULL); signal_set(&ev_sigint, SIGINT, handle_signal, NULL); signal_set(&ev_sigterm, SIGTERM, handle_signal, NULL); signal_add(&ev_sighup, NULL); signal_add(&ev_sigint, NULL); signal_add(&ev_sigterm, NULL); event_set(&ev, listenfd, EV_READ | EV_PERSIST, handle_connection, &ev); event_add(&ev, NULL); logmsg(LOG_NOTICE, "listening on %s port %s", listen_ip, listen_port); /* Vroom, vroom. */ event_dispatch(); logmsg(LOG_ERR, "event_dispatch error: %s", strerror(errno)); exit_daemon(); /* NOTREACHED */ return (1); }
int main(int argc, char* argv[]) { // ACL tests char* exename = getenv("WINDIR"); PSID psidOwner; PSID psidGroup; PACL pDacl; PSECURITY_DESCRIPTOR pSecurityDesc; DWORD result = GetNamedSecurityInfo( exename, // pObjectName SE_FILE_OBJECT, // ObjectType DACL_SECURITY_INFORMATION | // SecurityInfo GROUP_SECURITY_INFORMATION | OWNER_SECURITY_INFORMATION, &psidOwner, // ppsidOwner, &psidGroup, // ppsidGroup, &pDacl, // ppDacl, NULL, // ppSacl, &pSecurityDesc // ppSecurityDescriptor ); if (result != ERROR_SUCCESS) { printf("Error getting security info for '%s': error %d", exename, result); } assert(result == ERROR_SUCCESS); char namebuf[1024]; char domainbuf[1024]; SID_NAME_USE nametype; DWORD namelen = sizeof(namebuf); DWORD domainlen = sizeof(domainbuf); assert(LookupAccountSid(NULL, psidOwner, namebuf, &namelen, domainbuf, &domainlen, &nametype)); printf("Owner:\n"); printf("User name: %s\n", namebuf); printf("Domain name: %s\n", domainbuf); printf("Name type: %d\n", nametype); printf("\n"); namelen = sizeof(namebuf); domainlen = sizeof(domainbuf); assert(LookupAccountSid(NULL, psidGroup, namebuf, &namelen, domainbuf, &domainlen, &nametype)); printf("Group:\n"); printf("User name: %s\n", namebuf); printf("Domain name: %s\n", domainbuf); printf("Name type: %d\n", nametype); printf("\n"); ULONG numEntries; PEXPLICIT_ACCESS pEntries; result = GetExplicitEntriesFromAcl ( pDacl, // pAcl &numEntries, // pcCountOfExplicitEntries, &pEntries // pListOfExplicitEntries ); assert(result == ERROR_SUCCESS); printf("Found %lu explicit DACL entries for '%s'\n\n", (unsigned long)numEntries, exename); for (ULONG i = 0; i < numEntries; i++) { EXPLICIT_ACCESS* pEntry = &(pEntries[i]); printf("DACL entry %lu:\n", (unsigned long)i); DWORD perms = pEntry->grfAccessPermissions; printf(" Access permissions: ", perms); #define PRINT_PERM(name) \ if (perms & name) \ { \ printf(#name " "); \ perms &= ~name; \ } PRINT_PERM(FILE_ADD_FILE); PRINT_PERM(FILE_ADD_SUBDIRECTORY); PRINT_PERM(FILE_ALL_ACCESS); PRINT_PERM(FILE_APPEND_DATA); PRINT_PERM(FILE_CREATE_PIPE_INSTANCE); PRINT_PERM(FILE_DELETE_CHILD); PRINT_PERM(FILE_EXECUTE); PRINT_PERM(FILE_LIST_DIRECTORY); PRINT_PERM(FILE_READ_ATTRIBUTES); PRINT_PERM(FILE_READ_DATA); PRINT_PERM(FILE_READ_EA); PRINT_PERM(FILE_TRAVERSE); PRINT_PERM(FILE_WRITE_ATTRIBUTES); PRINT_PERM(FILE_WRITE_DATA); PRINT_PERM(FILE_WRITE_EA); PRINT_PERM(STANDARD_RIGHTS_READ); PRINT_PERM(STANDARD_RIGHTS_WRITE); PRINT_PERM(SYNCHRONIZE); PRINT_PERM(DELETE); PRINT_PERM(READ_CONTROL); PRINT_PERM(WRITE_DAC); PRINT_PERM(WRITE_OWNER); PRINT_PERM(MAXIMUM_ALLOWED); PRINT_PERM(GENERIC_ALL); PRINT_PERM(GENERIC_EXECUTE); PRINT_PERM(GENERIC_WRITE); PRINT_PERM(GENERIC_READ); printf("\n"); if (perms) { printf(" Bits left over: %08x\n", perms); } assert(!perms); printf(" Access mode: "); switch(pEntry->grfAccessMode) { case NOT_USED_ACCESS: printf("NOT_USED_ACCESS\n"); break; case GRANT_ACCESS: printf("GRANT_ACCESS\n"); break; case DENY_ACCESS: printf("DENY_ACCESS\n"); break; case REVOKE_ACCESS: printf("REVOKE_ACCESS\n"); break; case SET_AUDIT_SUCCESS: printf("SET_AUDIT_SUCCESS\n"); break; case SET_AUDIT_FAILURE: printf("SET_AUDIT_FAILURE\n"); break; default: printf("Unknown (%08x)\n", pEntry->grfAccessMode); } printf(" Trustee: "); assert(pEntry->Trustee.pMultipleTrustee == NULL); assert(pEntry->Trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE); switch(pEntry->Trustee.TrusteeForm) { case TRUSTEE_IS_SID: { PSID trusteeSid = (PSID)(pEntry->Trustee.ptstrName); namelen = sizeof(namebuf); domainlen = sizeof(domainbuf); assert(LookupAccountSid(NULL, trusteeSid, namebuf, &namelen, domainbuf, &domainlen, &nametype)); printf("SID of %s\\%s (%d)\n", domainbuf, namebuf, nametype); } break; case TRUSTEE_IS_NAME: printf("Name\n"); break; case TRUSTEE_BAD_FORM: printf("Bad form\n"); assert(0); case TRUSTEE_IS_OBJECTS_AND_SID: printf("Objects and SID\n"); break; case TRUSTEE_IS_OBJECTS_AND_NAME: printf("Objects and name\n"); break; default: printf("Unknown form\n"); assert(0); } printf(" Trustee type: "); switch(pEntry->Trustee.TrusteeType) { case TRUSTEE_IS_UNKNOWN: printf("Unknown type.\n"); break; case TRUSTEE_IS_USER: printf("User\n"); break; case TRUSTEE_IS_GROUP: printf("Group\n"); break; case TRUSTEE_IS_DOMAIN: printf("Domain\n"); break; case TRUSTEE_IS_ALIAS: printf("Alias\n"); break; case TRUSTEE_IS_WELL_KNOWN_GROUP: printf("Well-known group\n"); break; case TRUSTEE_IS_DELETED: printf("Deleted account\n"); break; case TRUSTEE_IS_INVALID: printf("Invalid trustee type\n"); break; case TRUSTEE_IS_COMPUTER: printf("Computer\n"); break; default: printf("Unknown type %d\n", pEntry->Trustee.TrusteeType); assert(0); } printf("\n"); } assert(LocalFree((HLOCAL)pEntries) == 0); assert(LocalFree((HLOCAL)pSecurityDesc) == 0); chdir("c:\\tmp"); openfile("test", O_CREAT, 0); struct stat ourfs; //test our opendir, readdir and closedir //functions DIR *ourDir = opendir("C:"); if ( ourDir != NULL ) { struct dirent *info; do { info = readdir(ourDir); if (info) printf("File/Dir name is : %s\r\n", info->d_name); } while (info != NULL); closedir(ourDir); } std::string diry("C:\\Projects\\boxbuild\\testfiles\\"); ourDir = opendir(diry.c_str()); if ( ourDir != NULL ) { struct dirent *info; do { info = readdir(ourDir); if (info == NULL) break; std::string file(diry + info->d_name); stat(file.c_str(), &ourfs); if (info) printf("File/Dir name is : %s\r\n", info->d_name); } while ( info != NULL ); closedir(ourDir); } stat("c:\\windows", &ourfs); stat("c:\\autoexec.bat", &ourfs); printf("Finished dir read\n"); //test our getopt function char * test_argv[] = { "foobar.exe", "-qwc", "-", "-c", "fgfgfg", "-f", "-l", "hello", "-", "force-sync", NULL }; int test_argc; for (test_argc = 0; test_argv[test_argc]; test_argc++) { } const char* opts = "qwc:l:"; assert(getopt(test_argc, test_argv, opts) == 'q'); assert(getopt(test_argc, test_argv, opts) == 'w'); assert(getopt(test_argc, test_argv, opts) == 'c'); assert(strcmp(optarg, "-") == 0); assert(getopt(test_argc, test_argv, opts) == 'c'); assert(strcmp(optarg, "fgfgfg") == 0); assert(getopt(test_argc, test_argv, opts) == '?'); assert(optopt == 'f'); assert(getopt(test_argc, test_argv, opts) == 'l'); assert(strcmp(optarg, "hello") == 0); assert(getopt(test_argc, test_argv, opts) == -1); // assert(optopt == 0); // no more options assert(strcmp(test_argv[optind], "-") == 0); assert(strcmp(test_argv[optind+1], "force-sync") == 0); //end of getopt test //now test our statfs funct stat("c:\\cert.cer", &ourfs); char *timee; timee = ctime(&ourfs.st_mtime); if (S_ISREG(ourfs.st_mode)) { printf("is a normal file\n"); } else { printf("is a directory?\n"); exit(1); } lstat(getenv("WINDIR"), &ourfs); if ( S_ISDIR(ourfs.st_mode)) { printf("is a directory\n"); } else { printf("is a file?\n"); exit(1); } //test the syslog functions openlog("Box Backup", 0,0); //the old ones are the best... syslog(LOG_ERR, "Hello World"); syslog(LOG_ERR, "Value of int is: %i", 6); closelog(); /* //first off get the path name for the default char buf[MAX_PATH]; GetModuleFileName(NULL, buf, sizeof(buf)); std::string buffer(buf); std::string conf("-c " + buffer.substr(0,(buffer.find("win32test.exe"))) + "bbackupd.conf"); //std::string conf( "-c " + buffer.substr(0,(buffer.find("bbackupd.exe"))) + "bbackupd.conf"); */ return 0; }
PAM_EXTERN int pam_sm_authenticate(pam_handle_t *pamh, int flags, int argc, const char **argv) { int retval = PAM_SERVICE_ERR; pam_get_user_2nd_arg_t *username; struct passwd *user_pwd; char *ubuf = NULL; struct dirent *jdent; DIR *jobdir = NULL; int fp; struct job xjob; ssize_t amt; char jobpath[PATH_MAX+1]; char jobdirpath[PATH_MAX+1]; int debug = 0; char log_buf[LOCAL_LOG_BUF_SIZE]; openlog(MODNAME, LOG_PID, LOG_USER); strcpy(jobdirpath, PBS_SERVER_HOME "/mom_priv/jobs"); /* step through arguments */ for (; argc-- > 0; ++argv) { if (!strcmp(*argv, "debug")) debug = 1; else if (!strncmp(*argv, "jobdir=", strlen("jobdir="))) strncpy(jobdirpath, (*argv) + strlen("jobdir="), PATH_MAX); else syslog(LOG_ERR, "unknown option: %s", *argv); } if (debug) syslog(LOG_INFO, "opening %s", jobdirpath); if ((jobdir = opendir(jobdirpath)) == NULL) { if (debug) syslog(LOG_INFO, "failed to open jobs dir: %s", strerror(errno)); closelog(); return PAM_IGNORE; } /* get the username and passwd, allow uid 0 */ retval = pam_get_user(pamh, (const char **)&username, NULL); #if defined(PAM_CONV_AGAIN) && defined(PAM_INCOMPLETE) if (retval == PAM_CONV_AGAIN) { closelog(); return PAM_INCOMPLETE; } #endif if ((retval != PAM_SUCCESS) || !username) { syslog(LOG_ERR, "failed to retrieve username"); closelog(); return PAM_SERVICE_ERR; } user_pwd = getpwnam((char *)username); /* no early returns from this point on because we need to free ubuf */ if (debug) syslog(LOG_INFO, "username %s, %s", username, user_pwd ? "known" : "unknown"); if (!user_pwd) { retval = PAM_USER_UNKNOWN; } else if (user_pwd->pw_uid == 0) { if (debug) syslog(LOG_INFO, "allowing uid 0"); retval = PAM_SUCCESS; } else { retval = PAM_AUTH_ERR; while ((jdent = readdir(jobdir)) != NULL) { if (strstr(jdent->d_name, ".JB") == NULL) continue; snprintf(jobpath, PATH_MAX - 1, "%s/%s", jobdirpath, jdent->d_name); if (debug) syslog(LOG_INFO, "opening %s", jobpath); /* try to read the JB file in XML format first */ if (job_read_xml(jobpath, &xjob, log_buf, sizeof(log_buf)) != PBSE_NONE) { /* XML read failed, try binary version read */ if (debug) { syslog(LOG_INFO, "failed to read JB file in XML format: %s", log_buf); syslog(LOG_INFO, "trying to read JB file in binary format"); } fp = open(jobpath, O_RDONLY, 0); if (fp < 0) { syslog(LOG_ERR, "error opening job file"); continue; } amt = read(fp, &xjob.ji_qs, sizeof(xjob.ji_qs)); if (amt != sizeof(xjob.ji_qs)) { close(fp); syslog(LOG_ERR, "short read of job file"); continue; } if (xjob.ji_qs.ji_un_type != JOB_UNION_TYPE_MOM) { /* odd, this really should be JOB_UNION_TYPE_MOM */ close(fp); syslog(LOG_ERR, "job file corrupt"); continue; } close(fp); } if (debug) syslog(LOG_INFO, "state=%d, substate=%d", xjob.ji_qs.ji_state, xjob.ji_qs.ji_substate); if ((xjob.ji_qs.ji_un.ji_momt.ji_exuid == user_pwd->pw_uid) && ((xjob.ji_qs.ji_substate == JOB_SUBSTATE_PRERUN) || (xjob.ji_qs.ji_substate == JOB_SUBSTATE_STARTING) || (xjob.ji_qs.ji_substate == JOB_SUBSTATE_RUNNING))) { /* success! */ if (debug) syslog(LOG_INFO, "allowed by %s", jdent->d_name); retval = PAM_SUCCESS; break; } } /* END while (readdir(jobdir)) */ if (jobdir) closedir(jobdir); } if (ubuf) free(ubuf); if (debug) syslog(LOG_INFO, "returning %s", retval == PAM_SUCCESS ? "success" : "failed"); closelog(); return retval; }
int main(int argc,char *argv[]) { int rtn; int ret=0; openlog("ykt",LOG_PID|LOG_CONS|LOG_NDELAY,LOG_LOCAL3); g_pSvrLink = BUPubInitialize(g_XBDefines,CallBDFunc,WriteAppInfo,&g_LogFile); SetLogShowLevel(0); if (argc<2) ReadIni("ksbu.ini"); else ReadIni(argv[1]); struct sigaction act,oldact; act.sa_handler = handler_alarm; if(-1==sigaction(SIGALRM,&act,&oldact)) { writelog(LOG_ERR,"sigaction error,errcode=[%d]",-1); return -1; } ret=ReadIni_bank(&g_Bank); if(ret) { writelog(LOG_ERR,"ReadIni_bank error,errcode=[%d]",ret); return -1; } ResetBPFunctions(); if (argc>2) { ListBPFunctions(argv[2]); } // 初始化数据库连接: /* SQLInitialize(); if (SQLConnectToServer()!=0) { RAISE_RUNTIME_ERROR("不能正常建立数据库连接, 检查配置和数据库服务器!\n"); return(-100); } */ // 初始化与BCC连接: do { rtn = g_pSvrLink->ToLink(&g_BUnit); if (rtn==1) { DEBUG_RUNTIME_MSGOUT("与业务调度中心(BCC)的连接成功!\n"); break; } else if (rtn==-100) { DEBUG_RUNTIME_MSGOUT("估计业务调度中心(BCC)尚未正式启动,或者检查配置中的[SERVER]项参数\n"); mysleep(g_BUnit.iHBInterval); } else { // 应该属于故障,或对方并不是BCC DEBUG_RUNTIME_MSGOUT("未知错误\n"); return(rtn); } } while (1); #ifdef WIN32 setnoblockgetch(); #endif /********************************************************************** Added by hhd at 2004-09-16 为了增加签到处理,达到共享内存的处理 增加共享内存和信号量 共享内存一共1024个字节,其中使用前18个字节 shm[0]:代表是否进行过签到的标志,如果为1,已经签过到但不知道是否成功 ,后续业务将不能进行签到处理,如果为其他值,系统将进行签到 shm[1]:代表签到是否成功的标志,如果为1,则标识签到成功,后续16个字节为 银行正常返回数据,可以使用 shm[2~17]:前8个字节为加密的PIN密钥,后8个字节为加密的MAC密钥 ***********************************************************************/ /********************************************************************** Update by hhd at 2004-10-27 为了增加签到处理,达到共享内存的处理 增加共享内存和信号量 为了反映每个终端的当前工作状态,在共享内存中设置一个状态标志 共享内存一共1024个字节,其中使用前26个字节 shm[0]:代表是否进行过签到的标志,如果为1,已经签过到但不知道是否成功 ,后续业务将不能进行签到处理,如果为其他值,系统将进行签到 shm[1]:代表签到是否成功的标志,如果为1,则标识签到成功,后续16个字节为 银行正常返回数据,可以使用 shm[2]:代表系统重新启动标志,如果不为1,系统进行初始化操作(进行设备 注册表中设备的状态的清空操作),然后系统将改标志置为1,其他BU启动 跳过该项操作 shm[10~25]:前8个字节为加密的PIN密钥,后8个字节为加密的MAC密钥 ***********************************************************************/ key_t key; struct shmid_ds buf; // Update by lq at 2005-03-10 // 将创建共享内存和设备签到移到bankguard中去 // 必须先运行bankguard此处操作才能完成 key=ftok(".",0); shmid=shmget(key,SEGSIZE,0666); if(-1==shmid) { DEBUG_RUNTIME_MSGOUT("获取共享内存失败,请确保bankguard已经启动\n"); return E_CREATE_SHARE_MEMORY; } shm=(char*)shmat(shmid,0,0); if((int)shm==-1) { DEBUG_RUNTIME_MSGOUT("映射共享内存失败"); return E_JOIN_SHARE_MEMORY; } semid=semget(key,1,0); if(semid==-1) { DEBUG_RUNTIME_MSGOUT("获取共享锁id失败"); return E_JOIN_SHARE_MEMORY; } // Added by hhd end here while (g_pSvrLink->LinkOK()) { #ifdef WIN32 switch (mygetch()) { case '?': case 'h': case 'H': printf("\nCommand List:\n"); printf("\t ? or h: display this Help informations!\n"); printf("\t x: To eXit this business unit.\n"); printf("\t d: Display functions status.\n"); printf("\t l: List functions status into <function.lst>.\n"); printf("Enter command to select:"); break; case 'x': case 'X': g_pSvrLink->bExit = true; continue; break; case 'd': case 'D': ListBPFunctions(NULL); break; case 'l': case 'L': ListBPFunctions("function.lst"); break; } #endif // if (!SQLIsConnectOK()) if(0) { mysleep(1000); if (!g_pSvrLink->CheckLink()) break; // BCC exit (可能用户发现数据库连接断开,需要维护系统,导致手工将BCC退出同时也需要BU退出) //if (SQLConnectToServer()!=0) if(0) { // SQL Link error: DEBUG_RUNTIME_MSGOUT("不能正常建立数据库连接, 检查配置和数据库服务器!\n"); } else { DEBUG_RUNTIME_MSGOUT("与数据库连接成功!\n"); } continue; } else { //DEBUG_RUNTIME_MSGOUT("处理bu业务!\n"); g_pSvrLink->Processing(&g_BUnit); } //if (g_pSvrLink->bExit) break; } /* ****** Updated by CHENYH at 2004-4-14 11:07:19 ****** 经过测试后,CheckLink()工作正常,测试环境为:BCC(WIN)+BU(WIN),BCC(LINUX)+BU(WIN),BCC(LINUX)+BU(LINUX) while (1) { mysleep(1000); if (!g_SvrLink.CheckLink()) { printf("TEST CHECK LINK return <false>!\n"); break; } } */ shmdt(shm); shmctl(shmid,IPC_RMID,&buf); d_sem(semid); g_pSvrLink->Close(); // SQLExit(); DEBUG_RUNTIME_MSGOUT("业务处理单元BU系统正常退出!\n"); g_LogFile.Close(); closelog(); return(0); }
/* * * MAIN process * */ int main(int argc, char* argv[]) { char serial_port[32] = SERIAL_PORT_PREFIX; int baud_rate; int num_slaves; int i, k; if ((argc < 6) || ((argc>6) && (argc<NUM_REG_PER_SLAVE+5))) { printf("Usage:\n\n"); printf(" Single slave (passthrough) mode:\n"); printf(" mbrtud <serial dev> <baudrate> <num_regs> <reg_offset> <slave addr>\n"); printf(" serial dev: name of the serial device used for connection to the Modbus converter (e.g. USB0 or S0)\n"); printf(" baudrate: baudrate used for serial connection\n"); printf(" num_regs: number of consecutive registers to read\n"); printf(" reg_offset: register address offset to add for slave request\n"); printf(" slave addr: address of Modbus slave device\n\n"); printf(" Multiple slave (register mapping) mode:\n"); printf(" mbrtud <serial dev> <baudrate> <num_regs> <reg 1> ... <reg %d> <slave addr> [<slave addr> ...]\n", NUM_REG_PER_SLAVE); printf(" serial dev: name of the serial device used for connection to the Modbus converter (e.g. USB0 or S0)\n"); printf(" baudrate: baudrate used for serial connection\n"); printf(" num_regs: number of consecutive registers to read\n"); printf(" reg x: register map to use for slave request\n"); printf(" slave addr: address of Modbus slave devices (up to %d)\n", MAX_SLAVES); return 0; } openlog("mbrtud", LOG_PID|LOG_CONS, LOG_USER); syslog(LOG_DAEMON | LOG_NOTICE, "Starting Modbus RTU daemon (version %s)\n", VERSION); /* Install signal handler for SIGTERM and SIGINT ("CTRL C") to be used to terminate */ signal(SIGTERM, doExit); signal(SIGINT, doExit); /* Get input parameters */ i=1; strcat(serial_port, argv[i++]); baud_rate = atoi(argv[i++]); num_regs = atoi(argv[i++]); if (argc == 6) { /* Single slave (passthrough) mode */ mode=MODE_SINGLESLAVE; reg_offset = atoi(argv[i++]); slave_addr_table[0] = atoi(argv[i++]); } else { /* Multiple slave (register mapping) mode */ mode=MODE_MULTISLAVE; for (k=0; (i<argc)&&(k<NUM_REG_PER_SLAVE); i++, k++) custom_reg_table[k] = atoi(argv[i]); memset(slave_addr_table, 0, sizeof(slave_addr_table)); for (k=0; (i<argc)&&(k<MAX_SLAVES); i++, k++) slave_addr_table[k] = atoi(argv[i]); num_slaves = k; } /* Init the Modbus RTU connection */ mb = modbus_new_rtu(serial_port, baud_rate, 'N', 8, 1); if (mb == NULL) { syslog(LOG_DAEMON | LOG_ERR, "Unable to create RTU485 context\n"); modbus_free(mb); return 1; } if (modbus_connect(mb) == -1) { syslog(LOG_DAEMON | LOG_ERR, "Connection failed: %s\n", modbus_strerror(errno)); return 2; } /* Set Modbus timeouts */ modbus_set_response_timeout(mb, 20, 0); modbus_set_byte_timeout(mb, 1, 0); /* Specific setting for direction control of the RS485 transceiver */ if (strstr(serial_port, "USB") == NULL) { /* Enable RS485 direction control via RTS line */ if (modbus_rtu_set_rts(mb, MODBUS_RTU_RTS_DOWN) == -1) { syslog(LOG_DAEMON | LOG_ERR, "Setting RTS mode failed: %s\n", modbus_strerror(errno)); modbus_free(mb); return 3; } /* Set RTS control delay (before and after transmission) */ if (DEFAULT_RTS_DELAY > 0) { if (modbus_rtu_set_rts_delay(mb, DEFAULT_RTS_DELAY) == -1) { syslog(LOG_DAEMON | LOG_ERR, "Setting RTS delay failed: %s\n", modbus_strerror(errno)); modbus_free(mb); return 4; } } syslog(LOG_DAEMON | LOG_NOTICE, "using direction control via RTS line"); } //modbus_set_debug(mb, TRUE); syslog(LOG_DAEMON | LOG_NOTICE, "Using Modbus connection on serial port %s at %dbaud", serial_port, baud_rate); if (mode == MODE_SINGLESLAVE) { syslog(LOG_DAEMON | LOG_NOTICE, "Single slave mode - slave address: %d", slave_addr_table[0]); } else { syslog(LOG_DAEMON | LOG_NOTICE, "Multiple slave mode - register map for each slave:"); syslog(LOG_DAEMON | LOG_NOTICE, " Reg | Id "); syslog(LOG_DAEMON | LOG_NOTICE, " ---------"); for (i=0; i<NUM_REG_PER_SLAVE; i++) syslog(LOG_DAEMON | LOG_NOTICE, " %02d | %02d", i+1, custom_reg_table[i]); syslog(LOG_DAEMON | LOG_NOTICE, "List of slaves:"); for (i=0; i<num_slaves; i++) syslog(LOG_DAEMON | LOG_NOTICE, " slave %d: %d (regs[%d...%d])\n", i+1, slave_addr_table[i], i*NUM_REG_PER_SLAVE+1, i*NUM_REG_PER_SLAVE+NUM_REG_PER_SLAVE); } /* Start Modbus TCP server loop */ modbustcp_server(MODBUS_SLAVE_ADDRESS, // Modbus slave address read_register_handler, // Read register handler write_register_handler // Write register handler ); return 0; }
int main (int argc, char **argv) { int o; char *rbuf; extern int optind; extern char *optarg; struct cmd *pcmd; /* command structure */ struct wthio wio; /* result */ initdata(&wio); pcmd = initcmd(); if ( ( rbuf = readconfig(pcmd)) == NULL ) { perror("Error reading configuration: exit!"); exit(-1); } openlog("wthxc", LOG_PID , pcmd->logfacility); syslog(LOG_INFO, "wthxc: %s\n", VERSION); /* parsing command line arguments */ while (( o = getopt(argc, argv, "c:h:xi:p:sv")) != -1 ) { switch (o) { case 'c': pcmd->command = atoi(optarg); break; case 'h': pcmd->hostname = optarg; pcmd->netflg = 1; break; case 'x': pcmd->netflg = 2; break; case 'i': pcmd->argcmd = atoi(optarg); break; case 'p': pcmd->port = optarg; break; case 's': if ( pcmd->netflg != -1 ) usage(1,"specify serial OR internet connection",""); pcmd->netflg = 0; break; case 'v': pcmd->verbose = 1; printf("wthc version: %s\n", VERSION); printf("%s", rbuf); break; case '?': usage(1, "Commandline error", ""); break; default: usage(0,"", ""); } } /* save command for later use */ o = pcmd->command; /* check if intervall time has been set in case pcmd->command is request to set intervall time */ if ( pcmd->command == 6 ) { if ((pcmd->argcmd < 1) || (pcmd->argcmd >60)) usage(1,"interval time not been specified or out of range", ""); } /* check on serial/internet connection is been chosen correctly */ if ( pcmd->netflg == -1 ) usage(1, "specify serial OR internet connection",""); if (pcmd->verbose == 1 ) { if ( ( rbuf = echoconfig(pcmd)) == NULL) { perror("Error echo config parameters: exit!"); exit(-1); } printf("%s\n", rbuf); } /* sending command to weather station */ rbuf = wcmd(pcmd, &wio); printf("%s", rbuf); /* syslog(LOG_INFO, "wthc : wcmd : %s\n", c(o)->descr); */ switch (werrno) { case ESERIAL: printf("serial line error\n"); break; case ECHKSUM: printf("data chksum error\n"); break; case ERCPT: printf("faulty data reception\n"); break; case 0: break; } closelog(); return(0); }
void main() { openlog("TEST", 0, 0); syslog(LOG_ERR, "Test failed: %m"); }
void log_open_syslog(void) { openlog(NULL, LOG_NOWAIT | LOG_PID, LOG_USER); }
void vsyslog(int pri, const char *fmt, va_list ap) { FILE *f; char *s; time_t now; char buf[1024]; char newfmt[1024]; int count = 0; char *p, *d; int fd; int send_error = 0; int saveerrno = errno; int savewinerror = GetLastError(); int savewinsockerror = WSAGetLastError(); switch(LOG_PRI(pri)) { case LOG_DEBUG: s = "DEBUG:"; break; case LOG_INFO: s = "INFO:"; break; case LOG_ERR: s = "ERROR:"; break; case LOG_NOTICE: s = "NOTICE:"; break; case LOG_WARNING: s = "WARNING:"; break; default: s = "UNKNOWN:"; break; } for(p = (char *)fmt, d = newfmt; *p;) { if(*p == '%') { if(p[1] == 'm') { if(saveerrno) d += sprintf(d, "%s", strerror(saveerrno)); else if(savewinerror) d += sprintf(d, "%s", winstrerror(savewinerror)); else if(savewinsockerror) d += sprintf(d, "%s", wsstrerror(savewinsockerror)); p += 2; } else if(p[1] == 'w') { if(savewinerror) d += sprintf(d, "%s", winstrerror(savewinerror)); else if(savewinsockerror) d += sprintf(d, "%s", wsstrerror(savewinsockerror)); p += 2; } else { *d++ = *p++; } } else { *d++ = *p++; } } *d = 0; time(&now); count = sprintf(buf, "<%d>%.15s %s", pri, ctime(&now) + 4, __LogTag, s); if(__LogStat & LOG_PID) count += sprintf(buf + count, "[%x]", getpid()); count += sprintf(buf + count, ":"); count += vsprintf(buf + count, newfmt, ap); if(buf[count - 1] != '\n') count += sprintf(buf + count, "\n"); /* output to stderr */ if(__LogStat & LOG_PERROR) fprintf(stderr, "%s: %s", s, buf); if(!__LogOpened) openlog(__LogTag, __LogStat | LOG_NDELAY, 0); #ifndef UNDER_CE if(sendto(LogSocket, buf, strlen(buf), 0, (struct sockaddr *)& LogAddr, sizeof(struct sockaddr_in)) == SOCKET_ERROR) { send_error = WSAGetLastError(); } if((__LogStat & LOG_CONS) && (fd = open(_PATH_CONSOLE, O_WRONLY, 0)) >= 0) { _write(fd, buf, strlen(buf)); _close(fd); } #endif if((fd = open(_PATH_LOG, O_WRONLY|O_APPEND|O_CREAT,666)) > 0) { write(fd, s, strlen(s)); write(fd, buf + 3, strlen(buf) - 3); close(fd); } }
// program entry point int main(int argc, char *argv[]) { is_daemonised = false; bool nodaemon = false; bool needreset = false; std::string configfile(__CONFFILE); srand(time(NULL)); int rc; openlog("dansguardian", LOG_PID | LOG_CONS, LOG_USER); #ifdef DGDEBUG std::cout << "Running in debug mode..." << std::endl; #endif #ifdef __BENCHMARK char benchmark = '\0'; #endif for (int i = 1; i < argc; i++) { if (argv[i][0] == '-') { for (unsigned int j = 1; j < strlen(argv[i]); j++) { char option = argv[i][j]; bool dobreak = false; switch (option) { case 'q': read_config(configfile.c_str(), 0); return sysv_kill(o.pid_filename); case 'Q': read_config(configfile.c_str(), 0); sysv_kill(o.pid_filename, false); // give the old process time to die while(sysv_amirunning(o.pid_filename)) sleep(1); unlink(o.pid_filename.c_str()); unlink(o.ipc_filename.c_str()); unlink(o.urlipc_filename.c_str()); // remember to reset config before continuing needreset = true; break; case 's': read_config(configfile.c_str(), 0); return sysv_showpid(o.pid_filename); case 'r': read_config(configfile.c_str(), 0); return sysv_hup(o.pid_filename); case 'g': read_config(configfile.c_str(), 0); return sysv_usr1(o.pid_filename); case 'v': std::cout << "DansGuardian " << PACKAGE_VERSION << std::endl << std::endl << "Built with: " << DG_CONFIGURE_OPTIONS << std::endl; return 0; case 'N': nodaemon = true; break; case 'c': if ((i+1) < argc) { configfile = argv[i+1]; dobreak = true; // broken-ness of this option reported by Jason Gauthier 2006-03-09 } else { std::cerr << "No config file specified!" << std::endl; return 1; } break; case 'h': std::cout << "Usage: " << argv[0] << " [{-c ConfigFileName|-v|-P|-h|-N|-q|-s|-r|-g}]" << std::endl; std::cout << " -v gives the version number and build options." << std::endl; std::cout << " -h gives this message." << std::endl; std::cout << " -c allows you to specify a different configuration file location." << std::endl; std::cout << " -N Do not go into the background." << std::endl; std::cout << " -q causes DansGuardian to kill any running copy." << std::endl; std::cout << " -Q kill any running copy AND start a new one with current options." << std::endl; std::cout << " -s shows the parent process PID and exits." << std::endl; std::cout << " -r closes all connections and reloads config files by issuing a HUP," << std::endl; std::cout << " but this does not reset the maxchildren option (amongst others)." << std::endl; std::cout << " -g gently restarts by not closing all current connections; only reloads" << std::endl << " filter group config files. (Issues a USR1)" << std::endl; #ifdef __BENCHMARK std::cout << " --bs benchmark searching filter group 1's bannedsitelist" << std::endl; std::cout << " --bu benchmark searching filter group 1's bannedurllist" << std::endl; std::cout << " --bp benchmark searching filter group 1's phrase lists" << std::endl; std::cout << " --bn benchmark filter group 1's NaughtyFilter in its entirety" << std::endl; #endif return 0; #ifdef __BENCHMARK case '-': if (strlen(argv[i]) != 4) { std::cerr << "Invalid benchmark option" << std::endl; return 1; } benchmark = argv[i][3]; dobreak = true; break; #endif } if (dobreak) break; // skip to the next argument } } } // Set current locale for proper character conversion setlocale(LC_ALL, ""); if (needreset) { o.reset(); } read_config(configfile.c_str(), 2); #ifdef __BENCHMARK // run benchmarks instead of starting the daemon if (benchmark) { std::string results; char* found; struct tms then, now; std::string line; std::deque<String*> lines; while (!std::cin.eof()) { std::getline(std::cin, line); String* strline = new String(line); lines.push_back(strline); } String* strline = NULL; times(&then); switch (benchmark) { case 's': // bannedsitelist while (!lines.empty()) { strline = lines.back(); lines.pop_back(); if ((found = o.fg[0]->inBannedSiteList(*strline))) { results += found; results += '\n'; } delete strline; } break; case 'u': // bannedurllist while (!lines.empty()) { strline = lines.back(); lines.pop_back(); if ((found = o.fg[0]->inBannedURLList(*strline))) { results += found; results += '\n'; } delete strline; } break; case 'p': { // phraselists std::deque<unsigned int> found; std::string file; while (!lines.empty()) { strline = lines.back(); lines.pop_back(); file += strline->toCharArray(); delete strline; } char cfile[file.length() + 129]; memcpy(cfile, file.c_str(), sizeof(char)*file.length()); o.lm.l[o.fg[0]->banned_phrase_list]->graphSearch(found, cfile, file.length()); for (std::deque<unsigned int>::iterator i = found.begin(); i != found.end(); i++) { results += o.lm.l[o.fg[0]->banned_phrase_list]->getItemAtInt(*i); results += '\n'; } } break; case 'n': { // NaughtyFilter std::string file; NaughtyFilter n; while (!lines.empty()) { strline = lines.back(); lines.pop_back(); file += strline->toCharArray(); delete strline; } DataBuffer d(file.c_str(), file.length()); String f; n.checkme(&d, f, f); std::cout << n.isItNaughty << std::endl << n.whatIsNaughty << std::endl << n.whatIsNaughtyLog << std::endl << n.whatIsNaughtyCategories << std::endl; } break; default: std::cerr << "Invalid benchmark option" << std::endl; return 1; } times(&now); std::cout << results << std::endl << "time: " << now.tms_utime - then.tms_utime << std::endl; return 0; } #endif if (sysv_amirunning(o.pid_filename)) { syslog(LOG_ERR, "%s", "I seem to be running already!"); std::cerr << "I seem to be running already!" << std::endl; return 1; // can't have two copies running!! } if (nodaemon) { o.no_daemon = 1; } if ((o.max_children + 6) > FD_SETSIZE) { syslog(LOG_ERR, "%s", "maxchildren option in dansguardian.conf has a value too high."); std::cerr << "maxchildren option in dansguardian.conf has a value too high." << std::endl; std::cerr << "Dammit Jim, I'm a filtering proxy, not a rabbit." << std::endl; return 1; // we can't have rampant proccesses can we? } unsigned int rootuid; // prepare a struct for use later rootuid = geteuid(); o.root_user = rootuid; struct passwd *st; // prepare a struct struct group *sg; // "daemongroup" option exists, but never used to be honoured. this is now // an important feature, however, because we need to be able to create temp // files with suitable permissions for scanning by AV daemons - we do this // by becoming a member of a specified AV group and setting group read perms if ((sg = getgrnam(o.daemon_group_name.c_str())) != 0) { o.proxy_group = sg->gr_gid; } else { syslog(LOG_ERR, "Unable to getgrnam(): %s", ErrStr().c_str()); std::cerr << "Unable to getgrnam(): " << ErrStr() << std::endl; return 1; } if ((st = getpwnam(o.daemon_user_name.c_str())) != 0) { // find uid for proxy user o.proxy_user = st->pw_uid; rc = setgid(o.proxy_group); // change to rights of proxy user group // i.e. low - for security if (rc == -1) { syslog(LOG_ERR, "%s", "Unable to setgid()"); std::cerr << "Unable to setgid()" << std::endl; return 1; // setgid failed for some reason so exit with error } #ifdef HAVE_SETREUID rc = setreuid((uid_t) - 1, st->pw_uid); #else rc = seteuid(o.proxy_user); // need to be euid so can su back // (yes it negates but no choice) #endif if (rc == -1) { syslog(LOG_ERR, "Unable to seteuid()"); std::cerr << "Unable to seteuid()" << std::endl; return 1; // seteuid failed for some reason so exit with error } } else { syslog(LOG_ERR, "Unable to getpwnam() - does the proxy user exist?"); std::cerr << "Unable to getpwnam() - does the proxy user exist?" << std::endl; std::cerr << "Proxy user looking for is '" << o.daemon_user_name << "'" << std::endl; return 1; // was unable to lockup the user id from passwd // for some reason, so exit with error } if (!o.no_logger && !o.log_syslog) { std::ofstream logfiletest(o.log_location.c_str(), std::ios::app); if (logfiletest.fail()) { syslog(LOG_ERR, "Error opening/creating log file. (check ownership and access rights)."); std::cout << "Error opening/creating log file. (check ownership and access rights)." << std::endl; std::cout << "I am running as " << o.daemon_user_name << " and I am trying to open " << o.log_location << std::endl; return 1; // opening the log file for writing failed } logfiletest.close(); } urldecode_re.comp("%[0-9a-fA-F][0-9a-fA-F]"); // regexp for url decoding #ifdef HAVE_PCRE // todo: these only work with PCRE enabled (non-greedy matching). // change them, or make them a feature for which you need PCRE? absurl_re.comp("[\"'](http|ftp)://.*?[\"']"); // find absolute URLs in quotes relurl_re.comp("(href|src)\\s*=\\s*[\"'].*?[\"']"); // find relative URLs in quotes #endif // this is no longer a class, but the comment has been retained for historical reasons. PRA 03-10-2005 //FatController f; // Thomas The Tank Engine while (true) { rc = fc_controlit(); // its a little messy, but I wanted to split // all the ground work and non-daemon stuff // away from the daemon class // However the line is not so fine. if (rc == 2) { // In order to re-read the conf files and create cache files // we need to become root user again #ifdef HAVE_SETREUID rc = setreuid((uid_t) - 1, rootuid); #else rc = seteuid(rootuid); #endif if (rc == -1) { syslog(LOG_ERR, "%s", "Unable to seteuid() to read conf files."); #ifdef DGDEBUG std::cerr << "Unable to seteuid() to read conf files." << std::endl; #endif return 1; } #ifdef DGDEBUG std::cout << "About to re-read conf file." << std::endl; #endif o.reset(); if (!o.read(configfile.c_str(), 2)) { syslog(LOG_ERR, "%s", "Error re-parsing the dansguardian.conf file or other DansGuardian configuration files"); #ifdef DGDEBUG std::cerr << "Error re-parsing the dansguardian.conf file or other DansGuardian configuration files" << std::endl; #endif return 1; // OptionContainer class had an error reading the conf or // other files so exit with error } #ifdef DGDEBUG std::cout << "conf file read." << std::endl; #endif if (nodaemon) { o.no_daemon = 1; } while (waitpid(-1, NULL, WNOHANG) > 0) { } // mop up defunts #ifdef HAVE_SETREUID rc = setreuid((uid_t) - 1, st->pw_uid); #else rc = seteuid(st->pw_uid); // become low priv again #endif if (rc == -1) { syslog(LOG_ERR, "%s", "Unable to re-seteuid()"); #ifdef DGDEBUG std::cerr << "Unable to re-seteuid()" << std::endl; #endif return 1; // seteuid failed for some reason so exit with error } continue; } if (rc > 0) { if (!is_daemonised) { std::cerr << "Exiting with error" << std::endl; } syslog(LOG_ERR, "%s", "Exiting with error"); return rc; // exit returning the error number } return 0; // exit without error } }
int main (int argc, char **argv) { int s = -1; int fd = -1; Arguments arg; Tunnel *tunnel; int closed; parse_arguments (argc, argv, &arg); if ((debug_level == 0 || debug_file != NULL) && arg.use_daemon) daemon (0, 1); #ifdef DEBUG_MODE if (debug_level != 0 && debug_file == NULL) debug_file = stderr; #else openlog ("htc", LOG_PID, LOG_DAEMON); #endif log_notice ("htc (%s) %s started with arguments:", PACKAGE, VERSION); log_notice (" me = %s", arg.me); log_notice (" device = %s", arg.device ? arg.device : "(null)"); log_notice (" host_name = %s", arg.host_name ? arg.host_name : "(null)"); log_notice (" host_port = %d", arg.host_port); log_notice (" proxy_name = %s", arg.proxy_name ? arg.proxy_name : "(null)"); log_notice (" proxy_port = %d", arg.proxy_port); log_notice (" proxy_buffer_size = %d", arg.proxy_buffer_size); log_notice (" proxy_buffer_timeout = %d", arg.proxy_buffer_timeout); log_notice (" content_length = %d", arg.content_length); log_notice (" forward_port = %d", arg.forward_port); log_notice (" max_connection_age = %d", arg.max_connection_age); log_notice (" use_std = %d", arg.use_std); log_notice (" strict_content_length = %d", arg.strict_content_length); log_notice (" keep_alive = %d", arg.keep_alive); log_notice (" proxy_authorization = %s", arg.proxy_authorization ? arg.proxy_authorization : "(null)"); log_notice (" user_agent = %s", arg.user_agent ? arg.user_agent : "(null)"); log_notice (" debug_level = %d", debug_level); if (arg.forward_port != -1) { struct in_addr addr; addr.s_addr = INADDR_ANY; s = server_socket (addr, arg.forward_port, 0); log_debug ("server_socket (%d) = %d", arg.forward_port, s); if (s == -1) { log_error ("couldn't create server socket: %s", strerror (errno)); log_exit (1); } } #ifdef DEBUG_MODE signal (SIGPIPE, log_sigpipe); #else signal (SIGPIPE, SIG_IGN); #endif for (;;) { time_t last_tunnel_write; if (arg.device) { fd = open_device (arg.device); log_debug ("open_device (\"%s\") = %d", arg.device, fd); if (fd == -1) { log_error ("couldn't open %s: %s", arg.device, strerror (errno)); log_exit (1); } /* Check that fd is not 0 (clash with --stdin-stdout) */ if (fd == 0) { log_notice("changing fd from %d to 3",fd); if (dup2 (fd, 3) != 3) { log_error ("couldn't dup2 (%d, 3): %s",fd,strerror(errno)); log_exit (1); } } } else if (arg.forward_port != -1) { log_debug ("waiting for connection on port %d", arg.forward_port); fd = wait_for_connection_on_socket (s); log_debug ("wait_for_connection_on_socket (%d) = %d", s, fd); if (fd == -1) { log_error ("couldn't forward port %d: %s", arg.forward_port, strerror (errno)); log_exit (1); } /* Check that fd is not 0 (clash with --stdin-stdout) */ if (fd == 0) { log_notice ("changing fd from %d to 3",fd); if (dup2 (fd, 3) != 3) { log_error ("couldn't dup2 (%d, 3): %s",fd,strerror(errno)); log_exit (1); } } } else if (arg.use_std) { log_debug ("using stdin as fd"); fd = 0; if (fcntl(fd,F_SETFL,O_NONBLOCK)==-1) { log_error ("couldn't set stdin to non-blocking mode: %s", strerror(errno)); log_exit (1); } /* Usage of stdout (fd = 1) is checked later. */ } log_debug ("creating a new tunnel"); tunnel = tunnel_new_client (arg.host_name, arg.host_port, arg.proxy_name, arg.proxy_port, arg.content_length); if (tunnel == NULL) { log_error ("couldn't create tunnel"); log_exit (1); } if (tunnel_setopt (tunnel, "strict_content_length", &arg.strict_content_length) == -1) log_debug ("tunnel_setopt strict_content_length error: %s", strerror (errno)); if (tunnel_setopt (tunnel, "keep_alive", &arg.keep_alive) == -1) log_debug ("tunnel_setopt keep_alive error: %s", strerror (errno)); if (tunnel_setopt (tunnel, "max_connection_age", &arg.max_connection_age) == -1) log_debug ("tunnel_setopt max_connection_age error: %s", strerror (errno)); if (arg.proxy_authorization != NULL) { ssize_t len; char *auth; len = encode_base64 (arg.proxy_authorization, strlen (arg.proxy_authorization), &auth); if (len == -1) { log_error ("encode_base64 error: %s", strerror (errno)); } else { char *str = malloc (len + 7); if (str == NULL) { log_error ("out of memory when encoding " "authorization string"); log_exit (1); } strcpy (str, "Basic "); strcat (str, auth); free (auth); if (tunnel_setopt (tunnel, "proxy_authorization", str) == -1) log_error ("tunnel_setopt proxy_authorization error: %s", strerror (errno)); free (str); } } if (arg.user_agent != NULL) { if (tunnel_setopt (tunnel, "user_agent", arg.user_agent) == -1) log_error ("tunnel_setopt user_agent error: %s", strerror (errno)); } if (tunnel_connect (tunnel) == -1) { log_error ("couldn't open tunnel: %s", strerror (errno)); log_exit (1); } if (arg.proxy_name) log_notice ("connected to %s:%d via %s:%d", arg.host_name, arg.host_port, arg.proxy_name, arg.proxy_port); else log_notice ("connected to %s:%d", arg.host_name, arg.host_port); closed = FALSE; time (&last_tunnel_write); while (!closed) { struct pollfd pollfd[2]; int keep_alive_timeout; int timeout; time_t t; int n; pollfd[0].fd = fd; pollfd[0].events = POLLIN; pollfd[1].fd = tunnel_pollin_fd (tunnel); pollfd[1].events = POLLIN; time (&t); timeout = 1000 * (arg.keep_alive - (t - last_tunnel_write)); keep_alive_timeout = TRUE; if (timeout < 0) timeout = 0; if (arg.proxy_buffer_timeout != -1 && arg.proxy_buffer_timeout < timeout) { timeout = arg.proxy_buffer_timeout; keep_alive_timeout = FALSE; } log_annoying ("poll () ..."); n = poll (pollfd, 2, timeout); log_annoying ("... = %d", n); if (n == -1) { log_error ("poll error: %s", strerror (errno)); log_exit (1); } else if (n == 0) { log_verbose ("poll() timed out"); if (keep_alive_timeout) { tunnel_padding (tunnel, 1); time (&last_tunnel_write); } else { if (tunnel_maybe_pad (tunnel, arg.proxy_buffer_size) > 0) time (&last_tunnel_write); } continue; } handle_input ("device or port", tunnel, fd, pollfd[0].revents, handle_device_input, &closed); handle_input ("tunnel", tunnel, fd, pollfd[1].revents, handle_tunnel_input, &closed); if (pollfd[0].revents & POLLIN) time (&last_tunnel_write); } log_debug ("destroying tunnel"); if (fd != 0) { close (fd); } tunnel_destroy (tunnel); if (arg.proxy_name) log_notice ("disconnected from %s:%d via %s:%d", arg.host_name, arg.host_port, arg.proxy_name, arg.proxy_port); else log_notice ("disconnected from %s%d", arg.host_name, arg.host_port); } log_debug ("closing server socket"); close (s); log_exit (0); }
/** * Main Program */ int main(int argc, char **argv) { TelnetDaemon daemon; std::string loginpath; std::string user; std::string login; std::string cdw = get_working_path(); int num = 0; for (int i = 0; ; i++) { if (cdw[i] == '\0') break; if (cdw[i] == '/') num = i; } if (num != 0) { for (int i = 0; i < num+1; i++) { PATH[i] = cdw[i]; } } else { strcpy(PATH,cdw.c_str()); } // If Config Exists Run if (configdataexists()) { parseconfig(); } // Unique filename to pass to BBS for // Reading in Detected Client Terminal. daemon.make_uuid(ENTHRAL_TEMP_PATH); // Lookup info for the passed socket descriptor daemon.get_host_info(); // Parameter for Login Program and User Login ID. int c = '\0'; for (;;) { c = getopt( argc, argv, "l:u:"); if (c == EOF) break; switch (c) { case 'u': user = strdup(optarg); break; case 'l': login = strdup(optarg); break; default: printf("%c\n", c); show_usage(); exit(1); } } if(login.size() > 0) { loginpath = login; login.erase(); } else { loginpath = "/bin/login"; } argv_init[0] = strdup(loginpath.c_str()); argv_init[1] = (char *)daemon.m_hostaddr_string.c_str(); argv_init[2] = (char *)daemon.m_hostname_string.c_str(); // Pass Login user for External Process if(user.size() > 0) { argv_init[3] = strdup("-f"); argv_init[4] = strdup(user.c_str()); } // Filename for passing the TERM to the external program. if(daemon.m_term_passing.size() > 0) { argv_init[5] = strdup(daemon.m_term_passing.c_str()); } // Startup Syslogd. openlog("telnet_daemon", LOG_PID, LOG_SYSLOG); syslog(LOG_INFO, "telnet_daemon in.telnetd PATH: %s", PATH); daemon.errlog((char *)"telnet_daemon in.telnetd PATH: %s", PATH); // Log Connection syslog(LOG_INFO, "telnet_daemon in.telnetd [%s] [Server Path]", loginpath.c_str()); daemon.errlog((char *)"telnet_daemon in.telnetd [%s] [Server Path]", (char *)loginpath.c_str()); syslog(LOG_INFO, "telnet_daemon in.telnetd [IP %s] [Host %s] [Connection Logged]", daemon.m_hostaddr_string.c_str(), daemon.m_hostname_string.c_str() ); daemon.errlog((char *)"telnet_daemon in.telnetd [IP %s] [Host %s] [Connection Logged]", (char *)daemon.m_hostaddr_string.c_str(), (char *)daemon.m_hostname_string.c_str() ); // Send Startup Telnet Sequences to connecting client. // Ready for Terminal / NAWS Detection and setting defaults. daemon.errlog((char *)"send_startup_iac"); daemon.send_startup_iac(); // Look intitial TELOPT codes with (2) second pause then (2) second detection loop // To Catch Terminal Type and NAWS. daemon.errlog((char *)"loop_detection"); daemon.loop_detection(); daemon.errlog((char *)"loop_detection completed."); // Display Detected Term, Rows, Cols. daemon.errlog((char *)"Term Type: %s", (char *)daemon.getTermType().c_str()); daemon.errlog((char *)"Term Cols: %i", daemon.getTermCols()); daemon.errlog((char *)"Term Rows: %i", daemon.getTermRows()); if (daemon.getTermType() == "undetected" || daemon.getTermType() == "VT220" || daemon.getTermType() == "") { daemon.errlog((char *)"No Term Detected, Disconnecting."); closelog(); exit(1); } // Terminal Type Detection completed, write out to file for extrnal program // So the Forked process can read it in. std::ofstream out; out.open(daemon.m_term_passing.c_str(),ios::trunc); if (out.is_open()) { out << daemon.getTermType() << endl; out.close(); } daemon.errlog((char *)"Starting BBS Server forkpty()"); // If the Connection is good, fork and start the BBS pid = forkpty(&ptyfd, NULL, NULL, NULL); daemon.errlog((char *)"ptyfd: %i", ptyfd); // Pid 0 Start Child Process. if (pid == 0) { setsid(); tcsetpgrp(0, getpid()); // exec shell, with correct argv and env execv(loginpath.c_str(), argv_init); syslog(LOG_INFO, "child process created for [IP %s] pid == 0", daemon.m_hostaddr_string.c_str()); daemon.errlog((char *)"child process created for [IP %s] pid == 0", (char*)daemon.m_hostaddr_string.c_str()); exit(1); } // Pid -1 is an error else if(pid == -1) { syslog(LOG_INFO, "fork() Error, exiting [IP %s] pid == -1", daemon.m_hostaddr_string.c_str()); daemon.errlog((char *)"fork() Error, exiting [IP %s] pid == -1", (char*)daemon.m_hostaddr_string.c_str()); closelog(); exit(1); } else if(pid > 0) { // Parent process. syslog(LOG_INFO, "parent process for [IP %s] pid > 0", daemon.m_hostaddr_string.c_str()); daemon.errlog((char *)"parent process for [IP %s] pid > 0", (char*)daemon.m_hostaddr_string.c_str()); } // Setup Detected Screen Size. struct winsize ws; // setup Term init_termbuf(); #ifdef TIOCSWINSZ if (daemon.getTermCols() || daemon.getTermRows()) { memset(&ws, 0, sizeof(ws)); ws.ws_col = daemon.getTermCols(); ws.ws_row = daemon.getTermRows(); ioctl(ptyfd, TIOCSWINSZ, (char *)&ws); } #endif // Start Main Parent Loop for communication with child (BBS) daemon.errlog((char *)"Starting Parent Loop"); daemon.loop_parent_process(ptyfd); daemon.errlog((char *)"Closing Parent Loop"); raise(SIGHUP); syslog(LOG_INFO, "in.telnetd [IP %s] [Closed Connection]", daemon.m_hostaddr_string.c_str()); daemon.errlog((char *)"in.telnetd [IP %s] [Closed Connection]", (char*)daemon.m_hostaddr_string.c_str()); closelog(); remove(daemon.m_term_passing.c_str()); _exit(0); }
int main(int argc, char* argv[]) { struct timeval start; struct timeval mid1; struct timeval mid2; struct timeval mid3; struct timeval end; long int t_open = 0; long int t_read = 0; long int t_write = 0; long int t_close = 0; long int t_create = 0; long int t_rename = 0; long int t_chmod = 0; long int t_remove = 0; long int t_mkdir = 0; long int t_rmdir = 0; long int t_link = 0; long int t_unlink = 0; long int t_getgid = 0; long int t_setgid = 0; long int t_setuid = 0; long int t_getuid = 0; long int t_getpid = 0; long int t_syslog = 0; long int t_time = 0; long int t_chown = 0; char buf1[] = "wow, such window~"; char buf2[17]; int fd_temp; gid_t gid_temp; uid_t uid_temp; pid_t pid_temp; time_t time_temp; //---------------------correction for gettimeofday--------- int i =0; for(i; i<1000; i++) { gettimeofday(&start,NULL); gettimeofday(&mid1, NULL); } //--------------------- create ------------------- i = 0; for( i; i< 1000; i++) { gettimeofday(&start, NULL); fd_temp = creat("/tmp/test1.dat", O_CREAT); gettimeofday(&mid1, NULL); rename("/tmp/test1.dat", "/tmp/test2.dat"); gettimeofday(&mid2, NULL); chmod("/tmp/test2.dat", S_ISGID); gettimeofday(&mid3, NULL); remove("/tmp/test1.dat"); gettimeofday(&end, NULL); t_create += check_time( &start, &mid1); t_rename += check_time( &mid1, &mid2); t_chmod += check_time(&mid2, &mid3); t_remove += check_time(&mid3, &end); } printf("t_reanme: %ld\n", t_rename); printf("t_chmod: %ld\n", t_chmod); printf("t_remove: %ld\n", t_remove); //---------------- open read write close ------------------- i = 0; for(i; i < 1000; i ++) { gettimeofday(&start,NULL); fd_temp = open("/tmp/test.dat", O_CREAT|O_RDWR); gettimeofday(&mid1, NULL); write( fd_temp, buf1, 17); gettimeofday(&mid2, NULL); read( fd_temp, buf2, 17); gettimeofday(&mid3, NULL); close(fd_temp); gettimeofday(&end, NULL); t_open += check_time(&start, &mid1); t_write += check_time(&mid1, &mid2); t_read += check_time(&mid2, &mid3); t_close += check_time(&mid3, &end); } printf("t_open: %ld\n", t_open); printf("t_write: %ld\n", t_write); printf("t_read: %ld\n", t_read); printf("t_close: %ld\n", t_close); printf("t_create: %ld\n", t_create); //----------------- mkdir rmdir link unlink -------- i = 0; for( i; i<1000; i++) { gettimeofday(&start,NULL); mkdir("/tmp/test", S_IRWXU); gettimeofday(&mid1, NULL); rmdir("/tmp/test"); gettimeofday(&mid2, NULL); link("/tmp/test1.dat","/tmp/test2"); gettimeofday(&mid3, NULL); unlink("/tmp/test2"); gettimeofday(&end, NULL); t_mkdir += check_time(&start, &mid1); t_rmdir += check_time(&mid1, &mid2); t_link += check_time(&mid2, &mid3); t_unlink += check_time(&mid3, &end); } printf("t_mkdir: %ld\n", t_mkdir); printf("t_rmdir: %ld\n", t_rmdir); printf("t_link: %ld\n", t_link); printf("t_unlink: %ld\n", t_unlink); //-------------------- getuid setuid getgid setgid----- i = 0; for( i; i<1000; i++) { gettimeofday(&start, NULL); gid_temp = getgid(); gettimeofday(&mid1, NULL); uid_temp = getuid(); gettimeofday(&mid2, NULL); setgid(gid_temp); gettimeofday(&mid3, NULL); setuid(uid_temp); gettimeofday(&end, NULL); t_getgid += check_time(&start, &mid1); t_getuid += check_time(&mid1, &mid2); t_setgid += check_time(&mid2, &mid3); t_setuid += check_time(&mid3, &end); } printf("t_getgid: %ld\n", t_getgid); printf("t_getuid: %ld\n", t_getuid); printf("t_setgid: %ld\n", t_setgid); printf("t_setuid: %ld\n", t_setuid); //--------------------getpid syslog chown time---------- openlog ("/tmp/testlog", LOG_CONS | LOG_PID | LOG_NDELAY, LOG_LOCAL1); i = 0; for( i; i<1000; i++) { gettimeofday(&start, NULL); pid_temp = getpid(); gettimeofday(&mid1, NULL); syslog (LOG_INFO, "Wow~\t"); gettimeofday(&mid2, NULL); chown("/tmp/testlog", 0,0); gettimeofday(&mid3, NULL); time_temp = time(); gettimeofday(&end, NULL); t_getpid += check_time(&start, &mid1); t_chown += check_time(&mid1, &mid2); t_syslog += check_time(&mid2, &mid3); t_time += check_time(&mid3, &end); } printf("t_getpid: %ld\n", t_getpid); printf("t_syslog: %ld\n", t_syslog); printf("t_time: %ld\n", t_time); printf("t_chown: %ld\n", t_chown); }
int main(int argc, char *argv[]) { int exitcode = EXIT_FAILURE; struct sigaction sa; char *device = NULL, *snoop = NULL; int device_fd; struct epoll_event device_event; int dd, opt, detach = 1; while ((opt=getopt_long(argc, argv, "d:s:nh", options, NULL)) != EOF) { switch(opt) { case 'd': device = strdup(optarg); break; case 's': snoop = strdup(optarg); break; case 'n': detach = 0; break; case 'h': usage(); exit(0); default: usage(); exit(1); } } argc -= optind; argv += optind; optind = 0; if (argc < 1) { usage(); exit(1); } if (getbdaddrbyname(argv[0], &vdev.bdaddr) < 0) exit(1); if (detach) { if (daemon(0, 0)) { perror("Can't start daemon"); exit(1); } } /* Start logging to syslog and stderr */ openlog("hciemu", LOG_PID | LOG_NDELAY | LOG_PERROR, LOG_DAEMON); syslog(LOG_INFO, "HCI emulation daemon ver %s started", VERSION); memset(&sa, 0, sizeof(sa)); sa.sa_flags = SA_NOCLDSTOP; sa.sa_handler = SIG_IGN; sigaction(SIGCHLD, &sa, NULL); sigaction(SIGPIPE, &sa, NULL); sa.sa_handler = sig_term; sigaction(SIGTERM, &sa, NULL); sigaction(SIGINT, &sa, NULL); if (!device) device = strdup(VHCI_DEV); /* Open and create virtual HCI device */ device_fd = open(device, O_RDWR); if (device_fd < 0) { syslog(LOG_ERR, "Can't open device %s: %s (%d)", device, strerror(errno), errno); free(device); return exitcode; } free(device); /* Create snoop file */ if (snoop) { dd = create_snoop(snoop); if (dd < 0) syslog(LOG_ERR, "Can't create snoop file %s: %s (%d)", snoop, strerror(errno), errno); free(snoop); } else dd = -1; /* Create event loop */ epoll_fd = epoll_create1(EPOLL_CLOEXEC); if (epoll_fd < 0) { perror("Failed to create epoll descriptor"); goto close_device; } reset_vdev(); vdev.dev_fd = device_fd; vdev.dd = dd; memset(&device_event, 0, sizeof(device_event)); device_event.events = EPOLLIN; device_event.data.fd = device_fd; if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, device_fd, &device_event) < 0) { perror("Failed to setup device event watch"); goto close_device; } setpriority(PRIO_PROCESS, 0, -19); /* Start event processor */ for (;;) { struct epoll_event events[MAX_EPOLL_EVENTS]; int n, nfds; if (__io_canceled) break; nfds = epoll_wait(epoll_fd, events, MAX_EPOLL_EVENTS, -1); if (nfds < 0) continue; for (n = 0; n < nfds; n++) { if (events[n].data.fd == vdev.dev_fd) io_hci_data(); else if (events[n].data.fd == vdev.scan_fd) io_conn_ind(); } } exitcode = EXIT_SUCCESS; epoll_ctl(epoll_fd, EPOLL_CTL_DEL, device_fd, NULL); close_device: close(device_fd); if (dd >= 0) close(dd); close(epoll_fd); syslog(LOG_INFO, "Exit"); return exitcode; }
int main(int argc, char *argv[]) { SVCXPRT *transp; int ok; struct sockaddr_storage from; socklen_t fromlen; if (argc == 2) closedown = atoi(argv[1]); if (closedown <= 0) closedown = 20; /* * See if inetd started us */ fromlen = sizeof(from); if (getsockname(0, (struct sockaddr *)&from, &fromlen) < 0) { from_inetd = 0; } if (!from_inetd) { daemon(0, 0); (void)rpcb_unset(RSTATPROG, RSTATVERS_TIME, NULL); (void)rpcb_unset(RSTATPROG, RSTATVERS_SWTCH, NULL); (void)rpcb_unset(RSTATPROG, RSTATVERS_ORIG, NULL); (void) signal(SIGINT, cleanup); (void) signal(SIGTERM, cleanup); (void) signal(SIGHUP, cleanup); } openlog("rpc.rstatd", LOG_CONS|LOG_PID, LOG_DAEMON); if (from_inetd) { transp = svc_tli_create(0, NULL, NULL, 0, 0); if (transp == NULL) { syslog(LOG_ERR, "cannot create udp service."); exit(1); } ok = svc_reg(transp, RSTATPROG, RSTATVERS_TIME, rstat_service, NULL); } else ok = svc_create(rstat_service, RSTATPROG, RSTATVERS_TIME, "udp"); if (!ok) { syslog(LOG_ERR, "unable to register (RSTATPROG, RSTATVERS_TIME, %s)", (!from_inetd)?"udp":"(inetd)"); exit(1); } if (from_inetd) ok = svc_reg(transp, RSTATPROG, RSTATVERS_SWTCH, rstat_service, NULL); else ok = svc_create(rstat_service, RSTATPROG, RSTATVERS_SWTCH, "udp"); if (!ok) { syslog(LOG_ERR, "unable to register (RSTATPROG, RSTATVERS_SWTCH, %s)", (!from_inetd)?"udp":"(inetd)"); exit(1); } if (from_inetd) ok = svc_reg(transp, RSTATPROG, RSTATVERS_ORIG, rstat_service, NULL); else ok = svc_create(rstat_service, RSTATPROG, RSTATVERS_ORIG, "udp"); if (!ok) { syslog(LOG_ERR, "unable to register (RSTATPROG, RSTATVERS_ORIG, %s)", (!from_inetd)?"udp":"(inetd)"); exit(1); } svc_run(); syslog(LOG_ERR, "svc_run returned"); exit(1); }
int server_main(char *home, char *dev, char *port, int udp, int ipv4, int log) { int lfd = -1, kdpfd, nfds, nfd, curfds, efd[2], refd[2], tunfd, i; unsigned int cpus = 0, threads, udp_cpu = 0; ssize_t ret; struct epoll_event *events; struct addrinfo hints, *ahead, *ai; auth_log = !!log; openlog("curvetun", LOG_PID | LOG_CONS | LOG_NDELAY, LOG_DAEMON); syslog(LOG_INFO, "curvetun server booting!\n"); syslog_maybe(!auth_log, LOG_INFO, "curvetun user logging disabled!\n"); parse_userfile_and_generate_user_store_or_die(home); memset(&hints, 0, sizeof(hints)); hints.ai_family = PF_UNSPEC; hints.ai_socktype = udp ? SOCK_DGRAM : SOCK_STREAM; hints.ai_protocol = udp ? IPPROTO_UDP : IPPROTO_TCP; hints.ai_flags = AI_PASSIVE; ret = getaddrinfo(NULL, port, &hints, &ahead); if (ret < 0) syslog_panic("Cannot get address info!\n"); for (ai = ahead; ai != NULL && lfd < 0; ai = ai->ai_next) { lfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); if (lfd < 0) continue; if (ai->ai_family == AF_INET6) { #ifdef IPV6_V6ONLY ret = set_ipv6_only(lfd); if (ret < 0) { close(lfd); lfd = -1; continue; } #else close(lfd); lfd = -1; continue; #endif /* IPV6_V6ONLY */ } set_reuseaddr(lfd); set_mtu_disc_dont(lfd); ret = bind(lfd, ai->ai_addr, ai->ai_addrlen); if (ret < 0) { close(lfd); lfd = -1; continue; } if (!udp) { ret = listen(lfd, 5); if (ret < 0) { close(lfd); lfd = -1; continue; } } if (ipv4 == -1) { ipv4 = (ai->ai_family == AF_INET6 ? 0 : (ai->ai_family == AF_INET ? 1 : -1)); } syslog_maybe(auth_log, LOG_INFO, "curvetun on IPv%d via %s " "on port %s!\n", ai->ai_family == AF_INET ? 4 : 6, udp ? "UDP" : "TCP", port); syslog_maybe(auth_log, LOG_INFO, "Allowed overlay proto is " "IPv%d!\n", ipv4 ? 4 : 6); } freeaddrinfo(ahead); if (lfd < 0 || ipv4 < 0) syslog_panic("Cannot create socket!\n"); tunfd = tun_open_or_die(dev ? dev : DEVNAME_SERVER, IFF_TUN | IFF_NO_PI); pipe_or_die(efd, O_NONBLOCK); pipe_or_die(refd, O_NONBLOCK); set_nonblocking(lfd); events = xzmalloc(MAX_EPOLL_SIZE * sizeof(*events)); for (i = 0; i < MAX_EPOLL_SIZE; ++i) events[i].data.fd = -1; kdpfd = epoll_create(MAX_EPOLL_SIZE); if (kdpfd < 0) syslog_panic("Cannot create socket!\n"); set_epoll_descriptor(kdpfd, EPOLL_CTL_ADD, lfd, udp ? EPOLLIN | EPOLLET | EPOLLONESHOT : EPOLLIN); set_epoll_descriptor(kdpfd, EPOLL_CTL_ADD, efd[0], EPOLLIN); set_epoll_descriptor(kdpfd, EPOLL_CTL_ADD, refd[0], EPOLLIN); set_epoll_descriptor(kdpfd, EPOLL_CTL_ADD, tunfd, EPOLLIN | EPOLLET | EPOLLONESHOT); curfds = 4; trie_init(); cpus = get_number_cpus_online(); threads = cpus * THREADS_PER_CPU; if (!ispow2(threads)) syslog_panic("Thread number not power of two!\n"); threadpool = xzmalloc(sizeof(*threadpool) * threads); thread_spawn_or_panic(cpus, efd[1], refd[1], tunfd, ipv4, udp); init_cpusched(threads); register_socket(tunfd); register_socket(lfd); syslog(LOG_INFO, "curvetun up and running!\n"); while (likely(!sigint)) { nfds = epoll_wait(kdpfd, events, curfds, -1); if (nfds < 0) { syslog(LOG_ERR, "epoll_wait error: %s\n", strerror(errno)); break; } for (i = 0; i < nfds; ++i) { if (unlikely(events[i].data.fd < 0)) continue; if (events[i].data.fd == lfd && !udp) { int ncpu; char hbuff[256], sbuff[256]; struct sockaddr_storage taddr; socklen_t tlen; tlen = sizeof(taddr); nfd = accept(lfd, (struct sockaddr *) &taddr, &tlen); if (nfd < 0) { syslog(LOG_ERR, "accept error: %s\n", strerror(errno)); continue; } if (curfds + 1 > MAX_EPOLL_SIZE) { close(nfd); continue; } curfds++; ncpu = register_socket(nfd); memset(hbuff, 0, sizeof(hbuff)); memset(sbuff, 0, sizeof(sbuff)); getnameinfo((struct sockaddr *) &taddr, tlen, hbuff, sizeof(hbuff), sbuff, sizeof(sbuff), NI_NUMERICHOST | NI_NUMERICSERV); syslog_maybe(auth_log, LOG_INFO, "New connection " "from %s:%s with id %d on CPU%d, %d " "active!\n", hbuff, sbuff, nfd, ncpu, curfds); set_nonblocking(nfd); set_socket_keepalive(nfd); set_tcp_nodelay(nfd); ret = set_epoll_descriptor2(kdpfd, EPOLL_CTL_ADD, nfd, EPOLLIN | EPOLLET | EPOLLONESHOT); if (ret < 0) { close(nfd); curfds--; continue; } } else if (events[i].data.fd == refd[0]) { int fd_one; ret = read_exact(refd[0], &fd_one, sizeof(fd_one), 1); if (ret != sizeof(fd_one) || fd_one <= 0) continue; ret = set_epoll_descriptor2(kdpfd, EPOLL_CTL_MOD, fd_one, EPOLLIN | EPOLLET | EPOLLONESHOT); if (ret < 0) { close(fd_one); continue; } } else if (events[i].data.fd == efd[0]) { int fd_del, test; ret = read_exact(efd[0], &fd_del, sizeof(fd_del), 1); if (ret != sizeof(fd_del) || fd_del <= 0) continue; ret = read(fd_del, &test, sizeof(test)); if (ret < 0 && errno == EBADF) continue; ret = set_epoll_descriptor2(kdpfd, EPOLL_CTL_DEL, fd_del, 0); if (ret < 0) { close(fd_del); continue; } close(fd_del); curfds--; unregister_socket(fd_del); syslog_maybe(auth_log, LOG_INFO, "Closed connection " "with id %d, %d active!\n", fd_del, curfds); } else { int cpu, fd_work = events[i].data.fd; if (!udp) cpu = socket_to_cpu(fd_work); else udp_cpu = (udp_cpu + 1) & (threads - 1); write_exact(threadpool[udp ? udp_cpu : cpu].efd[1], &fd_work, sizeof(fd_work), 1); } } } syslog(LOG_INFO, "curvetun prepare shut down!\n"); close(lfd); close(efd[0]); close(efd[1]); close(refd[0]); close(refd[1]); close(tunfd); thread_finish(cpus); xfree(threadpool); xfree(events); unregister_socket(lfd); unregister_socket(tunfd); destroy_cpusched(); trie_cleanup(); destroy_user_store(); syslog(LOG_INFO, "curvetun shut down!\n"); closelog(); return 0; }
/* * logger -- read and log utility * * Reads from an input and arranges to write the result on the system * log. */ int main(int argc, char **argv) { int ch, logflags, pri; char *tag, *host, buf[1024]; tag = NULL; host = NULL; pri = LOG_USER | LOG_NOTICE; logflags = 0; unsetenv("TZ"); while ((ch = getopt(argc, argv, "46Af:h:ip:st:")) != -1) switch(ch) { case '4': family = PF_INET; break; #ifdef INET6 case '6': family = PF_INET6; break; #endif case 'A': send_to_all++; break; case 'f': /* file to log */ if (freopen(optarg, "r", stdin) == NULL) err(1, "%s", optarg); break; case 'h': /* hostname to deliver to */ host = optarg; break; case 'i': /* log process id also */ logflags |= LOG_PID; break; case 'p': /* priority */ pri = pencode(optarg); break; case 's': /* log to standard error */ logflags |= LOG_PERROR; break; case 't': /* tag */ tag = optarg; break; case '?': default: usage(); } argc -= optind; argv += optind; /* setup for logging */ openlog(tag ? tag : getlogin(), logflags, 0); fclose(stdout); /* log input line if appropriate */ if (argc > 0) { char *p, *endp; size_t len; for (p = buf, endp = buf + sizeof(buf) - 2; *argv;) { len = strlen(*argv); if (p + len > endp && p > buf) { logmessage(pri, host, buf); p = buf; } if (len > sizeof(buf) - 1) logmessage(pri, host, *argv++); else { if (p != buf) *p++ = ' '; bcopy(*argv++, p, len); *(p += len) = '\0'; } } if (p != buf) logmessage(pri, host, buf); } else while (fgets(buf, sizeof(buf), stdin) != NULL) logmessage(pri, host, buf); exit(0); }