예제 #1
0
int
main() {
  char buf[100];
  time_t s, t;
  buffer_put(buffer_1, buf, fmt_httpdate(buf, time(&s)));
  buffer_putnlflush(buffer_1);
  buffer_puts(buffer_1, buf + scan_httpdate(buf, &t));
  buffer_putnlflush(buffer_1);
  buffer_putulong(buffer_1, s);
  buffer_puts(buffer_1, " vs. ");
  buffer_putulong(buffer_1, t);
  buffer_putnlflush(buffer_1);
  return 0;
}
예제 #2
0
파일: vartab_dump.c 프로젝트: rsenn/shish
/* ----------------------------------------------------------------------- */
void vartab_dump(struct vartab *vartab) {
  unsigned int i;
  struct var *var;

/*          buffer_puts(fd_out->w, "44: ");
          buffer_putulong(fd_out->w, (long)(vartab->table[44]));
          buffer_putnlflush(fd_out->w);
          buffer_puts(fd_out->w, "46: ");
          buffer_putulong(fd_out->w, (long)(vartab->table[46]));
          buffer_putnlflush(fd_out->w);*/
  
  buffer_puts(fd_out->w, "address  name                     value                   nlen offs vlen lev buck lexhash          rndhash\n");
  buffer_puts(fd_out->w, "-------------------------------------------------------------------------------------------------------------------\n");
  
  if(vartab) {
    for(; vartab; vartab = vartab->parent) {
      buffer_puts(fd_out->w, "level: ");
      buffer_putulong(fd_out->w, vartab->level);
      buffer_puts(fd_out->w, "\n===================================================================================================================");
      buffer_putnlflush(fd_out->w);
        
      for(i = 0; i < (unsigned int)VARTAB_BUCKETS; i++) {
        for(var = vartab->table[i]; var; var = var->bnext) {
          var_dump(var);
        }
      }
    }
  } else {
    for(var = var_list; var; var = var->gnext)
      var_dump(var);
  }
}
예제 #3
0
static void carp(const char* routine) {
  buffer_flush(buffer_1);
  buffer_puts(buffer_2,"httpbench: ");
  buffer_puts(buffer_2,routine);
  buffer_puts(buffer_2,": ");
  buffer_puterror(buffer_2);
  buffer_putnlflush(buffer_2);
}
예제 #4
0
void stack_print(stack *st) {
        int i;

        for (i = st->top; i >= 0; i--) {
            buffer_putlong(buffer_1, st->st[i]);
            buffer_puts(buffer_1, " ");
        }
        buffer_putnlflush(buffer_1);
}
예제 #5
0
int main() {
  static stralloc sa;
  /* static makes sure sa is initialized and empty;
   * use stralloc_init to initialize and stralloc_copys(&sa,"") to empty */
  if (buffer_get_token_sa(buffer_0,&sa," \t\n",3)==0) {
    buffer_putsa(buffer_1,&sa);
    buffer_putnlflush(buffer_1);
  }
  return 0;
}
예제 #6
0
/* ----------------------------------------------------------------------- */
int builtin_basename(int argc, char **argv) {
  if(!argv[shell_optind]) {
    builtin_errmsg(argv, "too few arguments", NULL);
    return 1;
  }

  buffer_puts(fd_out->w, shell_basename(argv[shell_optind]));
  buffer_putnlflush(fd_out->w);
  return 0;
}
예제 #7
0
파일: b64encode.c 프로젝트: rsenn/dirlist
void
b64encode(const char* c, long len) {
  char* buf = malloc(len * 2 + 4);
  buffer_put(buffer_1, buf, fmt_base64(buf, c, len));
  if(isatty(1))
    buffer_putnlflush(buffer_1);
  else
    buffer_flush(buffer_1);
  free(buf);
}
예제 #8
0
파일: xmlpp.c 프로젝트: rsenn/dirlist
int
main(int argc, char* argv[]) {
  xmlreader r;
  int ret;
  int c;
  int index = 0;
  struct longopt opts[] = {
      {"help", 0, NULL, 'h'},
      {"single-quote", 0, &quote_char, '\''},
      {"double-quote", 0, &quote_char, '"'},
      {"one-line", 0, NULL, 'o'},
      {"compact", 0, NULL, 'c'},
      {"indent", 0, NULL, 'l'},
      {0},
  };

  errmsg_iam(argv[0]);

  for(;;) {
    c = getopt_long(argc, argv, "hsdol:c", opts, &index);
    if(c == -1)
      break;
    if(c == 0)
      continue;

    switch(c) {
      case 'h': usage(argv[0]); return 0;
      case 's': quote_char = '\''; break;
      case 'd': quote_char = '"'; break;
      case 'o': one_line = 1; break;
      case 'c': compact = 1; break;
      case 'l': scan_int(optarg, &indent); break;
      default: usage(argv[0]); return 1;
    }
  }

  if(argc > 1)
    ret = buffer_mmapprivate(&infile, argv[1]);
  else
    ret = buffer_read_fd(&infile, 0);

  if(ret) {
    errmsg_infosys("input");
    return errno == ENOENT ? 127 : 1;
  }

  xml_reader_init(&r, &infile);
  xml_read_callback(&r, xml_read_function);
  buffer_putnlflush(buffer_1);
  buffer_close(&b);

  return 0;
}
예제 #9
0
파일: gpio_init.c 프로젝트: rsenn/dirlist
int
gpio_init() {
  int mem_dev = -1;
  void* mem_map = NULL;

  if(gpio != NULL) {
    buffer_puts(buffer_1, "gpio_init : Error: Seems to be already initialized!");
    buffer_putnlflush(buffer_1);
    return 0;
  }

  mem_dev = open_rwsync("/dev/mem");
  if(mem_dev == -1) {
    buffer_puts(buffer_1, "gpio_init : Error: Can't open \"/dev/mem\"!");
    buffer_putnlflush(buffer_1);
    return 0;
  }
#if !(defined(_WIN32) || defined(_WIN64))
  mem_map = mmap(NULL,                   /* Local mapping start address (NULL means don't care). */
                 BLOCK_SIZE,             /* Mapped memory block size. */
                 PROT_READ | PROT_WRITE, /* Enable read and write. */
                 MAP_SHARED,             /* No exclusive access. */
                 mem_dev,
                 GPIO_BASE); /* Offset to GPIO peripheral. */
  close(mem_dev);
  mem_dev = -1;

  if(mem_map == MAP_FAILED) {
    buffer_puts(buffer_1, "gpio_init : Error: Failed to create memory mapping!");
    buffer_putnlflush(buffer_1);
    return 0;
  }
#endif

  gpio = (volatile unsigned*)mem_map;
  return 1;

  /* [munmap() call is not necessary later, */
  /* because it will automatically unmap on process termination] */
}
예제 #10
0
int main() {
  int64 pfd[2];
  char buf[20480];
  unsigned int i;
  if (!io_pipe(pfd)) return 111;
  io_nonblock(pfd[1]);
  if (!io_fd(pfd[1])) return 111;
  switch (fork()) {
  case -1: return 111;
  case 0: /* child */
	   io_close(pfd[1]);
	   sleep(1);
	   for (;;) {
	    switch (io_waitread(pfd[0],buf,sizeof buf)) {
	    case -1: buffer_putsflush(buffer_2,"io_waitread returned -1!\n"); return 111;
	    case -3: buffer_puts(buffer_2,"io_waitread: ");
		      buffer_puterror(buffer_2);
		      buffer_putnlflush(buffer_2);
		      return 111;
	    case 0: io_close(pfd[0]);
		    return 0;
	    }
	   }
  }
  io_close(pfd[0]);
  for (i=0; i<sizeof(buf); ++i) buf[i]="abcdefghihjklmnopqrstuvwxyz"[i%26];
  for (i=0; i<1000; ++i) {
    int64 r;
    if ((r=io_waitwrite(pfd[1],buf,sizeof buf))!=sizeof buf) {
      buffer_puts(buffer_2,"io_waitwrite returned ");
      buffer_putlonglong(buffer_2,r);
      buffer_putnlflush(buffer_2);
    }
  }
  return 0;
}
예제 #11
0
파일: impgen.c 프로젝트: rsenn/dirlist
int
main(int argc, char* argv[]) {
  int optarg;

  for(optarg = 1; optarg < argc; ++optarg) {
    char *dll, *filename, *dll_name;
    size_t dllsz;
    uint32 i, *name_rvas, nexp, num_entries;
    pe_data_directory *datadir;
    pe_export_directory* expdata;
    pe32_opt_header* opt_hdr_32;
    pe_type type;

    filename = argv[optarg];

    dll = mmap_read(filename, &dllsz);
    if(dll == NULL) return 1;

    dll_name = str_basename(filename);

    opt_hdr_32 = pe_header_opt(dll);

    type = uint16_get(&opt_hdr_32->magic);

    datadir = pe_get_datadir(dll, &num_entries);

    if(num_entries < 1) /* no exports */
      return 1;

    expdata = pe_rva2ptr(dll, uint32_get(&datadir->virtual_address));

    nexp = uint32_get(&expdata->number_of_names);
    name_rvas = pe_rva2ptr(dll, uint32_get(&expdata->address_of_names));

    buffer_puts(buffer_1, "EXPORTS\n");
    (void)dll_name;
    /* buffer_putm_3(buffer_1, "LIBRARY ", dll_name, "\n"); */

    for(i = 0; i < nexp; i++) {
      buffer_putm_3(buffer_1, "  ", pe_rva2ptr(dll, uint32_get(&name_rvas[i])), " @ ");
      buffer_putulong(buffer_1, 1 + i);
      buffer_putnlflush(buffer_1);
    }
    mmap_unmap(dll, dllsz);
  }

  return 0;
}
예제 #12
0
static void

putsa(const char* name, stralloc* tag) {
  size_t i;
  buffer_putm_internal(buffer_1, name, ": ", 0);

  for(i = 0; i < tag->len; ++i) {
    if(tag->s[i] == '\r')
      buffer_puts(buffer_1, "\\r");
    else if(tag->s[i] == '\n')
      buffer_puts(buffer_1, "\\n");
    else if(tag->s[i] == '\t')
      buffer_puts(buffer_1, "\\t");
    else
      buffer_PUTC(buffer_1, tag->s[i]);
  }
  buffer_putnlflush(buffer_1);
}
예제 #13
0
int main() {
  char buf[1024];
  unsigned long long int i;
  if (sizeof(unsigned long) != 4)
    return 0;
  for (i=1; i<0xfffffffffull; i+=i+1) {
    int k;
    unsigned long test;
    buf[k=fmt_ulonglong(buf,i)]=0;
    buffer_puts(buffer_1,buf); buffer_putnlflush(buffer_1);
    if (buf[scan_ulong(buf,&test)])
      /* scan did not like the whole number */
      assert(i>0xffffffffull);
    else
      assert(i<=0xffffffffull);
  }
  return 0;
}
예제 #14
0
파일: builtin_break.c 프로젝트: rsenn/shish
/* continue/break a loop
 * ----------------------------------------------------------------------- */
int builtin_break(int argc, char **argv)
{
  unsigned int n = 1;
  
  if(argv[1])
  {
    scan_uint(argv[1], &n);

    if(n == 0)
    {
      sh_error(argv[0]);
      buffer_putm(fd_err->w, ": ", argv[1], ": invalid argument");
      buffer_putnlflush(fd_err->w);
      return 1;
    }
  }
  
  eval_jump(n, (*argv[0] == 'c'));
  return 0;
}
예제 #15
0
파일: list-r.c 프로젝트: rsenn/dirlist
void
usage(char* argv0) {
  buffer_putm_internal(buffer_1,
                       "Usage: ",
                       str_basename(argv0),
                       " [-o output] [infile or stdin]\n\n",
                       "  -1 ... -9           compression level; default is 3\n",
                       "\n",
                       "Options\n",
                       "  -h, --help                show this help\n",
                       "  -l, --list                long list\n",
                       "  -n, --numeric             numeric user/group\n",
                       "  -r, --relative            relative path\n",
                       "  -o, --output     FILE     write output to FILE\n",
                       "  -x, --exclude    PATTERN  exclude entries matching PATTERN\n",
                       "  -t, --time-style FORMAT   format time according to FORMAT\n",
                       "  -m, --min-size   BYTES    minimum file size\n",
                       "  -L, --dereference         dereference symlinks\n",
                       0);
  buffer_putnlflush(buffer_1);
}
예제 #16
0
파일: sln.c 프로젝트: rsenn/dirlist
int
mklink(char* target, char* link) {
  struct stat st;

  if(stat(target, &st) == -1) {
    errmsg_warnsys("stat failed", 0);
    return -1;
  }

#if !((defined(_WIN32) || defined(_WIN64)) && !(defined(__MSYS__) || defined(__CYGWIN__)))
  if(lstat(link, &st) != -1)
#endif
  {
    unlink(link);
  }

  if(verbose) {
    buffer_putm_internal(buffer_2, "'", link, "' -> '", target, "'", 0);
    buffer_putnlflush(buffer_2);
  }

  return symlink(path_basename(target), link);
}
예제 #17
0
파일: eval_pipeline.c 프로젝트: rsenn/shish
/* evaluate a pipeline (3.9.2)
 * ----------------------------------------------------------------------- */
int eval_pipeline(struct eval *e, struct npipe *npipe) {
  struct job *job;
  union node *node;
  struct fdstack st;
  unsigned int n;
  int pid = 0;
  int prevfd = -1;
  int status = -1;

/*  job = (e->flags & E_JCTL) ? job_new(npipe->ncmd) : NULL;*/
  job = job_new(npipe->ncmd);
  
  if(job == NULL) {
    buffer_puts(fd_err->w, "no job control");
    buffer_putnlflush(fd_err->w);
  }
  
  
  for(node = npipe->cmds; node; node = node->list.next) {
    fdstack_push(&st);
    
    /* if there was a previous command we read input from pipe */
    if(prevfd >= 0) {
      struct fd *in;
      
      fd_alloca(in);
      fd_push(in, STDIN_FILENO, FD_READ|FD_PIPE);
      fd_setfd(in, prevfd);
    }
    
    /* if it isn't the last command we have to create a pipe
       to pass output to the next command */
    if(node->list.next) {
      struct fd *out;
      
      fd_alloca(out);
      fd_push(out, STDOUT_FILENO, FD_WRITE|FD_PIPE);
      prevfd = fd_pipe(out);
      
      if(prevfd == -1) {
        close(prevfd);
        sh_error("pipe creation failed");
      }
    }

    if((n = fdstack_npipes(FD_HERE|FD_SUBST)))
      fdstack_pipe(n, fdstack_alloc(n));
    
    pid = job_fork(job, node, npipe->bgnd);
    
    if(!pid) {
      /* no job control for commands inside pipe */
/*      e->mode &= E_JCTL;*/
      
      /* exit after evaluating this subtree */
      exit(eval_tree(e, node, E_EXIT));
    }
    
    fdstack_pop(&st);
    fdstack_data();
  }
  
  if(!npipe->bgnd) {
    job_wait(job, 0, &status, 0);
  }

/*  if(job)
    shell_free(job);*/
 
	return WEXITSTATUS(status);
}
예제 #18
0
파일: dir_type.c 프로젝트: rsenn/dirlist
int
dir_type(struct dir_s* d) {
  int r = 0;
#if !USE_READDIR && (defined(_WIN32) || defined(_WIN32) || defined(__MSYS__))
  if(dir_INTERNAL(d)->dir_finddata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
    r |= D_SYMLINK;
  else if(dir_INTERNAL(d)->dir_finddata.dwFileAttributes & 0x10)
    r |= D_DIRECTORY;
  else if(dir_INTERNAL(d)->dir_finddata.dwFileAttributes & 0x20)
    r |= D_FILE;
#else
#ifndef DT_DIR
#define DT_DIR 4
#endif

#ifndef DT_REG
#define DT_REG 8
#endif

#ifndef DT_LNK
#define DT_LNK 10
#endif

#if defined(_DIRENT_HAVE_D_TYPE) || (!defined(__MSYS__) && !defined(__CYGWIN__))
  switch((dir_TYPE(d))) {
    case DT_DIR: {
      r |= D_DIRECTORY;
      break;
    }
    case DT_REG: {
      r |= D_FILE;
      break;
    }
    case DT_LNK: {
      r |= D_SYMLINK;
      break;
    }
    case 0:
    default: { break; }
  }
#else
  {
    stralloc sa;
    struct stat st;
    DIR* dh = dir_INTERNAL(d)->dir_handle;

    stralloc_init(&sa);
        dir_path(d, &sa);
    stralloc_nul(&sa);

    if(lstat(sa.s, &st) != -1) {
      if(S_ISLNK(st.st_mode))
        r |= D_SYMLINK;
      else if(S_ISDIR(st.st_mode))
        r |= D_DIRECTORY;
      else if(S_ISREG(st.st_mode))
        r |= D_FILE;
    }

#ifdef DEBUG_OUTPUT
    buffer_puts(buffer_2, "dir_type path: ");
    buffer_putsa(buffer_2, &sa);
    buffer_putnlflush(buffer_2);
#endif


//      printf("dh: %p __d_dirname: %s\n", dh, dh->__d_dirname);

    stralloc_free(&sa);
  }
//#error No dirent type method
#endif

#endif
  return r;
}
예제 #19
0
파일: t.c 프로젝트: Moscarda/opentracker-1
int main(int argc,char* argv[]) {
  static size_t x;
  x=23;
  atomic_add(&x,3);
  printf("%u\n",x);
  printf("%u\n",atomic_add_return(&x,-3));
  printf("%u\n",compare_and_swap(&x,26,17));
  printf("%u\n",compare_and_swap(&x,23,17));

#if 0
  atomic_add(&x,3); printf("%u\n",x);
  x=23;
  atomic_add(&x,3); assert(x==26);
  atomic_or(&x,1); assert(x==27);
  atomic_and(&x,-2); assert(x==26);
#endif

#if 0
  iarray a;
  char* c;
  iarray_init(&a,sizeof(io_entry));
  printf("15 -> %p\n",c=iarray_allocate(&a,15));
  printf("23 -> %p\n",c=iarray_allocate(&a,23));
  printf("1234567 -> %p\n",c=iarray_allocate(&a,1234567));
  printf("23 -> %p\n",iarray_get(&a,23));
#endif
#if 0
  io_batch* b=iob_new(1234);
  int64 fd=open("t.c",0);
  iob_addbuf(b,"fnord",5);
  iob_addfile_close(b,fd,0,7365);
  iob_write(1,b,writecb);
#endif
#if 0
  char dest[1024];
  unsigned long len;
  scan_urlencoded2("libstdc++.tar.gz",dest,&len);
  buffer_putmflush(buffer_1,dest,"\n");
#endif
#if 0
  static stralloc sa;
  stralloc_copym(&sa,"foo ","bar ","baz.\n");
  write(1,sa.s,sa.len);
#endif
#if 0
  buffer_putmflush(buffer_1,"foo ","bar ","baz.\n");
#endif
#if 0
  char* c="fnord";
  int fd=open_read(c);
  errmsg_iam(argv[0]);
  carp("could not open file `",c,"'");
  diesys(23,"could not open file `",c,"'");
#endif
#if 0
  errmsg_warn("could not open file `",c,"'",0);
  errmsg_warnsys("could not open file `",c,"'",0);
#endif
#if 0
  char buf[100]="/usr/bin/sh";
  int len=str_len(buf);
  assert(byte_rchr(buf,len,'/')==8);
  assert(byte_rchr(buf,len,'@')==len);
  assert(byte_rchr(buf,len,'h')==len-1);
  printf("%d\n",byte_rchr("x",1,'x'));
#endif
#if 0
  char buf[IP6_FMT+100];
  int i;
  char ip[16];
  uint32 scope_id;
  char* s="fec0::1:220:e0ff:fe69:ad92%eth0/64";
  char blubip[16]="\0\0\0\0\0\0\0\0\0\0\xff\xff\x7f\0\0\001";
  i=scan_ip6if(s,ip,&scope_id);
  assert(s[i]=='/');
  buffer_put(buffer_1,buf,fmt_ip6if(buf,ip,scope_id));
  buffer_putnlflush(buffer_1);
  buffer_put(buffer_1,buf,fmt_ip6ifc(buf,blubip,scope_id));
  buffer_putnlflush(buffer_1);
  scan_ip6("2001:7d0:0:f015:0:0:0:1",ip);
  buffer_put(buffer_1,buf,fmt_ip6(buf,ip));
  buffer_putnlflush(buffer_1);
#endif
#if 0
  char buf[100];
  int i;
  printf("%d\n",i=fmt_pad(buf,"fnord",5,7,10));
  buf[i]=0;
  puts(buf);
#endif
#if 0
  char ip[16];
  char buf[32];
  printf("%d (expect 2)\n",scan_ip6("::",ip));
  printf("%d (expect 3)\n",scan_ip6("::1",ip));
  printf("%d (expect 16)\n",scan_ip6("fec0:0:0:ffff::1/0",ip));
  printf("%.*s\n",fmt_ip6(buf,ip),buf);
#endif
#if 0
  static stralloc s,t;
  stralloc_copys(&s,"fnord");
  stralloc_copys(&t,"abc"); printf("%d\n",stralloc_diff(&s,&t));
  stralloc_copys(&t,"fnor"); printf("%d\n",stralloc_diff(&s,&t));
  stralloc_copys(&t,"fnord"); printf("%d\n",stralloc_diff(&s,&t));
  stralloc_copys(&t,"fnordh"); printf("%d\n",stralloc_diff(&s,&t));
  stralloc_copys(&t,"hausen"); printf("%d\n",stralloc_diff(&s,&t));
#endif
#if 0
  static stralloc s;
  stralloc_copys(&s,"fnord");
  printf("%d\n",stralloc_diffs(&s,"abc"));
  printf("%d\n",stralloc_diffs(&s,"fnor"));
  printf("%d\n",stralloc_diffs(&s,"fnord"));
  printf("%d\n",stralloc_diffs(&s,"fnordh"));
  printf("%d\n",stralloc_diffs(&s,"hausen"));
#endif
#if 0
  printf("%d\n",case_starts("fnordhausen","FnOrD"));
  printf("%d\n",case_starts("fnordhausen","blah"));
#endif
#if 0
  char buf[]="FnOrD";
  case_lowers(buf);
  puts(buf);
#endif
#if 0
  char buf[100]="foo bar baz";
  printf("%d (expect 7)\n",byte_rchr(buf,11,' '));
#endif
#if 0
  unsigned long size;
  char* buf=mmap_read(argv[1],&size);
  if (buf) {
    unsigned int x=fmt_yenc(0,buf,size);
    unsigned int y;
    char* tmp=malloc(x+1);
    y=fmt_yenc(tmp,buf,size);
    write(1,tmp,x);
  }
#endif
#if 0
  char buf[100];
  char buf2[100];
  unsigned int len,len2;
  buf[fmt_yenc(buf,"http://localhost/~fefe",22)]=0;
  buffer_puts(buffer_1,buf);
  buffer_putsflush(buffer_1,"\n");
  if ((buf[len2=scan_yenc(buf,buf2,&len)])!='\n') {
    buffer_putsflush(buffer_2,"parse error!\n");
    return 1;
  }
  buffer_put(buffer_1,buf2,len2);
  buffer_putsflush(buffer_1,"\n");
  return 0;
#endif
#if 0
  char buf[100];
  char buf2[100];
  unsigned int len,len2;
  buf[fmt_base64(buf,"foo:bar",7)]=0;
  buffer_puts(buffer_1,buf);
  buffer_putsflush(buffer_1,"\n");
  if ((buf[len2=scan_base64(buf,buf2,&len)])!=0) {
    buffer_putsflush(buffer_2,"parse error!\n");
    return 1;
  }
  buffer_put(buffer_1,buf2,len2);
  buffer_putsflush(buffer_1,"\n");
  return 0;
#endif
#if 0
  unsigned long size;
  char* buf=mmap_read(argv[1],&size);
  if (buf) {
    unsigned int x=fmt_uuencoded(0,buf,size);
    unsigned int y;
    char* tmp=malloc(x+1);
    y=fmt_uuencoded(tmp,buf,size);
    write(1,tmp,x);
  }
#endif
#if 0
  char buf[]="00000000000000000000000000000001";
  char ip[16];
  if (scan_ip6_flat(buf,ip) != str_len(buf))
    buffer_putsflush(buffer_2,"parse error!\n");
#endif
#if 0
  int fd=open_read("t.c");
  buffer b;
  char buf[1024];
  char line[20];
  int i;
  buffer_init(&b,read,fd,buf,1024);
  i=buffer_getline(&b,line,19);
  buffer_puts(buffer_1,"getline returned ");
  buffer_putulong(buffer_1,i);
  buffer_puts(buffer_1,"\n");
  buffer_puts(buffer_1,line);
  buffer_flush(buffer_1);
#endif
#if 0
  buffer_putulong(buffer_1,23);
//  buffer_putspace(buffer_1);
  buffer_putsflush(buffer_1,"\n");
//  buffer_flush(buffer_1);
#endif
#if 0
  long a,b,c;
  char buf[4096];
  char buf2[4096];
  memcpy(buf,buf2,4096);
  byte_copy(buf,4096,buf2);
  rdtscl(a);
  memcpy(buf,buf2,4096);
  rdtscl(b);
  byte_copy(buf,4096,buf2);
  rdtscl(c);
  printf("memcpy: %d - byte_copy: %d\n",b-a,c-b);
#endif
#if 0
  char ip[16];
  int i;
  if ((i=scan_ip6(argv[1],ip))) {
    char buf[128];
    buf[fmt_ip6(buf,ip)]=0;
    puts(buf);
  }
#endif
#if 0
  char buf[100];
  strcpy(buf,"foobarbaz");
  buf[fmt_fill(buf,3,5,100)]=0;
  printf("\"%s\"\n",buf);
#endif
#if 0
  unsigned long len;
  char *c=mmap_read("/etc/passwd",&len);
  printf("got map %p of len %lu\n",c,len);
#endif
#if 0
  char c;
  printf("%d\n",buffer_getc(buffer_0,&c));
  printf("%c\n",c);
#endif
#if 0
  char buf[100]="01234567890123456789012345678901234567890123456789";
  long a,b,c;
#endif
#if 0
  buf[ip4_fmt(buf,ip4loopback)]=0;
  buffer_puts(buffer_1small,buf);
  buffer_flush(buffer_1small);
#endif

#if 0
  buf[0]=0;
  buf[fmt_8long(buf,0)]=0;
  puts(buf);
  rdtscl(a);
  c=str_len(buf);
  rdtscl(b);
  /*byte_zero_djb(buf,j); */
//  printf("\n%lu %d\n",b-a,c);
#endif
#if 0
  buffer_puts(buffer_1small,"hello, world\n");
  buffer_flush(buffer_1small);
#endif
#if 0
  int s=socket_tcp4();
  char ip[4]={127,0,0,1};
  int t=socket_connect4(s,ip,80);
#endif
#if 0
  char buf[100]="foo bar baz fnord   ";
  char buf2[100]="foo braz fnord";
  long a,b,c;
  long i=0,j=0,k=0;
  double d;
  uint32 l,m,n;
  stralloc sa={0};
  stralloc_copys(&sa,"fnord");
  stralloc_catlong0(&sa,-23,5);
  stralloc_append(&sa,"\n");
  printf("%d %d\n",str_equal("fnord","fnord1"),str_equal("fnord1","fnord"));
  write(1,sa.s,sa.len);
  printf("%d %d\n",stralloc_starts(&sa,"fnord"),stralloc_starts(&sa,"fnord\na"));

  l=0xdeadbeef;
  uint32_pack_big((char*)&m,l);
  uint32_unpack_big((char*)&m,&n);
  printf("%x %x %x\n",l,m,n);

  rdtscl(a);
/*  i=scan_double("3.1415",&d); */
  rdtscl(b);
  /*byte_zero_djb(buf,j); */
  rdtscl(c);
  printf("%lu %lu\n",b-a,c-b);
#endif
#if 0
  size_t size;
  char* buf=mmap_read(argv[1],&size);
  if (buf) {
    unsigned int x=fmt_urlencoded2(0,buf,size,"x");
    unsigned int y;
    char* tmp=malloc(x+1);
    y=fmt_urlencoded2(tmp,buf,size,"x");
    write(1,tmp,x);
  }
#endif
#if 0
  printf("%d %d\n",strcmp("foo","bar"),str_diff("foo","bar"));
  printf("%d %d\n",strcmp("foo","üar"),str_diff("foo","üar"));
#endif
#if 0
  {
    int16 a;
    int32 b;
    int64 c;
    assert(imult16(4,10000,&a)==0);
    assert(imult16(-4,10000,&a)==0);
    assert(imult16(5,10,&a)==1 && a==50);
    assert(imult16(-3,10000,&a)==1 && a==-30000);

    assert(imult32(0x40000000,2,&b)==0);
    assert(imult32(0x3fffffff,2,&b)==1 && b==0x7ffffffe);

    assert(imult64(0x4000000000000000ll,2,&c)==0);
    assert(imult64(0x3fffffffffffffffll,2,&c)==1 && c==0x7ffffffffffffffell);
  }
#endif
#if 0
  stralloc a;
  printf("%d\n",stralloc_copym(&a,"fnord",", ","foo"));
#endif

  return 0;
}
예제 #20
0
int main(int argc,char* argv[]) {
  unsigned long count=1000;
  struct timeval a,b;
  unsigned long d;

#ifdef RLIMIT_NPROC
  {
    struct rlimit rl;
    rl.rlim_cur=RLIM_INFINITY; rl.rlim_max=RLIM_INFINITY;
    setrlimit(RLIMIT_NPROC,&rl);
  }
#endif

  for (;;) {
    int i;
    int c=getopt(argc,argv,"hc:");
    if (c==-1) break;
    switch (c) {
    case 'c':
      i=scan_ulong(optarg,&count);
      if (i==0 || optarg[i]) {
	buffer_puts(buffer_2,"pthreadbench: warning: could not parse count: ");
	buffer_puts(buffer_2,optarg+i+1);
	buffer_putsflush(buffer_2,"\n");
      }
      break;
    case 'h':
      buffer_putsflush(buffer_2,
		  "usage: pthreadbench [-h] [-c count]\n"
		  "\n"
		  "\t-h\tprint this help\n"
		  "\t-c n\tfork off n children (default: 1000)\n");
      return 0;
    }
  }

  {
    unsigned long i;
    int pfd[2];
    char buf[100];
    pthread_t *p=malloc(count*sizeof(pthread_t));
    if (!p) {
      buffer_puts(buffer_2,"out of memory!\n");
      exit(1);
    }
    if (pipe(pfd)==-1) {
      buffer_puts(buffer_2,"pipe failed: ");
      buffer_puterror(buffer_2);
      buffer_putnlflush(buffer_2);
    }
    for (i=0; i<count; ++i) {
      int r;
      gettimeofday(&a,0);
      switch ((r=pthread_create(p+i,0,(void*(*)(void*))mythread,pfd))) {
      case 0: /* ok */
	break;
      default:
	buffer_puts(buffer_2,"could not create thread: ");
	buffer_puterror(buffer_2);
	buffer_putsflush(buffer_2,".\n");
	exit(1);
      }
      if (read(pfd[0],buf,1)!=1) {
	buffer_putsflush(buffer_2,"thread did not write into pipe?!\n");
	exit(1);
      }
      gettimeofday(&b,0);
      d=(b.tv_sec-a.tv_sec)*1000000;
      d=d+b.tv_usec-a.tv_usec;
      buffer_putulong(buffer_1,d);
      buffer_puts(buffer_1,"\n");
    }
    buffer_flush(buffer_1);
  }

  return 0;
}
예제 #21
0
파일: term_read.c 프로젝트: rsenn/shish
/* ----------------------------------------------------------------------- */
int term_read(int fd, char *buf, unsigned int len) {
  char c;
  int ret;
  static unsigned long remain;
          
  if(remain) {
  check_remain:
    if(len > remain)
      len = remain;
    byte_copy(buf, len, &term_cmdline.s[term_cmdline.len - remain]);
    remain -= len;
    if(!remain) {
      tcsetattr(fd, TCSANOW, &term_tcattr);
      stralloc_zero(&term_cmdline);
    }
    return len;
  }
    
/*  tcsetattr(fd, TCSANOW, &term_tcattr);*/
  term_attr(term_input.fd, 1);
  
  prompt_show();
    
  while((ret = buffer_getc(&term_input, &c)) > 0) {
    switch(c) {
      /* control-c discards the current line */
      case 3:
        stralloc_zero(&term_cmdline);
      /* newline */
      case '\n':
        term_newline();
        remain = term_cmdline.len;
        goto check_remain;
      /* control-a is HOME */
      case 1:
        term_home();
        break;
      /* control-e is END */
      case 5:
        term_end();
        break;
      /* control-d is EOF */
      case 4:
      if(!term_cmdline.len) {
          buffer_puts(term_output, "EOF");
          buffer_putnlflush(term_output);
          ret = 0;
          goto fail;
        }
        break;
      /* do the ANSI codes */
      case '\033':
        term_ansi();
        break;
      /* backspace */
      case 127:
      case '\b':
        term_backspace();
        break;
      /* printable chars */
      case '\t':
        c = ' ';
      default:
        if(term_insert)
          term_insertc(c);
        else
          term_overwritec(c);
        break;
    }
  }
fail:
  return ret;
}
예제 #22
0
파일: sh_loop.c 프로젝트: rsenn/shish
/* main loop, parse lines into trees and execute them
 * ----------------------------------------------------------------------- */
void sh_loop(void) {
  struct parser p;
  union node *list;
  stralloc cmd;

  buffer_puts(fd_err->w, "nargarith.next: ");
  buffer_putulong(fd_err->w, &((struct nargarith*)0)->next);
  buffer_putnlflush(fd_err->w);


  /* if we're in interactive mode some 
     additional stuff is to be initialized */
  if(source->mode & SOURCE_IACTIVE)
    history_load();
  
  stralloc_init(&cmd);

  parse_init(&p, P_DEFAULT);
  
  while(!(parse_gettok(&p, P_DEFAULT) & T_EOF)) {
    p.pushback++;
    parse_lineno = source->line;

    var_setvint("LINENO", parse_lineno, V_DEFAULT);
    
    /* launch the parser to get a complete command */
    if((list = parse_list(&p)))
    {
      struct eval e;
      
      if(source->mode & SOURCE_IACTIVE)
      {
        tree_printlist(list, &cmd, NULL);
        stralloc_catc(&cmd, '\n');
        stralloc_nul(&cmd);
        history_set(cmd.s);
        cmd.s = NULL;
        history_advance();
      }

#ifdef DEBUG
      debug_list(list, 0);
      buffer_putnlflush(fd_err->w);
#endif /* DEBUG */
      eval_push(&e, E_JCTL);
      eval_tree(&e, list, E_ROOT|E_LIST);
      sh->exitcode = eval_pop(&e);
      
      stralloc_zero(&cmd);

      tree_free(list);
    } else if(!(p.tok & (T_NL | T_SEMI | T_BGND))) {
      /* we have a parse error */
      if(p.tok != T_EOF)
        parse_error(&p, 0);

      /* exit if not interactive */
      if(!(source->mode & SOURCE_IACTIVE))
        sh_exit(1);

      /* ..otherwise discard the input buffer */
      source_flush();
      p.pushback = 0;
    }
    
    if(p.tok & (T_NL|T_SEMI|T_BGND))
      p.pushback = 0;

    /* reset prompt */
    prompt_number = 0;
  }
}
예제 #23
0
파일: builtin_cd.c 프로젝트: rsenn/shish
/* change working directory
 * ----------------------------------------------------------------------- */
int builtin_cd(int argc, char **argv) {
  int c;
  int ok = 0;
  int symbolic = 1;
  const char *arg;
  unsigned long len;
  unsigned long n;
  stralloc newcwd;
  
  /* check options, -L for symlink, -P for physical path */
  while((c = shell_getopt(argc, argv, "LP")) > 0) {
    switch(c) {
      case 'L': symbolic = 1; break;
      case 'P': symbolic = 0; break;
      default: builtin_invopt(argv); return 1;
    }
  }
  
  arg = argv[shell_optind];
  stralloc_init(&newcwd);

  /* empty argument means chdir(HOME) */
  if(arg == NULL) {
    arg = var_value("HOME", &len);

    if(arg[0] == '\0') {
      sh_msg("HOME variable not set!");
      return 1;
    }
  }

  len = str_len(arg);
  
  /* when it isn't an absolute path we have to check CDPATH */
  if(arg[0] != '/') {
    char path[PATH_MAX + 1];
    const char *cdpath;

    /* loop through colon-separated CDPATH variable */
    cdpath = var_value("CDPATH", NULL);

    do {
      /* too much, too much :) */
      if((n = str_chr(cdpath, ':')) + len + 1 > PATH_MAX) {
        /* set error code and print the longer string in the error msg */
        errno = ENAMETOOLONG;
        return builtin_errmsgn(argv, (n > len ? cdpath : arg),
                               (n > len ? n : len), strerror(errno));
      }
      
      /* copy path prefix from cdpath if present */
      if(n) {
        byte_copy(path, n, cdpath);
        cdpath += n;
        path[n++] = '/';
      }
      
      /* copy the argument and canonicalize */
      str_copy(&path[n], arg);

      ok = shell_realpath(path, &newcwd, symbolic, &sh->cwd);

      /* skip the colon */
      if(*cdpath == ':')
        cdpath++;
    } while(*cdpath && !ok);

  }
  /* absolute path */
  else {
    /* last cdpath length set to 0, because we're not using cdpath here */
    n = 0;
    ok = shell_canonicalize(arg, &newcwd, symbolic);
  }
  
  stralloc_nul(&newcwd);

  /* try to chdir() if everything's ok */
  if(ok && chdir(newcwd.s) == 0) {
    /* print path if prefix was taken from cdpath */
    if(n) {
      buffer_putsa(fd_out->w, &newcwd);
      buffer_putnlflush(fd_out->w);
    }
    
    /* set the path */
    stralloc_move(&sh->cwd, &newcwd);

    /* if the path has symlinks then set sh->cwdsym */
    sh->cwdsym = (ok > 1);

    return 0;
  }
  
  /* we failed */
  builtin_error(argv, newcwd.s);
  stralloc_free(&newcwd);
  return 1;
}
예제 #24
0
void urlencode(const char* c) {
  char* buf=alloca(strlen(c)*3+1);
  buffer_put(buffer_1,buf,fmt_urlencoded(buf,c,strlen(c)));
  buffer_putnlflush(buffer_1);
}
예제 #25
0
파일: proxy.c 프로젝트: rsenn/dirlist
int
main(int argc, char* argv[]) {
  int s = socket_tcp6();
  uint32 scope_id;
  char ip[16];
  uint16 port;
  char hisip[16];
  uint16 hisport;
  uint32 hisscope_id;
  static char seed[128];
  static stralloc fqdn;
  static stralloc out;

  if(argc != 4) {
  usage:
    buffer_putsflush(buffer_2,
                     "usage: proxy myip myport hisip hisport\n"
                     "\n"
                     "e.g.: proxy 0 119 news.fu-berlin.de 119\n");
    return 0;
  }

  if(argv[1][scan_ip6if(argv[1], ip, &scope_id)]) {
    if(str_equal(argv[1], "0")) {
      byte_zero(ip, 16);
      scope_id = 0;
    } else
      goto usage;
  }
  if(argv[2][scan_ushort(argv[2], &port)])
    goto usage;
  if(argv[3][scan_ip6if(argv[3], hisip, &hisscope_id)]) {
    dns_random_init(seed);
    if(!stralloc_copys(&fqdn, argv[3]))
      goto nomem;
    if(dns_ip4(&out, &fqdn) == -1) {
      buffer_puts(buffer_2, "unable to find IP address for ");
      buffer_puts(buffer_2, argv[3]);
      buffer_puts(buffer_2, ": ");
      buffer_puterror(buffer_2);
      buffer_putnlflush(buffer_2);
      return 111;
    }
  } else if(!stralloc_catb(&out, hisip, 16)) {
  nomem:
    buffer_putsflush(buffer_2, "out of memory\n");
    return 111;
  }
  if(argv[4][scan_ushort(argv[4], &hisport)])
    goto usage;

  if(socket_bind6_reuse(s, ip, port, scope_id) == -1) {
    buffer_puts(buffer_2, "socket_bind6_reuse: ");
    buffer_puterror(buffer_2);
    buffer_putnlflush(buffer_2);
    return 111;
  }
  if(socket_listen(s, 16) == -1) {
    buffer_puts(buffer_2, "socket_listen: ");
    buffer_puterror(buffer_2);
    buffer_putnlflush(buffer_2);
    return 111;
  }
  if(!io_fd(s)) {
    buffer_puts(buffer_2, "io_fd: ");
    buffer_puterror(buffer_2);
    buffer_putnlflush(buffer_2);
    return 111;
  }
  io_wantread(s);
  for(;;) {
    int64 i;
    io_wait();
    while((i = io_canread()) != -1) {
      if(i == s) {
        /* the read event is on the server socket */
        /* that means it's an incoming connection */
        int n;
        while((n = socket_accept6(s, ip, &port, &scope_id)) != -1) {
          int x = socket_tcp6();
          if(x == -1) {
            buffer_puts(buffer_2, "socket_tcp6 failed: ");
          fail:
            buffer_puterror(buffer_2);
            buffer_putnlflush(buffer_2);
            io_close(n);
          } else {
            struct state* s = malloc(sizeof(struct state));
            if(!s)
              goto closefail;
            s->a = n;
            s->b = x;
            s->connected = 0;
            s->done = s->todo = 0;
            s->dir = UNDECIDED;
            io_nonblock(x);
            socket_connect6(x, out.s, hisport, hisscope_id);
            if(!io_fd(x) || !io_fd(n)) {
              buffer_puts(buffer_2, "io_fd failed: ");
            closefail:
              free(s);
              io_close(x);
              goto fail;
            }
            io_setcookie(x, s);
            io_setcookie(n, s);
            io_wantwrite(x);
          }
        }
        if(errno != EAGAIN) {
          buffer_puts(buffer_2, "socket_accept6 failed: ");
          buffer_puterror(buffer_2);
          buffer_putnlflush(buffer_2);
        }
      } else {
        /* read event on an established connection */
        struct state* s = io_getcookie(i);
        int l = io_tryread(i, s->buf, sizeof(s->buf));
        if(l == -1) {
          buffer_puts(buffer_2, "io_tryread(");
          buffer_putulong(buffer_2, i);
          buffer_puts(buffer_2, "): ");
          buffer_puterror(buffer_2);
          buffer_putnlflush(buffer_2);
          io_close(s->a);
          io_close(s->b);
        } else if(l == 0) {
          buffer_puts(buffer_2, "eof on fd #");
          buffer_putulong(buffer_2, i);
          buffer_putnlflush(buffer_2);
          io_close(i);
        } else {
          int r;
          switch(r = io_trywrite(i, s->buf, l)) {
            case -1:
              buffer_puts(buffer_2, "io_tryread(");
              buffer_putulong(buffer_2, i);
              buffer_puts(buffer_2, "): ");
              buffer_puterror(buffer_2);
              buffer_putnlflush(buffer_2);
              io_close(i);
              break;
            case 0:
              buffer_puts(buffer_2, "write eof on fd #");
              buffer_putulong(buffer_2, i);
              buffer_putnlflush(buffer_2);
              io_close(i);
            default:
              if(r != l) {
                buffer_puts(buffer_2, "short write on fd #");
                buffer_putulong(buffer_2, i);
                buffer_puts(buffer_2, ": wrote ");
                buffer_putulong(buffer_2, r);
                buffer_puts(buffer_2, ", wanted to write ");
                buffer_putulong(buffer_2, l);
                buffer_putsflush(buffer_2, ").\n");
              }
          }
        }
      }
    }
  }
  return 0;
}
예제 #26
0
int main(int argc,char* argv[]) {
  unsigned long count=1000;
  int v6;

  v6=0;

  {
    struct rlimit rl;
    rl.rlim_cur=RLIM_INFINITY; rl.rlim_max=RLIM_INFINITY;
    setrlimit(RLIMIT_NOFILE,&rl);
#ifdef RLIMIT_NPROC
    setrlimit(RLIMIT_NPROC,&rl);
#endif
  }

  for (;;) {
    int i;
    int c=getopt(argc,argv,"h6c:");
    if (c==-1) break;
    switch (c) {
    case 'c':
      i=scan_ulong(optarg,&count);
      if (i==0 || optarg[i]) {
	buffer_puts(buffer_2,"httpbench: warning: could not parse count: ");
	buffer_puts(buffer_2,optarg+i+1);
	buffer_putsflush(buffer_2,"\n");
      }
      break;
    case '6':
      v6=1;
      break;
    case 'h':
      buffer_putsflush(buffer_2,
		  "usage: bindbench [-h] [-6] [-c count]\n"
		  "\n"
		  "\t-h\tprint this help\n"
		  "\t-c n\tbind n sockets to port 0 (default: 1000)\n"
		  "\t-6\tbind IPv6 sockets instead of IPV4\n");
      return 0;
    }
  }


  {
    int i,r;
    char ip[16];
    int port;
#ifdef __i386__
    unsigned long long a,b,c;
#else
    struct timeval a,b,c;
    unsigned long d;
#endif
    int *socks=alloca(count*sizeof(int));
    port=0; byte_zero(ip,16);
    for (i=0; i<count; ++i) {
#ifdef __i386__
      rdtscl(a);
#else
      gettimeofday(&a,0);
#endif
      socks[i]=v6?socket_tcp6():socket_tcp4();
#ifdef __i386__
      rdtscl(b);
#else
      gettimeofday(&b,0);
#endif
      if (socks[i]==-1) {
	buffer_puts(buffer_2,"socket() failed: ");
	buffer_puterror(buffer_2);
	buffer_putnlflush(buffer_2);
	exit(1);
      }
      if (v6)
	r=socket_bind6(socks[i],ip,port,0);
      else
	r=socket_bind4(socks[i],ip,port);
      if (r==-1) {
	buffer_puts(buffer_2,"bind() failed: ");
	buffer_puterror(buffer_2);
	buffer_putnlflush(buffer_2);
	exit(1);
      }
#ifdef __i386__
      rdtscl(c);
      buffer_putulong(buffer_1,b-a);
#else
      gettimeofday(&c,0);
      d=(b.tv_sec-a.tv_sec)*1000000;
      d=d+b.tv_usec-a.tv_usec;
      buffer_putulong(buffer_1,d);
#endif
      buffer_putspace(buffer_1);
#ifdef __i386__
      buffer_putulong(buffer_1,c-b);
#else
      d=(c.tv_sec-b.tv_sec)*1000000;
      d=d+c.tv_usec-b.tv_usec;
      buffer_putulong(buffer_1,d);
#endif
      buffer_puts(buffer_1,"\n");
      if (i>50) {
	close(socks[10]);
	socks[10]=v6?socket_tcp6():socket_tcp4();
      }
    }
  }

  buffer_flush(buffer_1);
  return 0;
}
예제 #27
0
void cescape(const char* c) {
  char* buf=alloca(strlen(c)*5+1);
  buffer_put(buffer_1,buf,fmt_cescape(buf,c,strlen(c)));
  buffer_putnlflush(buffer_1);
}
예제 #28
0
int main(int argc,char* argv[]) {
  unsigned long count=1000;
  unsigned long interval=10;
  unsigned long sample=5;
  int keepalive=0;
  char ip[16];
  uint16 port=80;
  uint32 scope_id=0;
  stralloc ips={0};
  int s;
  char* request;
  int rlen;

  signal(SIGPIPE,SIG_IGN);

  if (!geteuid()) {
    struct rlimit rl;
    long l;
#ifdef RLIMIT_NPROC
    rl.rlim_cur=RLIM_INFINITY; rl.rlim_max=RLIM_INFINITY;
    setrlimit(RLIMIT_NPROC,&rl);
#endif
    for (l=0; l<20000; l+=500) {
      rl.rlim_cur=l; rl.rlim_max=l;
      if (setrlimit(RLIMIT_NOFILE,&rl)==-1) break;
    }
  }

  for (;;) {
    int i;
    int c=getopt(argc,argv,"c:i:s:kb");
    if (c==-1) break;
    switch (c) {
    case 'k':
      keepalive=1;
      break;
    case 'i':
      i=scan_ulong(optarg,&interval);
      if (i==0 || optarg[i]) {
	buffer_puts(buffer_2,"httpbench: warning: could not parse interval: ");
	buffer_puts(buffer_2,optarg+i+1);
	buffer_putsflush(buffer_2,"\n");
      }
      break;
    case 'c':
      i=scan_ulong(optarg,&count);
      if (i==0 || optarg[i]) {
	buffer_puts(buffer_2,"httpbench: warning: could not parse count: ");
	buffer_puts(buffer_2,optarg+i+1);
	buffer_putsflush(buffer_2,"\n");
      }
      break;
    case 's':
      i=scan_ulong(optarg,&sample);
      if (i==0 || optarg[i]) {
	buffer_puts(buffer_2,"httpbench: warning: could not parse sample size: ");
	buffer_puts(buffer_2,optarg+i+1);
	buffer_putsflush(buffer_2,"\n");
      }
      break;
    case 'b':
      bindport=10000;
      break;
    case '?':
usage:
      buffer_putsflush(buffer_2,
		  "usage: httpbench [-hb] [-c count] [-i interval] [-s sample] url\n"
		  "\n"
		  "\t-h\tprint this help\n"
		  "\t-c n\topen n connections total (default: 1000)\n"
		  "\t-i n\tevery n connections, measure the latency (default: 10)\n"
		  "\t-s n\tlatency == average of time to fetch an URL n times (default: 5)\n"
		  "\t-k\tenable HTTP keep-alive\n"
		  "\t-b\tbind the sockets ourselves, so the OS doesn't choose the ports\n"
		  "Setting the number of connections to 1 measures the throughput\n"
		  "instead of the latency (give URL to a large file).\n");
      return 0;
    }
  }

  if (!argv[optind]) goto usage;
  if (byte_diff(argv[optind],7,"http://")) goto usage;
  {
    char* host=argv[optind]+7;
    int colon=str_chr(host,':');
    int slash=str_chr(host,'/');
    char* c;
    if (host[0]=='[') {	/* ipv6 IP notation */
      int tmp;
      ++host;
      --colon; --slash;
      tmp=str_chr(host,']');
      if (host[tmp]==']') host[tmp]=0;
      if (host[tmp+1]==':') colon=tmp+1;
      if (colon<tmp+1) colon=tmp+1+str_len(host+tmp+1);
    }
    if (colon<slash) {
      host[colon]=0;
      c=host+colon+1;
      if (c[scan_ushort(c,&port)]!='/') goto usage;
      *c=0;
    }
    host[colon]=0;
    c=host+slash;
    *c=0;
    {
      char* tmp=alloca(str_len(host)+1);
      tmp[fmt_str(tmp,host)]=0;
      host=tmp;
    }
    *c='/';
    {
      int tmp=str_chr(host,'%');
      if (host[tmp]) {
	host[tmp]=0;
	scope_id=socket_getifidx(host+tmp+1);
	if (scope_id==0) {
	  buffer_puts(buffer_2,"httpbench: warning: network interface ");
	  buffer_puts(buffer_2,host+tmp+1);
	  buffer_putsflush(buffer_2," not found.\n");
	}
      }
    }

    {
      stralloc a={0};
      stralloc_copys(&a,host);
      if (dns_ip6(&ips,&a)==-1) {
	buffer_puts(buffer_2,"httpbench: could not resolve IP: ");
	buffer_puts(buffer_2,host);
	buffer_putnlflush(buffer_2);
	return 1;
      }
    }

    request=malloc(300+str_len(host)+str_len(c)*3);
    if (!request) panic("malloc");
    {
      int i;
      i=fmt_str(request,"GET ");
      i+=fmt_urlencoded(request+i,c,str_len(c));
      i+=fmt_str(request+i," HTTP/1.0\r\nHost: ");
      i+=fmt_str(request+i,host);
      i+=fmt_str(request+i,":");
      i+=fmt_ulong(request+i,port);
      i+=fmt_str(request+i,"\r\nUser-Agent: httpbench/1.0\r\nConnection: ");
      i+=fmt_str(request+i,keepalive?"keep-alive":"close");
      i+=fmt_str(request+i,"\r\n\r\n");
      rlen=i; request[rlen]=0;
    }

  }

  {
    int i;
    s=-1;
    for (i=0; i+16<=ips.len; i+=16) {
      char buf[IP6_FMT];
      int v6=byte_diff(ips.s+i,12,V4mappedprefix);
      buffer_puts(buffer_1,"connecting to ");
      buffer_put(buffer_1,buf,
		 v6?
		 fmt_ip6(buf,ips.s+i):
		 fmt_ip4(buf,ips.s+i+12));
      buffer_puts(buffer_1," port ");
      buffer_putulong(buffer_1,port);
      buffer_putnlflush(buffer_1);
      s=make_connection(ips.s+i,port,scope_id);
      if (s!=-1) {
	byte_copy(ip,16,ips.s+i);
	break;
      }
    }
    if (s==-1)
      return 1;
  }
  if (write(s,request,rlen)!=rlen) panic("write");
  if (readanswer(s,count==1)==-1) exit(1);
  close(s);
  if (count==1)
    return 0;

  {
    long i;
    long j;
    long err=0;
    int *socks;
    socks=malloc(sizeof(int)*count);
    if (!socks) panic("malloc");
    for (i=j=0; i<count; ++i) {
      struct timeval a,b;
      long d;
      if (j==0) {
	int k,s=0;
	long x=0,y=0;
	for (k=0; k<sample; ++k) {
	  if (!keepalive || !k) {
	    gettimeofday(&a,0);
	    s=make_connection(ip,port,scope_id);
	    if (s==-1)
	      panic("make_connection");
	    gettimeofday(&b,0);
	    d=(b.tv_sec-a.tv_sec)*1000000;
	    d=d+b.tv_usec-a.tv_usec;
	    x+=d;
	  }
	  gettimeofday(&a,0);
	  write(s,request,rlen);
	  if (readanswer(s,0)==-1) {
	    ++err;
	    keepalive=0;
	  }
	  gettimeofday(&b,0);
	  d=(b.tv_sec-a.tv_sec)*1000000;
	  d=d+b.tv_usec-a.tv_usec;
	  y+=d;
	  if (!keepalive) close(s);
	}
	if (keepalive) close(s);
	buffer_puts(buffer_1,"sample ");
	buffer_putulong(buffer_1,x);
	buffer_puts(buffer_1," ");
	buffer_putulong(buffer_1,y/sample);
	buffer_putnlflush(buffer_1);
      }
      ++j; if (j==interval) j=0;

      gettimeofday(&a,0);
      socks[i]=make_connection(ip,port,scope_id);
      if (socks[i]==-1)
	panic("make_connection");
      gettimeofday(&b,0);
      d=(b.tv_sec-a.tv_sec)*1000000;
      d=d+b.tv_usec-a.tv_usec;
      buffer_puts(buffer_1,"clat ");
      buffer_putulong(buffer_1,d);
      buffer_putnlflush(buffer_1);
    }
  }
  buffer_flush(buffer_1);
  return 0;
}
예제 #29
0
static int readanswer(int s,int measurethroughput) {
  char buf[8192];
  int i,j,body=-1,r;
  unsigned long rest;
  unsigned long done=0;
  struct timeval a,b;
  i=0;
  while ((r=read(s,buf+i,sizeof(buf)-i)) > 0) {
    i+=r;
    for (j=0; j+3<i; ++j) {
      if (buf[j]=='\r' && buf[j+1]=='\n' && buf[j+2]=='\r' && buf[j+3]=='\n') {
	body=j+4;
	break;
      }
    }
    if (body!=-1) {
      if (byte_diff(buf,7,"HTTP/1.")) {
	buffer_putsflush(buffer_2,"invalid HTTP response!\n");
	return -1;
      }
      break;
    }
  }
  if (r==-1) return -1;
  rest=-1;
  for (j=0; j<r; j+=str_chr(buf+j,'\n')) {
    if (byte_equal(buf+j,17,"\nContent-Length: ")) {
      char* c=buf+j+17;
      if (c[scan_ulong(c,&rest)]!='\r') {
	buffer_putsflush(buffer_2,"invalid Content-Length header!\n");
	return -1;
      }
      break;
    }
    ++j;
  }
  if (measurethroughput) {
    gettimeofday(&a,0);
    done=r-body;
  }
  rest-=(r-body);
  while (rest) {
    r=read(s,buf,rest>sizeof(buf)?sizeof(buf):rest);
    if (r<1) {
      if (r==-1)
	carp("read from HTTP socket");
      else {
	buffer_puts(buffer_2,"early HTTP EOF; expected ");
	buffer_putulong(buffer_2,rest);
	buffer_putsflush(buffer_2,"more bytes!\n");
	return -1;
      }
    } else {
      rest-=r;
      if (measurethroughput) {
	unsigned long x=done/1000000;
	unsigned long y;
	done+=r;
	y=done/1000000;
	if (x!=y) {
	  unsigned long d;
	  unsigned long long z;
	  gettimeofday(&b,0);
	  d=(b.tv_sec-a.tv_sec)*1000000;
	  d=d+b.tv_usec-a.tv_usec;
	  buffer_puts(buffer_1,"tput ");
	  z=1000000000ull/d;
	  buffer_putulong(buffer_1,z);
	  buffer_putnlflush(buffer_1);

	  byte_copy(&a,sizeof(a),&b);
	}
      }
    }
  }
  return 0;
}
예제 #30
0
/* sets or displays current hostname
 * ----------------------------------------------------------------------- */
int builtin_hostname(int argc, char **argv) {
  int c;
  int force = 0;
  
  /* check options */
  while((c = shell_getopt(argc, argv, "f")) > 0) {
    switch(c) {
      case 'f': force = 1; break;
      default: builtin_invopt(argv); return 1;
    }
  }
  
  /* if there is an argument we set it as new hostname */
  if(argv[shell_optind]) {
    unsigned long n;
    
    n = str_len(argv[shell_optind]);
    
    /* unless force is set and if the new hostname is 
       the same as the current then do not update it */
    if(!force && n == sh_hostname.len && 
       !byte_diff(sh_hostname.s, n, argv[shell_optind]))
      return 0;
      
#ifdef HAVE_SETHOSTNAME    
    /* set the supplied hostname */
#if !defined(__CYGWIN__) && !defined(__MINGW32__)
    if(sethostname(argv[shell_optind], n))
#else
    errno = ENOSYS;
#endif
    {
      /* report any error */
      builtin_error(argv, "sethostname");
      return 1;
    }
#endif
    
    /* on success update internal hostname */
    stralloc_copyb(&sh_hostname, argv[shell_optind], n);
  }
  /* if there is no argument we display the current hostname */
  else {
    /* force re-get of hostname by clearing it now */
    if(force)
      stralloc_zero(&sh_hostname);
    
    /* get hostname if it isn't there */
    if(sh_hostname.len == 0)
      shell_gethostname(&sh_hostname);
    
    /* report errors */
    if(sh_hostname.len == 0) {
      builtin_error(argv, "gethostname");
      return 1;
    }
    
    /* finally output the hostname */
    buffer_putsa(fd_out->w, &sh_hostname);
    buffer_putnlflush(fd_out->w);
  }
  
  return 0;
}