示例#1
0
void output2d(const star2d &A) {

	FILE *fp;
	char line[1024],*p,*p2,*var,*fmt;
	char *saveptr1,*saveptr2,*saveptr3;
	matrix rho0;
	
	fp=stdin;
	while(fgets(line,1024,fp)) {
		if(*line=='\n') fprintf(stdout,"\n");
		if(*line=='\\') {
			readconf(line);
			continue;
		}
		if(line[strlen(line)-1]=='\n') line[strlen(line)-1]='\0';
		if(*line=='$') {
			p=strtok_r(line,"$",&saveptr1);
		} else {
			p=strtok_r(line,"$",&saveptr1);
			if(p) fprintf(stdout,"%s",p);
			p=strtok_r(NULL,"$",&saveptr1);
		}
		while(p) {
			p++;
			var=strtok_r(p,"}",&saveptr2);
			var=strtok_r(var,",",&saveptr3);
			fmt=strtok_r(NULL,",",&saveptr3);
			p2=strtok_r(NULL,"}",&saveptr2);
			write(A,var,fmt);
			if(p2) fprintf(stdout,"%s",p2);
			p=strtok_r(NULL,"$",&saveptr1);
		}
	}
}
示例#2
0
CRoute_manager::CRoute_manager()
{
	readconf("./conf.json");

	if( (maintain_servfd = create_bind_socket("8080")) == -1 )
		exit(-1);

	if(listen(maintain_servfd, 10) == -1)
		exit(-1);

	if( (info_fd = create_bind_socket("9090")) == -1 )
		exit(-1);

	if(make_socket_non_blocking(info_fd) == -1)
		exit(1);      

	if(listen(info_fd, SOMAXCONN) == -1)
		exit(-1);

	if( pthread_create(&mt_thread_id,NULL,maintain_thread,(void*)this) != 0 )
		exit(-1);

	if( pthread_create(&info_thread_id,NULL,cellinfo_thread,(void*)this) != 0 )
		exit(-1);

	// if( pthread_create(&thread_id,NULL,request_cellinfo_thread,(void*)this) != 0 )
	// 	exit(-1);		
	

}
示例#3
0
int init_lcc(LCC **lccs, int *lccs_len)
{
	char tmpaddress[32+1] = "";
	char tmpstr[32+1] = "";
	
	if (readconf(CFG_FILE_PATH, "lcc.address", tmpaddress, 0) != 0) {
		*lccs = malloc(sizeof(LCC));
		if (*lccs == NULL) {
			fprintf(stderr, "datapublisher: error: init_lcc: malloc: ");
			perror(NULL);
			return 1;
		}
		
		strcpy((*lccs)->address, tmpaddress);
		*lccs_len = 1;
	}
	else if (readconf(CFG_FILE_PATH, "lcc.0.address", tmpaddress, 0) != 0) {
		int len=1, i=0;
	
		sprintf(tmpstr, "lcc.%d.address", len);
		while (readconf(CFG_FILE_PATH, tmpstr, tmpaddress, 0) != 0) {
			len++;
			sprintf(tmpstr, "lcc.%d.address", len);
		}
		
		*lccs = malloc(len * sizeof(LCC));
		if (*lccs == NULL) {
			fprintf(stderr, "datapublisher: error: init_lcc: malloc: ");
			perror(NULL);
			return 1;
		}
		
		for (i=0; i<len; i++) {
			sprintf(tmpstr, "lcc.%d.address", i);
			readconf(CFG_FILE_PATH, tmpstr, tmpaddress, 0);
			strcpy((*lccs+i)->address, tmpaddress);
		}
		*lccs_len = len;
	}
	else {
		fprintf (stderr, "datapublisher: error: init_lcc: no LCCs found in config file.\n");
		return 1;
	}
	
	return 0;
}
示例#4
0
文件: bouncequeue.c 项目: Sympa/sympa
/*
** Main loop.
*/
int
main(int argn, char **argv)
{
   char	*bouncedir;
   char        *listname;
   unsigned int		priority;
   int			firstline = 1;

   /* Usage : bouncequeue list-name */
   if (argn != 2) {
      exit(EX_USAGE);
   }

   listname = malloc(strlen(argv[1]) + 1);
   if (listname != NULL)
     strcpy(listname, argv[1]);

   if ((bouncedir = readconf(CONFIG)) == NULL)
      exit(EX_CONFIG);
   if (chdir(bouncedir) == -1) {
      exit(EX_NOPERM);
   }
   umask(027);
   snprintf(qfile, sizeof(qfile), "T.%s.%ld.%d", listname, time(NULL), getpid());
   fd = open(qfile, O_CREAT|O_WRONLY, 0600);
   if (fd == -1)
      exit(EX_TEMPFAIL);
   write(fd, "X-Sympa-To: ", 12);
   write(fd, listname, strlen(listname));
   write(fd, "\n", 1);
   while (fgets(buf, sizeof buf, stdin) != NULL) {
      if (firstline == 1 && strncmp(buf, "From ", 5) == 0) {
         firstline = 0;
         continue;
      }
      firstline = 0;
      write(fd, buf, strlen(buf));
   }
   while ((i = read(fileno(stdin), buf, sizeof buf)) > 0)
   close(fd);
   rename(qfile, qfile + 2);
   sleep(1);
   exit(0);
}
示例#5
0
int main(int argc, char* argv[])
{
	char dp_station_nr[8 + 1] = "";
	
	LCC *lccs = NULL;
	int lccs_len = 0;
	
	/*int in_fd = 0;
	int in_wd = 0;
	int in_len = 0;
	char in_buffer[INOTIFY_EVENT_BUF_LEN];*/
	
	int msg_id = 0;
	int msg_rc = 0;
	
	//char tmpstr[32+1] = "";
	//struct msqid_ds	msg_queue;
	
	// get station number
	if (readconf(CFG_FILE_PATH, "stationnr", dp_station_nr, 0) == 0) {
		fprintf(stderr, "datapublisher: error: main: readconf: could not gain station number\n");
		exit(EXIT_FAILURE);
	}
	
	// initialize LCCs
	if (init_lcc(&lccs, &lccs_len) != 0) {
		fprintf(stderr, "datapublisher: error: main: init_lcc: could not initiate LCCs\n");
		exit(EXIT_FAILURE);
	}
	
	// initialize message queue
	msg_id = msgget(10021, IPC_CREAT | 0666);
	if (msg_id < 0) {
		fprintf(stderr, "datapublisher: error: msgget: ");
		perror(NULL);
	}
	
	/*msgctl(msg_id, IPC_STAT, &msg_queue);
	while(msg_queue.msg_qnum == 0) {
		msgctl(msg_id, IPC_STAT, &msg_queue);
		usleep(100000L);
	}
	fprintf(stderr, "%d\n", msg_queue.msg_qnum);*/
	
	while (1) {
		msg_rc = msgrcv(msg_id, &dataMsg, sizeof(MsgType), 0, 0);
		if (msg_rc < 0) {
			fprintf(stderr, "datapublisher: error: msgrcv: ");
			perror(NULL);
		}
		else {
			char payload[256 + 1] = "";
			char topic[64 + 1] = "";
			
			//printf("rcv: %s %s %s %s\n", dataMsg.date, dataMsg.type, dataMsg.origin, dataMsg.value);
			
			sprintf(payload, "{\"date\": \"%s\", \"value\": %s}", dataMsg.date, dataMsg.value);
			sprintf(topic, "%s/%s/doserate", dp_station_nr, dataMsg.origin + 18);
			
			mqtt_client_send(lccs[0], topic, payload);
			//usleep(1000000L);
		}
	}
	
	/*in_fd = inotify_init();
	if (in_fd < 0) {
		fprintf(stderr, "datapublisher: error: inotify_init: ");
		perror(NULL);
	}
	
	in_wd = inotify_add_watch(in_fd, "/usbstick/datatxt/DET/monthly", IN_CLOSE_WRITE);
	if (in_wd < 0) {
		fprintf(stderr, "datapublisher: error: inotify_add_watch: ");
		perror(NULL);
	}
	
	in_len = read(in_fd, in_buffer, INOTIFY_EVENT_BUF_LEN);
	if (in_len < 0) {
		fprintf(stderr, "datapublisher: error: read: ");
		perror(NULL);
	}
	else {
		int i = 0;
		while (i < in_len) {
			struct inotify_event *event = (struct inotify_event*) &in_buffer[i];     
			if (event->len) {
				if (event->mask & IN_CLOSE_WRITE) {
					if (strcmp(event->name + 7, "1min.csv") == 0) {
						printf("file %s has been written and closed.\n", event->name);
					}
				}
			}
			i += INOTIFY_EVENT_SIZE + event->len;
		}
	}*/
	
	

	//MQTTAsync_destroy(&client);
 	return 0;
}
示例#6
0
文件: nameif.c 项目: 274914765/C
int main (int ac, char **av)
{
    FILE *ifh;

    char *p;

    int n;

    int linenum;

    char *line = NULL;

    size_t linel = 0;

    for (;;)
    {
        int c = getopt_long (ac, av, "c:s", lopt, NULL);

        if (c == -1)
            break;
        switch (c)
        {
            default:
            case '?':
                usage ();
            case 'c':
                fname = optarg;
                break;
            case 's':
                use_syslog = 1;
                break;
        }
    }

    if (use_syslog)
        openlog ("nameif", 0, LOG_LOCAL0);

    while (optind < ac)
    {
        struct change *ch = xmalloc (sizeof (struct change));

        char pos[30];

        if ((ac - optind) & 1)
            usage ();
        if (strlen (av[optind]) + 1 > IFNAMSIZ)
            complain (_("interface name `%s' too long"), av[optind]);
        strcpy (ch->ifname, av[optind]);
        optind++;
        sprintf (pos, _("argument %d"), optind);
        addchange (av[optind], ch, pos);
        optind++;
    }

    if (!clist || fname != default_conf)
        readconf ();

    ifh = fopen ("/proc/net/dev", "r");
    if (!ifh)
        complain (_("open of /proc/net/dev: %s"), strerror (errno));


    linenum = 0;
    while (getdelim (&line, &linel, '\n', ifh) > 0)
    {
        struct change *ch;

        unsigned char mac[6];

        if (linenum++ < 2)
            continue;

        p = line;
        while (isspace (*p))
            ++p;
        n = strcspn (p, ": \t");
        p[n] = 0;

        if (n > IFNAMSIZ - 1)
            complain (_("interface name `%s' too long"), p);

        if (getmac (p, mac) < 0)
            continue;

        ch = lookupmac (mac);
        if (!ch)
            continue;

        *ch->pprev = ch->next;
        if (strcmp (p, ch->ifname))
        {
            if (setname (p, ch->ifname) < 0)
                complain (_("cannot change name of %s to %s: %s"), p, ch->ifname, strerror (errno));
        }
        free (ch);
    }
    fclose (ifh);

    while (clist)
    {
        struct change *ch = clist;

        clist = clist->next;
        warning (_("interface '%s' not found"), ch->ifname);
        free (ch);
    }

    if (use_syslog)
        closelog ();
    return 0;
}
示例#7
0
/*
** Main loop.
*/
int
main(int argn, char **argv)
{
   char	*queuedir;
   char        *listname, *familyname;
   unsigned int		priority;
   int			firstline = 1;

   /* Usage : queue list-name family-name */
   if ((argn != 3)) {
     fprintf(stderr,"%s: usage error, two arguments expected : list-name family-name\n",
            argv[0]);
      exit(EX_USAGE);
   }

   listname = malloc(strlen(argv[1]) + 1);
   if (listname != NULL)
      strcpy(listname, argv[1]);

   familyname = malloc(strlen(argv[2]) + 1);
   if (familyname != NULL)
      strcpy(familyname, argv[2]);

   if ((queuedir = readconf(CONFIG)) == NULL){
     fprintf(stderr,"%s: cannot read configuration file '%s'.\n",
            argv[0],CONFIG);
      exit(EX_CONFIG);
   }
   if (chdir(queuedir) == -1) {
     char* buffer=(char*)malloc(strlen(argv[0])+strlen(queuedir)+80);
     sprintf(buffer,"%s: while changing dir to '%s'",argv[0],queuedir);
     perror(buffer);
     exit(EX_NOPERM);
   }
   umask(027);
   snprintf(qfile, sizeof(qfile), "T.%s.%ld.%d", listname, time(NULL), getpid());
   fd = open(qfile, O_CREAT|O_WRONLY, 0600);
   if (fd == -1){
     char* buffer=(char*)malloc(strlen(argv[0])+strlen(queuedir)+80);
     sprintf(buffer,"%s: while opening queue file '%s'",argv[0],qfile);
     perror(buffer);
     exit(EX_TEMPFAIL);
   }
   write(fd, "X-Sympa-Family: ", 16);
   write(fd, familyname, strlen(familyname));
   write(fd, "\n", 1);
   write(fd, "X-Sympa-To: ", 12);
   write(fd, listname, strlen(listname));
   fprintf(stderr,"list-name:%s, family-name:%s\n",listname, familyname);
   write(fd, "\n", 1);
   while (fgets(buf, sizeof buf, stdin) != NULL) {
      if (firstline == 1 && strncmp(buf, "From ", 5) == 0) {
         firstline = 0;
         continue;
      }
      firstline = 0;
      write(fd, buf, strlen(buf));
   }
   while ((i = read(fileno(stdin), buf, sizeof buf)) > 0)
   close(fd);
   rename(qfile, qfile + 2);
   sleep(1);
   exit(0);
}
示例#8
0
文件: main.c 项目: CRDevOps/srelay
int main(int ac, char **av)
{
  int     ch, i=0;
  pid_t   pid;
  FILE    *fp;
  uid_t   uid;
#ifdef USE_THREAD
  pthread_t tid;
  pthread_attr_t attr;
  struct rlimit rl;
  rlim_t max_fd = (rlim_t)MAX_FD;
  rlim_t save_fd = 0;
#endif

#ifdef USE_THREAD
  threading = 1;
  max_thread = MAX_THREAD;
#endif

  max_child = MAX_CHILD;
  cur_child = 0;

  /* create service socket table (malloc) */
  if (serv_init(NULL) < 0) {
    msg_out(crit, "cannot malloc: %m\n");
    exit(-1);
  }

  proxy_tbl = NULL;
  proxy_tbl_ind = 0;

  method_num = 0;

  uid = getuid();

  openlog(ident, LOG_PID | LOG_NDELAY, SYSLOGFAC);

  while((ch = getopt(ac, av, "a:c:i:J:m:o:p:u:frstbwgIqvh?")) != -1)
    switch (ch) {
    case 'a':
      if (optarg != NULL) {
	for (i=0; i<sizeof method_tab; optarg++) {
	  if (*optarg == '\0')
	    break;
	  switch (*optarg) {
	  case 'p':
	    if ( uid != 0 ) {
	      /* process does not started by root */
	      msg_out(warn, "uid == %d (!=0),"
		      "user/pass auth will not work, ignored.\n",
		      uid);
	      break;
	    }
	    method_tab[i++] = S5AUSRPAS;
	    method_num++;
	    break;
	  case 'n':
	    method_tab[i++] = S5ANOAUTH;
	    method_num++;
	    break;
	  default:
	    break;
	  }
	}
      }
      break;

    case 'b':
      bind_restrict = 0;
      break;

    case 'c':
      if (optarg != NULL) {
        config = strdup(optarg);
      }
      break;

    case 'u':
      if (optarg != NULL) {
        pwdfile = strdup(optarg);
      }
      break;

    case 'i':
      if (optarg != NULL) {
	if (serv_init(optarg) < 0) {
	  msg_out(warn, "cannot init server socket(-i %s): %m\n", optarg);
	  break;
	}
      }
      break;

#ifdef SO_BINDTODEVICE
    case 'J':
      if (optarg != NULL) {
	bindtodevice = strdup(optarg);
      }
      break;
#endif

    case 'o':
      if (optarg != NULL) {
	idle_timeout = atol(optarg);
      }
      break;

    case 'p':
      if (optarg != NULL) {
	pidfile = strdup(optarg);
      }
      break;

    case 'm':
      if (optarg != NULL) {
#ifdef USE_THREAD
	max_thread = atoi(optarg);
#endif
	max_child = atoi(optarg);
      }
      break;

    case 't':
#ifdef USE_THREAD
      threading = 0;    /* threading disabled. */
#endif
      break;

    case 'g':
      same_interface = 1;
      break;

    case 'f':
      fg = 1;
      break;

    case 'r':
      resolv_client = 1;
      break;

    case 's':
      forcesyslog = 1;
      break;

    case 'w':
#ifdef HAVE_LIBWRAP
      use_tcpwrap = 1;
#endif /* HAVE_LIBWRAP */
      break;

    case 'I':
      inetd_mode = 1;
      break;

    case 'q':
      be_quiet = 1;
      break;

    case 'v':
      show_version();
      exit(1);

    case 'h':
    case '?':
    default:
      usage();
    }

  ac -= optind;
  av += optind;

  if ((fp = fopen(config, "r")) != NULL) {
    if (readconf(fp) != 0) {
      /* readconf error */
      exit(1);
    }
    fclose(fp);
  }

  if (inetd_mode) {
    /* close all server socket if opened */
    close_all_serv();
    /* assuming that STDIN_FILENO handles bi-directional
     */
    exit(inetd_service(STDIN_FILENO));
    /* not reached */
  }

  if (serv_sock_ind == 0) {   /* no valid ifs yet */
    if (serv_init(":") < 0) { /* use default */
      /* fatal */
      msg_out(crit, "cannot open server socket\n");
      exit(1);
    }
  }

#ifdef USE_THREAD
  if ( ! threading ) {
#endif
    if (queue_init() != 0) {
      msg_out(crit, "cannot init signal queue\n");
      exit(1);
    }
#ifdef USE_THREAD
  }
#endif

  /* try changing working directory */
  if ( chdir(WORKDIR0) != 0 )
    if ( chdir(WORKDIR1) != 0 )
      msg_out(norm, "giving up chdir to workdir");

  if (!fg) {
    /* force stdin/out/err allocate to /dev/null */
    fclose(stdin);
    fp = fopen("/dev/null", "w+");
    if (fileno(fp) != STDIN_FILENO) {
      msg_out(crit, "fopen: %m");
      exit(1);
    }
    if (dup2(STDIN_FILENO, STDOUT_FILENO) == -1) {
      msg_out(crit, "dup2-1: %m");
      exit(1);
    }
    if (dup2(STDIN_FILENO, STDERR_FILENO) == -1) {
      msg_out(crit, "dup2-2: %m");
      exit(1);
    }

    switch(fork()) {
    case -1:
      msg_out(crit, "fork: %m");
      exit(1);
    case 0:
      /* child */
      pid = setsid();
      if (pid == -1) {
	msg_out(crit, "setsid: %m");
	exit(1);
      }
      break;
    default:
      /* parent */
      exit(0);
    }
  }

  master_pid = getpid();
  umask(S_IWGRP|S_IWOTH);
  if ((fp = fopen(pidfile, "w")) != NULL) {
    fprintf(fp, "%u\n", (unsigned)master_pid);
    fchown(fileno(fp), PROCUID, PROCGID);
    fclose(fp);
  } else {
    msg_out(warn, "cannot open pidfile %s", pidfile);
  }

  setsignal(SIGHUP, reload);
  setsignal(SIGINT, SIG_IGN);
  setsignal(SIGQUIT, SIG_IGN);
  setsignal(SIGILL, SIG_IGN);
  setsignal(SIGTRAP, SIG_IGN);
  setsignal(SIGABRT, SIG_IGN);
#ifdef SIGEMT
  setsignal(SIGEMT, SIG_IGN);
#endif
  setsignal(SIGFPE, SIG_IGN);
  setsignal(SIGBUS, SIG_IGN);
  setsignal(SIGSEGV, SIG_IGN);
  setsignal(SIGSYS, SIG_IGN);
  setsignal(SIGPIPE, SIG_IGN);
  setsignal(SIGALRM, SIG_IGN);
  setsignal(SIGTERM, cleanup);
  setsignal(SIGUSR1, SIG_IGN);
  setsignal(SIGUSR2, SIG_IGN);
#ifdef SIGPOLL
  setsignal(SIGPOLL, SIG_IGN);
#endif
  setsignal(SIGVTALRM, SIG_IGN);
  setsignal(SIGPROF, SIG_IGN);
  setsignal(SIGXCPU, SIG_IGN);
  setsignal(SIGXFSZ, SIG_IGN);

#ifdef USE_THREAD
  if ( threading ) {
    if (max_thread <= 0 || max_thread > THREAD_LIMIT) {
      max_thread = THREAD_LIMIT;
    }
    /* resource limit is problem in threadig (e.g. Solaris:=64)*/
    memset((caddr_t)&rl, 0, sizeof rl);
    if (getrlimit(RLIMIT_NOFILE, &rl) != 0)
      msg_out(warn, "getrlimit: %m");
    else
      save_fd = rl.rlim_cur;
    if (rl.rlim_cur < (rlim_t)max_fd)
      rl.rlim_cur = max_fd;        /* willing to fix to max_fd */
    if ( rl.rlim_cur != save_fd )  /* if rlim_cur is changed   */
      if (setrlimit(RLIMIT_NOFILE, &rl) != 0)
        msg_out(warn, "cannot set rlimit(max_fd)");

    setregid(0, PROCGID);
    setreuid(0, PROCUID);

    pthread_mutex_init(&mutex_select, NULL);
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

    msg_out(norm, "Starting: MAX_TH(%d)", max_thread);
    for (i=0; i<max_thread; i++) {
      if (pthread_create(&tid, &attr,
			 (void *)&serv_loop, (void *)NULL) != 0)
        exit(1);
    }
    main_thread = pthread_self();   /* store main thread ID */
    for (;;) {
      pause();
    }
  } else {
#endif
    setsignal(SIGCHLD, reapchild);
    setregid(0, PROCGID);
    setreuid(0, PROCUID);
    msg_out(norm, "Starting: MAX_CH(%d)", max_child);
    serv_loop();
#ifdef USE_THREAD
  }
#endif
  return(0);
}
示例#9
0
文件: dhcpd.c 项目: rubo77/MeshBSD
int
main(int argc, char *argv[])
{
	int ch, cftest = 0, daemonize = 1, rdomain = -1, udpsockmode = 0;
	char *sync_iface = NULL;
	char *sync_baddr = NULL;
	u_short sync_port = 0;
	struct servent *ent;
	struct in_addr udpaddr;

	/* Initially, log errors to stderr as well as to syslogd. */

	progname = argv[0]; /* XXX: yeah, ugly. */
	opterr = 0;
	while ((ch = getopt(argc, argv, "A:C:L:c:dfl:nu::Y:y:")) != -1)
		switch (ch) {
		case 'Y':
			syncsend = 1;
			break;
		case 'y':
			syncrecv = 1;
			break;
		}
	if (syncsend || syncrecv) {
		if ((ent = getservbyname("dhcpd-sync", "udp")) == NULL)
			errx(1, "Can't find service \"dhcpd-sync\" in "
			    "/etc/services");
		sync_port = ntohs(ent->s_port);
	}
	udpaddr.s_addr = htonl(INADDR_BROADCAST);

	optreset = optind = opterr = 1;
	while ((ch = getopt(argc, argv, "A:C:L:c:dfl:nu::Y:y:")) != -1)
		switch (ch) {
		case 'A':
			abandoned_tab = optarg;
			break;
		case 'C':
			changedmac_tab = optarg;
			break;
		case 'L':
			leased_tab = optarg;
			break;
		case 'c':
			path_dhcpd_conf = optarg;
			break;
		case 'd':
			daemonize = 0;
			log_perror = 1;
			break;
		case 'f':
			daemonize = 0;
			break;
		case 'l':
			path_dhcpd_db = optarg;
			break;
		case 'n':
			daemonize = 0;
			cftest = 1;
			log_perror = 1;
			break;
		case 'u':
			udpsockmode = 1;
			if (optarg != NULL) {
				if (inet_aton(optarg, &udpaddr) != 1)
					errx(1, "Cannot parse binding IP "
					    "address: %s", optarg);
			}
			break;
		case 'Y':
			if (sync_addhost(optarg, sync_port) != 0)
				sync_iface = optarg;
			syncsend = 1;
			break;
		case 'y':
			sync_baddr = optarg;
			syncrecv = 1;
			break;
		default:
			usage();
		}

	argc -= optind;
	argv += optind;

	while (argc > 0) {
		struct interface_info *tmp = calloc(1, sizeof(*tmp));
		if (!tmp)
			error("calloc");
		(void)strlcpy(tmp->name, argv[0], sizeof(tmp->name));
		tmp->next = interfaces;
		interfaces = tmp;
		argc--;
		argv++;
	}

	/* Default DHCP/BOOTP ports. */
	server_port = htons(SERVER_PORT);
	client_port = htons(CLIENT_PORT);

	tzset();

	(void)time(&cur_time);
	if (!readconf())
		error("Configuration file errors encountered");

	if (cftest)
		exit(0);

	db_startup();
	if (!udpsockmode || argc > 0)
		discover_interfaces(&rdomain);
	if (rdomain != -1) {
		if (setfib(rdomain) == -1)
			error("setfib (%m)");
	}
	if (udpsockmode)
		udpsock_startup(udpaddr);
	icmp_startup(1, lease_pinged);

	if (syncsend || syncrecv) {
		syncfd = sync_init(sync_iface, sync_baddr, sync_port);
		if (syncfd == -1)
			err(1, "sync init");
	}

	if ((pw = getpwnam("_dhcp")) == NULL)
		error("user \"_dhcp\" not found");

	if (daemonize)
		(void)daemon(0, 0);

	/* don't go near /dev/pf unless we actually intend to use it */
	if ((abandoned_tab != NULL) ||
	    (changedmac_tab != NULL) ||
	    (leased_tab != NULL)) {
		if (pipe(pfpipe) == -1)
			error("pipe (%m)");
		switch (pfproc_pid = fork()) {
		case -1:
			error("fork (%m)");
			/* NOTREACHED */
			exit(1);
		case 0:
			/* child process. start up table engine */
			(void)close(pfpipe[1]);
			pftable_handler();
			/* NOTREACHED */
			exit(1);
		default:
			(void)close(pfpipe[0]);
			gotpipe = 1;
			break;
		}
	}

	if (chroot("/var/empty") == -1)
		error("chroot %s: %m", "/var/empty");

	if (chdir("/") == -1)
		error("chdir(\"/\"): %m");
	if (setgroups(1, &pw->pw_gid) ||
	    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
		error("can't drop privileges: %m");

	add_timeout(cur_time + 5, periodic_scan, NULL);
	dispatch();

	/* not reached */
	exit(0);
}
示例#10
0
int main(int argc, char *argv[])
{
    char buf[2048], dev1[10]="tap0", dev2[10]="tap1", dev3[10]="tap2";
    int fd1, fd2, fd3, len;
    int fm;
    //int count=0;
    struct timeval time;
    //struct iphdr *myiphdr;
    //struct ether_header *myether;
    fd_set fds;

    //inizializzo i puntatori che gestiscono le catene
    primo_wlan = (struct rules*) malloc(sizeof(struct rules));
    primo_wlan->rule_type=0;
    primo_wlan->next=NULL;
    succ_wlan = primo_wlan;
    prec_wlan = primo_wlan;
    
    printf("Please connect:\n");
    printf("tap0 at br0(wlan)\n");
    printf("tap1 at br5\n");
    printf("tap2 at br6\n\n");
    
    printf("Start Now!\n");
	
    if( (fd1 = tun_alloc(dev1)) < 0 ){
       printf("1:Cannot allocate TUN device 1\n");
       exit(1);
    }

    if( (fd2 = tun_alloc(dev2)) < 0 ){
       printf("1:Cannot allocate TUN device 2\n");
       exit(1);
    }

    if( (fd3 = tun_alloc(dev3)) < 0 ){
       printf("1:Cannot allocate TUN device 3\n");
       exit(1);
    }
    
    fm = max(fd1, fd2);
    fm = max(fm, fd3);

	readconf();
	if (debug) {
		printf("dynamic: %d\n",dynamic);
		
    }
	
    while(1){
		FD_ZERO(&fds);
        FD_SET(fd1, &fds);
        FD_SET(fd2, &fds);
        FD_SET(fd3, &fds);
        
        select(fm+1, &fds, NULL, NULL, NULL);
		
		gettimeofday(&time, 0);
		
        //wlan
        if( FD_ISSET(fd1, &fds) ) {
			if (debug) printf("Packet received from wlan\n");
			
            if( (len = mytun_read(fd1, buf, sizeof(buf))) < 0 ){
                printf("2:Error in mytun_read\n");
            } 
			else {
			//qui lancia decisore.c che restituisce un intero che uso con uno switch case per fare le mytun_write
			//ci devo passare anche len per aggiornare bw nella lista
				if (debug) printf("Decisore decide :%d\n",decisore(buf,len,time));
				switch (decisore(buf,len,time)) { 
					case 5:  
						mytun_write(fd2, buf, len);
						if (debug) printf("%d.%.06d: Received %d bytes from wlan -> br5\n", (int)time.tv_sec, (int)time.tv_usec, len);
						break;
					case 6:
						mytun_write(fd3, buf, len);
						if (debug) printf("%d.%.06d: Received %d bytes from wlan -> br6\n", (int)time.tv_sec, (int)time.tv_usec, len);
						break;
					
					    /* Codice spostato al decisore !
						if (dynamic) {
							if (debug)
								printf ("Dynamic=%d", dynamic);
							//modificare, usare br5bw e br6bw per decidere dove mandare il pacchetto
							mytun_write(fd3, buf, len);
							if (debug) printf("DEFAULT %d.%.06d: Received %d bytes from wlan -> br6\n", (int)time.tv_sec, (int)time.tv_usec, len);
						}*/
				}			
/* OLD CODE
                myether = (struct ether_header *) buf;
                myiphdr = (struct iphdr *) &buf[14];   
                if ((count%10) >= 5) {            
                    mytun_write(fd2, buf, len);
                    printf("%d.%.06d: Received %d bytes from wlan -> br5\n", (int)time.tv_sec, (int)time.tv_usec, len);
                    count++;
                } else {
                    mytun_write(fd3, buf, len);
                    printf("%d.%.06d: Received %d bytes from wlan -> br6\n", (int)time.tv_sec, (int)time.tv_usec, len);
                    count++;
                }
                    
		    printf("Tipo ether: %04X\n", bswap_16(myether->ether_type));
		    if(bswap_16(myether->ether_type)==0x8000)
                	printf("Tipo IP   : %d\n", (myiphdr->protocol));                  
*/
            }
        }

		//br5
        if( FD_ISSET(fd2, &fds) ) {
			if (debug) printf("PACCHETTO FROM br5\n");
            if( (len = mytun_read(fd2, buf, sizeof(buf))) < 0 ){
                printf("2:Error in mytun_read\n");
            } else {
                mytun_write(fd1, buf, len);
            }
       
            if (debug) printf("%d.%.06d: Received %d bytes from br5 -> wlan\n", (int)time.tv_sec, (int)time.tv_usec, len);            
        }
	
		//br6
        if( FD_ISSET(fd3, &fds) ) {
			if (debug) printf("PACCHETTO FROM br6\n");
            if( (len = mytun_read(fd3, buf, sizeof(buf))) < 0 ){
                printf("2:Error in mytun_read\n");
            } else {
                mytun_write(fd1, buf, len);
            }
       
            if (debug) printf("%d.%.06d: Received %d bytes from br6 -> wlan\n", (int)time.tv_sec, (int)time.tv_usec, len);
        }
     }
}
示例#11
0
int getconfig_argv(int argc, char ** argv) {
	int ch=0;
	char conffile[512];

#define OPTS	\
		"b:" "B:" "c" "d:" "D" "e:" "E" "F" "G:" "h" "H" "i:" "I" "j:" "l:" "L:" "m:" "M:" "o:" "p:" "P:" "q:" "Q" \
		"r:" "R:" "s:" "S" "t:" "T:" "u:" "U" "w:" "W:" "v" "V" "z" "Z:"

#ifdef WITH_LONGOPTS
	const struct option long_opts[]={
		{"broken-crc",		1, NULL, 'b'},
		{"source-port",		1, NULL, 'B'},
		{"proc-duplicates",	0, NULL, 'c'},
		{"delay-type",		1, NULL, 'd'},
		{"no-defpayload",	0, NULL, 'D'},
		{"enable-modules",	1, NULL, 'e'},
		{"show-errors",		0, NULL, 'E'},
		{"try-frags",		0, NULL, 'F'},
		{"payload-group",	1, NULL, 'G'},
		{"help",		0, NULL, 'h'},
		{"do-dns",		0, NULL, 'H'},
		{"interface",		1, NULL, 'i'},
		{"immediate",		0, NULL, 'I'},
		{"ignore-seq",		1, NULL, 'j'},
		{"logfile",		1, NULL, 'l'},
		{"packet-timeout",	1, NULL, 'L'},
		{"mode",		1, NULL, 'm'},
		{"module-dir",		1, NULL, 'M'},
		{"format",		1, NULL, 'o'},
		{"ports",		1, NULL, 'p'},
		{"pcap-filter",		1, NULL, 'P'},
		{"covertness",		1, NULL, 'q'},
		{"quiet",		0, NULL, 'Q'},
		{"pps",			1, NULL, 'r'},
		{"repeats",		1, NULL, 'R'},
		{"source-addr",		1, NULL, 's'},
		{"no-shuffle",		0, NULL, 'S'},
		{"ip-ttl",		1, NULL, 't'},
		{"ip-tos",		1, NULL, 'T'},
		{"debug",		1, NULL, 'u'},
		{"no-openclosed",	0, NULL, 'U'},
		{"savefile",		1, NULL, 'w'},
		{"fingerprint",		1, NULL, 'W'},
		{"verbose",		1, NULL, 'v'}, /* this is different in the long / short opts */
		{"version",		0, NULL, 'V'},
		{"sniff",		0, NULL, 'z'},
		{"drone-str",		1, NULL, 'Z'},
		{NULL,			0, NULL,  0 }
	};
#endif /* LONG OPTION SUPPORT */

	scan_setdefaults();

	snprintf(conffile, sizeof(conffile) -1, CONF_FILE, s->profile);
	if (readconf(conffile) < 0) {
		return -1;
	}

#ifdef WITH_LONGOPTS
	while ((ch=getopt_long(argc, argv, OPTS, long_opts, NULL)) != -1) {
#else
	while ((ch=getopt(argc, argv, OPTS)) != -1) {
#endif
		switch (ch) {
			case 'b':
				if (scan_setbroken(optarg) < 0) {
					usage();
				}
				break;

			case 'B':
				if (scan_setsrcp(atoi(optarg)) < 0) {
					usage();
				}
				break;

			case 'c':
				if (scan_setprocdups(1) < 0) {
					usage();
				}
				break;

			case 'D': /* set no default payload */
				if (scan_setdefpayload(0) < 0) {
					usage();
				}
				break;

			case 'd':
				if (scan_setdelaytype(atoi(optarg)) < 0) {
					usage();
				}
				break;

			case 'e': /* enable modules */
				if (scan_setenablemodule(optarg) < 0) {
					usage();
				}
				break;

			case 'E': /* report and listen for non open/closed responses */
				if (scan_setprocerrors(1) < 0) {
					usage();
				}
				break;

			case 'F': /* fragment packets if possible */
				if (scan_settryfrags(1) < 0) {
					usage();
				}
				break;

			case 'G':
				if (scan_setpayload_grp(atoi(optarg)) < 0) {
					usage();
				}
				break;

			case 'h': /* help */
				usage();
				break;

			case 'H': /* resolve ip addresses into names during reporting phase */
				if (scan_setdodns(1) < 0) {
					usage();
				}
				break;

			case 'i': /* interface name */
				if (scan_setinterface(optarg) < 0) {
					usage();
				}
				break;

			case 'I':
				if (scan_setimmediate(1) < 0) {
					usage();
				}
				break;

			case 'j': /* ignore sequence numbers during tcp scanning */
				if (scan_setignoreseq(optarg) < 0) {
					usage();
				}
				break;

			case 'L': /* how long to wait for replies after done sending */
				if (scan_setrecvtimeout(atoi(optarg)) < 0) {
					usage();
				}
				break;

			case 'l': /* log to file, not tty */
				if ((s->_stdout=fopen(optarg, "a+")) == NULL) {
					terminate("logfile `%s' cant be opened", optarg);
				}
				s->_stderr=s->_stdout;
				break;

			case 'm': /* scan mode, tcp udp, etc */
				if (scan_setoptmode(optarg) < 0) {
					usage();
				}
				break;

			case 'M': /* module directory base */
				if (scan_setmoddir(optarg) < 0) {
					usage();
				}
				break;

			case 'o': /* report format string */
				if (scan_setformat(optarg) < 0) {
					usage();
				}
				break;
			

			case 'p': /* Global ports to scan */
				if (scan_setgports(optarg) < 0) {
					usage();
				}
				break;

			case 'P': /* pcap filter to use, like "! port 162" */
				if (scan_setpcapfilter(optarg) < 0) {
					usage();
				}
				break;

			case 'q': /* covertness */
				if (scan_setcovertness(atoi(optarg)) < 0) {
					usage();
				}
				break;

			case 'Q':
				if (scan_setreportquiet(1) < 0) {
					usage();
				}
				break;

			case 'r': /* rate of scan */
				if (scan_setpps(optarg) < 0) {
					usage();
				}
				break;

			case 'R': /* repeat scan n times */
				if (scan_setrepeats(atoi(optarg)) < 0) {
					usage();
				}
				break;

			case 's': /* set source ip address to optarg */
				if (scan_setsrcaddr(optarg) < 0) {
					usage();
				}
				break;

			case 'S': /* do not shuffle ports */
				if (scan_setshuffle(1) < 0) {
					usage();
				}
				break;

			case 't': /* ttl on outgoing IP datagrams */
				if (scan_setttl(optarg) < 0) {
					usage();
				}
				break;

			case 'T': /* TOS on outgoing IP datagram */
				if (scan_settos(atoi(optarg)) < 0) {
					usage();
				}
				break;

			case 'u': /* debug mask */
				if (scan_setdebug(optarg) < 0) {
					usage();
				}
				break;

			case 'U': /* do NOT translate Open/Closed in output, display as is */
				if (scan_settrans(0) < 0) {
					usage();
				}
				break;

			case 'v': /* verbose */
				if (optarg != NULL) {
					if (scan_setverbose(atoi(optarg)) < 0) usage();
				}
				else if (scan_setverboseinc() < 0) {
					usage();
				}
				break;

			case 'V':
				display_version();
				break;

			case 'w': /* write to pcap logfile optarg */
				if (scan_setsavefile(optarg) < 0) {
					usage();
				}
				break;

			case 'W': /* what stack to pretend to have */
				if (scan_setfingerprint(atoi(optarg)) < 0) {
					usage();
				}
				break;

			case 'z': /* im too lazy to run tcpdump mode */
				if (scan_setsniff(1) < 0) {
					usage();
				}
				break;

			case 'Z': /* used for cluster scanning */
				if (scan_setdronestring(optarg) < 0) {
					usage();
				}
				break;

			default:
				usage();
				break;
		} /* switch option */
	} /* getopt loop */

	/* its not set if its null, so set it, otherwise it is */
	if (s->mod_dir == NULL) {
		scan_setmoddir(MODULE_DIR);
	}

	s->argv_ext=fifo_init();

	for (; optind < argc; optind++) {
		fifo_push(s->argv_ext, xstrdup(argv[optind]));
	}

	return 1;
}


void do_targets(void) {
	union {
		void *ptr;
		char *str;
	} s_u;
	char *estr=NULL;

	for (s_u.ptr=fifo_pop(s->argv_ext); s_u.ptr != NULL; s_u.ptr=fifo_pop(s->argv_ext)) {
		if (workunit_add(s_u.str, &estr) < 0) {
			if (access(s_u.str, R_OK) == 0) {
				FILE *rfile=NULL;
				char lbuf[2048];
				char *tok=NULL, *rent=NULL;

				CLEAR(lbuf);

				rfile=fopen(s_u.str, "r");
				if (rfile == NULL) {
					continue;
				}

				while (fgets(lbuf, sizeof(lbuf) -1, rfile) != NULL) {
					for (tok=strtok_r(lbuf, "\t\r\n\v\f ", &rent); tok != NULL; tok=strtok_r(NULL, "\t\r\n\v\f ", &rent)) {
						if (workunit_add(tok, &estr) < 0) {
							ERR("cant add workunit `%s' from file `%s': %s", tok, s_u.str, estr);
						}
					}
				}

				fclose(rfile);
			}
			else {
				ERR("cant add workunit for argument `%s': %s", s_u.str, estr != NULL ? estr : ""); /* bad hostname? */
			}
		}
	}

	/* if we are not a drone */
	if (!(GET_LISTENDRONE() || GET_SENDDRONE())) {
		if (s->num_hosts < 1) {
			INF("What should i scan? I've got nothing to do.\n");
			usage();
			uexit(0);
		}
	}

	return;
}

static void usage(void) {

	INF("%s (version %s)\n"
   //xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
	"USAGE: %s [Options] Target List (ex. X.X.X.X/YY:S-E)\n"
	"-b, --broken-crc Broken CRC sums on [T]ransport, [N]etwork, or both[TN].\n"
	"-B, --source-port Source port.\n"
	"-c, --proc-duplicates Process duplicate replies.\n"
	"-d, --delay-type Delay type `%s'.\n"
	"-D, --no-defpayload  Only probe known protocols.\n"
	"-e, --enable-module  A comma separated list of modules to activate.\n"
	"-E, --proc-errors Process `non-open' responses. (ICMP errors, TCP RST, etc.).\n"
	"-G, --payload-group Group number TCP/UDP payload type selection (default all).\n"
	"-h, --help Help.\n"
	"-H, --do-dns Resolve hostnames during the reporting phase.\n"
	"-i, --interface Optional interface name, like eth0 or fxp1.\n"
	"-I, --immediate Display things as we find them.\n"
	"-j, --ignore-seq Ignore `A'll, 'R'eset sequence numbers for TCP header\n"
	"\t\tvalidation.\n"
	"-l, --logfile Write to this file not my terminal.\n"
	"-L, --packet-timeout Wait this long for packets to come back, default\n"
	"\t\tis %d secs.\n"
	"-m, --mode Scan mode, TCP/SYN scan is default, options are [U]DP, [T]CP,\n"
	"\t\tand [sf]TCP Connect. For -mT you can also specify tcp flags\n"
	"\t\tlike -mTsFpU for example that would send TCP SYN packets with\n"
	"\t\t(NO Syn|FIN|NO Push|URG)\n"
	"-M, --module-dir Modules directory.\n"
	"-o, --format Reply format, see man page for format specification\n"
	"-p, --ports Global ports to scan, if not specified in target options.\n"
	"-P, --pcap-filter Extra pcap filter string for reciever.\n"
	"-q, --covertness Covertness value from 0 to 255.\n"
	"-Q, --quiet Disable output to the screen.\n"
	"-r, --pps Packets per second in total, not per host.\n"
	"-R, --repeats Repeat packet scan N times.\n"
	"-s, --source-addr Source address for packets, `r' for random.\n"
	"-S, --no-shuffle Do not shuffle ports.\n"
	"-t, --ip-ttl Set TTL on sent packets for example, 62, 6-16 or r64-128.\n"
	"-T, --ip-tos Set TOS on sent packets.\n"
	"-u, --debug Enable debug messages. According to user provided mask.\n"
	"-U, --no-openclosed Don't say open or closed in output.\n"
	"-w, --safefile Write pcap file of recieved packets.\n"
	"-W, --fingerprint Stack to pretend to have OS fingerprints:\n"
	"\t\t0=cisco(def) 1=openbsd 2=WindowsXP 3=p0fsendsyn 4=FreeBSD\n"
	"\t\t5=nmap 6=linux 7:strangetcp\n"
	"-v, --verbose Verbose output. Support for up to -vvvvv, for really verbose.\n"
	"-V, --version Display version\n"
	"-z, --sniff Display packet parsing information.\n"
	"-Z, --drone-str Undocumented feature.\n\n"
	"Examples:\n"
	"Address ranges are CIDR like 1.2.3.4/8 for all of 1.?.?.?\n"
	"if you omit the CIDR mask then /32 is implied.\n"
	"Port ranges are like 1-4096 with 53 only scanning one port,\n"
	"`a' for all 65k and `p' for 1-1024\n"
	"%s -i eth1 -Ir 160 -E 192.168.1.0/24:1-4000 gateway:a\n\n"
	"Type `man %s` for more information about usage.",
	PROGNAME, VERSION, PROGNAME, delay_getopts(), DEF_SCANTIMEOUT, PROGNAME, PROGNAME);

	uexit(0);
}
示例#12
0
int
main(int argc, char *argv[])
{
	int ch, cftest = 0, daemonize = 1, rdomain = -1;
	extern char *__progname;
	char *sync_iface = NULL;
	char *sync_baddr = NULL;
	u_short sync_port = 0;
	struct servent *ent;

	/* Initially, log errors to stderr as well as to syslogd. */
	openlog_r(__progname, LOG_PID | LOG_NDELAY, DHCPD_LOG_FACILITY, &sdata);

	opterr = 0;
	while ((ch = getopt(argc, argv, "A:C:L:c:dfl:nY:y:")) != -1)
		switch (ch) {
		case 'Y':
			syncsend = 1;
			break;
		case 'y':
			syncrecv = 1;
			break;
		}
	if (syncsend || syncrecv) {
		if ((ent = getservbyname("dhcpd-sync", "udp")) == NULL)
			errx(1, "Can't find service \"dhcpd-sync\" in "
			    "/etc/services");
		sync_port = ntohs(ent->s_port);
	}

	optreset = optind = opterr = 1;
	while ((ch = getopt(argc, argv, "A:C:L:c:dfl:nY:y:")) != -1)
		switch (ch) {
		case 'A':
			abandoned_tab = optarg;
			break;
		case 'C':
			changedmac_tab = optarg;
			break;
		case 'L':
			leased_tab = optarg;
			break;
		case 'c':
			path_dhcpd_conf = optarg;
			break;
		case 'd':
			daemonize = 0;
			log_perror = 1;
			break;
		case 'f':
			daemonize = 0;
			break;
		case 'l':
			path_dhcpd_db = optarg;
			break;
		case 'n':
			daemonize = 0;
			cftest = 1;
			log_perror = 1;
			break;
		case 'Y':
			if (sync_addhost(optarg, sync_port) != 0)
				sync_iface = optarg;
			syncsend = 1;
			break;
		case 'y':
			sync_baddr = optarg;
			syncrecv = 1;
			break;
		default:
			usage();
		}

	argc -= optind;
	argv += optind;

	while (argc > 0) {
		struct interface_info *tmp = calloc(1, sizeof(*tmp));
		if (!tmp)
			error("calloc");
		strlcpy(tmp->name, argv[0], sizeof(tmp->name));
		tmp->next = interfaces;
		interfaces = tmp;
		argc--;
		argv++;
	}

	/* Default DHCP/BOOTP ports. */
	server_port = htons(SERVER_PORT);
	client_port = htons(CLIENT_PORT);

	tzset();

	time(&cur_time);
	if (!readconf())
		error("Configuration file errors encountered");

	if (cftest)
		exit(0);

	db_startup();
	discover_interfaces(&rdomain);

	if (rdomain != -1)
		if (setrtable(rdomain) == -1)
			error("setrtable (%m)");

	icmp_startup(1, lease_pinged);

	if (syncsend || syncrecv) {
		syncfd = sync_init(sync_iface, sync_baddr, sync_port);
		if (syncfd == -1)
			err(1, "sync init");
	}

	if ((pw = getpwnam("_dhcp")) == NULL)
		error("user \"_dhcp\" not found");

	if (daemonize)
		daemon(0, 0);

	/* don't go near /dev/pf unless we actually intend to use it */
	if ((abandoned_tab != NULL) ||
	    (changedmac_tab != NULL) ||
	    (leased_tab != NULL)){
		if (pipe(pfpipe) == -1)
			error("pipe (%m)");
		switch (pfproc_pid = fork()){
		case -1:
			error("fork (%m)");
			/* NOTREACHED */
			exit(1);
		case 0:
			/* child process. start up table engine */
			pftable_handler();
			/* NOTREACHED */
			exit(1);
		default:
			gotpipe = 1;
			break;
		}
	}

	if (chroot(_PATH_VAREMPTY) == -1)
		error("chroot %s: %m", _PATH_VAREMPTY);
	if (chdir("/") == -1)
		error("chdir(\"/\"): %m");
	if (setgroups(1, &pw->pw_gid) ||
	    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
		error("can't drop privileges: %m");

	bootp_packet_handler = do_packet;
	add_timeout(cur_time + 5, periodic_scan, NULL);
	dispatch();

	/* not reached */
	exit(0);
}
示例#13
0
void
ntp_intres(void)
{
	FILE *in;
#ifdef SYS_WINNT
	DWORD rc;
#else
	int	rc;
	struct	timeval tv;
	fd_set	fdset;
	int	time_left;
#endif

#ifdef DEBUG
	if (debug > 1) {
		msyslog(LOG_INFO, "NTP_INTRES running");
	}
#endif

	/* check out auth stuff */
	if (sys_authenticate) {
		if (!authistrusted(req_keyid)) {
			msyslog(LOG_ERR, "invalid request keyid %08x",
			    req_keyid );
			resolver_exit(1);
		}
	}

	/*
	 * Read the configuration info
	 * {this is bogus, since we are forked, but it is easier
	 * to keep this code - gdt}
	 */
	if ((in = fopen(req_file, "r")) == NULL) {
		msyslog(LOG_ERR, "can't open configuration file %s: %m",
			req_file);
		resolver_exit(1);
	}
	readconf(in, req_file);
	(void) fclose(in);

#ifdef DEBUG
	if (!debug)
#endif
		if (unlink(req_file))
			msyslog(LOG_WARNING,
				"unable to remove intres request file %s, %m",
				req_file);

	/*
	 * Set up the timers to do first shot immediately.
	 */
	resolve_timer = 0;
	resolve_value = MINRESOLVE;
	config_timer = CONFIG_TIME;

	for (;;) {
		checkparent();

		if (resolve_timer == 0) {
			/*
			 * Sleep a little to make sure the network is completely up
			 */
			sleep(SLEEPTIME);
			doconfigure(1);

			/* prepare retry, in case there's more work to do */
			resolve_timer = resolve_value;
#ifdef DEBUG
			if (debug > 2)
				msyslog(LOG_INFO, "resolve_timer: 0->%d", resolve_timer);
#endif
			if (resolve_value < MAXRESOLVE)
				resolve_value <<= 1;

			config_timer = CONFIG_TIME;
		} else if (config_timer == 0) {  /* MB: in which case would this be required ? */
			doconfigure(0);
			/* MB: should we check now if we could exit, similar to the code above? */
			config_timer = CONFIG_TIME;
#ifdef DEBUG
			if (debug > 2)
				msyslog(LOG_INFO, "config_timer: 0->%d", config_timer);
#endif
		}

		if (confentries == NULL)
			resolver_exit(0);   /* done */

#ifdef SYS_WINNT
		rc = WaitForSingleObject(ResolverEventHandle, 1000 * ALARM_TIME);  /* in milliseconds */

		if ( rc == WAIT_OBJECT_0 ) { /* signaled by the main thread */
			resolve_timer = 0;         /* retry resolving immediately */
			continue;
		}

		if ( rc != WAIT_TIMEOUT ) /* not timeout: error */
			resolver_exit(1);

#else  /* not SYS_WINNT */
		/* Bug 1386: fork() in NetBSD leaves timers running. */
		/* So we need to retry select on EINTR */
		time_left = ALARM_TIME;
		while (time_left > 0) {
		    tv.tv_sec = time_left;
		    tv.tv_usec = 0;
		    FD_ZERO(&fdset);
		    FD_SET(resolver_pipe_fd[0], &fdset);
		    rc = select(resolver_pipe_fd[0] + 1, &fdset, (fd_set *)0, (fd_set *)0, &tv);

		    if (rc == 0)		/* normal timeout */
			break;

		    if (rc > 0) {  /* parent process has written to the pipe */
			read(resolver_pipe_fd[0], (char *)&rc, sizeof(rc));  /* make pipe empty */
			resolve_timer = 0;   /* retry resolving immediately */
			break;
		    }

		    if ( rc < 0 ) {		/* select() returned error */
			if (errno == EINTR) {	/* Timer went off */
			    time_left -= (1<<EVENT_TIMEOUT);
			    continue;		/* try again */
			}
			msyslog(LOG_ERR, "ntp_intres: Error from select: %s",
			    strerror(errno));
			resolver_exit(1);
		    }
		}
#endif

		/* normal timeout, keep on waiting */
		if (config_timer > 0)
			config_timer--;
		if (resolve_timer > 0)
			resolve_timer--;
	}
}
示例#14
0
int
main(int argc, char *argv[]) {
	char *buf;
	struct disk *disks, *dp;
	int ch, ok;
	long long minwait, nextwait;
	struct sigaction sa;
	long long counter;
	int initial_debug;
	const char *conf_file, *save_file;

	conf_file = _PATH_CONF;
	save_file = _PATH_SAVE;
	debug = 0;

	while ((ch = getopt(argc, argv, "df:o:")) != -1)
		switch (ch) {
		case 'd':
			if (debug)
				debug *= 2;
			else
				debug = 1;
			break;
		case 'f':
			conf_file = optarg;
			break;
		case 'o':
			save_file = optarg;
			break;
		default:
			usage();
			/* NOTREACHED */
		}

	argv += optind;
	argc -= optind;

	if (argc != 0)
		usage();

	initial_debug = debug;

	openlog("diskcheckd", LOG_CONS|LOG_PID|(debug?LOG_PERROR:0),
		LOG_DAEMON);

	if (!debug && daemon(0, 0) < 0) {
		syslog(LOG_NOTICE, "daemon() failure: %m");
		exit(EXIT_FAILURE);
	}

	sa.sa_handler = sigterm;
	sa.sa_flags = SA_RESTART;
	sigemptyset(&sa.sa_mask);
	sigaction(SIGTERM, &sa, NULL);
	sigaction(SIGINT, &sa, NULL);

	sa.sa_handler = sighup;
	sigaction(SIGHUP, &sa, NULL);

	/* Read the configuration file and the saved offsets */
	disks = readconf(conf_file);
	readoffsets(disks, save_file);

	if ((buf = malloc(READ_SIZE)) == NULL) {
		syslog(LOG_NOTICE, "malloc failure: %m");
		exit(EXIT_FAILURE);
	}

	/* The main disk checking loop.
	 *
	 * We wait the shortest amount of time we need to before
	 * another disk is due for a read -- this time is updated
	 * in the 'nextwait' variable, which is then copied to
	 * 'minwait'.  After a sleep, 'minwait' is subtracted from
	 * each disk's 'next' field, and when that reaches zero,
	 * that disk is read again.
	 */
	counter = 0LL;
	minwait = 0LL;
	while (!got_sigterm) {
		ok = 0;
		nextwait = LLONG_MAX;
		for (dp = disks; dp->device != NULL; dp++)
			if (dp->fd != -1) {
				if (debug > 1)
					fprintf(stderr,
						"%s:  next(%qd) -= %qd\n",
						dp->device, dp->next, minwait);
				if ((dp->next -= minwait) == 0) {
					ok = 1;
					readchunk(dp, buf);
				}

				/* XXX debugging */
				if (dp->next < 0LL) {
					syslog(LOG_NOTICE,
					  "dp->next < 0 for %s", dp->device);
					abort();
				}

				if (dp->next < nextwait)
					nextwait = dp->next;
			}

		if (!ok) {
			syslog(LOG_EMERG, "all disks had read errors");
			exit(EXIT_FAILURE);
		}

		/* 300 seconds => 5 minutes */
		if (counter >= 300000000LL) {
			if (debug)
				fprintf(stderr, "counter rollover %qd => 0\n",
					counter);
			updateproctitle(disks);
			writeoffsets(disks, save_file);
			counter = 0LL;
		}

		minwait = nextwait;
		if (debug > 1) {
			--debug;
			fprintf(stderr, "sleep %qd, counter %qd\n",
				minwait, counter);
		}

		/*
		 * Handle whole seconds and usec separately to avoid overflow
		 * when calling usleep -- useconds_t is only 32 bits on at
		 * least some architectures, and minwait (being long long)
		 * may exceed INT_MAX.
		 */
		if (minwait > 1000000LL)
			sleep((unsigned int)(minwait / 1000000));
		if ((minwait % 1000000) > 0)
			usleep((useconds_t)(minwait % 1000000));
		counter += minwait;

		if (got_sighup) {
			/*
			 * Got a SIGHUP, so save the offsets, free the
			 * memory used for the disk structures, and then
			 * re-read the config file and the disk offsets.
			 */
			if (debug) {
				fprintf(stderr, "got SIGHUP, counter == %qd\n",
					counter);
				debug = initial_debug;
			}
			writeoffsets(disks, save_file);
			for (dp = disks; dp->device != NULL; dp++) {
				free(dp->device);
				close(dp->fd);
			}
			free(disks);
			disks = readconf(conf_file);
			readoffsets(disks, save_file);
			minwait = 0LL;
			got_sighup = 0;
		}
	}

	if (debug)
		fprintf(stderr, "got %s, counter == %qd\n",
			got_sigterm==SIGTERM?"SIGTERM":"SIGINT", counter);
	writeoffsets(disks, save_file);
	return (EXIT_SUCCESS);
}
示例#15
0
int main(int argc,char *argv[])
{
    int  status;
    int  rem;
	int  offset;
	int  len;
	char buffer[32];
	char wgetbuf[1024];
    int  fd;
    const char *port = "/dev/ttyS0";
	FILE *f;
	time_t t;
    
	t=time(NULL);
    // default to ttyS0 or invoke with 'linux_nmeap <other serial device>' 
    if (argc == 2) {
        port = argv[1];
    }
    
	readconf(argc, argv);


    /* --------------------------------------- */
    /* open the serial port device             */
    /* using default 9600 baud for most GPS    */
    /* --------------------------------------- */
    fd = openPort(getparam("gps_port"), atoi(getparam("baudrate")));
    if (fd < 0) {
        /* open failed */
        printf("openPort %d\n",fd);
        return fd;
    }
    
	/* ---------------------------------------*/
	/*STEP 2 : initialize the nmea context    */                                                
	/* ---------------------------------------*/
    status = nmeap_init(&nmea,(void *)&user_data);
    if (status != 0) {
        printf("nmeap_init %d\n",status);
        exit(1);
    }
    
	/* ---------------------------------------*/
	/*STEP 3 : add standard GPGGA parser      */                                                
	/* -------------------------------------- */
    status = nmeap_addParser(&nmea,"GPGGA",nmeap_gpgga,gpgga_callout,&gga);
    if (status != 0) {
        printf("nmeap_add %d\n",status);
        exit(1);
    }

	/* ---------------------------------------*/
	/*STEP 4 : add standard GPRMC parser      */                                                
	/* -------------------------------------- */
    status = nmeap_addParser(&nmea,"GPRMC",nmeap_gprmc,gprmc_callout,&rmc);
    if (status != 0) {
        printf("nmeap_add %d\n",status);
        exit(1);
    }
    
	/* ---------------------------------------*/
	/*STEP 5 : process input until done       */                                                
	/* -------------------------------------- */
    for(;;) {
		/* ---------------------------------------*/
		/*STEP 6 : get a buffer of input          */                                                
		/* -------------------------------------- */
        len = rem = read(fd,buffer,sizeof(buffer));
        if (len <= 0) {
            perror("read");
            break;
        }
        
        
		/* ----------------------------------------------*/
		/*STEP 7 : process input until buffer is used up */                                                
		/* --------------------------------------------- */
		offset = 0;
        while(rem > 0) {
			/* --------------------------------------- */
			/*STEP 8 : pass it to the parser           */
			/* status indicates whether a complete msg */
			/* arrived for this byte                   */
			/* NOTE : in addition to the return status */
			/* the message callout will be fired when  */
			/* a complete message is processed         */
			/* --------------------------------------- */
            status = nmeap_parseBuffer(&nmea,&buffer[offset],&rem);
			offset += (len - rem); 
            
			/* ---------------------------------------*/
			/*STEP 9 : process the return code        */
            /* DON"T NEED THIS IF USING CALLOUTS      */
            /* PICK ONE OR THE OTHER                  */
			/* -------------------------------------- */
            switch(status) {
            case NMEAP_GPGGA:
                printf("-------------switch\n");
                print_gga(&gga);
                printf("-------------\n");
                break;
            case NMEAP_GPRMC:
                printf("-------------switch\n");
                print_rmc(&rmc);
                printf("-------------\n");
                break;
            default:
                break;
            }

	if (!(f=fopen(getparam("kml_file"), "w"))) {
		perror("fopen");
		exit(1);
	};
	FLOCK(f);
	fprintf(f, 
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"\
"<kml xmlns=\"http://earth.google.com/kml/2.2\">\n"\
"<Document>\n"\
"<name>location.kml</name>\n"\
"   <Style id=\"location\">\n"\
"      <IconStyle>\n"\
"         <color>%s</color>\n"\
"         <scale>%s</scale>\n"\
"         <Icon>\n"\
"            <href>%s</href>\n"\
"         </Icon>\n"\
"      </IconStyle>\n"\
"      <LabelStyle>\n"\
"         <color>%s</color>\n"\
"         <scale>%s</scale>\n"\
"      </LabelStyle>\n"\
"      <ListStyle>\n"\
"      </ListStyle>\n"\
"   </Style>\n"\
"   <Placemark>\n"\
"      <name>%s</name>\n"\
"      <LookAt>\n"\
"         <longitude>%.6f</longitude>\n"\
"         <latitude>%.6f</latitude>\n"\
"         <altitude>%.0f</altitude>\n"\
"         <range>%s</range>\n"\
"         <tilt>%s</tilt>\n"\
"         <heading>%s</heading>\n"\
"      </LookAt>\n"\
"      <styleUrl>#location</styleUrl>\n"\
"      <description>Date: %.6lu \n"\
"                   Time: %.6lu \n"\
"		    Speed: %.1f</description>\n"\
"      <Point>\n"\
"         <coordinates>%.6f,%.6f,%.0f</coordinates>\n"\
"      </Point>\n"\
"   </Placemark>\n"\
"</Document>\n"\
"</kml>\n" , getparam("icon_color"), getparam("icon_scale"), getparam("icon_normal"), getparam("label_color"), getparam("label_scale"), getparam("object_name"), mylon, mylat, myalt, getparam("look_range"), getparam("look_tilt"), getparam("look_heading"), mydat, mytim, myspd, mylon, mylat, myalt);

	if (myval && mylat != 0 && mylon != 0) {
		int interval= atoi(getparam("interval"));
		if (!interval)
			interval = 30;
		if ( t+interval < time(NULL) ) {
			snprintf(wgetbuf, sizeof(wgetbuf), "wget 'http://trackme.org.ua/gps/flygps?ver=1&id=%s&lat=%f&lng=%f&alt=%.0f&speed=%f' -q -O /dev/null && gpio set A1 0 > /dev/null ; usleep 200000 ; gpio set A1 1 > /dev/null", getparam("object_name"), mylat, mylon, myalt, myspd);
			system(wgetbuf);
			t = time(NULL);
		}
	}


	fflush(f);
	FUNLOCK(f);
	fclose(f);
		}
    }
    
    /* close the serial port */
    close(fd);
    
    return 0;
}