Exemplo n.º 1
0
BOOL queue_dns_query(struct packet_struct *p,struct nmb_name *question)
{
	struct name_record *namerec = NULL;
	struct in_addr dns_ip;
	unstring qname;

	pull_ascii_nstring(qname, sizeof(qname), question->name);

	DEBUG(3,("DNS search for %s - ", nmb_namestr(question)));

        /* Unblock TERM signal so we can be killed in DNS lookup. */
        BlockSignals(False, SIGTERM);

	dns_ip.s_addr = interpret_addr(qname);

        /* Re-block TERM signal. */
        BlockSignals(True, SIGTERM);

	namerec = add_dns_result(question, dns_ip);
	if(namerec == NULL) {
		send_wins_name_query_response(NAM_ERR, p, NULL);
	} else {
		send_wins_name_query_response(0, p, namerec);
	}
	return False;
}
Exemplo n.º 2
0
/* see man pthread_exit(3) */
void gtthread_exit(void *retval){
	dlink_t* temp_link;
	dlink_t* temp_link2;

	BlockSignals();
	temp_link = schedule_queue->running;
	schedule_queue->running->thread_block->returnval = retval;
	temp_link->thread_block->exited = 1;

	if(schedule_queue->running != schedule_queue->begin){
		temp_link2 = FindNode(schedule_queue,schedule_queue->running->thread_block->parent_threadid);
		if(temp_link2 == NULL){
			fprintf(stderr,"gtthread_exit() error: no parent found");
		}
		else{
			temp_link2->thread_block->child_count--;
			UnblockSignals();
			raise(SIGVTALRM);
		}
	}

	else{
		temp_link->thread_block->exited = 0;
		schedule_queue->main_exited = 1;
		while(schedule_queue->running->thread_block->child_count!=0){
				UnblockSignals();
				raise(SIGVTALRM);
				BlockSignals();
		}

		//exit(*(int*)retval);
	}


	/*while(temp_link->thread_block->child_count!=0){
		UnblockSignals();
		raise(SIGVTALRM);
		BlockSignals();
	}

	if(schedule_queue->running == schedule_queue->begin){
		exit(0);
	}
	else{
		temp_link2 = FindNode(schedule_queue,schedule_queue->running->thread_block->parent_threadid);
		if(temp_link2 == NULL){
			fprintf(stderr,"Error: no parent found");
		}
		else{
			temp_link2->thread_block->child_count--;
			temp_link->thread_block->exited = 1;
			UnblockSignals();
			raise(SIGVTALRM);
		}
	}*/
}
Exemplo n.º 3
0
static void sig_hup(int sig)
{
  BlockSignals( True, SIGHUP );

  DEBUG( 0, ( "Got SIGHUP dumping debug info.\n" ) );

  write_browse_list( 0, True );

  dump_all_namelists();

  reload_after_sighup = True;

  BlockSignals(False,SIGHUP);

} /* sig_hup */
Exemplo n.º 4
0
int MyHttpd::Start(const RunOptions& options)
{
    ConfigReader cr;

    if (!LoadConfig(cr,options.configFile))
    {
        AppLog(Logger::ERROR,"MyHttpd exiting due to problem loading configuration");
        return 0;
    }

    sAppLog.SetLogLevel((options.debugLog) ? Logger::DEBUG : Logger::INFO);
    BlockSignals();

    RequestQueue &requestQueue=RequestQueue::GetInstance();
    requestQueue.AddWorker(mNrRequestWorkers);

    AddConnectionWorker(mNrConnectionWorkers);

    AllowSignals();
    signal(SIGINT,handlerInt);
    StartSites(cr);

    mKeepRunning=true;

    while (mKeepRunning)
    {
        usleep(1000);
    }

    AppLog(Logger::INFO,"MyHttpd shutting down");

    Stop();
    return 0;
}
Exemplo n.º 5
0
errno_t krb5_install_sigterm_handler(struct tevent_context *ev,
                                     struct krb5_ctx *krb5_ctx)
{
    const char *krb5_realm;
    char *sig_realm;
    struct tevent_signal *sige;

    BlockSignals(false, SIGTERM);

    krb5_realm = dp_opt_get_cstring(krb5_ctx->opts, KRB5_REALM);
    if (krb5_realm == NULL) {
        DEBUG(1, ("Missing krb5_realm option!\n"));
        return EINVAL;
    }

    sig_realm = talloc_strdup(krb5_ctx, krb5_realm);
    if (sig_realm == NULL) {
        DEBUG(1, ("talloc_strdup failed!\n"));
        return ENOMEM;
    }

    sige = tevent_add_signal(ev, krb5_ctx, SIGTERM, SA_SIGINFO, krb5_finalize,
                             sig_realm);
    if (sige == NULL) {
        DEBUG(1, ("tevent_add_signal failed.\n"));
        talloc_free(sig_realm);
        return ENOMEM;
    }
    talloc_steal(sige, sig_realm);

    return EOK;
}
Exemplo n.º 6
0
/*
  setup signal masks
*/
static void setup_signals(void)
{
    /* we are never interested in SIGPIPE */
    BlockSignals(true, SIGPIPE);

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

    /* We are no longer interested in USR1 */
    BlockSignals(true, SIGUSR1);

    /* We are no longer interested in SIGINT except for monitor */
    BlockSignals(true, SIGINT);

#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 receive them. */
    BlockSignals(false, SIGHUP);
    BlockSignals(false, SIGTERM);

#ifndef HAVE_PRCTL
        /* If prctl is not defined on the system, try to handle
         * some common termination signals gracefully */
    CatchSignal(SIGSEGV, sig_segv_abrt);
    CatchSignal(SIGABRT, sig_segv_abrt);
#endif

}
Exemplo n.º 7
0
/* see man pthread_join(3) */
int  gtthread_join(gtthread_t thread, void **status){
	gtid_t thread_id;
	dlink_t* temp_dlink;

	thread_id = thread.threadid;
	BlockSignals();
	temp_dlink = FindNode(schedule_queue,thread_id);
	if(temp_dlink == NULL){
		return -1;
	}
	else if(temp_dlink == schedule_queue->begin)
	{
		while(schedule_queue->main_exited==0){
			UnblockSignals();
			gtthread_yield();
			BlockSignals();
		}
		if(temp_dlink->thread_block->cancelled==1){
					*status = (void*)(int)-1;
		}
		else if(status!=NULL){
			*status = temp_dlink->thread_block->returnval;
		}
		UnblockSignals();
		return 0;
	}
	else{

		while(!(temp_dlink->thread_block->exited || temp_dlink->thread_block->finished|| temp_dlink->thread_block->cancelled)){
			UnblockSignals();
			gtthread_yield();
			BlockSignals();
		}
		if(temp_dlink->thread_block->cancelled==1){
			if(status!=NULL){
				*status = (void*)(int)-1;
			}
		}
		else if(status!=NULL){
			*status = temp_dlink->thread_block->returnval;
		}
		UnblockSignals();
		return 0;
	}
}
Exemplo n.º 8
0
/* see man pthread_self(3) */
gtthread_t gtthread_self(void){
	struct itimerval *timer;
	gtthread_t return_thread;

	BlockSignals();
	return_thread = *(schedule_queue->running->thread_block);
	UnblockSignals();
	return return_thread;
}
Exemplo n.º 9
0
void sync_browse_lists(struct work_record *work,
		       char *name, int nm_type, 
		       struct in_addr ip, bool local, bool servers)
{
	struct sync_record *s;
	static int counter;

	START_PROFILE(sync_browse_lists);
	/* Check we're not trying to sync with ourselves. This can
	   happen if we are a domain *and* a local master browser. */
	if (ismyip_v4(ip)) {
done:
		END_PROFILE(sync_browse_lists);
		return;
	}

	s = SMB_MALLOC_P(struct sync_record);
	if (!s) goto done;

	ZERO_STRUCTP(s);

	unstrcpy(s->workgroup, work->work_group);
	unstrcpy(s->server, name);
	s->ip = ip;

	if (asprintf(&s->fname, "%s/sync.%d", lp_lockdir(), counter++) < 0) {
		SAFE_FREE(s);
		goto done;
	}
	/* Safe to use as 0 means no size change. */
	all_string_sub(s->fname,"//", "/", 0);

	DLIST_ADD(syncs, s);

	/* the parent forks and returns, leaving the child to do the
	   actual sync and call END_PROFILE*/
	CatchChild();
	if ((s->pid = sys_fork())) return;

	BlockSignals( False, SIGTERM );

	DEBUG(2,("Initiating browse sync for %s to %s(%s)\n",
		 work->work_group, name, inet_ntoa(ip)));

	fp = x_fopen(s->fname,O_WRONLY|O_CREAT|O_TRUNC, 0644);
	if (!fp) {
		END_PROFILE(sync_browse_lists);
		_exit(1);
	}

	sync_child(name, nm_type, work->work_group, ip, local, servers,
		   s->fname);

	x_fclose(fp);
	END_PROFILE(sync_browse_lists);
	_exit(0);
}
Exemplo n.º 10
0
int  gtthread_mutex_lock(gtthread_mutex_t *mutex){
	BlockSignals();
	if(schedule_queue == NULL){
		fprintf(stderr,"\ngtthread_mutex_lock() Error: Did not initialize gtthread library with gtthread_init()\n");
		UnblockSignals();
		return -1;
	}
	else{
		while(mutex->threadid != -1){
			UnblockSignals();
			raise(SIGVTALRM);
			BlockSignals();
		}
		mutex->threadid = schedule_queue->running->thread_block->threadid;
		UnblockSignals();
		return 0;
	}
}
Exemplo n.º 11
0
static BOOL linux_oplock_receive_message(fd_set *fds, char *buffer, int buffer_len)
{
	int fd;
	struct files_struct *fsp;

	BlockSignals(True, RT_SIGNAL_LEASE);
	fd = fd_pending_array[0];
	fsp = file_find_fd(fd);
	fd_pending_array[0] = (SIG_ATOMIC_T)-1;
	if (signals_received > 1)
	memmove((void *)&fd_pending_array[0], (void *)&fd_pending_array[1],
			sizeof(SIG_ATOMIC_T)*(signals_received-1));
	signals_received--;
	/* now we can receive more signals */
	BlockSignals(False, RT_SIGNAL_LEASE);

	if (fsp == NULL) {
		DEBUG(0,("Invalid file descriptor %d in kernel oplock break!\n", (int)fd));
		return False;
	}

	DEBUG(3,("linux_oplock_receive_message: kernel oplock break request received for \
dev = %x, inode = %.0f fd = %d, fileid = %lu \n", (unsigned int)fsp->dev, (double)fsp->inode,
			fd, fsp->file_id));
     
	/*
	 * Create a kernel oplock break message.
	 */
     
	/* Setup the message header */
	SIVAL(buffer,OPBRK_CMD_LEN_OFFSET,KERNEL_OPLOCK_BREAK_MSG_LEN);
	SSVAL(buffer,OPBRK_CMD_PORT_OFFSET,0);
     
	buffer += OPBRK_CMD_HEADER_LEN;
     
	SSVAL(buffer,OPBRK_MESSAGE_CMD_OFFSET,KERNEL_OPLOCK_BREAK_CMD);
     
	memcpy(buffer + KERNEL_OPLOCK_BREAK_DEV_OFFSET, (char *)&fsp->dev, sizeof(fsp->dev));
	memcpy(buffer + KERNEL_OPLOCK_BREAK_INODE_OFFSET, (char *)&fsp->inode, sizeof(fsp->inode));	
	memcpy(buffer + KERNEL_OPLOCK_BREAK_FILEID_OFFSET, (char *)&fsp->file_id, sizeof(fsp->file_id));	

	return True;
}
Exemplo n.º 12
0
/*
  setup signal masks
*/
static void setup_signals(void)
{
	/* we are never interested in SIGPIPE */
	BlockSignals(true,SIGPIPE);

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

	/* We are no longer interested in USR1 */
	BlockSignals(true, SIGUSR1);

#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 receive them. */
	BlockSignals(false, SIGHUP);
	BlockSignals(false, SIGTERM);

	CatchSignal(SIGHUP, sig_hup);
	CatchSignal(SIGTERM, sig_term);
}
Exemplo n.º 13
0
/***************************************************************************
  we use this when we can't do async DNS lookups
  ****************************************************************************/
BOOL queue_dns_query(struct packet_struct *p,struct nmb_name *question,
		     struct name_record **n)
{
	char *qname = question->name;
	struct in_addr dns_ip;

	DEBUG(3,("DNS search for %s - ", nmb_namestr(question)));

        /* Unblock TERM signal so we can be killed in DNS lookup. */
        BlockSignals(False, SIGTERM);

	dns_ip.s_addr = interpret_addr(qname);

        /* Re-block TERM signal. */
        BlockSignals(True, SIGTERM);

	*n = add_dns_result(question, dns_ip);
        if(*n == NULL)
          send_wins_name_query_response(NAM_ERR, p, NULL);
        else
          send_wins_name_query_response(0, p, *n);
	return False;
}
Exemplo n.º 14
0
NET_API_STATUS libnetapi_net_init(struct libnetapi_ctx **context)
{
	NET_API_STATUS status;
	struct libnetapi_ctx *ctx = NULL;
	char *krb5_cc_env = NULL;

	TALLOC_CTX *frame = talloc_stackframe();

	ctx = talloc_zero(frame, struct libnetapi_ctx);
	if (!ctx) {
		TALLOC_FREE(frame);
		return W_ERROR_V(WERR_NOMEM);
	}

	BlockSignals(True, SIGPIPE);

	krb5_cc_env = getenv(KRB5_ENV_CCNAME);
	if (!krb5_cc_env || (strlen(krb5_cc_env) == 0)) {
		ctx->krb5_cc_env = talloc_strdup(ctx, "MEMORY:libnetapi");
		setenv(KRB5_ENV_CCNAME, ctx->krb5_cc_env, 1);
	}

	if (getenv("USER")) {
		ctx->username = talloc_strdup(ctx, getenv("USER"));
	} else {
		ctx->username = talloc_strdup(ctx, "");
	}
	if (!ctx->username) {
		TALLOC_FREE(frame);
		fprintf(stderr, "libnetapi_init: out of memory\n");
		return W_ERROR_V(WERR_NOMEM);
	}

	status = libnetapi_init_private_context(ctx);
	if (status != 0) {
		TALLOC_FREE(frame);
		return status;
	}

	libnetapi_initialized = true;

	talloc_steal(NULL, ctx);
	*context = stat_ctx = ctx;
	
	TALLOC_FREE(frame);
	return NET_API_STATUS_SUCCESS;
}
Exemplo n.º 15
0
void HALdisplayDriver ()
{
    do
    {
        BlockSignals ();
        if (messageFromHALos)
        {
            messageFromHALos = 0;
            GetMessageFromHALos ();
            ProcessIORequest ();
            SendMessageToHALos ();
        }
        UnblockSignals ();
    } while (1);

    return;
}
Exemplo n.º 16
0
/* see man pthread_cancel(3); but deferred cancelation does not need to be
 * implemented; all threads are canceled immediately */
int  gtthread_cancel(gtthread_t thread){
	dlink_t* temp_link;

	temp_link = FindNode(schedule_queue,thread.threadid);

	BlockSignals();

	//No thread found, return
	if(temp_link == NULL){
		UnblockSignals();
		return -1;
	}
	else if(temp_link->thread_block->cancelled == 1 || temp_link->thread_block->exited == 1 || temp_link->thread_block->finished == 1){
			UnblockSignals();
			return -1;
	}

	//Else if thread was main, exit
	else if(temp_link == schedule_queue->begin){

		if(schedule_queue->main_exited == 1){
			UnblockSignals();
			return -1;
		}
		else{
			schedule_queue->main_exited = 1;
			temp_link->thread_block->cancelled =1;
			UnblockSignals();
		}
	}
	//Else if thread was running
	else if(temp_link  == schedule_queue->running){
		temp_link->thread_block->cancelled =1;
		UnblockSignals();
		raise(SIGVTALRM);
	}
	//Else some other thread
	else{
		temp_link->thread_block->cancelled =1;
		UnblockSignals();
		return 0;
	}
	return -1;
}
Exemplo n.º 17
0
string GetCommandLine ()
{
    string commandLine;

    do
    {
        BlockSignals ();
        cout << "HALshell> ";
        getline (cin, commandLine);
        if (cullProcess)
        {
            cullProcess = 0;
            cin.clear ();
            cout << endl;
        }
        UnblockSignals ();
    } while (commandLine.length () == 0);

    return commandLine;
}
Exemplo n.º 18
0
int  gtthread_mutex_unlock(gtthread_mutex_t *mutex){
	BlockSignals();
	if(schedule_queue == NULL){
			fprintf(stderr,"\ngtthread_mutex_lock() Error: Did not initialize gtthread library with gtthread_init()\n");
			UnblockSignals();
			return -1;
	}
	else if(mutex->threadid == -1){
		UnblockSignals();
		return 0;
	}
	else if(schedule_queue->running->thread_block->threadid == mutex->threadid){
		mutex->threadid = -1;
		UnblockSignals();
		return 0;
	}
	else{
		fprintf(stderr,"\ngtthread_mutex_unlock() Error: Unlock by a different thread not permitted\n");
		return -1;
	}
}
Exemplo n.º 19
0
void WrapperFunction(void*(*start_routine)(void *), void* arg){
	void *returnval;
	dlink_t* temp_dlink;

	returnval = start_routine(arg);

	BlockSignals();
	//Need to fire a new thread
	schedule_queue->running->thread_block->finished =1;
	schedule_queue->running->thread_block->returnval = returnval;
	temp_dlink = FindNode(schedule_queue,schedule_queue->running->thread_block->parent_threadid);
	if(temp_dlink == NULL){
		fprintf(stderr,"gtthread_exit() error: no parent found");
		exit(1);
	}
	else{
		temp_dlink->thread_block->child_count--;
		UnblockSignals();
		raise(SIGVTALRM);
	}
}
Exemplo n.º 20
0
/**************************************************************************** **
  catch a sigterm
 **************************************************************************** */
static void sig_term(int sig)
{
  BlockSignals(True,SIGTERM);
  
  DEBUG(0,("Got SIGTERM: going down...\n"));
  
  /* Write out wins.dat file if samba is a WINS server */
  wins_write_database(False);
  
  /* Remove all SELF registered names. */
  release_my_names();
  
  /* Announce all server entries as 0 time-to-live, 0 type. */
  announce_my_servers_removed();

  /* If there was an async dns child - kill it. */
  kill_async_dns_child();

  exit(0);

} /* sig_term */
Exemplo n.º 21
0
/* see man pthread_create(3); the attr parameter is omitted, and this should
 * behave as if attr was NULL (i.e., default attributes) */
int  gtthread_create(gtthread_t *thread,
                     void *(*start_routine)(void *),
                     void *arg){
	struct itimerval* timer;
	gtid_t parent_id;
	dlink_t* thread_dlink;
	THREAD_COUNT++;

	//Allocate memory for a link
	thread_dlink = (dlink_t*)malloc(sizeof(dlink_t));
	if(thread_dlink == NULL){
		return -1;
	}


	//Stop Timer
	BlockSignals();
	parent_id = schedule_queue->running->thread_block->threadid;
	schedule_queue->running->thread_block->child_count++;
	UnblockSignals();

	//Initialize the link
	if(InitLink(thread_dlink,thread,THREAD_COUNT,parent_id)==-1){
		return -1;
	}

	//Make Thread Context
	if(getcontext(&(thread->thread_context))==-1){
		return -1;
	}
	thread->thread_context.uc_stack.ss_sp = (char*)malloc(sizeof(char)*20*MB);
	thread->thread_context.uc_stack.ss_size = sizeof(char)*20*MB;
	if(getcontext(thread->thread_context.uc_link)==-1){
		return -1;
	}
	makecontext(&(thread->thread_context),WrapperFunction, 2, start_routine,arg);

	//Add Link to Queue
	return(PushBack_Queue(thread_dlink,schedule_queue));
}
Exemplo n.º 22
0
void Wait ()
{
    do
    {
        BlockSignals ();
        if (cullProcess)
        {
            cullProcess = 0;
            SendCommandLine ("cull");
            cin.clear ();
            cout << endl;
        }
        else if (commandHandled)
        {
            commandHandled = 0;
            break;
        }
        UnblockSignals ();
    } while (1);

    return;
}
Exemplo n.º 23
0
static BOOL open_sockets(BOOL isdaemon, int port)
{
	/*
	 * The sockets opened here will be used to receive broadcast
	 * packets *only*. Interface specific sockets are opened in
	 * make_subnet() in namedbsubnet.c. Thus we bind to the
	 * address "0.0.0.0". The parameter 'socket address' is
	 * now deprecated.
	 */

	if ( isdaemon )
		ClientNMB = open_socket_in(SOCK_DGRAM, port,
					   0, interpret_addr(lp_socket_address()),
					   True);
	else
		ClientNMB = 0;
  
	ClientDGRAM = open_socket_in(SOCK_DGRAM, DGRAM_PORT,
					   3, interpret_addr(lp_socket_address()),
					   True);

	if ( ClientNMB == -1 )
		return( False );

#ifndef _XBOX
	/* we are never interested in SIGPIPE */
	BlockSignals(True,SIGPIPE);
#endif

	set_socket_options( ClientNMB,   "SO_BROADCAST" );
	set_socket_options( ClientDGRAM, "SO_BROADCAST" );

	/* Ensure we're non-blocking. */
	set_blocking( ClientNMB, False);
	set_blocking( ClientDGRAM, False);

	DEBUG( 3, ( "open_sockets: Broadcast sockets opened.\n" ) );
	return( True );
}
Exemplo n.º 24
0
NET_API_STATUS libnetapi_init(struct libnetapi_ctx **context)
{
	NET_API_STATUS ret;
	TALLOC_CTX *frame;
	if (stat_ctx && libnetapi_initialized) {
		*context = stat_ctx;
		return NET_API_STATUS_SUCCESS;
	}

#if 0
	talloc_enable_leak_report();
#endif
	frame = talloc_stackframe();

	/* Case tables must be loaded before any string comparisons occour */
	load_case_tables_library();

	/* When libnetapi is invoked from an application, it does not
	 * want to be swamped with level 10 debug messages, even if
	 * this has been set for the server in smb.conf */
	lp_set_cmdline("log level", "0");
	setup_logging("libnetapi", DEBUG_STDERR);

	if (!lp_load(get_dyn_CONFIGFILE(), true, false, false, true)) {
		TALLOC_FREE(frame);
		fprintf(stderr, "error loading %s\n", get_dyn_CONFIGFILE() );
		return W_ERROR_V(WERR_GENERAL_FAILURE);
	}

	init_names();
	load_interfaces();
	reopen_logs();

	BlockSignals(True, SIGPIPE);

	ret = libnetapi_net_init(context);
	TALLOC_FREE(frame);
	return ret;
}
Exemplo n.º 25
0
static bool open_sockets(bool isdaemon, int port)
{
	struct sockaddr_storage ss;
	const char *sock_addr = lp_socket_address();

	/*
	 * The sockets opened here will be used to receive broadcast
	 * packets *only*. Interface specific sockets are opened in
	 * make_subnet() in namedbsubnet.c. Thus we bind to the
	 * address "0.0.0.0". The parameter 'socket address' is
	 * now deprecated.
	 */

	if (!interpret_string_addr(&ss, sock_addr,
				AI_NUMERICHOST|AI_PASSIVE)) {
		DEBUG(0,("open_sockets: unable to get socket address "
			"from string %s", sock_addr));
		return false;
	}
	if (ss.ss_family != AF_INET) {
		DEBUG(0,("open_sockets: unable to use IPv6 socket"
			"%s in nmbd\n",
			sock_addr));
		return false;
	}

	if (isdaemon) {
		ClientNMB = open_socket_in(SOCK_DGRAM, port,
					   0, &ss,
					   true);
	} else {
		ClientNMB = 0;
	}

	if (ClientNMB == -1) {
		return false;
	}

	ClientDGRAM = open_socket_in(SOCK_DGRAM, DGRAM_PORT,
					   3, &ss,
					   true);

	if (ClientDGRAM == -1) {
		if (ClientNMB != 0) {
			close(ClientNMB);
		}
		return false;
	}

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

	set_socket_options( ClientNMB,   "SO_BROADCAST" );
	set_socket_options( ClientDGRAM, "SO_BROADCAST" );

	/* Ensure we're non-blocking. */
	set_blocking( ClientNMB, False);
	set_blocking( ClientDGRAM, False);

	DEBUG( 3, ( "open_sockets: Broadcast sockets opened.\n" ) );
	return( True );
}
Exemplo n.º 26
0
/*
  connect to a share - used when a tree_connect operation comes
  in. For a disk based backend we needs to ensure that the base
  directory exists (tho it doesn't need to be accessible by the user,
  that comes later)
*/
static NTSTATUS pvfs_connect(struct ntvfs_module_context *ntvfs,
			     struct ntvfs_request *req,
			     union smb_tcon* tcon)
{
	struct pvfs_state *pvfs;
	struct stat st;
	char *base_directory;
	NTSTATUS status;
	const char *sharename;

	switch (tcon->generic.level) {
	case RAW_TCON_TCON:
		sharename = tcon->tcon.in.service;
		break;
	case RAW_TCON_TCONX:
		sharename = tcon->tconx.in.path;
		break;
	case RAW_TCON_SMB2:
		sharename = tcon->smb2.in.path;
		break;
	default:
		return NT_STATUS_INVALID_LEVEL;
	}

	if (strncmp(sharename, "\\\\", 2) == 0) {
		char *p = strchr(sharename+2, '\\');
		if (p) {
			sharename = p + 1;
		}
	}

	/*
	 * TODO: call this from ntvfs_posix_init()
	 *       but currently we don't have a lp_ctx there
	 */
	status = pvfs_acl_init();
	NT_STATUS_NOT_OK_RETURN(status);

	pvfs = talloc_zero(ntvfs, struct pvfs_state);
	NT_STATUS_HAVE_NO_MEMORY(pvfs);

	/* for simplicity of path construction, remove any trailing slash now */
	base_directory = talloc_strdup(pvfs, share_string_option(ntvfs->ctx->config, SHARE_PATH, ""));
	NT_STATUS_HAVE_NO_MEMORY(base_directory);
	if (strcmp(base_directory, "/") != 0) {
		trim_string(base_directory, NULL, "/");
	}

	pvfs->ntvfs = ntvfs;
	pvfs->base_directory = base_directory;

	/* the directory must exist. Note that we deliberately don't
	   check that it is readable */
	if (stat(pvfs->base_directory, &st) != 0 || !S_ISDIR(st.st_mode)) {
		DEBUG(0,("pvfs_connect: '%s' is not a directory, when connecting to [%s]\n", 
			 pvfs->base_directory, sharename));
		return NT_STATUS_BAD_NETWORK_NAME;
	}

	ntvfs->ctx->fs_type = talloc_strdup(ntvfs->ctx, "NTFS");
	NT_STATUS_HAVE_NO_MEMORY(ntvfs->ctx->fs_type);

	ntvfs->ctx->dev_type = talloc_strdup(ntvfs->ctx, "A:");
	NT_STATUS_HAVE_NO_MEMORY(ntvfs->ctx->dev_type);

	if (tcon->generic.level == RAW_TCON_TCONX) {
		tcon->tconx.out.fs_type = ntvfs->ctx->fs_type;
		tcon->tconx.out.dev_type = ntvfs->ctx->dev_type;
	}

	ntvfs->private_data = pvfs;

	pvfs->brl_context = brlock_init(pvfs, 
				     pvfs->ntvfs->ctx->server_id,
				     pvfs->ntvfs->ctx->lp_ctx,
				     pvfs->ntvfs->ctx->msg_ctx);
	if (pvfs->brl_context == NULL) {
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	}

	pvfs->odb_context = odb_init(pvfs, pvfs->ntvfs->ctx);
	if (pvfs->odb_context == NULL) {
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	}

	/* allow this to be NULL - we just disable change notify */
	pvfs->notify_context = notify_init(pvfs, 
					   pvfs->ntvfs->ctx->server_id,  
					   pvfs->ntvfs->ctx->msg_ctx, 
					   pvfs->ntvfs->ctx->lp_ctx,
					   pvfs->ntvfs->ctx->event_ctx,
					   pvfs->ntvfs->ctx->config);

	pvfs->wbc_ctx = wbc_init(pvfs,
				 pvfs->ntvfs->ctx->msg_ctx,
				 pvfs->ntvfs->ctx->event_ctx);
	if (pvfs->wbc_ctx == NULL) {
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	}

	/* allocate the search handle -> ptr tree */
	pvfs->search.idtree = idr_init(pvfs);
	NT_STATUS_HAVE_NO_MEMORY(pvfs->search.idtree);

	status = pvfs_mangle_init(pvfs);
	NT_STATUS_NOT_OK_RETURN(status);

	pvfs_setup_options(pvfs);

	talloc_set_destructor(pvfs, pvfs_state_destructor);

#ifdef SIGXFSZ
	/* who had the stupid idea to generate a signal on a large
	   file write instead of just failing it!? */
	BlockSignals(true, SIGXFSZ);
#endif

	return NT_STATUS_OK;
}
Exemplo n.º 27
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);
}
Exemplo n.º 28
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);
}
Exemplo n.º 29
0
/*
 * Do some module- and library-wide intializations
 */
static void
SMBC_module_init(void * punused)
{
    bool conf_loaded = False;
    char *home = NULL;
    TALLOC_CTX *frame = talloc_stackframe();
                
    load_case_tables();
                
    setup_logging("libsmbclient", True);

    /* Here we would open the smb.conf file if needed ... */
                
    lp_set_in_client(True);
                
    home = getenv("HOME");
    if (home) {
        char *conf = NULL;
        if (asprintf(&conf, "%s/.smb/smb.conf", home) > 0) {
            if (lp_load(conf, True, False, False, True)) {
                conf_loaded = True;
            } else {
                DEBUG(5, ("Could not load config file: %s\n",
                          conf));
            }
            SAFE_FREE(conf);
        }
    }
                
    if (!conf_loaded) {
        /*
         * Well, if that failed, try the get_dyn_CONFIGFILE
         * Which points to the standard locn, and if that
         * fails, silently ignore it and use the internal
         * defaults ...
         */
                        
        if (!lp_load(get_dyn_CONFIGFILE(), True, False, False, False)) {
            DEBUG(5, ("Could not load config file: %s\n",
                      get_dyn_CONFIGFILE()));
        } else if (home) {
            char *conf;
            /*
             * We loaded the global config file.  Now lets
             * load user-specific modifications to the
             * global config.
             */
            if (asprintf(&conf,
                         "%s/.smb/smb.conf.append",
                         home) > 0) {
                if (!lp_load(conf, True, False, False, False)) {
                    DEBUG(10,
                          ("Could not append config file: "
                           "%s\n",
                           conf));
                }
                SAFE_FREE(conf);
            }
        }
    }
                
    load_interfaces();  /* Load the list of interfaces ... */
                
    reopen_logs();  /* Get logging working ... */
                
    /*
     * Block SIGPIPE (from lib/util_sock.c: write())
     * It is not needed and should not stop execution
     */
    BlockSignals(True, SIGPIPE);
                
    /* Create the mutex we'll use to protect initialized_ctx_count */
    if (SMB_THREAD_CREATE_MUTEX("initialized_ctx_count_mutex",
                                initialized_ctx_count_mutex) != 0) {
        smb_panic("SMBC_module_init: "
                  "failed to create 'initialized_ctx_count' mutex");
    }


    TALLOC_FREE(frame);
}
Exemplo n.º 30
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);
}