Exemple #1
0
/* fun: _nss_map_getpwnam_r
 * txt: get a passwd struct from username mapped to generic user.
 */
enum nss_status
_nss_map_getpwnam_r( const char *name, struct passwd *p,
		char *buffer, size_t buflen, int *errnop)
{
	map_conf_t *conf;

	if ((conf = read_conf()) == NULL) {
		return NSS_STATUS_NOTFOUND;
	}

	/* If out of memory */
	if ((p->pw_name = get_static(&buffer, &buflen, strlen(name) + 1)) == NULL) {
		return NSS_STATUS_TRYAGAIN;
	}

	/* pw_name stay as the name given */
	strcpy(p->pw_name, name);

	if ((p->pw_passwd = get_static(&buffer, &buflen, strlen("x") + 1)) == NULL) {
		return NSS_STATUS_TRYAGAIN;
	}

	strcpy(p->pw_passwd, "x");

	p->pw_uid = conf->pw_uid; /* UID_NUMBER; */
	p->pw_gid = conf->pw_gid; /* GID_NUMBER; */

	if ((p->pw_gecos = get_static(&buffer, &buflen, strlen(conf->pw_gecos) + 1 )) == NULL) {
		return NSS_STATUS_TRYAGAIN;
	}

	strcpy(p->pw_gecos, conf->pw_gecos);

	if ((p->pw_dir = get_static(&buffer, &buflen, strlen(conf->pw_dir) + 1 +
					strlen(name) + 1 )) == NULL) {
		return NSS_STATUS_TRYAGAIN;
	}

	strcpy(p->pw_dir, conf->pw_dir);
	strcat(p->pw_dir,"/");
	strcat(p->pw_dir,name);

	if ((p->pw_shell = get_static(&buffer, &buflen, strlen(conf->pw_shell) + 1 )) == NULL) {
		return NSS_STATUS_TRYAGAIN;
	}

	strcpy(p->pw_shell, conf->pw_shell);

	free_conf(conf);

	return NSS_STATUS_SUCCESS;
}
Exemple #2
0
void _gale_globals(void) {
	struct gale_global_data *G = gale_malloc_safe(sizeof(*gale_global));
	struct gale_text conf;
	memset(G,'\0',sizeof(*gale_global));
	gale_global = G;

	setlocale(LC_CTYPE, "");

	_gale_charsets();

	/* These are in this particular order to allow each 'conf' file to
	   redirect the location of the next one. */

	assert(NULL == G->error);
	assert(NULL == G->cleanup_list);

	G->home_dir = gale_var(G_("HOME"));
	make_dir(G->home_dir,0777);

	G->dot_gale = gale_var(G_("GALE_DIR"));
	if (0 != G->dot_gale.l) 
		make_dir(G->dot_gale,0700);
	else
		G->dot_gale = submk_dir(G->home_dir,G_(".gale"),0700);

	conf = gale_var(G_("GALE_CONF"));
	if (0 != conf.l) read_conf(dir_file(G->dot_gale,conf));
	read_conf(dir_file(G->dot_gale,G_("conf")));

	G->sys_dir = gale_var(G_("GALE_SYS_DIR"));
	if (0 == G->sys_dir.l) 
		G->sys_dir = gale_text_from(
			gale_global->enc_filesys,GALE_SYS_DIR,-1);
	make_dir(G->sys_dir,0);

	read_conf(dir_file(G->sys_dir,G_("conf")));

	_gale_charsets();
}
Exemple #3
0
int main(int argc, char **argv) {
    read_viutualhost_conf();
    read_conf();
    int i;
    for (i = 0; i < vhost_num; i++) {
        int pid = fork();
        skip_error(pid, "创建虚拟主机子进程时错误");

        if (pid == 0) {
            current_dir = root_dir[i];
            current_port = port[i];
            int server_sockfd, client_sockfd;
            int server_len, client_len;
            struct sockaddr_in server_address;
            struct sockaddr_in client_address;


            server_sockfd = socket(AF_INET, SOCK_STREAM, 0);
            check_error(server_sockfd, "socket出错");


            server_address.sin_family = AF_INET;
            server_address.sin_addr.s_addr = htonl(INADDR_ANY);
            srand((unsigned int) (time(NULL)));
            server_address.sin_port = htons(current_port);
            server_len = sizeof (server_address);
            int bind_id = bind(server_sockfd, (struct sockaddr *) &server_address, server_len);
            check_error(bind_id, "bind出错");

            int listen_id = listen(server_sockfd, max_connect);
            check_error(listen_id, "listen出错");
            while (1) {
                printf("server at port %d in %s waiting\n", current_port, current_dir);
                client_len = sizeof (client_address);
                client_sockfd = accept(server_sockfd,
                        (struct sockaddr *) &client_address, &client_len);
                skip_error(client_sockfd, "accept出错");

                process_request(client_sockfd);


            }

            exit(EXIT_SUCCESS);
        }
    }

    exit(EXIT_SUCCESS);
}
Exemple #4
0
int serve() {
	serve_ERRNO = 0;
	serv_conf * main_conf;
	main_conf = read_conf("dummylocation");
	if ((sock = create_serv_socket(main_conf)) == -1){
		serve_ERRNO = 1;
		return 1;
	}

	LOG("Created listening socket at %d\n", main_conf->port);
	signal(15, shutdown_handler);
	signal(2, shutdown_handler);
	LOG("Created signal handlers\n");
	start_ftp_server(sock, main_conf);
	close(sock);
	return 0;
}
Exemple #5
0
void
initialize (void)
{
    cfgfile = cfgfile ? cfgfile : CFGFILE;
    logfile = logfile ? logfile : LOGFILE;
    pidfile = pidfile ? pidfile : PIDFILE;

    read_conf (cfgfile);
    if (mode & DAEMON)
    {
        /* redirect stdout & stderr to a log file */
        redirect_to_log (logfile, STDOUT_FILENO | STDERR_FILENO);
        write_pid (pidfile);
    }

    dns_random_init (seed);
}
Exemple #6
0
int
main(int argc, char *argv[])
{
    DB **db;
    char **dir, **ignore;

    char *cfgfile;
    int c, i, err;

    prg = argv[0];
    opterr = 0;

    cfgfile = "@PKG_SYSCONFDIR@/pkg_filecheck.conf";

    while ((c=getopt(argc, argv, "c:h")) != -1) {
	switch (c) {
	case 'c':
	    cfgfile = optarg;
	    break;

	case 'h':
	    printf("usage: %s [-h] [-c config-file]\n", prg);
	    exit(0);

	default:
	    fprintf(stderr, "usage: %s [-h] [-c config-file]\n", prg);
	    exit(1);
	}
    }

    if (read_conf(cfgfile, &dir, &db, &ignore) < 0)
	exit(1);

    err = check(dir, db, ignore);

    for (i=0; db[i]; i++)
	db[i]->close(db[i]);
    free(dir);
    free(db);
    free(ignore);

    exit(err ? 1 : 0);
}
int main(int argc, char **argv)
{
    _list *list = (_list *)malloc(sizeof(_list));
    _conf_item *conf_item = NULL;
    int loop = 0;
    int chid = 0;
    if(argc < 2 || strcmp(argv[1], IDENTIFY)) {
        printf("please use sig_ctl to start the progarm\n");
        exit(0);
    }
    read_conf(list);
    for(conf_item = list->head; conf_item != NULL; conf_item = conf_item->next) {
        chid = vfork();
        if(0 > chid) {
            //error
        } else if(0 == chid) {
            char *argv[ARGC_SIZE] = {NULL};
            if(sigprocmask(SIG_SETMASK, &(conf_item->maskset), NULL)) {
                printf("sigprocmask error %d \n", errno);
            }
            for(loop = 0; loop < SIG_SIZE; ++loop) {
                if(conf_item->hand[loop] > 0) {
                    regist_handler(loop, conf_item->hand[loop]);
                }
            }
            argv[0] = conf_item->serv_path;
            for(loop = 0; conf_item->argv[loop][0]; loop++) {
                argv[loop + 1] = conf_item->argv[loop];
            }
            if(-1 == execv(conf_item->serv_path, argv)) {
                printf("execv error %d [%s] \n", errno, conf_item->serv_path);
            }
            exit(0);
        }
    }
    while(1) {
        pause();
    }
    return 0;

}
Exemple #8
0
int main(int argc, char *argv[])
{
	int i;
	signal(SIGPIPE, SIG_IGN);

	openlog("flexd", LOG_ERR , LOG_INFO);
	syslog(LOG_WARNING, "Starting flexd");

	if (ax25_config_load_ports() == 0) {
		fprintf(stderr, "flexd error: No AX25 port data configured\n");
		return 1;
	}

	process_options(argc, argv);

	if ((i = read_conf()) == -1)
		return 1;

	if ((is_daemon) && (!daemon_start(TRUE)) ) {
		fprintf(stderr, "flexd: cannot become a daemon\n");
		return 1;
	}

	if ((i = update_flex()) == -1) {
		fprintf(stderr, "\nStopping application. Restart flexd after changing the configuration\n");
		signal(SIGKILL, hup_handler);
		return (i);
	}

	signal(SIGHUP, hup_handler);
	signal(SIGALRM, alarm_handler);
	alarm(poll_time);

	for (;;)
		pause();

	return 0;
}
Exemple #9
0
int
main (int argc, char *argv[])
{
    int n = 0;
    time_t t = 0;
    struct sigaction sa;

    char qtype[2];
    char qclass[2];
    char header[12];
    const char *x = NULL;
    unsigned int pos = 0;
    unsigned long long qnum = 0;

    sa.sa_handler = handle_term;
    sigaction (SIGINT, &sa, NULL);
    sigaction (SIGTERM, &sa, NULL);

    sa.sa_handler = SIG_IGN;
    sigaction (SIGPIPE, &sa, NULL);

    prog = strdup ((x = strrchr (argv[0], '/')) != NULL ?  x + 1 : argv[0]);
    n = check_option (argc, argv);
    argc -= n;
    argv += n;

    if (mode & DAEMON)
        /* redirect stderr to a log file */
        redirect_to_log (logfile, STDERR_FILENO);

    time (&t);
    memset (seed, 0, sizeof (seed));
    strftime (seed, sizeof (seed), "%b-%d %Y %T %Z", localtime (&t));
    warnx ("version %s: starting %s\n", VERSION, seed);

    set_timezone ();
    if (debug_level)
        warnx ("TIMEZONE: %s", env_get ("TZ"));

    read_conf (cfgfile);
    if (!debug_level)
        if ((x = env_get ("DEBUG_LEVEL")))
            debug_level = atol (x);
    warnx ("DEBUG_LEVEL set to `%d'", debug_level);

    dns_random_init (seed);

    axfr = env_get ("AXFR");
    if (debug_level)
        warnx ("AXFR set to `%s'", axfr);
    x = env_get ("TCPREMOTEIP");
    if (debug_level)
        warnx ("TCPREMOTEIP set to `%s'", x);
    if (x)
        ip4_scan (x, ip);
    else
        byte_zero (ip, 4);

    x = env_get ("TCPREMOTEPORT");
    if (debug_level)
        warnx ("TCPREMOTEPORT set to `%s'", x);
    if (!x)
        x = "0";
    scan_ulong (x, &port);

    droproot ();
    for (;;)
    {
        netread (tcpheader, 2);
        uint16_unpack_big (tcpheader, &len);
        if (len > 512)
            errx (-1, "excessively large request");
        netread (buf, len);

        pos = dns_packet_copy (buf, len, 0, header, 12);
        if (!pos)
            errx (-1, "truncated request");
        if (header[2] & 254)
            errx (-1, "bogus query");
        if (header[4] || (header[5] != 1))
            errx (-1, "bogus query");

        pos = dns_packet_getname (buf, len, pos, &zone);
        if (!pos)
            errx (-1, "truncated request");
        zonelen = dns_domain_length (zone);
        pos = dns_packet_copy (buf, len, pos, qtype, 2);
        if (!pos)
            errx (-1, "truncated request");
        pos = dns_packet_copy (buf, len, pos, qclass, 2);
        if (!pos)
            errx (-1, "truncated request");

        if (byte_diff(qclass, 2, DNS_C_IN) && byte_diff(qclass, 2, DNS_C_ANY))
            errx (-1, "bogus query: bad class");

        log_query (++qnum, ip, port, header, zone, qtype);
        if (byte_equal(qtype,2,DNS_T_AXFR))
        {
            case_lowerb (zone, zonelen);
            fdcdb = open_read ("data.cdb");
            if (fdcdb == -1)
                errx (-1, "could not read from file `data.cdb'");
            doaxfr (header);
            close (fdcdb);
        }
        else
        {
            if (!response_query (zone, qtype, qclass))
                err (-1, "could not allocate enough memory");
            response[2] |= 4;
            case_lowerb (zone, zonelen);
            response_id (header);
            response[3] &= ~128;
            if (!(header[2] & 1))
                response[2] &= ~1;
            if (!respond (zone, qtype, ip))
                errx (-1, "could not find information in file `data.cdb'");
            print (response, response_len);
        }
    }
}
Exemple #10
0
void proptrj(char *fngro,char *fndat,t_topology *top,t_pinp *p)
{
  static char *ppp[efhNR] = { 
    "RAD", "TWIST", "RISE", "LEN", "NHX", "DIP", "RMS", "CPHI", 
    "RMSA", "PHI", "PSI", "HB3", "HB4", "HB5" 
  };
  FILE       *out;
  rvec       **EV;
  real       **evprj;
  atom_id    *index;
  int        natoms,nca,nSel,nframes,nev;
  rvec       *xav,*vav;
  atom_id    *ca_index,*bb_index;
  matrix     box;
  char       buf[256],*prop;
  double     x;
  int        i,j,d;
  
  nframes = p->nframes;
  nSel    = p->nSel;
  nev     = p->nev;
  
  prop=ppp[nSel];
  evprj=read_proj(nev,nframes,p->base);
  
  get_coordnum(fngro,&natoms);
  snew(xav,natoms);
  snew(vav,natoms);
  read_conf(fngro,buf,&natoms,xav,vav,box);
  fprintf(stderr,"Successfully read average positions (%s)\n",buf);
  
  EV=read_ev(fndat,natoms);
  
  fprintf(stderr,"Successfully read eigenvectors\n");

  snew(index,nev);
  for(i=0; (i<nev); i++)
    index[i]=i;
  snew(bb_index,natoms);
  for(i=0; (i<natoms); i++)
    bb_index[i]=i;
  snew(ca_index,natoms);
  for(i=nca=0; (i<natoms); i++)
    if ((strcmp("CA",*(top->atoms.atomname[i])) == 0))
      ca_index[nca++]=i;

  switch (p->funct) {
  case ptMC:
    switch(nSel) {
    case efhRAD:
      optim_radius(nev,xav,EV,evprj,natoms,nca,ca_index,p);
      break;
    case efhRISE:
      optim_rise(nev,xav,EV,evprj,natoms,nca,ca_index,p);
      break;
    default:
      break;
    }
    break;
  case ptREC:
    recombine(p->recomb,p->gamma,p->nskip,nframes,nev,natoms,
	      EV,evprj,xav,bb_index);
    break;
  case ptPTRJ:
    mkptrj(prop,nSel,natoms,xav,nframes,
	   nev,EV,evprj,nca,ca_index,bb_index,
	   top->atoms.atom,box);
    break;
  default:
    gmx_fatal(FARGS,"I Don't Know What to Do");
  }
}
Exemple #11
0
void run(Par *par)
{
  int i, itherm, nstep, istep, isamp, iblock, st;
  int nsamp = par->nsamp, nblock = par->nblock;
  char wfile[FNAMESIZE];
  Vec *pos, *vel, *force;
  double ekin, epot;
  double v0[NV], v1[NV], v2[NV];
  FILE *estream = NULL;

  // Initialize

  if (par->alpha > 0.0) {
    printf("Seed for random number generator: %d.\n", par->seed);
    init_ran(par->seed);
  }

  pos = malloc(par->n * sizeof(Vec));
  force = malloc(par->n * sizeof(Vec));
  vel = malloc(par->n * sizeof(Vec));

  // Read from file...
  if (par->readfile)
    st = read_conf(par->n, pos, vel, par->readfile);
  else {
    init_pos(par->n, &par->L, pos);
    set_temperature(par->n, par->t, vel);
  }

  // Get file name for writing to.
  get_filename(par, wfile);

  // Open file for writing energy results
  estream = fopen_wfile("efile/", wfile);
  if (!estream) return;

  measure(par->n, &par->L, pos, vel, &epot, &ekin);
  printf("Energy = %g \n", epot);

  double test;
  for(i=0; i<par->ntherm; i++) {
    test = pos[5].x;
    step(par, pos, vel, force);
    if(test == pos[5].x)
      printf("aha!\n");
  }
  //printf("rx ry vx vy = %g  %g  %g  %g\n", pos[0].x, pos[0].y, vel[0].x, vel[0].y);

  // Run and collect values
  printf("\nSimulate %d blocks x %d samples each: ", par->nblock, par->nsamp);
  fflush(stdout);

  init_vcorr(par->n, par->deltat, 0.1, 5.0);

  // Initialize for measuring a histogram of particle distances for
  // distances up to 5.0 and bin size 0.02.
  // init_pcorr(par->n, 0.02, 5.0);
  for (i = 0; i < NV; i++) v1[i] = v2[i] = 0.0;

  nstep = rint(1.0 / par->deltat);
  for (iblock = 0; iblock < nblock; iblock++) {

    for (i = 0; i < NV; i++) v0[i] = 0.0;
    for (isamp = 0; isamp < nsamp; isamp++) {
      for (istep = 0; istep < nstep; istep++) {
	      step(par, pos, vel, force);
	      measure_vcorr(par->n, vel);
      }

      // measure_pcorr(par->n, &par->L, pos);

      measure(par->n, &par->L, pos, vel, &epot, &ekin);
      if (estream) fprintf(estream, "%d %g\n", isamp + nsamp * iblock, epot + ekin);
      v0[0] += epot;
      //v0[1] += ekin;
      //v0[2] += epot + ekin;
    }
    for (i = 0; i < NV; i++) {
      v0[i] /= nsamp;
      v1[i] += v0[i];
      v2[i] += v0[i] * v0[i];
    }

    printf("%d ", iblock + 1);	fflush(stdout);
  }
  printf("\n");

  if (estream) fclose(estream);

  for (i = 0; i < NV; i++) {
    v1[i] /= nblock;
    v2[i] /= nblock;
  }

  // Write configuration to the named file.
  write_conf(par->n, pos, vel, "conf/", wfile);

  // Write velocity correlation results to files.
  write_vcorr(par->n, wfile);
  // write_pcorr(par->n, wfile);

  // Print out some results
  printf("\n");
  printf("v1: %.3f v2: %.3f nblock: %d \n",v1[0],v2[0],nblock);
  print_standard_error("Potential E:  ", v1[0], v2[0], nblock);
  //print_standard_error("Kinetic  E:   ", v1[1], v2[1], nblock);
  //print_standard_error("Total energy: ", v1[2], v2[2], nblock);


  // From the virial theorem:  pressure = N * T + Virial / Dimensionality

  free(vel);
  free(pos);
  
}
Exemple #12
0
int
main(int argc, char **argv)
{
	int x;

	umask(0077);

	/* initialize stuff */
	memset(&me, 0, sizeof(me));
	me.argc       = argc;
	me.argv       = argv;
	me.start      = time(NULL);
	me.settime    = time(NULL) + (60*60*4);

	/* setup signals */
	signal(SIGHUP,  do_signal);
	signal(SIGINT,  do_signal);
	signal(SIGQUIT, do_signal);
	signal(SIGILL,  do_signal);
	signal(SIGTRAP, do_signal);
	signal(SIGBUS,  do_signal);
	signal(SIGSEGV, do_signal);
	signal(SIGSYS,  do_signal);
	signal(SIGALRM, SIG_IGN);
	signal(SIGTERM, do_signal);
	signal(SIGPIPE, SIG_IGN);
	signal(SIGUSR1, SIG_IGN);
	signal(SIGUSR2, SIG_IGN);

	while ((x = getopt(me.argc, me.argv, "qd")) != -1) {
		switch (x) {
			case 'd':
				me.debug = 1;
				break;
		}
	}

	if (me.debug == 0)
		printf("%s by %s\n", VER_STR, MYEMAIL);

	if (read_conf())
		err(1, "ERROR! Unable to read configuration file");

	if (!me.servname || !me.servdesc)
		errx(1, "ERROR! Your M: line is invalid, incomplete, or missing!");

	for (x = 0; x < ALL; x++)
		if (!me.sclients[x].nick || check_nick(NULL, me.sclients[x].nick) ||
			!me.sclients[x].username || check_um(NULL, me.sclients[x].username) ||
			!me.sclients[x].realname || check_rm(NULL, me.sclients[x].realname))
			errx(1, "ERROR! Your N: line for %d is invalid, incomplete, or missing!", x);

	if (!me.chans[0])
		errx(1, "ERROR! You need at least one R: line in %s", CONF);

	if (!(me.logfd = fopen(PIDFILE, "w")))
		err(1, "ERROR! Unable to open pidfile");
	fprintf(me.logfd, "%d\n", getpid());
	fclose(me.logfd);

	if (!(me.logfd = fopen(LOGFILE, "a")))
		err(1, "ERROR! Unable to open logfile");

	if ((x = read_db(0)) > 0)
		err(1, "ERROR! Unable to read %s", databases[x]);

	if (me.ip.s_addr == NULL) {
		if (!self_lookup())
			err(1, "ERROR! self-lookup failed!");
		else
			printf("WARNING: no vhost defined in conf, using default of %s\n", inet_ntoa(me.ip));
	}

	if (me.debug == 0)
		switch (me.pid = fork())
		{
			case -1:
				err(1, "ERROR! Unable to fork");
			case 0:
				for (x = 0; x < 12; x++)
					if (x != fileno(me.logfd))
						close(x);
				break;
			default:
				printf("forked into the background: pid = %d\n", me.pid);
				return 0;
		}
	listen_sock(7272);
	try_next_hub();
	add_event(1, SERVTIMEOUT / 2, &ping_hub);
	add_event(1, CONNTIMEOUT / 3, &cleanup_dcc);
	io_loop();
	/* NOTREACHED */
	exit(0);
}
Exemple #13
0
int main(int argc, char** argv)
{
    bool daemonize = false;
    int ch;
    //The error return val for kevent or read
    int ret;
    while ((ch = getopt(argc, argv, "dh")) != -1) {
        switch (ch) {
            case 'd':
                daemonize = true;
                break;
            case 'h':
                usage(0);
            default:
                usage(1);
        }

    }

    Conf *conf = read_conf();

    Group *groups = read_externals();
    
    obtain_lock(conf);

    // Check that everything to do with the spool dir is OK.

    if (!check_spool_dir(conf))
        exit(1);

    if (daemonize) {
        daemon(1, 0);
        
        conf->mode = DAEMON_MODE;

        char *msgs_path; // msgs dir (within spool dir)
        if (asprintf(&msgs_path, "%s%s%s", conf->spool_dir, DIR_SEP, MSGS_DIR)
          == -1) {
            errx(1, "main: asprintf: unable to allocate memory");
        }

        // On platforms that support an appropriate mechanism (such as kqueue
        // or inotify), we try and monitor spool_dir/msgs so that if we're a
        // daemon then, as soon as someone starts fiddling with it (i.e. extsmail
        // putting a new message in there) we try to send all messages. This
        // gives the nice illusion that message sending with extsmail is pretty
        // much instant.

#ifdef HAVE_KQUEUE
        int kq = kqueue();
        if (kq == -1)
           err(1, "main: kqueue");

        int smf = open(msgs_path, O_RDONLY);
        if (smf == -1)
           err(1, "When opening '%s'", msgs_path);

        struct kevent changes;
        struct kevent events;
        EV_SET(&changes, smf, EVFILT_VNODE,
          EV_ADD | EV_ENABLE | EV_ONESHOT,
          NOTE_DELETE | NOTE_WRITE | NOTE_EXTEND | NOTE_TRUNCATE | NOTE_ATTRIB
          | NOTE_LINK | NOTE_RENAME | NOTE_REVOKE,
          0, 0);
#elif HAVE_INOTIFY
        int fd = inotify_init();
        if (fd < 0) {
            err(1, "main: inotify_init");
        }
   
        if (inotify_add_watch(fd, msgs_path,
          IN_ACCESS | IN_DELETE | IN_ATTRIB | IN_CLOSE_WRITE) < 0) {
            err(1, "main: inotify_add_watch");      
        }
#endif

        openlog(__progname, LOG_CONS, LOG_MAIL);

        while (1) {
            cycle(conf, groups);

            // On platforms that support an appropriate mechanism (such as kqueue
            // or inotify), we try and send messages as soon as we notice changes
            // to spool_dir/msgs. We also wake-up every POLL_WAIT seconds to
            // check the queue and send messages. This is in case the network
            // goes up and down - we can't just wait until the user tries sending
            // messages.
            //
            // Note that if kqueue / inotify return errors, they are deliberately
            // ignored: while support for these mechanisms is very nice, it's
            // still possible for extsmaild to operate without them.
            
#ifdef HAVE_KQUEUE
            struct timespec timeout = {POLL_WAIT, 0};
            kevent(kq, &changes, 1, &events, 1, &timeout);
#elif HAVE_INOTIFY
            fd_set descriptors;
            FD_ZERO(&descriptors);
            FD_SET(fd, &descriptors);
            struct timespec timeout = {POLL_WAIT, 0};
            if (pselect(fd + 1, &descriptors, NULL, NULL, &timeout, NULL) != -1)
            {
                // Even though we don't care what the result of the inotify read
                // is, we still need to read from it so that the buffer doesn't
                // fill up.
                char buf[INOTIFY_BUFLEN];
                read(fd, buf, INOTIFY_BUFLEN);
            }
#else
            // If no other support is available, we fall back on polling alone.
            sleep(POLL_WAIT);
#endif
        }
    }
    else {
        conf->mode = NORMAL_MODE;

        openlog(__progname, LOG_PERROR, LOG_MAIL);

        if (!cycle(conf, groups)) {
            closelog();
            return 1;
        }

        closelog();

        return 0;
    }
}
Exemple #14
0
int
main(int argc, char **argv)
{
    int return_code = 0;
    int fd = (-1);              /* fd == -1 means connection to fcron is not currently open */
    struct passwd *pass = NULL;

    rootuid = get_user_uid_safe(ROOTNAME);
    rootgid = get_group_gid_safe(ROOTGROUP);

    if (strrchr(argv[0], '/') == NULL)
        prog_name = argv[0];
    else
        prog_name = strrchr(argv[0], '/') + 1;

    user_uid = getuid();
    user_gid = getgid();
    if ((pass = getpwuid(user_uid)) == NULL)
        die("user \"%s\" is not in passwd file. Aborting.", USERNAME);
    user_str = strdup2(pass->pw_name);

    /* drop suid rights that we don't need, but keep the sgid rights
     * for now as we will need them for read_conf() and is_allowed() */
#ifdef USE_SETE_ID
    seteuid_safe(user_uid);
#endif
    if (setuid(user_uid) < 0)
        die_e("could not setuid() to %d", user_uid);

    /* interpret command line options */
    parseopt(argc, argv);

    /* read fcron.conf and update global parameters */
    read_conf();

    if (!is_allowed(user_str)) {
        die("User \"%s\" is not allowed to use %s. Aborting.", user_str,
            prog_name);
    }

    /* we don't need anymore special rights : drop remaining ones */
#ifdef USE_SETE_ID
    setegid_safe(user_gid);
#endif
    if (setgid(user_gid) < 0)
        die_e("could not setgid() to %d", user_gid);

    /* check for broken pipes ... */
    signal(SIGPIPE, sigpipe_handler);

    if (cmd_str == NULL)
        return_code = interactive_mode(fd);
    else
        return_code = talk_fcron(cmd_str, fd);

    xexit((return_code == OK) ? EXIT_OK : EXIT_ERR);

    /* never reached */
    return EXIT_OK;

}
Exemple #15
0
Fichier : ldmd.c Projet : dgaer/LDM
int main(
        int ac,
        char* av[])
{
    const char* pqfname = getQueuePath();
    int status;
    int doSomething = 1;
    in_addr_t ldmIpAddr = (in_addr_t) htonl(INADDR_ANY );
    unsigned ldmPort = LDM_PORT;

    ensureDumpable();

    /*
     * deal with the command line, set options
     */
    {
        extern int optind;
        extern int opterr;
        extern char *optarg;
        int ch;
        int logmask = LOG_MASK(LOG_ERR) | LOG_MASK(LOG_WARNING)
                | LOG_MASK(LOG_NOTICE);

        opterr = 1;

        while ((ch = getopt(ac, av, "I:vxl:nq:o:P:M:m:t:")) != EOF) {
            switch (ch) {
            case 'I': {
                in_addr_t ipAddr = inet_addr(optarg);

                if ((in_addr_t) -1 == ipAddr) {
                    (void) fprintf(stderr, "Interface specification \"%s\" "
                            "isn't an IP address\n", optarg);
                    exit(1);
                }

                ldmIpAddr = ipAddr;

                break;
            }
            case 'v':
                logmask |= LOG_MASK(LOG_INFO);
                break;
            case 'x':
                logmask |= LOG_MASK(LOG_DEBUG);
                break;
            case 'l':
                logfname = optarg;
                break;
            case 'q':
                pqfname = optarg;
                setQueuePath(optarg);
                break;
            case 'o':
                toffset = atoi(optarg);
                if (toffset == 0 && *optarg != '0') {
                    (void) fprintf(stderr, "%s: invalid offset %s\n", av[0],
                            optarg);
                    usage(av[0]);
                }
                break;
            case 'P': {
                unsigned port;
                int      nbytes;
                if (sscanf(optarg, "%5u %n", &port, &nbytes) != 1 ||
                        0 != optarg[nbytes] || port > 0xffff) {
                    (void)fprintf(stderr, "%s: invalid port number: %s\n",
                            av[0], optarg);
                    usage(av[0]);
                }
                ldmPort = port;
                break;
            }
            case 'M': {
                int max = atoi(optarg);
                if (max < 0) {
                    (void) fprintf(stderr,
                            "%s: invalid maximum number of clients %s\n", av[0],
                            optarg);
                    usage(av[0]);
                }
                maxClients = max;
                break;
            }
            case 'm':
                max_latency = atoi(optarg);
                if (max_latency <= 0) {
                    (void) fprintf(stderr, "%s: invalid max_latency %s\n",
                            av[0], optarg);
                    usage(av[0]);
                }
                break;
            case 'n':
                doSomething = 0;
                break;
            case 't':
                rpctimeo = (unsigned) atoi(optarg);
                if (rpctimeo == 0 || rpctimeo > 32767) {
                    (void) fprintf(stderr, "%s: invalid timeout %s", av[0],
                            optarg);
                    usage(av[0]);
                }
                break;
            case '?':
                usage(av[0]);
                break;
            } /* "switch" statement */
        } /* argument loop */

        if (ac - optind == 1)
            setLdmdConfigPath(av[optind]);
        (void) setulogmask(logmask);

        if (toffset != TOFFSET_NONE && toffset > max_latency) {
            (void) fprintf(stderr,
                    "%s: invalid toffset (%d) > max_latency (%d)\n", av[0],
                    toffset, max_latency);
            usage(av[0]);
        }
    } /* command-line argument decoding */

    if (logfname != NULL && *logfname == '-') {
        /*
         * Logging to standard error stream. Assume interactive.
         *
         * Make this process a process group leader so that all child processes
         * (e.g., upstream LDM, downstream LDM, pqact(1)s) will be signaled by
         * `cleanup()`.
         */
        (void)setpgid(0, 0); // can't fail
    }
#ifndef DONTFORK
    else {
        /*
         * Logging to system logging daemon or file. Make this process a daemon.
         */
        pid_t pid;
        pid = ldmfork();
        if (pid == -1) {
            log_add("Couldn't fork LDM daemon");
            log_log(LOG_ERR);
            exit(2);
        }

        if (pid > 0) {
            /* parent */
            (void) printf("%ld\n", (long) pid);
            exit(0);
        }

        /* detach the child from parents process group ?? */
        (void) setsid(); // also makes this process a process group leader
    }
#endif

    /*
     * Initialize logger.
     * (Close fd 2 to remap stderr to the logfile, when
     * appropriate. I know, this is anal.)
     */
    if (logfname == NULL )
        (void) fclose(stderr);
    else if (!(logfname[0] == '-' && logfname[1] == 0))
        (void) close(2);
    (void) openulog(ubasename(av[0]), (LOG_CONS | LOG_PID), LOG_LDM, logfname);
    unotice("Starting Up (version: %s; built: %s %s)", PACKAGE_VERSION,
            __DATE__, __TIME__);

    /*
     * register exit handler
     */
    if (atexit(cleanup) != 0) {
        serror("atexit");
        unotice("Exiting");
        exit(1);
    }

    /*
     * set up signal handlers
     */
    set_sigactions();

    /*
     * Close the standard input and standard output streams because they won't
     * be used (more anality :-)
     */
    (void) fclose(stdout);
    (void) fclose(stdin);

    /*
     * Vet the configuration file.
     */
    udebug("main(): Vetting configuration-file");
    if (read_conf(getLdmdConfigPath(), 0, ldmIpAddr, ldmPort) != 0) {
        log_log(LOG_ERR);
        exit(1);
    }

    if (doSomething) {
        int sock = -1;

        if (lcf_isServerNeeded()) {
            /*
             * Create a service portal. This should be done before anything is
             * created because this is the function that relinquishes superuser
             * privileges.
             */
            udebug("main(): Creating service portal");
            if (create_ldm_tcp_svc(&sock, ldmIpAddr, ldmPort) != ENOERR) {
                /* error reports are emitted from create_ldm_tcp_svc() */
                exit(1);
            }
            udebug("tcp sock: %d", sock);
        }

        /*
         * Verify that the product-queue can be open for writing.
         */
        udebug("main(): Opening product-queue");
        if ((status = pq_open(pqfname, PQ_DEFAULT, &pq))) {
            if (PQ_CORRUPT == status) {
                uerror("The product-queue \"%s\" is inconsistent", pqfname);
            }
            else {
                uerror("pq_open failed: %s: %s", pqfname, strerror(status));
            }
            exit(1);
        }
        (void) pq_close(pq);
        pq = NULL;

        /*
         * Create the sharable database of upstream LDM metadata.
         */
        udebug("main(): Creating shared upstream LDM database");
        if ((status = uldb_delete(NULL))) {
            if (ULDB_EXIST == status) {
                log_clear();
            }
            else {
                LOG_ADD0(
                        "Couldn't delete existing shared upstream LDM database");
                log_log(LOG_ERR);
                exit(1);
            }
        }
        if (uldb_create(NULL, maxClients * 1024)) {
            LOG_ADD0("Couldn't create shared upstream LDM database");
            log_log(LOG_ERR);
            exit(1);
        }

        /*
         * Initialize the multicast sender map.
         */
#if WANT_MULTICAST
        if (msm_init()) {
            LOG_ADD0("Couldn't initialize multicast LDM sender map");
            log_log(LOG_ERR);
            exit(1);
        }
#endif

        /*
         * Re-read (and execute) the configuration file (downstream LDM-s are
         * started).
         */
        lcf_free(); // Start with a clean slate to prevent duplicates
        udebug("main(): Reading configuration-file");
        if (read_conf(getLdmdConfigPath(), 1, ldmIpAddr, ldmPort) != 0) {
            log_log(LOG_ERR);
            exit(1);
        }

        if (lcf_isServerNeeded()) {
            /*
             * Serve
             */
            udebug("main(): Serving socket");
            sock_svc(sock);
        }
        else {
            /*
             * Wait until all child processes have terminated.
             */
            while (reap(-1, 0) > 0)
                /* empty */;
        }
    }   // configuration-file will be executed

    return (0);
}
static int mount_fuse(const char *mnt, const char *opts, char *devfd)
{
	int res;
	int fd;
	char *dev;
	struct stat stbuf;
	char *type = NULL;
	char *source = NULL;
	char *mnt_opts = NULL;
	const char *real_mnt = mnt;
	int mountpoint_fd = -1;

	fd = devfd ? check_fuse_device(devfd, &dev) : open_fuse_device(&dev);
	if (fd == -1)
		return -1;

	drop_privs();
	read_conf();

	if (getuid() != 0 && mount_max != -1) {
		int mount_count = count_fuse_fs();
		if (mount_count >= mount_max) {
			fprintf(stderr, "%s: too many FUSE filesystems mounted; mount_max=N can be set in /etc/fuse.conf\n", progname);
			goto fail_close_fd;
		}
	}

	res = check_version(dev);
	if (res != -1) {
		res = check_perm(&real_mnt, &stbuf, &mountpoint_fd);
		restore_privs();
		if (res != -1)
			res = do_mount(real_mnt, &type, stbuf.st_mode & S_IFMT,
				       fd, opts, dev, &source, &mnt_opts,
				       stbuf.st_size);
	} else
		restore_privs();

	if (mountpoint_fd != -1)
		close(mountpoint_fd);

	if (res == -1)
		goto fail_close_fd;

	res = chdir("/");
	if (res == -1) {
		fprintf(stderr, "%s: failed to chdir to '/'\n", progname);
		goto fail_close_fd;
	}

	if (geteuid() == 0) {
		res = add_mount(source, mnt, type, mnt_opts);
		if (res == -1) {
			/* Can't clean up mount in a non-racy way */
			goto fail_close_fd;
		}
	}

out_free:
	free(source);
	free(type);
	free(mnt_opts);
	free(dev);

	return fd;

fail_close_fd:
	close(fd);
	fd = -1;
	goto out_free;
}
Exemple #17
0
static enum nss_status
_nss_map_setgrent_locked()
{
	map_conf_t *conf;
	char *dir;
	struct stat s;
	char *name;

	conf = read_conf();

	if (conf == NULL) {
		DEBUG("%s:%d:setgrent_r:unable to open configuration file (%s).\n",
				__FILE__, __LINE__, MAIN_CONF_FILE);
		return NSS_STATUS_UNAVAIL;
	}

	/* XXX: The logname hack */
	if ( (name = getenv("LOGNAME")) == NULL )
	{
		DEBUG("%s:%d:setgrent_r:environment LOGNAME is not set.\n",
				__FILE__, __LINE__);
		return NSS_STATUS_UNAVAIL;
	}

	if (( dir = (char *)malloc( (strlen(name) + 1 +
						strlen(conf->pw_dir)  + 1 +
						strlen(MAIN_CONF_FILE)) * sizeof(char) ) ) == NULL)
	{
		DEBUG("%s:%d:setgrent_r:unable to adquire memory for config.\n",
				__FILE__, __LINE__);
		return NSS_STATUS_TRYAGAIN;
	}

	strcpy(dir, conf->pw_dir);
	strcat(dir,"/");
	strcat(dir,name);
	strcat(dir,"/");
	strcat(dir,USER_CONF_FILE);

	free_conf(conf);

	/* some security checking */
	if ( stat(dir, &s) == -1 )
		goto format_error;

	if ( ! S_ISREG(s.st_mode) )
		goto format_error;

	if ( (s.st_mode & S_IWGRP) || (s.st_mode & S_IWOTH) )
		goto format_error;

	if ( (s.st_uid) || (s.st_gid) )
		goto format_error;

	g_file = fopen(dir, "r");

	if (g_file == NULL)
		goto format_error;

	return NSS_STATUS_SUCCESS;

format_error:
	if(g_file != NULL) fclose(g_file);
	free(dir);
    return NSS_STATUS_UNAVAIL;

}
Exemple #18
0
int
main (int argc, char *argv[])
{
    int i = 0;
    time_t t = 0;
    struct sigaction sa;
    unsigned long cachesize = 0;
    char *x = NULL, char_seed[128];

    sa.sa_handler = handle_term;
    sigaction (SIGINT, &sa, NULL);
    sigaction (SIGTERM, &sa, NULL);

    sa.sa_handler = SIG_IGN;
    sigaction (SIGPIPE, &sa, NULL);

    seed_addtime ();
    seed_adduint32 (getpid ());
    seed_adduint32 (getppid ());
    seed_adduint32 (getuid ());
    seed_adduint32 (getgid ());

    seed_addtime ();
    prog = strdup ((x = strrchr (argv[0], '/')) != NULL ?  x + 1 : argv[0]);
    i = check_option (argc, argv);
    argc -= i;
    argv += i;

    if (mode & DAEMON)
    {
        i = fork ();
        if (i == -1)
            err (-1, "could not fork a daemon process");
        if (i > 0)
            return 0;
    }

    time (&t);
    strftime (char_seed, sizeof (char_seed), "%b-%d %Y %T %Z", localtime (&t));
    warnx ("version %s: starting: %s\n", VERSION, char_seed);

    set_timezone ();
    if (debug_level)
        warnx ("TIMEZONE: %s", env_get ("TZ"));

    read_conf (CFGFILE);
    if (!debug_level)
        if ((x = env_get ("DEBUG_LEVEL")))
            debug_level = atol (x);
    warnx ("DEBUG_LEVEL set to `%d'", debug_level);

    if ((x = env_get ("DATALIMIT")))
    {
        struct rlimit r;
        unsigned long dlimit = atol (x);

        if (getrlimit (RLIMIT_DATA,  &r) != 0)
            err (-1, "could not get resource RLIMIT_DATA");

        r.rlim_cur = (dlimit <= r.rlim_max) ? dlimit : r.rlim_max;

        if (setrlimit (RLIMIT_DATA, &r) != 0)
            err (-1, "could not set resource RLIMIT_DATA");

        if (debug_level)
            warnx ("DATALIMIT set to `%ld' bytes", r.rlim_cur);
    }

    if (!(x = env_get ("IP")))
        err (-1, "$IP not set");
    if (!ip4_scan (x, myipincoming))
        err (-1, "could not parse IP address `%s'", x);

    seed_addtime ();
    udp53 = socket_udp ();
    if (udp53 == -1)
        err (-1, "could not open UDP socket");
    if (socket_bind4_reuse (udp53, myipincoming, 53) == -1)
        err (-1, "could not bind UDP socket");

    seed_addtime ();
    tcp53 = socket_tcp ();
    if (tcp53 == -1)
        err (-1, "could not open TCP socket");
    if (socket_bind4_reuse (tcp53, myipincoming, 53) == -1)
        err (-1, "could not bind TCP socket");

    if (mode & DAEMON)
    {
        /* redirect stdout & stderr to a log file */
        redirect_to_log (LOGFILE, STDOUT_FILENO | STDERR_FILENO);

        write_pid (PIDFILE);
    }

    seed_addtime ();
    droproot ();
    if (mode & DAEMON)
        /* crerate a new session & detach from controlling tty */
        if (setsid () < 0)
            err (-1, "could not start a new session for the daemon");

    seed_addtime ();
    socket_tryreservein (udp53, 131072);

    memset (char_seed, 0, sizeof (char_seed));
    for (i = 0, x = (char *)seed; (unsigned)i < sizeof (char_seed); i++, x++)
        char_seed[i] = *x;
    dns_random_init (char_seed);

    if (!(x = env_get ("IPSEND")))
        err (-1, "$IPSEND not set");
    if (!ip4_scan (x, myipoutgoing))
        err (-1, "could not parse IP address `%s'", x);

    if (!(x = env_get ("CACHESIZE")))
        err (-1, "$CACHESIZE not set");
    scan_ulong (x, &cachesize);
    if (!cache_init (cachesize))
        err (-1, "could not allocate `%ld' bytes for cache", cachesize);

    if (env_get ("HIDETTL"))
        response_hidettl ();
    if (env_get ("FORWARDONLY"))
        query_forwardonly ();
    if (env_get ("MERGEQUERIES"))
        dns_enable_merge (log_merge);
    if (!roots_init ())
        err (-1, "could not read servers");
    if (debug_level > 3)
        roots_display();
    if (socket_listen (tcp53, 20) == -1)
        err (-1, "could not listen on TCP socket");
    if (!dbl_init() && debug_level > 1)
        warnx ("could not read dnsbl.cdb");

    doit ();

    return 0;
}
Exemple #19
0
enum nss_status
_nss_map_initgroups_dyn (const char *user, gid_t group, long int *start,
		long int *size, gid_t **groupsp, long int limit, int *errnop)
{
	gid_t *groups = *groupsp;
	FILE *fp = NULL;
	map_conf_t *conf;
	char *dir;
	struct stat s;
	struct group *g;

	conf = read_conf();

	if (conf == NULL) {
		DEBUG("%s:%d:initgroups_dyn:unable to open configuration file (%s).\n",
				__FILE__, __LINE__, MAIN_CONF_FILE);
		return NSS_STATUS_UNAVAIL;
	}

	if (( dir = (char *)malloc( (strlen(user) + 1 +
						strlen(conf->pw_dir)  + 1 +
						strlen(MAIN_CONF_FILE)) * sizeof(char) ) ) == NULL)
	{
		DEBUG("%s:%d:initgroups_dyn:unable to adquire memory for config.\n",
				__FILE__, __LINE__);
		return NSS_STATUS_TRYAGAIN;
	}

	strcpy(dir, conf->pw_dir);
	strcat(dir,"/");
	strcat(dir,user);
	strcat(dir,"/");
	strcat(dir,USER_CONF_FILE);
	free_conf(conf);

	/* some security checking */
	if ( stat(dir, &s) == -1 )
		goto format_error;

	if ( ! S_ISREG(s.st_mode) )
		goto format_error;

	if ( (s.st_mode & S_IWGRP) || (s.st_mode & S_IWOTH) )
		goto format_error;

	if ( (s.st_uid) || (s.st_gid) )
		goto format_error;

	if ( (fp = fopen(dir, "r")) == NULL )
		goto format_error;

	if ( (g = fgetgrent(fp)) == NULL )
		goto format_error;
	else
		fclose(fp);

	if (!internal_gid_in_list (groups, group, *start))
	{
		if (__builtin_expect (*start == *size, 0))
		{
			/* Need a bigger buffer.  */
			gid_t *newgroups;
			long int newsize;

			if (limit > 0 && *size == limit)
				/* We reached the maximum.  */
				goto done;

			if (limit <= 0)
				newsize = 2 * *size;
			else
				newsize = MIN (limit, 2 * *size);

			newgroups = realloc (groups, newsize * sizeof (*groups));
			if (newgroups == NULL)
				goto done;
			*groupsp = groups = newgroups;
			*size = newsize;
		}

		groups[(*start)++] = group;
	}

	groups[(*start)++] = g->gr_gid;

done:
	return NSS_STATUS_SUCCESS;

format_error:
	if(fp != NULL) fclose(fp);
	free(dir);
    return NSS_STATUS_UNAVAIL;

}
Exemple #20
0
int main(int argc, char* argv[]) {
    int rc;
    int opt = 0;
    int options_index = 0;
    char *conf_file = CONF;

    /*
    * parse argv 
    * more detail visit: http://www.gnu.org/software/libc/manual/html_node/Getopt.html
    */

    if (argc == 1) {
        usage();
        return 0;
    }

    while ((opt=getopt_long(argc, argv,"Vc:?h",long_options,&options_index)) != EOF) {
        switch (opt) {
            case  0 : break;
            case 'c':
                conf_file = optarg;
                break;
            case 'V':
                printf(PROGRAM_VERSION"\n");
                return 0;
            case ':':
            case 'h':
            case '?':
                usage();
                return 0;
        }
    }

    debug("conffile = %s", conf_file);

    if (optind < argc) {
        log_err("non-option ARGV-elements: ");
        while (optind < argc)
            log_err("%s ", argv[optind++]);
        return 0;
    }

    /*
    * read confile file
    */
    char conf_buf[BUFLEN];
    zv_conf_t cf;
    rc = read_conf(conf_file, &cf, conf_buf, BUFLEN);
    check(rc == ZV_CONF_OK, "read conf err");

    /*
    *   install signal handle for SIGPIPE
    *   when a fd is closed by remote, writing to this fd will cause system send
    *   SIGPIPE to this process, which exit the program
    */
    struct sigaction sa;
    memset(&sa, '\0', sizeof(sa));
    sa.sa_handler = SIG_IGN;
    sa.sa_flags = 0;
    if (sigaction(SIGPIPE,&sa,NULL)) {
        log_err("install sigal handler for SIGPIPI failed");
        return 0;
    }

    /*
    * initialize listening socket
    */
    int listenfd;
    struct sockaddr_in clientaddr;
    // initialize clientaddr and inlen to solve "accept Invalid argument" bug
    socklen_t inlen = 1;
    memset(&clientaddr, 0, sizeof(struct sockaddr_in));  
    
    listenfd = open_listenfd(cf.port);
    rc = make_socket_non_blocking(listenfd);
    check(rc == 0, "make_socket_non_blocking");

    /*
    * create epoll and add listenfd to ep
    */
    int epfd = zv_epoll_create(0);
    struct epoll_event event;
    
    zv_http_request_t *request = (zv_http_request_t *)malloc(sizeof(zv_http_request_t));
    zv_init_request_t(request, listenfd, &cf);

    event.data.ptr = (void *)request;
    event.events = EPOLLIN | EPOLLET;
    zv_epoll_add(epfd, listenfd, &event);

    /*
    create thread pool
    */
    zv_threadpool_t *tp = threadpool_init(cf.thread_num);
    
    /* epoll_wait loop */
    while (1) {
        int n;
        n = zv_epoll_wait(epfd, events, MAXEVENTS, -1);
        
        int i, fd;
        for (i=0; i<n; i++) {
            zv_http_request_t *r = (zv_http_request_t *)events[i].data.ptr;
            fd = r->fd;
            
            if (listenfd == fd) {
                /* we hava one or more incoming connections */

                while(1) {
                    debug("## ready to accept");
                    int infd = accept(listenfd, (struct sockaddr *)&clientaddr, &inlen);
                    if (infd == -1) {
                        if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) {
                            /* we have processed all incoming connections */
                            break;
                        } else {
                            log_err("accept");
                            break;
                        }
                    }

                    rc = make_socket_non_blocking(infd);
                    check(rc == 0, "make_socket_non_blocking");
                    debug("new connection fd %d", infd);
                    
                    zv_http_request_t *request = (zv_http_request_t *)malloc(sizeof(zv_http_request_t));
                    if (request == NULL) {
                        log_err("malloc(sizeof(zv_http_request_t))");
                        break;
                    }

                    zv_init_request_t(request, infd, &cf);
                    event.data.ptr = (void *)request;
                    event.events = EPOLLIN | EPOLLET;

                    zv_epoll_add(epfd, infd, &event);
                }   // end of while of accept

                debug("## end accept");
            } else {
                if ((events[i].events & EPOLLERR) ||
                    (events[i].events & EPOLLHUP) ||
                    (!(events[i].events & EPOLLIN))) {
                    log_err("epoll error fd: %d", r->fd);
                    close(fd);
                    continue;
                }
                /*
                do_request(infd);
                close(infd);
                */
                log_info("new task from fd %d", fd);
                rc = threadpool_add(tp, do_request, events[i].data.ptr);
                check(rc == 0, "threadpool_add");
            }
        }   //end of for
    }   // end of while(1)
    return 0;
}
Exemple #21
0
int main(
        int ac,
        char* av[])
{
    const char* pqfname = getQueuePath();
    int sock = -1;
    int status;
    int doSomething = 1;
    in_addr_t locIpAddr = (in_addr_t) htonl(INADDR_ANY );
    unsigned ldmPort = LDM_PORT;

    ensureDumpable();

    /*
     * deal with the command line, set options
     */
    {
        extern int optind;
        extern int opterr;
        extern char *optarg;
        int ch;
        int logmask = LOG_MASK(LOG_ERR) | LOG_MASK(LOG_WARNING)
                | LOG_MASK(LOG_NOTICE);

        opterr = 1;

        while ((ch = getopt(ac, av, "I:vxl:nq:o:P:M:m:t:")) != EOF) {
            switch (ch) {
            case 'I': {
                in_addr_t ipAddr = inet_addr(optarg);

                if ((in_addr_t) -1 == ipAddr) {
                    (void) fprintf(stderr, "Interface specification \"%s\" "
                            "isn't an IP address\n", optarg);
                    exit(1);
                }

                locIpAddr = ipAddr;

                break;
            }
            case 'v':
                logmask |= LOG_MASK(LOG_INFO);
                break;
            case 'x':
                logmask |= LOG_MASK(LOG_DEBUG);
                break;
            case 'l':
                logfname = optarg;
                break;
            case 'q':
                pqfname = optarg;
                setQueuePath(optarg);
                break;
            case 'o':
                toffset = atoi(optarg);
                if (toffset == 0 && *optarg != '0') {
                    (void) fprintf(stderr, "%s: invalid offset %s\n", av[0],
                            optarg);
                    usage(av[0]);
                }
                break;
            case 'P': {
                char* suffix = "";
                long port;

                errno = 0;
                port = strtol(optarg, &suffix, 0);

                if (0 != errno || 0 != *suffix || 0 >= port || 0xffff < port) {

                    (void) fprintf(stderr, "%s: invalid port %s\n", av[0],
                            optarg);
                    usage(av[0]);
                }

                ldmPort = (unsigned) port;

                break;
            }
            case 'M': {
                int max = atoi(optarg);
                if (max < 0) {
                    (void) fprintf(stderr,
                            "%s: invalid maximum number of clients %s\n", av[0],
                            optarg);
                    usage(av[0]);
                }
                maxClients = max;
                break;
            }
            case 'm':
                max_latency = atoi(optarg);
                if (max_latency <= 0) {
                    (void) fprintf(stderr, "%s: invalid max_latency %s\n",
                            av[0], optarg);
                    usage(av[0]);
                }
                break;
            case 'n':
                doSomething = 0;
                break;
            case 't':
                rpctimeo = (unsigned) atoi(optarg);
                if (rpctimeo == 0 || rpctimeo > 32767) {
                    (void) fprintf(stderr, "%s: invalid timeout %s", av[0],
                            optarg);
                    usage(av[0]);
                }
                break;
            case '?':
                usage(av[0]);
                break;
            } /* "switch" statement */
        } /* argument loop */

        if (ac - optind == 1)
            setLdmdConfigPath(av[optind]);
        (void) setulogmask(logmask);

        if (toffset != TOFFSET_NONE && toffset > max_latency) {
            (void) fprintf(stderr,
                    "%s: invalid toffset (%d) > max_latency (%d)\n", av[0],
                    toffset, max_latency);
            usage(av[0]);
        }
    } /* command-line argument decoding */

#ifndef DONTFORK
    /* 
     * daemon behavior
     *
     * Background the process unless we are logging to stderr, in which
     * case we assume interactive.
     */
    if (logfname == NULL || *logfname != '-') {
        /* detach */
        pid_t pid;
        pid = ldmfork();
        if (pid == -1) {
            log_add("Couldn't fork LDM daemon");
            log_log(LOG_ERR);
            exit(2);
        }

        if (pid > 0) {
            /* parent */
            (void) printf("%ld\n", (long) pid);
            exit(0);
        }

        /* detach the child from parents process group ?? */
        (void) setsid();
    }
#endif

    /*
     * Initialize logger.
     * (Close fd 2 to remap stderr to the logfile, when
     * appropriate. I know, this is anal.)
     */
    if (logfname == NULL )
        (void) fclose(stderr);
    else if (!(logfname[0] == '-' && logfname[1] == 0))
        (void) close(2);
    (void) openulog(ubasename(av[0]), (LOG_CONS | LOG_PID), LOG_LDM, logfname);
    unotice("Starting Up (version: %s; built: %s %s)", PACKAGE_VERSION,
            __DATE__, __TIME__);

    /*
     * register exit handler
     */
    if (atexit(cleanup) != 0) {
        serror("atexit");
        unotice("Exiting");
        exit(1);
    }

    /*
     * set up signal handlers
     */
    set_sigactions();

    /*
     * Close the standard input and standard output streams because they won't
     * be used (more anality :-)
     */
    (void) fclose(stdout);
    (void) fclose(stdin);

    if (!doSomething) {
        /*
         * Vet the configuration file.
         */
        udebug("main(): Vetting configuration-file");
        if (read_conf(getLdmdConfigPath(), doSomething, ldmPort) != 0) {
            log_log(LOG_ERR);
            exit(1);
        }
    }
    else {
        /*
         * Create a service portal. This should be done before anything is
         * created because this is the function that relinquishes superuser
         * privileges.
         */
        udebug("main(): Creating service portal");
        if (create_ldm_tcp_svc(&sock, locIpAddr, ldmPort) != ENOERR) {
            /* error reports are emitted from create_ldm_tcp_svc() */
            exit(1);
        }
        udebug("tcp sock: %d", sock);

        /*
         * Verify that the product-queue can be open for writing.
         */
        udebug("main(): Opening product-queue");
        if (status = pq_open(pqfname, PQ_DEFAULT, &pq)) {
            if (PQ_CORRUPT == status) {
                uerror("The product-queue \"%s\" is inconsistent", pqfname);
            }
            else {
                uerror("pq_open failed: %s: %s", pqfname, strerror(status));
            }
            exit(1);
        }
        (void) pq_close(pq);
        pq = NULL;

        /*
         * Create the sharable database of upstream LDM metadata.
         */
        udebug("main(): Creating shared upstream LDM database");
        if (status = uldb_delete(NULL)) {
            if (ULDB_EXIST == status) {
                log_clear();
            }
            else {
                LOG_ADD0(
                        "Couldn't delete existing shared upstream LDM database");
                log_log(LOG_ERR);
                exit(1);
            }
        }
        if (uldb_create(NULL, maxClients * 1024)) {
            LOG_ADD0("Couldn't create shared upstream LDM database");
            log_log(LOG_ERR);
            exit(1);
        }

        /*
         * Read the configuration file (downstream LDM-s are started).
         */
        udebug("main(): Reading configuration-file");
        if (read_conf(getLdmdConfigPath(), doSomething, ldmPort) != 0) {
            log_log(LOG_ERR);
            exit(1);
        }

        /*
         * Serve
         */
        udebug("main(): Serving socket");
        sock_svc(sock);
    } /* "doSomething" is true */

    return (0);
}
Exemple #22
0
int use_conf(char *test_path)
{
    int ret;
    size_t flags = 0;
    char filename[1024], errstr[1024];
    char *buffer;
    FILE *infile, *conffile;
    json_t *json;
    json_error_t error;

    sprintf(filename, "%s%cinput", test_path, dir_sep);
    if (!(infile = fopen(filename, "rb"))) {
        fprintf(stderr, "Could not open \"%s\"\n", filename);
        return 2;
    }

    sprintf(filename, "%s%cenv", test_path, dir_sep);
    conffile = fopen(filename, "rb");
    if (conffile) {
        read_conf(conffile);
        fclose(conffile);
    }

    if (conf.indent < 0 || conf.indent > 255) {
        fprintf(stderr, "invalid value for JSON_INDENT: %d\n", conf.indent);
        return 2;
    }

    if (conf.indent)
        flags |= JSON_INDENT(conf.indent);

    if (conf.compact)
        flags |= JSON_COMPACT;

    if (conf.ensure_ascii)
        flags |= JSON_ENSURE_ASCII;

    if (conf.preserve_order)
        flags |= JSON_PRESERVE_ORDER;

    if (conf.sort_keys)
        flags |= JSON_SORT_KEYS;

    if (conf.strip) {
        /* Load to memory, strip leading and trailing whitespace */
        buffer = loadfile(infile);
        json = json_loads(strip(buffer), 0, &error);
        free(buffer);
    }
    else
        json = json_loadf(infile, 0, &error);

    fclose(infile);

    if (!json) {
        sprintf(errstr, "%d %d %d\n%s\n",
                error.line, error.column, error.position,
                error.text);

        ret = cmpfile(errstr, test_path, "error");
        return ret;
    }

    buffer = json_dumps(json, flags);
    ret = cmpfile(buffer, test_path, "output");
    free(buffer);
    json_decref(json);

    return ret;
}
Exemple #23
0
int init()
{
  int i,j,k;
  /******************************************************
   * Variables assignments (ALL INITIAL VALUES)
   * ****************************************************/
  p_mynum = &mynum;
  p_mu = &mu;
  /***********************
   * Menu prompts
   * *********************/
  main_prompt = "";
  numerics_prompt = "numerics";
  graphics_prompt = "graphics";
  cross_prompt = "cross";
  periodics_prompt = "periodics";
  file_prompt = "file";
  cont_prompt = "continue";
  rand_prompt = "random";
  errors_prompt = "errors";
  sing_prompt = "singularity";
  traj_prompt = "trajectory";
  /* *********************** */
  /* Submenu prompts */
  /* *********************** */
  /* Histogram submenu of periodics menu */
  periodics_hist_prompt = (char *)malloc((strlen(periodics_prompt) +		\
				     strlen("/histogram")+2)*sizeof(char));
  periodics_hist_prompt = strcpy(periodics_hist_prompt,periodics_prompt);
  periodics_hist_prompt = strcat(periodics_hist_prompt,"/histogram");
  gnuplot_prompt = "gnuplot('q' to exit)";
  /* End of histogram submenu */
  /* Menu buffers */
  /* History buffers */
  buf_hist = (char ***)malloc(MAX_N_HIST_ENT*sizeof(char **));
  for(i=0;i<MAX_N_HIST_ENT;i++){
    buf_hist[i] = (char **)malloc(MAX_N_ARG*sizeof(char *));
    for(j=0;j<MAX_N_ARG;j++)
      buf_hist[i][j] = (char *)calloc(MAX_ARG_LEN,sizeof(char));
  }
  /* Commands and their arguments. See read_menu(...) function. */
  cmd = (char **)malloc(MAX_N_ARG*sizeof(char *));
  for(i=0;i<MAX_N_ARG;i++)/* We allocate memory for all possible arguments */
    cmd[i] = (char *)calloc(MAX_ARG_LEN,sizeof(char));
  /*Loading constants and parameters from the file --- conf_name. */
  if(strlen(conf_name) != 0) 
    if((read_conf(conf_name)) == -1)/*read_config is the binary conf file~(.bcf)*/
      fprintf(stdout,"Config file: could not open the file.\n");
  /*************************************/
  /*Converting new style entities to old one for compatibility*/
  if((fmod((double)DIM,(double)LDIM))>0.5){
    /*If reminder of DIM/LDIM == 1 or more than it is wrongly defined
      system.*/
    /*DIM comes from number of ODEs.
      LDIM is specified by the user in #system directive of ode
      file.*/
    /*Error in ODE system specification*/
    fprintf(stderr,"Fatal: not symmetric ODE system\n");
    return 151;
  }
  /*New style -> old style converter*/
  mynum.total_dim = LDIM;
  mynum.local_dim = (int)DIM/LDIM;
  mynum.num_par = PARDIM;
  if((strlen(method) >= METH_NAME_LEN) || (strlen(method2) >= METH_NAME_LEN)){
    fprintf(stderr,"Error: method has a very long name.\n");
    fprintf(stderr,"Max allowed length is %d.\n",METH_NAME_LEN-1);
    return 143;
  }
  strncpy(mynum.method,method,(size_t)strlen(method));
  strncpy(mynum.method2,method2,(size_t)strlen(method2));
  /********************************************
  Initializing values
  *********************************************/
  mynum.global_buffer = BUFFER;/*Reading default*/
  xs = (double **)calloc(BUFFER,sizeof(double *));
  for(i=0;i<BUFFER;i++){
    xs[i] = (double *)calloc(DIM,sizeof(double));
  }
  ts = (double *)calloc(BUFFER,sizeof(double));
  //ampl = (double *)calloc(DIM,sizeof(double));
  //max_x = (double *)calloc(DIM,sizeof(double));
  //min_x = (double *)calloc(DIM,sizeof(double));
  x_cross = (double *)calloc(DIM,sizeof(double));
  /* Vars */
  y = (long int *)malloc(DIM*sizeof(long int));
  x = (double *)malloc(DIM*sizeof(double));
  f = (double *)malloc(DIM*sizeof(double));
  for(i=0;i<DIM;i++){
    x[i] = xin[i];
    y[i] = yin[i];
  }
  ksi = (double *)malloc(DIM*sizeof(double));/*Noise is zero*/
  /* Propensities */
  pr = (double *)malloc(NREAC*sizeof(double));
  /* Auxillaries */
  a = (double *)malloc(AUXNUM*sizeof(double));
  /************************************************************/
  /*RANDOM number parameters initialization...*/
  random_init();
  /*CONTINUATION parameters intitialization...*/
  cont_init();
  /*ROOT FINDING parameters initialization...*/
  multiroot_init();
  /*Lyapunov parameters initialization...*/
  lyap_init();
  /* Graphics init */
  init_graph();
  /* periods histogram init */
  thist_init();
  /* T-system init */
  traj_init();
  //******************************************************
  // Loading init. conditions from the file -- init_name.
  if(strlen(init_name) != 0){
    FILE *init;
    init = fopen(init_name,"r");
    if(init == NULL){
      fprintf(stdout,"Cannot open file with initial conditions.\n");}
    else{
      j = 1;
      while(j<=DIM) {
	fscanf(init,"%lf",&x[j-1]);
	y[j-1] = (long int)x[j-1];/*discrete*/
	j += 1;
      }
      fprintf(stdout,"Initial points\n");
      j = 1;
      while(j<=DIM){
	xin[j-1] = x[j-1];
	yin[j-1] = y[j-1];
	fprintf(stdout,"%lf\n",xin[j-1]);
	j += 1;
      }
      fclose(init);
    }
  }

  return 0;
}
Exemple #24
0
static int mount_fuse(const char *mnt, const char *opts)
{
    int res;
    int fd;
    char *dev;
    struct stat stbuf;
    char *type = NULL;
    char *source = NULL;
    char *mnt_opts = NULL;
    const char *real_mnt = mnt;
    int currdir_fd = -1;
    int mountpoint_fd = -1;

    fd = open_fuse_device(&dev);
    if (fd == -1)
        return -1;

    drop_privs();
    read_conf();

    if (getuid() != 0 && mount_max != -1) {
        int mount_count = count_fuse_fs();
        if (mount_count >= mount_max) {
            fprintf(stderr, "%s: too many FUSE filesystems mounted; mount_max=N can be set in /etc/fuse.conf\n", progname);
            close(fd);
            return -1;
        }
    }

    res = check_version(dev);
    if (res != -1) {
        res = check_perm(&real_mnt, &stbuf, &currdir_fd, &mountpoint_fd);
        restore_privs();
        if (res != -1)
            res = do_mount(real_mnt, &type, stbuf.st_mode & S_IFMT, fd, opts,
                           dev, &source, &mnt_opts, stbuf.st_size);
    } else
        restore_privs();

    if (currdir_fd != -1) {
        fchdir(currdir_fd);
        close(currdir_fd);
    }
    if (mountpoint_fd != -1)
        close(mountpoint_fd);

    if (res == -1) {
        close(fd);
        return -1;
    }

    if (geteuid() == 0) {
        res = add_mount(source, mnt, type, mnt_opts);
        if (res == -1) {
            umount2(mnt, 2); /* lazy umount */
            close(fd);
            return -1;
        }
    }

    free(source);
    free(type);
    free(mnt_opts);
    free(dev);

    return fd;
}
Exemple #25
0
int main()
{
  cout<<"Effective confs: "<<nconfs<<endl;
  
  fin=open_file("rende_new","r");
  vector<pair<vector<int>,string>> full_Tr_map(nfull_Tr);
  
  //prepare all maps
  DEF_MAP_1(M_dM);
  DEF_MAP_1(M_d2M);
  DEF_MAP_1(M_dM_M_dM);
  DEF_MAP_1(M_d3M);
  DEF_MAP_1(M_dM_M_d2M);
  DEF_MAP_1(M_dM_M_dM_M_dM);
  DEF_MAP_1(M_d2M_M_d2M);
  DEF_MAP_1(M_d2M_M_dM_M_dM);
  DEF_MAP_1(M_dM_M_dM_M_dM_M_dM);
  DEF_MAP_2(M_dM,M_dM);
  DEF_MAP_2(M_dM,M_dM_M_dM);
  DEF_MAP_2(M_dM,M_d2M);
  DEF_MAP_3(M_dM,M_dM,M_dM);
  DEF_MAP_2(M_dM,M_dM_M_d2M);
  DEF_MAP_2(M_d2M,M_dM_M_dM);
  DEF_MAP_2(M_dM_M_dM,M_dM_M_dM);
  DEF_MAP_2(M_dM_M_dM_M_dM,M_dM);
  DEF_MAP_2(M_d2M,M_d2M);
  DEF_MAP_3(M_dM_M_dM,M_dM,M_dM);
  DEF_MAP_3(M_d2M,M_dM,M_dM);
  DEF_MAP_4(M_dM,M_dM,M_dM,M_dM);
  
  //read all flavour, confs and take all trace products conf by conf
  for(int iconf=0;iconf<nconfs;iconf++)
    {
      const int ijack=iconf/clust_size;
      
      read_conf();
      
      for(int iflav=0;iflav<nflavs;iflav++)
  	for(int ifull=0;ifull<nfull_Tr;ifull++)
  	  full_Tr[ind_full(iflav,ifull)][ijack]+=
  	    Tr(full_Tr_map[ifull].first,iflav).real();
      
  //     dcompl a=0;
  //     double nc=0;
  //     for(int icopy=0;icopy<ncopies;icopy++)
  //     	for(int jcopy=icopy+1;jcopy<ncopies;jcopy++)
  //     	   for(int kcopy=jcopy+1;kcopy<ncopies;kcopy++)
  // 	     for(int lcopy=kcopy+1;lcopy<ncopies;lcopy++)
  // 	     {
  // 	       a+=
  // 		 base_Tr[ind(0,M_dM,icopy)]*
  // 		 base_Tr[ind(0,M_dM,jcopy)]*
  // 		 base_Tr[ind(0,M_dM,kcopy)]*
  // 		 base_Tr[ind(0,M_dM,lcopy)];
  // 	       nc+=1;
  //     	      }
      
  //     double ex=a.real()/nc;
  //     double al=full_Tr[ind_full(0,Tr_M_dM_Tr_M_dM_Tr_M_dM_Tr_M_dM)][iconf];
  //     cout<<"exact: "<<ex<<", algo: "<<al<<", rel diff: "<<(ex-al)/(ex+al)<<", nc: "<<nc<<" "<<((1.0)*(nconfs)*(ncopies)*(ncopies-1)*(ncopies-2)*(ncopies-3))<<endl;
    }
  
  //close and clusterize
  fclose(fin);
  full_Tr.clusterize(clust_size);
  
  for(int ifull=0;ifull<nfull_Tr;ifull++)
    cout<<full_Tr_map[ifull].second<<" ("<<Tr_get_nperm(full_Tr_map[ifull].first)<<" "<<Tr_get_mult(full_Tr_map[ifull].first)<<") = "<<fTr(ifull)<<endl;
  
  //compute susc2
  jack susc2_disc=(fTr(Tr_M_dM_Tr_M_dM)-sqr(fTr(Tr_M_dM)))/(16*V4);
  jack susc2_conn=(fTr(Tr_M_d2M)-fTr(Tr_M_dM_M_dM))/(4*V4);
  jack susc2_tot=susc2_conn+susc2_disc;
  
  jack susc4=
    -6*fTr(Tr_M_dM_M_dM_Tr_M_dM_Tr_M_dM)/64
    +1*fTr(Tr_M_dM_Tr_M_dM_Tr_M_dM_Tr_M_dM)/256
    +6*fTr(Tr_M_d2M_Tr_M_dM_Tr_M_dM)/64
    -3*fTr(Tr_M_dM_Tr_M_dM)*fTr(Tr_M_d2M)/64
    +3*fTr(Tr_M_dM_Tr_M_dM)*fTr(Tr_M_dM_M_dM)/64
    -3*fTr(Tr_M_dM_Tr_M_dM)*fTr(Tr_M_dM_Tr_M_dM)/256
    -6*fTr(Tr_M_d2M_Tr_M_dM_M_dM)/16
    +3*fTr(Tr_M_dM_M_dM_Tr_M_dM_M_dM)/16
    +1*fTr(Tr_M_dM_M_dM_M_dM_Tr_M_dM)/2
    +1*fTr(Tr_M_dM_Tr_M_dM)/16
    +3*fTr(Tr_M_d2M_Tr_M_d2M)/16
    -33*fTr(Tr_M_dM_Tr_M_dM_M_d2M)/64
    -3*fTr(Tr_M_d2M)*fTr(Tr_M_d2M)/16
    +3*fTr(Tr_M_d2M)*fTr(Tr_M_dM_M_dM)/16
    -3*fTr(Tr_M_d2M)*fTr(Tr_M_dM_Tr_M_dM)/64
    -3*fTr(Tr_M_d2M_M_d2M)/4
    +3*fTr(Tr_M_d2M_M_dM_M_dM)/1
    -1*fTr(Tr_M_dM_M_dM)/1
    -3*fTr(Tr_M_dM_M_dM_M_dM_M_dM)/2
    +1*fTr(Tr_M_d2M)/4
    +3*fTr(Tr_M_dM_M_dM)*fTr(Tr_M_d2M)/16
    -3*fTr(Tr_M_dM_M_dM)*fTr(Tr_M_dM_M_dM)/16
    +3*fTr(Tr_M_dM_M_dM)*fTr(Tr_M_dM_Tr_M_dM)/64;
  
  susc4/=V4*Nt*Nt;
  
  cout<<"susc2 = "<<susc2_tot<<endl;
  cout<<"susc4 = "<<susc4<<endl;
  
  return 0;
}
Exemple #26
0
int main( int argc, char **argv )
{
	int n, i;
	char *com;

	fp_err = stderr;

	init_conf();

	com = argv[0];
	--argc;  ++argv;
	while( argc > 0 && argv[0][0] == '-' )  {
		switch( argv[0][1] )  {
		case 'C':
			if( argc < 2 )  usage( com );
			read_conf( argv[1] );
			--argc;  ++argv;
			break;
		/*******↓for server mode *******/
		case 'p':
   		        /* 引数が不正な場合はエラー出力 */
			if( argc < 2 )  usage( com );
			/* ポート番号の読み込み */
			i = atoi( argv[1] );
			if (i > 1024) {
			        nPort = i;
			}
			s_mode = 1;
			--argc;  ++argv;
			break;
		/*******↑***********************/
		case 'v':
			printf( "%s\n", moduleVersion );
			printf( "%s\n", protocolVersion );
			exit(0);
		default:
			usage( com );
		}
		--argc;  ++argv;
	}
	set_default_conf();

	initialize();

	n = setjmp( ebuf );

	if( n > 0 )  chasen_process = 0;	/* to restart 'chasen' process */

	for( ;; )  {
#ifdef PRINTDATA
		TmpMsg( "> " );
#endif
		n_arg = read_command( v_arg );

#ifdef PRINTDATA
		{
			int i;
			TmpMsg( "command is \n" );
			for( i=0; i<n_arg; ++i )  {
				TmpMsg( "  %d: %s\n", i+1, v_arg[i] );
			}
		}
#endif

		/* 「o」 で set Speak = NOW のショートカット */
		if( strcmp(v_arg[0],"o")==0 )  {
			setSpeak( "=", "NOW" );
			continue;
		}

		if( n_arg < 2 )  { unknown_com();  continue; }

		switch( commandID( v_arg[0] ) )  {
		  case C_set:
			if( n_arg < 4 )  { unknown_com();  break; }
			switch( slotID( v_arg[1] ) )  {
			  case S_Run:   setRun( v_arg[2], v_arg[3] );  break;
			  case S_Speaker:  setSpeaker( v_arg[2], v_arg[3] );  break;
			  case S_Alpha: setAlpha( v_arg[2], v_arg[3] );  break;
			  case S_Postfilter_coef: setPostfilter_coef( v_arg[2], v_arg[3] );  break;
			  case S_Text:  setText( v_arg[2], v_arg[3] );  break;
			  case S_Speak: setSpeak( v_arg[2], v_arg[3] );  break;

			  case S_SaveRAW: setSave( v_arg[2], v_arg[3] );  break;
			  case S_Save:    setSave( v_arg[2], v_arg[3] );  break;
			  case S_LoadRAW: setSpeechFile( v_arg[2], v_arg[3], RAW );  break;
			  case S_SpeechFile: setSpeechFile( v_arg[2], v_arg[3], RAW );  break;
			  case S_SaveWAV: setSaveWAV( v_arg[2], v_arg[3] );  break;
			  case S_LoadWAV: setSpeechFile( v_arg[2], v_arg[3], WAV );  break;

			  case S_SavePros:  setSavePros( v_arg[2], v_arg[3] );  break;
			  case S_LoadPros:  setProsFile( v_arg[2], v_arg[3] );  break;
			  case S_ProsFile:  setProsFile( v_arg[2], v_arg[3] );  break;

			  case S_ParsedText: setParsedText( v_arg[2], v_arg[3] );  break;
			  case S_Speak_syncinterval: setSpeakSyncinterval( v_arg[2], v_arg[3] );  break;
			  case S_AutoPlay: 
				slot_Auto_play = setLogYesNo( v_arg[2], v_arg[3] ); break;
			  case S_AutoPlayDelay: 
				slot_Auto_play_delay = atoi( v_arg[3] ); break;
			  case S_Log:   setLog( v_arg[2], v_arg[3] ); break;
			  case S_Log_conf:
				slot_Log_conf = setLogYesNo( v_arg[2], v_arg[3] ); break;
			  case S_Log_text:
				slot_Log_text = setLogYesNo( v_arg[2], v_arg[3] ); break;
			  case S_Log_arranged_text:
				slot_Log_arranged_text = setLogYesNo( v_arg[2], v_arg[3] ); break;
			  case S_Log_chasen:
				slot_Log_chasen = setLogYesNo( v_arg[2], v_arg[3] ); break;
			  case S_Log_tag:
				slot_Log_tag = setLogYesNo( v_arg[2], v_arg[3] ); break;
			  case S_Log_phoneme:
				slot_Log_phoneme = setLogYesNo( v_arg[2], v_arg[3] ); break;
			  case S_Log_mora:
				slot_Log_mora = setLogYesNo( v_arg[2], v_arg[3] ); break;
			  case S_Log_morph:
				slot_Log_morph = setLogYesNo( v_arg[2], v_arg[3] ); break;
			  case S_Log_aphrase:
				slot_Log_aphrase = setLogYesNo( v_arg[2], v_arg[3] ); break;
			  case S_Log_breath:
				slot_Log_breath = setLogYesNo( v_arg[2], v_arg[3] ); break;
			  case S_Log_sentence:
				slot_Log_sentence = setLogYesNo( v_arg[2], v_arg[3] ); break;
			  case S_Err:          setErr( v_arg[2], v_arg[3] ); break;
			  default:
				unknown_com();
			}
			break;
		  case C_inq:
			switch( slotID( v_arg[1] ) ) {
			  case S_Run:        inqRun();  break;
			  case S_ModuleVersion: inqModuleVersion();  break;
			  case S_ProtocolVersion: inqProtocolVersion();  break;
			  case S_SpeakerSet: inqSpeakerSet();  break;
			  case S_Speaker:    inqSpeaker();  break;
			  case S_SpeechFile: inqSpeechFile();  break;
			  case S_ProsFile:   inqProsFile();  break;
			  case S_AutoPlay:   inqAutoPlay();  break;
			  case S_AutoPlayDelay:   inqAutoPlayDelay();  break;
			  case S_Text_text:  inqTextText();  break;
			  case S_Text_pho:   inqTextPho();  break;
			  case S_Text_dur:   inqTextDur();  break;
			  case S_Speak_text: inqSpeakText();  break;
			  case S_Speak_pho:  inqSpeakPho();  break;
			  case S_Speak_dur:  inqSpeakDur();  break;
			  case S_Speak_utt:  inqSpeakUtt();  break;
			  case S_Speak_len:  inqSpeakLen();  break;
			  case S_Speak_stat: inqSpeakStat();  break;
			  case S_Speak_syncinterval: inqSpeakSyncinterval();  break;
			  case S_Log:
				RepMsg( "rep Log = %s\n", slot_Log_file );  break;
			  case S_Log_conf:
				RepMsg( "rep Log.conf = %s\n", YesNoSlot(S_Log_conf) );  break;
			  case S_Log_text:
				RepMsg( "rep Log.text = %s\n", YesNoSlot(S_Log_text) );  break;
			  case S_Log_arranged_text:
				RepMsg( "rep Log.arranged_text = %s\n", YesNoSlot(S_Log_arranged_text) );  break;
			  case S_Log_chasen:
				RepMsg( "rep Log.chasen = %s\n", YesNoSlot(S_Log_chasen) );  break;
			  case S_Log_tag:
				RepMsg( "rep Log.tag = %s\n", YesNoSlot(S_Log_tag) );  break;
			  case S_Log_phoneme:
				RepMsg( "rep Log.phoneme = %s\n", YesNoSlot(S_Log_phoneme) );  break;
			  case S_Log_mora:
				RepMsg( "rep Log.mora = %s\n", YesNoSlot(S_Log_mora) );  break;
			  case S_Log_morph:
				RepMsg( "rep Log.morph = %s\n", YesNoSlot(S_Log_morph) );  break;
			  case S_Log_aphrase:
				RepMsg( "rep Log.aphrase = %s\n", YesNoSlot(S_Log_aphrase) );  break;
			  case S_Log_breath:
				RepMsg( "rep Log.breath = %s\n", YesNoSlot(S_Log_breath) );  break;
			  case S_Log_sentence:
				RepMsg( "rep Log.sentence = %s\n", YesNoSlot(S_Log_sentence) );  break;
			  case S_Err:
				RepMsg( "rep Err = %s\n", slot_Err_file );  break;
			  default:
				unknown_com();
			}
			break;
		  case C_prop:
			{ SlotProp prop;
			if( strcmp(v_arg[2],"=")!=0 )  { unknown_com(); break; }
			if( strcmp(v_arg[3],"AutoOutput")==0 )  {
				prop = AutoOutput;
			} else if(strcmp(v_arg[3],"NoAutoOutput")==0 )  {
				prop = NoAutoOutput;
			} else {
				unknown_com(); break;
			}
			switch( slotID( v_arg[1] ) ) {
			  case S_Run:        prop_Run = prop;  break;
			  case S_ModuleVersion: prop_ModuleVersion = prop;  break;
			  case S_ProtocolVersion: prop_ProtocolVersion = prop;  break;
			  case S_SpeakerSet: prop_SpeakerSet = prop;  break;
			  case S_Speaker:    prop_Speaker = prop;  break;
			  case S_SpeechFile: prop_SpeechFile = prop;  break;
			  case S_ProsFile:   prop_ProsFile = prop;  break;
			  case S_Text:       prop_Text = prop;  break;
			  case S_Text_text:  prop_Text_text = prop;  break;
			  case S_Text_pho:   prop_Text_pho = prop;  break;
			  case S_Text_dur:   prop_Text_dur = prop;  break;
			  case S_Speak:      prop_Speak = prop;  break;
			  case S_Speak_text: prop_Speak_text = prop;  break;
			  case S_Speak_pho:  prop_Speak_pho = prop;  break;
			  case S_Speak_dur:  prop_Speak_dur = prop;  break;
			  case S_Speak_utt:  prop_Speak_utt = prop;  break;
			  case S_Speak_len:  prop_Speak_len = prop;  break;
			  case S_Speak_stat: prop_Speak_stat = prop;  break;
			  case S_Speak_syncinterval: prop_Speak_syncinterval = prop;  break;
			  default:
				unknown_com();
			}
			}
			break;
		  default:
			unknown_com();
		}
	}
	
	if( s_mode ) {
	        server_destroy ();
	}
	exit(0);
}
Exemple #27
0
Fichier : conf.c Projet : kdrx/sans
/*
 * @func parse_args()
 * @desc parse command line parameters
 */
int parse_args(int argc, char **argv, conf_t *conf)
{
    const char *conf_file = NULL;

    bzero(conf, sizeof(conf_t));

    for (int i = 1; i < argc; i++)
    {
        if ((strcmp(argv[i], "-h") == 0) || (strcmp(argv[i], "--help") == 0))
        {
            help();
            return -1;
        }
        else if ((strcmp(argv[i], "-c") == 0) || (strcmp(argv[i], "--config") == 0))
        {
            if (i + 2 > argc)
            {
                fprintf(stderr, "missing filename after '%s'\n", argv[i]);
                return 1;
            }
            conf_file = argv[i + 1];
            i++;
        }
        else if ((strcmp(argv[i], "-d") == 0) || (strcmp(argv[i], "--daemon") == 0))
        {
            conf->daemon = 1;
        }
        else if (strcmp(argv[i], "--pidfile") == 0)
        {
            if (i + 2 > argc)
            {
                fprintf(stderr, "missing filename after '%s'\n", argv[i]);
                return 1;
            }
            my_strncpy(conf->pidfile, argv[i + 1]);
            i++;
        }
        else if (strcmp(argv[i], "--logfile") == 0)
        {
            if (i + 2 > argc)
            {
                fprintf(stderr, "missing filename after '%s'\n", argv[i]);
                return 1;
            }
            my_strncpy(conf->logfile, argv[i + 1]);
            i++;
        }
        else if ((strcmp(argv[i], "-v") == 0) || (strcmp(argv[i], "--verbose") == 0))
        {
            conf->verbose = 1;
        }
        else if ((strcmp(argv[i], "-V") == 0) || (strcmp(argv[i], "--version") == 0))
        {
            printf("%s %s\n", PACKAGE, VERSION);
            return -1;
        }
        else
        {
            fprintf(stderr, "invalid option: %s\n", argv[i]);
            return -1;
        }
    }
    if (conf_file != NULL)
    {
        if (read_conf(conf_file, conf) != 0)
        {
            return -1;
        }
    }

    if (conf->pidfile[0] == '\0')
    {
        strcpy(conf->pidfile, "/run/sans.pid");
    }
    if (conf->logfile[0] == '\0')
    {
        strcpy(conf->logfile, "/var/log/sans.log");
    }
    if (conf->listen.addr[0] == '\0')
    {
        strcpy(conf->listen.addr, "127.0.0.1");
    }
    if (conf->listen.port[0] == '\0')
    {
        strcpy(conf->listen.port, "53");
    }
    if (conf->test_server.addr[0] == '\0')
    {
        strcpy(conf->test_server.addr, "8.8.8.8");
    }
    if (conf->test_server.port[0] == '\0')
    {
        strcpy(conf->test_server.port, "53");
    }
    if (conf->cn_server.addr[0] == '\0')
    {
        strcpy(conf->cn_server.addr, "114.114.114.114");
    }
    if (conf->cn_server.port[0] == '\0')
    {
        strcpy(conf->cn_server.port, "53");
    }
    if (conf->server.addr[0] == '\0')
    {
        strcpy(conf->server.addr, "8.8.4.4");
    }
    if (conf->server.port[0] == '\0')
    {
        strcpy(conf->server.port, "53");
    }
    return 0;
}
Exemple #28
0
int mix_configline(char *line)
{
  return (read_conf(ADDRESS) || read_conf(NAME) ||
	  read_conf(SHORTNAME) || read_conf(REMAILERADDR) ||
	  read_conf(ANONADDR) || read_conf(REMAILERNAME) ||
	  read_conf(ANONNAME) || read_conf(COMPLAINTS) ||
	  read_conf_i(AUTOREPLY) || read_conf(SMTPRELAY) ||
	  read_conf(SMTPUSERNAME) || read_conf(SMTPPASSWORD) ||
#ifdef USE_SOCK
	  read_conf(HELONAME) || read_conf(ENVFROM) ||
#endif /* USE_SOCK */
	  read_conf(SENDMAIL) || read_conf(SENDANONMAIL) ||
	  read_conf(PRECEDENCE) ||
	  read_conf_i(REMAIL) || read_conf_i(MIX) ||
	  read_conf_i(PGP) || read_conf_i(UNENCRYPTED) ||
	  read_conf_i(REMIX) || read_conf(NEWS) ||
	  read_conf_i(REPGP) || read_conf(EXTFLAGS) ||
	  read_conf(MAILtoNEWS) || read_conf(ERRLOG) ||
	  read_conf(ORGANIZATION) || read_conf(MID) ||
	  read_conf(TYPE1) || read_conf_i(POOLSIZE) ||
	  read_conf_i(RATE) || read_conf_i(MIDDLEMAN) ||
	  read_conf_i(INDUMMYP) ||
	  read_conf_i(OUTDUMMYP) ||
	  read_conf_i(AUTOBLOCK) || read_conf(FORWARDTO) ||
	  read_conf_i(STATSDETAILS) ||
	  read_conf_i(SIZELIMIT) || read_conf_i(INFLATEMAX) ||
	  read_conf_i(MAXRANDHOPS) || read_conf_i(BINFILTER) ||
	  read_conf_i(LISTSUPPORTED) ||
	  read_conf_t(PACKETEXP) || read_conf_t(IDEXP) ||
	  read_conf_t(SENDPOOLTIME) || read_conf_i(NUMCOPIES) ||
	  read_conf_t(MAILINTIME) ||
	  read_conf(CHAIN) || read_conf_i(VERBOSE) ||
	  read_conf_i(DISTANCE) || read_conf_i(MINREL) ||
	  read_conf_i(RELFINAL) || read_conf_t(MAXLAT) ||
	  read_conf_t(MINLAT) ||
	  read_conf(PGPPUBRING) || read_conf(PGPSECRING) ||
	  read_conf(PASSPHRASE) || read_conf_t(KEYLIFETIME) ||
	  read_conf_t(KEYGRACEPERIOD) || read_conf_t(KEYOVERLAPPERIOD) ||
#ifdef USE_SOCK
	  read_conf_i(POP3DEL) || read_conf_i(POP3SIZELIMIT) ||
	  read_conf_t(POP3TIME) ||
#endif /* USE_SOCK */
	  read_conf(MAILBOX) || read_conf(MAILABUSE) ||
	  read_conf(MAILBLOCK) || read_conf(MAILUSAGE) ||
	  read_conf(MAILANON) || read_conf(MAILERROR) ||
	  read_conf(MAILBOUNCE) || read_conf(MAILIN) ||

	  read_conf(DISCLAIMFILE) || read_conf(FROMDSCLFILE) ||
	  read_conf(MSGFOOTERFILE) ||
	  read_conf(POP3CONF) || read_conf(HELPFILE) ||
	  read_conf(REQUESTDIR)  ||
	  read_conf(ABUSEFILE) || read_conf(REPLYFILE) ||
	  read_conf(USAGEFILE) || read_conf(USAGELOG) ||
	  read_conf(BLOCKFILE) || read_conf(ADMKEYFILE) ||
	  read_conf(KEYFILE) || read_conf(PGPKEY) ||
	  read_conf(DSAPARAMS) || read_conf(DHPARAMS) ||
	  read_conf(MIXRAND) || read_conf(SECRING) ||
	  read_conf(PUBRING) || read_conf(IDLOG) ||
	  read_conf(STATS) || read_conf(DESTBLOCK) ||
	  read_conf(PGPMAXCOUNT) ||
	  read_conf(DESTALLOW) || read_conf(DESTALLOW2) ||
	  read_conf(SOURCEBLOCK) ||
	  read_conf(STAREX) || read_conf(ALLPINGERSURL) ||
	  read_conf(ALLPINGERSFILE) ||
	  read_conf(HDRFILTER) || read_conf(REGULAR) ||
	  read_conf(POOL) || read_conf(TYPE1LIST) ||
	  read_conf(TYPE2REL) ||
	  read_conf(PGPREMPUBRING) || read_conf(PGPREMPUBASC) ||
	  read_conf(PGPREMSECRING) || read_conf(NYMSECRING) ||
	  read_conf(NYMDB) || read_conf(PIDFILE) ||
	  read_conf(WGET) || read_conf(STATSSRC) ||
	  read_conf_i(STATSAUTOUPDATE) || read_conf_t(STATSINTERVAL) ||

	  read_conf_i(CLIENTAUTOFLUSH) ||
	  read_conf_i(MAXRECIPIENTS) ||
	  read_conf_i(SMTPPORT) ||
	  
	  read_conf_t(TIMESKEW_FORWARD) ||
	  read_conf_t(TIMESKEW_BACK) ||
	  read_conf_i(TEMP_FAIL) );
}
FFM::FFM(const std::string & conf_path) : num_features(0), num_fields(0), p(0.0), init_coeff(0.0), diff(0.0)
{
  W = nullptr;
  read_conf(conf_path);
}
Exemple #30
0
  uint DIMMER::looop(unsigned int scan_time, bool sw, bool door_bell_sw){
    bool longpress = false;
    bool shortpress = false;
    uint next_slot = 0;
    if (!first_scan){
      read_conf();
      first_scan = true;
    }

    longpress = (sw_press_acc > MIN_SCALING_TIME);
    shortpress = ((sw_press_acc > 0) && !sw && !longpress);

    sw_press_acc += scan_time; //how long is the sw pressed.
    sw_press_acc *= (sw==true);

    ringing_acc += scan_time;
    ringing_acc *= (ringing_latch==true);

    // timeout, turn it off
    time_off_acc += scan_time * (time_off_sp>0);
    time_off_acc *=(on==true);
    if(time_off_acc > time_off_sp) going_off = true;

    // auto publish
    republish_acc += scan_time;
    if(republish_acc > REPUBLISH_TIME){
      publish_now();

      D("Republish from: " << mqtt_name << " duty at: "
        << duty << " republish acc: " << republish_acc << std::endl);

      republish_acc = 0;
    }

    going_on_off_acc += scan_time; //Steps at automatic fadding

    next_slot = (sw_press_acc - MIN_SCALING_TIME)/SCALING_TIME; //for scaling on long press

    if (shortpress && ((going_on || going_off))){
      going_on = false; //reset
      going_off = false; //reset
      shortpress = false;
    }

    if (shortpress && !on) going_on = true; //set
    if (shortpress && on) going_off = true; //set


    if (going_on_off_acc > 0){
    if (going_on) goingOn();
    if (going_off) goingOff();
    going_on_off_acc = 0;
    }

    if (!sw){
      sw_slots = 0; //reset the counter
      up_down = false; //go down always first
      longpress = false;
    }

    if (longpress && (sw_slots < next_slot)) //fade
      fading();

    if(COIL::loop(15,1)){
      reconnect();
    }

    bool ringing = false;
    // Ring the light
    if (door_bell_sw || ringing_latch){
      duty = (((ringing_acc / 350) % 2) == 0)*70+15;
      ringing = true;
      ringing_latch = true;
      if (ringing_acc > 3000) ringing_latch = false;
      D("ringing at: " << duty << std::endl);
    }
    if (ringing && !ringing_latch)  // go back to the start value
      duty = old_duty;

    if (duty >= max_level) duty = max_level;
    if (duty <= 0) duty = 0;

    on = (duty > 0);

    if (((duty != old_duty) || (republish_acc > REPUBLISH_TIME)) && !going_on && !going_off && !ringing_latch){
      old_duty = duty;
      republish_acc *= (republish_acc < REPUBLISH_TIME); //Reset the counter when published was forced
      publish_now();
    }

    return duty;
  }