Пример #1
0
static int hostap_read_sta_data(void *priv,
                                struct hostap_sta_driver_data *data,
                                const u8 *addr)
{
    struct hostap_driver_data *drv = priv;
    char buf[1024], line[128], *pos;
    FILE *f;
    unsigned long val;

    memset(data, 0, sizeof(*data));
    snprintf(buf, sizeof(buf), "/proc/net/hostap/%s/" MACSTR,
             drv->iface, MAC2STR(addr));

    f = fopen(buf, "r");
    if (!f)
        return -1;
    /* Need to read proc file with in one piece, so use large enough
     * buffer. */
    setbuffer(f, buf, sizeof(buf));

    while (fgets(line, sizeof(line), f)) {
        pos = strchr(line, '=');
        if (!pos)
            continue;
        *pos++ = '\0';
        val = strtoul(pos, NULL, 10);
        if (strcmp(line, "rx_packets") == 0)
            data->rx_packets = val;
        else if (strcmp(line, "tx_packets") == 0)
            data->tx_packets = val;
        else if (strcmp(line, "rx_bytes") == 0)
            data->rx_bytes = val;
        else if (strcmp(line, "tx_bytes") == 0)
            data->tx_bytes = val;
    }

    fclose(f);

    return 0;
}
Пример #2
0
static FILE *setup_ofile(char *fname)
{
    if (fname) {
        char *buf;
        FILE *ofp = my_fopen(fname, "w");

        if (!ofp) {
            perror(fname);
            exit(1);
        }

        buf = malloc(SETBUFFER_SIZE);
        setbuffer(ofp, buf, SETBUFFER_SIZE);

        add_file(ofp, fname);
        add_buf(buf);

        return ofp;
    }

    return NULL;
}
struct gbFa* gbFaOpen(char *fileName, char* mode)
/* open a fasta file for reading or writing.  Uses atomic file
 * creation for write.*/
{
struct gbFa *fa;
AllocVar(fa);

strcpy(fa->fileName, fileName);
if (!(sameString(mode, "r") || sameString(mode, "w") || sameString(mode, "a")))
    errAbort("gbFaOpen only supports modes \"r\", \"w\" \"a\", got \"%s\"",
             mode);
fa->mode[0] = mode[0];

if (mode[0] == 'w')
    fa->fh = gbMustOpenOutput(fileName);
else
    fa->fh = gzMustOpen(fileName, mode);

if (mode[0] == 'a')
    {
    /* line number is wrong on append */
    fa->off = ftello(fa->fh);
    if (fa->off < 0)
        errnoAbort("can't get offset for append access for file: %s",
                   fileName);
    }
fa->fhBuf = needMem(FA_STDIO_BUFSIZ);
setbuffer(fa->fh, fa->fhBuf, FA_STDIO_BUFSIZ);

/* setup buffers if read access */
if (mode[0] == 'r')
    {
    fa->headerCap = 256;
    fa->headerBuf = needMem(fa->headerCap);
    fa->seqCap = 1024;
    fa->seqBuf = needMem(fa->seqCap);
    }
return fa;
}
Пример #4
0
/*
 * This function is called once to set up the terminal device streams.
 * On VMS, it translates TT until it finds the terminal, then assigns
 * a channel to it and sets it raw. On CPM it is a no-op.
 */
ttopen()

{
#if	USG | HPUX | XENIX
	ioctl(0, TCGETA, &otermio);	/* save old settings */
	ntermio.c_iflag = 0;		/* setup new settings */
	ntermio.c_oflag = 0;
	ntermio.c_cflag = otermio.c_cflag;
	ntermio.c_lflag = 0;
	ntermio.c_line = otermio.c_line;
	ntermio.c_cc[VMIN] = 1;
	ntermio.c_cc[VTIME] = 0;
	ioctl(0, TCSETAW, &ntermio);	/* and activate them */
	kbdflgs = fcntl( 0, F_GETFL, 0 );
	kbdpoll = FALSE;
#endif

#if     V7 | BSD | SUN
        gtty(0, &ostate);                       /* save old state */
        gtty(0, &nstate);                       /* get base of new state */
        nstate.sg_flags |= RAW;
        nstate.sg_flags &= ~(ECHO|CRMOD);       /* no echo for now... */
        stty(0, &nstate);                       /* set mode */
	ioctl(0, TIOCGETC, &otchars);		/* Save old characters */
	ioctl(0, TIOCSETC, &ntchars);		/* Place new character into K */
#if	BSD
	/* provide a smaller terminal output buffer so that
	   the type ahead detection works better (more often) */
	setbuffer(stdout, &tobuf[0], TBUFSIZ); 
	signal(SIGTSTP,SIG_DFL);	/* set signals so that we can */
	signal(SIGCONT,rtfrmshell);	/* suspend & restart emacs */
#endif
#endif
	/* on all screens we are not sure of the initial position
	   of the cursor					*/
	ttrow = 999;
	ttcol = 999;
}
Пример #5
0
/*
 * Similar to C setbuf(3s)
 * u		logical unit
 * buf		buffer to use: can pass %val(0) or a character(len=0)
 *		variable to disable buffering
 * size		character length which Fortran passes unbeknownst to user
 * return	0 if no error; else errno (system or Fortran)
 */
int
_Setbuf(_f_int *u, char *buf, size_t size) {
   struct fiostate cfs;
   unit *cup = setup(*u, &cfs);
   int res = errno;
   if (0 == res) {
     switch (cup->ufs) {
       case FS_TEXT:
       case STD:
	 if (buf && (0 == size)) {
	   buf = 0;
	 }
	 setbuffer(cup->ufp.std, buf, size);
	 res = errno;
	 break;
       default:
	 res = errno = FESTIOER;
         break;
      }
   }
   STMT_END( cup, TF_READ, NULL,  &cfs);
   return res;
}
Пример #6
0
void
ttopen()
{
	int s;
	s = tcgetattr(0, &otermios);
	if (s < 0) {
		perror("ttopen tcgetattr");
		ExitProgram(BAD(1));
	}
 /* the "|| USG" below is to support SVR4 -- let me know if
 	it conflicts on other systems */
#if ODT || ISC || USG
	setvbuf(stdout, tobuf, _IOLBF, TBUFSIZ);
#else
  	setbuffer(stdout, tobuf, TBUFSIZ);
#endif

	suspc =   otermios.c_cc[VSUSP];
	intrc =   otermios.c_cc[VINTR];
	killc =   otermios.c_cc[VKILL];
	startc =  otermios.c_cc[VSTART];
	stopc =   otermios.c_cc[VSTOP];
	backspc = otermios.c_cc[VERASE];
#ifdef VWERASE  /* Sun has it.  any others? */
	wkillc = otermios.c_cc[VWERASE];
#else
	wkillc =  tocntrl('W');
#endif

	/* this could probably be done more POSIX'ish? */
	(void)signal(SIGTSTP,SIG_DFL);		/* set signals so that we can */
	(void)signal(SIGCONT,rtfrmshell);	/* suspend & restart */
	(void)signal(SIGTTOU,SIG_IGN);		/* ignore output prevention */

#if USE_FCNTL
	kbd_flags = fcntl( 0, F_GETFL, 0 );
	kbd_is_polled = FALSE;
#endif

#if ! X11
	ntermios = otermios;

	/* setup new settings, preserve flow control, and allow BREAK */
	ntermios.c_iflag = BRKINT|(otermios.c_iflag & (IXON|IXANY|IXOFF));
	ntermios.c_oflag = 0;
	ntermios.c_lflag = ISIG;
	ntermios.c_cc[VMIN] = 1;
	ntermios.c_cc[VTIME] = 0;
#ifdef	VSWTCH
	ntermios.c_cc[VSWTCH] = -1;
#endif
	ntermios.c_cc[VSUSP] = -1;
	ntermios.c_cc[VSTART] = -1;
	ntermios.c_cc[VSTOP] = -1;
#endif

	ttmiscinit();

	ttunclean();


}
Пример #7
0
int
main (void)
{
  const char *tmpdir;
  char *fname;
  int fd;
  FILE *fp;
  const char outstr[] = "hello world!\n";
  char strbuf[sizeof outstr];
  char buf[200];
  struct stat64 st1;
  struct stat64 st2;
  int result = 0;

  tmpdir = getenv ("TMPDIR");
  if (tmpdir == NULL || tmpdir[0] == '\0')
    tmpdir = "/tmp";

  asprintf (&fname, "%s/tst-fseek.XXXXXX", tmpdir);
  if (fname == NULL)
    error (EXIT_FAILURE, errno, "cannot generate name for temporary file");

  /* Create a temporary file.   */
  fd = mkstemp (fname);
  if (fd == -1)
    error (EXIT_FAILURE, errno, "cannot open temporary file");

  fp = fdopen (fd, "w+");
  if (fp == NULL)
    error (EXIT_FAILURE, errno, "cannot get FILE for temporary file");

  setbuffer (fp, strbuf, sizeof (outstr) -1);

  if (fwrite (outstr, sizeof (outstr) - 1, 1, fp) != 1)
    {
      puts ("write error");
      result = 1;
      goto out;
    }

  /* The EOF flag must be reset.  */
  if (fgetc (fp) != EOF)
    {
      puts ("managed to read at end of file");
      result = 1;
    }
  else if (! feof (fp))
    {
      puts ("EOF flag not set");
      result = 1;
    }
  if (fseek (fp, 0, SEEK_CUR) != 0)
    {
      puts ("fseek(fp, 0, SEEK_CUR) failed");
      result = 1;
    }
  else if (feof (fp))
    {
      puts ("fseek() didn't reset EOF flag");
      result = 1;
    }

  /* Do the same for fseeko().  */
#ifdef USE_IN_LIBIO
    if (fgetc (fp) != EOF)
    {
      puts ("managed to read at end of file");
      result = 1;
    }
  else if (! feof (fp))
    {
      puts ("EOF flag not set");
      result = 1;
    }
  if (fseeko (fp, 0, SEEK_CUR) != 0)
    {
      puts ("fseek(fp, 0, SEEK_CUR) failed");
      result = 1;
    }
  else if (feof (fp))
    {
      puts ("fseek() didn't reset EOF flag");
      result = 1;
    }
#endif

  /* Go back to the beginning of the file: absolute.  */
  if (fseek (fp, 0, SEEK_SET) != 0)
    {
      puts ("fseek(fp, 0, SEEK_SET) failed");
      result = 1;
    }
  else if (fflush (fp) != 0)
    {
      puts ("fflush() failed");
      result = 1;
    }
  else if (lseek (fd, 0, SEEK_CUR) != 0)
    {
      puts ("lseek() returned different position");
      result = 1;
    }
  else if (fread (buf, sizeof (outstr) - 1, 1, fp) != 1)
    {
      puts ("fread() failed");
      result = 1;
    }
  else if (memcmp (buf, outstr, sizeof (outstr) - 1) != 0)
    {
      puts ("content after fseek(,,SEEK_SET) wrong");
      result = 1;
    }

#ifdef USE_IN_LIBIO
  /* Now with fseeko.  */
  if (fseeko (fp, 0, SEEK_SET) != 0)
    {
      puts ("fseeko(fp, 0, SEEK_SET) failed");
      result = 1;
    }
  else if (fflush (fp) != 0)
    {
      puts ("fflush() failed");
      result = 1;
    }
  else if (lseek (fd, 0, SEEK_CUR) != 0)
    {
      puts ("lseek() returned different position");
      result = 1;
    }
  else if (fread (buf, sizeof (outstr) - 1, 1, fp) != 1)
    {
      puts ("fread() failed");
      result = 1;
    }
  else if (memcmp (buf, outstr, sizeof (outstr) - 1) != 0)
    {
      puts ("content after fseeko(,,SEEK_SET) wrong");
      result = 1;
    }
#endif

  /* Go back to the beginning of the file: relative.  */
  if (fseek (fp, -(sizeof (outstr) - 1), SEEK_CUR) != 0)
    {
      puts ("fseek(fp, 0, SEEK_SET) failed");
      result = 1;
    }
  else if (fflush (fp) != 0)
    {
      puts ("fflush() failed");
      result = 1;
    }
  else if (lseek (fd, 0, SEEK_CUR) != 0)
    {
      puts ("lseek() returned different position");
      result = 1;
    }
  else if (fread (buf, sizeof (outstr) - 1, 1, fp) != 1)
    {
      puts ("fread() failed");
      result = 1;
    }
  else if (memcmp (buf, outstr, sizeof (outstr) - 1) != 0)
    {
      puts ("content after fseek(,,SEEK_SET) wrong");
      result = 1;
    }

#ifdef USE_IN_LIBIO
  /* Now with fseeko.  */
  if (fseeko (fp, -(sizeof (outstr) - 1), SEEK_CUR) != 0)
    {
      puts ("fseeko(fp, 0, SEEK_SET) failed");
      result = 1;
    }
  else if (fflush (fp) != 0)
    {
      puts ("fflush() failed");
      result = 1;
    }
  else if (lseek (fd, 0, SEEK_CUR) != 0)
    {
      puts ("lseek() returned different position");
      result = 1;
    }
  else if (fread (buf, sizeof (outstr) - 1, 1, fp) != 1)
    {
      puts ("fread() failed");
      result = 1;
    }
  else if (memcmp (buf, outstr, sizeof (outstr) - 1) != 0)
    {
      puts ("content after fseeko(,,SEEK_SET) wrong");
      result = 1;
    }
#endif

  /* Go back to the beginning of the file: from the end.  */
  if (fseek (fp, -(sizeof (outstr) - 1), SEEK_END) != 0)
    {
      puts ("fseek(fp, 0, SEEK_SET) failed");
      result = 1;
    }
  else if (fflush (fp) != 0)
    {
      puts ("fflush() failed");
      result = 1;
    }
  else if (lseek (fd, 0, SEEK_CUR) != 0)
    {
      puts ("lseek() returned different position");
      result = 1;
    }
  else if (fread (buf, sizeof (outstr) - 1, 1, fp) != 1)
    {
      puts ("fread() failed");
      result = 1;
    }
  else if (memcmp (buf, outstr, sizeof (outstr) - 1) != 0)
    {
      puts ("content after fseek(,,SEEK_SET) wrong");
      result = 1;
    }

#ifdef USE_IN_LIBIO
  /* Now with fseeko.  */
  if (fseeko (fp, -(sizeof (outstr) - 1), SEEK_END) != 0)
    {
      puts ("fseeko(fp, 0, SEEK_SET) failed");
      result = 1;
    }
  else if (fflush (fp) != 0)
    {
      puts ("fflush() failed");
      result = 1;
    }
  else if (lseek (fd, 0, SEEK_CUR) != 0)
    {
      puts ("lseek() returned different position");
      result = 1;
    }
  else if (fread (buf, sizeof (outstr) - 1, 1, fp) != 1)
    {
      puts ("fread() failed");
      result = 1;
    }
  else if (memcmp (buf, outstr, sizeof (outstr) - 1) != 0)
    {
      puts ("content after fseeko(,,SEEK_SET) wrong");
      result = 1;
    }
#endif

  if (fwrite (outstr, sizeof (outstr) - 1, 1, fp) != 1)
    {
      puts ("write error 2");
      result = 1;
      goto out;
    }

  if (fwrite (outstr, sizeof (outstr) - 1, 1, fp) != 1)
    {
      puts ("write error 3");
      result = 1;
      goto out;
    }

  if (fwrite (outstr, sizeof (outstr) - 1, 1, fp) != 1)
    {
      puts ("write error 4");
      result = 1;
      goto out;
    }

  if (fwrite (outstr, sizeof (outstr) - 1, 1, fp) != 1)
    {
      puts ("write error 5");
      result = 1;
      goto out;
    }

  if (fputc ('1', fp) == EOF || fputc ('2', fp) == EOF)
    {
      puts ("cannot add characters at the end");
      result = 1;
      goto out;
    }

  /* Check the access time.  */
  if (fstat64 (fd, &st1) < 0)
    {
      puts ("fstat64() before fseeko() failed\n");
      result = 1;
    }
  else
    {
      sleep (1);

      if (fseek (fp, -(2 + 2 * (sizeof (outstr) - 1)), SEEK_CUR) != 0)
	{
	  puts ("fseek() after write characters failed");
	  result = 1;
	  goto out;
	}
      else
	{

	  time_t t;
	  /* Make sure the timestamp actually can be different.  */
	  sleep (1);
	  t = time (NULL);

	  if (fstat64 (fd, &st2) < 0)
	    {
	      puts ("fstat64() after fseeko() failed\n");
	      result = 1;
	    }
	  if (st1.st_ctime >= t)
	    {
	      puts ("st_ctime not updated");
	      result = 1;
	    }
	  if (st1.st_mtime >= t)
	    {
	      puts ("st_mtime not updated");
	      result = 1;
	    }
	  if (st1.st_ctime >= st2.st_ctime)
	    {
	      puts ("st_ctime not changed");
	      result = 1;
	    }
	  if (st1.st_mtime >= st2.st_mtime)
	    {
	      puts ("st_mtime not changed");
	      result = 1;
	    }
	}
    }

  if (fread (buf, 1, 2 + 2 * (sizeof (outstr) - 1), fp)
      != 2 + 2 * (sizeof (outstr) - 1))
    {
      puts ("reading 2 records plus bits failed");
      result = 1;
    }
  else if (memcmp (buf, outstr, sizeof (outstr) - 1) != 0
	   || memcmp (&buf[sizeof (outstr) - 1], outstr,
		      sizeof (outstr) - 1) != 0
	   || buf[2 * (sizeof (outstr) - 1)] != '1'
	   || buf[2 * (sizeof (outstr) - 1) + 1] != '2')
    {
      puts ("reading records failed");
      result = 1;
    }
  else if (ungetc ('9', fp) == EOF)
    {
      puts ("ungetc() failed");
      result = 1;
    }
  else if (fseek (fp, -(2 + 2 * (sizeof (outstr) - 1)), SEEK_END) != 0)
    {
      puts ("fseek after ungetc failed");
      result = 1;
    }
  else if (fread (buf, 1, 2 + 2 * (sizeof (outstr) - 1), fp)
      != 2 + 2 * (sizeof (outstr) - 1))
    {
      puts ("reading 2 records plus bits failed");
      result = 1;
    }
  else if (memcmp (buf, outstr, sizeof (outstr) - 1) != 0
	   || memcmp (&buf[sizeof (outstr) - 1], outstr,
		      sizeof (outstr) - 1) != 0
	   || buf[2 * (sizeof (outstr) - 1)] != '1')
    {
      puts ("reading records for the second time failed");
      result = 1;
    }
  else if (buf[2 * (sizeof (outstr) - 1) + 1] == '9')
    {
      puts ("unget character not ignored");
      result = 1;
    }
  else if (buf[2 * (sizeof (outstr) - 1) + 1] != '2')
    {
      puts ("unget somehow changed character");
      result = 1;
    }

 out:
  unlink (fname);

  return result;
}
Пример #8
0
static void my_setbuffer(FILE *fp, char *buf, int size)
{
    setbuffer(_get_actual_fp(fp), buf, size);
}
Пример #9
0
static void survey_disk(const char *path)
{
	sg_t sg;
	FILE *out = NULL;

	printf("Scrubbing disk %s\n", path);
	
	if (!sg_open(&sg, path)) {
		fprintf(stderr, "Error opening disk %s: %m\n", path);
		return;
	}

	int dev_type;
	scsi_vendor_t vendor;
	scsi_model_t model;
	scsi_fw_revision_t revision;
	scsi_serial_t serial;
	if (!do_inquiry(&sg, vendor, model, revision, serial, &dev_type)) {
		fprintf(stderr, "Error while reading inquiry\n");
		goto Exit;
	}

	if (dev_type != TYPE_DISK) {
		fprintf(stderr, "Device is not a disk (%d), bailing out.\n", dev_type);
		goto Exit;
	}

	char filename[256];
	snprintf(filename, sizeof(filename), "disk-survey-%s-%s-%s.xml", strtrim(vendor), strtrim(model), strtrim(serial));
	out = fopen(filename, "w");
	if (!out) {
		fprintf(stderr, "Failed to open log file '%s' for output\n", filename);
		goto Exit;
	}

	char largebuf[1024*1024];
	setbuffer(out, largebuf, sizeof(largebuf));

	fprintf(out, "<survey>\n"
		     "\t<inquiry>\n"
	             "\t\t<vendor>%s</vendor>\n"
		     "\t\t<model>%s</model>\n"
		     "\t\t<revision>%s</revision>\n"
		     "\t\t<serial>%s</serial>\n"
		     "\t\t<raw>%s</raw>\n"
		     "\t</inquiry>\n"
		     , vendor, model, revision, serial, hex_encode(inquiry_buf, sizeof(inquiry_buf), 1));

	uint64_t num_blocks;
	uint32_t block_size;
	survey_disk_capacity(&sg, out, &num_blocks, &block_size);
	survey_vpds(&sg, out);
	survey_timestamp(&sg, out);
	survey_mode_pages(&sg, out);
	survey_read_diagnostics(&sg, out);

	if (disk_is_ata(vendor)) {
		survey_ata_identify(&sg, out);
	}

	// It woud be preferable to have no other IO during the read
	// performance test, so flush the pending output buffer to keep all of
	// the space for the next test
	fflush(out);
	survey_read_performance(&sg, out, num_blocks, block_size, path);

Exit:
	if (out) {
		fprintf(out, "</survey>\n");
		fclose(out);
	}
	sg_close(&sg);
}
Пример #10
0
void set_block_buffered(FILE *fp) {
    size_t size = 100000;
    char *buf = malloc(size);
    setbuffer(stdout, buf, size);
}
Пример #11
0
/// This is main...
int main(int argc,char* argv[]) {
  int ret;
  in_port_t fixedport = 0;
  struct sockaddr_storage fixedhost;
  struct addrinfo hints, *res, *reslist;
  struct tracker_s * conn;

  memset(&fixedhost, '\0', sizeof(fixedhost));
  printf("netsed " VERSION " by Alexey Shumkin <*****@*****.**>\n"
         "      based on 1.2 from Julien VdG <*****@*****.**>\n"
         "      which is based on 0.01c from Michal Zalewski <*****@*****.**>\n");
  setbuffer(stdout,NULL,0);

  parse_params(argc, argv);

  memset(&hints, '\0', sizeof(hints));
  hints.ai_family = family;
  hints.ai_flags = AI_CANONNAME;
  hints.ai_socktype = tcp ? SOCK_STREAM : SOCK_DGRAM;

  if ((ret = getaddrinfo(rhost, rport, &hints, &reslist))) {
    ERR("getaddrinfo(): %s\n", gai_strerror(ret));
    error("Impossible to resolve remote address or port.");
  }
  /* We have candidates for remote host. */
  for (res = reslist; res; res = res->ai_next) {
    int sd = -1;

    if ( (sd = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) < 0)
      continue;
    /* Has successfully built a socket for this address family. */
    /* Record the address structure and the port. */
    fixedport = get_port(res->ai_addr);
    if (!is_addr_any(res->ai_addr))
      memcpy(&fixedhost, res->ai_addr, res->ai_addrlen);
    close(sd);
    break;
  }
  freeaddrinfo(reslist);
  if (res == NULL)
    error("Failed in resolving remote host.");

  if (fixedhost.ss_family && fixedport)
    printf("[+] Using fixed forwarding to %s,%s.\n",rhost,rport);
  else if (fixedport)
    printf("[+] Using dynamic (transparent proxy) forwarding with fixed port %s.\n",rport);
  else if (fixedhost.ss_family)
    printf("[+] Using dynamic (transparent proxy) forwarding with fixed addr %s.\n",rhost);
  else
    printf("[+] Using dynamic (transparent proxy) forwarding.\n");
  if (foreground) {
      printf("Run in foreground...\n");
  } else {
    int x = fork();
    if (x == -1) {
      printf("Error creating a fork. Run in foreground...\n");
    } else if (x) {
      printf("Detached: PID=%d\n", x);
      exit(0);
    }
  }

  bind_and_listen(fixedhost.ss_family, tcp, lport);

  printf("[+] Listening on port %s/%s.\n", lport, (tcp)?"tcp":"udp");

  signal(SIGPIPE, SIG_IGN);
  struct sigaction sa;
  sa.sa_flags = 0;
  sigemptyset(&sa.sa_mask);
  sa.sa_handler = sig_int;
  if (sigaction(SIGINT, &sa, NULL) == -1) error("netsed: sigaction() failed");

  while (!stop) {
    struct sockaddr_storage s;
    socklen_t l = sizeof(s);
    struct sockaddr_storage conho;
    in_port_t conpo;
    char ipstr[INET6_ADDRSTRLEN], portstr[12];

    int sel;
    fd_set rd_set;
    struct timeval timeout, *ptimeout;
    int nfds = lsock;
    FD_ZERO(&rd_set);
    FD_SET(lsock,&rd_set);
    timeout.tv_sec = UDP_TIMEOUT+1;
    timeout.tv_usec = 0;
    ptimeout = NULL;

    {
      conn = connections;
      while(conn != NULL) {
        if(tcp) {
          FD_SET(conn->csock, &rd_set);
          if (nfds < conn->csock) nfds = conn->csock;
        } else {
          // adjust timeout to earliest connection end time
          int remain = UDP_TIMEOUT - (now - conn->time);
          if (remain < 0) remain = 0;
          if (timeout.tv_sec > remain) {
            timeout.tv_sec = remain;
            // time updated to need to timeout
            ptimeout = &timeout;
          }
        }
        FD_SET(conn->fsock, &rd_set);
        if (nfds < conn->fsock) nfds = conn->fsock;
        // point on next
        conn = conn->n;
      }
    }

    sel=select(nfds+1, &rd_set, (fd_set*)0, (fd_set*)0, ptimeout);
    time(&now);
    if (stop)
    {
      break;
    }
    if (sel < 0) {
      DBG("[!] select fail! %s\n", strerror(errno));
      break;
    }
    if (sel == 0) {
      DBG("[*] select timeout. now: %d\n", now);
      // Here we still have to go through the list to expire some udp
      // connection if they timed out... But no descriptor will be set.
      // For tcp, select will not timeout.
    }

    if (FD_ISSET(lsock, &rd_set)) {
      int csock=-1;
      ssize_t rd=-1;
      if (tcp) {
        csock = accept(lsock,(struct sockaddr*)&s,&l);
      } else {
        // udp does not handle accept, so track connections manually
        // also set csock if a new connection need to be registered
        // to share the code with tcp ;)
        rd = recvfrom(lsock,buf,sizeof(buf),0,(struct sockaddr*)&s,&l);
        if(rd >= 0) {
          conn = connections;
          while(conn != NULL) {
            // look for existing connections
            if ((conn->csl == l) && (0 == memcmp(&s, conn->csa, l))) {
              // found
              break;
            }
            // point on next
            conn = conn->n;
          }
          // not found
          if(conn == NULL) {
            // udp 'connection' socket is the listening one
            csock = lsock;
          } else {
            DBG("[+] Got incoming datagram from existing connection.\n");
          }
        } else {
          ERR("recvfrom(): %s", strerror(errno));
        }
      }

      // new connection (tcp accept, or udp conn not found)
      if ((csock)>=0) {
        int one=1;
        getnameinfo((struct sockaddr *) &s, l, ipstr, sizeof(ipstr),
                    portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV);
        printf("[+] Got incoming connection from %s,%s", ipstr, portstr);
        conn = malloc(sizeof(struct tracker_s));
        if(NULL == conn) error("netsed: unable to malloc() connection tracker struct");
        // protocol specific init
        if (tcp) {
          setsockopt(csock,SOL_SOCKET,SO_OOBINLINE,&one,sizeof(int));
          conn->csa = NULL;
          conn->csl = 0;
          conn->state = ESTABLISHED;
        } else {
          conn->csa = malloc(l);
          if(NULL == conn->csa) error("netsed: unable to malloc() connection tracker sockaddr struct");
          memcpy(conn->csa, &s, l);
          conn->csl = l;
          conn->state = UNREPLIED;
        }
        conn->csock = csock;
        conn->time = now;

        conn->live = malloc(rules * sizeof(struct rule_item));
        if(NULL == conn->live) error("netsed: unable to malloc() connection tracker sockaddr struct");
        memcpy(conn->live, rule_live, rules * sizeof(struct rule_item));

        l = sizeof(s);
#ifndef LINUX_NETFILTER
        // was OK for linux 2.2 nat
        getsockname(csock,(struct sockaddr*)&s,&l);
#else
        // for linux 2.4 and later
        getsockopt(csock, SOL_IP, SO_ORIGINAL_DST,(struct sockaddr*)&s,&l);
#endif
        getnameinfo((struct sockaddr *) &s, l, ipstr, sizeof(ipstr),
                    portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV);
        printf(" to %s,%s\n", ipstr, portstr);
        conpo = get_port((struct sockaddr *) &s);

        memcpy(&conho, &s, sizeof(conho));

        if (fixedport) conpo=fixedport;
        if (fixedhost.ss_family)
          memcpy(&conho, &fixedhost, sizeof(conho));

        // forward to addr
        memcpy(&s, &conho, sizeof(s));
        set_port((struct sockaddr *) &s, conpo);
        getnameinfo((struct sockaddr *) &s, l, ipstr, sizeof(ipstr),
                    portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV);
        printf("[*] Forwarding connection to %s,%s\n", ipstr, portstr);

        // connect will bind with some dynamic addr/port
        conn->fsock = socket(s.ss_family, tcp ? SOCK_STREAM : SOCK_DGRAM, 0);

        if (connect(conn->fsock,(struct sockaddr*)&s,l)) {
           printf("[!] Cannot connect to remote server, dropping connection.\n");
           freetracker(conn);
           conn = NULL;
        } else {
          setsockopt(conn->fsock,SOL_SOCKET,SO_OOBINLINE,&one,sizeof(int));
          conn->n = connections;
          connections = conn;
        }
      }
      // udp has data process forwarding
      if((rd >= 0) && (conn != NULL)) {
        b2server_sed(conn, rd);
      }
    } // lsock is set
    // all other sockets
    conn = connections;
    struct tracker_s ** pconn = &connections;
    while(conn != NULL) {
      // incoming data ?
      if(tcp && FD_ISSET(conn->csock, &rd_set)) {
        client2server_sed(conn);
      }
      if(FD_ISSET(conn->fsock, &rd_set)) {
        server2client_sed(conn);
      }
      // timeout ? udp only
      DBG("[!] connection last time: %d, now: %d\n", conn->time, now);
      if(!tcp && ((now - conn->time) >= UDP_TIMEOUT)) {
        DBG("[!] connection timeout.\n");
        conn->state = TIMEOUT;
      }
      if(conn->state >= DISCONNECTED) {
        // remove it
        (*pconn)=conn->n;
        freetracker(conn);
        conn=(*pconn);
      } else {
        // point on next
        pconn = &(conn->n);
        conn = conn->n;
      }
    }
  }

  clean_socks();
  exit(0);
}
Пример #12
0
/* this creates the specified number of child processes and runs fn()
   in all of them */
static double create_procs(int nprocs, void (*fn)(struct child_struct * ))
{
	int i, status;
	int synccount;
#ifdef OS2
        int cRunning;
#endif

#ifndef OS2
        signal(SIGCONT, sigcont);
#endif
        start_timer();

	synccount = 0;

	if (nprocs < 1) {
		fprintf(stderr,
			"create %d procs?  you must be kidding.\n",
			nprocs);
		return 1;
	}

	children = shm_setup(sizeof(struct child_struct)*nprocs);
	if (!children) {
		printf("Failed to setup shared memory\n");
		return end_timer();
	}
        #ifdef OS2
        sem_create_os2();
        #endif

	memset(children, 0, sizeof(*children)*nprocs);

	for (i=0;i<nprocs;i++) {
		children[i].id = i;
		children[i].nprocs = nprocs;
	}

	for (i=0;i<nprocs;i++) {
		if (fork() == 0) {
                        #ifdef OS2
                        shm_attach_os2();
                        #endif
			setbuffer(stdout, NULL, 0);
			nb_setup(&children[i]);
			children[i].status = getpid();
                        #ifndef OS2
			pause();
                        #else
                        sem_wait_os2();
                        #endif
			fn(&children[i]);
			_exit(0);
		}
	}

	do {
		synccount = 0;
		for (i=0;i<nprocs;i++) {
			if (children[i].status) synccount++;
		}
		if (synccount == nprocs) break;
		sleep(1);
	} while (end_timer() < 30);

	if (synccount != nprocs) {
		printf("FAILED TO START %d CLIENTS (started %d)\n", nprocs, synccount);
		return end_timer();
	}

	start_timer();
#ifndef OS2
	kill(0, SIGCONT);

	signal(SIGALRM, sig_alarm);
	alarm(PRINT_FREQ);

	printf("%d clients started\n", nprocs);

	for (i=0;i<nprocs;) {
		if (waitpid(0, &status, 0) == -1) continue;
		if (WEXITSTATUS(status) != 0) {
			printf("Child failed with status %d\n",
			       WEXITSTATUS(status));
			exit(1);
		}
		i++;
	}

	alarm(0);
	sig_alarm();

#else

        sem_signal_os2();
        printf("%d clients started\n", nprocs);

        do
        {
            sleep(1);
            sig_alarm();

            for (cRunning = i = 0; i < nprocs; i++)
                    if (!children[i].done)
                        cRunning++;
        } while (cRunning > 0);
        status = status;
#endif

	printf("\n");
	return end_timer();
}
Пример #13
0
void xsetbuf(FILE *f, char *buf)
{
	setbuffer(f, buf, bufsize);
}
Пример #14
0
void runSuccess() {
    FILE* file = VALID_FILE;
    if (file != NULL) {
        setbuffer(file, NULL, 0);
    }
}
Пример #15
0
void log_file_init(logd_file * plf)
{
	char fullfilename[256];
	char mylink[256];
	const char *symfilename;
	char date_str[256];
	char gmt_str[256];
	char cmd_str[256];
	int ret;
	int round_off = 0;
	syslog_init ( plf );
	aln_interval *pal = NULL;
        time_t et;
        struct tm etime;
	pal =(aln_interval *)malloc(sizeof(aln_interval));
	if(pal == NULL){
	    complain_error_msg(1, "Memory allocation failed!");
	    exit(EXIT_FAILURE);
	}
	memset(pal ,0,sizeof(aln_interval));
	plf->pai = pal;
	/* Get current time */
	time_t cur_time = time(NULL);
	struct tm loctime ;
	struct tm gtime;

	localtime_r(&cur_time, &loctime);
	gmtime_r(&cur_time, &gtime);
	plf->st_time = (uint64_t)cur_time;
	strftime(plf->hour, 3, "%H", &loctime);
	// modify the date_str to include the file_start_min
	if(pal->use_file_time == 1){
	    loctime.tm_min = pal->file_start_min;
	    pal->use_file_time = 0;
	}
        if((loctime.tm_min )&&(plf->rt_interval)){
                round_off  = loctime.tm_min%plf->rt_interval;
                if(round_off){
                        loctime.tm_min = abs(loctime.tm_min - round_off);
                        loctime.tm_sec = 0;
                }
        }
	strftime(plf->file_start_time,SIZE_OF_TIMEBUFFER,
		"%G%m%d%H%M", &loctime);
        if(plf->rt_interval){
            et = mktime(&loctime);
            et = et + (60 * plf->rt_interval);
            localtime_r(&et,&etime);
            strftime(plf->file_end_time,
                SIZE_OF_TIMEBUFFER, "%G%m%d%H%M", &etime);
        } else {
            memset(plf->file_end_time,'\0',sizeof(plf->file_end_time));
        }
	/* adjust the fileid */
	plf->cur_fileid ++;
	if(plf->log_rotation){//if log-rotation is enabled, then we need to increament the file-id
	    if(plf->cur_fileid >= plf->max_fileid) plf->cur_fileid = 0;
	    log_save_fileid();
	}

	if (plf->type != TYPE_SYSLOG) {//no log file is created for syslog
	    if(plf->log_rotation){
		snprintf(cmd_str, sizeof(cmd_str), "%s %s/%s.%d.%s", "rm -f",
			log_folderpath, plf->filename, plf->cur_fileid, "*");
		//printf("----cmd_str= %s\n", cmd_str);
		system(cmd_str);
	    }

	    strftime(date_str, 256, "%Y%m%d_%H:%M:%S", &loctime);
	    snprintf(fullfilename, sizeof(fullfilename), "%s/%s.%d.%s",
		    log_folderpath, plf->filename, plf->cur_fileid, date_str);
	    if(plf->fullfilename) { free(plf->fullfilename); }
		plf->fullfilename = strdup(fullfilename);

		plf->fp = fopen(fullfilename, "w");
		if(!plf->fp) {
		    complain_error_errno(1, "Opening %s", fullfilename);
		}

		if (plf->type == TYPE_ACCESSLOG) {
			plf->io_buf = (char *) calloc(IOBUF_SIZE, 1);
			setbuffer(plf->fp, plf->io_buf, IOBUF_SIZE);
		}

		plf->cur_filesize = 0;
	}
    symfilename = plf->filename; // default: "access.log"
if((plf->fp) && (plf->type != TYPE_SYSLOG)){
    ret = fprintf(plf->fp, "#Version: 1.0\n");
    plf->cur_filesize += ret;

    ret = fprintf(plf->fp,
            "#Software: Media Flow Controller v(%s)\n",
            NKN_BUILD_PROD_RELEASE);
    plf->cur_filesize += ret;

    strftime(gmt_str, 256, "%Y-%m-%d %T", &gtime);
    ret = fprintf(plf->fp, "#Date: %s\n", gmt_str);
    plf->cur_filesize += ret;

    ret = fprintf(plf->fp, "#Remarks: -\n");
    plf->cur_filesize += ret;
}

	switch(plf->type) {
	case TYPE_ACCESSLOG:
		symfilename = plf->filename; // default: "access.log"
		if(plf->show_format){
			ret = fprintf(plf->fp, "#Version: 1.0\n");
			plf->cur_filesize += ret;
			strftime(date_str, 256, "%m-%d-%Y %H:%M:%S", &loctime);
			ret = fprintf(plf->fp, "#Date: %s\n", date_str);
			plf->cur_filesize += ret;
			ret = fprintf(plf->fp, "#Fields: %s\n", plf->format);
			plf->cur_filesize += ret;
                	fflush(plf->fp);
		}
		break;
	case TYPE_TRACELOG: symfilename = plf->filename; break; //default: trace.log
	case TYPE_CACHELOG: symfilename = plf->filename; break; // default : "cache.log"
	case TYPE_FUSELOG: symfilename = plf->filename; break; // default : "fuse.log"
	case TYPE_STREAMLOG:
		symfilename = plf->filename; // default : "stream.log"
		if(plf->show_format){
/*			ret = fprintf(plf->fp, "#Version: 1.0\n");
			plf->cur_filesize += ret;
			strftime(date_str, 256, "%m-%d-%Y %H:%M:%S", loctime);
			ret = fprintf(plf->fp, "#Date: %s\n", date_str);
			plf->cur_filesize += ret;*/
			ret = fprintf(plf->fp, "#Fields: %s\n", plf->format);
			plf->cur_filesize += ret;
                	fflush(plf->fp);
		}
		break;
	case TYPE_SYSLOG: break; //We don't create a file for syslog
	case TYPE_ERRORLOG: symfilename = plf->filename; break; // default :  "error.log"
	case TYPE_MFPLOG: symfilename = plf->filename; break; // default :  "mfp.log"
	case TYPE_CRAWLLOG: symfilename = plf->filename; 
                            crawl_write_version(plf);
                            break; // default :  "crawl.log"
	case TYPE_CBLOG: symfilename = plf->filename; break; // default :  "cb.log"
	default: symfilename = "other.log"; break;
	}
	/* Create a symbol link for web GUI */
	if (plf->type != TYPE_SYSLOG) {
		snprintf(mylink, sizeof(mylink), "ln -fs %s %s/%s",
			fullfilename, log_folderpath, symfilename);
		system(mylink);
	}
	return ;
}
Пример #16
0
int
main(int argc, char *argv[])
{
	char	buffer[BUFSIZ];
	wchar_t	wbuffer[BUFSIZ];
	char	*buf;
	wchar_t	*wbuf;
	FILE	*f;
	off_t	off;
	fpos_t	pos;
	size_t	size;
	int	fd, r;
	char	c;
	wchar_t	wc;

	if ((fd = dup(1)) == -1)
		err(2, "dup");
	if ((dup_stdout = fdopen(fd, "w")) == NULL)
		err(2, "fdopen");
	if ((fd = mkstemp(filename)) == -1)
		err(2, "mkstemp");
	if (write(fd, "0123456789\n\n", 12) != 12 || close(fd))
		err(2, "write + close");

	/* status */
	TEST_UNCHANGED(fwide(f, 0));
	TEST_NARROW(fwide(f, -1));
	TEST_WIDE(fwide(f, 1));
	TEST_UNCHANGED(feof(f));
	TEST_UNCHANGED(ferror(f));
	TEST_UNCHANGED(fileno(f));
	TEST_UNCHANGED(clearerr(f));

	/* flush and purge */
	TEST_UNCHANGED(fflush(f));
	TEST_UNCHANGED(fpurge(f));

	/* positioning */
	TEST_UNCHANGED(fgetpos(f, &pos));
	TEST_UNCHANGED(fgetpos(f, &pos); fsetpos(f, &pos));
	TEST_UNCHANGED(ftell(f));
	TEST_UNCHANGED(ftello(f));
	TEST_UNCHANGED(fseek(f, 1, SEEK_CUR));
	TEST_UNCHANGED(fseek(f, 1, SEEK_SET));
	TEST_UNCHANGED(fseek(f, 1, SEEK_END));
	TEST_UNCHANGED(fseeko(f, 1, SEEK_CUR));
	TEST_UNCHANGED(fseeko(f, 1, SEEK_SET));
	TEST_UNCHANGED(fseeko(f, 1, SEEK_END));
	TEST_UNCHANGED(rewind(f));

	/* buffering */
	TEST_UNCHANGED(setbuf(f, NULL));
	TEST_UNCHANGED(setbuf(f, buffer));
	TEST_UNCHANGED(setvbuf(f, buffer, _IONBF, BUFSIZ));
	TEST_UNCHANGED(setvbuf(f, buffer, _IOLBF, BUFSIZ));
	TEST_UNCHANGED(setvbuf(f, buffer, _IOFBF, BUFSIZ));
	TEST_UNCHANGED(setvbuf(f, NULL, _IONBF, 0));
	TEST_UNCHANGED(setvbuf(f, NULL, _IOLBF, 0));
	TEST_UNCHANGED(setvbuf(f, NULL, _IOFBF, 0));
	TEST_UNCHANGED(setbuffer(f, NULL, 0));
	TEST_UNCHANGED(setbuffer(f, buffer, BUFSIZ));
	TEST_UNCHANGED(setlinebuf(f));

	/* locking */
	TEST_UNCHANGED(flockfile(f);funlockfile(f));
	TEST_UNCHANGED(ftrylockfile(f);funlockfile(f));

	/* input */
	TEST_NARROW(getc(f));
	TEST_NARROW(getc_unlocked(f));
	TEST_NARROW(fgetc(f));
	TEST_NARROW(c = fgetc(f); ungetc(c, f));
	TEST_NARROW(fgets(buffer, BUFSIZ, f));
	TEST_NARROW(fscanf(f, "%s\n", buffer));
	TEST_NARROW(fgetln(f, &size));

	/* output */
	TEST_NARROW(putc('c', f));
	TEST_NARROW(putc_unlocked('c', f));
	TEST_NARROW(fputc('c', f));
	TEST_NARROW(fputs("foo", f));
	TEST_NARROW(fprintf(f, "%s\n", "foo"));

	/* input from stdin */
	TEST_NARROW_STD(stdin, getchar());
	TEST_NARROW_STD(stdin, getchar_unlocked());
	TEST_NARROW_STD(stdin, fgets(buffer, BUFSIZ, stdin));
	TEST_NARROW_STD(stdin, scanf("%s\n", buffer));

	/* output to stdout */
	TEST_NARROW_STD(stdout, putchar('c'));
	TEST_NARROW_STD(stdout, putchar_unlocked('c'));
	TEST_NARROW_STD(stdout, puts("foo"));
	TEST_NARROW_STD(stdout, printf("foo"));

	/* word-size ops */
	/*
	 * fread and fwrite are specified as being implemented in
	 * terms of fgetc() and fputc() and therefore must set the
	 * stream orientation to narrow.
	 */
	TEST_NARROW(fread(buffer, 4, BUFSIZ / 4, f));
	TEST_NARROW(fwrite(buffer, 4, BUFSIZ / 4, f));

	/*
	 * getw() and putw() aren't specified anywhere but logically
	 * should behave the same as fread/fwrite.  Not all OSes agree:
	 * Solaris 10 has them not changing the orientation.
	 */
	TEST_NARROW(getw(f));
	TEST_NARROW(putw(1234, f));


	/* WIDE CHAR TIME! */

	/* input */
	TEST_WIDE(getwc(f));
	TEST_WIDE(fgetwc(f));
	TEST_WIDE(wc = fgetwc(f); ungetwc(wc, f));
	TEST_WIDE(fgetws(wbuffer, BUFSIZ, f));
	TEST_WIDE(fwscanf(f, L"%s\n", wbuffer));

	/* output */
	TEST_WIDE(putwc(L'c', f));
	TEST_WIDE(fputwc(L'c', f));
	TEST_WIDE(fputws(L"foo", f));
	TEST_WIDE(fwprintf(f, L"%s\n", L"foo"));

	/* input from stdin */
	TEST_WIDE_STD(stdin, getwchar());
	TEST_WIDE_STD(stdin, wscanf(L"%s\n", wbuffer));

	/* output to stdout */
	TEST_WIDE_STD(stdout, putwchar(L'c'));
	TEST_WIDE_STD(stdout, wprintf(L"foo"));


	/* memory streams */
	f = open_memstream(&buf, &size);
	if (!((r = fwide(f, 0)) < 0))
		fail(__LINE__, r, "<", "open_memstream()");
	fclose(f);
	f = open_wmemstream(&wbuf, &size);
	if (!((r = fwide(f, 0)) > 0))
		fail(__LINE__, r, ">", "open_wmemstream()");
	fclose(f);


	/* random stuff? */
	TEST_UNCHANGED_STD(stderr, perror("foo"));

	remove(filename);
	if (failures)
		exit(1);
	exit(0);
}
Пример #17
0
int
main(int argc, char *argv[])

{
    char *env_top;
    char **preset_argv;
    int preset_argc = 0;
    void *mask;
    int need_mini = 1;

    struct statics statics;
    globalstate *gstate;

    /* get our name */
    if (argc > 0)
    {
	if ((myname = strrchr(argv[0], '/')) == 0)
	{
	    myname = argv[0];
	}
	else
	{
	    myname++;
	}
    }

    /* binary compatibility check */
#ifdef HAVE_UNAME
    {
	struct utsname uts;

	if (uname(&uts) == 0)
	{
	    if (strcmp(uts.machine, UNAME_HARDWARE) != 0)
	    {
		fprintf(stderr, "%s: incompatible hardware platform\n",
			myname);
		exit(EX_UNAVAILABLE);
	    }
	}
    }
#endif

    /* initialization */
    gstate = (globalstate *)calloc(1, sizeof(globalstate));
    gstate->statics = &statics;
    time_mark(NULL);

    /* preset defaults for various options */
    gstate->show_usernames = Yes;
    gstate->topn = DEFAULT_TOPN;
    gstate->delay = DEFAULT_DELAY;
    gstate->fulldraw = Yes;
    gstate->use_color = Yes;
    gstate->interactive = Maybe;

    /* preset defaults for process selection */
    gstate->pselect.idle = Yes;
    gstate->pselect.system = No;
    gstate->pselect.fullcmd = No;
    gstate->pselect.command = NULL;
    gstate->pselect.uid = -1;
    gstate->pselect.mode = 0;

    /* use a large buffer for stdout */
#ifdef HAVE_SETVBUF
    setvbuf(stdout, stdoutbuf, _IOFBF, BUFFERSIZE);
#else
#ifdef HAVE_SETBUFFER
    setbuffer(stdout, stdoutbuf, BUFFERSIZE);
#endif
#endif

    /* get preset options from the environment */
    if ((env_top = getenv("TOP")) != NULL)
    {
	preset_argv = argparse(env_top, &preset_argc);
	preset_argv[0] = myname;
	do_arguments(gstate, preset_argc, preset_argv);
    }

    /* process arguments */
    do_arguments(gstate, argc, argv);

#ifdef ENABLE_COLOR
    /* If colour has been turned on read in the settings. */
    env_top = getenv("TOPCOLOURS");
    if (!env_top)
    {
	env_top = getenv("TOPCOLORS");
    }
    /* must do something about error messages */
    color_env_parse(env_top);
    color_activate(gstate->use_color);
#endif

    /* in order to support forward compatability, we have to ensure that
       the entire statics structure is set to a known value before we call
       machine_init.  This way fields that a module does not know about
       will retain their default values */
    memzero((void *)&statics, sizeof(statics));
    statics.boottime = -1;

    /* call the platform-specific init */
    if (machine_init(&statics) == -1)
    {
	exit(EX_SOFTWARE);
    }

    /* create a helper list of sort order names */
    gstate->order_namelist = string_list(statics.order_names);

    /* look up chosen sorting order */
    if (gstate->order_name != NULL)
    {
	int i;

	if (statics.order_names == NULL)
	{
	    message_error(" This platform does not support arbitrary ordering");
	}
	else if ((i = string_index(gstate->order_name,
				   statics.order_names)) == -1)
	{
	    message_error(" Sort order `%s' not recognized", gstate->order_name);
	    message_error(" Recognized sort orders: %s", gstate->order_namelist);
	}
	else
	{
	    gstate->order_index = i;
	}
    }

    /* initialize extensions */
    init_username();

    /* initialize termcap */
    gstate->smart_terminal = screen_readtermcap(gstate->interactive);

    /* determine interactive state */
    if (gstate->interactive == Maybe)
    {
	gstate->interactive = smart_terminal;
    }

    /* if displays were not specified, choose an appropriate default */
    if (gstate->displays == 0)
    {
	gstate->displays = gstate->smart_terminal ? Infinity: 1;
    }

    /* we don't need a mini display when delay is less than 2
       seconds or when we are not on a smart terminal */
    if (gstate->delay <= 1 || !smart_terminal)
    {
	need_mini = 0;
    }

    /* set constants for username/uid display */
    if (gstate->show_usernames)
    {
	gstate->header_text = format_header("USERNAME");
	gstate->get_userid = username;
    }
    else
    {
	gstate->header_text = format_header("   UID  ");
	gstate->get_userid = itoa7;
    }
    gstate->pselect.usernames = gstate->show_usernames;

    /* initialize display */
    if ((gstate->max_topn = display_init(&statics)) == -1)
    {
	fprintf(stderr, "%s: can't allocate sufficient memory\n", myname);
	exit(EX_OSERR);
    }

    /* check for infinity and for overflowed screen */
    if (gstate->topn == Infinity)
    {
	gstate->topn = INT_MAX;
    }
    else if (gstate->topn > gstate->max_topn)
    {
#if 0
	message_error(" This terminal can only display %d processes",
		      gstate->max_topn);
#endif
    }

#ifdef ENABLE_COLOR
    /* producing a list of color tags is easy */
    if (gstate->show_tags)
    {
	color_dump(stdout);
	exit(EX_OK);
    }
#endif

    /* hold all signals while we initialize the screen */
    mask = hold_signals();
    screen_init();

    /* set the signal handlers */
    set_signals();

    /* longjmp re-entry point */
    /* set the jump buffer for long jumps out of signal handlers */
    if (setjmp(jmp_int) != 0)
    {
	/* this is where we end up after processing sigwinch or sigtstp */

	/* tell display to resize its buffers, and get the new length */
	if ((gstate->max_topn = display_resize()) == -1)
	{
	    /* thats bad */
	    quit(EX_OSERR);
	    /*NOTREACHED*/
	}

	/* set up for a full redraw, and get the current line count */
	gstate->fulldraw = Yes;

	/* safe to release the signals now */
	release_signals(mask);
    }
    else
    {
	/* release the signals */
	release_signals(mask);

	/* some systems require a warmup */
	/* always do a warmup for batch mode */
	if (gstate->interactive == 0 || statics.flags.warmup)
	{
	    struct system_info system_info;
	    struct timeval timeout;

	    time_mark(&(gstate->now));
	    get_system_info(&system_info);
	    (void)get_process_info(&system_info, &gstate->pselect, 0);
	    timeout.tv_sec = 1;
	    timeout.tv_usec = 0;
	    select(0, NULL, NULL, NULL, &timeout);

	    /* if we've warmed up, then we can show good states too */
	    gstate->show_cpustates = Yes;
	    need_mini = 0;
	}
    }

    /* main loop */
    while ((gstate->displays == -1) || (--gstate->displays > 0))
    {
	do_display(gstate);
	if (gstate->interactive)
	{
	    if (need_mini)
	    {
		do_minidisplay(gstate);
		need_mini = 0;
	    }
	    do_command(gstate);
	}
	else
	{
	    do_wait(gstate);
	}
    }

    /* do one last display */
    do_display(gstate);

    quit(EX_OK);
    /* NOTREACHED */
    return 1; /* Keep compiler quiet. */
}
Пример #18
0
int
glibc_test(void)
{
	const char *tmpdir;
	char *fname;
	int fd;
	FILE *fp;
	const char outstr[] = "hello world!\n";
	char strbuf[sizeof outstr];
	char buf[200];
	struct stat st1;
	struct stat st2;
	int result = 0;

	tmpdir = getenv("TMPDIR");
	if (tmpdir == NULL || tmpdir[0] == '\0')
		tmpdir = "/tmp";

	asprintf(&fname, "%s/tst-fseek.XXXXXX", tmpdir);
	if (fname == NULL)
		error(EXIT_FAILURE, errno, "cannot generate name for temporary file");

	/* Create a temporary file.   */
	fd = mkstemp(fname);
	if (fd == -1)
		error(EXIT_FAILURE, errno, "cannot open temporary file");

	fp = fdopen(fd, "w+");
	if (fp == NULL)
		error(EXIT_FAILURE, errno, "cannot get FILE for temporary file");

	setbuffer(fp, strbuf, sizeof(outstr) - 1);

	if (fwrite(outstr, sizeof(outstr) - 1, 1, fp) != 1) {
		printf("%d: write error\n", __LINE__);
		result = 1;
		goto out;
	}

	/* The EOF flag must be reset.  */
	if (fgetc(fp) != EOF) {
		printf("%d: managed to read at end of file\n", __LINE__);
		result = 1;
	} else if (!feof(fp)) {
		printf("%d: EOF flag not set\n", __LINE__);
		result = 1;
	}
	if (fseek(fp, 0, SEEK_CUR) != 0) {
		printf("%d: fseek(fp, 0, SEEK_CUR) failed\n", __LINE__);
		result = 1;
	} else if (feof(fp)) {
		printf("%d: fseek() didn't reset EOF flag\n", __LINE__);
		result = 1;
	}

	/* Do the same for fseeko().  */
	if (fgetc(fp) != EOF) {
		printf("%d: managed to read at end of file\n", __LINE__);
		result = 1;
	} else if (!feof(fp)) {
		printf("%d: EOF flag not set\n", __LINE__);
		result = 1;
	}
	if (fseeko(fp, 0, SEEK_CUR) != 0) {
		printf("%d: fseek(fp, 0, SEEK_CUR) failed\n", __LINE__);
		result = 1;
	} else if (feof(fp)) {
		printf("%d: fseek() didn't reset EOF flag\n", __LINE__);
		result = 1;
	}

	/* Go back to the beginning of the file: absolute.  */
	if (fseek(fp, 0, SEEK_SET) != 0) {
		printf("%d: fseek(fp, 0, SEEK_SET) failed\n", __LINE__);
		result = 1;
	} else if (fflush(fp) != 0) {
		printf("%d: fflush() failed\n", __LINE__);
		result = 1;
	} else if (lseek(fd, 0, SEEK_CUR) != 0) {
		printf("%d: lseek() returned different position\n", __LINE__);
		result = 1;
	} else if (fread(buf, sizeof(outstr) - 1, 1, fp) != 1) {
		printf("%d: fread() failed\n", __LINE__);
		result = 1;
	} else if (memcmp(buf, outstr, sizeof(outstr) - 1) != 0) {
		printf("%d: content after fseek(,,SEEK_SET) wrong\n", __LINE__);
		result = 1;
	}

	/* Now with fseeko.  */
	if (fseeko(fp, 0, SEEK_SET) != 0) {
		printf("%d: fseeko(fp, 0, SEEK_SET) failed\n", __LINE__);
		result = 1;
	} else if (fflush(fp) != 0) {
		printf("%d: fflush() failed\n", __LINE__);
		result = 1;
	} else if (lseek(fd, 0, SEEK_CUR) != 0) {
		printf("%d: lseek() returned different position\n", __LINE__);
		result = 1;
	} else if (fread(buf, sizeof(outstr) - 1, 1, fp) != 1) {
		printf("%d: fread() failed\n", __LINE__);
		result = 1;
	} else if (memcmp(buf, outstr, sizeof(outstr) - 1) != 0) {
		printf("%d: content after fseeko(,,SEEK_SET) wrong\n", __LINE__);
		result = 1;
	}

	/* Go back to the beginning of the file: relative.  */
	if (fseek(fp, -((int) sizeof(outstr) - 1), SEEK_CUR) != 0) {
		printf("%d: fseek(fp, 0, SEEK_SET) failed\n", __LINE__);
		result = 1;
	} else if (fflush(fp) != 0) {
		printf("%d: fflush() failed\n", __LINE__);
		result = 1;
	} else if (lseek(fd, 0, SEEK_CUR) != 0) {
		printf("%d: lseek() returned different position\n", __LINE__);
		result = 1;
	} else if (fread(buf, sizeof(outstr) - 1, 1, fp) != 1) {
		printf("%d: fread() failed\n", __LINE__);
		result = 1;
	} else if (memcmp(buf, outstr, sizeof(outstr) - 1) != 0) {
		printf("%d: content after fseek(,,SEEK_SET) wrong\n", __LINE__);
		result = 1;
	}

	/* Now with fseeko.  */
	if (fseeko(fp, -((int) sizeof(outstr) - 1), SEEK_CUR) != 0) {
		printf("%d: fseeko(fp, 0, SEEK_SET) failed\n", __LINE__);
		result = 1;
	} else if (fflush(fp) != 0) {
		printf("%d: fflush() failed\n", __LINE__);
		result = 1;
	} else if (lseek(fd, 0, SEEK_CUR) != 0) {
		printf("%d: lseek() returned different position\n", __LINE__);
		result = 1;
	} else if (fread(buf, sizeof(outstr) - 1, 1, fp) != 1) {
		printf("%d: fread() failed\n", __LINE__);
		result = 1;
	} else if (memcmp(buf, outstr, sizeof(outstr) - 1) != 0) {
		printf("%d: content after fseeko(,,SEEK_SET) wrong\n", __LINE__);
		result = 1;
	}

	/* Go back to the beginning of the file: from the end.  */
	if (fseek(fp, -((int) sizeof(outstr) - 1), SEEK_END) != 0) {
		printf("%d: fseek(fp, 0, SEEK_SET) failed\n", __LINE__);
		result = 1;
	} else if (fflush(fp) != 0) {
		printf("%d: fflush() failed\n", __LINE__);
		result = 1;
	} else if (lseek(fd, 0, SEEK_CUR) != 0) {
		printf("%d: lseek() returned different position\n", __LINE__);
		result = 1;
	} else if (fread(buf, sizeof(outstr) - 1, 1, fp) != 1) {
		printf("%d: fread() failed\n", __LINE__);
		result = 1;
	} else if (memcmp(buf, outstr, sizeof(outstr) - 1) != 0) {
		printf("%d: content after fseek(,,SEEK_SET) wrong\n", __LINE__);
		result = 1;
	}

	/* Now with fseeko.  */
	if (fseeko(fp, -((int) sizeof(outstr) - 1), SEEK_END) != 0) {
		printf("%d: fseeko(fp, 0, SEEK_SET) failed\n", __LINE__);
		result = 1;
	} else if (fflush(fp) != 0) {
		printf("%d: fflush() failed\n", __LINE__);
		result = 1;
	} else if (lseek(fd, 0, SEEK_CUR) != 0) {
		printf("%d: lseek() returned different position\n", __LINE__);
		result = 1;
	} else if (fread(buf, sizeof(outstr) - 1, 1, fp) != 1) {
		printf("%d: fread() failed\n", __LINE__);
		result = 1;
	} else if (memcmp(buf, outstr, sizeof(outstr) - 1) != 0) {
		printf("%d: content after fseeko(,,SEEK_SET) wrong\n", __LINE__);
		result = 1;
	}

	if (fwrite(outstr, sizeof(outstr) - 1, 1, fp) != 1) {
		printf("%d: write error 2\n", __LINE__);
		result = 1;
		goto out;
	}

	if (fwrite(outstr, sizeof(outstr) - 1, 1, fp) != 1) {
		printf("%d: write error 3\n", __LINE__);
		result = 1;
		goto out;
	}

	if (fwrite(outstr, sizeof(outstr) - 1, 1, fp) != 1) {
		printf("%d: write error 4\n", __LINE__);
		result = 1;
		goto out;
	}

	if (fwrite(outstr, sizeof(outstr) - 1, 1, fp) != 1) {
		printf("%d: write error 5\n", __LINE__);
		result = 1;
		goto out;
	}

	if (fputc('1', fp) == EOF || fputc('2', fp) == EOF) {
		printf("%d: cannot add characters at the end\n", __LINE__);
		result = 1;
		goto out;
	}

	/* Check the access time.  */
	if (fstat(fd, &st1) < 0) {
		printf("%d: fstat() before fseeko() failed\n\n", __LINE__);
		result = 1;
	} else {
		sleep(1);

		if (fseek(fp, -(2 + 2 * (sizeof(outstr) - 1)), SEEK_CUR) != 0) {
			printf("%d: fseek() after write characters failed\n", __LINE__);
			result = 1;
			goto out;
		} else {
			time_t t;
			/* Make sure the timestamp actually can be different.  */
			sleep(1);
			t = time(NULL);

			if (fstat(fd, &st2) < 0) {
				printf("%d: fstat() after fseeko() failed\n\n", __LINE__);
				result = 1;
			}
			if (st1.st_ctime >= t) {
				printf("%d: st_ctime not updated\n", __LINE__);
				result = 1;
			}
			if (st1.st_mtime >= t) {
				printf("%d: st_mtime not updated\n", __LINE__);
				result = 1;
			}
			if (st1.st_ctime >= st2.st_ctime) {
				printf("%d: st_ctime not changed\n", __LINE__);
				result = 1;
			}
			if (st1.st_mtime >= st2.st_mtime) {
				printf("%d: st_mtime not changed\n", __LINE__);
				result = 1;
			}
		}
	}

	if (fread(buf, 1, 2 + 2 * (sizeof(outstr) - 1), fp) != 2 + 2
		* (sizeof(outstr) - 1)) {
		printf("%d: reading 2 records plus bits failed\n", __LINE__);
		result = 1;
	} else if (memcmp(buf, outstr, sizeof(outstr) - 1) != 0
		|| memcmp(&buf[sizeof(outstr) - 1], outstr, sizeof(outstr) - 1) != 0
		|| buf[2 * (sizeof(outstr) - 1)] != '1'
		|| buf[2 * (sizeof(outstr) - 1) + 1] != '2') {
		printf("%d: reading records failed\n", __LINE__);
		result = 1;
	} else if (ungetc('9', fp) == EOF) {
		printf("%d: ungetc() failed\n", __LINE__);
		result = 1;
	} else if (fseek(fp, -(2 + 2 * (sizeof(outstr) - 1)), SEEK_END) != 0) {
		printf("%d: fseek after ungetc failed\n", __LINE__);
		result = 1;
	} else if (fread(buf, 1, 2 + 2 * (sizeof(outstr) - 1), fp)
		!= 2 + 2 * (sizeof(outstr) - 1)) {
		printf("%d: reading 2 records plus bits failed\n", __LINE__);
		result = 1;
	} else if (memcmp(buf, outstr, sizeof(outstr) - 1) != 0
		|| memcmp(&buf[sizeof(outstr) - 1], outstr, sizeof(outstr) - 1) != 0
		|| buf[2 * (sizeof(outstr) - 1)] != '1') {
		printf("%d: reading records for the second time failed\n", __LINE__);
		result = 1;
	} else if (buf[2 * (sizeof(outstr) - 1) + 1] == '9') {
		printf("%d: unget character not ignored\n", __LINE__);
		result = 1;
	} else if (buf[2 * (sizeof(outstr) - 1) + 1] != '2') {
		printf("%d: unget somehow changed character\n", __LINE__);
		result = 1;
	}

	fclose(fp);

	fp = fopen(fname, "r");
	if (fp == NULL) {
		printf("%d: fopen() failed\n\n", __LINE__);
		result = 1;
	} else if (fstat(fileno(fp), &st1) < 0) {
		printf("%d: fstat() before fseeko() failed\n\n", __LINE__);
		result = 1;
	} else if (fseeko(fp, 0, SEEK_END) != 0) {
		printf("%d: fseeko(fp, 0, SEEK_END) failed\n", __LINE__);
		result = 1;
	} else if (ftello(fp) != st1.st_size) {
		printf("%d: fstat st_size %zd ftello %zd\n", __LINE__,
			(size_t) st1.st_size, (size_t) ftello(fp));
		result = 1;
	} else
		printf("%d: SEEK_END works\n", __LINE__);
	if (fp != NULL)
		fclose(fp);

	fp = fopen(fname, "r");
	if (fp == NULL) {
		printf("%d: fopen() failed\n\n", __LINE__);
		result = 1;
	} else if (fstat(fileno(fp), &st1) < 0) {
		printf("%d: fstat() before fgetc() failed\n\n", __LINE__);
		result = 1;
	} else if (fgetc(fp) == EOF) {
		printf("%d: fgetc() before fseeko() failed\n\n", __LINE__);
		result = 1;
	} else if (fseeko(fp, 0, SEEK_END) != 0) {
		printf("%d: fseeko(fp, 0, SEEK_END) failed\n", __LINE__);
		result = 1;
	} else if (ftello(fp) != st1.st_size) {
		printf("%d: fstat st_size %zd ftello %zd\n", __LINE__,
			(size_t) st1.st_size, (size_t) ftello(fp));
		result = 1;
	} else
		printf("%d: SEEK_END works\n", __LINE__);
	if (fp != NULL)
		fclose(fp);

out:
	unlink(fname);

	return result;
}
Пример #19
0
void __darwin_setbuffer(__darwin_FILE* fp, char* buf, size_t size)
{
	setbuffer(fp->linux_fp, buf, size);
}
Пример #20
0
// Parses /proc/PID/maps file for the process memory sections.
bool HIDDEN ReloadProcessMemoryInfo()
{
	Section *section = _initialSection.next;
	while (section != NULL)
	{
		Section *next = section->next;
		delete section;
		section = next;
	}
	_initialSection.next = NULL;

	char file[_MAX_FNAME];
	char buffer[2048];

	pid_t pid = getpid();
	snprintf(file, sizeof(file), "/proc/%d/maps", pid);
	file[sizeof(file)-1] = 0;

	FILE *fp = fopen(file, "rt");
	if (!fp)
		return false;

	static char mbuffer[65536];
	setbuffer(fp, mbuffer, sizeof(mbuffer));

	size_t length = 0;
	size_t start, end, size;
	char accessProtection[5];
	int inode;
	int fields;
	section = &_initialSection;
	while (!feof(fp))
	{
		if (fgets(buffer, sizeof(buffer), fp) == NULL)
			break;

		fields = sscanf(buffer, "%lx-%lx %4s %*s %*s %d %255s", &start, &end, accessProtection, &inode, file);
		//printf("%lx-%lx %4s %d %s\n", start, end, accessProtection, inode, fields > 4 ? file : "");
		if (fields < 4)
			return false;

		section->next = new Section;
		section = section->next;
		section->next = NULL;
		section->start = start;
		section->end = end;
		section->size = end - start;
		section->protection = 0;
		if (accessProtection[0] == 'r') section->protection |= PROT_READ;
		if (accessProtection[1] == 'w') section->protection |= PROT_WRITE;
		if (accessProtection[2] == 'x') section->protection |= PROT_EXEC;
		section->inode = inode;
		if (fields > 4)
		{
			strncpy(section->filename, file, _MAX_FNAME);
			section->filename[_MAX_FNAME - 1] = 0;
			section->namelen = strlen(section->filename);
		}
		else
		{
			section->filename[0] = 0;
			section->namelen = 0;
		}
	}

	fclose(fp);

	return true;
}
Пример #21
0
void setbuf(FILE *stream, char *buf) {
	setbuffer(stream, buf, BUFSIZ);
}
Пример #22
0
void
init_io(void)
{
    long ttpgrp;
    static char outbuf[BUFSIZ], errbuf[BUFSIZ];

#ifdef RSH_BUG_WORKAROUND
    int i;
#endif

/* stdout, stderr fully buffered */
#ifdef _IOFBF
    setvbuf(stdout, outbuf, _IOFBF, BUFSIZ);
    setvbuf(stderr, errbuf, _IOFBF, BUFSIZ);
#else
    setbuffer(stdout, outbuf, BUFSIZ);
    setbuffer(stderr, errbuf, BUFSIZ);
#endif

/* This works around a bug in some versions of in.rshd. *
 * Currently this is not defined by default.            */
#ifdef RSH_BUG_WORKAROUND
    if (cmd) {
	for (i = 3; i < 10; i++)
	    close(i);
    }
#endif

    if (shout) {
	fclose(shout);
	shout = 0;
    }
    if (SHTTY != -1) {
	zclose(SHTTY);
	SHTTY = -1;
    }

    /* Make sure the tty is opened read/write. */
    if (isatty(0)) {
	zsfree(ttystrname);
	if ((ttystrname = ztrdup(ttyname(0))))
	    SHTTY = movefd(open(ttystrname, O_RDWR));
    }
    if (SHTTY == -1 && (SHTTY = movefd(open("/dev/tty", O_RDWR))) != -1) {
	zsfree(ttystrname);
	ttystrname = ztrdup("/dev/tty");
    }
    if (SHTTY == -1) {
	zsfree(ttystrname);
	ttystrname = ztrdup("");
    }

    /* We will only use zle if shell is interactive, *
     * SHTTY != -1, and shout != 0                   */
    if (interact && SHTTY != -1) {
	init_shout();
	if(!shout)
	    opts[USEZLE] = 0;
    } else
	opts[USEZLE] = 0;

#ifdef JOB_CONTROL
    /* If interactive, make the shell the foreground process */
    if (opts[MONITOR] && interact && (SHTTY != -1)) {
	attachtty(GETPGRP());
	if ((mypgrp = GETPGRP()) > 0) {
	    while ((ttpgrp = gettygrp()) != -1 && ttpgrp != mypgrp) {
		sleep(1);
		mypgrp = GETPGRP();
		if (mypgrp == gettygrp())
		    break;
#ifndef __EMX__
		killpg(mypgrp, SIGTTIN);
#endif
		mypgrp = GETPGRP();
	    }
	} else
	    opts[MONITOR] = 0;
    } else
	opts[MONITOR] = 0;
#else
    opts[MONITOR] = 0;
#endif
}
static int
madwifi_read_sta_driver_data(void *priv, struct hostap_sta_driver_data *data,
			     const u8 *addr)
{
	struct madwifi_driver_data *drv = priv;

#ifdef MADWIFI_BSD
	struct ieee80211req_sta_stats stats;

	memset(data, 0, sizeof(*data));

	/*
	 * Fetch statistics for station from the system.
	 */
	memset(&stats, 0, sizeof(stats));
	memcpy(stats.is_u.macaddr, addr, IEEE80211_ADDR_LEN);
	if (set80211priv(drv,
#ifdef MADWIFI_NG
			 IEEE80211_IOCTL_STA_STATS,
#else /* MADWIFI_NG */
			 IEEE80211_IOCTL_GETSTASTATS,
#endif /* MADWIFI_NG */
			 &stats, sizeof(stats))) {
		wpa_printf(MSG_DEBUG, "%s: Failed to fetch STA stats (addr "
			   MACSTR ")", __func__, MAC2STR(addr));
		if (memcmp(addr, drv->acct_mac, ETH_ALEN) == 0) {
			memcpy(data, &drv->acct_data, sizeof(*data));
			return 0;
		}

		printf("Failed to get station stats information element.\n");
		return -1;
	}

	data->rx_packets = stats.is_stats.ns_rx_data;
	data->rx_bytes = stats.is_stats.ns_rx_bytes;
	data->tx_packets = stats.is_stats.ns_tx_data;
	data->tx_bytes = stats.is_stats.ns_tx_bytes;
	return 0;

#else /* MADWIFI_BSD */

	char buf[1024], line[128], *pos;
	FILE *f;
	unsigned long val;

	memset(data, 0, sizeof(*data));
	snprintf(buf, sizeof(buf), "/proc/net/madwifi/%s/" MACSTR,
		 drv->iface, MAC2STR(addr));

	f = fopen(buf, "r");
	if (!f) {
		if (memcmp(addr, drv->acct_mac, ETH_ALEN) != 0)
			return -1;
		memcpy(data, &drv->acct_data, sizeof(*data));
		return 0;
	}
	/* Need to read proc file with in one piece, so use large enough
	 * buffer. */
	setbuffer(f, buf, sizeof(buf));

	while (fgets(line, sizeof(line), f)) {
		pos = strchr(line, '=');
		if (!pos)
			continue;
		*pos++ = '\0';
		val = strtoul(pos, NULL, 10);
		if (strcmp(line, "rx_packets") == 0)
			data->rx_packets = val;
		else if (strcmp(line, "tx_packets") == 0)
			data->tx_packets = val;
		else if (strcmp(line, "rx_bytes") == 0)
			data->rx_bytes = val;
		else if (strcmp(line, "tx_bytes") == 0)
			data->tx_bytes = val;
	}

	fclose(f);

	return 0;
#endif /* MADWIFI_BSD */
}
Пример #24
0
int main(int argc, char **argv)
{
	pid_t daemon_pid = -1;
	char *my_libc = NULL, *daemon_libc = NULL;
	char *dl_open_address = NULL;
	char *dlopen_mode = NULL;
	FILE *pfd = NULL;
	char buf[128], *space = NULL;

	/* nm /lib64/libc.so.6|grep __libc_dlopen_mode: 00000000000f2a40 t __libc_dlopen_mode */
	size_t dlopen_offset = 0;

	if (argc < 3) {
		usage(argv[0]);
		return 1;
	}

	setbuffer(stdout, NULL, 0);

	my_libc = find_libc_start(getpid());
	if (!my_libc) {
		printf("Nuts! Unable to locate my own libc! bailing out\n");
		return 1;
	}
	
	printf("Trying to obtain __libc_dlopen_mode() address relative to libc start address.\n");
	printf("[1] Using my own __libc_dlopen_mode ...\n");
	dlopen_mode = dlsym(NULL, "__libc_dlopen_mode");
	if (dlopen_mode)
		dlopen_offset = dlopen_mode - my_libc;

	if (dlopen_offset == 0 && 
	    ((pfd = popen("nm /lib64/libc.so.6|grep __libc_dlopen_mode", "r")) != NULL ||
	     (pfd = popen("nm /lib/libc.so.6|grep __libc_dlopen_mode", "r")) != NULL)) {
		printf("[2] Using nm method ... ");
		fgets(buf, sizeof(buf), pfd);
		if ((space = strchr(buf, ' ')) != NULL)
			*space = 0;
		dlopen_offset = strtoul(buf, NULL, 16);
		fclose(pfd);
	}
	if (dlopen_offset == 0) {
		printf("failed!\nNo more methods, bailing out.\n");
		return 1;
	}
	printf("success!\n");

	dl_open_address = my_libc + dlopen_offset;
	daemon_pid = (pid_t)atoi(argv[1]);
	daemon_libc = find_libc_start(daemon_pid);
	if (!daemon_libc) {
		printf("Unable to locate target's libc! bailing out!\n");
		return 1;
	}

	printf("me: {__libc_dlopen_mode:%p, dlopen_offset:0x%zx}\n=> daemon: {__libc_dlopen_mode:%p, libc:%p}\n",
	       dl_open_address, dlopen_offset, daemon_libc + dlopen_offset, daemon_libc);

	inject_code(daemon_pid, (size_t)daemon_libc,
	            (size_t)(daemon_libc + dlopen_offset), argv[2]);

	printf("done.\n");
	return 0;
}