Beispiel #1
0
static void dispatch(const char *dir,const char *def)
     /* Hand off control to one of the command files in the list directory. */
{
  if (!is_dir(dir))
    return;
  if (!stralloc_append(&basedir,"/")) die_nomem();
  if (!stralloc_cats(&basedir,dir)) die_nomem();
  /* FIXME: set up $EXT $EXT2 $EXT3 $EXT4 ?  Is it feasable? */
  if (def == 0 || *def == 0)
    execute("editor",0);
  else if (str_diff(def,"owner") == 0)
    execute("owner",0);
  else if (str_diff(def,"digest-owner") == 0)
    execute("owner",0);
  else {
    try_dispatch(def,"digest-return-",14,"digest/bouncer");
    try_dispatch(def,"return-",7,"bouncer");
    try_dispatch(def,"confirm-",8,"confirmer");
    try_dispatch(def,"discard-",8,"confirmer");
    try_dispatch(def,"accept-",7,"moderator");
    try_dispatch(def,"reject-",7,"moderator");
    /* If nothing else matches, call the manager. */
    execute("manager",def);
  }
}
Beispiel #2
0
int
qldap_get_dotmode(qldap *q, stralloc *dm)
{
	int	r;

	/* get and check the status of the account */
	r = qldap_get_attr(q, LDAP_DOTMODE, &ldap_attr, SINGLE_VALUE);
	if (r == NOSUCH) {
		if (!stralloc_copy(dm, &dotmode)) return ERRNO;
		return OK;
	}
	if (r != OK)
		return r;

	if (!case_diffs(DOTMODE_LDAPONLY, ldap_attr.s)) {
		if (!stralloc_copys(dm, DOTMODE_LDAPONLY)) return ERRNO;
	} else if (!str_diff(DOTMODE_LDAPWITHPROG, ldap_attr.s)) {
		if (!stralloc_copys(dm, DOTMODE_LDAPWITHPROG)) return ERRNO;
	} else if (!str_diff(DOTMODE_DOTONLY, ldap_attr.s)) {
		if (!stralloc_copys(dm, DOTMODE_DOTONLY)) return ERRNO;
	} else if (!str_diff(DOTMODE_BOTH, ldap_attr.s)) {
		if (!stralloc_copys(dm, DOTMODE_BOTH)) return ERRNO;
	} else if (!str_diff(DOTMODE_NONE, ldap_attr.s)) {
		if (!stralloc_copys(dm, DOTMODE_NONE)) return ERRNO;
	} else {
		return ILLVAL;
	}
	if (!stralloc_0(dm)) return ERRNO;
	return OK;
}
Beispiel #3
0
int utmp_logout(const char *line) {
  int fd;
  uw_tmp ut;
  int ok =-1;

  if ((fd =open(UW_TMP_UFILE, O_RDWR, 0)) < 0)
    strerr_die4sys(111, FATAL, "unable to open ", UW_TMP_UFILE, ": ");
  if (lock_ex(fd) == -1)
    strerr_die4sys(111, FATAL, "unable to lock: ", UW_TMP_UFILE, ": ");

  while (read(fd, &ut, sizeof(uw_tmp)) == sizeof(uw_tmp)) {
    if (!ut.ut_name[0] || (str_diff(ut.ut_line, line) != 0)) continue;
    memset(ut.ut_name, 0, sizeof ut.ut_name);
    memset(ut.ut_host, 0, sizeof ut.ut_host);
    if (time(&ut.ut_time) == -1) break;
#ifdef DEAD_PROCESS
    ut.ut_type =DEAD_PROCESS;
#endif
    if (lseek(fd, -(off_t)sizeof(uw_tmp), SEEK_CUR) == -1) break;
    if (write(fd, &ut, sizeof(uw_tmp)) != sizeof(uw_tmp)) break;
    ok =1;
    break;
  }
  close(fd);
  return(ok);
}
Beispiel #4
0
int flag_isnameset(const char *name)
{
  int i;
  for (i = 0; i < NO_FLAGS; ++i) {
    if (flags[i].filename != 0
	&& str_diff(name, flags[i].filename) == 0)
      return flags[i].state;
  }
  return -1;
}
Beispiel #5
0
int main(void)
{
  const char *s = "ABCD1234EFGHXXXX";
  const char *t = "ABCD1234EFGHXXXX";
  const char *u = "AbCdEfGh";
  const char *v = "aBcDeFgH";
  char *x;
  long i;
  unsigned long pos;

  test_assert(str_chr(s, 'D') == 3);

  i = str_char(s, 'D', &pos);
  test_assert(i == 1);
  test_assert(pos == 3);

  test_assert(str_diff(s, t) == 0);
  test_assert(str_same(s, t));
  test_assert(str_ndiff(s, t, 8) == 0);
  test_assert(str_nsame(s, t, 8) == 1);

  test_assert(str_casei_diff(u, v) == 0);
  test_assert(str_casei_same(u, v) == 1);
  test_assert(str_casei_ndiff(u, v, 8) == 0);
  test_assert(str_casei_nsame(u, v, 8) == 1);;

  test_assert(str_rchr(s, 'X') == 15);

  i = str_rchar(s, 'X', &pos);
  test_assert(i == 1);
  test_assert(pos == 15);

  test_assert(str_dup(s, &x));

  test_assert(str_same(s, x) == 1);
  test_assert(str_nsame(s, x, 8) == 1);

  test_assert(str_starts(s, "ABCD") == 1);
  test_assert(str_starts(s, "XYZA") == 0);
  test_assert(str_starts(s, "1234EFGH1234EFGH1234EFGH") == 0);

  test_assert(str_ends(s, "XXXX") == 1);
  test_assert(str_ends(s, "ABCD") == 0);
  test_assert(str_ends(s, "GH1234EFGH123GH1234EFGH123") == 0);

  test_assert(str_len(s) == 16);
  
  str_toupper(x);
  test_assert(x[0] == 'A');
  str_tolower(x);
  test_assert(x[0] == 'a');

  return 0;
}
Beispiel #6
0
int filesfit(struct cyclog *d)
{
  DIR *dir;
  direntry *x;
  int count;
  int i;

  dir = opendir(".");
  if (!dir) return -1;

  fn[0] = '@';
  fn[1] = 'z';
  fn[2] = 0;

  count = 0;
  for (;;) {
    errno = 0;
    x = readdir(dir);
    if (!x) break;
    if (x->d_name[0] == '@')
      if (str_len(x->d_name) >= 25) {
        ++count;
        if (str_diff(x->d_name,fn) < 0) {
          for (i = 0;i < 25;++i)
            fn[i] = x->d_name[i];
          fn[25] = 0;
        }
      }
  }
  if (errno) { closedir(dir); return -1; }
  closedir(dir);

  if (count < d->num) return 1;

  dir = opendir(".");
  if (!dir) return -1;

  for (;;) {
    errno = 0;
    x = readdir(dir);
    if (!x) break;
    if (x->d_name[0] == '@')
      if (str_len(x->d_name) >= 25)
        if (str_start(x->d_name,fn)) {
	  unlink(x->d_name);
	  break;
        }
  }
  if (errno) { closedir(dir); return -1; }
  closedir(dir);
  return 0;
}
const char *get_from(const char *adr, /* target address */
		     const char *act) /* action */
/* If we captured a from line, it will be from the subscriber, except   */
/* when -S is used when it's usually from the subscriber, but of course */
/* could be from anyone. The matching to stored data is required only   */
/* to support moderated lists, and in cases where a new -sc is issued   */
/* because an old one was invalid. In this case, we read through the    */
/* from file trying to match up a timestamp with that starting in       */
/* *(act+3). If the time stamp matches, we compare the target address   */
/* itself. act + 3 must be a legal part of the string returns pointer to*/
/* fromline, NULL if not found. Since the execution time from when to   */
/* storage may differ, we can't assume that the timestamps are in order.*/
{
  int fd;
  const char *fl;
  unsigned int pos;
  unsigned long thistime;
  unsigned long linetime;

  if (!flagstorefrom) return 0;
  if (fromline.len) {	/* easy! We got it in this message */
    stralloc_0(&fromline);
    return fromline.s;
  }			/* need to recover it from DIR/from */
  fl = 0;
  (void) scan_ulong(act+3,&thistime);
  if ((fd = open_read("from")) == -1) {
    if (errno == error_noent)
      return 0;
    else
      strerr_die2sys(111,FATAL,MSG1(ERR_READ,"from"));
  }
  substdio_fdbuf(&sstext,read,fd,textbuf,(int) sizeof(textbuf));
  for (;;) {
    if (getln(&sstext,&fromline,&match,'\n') == -1)
      strerr_die2sys(111,FATAL,MSG1(ERR_READ,"from"));
    if (!match) break;
    fromline.s[fromline.len - 1] = (char) 0;
	/* now:time addr\0fromline\0 read all. They can be out of order! */
    pos = scan_ulong(fromline.s,&linetime);
    if (linetime != thistime) continue;
    if (!str_diff(fromline.s + pos + 1,adr)) {
      pos = str_len(fromline.s);
      if (pos < fromline.len) {
	fl = fromline.s + pos + 1;
	break;
      }
    }
  }
  close(fd);
  return fl;
}
Beispiel #8
0
int vmailmgr_autoconvert(void)
{
  int writefd = -1;
  ibuf reader;
  struct cdb_make writer;
  int error = 0;
  int readall = 0;
  int writerr = 0;
  if ((writefd = path_mktemp(pwfile, &tmppwfile)) != -1) {

    if (cdb_make_start(&writer, writefd) != 0)
      error = CVME_IO | CVME_FATAL;
    else {

      if (ibuf_open(&reader, pwfile, 0)) {

	uint32 end;
	struct stat st;
	if (fstat(reader.io.fd, &st) == 0
	    && fchmod(writefd, st.st_mode) == 0
	    && fchown(writefd, st.st_uid, st.st_gid) == 0
	    && read_start(&reader, &end)) {
	  while (ibuf_tell(&reader) < end) {
	    if (!read_cdb_pair(&reader, &key, &data))
	      break;
	    if (str_diff(&key, &virtuser) == 0)
	      if (!convert_data()) {
		writerr = 1;
		break;
	      }
	    if (cdb_make_add(&writer, key.s, key.len, data.s, data.len) != 0) {
	      writerr = 1;
	      break;
	    }
	  }
	  readall = ibuf_tell(&reader) == end;
	}
	ibuf_close(&reader);
      }
      if (cdb_make_finish(&writer) != 0)
	error |= CVME_FATAL;
      else
	if (readall && !writerr)
	  rename(tmppwfile.s, pwfile);
    }
    close(writefd);
    unlink(tmppwfile.s);
  }
  return error;
}
Beispiel #9
0
int
call_puts(struct call *cc, const char *s)
{
	if (cc->flagerr || cc->flagabort) return -1;
	if (cc->flagstar && str_diff(s, "*") == 0) {
		cc->flagabort = 1;
		return -1;
	}
	if (substdio_puts(&cc->ssto, s) == -1) {
		cc->flagerr = 1;
		return -1;
	}
	return 0;
}
Beispiel #10
0
dict_entry* dict_get(dict* d, const str* s)
{
    uint32 hash;
    unsigned i;
    dict_entry* slot;
    if (!d->size || !d->table) return 0;
    hash = dict_hashstr(s);
    i = hash % d->size;
    while ((slot = d->table[i]) != 0) {
        if (hash == slot->hash)
            if (str_diff(s, &slot->key) == 0)
                return slot;
        if (++i >= d->size) i = 0;
    }
    return 0;
}
Beispiel #11
0
int prot_readgroups (char const *name, gid_t *tab, unsigned int max)
{
  unsigned int n = 0 ;
  for (;;)
  {
    struct group *gr ;
    register char **member ;
    errno = 0 ;
    if (n >= max) break ;
    gr = getgrent() ;
    if (!gr) break ;
    for (member = gr->gr_mem ; *member ; member++)
      if (!str_diff(name, *member)) break ;
    if (*member) tab[n++] = gr->gr_gid ;
  }
  endgrent() ;
  return errno ? -1 : (int)n ;
}
Beispiel #12
0
static void parse_flags(int argc, char *argv[])
{
  int ind;
  unsigned int jnd;

  --argc;
  ++argv;

  if (!argc) { usage(); exit(111); }

  flag = 0;
  for (ind = 0; ind < argc; ++ind) {
    for (jnd = 0; jnd < sizeof(flags) / sizeof(flags[0]); ++jnd) {
      if (str_diff(argv[ind], flags[jnd].flag) == 0) {
        flag |= flags[jnd].val;
        break;
      }
    }
  }
}
Beispiel #13
0
static void filter_server_data(char* data, ssize_t size)
{
  if(saved_label.len > 0) {
    /* Skip continuation data */
    if(data[0] != '+') {
      int resp;
      /* Check if the response is tagged with the saved label */
      str_copyb(&linebuf, data, size);
      resp = parse_label();
      if(resp > 0) {
	if(!str_diff(&label, &saved_label)) {
	  log_line(data, size);
	  /* Check if the response was an OK */
	  if(!strncasecmp(linebuf.s + resp, "OK ", 3))
	    accept_client(username.s);
	  else
	    deny_client(username.s);
	  str_truncate(&saved_label, 0);
	}
      }
    }
  }
  write_client(data, size);
}
Beispiel #14
0
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;
}
Beispiel #15
0
int main(int argc,char *argv[])
//int argc;
//char *argv[];
{
  int dummy;
  char *proto;
  int opt;
  int flagremoteinfo;
  unsigned long timeout;
// struct sockaddr_in *v4;

  sig_pipeignore();

  flagremoteinfo = 1;
  timeout = 30;
  while ((opt = getopt(argc,argv,"rRt:")) != opteof)
    switch(opt)
    {
     case 'r': flagremoteinfo = 1; break;
     case 'R': flagremoteinfo = 0; break;
     case 't': scan_ulong(subgetoptarg,&timeout); break;
    }

  argv += subgetoptind;
  argc -= subgetoptind;

  if (argc < 1) die();
  if (!env_init()) die();

  proto = env_get("PROTO");
  if (!proto || str_diff(proto,"TCP"))
  {
    if (!env_puts("PROTO=TCP")) die();

    dummy = sizeof(salocal);
    if (getsockname(0,(struct sockaddr *) &salocal, (socklen_t *) &dummy) == -1) die();
    mappedtov4(&salocal);
    switch(salocal.sa.sa_family) {
    case AF_INET:
      localport = ntohs(salocal.sa4.sin_port);
      temp[fmt_ulong(temp,localport)] = 0;
    if (!env_put("TCPLOCALPORT",temp)) die();
      temp[ip4_fmt(temp,(char *) &salocal.sa4.sin_addr)] = 0;
    if (!env_put("TCPLOCALIP",temp)) die();

    switch(dns_ptr(&localname,&salocal.sa4.sin_addr)) {
      case DNS_MEM: die();
      case DNS_SOFT:
        if (!stralloc_copys(&localname,"softdnserror")) die();
      case 0:
        if (!stralloc_0(&localname)) die();
        case_lowers(localname.s);
        if (!env_put("TCPLOCALHOST",localname.s)) die();
        break;
      default:
        if (!env_unset("TCPLOCALHOST")) die();
    }
    break;
#ifdef INET6
    case AF_INET6:
      localport = ntohs(salocal.sa6.sin6_port);
      temp[fmt_ulong(temp,localport)] = 0;
      if (!env_put("TCPLOCALPORT",temp)) die();
      temp[ip6_fmt(temp,(char *) &salocal.sa6.sin6_addr)] = 0;
      if (!env_put("TCPLOCALIP",temp)) die();
      switch(dns_ptr6(&localname,&salocal.sa6.sin6_addr)) {
        case DNS_MEM: die();
        case DNS_SOFT:
             if (!stralloc_copys(&localname,"softdnserror")) die();
        case 0:
             if (!stralloc_0(&localname)) die();
          case_lowers(localname.s);
          if (!env_put("TCPLOCALHOST",localname.s)) die();
          break;
        default:
             if (!env_unset("TCPLOCALHOST")) die();
      }
      break;
#endif
    default:
      die();
    }

    dummy = sizeof(saremote);
    if (getpeername(0,(struct sockaddr *) &saremote, (socklen_t *) &dummy) == -1) die();
      mappedtov4(&saremote);

    switch(saremote.sa.sa_family) {
    case AF_INET:
      remoteport = ntohs(saremote.sa4.sin_port);
      temp[fmt_ulong(temp,remoteport)] = 0;
    if (!env_put("TCPREMOTEPORT",temp)) die();

    temp[ip4_fmt(temp,(char *)&saremote.sa4.sin_addr)] = 0;
    if (!env_put("TCPREMOTEIP",temp)) die();

    switch(dns_ptr(&remotename,&saremote.sa4.sin_addr)) {
    case DNS_MEM: die();
    case DNS_SOFT:
      if (!stralloc_copys(&remotename,"softdnserror")) die();
    case 0:
      if (!stralloc_0(&remotename)) die();
      case_lowers(remotename.s);
      if (!env_put("TCPREMOTEHOST",remotename.s)) die();
      break;
    default:
      if (!env_unset("TCPREMOTEHOST")) die();
    }
    break;
#ifdef INET6
    case AF_INET6:
    remoteport = ntohs(saremote.sa6.sin6_port);
      temp[fmt_ulong(temp,remoteport)] = 0;
    if (!env_put("TCPREMOTEPORT",temp)) die();
    temp[ip6_fmt(temp,(char *) &saremote.sa6.sin6_addr)] = 0;
    if (!env_put("TCPREMOTEIP",temp)) die();
    switch(dns_ptr6(&remotename,&saremote.sa6.sin6_addr)) {
     case DNS_MEM: die();
     case DNS_SOFT:
       if (!stralloc_copys(&remotename,"softdnserror")) die();
     case 0:
       if (!stralloc_0(&remotename)) die();
       case_lowers(remotename.s);
       if (!env_put("TCPREMOTEHOST",remotename.s)) die();
       break;
     default:
       if (!env_unset("TCPREMOTEHOST")) die();
    }
    break;
#endif
    default:
      die();
    }

    if (!env_unset("TCPREMOTEINFO")) die();

    if (flagremoteinfo)
    {
      char *rinfo;
      rinfo = remoteinfo_get(&saremote, &salocal,(int) timeout);
      if (rinfo)
        if (!env_put("TCPREMOTEINFO",rinfo)) die();
    }
  }

  sig_pipedefault();
  execvp(*argv,argv);
  die();
  return(0);  /* never reached */
}
Beispiel #16
0
int main (int argc, char const *const *argv, char const *const *envp)
{
  char const *delim = DELIM_DEFAULT ;
  char const *codes = 0 ;
  int crunch = 0, chomp = 0, not = 1, par = 0 ;
  PROG = "forbacktickx" ;
  {
    subgetopt_t l = SUBGETOPT_ZERO ;
    for (;;)
    {
      register int opt = subgetopt_r(argc, argv, "epnCc0d:o:x:", &l) ;
      if (opt == -1) break ;
      switch (opt)
      {
	case 'e' : break ; /* compat */
        case 'p' : par = 1 ; break ;
        case 'n' : chomp = 1 ; break ;
        case 'C' : crunch = 1 ; break ;
        case 'c' : crunch = 0 ; break ;
        case '0' : delim = 0 ; break ;
        case 'd' : delim = l.arg ; break ;
        case 'o' :
        {
          unsigned short okcodes[256] ;
          unsigned int nbc ;
          if (!ushort_scanlist(okcodes, 256, l.arg, &nbc)) dieusage() ;
          codes = l.arg ;
          not = 0 ;
          break ;
        }
        case 'x' :
        {
          unsigned short okcodes[256] ;
          unsigned int nbc ;
          if (!ushort_scanlist(okcodes, 256, l.arg, &nbc)) dieusage() ;
          codes = l.arg ;
          not = 1 ;
          break ;
        }
        default : dieusage() ;
      }
    }
    argc -= l.ind ; argv += l.ind ;
  }
  if (argc < 2) dieusage() ;
  if (!argv[0][0]) dieusage() ;
  if (!argv[1][0]) strerr_dief1x(100, "empty block") ;
  {
    unsigned int m = 0, i = 1 ;
    int fd = dup(0) ;
    char const *newargv[argc + 18] ;
    char fmt[UINT_FMT] ;
    if (fd < 0)
    {
      if (errno != EBADF) strerr_diefu1sys(111, "dup stdin") ;
    }
    else fmt[uint_fmt(fmt, (unsigned int)fd)] = 0 ;
    newargv[m++] = EXECLINE_BINPREFIX "pipeline" ;
    newargv[m++] = "--" ;
    while (argv[i] && argv[i][0] != EXECLINE_BLOCK_END_CHAR && (!EXECLINE_BLOCK_END_CHAR || (argv[i][0] && argv[i][1])))
      newargv[m++] = argv[i++] ;
    if (!argv[i]) strerr_dief1x(100, "unterminated block") ;
    newargv[m++] = "" ; i++ ;
    newargv[m++] = EXECLINE_BINPREFIX "unexport" ;
    newargv[m++] = "!" ;
    newargv[m++] = EXECLINE_BINPREFIX "forstdin" ;
    if (par) newargv[m++] = "-p" ;
    if (chomp) newargv[m++] = "-n" ;
    if (crunch) newargv[m++] = "-C" ;
    if (!delim) newargv[m++] = "-0" ;
    else if (str_diff(delim, DELIM_DEFAULT))
    {
      newargv[m++] = "-d" ;
      newargv[m++] = delim ;
    }
    if (codes)
    {
      newargv[m++] = not ? "-x" : "-o" ;
      newargv[m++] = codes ;
    }
    newargv[m++] = "--" ;
    newargv[m++] = argv[0] ;
    if (fd < 0)
    {
      newargv[m++] = EXECLINE_BINPREFIX "fdclose" ;
      newargv[m++] = "0" ;
    }
    else
    {
      newargv[m++] = EXECLINE_BINPREFIX "fdmove" ;
      newargv[m++] = "0" ;
      newargv[m++] = fmt ;
    }
    while (argv[i]) newargv[m++] = argv[i++] ;
    newargv[m++] = 0 ;
    pathexec_run(newargv[0], newargv, envp) ;
    strerr_dieexec(111, newargv[0]) ;
  }
}
Beispiel #17
0
int main(int argc,char **argv)
{
  unsigned long ttl;
  struct stat st;
  int i;
  int j;
  int k;
  char ch;

  if (!*argv) die_usage();

  if (!*++argv) die_usage();
  fn = *argv;

  if (!*++argv) die_usage();
  fnnew = *argv;

  if (!*++argv) die_usage();
  if (str_diff(*argv,"add")) die_usage();

  if (!*++argv) die_usage();
  if (str_equal(*argv,"ns")) mode = '.';
  else if (str_equal(*argv,"childns")) mode = '&';
  else if (str_equal(*argv,"host")) mode = '=';
  else if (str_equal(*argv,"host6")) mode = '6';
  else if (str_equal(*argv,"alias")) mode = '+';
  else if (str_equal(*argv,"alias6")) mode = '3';
  else if (str_equal(*argv,"mx")) mode = '@';
  else die_usage();

  if (!*++argv) die_usage();
  if (!dns_domain_fromdot(&target,*argv,str_len(*argv))) nomem();

  if (!*++argv) die_usage();
  if (mode == '6' || mode == '3') {
    if (!ip6_scan(*argv,targetip6)) die_usage();
  } else {
    if (!ip4_scan(*argv,targetip)) die_usage();
  }

  umask(077);

  fd = open_read(fn);
  if (fd == -1) die_read();
  if (fstat(fd,&st) == -1) die_read();
  buffer_init(&b,buffer_unixread,fd,bspace,sizeof bspace);

  fdnew = open_trunc(fnnew);
  if (fdnew == -1) die_write();
  if (fchmod(fdnew,st.st_mode & 0644) == -1) die_write();
  buffer_init(&bnew,buffer_unixwrite,fdnew,bnewspace,sizeof bnewspace);

  switch(mode) {
    case '.': case '&':
      ttl = TTL_NS;
      for (i = 0;i < 26;++i) {
	ch = 'a' + i;
	if (!stralloc_copyb(&f[0],&ch,1)) nomem();
	if (!stralloc_cats(&f[0],".ns.")) nomem();
	if (!dns_domain_todot_cat(&f[0],target)) nomem();
	if (!dns_domain_fromdot(&names[i],f[0].s,f[0].len)) nomem();
      }
      break;
    case '+': case '=': case '6': case '3':
      ttl = TTL_POSITIVE;
      break;
    case '@':
      ttl = TTL_POSITIVE;
      for (i = 0;i < 26;++i) {
	ch = 'a' + i;
	if (!stralloc_copyb(&f[0],&ch,1)) nomem();
	if (!stralloc_cats(&f[0],".mx.")) nomem();
	if (!dns_domain_todot_cat(&f[0],target)) nomem();
	if (!dns_domain_fromdot(&names[i],f[0].s,f[0].len)) nomem();
      }
      break;
  }

  while (match) {
    if (getln(&b,&line,&match,'\n') == -1) die_read();

    put(line.s,line.len);
    if (line.len && !match) put("\n",1);

    while (line.len) {
      ch = line.s[line.len - 1];
      if ((ch != ' ') && (ch != '\t') && (ch != '\n')) break;
      --line.len;
    }
    if (!line.len) continue;
    if (line.s[0] == '#') continue;

    j = 1;
    for (i = 0;i < NUMFIELDS;++i) {
      if (j >= line.len) {
	if (!stralloc_copys(&f[i],"")) nomem();
      }
      else {
        k = byte_chr(line.s + j,line.len - j,':');
	if (!stralloc_copyb(&f[i],line.s + j,k)) nomem();
	j += k + 1;
      }
    }

    switch(mode) {
      case '.': case '&':
	if (line.s[0] == mode) {
          if (!dns_domain_fromdot(&d1,f[0].s,f[0].len)) nomem();
	  if (dns_domain_equal(d1,target)) {
	    if (byte_chr(f[2].s,f[2].len,'.') >= f[2].len) {
	      if (!stralloc_cats(&f[2],".ns.")) nomem();
	      if (!stralloc_catb(&f[2],f[0].s,f[0].len)) nomem();
	    }
	    if (!dns_domain_fromdot(&d2,f[2].s,f[2].len)) nomem();
	    if (!stralloc_0(&f[3])) nomem();
	    if (!scan_ulong(f[3].s,&ttl)) ttl = TTL_NS;
	    for (i = 0;i < 26;++i)
	      if (dns_domain_equal(d2,names[i])) {
	        used[i] = 1;
		break;
	      }
	  }
	}
	break;

      case '=':
	if (line.s[0] == '=') {
	  if (!dns_domain_fromdot(&d1,f[0].s,f[0].len)) nomem();
	  if (dns_domain_equal(d1,target))
	    strerr_die2x(100,FATAL,"host name already used");
	  if (!stralloc_0(&f[1])) nomem();
	  if (ip4_scan(f[1].s,ip))
	    if (byte_equal(ip,4,targetip))
	      strerr_die2x(100,FATAL,"IP address already used");
	}
	break;

      case '6':
	if (line.s[0] == '6') {
	  if (!dns_domain_fromdot(&d1,f[0].s,f[0].len)) nomem();
	  if (dns_domain_equal(d1,target))
	    strerr_die2x(100,FATAL,"host name already used");
	  if (!stralloc_0(&f[1])) nomem();
	  if (ip6_scan(f[1].s,ip6))
	    if (byte_equal(ip,16,targetip6))
	      strerr_die2x(100,FATAL,"IPv6 address already used");
	}
	break;

      case '@':
	if (line.s[0] == '@') {
          if (!dns_domain_fromdot(&d1,f[0].s,f[0].len)) nomem();
	  if (dns_domain_equal(d1,target)) {
	    if (byte_chr(f[2].s,f[2].len,'.') >= f[2].len) {
	      if (!stralloc_cats(&f[2],".mx.")) nomem();
	      if (!stralloc_catb(&f[2],f[0].s,f[0].len)) nomem();
	    }
	    if (!dns_domain_fromdot(&d2,f[2].s,f[2].len)) nomem();
	    if (!stralloc_0(&f[4])) nomem();
	    if (!scan_ulong(f[4].s,&ttl)) ttl = TTL_POSITIVE;
	    for (i = 0;i < 26;++i)
	      if (dns_domain_equal(d2,names[i])) {
	        used[i] = 1;
		break;
	      }
	  }
	}
	break;
    }
  }

  if (!stralloc_copyb(&f[0],&mode,1)) nomem();
  if (!dns_domain_todot_cat(&f[0],target)) nomem();
  if (!stralloc_cats(&f[0],":")) nomem();
  if (mode == '6' || mode == '3') {
    if (!stralloc_catb(&f[0],ip6str,ip6_fmt_flat(ip6str,targetip6))) nomem();
  } else {
    if (!stralloc_catb(&f[0],ipstr,ip4_fmt(ipstr,targetip))) nomem();
  }
  switch(mode) {
    case '.': case '&': case '@':
      for (i = 0;i < 26;++i)
	if (!used[i])
	  break;
      if (i >= 26)
	strerr_die2x(100,FATAL,"too many records for that domain");
      ch = 'a' + i;
      if (!stralloc_cats(&f[0],":")) nomem();
      if (!stralloc_catb(&f[0],&ch,1)) nomem();
      if (mode == '@')
        if (!stralloc_cats(&f[0],":")) nomem();
      break;
  }
  if (!stralloc_cats(&f[0],":")) nomem();
  if (!stralloc_catb(&f[0],strnum,fmt_ulong(strnum,ttl))) nomem();
  if (!stralloc_cats(&f[0],"\n")) nomem();
  put(f[0].s,f[0].len);

  if (buffer_flush(&bnew) == -1) die_write();
  if (fsync(fdnew) == -1) die_write();
  if (close(fdnew) == -1) die_write(); /* NFS dorks */
  if (rename(fnnew,fn) == -1)
    strerr_die6sys(111,FATAL,"unable to move ",fnnew," to ",fn,": ");
  _exit(0);
}
Beispiel #18
0
int
main (int argc, char *argv[])
{
    char ch = 0;
    struct stat st;
    unsigned long ttl = 0;
    unsigned i = 0, j = 0, k = 0;

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

    if (argc < 6)
    {
        usage ();
        return -1;
    }

    fn = *argv;

    argv++;
    fnnew = *argv;

    argv++;
    if (str_diff (*argv, "add"))
    {
        usage ();
        return -1;
    }

    argv++;
    if (str_equal (*argv, "ns"))
        mode = '.';
    else if (str_equal (*argv, "childns"))
        mode = '&';
    else if (str_equal (*argv, "host"))
        mode = '=';
    else if (str_equal (*argv, "alias"))
        mode = '+';
    else if (str_equal (*argv, "mx"))
        mode = '@';
    else
        errx (-1, "invalid record type `%s'", *argv);

    argv++;
    if (!dns_domain_fromdot (&target, *argv, str_len (*argv)))
        err (-1, "could not allocate enough memory");

    argv++;
    if (!ip4_scan (*argv, targetip))
        errx (-1, "could not parse IP `%s'", *argv);

    umask(077);

    fd = open_read (fn);
    if (fd == -1)
        err (-1, "could not read from `%s'", fn);
    if (fstat (fd, &st) == -1)
        err (-1, "could not read from `%s'", fn);
    buffer_init (&b, buffer_unixread, fd, bspace, sizeof bspace);

    fdnew = open_trunc (fnnew);
    if (fdnew == -1)
        err (-1, "could not write to `%s'", fnnew);
    if (fchmod (fdnew, st.st_mode & 0644) == -1)
        err (-1, "could not write to `%s'", fnnew);
    buffer_init (&bnew, buffer_unixwrite, fdnew, bnewspace, sizeof bnewspace);

    switch (mode)
    {
    case '.':
    case '&':
        ttl = TTL_NS;
        for (i = 0; i < 26; i++)
        {
            ch = 'a' + i;
            if (!stralloc_copyb (&f[0], &ch, 1))
                err (-1, "could not allocate enough memory");
            if (!stralloc_cats (&f[0], ".ns."))
                err (-1, "could not allocate enough memory");
            if (!dns_domain_todot_cat (&f[0], target))
                err (-1, "could not allocate enough memory");
            if (!dns_domain_fromdot (&names[i], f[0].s, f[0].len))
                err (-1, "could not allocate enough memory");
        }
        break;

    case '+':
    case '=':
        ttl = TTL_POSITIVE;
        break;

    case '@':
        ttl = TTL_POSITIVE;
        for (i = 0; i < 26; i++)
        {
            ch = 'a' + i;
            if (!stralloc_copyb (&f[0], &ch, 1))
                err (-1, "could not allocate enough memory");
            if (!stralloc_cats (&f[0], ".mx."))
                err (-1, "could not allocate enough memory");
            if (!dns_domain_todot_cat (&f[0], target))
                err (-1, "could not allocate enough memory");
            if (!dns_domain_fromdot (&names[i], f[0].s, f[0].len))
                err (-1, "could not allocate enough memory");
        }
        break;
    }

    while (match)
    {
        if (getln (&b, &line, &match, '\n') == -1)
            err (-1, "could not read from `%s'", fn);

        put (line.s, line.len);
        if (line.len && !match)
            put ("\n", 1);

        while (line.len)
        {
            ch = line.s[line.len - 1];
            if ((ch != ' ') && (ch != '\t') && (ch != '\n'))
                break;

            --line.len;
        }
        if (!line.len || line.s[0] == '#')
            continue;

        j = 1;
        for (i = 0; i < NUMFIELDS; i++)
        {
            if (j >= line.len)
            {
                if (!stralloc_copys (&f[i], ""))
                    err (-1, "could not allocate enough memory");
            }
            else
            {
                k = byte_chr (line.s + j, line.len - j, ':');
                if (!stralloc_copyb (&f[i], line.s + j, k))
                    err (-1, "could not allocate enough memory");
                j += k + 1;
            }
        }

        switch(mode)
        {
        case '.':
        case '&':
            if (line.s[0] == mode)
            {
                if (!dns_domain_fromdot (&d1, f[0].s, f[0].len))
                    err (-1, "could not allocate enough memory");
                if (dns_domain_equal (d1, target))
                {
                    if (byte_chr (f[2].s, f[2].len, '.') >= f[2].len)
                    {
                        if (!stralloc_cats (&f[2], ".ns."))
                            err (-1, "could not allocate enough memory");
                        if (!stralloc_catb (&f[2], f[0].s, f[0].len))
                            err (-1, "could not allocate enough memory");
                    }
                    if (!dns_domain_fromdot (&d2, f[2].s, f[2].len))
                        err (-1, "could not allocate enough memory");
                    if (!stralloc_0 (&f[3]))
                        err (-1, "could not allocate enough memory");
                    if (!scan_ulong (f[3].s, &ttl))
                        ttl = TTL_NS;
                    for (i = 0; i < 26; i++)
                    {
                        if (dns_domain_equal (d2, names[i]))
                        {
                            used[i] = 1;
                            break;
                        }
                    }
                }
            }
            break;

        case '=':
            if (line.s[0] == '=')
            {
                if (!dns_domain_fromdot (&d1, f[0].s, f[0].len))
                    err (-1, "could not allocate enough memory");
                if (dns_domain_equal (d1, target))
                    errx (-1, "host name is already used");
                if (!stralloc_0 (&f[1]))
                    err (-1, "could not allocate enough memory");
                if (ip4_scan (f[1].s, ip))
                    if (byte_equal(ip, 4, targetip))
                        errx (-1, "IP address is already used");
            }
            break;

        case '@':
            if (line.s[0] == '@')
            {
                if (!dns_domain_fromdot (&d1, f[0].s, f[0].len))
                    err (-1, "could not allocate enough memory");
                if (dns_domain_equal (d1, target))
                {
                    if (byte_chr (f[2].s, f[2].len, '.') >= f[2].len)
                    {
                        if (!stralloc_cats (&f[2], ".mx."))
                            err (-1, "could not allocate enough memory");
                        if (!stralloc_catb (&f[2], f[0].s, f[0].len))
                            err (-1, "could not allocate enough memory");
                    }
                    if (!dns_domain_fromdot (&d2, f[2].s, f[2].len))
                        err (-1, "could not allocate enough memory");
                    if (!stralloc_0 (&f[4]))
                        err (-1, "could not allocate enough memory");
                    if (!scan_ulong (f[4].s, &ttl))
                        ttl = TTL_POSITIVE;
                    for (i = 0; i < 26; i++)
                    {
                        if (dns_domain_equal (d2, names[i]))
                        {
                            used[i] = 1;
                            break;
                        }
                    }
                }
            }
            break;
        }
    }

    if (!stralloc_copyb (&f[0], &mode, 1))
        err (-1, "could not allocate enough memory");
    if (!dns_domain_todot_cat (&f[0], target))
        err (-1, "could not allocate enough memory");
    if (!stralloc_cats (&f[0], ":"))
        err (-1, "could not allocate enough memory");
    if (!stralloc_catb (&f[0], ipstr, ip4_fmt (ipstr, targetip)))
        err (-1, "could not allocate enough memory");

    switch (mode)
    {
    case '.':
    case '&':
    case '@':
        for (i = 0; i < 26; i++)
        {
            if (!used[i])
                break;
        }
        if (i >= 26)
            errx (-1, "too many records for domain `%s'", target);

        ch = 'a' + i;
        if (!stralloc_cats (&f[0], ":"))
            err (-1, "could not allocate enough memory");
        if (!stralloc_catb (&f[0], &ch, 1))
            err (-1, "could not allocate enough memory");
        if (mode == '@')
            if (!stralloc_cats (&f[0], ":"))
                err (-1, "could not allocate enough memory");

        break;
    }

    if (!stralloc_cats (&f[0], ":"))
        err (-1, "could not allocate enough memory");
    if (!stralloc_catb (&f[0], strnum, fmt_ulong (strnum, ttl)))
        err (-1, "could not allocate enough memory");
    if (!stralloc_cats (&f[0], "\n"))
        err (-1, "could not allocate enough memory");
    put (f[0].s, f[0].len);

    if (buffer_flush (&bnew) == -1)
        err (-1, "could not write to `%s'", fnnew);
    if (fsync (fdnew) == -1)
        err (-1, "could not write to `%s'", fnnew);
    if (close (fdnew) == -1)
        err (-1, "could not write to `%s'", fnnew); /* NFS dorks */

    if (rename (fnnew, fn) == -1)
        err (-1, "could not move `%s' to `%s'", fnnew, fn);

    return 0;
}
Beispiel #19
0
int main(int argc, char **argv) {
  unsigned int i, done;
  char *x;

  progname =*argv;
  for (i =str_len(*argv); i; --i) if ((*argv)[i -1] == '/') break;
  *argv +=i;
  optprogname =progname =*argv;
  service =argv;
  services =1;
  lsb =(str_diff(progname, "sv"));
  if ((x =env_get("SVDIR"))) varservice =x;
  if ((x =env_get("SVWAIT"))) scan_ulong(x, &wait);
  while ((i =getopt(argc, (const char* const*)argv, "w:vV")) != opteof) {
    switch(i) {
    case 'w': scan_ulong(optarg, &wait);
    case 'v': verbose =1; break;
    case 'V': strerr_warn1(VERSION, 0);
    case '?': usage();
    }
  }
  argv +=optind; argc -=optind;
  if (!(action =*argv++)) usage(); --argc;
  if (!lsb) { service =argv; services =argc; }
  if (!*service) usage();

  taia_now(&tnow); tstart =tnow;
  if ((curdir =open_read(".")) == -1)
    fatal("unable to open current directory");

  act =&control; acts ="s";
  if (verbose) cbk =&check;
  switch (*action) {
  case 'x': case 'e':
    acts ="x"; break;
  case 'X': case 'E':
    acts ="x"; kll =1; cbk =&check; break;
  case 'D':
    acts ="d"; kll =1; cbk =&check; break;
  case 'T':
    acts ="tc"; kll =1; cbk =&check; break;
  case 'c':
    if (!str_diff(action, "check")) { act =0; acts ="C"; cbk =&check; break; }
  case 'u': case 'd': case 'o': case 't': case 'p': case 'h':
  case 'a': case 'i': case 'k': case 'q': case '1': case '2':
    action[1] =0; acts =action; break;
  case 's':
    if (!str_diff(action, "shutdown")) { acts ="x"; cbk =&check; break; }
    if (!str_diff(action, "start")) { acts ="u"; cbk =&check; break; }
    if (!str_diff(action, "stop")) { acts ="d"; cbk =&check; break; }
    if (lsb && str_diff(action, "status")) usage();
    act =&status; cbk =0; break;
  case 'r':
    if (!str_diff(action, "restart")) { acts ="tcu"; cbk =&check; break; }
    usage();
  case 'f':
    if (!str_diff(action, "force-reload"))
      { acts ="tc"; kll =1; cbk =&check; break; }
    if (!str_diff(action, "force-restart"))
      { acts ="tcu"; kll =1; cbk =&check; break; }
    if (!str_diff(action, "force-shutdown"))
      { acts ="x"; kll =1; cbk =&check; break; }
    if (!str_diff(action, "force-stop"))
      { acts ="d"; kll =1; cbk =&check; break; }
  default:
    usage();
  }

  servicex =service;
  for (i =0; i < services; ++i) {
    if ((**service != '/') && (**service != '.') && **service &&
        ((*service)[str_len(*service) -1] != '/')) {
      if ((chdir(varservice) == -1) || (chdir(*service) == -1)) {
        fail("unable to change to service directory");
        *service =0;
      }
    }
    else
      if (chdir(*service) == -1) {
        fail("unable to change to service directory");
        *service =0;
      }
    if (*service) if (act && (act(acts) == -1)) *service =0;
    if (fchdir(curdir) == -1) fatal("unable to change to original directory");
    service++;
  }

  if (*cbk)
    for (;;) {
      taia_sub(&tdiff, &tnow, &tstart);
      service =servicex; done =1;
      for (i =0; i < services; ++i, ++service) {
        if (!*service) continue;
        if ((**service != '/') && (**service != '.')) {
          if ((chdir(varservice) == -1) || (chdir(*service) == -1)) {
            fail("unable to change to service directory");
            *service =0;
          }
        }
        else
          if (chdir(*service) == -1) {
            fail("unable to change to service directory");
            *service =0;
          }
        if (*service) { if (cbk(acts) != 0) *service =0; else done =0; }
        if (*service && taia_approx(&tdiff) > wait) {
          kll ? outs(KILL) : outs(TIMEOUT);
          if (svstatus_get() > 0) { svstatus_print(*service); ++rc; }
          flush("\n");
          if (kll) control("k");
          *service =0;
        }
        if (fchdir(curdir) == -1)
          fatal("unable to change to original directory");
      }
      if (done) break;
      usleep(420000);
      taia_now(&tnow);
    }
  return(rc > 99 ? 99 : rc);
}
Beispiel #20
0
int sv_main(int argc, char **argv)
{
	unsigned opt;
	unsigned i, want_exit;
	char *x;

	for (i = strlen(*argv); i; --i)
		if ((*argv)[i-1] == '/')
			break;
	*argv += i;
	service = argv;
	services = 1;
	if ((x = getenv("SVDIR"))) varservice = x;
	if ((x = getenv("SVWAIT"))) waitsec = xatoul(x);
	/* TODO: V can be handled internally by getopt_ulflags */
	opt = getopt32(argc, argv, "w:vV", &x);
	if (opt & 1) waitsec = xatoul(x);
	if (opt & 2) verbose = 1;
	if (opt & 4) usage();
	if (!(action = *argv++)) usage();
	--argc;
	service = argv; services = argc;
	if (!*service) usage();

	taia_now(&tnow); tstart = tnow;
	if ((curdir = open_read(".")) == -1)
		fatal_cannot("open current directory");

	act = &control; acts = "s";
	if (verbose) cbk = &check;
	switch (*action) {
	case 'x': case 'e':
		acts = "x"; break;
	case 'X': case 'E':
		acts = "x"; kll = 1; cbk = &check; break;
	case 'D':
		acts = "d"; kll = 1; cbk = &check; break;
	case 'T':
		acts = "tc"; kll = 1; cbk = &check; break;
	case 'c':
		if (!str_diff(action, "check")) {
			act = 0;
			acts = "c";
			cbk = &check;
			break;
		}
	case 'u': case 'd': case 'o': case 't': case 'p': case 'h':
	case 'a': case 'i': case 'k': case 'q': case '1': case '2':
		action[1] = 0; acts = action; break;
	case 's':
		if (!str_diff(action, "shutdown")) {
			acts = "x";
			cbk = &check;
			break;
		}
		if (!str_diff(action, "start")) {
			acts = "u";
			cbk = &check;
			break;
		}
		if (!str_diff(action, "stop")) {
			acts = "d";
			cbk = &check;
			break;
		}
		act = &status; cbk = 0; break;
	case 'r':
		if (!str_diff(action, "restart")) {
			acts = "tcu";
			cbk = &check;
			break;
		}
		usage();
	case 'f':
		if (!str_diff(action, "force-reload"))
			{ acts = "tc"; kll = 1; cbk = &check; break; }
		if (!str_diff(action, "force-restart"))
			{ acts = "tcu"; kll = 1; cbk = &check; break; }
		if (!str_diff(action, "force-shutdown"))
			{ acts = "x"; kll = 1; cbk = &check; break; }
		if (!str_diff(action, "force-stop"))
			{ acts = "d"; kll = 1; cbk = &check; break; }
	default:
		usage();
	}

	servicex = service;
	for (i = 0; i < services; ++i) {
		if ((**service != '/') && (**service != '.')) {
			if ((chdir(varservice) == -1) || (chdir(*service) == -1)) {
				fail("cannot change to service directory");
				*service = 0;
			}
		} else if (chdir(*service) == -1) {
			fail("cannot change to service directory");
			*service = 0;
		}
		if (*service) if (act && (act(acts) == -1)) *service = 0;
		if (fchdir(curdir) == -1) fatal_cannot("change to original directory");
		service++;
	}

	if (*cbk)
		for (;;) {
			taia_sub(&tdiff, &tnow, &tstart);
			service = servicex; want_exit = 1;
			for (i = 0; i < services; ++i, ++service) {
				if (!*service) continue;
				if ((**service != '/') && (**service != '.')) {
					if ((chdir(varservice) == -1) || (chdir(*service) == -1)) {
						fail("cannot change to service directory");
						*service = 0;
					}
				} else if (chdir(*service) == -1) {
					fail("cannot change to service directory");
					*service = 0;
				}
				if (*service) { if (cbk(acts) != 0) *service = 0; else want_exit = 0; }
				if (*service && taia_approx(&tdiff) > waitsec) {
					kll ? printf(KILL) : printf(TIMEOUT);
					if (svstatus_get() > 0) { svstatus_print(*service); ++rc; }
					puts(""); /* will also flush the output */
					if (kll) control("k");
					*service = 0;
				}
				if (fchdir(curdir) == -1)
					fatal_cannot("change to original directory");
			}
			if (want_exit) break;
			usleep(420000);
			taia_now(&tnow);
		}
	return rc > 99 ? 99 : rc;
}