Пример #1
0
/*!
 * This function is directly exported.
 *
 * @param driver_handle
 * @param dsp
 * @param params
 *
 * @return 0 on success
 * @return 1 on failure
 */
int igd_module_init(igd_driver_h driver_handle,
	igd_dispatch_t **dsp,
	igd_param_t *params)
{
	igd_context_t *context = (igd_context_t *)driver_handle;
	device_context_t *device;
	int ret = 0;

	EMGD_TRACE_ENTER;

	device = &context->device_context;
	context->device_context.power_state = IGD_POWERSTATE_D0;
	context->mod_dispatch.init_params = params;
	context->dispatch.idle = empty_idle;
	context->dispatch.sync = empty_sync;
	context->mod_dispatch.in_dih_clone_mode = 0;
	context->mod_dispatch.dih_clone_display = 0;
	context->mod_dispatch.fb_blend_ovl_override = 0;

	/* Intialize IGD Modules */
	ret = init_modules(params, context);
	if (ret) {
		EMGD_ERROR_EXIT("Init Modules Failed");
		return ret;
	}

	OPT_MICRO_VOID_CALL(_init_dispatch(context));

	*dsp = &context->dispatch;

	EMGD_TRACE_EXIT;
	return 0;
}
Пример #2
0
int main(int argc, char **argv)
{
#if ! defined(_WIN32)
     __log_error = (void (*)(void *, const char *,...)) log_server;     /*set c-icap library log  function */
#else
     __vlog_error = vlog_server;        /*set c-icap library  log function */
#endif

     mem_init();
     init_internal_lookup_tables();
     ci_acl_init();
     init_http_auth();
     if (init_body_system() != CI_OK) {
         ci_debug_printf(1, "Can not initialize body system\n");
         exit(-1);
     }
     ci_txt_template_init();
     ci_txt_template_set_dir(DATADIR"templates");
     commands_init();

     if (!(CI_CONF.MAGIC_DB = ci_magic_db_load(CI_CONF.magics_file))) {
          ci_debug_printf(1, "Can not load magic file %s!!!\n",
                          CI_CONF.magics_file);
     }
     init_conf_tables();
     request_stats_init();
     init_modules();
     init_services();
     config(argc, argv);
     compute_my_hostname();
     ci_debug_printf(2, "My hostname is:%s\n", MY_HOSTNAME);

     if (!log_open()) {
          ci_debug_printf(1, "Can not init loggers. Exiting.....\n");
          exit(-1);
     }

#if ! defined(_WIN32)
     if (is_icap_running(CI_CONF.PIDFILE)) {
          ci_debug_printf(1, "c-icap server already running!\n");
          exit(-1);
     }
     if (DAEMON_MODE)
          run_as_daemon();
     if (!set_running_permissions(CI_CONF.RUN_USER, CI_CONF.RUN_GROUP))
          exit(-1);
     store_pid(CI_CONF.PIDFILE);
#endif

     if (!init_server(CI_CONF.ADDRESS, CI_CONF.PORT, &(CI_CONF.PROTOCOL_FAMILY)))
          return -1;
     post_init_modules();
     post_init_services();
     start_server();
     clear_pid(CI_CONF.PIDFILE);
     return 0;
}
Пример #3
0
/* Modify module type. */
void update_module_type(uint8_t new_type)
{
    module_type = new_type;
    init_modules();
    // Keep module_type state in memory. TODO: Does this stay in EEPROM
    // even when I re-run micronucleus? We wouldn't want that though.
    // Unsure whether this is in interrupt context or standard context here
    cli();
    eeprom_write_byte(MODULE_TYPE_EEPROM_ADDR, module_type);
    sei();
}
Пример #4
0
  t_loadmod	*loadmod_init(const char *module_path, double program_version)
  {
    t_loadmod	*t;

    version = program_version;
    t = malloc(sizeof(*t));
    list_init(&(t->file_list));
    list_init(&(t->module_list));
    init_files(&(t->file_list), module_path);
    init_modules(t);
    return (t);
  }
Пример #5
0
void OpenIBootConsole()
{
	init_modules();
	bufferPrintf(	"  ___                   _ ____              _   \r\n"
					" / _ \\ _ __   ___ _ __ (_) __ )  ___   ___ | |_ \r\n"
					"| | | | '_ \\ / _ \\ '_ \\| |  _ \\ / _ \\ / _ \\| __|\r\n"
					"| |_| | |_) |  __/ | | | | |_) | (_) | (_) | |_ \r\n"
					" \\___/| .__/ \\___|_| |_|_|____/ \\___/ \\___/ \\__|\r\n"
					"      |_|                                       \r\n"
					"\r\n"
					"version: %s\r\n", OPENIBOOT_VERSION_STR);
	DebugPrintf("                    DEBUG MODE\r\n");
}
Пример #6
0
void usage(int rc)
{
	struct mod_action mod;
	FILE *fp = rc ? stderr : stdout;

	version(fp);
	fprintf(fp, "Copyright (C) 2000-2008, Parallels, Inc.\n");
	fprintf(fp, "This program may be distributed under the terms of the GNU GPL License.\n\n");
	fprintf(fp, "Usage: vzctl [options] <command> <veid> [parameters]\n"
"vzctl destroy | mount | umount | stop | restart | status | enter <veid>\n"
"vzctl create <veid> [--ostemplate <name>] [--config <name>]\n"
"   [--private <path>] [--root <path>] [--ipadd <addr>] | [--hostname <name>]\n"
"vzctl start <veid> [--force] [--wait]\n"
"vzctl exec | exec2 <veid> <command> [arg ...]\n"
"vzctl runscript <veid> <script>\n"
"vzctl chkpnt <veid> [--dumpfile <name>]\n"
"vzctl restore <veid> [--dumpfile <name>]\n"
"vzctl set <veid> [--save] [--setmode restart|ignore]\n"
"   [--ipadd <addr>] [--ipdel <addr>|all] [--hostname <name>]\n"
"   [--nameserver <addr>] [--searchdomain <name>] [--onboot yes|no]\n"
"   [--userpasswd <user>:<passwd>] [--cpuunits <N>] [--cpulimit <N>] [--cpus <N>]\n"
"   [--diskspace <soft>[:<hard>]] [--diskinodes <soft>[:<hard>]]\n"
"   [--quotatime <N>] [--quotaugidlimit <N>]\n"
"   [--noatime yes|no] [--capability <name>:on|off ...]\n"
"   [--devices b|c:major:minor|all:r|w|rw]\n"
"   [--devnodes device:r|w|rw|none]\n"
"   [--netif_add <ifname[,mac,host_ifname,host_mac]]>] [--netif_del <ifname>]\n"
"   [--applyconfig <name>] [--applyconfig_map <name>]\n"
"   [--features <name:on|off>] [--name <vename>]\n"
"   [--ioprio <N>]\n");


	fprintf(fp, "   [--iptables <name>] [--disabled <yes|no>]\n");
	fprintf(fp, "   [UBC parameters]\n"
"UBC parameters (N - items, P - pages, B - bytes):\n"
"Two numbers divided by colon means barrier:limit.\n"
"In case the limit is not given it is set to the same value as the barrier.\n"
"   --numproc N[:N]	--numtcpsock N[:N]	--numothersock N[:N]\n"
"   --vmguarpages P[:P]	--kmemsize B[:B]	--tcpsndbuf B[:B]\n"
"   --tcprcvbuf B[:B]	--othersockbuf B[:B]	--dgramrcvbuf B[:B]\n"
"   --oomguarpages P[:P]	--lockedpages P[:P]	--privvmpages P[:P]\n"
"   --shmpages P[:P]	--numfile N[:N]		--numflock N[:N]\n"
"   --numpty N[:N]	--numsiginfo N[:N]	--dcachesize N[:N]\n"
"   --numiptent N[:N]	--physpages P[:P]	--avnumproc N[:N]\n");
	memset(&mod, 0, sizeof(mod));
	set_log_level(0);
	init_modules(&mod, NULL);
	mod_print_usage(&mod);
	free_modules(&mod);
	exit(rc);
}
Пример #7
0
int main()
{
	initStatusLED();
	initUSB();

	// Globally enable interrupts
	sei();

	init_modules();
	// Endless loop
	for (;;) {

		/* Regularly restart watchdog timer to prevent it from elapsing. */
		wdt_reset();
		usbPoll();
		
		if (usbInterruptIsReady()) {
      if (isSendingSysExMsg) {
        handleMidiSend();
      } else {
        switch (module_type) {
          case ANALOG_INPUT:
            analog_input_device_main_loop(uADC);
            break;

          case ANALOG_OUTPUT:
            analog_output_device_main_loop();
            break;

          case DIGITAL_INPUT:
            digital_input_device_main_loop(uADC);
            break;

          case DIGITAL_OUTPUT:
            digital_output_device_main_loop();
            break;

          case I2C_DEVICE:
            /* Not implemented yet. */
            break;

          default:
            break;
        }
      }
		}
	}
	return 0;
}
Пример #8
0
void load_modules(  )
{
   DIR *dp;
   struct dirent *dentry;
   char directory_name[100];

   return;  // castrated for now.

   mudstrlcpy( directory_name, "../src/modules/so", 100 );
   dp = opendir( directory_name );
   dentry = readdir( dp );
   while( dentry )
   {
      /*
       * Added by Tarl 3 Dec 02 because we are now using CVS 
       */
      if( !str_cmp( dentry->d_name, "CVS" ) )
      {
         dentry = readdir( dp );
         continue;
      }
      if( dentry->d_name[0] != '.' )
      {
         string filename = dentry->d_name;
         string name;
         string::size_type ps;
         char path[100];

         if( ( ps = filename.find( '.' ) ) == string::npos )
            name = filename;
         else
            name = filename.substr( 0, ps );

         snprintf( path, 100, "%s/%s", directory_name, name.c_str(  ) );
         module[name] = dlopen( path, RTLD_NOW );
         if( !module[name] )
         {
            log_string( dlerror(  ) );
            continue;
         }
      }
      dentry = readdir( dp );
   }
   closedir( dp );

   init_modules(  );
}
Пример #9
0
int main(void)
{
	int i;

	rcc_clock_setup_in_hsi_out_48mhz();
	debug_init();
	printf("Device UP!\nFW version %s\n", FW_VERSION);

	cmd_init();

	CMD_REGISTER_LIST(main_cmds);
	init_modules();
	printf("Init complete..\n");

	while (1) {
		cmd_poll();
	}
}
Пример #10
0
void startup() {
	totalbytes = 0;
	               
	printf("Acidblood %s\n", VERSION);
	init_conf() ;
	init_signals() ;
	init_networking() ;
	conf_userdata=NULL ;
	conf_channels=NULL ;
	init_usercommands() ;
	init_ctcp() ;
	init_srvcommands() ;
	init_log();
	init_serverinfo() ;
	init_numeric() ;
	init_timers() ;
	init_events() ;
	read_main_config() ;
	init_modules() ;
}
Пример #11
0
int
main(int argc, char *argv[])
{
	if (argc < 2)
		return (-1);

	const char *mod = argv[1];	
	int fd = -1;

	init_modules();
	polysome *p = get_module(mod);
	if (p == NULL) {
		printf("%s invalid\n", mod);
	} else {
		printf("%s valid\n", p->name);
		ovvar_t ov;
		memset(&ov, 0, sizeof(ov));

		init_ov(&ov);
		printf("path %s\n", ov.path);
		
		p->ss(&ov);
		printf("path %s be read\n", ov.fpath);
		printf("ov.a: %d, ov.b: %d\n", ov.a, ov.b);
		p->gs(&ov);

		for (rci_t i = 0; i < (ov.a + ov.b); i ++)
			printf("%ld ", ov.signature[i]);

		printf("\n");

		free_ov(&ov);
	}

	free_modules();

	return (0);
}
Пример #12
0
   // ----------------------------------------------------------------------
   void
   LocalizationProcessor::
   boot( void )
      throw()
   {
      neighborhood_.set_source( owner_w() );

      random_ = owner().world().simulation_controller().
                     random_variable_keeper().find( "uni[0;1]" );

      init_parameters();
      init_modules();
      init_proc_type();
      assert( dist_module_ && pos_module_ && ref_module_ );

      dist_module_->set_owner( *this );
      dist_module_->boot();

      pos_module_->set_owner( *this );
      pos_module_->boot();

      ref_module_->set_owner( *this );
      ref_module_->boot();
   }
Пример #13
0
//there has to be a better way to do this :/
void Run(void)
{
  
    char *ce; 
    SetSig       ();
    Banner       ();

        if ((ce = (char *)get_config_entry("?omega", "version")))
        {
			if (CONFIG_VERSION != atoi(ce))
			{
				fprintf(stderr, "\033[1;31mCRITICAL\033[0m: Invalid configuration file version. [Given: %s][Required: %d]", ce, CONFIG_VERSION); 
				Exit(0);	
			}	
	} else { 
		fprintf(stderr, "\033[1;31mERROR\033[0m: Unable to determine the configuration file version. Please make sure you have all <?omega> intact\n");
		fprintf(stderr, "Assuming configuration version \033[1;31m%d\033[0m\n\n", CONFIG_VERSION);
	} 

#ifdef HAVE_SETPROCTITLE
    setproctitle("%s", CfgSettings.servername);
#endif

    open_log  ();
    init_uid ();
	
    AddEventEx ("House Keeping", 900, EVENT_UNLIMITED, ev_housekeeping);
 
    AddEvent ("BURST", burst_local_users);
    AddEvent ("BURST", burst_local_servers);
    AddEvent ("CONNECT", introduce_users);
	
    if ((Omega->me = new_serv(NULL, CfgSettings.servername)))
    {
        strlcpy (Omega->me->sid, CfgSettings.sid, sizeof(Omega->me->sid));
        Omega->me->eos = 1; //mark us as already EOS'ed
    }
    else
    {
		fprintf (stderr, "Unable to create our server entry\n");
		exit (0);
    }

    /*
     * Initialize our core for running
     */

	database_init (); 
    protocol_init ();
	
    servsock    	 = add_new_socket ((void*) psr_HandleEvent, NULL);
    servsock->flags	|= SOCK_UPLINK;
	strlcpy (servsock->name, "Uplink", sizeof(servsock->name));

#ifdef HAVE_GNUTLS
        servsock->tls_enabled   = get_config_bool("link", "gnutls", 0);
#endif
	
    psr_init      ();
	init_access();

	init_modules();
	introduce_users (0, NULL);

    /*
     * Connect to the IRCd if we don't connect Add an event to connect...
     */

    printf ("\r\n");
    printf ("Connecting to \033[1;32m%s\033[0m port \033[1;32m%d\033[0m\033[0m\n", CfgSettings.uplink, CfgSettings.port);
    if (Connect (servsock, CfgSettings.uplink, CfgSettings.local_ip, CfgSettings.port))
        ircd_connect ();
    else
        AddEventEx ("Connect Uplink", 60, 3, ev_connectuplink);

    /*
     * Okay begin
     */

    OneTimeAround   ();

    return;
}
Пример #14
0
void init() {
	init_clocks();
	init_modules();
	init_interrupts();
	tcs_init();
}
Пример #15
0
int main(int arg_c, char **arg_v)
{
  int i, xx;
  char s[25];
  FILE *f;
  struct sigaction sv;
  struct chanset_t *chan;
#ifdef DEBUG
  struct rlimit cdlim;
#endif
#ifdef STOP_UAC
  int nvpair[2];
#endif

/* Make sure it can write core, if you make debug. Else it's pretty
 * useless (dw)
 *
 * Only allow unlimited size core files when compiled with DEBUG defined.
 * This is not a good idea for normal builds -- in these cases, use the
 * default system resource limits instead.
 */
#ifdef DEBUG
  cdlim.rlim_cur = RLIM_INFINITY;
  cdlim.rlim_max = RLIM_INFINITY;
  setrlimit(RLIMIT_CORE, &cdlim);
#endif

#ifdef DEBUG_CONTEXT
  /* Initialise context list */
  for (i = 0; i < 16; i++)
    Context;
#endif

/* Include patch.h header for patch("...") */
#include "patch.h"

  argc = arg_c;
  argv = arg_v;

  /* Version info! */
  egg_snprintf(ver, sizeof ver, "eggdrop v%s", egg_version);
  egg_snprintf(version, sizeof version,
               "Eggdrop v%s (C) 1997 Robey Pointer (C) 2010 Eggheads",
               egg_version);
  /* Now add on the patchlevel (for Tcl) */
  sprintf(&egg_version[strlen(egg_version)], " %u", egg_numver);
  strcat(egg_version, egg_xtra);

/* For OSF/1 */
#ifdef STOP_UAC
  /* Don't print "unaligned access fixup" warning to the user */
  nvpair[0] = SSIN_UACPROC;
  nvpair[1] = UAC_NOPRINT;
  setsysinfo(SSI_NVPAIRS, (char *) nvpair, 1, NULL, 0);
#endif

  /* Set up error traps: */
  sv.sa_handler = got_bus;
  sigemptyset(&sv.sa_mask);
#ifdef SA_RESETHAND
  sv.sa_flags = SA_RESETHAND;
#else
  sv.sa_flags = 0;
#endif
  sigaction(SIGBUS, &sv, NULL);
  sv.sa_handler = got_segv;
  sigaction(SIGSEGV, &sv, NULL);
#ifdef SA_RESETHAND
  sv.sa_flags = 0;
#endif
  sv.sa_handler = got_fpe;
  sigaction(SIGFPE, &sv, NULL);
  sv.sa_handler = got_term;
  sigaction(SIGTERM, &sv, NULL);
  sv.sa_handler = got_hup;
  sigaction(SIGHUP, &sv, NULL);
  sv.sa_handler = got_quit;
  sigaction(SIGQUIT, &sv, NULL);
  sv.sa_handler = SIG_IGN;
  sigaction(SIGPIPE, &sv, NULL);
  sv.sa_handler = got_ill;
  sigaction(SIGILL, &sv, NULL);
  sv.sa_handler = got_alarm;
  sigaction(SIGALRM, &sv, NULL);

  /* Initialize variables and stuff */
  now = time(NULL);
  chanset = NULL;
  egg_memcpy(&nowtm, localtime(&now), sizeof(struct tm));
  lastmin = nowtm.tm_min;
  srandom((unsigned int) (now % (getpid() + getppid())));
  init_mem();
  init_language(1);
  if (argc > 1)
    for (i = 1; i < argc; i++)
      do_arg(argv[i]);

  printf("\n%s\n", version);

#ifndef CYGWIN_HACKS
  /* Don't allow eggdrop to run as root
   * This check isn't useful under cygwin and has been
   * reported to cause trouble in some situations.
   */
  if (((int) getuid() == 0) || ((int) geteuid() == 0))
    fatal("ERROR: Eggdrop will not run as root!", 0);
#endif

#ifndef REPLACE_NOTIFIER
  init_threaddata(1);
#endif
  init_userent();
  init_misc();
  init_bots();
  init_modules();
  if (backgrd)
    bg_prepare_split();
  init_tcl(argc, argv);
  init_language(0);
#ifdef STATIC
  link_statics();
#endif
  strncpyz(s, ctime(&now), sizeof s);
  strcpy(&s[11], &s[20]);
  putlog(LOG_ALL, "*", "--- Loading %s (%s)", ver, s);
  chanprog();
  if (!encrypt_pass) {
    printf(MOD_NOCRYPT);
    bg_send_quit(BG_ABORT);
    exit(1);
  }
  i = 0;
  for (chan = chanset; chan; chan = chan->next)
    i++;
  putlog(LOG_MISC, "*", "=== %s: %d channels, %d users.",
         botnetnick, i, count_users(userlist));
#ifdef TLS
  ssl_init();
#endif
  cache_miss = 0;
  cache_hit = 0;
  if (!pid_file[0])
    egg_snprintf(pid_file, sizeof pid_file, "pid.%s", botnetnick);

  /* Check for pre-existing eggdrop! */
  f = fopen(pid_file, "r");
  if (f != NULL) {
    fgets(s, 10, f);
    xx = atoi(s);
    i = kill(xx, SIGCHLD);      /* Meaningless kill to determine if pid
                                 * is used */
    if (i == 0 || errno != ESRCH) {
      printf(EGG_RUNNING1, botnetnick);
      printf(EGG_RUNNING2, pid_file);
      bg_send_quit(BG_ABORT);
      exit(1);
    }
  }

  /* Move into background? */
  if (backgrd) {
    bg_do_split();
  } else {                        /* !backgrd */
    xx = getpid();
    if (xx != 0) {
      FILE *fp;

      /* Write pid to file */
      unlink(pid_file);
      fp = fopen(pid_file, "w");
      if (fp != NULL) {
        fprintf(fp, "%u\n", xx);
        if (fflush(fp)) {
          /* Let the bot live since this doesn't appear to be a botchk */
          printf(EGG_NOWRITE, pid_file);
          fclose(fp);
          unlink(pid_file);
        } else
          fclose(fp);
      } else
        printf(EGG_NOWRITE, pid_file);
    }
  }

  use_stderr = 0;               /* Stop writing to stderr now */
  if (backgrd) {
    /* Ok, try to disassociate from controlling terminal (finger cross) */
#ifdef HAVE_SETPGID
    setpgid(0, 0);
#endif
    /* Tcl wants the stdin, stdout and stderr file handles kept open. */
    freopen("/dev/null", "r", stdin);
    freopen("/dev/null", "w", stdout);
    freopen("/dev/null", "w", stderr);
#ifdef CYGWIN_HACKS
    FreeConsole();
#endif
  }

  /* Terminal emulating dcc chat */
  if (!backgrd && term_z) {
    int n = new_dcc(&DCC_CHAT, sizeof(struct chat_info));

    getvhost(&dcc[n].sockname, AF_INET);
    dcc[n].sock = STDOUT;
    dcc[n].timeval = now;
    dcc[n].u.chat->con_flags = conmask;
    dcc[n].u.chat->strip_flags = STRIP_ALL;
    dcc[n].status = STAT_ECHO;
    strcpy(dcc[n].nick, "HQ");
    strcpy(dcc[n].host, "llama@console");
    /* HACK: Workaround not to pass literal "HQ" as a non-const arg */
    dcc[n].user = get_user_by_handle(userlist, dcc[n].nick);
    /* Make sure there's an innocuous HQ user if needed */
    if (!dcc[n].user) {
      userlist = adduser(userlist, dcc[n].nick, "none", "-", USER_PARTY);
      dcc[n].user = get_user_by_handle(userlist, dcc[n].nick);
    }
    setsock(STDOUT, 0);          /* Entry in net table */
    dprintf(n, "\n### ENTERING DCC CHAT SIMULATION ###\n\n");
    dcc_chatter(n);
  }

  then = now;
  online_since = now;
  autolink_cycle(NULL);         /* Hurry and connect to tandem bots */
  add_help_reference("cmds1.help");
  add_help_reference("cmds2.help");
  add_help_reference("core.help");
  add_hook(HOOK_SECONDLY, (Function) core_secondly);
  add_hook(HOOK_MINUTELY, (Function) core_minutely);
  add_hook(HOOK_HOURLY, (Function) core_hourly);
  add_hook(HOOK_REHASH, (Function) event_rehash);
  add_hook(HOOK_PRE_REHASH, (Function) event_prerehash);
  add_hook(HOOK_USERFILE, (Function) event_save);
  add_hook(HOOK_BACKUP, (Function) backup_userfile);
  add_hook(HOOK_DAILY, (Function) event_logfile);
  add_hook(HOOK_DAILY, (Function) event_resettraffic);
  add_hook(HOOK_LOADED, (Function) event_loaded);

  call_hook(HOOK_LOADED);

  debug0("main: entering loop");
  while (1) {
    mainloop(1);
  }
}
Пример #16
0
int main(int argc, char **argv)
{
  int xx, i;
#ifdef STOP_UAC
  int nvpair[2];
#endif
  char buf[520], s[25];
  FILE *f;
#ifndef ENABLE_STRIP
  struct rlimit cdlim;
#endif

  /* Don't allow Eggdrop to run as root. */
  if (((int) getuid() == 0) || ((int) geteuid() == 0))
    fatal("ERROR: Eggdrop will not run as root!", 0);

#ifndef ENABLE_STRIP
  cdlim.rlim_cur = RLIM_INFINITY;
  cdlim.rlim_max = RLIM_INFINITY;
  setrlimit(RLIMIT_CORE, &cdlim);
#endif

#include "patch.h"
  /* Version info! */
  egg_snprintf(ver, sizeof ver, "eggdrop v%s", egg_version);
  egg_snprintf(version, sizeof version,
               "Eggdrop v%s (C) 1997 Robey Pointer (C) 2005 Eggheads",
               egg_version);
  /* Now add on the patchlevel (for Tcl) */
  sprintf(&egg_version[strlen(egg_version)], " %u", egg_numver);
  strcat(egg_version, egg_xtra);

#ifdef STOP_UAC
  nvpair[0] = SSIN_UACPROC;
  nvpair[1] = UAC_NOPRINT;
  setsysinfo(SSI_NVPAIRS, (char *) nvpair, 1, NULL, 0);
#endif

  /* Set up error / signal traps. */
  setup_signal_traps();

  /* Initialize a few variables before main loop. */
  cache_miss = 0;
  cache_hit  = 0;
  chanset    = NULL;
  now        = time(NULL);

  egg_memcpy(&nowtm, localtime(&now), sizeof(struct tm));
  lastmin = nowtm.tm_min;

  /* Initialize random number generator. */
  srandom((unsigned int) (now % (getpid() + getppid())));

  init_mem();
  init_language(1);

  /* Process command line arguments. */
  process_args(argc, argv);

  printf("\n%s\n", version);

  init_dcc_max();
  init_userent();
  logfile_init(0);
  init_bots();
  init_net();
  init_modules();

  if (backgrd)
    bg_prepare_split();

  init_tcl(argc, argv);
  init_language(0);
  help_init();
  traffic_init();
  logfile_init(1);

#ifdef STATIC
  link_statics();
#endif

  strncpyz(s, ctime(&now), sizeof s);
  strcpy(&s[11], &s[20]);
  putlog(LOG_ALL, "*", "--- Loading %s (%s)", ver, s);

  /* Read configuration data. */
  readconfig();

  /* Check for encryption module. */
  if (!encrypt_pass) {
    printf(MOD_NOCRYPT);
    bg_send_quit(BG_ABORT);
    exit(1);
  }

  putlog(LOG_MISC, "*", "=== %s: %d channels, %d users.", botnetnick,
         count_channels(), count_users(userlist));

  if (!pid_file[0])
    egg_snprintf(pid_file, sizeof pid_file, "pid.%s", botnetnick);

  /* Check for pre-existing eggdrop! */
  f = fopen(pid_file, "r");
  if (f != NULL) {
    fgets(s, 10, f);
    xx = atoi(s);
    kill(xx, SIGCHLD); /* Meaningless kill to determine if PID is used. */
    if (errno != ESRCH) {
      printf(EGG_RUNNING1, botnetnick);
      printf(EGG_RUNNING2, pid_file);
      bg_send_quit(BG_ABORT);
      exit(1);
    }
  }

  /* Move into background? */
  if (backgrd) {
#ifndef CYGWIN_HACKS
    bg_do_split();
  }
  else {
#endif
    xx = getpid();
    if (xx != 0) {
      FILE *fp;

      /* Write PID to file. */
      unlink(pid_file);
      fp = fopen(pid_file, "w");
      if (fp != NULL) {
        fprintf(fp, "%u\n", xx);
        if (fflush(fp)) {
          /* Let the bot live since this doesn't appear to be a botchk. */
          printf("Cannot not write to '%s' (PID file).\n", pid_file);
          fclose(fp);
          unlink(pid_file);
        }
        else
          fclose(fp);
      }
      else
        printf("Cannot not write to '%s' (PID file).\n", pid_file);
#ifdef CYGWIN_HACKS
      printf("Launched into the background (PID: %d)\n\n", xx);
#endif
    }
  }

  use_stderr = 0;               /* Stop writing to stderr now */
  if (backgrd) {
    /* Ok, try to disassociate from controlling terminal (finger cross) */
#if defined(HAVE_SETPGID) && !defined(CYGWIN_HACKS)
    setpgid(0, 0);
#endif

    /* Tcl wants the stdin, stdout and stderr file handles kept open. */
    freopen("/dev/null", "r", stdin);
    freopen("/dev/null", "w", stdout);
    freopen("/dev/null", "w", stderr);

#ifdef CYGWIN_HACKS
    FreeConsole();
#endif
  }

  /* Terminal emulating dcc chat */
  if (!backgrd && term_z) {
    int n = new_dcc(&DCC_CHAT, sizeof(struct chat_info));

    dcc[n].addr = iptolong(getmyip());
    dcc[n].sock = STDOUT;
    dcc[n].timeval = now;
    dcc[n].u.chat->con_flags = conmask;
    dcc[n].u.chat->strip_flags = STRIP_ALL;
    dcc[n].status = STAT_ECHO;
    strcpy(dcc[n].nick, "HQ");
    strcpy(dcc[n].host, "llama@console");
    /* HACK: Workaround not to pass literal "HQ" as a non-const arg */
    dcc[n].user = get_user_by_handle(userlist, dcc[n].nick);
    /* Make sure there's an innocuous HQ user if needed */
    if (!dcc[n].user) {
      userlist = adduser(userlist, dcc[n].nick, "none", "-", USER_PARTY);
      dcc[n].user = get_user_by_handle(userlist, dcc[n].nick);
    }
    setsock(STDOUT, 0); /* Entry in net table */
    dprintf(n, "\n### ENTERING DCC CHAT SIMULATION ###\n\n");
    dcc_chatter(n);
  }

  then = now;
  online_since = now;
  autolink_cycle(NULL); /* Hurry and connect to tandem bots. */
  add_help_reference("cmds1.help");
  add_help_reference("cmds2.help");
  add_help_reference("core.help");

  /* Create hooks. */
  add_hook(HOOK_SECONDLY, (Function) core_secondly);
  add_hook(HOOK_MINUTELY, (Function) core_minutely);
  add_hook(HOOK_HOURLY, (Function) core_hourly);
  add_hook(HOOK_REHASH, (Function) event_rehash);
  add_hook(HOOK_PRE_REHASH, (Function) event_prerehash);
  add_hook(HOOK_USERFILE, (Function) event_save);
  add_hook(HOOK_BACKUP, (Function) backupuserfile);
  add_hook(HOOK_DAILY, (Function) event_logfile);
  add_hook(HOOK_DAILY, (Function) traffic_reset);
  add_hook(HOOK_LOADED, (Function) event_loaded);

  call_hook(HOOK_LOADED);

  debug0("main: entering loop");
  while (1) {
    int socket_cleanup = 0;

#ifdef USE_TCL_EVENTS
    /* Process a single Tcl event. */
    Tcl_DoOneEvent(TCL_ALL_EVENTS | TCL_DONT_WAIT);
#endif

    now = time(NULL);
    random();

    /* Every second... */
    if (now != then) {
      call_hook(HOOK_SECONDLY);
      then = now;
    }

    /* Only do this every so often. */
    if (!socket_cleanup) {
      socket_cleanup = 5;

      /* Remove dead dcc entries. */
      dcc_remove_lost();

      /* Check for server or dcc activity. */
      dequeue_sockets();
    }
    else {
      socket_cleanup--;
    }

    /* Free unused structures. */
    garbage_collect();

    xx = sockgets(buf, &i);
    if (xx >= 0) { /* Non-error */
      int idx;

      for (idx = 0; idx < dcc_total; idx++) {
        if (dcc[idx].sock != xx)
          continue;

        if (dcc[idx].type && dcc[idx].type->activity) {
          traffic_update_in(dcc[idx].type, (strlen(buf) + 1)); /* Traffic stats. */
          dcc[idx].type->activity(idx, buf, i);
        }
        else {
          putlog(LOG_MISC, "*", "!!! untrapped dcc activity: type %s, sock %d",
                 dcc[idx].type->name, dcc[idx].sock);
        }

        break;
      }
    }
    else if (xx == -1) { /* EOF */
      int idx;

      if (i == STDOUT && !backgrd)
        fatal("END OF FILE ON TERMINAL", 0);

      for (idx = 0; idx < dcc_total; idx++) {
        if (dcc[idx].sock != i)
          continue;

        if (dcc[idx].type && dcc[idx].type->eof) {
          dcc[idx].type->eof(idx);
        }
        else {
          putlog(LOG_MISC, "*",
                 "*** ATTENTION: DEAD SOCKET (%d) OF TYPE %s UNTRAPPED",
                 i, dcc[idx].type ? dcc[idx].type->name : "*UNKNOWN*");
          killsock(i);
          lostdcc(idx);
        }

        idx = dcc_total + 1;
      }

      if (idx == dcc_total) {
        putlog(LOG_MISC, "*",
               "(@) EOF socket %d, not a dcc socket, not anything.", i);
        close(i);
        killsock(i);
      }
    }
    else if (xx == -2 && errno != EINTR) { /* select() error */
      putlog(LOG_MISC, "*", "* Socket error #%d; recovering.", errno);
      for (i = 0; i < dcc_total; i++) {
        if ((fcntl(dcc[i].sock, F_GETFD, 0) == -1) && (errno == EBADF)) {
          putlog(LOG_MISC, "*",
                 "DCC socket %d (type %d, name '%s') expired -- pfft",
                 dcc[i].sock, dcc[i].type, dcc[i].nick);
          killsock(dcc[i].sock);
          lostdcc(i);
          i--;
        }
      }
    }
    else if (xx == -3) {
      call_hook(HOOK_IDLE);
      socket_cleanup = 0;       /* If we've been idle, cleanup & flush */
    }

    if (do_restart) {
      if (do_restart == -2) {
        rehash();
      }
      else {
        int f = 1;
        module_entry *p;
        Function startfunc;
        char name[256];


        check_tcl_event("prerestart");

        /* Unload as many modules as possible */
        while (f) {
          f = 0;

          for (p = module_list; p != NULL; p = p->next) {
            dependancy *d = dependancy_list;
            int ok = 1;

            while (ok && d) {
              if (d->needed == p)
                ok = 0;

              d = d->next;
            }
            if (ok) {
              strcpy(name, p->name);

              if (module_unload(name, botnetnick) == NULL) {
                f = 1;
                break;
              }
            }
          }
        }

        /* Make sure we don't have any modules left hanging around other than
         * "eggdrop" and the two that are supposed to be.
         */
        for (f = 0, p = module_list; p; p = p->next) {
          if (strcmp(p->name, "eggdrop") && strcmp(p->name, "encryption") &&
              strcmp(p->name, "uptime")) {
            f++;
          }
        }
        if (f != 0) {
          putlog(LOG_MISC, "*", MOD_STAGNANT);
        }

        /* Flush log files to disk. */
        flushlogs();

        /* Clean up Tcl stuff. */
        kill_tcl();

        /* Initialize stuff again. */
        init_tcl(argc, argv);
        init_language(0);
        help_init();
        traffic_init();
        logfile_init(1);

        /* This resets our modules which we didn't unload (encryption and uptime). */
        for (p = module_list; p; p = p->next) {
          if (p->funcs) {
            startfunc = p->funcs[MODCALL_START];
            startfunc(NULL);
          }
        }

        rehash();
        restart_chons();
        call_hook(HOOK_LOADED);
      }

      do_restart = 0;
    }
  }
}
Пример #17
0
asmlinkage void __init start_kernel(void)
{
	char * command_line;
	extern char saved_command_line[];

/*
 * Interrupts are still disabled. Do necessary setups, then
 * enable them
 */
	lock_kernel();
	printk(linux_banner);
	setup_arch(&command_line);
	printk("Kernel command line: %s\n", saved_command_line);
	parse_options(command_line);
	trap_init();
	init_IRQ();
	sched_init();
	softirq_init();
	time_init();

	/*
	 * HACK ALERT! This is early. We're enabling the console before
	 * we've done PCI setups etc, and console_init() must be aware of
	 * this. But we do want output early, in case something goes wrong.
	 */
	console_init();
#ifdef CONFIG_MODULES
	init_modules();
#endif
	if (prof_shift) {
		unsigned int size;
		/* only text is profiled */
		prof_len = (unsigned long) &_etext - (unsigned long) &_stext;
		prof_len >>= prof_shift;
		
		size = prof_len * sizeof(unsigned int) + PAGE_SIZE-1;
		prof_buffer = (unsigned int *) alloc_bootmem(size);
	}

	kmem_cache_init();
	sti();
	calibrate_delay();
#ifdef CONFIG_BLK_DEV_INITRD
	if (initrd_start && !initrd_below_start_ok &&
			initrd_start < min_low_pfn << PAGE_SHIFT) {
		printk(KERN_CRIT "initrd overwritten (0x%08lx < 0x%08lx) - "
		    "disabling it.\n",initrd_start,min_low_pfn << PAGE_SHIFT);
		initrd_start = 0;
	}
#endif
	mem_init();
	kmem_cache_sizes_init();
	pgtable_cache_init();

	/*
	 * For architectures that have highmem, num_mappedpages represents
	 * the amount of memory the kernel can use.  For other architectures
	 * it's the same as the total pages.  We need both numbers because
	 * some subsystems need to initialize based on how much memory the
	 * kernel can use.
	 */
	if (num_mappedpages == 0)
		num_mappedpages = num_physpages;
  
	fork_init(num_mappedpages);
	proc_caches_init();
	vfs_caches_init(num_physpages);
	buffer_init(num_physpages);
	page_cache_init(num_physpages);
#if defined(CONFIG_ARCH_S390)
	ccwcache_init();
#endif
	signals_init();
#ifdef CONFIG_PROC_FS
	proc_root_init();
#endif
	check_bugs();
	printk("POSIX conformance testing by UNIFIX\n");

	/* 
	 *	We count on the initial thread going ok 
	 *	Like idlers init is an unlocked kernel thread, which will
	 *	make syscalls (and thus be locked).
	 */
	smp_init();
#if defined(CONFIG_SYSVIPC)
	ipc_init();
#endif
	rest_init();
}
Пример #18
0
void  main()

{
   int   message[8], flag;
   char  string[6];

   gl_apid = appl_init();

   if (! _app) {
        menu_register (gl_apid, "  Super Server");
        evnt_timer (1000, 0);
      }

   if (! rsrc_load ("IND.RSC")) {
        form_alert (1, "[1][ |   Cannot find IND.RSC !   ][ Cancel ]");
        terminate();   return;
      }

   get_path();

   if (initialise_windows (4, ICONIFY) == 0) {
        leave_windows();   rsrc_free();   terminate();
        return;
      }

   if (get_version (string) > 0) {
        form_alert (1, 
                "[1][ |   STiK is not loaded,    | |      or corrupted !][ Cancel ]");
        leave_windows();   rsrc_free();   terminate();
        return;
      }
   change_freestring (START, ST_VERS,  -1, string, 5);
   change_freestring (START, SS_VERS,  -1, version, 5);

   set_api_struct();

   if (init_modules() == 0) {
        leave_windows();   rsrc_free();   terminate();
        return;
      }
   set_callbacks (CB_EVENT, (FUNC) check_modules, (FUNC) 0L);

   init_configs();

   graf_mouse (ARROW, NULL);

   if (_app) {
        do_some_work();
        while (! exit_inetd) {
             evnt_mesag (message);
             message_handler (message);
             while ((flag = operate_events()) >= 0);
             if (flag == -4)
                  exit_inetd = TRUE;
           }
      }
     else {
        FOREVER {
             evnt_mesag (message);
             message_handler (message);
           }
      }

   if (strings)   Mfree (strings);

   terminate_modules();

   leave_windows();

   rsrc_free();

   appl_exit();
 }
Пример #19
0
/**
 * Main entry point
 */
int
main(int argc, char **argv)
{
	TRACE_FUNC_START();
	int rc;

	/* accept command-line arguments */
	while ( (rc = getopt(argc, argv, "a:b:hsdf:")) != -1) {
		switch(rc) {
		case 'a':
			pc_info.rshell_args = (int8_t *)strdup(optarg);
			if (NULL == pc_info.rshell_args) {
				TRACE_ERR("Can't strdup remote shell args!!\n");
			}
			break;
		case 'b':
			pc_info.batch_size = atoi(optarg);
			TRACE_DEBUG_LOG("Taking batch_size as %d\n", 
					pc_info.batch_size);
			break;
		case 'd':
			pc_info.daemonize = 1;
			break;
		case 'h':
			print_help(*argv);
			break;
		case 'f':
			pc_info.lua_startup_file = (uint8_t *)strdup(optarg);
			if (NULL == pc_info.lua_startup_file) {
				TRACE_ERR("Can't strdup string for lua_startup_file: %s\n",
					  strerror(errno));
			}
			TRACE_DEBUG_LOG("Taking file %s as startup\n",
					pc_info.lua_startup_file);
			load_lua_file(optarg);
			break;
		case 's':
			pc_info.rshell = 1;
			break;
		default:
			print_help(*argv);
			break;
		}
	}

	/* init_modules */
	init_modules();

	/* check if rshell and daemonize are both enabled */
	if (pc_info.daemonize && pc_info.rshell) {
		fprintf(stdout, "You cannot create a daemon process and "
			"a remote shell at the same time!\n");
		fflush(stdout);
		print_help(*argv);
		return EXIT_FAILURE;
	}
	
	/* warp to remote shell, if asked */
	if (pc_info.rshell) {
		if (pc_info.rshell_args == NULL)
			fprintf(stdout, "Using localhost and port %d by default\n",
				BRICKS_LISTEN_PORT);
		lua_kickoff(LUA_EXE_REMOTE_SHELL, pc_info.rshell_args);
		return EXIT_SUCCESS;
	}

	/* daemonize, if asked */
	if ((pc_info.daemonize && (rc=do_daemonize()) == 0) ||
	    !pc_info.daemonize) {
		if (mark_pid_file(pv.pid_file) != 0) {
			TRACE_FUNC_END();
			TRACE_ERR("Can't lock the pid file.\n"
				  "Is a previous bricks daemon already running??\n");
		}
		export_global_socket();
		lua_kickoff((pc_info.daemonize) ? 
			    LUA_EXE_SCRIPT : LUA_EXE_HOME_SHELL, NULL);
	}

	/* initialize file printing mini-module */
	print_status_file();

	/* 
	 * if the user wants to daemonize and the process 
	 * is the child, then jump to accepting requests...
	 */
	if (pc_info.daemonize && rc == 0) {
		start_listening_reqs();
	}
	
	TRACE_FUNC_END();
	clean_exit(EXIT_SUCCESS);

	/* control will never come here */
	return EXIT_SUCCESS;
}
Пример #20
0
/**
 * Main routine, start of the program execution.
 * \param argc the number of arguments
 * \param argv pointer to the arguments array
 * \return don't return on sucess, -1 on error
 * \see main_loop
 */
int main(int argc, char** argv)
{
	/* configure by default logging to syslog */
	int cfg_log_stderr = 0;
	FILE* cfg_stream;
	int c,r;
	char *tmp;
	int tmp_len;
	int port;
	int proto;
	char *options;
	int ret;
	unsigned int seed;
	int rfd;

	/*init*/
	ret=-1;
	my_argc=argc; my_argv=argv;

	/*init pkg mallocs (before parsing cfg or cmd line !)*/
	if (init_pkg_mallocs()==-1)
		goto error00;

	init_route_lists();
	/* process command line (get port no, cfg. file path etc) */
	opterr=0;
	options="f:cCm:b:l:n:N:rRvdDETSVhw:t:u:g:P:G:W:o:";

	while((c=getopt(argc,argv,options))!=-1){
		switch(c){
			case 'f':
					cfg_file=optarg;
					break;
			case 'C':
					config_check |= 2;
			case 'c':
					if (config_check==3)
						break;
					config_check |= 1;
					cfg_log_stderr=1; /* force stderr logging */
					break;
			case 'm':
					shm_mem_size=strtol(optarg, &tmp, 10) * 1024 * 1024;
					if (tmp &&(*tmp)){
						LM_ERR("bad shmem size number: -m %s\n", optarg);
						goto error00;
					};

					break;
			case 'b':
					maxbuffer=strtol(optarg, &tmp, 10);
					if (tmp &&(*tmp)){
						LM_ERR("bad max buffer size number: -b %s\n", optarg);
						goto error00;
					}
					break;
			case 'l':
					if (parse_phostport(optarg, strlen(optarg), &tmp, &tmp_len,
											&port, &proto)<0){
						LM_ERR("bad -l address specifier: %s\n", optarg);
						goto error00;
					}
					tmp[tmp_len]=0; /* null terminate the host */
					/* add a new addr. to our address list */
					if (add_listen_iface(tmp, port, proto, 0, 0, 0)!=0){
						LM_ERR("failed to add new listen address\n");
						goto error00;
					}
					break;
			case 'n':
					children_no=strtol(optarg, &tmp, 10);
					if ((tmp==0) ||(*tmp)){
						LM_ERR("bad process number: -n %s\n", optarg);
						goto error00;
					}
					break;
			case 'v':
					check_via=1;
					break;
			case 'r':
					received_dns|=DO_DNS;
					break;
			case 'R':
					received_dns|=DO_REV_DNS;
			case 'd':
#ifdef CHANGEABLE_DEBUG_LEVEL
					(*debug)++;
#else
					debug++;
#endif
					break;
			case 'D':
					dont_fork=1;
					break;
			case 'E':
					cfg_log_stderr=1;
					break;
			case 'T':
#ifdef USE_TCP
					tcp_disable=1;
#else
					LM_WARN("tcp support not compiled in\n");
#endif
					break;
			case 'S':
#ifdef USE_SCTP
					sctp_disable=1;
#else
					LM_WARN("sctp support not compiled in\n");
#endif
			break;
			case 'N':
#ifdef USE_TCP
					tcp_children_no=strtol(optarg, &tmp, 10);
					if ((tmp==0) ||(*tmp)){
						LM_ERR("bad process number: -N %s\n", optarg);
						goto error00;
					}
#else
					LM_WARN("tcp support not compiled in\n");
#endif
					break;
			case 'W':
#ifdef USE_TCP
					tcp_poll_method=get_poll_type(optarg);
					if (tcp_poll_method==POLL_NONE){
						LM_ERR("bad poll method name: -W %s\ntry "
							"one of %s.\n", optarg, poll_support);
						goto error00;
					}
#else
					LM_WARN("tcp support not compiled in\n");
#endif
					break;
			case 'V':
					printf("version: %s\n", version);
					printf("flags: %s\n", flags );
					print_ct_constants();
					printf("%s\n",id);
					printf("%s compiled on %s with %s\n", __FILE__,
							compiled, COMPILER );
					
					exit(0);
					break;
			case 'h':
					printf("version: %s\n", version);
					printf("%s",help_msg);
					exit(0);
					break;
			case 'w':
					working_dir=optarg;
					break;
			case 't':
					chroot_dir=optarg;
					break;
			case 'u':
					user=optarg;
					break;
			case 'g':
					group=optarg;
					break;
			case 'P':
					pid_file=optarg;
					break;
			case 'G':
					pgid_file=optarg;
					break;
			case 'o':
					if (add_arg_var(optarg) < 0)
						LM_ERR("cannot add option %s\n", optarg);
					break;
			case '?':
					if (isprint(optopt))
						LM_ERR("Unknown option `-%c`.\n", optopt);
					else
						LM_ERR("Unknown option character `\\x%x`.\n", optopt);
					goto error00;
			case ':':
					LM_ERR("Option `-%c` requires an argument.\n", optopt);
					goto error00;
			default:
					abort();
		}
	}

	log_stderr = cfg_log_stderr;

	/* fill missing arguments with the default values*/
	if (cfg_file==0) cfg_file=CFG_FILE;

	/* load config file or die */
	cfg_stream=fopen (cfg_file, "r");
	if (cfg_stream==0){
		LM_ERR("loading config file(%s): %s\n", cfg_file,
				strerror(errno));
		goto error00;
	}

	/* seed the prng, try to use /dev/urandom if possible */
	/* no debugging information is logged, because the standard
	   log level prior the config file parsing is L_NOTICE */
	seed=0;
	if ((rfd=open("/dev/urandom", O_RDONLY))!=-1){
try_again:
		if (read(rfd, (void*)&seed, sizeof(seed))==-1){
			if (errno==EINTR) goto try_again; /* interrupted by signal */
			LM_WARN("could not read from /dev/urandom (%d)\n", errno);
		}
		LM_DBG("initialize the pseudo random generator from "
			"/dev/urandom\n");
		LM_DBG("read %u from /dev/urandom\n", seed);
			close(rfd);
	}else{
		LM_WARN("could not open /dev/urandom (%d)\n", errno);
		LM_WARN("using a unsafe seed for the pseudo random number generator");
	}
	seed+=getpid()+time(0);
	LM_DBG("seeding PRNG with %u\n", seed);
	srand(seed);
	LM_DBG("test random number %u\n", rand());

	/*register builtin  modules*/
	register_builtin_modules();

#ifdef USE_TLS
	/* initialize default TLS domains,
	   must be done before reading the config */
	if (pre_init_tls()<0){
		LM_CRIT("could not pre_init_tls, exiting...\n");
		goto error00;
	}
#endif /* USE_TLS */

	if (preinit_black_lists()!=0) {
		LM_CRIT("failed to alloc black list's anchor\n");
		goto error00;
	}

	/* parse the config file, prior to this only default values
	   e.g. for debugging settings will be used */
	yyin=cfg_stream;
	if ((yyparse()!=0)||(cfg_errors)){
		LM_ERR("bad config file (%d errors)\n", cfg_errors);
		goto error00;
	}

	if (config_check>1 && check_rls()!=0) {
		LM_ERR("bad function call in config file\n");
		return ret;
	}
#ifdef EXTRA_DEBUG
	print_rl();
#endif

	/* init the resolver, before fixing the config */
	resolv_init();

	/* fix parameters */
	if (port_no<=0) port_no=SIP_PORT;
#ifdef USE_TLS
	if (tls_port_no<=0) tls_port_no=SIPS_PORT;
#endif
	
	
	if (children_no<=0) children_no=CHILD_NO;
#ifdef USE_TCP
	if (!tcp_disable){
		if (tcp_children_no<=0) tcp_children_no=children_no;
	}
#endif
	
	if (working_dir==0) working_dir="/";

	/* get uid/gid */
	if (user){
		if (user2uid(&uid, &gid, user)<0){
			LM_ERR("bad user name/uid number: -u %s\n", user);
			goto error00;
		}
	}
	if (group){
		if (group2gid(&gid, group)<0){
			LM_ERR("bad group name/gid number: -u %s\n", group);
			goto error00;
		}
	}
	if (fix_all_socket_lists()!=0){
		LM_ERR("failed to initialize list addresses\n");
		goto error00;
	}
	/* print all the listen addresses */
	printf("Listening on \n");
	print_all_socket_lists();
	printf("Aliases: \n");
	/*print_aliases();*/
	print_aliases();
	printf("\n");
	
	if (dont_fork){
		LM_WARN("no fork mode %s\n", 
				(udp_listen)?(
				(udp_listen->next)?" and more than one listen address found"
				"(will use only the first one)":""
				):"and no udp listen address found" );
	}
	if (config_check){
		LM_NOTICE("config file ok, exiting...\n");
		return 0;
	}


	time(&startup_time);

	/*init shm mallocs
	 *  this must be here 
	 *     -to allow setting shm mem size from the command line
	 *       => if shm_mem should be settable from the cfg file move
	 *       everything after
	 *     -it must be also before init_timer and init_tcp
	 *     -it must be after we know uid (so that in the SYSV sems case,
	 *        the sems will have the correct euid)
	 * --andrei */
	if (init_shm_mallocs()==-1)
		goto error;
	/*init timer, before parsing the cfg!*/
	if (init_timer()<0){
		LM_CRIT("could not initialize timer, exiting...\n");
		goto error;
	}
	
#ifdef USE_TCP
	if (!tcp_disable){
		/*init tcp*/
		if (init_tcp()<0){
			LM_CRIT("could not initialize tcp, exiting...\n");
			goto error;
		}
	}
#ifdef USE_TLS
	if (!tls_disable){
		/* init tls*/
		if (init_tls()<0){
			LM_CRIT("could not initialize tls, exiting...\n");
			goto error;
		}
	}
#endif /* USE_TLS */
#endif /* USE_TCP */

	/* init_daemon? */
	if (!dont_fork){
		if ( daemonize((log_name==0)?argv[0]:log_name, &own_pgid) <0 )
			goto error;
	}

	/* install signal handlers */
	if (install_sigs() != 0){
		LM_ERR("could not install the signal handlers\n");
		goto error;
	}

#ifdef CHANGEABLE_DEBUG_LEVEL
#ifdef SHM_MEM
	debug=shm_malloc(sizeof(int));
	if (debug==0) {
		LM_ERR("ERROR: out of memory\n");
		goto error;
	}
	*debug = debug_init;
#else
	LM_WARN("no shm mem support compiled -> changeable debug "
		"level turned off\n");
#endif
#endif

	if (disable_core_dump) set_core_dump(0, 0);
	else set_core_dump(1, shm_mem_size+PKG_MEM_POOL_SIZE+4*1024*1024);
	if (open_files_limit>0){
		if(increase_open_fds(open_files_limit)<0){ 
			LM_ERR("ERROR: error could not increase file limits\n");
			goto error;
		}
	}

	/* print OpenSIPS version to log for history tracking */
	LM_NOTICE("version: %s\n", version);
	
	/* print some data about the configuration */
#ifdef SHM_MEM
	LM_INFO("using %ld Mb shared memory\n", ((shm_mem_size/1024)/1024));
#endif
	LM_INFO("using %i Mb private memory per process\n", ((PKG_MEM_POOL_SIZE/1024)/1024));

	/* init serial forking engine */
	if (init_serialization()!=0) {
		LM_ERR("failed to initialize serialization\n");
		goto error;
	}
	/* Init statistics */
	if (init_stats_collector()<0) {
		LM_ERR("failed to initialize statistics\n");
		goto error;
	}
	/* Init MI */
	if (init_mi_core()<0) {
		LM_ERR("failed to initialize MI core\n");
		goto error;
	}
	/* init black list engine */
	if (init_black_lists()!=0) {
		LM_CRIT("failed to init black lists\n");
		goto error;
	}
	/* init resolver's blacklist */
	if (resolv_blacklist_init()!=0) {
		LM_CRIT("failed to create DNS blacklist\n");
		goto error;
	}

	/* init modules */
	if (init_modules() != 0) {
		LM_ERR("error while initializing modules\n");
		goto error;
	}

	/* register route timers */
	if(register_route_timers() < 0) {
		LM_ERR("Failed to register timer\n");
		goto error;
	}

	/* check pv context list */
	if(pv_contextlist_check() != 0) {
		LM_ERR("used pv context that was not defined\n");
		goto error;
	}
	/* init multi processes support */
	if (init_multi_proc_support()!=0) {
		LM_ERR("failed to init multi-proc support\n");
		goto error;
	}

	#ifdef PKG_MALLOC
	/* init stats support for pkg mem */
	if (init_pkg_stats(counted_processes)!=0) {
		LM_ERR("failed to init stats for pkg\n");
		goto error;
	}
	#endif

	/* fix routing lists */
	if ( (r=fix_rls())!=0){
		LM_ERR("failed to fix configuration with err code %d\n", r);
		goto error;
	};


	ret=main_loop();

error:
	/*kill everything*/
	kill_all_children(SIGTERM);
	/*clean-up*/
	cleanup(0);
error00:
	return ret;
}
Пример #21
0
/**
 * Main routine, start of the program execution.
 * \param argc the number of arguments
 * \param argv pointer to the arguments array
 * \return don't return on sucess, -1 on error
 * \see main_loop
 */
int main(int argc, char** argv)
{
	/* configure by default logging to syslog */
	int cfg_log_stderr = 0;
	FILE* cfg_stream;
	int c,r;
	char *tmp;
	int tmp_len;
	int port;
	int proto;
	char *options;
	int ret;
	unsigned int seed;
	int rfd;

	/*init*/
	ret=-1;
	my_argc=argc; my_argv=argv;

	/* process pkg mem size from command line */
	opterr=0;
	options="f:cCm:M:b:l:n:N:rRvdDFETSVhw:t:u:g:P:G:W:o:";

	while((c=getopt(argc,argv,options))!=-1){
		switch(c){
			case 'M':
					pkg_mem_size=strtol(optarg, &tmp, 10) * 1024 * 1024;
					if (tmp &&(*tmp)){
						LM_ERR("bad pkgmem size number: -m %s\n", optarg);
						goto error00;
					};

					break;
		}
	}
	/*init pkg mallocs (before parsing cfg but after parsing cmd line !)*/
	if (init_pkg_mallocs()==-1)
		goto error00;

	init_route_lists();

	/* process command line (get port no, cfg. file path etc) */
	/* first reset getopt */
	optind = 1;
	while((c=getopt(argc,argv,options))!=-1){
		switch(c){
			case 'f':
					cfg_file=optarg;
					break;
			case 'C':
					config_check |= 2;
			case 'c':
					if (config_check==3)
						break;
					config_check |= 1;
					cfg_log_stderr=1; /* force stderr logging */
					break;
			case 'm':
					shm_mem_size=strtol(optarg, &tmp, 10) * 1024 * 1024;
					if (tmp &&(*tmp)){
						LM_ERR("bad shmem size number: -m %s\n", optarg);
						goto error00;
					};

					break;
			case 'M':
					/* ignoring it, parsed previously */

					break;
			case 'b':
					maxbuffer=strtol(optarg, &tmp, 10);
					if (tmp &&(*tmp)){
						LM_ERR("bad max buffer size number: -b %s\n", optarg);
						goto error00;
					}
					break;
			case 'l':
					if (parse_phostport(optarg, strlen(optarg), &tmp, &tmp_len,
											&port, &proto)<0){
						LM_ERR("bad -l address specifier: %s\n", optarg);
						goto error00;
					}
					tmp[tmp_len]=0; /* null terminate the host */
					/* add a new addr. to our address list */
					if (add_cmd_listener(tmp, port, proto)!=0){
						LM_ERR("failed to add new listen address\n");
						goto error00;
					}
					break;
			case 'n':
					children_no=strtol(optarg, &tmp, 10);
					if ((tmp==0) ||(*tmp)){
						LM_ERR("bad process number: -n %s\n", optarg);
						goto error00;
					}
					break;
			case 'v':
					check_via=1;
					break;
			case 'r':
					received_dns|=DO_DNS;
					break;
			case 'R':
					received_dns|=DO_REV_DNS;
				    break;
			case 'd':
					(*debug)++;
					break;
			case 'D':
					dont_fork=1;
					break;
			case 'F':
					no_daemon_mode=1;
					break;
			case 'E':
					cfg_log_stderr=1;
					break;
			case 'N':
					tcp_children_no=strtol(optarg, &tmp, 10);
					if ((tmp==0) ||(*tmp)){
						LM_ERR("bad process number: -N %s\n", optarg);
						goto error00;
					}
					break;
			case 'W':
					io_poll_method=get_poll_type(optarg);
					if (io_poll_method==POLL_NONE){
						LM_ERR("bad poll method name: -W %s\ntry "
							"one of %s.\n", optarg, poll_support);
						goto error00;
					}
					break;
			case 'V':
					printf("version: %s\n", version);
					printf("flags: %s\n", flags );
					print_ct_constants();
					printf("%s compiled on %s with %s\n", __FILE__,
							compiled, COMPILER );

					exit(0);
					break;
			case 'h':
					printf("version: %s\n", version);
					printf("%s",help_msg);
					exit(0);
					break;
			case 'w':
					working_dir=optarg;
					break;
			case 't':
					chroot_dir=optarg;
					break;
			case 'u':
					user=optarg;
					break;
			case 'g':
					group=optarg;
					break;
			case 'P':
					pid_file=optarg;
					break;
			case 'G':
					pgid_file=optarg;
					break;
			case 'o':
					if (add_arg_var(optarg) < 0)
						LM_ERR("cannot add option %s\n", optarg);
					break;
			case '?':
					if (isprint(optopt))
						LM_ERR("Unknown option `-%c`.\n", optopt);
					else
						LM_ERR("Unknown option character `\\x%x`.\n", optopt);
					goto error00;
			case ':':
					LM_ERR("Option `-%c` requires an argument.\n", optopt);
					goto error00;
			default:
					abort();
		}
	}

	log_stderr = cfg_log_stderr;

	/* fill missing arguments with the default values*/
	if (cfg_file==0) cfg_file=CFG_FILE;

	/* load config file or die */
	cfg_stream=fopen (cfg_file, "r");
	if (cfg_stream==0){
		LM_ERR("loading config file(%s): %s\n", cfg_file,
				strerror(errno));
		goto error00;
	}

	/* seed the prng, try to use /dev/urandom if possible */
	/* no debugging information is logged, because the standard
	   log level prior the config file parsing is L_NOTICE */
	seed=0;
	if ((rfd=open("/dev/urandom", O_RDONLY))!=-1){
try_again:
		if (read(rfd, (void*)&seed, sizeof(seed))==-1){
			if (errno==EINTR) goto try_again; /* interrupted by signal */
			LM_WARN("could not read from /dev/urandom (%d)\n", errno);
		}
		LM_DBG("initialize the pseudo random generator from "
			"/dev/urandom\n");
		LM_DBG("read %u from /dev/urandom\n", seed);
			close(rfd);
	}else{
		LM_WARN("could not open /dev/urandom (%d)\n", errno);
		LM_WARN("using a unsafe seed for the pseudo random number generator");
	}
	seed+=getpid()+time(0);
	LM_DBG("seeding PRNG with %u\n", seed);
	srand(seed);
	LM_DBG("test random number %u\n", rand());

	/*register builtin  modules*/
	register_builtin_modules();

	/* init avps */
	if (init_global_avps() != 0) {
		LM_ERR("error while initializing avps\n");
		goto error;
	}

	/* used for parser debugging */
#ifdef DEBUG_PARSER
	yydebug = 1;
#endif

	/*
	 * initializes transport interfaces - we initialize them here because we
	 * can have listening interfaces declared in the command line
	 */
	if (trans_init() < 0) {
		LM_ERR("cannot initialize transport interface\n");
		goto error;
	}

		/* get uid/gid */
	if (user){
		if (user2uid(&uid, &gid, user)<0){
			LM_ERR("bad user name/uid number: -u %s\n", user);
			goto error00;
		}
	}
	if (group){
		if (group2gid(&gid, group)<0){
			LM_ERR("bad group name/gid number: -u %s\n", group);
			goto error00;
		}
	}

		/*init shm mallocs
	 *  this must be here
	 *     -to allow setting shm mem size from the command line
	 *     -it must be also before init_timer and init_tcp
	 *     -it must be after we know uid (so that in the SYSV sems case,
	 *        the sems will have the correct euid)
	 * --andrei */
	if (init_shm_mallocs()==-1)
		goto error;

	if (init_stats_collector() < 0) {
		LM_ERR("failed to initialize statistics\n");
		goto error;
	}

	/* parse the config file, prior to this only default values
	   e.g. for debugging settings will be used */
	yyin=cfg_stream;
	if ((yyparse()!=0)||(cfg_errors)){
		LM_ERR("bad config file (%d errors)\n", cfg_errors);
		goto error00;
	}

	if (config_check>1 && check_rls()!=0) {
		LM_ERR("bad function call in config file\n");
		return ret;
	}

	if (solve_module_dependencies(modules) != 0) {
		LM_ERR("failed to solve module dependencies\n");
		return -1;
	}

#ifdef EXTRA_DEBUG
	print_rl();
#endif

	if (no_daemon_mode+dont_fork > 1) {
		LM_ERR("cannot use -D (fork=no) and -F together\n");
		return ret;
	}

	/* init the resolver, before fixing the config */
	resolv_init();

	fix_poll_method( &io_poll_method );

	/* fix temporary listeners added in the cmd line */
	if (fix_cmd_listeners() < 0) {
		LM_ERR("cannot add temproray listeners\n");
		return ret;
	}

	/* load transport protocols */
	if (trans_load() < 0) {
		LM_ERR("cannot load transport protocols\n");
		goto error;
	}

	/* fix parameters */
	if (working_dir==0) working_dir="/";

	if (fix_all_socket_lists()!=0){
		LM_ERR("failed to initialize list addresses\n");
		goto error00;
	}
	/* print all the listen addresses */
	printf("Listening on \n");
	print_all_socket_lists();
	printf("Aliases: \n");
	/*print_aliases();*/
	print_aliases();
	printf("\n");

	if (dont_fork){
		LM_WARN("no fork mode %s\n",
				(protos[PROTO_UDP].listeners)?(
				(protos[PROTO_UDP].listeners->next)?" and more than one listen"
				" address found(will use only the first one)":""
				):"and no udp listen address found" );
	}
	if (config_check){
		LM_NOTICE("config file ok, exiting...\n");
		return 0;
	}

	time(&startup_time);



	/* Init statistics */
	init_shm_statistics();

	/*init UDP networking layer*/
	if (udp_init()<0){
		LM_CRIT("could not initialize tcp, exiting...\n");
		goto error;
	}
	/*init TCP networking layer*/
	if (tcp_init()<0){
		LM_CRIT("could not initialize tcp, exiting...\n");
		goto error;
	}

	/* init_daemon? */
	if (!dont_fork){
		if ( daemonize((log_name==0)?argv[0]:log_name, &own_pgid) <0 )
			goto error;
	}

	/* install signal handlers */
	if (install_sigs() != 0){
		LM_ERR("could not install the signal handlers\n");
		goto error;
	}

	if (disable_core_dump) set_core_dump(0, 0);
	else set_core_dump(1, shm_mem_size+pkg_mem_size+4*1024*1024);
	if (open_files_limit>0){
		if(increase_open_fds(open_files_limit)<0){
			LM_ERR("ERROR: error could not increase file limits\n");
			goto error;
		}
	}

	/* print OpenSIPS version to log for history tracking */
	LM_NOTICE("version: %s\n", version);

	/* print some data about the configuration */
	LM_INFO("using %ld Mb shared memory\n", ((shm_mem_size/1024)/1024));
	LM_INFO("using %ld Mb private memory per process\n",
		((pkg_mem_size/1024)/1024));

	/* init timer */
	if (init_timer()<0){
		LM_CRIT("could not initialize timer, exiting...\n");
		goto error;
	}

	/* init serial forking engine */
	if (init_serialization()!=0) {
		LM_ERR("failed to initialize serialization\n");
		goto error;
	}
	/* Init MI */
	if (init_mi_core()<0) {
		LM_ERR("failed to initialize MI core\n");
		goto error;
	}

	/* Register core events */
	if (evi_register_core() != 0) {
		LM_ERR("failed register core events\n");
		goto error;
	}

	/* init black list engine */
	if (init_black_lists()!=0) {
		LM_CRIT("failed to init blacklists\n");
		goto error;
	}
	/* init resolver's blacklist */
	if (resolv_blacklist_init()!=0) {
		LM_CRIT("failed to create DNS blacklist\n");
		goto error;
	}

	/* init modules */
	if (init_modules() != 0) {
		LM_ERR("error while initializing modules\n");
		goto error;
	}

	/* register route timers */
	if(register_route_timers() < 0) {
		LM_ERR("Failed to register timer\n");
		goto error;
	}

	/* check pv context list */
	if(pv_contextlist_check() != 0) {
		LM_ERR("used pv context that was not defined\n");
		goto error;
	}

	/* init query list now in shm
	 * so all processes that will be forked from now on
	 * will have access to it
	 *
	 * if it fails, give it a try and carry on */
	if (init_ql_support() != 0) {
		LM_ERR("failed to initialise buffering query list\n");
		query_buffer_size = 0;
		*query_list = NULL;
	}

	/* init multi processes support */
	if (init_multi_proc_support()!=0) {
		LM_ERR("failed to init multi-proc support\n");
		goto error;
	}

	#ifdef PKG_MALLOC
	/* init stats support for pkg mem */
	if (init_pkg_stats(counted_processes)!=0) {
		LM_ERR("failed to init stats for pkg\n");
		goto error;
	}
	#endif

	/* init avps */
	if (init_extra_avps() != 0) {
		LM_ERR("error while initializing avps\n");
		goto error;
	}

	/* fix routing lists */
	if ( (r=fix_rls())!=0){
		LM_ERR("failed to fix configuration with err code %d\n", r);
		goto error;
	};

	ret=main_loop();

error:
	/*kill everything*/
	kill_all_children(SIGTERM);
	/*clean-up*/
	cleanup(0);
error00:
	return ret;
}
Пример #22
0
int main(int argc, char *argv[], char *envp[])
{
	int action = 0;
	int verbose = 0;
	int verbose_tmp;
	int verbose_custom = 0;
	int quiet = 0;
	int veid, ret, skiplock = 0;
	char buf[256];
	vps_param *gparam = NULL, *vps_p = NULL, *cmd_p = NULL;
	const char *action_nm;
	struct sigaction act;
	char *name = NULL, *opt;

	_proc_title = argv[0];
	_proc_title_len = envp[0] - argv[0];

	gparam = init_vps_param();
	vps_p = init_vps_param();
	cmd_p = init_vps_param();

	sigemptyset(&act.sa_mask);
	act.sa_handler = SIG_IGN;
	act.sa_flags = 0;
	sigaction(SIGPIPE, &act, NULL);

	while (argc > 1) {
		opt = argv[1];

		if (!strcmp(opt, "--verbose")) {
			if (argc > 2 &&
			    !parse_int(argv[2], &verbose_tmp))
			{
				verbose += verbose_tmp;
				argc--; argv++;
			} else {
				verbose++;
			}
			verbose_custom = 1;
		} else if (!strncmp(opt, "--verbose=", 10)) {
			if (parse_int(opt + 10, &verbose_tmp)) {
				fprintf(stderr, "Invalid value for"
					" --verbose\n");
				exit(VZ_INVALID_PARAMETER_VALUE);
			}
			verbose += verbose_tmp;
			verbose_custom = 1;
		} else if (!strcmp(opt, "--quiet"))
			quiet = 1;
		else if (!strcmp(opt, "--version")) {
			version(stdout);
			exit(0);
		} else if (!strcmp(opt, "--skiplock"))
			skiplock = YES;
		else
			break;
		argc--; argv++;
	}
	if (argc <= 1)
		usage(VZ_INVALID_PARAMETER_SYNTAX);
	action_nm = argv[1];
	init_log(NULL, 0, 1, verbose, 0, NULL);
	if (!strcmp(argv[1], "set")) {
		init_modules(&g_action, "set");
		action = ACTION_SET;
	//	status = ST_SET;
	} else if (!strcmp(argv[1], "create")) {
		init_modules(&g_action, "create");
		action = ACTION_CREATE;
	//	status = ST_CREATE;
	} else if (!strcmp(argv[1], "start")) {
		init_modules(&g_action, "set");
		action = ACTION_START;
	//	status = ST_START;
	} else if (!strcmp(argv[1], "stop")) {
		init_modules(&g_action, "set");
		action = ACTION_STOP;
	//	status = ST_STOP;
	} else if (!strcmp(argv[1], "restart")) {
		action = ACTION_RESTART;
	//	status = ST_RESTART;
	} else if (!strcmp(argv[1], "destroy")) {
		action = ACTION_DESTROY;
	//	status = ST_DESTROY;
	} else if (!strcmp(argv[1], "mount")) {
		action = ACTION_MOUNT;
	//	status = ST_MOUNT;
	} else if (!strcmp(argv[1], "umount")) {
		action = ACTION_UMOUNT;
	//	status = ST_UMOUNT;
	} else if (!strcmp(argv[1], "exec3")) {
		action = ACTION_EXEC3;
	} else if (!strcmp(argv[1], "exec2")) {
		action = ACTION_EXEC2;
	} else if (!strcmp(argv[1], "exec")) {
		action = ACTION_EXEC;
	} else if (!strcmp(argv[1], "runscript")) {
		action = ACTION_RUNSCRIPT;
	} else if (!strcmp(argv[1], "enter")) {
		action = ACTION_ENTER;
	} else if (!strcmp(argv[1], "status")) {
		action = ACTION_STATUS;
		quiet = 1;
	} else if (!strcmp(argv[1], "chkpnt")) {
		action = ACTION_CHKPNT;
	} else if (!strcmp(argv[1], "restore")) {
		action = ACTION_RESTORE;
	} else if (!strcmp(argv[1], "quotaon")) {
		action = ACTION_QUOTAON;
	} else if (!strcmp(argv[1], "quotaoff")) {
		action = ACTION_QUOTAOFF;
	} else if (!strcmp(argv[1], "quotainit")) {
		action = ACTION_QUOTAINIT;
	} else if (!strcmp(argv[1], "--help")) {
		usage(0);
	} else {
		init_modules(&g_action, action_nm);
		action = ACTION_CUSTOM;
		if (!g_action.mod_count) {
			fprintf(stderr, "Bad command: %s\n", argv[1]);
			ret = VZ_INVALID_PARAMETER_SYNTAX;
			goto error;
		}
	}
	if (argc < 3) {
		fprintf(stderr, "CT ID missing\n");
		ret = VZ_INVALID_PARAMETER_VALUE;
		goto error;
	}
	if (parse_int(argv[2], &veid)) {
		name = strdup(argv[2]);
		veid = get_veid_by_name(name);
		if (veid < 0) {
			fprintf(stderr, "Bad CT ID %s\n", argv[2]);
			ret = VZ_INVALID_PARAMETER_VALUE;
			goto error;
		}
	}
	argc -= 2; argv += 2;
	/* Read global config file */
	if (vps_parse_config(veid, GLOBAL_CFG, gparam, &g_action)) {
		fprintf(stderr, "Global configuration file %s not found\n",
			GLOBAL_CFG);
		ret = VZ_NOCONFIG;
		goto error;
	}
	init_log(gparam->log.log_file, veid, gparam->log.enable != NO,
		gparam->log.level, quiet, "vzctl");
	/* Set verbose level from global config if not overwriten
	   by --verbose
	*/
	if (!verbose_custom && gparam->log.verbose != NULL) {
		verbose = *gparam->log.verbose;
		verbose_custom = 1;
	}
	if (verbose < -1)
		verbose = -1;
	if (verbose_custom)
		set_log_verbose(verbose);
	if ((ret = parse_action_opt(veid, action, argc, argv, cmd_p,
		action_nm)))
	{
		goto error;
	}
	if (veid == 0 && action != ACTION_SET) {
		fprintf(stderr, "Only set actions are allowed for CT0\n");
		ret = VZ_INVALID_PARAMETER_VALUE;
		goto error;
	} else if (veid < 0) {
		fprintf(stderr, "Bad CT ID %d\n", veid);
		ret = VZ_INVALID_PARAMETER_VALUE;
		goto error;
	}
	get_vps_conf_path(veid, buf, sizeof(buf));
	if (stat_file(buf)) {
		if (vps_parse_config(veid, buf, vps_p, &g_action)) {
			logger(-1, 0, "Error in config file %s",
				buf);
			ret = VZ_NOCONFIG;
			goto error;
		}
		if (name != NULL &&
		    vps_p->res.name.name != NULL &&
		    strcmp(name, vps_p->res.name.name))
		{
			logger(-1, 0, "Unable to find container by name %s",
					name);
			ret = VZ_INVALID_PARAMETER_VALUE;
			goto error;
		}
	} else if (action != ACTION_CREATE &&
			action != ACTION_STATUS &&
			action != ACTION_SET)
	{
		logger(-1, 0, "Container config file does not exist");
		ret = VZ_NOVECONFIG;
		goto error;
	}
	merge_vps_param(gparam, vps_p);
	merge_global_param(cmd_p, gparam);
	ret = run_action(veid, action, gparam, vps_p, cmd_p, argc-1, argv+1,
		skiplock);

error:
	free_modules(&g_action);
	free_vps_param(gparam);
	free_vps_param(vps_p);
	free_vps_param(cmd_p);
	free_log();
	if (name != NULL) free(name);

	return ret;
}
Пример #23
0
int
main (void)
{

  /*****************************************************************************
   *
   * initialize and register all modules
   *
   *****************************************************************************/

  init_modules();

#ifdef ENABLE_DIO
  register_module((uint16_t**)gpio_Mod_Info);
#endif

#ifdef ENABLE_ADC
  register_module((uint16_t**)ADC_Mod_Info);
#endif

#ifdef ENABLE_PWM
  register_module((uint16_t**)pwm_Mod_Info);
#endif


  /*****************************************************************************
   *
   * initilaize 1ms timer-interrupt and enable interrupts globaly
   *
   *****************************************************************************/

  init_SysTimer ();
  DebugTick = request_SysTimer ();
  ProcTick = request_SysTimer ();

  /*****************************************************************************
   *
   * initilaize spi-communication and data-structures
   *
   *****************************************************************************/

  RPi_init (MAX(sizeof(OMap_t), sizeof(IMap_t)), 20, &RPi);

  /*****************************************************************************
   *
   * register SPI-commands from all modules
   *
   *****************************************************************************/

  register_mod_spi_commands();

  sps_init ();

#ifdef ENABLE_XCOM
  /*****************************************************************************
   *
   * check if slave present and enable it
   *
   *****************************************************************************/

  if (Xcom_init ())
    {
      Features |= SP_BIT;
      SlaveTick = request_SysTimer();
    }
#endif

  RPi_start ();	// Finaly start SPI-communication

  DDRD |= ((1 << PD4) | (1 << PD5));

  DEBUGTICK = 0;

  /*****************************************************************************
   *
   * main loop starts her
   *
   *****************************************************************************/

  while (1)
    {

      /*****************************************************************************
       *
       * call the components workers
       *
       *****************************************************************************/

      RPi_worker ();
      sps_worker ();

/*	  switch (RPi.Status)
	    {
	    case RPI_STAT_IDLE:
	      PORTD |= ((1 << PD4) | (1 << PD5)); // 1 1;
	      break;
	    case RPI_STAT_RUN:
	      PORTD = PORTB & ~((1 << PD4) | (1 << PD5));	// 0 0
	      break;
	    case RPI_STAT_AUTO:
	      PORTD &= ~(1 << PD4);
	      PORTD |= (1 << PD5);	// 0 1
	      break;
	    case RPI_STAT_CRC16_ERROR:
	      PORTD &= ~(1 << PD5);
	      PORTD |= (1 << PD4);	// 1 0
	      break;
	    case RPI_STAT_MAN:
	    case RPI_STAT_MAN_UNKNOWN:
	      break;
	    }
	    */

      /*****************************************************************************
       *
       * some debugging helper
       *
       *****************************************************************************/

/*      if (DEBUGTICK == 2)
	{
	      DEBUGTICK = 0;
	}
*/

#ifdef ENABLE_XCOMM
      if (SLAVE_PRESENT)
	{
	  Xcom_worker ();
	  if (SL_TICK == 3)
	    {
/*	      if (make_crc16 (sizeof(SMap_t), (uint8_t *) &XcomRxBuffer.buf)
		  == XcomRxBuffer.rio.crc16)
		{
		  memcpy((void *)&SlaveMap,&XcomRxBuffer.rio.io,sizeof(SMap_t));
		}
*/
	      Xcom_ack ();
	      Xcom_cmd (XCMD_INPUT, 15, &RealOutput);
//	      Xcom_cmd (XCMD_INPUT, sizeof(IMap_t), &InputMap);
	      SL_TICK++;
	    }
	  if (SL_TICK == 16)
	    {
	      Xcom_ack ();
	      Xcom_cmd (XCMD_OUTPUT, sizeof(OMap_t), RPi.tx);
	      SL_TICK++;
	    }
	  if (SL_TICK >= 25)
	    {
	      SL_TICK = 0;
	    }

	}
#endif

      /*****************************************************************************
       *
       * main loop ends here
       *
       *****************************************************************************/

    }

}
Пример #24
0
int main(int argc, char** argv)
{

	FILE* cfg_stream;
	int c,r;
	char *tmp;
	int tmp_len;
	int port;
	int proto;
	char *options;
	int ret;
	unsigned int seed;
	int rfd;

	/*init*/
	ret=-1;
	my_argc=argc; my_argv=argv;
	
	/*init pkg mallocs (before parsing cfg or cmd line !)*/
	if (init_pkg_mallocs()==-1)
		goto error;

#ifdef DBG_MSG_QA
	fprintf(stderr, "WARNING: ser startup: "
		"DBG_MSG_QA enabled, ser may exit abruptly\n");
#endif



	/* process command line (get port no, cfg. file path etc) */
	opterr=0;
	options=
#ifdef STATS
	"s:"
#endif
	"f:cm:b:l:n:N:rRvdDETVhw:t:u:g:P:G:i:x:";
	
	while((c=getopt(argc,argv,options))!=-1){
		switch(c){
			case 'f':
					cfg_file=optarg;
					break;
			case 'c':
					config_check=1;
					log_stderr=1; /* force stderr logging */
					break;
			case 's':
				#ifdef STATS
					stat_file=optarg;
				#endif
					break;
			case 'm':
					shm_mem_size=strtol(optarg, &tmp, 10) * 1024 * 1024;
					if (tmp &&(*tmp)){
						fprintf(stderr, "bad shmem size number: -m %s\n",
										optarg);
						goto error;
					};
					LOG(L_INFO, "ser: shared memory: %ld bytes\n",
									shm_mem_size );
					break;

			case 'b':
					maxbuffer=strtol(optarg, &tmp, 10);
					if (tmp &&(*tmp)){
						fprintf(stderr, "bad max buffer size number: -p %s\n",
											optarg);
						goto error;
					}
					break;
			case 'l':
					if (parse_phostport(optarg, &tmp, &tmp_len,
											&port, &proto)<0){
						fprintf(stderr, "bad -l address specifier: %s\n",
										optarg);
						goto error;
					}
					tmp[tmp_len]=0; /* null terminate the host */
					/* add a new addr. to our address list */
					if (add_listen_iface(tmp, port, proto, 0)!=0){
						fprintf(stderr, "failed to add new listen address\n");
						goto error;
					}
					break;
			case 'n':
					children_no=strtol(optarg, &tmp, 10);
					if ((tmp==0) ||(*tmp)){
						fprintf(stderr, "bad process number: -n %s\n",
									optarg);
						goto error;
					}
					break;
			case 'v':
					check_via=1;
					break;
			case 'r':
					received_dns|=DO_DNS;
					break;
			case 'R':
					received_dns|=DO_REV_DNS;
			case 'd':
					debug++;
					break;
			case 'D':
					dont_fork=1;
					break;
			case 'E':
					log_stderr=1;
					break;
			case 'T':
#ifdef USE_TCP
					tcp_disable=1;
#else
					fprintf(stderr,"WARNING: tcp support not compiled in\n");
#endif
					break;
			case 'N':
#ifdef USE_TCP
					tcp_children_no=strtol(optarg, &tmp, 10);
					if ((tmp==0) ||(*tmp)){
						fprintf(stderr, "bad process number: -N %s\n",
									optarg);
						goto error;
					}
#else
					fprintf(stderr,"WARNING: tcp support not compiled in\n");
#endif
					break;
			case 'V':
					printf("version: %s\n", version);
					printf("flags: %s\n", flags );
					print_ct_constants();
					printf("%s\n",id);
					printf("%s compiled on %s with %s\n", __FILE__,
							compiled, COMPILER );
					
					exit(0);
					break;
			case 'h':
					printf("version: %s\n", version);
					printf("%s",help_msg);
					exit(0);
					break;
			case 'w':
					working_dir=optarg;
					break;
			case 't':
					chroot_dir=optarg;
					break;
			case 'u':
					user=optarg;
					break;
			case 'g':
					group=optarg;
					break;
			case 'P':
					pid_file=optarg;
					break;
		        case 'G':
				        pgid_file=optarg;
				        break;
			case 'i':
					fifo=optarg;
					break;
			case 'x':
					unixsock_name=optarg;
					break;
			case '?':
					if (isprint(optopt))
						fprintf(stderr, "Unknown option `-%c´.\n", optopt);
					else
						fprintf(stderr, 
								"Unknown option character `\\x%x´.\n",
								optopt);
					goto error;
			case ':':
					fprintf(stderr, 
								"Option `-%c´ requires an argument.\n",
								optopt);
					goto error;
			default:
					abort();
		}
	}
	
	/* fill missing arguments with the default values*/
	if (cfg_file==0) cfg_file=CFG_FILE;

	/* load config file or die */
	cfg_stream=fopen (cfg_file, "r");
	if (cfg_stream==0){
		fprintf(stderr, "ERROR: loading config file(%s): %s\n", cfg_file,
				strerror(errno));
		goto error;
	}

	/* seed the prng */
	/* try to use /dev/urandom if possible */
	seed=0;
	if ((rfd=open("/dev/urandom", O_RDONLY))!=-1){
try_again:
		if (read(rfd, (void*)&seed, sizeof(seed))==-1){
			if (errno==EINTR) goto try_again; /* interrupted by signal */
			LOG(L_WARN, "WARNING: could not read from /dev/urandom (%d)\n",
						errno);
		}
		DBG("read %u from /dev/urandom\n", seed);
			close(rfd);
	}else{
		LOG(L_WARN, "WARNING: could not open /dev/urandom (%d)\n", errno);
	}
	seed+=getpid()+time(0);
	DBG("seeding PRNG with %u\n", seed);
	srand(seed);
	DBG("test random number %u\n", rand());
	
	
	
	/* register a diagnostic FIFO command  - moved to fifo server - bogdan
	if (register_core_fifo()<0) {
		LOG(L_CRIT, "unable to register core FIFO commands\n");
		goto error;
	}*/

	/*register builtin  modules*/
	register_builtin_modules();

	yyin=cfg_stream;
	if ((yyparse()!=0)||(cfg_errors)){
		fprintf(stderr, "ERROR: bad config file (%d errors)\n", cfg_errors);
		goto error;
	}
	
	
	
	print_rl();
	
	/* fix parameters */
	if (port_no<=0) port_no=SIP_PORT;
#ifdef USE_TLS
	if (tls_port_no<=0) tls_port_no=SIPS_PORT;
#endif
	
	
	if (children_no<=0) children_no=CHILD_NO;
#ifdef USE_TCP
	if (!tcp_disable){
		if (tcp_children_no<=0) tcp_children_no=children_no;
	}
#endif
	
	if (working_dir==0) working_dir="/";
	
	/* get uid/gid */
	if (user){
		if (user2uid(&uid, &gid, user)<0){
			fprintf(stderr, "bad user name/uid number: -u %s\n", user);
			goto error;
		}
	}
	if (group){
		if (group2gid(&gid, group)<0){
				fprintf(stderr, "bad group name/gid number: -u %s\n", group);
			goto error;
		}
	}
	/* fix sock/fifo uid/gid */
	if (sock_user){
		if (user2uid(&sock_uid, 0, sock_user)<0){
			fprintf(stderr, "bad socket user name/uid number %s\n", user);
			goto error;
		}
	}
	if (sock_group){
		if (group2gid(&sock_gid, sock_group)<0){
			fprintf(stderr, "bad group name/gid number: -u %s\n", group);
			goto error;
		}
	}
	if (fix_all_socket_lists()!=0){
		fprintf(stderr,  "failed to initialize list addresses\n");
		goto error;
	}
	/* print all the listen addresses */
	printf("Listening on \n");
	print_all_socket_lists();
	printf("Aliases: \n");
	/*print_aliases();*/
	print_aliases();
	printf("\n");
	
	if (dont_fork){
		fprintf(stderr, "WARNING: no fork mode %s\n", 
				(udp_listen)?(
				(udp_listen->next)?" and more than one listen address found"
				"(will use only the the first one)":""
				):"and no udp listen address found" );
	}
	if (config_check){
		fprintf(stderr, "config file ok, exiting...\n");
		goto error;
	}


	/*init shm mallocs
	 *  this must be here 
	 *     -to allow setting shm mem size from the command line
	 *       => if shm_mem should be settable from the cfg file move
	 *       everything after
	 *     -it must be also before init_timer and init_tcp
	 *     -it must be after we know uid (so that in the SYSV sems case,
	 *        the sems will have the correct euid)
	 * --andrei */
	if (init_shm_mallocs()==-1)
		goto error;
	/*init timer, before parsing the cfg!*/
	if (init_timer()<0){
		LOG(L_CRIT, "could not initialize timer, exiting...\n");
		goto error;
	}
	
#ifdef USE_TCP
	if (!tcp_disable){
		/*init tcp*/
		if (init_tcp()<0){
			LOG(L_CRIT, "could not initialize tcp, exiting...\n");
			goto error;
		}
	}
#ifdef USE_TLS
	if (!tls_disable){
		/* init tls*/
		if (init_tls()<0){
			LOG(L_CRIT, "could not initialize tls, exiting...\n");
			goto error;
		}
	}
#endif /* USE_TLS */
#endif /* USE_TCP */
	/* init_daemon? */
	if (!dont_fork){
		if ( daemonize(argv[0]) <0 ) goto error;
	}
	if (install_sigs() != 0){
		fprintf(stderr, "ERROR: could not install the signal handlers\n");
		goto error;
	}
	
	
	/*alloc pids*/
#ifdef SHM_MEM
	pt=shm_malloc(sizeof(struct process_table)*process_count());
#else
	pt=pkg_malloc(sizeof(struct process_table)*process_count());
#endif
	if (pt==0){
		fprintf(stderr, "ERROR: out  of memory\n");
		goto error;
	}
	memset(pt, 0, sizeof(struct process_table)*process_count());

	if (disable_core_dump) set_core_dump(0, 0);
	else set_core_dump(1, shm_mem_size+PKG_MEM_POOL_SIZE+4*1024*1024);
	if (open_files_limit>0){
		if(increase_open_fds(open_files_limit)<0){ 
			fprintf(stderr, "ERROR: error could not increase file limits\n");
			goto error;
		}
	}
	
	if (init_modules() != 0) {
		fprintf(stderr, "ERROR: error while initializing modules\n");
		goto error;
	}
	/* fix routing lists */
	if ( (r=fix_rls())!=0){
		fprintf(stderr, "ERROR: error %d while trying to fix configuration\n",
						r);
		goto error;
	};

#ifdef STATS
	if (init_stats(  dont_fork ? 1 : children_no  )==-1) goto error;
#endif
	
	ret=main_loop();
	/*kill everything*/
	kill_all_children(SIGTERM);
	/*clean-up*/
	cleanup(0);
	return ret;

error:
	/*kill everything*/
	kill_all_children(SIGTERM);
	/*clean-up*/
	cleanup(0);
	return -1;

}
Пример #25
0
static void usage(int rc)
{
	struct mod_action mod;
	FILE *fp = rc ? stderr : stdout;

	version(fp);
	fprintf(fp,
"Copyright (C) 2000-2013, Parallels, Inc.\n"
"This program may be distributed under the terms of the GNU GPL License.\n"
"\n"
"Usage: vzctl [options] <command> <ctid> [parameters]\n"
"\n"
"vzctl create <ctid> [--ostemplate <name>] [--config <name>]\n"
"   [--layout ploop|simfs] [--hostname <name>] [--name <name>] [--ipadd <addr>]\n"
"   [--diskspace <kbytes>] [--private <path>] [--root <path>]\n"
"   [--local_uid <UID>] [--local_gid <GID>]\n"
"vzctl start <ctid> [--force] [--wait] [--skip-fsck]\n"
"vzctl destroy | mount | umount | stop | restart | status <ctid>\n"
#ifdef HAVE_PLOOP
"vzctl convert <ctid> [--layout ploop[:mode]]\n"
"vzctl compact <ctid>\n"
"vzctl snapshot <ctid> [--id <uuid>] [--name <name>] [--description <desc>]\n"
"   [--skip-suspend]\n"
"vzctl snapshot-switch | snapshot-delete <ctid> --id <uuid>\n"
"vzctl snapshot-mount <ctid> --id <uuid> --target <dir>\n"
"vzctl snapshot-umount <ctid> --id <uuid>\n"
"vzctl snapshot-list <ctid> [-H] [-o field[,field...]] [--id <uuid>]\n"
#endif
"vzctl quotaon | quotaoff | quotainit <ctid>\n"
"vzctl console <ctid> [ttyno]\n"
"vzctl enter <ctid> [--exec <command> [arg ...]]\n"
"vzctl exec | exec2 <ctid> <command> [arg ...]\n"
"vzctl runscript <ctid> <script>\n"
"vzctl suspend | resume <ctid> [--dumpfile <name>]\n"
"vzctl set <ctid> [--save] [--force] [--setmode restart|ignore]\n"
"   [--ram <bytes>[KMG]] [--swap <bytes>[KMG]]\n"
"   [--ipadd <addr>] [--ipdel <addr>|all] [--hostname <name>]\n"
"   [--nameserver <addr>] [--searchdomain <name>]\n"
"   [--onboot yes|no] [--bootorder <N>]\n"
"   [--userpasswd <user>:<passwd>]\n"
"   [--cpuunits <N>] [--cpulimit <N>] [--cpus <N>] [--cpumask <cpus>]\n"
"   [--diskspace <soft>[:<hard>]] [--diskinodes <soft>[:<hard>]]\n"
"   [--quotatime <N>] [--quotaugidlimit <N>] [--mount_opts <opt>[,<opt>...]]\n"
"   [--capability <name>:on|off ...]\n"
"   [--devices b|c:major:minor|all:r|w|rw]\n"
"   [--devnodes device:r|w|rw|none]\n"
"   [--netif_add <ifname[,mac,host_ifname,host_mac,bridge]]>]\n"
"   [--netif_del <ifname>]\n"
"   [--applyconfig <name>] [--applyconfig_map <name>]\n"
"   [--features <name:on|off>] [--name <vename>]\n"
"   [--ioprio <N>] [--iolimit <N>] --iopslimit <N>\n"
"   [--pci_add [<domain>:]<bus>:<slot>.<func>] [--pci_del <d:b:s.f>]\n"
"   [--iptables <name>] [--disabled <yes|no>]\n"
"   [--stop-timeout <seconds>\n"
"   [UBC parameters]\n"
"\n"
"UBC parameters (N - items, P - pages, B - bytes):\n"
"Two numbers divided by colon means barrier:limit.\n"
"In case the limit is not given it is set to the same value as the barrier.\n"
"   --numproc N[:N]	--numtcpsock N[:N]	--numothersock N[:N]\n"
"   --vmguarpages P[:P]	--kmemsize B[:B]	--tcpsndbuf B[:B]\n"
"   --tcprcvbuf B[:B]	--othersockbuf B[:B]	--dgramrcvbuf B[:B]\n"
"   --oomguarpages P[:P]	--lockedpages P[:P]	--privvmpages P[:P]\n"
"   --shmpages P[:P]	--numfile N[:N]		--numflock N[:N]\n"
"   --numpty N[:N]	--numsiginfo N[:N]	--dcachesize N[:N]\n"
"   --numiptent N[:N]	--physpages P[:P]	--avnumproc N[:N]\n"
"   --swappages P[:P]\n"
);
	memset(&mod, 0, sizeof(mod));
	set_log_level(0);
	init_modules(&mod, NULL);
	mod_print_usage(&mod);
	free_modules(&mod);
	exit(rc);
}
Пример #26
0
int main(int argc, char *argv[], char *envp[])
{
	act_t action = -1;
	int verbose = 0;
	int verbose_custom = 0;
	int quiet = 0;
	int veid, ret, skiplock = 0;
	char buf[256];
	vps_param *gparam = NULL, *vps_p = NULL, *cmd_p = NULL;
	const char *action_nm;
	struct sigaction act;
	char *name = NULL, *opt;

	_proc_title = argv[0];
	_proc_title_len = envp[0] - argv[0];

	gparam = init_vps_param();
	vps_p = init_vps_param();
	cmd_p = init_vps_param();

	sigemptyset(&act.sa_mask);
	act.sa_handler = SIG_IGN;
	act.sa_flags = 0;
	sigaction(SIGPIPE, &act, NULL);

	while (argc > 1) {
		opt = argv[1];

		if (!strcmp(opt, "--verbose")) {
			verbose++;
			verbose_custom = 1;
		} else if (!strcmp(opt, "--quiet"))
			quiet = 1;
		else if (!strcmp(opt, "--version")) {
			version(stdout);
			exit(0);
		} else if (!strcmp(opt, "--skiplock"))
			skiplock = YES;
		else
			break;
		argc--; argv++;
	}
	if (argc <= 1)
		usage(VZ_INVALID_PARAMETER_SYNTAX);
	action_nm = argv[1];
	init_log(NULL, 0, 1, verbose, quiet, NULL);
	if (!strcmp(argv[1], "set")) {
		init_modules(&g_action, "set");
		action = ACTION_SET;
	} else if (!strcmp(argv[1], "create")) {
		init_modules(&g_action, "create");
		action = ACTION_CREATE;
	} else if (!strcmp(argv[1], "start")) {
		init_modules(&g_action, "set");
		action = ACTION_START;
	} else if (!strcmp(argv[1], "stop")) {
		init_modules(&g_action, "set");
		action = ACTION_STOP;
	} else if (!strcmp(argv[1], "restart")) {
		action = ACTION_RESTART;
	} else if (!strcmp(argv[1], "destroy") || !strcmp(argv[1], "delete")) {
		action = ACTION_DESTROY;
	} else if (!strcmp(argv[1], "mount")) {
		action = ACTION_MOUNT;
	} else if (!strcmp(argv[1], "umount")) {
		action = ACTION_UMOUNT;
	} else if (!strcmp(argv[1], "exec3")) {
		action = ACTION_EXEC3;
	} else if (!strcmp(argv[1], "exec2")) {
		action = ACTION_EXEC2;
	} else if (!strcmp(argv[1], "exec")) {
		action = ACTION_EXEC;
	} else if (!strcmp(argv[1], "runscript")) {
		action = ACTION_RUNSCRIPT;
	} else if (!strcmp(argv[1], "enter")) {
		action = ACTION_ENTER;
	} else if (!strcmp(argv[1], "console")) {
		action = ACTION_CONSOLE;
#ifdef HAVE_PLOOP
	} else if (!strcmp(argv[1], "convert")) {
		action = ACTION_CONVERT;
	} else if (!strcmp(argv[1], "compact")) {
		action = ACTION_COMPACT;
#endif
	} else if (!strcmp(argv[1], "status")) {
		action = ACTION_STATUS;
		quiet = 1;
	} else if (!strcmp(argv[1], "suspend") || !strcmp(argv[1], "chkpnt")) {
		action = ACTION_SUSPEND;
	} else if (!strcmp(argv[1], "resume") || !strcmp(argv[1], "restore")) {
		action = ACTION_RESUME;
	} else if (!strcmp(argv[1], "quotaon")) {
		action = ACTION_QUOTAON;
	} else if (!strcmp(argv[1], "quotaoff")) {
		action = ACTION_QUOTAOFF;
	} else if (!strcmp(argv[1], "quotainit")) {
		action = ACTION_QUOTAINIT;
#ifdef HAVE_PLOOP
	} else if (!strcmp(argv[1], "snapshot")) {
		action = ACTION_SNAPSHOT_CREATE;
	} else if (!strcmp(argv[1], "snapshot-switch")) {
		action = ACTION_SNAPSHOT_SWITCH;
	} else if (!strcmp(argv[1], "snapshot-delete")) {
		action = ACTION_SNAPSHOT_DELETE;
	} else if (!strcmp(argv[1], "snapshot-list")) {
		action = ACTION_SNAPSHOT_LIST;
	} else if (!strcmp(argv[1], "snapshot-mount")) {
		action = ACTION_SNAPSHOT_MOUNT;
	} else if (!strcmp(argv[1], "snapshot-umount")) {
		action = ACTION_SNAPSHOT_UMOUNT;
#endif
	} else if (!strcmp(argv[1], "--help")) {
		usage(0);
	} else {
		init_modules(&g_action, action_nm);
		action = ACTION_CUSTOM;
		if (!g_action.mod_count) {
			fprintf(stderr, "Bad command: %s\n", argv[1]);
			ret = VZ_INVALID_PARAMETER_SYNTAX;
			goto error;
		}
	}
	if (argc < 3) {
		fprintf(stderr, "CT ID missing\n");
		ret = VZ_INVALID_PARAMETER_VALUE;
		goto error;
	}
	if (parse_int(argv[2], &veid)) {
		name = strdup(argv[2]);
		veid = get_veid_by_name(name);
	}
	if (veid < 0 || veid > VEID_MAX) {
		fprintf(stderr, "Bad CT ID %s\n", argv[2]);
		ret = VZ_INVALID_PARAMETER_VALUE;
		goto error;
	}

	argc -= 2; argv += 2;
	/* getopt_long() prints argv[0] when reporting errors */
	argv[0] = _proc_title;

	/* Read global config file */
	if (vps_parse_config(veid, GLOBAL_CFG, gparam, &g_action)) {
		ret = VZ_NOCONFIG;
		goto error;
	}
	init_log(gparam->log.log_file, veid, gparam->log.enable != NO,
		gparam->log.level, quiet, "vzctl");
	/* Set verbose level from global config if not overwriten
	   by --verbose
	*/
	if (!verbose_custom && gparam->log.verbose != NULL) {
		verbose = *gparam->log.verbose;
		verbose_custom = 1;
	}
	if (verbose < -1)
		verbose = -1;
	if (verbose_custom)
		set_log_verbose(verbose);
	if ((ret = parse_action_opt(veid, action, argc, argv, cmd_p,
		action_nm)))
	{
		goto error;
	}
	if (veid == 0 && action != ACTION_SET) {
		fprintf(stderr, "Only set actions are allowed for CT0\n");
		ret = VZ_INVALID_PARAMETER_VALUE;
		goto error;
	} else if (veid < 0) {
		fprintf(stderr, "Bad CT ID %d\n", veid);
		ret = VZ_INVALID_PARAMETER_VALUE;
		goto error;
	}
	get_vps_conf_path(veid, buf, sizeof(buf));
	if (stat_file(buf) == 1) {
		if (vps_parse_config(veid, buf, vps_p, &g_action)) {
			ret = VZ_NOCONFIG;
			goto error;
		}
		if (name != NULL &&
		    vps_p->res.name.name != NULL &&
		    strcmp(name, vps_p->res.name.name))
		{
			logger(-1, 0, "Unable to find container by name %s",
					name);
			ret = VZ_INVALID_PARAMETER_VALUE;
			goto error;
		}
	} else if (action != ACTION_CREATE &&
			action != ACTION_STATUS &&
			action != ACTION_SET)
	{
		logger(-1, 0, "Container config file does not exist");
		ret = VZ_NOVECONFIG;
		goto error;
	}
	merge_vps_param(gparam, vps_p);
	merge_global_param(cmd_p, gparam);
	ret = run_action(veid, action, gparam, vps_p, cmd_p, argc, argv,
		skiplock);

error:
	free_modules(&g_action);
	free_vps_param(gparam);
	free_vps_param(vps_p);
	free_vps_param(cmd_p);
	free_log();
	free(name);

	return ret;
}
Пример #27
0
asmlinkage void __init start_kernel(void)
{
	char * command_line;

#ifdef __SMP__
	static int boot_cpu = 1;
	/* "current" has been set up, we need to load it now */
	if (!boot_cpu)
		initialize_secondary();
	boot_cpu = 0;
#endif

/*
 * Interrupts are still disabled. Do necessary setups, then
 * enable them
 */
	printk(linux_banner);
	setup_arch(&command_line, &memory_start, &memory_end);
	memory_start = paging_init(memory_start,memory_end);
	trap_init();
	init_IRQ();
	sched_init();
	time_init();
	parse_options(command_line);

	/*
	 * HACK ALERT! This is early. We're enabling the console before
	 * we've done PCI setups etc, and console_init() must be aware of
	 * this. But we do want output early, in case something goes wrong.
	 */
	memory_start = console_init(memory_start,memory_end);
#ifdef CONFIG_MODULES
	init_modules();
#endif
	if (prof_shift) {
		prof_buffer = (unsigned int *) memory_start;
		/* only text is profiled */
		prof_len = (unsigned long) &_etext - (unsigned long) &_stext;
		prof_len >>= prof_shift;
		memory_start += prof_len * sizeof(unsigned int);
		memset(prof_buffer, 0, prof_len * sizeof(unsigned int));
	}

#ifdef CONFIG_REMOTE_DEBUG
	set_debug_traps();
	/* breakpoint(); */	/* execute a BREAK insn */
#endif
	memory_start = kmem_cache_init(memory_start, memory_end);
	sti();
	calibrate_delay();
#ifdef CONFIG_CPU_R5900
	r5900_init();
#endif
#ifdef CONFIG_BLK_DEV_INITRD
	if (initrd_start && !initrd_below_start_ok && initrd_start < memory_start) {
		printk(KERN_CRIT "initrd overwritten (0x%08lx < 0x%08lx) - "
		    "disabling it.\n",initrd_start,memory_start);
		initrd_start = 0;
	}
#endif
#ifdef CONFIG_BINFMT_IRIX
	init_inventory ();
#endif
	mem_init(memory_start,memory_end);
	kmem_cache_sizes_init();
#ifdef CONFIG_PROC_FS
	proc_root_init();
#endif
	uidcache_init();
	filescache_init();
	dcache_init();
	vma_init();
	buffer_init();
	signals_init();
	inode_init();
	file_table_init();
#if defined(CONFIG_SYSVIPC)
	ipc_init();
#endif
#if defined(CONFIG_QUOTA)
	dquot_init_hash();
#endif
	check_bugs();
	printk("POSIX conformance testing by UNIFIX\n");

	/* 
	 *	We count on the initial thread going ok 
	 *	Like idlers init is an unlocked kernel thread, which will
	 *	make syscalls (and thus be locked).
	 */
	smp_init();
	kernel_thread(init, NULL, CLONE_FS | CLONE_FILES | CLONE_SIGHAND);
	current->need_resched = 1;
 	cpu_idle(NULL);
}
Пример #28
0
asmlinkage void start_kernel(void)
{
	char * command_line;

/*
 *	This little check will move.
 */

#ifdef __SMP__
	static int first_cpu=1;
	
	if(!first_cpu)
		start_secondary();
	first_cpu=0;
	
#endif	
/*
 * Interrupts are still disabled. Do necessary setups, then
 * enable them
 */
	setup_arch(&command_line, &memory_start, &memory_end);
	memory_start = paging_init(memory_start,memory_end);
	trap_init();
#ifndef	CONFIG_OSFMACH3
	init_IRQ();
#endif	/* CONFIG_OSFMACH3 */
	sched_init();
	time_init();
	parse_options(command_line);
#ifdef CONFIG_MODULES
	init_modules();
#endif
#ifdef CONFIG_PROFILE
	if (!prof_shift)
#ifdef CONFIG_PROFILE_SHIFT
		prof_shift = CONFIG_PROFILE_SHIFT;
#else
		prof_shift = 2;
#endif
#endif
	if (prof_shift) {
		prof_buffer = (unsigned int *) memory_start;
		/* only text is profiled */
		prof_len = (unsigned long) &_etext - (unsigned long) &_stext;
		prof_len >>= prof_shift;
		memory_start += prof_len * sizeof(unsigned int);
		memset(prof_buffer, 0, prof_len * sizeof(unsigned int));
	}
	memory_start = console_init(memory_start,memory_end);
#ifdef CONFIG_PCI
	memory_start = pci_init(memory_start,memory_end);
#endif
	memory_start = kmalloc_init(memory_start,memory_end);
	sti();
	calibrate_delay();
	memory_start = inode_init(memory_start,memory_end);
	memory_start = file_table_init(memory_start,memory_end);
	memory_start = name_cache_init(memory_start,memory_end);
#ifndef	CONFIG_OSFMACH3
#ifdef CONFIG_BLK_DEV_INITRD
	if (initrd_start && initrd_start < memory_start) {
		printk(KERN_CRIT "initrd overwritten (0x%08lx < 0x%08lx) - "
		    "disabling it.\n",initrd_start,memory_start);
		initrd_start = 0;
	}
#endif
#endif	/* CONFIG_OSFMACH3 */
	mem_init(memory_start,memory_end);
	buffer_init();
	sock_init();
#if defined(CONFIG_SYSVIPC) || defined(CONFIG_KERNELD)
	ipc_init();
#endif
	dquot_init();
	arch_syms_export();
	sti();
	check_bugs();

	printk(linux_banner);
#ifdef __SMP__
	smp_init();
#endif
	sysctl_init();
	/* 
	 *	We count on the initial thread going ok 
	 *	Like idlers init is an unlocked kernel thread, which will
	 *	make syscalls (and thus be locked).
	 */
#ifdef	CONFIG_OSFMACH3
	osfmach3_start_init(argv_init, envp_init);
#else	/* CONFIG_OSFMACH3 */
	kernel_thread(init, NULL, 0);
#endif	/* CONFIG_OSFMACH3 */
/*
 * task[0] is meant to be used as an "idle" task: it may not sleep, but
 * it might do some general things like count free pages or it could be
 * used to implement a reasonable LRU algorithm for the paging routines:
 * anything that can be useful, but shouldn't take time from the real
 * processes.
 *
 * Right now task[0] just does a infinite idle loop.
 */
 	cpu_idle(NULL);
}
Пример #29
0
int main(int argc, char *argv[]) {

    int ret = 0;

#ifndef RUN_STANDALONE
    openlog("xcpmd", 0, LOG_DAEMON);
    daemonize();
#endif

    xcpmd_log(LOG_INFO, "Starting XenClient power management daemon.\n");

    //Initialize libevent library
    event_init();

    //Initialize xenstore.
    if (xenstore_init() == -1) {
        xcpmd_log(LOG_ERR, "Unable to init xenstore\n");
        return -1;
    }

    // Allow everyone to read from /pm/ in xenstore
    xenstore_rm("/pm");
    xenstore_mkdir("/pm");
    xenstore_chmod("r0", 1, "/pm");

    initialize_platform_info();


    xcpmd_log(LOG_INFO, "Starting DBUS server.\n");
    if (xcpmd_dbus_initialize() == -1) {
        xcpmd_log(LOG_ERR, "Failed to initialize DBUS server\n");
        goto xcpmd_err;
    }

    xcpmd_log(LOG_INFO, "Starting ACPI events monitor.\n");
    if (acpi_events_initialize() == -1) {
        xcpmd_log(LOG_ERR, "Failed to initialize ACPI events monitor\n");
        goto xcpmd_err;
    }

    // Load modules
    xcpmd_log(LOG_INFO, "Loading modules.\n");
    if (init_modules() == -1) {
        xcpmd_log(LOG_ERR, "Failed to load all modules\n");
        goto xcpmd_err;
    }

    //This relies on both acpi-events and acpi-module having been initialized
    xcpmd_log(LOG_INFO, "Initializing ACPI state.\n");
    acpi_initialize_state();

    // Load policy
    xcpmd_log(LOG_INFO, "Loading policy.\n");
    if (load_policy_from_db() == -1) {
        xcpmd_log(LOG_WARNING, "Error loading policy from DB; continuing...\n");
    }

#ifdef POLICY_FILE_PATH
    if (load_policy_from_file(POLICY_FILE_PATH) == -1) {
        xcpmd_log(LOG_WARNING, "Error loading policy from file %s; continuing...\n", POLICY_FILE_PATH);
    }
#endif

#ifdef XCPMD_DEBUG
    xcpmd_log(LOG_DEBUG, "Rules loaded:\n");
    print_rules();
#endif

    xcpmd_log(LOG_INFO, "Entering event loop.\n");
    event_dispatch();

    goto xcpmd_out;

xcpmd_err:
    ret = -1;
xcpmd_out:
    uninit_modules();
    acpi_events_cleanup();
    xcpmd_dbus_cleanup();
#ifndef RUN_STANDALONE
    closelog();
#endif

    return ret;
}
Пример #30
0
static int mod_init(void)
{
    char *dname_src, *bname_src;

    int i;
    PyObject *sys_path, *pDir, *pModule, *pFunc, *pArgs;
    PyThreadState *mainThreadState;

    if (script_name.len == 0) {
        script_name.len = strlen(script_name.s);
    }
    if (mod_init_fname.len == 0) {
        mod_init_fname.len = strlen(mod_init_fname.s);
    }
    if (child_init_mname.len == 0) {
        child_init_mname.len = strlen(child_init_mname.s);
    }

    dname_src = as_asciiz(&script_name);
    bname_src = as_asciiz(&script_name);

    if(dname_src==NULL || bname_src==NULL)
    {
        LM_ERR("no more pkg memory\n");
        return -1;
    }

    dname = strdup(dirname(dname_src));
    if (strlen(dname) == 0)
        dname = ".";
    bname = strdup(basename(bname_src));
    i = strlen(bname);
    if (bname[i - 1] == 'c' || bname[i - 1] == 'o')
        i -= 1;
    if (bname[i - 3] == '.' && bname[i - 2] == 'p' && bname[i - 1] == 'y') {
        bname[i - 3] = '\0';
    } else {
        LM_ERR("%s: script_name doesn't look like a python script\n",
          script_name.s);
        return -1;
    }

    Py_Initialize();
    PyEval_InitThreads();
    mainThreadState = PyThreadState_Get();

    format_exc_obj = InitTracebackModule();

    if (format_exc_obj == NULL || !PyCallable_Check(format_exc_obj))
    {
        Py_XDECREF(format_exc_obj);
        PyEval_ReleaseLock();
        return -1;
    }

    sys_path = PySys_GetObject("path");
    /* PySys_GetObject doesn't pass reference! No need to DEREF */
    if (sys_path == NULL) {
	if (!PyErr_Occurred())
	    PyErr_Format(PyExc_AttributeError, "'module' object 'sys' has no attribute 'path'");
	python_handle_exception("mod_init");
	Py_DECREF(format_exc_obj);
        PyEval_ReleaseLock();
        return -1;
    }

    pDir = PyString_FromString(dname);
    if (pDir == NULL) {
	if (!PyErr_Occurred())
	    PyErr_Format(PyExc_AttributeError, "PyString_FromString() has failed");
	python_handle_exception("mod_init");
	Py_DECREF(format_exc_obj);
        PyEval_ReleaseLock();
        return -1;
    }

    PyList_Insert(sys_path, 0, pDir);
    Py_DECREF(pDir);

    if (init_modules() != 0) {
	if (!PyErr_Occurred())
	    PyErr_SetString(PyExc_AttributeError, "init_modules() has failed");
	python_handle_exception("mod_init");
	Py_DECREF(format_exc_obj);
        PyEval_ReleaseLock();
        return -1;
    }

    if (python_msgobj_init() != 0) {
	if (!PyErr_Occurred())
	    PyErr_SetString(PyExc_AttributeError, "python_msgobj_init() has failed");
	python_handle_exception("mod_init");
	Py_DECREF(format_exc_obj);
        PyEval_ReleaseLock();
        return -1;
    }

    pModule = PyImport_ImportModule(bname);
    if (pModule == NULL) {
	if (!PyErr_Occurred())
	    PyErr_Format(PyExc_ImportError, "No module named '%s'", bname);
	python_handle_exception("mod_init");
	Py_DECREF(format_exc_obj);
        PyEval_ReleaseLock();
        return -1;
    }

    pkg_free(dname_src);
    pkg_free(bname_src);

    pFunc = PyObject_GetAttrString(pModule, mod_init_fname.s);
    Py_DECREF(pModule);

    /* pFunc is a new reference */

    if (pFunc == NULL) {
	if (!PyErr_Occurred())
	    PyErr_Format(PyExc_AttributeError, "'module' object '%s' has no attribute '%s'",  bname, mod_init_fname.s);
	python_handle_exception("mod_init");
	Py_DECREF(format_exc_obj);
        Py_XDECREF(pFunc);
        PyEval_ReleaseLock();
        return -1;
    }

    if (!PyCallable_Check(pFunc)) {
	if (!PyErr_Occurred())
	    PyErr_Format(PyExc_AttributeError, "module object '%s' has is not callable attribute '%s'", bname, mod_init_fname.s);
	python_handle_exception("mod_init");
	Py_DECREF(format_exc_obj);
        Py_XDECREF(pFunc);
        PyEval_ReleaseLock();
        return -1;
    }


    pArgs = PyTuple_New(0);
    if (pArgs == NULL) {
	python_handle_exception("mod_init");
        Py_DECREF(format_exc_obj);
        Py_DECREF(pFunc);
        PyEval_ReleaseLock();
        return -1;
    }

    handler_obj = PyObject_CallObject(pFunc, pArgs);

    Py_XDECREF(pFunc);
    Py_XDECREF(pArgs);

    if (handler_obj == Py_None) {
	if (!PyErr_Occurred())
	    PyErr_Format(PyExc_TypeError, "Function '%s' of module '%s' has returned None. Should be a class instance.", mod_init_fname.s, bname);
	python_handle_exception("mod_init");
        Py_DECREF(format_exc_obj);
        PyEval_ReleaseLock();
        return -1;
    }

    if (PyErr_Occurred()) {
        python_handle_exception("mod_init");
        Py_XDECREF(handler_obj);
        Py_DECREF(format_exc_obj);
        PyEval_ReleaseLock();
        return -1;
    }

    if (handler_obj == NULL) {
        LM_ERR("PyObject_CallObject() returned NULL but no exception!\n");
	if (!PyErr_Occurred())
	    PyErr_Format(PyExc_TypeError, "Function '%s' of module '%s' has returned not returned object. Should be a class instance.", mod_init_fname.s, bname);
	python_handle_exception("mod_init");
        Py_DECREF(format_exc_obj);
        PyEval_ReleaseLock();
        return -1;
    }

    myThreadState = PyThreadState_New(mainThreadState->interp);
    PyEval_ReleaseLock();

    return 0;
}