Ejemplo n.º 1
0
static int daemonize (void)
{
	struct rlimit rl;

	pid_t pid = 0;
	int   i   = 0;

	if (0 != chdir ("/")) {
		fprintf (stderr, "Error: chdir() failed: %s\n", strerror (errno));
		return -1;
	}

	if (0 != getrlimit (RLIMIT_NOFILE, &rl)) {
		fprintf (stderr, "Error: getrlimit() failed: %s\n", strerror (errno));
		return -1;
	}

	if (0 > (pid = fork ())) {
		fprintf (stderr, "Error: fork() failed: %s\n", strerror (errno));
		return -1;
	}
	else if (pid != 0) {
		exit (0);
	}

	if (0 != pidfile_create ())
		return -1;

	setsid ();

	if (RLIM_INFINITY == rl.rlim_max)
		rl.rlim_max = 1024;

	for (i = 0; i < (int)rl.rlim_max; ++i)
		close (i);

	errno = 0;
	if (open ("/dev/null", O_RDWR) != 0) {
		syslog (LOG_ERR, "Error: couldn't connect STDIN to /dev/null: %s",
				strerror (errno));
		return -1;
	}

	errno = 0;
	if (dup (0) != 1) {
		syslog (LOG_ERR, "Error: couldn't connect STDOUT to /dev/null: %s",
				strerror (errno));
		return -1;
	}

	errno = 0;
	if (dup (0) != 2) {
		syslog (LOG_ERR, "Error: couldn't connect STDERR to /dev/null: %s",
				strerror (errno));
		return -1;
	}
	return 0;
} /* daemonize */
Ejemplo n.º 2
0
Archivo: main.c Proyecto: CoiLock/uhub
int main(int argc, char** argv)
{
	int ret = 0;

	parse_command_line(argc, argv);

	if (arg_check_config)
	{
		return check_configuration(arg_dump_config);
	}

#ifndef WIN32
	if (arg_fork)
	{
		ret = fork();
		if (ret == -1)
		{
			LOG_FATAL("Unable to fork to background!");
			return -1;
		}
		else if (ret == 0)
		{
			/* child process - detatch from TTY */
			fclose(stdin);
			fclose(stdout);
			fclose(stderr);
			close(0);
			close(1);
			close(2);
		}
		else
		{
			/* parent process */
			LOG_DEBUG("Forked to background\n");
			return 0;
		}
	}

	if (pidfile_create() == -1)
		return -1;

	if (drop_privileges() == -1)
		return -1;
#endif /* WIN32 */

	ret = main_loop();

#ifndef WIN32
	pidfile_destroy();
#endif

	return ret;
}
Ejemplo n.º 3
0
void pidfile_init( const char *pidfile ) {

	if( pidfile_exists( pidfile ) == 1 ) {

		pss_fatal( "Daemon already running (pidfile %s exists)!\n", pidfile == NULL ? DEFAULT_PIDFILE : pidfile );

	} else {

		pidfile_create( pidfile );

	}

}
Ejemplo n.º 4
0
int main(int argc, char **argv)
{
	int ret = 0;

	deamonize();
	ret = pidfile_create("/var/run/test.pid", 0);
	printf("ret = %d\n", ret);

	printf("press Enter to exit.pid = %d\n", getpid());
	while(1)
	{
		sleep(10);
	}

	return 0;
}
Ejemplo n.º 5
0
int main( int argc, char *argv[] )
{
  int c;
  int option_index = 0;
  int received;
  int mq_id;
  struct sIPCMsg mymsg;

  char *ttydev = DEFAULT_TTY;
  char *parity_s = DEFAULT_PAR;
  int parity;
  int baud = DEFAULT_BAUD;
  USHORT result[255] = {0,};
  int result_int = 0;

  USHORT usLen;
  eMBErrorCode err = MB_ENOERR;

  int reg_start = DEFAULT_REGISTER_START;
  int address = DEFAULT_ADDRESS;
  int regt = -1;
  int reg_action = -1;
  int reg_action_param = -1;
  int no_reg = -1;
  int run_forground = 0;
  int errorcount = 0;
  struct pidfile *pidfile = NULL;

  UCHAR *pucFrame;
  eMBException    eException;
  UCHAR ucFuncType;

  /* Parse cmd-line options */
  while ( (c = getopt_long (argc, argv, "hVd:s:p:r:t:c:a:f", long_options, &option_index)) != EOF ) {    
    switch (c) {
      case 'h':
        fprintf(stderr, "%s", helptext);
        exit(EXIT_SUCCESS);
      case 'V':
        exit(EXIT_SUCCESS);
      case 'd':
        ttydev = strndup(optarg, MAXLEN);
        break;
      case 's':
        baud = atoi(optarg);
        break; 
      case 'p':
        parity_s = strndup(optarg, MAXLEN);
        break;
      case 'f': // run in forground
	run_forground = 1;
	break;
      case '?':
        /* getopt_long already printed an error message. */
      default:
        fprintf(stderr, "%s", helptext);
        exit(EXIT_SUCCESS);
    }
  }

  if(!run_forground){
      fprintf(stderr, "Deamonizing...\n");
      daemon(0, 0);
  }


  /* Setup signalhandler so that we shut down 
     nicely on CTRL+C */
  signal(SIGINT, int_handler);
  
  pidfile = pidfile_create(DEFAULT_PIDFILE, PMODE_RETURN, 0);

  mq_id = create_ipc();


  /* Allocate space for an ADU frame */
  pucFrame = eMBAllocateFrame(&usLen);

  while(outer_loop) {

    if(running == 1) 
      printf("Restarting modbus layer\n");   
    else {
      printf("\n\n\n\n Restarting modbus layer\n\n\n\n");
      running = 1;
      errorcount = 0;
    }

    /* Parse user inputs... */
    if(strcmp(parity_s, "even") == 0)
      parity = MB_PAR_EVEN;
    else if(strcmp(parity_s, "odd") == 0)
      parity = MB_PAR_ODD;
    else
      parity = MB_PAR_NONE;

    PRINT_DBG(1, "init modbus at tty: %s parity %d baud %d", ttydev, parity, baud);

    /* mode, port, baud, parity */
    eMBMasterInit(MB_RTU, ttydev, baud, parity);

    while(running) {

      /* Check message queue */
      if((received = msgrcv(mq_id, &mymsg, sizeof(mymsg.text), 1, IPC_NOWAIT)) > 0) {

        /* Address */
        address = parse_address(mymsg.text);
        /* Starting register */
        reg_start = parse_reg_start(mymsg.text);
        /* Register type */
        regt = parse_reg_type(mymsg.text);
        /* Register action */
        reg_action_param = 0;
        reg_action = parse_reg_action(mymsg.text, &reg_action_param);
        /* Optional: number of registers */
        no_reg = parse_no_reg(mymsg.text);


#ifdef DBG
	if(dbglev>=1){
	    printf("Got: %s\n", mymsg.text);
	    printf("Parsing command:\n");
	    printf("Address: 0x%02x\n", address);
	    printf("Register: %d\n", reg_start);
	    printf("Register type: %d\n", regt);
	    printf("Register action: %d  Arg: %d\n", reg_action, reg_action_param);
	    printf("Register count: %d\n", no_reg);
	}
#endif

        switch(regt) {
          case MB_TYPE_COILS:
            switch(reg_action) {
              case ACTION_READ:
                err = build_eMBMasterReadCoils (pucFrame, reg_start, reg_action_param, &usLen);
                break;
              case ACTION_WRITE:
                err = build_eMBMasterWriteCoils (pucFrame, reg_start, reg_action_param ? 0xff : 0x0, &usLen);
                break;
              case ACTION_WRITEMULTIPLE:
                err = build_eMBMasterWriteMultipleCoils (pucFrame, reg_start, no_reg, reg_action_param ? 0xff : 0x0, &usLen);
                break;
            }
            break;
          case MB_TYPE_INPUT:
            err = build_eMBMasterReadInput (pucFrame, reg_start, reg_action_param, &usLen);
            break;
          case MB_TYPE_HOLDING:
            switch(reg_action) {
              case ACTION_READ:
                err = build_eMBMasterReadHolding (pucFrame, reg_start, reg_action_param, &usLen);
                break;
              case ACTION_WRITE:
                err = build_eMBMasterWriteSingleHolding (pucFrame, reg_start, reg_action_param, &usLen);
                break;
            }
            break;
        }
     
#ifdef DBG
        if(dbglev){
          int n;
          printf("Dumping built frame:\n");
          for(n=0; n<10; n++)
            printf("%02x ",pucFrame[n]);
          printf("\n");            
        }
#endif
      
        /* ? */
        eMBEnable();

        memset(result, 0, sizeof(result));

        if(err == MB_EX_NONE) {
          /* Set the address of the device in question */
          eMBSetSlaveAddress(address);

          /* Send the frame */
          if( (err = eMBSendFrame(pucFrame, usLen)) == MB_ENOERR) {
            printf(" ---- done processing frame ----\n");
            eException = MB_EX_ILLEGAL_FUNCTION;
            ucFuncType = pucFrame[MB_PDU_FUNC_OFF];      

#ifdef DBG
	    if(dbglev){
            printf("%s():%d - after send...\n", __FUNCTION__, __LINE__);
            {
              int n;
              printf("Dumping received frame:\n");
              for(n=0; n<10; n++)
                printf("%02x ",pucFrame[n]);
              printf("\n");            
            }
	    }
#endif
          

            if(ucFuncType & 0x80) {
              UCHAR ucExceptType = pucFrame[MB_PDU_FUNC_OFF+1];
              /* We encountered some sort of error */
              switch(ucExceptType) {
                case MB_EX_ILLEGAL_FUNCTION:
                  fprintf(stderr, "Error! Illegal function!\n");
                  break;
                case MB_EX_ILLEGAL_DATA_ADDRESS:
                  fprintf(stderr, "Error! Illegal data address!\n");
                  break;
                case MB_EX_ILLEGAL_DATA_VALUE:
                  fprintf(stderr, "Error! Illegal data value!\n");
                  break;
                case MB_EX_SLAVE_DEVICE_FAILURE:
                  fprintf(stderr, "Error! Slave device failure!\n");
                  break;
                default:
                  fprintf(stderr, "Unknown error (%d)!\n", eException);
                  break;
              }
            } else {
              switch(ucFuncType) {
                case MB_FUNC_READ_COILS:
                  eException = parse_eMBMasterReadCoils(pucFrame, &usLen, (void *)result);
#ifdef DBG
                  if(dbglev)
		      printf("Reply: %04x\n", result[0]);
#endif
                  break;
                case MB_FUNC_WRITE_SINGLE_COIL:
                  eException = parse_eMBMasterWriteCoils(pucFrame, &usLen, (void *)result);
#ifdef DBG
		  if(dbglev)
		      printf("Reply: %04x\n", result[0]);
#endif
                  break;
                case MB_FUNC_READ_INPUT_REGISTER:
                  eException = parse_eMBMasterReadInput(pucFrame, &usLen, (void *)result);
#ifdef DBG
		  if(dbglev)
		      printf("Reply (%d): %04x\n", eException, result[0]);
#endif
                  break;
                case MB_FUNC_READ_HOLDING_REGISTER:
                  eException = parse_eMBMasterReadHolding(pucFrame, &usLen, (void *)result);
		  
		 
		  
#ifdef DBG
                  printf("Reply: %04x %04x %d %d\n", result[0],result[1], result_int, reg_action_param);
#endif
                  break;
                case MB_FUNC_WRITE_REGISTER:
                  eException = parse_eMBMasterWriteSingleHolding(pucFrame, &usLen, (void *)result);
#ifdef DBG
                  printf("Reply: %04x\n", result[0]);
#endif
                  break;
                case MB_FUNC_WRITE_MULTIPLE_COILS:
                  usLen = 5;
                  eException =  parse_eMBMasterWriteMultipleCoils(pucFrame, &usLen, (void *)result);
                  if(eException == MB_EX_NONE)
                    printf("Write multiple coils SUCCESS!\n");
                  else
                    printf("Write multiple coils FAIL!\n");
                  break;
                default:
                  printf("Unknown function type : %x\n", ucFuncType);
                  printf("%d : %s()\n", __LINE__, __FUNCTION__);
                  {
                    int n;
                    for(n=0; n<10; n++)
                      printf("%02x ",pucFrame[n]);
                    printf("\n");            
                  }
                  break;
              }
	      switch(ucFuncType) {
		case MB_FUNC_READ_HOLDING_REGISTER:
		case MB_FUNC_READ_INPUT_REGISTER:
		   if(reg_action_param == 2){
		      printf("!!!!\n");
		      result_int = (result[0]<<16) | result[1];
		  }else {
		      result_int = result[0];
		  }
		  break;
		default:
		  result_int = result[0];
		  break;
	      }
              if(eException == MB_EX_NONE) {
		  snprintf(mymsg.text, sizeof(mymsg.text), "%ld:REG:%d:RESULT:%d",  time(NULL), reg_start, result_int);
              } else {
                snprintf(mymsg.text, sizeof(mymsg.text), "ERROR:Parsing frame");
              }
#ifdef DBG
              printf("%s():%d - reply: %s\n",
                     __FUNCTION__, __LINE__, mymsg.text);
#endif
              goto out;

            }
          } else {
            printf("Error sending frame. (%d)\n", err);
            snprintf(mymsg.text, sizeof(mymsg.text), "ERROR:Sending frame");
            if(errorcount > 10)
              running = 0;
            else
              errorcount++;
          }
        } else {
          printf("Error in frame arguments.\n");
          snprintf(mymsg.text, sizeof(mymsg.text), "ERROR:Wrong argument");
        }
      out:
        /* Set the reply */
        mymsg.type = 2;
#ifdef DBG
        printf("%s():%d - reply: %s\n",
               __FUNCTION__, __LINE__, mymsg.text);
#endif
        msgsnd(mq_id, &mymsg, sizeof(mymsg.text), IPC_NOWAIT);

        eMBDisable();
      } else {
        //printf("No messages. Sleeping (%d - %s)\n", received, received < 0 ? strerror(errno) :  "");
      } 
      usleep(1000);
    }
    //    free(pucFrame);
    eMBClose();
  }

  destroy_ipc(PROJ_ID);

  pidfile_delete(pidfile);

  return 0;
}
Ejemplo n.º 6
0
 int main(int argc,const char *argv[])
{
	/* shall I run as a daemon */
	bool is_daemon = false;
	bool interactive = false;
	bool Fork = true;
	bool no_process_group = false;
	bool log_stdout = false;
	char *ports = NULL;
	char *profile_level = NULL;
	int opt;
	poptContext pc;
	bool print_build_options = False;
        enum {
		OPT_DAEMON = 1000,
		OPT_INTERACTIVE,
		OPT_FORK,
		OPT_NO_PROCESS_GROUP,
		OPT_LOG_STDOUT
	};
	struct poptOption long_options[] = {
	POPT_AUTOHELP
	{"daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
	{"interactive", 'i', POPT_ARG_NONE, NULL, OPT_INTERACTIVE, "Run interactive (not a daemon)"},
	{"foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Run daemon in foreground (for daemontools, etc.)" },
	{"no-process-group", '\0', POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
	{"log-stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
	{"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
	{"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
	{"profiling-level", 'P', POPT_ARG_STRING, &profile_level, 0, "Set profiling level","PROFILE_LEVEL"},
	POPT_COMMON_SAMBA
	POPT_COMMON_DYNCONFIG
	POPT_TABLEEND
	};
	struct smbd_parent_context *parent = NULL;
	TALLOC_CTX *frame;
	NTSTATUS status;
	uint64_t unique_id;
	struct tevent_context *ev_ctx;
	struct messaging_context *msg_ctx;

	/*
	 * Do this before any other talloc operation
	 */
	talloc_enable_null_tracking();
	frame = talloc_stackframe();

	setup_logging(argv[0], DEBUG_DEFAULT_STDOUT);

	load_case_tables();

	smbd_init_globals();

	TimeInit();

#ifdef HAVE_SET_AUTH_PARAMETERS
	set_auth_parameters(argc,argv);
#endif

	pc = poptGetContext("smbd", argc, argv, long_options, 0);
	while((opt = poptGetNextOpt(pc)) != -1) {
		switch (opt)  {
		case OPT_DAEMON:
			is_daemon = true;
			break;
		case OPT_INTERACTIVE:
			interactive = true;
			break;
		case OPT_FORK:
			Fork = false;
			break;
		case OPT_NO_PROCESS_GROUP:
			no_process_group = true;
			break;
		case OPT_LOG_STDOUT:
			log_stdout = true;
			break;
		case 'b':
			print_build_options = True;
			break;
		default:
			d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
				  poptBadOption(pc, 0), poptStrerror(opt));
			poptPrintUsage(pc, stderr, 0);
			exit(1);
		}
	}
	poptFreeContext(pc);

	if (interactive) {
		Fork = False;
		log_stdout = True;
	}

	if (log_stdout) {
		setup_logging(argv[0], DEBUG_STDOUT);
	} else {
		setup_logging(argv[0], DEBUG_FILE);
	}

	if (print_build_options) {
		build_options(True); /* Display output to screen as well as debug */
		exit(0);
	}

#ifdef HAVE_SETLUID
	/* needed for SecureWare on SCO */
	setluid(0);
#endif

	set_remote_machine_name("smbd", False);

	if (interactive && (DEBUGLEVEL >= 9)) {
		talloc_enable_leak_report();
	}

	if (log_stdout && Fork) {
		DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
		exit(1);
	}

	/* we want to re-seed early to prevent time delays causing
           client problems at a later date. (tridge) */
	generate_random_buffer(NULL, 0);

	/* get initial effective uid and gid */
	sec_init();

	/* make absolutely sure we run as root - to handle cases where people
	   are crazy enough to have it setuid */
	gain_root_privilege();
	gain_root_group_privilege();

	fault_setup();
	dump_core_setup("smbd", lp_logfile());

	/* we are never interested in SIGPIPE */
	BlockSignals(True,SIGPIPE);

#if defined(SIGFPE)
	/* we are never interested in SIGFPE */
	BlockSignals(True,SIGFPE);
#endif

#if defined(SIGUSR2)
	/* We are no longer interested in USR2 */
	BlockSignals(True,SIGUSR2);
#endif

	/* POSIX demands that signals are inherited. If the invoking process has
	 * these signals masked, we will have problems, as we won't recieve them. */
	BlockSignals(False, SIGHUP);
	BlockSignals(False, SIGUSR1);
	BlockSignals(False, SIGTERM);

	/* Ensure we leave no zombies until we
	 * correctly set up child handling below. */

	CatchChild();

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

	reopen_logs();

	DEBUG(0,("smbd version %s started.\n", samba_version_string()));
	DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));

	DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
		 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));

	/* Output the build options to the debug log */ 
	build_options(False);

	if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
		DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
		exit(1);
	}

	if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
		DEBUG(0, ("error opening config file '%s'\n", get_dyn_CONFIGFILE()));
		exit(1);
	}

	/* Init the security context and global current_user */
	init_sec_ctx();

	/*
	 * Initialize the event context. The event context needs to be
	 * initialized before the messaging context, cause the messaging
	 * context holds an event context.
	 * FIXME: This should be s3_tevent_context_init()
	 */
	ev_ctx = server_event_context();
	if (ev_ctx == NULL) {
		exit(1);
	}

	/*
	 * Init the messaging context
	 * FIXME: This should only call messaging_init()
	 */
	msg_ctx = server_messaging_context();
	if (msg_ctx == NULL) {
		exit(1);
	}

	/*
	 * Reloading of the printers will not work here as we don't have a
	 * server info and rpc services set up. It will be called later.
	 */
	if (!reload_services(NULL, -1, False)) {
		exit(1);
	}

	/* ...NOTE... Log files are working from this point! */

	DEBUG(3,("loaded services\n"));

	init_structs();

#ifdef WITH_PROFILE
	if (!profile_setup(msg_ctx, False)) {
		DEBUG(0,("ERROR: failed to setup profiling\n"));
		return -1;
	}
	if (profile_level != NULL) {
		int pl = atoi(profile_level);
		struct server_id src;

		DEBUG(1, ("setting profiling level: %s\n",profile_level));
		src.pid = getpid();
		set_profile_level(pl, src);
	}
#endif

	if (!is_daemon && !is_a_socket(0)) {
		if (!interactive)
			DEBUG(0,("standard input is not a socket, assuming -D option\n"));

		/*
		 * Setting is_daemon here prevents us from eventually calling
		 * the open_sockets_inetd()
		 */

		is_daemon = True;
	}

	if (is_daemon && !interactive) {
		DEBUG( 3, ( "Becoming a daemon.\n" ) );
		become_daemon(Fork, no_process_group, log_stdout);
	}

        generate_random_buffer((uint8_t *)&unique_id, sizeof(unique_id));
        set_my_unique_id(unique_id);

#if HAVE_SETPGID
	/*
	 * If we're interactive we want to set our own process group for
	 * signal management.
	 */
	if (interactive && !no_process_group)
		setpgid( (pid_t)0, (pid_t)0);
#endif

	if (!directory_exist(lp_lockdir()))
		mkdir(lp_lockdir(), 0755);

	if (is_daemon)
		pidfile_create("smbd");

	status = reinit_after_fork(msg_ctx,
				   ev_ctx,
				   procid_self(), false);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(0,("reinit_after_fork() failed\n"));
		exit(1);
	}

	smbd_server_conn->msg_ctx = msg_ctx;

	smbd_setup_sig_term_handler();
	smbd_setup_sig_hup_handler(ev_ctx,
				   msg_ctx);

	/* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */

	if (smbd_memcache() == NULL) {
		exit(1);
	}

	memcache_set_global(smbd_memcache());

	/* Initialise the password backed before the global_sam_sid
	   to ensure that we fetch from ldap before we make a domain sid up */

	if(!initialize_password_db(false, ev_ctx))
		exit(1);

	if (!secrets_init()) {
		DEBUG(0, ("ERROR: smbd can not open secrets.tdb\n"));
		exit(1);
	}

	if (lp_server_role() == ROLE_DOMAIN_BDC || lp_server_role() == ROLE_DOMAIN_PDC) {
		struct loadparm_context *lp_ctx = loadparm_init_s3(NULL, loadparm_s3_context());
		if (!open_schannel_session_store(NULL, lp_ctx)) {
			DEBUG(0,("ERROR: Samba cannot open schannel store for secured NETLOGON operations.\n"));
			exit(1);
		}
		TALLOC_FREE(lp_ctx);
	}

	if(!get_global_sam_sid()) {
		DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
		exit(1);
	}

	if (!sessionid_init()) {
		exit(1);
	}

	if (!connections_init(True))
		exit(1);

	if (!locking_init())
		exit(1);

	if (!messaging_tdb_parent_init(ev_ctx)) {
		exit(1);
	}

	if (!notify_internal_parent_init(ev_ctx)) {
		exit(1);
	}

	if (!serverid_parent_init(ev_ctx)) {
		exit(1);
	}

	if (!W_ERROR_IS_OK(registry_init_full()))
		exit(1);

	/* Open the share_info.tdb here, so we don't have to open
	   after the fork on every single connection.  This is a small
	   performance improvment and reduces the total number of system
	   fds used. */
	if (!share_info_db_init()) {
		DEBUG(0,("ERROR: failed to load share info db.\n"));
		exit(1);
	}

	status = init_system_info();
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, ("ERROR: failed to setup system user info: %s.\n",
			  nt_errstr(status)));
		return -1;
	}

	if (!init_guest_info()) {
		DEBUG(0,("ERROR: failed to setup guest info.\n"));
		return -1;
	}

	if (!file_init(smbd_server_conn)) {
		DEBUG(0, ("ERROR: file_init failed\n"));
		return -1;
	}

	/* This MUST be done before start_epmd() because otherwise
	 * start_epmd() forks and races against dcesrv_ep_setup() to
	 * call directory_create_or_exist() */
	if (!directory_create_or_exist(lp_ncalrpc_dir(), geteuid(), 0755)) {
		DEBUG(0, ("Failed to create pipe directory %s - %s\n",
			  lp_ncalrpc_dir(), strerror(errno)));
		return -1;
	}

	if (is_daemon && !interactive) {
		if (rpc_epmapper_daemon() == RPC_DAEMON_FORK) {
			start_epmd(ev_ctx, msg_ctx);
		}
	}

	if (!dcesrv_ep_setup(ev_ctx, msg_ctx)) {
		exit(1);
	}

	/* only start other daemons if we are running as a daemon
	 * -- bad things will happen if smbd is launched via inetd
	 *  and we fork a copy of ourselves here */
	if (is_daemon && !interactive) {

		if (rpc_lsasd_daemon() == RPC_DAEMON_FORK) {
			start_lsasd(ev_ctx, msg_ctx);
		}

		if (!_lp_disable_spoolss() &&
		    (rpc_spoolss_daemon() != RPC_DAEMON_DISABLED)) {
			bool bgq = lp_parm_bool(-1, "smbd", "backgroundqueue", true);

			if (!printing_subsystem_init(ev_ctx, msg_ctx, true, bgq)) {
				exit(1);
			}
		}
	} else if (!_lp_disable_spoolss() &&
		   (rpc_spoolss_daemon() != RPC_DAEMON_DISABLED)) {
		if (!printing_subsystem_init(ev_ctx, msg_ctx, false, false)) {
			exit(1);
		}
	}

	if (!is_daemon) {
		/* inetd mode */
		TALLOC_FREE(frame);

		/* Started from inetd. fd 0 is the socket. */
		/* We will abort gracefully when the client or remote system
		   goes away */
		smbd_server_conn->sock = dup(0);

		/* close our standard file descriptors */
		if (!debug_get_output_is_stdout()) {
			close_low_fds(False); /* Don't close stderr */
		}

#ifdef HAVE_ATEXIT
		atexit(killkids);
#endif

	        /* Stop zombies */
		smbd_setup_sig_chld_handler(ev_ctx);

		smbd_process(ev_ctx, smbd_server_conn);

		exit_server_cleanly(NULL);
		return(0);
	}

	parent = talloc_zero(ev_ctx, struct smbd_parent_context);
	if (!parent) {
		exit_server("talloc(struct smbd_parent_context) failed");
	}
	parent->interactive = interactive;

	if (!open_sockets_smbd(parent, ev_ctx, msg_ctx, ports))
		exit_server("open_sockets_smbd() failed");

	/* do a printer update now that all messaging has been set up,
	 * before we allow clients to start connecting */
	printing_subsystem_update(ev_ctx, msg_ctx, false);

	TALLOC_FREE(frame);
	/* make sure we always have a valid stackframe */
	frame = talloc_stackframe();

	smbd_parent_loop(ev_ctx, parent);

	exit_server_cleanly(NULL);
	TALLOC_FREE(frame);
	return(0);
}
Ejemplo n.º 7
0
 int main(int argc, const char *argv[])
{
	static bool is_daemon;
	static bool opt_interactive;
	static bool Fork = true;
	static bool no_process_group;
	static bool log_stdout;
	poptContext pc;
	char *p_lmhosts = NULL;
	int opt;
	enum {
		OPT_DAEMON = 1000,
		OPT_INTERACTIVE,
		OPT_FORK,
		OPT_NO_PROCESS_GROUP,
		OPT_LOG_STDOUT
	};
	struct poptOption long_options[] = {
	POPT_AUTOHELP
	{"daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon(default)" },
	{"interactive", 'i', POPT_ARG_NONE, NULL, OPT_INTERACTIVE, "Run interactive (not a daemon)" },
	{"foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Run daemon in foreground (for daemontools & etc)" },
	{"no-process-group", 0, POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
	{"log-stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
	{"hosts", 'H', POPT_ARG_STRING, &p_lmhosts, 0, "Load a netbios hosts file"},
	{"port", 'p', POPT_ARG_INT, &global_nmb_port, 0, "Listen on the specified port" },
	POPT_COMMON_SAMBA
	{ NULL }
	};
	TALLOC_CTX *frame;
	NTSTATUS status;

	/*
	 * Do this before any other talloc operation
	 */
	talloc_enable_null_tracking();
	frame = talloc_stackframe();

	setup_logging(argv[0], DEBUG_DEFAULT_STDOUT);

	load_case_tables();

	global_nmb_port = NMB_PORT;

	pc = poptGetContext("nmbd", argc, argv, long_options, 0);
	while ((opt = poptGetNextOpt(pc)) != -1) {
		switch (opt) {
		case OPT_DAEMON:
			is_daemon = true;
			break;
		case OPT_INTERACTIVE:
			opt_interactive = true;
			break;
		case OPT_FORK:
			Fork = false;
			break;
		case OPT_NO_PROCESS_GROUP:
			no_process_group = true;
			break;
		case OPT_LOG_STDOUT:
			log_stdout = true;
			break;
		default:
			d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
				  poptBadOption(pc, 0), poptStrerror(opt));
			poptPrintUsage(pc, stderr, 0);
			exit(1);
		}
	};
	poptFreeContext(pc);

	global_in_nmbd = true;
	
	StartupTime = time(NULL);
	
	sys_srandom(time(NULL) ^ sys_getpid());
	
	if (!override_logfile) {
		char *lfile = NULL;
		if (asprintf(&lfile, "%s/log.nmbd", get_dyn_LOGFILEBASE()) < 0) {
			exit(1);
		}
		lp_set_logfile(lfile);
		SAFE_FREE(lfile);
	}
	
	fault_setup();
	dump_core_setup("nmbd", lp_logfile());
	
	/* POSIX demands that signals are inherited. If the invoking process has
	 * these signals masked, we will have problems, as we won't receive them. */
	BlockSignals(False, SIGHUP);
	BlockSignals(False, SIGUSR1);
	BlockSignals(False, SIGTERM);

#if defined(SIGFPE)
	/* we are never interested in SIGFPE */
	BlockSignals(True,SIGFPE);
#endif

	/* We no longer use USR2... */
#if defined(SIGUSR2)
	BlockSignals(True, SIGUSR2);
#endif

	if ( opt_interactive ) {
		Fork = False;
		log_stdout = True;
	}

	if ( log_stdout && Fork ) {
		DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
		exit(1);
	}

	if (log_stdout) {
		setup_logging(argv[0], DEBUG_STDOUT);
	} else {
		setup_logging( argv[0], DEBUG_FILE);
	}

	reopen_logs();

	DEBUG(0,("nmbd version %s started.\n", samba_version_string()));
	DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));

	if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
		DEBUG(0, ("error opening config file '%s'\n", get_dyn_CONFIGFILE()));
		exit(1);
	}

	if (nmbd_messaging_context() == NULL) {
		return 1;
	}

	if ( !reload_nmbd_services(False) )
		return(-1);

	if(!init_names())
		return -1;

	reload_nmbd_services( True );

	if (strequal(lp_workgroup(),"*")) {
		DEBUG(0,("ERROR: a workgroup name of * is no longer supported\n"));
		exit(1);
	}

	set_samba_nb_type();

	if (!is_daemon && !is_a_socket(0)) {
		DEBUG(0,("standard input is not a socket, assuming -D option\n"));
		is_daemon = True;
	}
  
	if (is_daemon && !opt_interactive) {
		DEBUG( 2, ( "Becoming a daemon.\n" ) );
		become_daemon(Fork, no_process_group, log_stdout);
	}

#if HAVE_SETPGID
	/*
	 * If we're interactive we want to set our own process group for 
	 * signal management.
	 */
	if (opt_interactive && !no_process_group)
		setpgid( (pid_t)0, (pid_t)0 );
#endif

	if (nmbd_messaging_context() == NULL) {
		return 1;
	}

#ifndef SYNC_DNS
	/* Setup the async dns. We do it here so it doesn't have all the other
		stuff initialised and thus chewing memory and sockets */
	if(lp_we_are_a_wins_server() && lp_dns_proxy()) {
		start_async_dns();
	}
#endif

	if (!directory_exist(lp_lockdir())) {
		mkdir(lp_lockdir(), 0755);
	}

	pidfile_create("nmbd");

	status = reinit_after_fork(nmbd_messaging_context(),
				   nmbd_event_context(),
				   procid_self(), false);

	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(0,("reinit_after_fork() failed\n"));
		exit(1);
	}

	if (!nmbd_setup_sig_term_handler())
		exit(1);
	if (!nmbd_setup_sig_hup_handler())
		exit(1);

	/* get broadcast messages */

	if (!serverid_register(procid_self(),
				FLAG_MSG_GENERAL |
				FLAG_MSG_NMBD |
				FLAG_MSG_DBWRAP)) {
		DEBUG(1, ("Could not register myself in serverid.tdb\n"));
		exit(1);
	}

	messaging_register(nmbd_messaging_context(), NULL,
			   MSG_FORCE_ELECTION, nmbd_message_election);
#if 0
	/* Until winsrepl is done. */
	messaging_register(nmbd_messaging_context(), NULL,
			   MSG_WINS_NEW_ENTRY, nmbd_wins_new_entry);
#endif
	messaging_register(nmbd_messaging_context(), NULL,
			   MSG_SHUTDOWN, nmbd_terminate);
	messaging_register(nmbd_messaging_context(), NULL,
			   MSG_SMB_CONF_UPDATED, msg_reload_nmbd_services);
	messaging_register(nmbd_messaging_context(), NULL,
			   MSG_SEND_PACKET, msg_nmbd_send_packet);

	TimeInit();

	DEBUG( 3, ( "Opening sockets %d\n", global_nmb_port ) );

	if ( !open_sockets( is_daemon, global_nmb_port ) ) {
		kill_async_dns_child();
		return 1;
	}

	/* Determine all the IP addresses we have. */
	load_interfaces();

	/* Create an nmbd subnet record for each of the above. */
	if( False == create_subnets() ) {
		DEBUG(0,("ERROR: Failed when creating subnet lists. Exiting.\n"));
		kill_async_dns_child();
		exit(1);
	}

	/* Load in any static local names. */ 
	if (p_lmhosts) {
		set_dyn_LMHOSTSFILE(p_lmhosts);
	}
	load_lmhosts_file(get_dyn_LMHOSTSFILE());
	DEBUG(3,("Loaded hosts file %s\n", get_dyn_LMHOSTSFILE()));

	/* If we are acting as a WINS server, initialise data structures. */
	if( !initialise_wins() ) {
		DEBUG( 0, ( "nmbd: Failed when initialising WINS server.\n" ) );
		kill_async_dns_child();
		exit(1);
	}

	/* 
	 * Register nmbd primary workgroup and nmbd names on all
	 * the broadcast subnets, and on the WINS server (if specified).
	 * Also initiate the startup of our primary workgroup (start
	 * elections if we are setup as being able to be a local
	 * master browser.
	 */

	if( False == register_my_workgroup_and_names() ) {
		DEBUG(0,("ERROR: Failed when creating my my workgroup. Exiting.\n"));
		kill_async_dns_child();
		exit(1);
	}

	if (!initialize_nmbd_proxy_logon()) {
		DEBUG(0,("ERROR: Failed setup nmbd_proxy_logon.\n"));
		kill_async_dns_child();
		exit(1);
	}

	if (!nmbd_init_packet_server()) {
		kill_async_dns_child();
                exit(1);
        }

	TALLOC_FREE(frame);
	process();

	kill_async_dns_child();
	return(0);
}
Ejemplo n.º 8
0
/**************************************************************************** **
 main program
 **************************************************************************** */
 int main(int argc, const char *argv[])
{
	pstring logfile;
	static BOOL opt_interactive;
	poptContext pc;
	static char *p_lmhosts = dyn_LMHOSTSFILE;
	static BOOL no_process_group = False;
	struct poptOption long_options[] = {
	POPT_AUTOHELP
	{"daemon", 'D', POPT_ARG_VAL, &is_daemon, True, "Become a daemon(default)" },
	{"interactive", 'i', POPT_ARG_VAL, &opt_interactive, True, "Run interactive (not a daemon)" },
	{"foreground", 'F', POPT_ARG_VAL, &Fork, False, "Run daemon in foreground (for daemontools & etc)" },
	{"no-process-group", 0, POPT_ARG_VAL, &no_process_group, True, "Don't create a new process group" },
	{"log-stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
	{"hosts", 'H', POPT_ARG_STRING, &p_lmhosts, 'H', "Load a netbios hosts file"},
	{"port", 'p', POPT_ARG_INT, &global_nmb_port, NMB_PORT, "Listen on the specified port" },
	POPT_COMMON_SAMBA
	{ NULL }
	};

	load_case_tables();

	global_nmb_port = NMB_PORT;

	pc = poptGetContext("nmbd", argc, argv, long_options, 0);
	while (poptGetNextOpt(pc) != -1) {};
	poptFreeContext(pc);

	global_in_nmbd = True;
	
	StartupTime = time(NULL);
	
	sys_srandom(time(NULL) ^ sys_getpid());
	
	if (!override_logfile) {
		slprintf(logfile, sizeof(logfile)-1, "%s/log.nmbd", dyn_LOGFILEBASE);
		lp_set_logfile(logfile);
	}
	
	fault_setup((void (*)(void *))fault_continue );
	dump_core_setup("nmbd");
	
	/* POSIX demands that signals are inherited. If the invoking process has
	 * these signals masked, we will have problems, as we won't receive them. */
	BlockSignals(False, SIGHUP);
	BlockSignals(False, SIGUSR1);
	BlockSignals(False, SIGTERM);
	
	CatchSignal( SIGHUP,  SIGNAL_CAST sig_hup );
	CatchSignal( SIGTERM, SIGNAL_CAST sig_term );
	
#if defined(SIGFPE)
	/* we are never interested in SIGFPE */
	BlockSignals(True,SIGFPE);
#endif

	/* We no longer use USR2... */
#if defined(SIGUSR2)
	BlockSignals(True, SIGUSR2);
#endif

	if ( opt_interactive ) {
		Fork = False;
		log_stdout = True;
	}

	if ( log_stdout && Fork ) {
		DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
		exit(1);
	}

	setup_logging( argv[0], log_stdout );

	reopen_logs();

	DEBUG( 0, ( "Netbios nameserver version %s started.\n", SAMBA_VERSION_STRING) );
	DEBUGADD( 0, ( "%s\n", COPYRIGHT_STARTUP_MESSAGE ) );

	if ( !reload_nmbd_services(False) )
		return(-1);

	if(!init_names())
		return -1;

	reload_nmbd_services( True );

	if (strequal(lp_workgroup(),"*")) {
		DEBUG(0,("ERROR: a workgroup name of * is no longer supported\n"));
		exit(1);
	}

	set_samba_nb_type();

	if (!is_daemon && !is_a_socket(0)) {
		DEBUG(0,("standard input is not a socket, assuming -D option\n"));
		is_daemon = True;
	}
  
	if (is_daemon && !opt_interactive) {
		DEBUG( 2, ( "Becoming a daemon.\n" ) );
		become_daemon(Fork, no_process_group);
	}

#if HAVE_SETPGID
	/*
	 * If we're interactive we want to set our own process group for 
	 * signal management.
	 */
	if (opt_interactive && !no_process_group)
		setpgid( (pid_t)0, (pid_t)0 );
#endif

#ifndef SYNC_DNS
	/* Setup the async dns. We do it here so it doesn't have all the other
		stuff initialised and thus chewing memory and sockets */
	if(lp_we_are_a_wins_server() && lp_dns_proxy()) {
		start_async_dns();
	}
#endif

	if (!directory_exist(lp_lockdir(), NULL)) {
		mkdir(lp_lockdir(), 0755);
	}

	pidfile_create("nmbd");
	message_init();
	message_register(MSG_FORCE_ELECTION, nmbd_message_election, NULL);
#if 0
	/* Until winsrepl is done. */
	message_register(MSG_WINS_NEW_ENTRY, nmbd_wins_new_entry, NULL);
#endif
	message_register(MSG_SHUTDOWN, nmbd_terminate, NULL);
	message_register(MSG_SMB_CONF_UPDATED, msg_reload_nmbd_services, NULL);
	message_register(MSG_SEND_PACKET, msg_nmbd_send_packet, NULL);

	TimeInit();

	DEBUG( 3, ( "Opening sockets %d\n", global_nmb_port ) );

	if ( !open_sockets( is_daemon, global_nmb_port ) ) {
		kill_async_dns_child();
		return 1;
	}

	/* Determine all the IP addresses we have. */
	load_interfaces();

	/* Create an nmbd subnet record for each of the above. */
	if( False == create_subnets() ) {
		DEBUG(0,("ERROR: Failed when creating subnet lists. Exiting.\n"));
		kill_async_dns_child();
		exit(1);
	}

	/* Load in any static local names. */ 
	load_lmhosts_file(p_lmhosts);
	DEBUG(3,("Loaded hosts file %s\n", p_lmhosts));

	/* If we are acting as a WINS server, initialise data structures. */
	if( !initialise_wins() ) {
		DEBUG( 0, ( "nmbd: Failed when initialising WINS server.\n" ) );
		kill_async_dns_child();
		exit(1);
	}

	/* 
	 * Register nmbd primary workgroup and nmbd names on all
	 * the broadcast subnets, and on the WINS server (if specified).
	 * Also initiate the startup of our primary workgroup (start
	 * elections if we are setup as being able to be a local
	 * master browser.
	 */

	if( False == register_my_workgroup_and_names() ) {
		DEBUG(0,("ERROR: Failed when creating my my workgroup. Exiting.\n"));
		kill_async_dns_child();
		exit(1);
	}

	/* We can only take signals in the select. */
	BlockSignals( True, SIGTERM );

	process();

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

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

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

	poptFreeContext(pc);

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

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

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

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

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

	cleanup_tmp_files(cmdline_lp_ctx);

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

	pidfile_create(lpcfg_piddir(cmdline_lp_ctx), binary_name);

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

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

	gensec_init(); /* FIXME: */

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

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

	process_model_init(cmdline_lp_ctx); 

	shared_init = load_samba_modules(NULL, "service");

	run_init_functions(static_init);
	run_init_functions(shared_init);

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

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

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

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

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

	prime_ldb_databases(event_ctx);

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

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

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

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

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

	return 0;
}
Ejemplo n.º 10
0
int main(int argc, char *argv[])
{
	char optstring[] = "i:p:dfs:vh";
	struct option longopts[] = {
		{"isns-server",		1, NULL, 'i'},
		{"isns-port",		1, NULL, 'p'},
		{"debug",		0, NULL, 'd'},
		{"foreground",		0, NULL, 'f'},
		{"configfs-iscsi-path",	1, NULL, 's'},
		{"version",		0, NULL, 'v'},
		{"help",		0, NULL, 'h'},
		{NULL,			0, NULL, 0}
        };
	int option;
	int longindex = 0;
	int ifd = -1, sfd = -1, tfd = -1;
	struct epoll_event events[EPOLL_MAX_FD];
	ssize_t nr_events;
	bool daemon = true;
	int ret = EXIT_FAILURE;
	size_t configsz;

	conffile_read();

	while ((option = getopt_long(argc, argv, optstring, longopts,
				     &longindex)) != -1) {
		switch (option) {
		case 'i':
			configsz = sizeof(config.isns_server);
			strncpy(config.isns_server, optarg, configsz);
			config.isns_server[configsz - 1] = '\0';
			break;
		case 'p':
			sscanf(optarg, "%hu", &config.isns_port);
			break;
		case 'd':
			config.log_level = LOG_DEBUG;
			daemon = false;
			break;
		case 'f':
			daemon = false;
			break;
		case 's':
			configsz = sizeof(config.configfs_iscsi_path);
			strncpy(config.configfs_iscsi_path, optarg, configsz);
			config.configfs_iscsi_path[configsz - 1] = '\0';
			break;
		case 'v':
			printf(PROGNAME " version " TARGET_ISNS_VERSION "\n");
			exit(EXIT_SUCCESS);
			break;
		case 'h':
			print_usage();
			exit(EXIT_SUCCESS);
			break;
		case ':':
		case '?':
			exit(EXIT_FAILURE);
			break;
		}
	}

	if (!configfs_iscsi_path_exists()) {
		fprintf(stderr,
			"Error: configfs is not mounted or the "
			"target and iSCSI modules are not loaded.\n");
		fprintf(stderr,
			"Error: %s missing.\n",
			config.configfs_iscsi_path);
		exit(EXIT_FAILURE);
	}

	if (daemon) {
		daemonize();
		pidfile_create();
	}

	log_init(PROGNAME, daemon, config.log_level);
	log_print(LOG_INFO, PROGNAME " version " TARGET_ISNS_VERSION " started");

	epoll_init_fds();
	if (isns_init(config.isns_server, config.isns_port) == -1) {
		log_print(LOG_ERR, "failed to initialize iSNS client");
		goto err_init;
	}

	if ((epoll_fd = epoll_create1(0)) == -1) {
		log_print(LOG_ERR, "failed to create epoll instance");
		goto err_epoll_fd;
	}

	if ((tfd = isns_registration_timer_init()) == -1) {
		log_print(LOG_ERR, "failed to create timerfd instance");
		goto err_tfd;
	}
	epoll_set_fd(EPOLL_REGISTRATION_TIMER, tfd);

	if ((ifd = configfs_inotify_init()) == -1) {
		log_print(LOG_ERR, "failed to create inotify instance");
		goto err_ifd;
	}
	epoll_set_fd(EPOLL_INOTIFY, ifd);

	if ((sfd = signal_init()) == -1) {
		log_print(LOG_ERR, "failed to create signalfd instance");
		goto err_sfd;
	}
	epoll_set_fd(EPOLL_SIGNAL, sfd);

	isns_start();
	while (true) {
		nr_events = epoll_wait(epoll_fd, events, ARRAY_SIZE(events), -1);

		for (int i = 0; i < nr_events; i++) {
			int fd = events[i].data.fd;

			if (fd == epoll_set[EPOLL_SIGNAL]) {
				if (signal_is_quit(fd))
					goto quit;
			} else if (fd == epoll_set[EPOLL_INOTIFY])
				configfs_inotify_events_handle();
			else if (fd == epoll_set[EPOLL_REGISTRATION_TIMER])
				isns_registration_refresh();
			else if (fd == epoll_set[EPOLL_ISNS])
				isns_handle();
			else if (fd == epoll_set[EPOLL_SCN_LISTEN])
				isns_scn_handle(true);
			else if (fd == epoll_set[EPOLL_SCN])
				isns_scn_handle(false);
		}
	}

quit:
	ret = EXIT_SUCCESS;
	isns_stop();
	sleep(1);
	close(sfd);
err_sfd:
	configfs_inotify_cleanup(); /* closes ifd */
err_ifd:
	close(tfd);
err_tfd:
	close(epoll_fd);
err_epoll_fd:
	isns_exit();
err_init:
	log_print(LOG_INFO, PROGNAME " stopped");
	log_close();
	if (daemon)
		pidfile_remove();

	return ret;
}
Ejemplo n.º 11
0
int main(int argc, char **argv)
{
	pstring logfile;
	static BOOL interactive = False;
	static BOOL Fork = True;
	static BOOL log_stdout = False;
	struct poptOption long_options[] = {
		POPT_AUTOHELP
		{ "stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
		{ "foreground", 'F', POPT_ARG_VAL, &Fork, False, "Daemon in foreground mode" },
		{ "interactive", 'i', POPT_ARG_NONE, NULL, 'i', "Interactive mode" },
		{ "single-daemon", 'Y', POPT_ARG_VAL, &opt_dual_daemon, False, "Single daemon mode" },
		{ "no-caching", 'n', POPT_ARG_VAL, &opt_nocache, True, "Disable caching" },
		POPT_COMMON_SAMBA
		POPT_TABLEEND
	};
	poptContext pc;
	int opt;

	/* glibc (?) likes to print "User defined signal 1" and exit if a
	   SIGUSR[12] is received before a handler is installed */

 	CatchSignal(SIGUSR1, SIG_IGN);
 	CatchSignal(SIGUSR2, SIG_IGN);

	fault_setup((void (*)(void *))fault_quit );

	/* Initialise for running in non-root mode */

	sec_init();

	set_remote_machine_name("winbindd", False);

	/* Set environment variable so we don't recursively call ourselves.
	   This may also be useful interactively. */

	setenv(WINBINDD_DONT_ENV, "1", 1);

	/* Initialise samba/rpc client stuff */

	pc = poptGetContext("winbindd", argc, (const char **)argv, long_options,
						POPT_CONTEXT_KEEP_FIRST);

	while ((opt = poptGetNextOpt(pc)) != -1) {
		switch (opt) {
			/* Don't become a daemon */
		case 'i':
			interactive = True;
			log_stdout = True;
			Fork = False;
			break;
		}
	}


	if (log_stdout && Fork) {
		printf("Can't log to stdout (-S) unless daemon is in foreground +(-F) or interactive (-i)\n");
		poptPrintUsage(pc, stderr, 0);
		exit(1);
	}

	pstr_sprintf(logfile, "%s/log.winbindd", dyn_LOGFILEBASE);
	lp_set_logfile(logfile);
	setup_logging("winbindd", log_stdout);
	reopen_logs();

	DEBUG(1, ("winbindd version %s started.\n", SAMBA_VERSION_STRING) );
	DEBUGADD( 1, ( "Copyright The Samba Team 2000-2004\n" ) );

	if (!reload_services_file()) {
		DEBUG(0, ("error opening config file\n"));
		exit(1);
	}

	/* Setup names. */

	if (!init_names())
		exit(1);

  	load_interfaces();

	if (!secrets_init()) {

		DEBUG(0,("Could not initialize domain trust account secrets. Giving up\n"));
		return False;
	}

	/* Enable netbios namecache */

	namecache_enable();

	/* Check winbindd parameters are valid */

	ZERO_STRUCT(server_state);

	/* Winbind daemon initialisation */

	if ( (!winbindd_param_init()) || (!winbindd_upgrade_idmap()) ||
	     (!idmap_init(lp_idmap_backend())) ) {
		DEBUG(1, ("Could not init idmap -- netlogon proxy only\n"));
		idmap_proxyonly();
	}

	generate_wellknown_sids();

	/* Unblock all signals we are interested in as they may have been
	   blocked by the parent process. */

	BlockSignals(False, SIGINT);
	BlockSignals(False, SIGQUIT);
	BlockSignals(False, SIGTERM);
	BlockSignals(False, SIGUSR1);
	BlockSignals(False, SIGUSR2);
	BlockSignals(False, SIGHUP);
	BlockSignals(False, SIGCHLD);

	/* Setup signal handlers */
	
	CatchSignal(SIGINT, termination_handler);      /* Exit on these sigs */
	CatchSignal(SIGQUIT, termination_handler);
	CatchSignal(SIGTERM, termination_handler);
	CatchSignal(SIGCHLD, sigchld_handler);

	CatchSignal(SIGPIPE, SIG_IGN);                 /* Ignore sigpipe */

	CatchSignal(SIGUSR2, sigusr2_handler);         /* Debugging sigs */
	CatchSignal(SIGHUP, sighup_handler);

	if (!interactive)
		become_daemon(Fork);

	pidfile_create("winbindd");

#if HAVE_SETPGID
	/*
	 * If we're interactive we want to set our own process group for
	 * signal management.
	 */
	if (interactive)
		setpgid( (pid_t)0, (pid_t)0);
#endif

	if (opt_dual_daemon) {
		do_dual_daemon();
	}

	/* Initialise messaging system */

	if (!message_init()) {
		DEBUG(0, ("unable to initialise messaging system\n"));
		exit(1);
	}
	
	/* React on 'smbcontrol winbindd reload-config' in the same way
	   as to SIGHUP signal */
	message_register(MSG_SMB_CONF_UPDATED, msg_reload_services);
	message_register(MSG_SHUTDOWN, msg_shutdown);
	
	poptFreeContext(pc);

	netsamlogon_cache_init(); /* Non-critical */
	
	init_domain_list();

	/* Loop waiting for requests */

	process_loop();

	trustdom_cache_shutdown();

	return 0;
}
Ejemplo n.º 12
0
int32_t main(int32_t argc, char *argv[])
{
	fix_stacksize();
		
	run_tests();
	int32_t i, j;
	prog_name = argv[0];
	struct timespec start_ts;
	cs_gettime(&start_ts); // Initialize clock_type

	if(pthread_key_create(&getclient, NULL))
	{
		fprintf(stderr, "Could not create getclient, exiting...");
		exit(1);
	}

	void (*mod_def[])(struct s_module *) =
	{
#ifdef MODULE_MONITOR
		module_monitor,
#endif
#ifdef MODULE_CAMD33
		module_camd33,
#endif
#ifdef MODULE_CAMD35
		module_camd35,
#endif
#ifdef MODULE_CAMD35_TCP
		module_camd35_tcp,
#endif
#ifdef MODULE_NEWCAMD
		module_newcamd,
#endif
#ifdef MODULE_CCCAM
		module_cccam,
#endif
#ifdef MODULE_PANDORA
		module_pandora,
#endif
#ifdef MODULE_GHTTP
		module_ghttp,
#endif
#ifdef CS_CACHEEX
		module_csp,
#endif
#ifdef MODULE_GBOX
		module_gbox,
#endif
#ifdef MODULE_CONSTCW
		module_constcw,
#endif
#ifdef MODULE_RADEGAST
		module_radegast,
#endif
#ifdef MODULE_SCAM
		module_scam,
#endif
#ifdef MODULE_SERIAL
		module_serial,
#endif
#ifdef HAVE_DVBAPI
		module_dvbapi,
#endif
		0
	};
	
	find_conf_dir();

	parse_cmdline_params(argc, argv);

	if(bg && do_daemon(1, 0))
	{
		printf("Error starting in background (errno=%d: %s)", errno, strerror(errno));
		cs_exit(1);
	}

	get_random_bytes_init();

#ifdef WEBIF
	if(cs_restart_mode)
		{ restart_daemon(); }
#endif

	memset(&cfg, 0, sizeof(struct s_config));
	cfg.max_pending = max_pending;

	if(cs_confdir[strlen(cs_confdir) - 1] != '/') { strcat(cs_confdir, "/"); }
	init_signal_pre(); // because log could cause SIGPIPE errors, init a signal handler first
	init_first_client();
	cs_lock_create(__func__, &system_lock, "system_lock", 5000);
	cs_lock_create(__func__, &config_lock, "config_lock", 10000);
	cs_lock_create(__func__, &gethostbyname_lock, "gethostbyname_lock", 10000);
	cs_lock_create(__func__, &clientlist_lock, "clientlist_lock", 5000);
	cs_lock_create(__func__, &readerlist_lock, "readerlist_lock", 5000);
	cs_lock_create(__func__, &fakeuser_lock, "fakeuser_lock", 5000);
	cs_lock_create(__func__, &ecmcache_lock, "ecmcache_lock", 5000);
	cs_lock_create(__func__, &ecm_pushed_deleted_lock, "ecm_pushed_deleted_lock", 5000);
	cs_lock_create(__func__, &readdir_lock, "readdir_lock", 5000);
	cs_lock_create(__func__, &cwcycle_lock, "cwcycle_lock", 5000);
	init_cache();
	cacheex_init_hitcache();
	init_config();
	cs_init_log();
	init_machine_info();
	init_check();
	if(!oscam_pidfile && cfg.pidfile)
		{ oscam_pidfile = cfg.pidfile; }
	if(!oscam_pidfile)
	{
		oscam_pidfile = get_tmp_dir_filename(default_pidfile, sizeof(default_pidfile), "oscam.pid");
	}
	if(oscam_pidfile)
		{ pidfile_create(oscam_pidfile); }
	cs_init_statistics();
	coolapi_open_all();
	init_stat();
	ssl_init();

	// These initializations *MUST* be called after init_config()
	// because modules depend on config values.
	for(i = 0; mod_def[i]; i++)
	{
		struct s_module *module = &modules[i];
		mod_def[i](module);
	}

	init_sidtab();
	init_readerdb();
	cfg.account = init_userdb();
	init_signal();
	init_provid();
	init_srvid();
	init_tierid();
	init_fakecws();

	start_garbage_collector(gbdb);

	cacheex_init();

	init_len4caid();
	init_irdeto_guess_tab();

	write_versionfile(false);

	led_init();
	led_status_default();

	azbox_init();

	mca_init();

	global_whitelist_read();
	ratelimit_read();

	for(i = 0; i < CS_MAX_MOD; i++)
	{
		struct s_module *module = &modules[i];
		if((module->type & MOD_CONN_NET))
		{
			for(j = 0; j < module->ptab.nports; j++)
			{
				start_listener(module, &module->ptab.ports[j]);
			}
		}
	}

	//set time for server to now to avoid 0 in monitor/webif
	first_client->last = time((time_t *)0);

	webif_init();

	start_thread("reader check", (void *) &reader_check, NULL, NULL, 1, 1);
	cw_process_thread_start();
	checkcache_process_thread_start();

	lcd_thread_start();

	do_report_emm_support();

	init_cardreader();

	cs_waitforcardinit();
	
	emm_load_cache();
	load_emmstat_from_file();

	led_status_starting();

	ac_init();

	start_thread("card poll", (void *) &card_poll, NULL, NULL, 1, 1);

	for(i = 0; i < CS_MAX_MOD; i++)
	{
		struct s_module *module = &modules[i];
		if((module->type & MOD_CONN_SERIAL) && module->s_handler)
			{ module->s_handler(NULL, NULL, i); }
	}

	// main loop function
	process_clients();

	SAFE_COND_SIGNAL(&card_poll_sleep_cond); // Stop card_poll thread
	cw_process_thread_wakeup(); // Stop cw_process thread
	SAFE_COND_SIGNAL(&reader_check_sleep_cond); // Stop reader_check thread

	// Cleanup
#ifdef MODULE_GBOX	
	stop_sms_sender();
#endif
	webif_close();
	azbox_close();
	coolapi_close_all();
	mca_close();

	led_status_stopping();
	led_stop();
	lcd_thread_stop();

	remove_versionfile();

	stat_finish();
	dvbapi_stop_all_descrambling();
	dvbapi_save_channel_cache();
	emm_save_cache();
	save_emmstat_to_file();
	
	cccam_done_share();
	gbox_send_good_night(); 

	kill_all_clients();
	kill_all_readers();
	for(i = 0; i < CS_MAX_MOD; i++)
	{
		struct s_module *module = &modules[i];
		if((module->type & MOD_CONN_NET))
		{
			for(j = 0; j < module->ptab.nports; j++)
			{
				struct s_port *port = &module->ptab.ports[j];
				if(port->fd)
				{
					shutdown(port->fd, SHUT_RDWR);
					close(port->fd);
					port->fd = 0;
				}
			}
		}
	}

	if(oscam_pidfile)
		{ unlink(oscam_pidfile); }

	// sleep a bit, so hopefully all threads are stopped when we continue
	cs_sleepms(200);

	free_cache();
	cacheex_free_hitcache();
	webif_tpls_free();
	init_free_userdb(cfg.account);
	cfg.account = NULL;
	init_free_sidtab();
	free_readerdb();
	free_irdeto_guess_tab();
	config_free();
	ssl_done();

	detect_valgrind();
	if (!running_under_valgrind)
		cs_log("cardserver down");
	else
		cs_log("running under valgrind, waiting 5 seconds before stopping cardserver");
	log_free();

	if (running_under_valgrind) sleep(5); // HACK: Wait a bit for things to settle

	stop_garbage_collector();

	NULLFREE(first_client->account);
	NULLFREE(first_client);
	free(stb_boxtype);
	free(stb_boxname);

	// This prevents the compiler from removing config_mak from the final binary
	syslog_ident = config_mak;

	return exit_oscam;
}
Ejemplo n.º 13
0
static int daemonize(void) {
  if (chdir("/") != 0) {
    fprintf(stderr, "Error: chdir() failed: %s\n", strerror(errno));
    return -1;
  }

  struct rlimit rl;
  if (getrlimit(RLIMIT_NOFILE, &rl) != 0) {
    fprintf(stderr, "Error: getrlimit() failed: %s\n", strerror(errno));
    return -1;
  }

  pid_t pid = fork();
  if (pid < 0) {
    fprintf(stderr, "Error: fork() failed: %s\n", strerror(errno));
    return -1;
  } else if (pid != 0) {
    exit(0);
  }

  if (pidfile_create() != 0)
    return -1;

  setsid();

  if (rl.rlim_max == RLIM_INFINITY)
    rl.rlim_max = 1024;

  for (int i = 0; i < (int)rl.rlim_max; ++i)
    close(i);

  int dev_null = open("/dev/null", O_RDWR);
  if (dev_null == -1) {
    syslog(LOG_ERR, "Error: couldn't open /dev/null: %s", strerror(errno));
    return -1;
  }

  if (dup2(dev_null, STDIN_FILENO) == -1) {
    close(dev_null);
    syslog(LOG_ERR, "Error: couldn't connect STDIN to /dev/null: %s",
           strerror(errno));
    return -1;
  }

  if (dup2(dev_null, STDOUT_FILENO) == -1) {
    close(dev_null);
    syslog(LOG_ERR, "Error: couldn't connect STDOUT to /dev/null: %s",
           strerror(errno));
    return -1;
  }

  if (dup2(dev_null, STDERR_FILENO) == -1) {
    close(dev_null);
    syslog(LOG_ERR, "Error: couldn't connect STDERR to /dev/null: %s",
           strerror(errno));
    return -1;
  }

  if ((dev_null != STDIN_FILENO) && (dev_null != STDOUT_FILENO) &&
      (dev_null != STDERR_FILENO))
    close(dev_null);

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

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

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

	poptFreeContext(pc);

	talloc_enable_null_tracking();

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

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

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

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

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

	cleanup_tmp_files(cmdline_lp_ctx);

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

	pidfile_create(lpcfg_pid_directory(cmdline_lp_ctx), binary_name);

	if (lpcfg_server_role(cmdline_lp_ctx) == ROLE_ACTIVE_DIRECTORY_DC) {
		if (!open_schannel_session_store(talloc_autofree_context(), cmdline_lp_ctx)) {
			exit_daemon("Samba cannot open schannel store for secured NETLOGON operations.", EACCES);
		}
	}

	/* make sure we won't go through nss_winbind */
	if (!winbind_off()) {
		exit_daemon("Samba failed to disable recusive winbindd calls.", EACCES);
	}

	gensec_init(); /* FIXME: */

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

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

	process_model_init(cmdline_lp_ctx); 

	shared_init = load_samba_modules(NULL, "service");

	run_init_functions(static_init);
	run_init_functions(shared_init);

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

	if (event_ctx == NULL) {
		exit_daemon("Initializing event context failed", EACCES);
	}

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

	/* catch EOF on stdin */
#ifdef SIGTTIN
	signal(SIGTTIN, SIG_IGN);
#endif

	if (fstat(0, &st) != 0) {
		exit_daemon("Samba failed to set standard input handler", ENOTTY);
	}

	if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode)) {
		tevent_add_fd(event_ctx,
				event_ctx,
				0,
				stdin_event_flags,
				server_stdin_handler,
				discard_const(binary_name));
	}

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

	if (lpcfg_server_role(cmdline_lp_ctx) != ROLE_ACTIVE_DIRECTORY_DC
	    && !lpcfg_parm_bool(cmdline_lp_ctx, NULL, "server role check", "inhibit", false)
	    && !str_list_check_ci(lpcfg_server_services(cmdline_lp_ctx), "smb") 
	    && !str_list_check_ci(lpcfg_dcerpc_endpoint_servers(cmdline_lp_ctx), "remote")
	    && !str_list_check_ci(lpcfg_dcerpc_endpoint_servers(cmdline_lp_ctx), "mapiproxy")) {
		DEBUG(0, ("At this time the 'samba' binary should only be used for either:\n"));
		DEBUGADD(0, ("'server role = active directory domain controller' or to access the ntvfs file server with 'server services = +smb' or the rpc proxy with 'dcerpc endpoint servers = remote'\n"));
		DEBUGADD(0, ("You should start smbd/nmbd/winbindd instead for domain member and standalone file server tasks\n"));
		exit_daemon("Samba detected misconfigured 'server role' and exited. Check logs for details", EINVAL);
	};

	prime_ldb_databases(event_ctx);

	status = setup_parent_messaging(event_ctx, cmdline_lp_ctx);
	if (!NT_STATUS_IS_OK(status)) {
		exit_daemon("Samba failed to setup parent messaging", NT_STATUS_V(status));
	}

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

	status = server_service_startup(event_ctx, cmdline_lp_ctx, model, 
					lpcfg_server_services(cmdline_lp_ctx));
	if (!NT_STATUS_IS_OK(status)) {
		exit_daemon("Samba failed to start services", NT_STATUS_V(status));
	}

	if (opt_daemon) {
		daemon_ready("samba");
	}

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

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

	return 0;
}
Ejemplo n.º 15
0
 int main2(int argc,const char *argv[])
{
	/* shall I run as a daemon */
	static BOOL is_daemon = False;
	static BOOL interactive = False;
	static BOOL Fork = True;
	static BOOL no_process_group = False;
	static BOOL log_stdout = False;
	static char *ports = NULL;
	int opt;
#ifndef _XBOX
	poptContext pc;

	struct poptOption long_options[] = {
	POPT_AUTOHELP
	{"daemon", 'D', POPT_ARG_VAL, &is_daemon, True, "Become a daemon (default)" },
	{"interactive", 'i', POPT_ARG_VAL, &interactive, True, "Run interactive (not a daemon)"},
	{"foreground", 'F', POPT_ARG_VAL, &Fork, False, "Run daemon in foreground (for daemontools, etc.)" },
	{"no-process-group", '\0', POPT_ARG_VAL, &no_process_group, True, "Don't create a new process group" },
	{"log-stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
	{"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
	{"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
	POPT_COMMON_SAMBA
	POPT_COMMON_DYNCONFIG
	POPT_TABLEEND
	};
#else
	interactive = True;
	log_stdout = True;
#endif

	load_case_tables();

#ifdef HAVE_SET_AUTH_PARAMETERS
	set_auth_parameters(argc,argv);
#endif

#ifndef _XBOX
	pc = poptGetContext("smbd", argc, argv, long_options, 0);
	
	while((opt = poptGetNextOpt(pc)) != -1) {
		switch (opt)  {
		case 'b':
			build_options(True); /* Display output to screen as well as debug */ 
			exit(0);
			break;
		}
	}

	poptFreeContext(pc);
#endif

#ifdef HAVE_SETLUID
	/* needed for SecureWare on SCO */
	setluid(0);
#endif

	sec_init();

	set_remote_machine_name("smbd", False);

	if (interactive) {
		Fork = False;
		log_stdout = True;
	}

	if (interactive && (DEBUGLEVEL >= 9)) {
		talloc_enable_leak_report();
	}

	if (log_stdout && Fork) {
		DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
		exit(1);
	}

	setup_logging(argv[0],log_stdout);

	/* we want to re-seed early to prevent time delays causing
           client problems at a later date. (tridge) */
	generate_random_buffer(NULL, 0);

	/* make absolutely sure we run as root - to handle cases where people
	   are crazy enough to have it setuid */

	gain_root_privilege();
	gain_root_group_privilege();

#ifndef _XBOX
	fault_setup((void (*)(void *))exit_server_fault);
	dump_core_setup("smbd");
#endif

	CatchSignal(SIGTERM , SIGNAL_CAST sig_term);
#ifndef _XBOX
	CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
	
	/* we are never interested in SIGPIPE */
	BlockSignals(True,SIGPIPE);
#endif

#if defined(SIGFPE)
	/* we are never interested in SIGFPE */
	BlockSignals(True,SIGFPE);
#endif

#if defined(SIGUSR2)
	/* We are no longer interested in USR2 */
	BlockSignals(True,SIGUSR2);
#endif

	/* POSIX demands that signals are inherited. If the invoking process has
	 * these signals masked, we will have problems, as we won't recieve them. */
#ifndef _XBOX
	BlockSignals(False, SIGHUP);
#endif
	BlockSignals(False, SIGUSR1);
	BlockSignals(False, SIGTERM);

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

	init_sec_ctx();

	reopen_logs();

	DEBUG(0,( "smbd version %s started.\n", SAMBA_VERSION_STRING));
	DEBUGADD( 0, ( "%s\n", COPYRIGHT_STARTUP_MESSAGE ) );

	DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
		 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));

	/* Output the build options to the debug log */ 
	build_options(False);

	if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
		DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
		exit(1);
	}

	/*
	 * Do this before reload_services.
	 */

	if (!reload_services(False))
		return(-1);	

	init_structs();

#ifdef WITH_PROFILE
	if (!profile_setup(False)) {
		DEBUG(0,("ERROR: failed to setup profiling\n"));
		return -1;
	}
#endif

	DEBUG(3,( "loaded services\n"));

	if (!is_daemon && !is_a_socket(0)) {
		if (!interactive)
			DEBUG(0,("standard input is not a socket, assuming -D option\n"));

		/*
		 * Setting is_daemon here prevents us from eventually calling
		 * the open_sockets_inetd()
		 */

		is_daemon = True;
	}

	if (is_daemon && !interactive) {
		DEBUG( 3, ( "Becoming a daemon.\n" ) );
		become_daemon(Fork, no_process_group);
	}

#if HAVE_SETPGID
	/*
	 * If we're interactive we want to set our own process group for
	 * signal management.
	 */
	if (interactive && !no_process_group)
		setpgid( (pid_t)0, (pid_t)0);
#endif

	if (!directory_exist(lp_lockdir(), NULL))
		mkdir(lp_lockdir(), 0755);

#ifndef _XBOX
	if (is_daemon)
		pidfile_create("smbd");
#endif

	/* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */
	if (!message_init())
		exit(1);

	/* Initialize our global sam sid first -- quite a lot of the other
	 * initialization routines further down depend on it.
	 */

	/* Initialise the password backed before the global_sam_sid
	   to ensure that we fetch from ldap before we make a domain sid up */

	if(!initialize_password_db(False))
		exit(1);

	/* Fail gracefully if we can't open secrets.tdb */

	if (!secrets_init()) {
		DEBUG(0, ("ERROR: smbd can not open secrets.tdb\n"));
		exit(1);
	}

	if(!get_global_sam_sid()) {
		DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
		exit(1);
	}

	if (!session_init())
		exit(1);

	if (conn_tdb_ctx() == NULL)
		exit(1);

	if (!locking_init(0))
		exit(1);

	namecache_enable();

	if (!init_registry())
		exit(1);

#if 0
	if (!init_svcctl_db())
                exit(1);
#endif

#ifndef _XBOX
	if (!print_backend_init())
		exit(1);
#endif

	if (!init_guest_info()) {
		DEBUG(0,("ERROR: failed to setup guest info.\n"));
		return -1;
	}

	/* Setup the main smbd so that we can get messages. */
	/* don't worry about general printing messages here */

	claim_connection(NULL,"",0,True,FLAG_MSG_GENERAL|FLAG_MSG_SMBD);

	/* only start the background queue daemon if we are 
	   running as a daemon -- bad things will happen if
	   smbd is launched via inetd and we fork a copy of 
	   ourselves here */
#ifndef _XBOX
	if ( is_daemon && !interactive )
		start_background_queue(); 
#endif
	/* Always attempt to initialize DMAPI. We will only use it later if
	 * lp_dmapi_support is set on the share, but we need a single global
	 * session to work with.
	 */
	dmapi_init_session();

	if (!open_sockets_smbd(is_daemon, interactive, ports))
		exit(1);

	/*
	 * everything after this point is run after the fork()
	 */ 

	static_init_rpc;

	init_modules();

	/* possibly reload the services file. */
	reload_services(True);

	if (!init_account_policy()) {
		DEBUG(0,("Could not open account policy tdb.\n"));
		exit(1);
	}

	if (*lp_rootdir()) {
		if (sys_chroot(lp_rootdir()) == 0)
			DEBUG(2,("Changed root to %s\n", lp_rootdir()));
	}

	/* Setup oplocks */
	if (!init_oplocks())
		exit(1);
	
	/* Setup change notify */
	if (!init_change_notify())
		exit(1);

	/* Setup aio signal handler. */
	initialize_async_io_handler();

	/* re-initialise the timezone */
	TimeInit();

	/* register our message handlers */
	message_register(MSG_SMB_FORCE_TDIS, msg_force_tdis);

	smbd_process();

#ifdef _XBOX
	xb_DecClientCount();
#endif

	namecache_shutdown();

	exit_server_cleanly(NULL);
	return(0);
}
Ejemplo n.º 16
0
int32_t main (int32_t argc, char *argv[])
{
	int32_t i, j;
	prog_name = argv[0];
	if (pthread_key_create(&getclient, NULL)) {
		fprintf(stderr, "Could not create getclient, exiting...");
		exit(1);
	}

  void (*mod_def[])(struct s_module *)=
  {
#ifdef MODULE_MONITOR
           module_monitor,
#endif
#ifdef MODULE_CAMD33
           module_camd33,
#endif
#ifdef MODULE_CAMD35
           module_camd35,
#endif
#ifdef MODULE_CAMD35_TCP
           module_camd35_tcp,
#endif
#ifdef MODULE_NEWCAMD
           module_newcamd,
#endif
#ifdef MODULE_CCCAM
           module_cccam,
#endif
#ifdef MODULE_PANDORA
           module_pandora,
#endif
#ifdef MODULE_GHTTP
           module_ghttp,
#endif
#ifdef CS_CACHEEX
           module_csp,
#endif
#ifdef MODULE_GBOX
           module_gbox,
#endif
#ifdef MODULE_CONSTCW
           module_constcw,
#endif
#ifdef MODULE_RADEGAST
           module_radegast,
#endif
#ifdef MODULE_SERIAL
           module_serial,
#endif
#ifdef HAVE_DVBAPI
	   module_dvbapi,
#endif
           0
  };

  void (*cardsystem_def[])(struct s_cardsystem *)=
  {
#ifdef READER_NAGRA
	reader_nagra,
#endif
#ifdef READER_IRDETO
	reader_irdeto,
#endif
#ifdef READER_CONAX
	reader_conax,
#endif
#ifdef READER_CRYPTOWORKS
	reader_cryptoworks,
#endif
#ifdef READER_SECA
	reader_seca,
#endif
#ifdef READER_VIACCESS
	reader_viaccess,
#endif
#ifdef READER_VIDEOGUARD
	reader_videoguard1,
	reader_videoguard2,
	reader_videoguard12,
#endif
#ifdef READER_DRE
	reader_dre,
#endif
#ifdef READER_TONGFANG
	reader_tongfang,
#endif
#ifdef READER_BULCRYPT
	reader_bulcrypt,
#endif
#ifdef READER_GRIFFIN
	reader_griffin,
#endif
#ifdef READER_DGCRYPT
	reader_dgcrypt,
#endif
	0
  };

  void (*cardreader_def[])(struct s_cardreader *)=
  {
#ifdef CARDREADER_DB2COM
	cardreader_db2com,
#endif
#if defined(CARDREADER_INTERNAL_AZBOX)
	cardreader_internal_azbox,
#elif defined(CARDREADER_INTERNAL_COOLAPI)
	cardreader_internal_cool,
#elif defined(CARDREADER_INTERNAL_SCI)
	cardreader_internal_sci,
#endif
#ifdef CARDREADER_PHOENIX
	cardreader_mouse,
#endif
#ifdef CARDREADER_MP35
	cardreader_mp35,
#endif
#ifdef CARDREADER_PCSC
	cardreader_pcsc,
#endif
#ifdef CARDREADER_SC8IN1
	cardreader_sc8in1,
#endif
#ifdef CARDREADER_SMARGO
	cardreader_smargo,
#endif
#ifdef CARDREADER_SMART
	cardreader_smartreader,
#endif
#ifdef CARDREADER_STAPI
	cardreader_stapi,
#endif
	0
  };

  parse_cmdline_params(argc, argv);

  if (bg && do_daemon(1,0))
  {
    printf("Error starting in background (errno=%d: %s)", errno, strerror(errno));
    cs_exit(1);
  }

  get_random_bytes_init();

#ifdef WEBIF
  if (cs_restart_mode)
    restart_daemon();
#endif

  memset(&cfg, 0, sizeof(struct s_config));
  cfg.max_pending = max_pending;

  if (cs_confdir[strlen(cs_confdir) - 1] != '/') strcat(cs_confdir, "/");
  init_signal_pre(); // because log could cause SIGPIPE errors, init a signal handler first
  init_first_client();
  cs_lock_create(&system_lock, 5, "system_lock");
  cs_lock_create(&config_lock, 10, "config_lock");
  cs_lock_create(&gethostbyname_lock, 10, "gethostbyname_lock");
  cs_lock_create(&clientlist_lock, 5, "clientlist_lock");
  cs_lock_create(&readerlist_lock, 5, "readerlist_lock");
  cs_lock_create(&fakeuser_lock, 5, "fakeuser_lock");
  cs_lock_create(&ecmcache_lock, 5, "ecmcache_lock");
  cs_lock_create(&readdir_lock, 5, "readdir_lock");
  cs_lock_create(&cwcycle_lock, 5, "cwcycle_lock");
  cs_lock_create(&hitcache_lock, 5, "hitcache_lock");
  coolapi_open_all();
  init_config();
  cs_init_log();
  if (!oscam_pidfile && cfg.pidfile)
    oscam_pidfile = cfg.pidfile;
  if (!oscam_pidfile) {
    oscam_pidfile = get_tmp_dir_filename(default_pidfile, sizeof(default_pidfile), "oscam.pid");
  }
  if (oscam_pidfile)
    pidfile_create(oscam_pidfile);
  cs_init_statistics();
  init_check();
  init_stat();

  // These initializations *MUST* be called after init_config()
  // because modules depend on config values.
  for (i=0; mod_def[i]; i++)
  {
	struct s_module *module = &modules[i];
	mod_def[i](module);
  }
  for (i=0; cardsystem_def[i]; i++)
  {
	memset(&cardsystems[i], 0, sizeof(struct s_cardsystem));
	cardsystem_def[i](&cardsystems[i]);
  }
  for (i=0; cardreader_def[i]; i++)
  {
	memset(&cardreaders[i], 0, sizeof(struct s_cardreader));
	cardreader_def[i](&cardreaders[i]);
  }

  init_sidtab();
  init_readerdb();
  cfg.account = init_userdb();
  init_signal();
  init_srvid();
  init_tierid();
  init_provid();

  start_garbage_collector(gbdb);

  cacheex_init();

  init_len4caid();
  init_irdeto_guess_tab();

  write_versionfile(false);

  led_init();
  led_status_default();

  azbox_init();

  mca_init();

  global_whitelist_read();
  cacheex_load_config_file();

	for (i = 0; i < CS_MAX_MOD; i++) {
		struct s_module *module = &modules[i];
		if ((module->type & MOD_CONN_NET)) {
			for (j = 0; j < module->ptab.nports; j++) {
				start_listener(module, &module->ptab.ports[j]);
			}
		}
	}

	//set time for server to now to avoid 0 in monitor/webif
	first_client->last=time((time_t *)0);

	webif_init();

	start_thread((void *) &reader_check, "reader check");
	cw_process_thread_start();

	lcd_thread_start();

	do_report_emm_support();

	init_cardreader();

	cs_waitforcardinit();

	led_status_starting();

	ac_init();

	for (i = 0; i < CS_MAX_MOD; i++) {
		struct s_module *module = &modules[i];
		if ((module->type & MOD_CONN_SERIAL) && module->s_handler)
			module->s_handler(NULL, NULL, i);
	}

	// main loop function
	process_clients();

	cw_process_thread_wakeup(); // Stop cw_process thread
	pthread_cond_signal(&reader_check_sleep_cond); // Stop reader_check thread

	// Cleanup
	webif_close();
	azbox_close();
	coolapi_close_all();
	mca_close();

	led_status_stopping();
	led_stop();
	lcd_thread_stop();

	remove_versionfile();

	stat_finish();
	cccam_done_share();

	kill_all_clients();
	kill_all_readers();

	if (oscam_pidfile)
		unlink(oscam_pidfile);

	webif_tpls_free();
	init_free_userdb(cfg.account);
	cfg.account = NULL;
	init_free_sidtab();
	free_readerdb();
	free_irdeto_guess_tab();
	config_free();

	cs_log("cardserver down");
	log_free();

	stop_garbage_collector();

	free(first_client->account);
	free(first_client);

	// This prevents the compiler from removing config_mak from the final binary
	syslog_ident = config_mak;

	return exit_oscam;
}
Ejemplo n.º 17
0
/**
 * @brief openvassd.
 * @param argc Argument count.
 * @param argv Argument vector.
 */
int
main (int argc, char *argv[])
{
  int exit_early = 0, scanner_port = 9391;
  pid_t handler_pid;
  char *myself;
  struct arglist *options = emalloc (sizeof (struct arglist));
  struct addrinfo *mysaddr;
  struct addrinfo hints;
  struct addrinfo ai;
  struct sockaddr_in saddr;
  struct sockaddr_in6 s6addr;

  proctitle_init (argc, argv);
  gcrypt_init ();

  if ((myself = strrchr (*argv, '/')) == 0)
    myself = *argv;
  else
    myself++;

  static gboolean display_version = FALSE;
  static gboolean dont_fork = FALSE;
  static gchar *address = NULL;
  static gchar *port = NULL;
  static gchar *config_file = NULL;
  static gchar *gnutls_priorities = "NORMAL";
  static gchar *dh_params = NULL;
  static gboolean print_specs = FALSE;
  static gboolean print_sysconfdir = FALSE;
  static gboolean only_cache = FALSE;
  GError *error = NULL;
  GOptionContext *option_context;
  static GOptionEntry entries[] = {
    {"version", 'V', 0, G_OPTION_ARG_NONE, &display_version,
     "Display version information", NULL},
    {"foreground", 'f', 0, G_OPTION_ARG_NONE, &dont_fork,
     "Do not run in daemon mode but stay in foreground", NULL},
    {"listen", 'a', 0, G_OPTION_ARG_STRING, &address,
     "Listen on <address>", "<address>"},
    {"port", 'p', 0, G_OPTION_ARG_STRING, &port,
     "Use port number <number>", "<number>"},
    {"config-file", 'c', 0, G_OPTION_ARG_FILENAME, &config_file,
     "Configuration file", "<.rcfile>"},
    {"cfg-specs", 's', 0, G_OPTION_ARG_NONE, &print_specs,
     "Print configuration settings", NULL},
    {"sysconfdir", 'y', 0, G_OPTION_ARG_NONE, &print_sysconfdir,
     "Print system configuration directory (set at compile time)", NULL},
    {"only-cache", 'C', 0, G_OPTION_ARG_NONE, &only_cache,
     "Exit once the NVT cache has been initialized or updated", NULL},
    {"gnutls-priorities", '\0', 0, G_OPTION_ARG_STRING, &gnutls_priorities,
     "GnuTLS priorities string", "<string>"},
    {"dh-params", '\0', 0, G_OPTION_ARG_STRING, &dh_params,
     "Diffie-Hellman parameters file", "<string>"},
    {NULL}
  };

  option_context =
    g_option_context_new ("- Scanner of the Open Vulnerability Assessment System");
  g_option_context_add_main_entries (option_context, entries, NULL);
  if (!g_option_context_parse (option_context, &argc, &argv, &error))
    {
      g_print ("%s\n\n", error->message);
      exit (0);
    }
  g_option_context_free (option_context);

  if (print_sysconfdir)
    {
      g_print ("%s\n", SYSCONFDIR);
      exit (0);
    }

  /* Switch to UTC so that OTP times are always in UTC. */
  if (setenv ("TZ", "utc 0", 1) == -1)
    {
      g_print ("%s\n\n", strerror (errno));
      exit (0);
    }
  tzset ();

  if (print_specs)
    exit_early = 2;           /* no cipher initialization */

  if (address != NULL)
    {
      memset (&hints, 0, sizeof (hints));
      hints.ai_socktype = SOCK_STREAM;
      hints.ai_protocol = IPPROTO_TCP;
      hints.ai_flags = AI_NUMERICHOST;
      if (getaddrinfo (address, NULL, &hints, &mysaddr))
        {
          printf ("Invalid IP address.\n");
          printf ("Please use %s --help for more information.\n", myself);
          exit (0);
        }
      /* deep copy */
      ai.ai_family = mysaddr->ai_family;
      if (ai.ai_family == AF_INET)
        {
          memcpy (&saddr, mysaddr->ai_addr, mysaddr->ai_addrlen);
          ai.ai_addr = (struct sockaddr *) &saddr;
        }
      else
        {
          memcpy (&s6addr, mysaddr->ai_addr, mysaddr->ai_addrlen);
          ai.ai_addr = (struct sockaddr *) &s6addr;
        }
      ai.ai_family = mysaddr->ai_family;
      ai.ai_protocol = mysaddr->ai_protocol;
      ai.ai_socktype = mysaddr->ai_socktype;
      ai.ai_addrlen = mysaddr->ai_addrlen;
      freeaddrinfo (mysaddr);
    }
  else
    {
      /* Default to IPv4 */
      /*Warning: Not filling all the fields */
      saddr.sin_addr.s_addr = INADDR_ANY;
      saddr.sin_family = ai.ai_family = AF_INET;
      ai.ai_addrlen = sizeof (saddr);
      ai.ai_addr = (struct sockaddr *) &saddr;
    }

  if (port != NULL)
    {
      scanner_port = atoi (port);
      if ((scanner_port <= 0) || (scanner_port >= 65536))
        {
          printf ("Invalid port specification.\n");
          printf ("Please use %s --help for more information.\n", myself);
          exit (1);
        }
    }

  if (display_version)
    {
      printf ("OpenVAS Scanner %s\n", OPENVASSD_VERSION);
      printf
        ("Nessus origin: (C) 2004 Renaud Deraison <*****@*****.**>\n");
      printf
        ("Most new code since OpenVAS: (C) 2013 Greenbone Networks GmbH\n");
      printf ("License GPLv2: GNU GPL version 2\n");
      printf
        ("This is free software: you are free to change and redistribute it.\n"
         "There is NO WARRANTY, to the extent permitted by law.\n\n");
      exit (0);
    }

  if (config_file != NULL)
    arg_add_value (options, "acc_hint", ARG_INT, sizeof (int), (void *) 1);

  if (!config_file)
    {
      config_file = emalloc (strlen (OPENVASSD_CONF) + 1);
      strncpy (config_file, OPENVASSD_CONF, strlen (OPENVASSD_CONF));
    }

  arg_add_value (options, "scanner_port", ARG_INT, sizeof (gpointer),
                 GSIZE_TO_POINTER (scanner_port));
  arg_add_value (options, "config_file", ARG_STRING, strlen (config_file),
                 config_file);
  arg_add_value (options, "addr", ARG_PTR, -1, &ai);

  if (only_cache)
    {
      init_openvassd (options, 0, 1, dont_fork);
      init_plugins (options);
      exit (0);
    }

  init_openvassd (options, 1, exit_early, dont_fork);
  g_options = options;
  global_iana_socket = GPOINTER_TO_SIZE (arg_get_value (options, "isck"));
  global_plugins = arg_get_value (options, "plugins");

  /* special treatment */
  if (print_specs)
    dump_cfg_specs (global_preferences);
  if (exit_early)
    exit (0);

  init_ssl_ctx (gnutls_priorities, dh_params);
  // Daemon mode:
  if (dont_fork == FALSE)
    set_daemon_mode ();
  pidfile_create ("openvassd");
  handler_pid = loading_handler_start ();
  init_plugins (options);
  loading_handler_stop (handler_pid);
  main_loop ();
  exit (0);
}