int main(int argc, char **argv) {
    guchar image_data[width * height * 3];
    
    collect_data(image_data);
    print_hash(width*height*3, image_data);
    draw_image(argc, argv, image_data);
}
Beispiel #2
0
  void poll_monitor::run()
  {
    collect_initial_data();

    for (;;)
    {
#ifdef HAVE_CXX_MUTEX
      unique_lock<mutex> run_guard(run_mutex);
      if (should_stop) break;
      run_guard.unlock();
#endif

      FSW_ELOG(_("Done scanning.\n"));

      sleep(latency < MIN_POLL_LATENCY ? MIN_POLL_LATENCY : latency);

      time(&curr_time);

      collect_data();

      if (events.size())
      {
        notify_events(events);
        events.clear();
      }
    }
  }
Beispiel #3
0
/**
 * Cron job for the system.
 *
 * Run at the top of the second but may take longer than a second
 */
void do_cron(void)
{
  /* ---- Local representation of the time ---- */
  while (ticks) {
    /* Update time internally */
    ticks--; time.epoch++; time.second++;
    if (time.second >= 60) {
      time.second = 0; time.minute++;
      if (time.minute >= 60) {
        time.minute = 0; time.hour++;
        if (time.hour >= 24) {
          time.hour = 0; time.day++;
          if (time.day > days_in_month(&time)) {
            time.day = 1; time.month++;
            if (time.month > 12) {
              time.month = 0; time.year++;
            }
          }
        }
      }
    }
  }

  /* ---- Data every 30 seconds ---- */
  if (time.second == TELEM_TOM) {
    dp = collect_data();
    memcpy(&dp->time, &time, sizeof(struct tracker_time));
  } else if (time.second == ((TELEM_TOM + 55)%60)) { /* 5 seconds for async things */
    collect_data_async();
  }

  /* ---- Telemetry output ---- */
  if (has_telemetry_woken_up > 0) {
    cron_telemetry(&time, dp);
  } else {
    has_telemetry_woken_up = TELEMETRY_WAKEUP_TEST(dp) ? 0xF : 0;
  }

  /* ---- Record for backlog ---- */
  if ((time.minute == 0) && (time.second == 0)) { /* Once per hour */

    kick_the_watchdog();

    if (gps_is_locked()) { /* Don't bother with no GPS */
      record_backlog(dp);
    }
  }

  /* Update internal time from GPS */
  /* We do this just after midnight or if time is yet to set UTC exactly */
  if (((time.hour == 0) && (time.minute == 0) && (time.second == 0)) ||
      ((time.second == 0) && !(time.valid & UBX_TIMEUTC_VALID_UTC))) {

    kick_the_watchdog();

    read_gps_time();
  }
}
Beispiel #4
0
static void
parse_line (char *line, unsigned int lineno)
{
  char *p;
  char *event_type, *address, *data, *status, *datatag;

  if (debug)
    printf ("line[%u] ='%s'\n", lineno, line);

  p = strtok (line, " ");
  if (!p)
    die ("invalid line %d (no URB)");
  p = strtok (NULL, " ");
  if (!p)
    die ("invalid line %d (no timestamp)");
  event_type = strtok (NULL, " ");
  if (!event_type)
    die ("invalid line %d (no event type)");
  address = strtok (NULL, " ");
  if (!address)
    die ("invalid line %d (no address");
  if (usb_bus || usb_dev)
    {
      int bus, dev;

      p = strchr (address, ':');
      if (!p)
        die ("invalid line %d (invalid address");
      p++;
      bus = atoi (p);
      p = strchr (p, ':');
      if (!p)
        die ("invalid line %d (invalid address");
      p++;
      dev = atoi (p);

      if ((usb_bus && usb_bus != bus) || (usb_dev && usb_dev != dev))
        return;  /* We don't want that one.  */
    }
  if (*address != 'B' || (address[1] != 'o' && address[1] != 'i'))
    return; /* We only want block in and block out.  */
  status = strtok (NULL, " ");
  if (!status)
    return;
  if (!strchr ("-0123456789", *status))
    return; /* Setup packet.  */
  /* We don't support "Z[io]" types thus we don't need to check here.  */
  p = strtok (NULL, " ");
  if (!p)
    return; /* No data length.  */

  datatag = strtok (NULL, " ");
  if (datatag && *datatag == '=')
    {
      data = strtok (NULL, "");
      collect_data (data?data:"", address, lineno);
    }
}
static void
get_data(SysinfoPlugin* plugin, SysinfoPluginData* data)
{
  NetData* plugin_data = (NetData*)plugin->plugin_data;

  collect_data(plugin_data);

  data->data = plugin_data->rate;
}
Beispiel #6
0
/*
 * Update the monitor data lists.
 * return 0, or -1 on error and leave errno unchanged
 */
int
monitor_update()
{
	if (setjmp(dm_jmpbuffer) == 0) {
		collect_data();
		list_create();
		return (0);
	} else {
		return (-1);
	}
}
Beispiel #7
0
/*
 * Count how big the total datasize is by recursing through the pages.  Then
 * allocate a buffer and copy the data as you recurse up.
 */
static int
collect_data(HTAB *hashp, BUFHEAD *bufp, int len, int set)
{
	uint16_t *bp;
	char *p;
	BUFHEAD *xbp;
	uint16_t save_addr;
	int mylen, totlen;

	p = bufp->page;
	bp = (uint16_t *)(void *)p;
	mylen = hashp->BSIZE - bp[1];
	save_addr = bufp->addr;

	if (bp[2] == FULL_KEY_DATA) {		/* End of Data */
		totlen = len + mylen;
		if (hashp->tmp_buf)
			free(hashp->tmp_buf);
		if ((hashp->tmp_buf = calloc(1, (size_t)totlen)) == NULL)
			return (-1);
		if (set) {
			hashp->cndx = 1;
			if (bp[0] == 2) {	/* No more buckets in chain */
				hashp->cpage = NULL;
				hashp->cbucket++;
			} else {
				hashp->cpage =
				    __get_buf(hashp, (uint32_t)bp[bp[0] - 1],
				    bufp, 0);
				if (!hashp->cpage)
					return (-1);
				else if (!((uint16_t *)(void *)hashp->cpage->page)[0]) {
					hashp->cbucket++;
					hashp->cpage = NULL;
				}
			}
		}
	} else {
		xbp = __get_buf(hashp, (uint32_t)bp[bp[0] - 1], bufp, 0);
		if (!xbp || ((totlen =
		    collect_data(hashp, xbp, len + mylen, set)) < 1))
			return (-1);
	}
	if (bufp->addr != save_addr) {
		errno = EINVAL;			/* Out of buffers. */
		return (-1);
	}
	memmove(&hashp->tmp_buf[len], (bufp->page) + bp[1], (size_t)mylen);
	return (totlen);
}
Beispiel #8
0
void run_memtop(void) {
    //TODO: initialization for read and select
    fd_set rd;
    struct timeval timeout;
    int bytes;
    char buf[BUFFER_SIZE];
    // Should I put this code insize FD_ISSET or where?
    // With
    if (fcntl(STDIN_FILENO,F_SETFL,O_NONBLOCK) == -1) {
                perror("fcntl()\n");
    }
    //to avoid unused variable warning. You may remove it once you use buf.
    buf[0] = 0;
    while(1) {
        //TODO: call select, read, and process_data
        FD_ZERO(&rd);               // Clear the fd set
        FD_SET(STDIN_FILENO,&rd);   // Fill the fd set
        timeout.tv_sec  = 0;        // Waiting time is 0
        timeout.tv_usec = 0;         
        if (select(1,&rd,NULL,NULL,&timeout) == -1) {
            perror("select()");
        }
        // Check if STDIN_FILENO ready or not 
        if (FD_ISSET(STDIN_FILENO,&rd)) {
            // read up to BUFFER_SIZE bytes
            
            if ((bytes = read(STDIN_FILENO,buf,BUFFER_SIZE)) == -1) {
                perror("read()\n");
            }
            if (process_input(buf,bytes) != 0) {
                break;
            }
        }

        //read proc filesystem
        int n_procs = 0;
        process_t *proc_arr = collect_data(&n_procs);

        if (proc_arr == NULL) {
            continue;
        }

        sort_data(proc_arr, n_procs);
        //update display
        display_data(proc_arr, n_procs);
                //free proc_data
        free(proc_arr);
    }
}
static NetData*
init_data()
{
  NetData* data = g_new(NetData, 1);

  data->current = g_new(double, DATA_FIELDS);
  data->last = g_new(double, DATA_FIELDS);
  data->rate = g_new(double, DATA_FIELDS);

  get_interfaces(data);

  //do a first run so that we have some meaningful numbers for the next
  //time around
  collect_data(data);

  return data;
}
Beispiel #10
0
static int asn1_collect(BUF_MEM *buf, unsigned char **in, long len, char inf, int tag, int aclass)
{
	unsigned char *p, *q;
	long plen;
	char cst, ininf;
	p = *in;
	inf &= 1;
	while(len > 0) {
		q = p;
		/* Check for EOC */
		if(asn1_check_eoc(&p, len)) {
			/* EOC is illegal outside indefinite length constructed form */
			if(!inf) {
				ASN1err(ASN1_F_ASN1_COLLECT, ASN1_R_UNEXPECTED_EOC);
				return 0;
			}
			inf = 0;
			break;
		}
		if(!asn1_check_tlen(&plen, NULL, NULL, &ininf, &cst, &p, len, tag, aclass, 0, NULL)) {
			ASN1err(ASN1_F_ASN1_COLLECT, ERR_R_NESTED_ASN1_ERROR);
			return 0;
		}
		/* If indefinite length constructed update max length */
		if(cst) {
#ifdef OPENSSL_ALLOW_NESTED_ASN1_STRINGS
			if (!asn1_collect(buf, &p, plen, ininf, tag, aclass))
				return 0;
#else
			ASN1err(ASN1_F_ASN1_COLLECT, ASN1_R_NESTED_ASN1_STRING);
			return 0;
#endif
		} else {
			if(plen && !collect_data(buf, &p, plen)) return 0;
		}
		len -= p - q;
	}
	if(inf) {
		ASN1err(ASN1_F_ASN1_COLLECT, ASN1_R_MISSING_EOC);
		return 0;
	}
	*in = p;
	return 1;
}
Beispiel #11
0
  void poll_monitor::run()
  {
    collect_initial_data();

    while (true)
    {
      FSW_ELOG(_("Done scanning.\n"));

      sleep(latency < MIN_POLL_LATENCY ? MIN_POLL_LATENCY : latency);

      time(&curr_time);

      collect_data();

      if (events.size())
      {
        notify_events(events);
        events.clear();
      }
    }
  }
Beispiel #12
0
void
handle(char *thefile, int checkpoint, int restart, char *restartdata)
{
  static int num = 0;
  static char *dirstack = 0;
  static int dirsize = 0;
  static int dirnum = 0;
  int i, args, ret;
  char *estack[EMAX];
  char **command;
  char *dirname;
  struct termios globalterm;
#ifdef TIOCSWINSZ
  struct winsize ws;
#endif
  int aid, uid, gid, euid, egid, fd, fd2;
  int ngroups;
  gid_t *gidset;
  int again;
  DIR *dir;
  struct dirent *temp;
  char *file;
  int filedes[2], fdpipe[2], mail, mywait;
  mode_t mask;
  int prio;
  struct sockaddr_in myclient;
  struct rlimit myrlimit[8];
  int miport, miport2;
  u_short rport;
  fd_set readfrom, ready;
  int maxfdp1;
  long oldmask;
  int ppid = 0;
  int pty1, pty2;

  char *userid, *mailuserid, *jobname, *onlyhost, *cookie;

  restartfile = restartdata;
  restartmode = restart;
  checkpointmode = checkpoint;

  again = 1;
  file = thefile;

  /*Change the status line in ps to make clearer who exactly we are.*/

  globalargv[0] = "queued_slave";

  /*if(ReadHosts(QHOSTSFILE) < 0)
    {
    fprintf(stderr, "Can not read queue hosts file %s\n", QHOSTSFILE);
    exit(1);
    }
  */


  while (again==1) {
    again=0;
    mode = 'i';

    sigsetmask(~0L);

    mail = 1;

    if((fd = open(file, O_RDONLY))<0) continue;
    if((queue=fdopen(fd, "r"))==0) continue;

    /*Another daemon deleted the file while we were trying to lock the
      file.*/

    /*The draft protocol says that VERSION1 should be the first thing
      in the file.*/

    {char *version=fgetl(queue);
    if(strcmp(version,"VERSION1")) {
     syslog(LOG_ERR, "Unsuported job control file version.\n");
     exit(2);
    }
    free (version);
    }


    /*The following three pieces of info are needed at the beginning
     because jobinfo() reads them in first for logging info.*/

    netfread(&uid, sizeof(int), 1, queue);
    userid=fgetl(queue);
    mailuserid=fgetl(queue);
    jobname=fgetl(queue);
    onlyhost=fgetl(queue); /*Batchd already checked this for us.*/
    netfread(&donthang, sizeof(donthang), 1, queue);

    cookie=fgetl(queue); /*it general, it prevents a mix-up of ports
			   if queue.c has been killed in the mean-time
			   and another queue.c is residing on the same
			   port.  With NO_ROOT, prevents malicious
			   users; in general, it prevents*/

    /* EJD - 8/14/2000 - Don't need to swap host address */
    fread(&(myclient.sin_addr), sizeof(myclient.sin_addr), 1, queue);
    {int tmpport;
    netfread(&tmpport, sizeof(int), 1, queue);
    rport = htons((u_short) tmpport);
    }

   {register int i;
   int adj = 0;
   netfread(&args, sizeof(int), 1, queue);

#ifdef ENABLE_CHECKPOINT

   /*WGK 1999/3/5 Modified to support user checkpoint restart API.*/
   if((checkpoint == USER_CHECKPOINT) && restart && (restartdata) && (*restartdata)) adj = 1;

#endif /*ENABLE_CHECKPOINT*/

   command = (char **) malloc((args + 1 + adj)*sizeof(char*));

   if (args) command[0] = fgetl(queue);

   if (adj) {
     command[1] = restartdata;
     args++;}

   for(i=adj+1;i<args;++i) command[i] = fgetl(queue);
   command[args] = 0;
   }

   pipe(filedes);

   dirname=fgetl(queue);
   netfread(&aid, sizeof(int), 1, queue);
   netfread(&euid, sizeof(int), 1, queue);
   netfread(&egid, sizeof(int), 1, queue);
   netfread(&gid, sizeof(int), 1, queue);
   netfread(&ngroups, sizeof(int), 1, queue);

   if((gidset = malloc(ngroups*sizeof(gid_t)))==0) {
     syslog(LOG_ERR, "Out of memory.\n");
     exit(2);
   }

   netfread(gidset, sizeof(gid_t), ngroups, queue);
   netfread(&ttyinput, sizeof(ttyinput), 1, queue);
   netfread(&ttyoutput, sizeof(ttyoutput), 1, queue);
   netfread(&ttyerror, sizeof(ttyoutput), 1, queue);
   netfread(&globalterm, sizeof(globalterm), 1, queue);
#ifdef TIOCSWINSZ
   netfread(&ws, sizeof(ws), 1, queue);
#endif
   num = 0;
   while (*(estack[num] = fgetl(queue))!=0) {
     if(strcmp(estack[num], "QMAIL=FALSE")==0) mail =0;
     if(++num + 1 > EMAX) {
       syslog(LOG_ERR, "Too many environmental variables!\n");
       exit(2);
     }
   }
   sprintf(tmp, "QUEUE=%c", mode);
   estack[num]=tmp;
   estack[num+1]=0;
   netfread(&mask, sizeof(mode_t), 1, queue);
   netfread(&prio, sizeof(int), 1, queue);
   netfread(myrlimit, sizeof(struct rlimit), 8, queue);
   /*unlink(file);*/
   /*fclose(queue);*/
   if(donthang==0) {

     {

       int slptim, length, miport;
       struct sockaddr_in address1, address2;
       long oldmask;
       char c;
       struct hostent	*hostp;
       fd_set readfdesc;
       length = sizeof(myclient.sin_addr);
       if ( (hostp = gethostbyaddr(&(myclient.sin_addr), length, AF_INET)) == NULL) {
	 syslog(LOG_ERR, "gethostbyaddr failed: %m");
	 goto berror;
       }
#ifndef NO_ROOT
       miport = IPPORT_RESERVED - 1;
#else
       miport = 32700;
#endif
       slptim  = 1;
       oldmask = sigblock(sigmask(SIGURG));
       while (1) {

#ifndef NO_ROOT
	 if ( (fdsock1 = rresvport(&miport)) < 0) {
	   /*	    if (errno == EAGAIN)
		    fprintf(stderr, "socket: All ports are in use?\n");
		    else */
	   syslog(LOG_ERR, "handle: %m");
	   sigsetmask(oldmask);
	   goto berror;
	 }
#else
	 if ( (fdsock1 = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
	   /*if (errno == EAGAIN)
	     fprintf(stderr, "socket: All ports are in use?\n");
	     else*/
	   syslog(LOG_ERR, "handle: %m");
	   sigsetmask(oldmask);
	   goto berror;
	 }

#endif

	 bzero((char *) &address1, sizeof(address1));
	 address1.sin_family = hostp->h_addrtype;
	 bcopy(hostp->h_addr_list[0], (caddr_t)&address1.sin_addr,
	       hostp->h_length);
	 address1.sin_port = rport;
	 if (connect(fdsock1, (struct sockaddr *) &address1,
		     sizeof(address1)) >= 0)
	   break;		/* OK*/

	 close(fdsock1);
#ifndef NO_ROOT
	 if (errno == EADDRINUSE) {
	   miport--;
	   continue;
	 }
#endif

	 if (errno == ECONNREFUSED & slptim <= 4) {
	   /*Connection refused; maybe server just overloaded? Sleep a bit, then try again.*/
	
	   sleep(slptim);
	   slptim += 2;	
	   continue;
	 }

	 if (hostp->h_addr_list[1] != NULL) {
	   /*Be sure to try all possible addrs for the host.*/
	   perror((char *) 0);
	
	   hostp->h_addr_list++;
	   bcopy(hostp->h_addr_list[0], (caddr_t) &address1.sin_addr,
		 hostp->h_length);


	   /*inet_ntoa is trustworthy, but we don't really need this
	     bit of code unless we are having problems .*/
	   /*	    {
		    char addr_buf[100];
		    sprintf(&addr_buf, "Attempting to connect to queue on %s\n",
		    inet_ntoa((struct in_addr)address1.sin_addr));
		    syslog(LOG_NOTICE, &addr_buf);
		    }*/
	   continue;
	 }
	
	 /*perror(hostp->h_name);*/	/*so long*/
	 sigsetmask(oldmask);
	 goto berror;
       }

       {
	 /*We create a second socket which handles sterr and also
	   control messages between the clients. This needs to be on a
	   reserved port as well.*/

	 char num[8];
	 int tempsocket, length;
	 struct sockaddr_in hello;


#ifndef NO_ROOT
	 miport--;	/* decrement for starting port# */
	 if ( (tempsocket = rresvport(&miport)) < 0)
	   goto berror;
#else
	 miport--;
	 tempsocket = socket(AF_INET, SOCK_STREAM, 0);
	 {

	   hello.sin_family=AF_INET;
	   hello.sin_addr.s_addr = htonl(INADDR_ANY);
	 portagain:
	   hello.sin_port = htons(miport);
	   if(bind(tempsocket, &hello, sizeof(hello))<0) {
	     if (miport >0) {
	       miport--;
	       goto portagain;
	     }
	     perror("bind");
	     exit(2);
	   }
	 }
#endif /*NO_ROOT*/


	 /*WGK 1998/12/24 Now we want to read our cookie from Queue to
	   make so this isn't another queue.c using the same port
	   since the old one died. Also, in NO_ROOT stops malicious
	   users in the absence of HAVE_IDENTD */

	 /*#if defined(HAVE_IDENTD) || !defined(NO_ROOT) || defined(NO_SECURITY)*/
	 /*WGK 1998/12/25 get speed back if crypt() isn't needed because portsare privileged or verifiable.*/
	 /*#define ONE_WAY(a) ""*/
	 /*#else*/
	 /*Performance hit.*/
	 /*#define ONE_WAY(a) crypt(a, "aa");*/
	 /*#endif*/

	 /*WGK 2000/07/18 sha1 ([FIPS180-1], [ANSI930-2] & [ISOIEC10118-3])
 is a much faster one-way function
than crypt, so we can simplify the code here a bit, provided MD5 compiles
correctly on your machine (use the md5test -x testing option if in doubt.
If not, you can always go back to the above code, which used slow UNIX
crypt().*/

	 #define ONE_WAY(a) sha1(a);
         #define randomstr(a) strcpy(a,"bigbird")

    {char cnounce[21], nounce[21], bigcookie[256];
    char *randomcookie;
    int k;

      randomstr(&cnounce[0]);

      /*Send cnounce, as compliant with draft protocol. WGK 2000/07/20*/
      write(fdsock1, &cnounce, strlen(cnounce)+1);

      /*Read nounce, as compliant with draft protocol. WGK 2000/07/20*/

      alarm(5);
      k = 0;
      do {
	read(fdsock1, &nounce[k], 1);
	k++;
      } while (nounce[k-1] && k<21);
      alarm(0);
      nounce[20] = 0;

      /*Response to challenge is constructed from nounce, cookie, and cnounce.*/

      strcpy(bigcookie,nounce);
      strcat(bigcookie,cookie);
      strcat(bigcookie,cnounce);

      randomcookie = ONE_WAY(bigcookie);

      /*Write the challenge response, thus proving via digest authentication we know the cookie without actually giving away what the cookie is. This concludes the mutual authentication as outlined in the draft protocol. WGK 07/20/2000 */

      write(fdsock1, &randomcookie[0], strlen(randomcookie)+1);

      /* Reverse the procedure. Read cnounce.*/

    alarm(5);
    k = 0;
    do {
      read(fdsock1, &cnounce[k], 1);
      k++;
    } while (cnounce[k-1] && k<21);
    alarm(0);
    cnounce[20] = 0;


    /*OK, cnounce read, now generate nounce.*/
    randomstr(&nounce[0]);
    write(fdsock1, &nounce, strlen(nounce)+1);

    strcpy(bigcookie,nounce);
    strcat(bigcookie,cookie);
    strcat(bigcookie,cnounce);
    {
      int flag = 0;
      char c;
      /*Crypt always returns the same number of characters, so we
	don't need to worry about the wrong daemon here.*/
      char *remotecookie;
      int k, j;
      remotecookie = ONE_WAY(bigcookie);
      j =strlen(remotecookie)+1;
      alarm(5);
      flag = 0;
      for(k=0;k<j&&!flag;k++){
	read(fdsock1, &c, 1);
	if (c != remotecookie[k]) flag = 1;
      }
      alarm(0);

      if (flag) {
	/*Alert queue.c that cookie is bad; it will have to
	  wait for a new queued */
	c = 1;
	write(fdsock1, &c, 1);
	/*die.*/
	goto berror2;
      }

	 /*All clear*/
	 c = 0;
	 write(fdsock1, &c, 1);


    }

    }

	 listen(tempsocket, 1);

	 /*Port number is written out on ASCII for queue, so that it
	   knows where to connect to.*/


	 sprintf(num, "%d", miport);
	 if (write(fdsock1, num, strlen(num)+1) != strlen(num)+1) {
	   syslog(LOG_ERR, "write: setting up queued control/stderr socket: %m");
	   close(tempsocket);
	   goto berror;
	 }

	 FD_ZERO(&readfdesc);
	 FD_SET(fdsock1, &readfdesc);
	 FD_SET(tempsocket, &readfdesc);
	 errno = 0;
	 if ((select(32, &readfdesc, (fd_set *) 0, (fd_set *) 0,
		     (struct timeval *) 0) < 1) ||
	     !FD_ISSET(tempsocket, &readfdesc)) {
	   if (errno != 0)
	     syslog(LOG_ERR, "select: setting up queued control/stderr socket: %m");
	   else
	     syslog(LOG_ERR,
		    "select: Strangeness in setting up queued control/stderr socket.\n");
	   close(tempsocket);
	   goto berror;
	 }

	 /*accept to the connect from queue.*/

	 length = sizeof(address2);
	 fdsock2 = accept(tempsocket, &address2, &length);
	 close(tempsocket);	
	 if (fdsock2 < 0) {
	   syslog(LOG_ERR, "accept on secondary socket: %m");
	   miport = 0;
	   goto berror2;
	 }

#ifndef NO_ROOT

	 /*Verify that queue is connecting to us via a reserved port
           as well.*/

	 address2.sin_port = ntohs((u_short) address2.sin_port);
	 if ((address2.sin_family != AF_INET) ||
	     (address2.sin_port >= IPPORT_RESERVED) ||
	     (address2.sin_port <  IPPORT_RESERVED/2)) {
	   syslog(LOG_ERR,
		  "queued: Remote queue did not bind from a reserved port!\n");
	   goto berror2;
	 }
#else
#ifdef HAVE_IDENTD
	 /*We don't use reserved ports since we can't get root, so we
	   try to use identd information instead to prevent another
	   user on the same host from masquerading as the legitimate
	   queue.*/



	 if(!check_ident(&hello, &address2)) {
	   syslog(LOG_ERR,
		  "queued: Remote queue host returned bad identd information and -DHAVE_IDENTD was set!\n");
	   goto berror2;
	 }
		
#endif /*HAVE_IDENTD*/
#endif /*NO_ROOT*/
       }

       alarm(5);
       if (read(fdsock1, &c, 1) != 1) {	
	 /* to start off, read a status byte from server.*/
	 syslog(LOG_ERR, "Queued: Failed to read status byte from queue\n");
	 goto berror2;
       }
       alarm(0);


       if (c != 0) {
	 alarm(30);
	 /*Non-zero staus byte indicates an error on the queue side.*/

	 while (read(fdsock1, &c, 1) == 1) {
	   write(2, &c, 1);
	   if (c == '\n')
	     break;
	 }
	 alarm(0);
	 goto berror2;
       }

       sigsetmask(oldmask);


	


       /* We want to turn on SO_KEEPALIVE so that we can detect when
	  either one of the daemons has gone down, such as due to a
	  host or client crash.*/

       if (keepalive &&
	   setsockopt(fdsock2, SOL_SOCKET, SO_KEEPALIVE, (char *) &one,
		      sizeof(one)) < 0)
	 syslog(LOG_WARNING, "setsockopt SO_KEEPALIVE error: %m");

       if (pipe(fdpipe) < 0) {
	 syslog(LOG_ERR, "Can't make pipe.\n");
	 exit(1);
       }

       if (fdpipe[0] > fdsock2)
	 maxfdp1 = fdpipe[0];
       else
	 maxfdp1 = fdsock2;
       maxfdp1++;

     }
     if(ttyinput||ttyoutput) {
       if((pty1 = allocpty())<0) {
	 FILE *temp;
	 temp = fdopen(fdsock2, "w");
	 fprintf(temp, "No more ptys.\n");
	 syslog(LOG_ERR, "No more ptys.\n");
	 fclose(temp);
	 exit(2);
       }
       fchown(pty1, 0, 0);
       fchmod(pty1, S_IRUSR|S_IWUSR);
     }
   }
   dead = 0;

   {
#ifdef __hpux
     struct sigvec mysignal;
     mysignal.sv_handler = chldsigh;
     mysignal.sv_mask = ~sigmask(SIGCHLD);
     mysignal.sv_flags = SV_BSDSIG;
     sigvector(SIGCHLD, &mysignal, NULL);
     mysignal.sv_handler = bigsigh;
     sigvector(SIGUSR1, &mysignal, NULL);
     sigvector(SIGUSR2, &mysignal, NULL);
     sigvector(SIGCONT, &mysignal, NULL);
     sigvector(SIGTERM, &mysignal, NULL);
#else /*GNU/Linux*/
     struct sigaction mysignal;
     mysignal.sa_handler = chldsigh;

     /*See previous comment.*/
     *((unsigned long int*) &mysignal.sa_mask) = ~sigmask(SIGCHLD);

     /*#ifdef linux
       mysignal.sa_mask.__val[0] = ~sigmask(SIGCHLD);
       #else
       mysignal.sa_mask.__sigbits[0] = ~sigmask(SIGCHLD);
       #endif
     */

     mysignal.sa_flags = SA_RESTART; /*BSD signal behavior*/
     sigaction(SIGCHLD, &mysignal, NULL);
     mysignal.sa_handler = bigsigh;
     sigaction(SIGUSR1, &mysignal, NULL);
     sigaction(SIGUSR2, &mysignal, NULL);
     sigaction(SIGCONT, &mysignal, NULL);
     sigaction(SIGTERM, &mysignal, NULL);
#endif
     mywait = 0;
     sigsetmask(~(sigmask(SIGCHLD)|sigmask(SIGUSR1)|sigmask(SIGUSR2)|sigmask(SIGCONT)|sigmask(SIGTERM)));
   }

   fflush(stdout);
   fflush(stdin);
   setsid();
   setpgid(0, 0);

   if((donthang==0) && (ttyinput||ttyoutput)){
     if((pty2 = open(mtos(), O_RDWR))<0) {
       syslog(LOG_ERR, "slave pty fd # %d open: %s %m", pty1, mtos());
       exit(2);
     }
   }

#if FORK > 0
   if((pid=fork())==0) {
#endif

     close(fd3);

     setpgid(0, 0);

     if(ttyinput||ttyoutput) {
       tcsetpgrp(pty2, getpid());

#ifndef NO_ROOT
       /*Without privileges, we can't create a utmp entry.*/
       mkutmp("root", pty2, uid, gid);
#endif

       tcflush(pty2, TCIOFLUSH);
#ifdef TCSANOW
       /*IRIX requires TCSANOW to be present.*/
       if(tcsetattr(pty2, TCSANOW, &globalterm)<0) {
	 syslog(LOG_ERR, "tcsetattr on fd %d: %m", pty2);
	 exit(2);
       }
#else
       if(tcsetattr(pty2, 0, &globalterm)<0) {
	 syslog(LOG_ERR, "tcsetattr on fd %d: %m", pty2);
	 exit(2);
       }
#endif /*TCSANOW*/
#ifdef TIOCSWINSZ
       if(ioctl (pty2, TIOCSWINSZ, (char *)&ws) <0) {
	 syslog(LOG_ERR, "ioctl TIOCSWINSZ: %m");
	 exit(2);
       };
#endif
     }

     umask(mask);
#ifndef NO_ROOT
     if(setgroups(ngroups, gidset)<0){
       syslog(LOG_ERR, "setgroups: %m");
       exit(2);
     }
#endif

     free(gidset);

#if defined(HAVE_SYS_AUDIT_H) && defined(__hpux)
     setaudid(aid); /*HP-UX*/
#endif

     /* WGK 98/08/06 the latest GNU/Linux kernel has implemented
       setresuid but not setresgid, even though it is documented in
       the man page. :-(

       When the effective user id is root, setgid(x) should be
       equivalent to setresgid(x, x, x) so, it shouldn't matter for
       this application.  (They are _not_equivalent when the effective
       user is not root, which is why setgid IMHO should be made
       obsolete as it behaves quite differently depending on who the
       user is.)  */

#ifdef HAVE_SETRESGID
     if(setresgid(gid, gid, gid)<0) {
       /*GNU/Linux kernel doesn't support it yet?*/
#endif
       if(setgid(gid)<0) {
#ifndef NO_ROOT
	 syslog(LOG_ERR, "setgid: %m");
	 exit(2);
#endif
	 ;
       }
#ifdef HAVE_SETRESGID
     }
#endif

#ifndef NO_ROOT
#ifdef HAVE_SETRESUID
     if(setresuid(uid, uid, uid)<0) {
       /*GNU/Linux kernel doesn't support it yet?*/
#endif

       if (setuid(uid)<0) {
	 syslog(LOG_ERR, "setuid: %m");
	 exit(2);
       }
#ifdef HAVE_SETRESUID
     }
#endif /*HAVE_SETRESUID*/
#endif /*NO_ROOT*/

     setpriority(PRIO_PROCESS, 0, prio);
     /*   for(i=0;i<8;++i) {
       static struct rlimit templimit;*/
       /*Do not

WGK 2000/08/11 Eric Deal <*****@*****.**> pointed out that this
"Do not" comment looks bogus, because it goes too far into the code.

The entire for loop should be commented out, which I've now this. This
probably created another bug involving Xwindows applications that close
stdin and stdout that wasn't present in old versions of Queue.
*//*
	 getrlimit(i, &templimit);

	 (templimit.rlim_curr < myrlimit[i].rlim_curr ? myrlimit[i].rlim_curr = templimit.rlim_curr)
	 (templimit.rlim_max < myrlimit[i].rlim_max ? myrlimit[i].rlim_max = templimit.rlim_max)
	 ssetrlimit(i, &myrlimit[i]);
	 }*/

	 closelog();

	 fflush(stdout);
	 fflush(stderr);

	 #if FORK > 0
	 if(donthang==1)
	 {
	 int fd;
	 fd = open("/dev/null", O_RDWR);
	 dup2(fd, 0);
	 if(mail!=1) {
	 dup2(fd, 2);
	 dup2(fd, 1);
	 }
	 close(fd);
	 }
	 else {
	 #endif

	 close(fdsock2);		/* control process handles this fd */
       close(fdpipe[0]);	/* close read end of pipe */
       dup2(fdpipe[1], 2);	/* stderr of shell has to go through
				   pipe to control process */
       close(fdpipe[1]);
       if(ttyoutput==0) dup2(fdsock1, 1);
       else {dup2(pty2, 1);
       if(ttyerror) {
	 dup2(pty2, 2);
       }
       }
       if(ttyinput==0) dup2(fdsock1, 0);
       else {dup2(pty2, 0);
       }
       if(!(ttyinput||ttyoutput)) close(fdsock1);
       /*
	 For some bizarre reason adding this breaks everything
	 else close(pty2);*/

#if FORK > 0

     }

#endif

     /*We chdir as the user because, under NFS, we are more likely to
       get there as the real user, and also because this way stderr is OK
       so that we can send over a message.*/

     if (chdir(dirname)<0) {
       char junk[256];
       if(gethostname(junk, 255)==0){
	 junk[255] = 0;
	 fprintf(stderr, "queued: chdir to %s on host %s failed.\n", dirname, junk);
       }

     }
     else
       {
	 register int i, tmp;
	 char *path, *cur, *start, *end;
	 char **search;
#define MAXCMD 1024
	 char file[MAXCMD+1];
	 char flag = 0;
	 int len;

	 if((*command[0] == '/') || (*command[0] == '.'))  {
	   strncpy(file, command[0], MAXCMD);
	   file[MAXCMD] = 0;
	   if(access(file, X_OK)==0)   flag = 1;
	 }
	 else {

	   /*1999/02/13 WGK bugfix. Search through estack to find PATH.*/

	   len = MAXCMD - strlen(command[0]) - 1;

	   path = NULL;

	   {char **tmp = estack;
	   while(tmp && *tmp && **tmp) {
	     if(!strncmp(*tmp, "PATH=", 5)) {
	       path = *tmp + 5;
	       break;
	     }
	     tmp++;
	   }
	   }

	   if(path && *path) {
	     cur = path;
	     end = path + strlen(path);
	     start = cur;
	     while(cur++!=end) {
	       if(((cur==end)||(*cur==':'))&&((cur-start)<len)) {
		 strncpy(file, start, cur - start);
		 file[cur-start] = 0;
		 strcat(file, "/");
		 strcat(file, command[0]);
		 if(access(file, X_OK)==0) {
		   flag = 1;
		   break;
		 }
		 start = cur + 1;
	       }
	     }
	   }
	 }

	 if(!flag) {
	   fprintf(stderr, "%s: Command not found.\n", command[0]);
	   fflush(stderr);
	   /*WGK 98/12/23 Bugfix Not sure why a simple exit doesn't
	     work here (it seemed to work on some operating systems
	     after a sleep.

	     Instead, we'll do the normal the signal-handler stuff and
	     then do an exit(2) instead of the exec. This seems to fix
	     the problem.

	     What may be happening is that we receive notification of
	     our death or something via signals (perhaps a pipe/socket
	     related signal) and this causes a hang in exit in our
	     signal handler; clearing all signals before exit fixes
	     the problem. Of course, then it's not clear why a sleep()
	     seemed to fix it sometimes as well. */
	 }
	 {
	   register int i;
#ifdef __hpux
	   for(i=0;i<64;++i) sigvector(i, SIG_DFL, NULL);
#else
	   /*GNU/Linux*/
	   struct sigaction myaction;
	   myaction.sa_handler= SIG_DFL;
	   for(i=0;i<64;++i) sigaction(i, &myaction, NULL);
#endif
	   sigsetmask(0L);
	 }
	 /*WGK 1999/3/5 restart kernel API.*/
#ifdef HAVE_ASM_CHECKPOINT_H
	 if (checkpoint==KERNEL_CHECKPOINT && flag) {
	   ret=collect_data(getpid());
	   if (ret!=0)
	     {
	       fprintf(stderr, "Error (%d) preparing to collect data\n", ret);
	       exit(2);
	     }
	 }

	 if((checkpoint==KERNEL_CHECKPOINT) && flag && restart == RESTART && restartdata && *restartdata) {
	   mrestart(restartdata);
	   /*Normally not reached.*/
	   fprintf(stderr, "QueueD: handle: In process migration, unable to restart file %s\n",
		   restartdata);
	   exit(2);
	 }
#endif /*HAVE_ASM_CHECKPOINT_H*/

	 if (flag) execve(file, command, estack);
       }
     /*WGK 98/12/23 Command not found or problem with the exec.*/
     exit(2);

#if FORK > 0
   }
#endif

   close(filedes[0]);

   if(donthang == 0) {
     int null;
     close(fdpipe[1]);	/*Close the write end of pipe.*/

     null = open("/dev/null", O_RDWR);

     FD_ZERO(&readfrom);

     FD_SET(fdsock2, &readfrom);
     /*The following line is needed because of the drain code.*/
     fcntl(fdsock2, F_SETFL, O_NDELAY);
     FD_SET(fdpipe[0], &readfrom);
     fcntl(fdpipe[0], F_SETFL, O_NDELAY);
     if (ttyinput) {
       FD_SET(fdsock1, &readfrom);
       fcntl(fdsock1, F_SETFL, O_NDELAY);
     }
     if (ttyoutput) {
       FD_SET(pty1, &readfrom);
       /* Very important! */
       fcntl(pty1, F_SETFL, O_NDELAY);
     }
     if(!(ttyoutput||ttyinput))	close(fdsock1);

     do {
       ready = readfrom;
       if (select(32, &ready, (fd_set *) 0,
		  (fd_set *) 0, (struct timeval *) 0) < 0)
	 /* wait until something to read */
	 {if(errno!=EINTR) break;
	 if(dead) {
	   FD_CLR(fdsock2, &readfrom);
	   if(ttyinput||ttyoutput) {
	     FD_CLR(fdsock1, &readfrom);
	     if(FD_ISSET(pty1, &readfrom)){
	       /*without the next line we sometimes go infinite loop!*/
	       FD_SET(pty1, &ready);
	       /*We can't do a select because select will block on the
		 dead pty.  But, we could still need to drain stderr
		 too! So set this, and let nblocking worry about the
		 rest.*/
	       FD_SET(fdpipe[0], &ready);
	       goto drain;}
	   }
	 }
	 continue;
	 }
     drain:				
       if (FD_ISSET(fdsock2, &ready)) {
	 static char sigval;
	 if ((read(fdsock2, &sigval, 1)) <=0) {
	   /*The death of the control stream
	     is ominous. We invoke the
	     our SIGTERM handler.*/
				/*	raise(SIGTERM); */
	   FD_CLR(fdsock2, &readfrom);
	 }
	 else {

	   /*printf ("Received: %d\n", (int) sigval);*/

	   /* WK 95/7/10: A determined user may restart a stopped job
	      anyway by directly sending SIGCONT to the process, and
	      we would be none the wiser since wait() would not tell
	      us the process was restarted. Only actively scanning the
	      process table entry would alert us to this
	      situation. Since we don't do this, I see no reason to be
	      HAVE_IDENTD over SIGCONTs comming from the stub. A
	      second problem is that some signals, eg SIGTERM, are
	      followed by a SIGCONT by the operating system (HP-UX) to
	      force the process to resume prior to termination. So, if
	      the user sends over a SIGTERM and we propagate, we are,
	      in effect, sending a SIGCONT too. We could catch this,
	      but it gets complicated and may prevent the user from
	      killing stopped jobs before they restart.*/

	   if(((int)sigval==SIGCONT)&(ttyinput||ttyoutput))
	     tcsetpgrp(pty1, pid);


	   /*If the signal is SIGWINCH we can expect the window size
             to be sent as well.*/
#ifdef TIOCSWINSZ
	   if (((int)sigval == SIGWINCH) & (ttyinput||ttyoutput)) {
	     struct winsize ws;
	     /*WGK Our code in WINCH ensures that all of this is sent
	       as a single packet, so we need not be concerned about
	       the fact that we are non-blocking here.*/
	     read(fdsock2, &ws, sizeof(ws));
	     /*printf ("Queued New window size: %d %d\n", ws.ws_row, ws.ws_col);*/
	     /*WGK note: On some systems the following ioctl will
               generate a SIGWINCH as well.*/
	     ioctl (pty1, TIOCSWINSZ, (char *)&ws);
	   }
#endif

	   kill(-pid, (int) sigval);
	 }
       }
       if (FD_ISSET(fdpipe[0], &ready)) {
	 static int cc;
	 static char buf[BUFSIZ];
	 errno = 0;
	 cc = read(fdpipe[0], buf, sizeof(buf));
	 if (cc <= 0) {
	   FD_CLR(fdpipe[0], &readfrom);
	 } else
	   write(fdsock2, buf, cc);
       }

       if ((ttyinput|ttyoutput) && FD_ISSET(pty1, &ready)) {
	 static int cc;
	 static char buf[BUFSIZ];
	 errno = 0;
	 cc = read(pty1, buf, sizeof(buf));
	 if (cc <= 0) {
	   FD_CLR(pty1, &readfrom);
	 } else
	   write(fdsock1, buf, cc);
       }
       if (FD_ISSET(fdsock1, &ready)) {
	 static int cc;
	 static char buf[BUFSIZ];
	 errno = 0;
	 cc = read(fdsock1, buf, sizeof(buf));
	 if (cc <= 0) {
	   FD_CLR(fdsock1, &readfrom);
	 } else
	   /*We should only be here if
	     ttyinput, otherwise we would have given up fdsock1.*/
	   /*assert(ttyinput);*/
	   write(pty1, buf, cc);
       }
       if(dead) {
	 FD_CLR(fdsock2, &readfrom);
	 if(ttyinput||ttyoutput) {
	   FD_CLR(fdsock1, &readfrom);
	   if(FD_ISSET(pty1, &readfrom)){
	     FD_SET(fdsock2, &ready);
	     FD_SET(pty1, &ready);
	     goto drain;}
	 }
       }
			
     } while (FD_ISSET(fdsock2, &readfrom) ||
	      FD_ISSET(fdpipe[0], &readfrom)||
	      ((ttyinput|ttyoutput)&&FD_ISSET(pty1, &readfrom))
	      ||FD_ISSET(fdsock1, &readfrom));
     close(null);
     close(fdpipe[0]);
     if(ttyinput||ttyoutput) {
       /*We need pty2 help open in case process suspends. If no active
	 process on pty2, pty2 process group gets HANGUP.*/
       close(pty2);
       close(pty1);
       close(fdsock1);
       deallocpty();
     }
   }

   /* WK 95/7/10 We wait here until the SIGCHLD handler puts our wait
      status into newwait. Actually, will the above mess even
      terminate if dead is not set? Yes, but only under wierd
      conditions in which the sockets are closed prematurely and the
      child is subsequently killed. Sleep(3c) is supposed to be
      interrupted by caught signals, so we should be OK.*/

   while (!dead) sleep(1);

   /* Shut it down*/
   sigsetmask(~0L);

   /*Stub will die after fdsock2 is closed, so we don't want that to
     happen until we know exit status has been delivered via dead
     above.*/

   close(fdsock2);

   if(donthang==1) queue = fdopen(filedes[1], "w");
   else {
     close(filedes[1]);
     queue=fopen("/dev/null", "w");
   }
   /*Get rid of anything else*/

   wait(NULL);

   /*Simulate exit status of child.*/

   if(WIFEXITED(mywait)!=0) exit(WEXITSTATUS(mywait));
   if(WCOREDUMP(mywait)==0) {
     /*Process did not dump core, so prevent a simulated core dump.*/
     struct rlimit rlp;
     rlp.rlim_cur = 0;
     rlp.rlim_max = 0;

#ifdef __hpux
#define RLIMIT_CORE 4
#endif

     setrlimit(RLIMIT_CORE, &rlp);
   }
   if(WIFSIGNALED(mywait)==0)
     fprintf(queue, "\nShell terminated from unknown cause.\n");
   fflush(stdout);
   fclose(queue);
   if(WIFSIGNALED(mywait)!=0) {
     signal(WTERMSIG(mywait), SIG_DFL);
     sigsetmask(~sigmask(WTERMSIG(mywait)));
     /*Make sure everything gets flushed out.*/
     /*_cleanup();*/
     fflush(NULL);
     raise(WTERMSIG(mywait));
   }
   exit(2);


   /*Connection to qhang failed.*/
 berror2:
   if(donthang==0) close(fdsock2);
 berror:
   if(donthang==0) {close(fdsock1);
   sigsetmask(oldmask);
   close(filedes[0]);
   close(filedes[1]);
   break;
   }
 }
exit(2);
}
Beispiel #13
0
static void pike_top(rpc_t *rpc, void *c)
{

	DBG("pike: top");

	int i;
	void *handle;
	struct TopListItem_t *top_list_root;
	struct TopListItem_t *ti = 0;
	char addr_buff[40];
	char *ip_addr = 0;
	char *leaf_hits_prev = 0;
	char *leaf_hits_curr = 0;
	char *expires = 0;
	char *status = 0;
	size_t ip_addr_size = 0;
	size_t leaf_hits_prev_size = 0;
	size_t leaf_hits_curr_size = 0;
	size_t expires_size = 0;
	size_t status_size = 0;
	
	char *stropts;
	int   options = 0;
	
	/* obtain params */
	if (rpc->scan(c, "s", &stropts) <= 0)
		stropts = "HOT";

	DBG("pike:top: string options: '%s'", stropts);
	if ( strstr(stropts, "ALL") ) { 
		options = NODE_STATUS_ALL;
	} else if ( strstr(stropts, "HOT") ) {
		options |= NODE_STATUS_HOT;
	} else if ( strstr(stropts, "WARM") ) {
		options |= NODE_STATUS_WARM;
	}
	DBG("pike:top: options: 0x%02x\n", options);
	
	
	print_tree( 0 );
	
	collect_data(options);
	top_list_root = pike_top_get_root();
	DBG("pike_top: top_list_root = %p", top_list_root);
	
	rpc->add(c, "{", &handle);
	rpc->struct_add(handle, "d", "max_hits", get_max_hits());
	i = 0; // it is passed as number of rows
	if ( top_list_root == 0 ) {
		DBG("pike_top: no data");
	}
	else {
		for( ti = top_list_root, i = 0; ti != 0; ti = ti->next, ++i ) {
			pike_top_print_addr(ti->ip_addr, ti->addr_len, addr_buff, sizeof(addr_buff));
			DBG("pike:top: result[%d]: %s leaf_hits[%d,%d] hits[%d,%d] expires: %d status: 0x%02x",
					i, addr_buff, ti->leaf_hits[0], ti->leaf_hits[1],
					ti->hits[0], ti->hits[1], ti->expires, ti->status); 
			rpc->struct_add(handle, "sddds",
							concat(ip_addr, ip_addr_size, "ip_addr", i), addr_buff,
							concat(leaf_hits_prev, leaf_hits_prev_size, "leaf_hits_prev", i), ti->leaf_hits[0],
							concat(leaf_hits_curr, leaf_hits_curr_size, "leaf_hits_curr", i), ti->leaf_hits[1],
							concat(expires, expires_size, "expires", i), ti->expires,
							concat(status, status_size, "status", i), node_status_array[ti->status]);
		}
	}
	rpc->struct_add(handle, "d", "number_of_rows", i);
	/* free buffers */
	free(ip_addr);
	free(leaf_hits_prev);
	free(leaf_hits_curr);
	free(expires);
	free(status);
	pike_top_list_clear();
	
	rpc->send(c);
}
Beispiel #14
0
int main(int argc, char **argv)
{
	

	//#setup#
	//data_collector is responsible for processing 
	//any files specified in the user-specified options.
	set_error_file(stderr);


	int temp_status = temp_init();
	if(temp_status != 0)
	{
		die("error %d: temperature sensor initialization", 
			temp_status);
	}

	if(INTERVAL < MIN_INTERVAL)
	{
		die("error: INTERVAL %d is less than %d\n", 
			(int)INTERVAL,	(int)MIN_INTERVAL);
	}

//	sigemptyset(&mask_chld);
//	sigaddset(&mask_chld, SIGCHLD);

	//if(signal(SIGCHLD, child_terminated) == SIG_ERR)
	//{
	//	die("setting SIGCHLD handler failed\n");
	//}

	options_populate(argc, argv);

	//Determine the proper error file ASAP.
	//Otherwise keep the default, stderr, set above.
	if(options_opt.error_file != NULL)
	{
		if(!options_opt.append_error && 
			(access(options_opt.output_file, F_OK) != -1))
		{
			die("Error file %s already exists and -a not specified\n", 
				options_opt.error_file);
		}

		//Open in append mode. If the file doesn't exist,
		//it will be created.
		set_error_file(fopen(options_opt.error_file, "a"));
	}
		
	timeout_ms = options_opt.timeout_sec*1000;
		
	//##open file##
	//If an output file is unspecified by the user, output
	//to stdout.
	if(options_opt.output_file != NULL)
	{
		if(access(options_opt.output_file, F_OK) != -1)
		{
			die("File %s already exists\n", options_opt.output_file);
		}

		output_file_handle = fopen(options_opt.output_file, "w");
	}
	else
	{
		output_file_handle = stdout;
	}

	start_power();

	#ifdef COLLECT_PWS
	init_pws();
	start_pws();	
	#endif 
	//signal typically returns a pointer to the previous
	//signal handler, but can also error
	//if(signal(SIGALRM, collect) == SIG_ERR)
	//{
	//	fprintf(stderr, "error: could not set SIGALRM signal handler\n");
	//	exit(1);
	//}

	//#debug#
	collect_data();
	


		


	
	//#loop#
//	alarm(INTERVAL);
//	pause();

	//#cleanup#
	fclose(output_file_handle);
	temp_cleanup();
	power_cleanup();
	delete_options();

	#ifdef COLLECT_PWS
	pws_cleanup();
	#endif

}
Beispiel #15
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(shell_sequence_process, ev, data) {

	static struct etimer etimer;

	PROCESS_EXITHANDLER(leds_off(LEDS_ALL));

	PROCESS_BEGIN();

	static uint16_t temp3;
	temp3 = mylog(std_dev_0/std_dev_1);

	// Error probability parameters
	// alpha = 0.001 - Probability of false alarm.
	// beta = 0.001 - Probability of miss.
	static int b = 7;	// b = log((1-beta)/alpha) = 6.9068

	// Variables
	uint16_t observation;
	static int16_t S_n;
	// Make sure to actually reset S_n every time we run a sequence.
	S_n = 0;
	static int16_t suff_stat = 0;
	static int16_t min_level;
	min_level = 0;
	uint16_t temp1 = 0;
	uint16_t temp2 = 0;
	static int decision;
	// Make sure to actually reset decision every time we run a sequence.
	decision = 0;
	int a = 0;
	int c = 0;

	etimer_set(&etimer, (CLOCK_SECOND / 16));

	while(1) {

		blink_LEDs(LEDS_ALL);

		// Get reading from sensor.
		SENSORS_ACTIVATE(light_sensor);

		// Give the sensors time to activate before taking a reading.
		PROCESS_WAIT_UNTIL(etimer_expired(&etimer));
		etimer_set(&etimer, 11 * (CLOCK_SECOND / 16));
		observation = light_sensor.value(LIGHT_SENSOR_PHOTOSYNTHETIC);
		SENSORS_DEACTIVATE(light_sensor);

		printf("cusum-seq: observation = %d\n",observation);

		// Calculate new statistic based on:
		// suff_stat = log(std_dev_0/std_dev_1)
		// - ((observation - mean_1)^2) / (2*(std_dev_1^2)
		// + ((observation - mean_0)^2) / (2*(std_dev_0^2)	
		//suff_stat =  log(std_dev_0 / std_dev_1) - pow2(observation - mean_1) / (2*pow2(std_dev_1)) + pow2(observation - mean_0) / (2*pow2(std_dev_0));

		a = abs_sub(observation, mean_1);
		c = abs_sub(observation, mean_0);

		// If a or c is too large, calculating temp1 or temp2 can be tough.
		temp1 = temp3 + log_exp_term(c, std_dev_0);
		temp2 = log_exp_term(a, std_dev_1);
		suff_stat = temp1 - temp2;

		// Do appropriate overflow protection.
		if(S_n/2 + suff_stat/2 > 16384 ) {
			S_n = 32767;
		} else if( S_n/2 + suff_stat/2 < -16384) {
			S_n = -32768;
		} else {
			S_n = S_n + suff_stat;
		}

		// Reset the min_level appropriately.
		if(S_n < min_level) {
			min_level = S_n;
		}

		// DEBUG CODE
		printf("cusum-seq: min_level = %d\n",min_level);
		printf("cusum-seq: S_n = %d\n\n",S_n);

			
		// Make decision based on statistic.
		if(S_n >= b + min_level) {
			
			leds_on(LEDS_RED);

			rimeaddr_t addr;
			packetbuf_copyfrom("Change detected", strlen("Change detected"));
			addr.u8[0] = 62;
			addr.u8[1] = 41;
			mesh_send(&mesh, &addr);

			// Send out an observation of data if change detected.
			collect_data(&sequence_command);

			//PROCESS_END();
			if(STOP_MODE) {
				leds_off(LEDS_RED);
				PROCESS_EXIT();
			}
		}

		PROCESS_WAIT_UNTIL(etimer_expired(&etimer));
	}

	PROCESS_END();
}
Beispiel #16
0
static int asn1_collect(BUF_MEM *buf, const unsigned char **in, long len,
			char inf, int tag, int aclass, int depth)
	{
	const unsigned char *p, *q;
	long plen;
	char cst, ininf;
	p = *in;
	inf &= 1;
	/* If no buffer and not indefinite length constructed just pass over
	 * the encoded data */
	if (!buf && !inf)
		{
		*in += len;
		return 1;
		}
	while(len > 0)
		{
		q = p;
		/* Check for EOC */
		if (asn1_check_eoc(&p, len))
			{
			/* EOC is illegal outside indefinite length
			 * constructed form */
			if (!inf)
				{
				ASN1err(ASN1_F_ASN1_COLLECT,
					ASN1_R_UNEXPECTED_EOC);
				return 0;
				}
			inf = 0;
			break;
			}

		if (!asn1_check_tlen(&plen, NULL, NULL, &ininf, &cst, &p,
					len, tag, aclass, 0, NULL))
			{
			ASN1err(ASN1_F_ASN1_COLLECT, ERR_R_NESTED_ASN1_ERROR);
			return 0;
			}

		/* If indefinite length constructed update max length */
		if (cst)
			{
			if (depth >= ASN1_MAX_STRING_NEST)
				{
				ASN1err(ASN1_F_ASN1_COLLECT,
					ASN1_R_NESTED_ASN1_STRING);
				return 0;
				}
			if (!asn1_collect(buf, &p, plen, ininf, tag, aclass,
						depth + 1))
				return 0;
			}
		else if (plen && !collect_data(buf, &p, plen))
			return 0;
		len -= p - q;
		}
	if (inf)
		{
		ASN1err(ASN1_F_ASN1_COLLECT, ASN1_R_MISSING_EOC);
		return 0;
		}
	*in = p;
	return 1;
	}
Beispiel #17
0
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
	case WM_CREATE:
	{
		SetWindowText(hWnd, L"Sender");
		color_radiogroup = CreateWindow(L"BUTTON", L"Color", WS_VISIBLE | WS_CHILD | BS_GROUPBOX,
			50, 50, 100, 100, hWnd, NULL, hInst, NULL);
 		CreateWindow(L"BUTTON", L"Red", WS_VISIBLE | WS_CHILD | BS_AUTORADIOBUTTON,
			7, 20, 60, 10, color_radiogroup, (HMENU)IDC_RED_RADIO, hInst, NULL);
		CreateWindow(L"BUTTON", L"Green", WS_VISIBLE | WS_CHILD | BS_AUTORADIOBUTTON,
			7, 40, 60, 10, color_radiogroup, (HMENU)IDC_GREEN_RADIO, hInst, NULL);
		CreateWindow(L"BUTTON", L"Blue", WS_VISIBLE | WS_CHILD | BS_AUTORADIOBUTTON,
			7, 60, 60, 10, color_radiogroup, (HMENU)IDC_BLUE_RADIO, hInst, NULL);

		shape_radiogroup = CreateWindow(L"BUTTON", L"Shape", WS_VISIBLE | WS_CHILD | BS_GROUPBOX,
			150, 50, 100, 100, hWnd, NULL, hInst, NULL);
		CreateWindow(L"BUTTON", L"Diamond", WS_VISIBLE | WS_CHILD | BS_AUTORADIOBUTTON,
			7, 20, 80, 10, shape_radiogroup, (HMENU)IDC_DIAMOND_RADIO, hInst, NULL);
		CreateWindow(L"BUTTON", L"Square", WS_VISIBLE | WS_CHILD | BS_AUTORADIOBUTTON,
			7, 40, 80, 10, shape_radiogroup, (HMENU)IDC_SQUARE_RADIO, hInst, NULL);
		CreateWindow(L"BUTTON", L"Circle", WS_VISIBLE | WS_CHILD | BS_AUTORADIOBUTTON,
			7, 60, 80, 10, shape_radiogroup, (HMENU)IDC_CIRCLE_RADIO, hInst, NULL);
		CreateWindow(L"BUTTON", L"Star", WS_VISIBLE | WS_CHILD | BS_AUTORADIOBUTTON,
			7, 80, 80, 10, shape_radiogroup, (HMENU)IDC_STAR_RADIO, hInst, NULL);
		checkbox_draw = CreateWindow(L"BUTTON", L"Draw", WS_VISIBLE | WS_CHILD | BS_CHECKBOX,
			50, 155, 80, 10, hWnd, (HMENU)IDC_CHECKBOX_DRAW, hInst, NULL);

		WM_SETCOLOR = RegisterWindowMessage(L"set_drawing_color");
		WM_SETSHAPE = RegisterWindowMessage(L"set_drawing_shape");
		WM_DISACTIV = RegisterWindowMessage(L"dis_activate");

		SetTimer(hWnd, IDT_TIMER1, 100, NULL);
		break;
	}
	case WM_TIMER:
	{
		switch (wParam) {
		case IDT_TIMER1:
			collect_data(hWnd);
			target_hwnd = FindWindow(NULL, L"Accessor");
			if (target_hwnd != NULL) {
				SendMessage(target_hwnd, WM_SETCOLOR, (WPARAM)current_state.color, NULL);
				SendMessage(target_hwnd, WM_SETSHAPE, (WPARAM)current_state.shape, NULL);
				SendMessage(target_hwnd, WM_DISACTIV, (WPARAM)current_state.active, NULL);
			}
			break;
		}
		break;
	}
    case WM_COMMAND:
        {
            int wmId = LOWORD(wParam);
            // Parse the menu selections:
            switch (wmId)
            {
            case IDM_EXIT:
                DestroyWindow(hWnd);
                break;
			case IDC_CHECKBOX_DRAW:
			{
				bool checked = IsDlgButtonChecked(hWnd, IDC_CHECKBOX_DRAW);
				if (!checked) {
					CheckDlgButton(hWnd, IDC_CHECKBOX_DRAW, BST_CHECKED);
				}
				else {
					CheckDlgButton(hWnd, IDC_CHECKBOX_DRAW, BST_UNCHECKED);
				}
				break;
			}
            default:
                return DefWindowProc(hWnd, message, wParam, lParam);
            }
        }
        break;
    case WM_PAINT:
        {
            PAINTSTRUCT ps;
            HDC hdc = BeginPaint(hWnd, &ps);
            // TODO: Add any drawing code that uses hdc here...
            EndPaint(hWnd, &ps);
        }
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}
Beispiel #18
0
/* finish the emergency call frees resources:
   - pull call cell this call from list linked eme_calls
   - send esct to VPC to release ESQK Key*/
int send_esct(struct sip_msg *msg, str callid_ori, str from_tag){

	char* esct_callid;
	NODE* info_call;
	char* xml = NULL;
	time_t rawtime;
	struct tm * timeinfo;
	char* response;
	int resp;
	char* callidHeader;
	char* ftag;
	unsigned int hash_code;
	str callid;

	callidHeader = pkg_malloc(callid_ori.len + 1);
	if(callidHeader == NULL){
		LM_ERR("No memory left\n");
		return -1;
	}
	memset(callidHeader, 0, callid_ori.len + 1);
	memcpy(callidHeader, callid_ori.s, callid_ori.len);


	ftag = pkg_malloc(from_tag.len + 1);
	if(ftag == NULL){
		LM_ERR("No memory left\n");
		return -1;
	}
	memset(ftag, 0, from_tag.len + 1);
	memcpy(ftag, from_tag.s, from_tag.len);


	// extract call cell with same callid from list linked eme_calls
	LM_DBG(" --- BYE  callid=%s \n", callidHeader);

	callid.s = callidHeader,
		callid.len = strlen(callidHeader);

	hash_code= core_hash(&callid, 0, emet_size);
	LM_DBG("********************************************HASH_CODE%d\n", hash_code);

	info_call= search_ehtable(call_htable, callidHeader, ftag, hash_code, 1);
	if (info_call == NULL) {
		LM_ERR(" --- BYE DID NOT FIND CALLID \n");
		return -1;
	}else{
		if (collect_data(info_call, db_url, *db_table) == 1) {
			LM_DBG("****** REPORT OK\n");
		} else {
			LM_DBG("****** REPORT NOK\n");
		}
	}

	if (strlen(info_call->esct->esqk) > 0){

		// if VPC provide ESQK then opensips need send esct to free this key
		LM_DBG(" --- SEND ESQK =%s\n \n",info_call->esct->esqk);

		time(&rawtime);
		timeinfo = localtime(&rawtime);

		strftime(info_call->esct->datetimestamp, MAX_TIME_SIZE, "%Y-%m-%dT%H:%M:%S%Z", timeinfo);
		LM_DBG(" --- TREAT BYE - XML ESCT %s \n \n", xml);

		xml = buildXmlFromModel(info_call->esct);

		// sends HTTP POST esctRequest to VPC
		resp = post(url_vpc, xml, &response);
		if (resp == -1) {
			LM_ERR(" --- PROBLEM IN POST DO BYE\n \n");
			shm_free(info_call);
			pkg_free(xml);
			return -1;
		}

		// verify if esct response came OK
		esct_callid = parse_xml_esct(response);
		if (esct_callid== NULL) {
			LM_ERR(" --- esctAck invalid format or without mandatory field \n \n");
		} else {
			if (strcmp(esct_callid, callidHeader)){
				LM_ERR(" --- callid in esctAck different from asctRequest \n \n");
			}
			if(esct_callid)
				pkg_free(esct_callid);
		}
		pkg_free(response);
		pkg_free(xml);

	}
	shm_free(info_call->esct->esgwri);
	shm_free(info_call);

	return 1;

}
Beispiel #19
0
int main (int argc,char * argv[]) {
	struct parameters* param = 0;
	struct seq_stats* seq_stats = 0;
	FILE* outfile =0;
	int i;
	
	init_nuc_code();
	
	param = interface(param,argc,argv);
	if(param->summary){
		if ((outfile = fopen(param->summary, "w")) == NULL){
			fprintf(stderr,"can't open output\n");
			exit(-1);
		}
	}
	
	if(param->format || (!param->infiles && !isatty(0))){
		if(!param->format){
			fprintf(stderr,"No format specified. Use -f <sam | bam | fa | fq > \n");
			exit(-1);
		}
		if(!strcmp("sam", param->format)){
			param->sam = 1;
			//}else if (byg_end(".bam", param->infile[i])  == strlen(param->infile[i])){
		}else if (!strcmp("bam",  param->format)){
			param->sam = 2;
			//}else if (byg_end(".fa", param->infile[i])  == strlen(param->infile[i])){
		}else if (!strcmp("fa", param->format)){
			param->sam = 0;
			//}else if (byg_end(".fq", param->infile[i])  == strlen(param->infile[i])){
		}else if (!strcmp("fq",  param->format)){
			param->sam = 0;
			//}else if (byg_end(".fastq", param->infile[i])  == strlen(param->infile[i])){
		}else if (!strcmp("fastq",  param->format)){
			param->sam = 0;
			//}else if (byg_end(".fastaq", param->infile[i])  == strlen(param->infile[i])){
		}else if (!strcmp("fastaq",  param->format)){
			param->sam = 0;
			//}else if (byg_end(".fasta", param->infile[i])  == strlen(param->infile[i])){
		}else if (!strcmp("fasta",  param->format)){
			param->sam = 0;
		}else{
			param->sam = -1;
		}
		if(param->sam != -1 && !param->infiles && !isatty(0)){
			fprintf(stdout,"Working on: stdin\n");
			seq_stats = init_seq_stats(param->kmer_size);
			seq_stats->sam = param->sam;
			if(param->sam == 0){
				seq_stats = collect_data(seq_stats,param,&read_fasta_fastq,-1);
			}else if(param->sam == 2){
				seq_stats = collect_data(seq_stats,param,&read_sam_chunk,-1);
			}else{
				seq_stats = collect_data(seq_stats,param,&read_sam_chunk,-1);
			}
			
			if(sanity_check(seq_stats)){
				if(param->summary){
					print_summary(seq_stats,param,-1,outfile);
				}else{
					print_html_page(seq_stats,param,-1);
				}
			}
			free_seq_stats(seq_stats);
		}
	}
	
	for(i = 0; i < param->infiles;i++){
		if(!param->format || param->sam == -1){
			param->sam = 0;
			
			//if(byg_end(".sam", param->infile[i])   == strlen(param->infile[i])){
			if(!strcmp(".sam", param->infile[i] + (strlen(param->infile[i] ) - 4))){
				param->sam = 1;
			//}else if (byg_end(".bam", param->infile[i])  == strlen(param->infile[i])){
			}else if (!strcmp(".bam", param->infile[i] + (strlen(param->infile[i] ) - 4))){
				param->sam = 2;
			//}else if (byg_end(".fa", param->infile[i])  == strlen(param->infile[i])){
			}else if (!strcmp(".fa", param->infile[i] + (strlen(param->infile[i] ) - 3))){
				param->sam = 0;
			//}else if (byg_end(".fq", param->infile[i])  == strlen(param->infile[i])){
			}else if (!strcmp(".fq", param->infile[i] + (strlen(param->infile[i] ) - 3))){
				param->sam = 0;
			//}else if (byg_end(".fastq", param->infile[i])  == strlen(param->infile[i])){
			}else if (!strcmp(".fastq", param->infile[i] + (strlen(param->infile[i] ) - 6))){
				param->sam = 0;
			//}else if (byg_end(".fastaq", param->infile[i])  == strlen(param->infile[i])){
			}else if (!strcmp(".fastaq", param->infile[i] + (strlen(param->infile[i] ) - 7))){
				param->sam = 0;
			//}else if (byg_end(".fasta", param->infile[i])  == strlen(param->infile[i])){
			}else if (!strcmp(".fasta", param->infile[i] + (strlen(param->infile[i] ) - 6))){
				param->sam = 0;
			}else if(!strcmp(".sam.gz", param->infile[i] + (strlen(param->infile[i] ) - 7))){
				param->sam = 1;
				param->gzipped  = 1;
				//}else if (byg_end(".bam", param->infile[i])  == strlen(param->infile[i])){
			}else if (!strcmp(".bam.gz", param->infile[i] + (strlen(param->infile[i] ) - 7))){
				param->sam = 2;
				param->gzipped  = 1;
				//}else if (byg_end(".fa", param->infile[i])  == strlen(param->infile[i])){
			}else if (!strcmp(".fa.gz", param->infile[i] + (strlen(param->infile[i] ) - 6))){
				param->sam = 0;
				param->gzipped  = 1;
				//}else if (byg_end(".fq", param->infile[i])  == strlen(param->infile[i])){
			}else if (!strcmp(".fq.gz", param->infile[i] + (strlen(param->infile[i] ) - 6))){
				param->sam = 0;
				param->gzipped  = 1;
				//}else if (byg_end(".fastq", param->infile[i])  == strlen(param->infile[i])){
			}else if (!strcmp(".fastq.gz", param->infile[i] + (strlen(param->infile[i] ) - 9))){
				param->sam = 0;
				param->gzipped  = 1;
				//}else if (byg_end(".fastaq", param->infile[i])  == strlen(param->infile[i])){
			}else if (!strcmp(".fastaq.gz", param->infile[i] + (strlen(param->infile[i] ) - 10))){
				param->sam = 0;
				param->gzipped  = 1;
				//}else if (byg_end(".fasta", param->infile[i])  == strlen(param->infile[i])){
			}else if (!strcmp(".fasta.gz", param->infile[i] + (strlen(param->infile[i] ) - 9))){
				param->sam = 0;
				param->gzipped  = 1;
			}else{
				param->sam = -1;
			}
		}
		//fprintf(stdout,"Loking at on:%s	%d\n",param->infile[i],sam);
		if(param->sam != -1){
			fprintf(stdout,"Working on:%s\n",param->infile[i]);
			seq_stats = init_seq_stats(param->kmer_size);
			seq_stats->sam = param->sam;
			if(param->sam == 0){
				seq_stats = collect_data(seq_stats,param,&read_fasta_fastq,i);
			}else if(param->sam == 2){
				seq_stats = collect_data(seq_stats,param,&read_sam_chunk,i);
			}else{
				seq_stats = collect_data(seq_stats,param,&read_sam_chunk,i);
			}
			
			if(sanity_check(seq_stats)){
				if(param->summary){
					print_summary(seq_stats,param,i,outfile);
				}else{
					print_html_page(seq_stats,param,i);
				}
			}
			free_seq_stats(seq_stats);
		}		
	}
	if(param->summary){
		fclose(outfile);
	}
	free_param(param);
	return 0;
}
Beispiel #20
0
/*
 * Return the data for the key/data pair that begins on this page at this
 * index (index should always be 1).
 */
int
__big_return(HTAB *hashp, BUFHEAD *bufp, int ndx, DBT *val, int set_current)
{
	BUFHEAD *save_p;
	uint16_t *bp, len, off, save_addr;
	char *tp;

	bp = (uint16_t *)(void *)bufp->page;
	while (bp[ndx + 1] == PARTIAL_KEY) {
		bufp = __get_buf(hashp, (uint32_t)bp[bp[0] - 1], bufp, 0);
		if (!bufp)
			return (-1);
		bp = (uint16_t *)(void *)bufp->page;
		ndx = 1;
	}

	if (bp[ndx + 1] == FULL_KEY) {
		bufp = __get_buf(hashp, (uint32_t)bp[bp[0] - 1], bufp, 0);
		if (!bufp)
			return (-1);
		bp = (uint16_t *)(void *)bufp->page;
		save_p = bufp;
		save_addr = save_p->addr;
		off = bp[1];
		len = 0;
	} else
		if (!FREESPACE(bp)) {
			/*
			 * This is a hack.  We can't distinguish between
			 * FULL_KEY_DATA that contains complete data or
			 * incomplete data, so we require that if the data
			 * is complete, there is at least 1 byte of free
			 * space left.
			 */
			off = bp[bp[0]];
			len = bp[1] - off;
			save_p = bufp;
			save_addr = bufp->addr;
			bufp = __get_buf(hashp, (uint32_t)bp[bp[0] - 1], bufp,
			    0);
			if (!bufp)
				return (-1);
			bp = (uint16_t *)(void *)bufp->page;
		} else {
			/* The data is all on one page. */
			tp = (char *)(void *)bp;
			off = bp[bp[0]];
			val->data = (uint8_t *)tp + off;
			val->size = bp[1] - off;
			if (set_current) {
				if (bp[0] == 2) {	/* No more buckets in
							 * chain */
					hashp->cpage = NULL;
					hashp->cbucket++;
					hashp->cndx = 1;
				} else {
					hashp->cpage = __get_buf(hashp,
					    (uint32_t)bp[bp[0] - 1], bufp, 0);
					if (!hashp->cpage)
						return (-1);
					hashp->cndx = 1;
					if (!((uint16_t *)(void *)
					    hashp->cpage->page)[0]) {
						hashp->cbucket++;
						hashp->cpage = NULL;
					}
				}
			}
			return (0);
		}

	val->size = collect_data(hashp, bufp, (int)len, set_current);
	if (val->size == (size_t)-1)
		return (-1);
	if (save_p->addr != save_addr) {
		/* We are pretty short on buffers. */
		errno = EINVAL;			/* OUT OF BUFFERS */
		return (-1);
	}
	memmove(hashp->tmp_buf, (save_p->page) + off, (size_t)len);
	val->data = (uint8_t *)hashp->tmp_buf;
	return (0);
}
Beispiel #21
0
void main(int argc, char **argv) {
	
	double start_t, end_t;
	
	int my_rank, p;
	complex A[512*512], B[512*512], C[512*512];

	/* initialize MPI */
	MPI_Init(&argc, &argv);
	MPI_Comm_size(MPI_COMM_WORLD, &p);
	MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
	
	/* Create MPI Datatype for Complex */
    const float nitems=2;
    int          blocklengths[2] = {1,1};
    MPI_Datatype types[2] = {MPI_FLOAT, MPI_FLOAT};
    MPI_Aint     offsets[2];

    offsets[0] = offsetof(complex, r);
    offsets[1] = offsetof(complex, i);

    MPI_Type_create_struct(nitems, blocklengths, offsets, types, &mpi_complex);
    MPI_Type_commit(&mpi_complex);
	
	/* Initialize Data*/
	if(my_rank == 0) {
		initialize_data(f1_name, A);
		initialize_data(f2_name, B);
		start_t = MPI_Wtime();
		dist_data(A, p);
		dist_data(B, p);
	} else {
		recv_data(A, p, my_rank);
		recv_data(B, p, my_rank);
	}
	
	/* 2D FFT on A */
	execute_fft(A, 1, p, my_rank);
	collect_data(A, p, my_rank);
	if(my_rank == 0) {
		transpose(A);
		dist_data(A, p);
	} else {
		recv_data(A, p, my_rank);
	}
	execute_fft(A, 1, p, my_rank);
	
	/* 2D FFT on B */
	execute_fft(B, 1, p, my_rank);
	collect_data(B, p, my_rank);
	if(my_rank == 0) {
		transpose(B);
		dist_data(B, p);
	} else {
		recv_data(B, p, my_rank);
	}
	execute_fft(B, 1, p, my_rank);
	
	/* Multiplication Step */
	execute_mm(A, B, C, p, my_rank);
	
	/* 2D FFT on C */
	execute_fft(C, -1, p, my_rank);
	collect_data(C, p, my_rank);
	if(my_rank == 0) {
		transpose(C);
		dist_data(C, p);
	} else {
		recv_data(C, p, my_rank);
	}
	execute_fft(C, -1, p, my_rank);
	collect_data(C, p, my_rank);
	
	end_t = MPI_Wtime();
	
	if(my_rank == 0) {
		output_data(f_out, C);
		printf("\nElapsed time = %g s\n", end_t - start_t);
		printf("--------------------------------------------\n");
	}
	
	MPI_Finalize();
}
void
get_status(unsigned int clientreg, void *clientarg)
{
  /*
   * This function returns the value of the status variable.
   * If the value of status is 0 (no collection is running), it
   * calles collect_data to start one.
   *  
   */
	
  /*
   * Extract the cache from the passed argument.
   */
    netsnmp_delegated_cache *cache = (netsnmp_delegated_cache *) clientarg;
    netsnmp_request_info *requests;
    netsnmp_agent_request_info *reqinfo;
    u_long         *delay_time_cache = NULL;

    /*
     * Make sure the cache created earlier is still
     * valid.  If not, the request timed out for some reason and we
     * do not need to keep processing things.  Should never happen, but
     * this double checks. 
     */
    cache = netsnmp_handler_check_cache(cache);

    if (!cache) {
        snmp_log(LOG_ERR, "illegal call to return delayed response\n");
        return;
    }

    /*
     * Re-establish the previous pointers,
     */
    reqinfo = cache->reqinfo;
    requests = cache->requests;

    DEBUGMSGTL(("demo_module_10",
                "continuing delayed request, mode = %d\n",
                cache->reqinfo->mode));
    
    /*
     * Set delegated to zero to indicate that the request is no longer
     * delegated and answer the query.
     */
    requests->delegated = 0;

    switch (cache->reqinfo->mode) {
        /*
         * Registering as an instance means we do not need to deal with
         * GETNEXT processing, so we do not handle it here at all.
         * 
         * However, since the instance handler already reset the mode
         * back to GETNEXT from the GET mode, we need to do the
         * same thing in both cases.
	 *
         */
	case MODE_GET:
            // no collection running, start one.
	    if (status == 0)
		    collect_data();
	    snmp_set_var_typed_value(requests->requestvb,
	        ASN_INTEGER, (u_char *) & status,
		    sizeof (status) /* length in bytes */);
		break;
	case MODE_SET_RESERVE1:
	    /*
	     * check type 
	     */
	    if (requests->requestvb->type != ASN_INTEGER) {
		    /*
		     * If not an integer, return SNMP error. 
		     */
		    netsnmp_set_request_error(reqinfo, requests,
                                      SNMP_ERR_WRONGTYPE);
		    /*
		     * Free cache. It is no longer needed. 
		     */
		    netsnmp_free_delegated_cache(cache);
		    return;
	    }
	    break;
   	case MODE_SET_RESERVE2:
		    /*
		     * Store old value for UNDO support in the future. 
		     */
		    memdup((u_char **) & delay_time_cache,
			(u_char *) & delay_time, sizeof(delay_time));

		    /*
		     * malloc failed 
		     */
		    if (delay_time_cache == NULL) {
			    netsnmp_set_request_error(reqinfo, requests,
                                      SNMP_ERR_RESOURCEUNAVAILABLE);
			    netsnmp_free_delegated_cache(cache);
			    return;
		    }

		    /*
		     * Add our temporary information to the request itself.
		     * This is then retrivable later.  The free function
		     * passed auto-frees it when the request is later
		     * deleted.  
		     */
		    netsnmp_request_add_list_data(requests,
                                      netsnmp_create_data_list
                                      (DELAYED_INSTANCE_SET_NAME,
                                       delay_time_cache, free));
		    break;
	case MODE_SET_ACTION:
		// get status integer from request
		// if status == 0, start data collection, else return error
		if (*(requests->requestvb->val.integer) == 0) {
			status = *(requests->requestvb->val.integer);
		        collect_data();
		} else
			netsnmp_set_request_error(reqinfo, requests,
			    SNMP_ERR_WRONGTYPE);
		break;
	case MODE_SET_UNDO:
	    /*
	     * A failure occurred. Reset to the
	     * previously value by extracting the previosuly
	     * stored information from the request.
	     */
	    delay_time =
		*((u_long *) netsnmp_request_get_list_data(requests,
                                                       DELAYED_INSTANCE_SET_NAME));
	    break;
	case MODE_SET_COMMIT:
		break;
	case MODE_SET_FREE:
	    /*
	     * The only thing to do here is free the old memdup'ed
	     * value, but it's auto-freed by the datalist recovery, so
	     * we don't have anything to actually do here 
	     */
	    break;
    }

    /*
     * free the information cache 
     */
    netsnmp_free_delegated_cache(cache);
		
}