Exemplo n.º 1
0
// Main
int main(int argc, char *argv[]) {
    char pass[MAXPASS + 1];
    int npass;
    int retval = EXIT_FAILURE;
    int debug = 0;
    int ch;
    char *user = NULL;

    /*
     * Catch or ignore as many signal as possible.
     */
    setup_signals();

    /* loop through each command line var and process it */
    while((ch = getopt(argc, argv, "d")) != -1) {
        switch(ch) {
            case 'd': /* Set debug mode on */
                debug = 1;
                break;
        }
    }
    
    /* there should be at least one left over argument */
    if (optind < argc) {
        /* grab the first additional argument as the user name */
        user = strdup(argv[optind]);
    }

    /*
     * we establish that this program is running with non-tty stdin.
     * this is to discourage casual use. It does *NOT* prevent an
     * intruder from repeatadly running this program to determine the
     * OTP/passcode of the current user (brute force attack, but one for
     * which the attacker must already have gained access to the user's
     * account).
     */
    if (isatty(STDIN_FILENO) || user == NULL ) {
        syslog(LOG_AUTH
            ,"inappropriate use of Unix helper binary [UID=%d]"
            ,getuid());
        fprintf(stderr
            ,"This binary is not designed for running in this way\n"
             "-- the system administrator has been informed\n");
        sleep(10);    // this should discourage/annoy the user
        return EXIT_FAILURE;
    }

    /*
     * Determine what the current user's name is.
     * On a SELinux enabled system with a strict policy leaving the
     * existing check prevents shadow password authentication from working.
     * We must thus skip the check if the real uid is 0.
     */
    if (getuid() != 0) {
        /* if the caller specifies the username, verify that user
         matches it */
        if (strcmp(user, getuidname(getuid()))) {
            syslog(LOG_AUTH
                ,"mismatch of %s|%s", user, getuidname(getuid()));
            free(user);
            return EXIT_FAILURE;
        }
    }

    /* read the OTP/passcode from stdin (a pipe from the pam_yubikey module) */
    npass = read(STDIN_FILENO, pass, MAXPASS);

    if (npass < 0) {    /* is it a valid OTP/passcode? */
        syslog(LOG_DEBUG, "no OTP/passcode supplied");
    } else if (npass >= MAXPASS) {
        syslog(LOG_DEBUG, "OTP/passcode too long");
    } else {
        pass[npass] = '\0';    /* NUL terminate */
        retval = _yubi_verify_otp_passcode(user, pass, debug);
    }

    memset(pass, '\0', MAXPASS);    /* clear memory of the OTP/passcode */

    /* return pass or fail */
    if ((retval != EXIT_SUCCESS) && (retval != 128)) {
        syslog(LOG_AUTH, "OTP/passcode check failed for user (%s)", user);
        free(user);
        return EXIT_FAILURE;
    }
    
    free(user);
    return retval;
}
Exemplo n.º 2
0
int
main (int argc, char *argv[])
{
	char *bad_domains = NULL;
	GError *error = NULL;
	gboolean wrote_pidfile = FALSE;
	gs_free char *pidfile = NULL;
	gs_unref_object NMDhcpClient *dhcp4_client = NULL;
	gs_unref_object NMRDisc *rdisc = NULL;
	GByteArray *hwaddr = NULL;
	size_t hwaddr_len = 0;
	gconstpointer tmp;
	gs_free NMUtilsIPv6IfaceId *iid = NULL;

	nm_g_type_init ();

	setpgid (getpid (), getpid ());

	do_early_setup (&argc, &argv);

	if (global_opt.g_fatal_warnings) {
		GLogLevelFlags fatal_mask;

		fatal_mask = g_log_set_always_fatal (G_LOG_FATAL_MASK);
		fatal_mask |= G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL;
		g_log_set_always_fatal (fatal_mask);
	}

	if (global_opt.show_version) {
		fprintf (stdout, NM_DIST_VERSION "\n");
		exit (0);
	}

	nm_main_utils_ensure_root ();

	if (!global_opt.ifname || !global_opt.uuid) {
		fprintf (stderr, _("An interface name and UUID are required\n"));
		exit (1);
	}

	ifindex = if_nametoindex (global_opt.ifname);
	if (ifindex <= 0) {
		fprintf (stderr, _("Failed to find interface index for %s (%s)\n"), global_opt.ifname, strerror (errno));
		exit (1);
	}
	pidfile = g_strdup_printf (NMIH_PID_FILE_FMT, ifindex);
	nm_main_utils_ensure_not_running_pidfile (pidfile);

	nm_main_utils_ensure_rundir ();

	if (!nm_logging_setup (global_opt.opt_log_level,
	                       global_opt.opt_log_domains,
	                       &bad_domains,
	                       &error)) {
		fprintf (stderr,
		         _("%s.  Please use --help to see a list of valid options.\n"),
		         error->message);
		exit (1);
	} else if (bad_domains) {
		fprintf (stderr,
		         _("Ignoring unrecognized log domain(s) '%s' passed on command line.\n"),
		         bad_domains);
		g_clear_pointer (&bad_domains, g_free);
	}

	if (global_opt.become_daemon && !global_opt.debug) {
		if (daemon (0, 0) < 0) {
			int saved_errno;

			saved_errno = errno;
			fprintf (stderr, _("Could not daemonize: %s [error %u]\n"),
			         g_strerror (saved_errno),
			         saved_errno);
			exit (1);
		}
		if (nm_main_utils_write_pidfile (pidfile))
			wrote_pidfile = TRUE;
	}

	/* Set up unix signal handling - before creating threads, but after daemonizing! */
	main_loop = g_main_loop_new (NULL, FALSE);
	setup_signals ();

	nm_logging_syslog_openlog (global_opt.logging_backend
	                           ? global_opt.logging_backend
	                           : (global_opt.debug ? "debug" : NULL));

	nm_log_info (LOGD_CORE, "nm-iface-helper (version " NM_DIST_VERSION ") is starting...");

	/* Set up platform interaction layer */
	nm_linux_platform_setup ();

	tmp = nm_platform_link_get_address (NM_PLATFORM_GET, ifindex, &hwaddr_len);
	if (tmp) {
		hwaddr = g_byte_array_sized_new (hwaddr_len);
		g_byte_array_append (hwaddr, tmp, hwaddr_len);
	}

	if (global_opt.iid_str) {
		GBytes *bytes;
		gsize ignored = 0;

		bytes = nm_utils_hexstr2bin (global_opt.iid_str);
		if (!bytes || g_bytes_get_size (bytes) != sizeof (*iid)) {
			fprintf (stderr, _("(%s): Invalid IID %s\n"), global_opt.ifname, global_opt.iid_str);
			exit (1);
		}
		iid = g_bytes_unref_to_data (bytes, &ignored);
	}

	if (global_opt.dhcp4_address) {
		nm_platform_sysctl_set (NM_PLATFORM_GET, nm_utils_ip4_property_path (global_opt.ifname, "promote_secondaries"), "1");

		dhcp4_client = nm_dhcp_manager_start_ip4 (nm_dhcp_manager_get (),
		                                          global_opt.ifname,
		                                          ifindex,
		                                          hwaddr,
		                                          global_opt.uuid,
		                                          global_opt.priority_v4,
		                                          !!global_opt.dhcp4_hostname,
		                                          global_opt.dhcp4_hostname,
		                                          global_opt.dhcp4_clientid,
		                                          45,
		                                          NULL,
		                                          global_opt.dhcp4_address);
		g_assert (dhcp4_client);
		g_signal_connect (dhcp4_client,
		                  NM_DHCP_CLIENT_SIGNAL_STATE_CHANGED,
		                  G_CALLBACK (dhcp4_state_changed),
		                  NULL);
	}

	if (global_opt.slaac) {
		nm_platform_link_set_user_ipv6ll_enabled (NM_PLATFORM_GET, ifindex, TRUE);

		rdisc = nm_lndp_rdisc_new (ifindex, global_opt.ifname, global_opt.uuid, global_opt.addr_gen_mode);
		g_assert (rdisc);

		if (iid)
			nm_rdisc_set_iid (rdisc, *iid);

		nm_platform_sysctl_set (NM_PLATFORM_GET, nm_utils_ip6_property_path (global_opt.ifname, "accept_ra"), "1");
		nm_platform_sysctl_set (NM_PLATFORM_GET, nm_utils_ip6_property_path (global_opt.ifname, "accept_ra_defrtr"), "0");
		nm_platform_sysctl_set (NM_PLATFORM_GET, nm_utils_ip6_property_path (global_opt.ifname, "accept_ra_pinfo"), "0");
		nm_platform_sysctl_set (NM_PLATFORM_GET, nm_utils_ip6_property_path (global_opt.ifname, "accept_ra_rtr_pref"), "0");

		g_signal_connect (NM_PLATFORM_GET,
		                  NM_PLATFORM_SIGNAL_IP6_ADDRESS_CHANGED,
		                  G_CALLBACK (ip6_address_changed),
		                  rdisc);
		g_signal_connect (rdisc,
		                  NM_RDISC_CONFIG_CHANGED,
		                  G_CALLBACK (rdisc_config_changed),
		                  NULL);
		g_signal_connect (rdisc,
		                  NM_RDISC_RA_TIMEOUT,
		                  G_CALLBACK (rdisc_ra_timeout),
		                  NULL);
		nm_rdisc_start (rdisc);
	}

	g_main_loop_run (main_loop);

	g_clear_pointer (&hwaddr, g_byte_array_unref);

	if (pidfile && wrote_pidfile)
		unlink (pidfile);

	nm_log_info (LOGD_CORE, "exiting");
	exit (0);
}
Exemplo n.º 3
0
int main(int argc,char *argv[])
{
   vm_instance_t *vm;

#ifdef PROFILE
   atexit(profiler_savestat);
#endif

   printf("Cisco Router Simulation Platform (version %s)\n",sw_version);
   printf("Copyright (c) 2005-2007 Christophe Fillot.\n");
   printf("Build date: %s %s\n\n",__DATE__,__TIME__);

   /* Register platforms */
   register_default_platforms();

   /* Initialize timers */
   timer_init();

   /* Initialize object registry */
   registry_init();
   
   /* Initialize ATM module (for HEC checksums) */
   atm_init();

   /* Initialize CRC functions */
   crc_init();

   /* Initialize NetIO code */
   netio_rxl_init();

   /* Initialize NetIO packet filters */
   netio_filter_load_all();

   /* Initialize VTTY code */
   vtty_init();
   
   /* Parse standard command line */
   if (!run_hypervisor(argc,argv))
      parse_std_cmd_line(argc,argv);

   /* Create general log file */
   create_log_file();

   /* Periodic tasks initialization */
   if (ptask_init(0) == -1)
      exit(EXIT_FAILURE);

   /* Create instruction lookup tables */
   mips64_jit_create_ilt();
   mips64_exec_create_ilt();
   ppc32_jit_create_ilt();
   ppc32_exec_create_ilt();
   
   setup_signals();

   if (!hypervisor_mode) {
      /* Initialize the default instance */
      vm = vm_acquire("default");
      assert(vm != NULL);

      if (vm->platform->init_instance(vm) == -1) {
         fprintf(stderr,"Unable to initialize router instance.\n");
         exit(EXIT_FAILURE);
      }

      /* Start GDB server before the image to allow debugging from
         the begining of it's execution */ 
      if (vm->gdb_server_running)
      {
        /* Stop main CPU */
        vm_suspend(vm);
//         cpu_stop(vm->boot_cpu);
      
        if (gdb_server_start_listener(vm) < 0) {
            fprintf(stderr,"GDB server unable to create TCP sockets.\n");
            exit(EXIT_FAILURE);
        }
      }

#if (DEBUG_INSN_PERF_CNT > 0) || (DEBUG_BLOCK_PERF_CNT > 0)
      {
         m_uint32_t counter,prev = 0,delta;
         while(vm->status == VM_STATUS_RUNNING) {
            counter = cpu_get_perf_counter(vm->boot_cpu);
            delta = counter - prev;
            prev = counter;
            printf("delta = %u\n",delta);
            sleep(1);
         }
      }
#else
      /* Start instance monitoring */
      vm_monitor(vm);
#endif

      // FIXME: remove this kludge
      if (vm->gdb_server_running)
      {
         //while (vm->gdb_conn->active)
         //   usleep(1000000);
         gdb_server_close_control_sockets();
      }

      /* Free resources used by instance */
      vm_release(vm);

   } else {
      hypervisor_tcp_server(hypervisor_ip_address,hypervisor_tcp_port);
   }

   dynamips_reset();
   close_log_file();
   return(0);
}
Exemplo n.º 4
0
int
main(int argc, char *argv[])
{
	/* TODO: refactor main() function */

	char dir[PATH_MAX];
	char lwin_path[PATH_MAX] = "";
	char rwin_path[PATH_MAX] = "";
	int lwin_handle = 0, rwin_handle = 0;
	int old_config;
	int no_configs;

	init_config();

	if(is_in_string_array(argv + 1, argc - 1, "--logging"))
	{
		init_logger(1);
	}

	(void)setlocale(LC_ALL, "");
	if(getcwd(dir, sizeof(dir)) == NULL)
	{
		perror("getcwd");
		return -1;
	}
#ifdef _WIN32
	to_forward_slash(dir);
#endif

	init_filelists();
	init_registers();
	set_config_paths();
	reinit_logger();

	init_commands();
	init_builtin_functions();
	update_path_env(1);

	if(init_status() != 0)
	{
		puts("Error during session status initialization.");
		return -1;
	}

	no_configs = is_in_string_array(argv + 1, argc - 1, "--no-configs");

	/* Tell file type module what function to use to check availability of
	 * external programs. */
	config_filetypes(&external_command_exists);
	/* This should be called before loading any configuration file. */
	reset_all_file_associations(curr_stats.env_type == ENVTYPE_EMULATOR_WITH_X);

	init_option_handlers();

	old_config = is_old_config();
	if(!old_config && !no_configs)
		read_info_file(0);

	ipc_pre_init();

	parse_args(argc, argv, dir, lwin_path, rwin_path, &lwin_handle, &rwin_handle);

	ipc_init(&parse_recieved_arguments);

	init_background();

	set_view_path(&lwin, lwin_path);
	set_view_path(&rwin, rwin_path);

	/* Force view switch when path is specified for invisible pane. */
	if(lwin_path[0] != '\0' && rwin_path[0] == '\0' && curr_view != &lwin)
	{
		change_window();
	}

	load_initial_directory(&lwin, dir);
	load_initial_directory(&rwin, dir);

	/* Force split view when two paths are specified on command-line. */
	if(lwin_path[0] != '\0' && rwin_path[0] != '\0')
	{
		curr_stats.number_of_windows = 2;
	}

	/* Setup the ncurses interface. */
	if(!setup_ncurses_interface())
		return -1;

	colmgr_init(COLOR_PAIRS);
	init_modes();
	init_undo_list(&perform_operation, NULL, &cfg.undo_levels);
	load_local_options(curr_view);

	curr_stats.load_stage = 1;

	if(!old_config && !no_configs)
	{
		load_scheme();
		source_config();
	}

	write_color_scheme_file();
	setup_signals();

	if(old_config && !no_configs)
	{
		convert_configs();

		curr_stats.load_stage = 0;
		read_info_file(0);
		curr_stats.load_stage = 1;

		set_view_path(&lwin, lwin_path);
		set_view_path(&rwin, rwin_path);

		load_initial_directory(&lwin, dir);
		load_initial_directory(&rwin, dir);

		source_config();
	}

	(void)create_trash_dir(cfg.trash_dir);

	check_path_for_file(&lwin, lwin_path, lwin_handle);
	check_path_for_file(&rwin, rwin_path, rwin_handle);

	curr_stats.load_stage = 2;

	exec_startup_commands(argc, argv);
	update_screen(UT_FULL);
	modes_update();

	/* Update histories of the views to ensure that their current directories,
	 * which might have been set using command-line parameters, are stored in the
	 * history.  This is not done automatically as history manipulation should be
	 * postponed until views are fully loaded, otherwise there is no correct
	 * information about current file and relative cursor position. */
	save_view_history(&lwin, NULL, NULL, -1);
	save_view_history(&rwin, NULL, NULL, -1);

	curr_stats.load_stage = 3;

	main_loop();

	return 0;
}
Exemplo n.º 5
0
int main(int argc,char *argv[])
{
    vm_instance_t *vm;

#ifdef PROFILE
    atexit(profiler_savestat);
#endif

#ifdef USE_UNSTABLE
    printf("Cisco Router Simulation Platform (version %s/%s unstable)\n",
           sw_version,os_name);
#else
    printf("Cisco Router Simulation Platform (version %s/%s stable)\n",
           sw_version,os_name);
#endif

    printf("Copyright (c) 2005-2011 Christophe Fillot.\n");
    printf("Build date: %s %s\n\n",__DATE__,__TIME__);

    gen_uuid_init();

    /* Register platforms */
    register_default_platforms();

    /* Initialize timers */
    timer_init();

    /* Initialize object registry */
    registry_init();

    /* Initialize ATM module (for HEC checksums) */
    atm_init();

    /* Initialize CRC functions */
    crc_init();

    /* Initialize NetIO code */
    netio_rxl_init();

    /* Initialize NetIO packet filters */
    netio_filter_load_all();

    /* Initialize VTTY code */
    vtty_init();

    /* Parse standard command line */
    atexit(destroy_cmd_line_vars);
    if (!run_hypervisor(argc,argv))
        parse_std_cmd_line(argc,argv);

    /* Create general log file */
    create_log_file();

    /* Periodic tasks initialization */
    if (ptask_init(0) == -1)
        exit(EXIT_FAILURE);

    /* Create instruction lookup tables */
    mips64_jit_create_ilt();
    mips64_exec_create_ilt();
    ppc32_jit_create_ilt();
    ppc32_exec_create_ilt();

    setup_signals();

    if (!hypervisor_mode) {
        /* Initialize the default instance */
        vm = vm_acquire("default");
        assert(vm != NULL);

        if (vm_init_instance(vm) == -1) {
            fprintf(stderr,"Unable to initialize router instance.\n");
            exit(EXIT_FAILURE);
        }

#if (DEBUG_INSN_PERF_CNT > 0) || (DEBUG_BLOCK_PERF_CNT > 0)
        {
            m_uint32_t counter,prev = 0,delta;
            while(vm->status == VM_STATUS_RUNNING) {
                counter = cpu_get_perf_counter(vm->boot_cpu);
                delta = counter - prev;
                prev = counter;
                printf("delta = %u\n",delta);
                sleep(1);
            }
        }
#else
        /* Start instance monitoring */
        vm_monitor(vm);
#endif

        /* Free resources used by instance */
        vm_release(vm);
    } else {
        hypervisor_tcp_server(hypervisor_ip_address,hypervisor_tcp_port);
    }

    dynamips_reset();
    close_log_file();
    return(0);
}
Exemplo n.º 6
0
int main(int argc, char *argv[])
{
    int result = 0;
    struct cc_event_context *context = NULL;
    sd_event *event = NULL;
    struct cc_server_Calculator *instance1 = NULL, *instance2 = NULL;

    CC_LOG_OPEN("simpleserver");
    printf("Started simpleserver\n");

    result = cc_backend_startup();
    if (result < 0) {
        printf("unable to startup backend: %s\n", strerror(-result));
        goto fail;
    }
    result = cc_server_Calculator_new(
        "org.genivi.capic.Server:/instance1:org.genivi.capic.Calculator",
        &impl1, NULL, &instance1);
    if (result < 0) {
        printf("unable to create server instance '/instance1': %s\n", strerror(-result));
        goto fail;
    }
    result = cc_server_Calculator_new(
        "org.genivi.capic.Server:/instance2:org.genivi.capic.Calculator",
        &impl2, NULL, &instance2);
    if (result < 0) {
        printf("unable to create server instance '/instance2': %s\n", strerror(-result));
        goto fail;
    }

    result = cc_backend_get_event_context(&context);
    if (result < 0) {
        printf("unable to get backend event context: %s\n", strerror(-result));
        goto fail;
    }
    event = (sd_event *) cc_event_get_native(context);
    assert(event);
    sd_event_ref(event);
    result = setup_signals(event);
    if (result < 0) {
        printf("unable to setup signal sources: %s\n", strerror(-result));
        goto fail;
    }

    printf("entering main loop...\n");
    result = sd_event_loop(event);
    if (result < 0) {
        printf("unable to run event loop: %s\n", strerror(-result));
        goto fail;
    }

fail:
    if (event)
        sd_event_unref(event);
    instance2 = cc_server_Calculator_free(instance2);
    instance1 = cc_server_Calculator_free(instance1);
    cc_backend_shutdown();

    CC_LOG_CLOSE();
    printf("exiting simpleserver\n");

    return result;
}
Exemplo n.º 7
0
// program execution starts here!
int main( int argc, char** argv ) {
   curl_global_init(CURL_GLOBAL_ALL);

   // start up protocol buffers
   GOOGLE_PROTOBUF_VERIFY_VERSION;
   
   g_config_file = strdup( METADATA_DEFAULT_CONFIG );
   
   // process command-line options
   int c;
   int rc;
   bool make_daemon = true;
   bool good_input = true;
   char* mc_root = NULL;
   char* logfile = NULL;
   char* pidfile = NULL;
   int portnum = 0;
   int reload_pid = 0;
   
   while((c = getopt(argc, argv, "fc:m:p:u:l:P:k:")) != -1) {
      switch( c ) {
         case 'f': {
            make_daemon = false;
            break;
         }
         case '?': {
            usage( argv[0], 1 );
         }
         case 'c': {
            g_config_file = realpath( optarg, NULL );
            break;
         }
         case 'm': {
            mc_root = realpath( optarg, NULL );
            break;
         }
         case 'P': {
            portnum = strtol( optarg, NULL, 10 );
            if( portnum <= 0 )
               good_input = false;
            break;
         }
         case 'u': {
            g_secrets_file = realpath( optarg, NULL );
            break;
         }
         case 'l': {
            logfile = strdup( optarg );
            break;
         }
         case 'p': {
            pidfile = realpath( optarg, NULL );
            break;
         }
         case 'k': {
            reload_pid = strtol( optarg, NULL, 10 );
            if( reload_pid <= 0 )
               good_input = false;
            break;
         }
         default: {
            fprintf(stderr, "Ignoring unrecognized option %c\n", c);
            good_input = false;
            break;
         }
      }
   }
   
   if( !good_input ) {
      usage( argv[0], 1 );
   }

   if( reload_pid > 0 ) {
      // all we're doing is telling a running metadata server to reload
      kill( reload_pid, SIGUSR1 );
      exit(0);
   }
   
   // read the config
   struct md_syndicate_conf conf;
   g_conf = &conf;

   dbprintf("reading config %s\n", g_config_file);
   if( md_read_conf( g_config_file, &conf ) != 0 ) {
      errorf("Could not read config at %s\n", g_config_file);
      usage( argv[0], 1 );
   }
   
   // user-given portnum?
   if( portnum > 0 ) {
      conf.portnum = portnum;
   }
   if( conf.portnum == 0 ) {
      errorf("Invalid port number %d.  Specify PORTNUM in the config file or pass -p\n", conf.portnum);
      exit(1);
   }
   
   // master copy supplied in args?
   if( mc_root ) {
      if( conf.master_copy_root ) {
         free( conf.master_copy_root );
      }
      conf.master_copy_root = mc_root;
   }
   
   // secrets file supplied in args?
   if( g_secrets_file ) {
      if( conf.secrets_file ) {
         free( conf.secrets_file );
      }
      conf.secrets_file = g_secrets_file;
   }
   else if( conf.secrets_file ) {
      g_secrets_file = strdup( conf.secrets_file );
   }
  
   // pidfile supplied in args?
   if( pidfile ) {
      if( conf.md_pidfile_path ) {
         free( conf.md_pidfile_path );
      }
      conf.md_pidfile_path = pidfile;
   }

   dbprintf("%s", "initializing libsyndicate\n");
   
   // set the config
   if( md_init( &conf, NULL ) != 0 )
      exit(1);
   
   md_connect_timeout( conf.query_timeout );
   md_signals( 0 );        // no signals

   dbprintf("reading users file %s\n", conf.secrets_file );

   // read the users file
   struct md_user_entry **users = NULL;
   if( conf.secrets_file ) {
      users = md_parse_secrets_file( conf.secrets_file );
      if( users == NULL ) {
         exit(1);
      }
   }
   else {
      errorf("No secrets file given.  Pass -u or specify a value for %s in the config\n", SECRETS_FILE_KEY );
      usage( argv[0], 1 );
   }

   // need to daemonize?
   if( make_daemon ) {
      FILE* log = NULL;
      rc = md_daemonize( logfile, conf.md_pidfile_path, &log );
      if( rc < 0 ) {
         errorf("md_daemonize rc = %d\n", rc );
         exit(1);
      }

      if( log )
         conf.md_logfile = log;
   }

   // setup the reload semaphore
   sem_init( &reload_sem, 0, 0 );

   reload_thread = md_start_thread( reloader, NULL, true );
   
   // start HTTP
   rc = http_init( &http, &conf, users );
   if( rc != 0 ) {
      exit(1);
   }

   // start validator
   rc = validator_init( &conf );
   if( rc != 0 ) {
      exit(1);
   }

   setup_signals();

   while( 1 ) {
      sleep(1);
   }

   // we never reach this point--the signal handler cleans up
   return 0;
}
Exemplo n.º 8
0
int main(int argc, char **argv) {
  auto_handle * ses = NULL;
  char *config_file = NULL;
  char *logfile = NULL;
  char *pidfile = NULL;
  char *xmlfile = NULL;
  char erbuf[100];
  NODE *current = NULL;
  uint32_t count = 0;
  uint8_t first_run = 1;
  uint8_t once = 0;
  uint8_t verbose = AM_DEFAULT_VERBOSE;
  uint8_t append_log = 0;
  uint8_t match_only = 0;

  /* this sets the log level to the default before anything else is done.
  ** This way, if any outputting happens in readargs(), it'll be printed
  ** to stderr.
  */
  log_init(NULL, verbose, 0);

  readargs(argc, argv, &config_file, &logfile, &pidfile, &xmlfile, &nofork, &verbose, &once, &append_log, &match_only);

  /* reinitialize the logging with the values from the command line */
  log_init(logfile, verbose, append_log);

  dbg_printf(P_MSG, "Automatic version: %s", LONG_VERSION_STRING);

  if(!config_file) {
    config_file = am_strdup(AM_DEFAULT_CONFIGFILE);
  }

  strncpy(AutoConfigFile, config_file, strlen(config_file));

  ses = session_init();
  ses->match_only = match_only;

  if(parse_config_file(ses, AutoConfigFile) != 0) {
     if(errno == ENOENT) {
        snprintf(erbuf, sizeof(erbuf), "Cannot find file '%s'", config_file);
     } else {
        snprintf(erbuf, sizeof(erbuf), "Unknown error");
     }

     fprintf(stderr, "Error parsing config file: %s\n", erbuf);
     shutdown_daemon(ses);
  }

  if(!setupSession(ses)) {
     shutdown_daemon(ses);
  }

  setup_signals();

  if(!nofork) {
    /* start daemon */
    if(daemonize(pidfile) != 0) {
      dbg_printf(P_ERROR, "Error: Daemonize failed. Aborting...");
      shutdown_daemon(mySession);
    }
    dbg_printft( P_MSG, "Daemon started");
  }

  dbg_printf(P_INFO, "verbose level: %d", verbose);
  dbg_printf(P_INFO, "foreground mode: %s", nofork == true ? "yes" : "no");

  while(!closing) {
    isRunning = true;
    dbg_printft( P_INFO, "------ Checking for new episodes ------");
    if(xmlfile && *xmlfile) {
      processFile(mySession, xmlfile);
      once = 1;
    } else {
      current = mySession->feeds;
      count = 0;
      while(current && current->data) {
        ++count;
        processFeed(mySession, current->data, first_run);
        current = current->next;
      }
      if(first_run) {
        dbg_printf(P_INFO2, "New bucket size: %d", mySession->max_bucket_items);
      }
      first_run = 0;
    }

    /* leave loop when program is only supposed to run once */
    if(once) {
      break;
    }

    isRunning = false;

    if(seenHUP) {
      signal_handler(SIGHUP);
    }

    sleep(mySession->check_interval * 60);
  }

  shutdown_daemon(mySession);
  return 0;
}
Exemplo n.º 9
0
int main(int argc, char** argv)
{
  struct host_answer ans_buf;
  struct host_request req_buf;
  struct hostent *from;
  int found = 0;
  int pos = 1;
  char *dir;
  char tmppath[1024];

  while ((pos < argc) && (*(argv[pos]) == '-')) {
    switch (*(argv[pos] + 1)) {
      case 'd':
        if (*(argv[pos] + 2))
          dir = argv[pos] + 2;
        else if (++pos < argc)
          dir = argv[pos];
        else {
          fprintf(stderr, "Directory arg expected after option -d.\n");
          fflush(NULL);
          exit(1);
        }
        break;
    }
  }

  my_name = "HOSTS";

  setup_pid_file(dir);
  sleep(1);

  setup_signals();

  sprintf(tmppath, "%s/misc/dns_send_fifo", dir);
  fprintf(stderr, "opening send fifo: %s\n", tmppath);
  if ((dns_send_fifo = open(tmppath, O_RDONLY)) == -1) {
    perror("open fifo");
    exit(1);
  }
  sprintf(tmppath, "%s/misc/dns_receive_fifo", dir);
  fprintf(stderr, "opening receive fifo: %s\n", tmppath);
  if ((dns_receive_fifo = open(tmppath, O_WRONLY)) == -1) {
    perror("open fifo");
    exit(1);
  }
  parent_pid = getppid(); /* if my parent pid changes, then it must mean that my parent died... so
   I should as well */
  fprintf(stderr, "%s lookup process started with parent ID %d\n", my_name, (int) parent_pid);
  fflush(NULL);

  while (1) {
    while ((found = get_message(MSG_HOST_REQ, (void *) &req_buf, sizeof(struct host_request))) == -1)
      ;
    if (found) {

      /* okay... we have a message.. check for validity */

      if (req_buf.desc == 0) {
        break;
      }

      memset(&ans_buf, 0, sizeof(ans_buf));
      ans_buf.mtype = MSG_HOST_ANS;
      ans_buf.desc = req_buf.desc;
      strcpy(ans_buf.addr, req_buf.addr);

      if (!(from = gethostbyaddr((char *) &req_buf.sock.sin_addr, sizeof(req_buf.sock.sin_addr), AF_INET))) {
        if (h_errno != 1)
          strcpy(ans_buf.hostname, req_buf.addr);
      } else {
        *(from->h_name + 100) = 0;
        strcpy(ans_buf.hostname, from->h_name);
      }

      /* send the answer back... */
      if (write(dns_receive_fifo, (void *) &ans_buf, sizeof(struct host_answer)) == -1) {
        perror("write");
        clean_up();
        break;
      }
    } else {
      break;
    }
  }
  return 0;
}
Exemplo n.º 10
0
void loop(int port, char *cmd[]) {
    int sockfd; // socket fd
    int ready[2]; // ready pipe
    int rd; // pipe reader fd
    int wr; // pipe writer fd
    int pid; // temp child pid;
    fd_set rset; // fd set for pipe reader
    char *p; // GRACE_START_TIMEOUT
    int rt; // start timeout

    sockfd = createsock(port);
    setup_signals();

    rt = 10;
    if ((p = getenv(GRACE_START_TIMEOUT)) != NULL) {
        rt = atoi(p);
    }
    timeout.tv_sec = rt;
    timeout.tv_usec = 0;

    while(1) {
        if (pipe(ready) < 0) {
            SYSERR("pipe");
        }
        rd = ready[0];
        wr = ready[1];

        pid = fork();
        if (pid < 0) {
            SYSERR("fork");
        }

        if (pid == 0) {
            close(rd);
            close(srd);
            close(swr);
            // sigmask is preserved for child process, so we need to clear it;
            clear_sigmask();
            setenvs(sockfd, wr);
            execvp(cmd[0], cmd);
            SYSERR("execvp");
        }

        // close the write end of the pipe;
        close(wr);

        wait_child(pid, rd);

        close(rd);

        // successfully started; then kill the old one.
        if (childpid) {
            kill(childpid, SIGTERM);
        }
        childpid = pid;

        wait_restart();

        if (termniate) {
            if (childpid) {
                kill(childpid, SIGTERM);
            }
            exit(0);
        }
    }
}
Exemplo n.º 11
0
int
main (int argc, char *argv[])
{
	GOptionContext *opt_ctx;
	GError *error = NULL;
	NMConnectionList *list;
	DBusGConnection *bus;
	char *type = NULL;
	gboolean create = FALSE;
	gboolean show = FALSE;
	gboolean success;
	char *uuid = NULL;
	NMCEService *service = NULL;
	DBusGProxy *proxy = NULL;
	gboolean show_list;

	GOptionEntry entries[] = {
		{ ARG_TYPE,   0, 0, G_OPTION_ARG_STRING, &type,   "Type of connection to show or create", NM_SETTING_WIRED_SETTING_NAME },
		{ ARG_CREATE, 0, 0, G_OPTION_ARG_NONE,   &create, "Create a new connection", NULL },
		{ ARG_SHOW,   0, 0, G_OPTION_ARG_NONE,   &show,   "Show a given connection type page", NULL },
		{ "edit",     0, 0, G_OPTION_ARG_STRING, &uuid,   "Edit an existing connection with a given UUID", "UUID" },
		{ NULL }
	};

	bindtextdomain (GETTEXT_PACKAGE, NMALOCALEDIR);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	gtk_init (&argc, &argv);
	textdomain (GETTEXT_PACKAGE);

	opt_ctx = g_option_context_new (NULL);
	g_option_context_set_summary (opt_ctx, "Allows users to view and edit network connection settings");
	g_option_context_add_main_entries (opt_ctx, entries, NULL);
	success = g_option_context_parse (opt_ctx, &argc, &argv, &error);
	g_option_context_free (opt_ctx);

	if (!success) {
		g_warning ("%s\n", error->message);
		g_error_free (error);
		return 1;
	}

	/* Just one page for both CDMA & GSM, handle that here */
	if (type && g_strcmp0 (type, NM_SETTING_CDMA_SETTING_NAME) == 0)
		type = (char *) NM_SETTING_GSM_SETTING_NAME;

	/* Inits the dbus-glib type system too */
	bus = dbus_g_bus_get (DBUS_BUS_SESSION, NULL);
	if (bus) {
		proxy = dbus_g_proxy_new_for_name (bus,
		                                   "org.freedesktop.DBus",
		                                   "/org/freedesktop/DBus",
		                                   "org.freedesktop.DBus");
		g_assert (proxy);

		/* Check for an existing instance on the bus, and if there
		 * is one, send the arguments to it and exit instead of opening
		 * a second instance of the connection editor.
		 */
		if (try_existing_instance (bus, proxy, type, create, show, uuid))
			return 0;
	}

	loop = g_main_loop_new (NULL, FALSE);

	list = nm_connection_list_new ();
	if (!list) {
		g_warning ("Failed to initialize the UI, exiting...");
		return 1;
	}
	g_signal_connect_swapped (list, "done", G_CALLBACK (g_main_loop_quit), loop);

	/* Create our single-instance-app service if we can */
	if (proxy)
		service = nm_ce_service_new (bus, proxy, list);

	/* Show the dialog */
	g_signal_connect_swapped (list, "done", G_CALLBACK (g_main_loop_quit), loop);

	/* Figure out what page or editor window we'll show initially */
	show_list = handle_arguments (list, type, create, show, uuid, (create || show || uuid));
	if (show_list)
		nm_connection_list_present (list);

	setup_signals ();
	g_main_loop_run (loop);

	/* Cleanup */
	g_object_unref (list);
	if (service)
		g_object_unref (service);
	if (proxy)
		g_object_unref (proxy);
	if (bus)
		dbus_g_connection_unref (bus);
	return 0;
}
Exemplo n.º 12
0
int main(int argc, char *argv[])
{
	char pass[MAXPASS + 1];
	char option[8];
	int npass, opt;
	int force_failure = 0;
	int retval = UNIX_FAILED;
	char *user;

	/*
	 * Catch or ignore as many signal as possible.
	 */
	setup_signals();

	/*
	 * we establish that this program is running with non-tty stdin.
	 * this is to discourage casual use. It does *NOT* prevent an
	 * intruder from repeatadly running this program to determine the
	 * password of the current user (brute force attack, but one for
	 * which the attacker must already have gained access to the user's
	 * account).
	 */

	if (isatty(STDIN_FILENO)) {

		_log_err(LOG_NOTICE
		      ,"inappropriate use of Unix helper binary [UID=%d]"
			 ,getuid());
		fprintf(stderr
		 ,"This binary is not designed for running in this way\n"
		      "-- the system administrator has been informed\n");
		sleep(10);	/* this should discourage/annoy the user */
		return UNIX_FAILED;
	}

	/*
	 * determine the current user's name is
	 */
	user = getuidname(getuid());
	if (argc == 2) {
	    /* if the caller specifies the username, verify that user
	       matches it */
	    if (strcmp(user, argv[1])) {
		force_failure = 1;
	    }
	}

	/* read the nollok/nonull option */

	npass = read(STDIN_FILENO, option, 8);

	if (npass < 0) {
		_log_err(LOG_DEBUG, "no option supplied");
		return UNIX_FAILED;
	} else {
		option[7] = '\0';
		if (strncmp(option, "nullok", 8) == 0)
			opt = 1;
		else
			opt = 0;
	}

	/* read the password from stdin (a pipe from the pam_unix module) */

	npass = read(STDIN_FILENO, pass, MAXPASS);

	if (npass < 0) {	/* is it a valid password? */

		_log_err(LOG_DEBUG, "no password supplied");

	} else if (npass >= MAXPASS) {

		_log_err(LOG_DEBUG, "password too long");

	} else {
		if (npass == 0) {
			/* the password is NULL */

			retval = _unix_verify_password(user, NULL, opt);

		} else {
			/* does pass agree with the official one? */

			pass[npass] = '\0';	/* NUL terminate */
			retval = _unix_verify_password(user, pass, opt);

		}
	}

	memset(pass, '\0', MAXPASS);	/* clear memory of the password */

	/* return pass or fail */

	if ((retval != UNIX_PASSED) || force_failure) {
	    return UNIX_FAILED;
	} else {
	    return UNIX_PASSED;
	}
}
Exemplo n.º 13
0
int main_loop( CamConfig *ccfg, Socket *picture_sock, char *picture_mem  ){
  Socket *listen_socket;
  SockSet *readset = NULL, *writeset = NULL;
  list_t *client_sockets;
  lnode_t *node;
  int cfg_listen_port, highest_fd, picture_client_ready;
  int num_sclients, num_clients;
  ClientInfo *clientinfo, *clientinfo2;

  if( (client_sockets = list_create( -1 )) == NULL)
    return -1;

  cfg_listen_port = camconfig_query_def_int( ccfg, SEC_SOCKET, 
					     "listen_port",
					     CAMCONFIG_DEF_LISTEN_PORT );

  if( (readset = sockset_new()) == NULL ||
      (writeset = sockset_new()) == NULL )
  {
    camserv_log( MODNAME, "Error allocating memory for socksets!");
    if( readset ) sockset_dest( readset );
    if( writeset ) sockset_dest( writeset );
    list_destroy( client_sockets );
    return -1;
  }

  if((listen_socket = socket_serve_tcp( NULL, cfg_listen_port, 100 )) == NULL )
  {
      camserv_log( MODNAME, "Error setting up socket on port \"%d\".  Exiting",
	       cfg_listen_port  );
      list_destroy( client_sockets );
      sockset_dest( readset );
      sockset_dest( writeset );
      return -1;
  }

  highest_fd = MAX( socket_query_fd( listen_socket ), 
		    socket_query_fd( picture_sock ));
  clientinfo = clientinfo_new( listen_socket );
  clientinfo2 = clientinfo_new( picture_sock );

  if( !clientinfo || !clientinfo2 ||
      sockset_add_fd( readset, listen_socket, clientinfo ) == -1 ||
      sockset_add_fd( readset, picture_sock, clientinfo2 ) == -1 )
  {
    camserv_log( MODNAME, "Error adding initial sockets to sockset!");
    sockset_dest( readset );
    sockset_dest( writeset );
    if( clientinfo )  clientinfo_dest( clientinfo );
    if( clientinfo2 ) clientinfo_dest( clientinfo2 );
    list_destroy( client_sockets );
    return -1;
  }

  num_clients = 0;
  num_sclients = 0;
  picture_client_ready = 1;

  setup_signals();
  Abort = 0;
  while( !Abort ){
    int sel_res, i, nset_socks;
    void **set_socks;

    /* Only need to execute this if we have a streaming client */
    if( (num_sclients > 0) && picture_client_ready == 1 ){
      send( socket_query_fd( picture_sock ), "0", sizeof( "0" ), 0 );
      picture_client_ready = 0;
    }

    sockset_reset( readset );
    sockset_reset( writeset );

    sel_res = sockset_select( highest_fd + 1, readset, writeset, NULL );
    /* Service the event */
    if( sel_res == -1 ){
      camserv_log( MODNAME, "select() failure: %s", strerror( errno ));
      break;
    } else if( sel_res == 0 ){
      camserv_log( MODNAME, "Unexpected select() fall through!" );
      continue;
    } 

    /* Readable sockets */
    set_socks = sockset_query_socks( readset );
    nset_socks = sockset_query_nsocks( readset );
    for( i=0; i< nset_socks; i++ ){
      ClientInfo *new_cinfo;

      clientinfo = set_socks[ i ];

      if( clientinfo->socket == listen_socket ) {
	/* New client */
	if( (new_cinfo = accept_client( listen_socket )) == NULL )
	  continue;

	if( (node = lnode_create( new_cinfo )) == NULL ){
	  clientinfo_dest( new_cinfo );
	  continue;
	}

	if( sockset_add_fd( readset, new_cinfo->socket, new_cinfo ) == -1 ){
	  camserv_log( MODNAME, "Failed to add socket %d to socket read set!",
		   socket_query_fd( new_cinfo->socket ));
	  clientinfo_dest( new_cinfo );
	  lnode_destroy( node );
	  continue;
	}

	if( socket_query_fd( new_cinfo->socket ) > highest_fd )
	  highest_fd = socket_query_fd( new_cinfo->socket );

	list_append( client_sockets, node );
	num_clients++;
	/* Init resource limit for this client */
	new_cinfo->create_time = time( NULL );
	new_cinfo->bytes       = 0;
	new_cinfo->frames      = 0;
	new_cinfo->max_seconds = camconfig_query_def_int( ccfg, SEC_SOCKET,
							  "max_seconds", 0 );
	new_cinfo->max_bytes   = camconfig_query_def_int( ccfg, SEC_SOCKET,
							  "max_bytes", 0 );
	new_cinfo->max_frames  = camconfig_query_def_int( ccfg, SEC_SOCKET,
							  "max_frames", 0 );

	/* Send fresh request for a picture */
	send( socket_query_fd( picture_sock ), "0", sizeof( "0" ), 0 );
	picture_client_ready = 0;
	/* Put this read socket on hold until the picture comes back */
	sockset_hold( readset, new_cinfo->socket );	

      } else {
	char cmdbuf[ 1024 ];
	int readlen;

	clientinfo = set_socks[ i ];

	/* Regular joe client, set readable */
	if( (readlen = read( socket_query_fd( clientinfo->socket), cmdbuf, 
			     sizeof( cmdbuf ) - 1)) <= 0 )
	{
	  camserv_log( MODNAME, "Closing socket: %s", 
		       socket_query_remote_name( clientinfo->socket ));

	  if (clientinfo->client_type == CLIENT_T_BROWSER ||
	      clientinfo->client_type == CLIENT_T_PROXY) {
	      num_sclients--;
	  }
	  client_remove( client_sockets, clientinfo );
	  sockset_del_fd( readset, clientinfo->socket );
	  sockset_unhold_all( writeset );
	  sockset_del_fd( writeset, clientinfo->socket );
	  clientinfo_dest( clientinfo );
	  num_clients--;
	} else {
	  if( clientinfo->socket == picture_sock ) {
	    if( dispatch_pictaker( cmdbuf, picture_mem ) == -1 )
	      camserv_log( MODNAME, "Pictaker dispatch failure!");
	    sockset_unhold_all( writeset );
	    /* Release the read hold as the picture has now been taken */
	    sockset_unhold_all( readset );
	    picture_client_ready = 1;
	  } else {
	    /* Information from a regular client */
	    cmdbuf[ readlen ] = '\0';
	    if( clientinfo->client_type == CLIENT_T_UNINIT ) {
	      char *preamble;
	      int pre_size;

	      /* Figure out what type of client we have */
	      if( !strncmp( cmdbuf, "GET", 3 )) {
		if( strstr( cmdbuf, "/singleframe" )) {
		  clientinfo->client_type = CLIENT_T_SINGLE;
		} else {
		  clientinfo->client_type = CLIENT_T_BROWSER;
		  num_sclients++;
	        }
	      } else if( !strncmp( cmdbuf, "PROXY", 5 )) {
		clientinfo->client_type = CLIENT_T_PROXY;
		/* Here we are in the same state as being done writing a pic */
		clientinfo->state       = CINFO_STATE_PICTURE;
		num_sclients++;	
		databuf_buf_set( clientinfo->writebuf, NULL, 0 ); 
	      } else 
		clientinfo->client_type = CLIENT_T_BROWSER;

	      if( clientinfo->client_type != CLIENT_T_PROXY ) {
		/* Send the initial preamble.  Only now we can decide which 
		   type of preamble to send (single vs. multi-part) */
		if( clientinfo->client_type == CLIENT_T_SINGLE )
		  preamble = get_single_preamble_text( &pre_size );
		else
		  preamble = get_multi_preamble_text( &pre_size );
		databuf_buf_set( clientinfo->writebuf, preamble, pre_size );
	      }

	      if( sockset_add_fd( writeset, clientinfo->socket, 
				  clientinfo ) == -1 )
	      {
  		  camserv_log( MODNAME, "Failed to add socket %d to write set!",
			   socket_query_fd( clientinfo->socket ));
	      }
	  } 
	} 
      } 
    } 
  } 

    if( set_socks != NULL ) free( set_socks );

    /* Writable sockets */
    set_socks = sockset_query_socks( writeset );
    nset_socks = sockset_query_nsocks( writeset );
    for( i=0; i< nset_socks; i++ ){
      ClientInfo *cinfo;

      cinfo = set_socks[ i ];
      if( cinfo->client_type == CLIENT_T_BROWSER ||
	  cinfo->client_type == CLIENT_T_SINGLE ) 
      {
	int result;

	if( (result = write_regular_client( cinfo, writeset )) != 0 ){
	  /* result: 1=close requested, -1=error detected */
	  if( result == -1 )
	    camserv_log( MODNAME, "Databuf write error on socket: %s\n",
			 socket_query_remote_name( cinfo->socket ));
	  
	  if (cinfo->client_type == CLIENT_T_BROWSER) {
	      num_sclients--;
	  }

	  client_remove( client_sockets, cinfo );
	  sockset_del_fd( readset, cinfo->socket );
	  sockset_del_fd( writeset, cinfo->socket );
	  clientinfo_dest( cinfo );
	  num_clients--;
	}
      } else {
	if( write_proxy_client( cinfo, writeset ) == -1 ){
	  camserv_log( MODNAME, "Databuf write error on socket: %d",
		   socket_query_fd( cinfo->socket ));

	  /* Should be proxy, but better check */
	  if (cinfo->client_type == CLIENT_T_PROXY) {
	      num_sclients--;
	  }
	  client_remove( client_sockets, cinfo );
	  sockset_del_fd( readset, cinfo->socket );
	  sockset_del_fd( writeset, cinfo->socket );
	  clientinfo_dest( cinfo );
	  num_clients--;
	}
      }
    }
    if( set_socks != NULL ) free( set_socks );
  }

  camserv_log( MODNAME, "Aborting.");
  sockset_dest( readset );
  sockset_dest( writeset );

  for( node = list_first( client_sockets) ; node; 
       node=list_next( client_sockets, node ))
  {
    clientinfo_dest( node->data );
  }

  /* Tell the picture taker to get out!  Get out! */
  camserv_log( MODNAME, "Closing picture taker");
  send( socket_query_fd( picture_sock ), "9", sizeof( "9" ), 0 );
  sleep( 3 );
  camserv_log( MODNAME, "done\n");

  list_destroy_nodes( client_sockets );
  list_destroy( client_sockets );
  socket_dest( listen_socket );
  return 0;
}
Exemplo n.º 14
0
int main(int argc, char *argv[])
{
#ifndef _WIN32
  if (geteuid() == 0)
  {
    fprintf(stderr, "Running IRC services is root is not recommended.");
    return 1;
  }
  setup_corefile();
#endif
  memset(&ServicesInfo, 0, sizeof(ServicesInfo));
  memset(&ServicesState, 0, sizeof(ServicesState));

  ServicesState.configfile = CPATH; 
  ServicesState.logfile    = LPATH;
  ServicesState.pidfile    = PPATH;
  ServicesState.fully_connected = 0;

  parseargs(&argc, &argv, myopts);

  if(ServicesState.printversion)
  {
    printf("oftc-ircservices: version: %s\n", VERSION);
    exit(EXIT_SUCCESS);
  }

  if(chdir(DPATH))
  {
    perror("chdir");
    exit(EXIT_FAILURE);
  }

#ifndef _WIN32
  if(!ServicesState.foreground)
    make_daemon();
  else
    print_startup(getpid());
#endif

  setup_signals();
  memset(&me, 0, sizeof(me));

  libio_init(!ServicesState.foreground);
  init_events();
  iorecv_cb = register_callback("iorecv", iorecv_default);
  connected_cb = register_callback("server connected", server_connected);
  iosend_cb = register_callback("iosend", iosend_default);

  OpenSSL_add_all_digests();
 
  init_interface();
  check_pidfile(ServicesState.pidfile);
  init_log(ServicesState.logfile);

#ifdef HAVE_RUBY
  init_ruby();
  signal(SIGSEGV, SIG_DFL);
#endif

  init_channel();
  init_conf();
  init_client();
  init_parser();
  init_channel_modes();
  init_mqueue();
  init_tor();

  me.from = me.servptr = &me;
  SetServer(&me);
  SetMe(&me);
  dlinkAdd(&me, &me.node, &global_client_list);
  
  read_services_conf(TRUE);
  init_db();
  init_uid();
 
#ifdef HAVE_PYTHON
  init_python();
#endif

  init_kill();

  write_pidfile(ServicesState.pidfile);
  ilog(L_NOTICE, "Services Ready");

  db_load_driver();
#ifdef USE_SHARED_MODULES
  if(chdir(MODPATH))
  {
    ilog(L_ERROR, "Could not load core modules from %s: %s",
         MODPATH, strerror(errno));
    exit(EXIT_FAILURE);
  }

  /* Go back to DPATH after checking to see if we can chdir to MODPATH */
  chdir(DPATH);
#else
  load_all_modules(1);
#endif

  boot_modules(1);
  
  connect_server();

  for(;;)
  {
    while (eventNextTime() <= CurrentTime)
      eventRun();

    execute_callback(do_event_cb);

    if(events_loop() == -1)
    {
      ilog(L_CRIT, "libevent returned error %d", errno);
      services_die("Libevent returned some sort of error", NO);
      break;
    }

    comm_select();
    send_queued_all();

    if(dorehash)
    {
      ilog(L_INFO, "Got SIGHUP, reloading configuration");
      read_services_conf(NO);
      dorehash = 0;
    }
  }

  return 0;
}
Exemplo n.º 15
0
/* main() for udpxrec module
 */
int udpxrec_main( int argc, char* const argv[] )
{
    int rc = 0, ch = 0, custom_log = 0, no_daemon = 0;
    static const char OPTMASK[] = "vb:e:M:p:B:n:m:l:c:R:u:T";
    time_t now = time(NULL);
    char now_buf[ 32 ] = {0}, sel_buf[ 32 ] = {0}, app_finfo[80] = {0};

    extern int optind, optopt;
    extern const char IPv4_ALL[];

    mk_app_info(g_udpxrec_app, g_app_info, sizeof(g_app_info) - 1);

    if( argc < 2 ) {
        usage( argv[0], stderr );
        return ERR_PARAM;
    }

    rc = init_recopt( &g_recopt );
    while( (0 == rc) && (-1 != (ch = getopt( argc, argv, OPTMASK ))) ) {
        switch(ch) {
            case 'T':   no_daemon = 1; break;
            case 'v':   set_verbose( &g_recopt.is_verbose ); break;
            case 'b':
                        if( (time_t)0 != g_recopt.end_time ) {
                            (void) fprintf( stderr, "Cannot specify start-recording "
                                    "time after end-recording time has been set\n" );
                        }

                        rc = a2time( optarg, &g_recopt.bg_time, time(NULL) );
                        if( 0 != rc ) {
                            (void) fprintf( stderr, "Invalid time: [%s]\n", optarg );
                            rc = ERR_PARAM;
                        }
                        else {
                            if( g_recopt.bg_time < now ) {
                                (void)strncpy( now_buf, Zasctime(localtime( &now )),
                                        sizeof(now_buf) );
                                (void)strncpy( sel_buf,
                                        Zasctime(localtime( &g_recopt.bg_time )),
                                        sizeof(sel_buf) );

                                (void) fprintf( stderr,
                                        "Selected %s time is in the past, "
                                        "now=[%s], selected=[%s]\n", "start",
                                        now_buf, sel_buf );
                                rc = ERR_PARAM;
                            }
                        }

                        break;
            case 'e':
                        if( (time_t)0 == g_recopt.bg_time ) {
                            g_recopt.bg_time = time(NULL);
                            (void)fprintf( stderr,
                                    "Start-recording time defaults to now [%s]\n",
                                    Zasctime( localtime( &g_recopt.bg_time ) ) );
                        }

                        rc = a2time( optarg, &g_recopt.end_time, g_recopt.bg_time );
                        if( 0 != rc ) {
                            (void) fprintf( stderr, "Invalid time: [%s]\n", optarg );
                            rc = ERR_PARAM;
                        }
                        else {
                            if( g_recopt.end_time < now ) {
                                (void)strncpy( now_buf, Zasctime(localtime( &now )),
                                        sizeof(now_buf) );
                                (void)strncpy( sel_buf,
                                        Zasctime(localtime( &g_recopt.end_time )),
                                        sizeof(sel_buf) );

                                (void) fprintf( stderr,
                                        "Selected %s time is in the past, "
                                        "now=[%s], selected=[%s]\n", "end",
                                        now_buf, sel_buf );
                                rc = ERR_PARAM;
                            }
                        }
                        break;

            case 'M':
                        rc = a2int64( optarg, &g_recopt.max_fsize );
                        if( 0 != rc ) {
                            (void) fprintf( stderr, "Invalid file size: [%s]\n",
                                    optarg );
                            rc = ERR_PARAM;
                        }
                        break;
            case 'p':
                        g_recopt.pidfile = strdup(optarg);
                        break;

            case 'B':
                        rc = a2size( optarg, &g_recopt.bufsize );
                        if( 0 != rc ) {
                            (void) fprintf( stderr, "Invalid buffer size: [%s]\n",
                                    optarg );
                            rc = ERR_PARAM;
                        }
                        else if( (g_recopt.bufsize < MIN_MCACHE_LEN) ||
                                 (g_recopt.bufsize > MAX_MCACHE_LEN)) {
                            (void) fprintf( stderr,
                                "Buffer size must be in [%ld-%ld] bytes range\n",
                                (long)MIN_MCACHE_LEN, (long)MAX_MCACHE_LEN );
                            rc = ERR_PARAM;
                        }

                        break;
            case 'n':
                      g_recopt.nice_incr = atoi( optarg );
                      if( 0 == g_recopt.nice_incr ) {
                        (void) fprintf( stderr,
                            "Invalid nice-value increment: [%s]\n", optarg );
                        rc = ERR_PARAM;
                      }
                      break;
            case 'm':
                      rc = get_ipv4_address( optarg, g_recopt.mcast_addr,
                              sizeof(g_recopt.mcast_addr) );
                      if( 0 != rc ) {
                        (void) fprintf( stderr, "Invalid multicast address: [%s]\n",
                                        optarg );
                          rc = ERR_PARAM;
                      }
                      break;
            case 'l':
                      g_flog = fopen( optarg, "a" );
                      if( NULL == g_flog ) {
                        rc = errno;
                        (void) fprintf( stderr, "Error opening logfile [%s]: %s\n",
                                optarg, strerror(rc) );
                        rc = ERR_PARAM; break;
                      }

                      Setlinebuf( g_flog );
                      custom_log = 1;
                      break;

            case 'c':
                      rc = get_addrport( optarg, g_recopt.rec_channel,
                                         sizeof( g_recopt.rec_channel ),
                                         &g_recopt.rec_port );
                      if( 0 != rc ) rc = ERR_PARAM;
                      break;

            case 'R':
                      g_recopt.rbuf_msgs = atoi( optarg );
                      if( (g_recopt.rbuf_msgs <= 0) && (-1 != g_recopt.rbuf_msgs) ) {
                        (void) fprintf( stderr,
                                "Invalid rcache size: [%s]\n", optarg );
                        rc = ERR_PARAM;
                      }
                      break;

            case 'u':
                      g_recopt.waitupd_sec = atoi(optarg);
                      if( g_recopt.waitupd_sec <= 0 ) {
                          (void) fprintf( stderr, "Invalid wait-update value [%s] "
                                  "(must be a number > 0)\n", optarg );
                          rc = ERR_PARAM;
                      }
                      break;

            case ':':
                      (void) fprintf( stderr, "Option [-%c] requires an argument\n",
                              optopt );
                      rc = ERR_PARAM; break;
            case '?':
                      (void) fprintf( stderr, "Unrecognized option: [-%c]\n", optopt );
                      rc = ERR_PARAM; break;
            default:
                      usage( argv[0], stderr );
                      rc = ERR_PARAM; break;

        } /* switch */
    } /* while getopt */

    if( 0 == rc ) {
        if( optind >= argc ) {
            (void) fputs( "Missing destination file parameter\n", stderr );
            rc = ERR_PARAM;
        }
        else {
            g_recopt.dstfile = strdup( argv[optind] );
        }

        if( !(g_recopt.max_fsize > 0 || g_recopt.end_time)  ) {
            (void) fputs( "Must specify either max file [-M] size "
                    "or end time [-e]\n", stderr );
            rc = ERR_PARAM;
        }

        if( !g_recopt.rec_channel[0] || !g_recopt.rec_port ) {
            (void) fputs( "Must specify multicast channel to record from\n",
                    stderr );
            rc = ERR_PARAM;
        }
    }

    if( rc ) {
        free_recopt( &g_recopt );
        return rc;
    }

    do {
        if( '\0' == g_recopt.mcast_addr[0] ) {
            (void) strncpy( g_recopt.mcast_addr, IPv4_ALL,
                    sizeof(g_recopt.mcast_addr) - 1 );
        }

        if( !custom_log ) {
            /* in debug mode output goes to stderr, otherwise to /dev/null */
            g_flog = ((uf_TRUE == g_recopt.is_verbose)
                    ? stderr
                    : fopen( "/dev/null", "a" ));
            if( NULL == g_flog ) {
                perror("fopen");
                rc = ERR_INTERNAL; break;
            }
        }

        if( 0 == geteuid() ) {
            if( !no_daemon ) {
                if( stderr == g_flog ) {
                    (void) fprintf( stderr,
                        "Logfile must be specified to run "
                        "in verbose mode in background\n" );
                    rc = ERR_PARAM; break;
                }

                if( NULL == g_recopt.pidfile ) {
                    (void) fprintf( stderr, "pidfile must be specified "
                            "to run as daemon\n" );
                    rc = ERR_PARAM; break;
                }

                if( 0 != (rc = daemonize(0, g_flog)) ) {
                    rc = ERR_INTERNAL; break;
                }
            }

        } /* 0 == geteuid() */

        if( NULL != g_recopt.pidfile ) {
            rc = make_pidfile( g_recopt.pidfile, getpid(), g_flog );
            if( 0 != rc ) break;
        }

        (void) set_nice( g_recopt.nice_incr, g_flog );

        if( 0 != (rc = setup_signals()) ) break;

        TRACE( fprint_recopt( g_flog, &g_recopt ) );

        TRACE( printcmdln( g_flog, g_app_info, argc, argv ) );

        if( g_recopt.bg_time ) {
            if( 0 != (rc = verify_channel()) || g_quit )
                break;

            rc = wait_till( g_recopt.bg_time, g_recopt.waitupd_sec );
            if( rc || g_quit ) break;
        }

        rc = record();

        if( NULL != g_recopt.pidfile ) {
            if( -1 == unlink(g_recopt.pidfile) ) {
                mperror( g_flog, errno, "unlink [%s]", g_recopt.pidfile );
            }
        }
    }
    while(0);

    if( g_flog ) {
        (void)tmfprintf( g_flog, "%s is exiting with rc=[%d]\n",
                app_finfo, rc );
    }

    if( g_flog && (stderr != g_flog) ) {
        (void) fclose(g_flog);
    }

    free_recopt( &g_recopt );

    return rc;
}
Exemplo n.º 16
0
int
main(int argc, char *argv[])
{
   uid_t         uid, euid;
   int           portarg = 0,  fd;
#ifdef SAVE_MAXCLIENT_STATS
   FILE 	*mcsfp;
#endif

   memset(&me, 0, sizeof(aClient));
	
   if ((timeofday = time(NULL)) == -1) 
   {
      (void) fprintf(stderr, "ERROR: Clock Failure (%d)\n", errno);
      exit(errno);
   }
	
   build_version();
	
   Count.server = 1;		/* us */
   Count.oper = 0;
   Count.chan = 0;
   Count.local = 0;
   Count.total = 0;
   Count.invisi = 0;
   Count.unknown = 0;
   Count.max_loc = 0;
   Count.max_tot = 0;
   Count.today = 0;
   Count.weekly = 0;
   Count.monthly = 0;
   Count.yearly = 0;
   Count.start = NOW;
   Count.day = NOW;
   Count.week = NOW;
   Count.month = NOW;
   Count.year = NOW;

#ifdef SAVE_MAXCLIENT_STATS
	mcsfp=fopen(DPATH "/.maxclients", "r");
	if(mcsfp!=NULL) {
		fscanf(mcsfp, "%d %d %li %li %li %ld %ld %ld %ld", &Count.max_loc, 
			&Count.max_tot, &Count.weekly, &Count.monthly, &Count.yearly, 
			&Count.start, &Count.week, &Count.month, &Count.year);
		fclose(mcsfp);
	}
#endif
	

	
   /*
    * this code by [email protected] 
    * it is intended to keep the ircd from being swapped out. BSD
    * swapping criteria do not match the requirements of ircd
    */
	
#ifdef INITIAL_DBUFS
   dbuf_init();			/* set up some dbuf stuff to control paging */
#endif

   sbrk0 = (char *) sbrk((size_t) 0);
   uid = getuid();
   euid = geteuid();
#ifdef	PROFIL
   (void) monstartup(0, etext);
   (void) moncontrol(1);
   (void) signal(SIGUSR1, s_monitor);
#endif
	
   myargv = argv;
   (void) umask(077);		/* better safe than sorry --SRB  */
   memset((char *) &me, '\0', sizeof(me));
	
   setup_signals();
   /*
    * * All command line parameters have the syntax "-fstring"  or "-f
    * string" (e.g. the space is optional). String may  be empty. Flag
    * characters cannot be concatenated (like "-fxyz"), it would
    * conflict with the form "-fstring".
    */
   while (--argc > 0 && (*++argv)[0] == '-') 
   {
	char       *p = argv[0] + 1;
	int         flag = *p++;
		
        if (flag == '\0' || *p == '\0') 
	{
	   if (argc > 1 && argv[1][0] != '-') 
	   {
		p = *++argv;
		argc -= 1;
	   }
	   else
		p = "";
	   }
		
      switch (flag) 
      {
		 case 'a':
			bootopt |= BOOT_AUTODIE;
			break;
		 case 'c':
			bootopt |= BOOT_CONSOLE;
			break;
		 case 'q':
			bootopt |= BOOT_QUICK;
			break;
		 case 'd':
			(void) setuid((uid_t) uid);
			dpath = p;
			break;
		 case 'o':		/* Per user local daemon... */
			(void) setuid((uid_t) uid);
			bootopt |= BOOT_OPER;
			break;
#ifdef CMDLINE_CONFIG
		 case 'f':
			(void) setuid((uid_t) uid);
			configfile = p;
			break;
			
# ifdef KPATH
		 case 'k':
			(void) setuid((uid_t) uid);
			klinefile = p;
			break;
# endif
			
#endif
		 case 'h':
			strncpyzt(me.name, p, sizeof(me.name));
			break;
		 case 'i':
			bootopt |= BOOT_INETD | BOOT_AUTODIE;
			break;
		 case 'p':
			if ((portarg = atoi(p)) > 0)
			  portnum = portarg;
			break;
		 case 's':
			bootopt |= BOOT_STDERR;
			break;
		 case 't':
			(void) setuid((uid_t) uid);
			bootopt |= BOOT_TTY;
			break;
		 case 'v':
			(void) printf("ircd %s\n", version);
			exit(0);
		 case 'x':
#ifdef	DEBUGMODE
			(void) setuid((uid_t) uid);
			debuglevel = atoi(p);
			debugmode = *p ? p : "0";
			bootopt |= BOOT_DEBUG;
			break;
#else
			(void) fprintf(stderr,
				"%s: DEBUGMODE must be defined for -x y\n",
								myargv[0]);
			exit(0);
#endif
		 default:
			bad_command();
			break;
      }
   }
	
   if (chdir(dpath)) 
   {
      perror("chdir");
      exit(-1);
   }
   if ((uid != euid) && !euid) 
   {
      (void) fprintf(stderr,
	"ERROR: do not run ircd setuid root. Make it setuid a normal user.\n");
      exit(-1);
   }
	
   if (argc > 0)
	  return bad_command();	/* This should exit out  */
   initialize_ssl();

   motd = (aMotd *) NULL;
   helpfile = (aMotd *) NULL;
   motd_tm = NULL;
#ifdef SHORT_MOTD
   shortmotd = NULL;
#endif
	
   read_motd(MOTD);
   read_help(HELPFILE);
#ifdef SHORT_MOTD
   read_shortmotd(SHORTMOTD);
#endif
	
   clear_client_hash_table();
   clear_channel_hash_table();
   clear_scache_hash_table();	/* server cache name table */
   clear_ip_hash_table();	/* client host ip hash table */

   initlists();
   initclass();
   initwhowas();
   initstats();
   init_tree_parse(msgtab);
   init_send();
   NOW = time(NULL);
   open_debugfile();
   NOW = time(NULL);
   init_fdlist(&serv_fdlist);
   init_fdlist(&oper_fdlist);
   init_fdlist(&listen_fdlist);
	
#ifndef NO_PRIORITY
   init_fdlist(&busycli_fdlist);
#endif
	
   init_fdlist(&default_fdlist);
	  {
		  int i;
		  
		  for (i = MAXCONNECTIONS + 1; i > 0; i--) 
		  {
			  default_fdlist.entry[i] = i - 1;
		  }
	  }

   if ((timeofday = time(NULL)) == -1) 
   {
#ifdef USE_SYSLOG
      syslog(LOG_WARNING, "Clock Failure (%d), TS can be corrupted", errno);
#endif
      sendto_ops("Clock Failure (%d), TS can be corrupted", errno);
   }

#ifdef WINGATE_NOTICE
   strcpy(ProxyMonURL, "http://");
   strncpyzt((ProxyMonURL + 7), DEFAULT_PROXY_INFO_URL, (TOPICLEN + 1) - 7);
   strncpyzt(ProxyMonHost, MONITOR_HOST, (HOSTLEN + 1));
#endif
	
   if (portnum < 0)
	  portnum = PORTNUM;
   me.port = portnum;
   (void) init_sys();
   me.flags = FLAGS_LISTEN;
#ifndef _WIN32
   if (bootopt & BOOT_INETD) 
   {
      me.fd = 0;
      local[0] = &me;
      me.flags = FLAGS_LISTEN;
   }
   else
#endif
	  me.fd = -1;
	
#ifdef USE_SYSLOG
# define SYSLOG_ME     "ircd"
   openlog(SYSLOG_ME, LOG_PID | LOG_NDELAY, LOG_FACILITY);
#endif
   if ((fd = openconf(configfile)) == -1) 
   {
      Debug((DEBUG_FATAL, "Failed in reading configuration file %s",
				 configfile));
      (void) printf("Couldn't open configuration file %s\n",
						  configfile);
      exit(-1);
   }
   (void) initconf(bootopt, fd);
	
   /* comstuds SEPARATE_QUOTE_KLINES_BY_DATE code */
#ifdef SEPARATE_QUOTE_KLINES_BY_DATE
	  {
		  struct tm  *tmptr;
		  char        timebuffer[20], filename[200];
		  
		  tmptr = localtime(&NOW);
		  (void) strftime(timebuffer, 20, "%y%m%d", tmptr);
		  ircsprintf(filename, "%s.%s", klinefile, timebuffer);
		  if ((fd = openconf(filename)) == -1) 
		  {
			  Debug((DEBUG_ERROR, "Failed reading kline file %s",
						filename));
			  (void) printf("Couldn't open kline file %s\n",
								 filename);
		  }
		  else
			 (void) initconf(0, fd);
	  }
#else
# ifdef KPATH
   if ((fd = openconf(klinefile)) == -1) 
   {
      Debug((DEBUG_ERROR, "Failed reading kline file %s", klinefile));
      (void) printf("Couldn't open kline file %s\n", klinefile);
   }
   else
	  (void) initconf(0, fd);
# endif
#endif
   if (!(bootopt & BOOT_INETD)) 
   {
		static char star[] = "*";
		aConfItem  *aconf;
		u_long      vaddr;
		
      if ((aconf = find_me()) && portarg <= 0 && aconf->port > 0)
		  portnum = aconf->port;

      Debug((DEBUG_ERROR, "Port = %d", portnum));

      if ((aconf->passwd[0] != '\0') && (aconf->passwd[0] != '*'))
		  vaddr = inet_addr(aconf->passwd);
      else
		  vaddr = (u_long) NULL;
		
      if (inetport(&me, star, portnum, vaddr)) 
      {
			if (bootopt & BOOT_STDERR)
			  fprintf(stderr, "Couldn't bind to primary port %d\n", portnum);
#ifdef USE_SYSLOG
			(void) syslog(LOG_CRIT, "Couldn't bind to primary port %d\n", portnum);
#endif
			exit(1);
      }
   }
   else if (inetport(&me, "*", 0, 0)) 
   {
      if (bootopt & BOOT_STDERR)
		  fprintf(stderr, "Couldn't bind to port passed from inetd\n");
#ifdef USE_SYSLOG
      (void) syslog(LOG_CRIT, "Couldn't bind to port passed from inetd\n");
#endif
      exit(1);
   }
	
   (void) get_my_name(&me, me.sockhost, sizeof(me.sockhost) - 1);
   if (me.name[0] == '\0')
	  strncpyzt(me.name, me.sockhost, sizeof(me.name));
   me.hopcount = 0;
   me.authfd = -1;
   me.confs = NULL;
   me.next = NULL;
   me.user = NULL;
   me.from = &me;
   SetMe(&me);
   make_server(&me);
   me.serv->up = me.name;
   me.lasttime = me.since = me.firsttime = NOW;
   (void) add_to_client_hash_table(me.name, &me);
	
   /* We don't want to calculate these every time they are used :) */
	
   sprintf(REPORT_DO_DNS, REPORT_DO_DNS_, me.name);
   sprintf(REPORT_FIN_DNS, REPORT_FIN_DNS_, me.name);
   sprintf(REPORT_FIN_DNSC, REPORT_FIN_DNSC_, me.name);
   sprintf(REPORT_FAIL_DNS, REPORT_FAIL_DNS_, me.name);
   sprintf(REPORT_DO_ID, REPORT_DO_ID_, me.name);
   sprintf(REPORT_FIN_ID, REPORT_FIN_ID_, me.name);
   sprintf(REPORT_FAIL_ID, REPORT_FAIL_ID_, me.name);
   R_do_dns = strlen(REPORT_DO_DNS);
   R_fin_dns = strlen(REPORT_FIN_DNS);
   R_fin_dnsc = strlen(REPORT_FIN_DNSC);
   R_fail_dns = strlen(REPORT_FAIL_DNS);
   R_do_id = strlen(REPORT_DO_ID);
   R_fin_id = strlen(REPORT_FIN_ID);
   R_fail_id = strlen(REPORT_FAIL_ID);
	
   check_class();
   if (bootopt & BOOT_OPER) 
   {
      aClient    *tmp = add_connection(&me, 0);
		
      if (!tmp)
		  exit(1);
      SetMaster(tmp);
   }
   else
	  write_pidfile();
	
   Debug((DEBUG_NOTICE, "Server ready..."));
#ifdef USE_SYSLOG
   syslog(LOG_NOTICE, "Server Ready");
#endif
   NOW = time(NULL);
	
#ifndef NO_PRIORITY
   check_fdlists();
#endif
	
   if ((timeofday = time(NULL)) == -1) 
   {
#ifdef USE_SYSLOG
      syslog(LOG_WARNING, "Clock Failure (%d), TS can be corrupted", errno);
#endif
      sendto_ops("Clock Failure (%d), TS can be corrupted", errno);
   }

#ifdef DUMP_DEBUG
   dumpfp=fopen("dump.log", "w");
#endif

   io_loop();
   return 0;
}
Exemplo n.º 17
0
/*
 main server.
*/
static int binary_smbd_main(const char *binary_name, int argc, const char *argv[])
{
	bool opt_daemon = false;
	bool opt_interactive = false;
	int opt;
	poptContext pc;
#define _MODULE_PROTO(init) extern NTSTATUS init(void);
	STATIC_service_MODULES_PROTO;
	init_module_fn static_init[] = { STATIC_service_MODULES };
	init_module_fn *shared_init;
	struct tevent_context *event_ctx;
	uint16_t stdin_event_flags;
	NTSTATUS status;
	const char *model = "standard";
	int max_runtime = 0;
	enum {
		OPT_DAEMON = 1000,
		OPT_INTERACTIVE,
		OPT_PROCESS_MODEL,
		OPT_SHOW_BUILD
	};
	struct poptOption long_options[] = {
		POPT_AUTOHELP
		{"daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON,
		 "Become a daemon (default)", NULL },
		{"interactive",	'i', POPT_ARG_NONE, NULL, OPT_INTERACTIVE,
		 "Run interactive (not a daemon)", NULL},
		{"model", 'M', POPT_ARG_STRING,	NULL, OPT_PROCESS_MODEL, 
		 "Select process model", "MODEL"},
		{"maximum-runtime",0, POPT_ARG_INT, &max_runtime, 0, 
		 "set maximum runtime of the server process, till autotermination", "seconds"},
		{"show-build", 'b', POPT_ARG_NONE, NULL, OPT_SHOW_BUILD, "show build info", NULL },
		POPT_COMMON_SAMBA
		POPT_COMMON_VERSION
		{ NULL }
	};

	pc = poptGetContext(binary_name, argc, argv, long_options, 0);
	while((opt = poptGetNextOpt(pc)) != -1) {
		switch(opt) {
		case OPT_DAEMON:
			opt_daemon = true;
			break;
		case OPT_INTERACTIVE:
			opt_interactive = true;
			break;
		case OPT_PROCESS_MODEL:
			model = poptGetOptArg(pc);
			break;
		case OPT_SHOW_BUILD:
			show_build();
			break;
		default:
			fprintf(stderr, "\nInvalid option %s: %s\n\n",
				  poptBadOption(pc, 0), poptStrerror(opt));
			poptPrintUsage(pc, stderr, 0);
			return 1;
		}
	}

	if (opt_daemon && opt_interactive) {
		fprintf(stderr,"\nERROR: "
			  "Option -i|--interactive is not allowed together with -D|--daemon\n\n");
		poptPrintUsage(pc, stderr, 0);
		return 1;
	} else if (!opt_interactive) {
		/* default is --daemon */
		opt_daemon = true;
	}

	poptFreeContext(pc);

	setup_logging(binary_name, opt_interactive?DEBUG_STDOUT:DEBUG_FILE);
	setup_signals();

	/* we want total control over the permissions on created files,
	   so set our umask to 0 */
	umask(0);

	DEBUG(0,("%s version %s started.\n", binary_name, SAMBA_VERSION_STRING));
	DEBUGADD(0,("Copyright Andrew Tridgell and the Samba Team 1992-2011\n"));

	if (sizeof(uint16_t) < 2 || sizeof(uint32_t) < 4 || sizeof(uint64_t) < 8) {
		DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
		DEBUGADD(0,("sizeof(uint16_t) = %u, sizeof(uint32_t) %u, sizeof(uint64_t) = %u\n",
			    (unsigned int)sizeof(uint16_t), (unsigned int)sizeof(uint32_t), (unsigned int)sizeof(uint64_t)));
		return 1;
	}

	if (opt_daemon) {
		DEBUG(3,("Becoming a daemon.\n"));
		become_daemon(true, false, false);
	}

	cleanup_tmp_files(cmdline_lp_ctx);

	if (!directory_exist(lpcfg_lockdir(cmdline_lp_ctx))) {
		mkdir(lpcfg_lockdir(cmdline_lp_ctx), 0755);
	}

	pidfile_create(lpcfg_piddir(cmdline_lp_ctx), binary_name);

	/* Set up a database to hold a random seed, in case we don't
	 * have /dev/urandom */
	if (!randseed_init(talloc_autofree_context(), cmdline_lp_ctx)) {
		return 1;
	}

	if (lpcfg_server_role(cmdline_lp_ctx) == ROLE_DOMAIN_CONTROLLER) {
		if (!open_schannel_session_store(talloc_autofree_context(), lpcfg_private_dir(cmdline_lp_ctx))) {
			DEBUG(0,("ERROR: Samba cannot open schannel store for secured NETLOGON operations.\n"));
			exit(1);
		}
	}

	gensec_init(); /* FIXME: */

	ntptr_init();	/* FIXME: maybe run this in the initialization function 
						of the spoolss RPC server instead? */

	ntvfs_init(cmdline_lp_ctx); 	/* FIXME: maybe run this in the initialization functions 
						of the SMB[,2] server instead? */

	process_model_init(cmdline_lp_ctx); 

	shared_init = load_samba_modules(NULL, "service");

	run_init_functions(static_init);
	run_init_functions(shared_init);

	talloc_free(shared_init);
	
	/* the event context is the top level structure in smbd. Everything else
	   should hang off that */
	event_ctx = s4_event_context_init(talloc_autofree_context());

	if (event_ctx == NULL) {
		DEBUG(0,("Initializing event context failed\n"));
		return 1;
	}

	if (opt_interactive) {
		/* terminate when stdin goes away */
		stdin_event_flags = TEVENT_FD_READ;
	} else {
		/* stay alive forever */
		stdin_event_flags = 0;
	}

	/* catch EOF on stdin */
#ifdef SIGTTIN
	signal(SIGTTIN, SIG_IGN);
#endif
	tevent_add_fd(event_ctx, event_ctx, 0, stdin_event_flags,
		      server_stdin_handler,
		      discard_const(binary_name));

	if (max_runtime) {
		DEBUG(0,("Called with maxruntime %d - current ts %llu\n",
		      max_runtime, (unsigned long long) time(NULL)));
		tevent_add_timer(event_ctx, event_ctx,
				 timeval_current_ofs(max_runtime, 0),
				 max_runtime_handler,
				 discard_const(binary_name));
	}

	prime_ldb_databases(event_ctx);

	status = setup_parent_messaging(event_ctx, cmdline_lp_ctx);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(0,("Failed to setup parent messaging - %s\n", nt_errstr(status)));
		return 1;
	}

	DEBUG(0,("%s: using '%s' process model\n", binary_name, model));

	status = server_service_startup(event_ctx, cmdline_lp_ctx, model, 
					lpcfg_server_services(cmdline_lp_ctx));
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(0,("Starting Services failed - %s\n", nt_errstr(status)));
		return 1;
	}

	/* wait for events - this is where smbd sits for most of its
	   life */
	tevent_loop_wait(event_ctx);

	/* as everything hangs off this event context, freeing it
	   should initiate a clean shutdown of all services */
	talloc_free(event_ctx);

	return 0;
}
Exemplo n.º 18
0
/* Entry-point.  Has same semantics as main(). */
static int
vifm_main(int argc, char *argv[])
{
	/* TODO: refactor vifm_main() function */

	static const int quit = 0;

	char **files = NULL;
	int nfiles = 0;
	int lwin_cv, rwin_cv;

	char dir[PATH_MAX + 1];
	if(get_start_cwd(dir, sizeof(dir)) != 0)
	{
		return -1;
	}

	args_parse(&vifm_args, argc, argv, dir);
	args_process(&vifm_args, 1);

	lwin_cv = (strcmp(vifm_args.lwin_path, "-") == 0 && vifm_args.lwin_handle);
	rwin_cv = (strcmp(vifm_args.rwin_path, "-") == 0 && vifm_args.rwin_handle);
	if(lwin_cv || rwin_cv)
	{
		files = read_stream_lines(stdin, &nfiles, 1, NULL, NULL);
		if(reopen_term_stdin() != 0)
		{
			free_string_array(files, nfiles);
			return EXIT_FAILURE;
		}
	}

	(void)setlocale(LC_ALL, "");
	srand(time(NULL));

	cfg_init();

	if(vifm_args.logging)
	{
		init_logger(1, vifm_args.startup_log_path);
	}

	init_filelists();
	tabs_init();
	regs_init();
	cfg_discover_paths();
	reinit_logger(cfg.log_file);

	/* Commands module also initializes bracket notation and variables. */
	init_commands();

	init_builtin_functions();
	update_path_env(1);

	if(stats_init(&cfg) != 0)
	{
		free_string_array(files, nfiles);

		puts("Error during session status initialization.");
		return -1;
	}

	/* Tell file type module what function to use to check availability of
	 * external programs. */
	ft_init(&external_command_exists);
	/* This should be called before loading any configuration file. */
	ft_reset(curr_stats.exec_env_type == EET_EMULATOR_WITH_X);

	init_option_handlers();

	if(!vifm_args.no_configs)
	{
		/* vifminfo must be processed this early so that it can restore last visited
		 * directory. */
		read_info_file(0);
	}

	curr_stats.ipc = ipc_init(vifm_args.server_name, &parse_received_arguments,
			&eval_received_expression);
	if(ipc_enabled() && curr_stats.ipc == NULL)
	{
		fputs("Failed to initialize IPC unit", stderr);
		return -1;
	}
	/* Export chosen server name to parsing unit. */
	{
		var_t var = var_from_str(ipc_get_name(curr_stats.ipc));
		setvar("v:servername", var);
		var_free(var);
	}

	args_process(&vifm_args, 0);

	bg_init();

	fops_init(&enter_prompt_mode, &prompt_msg_custom);

	set_view_path(&lwin, vifm_args.lwin_path);
	set_view_path(&rwin, vifm_args.rwin_path);

	if(need_to_switch_active_pane(vifm_args.lwin_path, vifm_args.rwin_path))
	{
		swap_view_roles();
	}

	load_initial_directory(&lwin, dir);
	load_initial_directory(&rwin, dir);

	/* Force split view when two paths are specified on command-line. */
	if(vifm_args.lwin_path[0] != '\0' && vifm_args.rwin_path[0] != '\0')
	{
		curr_stats.number_of_windows = 2;
	}

	/* Prepare terminal for further operations. */
	curr_stats.original_stdout = reopen_term_stdout();
	if(curr_stats.original_stdout == NULL)
	{
		free_string_array(files, nfiles);
		return -1;
	}

	if(!setup_ncurses_interface())
	{
		free_string_array(files, nfiles);
		return -1;
	}

	init_modes();
	un_init(&undo_perform_func, NULL, &ui_cancellation_requested,
			&cfg.undo_levels);
	load_view_options(curr_view);

	curr_stats.load_stage = 1;

	/* Make v:count exist during processing configuration. */
	set_count_vars(0);

	if(!vifm_args.no_configs)
	{
		load_scheme();
		cfg_load();
	}

	if(lwin_cv || rwin_cv)
	{
		flist_custom_set(lwin_cv ? &lwin : &rwin, "-", dir, files, nfiles);
	}
	free_string_array(files, nfiles);

	cs_load_pairs();
	cs_write();
	setup_signals();

	/* Ensure trash directories exist, it might not have been called during
	 * configuration file sourcing if there is no `set trashdir=...` command. */
	(void)set_trash_dir(cfg.trash_dir);

	check_path_for_file(&lwin, vifm_args.lwin_path, vifm_args.lwin_handle);
	check_path_for_file(&rwin, vifm_args.rwin_path, vifm_args.rwin_handle);

	curr_stats.load_stage = 2;

	/* Update histories of the views to ensure that their current directories,
	 * which might have been set using command-line parameters, are stored in the
	 * history.  This is not done automatically as history manipulation should be
	 * postponed until views are fully loaded, otherwise there is no correct
	 * information about current file and relative cursor position. */
	flist_hist_save(&lwin, NULL, NULL, -1);
	flist_hist_save(&rwin, NULL, NULL, -1);

	/* Trigger auto-commands for initial directories. */
	if(!lwin_cv)
	{
		(void)vifm_chdir(flist_get_dir(&lwin));
		vle_aucmd_execute("DirEnter", flist_get_dir(&lwin), &lwin);
	}
	if(!rwin_cv)
	{
		(void)vifm_chdir(flist_get_dir(&rwin));
		vle_aucmd_execute("DirEnter", flist_get_dir(&rwin), &rwin);
	}

	update_screen(UT_FULL);
	modes_update();

	/* Run startup commands after loading file lists into views, so that commands
	 * like +1 work. */
	exec_startup_commands(&vifm_args);

	curr_stats.load_stage = 3;

	event_loop(&quit);

	return 0;
}
Exemplo n.º 19
0
int
main(int argc, char *argv[])
{
	struct weston_launch wl;
	int i, c;
	char *tty = NULL;
	struct option opts[] = {
		{ "user",    required_argument, NULL, 'u' },
		{ "tty",     required_argument, NULL, 't' },
		{ "verbose", no_argument,       NULL, 'v' },
		{ "help",    no_argument,       NULL, 'h' },
		{ 0,         0,                 NULL,  0  }
	};	

	memset(&wl, 0, sizeof wl);

	while ((c = getopt_long(argc, argv, "u:t::vh", opts, &i)) != -1) {
		switch (c) {
		case 'u':
			wl.new_user = optarg;
			if (getuid() != 0)
				error(1, 0, "Permission denied. -u allowed for root only");
			break;
		case 't':
			tty = optarg;
			break;
		case 'v':
			wl.verbose = 1;
			break;
		case 'h':
			help("weston-launch");
			exit(EXIT_FAILURE);
		}
	}

	if ((argc - optind) > (MAX_ARGV_SIZE - 6))
		error(1, E2BIG, "Too many arguments to pass to weston");

	if (wl.new_user)
		wl.pw = getpwnam(wl.new_user);
	else
		wl.pw = getpwuid(getuid());
	if (wl.pw == NULL)
		error(1, errno, "failed to get username");

	if (!weston_launch_allowed(&wl))
		error(1, 0, "Permission denied. You should either:\n"
#ifdef HAVE_SYSTEMD_LOGIN
		      " - run from an active and local (systemd) session.\n"
#else
		      " - enable systemd session support for weston-launch.\n"
#endif
		      " - or add yourself to the 'weston-launch' group.");

	if (setup_tty(&wl, tty) < 0)
		exit(EXIT_FAILURE);

	if (wl.new_user && setup_pam(&wl) < 0)
		exit(EXIT_FAILURE);

	if (setup_launcher_socket(&wl) < 0)
		exit(EXIT_FAILURE);

	if (setup_signals(&wl) < 0)
		exit(EXIT_FAILURE);

	wl.child = fork();
	if (wl.child == -1) {
		error(1, errno, "fork failed");
		exit(EXIT_FAILURE);
	}

	if (wl.child == 0)
		launch_compositor(&wl, argc - optind, argv + optind);

	close(wl.sock[1]);
	if (wl.tty != STDIN_FILENO)
		close(wl.tty);

	while (1) {
		struct pollfd fds[2];
		int n;

		fds[0].fd = wl.sock[0];
		fds[0].events = POLLIN;
		fds[1].fd = wl.signalfd;
		fds[1].events = POLLIN;

		n = poll(fds, 2, -1);
		if (n < 0)
			error(0, errno, "poll failed");
		if (fds[0].revents & POLLIN)
			handle_socket_msg(&wl);
		if (fds[1].revents)
			handle_signal(&wl);
	}

	return 0;
}
Exemplo n.º 20
0
int main(int argc, char **argv) {	
  int c;

  // disable buffering for stdout and stderr streams
  setvbuf(stdout, NULL, _IONBF, 0);
  setvbuf(stderr, NULL, _IONBF, 0);

  // print out pid (for logger)
  printf("%d\n",getpid());

  Progname  = argv[0];
  fsname  = NULL;

  while ((c = getopt(argc, argv, "v")) != EOF) {
    switch (c) {
    case 'v':
      Verbose = 1;
      break;
    case '?':
      default:
      usage(Progname);
      exit(1);
    }
  }
  if ((argc-optind)!=2) {
    usage(Progname);
    exit(1);
  }
  DMAPI_SESSION_NAME = argv[optind++];
  fsname = argv[optind];
  

  // reset global state
  global_state=0;

  printf("Starting up yamssRecallDaemon\n");

  // setup various signal handlers
  printf("Installing signal handlers\n");
  setup_signals();	
  
  // initialize dmap
  printf("Initializing DMAPI\n");
  setup_dmapi();

  // setup event disposition for mount
  printf("Setting disposition for MOUNT events\n");
  register_mount();

  // recover existing tokens for mount events
  printf("Recovering existing tokens for MOUNT events\n");
  token_recovery(DM_EVENT_MOUNT);

  // try to finalize inizialization
  finalize_init();

  // start main loop
  printf("Starting main event loop\n");
  event_loop();
  return(0);
}
Exemplo n.º 21
0
int main(int argc, char **argv) {
  auto_handle *session = NULL;
  char *config_file = NULL;
  char *logfile = NULL;
  char *xmlfile = NULL;
  char erbuf[100];
  NODE *current = NULL;
  uint32_t count = 0;
  uint8_t first_run = 1;
  uint8_t once = 0;
  uint8_t verbose = AM_DEFAULT_VERBOSE;
  uint8_t append_log = 0;
  uint8_t match_only = 0;

  /* this sets the log level to the default before anything else is done.
  ** This way, if any outputting happens in readargs(), it'll be printed
  ** to stderr.
  */
  log_init(NULL, verbose, 0);

  readargs(argc, argv, &config_file, &logfile, &xmlfile, &nofork, &verbose, &once, &append_log, &match_only);

  /* reinitialize the logging with the values from the command line */
  log_init(logfile, verbose, append_log);

  if(!config_file) {
    config_file = am_strdup(AM_DEFAULT_CONFIGFILE);
  }
  strncpy(AutoConfigFile, config_file, strlen(config_file));

  session = session_init();
  session->match_only = match_only;

  if(parse_config_file(session, AutoConfigFile) != 0) {
    if(errno == ENOENT) {
      snprintf(erbuf, sizeof(erbuf), "Cannot find file '%s'", config_file);
    } else {
      snprintf(erbuf, sizeof(erbuf), "Unknown error");
    }
    fprintf(stderr, "Error parsing config file: %s\n", erbuf);
    shutdown_daemon(session);
  }

  setup_signals();

  if(!nofork) {

    /* start daemon */
    if(daemonize() != 0) {
      dbg_printf(P_ERROR, "Error: Daemonize failed. Aborting...");
      shutdown_daemon(session);
    }

    dbg_printft( P_MSG, "Daemon started");
  }

  filter_printList(session->filters);

  dbg_printf(P_MSG, "Trailermatic version: %s", LONG_VERSION_STRING);
  dbg_printf(P_INFO, "verbose level: %d", verbose);
  dbg_printf(P_INFO, "foreground mode: %s", nofork == 1 ? "yes" : "no");
  dbg_printf(P_INFO, "config file: %s", AutoConfigFile);
  dbg_printf(P_INFO, "check interval: %d min", session->check_interval);
  dbg_printf(P_INFO, "download folder: %s", session->download_folder);
  dbg_printf(P_INFO, "state file: %s", session->statefile);
  dbg_printf(P_MSG,  "%d feed URLs", listCount(session->feeds));
  dbg_printf(P_MSG,  "Read %d filters from config file", listCount(session->filters));

  if(session->prowl_key) {
    dbg_printf(P_INFO, "Prowl API key: %s", session->prowl_key);
  }

  if(listCount(session->feeds) == 0) {
    dbg_printf(P_ERROR, "No feed URL specified in trailermatic.conf!\n");
    shutdown_daemon(session);
  }

  if(listCount(session->filters) == 0) {
    dbg_printf(P_ERROR, "No filters specified in trailermatic.conf!\n");
    shutdown_daemon(session);
  }

  /* check if Prowl API key is given, and if it is valid */
  if(session->prowl_key && verifyProwlAPIKey(session->prowl_key) ) {
    session->prowl_key_valid = 1;
  }

  load_state(session->statefile, &session->downloads);
  while(!closing) {
    dbg_printft( P_INFO, "------ Checking for new trailers ------");
     if(xmlfile && *xmlfile) {
       processFile(session, xmlfile);
       once = 1;
    } else {
      current = session->feeds;
      count = 0;
      while(current && current->data) {
        ++count;
        dbg_printf(P_INFO2, "Checking feed %d ...", count);
        processFeed(session, current->data, first_run);
        current = current->next;
      }
      if(first_run) {
        dbg_printf(P_INFO2, "New bucket size: %d", session->max_bucket_items);
      }
      first_run = 0;
    }
    /* leave loop when program is only supposed to run once */
    if(once) {
      break;
    }
    sleep(session->check_interval * 60);
  }
  shutdown_daemon(session);
  return 0;
}
Exemplo n.º 22
0
int
main(int argc, char *argv[])
{
  /* Check to see if the user is running us as root, which is a nono */
  if (!geteuid())
  {
    fprintf(stderr, "ERROR: This server won't run as root/superuser\n");
    return -1;
  }

  /* Setup corefile size immediately after boot -kre */
  setup_corefile();

  /* Save server boot time right away, so getrusage works correctly */
  set_time();

  /* It's not random, but it ought to be a little harder to guess */
  init_genrand(SystemTime.tv_sec ^ (SystemTime.tv_usec | (getpid() << 20)));

  dlinkAdd(&me, &me.node, &global_client_list);

  ConfigGeneral.dpath      = DPATH;
  ConfigGeneral.spath      = SPATH;
  ConfigGeneral.mpath      = MPATH;
  ConfigGeneral.configfile = CPATH;    /* Server configuration file */
  ConfigGeneral.klinefile  = KPATH;    /* Server kline file         */
  ConfigGeneral.glinefile  = GPATH;    /* Server gline file         */
  ConfigGeneral.xlinefile  = XPATH;    /* Server xline file         */
  ConfigGeneral.dlinefile  = DLPATH;   /* dline file                */
  ConfigGeneral.resvfile   = RESVPATH; /* resv file                 */

  myargv = argv;
  umask(077);  /* umask 077: u=rwx,g=,o= */

  parseargs(&argc, &argv, myopts);

  if (printVersion)
  {
    printf("ircd: version %s(%s)\n", ircd_version, serno);
    exit(EXIT_SUCCESS);
  }

  if (chdir(ConfigGeneral.dpath))
  {
    perror("chdir");
    exit(EXIT_FAILURE);
  }

  ssl_init();

  if (!server_state.foreground)
  {
    make_daemon();
    close_standard_fds(); /* this needs to be before init_netio()! */
  }
  else
    print_startup(getpid());

  setup_signals();

  /* We need this to initialise the fd array before anything else */
  fdlist_init();
  log_set_file(LOG_TYPE_IRCD, 0, logFileName);

  init_netio();         /* This needs to be setup early ! -- adrian */

  /* Check if there is pidfile and daemon already running */
  check_pidfile(pidFileName);

  mp_pool_init();
  init_dlink_nodes();
  init_isupport();
  dbuf_init();
  hash_init();
  ipcache_init();
  client_init();
  class_init();
  whowas_init();
  watch_init();
  auth_init();          /* Initialise the auth code */
  init_resolver();      /* Needs to be setup before the io loop */
  modules_init();
  read_conf_files(1);   /* cold start init conf files */
  init_uid();
  initialize_server_capabs();   /* Set up default_server_capabs */
  initialize_global_set_options();  /* Has to be called after read_conf_files() */
  channel_init();
  read_links_file();
  motd_init();
  user_usermodes_init();
#ifdef HAVE_LIBGEOIP
  geoip_ctx = GeoIP_new(GEOIP_MEMORY_CACHE);
#endif

  if (EmptyString(ConfigServerInfo.sid))
  {
    ilog(LOG_TYPE_IRCD, "ERROR: No server id specified in serverinfo block.");
    exit(EXIT_FAILURE);
  }

  strlcpy(me.id, ConfigServerInfo.sid, sizeof(me.id));

  if (EmptyString(ConfigServerInfo.name))
  {
    ilog(LOG_TYPE_IRCD, "ERROR: No server name specified in serverinfo block.");
    exit(EXIT_FAILURE);
  }

  strlcpy(me.name, ConfigServerInfo.name, sizeof(me.name));

  /* serverinfo{} description must exist.  If not, error out.*/
  if (EmptyString(ConfigServerInfo.description))
  {
    ilog(LOG_TYPE_IRCD, "ERROR: No server description specified in serverinfo block.");
    exit(EXIT_FAILURE);
  }

  strlcpy(me.info, ConfigServerInfo.description, sizeof(me.info));

  me.from = &me;
  me.servptr = &me;
  me.connection->lasttime = CurrentTime;
  me.connection->since = CurrentTime;
  me.connection->firsttime = CurrentTime;

  SetMe(&me);
  make_server(&me);

  hash_add_id(&me);
  hash_add_client(&me);

  dlinkAdd(&me, make_dlink_node(), &global_server_list);

  load_kline_database();
  load_dline_database();
  load_gline_database();
  load_xline_database();
  load_resv_database();

  load_all_modules(1);
  load_conf_modules();
  load_core_modules(1);

  write_pidfile(pidFileName);

  ilog(LOG_TYPE_IRCD, "Server Ready");

  event_addish(&event_cleanup_glines, NULL);
  event_addish(&event_cleanup_tklines, NULL);

  /* We want try_connections to be called as soon as possible now! -- adrian */
  /* No, 'cause after a restart it would cause all sorts of nick collides */
  event_addish(&event_try_connections, NULL);

  /* Setup the timeout check. I'll shift it later :)  -- adrian */
  event_add(&event_comm_checktimeouts, NULL);

  event_addish(&event_save_all_databases, NULL);

  if (ConfigServerHide.links_delay > 0)
  {
    event_write_links_file.when = ConfigServerHide.links_delay;
    event_addish(&event_write_links_file, NULL);
  }
  else
    ConfigServerHide.links_disabled = 1;

  if (splitmode)
    event_addish(&splitmode_event, NULL);

  io_loop();
  return 0;
}
Exemplo n.º 23
0
/*
 * Entry point. Process command line options, start up pcap and enter capture loop.
 */
int main(int argc, char *argv[])
{
    pthread_t packetth;
    options_t *options;

    options = parse_options(argc, argv);

    if (options->verbose)
        set_loglevel(LOG_INFO);

    if (options->adjunct)
        create_pidfile();

    /*
     * In adjunct mode, it's important that the attached program gets
     * notification of images in a timely manner. Make stdout line-buffered
     * for this reason.
     */
    if (options->adjunct)
        setvbuf(stdout, NULL, _IOLBF, 0);

    /*
     * If a directory name has not been specified, then we need to create one.
     * Otherwise, check that it's a directory into which we may write files.
     */
    if (options->tmpdir) {
        check_dir_is_rw(options->tmpdir);
        set_tmpdir(options->tmpdir, TMPDIR_USER_OWNED, options->max_tmpfiles, options->adjunct);

    } else {
        /* need to make a temporary directory. */
        set_tmpdir(make_tmpdir(), TMPDIR_APP_OWNED, options->max_tmpfiles, options->adjunct);
    }

    setup_signals();

    /* Start up the audio player, if required. */
    if (!options->adjunct && (options->extract_type & m_audio))
        do_mpeg_player();

#ifndef NO_DISPLAY_WINDOW
    /* Possibly fork to start the display child process */
    if (!options->adjunct && (options->extract_type & m_image))
        do_image_display(options->savedimgpfx, options->beep);
    else
        log_msg(LOG_INFO, "operating in adjunct mode");
#endif /* !NO_DISPLAY_WINDOW */

    init_mediadrv(options->extract_type, !options->adjunct);

    /* Start up pcap. */
    if (options->dumpfile)
        packetcapture_open_offline(options->dumpfile);
    else
        packetcapture_open_live(options->interface, options->filterexpr, options->promisc);

    connection_alloc_slots();

    /*
     * Actually start the capture stuff up. Unfortunately, on many platforms,
     * libpcap doesn't have read timeouts, so we start the thing up in a
     * separate thread. Yay!
     */
    pthread_create(&packetth, NULL, capture_thread, NULL);

    while (!foad)
        sleep(1);

    if (options->verbose)
        print_exit_reason();

    pthread_cancel(packetth); /* make sure thread quits even if it's stuck in pcap_dispatch */
    pthread_join(packetth, NULL);

    /* Clean up. */
    /*    pcap_freecode(pc, &filter);*/ /* not on some systems... */
    packetcapture_close();

    /* Easier for memory-leak debugging if we deallocate all this here.... */
    connection_free_slots();

    clean_tmpdir();

    if (options->adjunct)
        close_pidfile();

    return 0;
}
Exemplo n.º 24
0
int status_client_ncurses(struct config *conf, enum action act, const char *sclient)
{
	int fd=0;
        int ret=0;
	int sel=0;
	char *rbuf=NULL;
	char buf[512]="";
	int count=0;
	int details=0;
	char *last_rbuf=NULL;
	int srbr=0;
	char *client=NULL;
	int enterpressed=0;
//	int loop=0;
	int reqdone=0;

#ifdef HAVE_NCURSES_H
	int stdinfd=fileno(stdin);
	actg=act; // So that the sighandler can call endwin().
#else
	if(act==ACTION_STATUS)
	{
		printf("To use the live status monitor, you need to recompile with ncurses support.\n");
		return -1;
	}
#endif

	setup_signals();

	/* NULL == ::1 or 127.0.0.1 */
	if((fd=init_client_socket(NULL, conf->status_port))<0)
		return -1;
	set_non_blocking(fd);

#ifdef HAVE_NCURSES_H
	if(actg==ACTION_STATUS)
	{
		initscr();
		start_color();
		init_pair(1, COLOR_WHITE, COLOR_BLACK);
		init_pair(2, COLOR_WHITE, COLOR_BLACK);
		init_pair(3, COLOR_WHITE, COLOR_BLACK);
		raw();
		keypad(stdscr, TRUE);
		noecho();
		curs_set(0);
		halfdelay(3);
		//nodelay(stdscr, TRUE);
	}
#endif
#ifdef DBFP
	dbfp=fopen("/tmp/dbfp", "w");
#endif

	while(!ret)
	{
		int l;
		int mfd=-1;
		fd_set fsr;
		fd_set fse;
		struct timeval tval;

		// Failsafe to prevent the snapshot ever getting permanently
		// stuck.
		//if(act==ACTION_STATUS_SNAPSHOT && loop++>10000)
		//	break;

		if(sclient && !client)
		{
			client=strdup(sclient);
			details=1;
		}

		if((enterpressed || need_status()) && !reqdone)
		{
			char *req=NULL;
			if(details && client) req=client;
			if(request_status(fd, req, conf))
			{
				ret=-1;
				break;
			}
			enterpressed=0;
			if(act==ACTION_STATUS_SNAPSHOT)
				reqdone++;
		}

		FD_ZERO(&fsr);
		FD_ZERO(&fse);

		tval.tv_sec=1;
		tval.tv_usec=0;

		add_fd_to_sets(fd, &fsr, NULL, &fse, &mfd);
#ifdef HAVE_NCURSES_H
		if(actg==ACTION_STATUS)
			add_fd_to_sets(stdinfd, &fsr, NULL, &fse, &mfd);
#endif

		if(select(mfd+1, &fsr, NULL, &fse, &tval)<0)
		{
			if(errno!=EAGAIN && errno!=EINTR)
			{
				logp("select error: %s\n",
					strerror(errno));
				ret=-1;
				break;
			}
			continue;
		}

		if(FD_ISSET(fd, &fse))
		{
			ret=-1;
			break;
		}

#ifdef HAVE_NCURSES_H
		if(actg==ACTION_STATUS)
		{
			if(FD_ISSET(stdinfd, &fse))
			{
				ret=-1;
				break;
			}
			if(FD_ISSET(stdinfd, &fsr))
			{
				int quit=0;
				
				switch(getch())
				{
					case 'q':
					case 'Q':
						quit++;
						break;
					case KEY_UP:
					case 'k':
					case 'K':
						if(details) break;
						sel--;
						break;
					case KEY_DOWN:
					case 'j':
					case 'J':
						if(details) break;
						sel++;
						break;
					case KEY_ENTER:
					case '\n':
					case ' ':
						if(details) details=0;
						else details++;
						enterpressed++;
						break;
					case KEY_LEFT:
					case 'h':
					case 'H':
						details=0;
						break;
					case KEY_RIGHT:
					case 'l':
					case 'L':
						details++;
						break;
					case KEY_NPAGE:
					{
						int row=0, col=0;
						getmaxyx(stdscr, row, col);
						sel+=row-TOP_SPACE;
						break;
					}
					case KEY_PPAGE:
					{
						int row=0, col=0;
						getmaxyx(stdscr, row, col);
						sel-=row-TOP_SPACE;
						break;
					}
				}
				if(quit) break;

				if(sel<0) sel=0;
				if(sel>=count) sel=count-1;

				// Attempt to print stuff to the screen right
				// now, to give the impression of key strokes
				// being responsive.
				if(!details && !sclient)
				{
				  if((srbr=show_rbuf(last_rbuf,
					conf, sel, &client,
					&count, details, sclient))<0)
				  {
					ret=-1;
					break;
				  }
				  if(!details) print_star(sel);
				
				  refresh();
				}
			}
		}
#endif

		if(FD_ISSET(fd, &fsr))
		{
			// ready to read.
			if((l=read(fd, buf, sizeof(buf)-1))>0)
			{
				size_t r=0;
				buf[l]='\0';
				if(rbuf) r=strlen(rbuf);
				rbuf=(char *)realloc(rbuf, r+l+1);
				if(!r) *rbuf='\0';
				strcat(rbuf+r, buf);
			}
			else
				break;

			if(act==ACTION_STATUS_SNAPSHOT)
			{
				if(rbuf)
				{
					if(!strcmp(rbuf, "\n"))
					{
						// This happens when there are
						// no backup clients.
						break;
					}
					if(strstr(rbuf, "\n-list end-\n"))
					{
						printf("%s", rbuf);
						break;
					}
				}
				continue;
			}

			//if(rbuf) printf("rbuf: %s\n", rbuf);
/*
			if(l<0)
			{
				ret=-1;
				break;
			}
*/
		}

		if((srbr=show_rbuf(rbuf, conf,
			sel, &client, &count, details, sclient))<0)
		{
			ret=-1;
			break;
		}
		else if(srbr)
		{
			// Remember it, so that we can present the detailed
			// screen without delay, above.
			if(last_rbuf) free(last_rbuf);
			last_rbuf=rbuf;
			rbuf=NULL;
		}

		if(sclient) details++;

		usleep(20000);
#ifdef HAVE_NCURSES_H
		if(actg==ACTION_STATUS)
		{
			flushinp();
			continue;
		}
#endif
		if(count)
		{
			printf("\n");
			break;
		}
	}
#ifdef HAVE_NCURSES_H
	if(actg==ACTION_STATUS) endwin();
#endif
	close_fd(&fd);
	if(last_rbuf) free(last_rbuf);
	if(rbuf) free(rbuf);
#ifdef DBFP
	if(dbfp) fclose(dbfp);
#endif
	return ret;
}
Exemplo n.º 25
0
void LLApp::setupErrorHandling()
{
	// Error handling is done by starting up an error handling thread, which just sleeps and
	// occasionally checks to see if the app is in an error state, and sees if it needs to be run.

#if LL_WINDOWS
	// This sets a callback to handle w32 signals to the console window.
	// The viewer shouldn't be affected, sicne its a windowed app.
	SetConsoleCtrlHandler( (PHANDLER_ROUTINE) ConsoleCtrlHandler, TRUE);

	// Install the Google Breakpad crash handler for Windows
	if(mExceptionHandler == 0)
	{
		llwarns << "adding breakpad exception handler" << llendl;
		mExceptionHandler = new google_breakpad::ExceptionHandler(
			L"C:\\Temp\\", 0, windows_post_minidump_callback, 0, google_breakpad::ExceptionHandler::HANDLER_ALL);
	}

#else
	//
	// Start up signal handling.
	//
	// There are two different classes of signals.  Synchronous signals are delivered to a specific
	// thread, asynchronous signals can be delivered to any thread (in theory)
	//
	setup_signals();
	
	// Add google breakpad exception handler configured for Darwin/Linux.
	bool installHandler = true;
#ifdef LL_DARWIN
	// For the special case of Darwin, we do not want to install the handler if
	// the process is being debugged as the app will exit with value ABRT (6) if
	// we do.  Unfortunately, the code below which performs that test relies on
	// the structure kinfo_proc which has been tagged by apple as an unstable
	// API.  We disable this test for shipping versions to avoid conflicts with
	// future releases of Darwin.  This test is really only needed for developers
	// starting the app from a debugger anyway.
	#ifndef LL_RELEASE_FOR_DOWNLOAD
    int mib[4];
	mib[0] = CTL_KERN;
	mib[1] = KERN_PROC;
	mib[2] = KERN_PROC_PID;
	mib[3] = getpid();
	
	struct kinfo_proc info;
	memset(&info, 0, sizeof(info));
	
	size_t size = sizeof(info);
	int result = sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0);
	if((result == 0) || (errno == ENOMEM))
	{
		// P_TRACED flag is set, so this process is being debugged; do not install
		// the handler
		if(info.kp_proc.p_flag & P_TRACED) installHandler = false;
	}
	else
	{
		// Failed to discover if the process is being debugged; default to
		// installing the handler.
		installHandler = true;
	}
	#endif
#endif
	if(installHandler && (mExceptionHandler == 0))
	{
		std::string dumpPath = "/tmp/";
		mExceptionHandler = new google_breakpad::ExceptionHandler(dumpPath, 0, &unix_post_minidump_callback, 0, true);
	}
#endif

	startErrorThread();
}
Exemplo n.º 26
0
int main(int argc, char **argv) {
  init(argc, argv);
  setup_signals();
  reopenlog();
#ifdef HAVE_SETITIMER
  if (recheck) {
    struct itimerval itv;
    itv.it_interval.tv_sec  = itv.it_value.tv_sec  = recheck;
    itv.it_interval.tv_usec = itv.it_value.tv_usec = 0;
    if (setitimer(ITIMER_REAL, &itv, NULL) < 0)
      error(errno, "unable to setitimer()");
  }
#else
  alarm(recheck);
#endif
#ifndef NO_STATS
  stats_time = time(NULL);
  if (statsfile)
    dumpstats_z();
#endif

  pkt.p_peer = (struct sockaddr *)&peer_sa;

  if (numsock == 1) {
    /* optimized case for only one socket */
    int fd = sock[0];
    for(;;) {
      if (signalled) do_signalled();
      request(fd);
    }
  }
  else {
    /* several sockets, do select/poll loop */
#ifdef NO_POLL
    fd_set rfds;
    int maxfd = 0;
    int *fdi, *fde = sock + numsock;
    FD_ZERO(&rfds);
    for (fdi = sock; fdi < fde; ++fdi) {
      FD_SET(*fdi, &rfds);
      if (*fdi > maxfd) maxfd = *fdi;
    }
    ++maxfd;
    for(;;) {
      fd_set rfd = rfds;
      if (signalled) do_signalled();
      if (select(maxfd, &rfd, NULL, NULL, NULL) <= 0)
        continue;
      for(fdi = sock; fdi < fde; ++fdi) {
        if (FD_ISSET(*fdi, &rfd))
          request(*fdi);
      }
    }
#else /* !NO_POLL */
    struct pollfd pfda[MAXSOCK];
    struct pollfd *pfdi, *pfde = pfda + numsock;
    int r;
    for(r = 0; r < numsock; ++r) {
      pfda[r].fd = sock[r];
      pfda[r].events = POLLIN;
    }
    for(;;) {
      if (signalled) do_signalled();
      r = poll(pfda, numsock, -1);
      if (r <= 0) continue;
      for(pfdi = pfda; pfdi < pfde; ++pfdi) {
        if (!(pfdi->revents & POLLIN)) continue;
        request(pfdi->fd);
        if (!--r) break;
      }
    }
#endif /* NO_POLL */
  }
}
Exemplo n.º 27
0
EditorContextMenu::EditorContextMenu(QWidget *parent) : QMenu(parent)
{
 setup_actions();
 setup_signals();
 setup_menu();
}
Exemplo n.º 28
0
int main(int argc, char *argv[])
{
    mrp_mainloop_t *ml;

    mrp_clear(&cfg);
    parse_cmdline(&cfg, argc, argv);

    mrp_log_set_mask(cfg.log_mask);
    mrp_log_set_target(cfg.log_target);

    ml = mainloop_create(&cfg);

    if (ml == NULL)
        fatal("failed to create main loop.");

    dbus_test.ml = ml;
    setup_dbus_tests(ml);
    ml = dbus_test.ml;

    setup_timers(ml);
    setup_io(ml);
    setup_signals(ml);
    MRP_UNUSED(setup_deferred);   /* XXX TODO: add deferred tests... */

#ifdef GLIB_ENABLED
    if (cfg.mainloop_type != MAINLOOP_GLIB && cfg.mainloop_type != MAINLOOP_QT) {
        if (cfg.ngio > 0 || cfg.ngtimer > 0)
            glib_pump_setup(ml);
    }

    setup_glib_io();
    setup_glib_timers();
#endif

    if (mrp_add_timer(ml, 1000, check_quit, NULL) == NULL)
        fatal("failed to create quit-check timer");

    setup_wakeup(ml);

    mainloop_run(&cfg);

    check_io();
    check_timers();
    check_signals();

#ifdef GLIB_ENABLED
    check_glib_io();
    check_glib_timers();
#endif

    if (dbus_test.client != 0)
        close(dbus_test.pipe[1]);   /* let the client continue */

    check_dbus();

#ifdef GLIB_ENABLED
    if (cfg.mainloop_type != MAINLOOP_GLIB) {
        if (cfg.ngio > 0 || cfg.ngtimer > 0)
            glib_pump_cleanup();
    }
#endif

    cleanup_wakeup();

    mainloop_cleanup(&cfg);
}
Exemplo n.º 29
0
int main(int argc, char *argv[])
{
    int fd = -1;
    pid_t pgid = -1;
    server_conf_t *conf;
    int log_priority = LOG_INFO;

#ifndef NDEBUG
    log_priority = LOG_DEBUG;
#endif /* NDEBUG */
    log_set_file(stderr, log_priority, 0);

    conf = create_server_conf();
    tp_global = conf->tp;

    process_cmdline(conf, argc, argv);
    if (!conf->enableForeground) {
        begin_daemonize(&fd, &pgid);
    }
    process_config(conf);
    setup_coredump(conf);
    setup_signals(conf);

    if (!(environ = get_sane_env())) {
        log_err(ENOMEM, "Unable to create sanitized environment");
    }
    if (conf->enableVerbose) {
        display_configuration(conf);
    }
    if (list_is_empty(conf->objs)) {
        log_err(0, "Configuration \"%s\" has no consoles defined",
            conf->confFileName);
    }
    if (conf->tStampMinutes > 0) {
        schedule_timestamp(conf);
    }
    create_listen_socket(conf);

    if (!conf->enableForeground) {
        if (conf->syslogFacility > 0) {
            log_set_syslog(argv[0], conf->syslogFacility);
        }
        if (conf->logFileName) {
            open_daemon_logfile(conf);
        }
        else {
            log_set_file(NULL, 0, 0);
        }
        end_daemonize(fd);
    }

    log_msg(LOG_NOTICE, "Starting ConMan daemon %s (pid %d)",
        VERSION, (int) getpid());

#if WITH_FREEIPMI
    ipmi_init(conf->numIpmiObjs);
#endif /* WITH_FREEIPMI */

    open_objs(conf);
    mux_io(conf);

#if WITH_FREEIPMI
    ipmi_fini();
#endif /* WITH_FREEIPMI */

    destroy_server_conf(conf);

    if (pgid > 0) {
        if (kill(-pgid, SIGTERM) < 0) {
            log_msg(LOG_WARNING, "Unable to terminate process group ID %d: %s",
                pgid, strerror(errno));
        }
    }
    log_msg(LOG_NOTICE, "Stopping ConMan daemon %s (pid %d)",
        VERSION, (int) getpid());
    exit(0);
}
Exemplo n.º 30
0
/** Run the daemon.
 * @param[in] argc Number of arguments in \a argv.
 * @param[in] argv Arguments to program execution.
 */
int main(int argc, char **argv) {
  CurrentTime = time(NULL);

  thisServer.argc = argc;
  thisServer.argv = argv;
  thisServer.uid  = getuid();
  thisServer.euid = geteuid();

#ifdef MDEBUG
  mem_dbg_initialise();
#endif

#if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
  set_core_limit();
#endif

  umask(077);                   /* better safe than sorry --SRB */
  memset(&me, 0, sizeof(me));
  memset(&me_con, 0, sizeof(me_con));
  cli_connect(&me) = &me_con;
  cli_fd(&me) = -1;

  parse_command_line(argc, argv);

  if (chdir(dpath)) {
    fprintf(stderr, "Fail: Cannot chdir(%s): %s, check DPATH\n", dpath, strerror(errno));
    return 2;
  }

  if (!set_userid_if_needed())
    return 3;

  /* Check paths for accessibility */
  if (!check_file_access(SPATH, 'S', X_OK) ||
      !check_file_access(configfile, 'C', R_OK))
    return 4;

  if (!init_connection_limits())
    return 9;

  close_connections(!(thisServer.bootopt & (BOOT_DEBUG | BOOT_TTY | BOOT_CHKCONF)));

  /* daemon_init() must be before event_init() because kqueue() FDs
   * are, perversely, not inherited across fork().
   */
  daemon_init(thisServer.bootopt & BOOT_TTY);

#ifdef DEBUGMODE
  /* Must reserve fd 2... */
  if (debuglevel >= 0 && !(thisServer.bootopt & BOOT_TTY)) {
    int fd;
    if ((fd = open("/dev/null", O_WRONLY)) < 0) {
      fprintf(stderr, "Unable to open /dev/null (to reserve fd 2): %s\n",
	      strerror(errno));
      return 8;
    }
    if (fd != 2 && dup2(fd, 2) < 0) {
      fprintf(stderr, "Unable to reserve fd 2; dup2 said: %s\n",
	      strerror(errno));
      return 8;
    }
  }
#endif

  event_init(MAXCONNECTIONS);

  setup_signals();
  feature_init(); /* initialize features... */
  log_init(*argv);
  set_nomem_handler(outofmemory);

  initload();
  init_list();
  init_hash();
  init_class();
  initwhowas();
  initmsgtree();
  initstats();

  /* we need this for now, when we're modular this 
     should be removed -- hikari */
  ircd_crypt_init();

  motd_init();

  if (!init_conf()) {
    log_write(LS_SYSTEM, L_CRIT, 0, "Failed to read configuration file %s",
	      configfile);
    return 7;
  }

  if (thisServer.bootopt & BOOT_CHKCONF) {
    if (dbg_client)
      conf_debug_iline(dbg_client);
    fprintf(stderr, "Configuration file %s checked okay.\n", configfile);
    return 0;
  }

  debug_init(thisServer.bootopt & BOOT_TTY);
  if (check_pid()) {
    Debug((DEBUG_FATAL, "Failed to acquire PID file lock after fork"));
    exit(2);
  }

  init_server_identity();

  uping_init();

  stats_init();

  IPcheck_init();
  timer_add(timer_init(&connect_timer), try_connections, 0, TT_RELATIVE, 1);
  timer_add(timer_init(&ping_timer), check_pings, 0, TT_RELATIVE, 1);
  timer_add(timer_init(&destruct_event_timer), exec_expired_destruct_events, 0, TT_PERIODIC, 60);
  timer_add(timer_init(&mute_timer), check_expired_mutes, 0, TT_PERIODIC, 30);

  CurrentTime = time(NULL);

  SetMe(&me);
  cli_magic(&me) = CLIENT_MAGIC;
  cli_from(&me) = &me;
  make_server(&me);

  cli_serv(&me)->timestamp = TStime();  /* Abuse own link timestamp as start TS */
  cli_serv(&me)->prot      = atoi(MAJOR_PROTOCOL);
  cli_serv(&me)->up        = &me;
  cli_serv(&me)->down      = NULL;
  cli_handler(&me)         = SERVER_HANDLER;

  SetYXXCapacity(&me, MAXCLIENTS);

  cli_lasttime(&me) = cli_since(&me) = cli_firsttime(&me) = CurrentTime;

  hAddClient(&me);

  write_pidfile();
  init_counters();

  Debug((DEBUG_NOTICE, "Server ready..."));
  log_write(LS_SYSTEM, L_NOTICE, 0, "Server Ready");

  event_loop();

  return 0;
}