Example #1
0
NOEXPORT int create_pid(void) {
    int pf;
    char *pid;

    if(!global_options.pidfile) {
        s_log(LOG_DEBUG, "No pid file being created");
        return 0;
    }
    if(global_options.pidfile[0]!='/') {
        /* to prevent creating pid file relative to '/' after daemonize() */
        s_log(LOG_ERR, "Pid file (%s) must be full path name", global_options.pidfile);
        return 1;
    }
    global_options.dpid=(unsigned long)getpid();

    /* silently remove old pid file */
    unlink(global_options.pidfile);
    pf=open(global_options.pidfile, O_WRONLY|O_CREAT|O_TRUNC|O_EXCL, 0644);
    if(pf==-1) {
        s_log(LOG_ERR, "Cannot create pid file %s", global_options.pidfile);
        ioerror("create");
        return 1;
    }
    pid=str_printf("%lu\n", global_options.dpid);
    if(write(pf, pid, strlen(pid))<(int)strlen(pid)) {
        s_log(LOG_ERR, "Cannot write pid file %s", global_options.pidfile);
        ioerror("write");
        return 1;
    }
    str_free(pid);
    close(pf);
    s_log(LOG_DEBUG, "Created pid file %s", global_options.pidfile);
    atexit(delete_pid);
    return 0;
}
Example #2
0
NOEXPORT int daemonize(int fd) { /* go to background */
    if(global_options.option.foreground)
        return 0;
    dup2(fd, 0);
    dup2(fd, 1);
    dup2(fd, 2);
#if defined(HAVE_DAEMON) && !defined(__BEOS__)
    /* set noclose option when calling daemon() function,
     * so it does not require /dev/null device in the chrooted directory */
    if(daemon(0, 1)==-1) {
        ioerror("daemon");
        return 1;
    }
#else
    chdir("/");
    switch(fork()) {
    case -1:    /* fork failed */
        ioerror("fork");
        return 1;
    case 0:     /* child */
        break;
    default:    /* parent */
        exit(0);
    }
#endif
    tls_alloc(NULL, ui_tls, "main"); /* reuse thread-local storage */
#ifdef HAVE_SETSID
    setsid(); /* ignore the error */
#endif
    return 0;
}
Example #3
0
ssize_t safeRead(int fd, void *buf, size_t count, const char* marker)
{
  //double tm1, tm2;
  //tm1 = MPI_Wtime();
  ssize_t ret = read(fd, buf, count);
  if (ret == -1) {
    if(errno == EAGAIN) 
      ioerror("%s The file descriptor fd (%d) refers to a file other than a socket and has been marked nonblocking (O_NONBLOCK), and the read would block.\n", marker, fd);
    else if(errno == EWOULDBLOCK)
      ioerror("%s The file descriptor fd (%d) refers to a socket and has been marked nonblocking (O_NONBLOCK), and the read would block. POSIX.1-2001 allows either error to be returned for this case, and does not require these constants to have the same value, so a portable application should check for both possibilities.\n", marker, fd);
    else if(errno == EBADF)
      ioerror("%s fd (%d) is not a valid file descriptor or is not open for reading.\n", marker, fd);
    else if(errno == EFAULT)
      ioerror("%s fd (%d): buf is outside your accessible address space.\n", marker, fd);
    else if(errno == EINTR)
      ioerror("%s fd (%d): The call was interrupted by a signal before any data was read; see signal(7).\n", marker, fd);
    else if(errno == EINVAL)
      ioerror("%s fd (%d) is attached to an object which is unsuitable for reading; or the file was opened with the O_DIRECT flag, and either the address specified in buf, the value specified in count, or the current file offset is not suitably aligned.\n", marker, fd);
    else if(errno == EINVAL)
      ioerror("%s fd (%d) was created via a call to timerfd_create(2) and the wrong size buffer was given to read(); see timerfd_create(2) for further information.\n", marker, fd);
    else if(errno == EIO)
      ioerror("%s I/O error for fd (%d). This will happen for example when the process is in a background process group, tries to read from its controlling terminal, and either it is ignoring or blocking SIGTTIN or its process group is orphaned. It may also occur when there is a low-level I/O error while reading from a disk or tape.\n", marker, fd);
    else if(errno == EISDIR)
      ioerror("%s fd (%d) refers to a directory.\n", marker, fd);
    else 
      ioerror("%s fd (%d) unknown IO error.\n", marker, fd);
  }
  //tm2 = MPI_Wtime();
  //read_time += tm2-tm1;
  return ret;
}
Example #4
0
static void daemonize(void) { /* go to background */
#if defined(HAVE_DAEMON) && !defined(__BEOS__)
    if(daemon(0,0)==-1) {
        ioerror("daemon");
        exit(1);
    }
#else
    chdir("/");
    switch(fork()) {
    case -1:    /* fork failed */
        ioerror("fork");
        exit(1);
    case 0:     /* child */
        break;
    default:    /* parent */
        exit(0);
    }
    close(0);
    close(1);
    close(2);
#endif
#ifdef HAVE_SETSID
    setsid(); /* Ignore the error */
#endif
}
Example #5
0
static int auth_libwrap(CLI *c) {
#ifdef USE_LIBWRAP
    struct request_info request;
    int fd[2];
    int result=0; /* deny by default */

    if(pipe(fd)<0) {
        ioerror("pipe");
        return -1;
    }
    if(alloc_fd(fd[0]) || alloc_fd(fd[1]))
        return -1;
    switch(fork()) {
    case -1:    /* error */
        close(fd[0]);
        close(fd[1]);
        ioerror("fork");
        return -1;
    case  0:    /* child */
        close(fd[0]); /* read side */
        request_init(&request,
            RQ_DAEMON, c->opt->servname, RQ_FILE, c->local_rfd.fd, 0);
        fromhost(&request);
        result=hosts_access(&request);
        write_blocking(c, fd[1], (u8 *)&result, sizeof(result));
            /* ignore the returned error */
        close(fd[1]); /* write side */
        _exit(0);
    default:    /* parent */
        close(fd[1]); /* write side */
        read_blocking(c, fd[0], (u8 *)&result, sizeof(result));
            /* ignore the returned error */
        close(fd[0]); /* read side */
        /* no need to wait() for zombies here:
         *  - in UCONTEXT/PTHREAD mode they're removed using the signal pipe
         *  - in FORK mode they're removed with the client process */
    }

    if(!result) {
        s_log(LOG_WARNING, "Connection from %s REFUSED by libwrap",
            c->accepting_address);
        s_log(LOG_DEBUG, "See hosts_access(5) manual for details");
        return -1; /* FAILED */
    }
    s_log(LOG_DEBUG, "Connection from %s permitted by libwrap",
        c->accepting_address);
#endif
    return 0; /* OK */
}
Example #6
0
int s_pipe(int pipefd[2], int nonblock, char *msg) {
    int retval;

#ifdef USE_NEW_LINUX_API
    if(nonblock)
        retval=pipe2(pipefd, O_NONBLOCK|O_CLOEXEC);
    else
        retval=pipe2(pipefd, O_CLOEXEC);
#else
    retval=pipe(pipefd);
#endif
    if(retval<0) {
        ioerror(msg);
        return -1;
    }
    if(setup_fd(pipefd[0], nonblock, msg)<0) {
        close(pipefd[1]);
        return -1;
    }
    if(setup_fd(pipefd[1], nonblock, msg)<0) {
        close(pipefd[0]);
        return -1;
    }
    return 0;
}
Example #7
0
NOEXPORT void delete_pid(void) {
    if((unsigned long)getpid()!=global_options.dpid)
        return; /* current process is not main daemon process */
    s_log(LOG_DEBUG, "removing pid file %s", global_options.pidfile);
    if(unlink(global_options.pidfile)<0)
        ioerror(global_options.pidfile); /* not critical */
}
Example #8
0
void umount_cmd(int term, char **args, int argc)
{
	char *current_dir = NULL;

	if(argc != 1)
	{
		term_color_print(term, "\nInvalid parameters.\n", 12);
		term_color_print(term, "Usage: umount path\n", 7);
		return;
	}

	current_dir = get_env("CURRENT_PATH", term);
	
	if(strprefix(args[0], current_dir))
	{
		term_color_print(term, "Cannot umount dir, because it's a prefix of the current path.\n", 12);
		return;
	}

	if(umount(args[0]))
	{
		term_color_print(term, mapioerr(ioerror()), 12);
		term_color_print(term, "\n", 12);
	}
}
Example #9
0
DISK_FILE *file_open(char *name, int wr) {
    DISK_FILE *df;
#ifdef USE_WIN32
    LPTSTR tstr;
#endif /* USE_WIN32 */

    df=calloc(1, sizeof(DISK_FILE));
    if(!df)
        return NULL;
#ifdef USE_WIN32
    tstr=str2tstr(name);
    df->fh=CreateFile(tstr, wr ? GENERIC_WRITE : GENERIC_READ,
        FILE_SHARE_READ, NULL, wr ? OPEN_ALWAYS : OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL);
    free(tstr);
    if(df->fh!=INVALID_HANDLE_VALUE) { /* OK! */
        if(wr) /* append */
            SetFilePointer(df->fh, 0, NULL, FILE_END);
        return df;
    }
#else /* USE_WIN32 */
    df->fd=open(name, wr ? O_CREAT|O_WRONLY|O_APPEND : O_RDONLY, 0640);
    if(df->fd>=0) { /* OK! */
#ifndef __vms
        fcntl(df->fd, F_SETFD, FD_CLOEXEC);
#endif /* ! __vms */
        return df;
    }
#endif /* USE_WIN32 */
    /* failed to open the file */
    free(df);
    ioerror(name);
    return NULL;
}
Example #10
0
File: io.c Project: ahamid/sartoris
void rm_cmd(int term, char **args, int argc)
{
	char *path = NULL;

	if(argc != 1)
	{
		term_color_print(term, invalid_params, 12);
		term_color_print(term, "Usage: rm filepath.\n", 7);
		return;
	}

	path = build_path(args[0], term);

	if(path == NULL)
	{
		term_color_print(term, "Invalid directory.\n", 7);
		return;
	}

	if(rm(path))
	{
		term_color_print(term, mapioerr(ioerror()), 12);
		term_color_print(term, "\n", 12);
	}
	free(path);
}
Example #11
0
File: io.c Project: ahamid/sartoris
// creates a hard link
void mklink_cmd(int term, char **args, int argc)
{
	char *path = NULL, *path2 = NULL;

	if(argc != 2)
	{
		term_color_print(term, invalid_params, 12);
		term_color_print(term, "Usage: ln filename linkname.\n", 7);
		return;
	}

	path = build_path(args[0], term);

	if(path == NULL)
	{
		term_color_print(term, "Invalid filename.\n", 7);
		return;
	}

	path2 = build_path(args[1], term);

	if(path2 == NULL)
	{
		term_color_print(term, "Invalid linkname.\n", 7);
		return;
	}

	if(mklink(path, path2))
	{
		term_color_print(term, mapioerr(ioerror()), 12);
		term_color_print(term, "\n", 11);
	}
	free(path);
	free(path2);
}
Example #12
0
File: io.c Project: ahamid/sartoris
// creates a device file
// mkdevice filename service_name logic_device
void mkdevice_cmd(int term, char **args, int argc)
{
	int logic_dev = 0;
	char *path = NULL;

	// check parameters
	if(argc != 3 || !isnumeric(args[2]))
	{
		term_color_print(term, invalid_params, 12);
		term_color_print(term, "Usage: mkdevice filename Service_name logic_device.\n", 7);
		return;
	}

	path = build_path(args[0], term);

	if(path == NULL)
	{
		term_color_print(term, "Invalid path.\n", 7);
		return;
	}

	logic_dev = atoi(args[2]);

	if(mkdevice(path, args[1], logic_dev))
	{
		term_color_print(term, mapioerr(ioerror()), 12);
		term_color_print(term, "\n", 12);
	}
	free(path);
}
Example #13
0
DISK_FILE *file_open(char *name, int wr) {
    DISK_FILE *df;
    int fd, flags;

    /* open file */
    if(wr)
        flags=O_CREAT|O_WRONLY|O_APPEND;
    else
        flags=O_RDONLY;
#ifdef O_NONBLOCK
    flags|=O_NONBLOCK;
#elif defined O_NDELAY
    flags|=O_NDELAY;
#endif
#ifdef O_CLOEXEC
    flags|=O_CLOEXEC;
#endif /* O_CLOEXEC */
    fd=open(name, flags, 0640);
    if(fd<0) {
        ioerror(name);
        return NULL;
    }

    /* setup df structure */
    df=str_alloc(sizeof df);
    df->fd=fd;
    return df;
}
Example #14
0
static void delete_pid(void) {
    s_log(LOG_DEBUG, "removing pid file %s", options.pidfile);
    if((unsigned long)getpid()!=options.dpid)
        return; /* current process is not main daemon process */
    if(unlink(options.pidfile)<0)
        ioerror(options.pidfile); /* not critical */
}
Example #15
0
static void create_pid(void) {
    int pf;
    char pid[STRLEN];

    if(!options.pidfile) {
        s_log(LOG_DEBUG, "No pid file being created");
        return;
    }
    if(options.pidfile[0]!='/') {
        s_log(LOG_ERR, "Pid file (%s) must be full path name", options.pidfile);
        /* Why?  Because we don't want to confuse by
           allowing '.', which would be '/' after
           daemonizing) */
        exit(1);
    }
    options.dpid=(unsigned long)getpid();

    /* silently remove old pid file */
    unlink(options.pidfile);
    if((pf=open(options.pidfile, O_WRONLY|O_CREAT|O_TRUNC|O_EXCL,0644))==-1) {
        s_log(LOG_ERR, "Cannot create pid file %s", options.pidfile);
        ioerror("create");
        exit(1);
    }
    sprintf(pid, "%lu\n", options.dpid);
    write(pf, pid, strlen(pid));
    close(pf);
    s_log(LOG_DEBUG, "Created pid file %s", options.pidfile);
    atexit(delete_pid);
}
Example #16
0
NOEXPORT void cron_thread(void *arg) {
    (void)arg; /* skip warning about unused parameter */
    tls_alloc(NULL, NULL, "cron");
    if(!SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST))
        ioerror("SetThreadPriority");
    cron_worker();
    _endthread(); /* it should never be executed */
}
Example #17
0
int
getcommand(void)
{
	int	c, i, done;
	const char	*s, *(*func)(char);
	PLANE	*pp;

	rezero();

	do {
		c = gettoken();
		if (c == tty_new.c_cc[VERASE]) {
			if (pop() < 0)
				noise();
		} else if (c == tty_new.c_cc[VKILL]) {
			while (pop() >= 0)
				;
		} else {
			done = 0;
			for (i = 0; i < st[T_STATE].num_rules; i++) {
				if (st[T_STATE].rule[i].token == c ||
				    st[T_STATE].rule[i].token == tval) {
					push(i, (c >= ALPHATOKEN) ? tval : c);
					done = 1;
					break;
				}
			}
			if (!done)
				noise();
		}
	} while (T_STATE != -1);

	if (level == 1)
		return (1);	/* forced update */

	dest_type = T_NODEST;
	
	for (i = 0; i < level; i++) {
		func = st[stack[i].state].rule[stack[i].rule].func;
		if (func != NULL)
			if ((s = (*func)(stack[i].ch)) != NULL) {
				ioerror(stack[i].pos, strlen(stack[i].str), s);
				return (-1);
			}
	}

	pp = findplane(p.plane_no);
	if (pp->new_altitude != p.new_altitude)
		pp->new_altitude = p.new_altitude;
	else if (pp->status != p.status)
		pp->status = p.status;
	else {
		pp->new_dir = p.new_dir;
		pp->delayd = p.delayd;
		pp->delayd_no = p.delayd_no;
	}
	return (0);
}
Example #18
0
int create_client(int ls, int s, void *arg, void *(*cli)(void *)) {
    s_log(LOG_DEBUG, "Creating a new thread");
    if(_beginthread((void(*)(void *))cli, STACK_SIZE, arg)==-1) {
        ioerror("_beginthread");
        return -1;
    }
    s_log(LOG_DEBUG, "New thread created");
    return 0;
}
Example #19
0
// usage: mount dev_file path -rwd
void mount_cmd(int term, char **args, int argc)
{
	int mode = IOLIB_MOUNTMODE_READ | IOLIB_MOUNTMODE_WRITE | IOLIB_MOUNTMODE_DEDICATED;
	int dev_index = 0;

	if(argc != 2 && argc != 3)
	{
		term_color_print(term, "Invalid parameters.\n", 12);
		term_color_print(term, "Usage: mount [-r|w|d] device_file path.\n", 7);
		return;
	}

	if(argc == 3)
	{
		mode = 0;

		// calculate mount mode
		if(streq(args[0] , "-r"))
		{
			mode |= IOLIB_MOUNTMODE_READ;
		}
		else if(streq(args[0] , "-w"))
		{
			mode |= IOLIB_MOUNTMODE_WRITE;
		}
		else if(streq(args[0] , "-rd") || streq(args[0] , "-dr"))
		{
			mode |= IOLIB_MOUNTMODE_READ | IOLIB_MOUNTMODE_DEDICATED;
		}
		else if(streq(args[0] , "-wd") || streq(args[0] , "-dw"))
		{
			mode |= IOLIB_MOUNTMODE_WRITE | IOLIB_MOUNTMODE_DEDICATED;
		}
		else if(streq(args[0] , "-rwd") || streq(args[0] , "-rdw") || streq(args[0] , "-drw")  || streq(args[0] , "-dwr")  || streq(args[0] , "-wrd"))
		{
			mode |= IOLIB_MOUNTMODE_WRITE | IOLIB_MOUNTMODE_READ | IOLIB_MOUNTMODE_DEDICATED;
		}
		else if(streq(args[0] , "-wr") || streq(args[0] , "-rw"))
		{
			mode |= IOLIB_MOUNTMODE_WRITE | IOLIB_MOUNTMODE_READ;
		}
		else
		{
			term_color_print(term, "Mount mode is invalid.\n", 12);
			term_color_print(term, "Usage: mount [-r|w|d] device_file path.\n", 7);
			return;
		}
		dev_index = 1;
	}

	if(mount(args[dev_index], args[dev_index+1], mode))
	{
		term_color_print(term, mapioerr(ioerror()), 12);
		term_color_print(term, "\n", 12);
	}
}
Example #20
0
static void get_limits(void) {
#ifdef USE_WIN32
    max_clients=0;
    s_log(LOG_NOTICE, "No limit detected for the number of clients");
#else
    max_fds=0; /* unlimited */

#if defined HAVE_SYSCONF
    max_fds=sysconf(_SC_OPEN_MAX);
    if(max_fds<0)
        ioerror("sysconf");
#elif defined HAVE_GETRLIMIT
    struct rlimit rlim;
    if(getrlimit(RLIMIT_NOFILE, &rlim)<0)
        ioerror("getrlimit");
    else
        max_fds=rlim.rlim_cur;
    if(max_fds==RLIM_INFINITY)
        max_fds=0; /* RLIM_INFINITY should be equal to zero, anyway */
#endif
    s_log(LOG_INFO, "file ulimit = %d%s (can be changed with 'ulimit -n')",
        max_fds, max_fds ? "" : " (unlimited)");
#ifdef USE_POLL
    s_log(LOG_INFO, "poll() used - no FD_SETSIZE limit for file descriptors");
#else
    s_log(LOG_INFO,
        "FD_SETSIZE = %d (some systems allow to increase this value)",
        FD_SETSIZE);
    if(!max_fds || max_fds>FD_SETSIZE)
        max_fds=FD_SETSIZE;
#endif
    if(max_fds && max_fds<16) /* stunnel needs at least 16 file desriptors */
        max_fds=16;
    if(max_fds) {
        max_clients=max_fds>=256 ? max_fds/4 : (max_fds-6)/2;
//        max_clients=max_fds>=256 ? max_fds*125/256 : (max_fds-6)/2;
        s_log(LOG_NOTICE, "%d clients allowed", max_clients);
    } else {
        max_clients=0;
        s_log(LOG_NOTICE, "No limit detected for the number of clients");
    }
#endif
}
Example #21
0
int safeOpen(const char *pathname,int flags)
{
   double tm1, tm2;
   //tm1 = MPI_Wtime();
   int fd = open(pathname, flags);
   if (fd < 0){
     ioerror("Cannot open file %s\n", pathname);  
     throw;
   }
   //tm2 = MPI_Wtime();
   //open_time += tm2-tm1;
   return fd;
}
Example #22
0
int create_client(SOCKET ls, SOCKET s, CLI *arg, void *(*cli)(void *)) {
    (void)ls; /* this parameter is only used with USE_FORK */
    s_log(LOG_DEBUG, "Creating a new thread");
    if((long)_beginthread((void(*)(void *))cli, NULL, arg->opt->stack_size, arg)==-1L) {
        ioerror("_beginthread");
        str_free(arg);
        if(s>=0)
            closesocket(s);
        return -1;
    }
    s_log(LOG_DEBUG, "New thread created");
    return 0;
}
Example #23
0
void get_limits(void) { /* set max_fds and max_clients */
    /* start with current ulimit */
#if defined(HAVE_SYSCONF)
    errno=0;
    max_fds=(SOCKET)sysconf(_SC_OPEN_MAX);
    if(errno)
        ioerror("sysconf");
    if(max_fds<0)
        max_fds=0; /* unlimited */
#elif defined(HAVE_GETRLIMIT)
    struct rlimit rlim;

    if(getrlimit(RLIMIT_NOFILE, &rlim)<0) {
        ioerror("getrlimit");
        max_fds=0; /* unlimited */
    } else
        max_fds=rlim.rlim_cur!=RLIM_INFINITY ? rlim.rlim_cur : 0;
#else
    max_fds=0; /* unlimited */
#endif /* HAVE_SYSCONF || HAVE_GETRLIMIT */

#if !defined(USE_WIN32) && !defined(USE_POLL) && !defined(__INNOTEK_LIBC__)
    /* apply FD_SETSIZE if select() is used on Unix */
    if(!max_fds || max_fds>FD_SETSIZE)
        max_fds=FD_SETSIZE; /* start with select() limit */
#endif /* select() on Unix */

    /* stunnel needs at least 16 file desriptors */
    if(max_fds && max_fds<16)
        max_fds=16;

    if(max_fds) {
        max_clients=(long)(max_fds>=256 ? max_fds*125/256 : (max_fds-6)/2);
        s_log(LOG_DEBUG, "Clients allowed=%ld", max_clients);
    } else {
        max_clients=0;
        s_log(LOG_DEBUG, "No limit detected for the number of clients");
    }
}
Example #24
0
int create_client(int ls, int s, CLI *arg, void *(*cli)(void *)) {
    CONTEXT *context;

    (void)ls; /* this parameter is only used with USE_FORK */
    
    s_log(LOG_DEBUG, "Creating a new context");
    context=new_context();
    if(!context) {
        if(arg)
            str_free(arg);
        if(s>=0)
            closesocket(s);
        return -1;
    }

    /* initialize context_t structure */
    if(getcontext(&context->context)<0) {
        str_free(context);
        if(arg)
            str_free(arg);
        if(s>=0)
            closesocket(s);
        ioerror("getcontext");
        return -1;
    }
    context->context.uc_link=NULL; /* stunnel does not use uc_link */

    /* create stack */
    context->stack=str_alloc(arg->opt->stack_size);
    if(!context->stack) {
        str_free(context);
        if(arg)
            str_free(arg);
        if(s>=0)
            closesocket(s);
        s_log(LOG_ERR, "Unable to allocate stack");
        return -1;
    }
    str_detach(context->stack);
#if defined(__sgi) || ARGC==2 /* obsolete ss_sp semantics */
    context->context.uc_stack.ss_sp=context->stack+arg->opt->stack_size-8;
#else
    context->context.uc_stack.ss_sp=context->stack;
#endif
    context->context.uc_stack.ss_size=arg->opt->stack_size;
    context->context.uc_stack.ss_flags=0;

    makecontext(&context->context, (void(*)(void))cli, ARGC, arg);
    s_log(LOG_DEBUG, "New context created");
    return 0;
}
Example #25
0
void SDArrayBAux::load_aux(InpArchive &ar, const BitArrayInterface* ba) {
	bits = ba;
	ar.loadclass("SDArray_blk_aux");
	ar.var("length").load(len);
	ar.var("sum").load(sum);
	ar.var("w1").load(w1);
	ar.var("w2").load(w2);
	uint64_t bal;
	ar.var("store_bit_len").load(bal);
	header.load(ar.var("header"));
	ar.endclass();
	if (bal != bits->length()) throw ioerror("mismatch length");
	blk.clear();
}
Example #26
0
int s_poll_wait(s_poll_set *fds, int timeout) {
    CONTEXT *ctx; /* current context */
    static CONTEXT *to_free=NULL; /* delayed memory deallocation */

    /* remove the current context from ready queue */
    ctx=ready_head;
    ready_head=ready_head->next;
    if(!ready_head) /* the queue is empty */
        ready_tail=NULL;

    if(fds) { /* something to wait for -> swap the context */
        ctx->fds=fds; /* set file descriptors to wait for */
        ctx->finish=timeout<0 ? -1 : time(NULL)+timeout;
        /* move (append) the current context to the waiting queue */
        ctx->next=NULL;
        if(waiting_tail)
            waiting_tail->next=ctx;
        waiting_tail=ctx;
        if(!waiting_head)
            waiting_head=ctx;
        while(!ready_head) /* no context ready */
            scan_waiting_queue();
        if(ctx->id!=ready_head->id) {
            s_log(LOG_DEBUG, "Context swap: %ld -> %ld",
                ctx->id, ready_head->id);
            swapcontext(&ctx->ctx, &ready_head->ctx);
            s_log(LOG_DEBUG, "Current context: %ld", ready_head->id);
            if(to_free) {
                s_log(LOG_DEBUG, "Releasing context %ld", to_free->id);
                free(to_free);
                to_free=NULL;
            }
        }
        return ready_head->ready;
    } else { /* nothing to wait for -> drop the context */
        /* it's illegal to deallocate the stack of the current context */
        if(to_free) {
            s_log(LOG_DEBUG, "Releasing context %ld", to_free->id);
            free(to_free);
        }
        to_free=ctx;
        while(!ready_head) /* no context ready */
            scan_waiting_queue();
        s_log(LOG_DEBUG, "Context set: %ld (dropped) -> %ld",
            ctx->id, ready_head->id);
        setcontext(&ready_head->ctx);
        ioerror("setcontext"); /* should not ever happen */
        return 0;
    }
}
Example #27
0
int libwrap_init() {
#ifdef USE_PTHREAD
    int i, j, rfd, result;
    char servname[SERVNAME_LEN];
    static int initialized=0;
    SERVICE_OPTIONS *opt;

    if(initialized) /* during startup or previous configuration file reload */
        return 0;
    for(opt=service_options.next; opt; opt=opt->next)
        if(opt->option.libwrap) /* libwrap is enabled for this service */
            break;
    if(!opt) /* disabled for all sections or inetd mode (no sections) */
        return 0;

    num_processes=LIBWRAP_CLIENTS;
    ipc_socket=str_alloc(2*num_processes*sizeof(int));
    busy=str_alloc(num_processes*sizeof(int));
    for(i=0; i<num_processes; ++i) { /* spawn a child */
        if(s_socketpair(AF_UNIX, SOCK_STREAM, 0, ipc_socket+2*i, 0, "libwrap_init"))
            return 1;
        switch(fork()) {
        case -1:    /* error */
            ioerror("fork");
            return 1;
        case  0:    /* child */
            drop_privileges(0); /* libwrap processes are not chrooted */
            close(0); /* stdin */
            close(1); /* stdout */
            if(!global_options.option.foreground) /* for logging in read_fd */
                close(2); /* stderr */
            for(j=0; j<=i; ++j) /* close parent-side sockets created so far */
                close(ipc_socket[2*j]);
            while(1) { /* main libwrap child loop */
                if(read_fd(ipc_socket[2*i+1], servname, SERVNAME_LEN, &rfd)<=0)
                    _exit(0);
                result=check(servname, rfd);
                write(ipc_socket[2*i+1], (u8 *)&result, sizeof result);
                if(rfd>=0)
                    close(rfd);
            }
        default:    /* parent */
            close(ipc_socket[2*i+1]); /* child-side socket */
        }
    }
    initialized=1;
#endif /* USE_PTHREAD */
    return 0;
}
Example #28
0
NOEXPORT void tray_update(const int num) {
    NOTIFYICONDATA nid;
    static ICON_TYPE previous_icon=ICON_NONE;
    ICON_TYPE current_icon;
    LPTSTR tip;

    if(!global_options.option.taskbar) { /* currently disabled */
        tray_delete(); /* remove the taskbark icon if exists */
        return;
    }
    if(!tray_menu_handle) /* initialize taskbar */
        tray_menu_handle=LoadMenu(ghInst, MAKEINTRESOURCE(IDM_TRAYMENU));
    if(!tray_menu_handle) {
        ioerror("LoadMenu");
        return;
    }
    if(cmdline.service)
        EnableMenuItem(tray_menu_handle, IDM_EDIT_CONFIG, MF_GRAYED);

    ZeroMemory(&nid, sizeof nid);
    nid.cbSize=sizeof nid;
    nid.uID=1; /* application-defined icon ID */
    nid.uFlags=NIF_MESSAGE|NIF_TIP;
    nid.uCallbackMessage=WM_SYSTRAY; /* notification message */
    nid.hWnd=hwnd; /* window to receive notifications */
    if(num<0) {
        tip=str_tprintf(TEXT("Server is down"));
        current_icon=ICON_ERROR;
    } else if(num>0) {
        tip=str_tprintf(TEXT("%d active session(s)"), num);
        current_icon=ICON_ACTIVE;
    } else {
        tip=str_tprintf(TEXT("Server is idle"));
        current_icon=ICON_IDLE;
    }
    _tcsncpy(nid.szTip, tip, 63);
    nid.szTip[63]=TEXT('\0');
    str_free(tip);
    nid.hIcon=global_options.icon[current_icon];
    if(current_icon!=previous_icon) {
        nid.uFlags|=NIF_ICON;
        previous_icon=current_icon;
    }
    if(Shell_NotifyIcon(NIM_MODIFY, &nid)) /* modify tooltip */
        return; /* OK: taskbar icon exists */
    /* tooltip update failed - try to create the icon */
    nid.uFlags|=NIF_ICON;
    Shell_NotifyIcon(NIM_ADD, &nid);
}
Example #29
0
NOEXPORT void tray_delete(void) {
    NOTIFYICONDATA nid;

    if(tray_menu_handle) {
        ZeroMemory(&nid, sizeof nid);
        nid.cbSize=sizeof nid;
        nid.uID=1; /* application-defined icon ID */
        nid.hWnd=hwnd; /* window to receive notifications */
        nid.uFlags=NIF_TIP; /* not really sure what to put here, but it works */
        Shell_NotifyIcon(NIM_DELETE, &nid); /* this removes the icon */
        if(!DestroyMenu(tray_menu_handle)) /* release menu resources */
            ioerror("DestroyMenu");
        tray_menu_handle=NULL;
    }
}
Example #30
0
NOEXPORT void *cron_thread(void *arg) {
#ifdef SCHED_BATCH
    struct sched_param param;
#endif

    (void)arg; /* skip warning about unused parameter */
    tls_alloc(NULL, NULL, "cron");
#ifdef SCHED_BATCH
    param.sched_priority=0;
    if(pthread_setschedparam(pthread_self(), SCHED_BATCH, &param))
        ioerror("pthread_getschedparam");
#endif
    cron_worker();
    return NULL; /* it should never be executed */
}