Example #1
0
/* evaluate case conditional construct (3.9.4.3)
 * ----------------------------------------------------------------------- */
int eval_case(struct eval *e, struct ncase *ncase) {
  union node *node;
  union node *pat;
  int ret = 0;
  stralloc word;
  stralloc pattern;
  stralloc_init(&word);
  stralloc_init(&pattern);

  if(ncase->word)
    expand_catsa(ncase->word, &word, X_NOSPLIT);
  
  stralloc_nul(&word);

  for(node = ncase->list; node; node = node->list.next) {
    for(pat = node->ncasenode.pats; pat; pat = pat->list.next) {
      expand_catsa(pat, &pattern, X_NOSPLIT);
      stralloc_nul(&pattern);
      
      if(shell_fnmatch(pattern.s, pattern.len, word.s, word.len, SH_FNM_PERIOD) == 0) {
        ret = eval_tree(e, node->ncasenode.cmds, E_LIST);
        goto end;
      }
      
      stralloc_zero(&pattern);
    }
  }

end:  
  stralloc_free(&pattern);
  stralloc_free(&word);

  return ret;
}
Example #2
0
int main(int argc, const char ** argv )
{
    cmd = (char*) *argv++; --argc;
    section = (char*) *argv++; --argc;
    manual = (char*) *argv++; --argc;
    
    stralloc tempCMD1 = {0};
    tempCMD1 = generateSearchCMD( manual,tempCMD1);
    
    int fd[2];
    pipe(fd);
    int status;
    
    pid_t child;
    
    if ( (child = fork() ) < 0 )
    {
        return 0;
    }
    else if( child == 0 )
    {
        dup2(fd[1],1);
        close(fd[0]);
	close(fd[1]);
        system(tempCMD1.s);
        stralloc_free(&tempCMD1);
        exit(255);
    }
    else {
        stralloc tempCMD2 = {0};
        ssize_t nbytes;
        char buff[64];
       

        close(fd[1]);
        while(( nbytes = read(fd[0] , buff , sizeof buff )) > 0 )
        {
            stralloc_catb( &tempCMD2 , buff , nbytes );
        };
        
        stralloc temp = {0};
        stralloc_copys( &temp , cmdCAT );
        stralloc_cat( &temp , &tempCMD2 );
        
        char *t = temp.s;
	
        printManual(t);        
        
        stralloc_free(&tempCMD2);
        stralloc_free(&temp);
    }
     
    close(fd[0]);
    close(fd[1]);
    wait(&status);
    return 0;
}
Example #3
0
/* evaluates backquoted command list, while writing stdout to a stralloc 
 */
union node*
expand_command(struct nargcmd *cmd, union node **nptr, struct vartab* varstack, int flags) {
  union node *n = *nptr;
  stralloc sa;
  stralloc_init(&sa);

  /* make the output buffer write to the stralloc */
  buffer_tosa(buffer_1, &sa); 

  /* evaluate the command tree in a subshell */
  /*sh_push(&sh);
  sh_subshell(cmd->list, E_EXIT);
  sh_pop(&sh);*/

  /* split trailing newlines */
  while(sa.len && sa.s[sa.len - 1] == '\n')
    sa.len--;

  /* expand the output of the command 
   
     FIXME: we could do this much nicer by doing an
            expand_write() which is set as buffer op 
            on the output fd.
   
            so we won't have to alloc all the stuff twice!
   */
  n = expand_cat(sa.s, sa.len, nptr, varstack, flags);
  stralloc_free(&sa);

  return n;
}
Example #4
0
char *get_name(FILE *f)
{
	int c;
	stralloc name = {0};
	char *strp;
	char d;

	/* consume leading whitespace */
	do {
		c = fgetc(f);	
	} while(isspace(c));
	ungetc(c, f);

	/* append non-whitespace chars */
	while (1) {
		c = fgetc(f);
		if (c < 0 || isspace(c)) {
			stralloc_0(&name);
			strp = strdup(name.s);
			stralloc_free(&name);
			return strp;
		}
		d = c;
		stralloc_append(&name, &d);
	}
}
int absolutepath (stralloc *sa, const char *path)
{
  int r = 1 ;
  if (!path) r = stralloc_copys(sa, "/") ;
  else if (path[0] == '/') r = stralloc_copys(sa, path) ;
  else
  {
    unsigned int n = 0 ;
    for (;;)
    {
      n += 1024 ;
      if (!stralloc_ready(sa, n))
      {
        r = 0 ;
        break ;
      }
      if (getcwd(sa->s, n)) break ;
      if (errno != ENOMEM)
      {
        r = 0 ;
        break ;
      }
    }
    sa->len = str_len(sa->s) ;
    if (r) r = stralloc_append(sa, "/") && stralloc_cats(sa, path) ;
    if (!r) stralloc_free(sa) ;
  }
  return r ? stralloc_0(sa) : 0 ;
}
Example #6
0
/* process all here-docs
 * 
 * nredir->data is set to the next here-doc redirection by redir_addhere()
 * after processing it is set to the content of the here-doc (an narg node)
 * ----------------------------------------------------------------------- */
void redir_source(void) {
  struct parser p;
  stralloc delim;
  int r;
    
  parse_init(&p, P_HERE);
      
  stralloc_init(&delim);
  
  for(; redir_list; redir_list = &redir_list->data->nredir) {
    /* expand the delimiter */
    stralloc_init(&delim);
    expand_catsa((union node *)redir_list, &delim, 0);
    
    /* when any character of the delimiter has been escaped
       then treat the whole here-doc as non-expanded word */
    r = parse_here(&p, &delim, (redir_list->list->nargstr.flag & S_ESCAPED));
    
    tree_free(redir_list->list);
    redir_list->list = parse_getarg(&p);
    
    /* free expanded delimiters */
    stralloc_free(&delim);
  }
}
Example #7
0
static void ftrigio_deepfree (ftrigio_t *p)
{
  ftrig1_free(&p->trig) ;
  stralloc_free(&p->sa) ;
  regfree(&p->re) ;
  *p = ftrigio_zero ;
}
void genalloc_deepfree_size (genalloc *g, freefunc_t_ref f, unsigned int size)
{
  unsigned int len = g->len / size ;
  register unsigned int i = 0 ;
  for (; i < len ; i++) (*f)(g->s + i * size) ;
  stralloc_free(g) ;
}
Example #9
0
static void uniq (genalloc *lines)
{
  unsigned int len = genalloc_len(stralloc, lines) ;
  register stralloc *s = genalloc_s(stralloc, lines) ;
  register unsigned int i = 1 ;
  for (; i < len ; i++)
    if (!sacmp(s+i-1, s+i)) stralloc_free(s+i-1) ;
}
Example #10
0
static void cleanup (void)
{
  int e = errno ;
  satmp.s[llen] = 0 ;
  unlink(satmp.s) ;
  satmp.s[llen] = ':' ;
  rm_rf_in_tmp(&satmp, 0) ;
  stralloc_free(&satmp) ;
  errno = e ;
}
Example #11
0
int write_fifodir(char *dirname, stralloc *sa, void (*oaw_func)(char *, stralloc *))
{
  DIR *dir = NULL;
  stralloc name = {0};
  struct dirent *x = NULL;
  static struct stat st;

  /* read directory */
  dir = opendir(dirname);
  if(dir == NULL)
    {
      strerr_warn3("can't opendir() ", dirname, ": ", &strerr_sys);
      return -1;
    }

  while (x = readdir(dir))
    {
      if(x == NULL)
	{
	  strerr_warn3("can't readdir() ", dirname, ": ", &strerr_sys);
	  if(name.a) 
	    stralloc_free(&name);
	  return -1;
	}

      /* Ignore everything starting with a . */
      if(x->d_name[0] != '.')
	{ 
	  stralloc_copys(&name, dirname);
	  stralloc_cats(&name, "/");
	  stralloc_cats(&name, x->d_name);
	  stralloc_0(&name);

	  if(stat(name.s, &st) == -1)
	    {
	      strerr_warn2("can't stat ", name.s, &strerr_sys);
	    }

	  if(S_ISFIFO(st.st_mode))
	    {
	      oaw_func(name.s, sa);
	    }
	  else
	    {
	      buffer_puts(buffer_2, "ddnsd: warning: ");
	      buffer_puts(buffer_2, name.s);
	      buffer_puts(buffer_2, " is no fifo, ignoring\n");
	      buffer_flush(buffer_2);
	    }
	}
    }
  closedir(dir);  

  return 0;
}
Example #12
0
int string_quote (stralloc *sa, char const *s, unsigned int len)
{
  unsigned int base = sa->len ;
  int wasnull = !sa->s ;
  if (!stralloc_catb(sa, "\"", 1)) return 0 ;
  if (!string_quote_nodelim(sa, s, len) || !stralloc_catb(sa, "\"", 1))
  {
    if (wasnull) stralloc_free(sa) ; else sa->len = base ;
    return 0 ;
  }
  return 1 ;
}
int s6dns_analyze_record_strings (genwrite_t *gp, s6dns_message_rr_t const *rr, char const *packet, unsigned int packetlen, unsigned int start)
{
  stralloc sa = STRALLOC_ZERO ;
  char buf[rr->rdlength] ;
  unsigned int pos = start ;
  register int r = s6dns_message_get_strings(buf, rr->rdlength, packet, packetlen, &pos) ;
  if (r < 0) return 0 ;
  if (rr->rdlength != pos - start) return (errno = EPROTO, 0) ;
  if (!string_quote(&sa, buf, r)) return 0 ;
  r = (*gp->put)(gp->target, sa.s, sa.len) >= 0 ;
  stralloc_free(&sa) ;
  return r ;
}
Example #14
0
static void
free_service (aa_service *s)
{
    genalloc_free (int, &s->needs);
    genalloc_free (int, &s->wants);
    genalloc_free (int, &s->after);
    aa_service_status_free (&s->st);
    if (s->fd_out > 0)
        close_fd (s->fd_out);
    if (s->fd_progress > 0)
        close_fd (s->fd_progress);
    stralloc_free (&s->sa_out);
}
int ftrig1_make (ftrig1 *f, char const *path)
{
  ftrig1 ff = FTRIG1_ZERO ;
  unsigned int pathlen = str_len(path) ;
  int e = 0 ;
  char tmp[pathlen + 46 + FTRIG1_PREFIXLEN] ;
  
  byte_copy(tmp, pathlen, path) ;
  tmp[pathlen] = '/' ; tmp[pathlen+1] = '.' ;
  byte_copy(tmp + pathlen + 2, FTRIG1_PREFIXLEN, FTRIG1_PREFIX) ;
  tmp[pathlen + 2 + FTRIG1_PREFIXLEN] = ':' ;
  if (!timestamp(tmp + pathlen + 3 + FTRIG1_PREFIXLEN)) return 0 ;
  tmp[pathlen + 28 + FTRIG1_PREFIXLEN] = ':' ;
  if (random_name(tmp + pathlen + 29 + FTRIG1_PREFIXLEN, 16) < 16) return 0 ;
  tmp[pathlen + 45 + FTRIG1_PREFIXLEN] = 0 ;
  
  {
    mode_t m = umask(0) ;
    if (fifo_make(tmp, S_IRUSR|S_IWUSR|S_IWGRP|S_IWOTH) == -1)
    {
      umask(m) ;
      return 0 ;
    }
    umask(m) ;
  }

  if (!stralloc_catb(&ff.name, tmp, pathlen+1)) { e = errno ; goto err0 ; }
  if (!stralloc_catb(&ff.name, tmp + pathlen + 2, FTRIG1_PREFIXLEN + 44))
  {
    e = errno ; goto err1 ;
  }
  ff.fd = open_read(tmp) ;
  if (ff.fd == -1) { e = errno ; goto err1 ; }
  ff.fdw = open_write(tmp) ;
  if (ff.fdw == -1) { e = errno ; goto err2 ; }
  if (rename(tmp, ff.name.s) == -1) goto err3 ;
  *f = ff ;
  return 1 ;

 err3:
  e = errno ;
  fd_close(ff.fdw) ;
 err2:
  fd_close(ff.fd) ;
 err1:
  stralloc_free(&ff.name) ;
 err0:
  unlink(tmp) ;
  errno = e ;
  return 0 ;
}
static int makeuniquename (stralloc *sa, char const *path, char const *magic)
{
  unsigned int base = sa->len ;
  int wasnull = !sa->s ;
  if (!stralloc_cats(sa, path)) return 0 ;
  if (!stralloc_cats(sa, magic)) goto err ;
  if (random_sauniquename(sa, 8) == -1) goto err ;
  if (!stralloc_0(sa)) goto err ;
  return 1 ;

err:
  if (wasnull) stralloc_free(sa) ; else sa->len = base ;
  return 0 ;
}
void unixmessage_receiver_free (unixmessage_receiver_t *b)
{
  register unsigned int h = b->maindata.len ;
  b->fd = -1 ;
  stralloc_free(&b->maindata) ;
  h = h != b->mainlen || b->auxdata.len != b->auxlen || cbuffer_len(&b->auxb) ;
  if (h)
  {
    register unsigned int n = b->auxdata.len / sizeof(int) ;
    while (n--) fd_close(((int *)b->auxdata.s)[n]) ;
  }
  stralloc_free(&b->auxdata) ;
  if (h)
  {
    register unsigned int n = cbuffer_len(&b->auxb) / sizeof(int) ;
    if (n)
    {
      int fds[n] ;
      cbuffer_get(&b->auxb, (char *)fds, n * sizeof(int)) ;
      while (n--) fd_close(fds[n]) ;
    }
  }
}
Example #18
0
void el_substandrun_str (stralloc *src, unsigned int srcbase, char const *const *envp, exlsn_t const *info)
{
    stralloc dst = STRALLOC_ZERO ;
    register int r = el_substitute(&dst, src->s + srcbase, src->len, info->vars.s, info->values.s, genalloc_s(elsubst_t const, &info->data), genalloc_len(elsubst_t const, &info->data)) ;
    if (r < 0) strerr_diefu1sys(111, "el_substitute") ;
    if (!r) _exit(0) ;
    stralloc_free(src) ;
    {
        char const *v[r + 1] ;
        if (!env_make(v, r, dst.s, dst.len)) strerr_diefu1sys(111, "env_make") ;
        v[r] = 0 ;
        pathexec_r(v, envp, env_len(envp), info->modifs.s, info->modifs.len) ;
    }
    strerr_dieexec(111, dst.s) ;
}
int mkdir_unique (stralloc *sa, char const *fn, unsigned int mode)
{
  unsigned int base = sa->len ;
  int wasnull = !sa->s ;
  if (!stralloc_cats(sa, fn)) return 0 ;
  if (!stralloc_cats(sa, "/mkdir_unique")) goto fail ;
  if (random_sauniquename(sa, 8) < 0) goto fail ;
  if (!stralloc_0(sa)) goto fail ;
  if (mkdir(sa->s + base, mode) < 0) goto fail ;
  sa->len-- ;
  return 1 ;

 fail:
  if (wasnull) stralloc_free(sa) ;
  else sa->len = base ;
  return 0 ;
}
Example #20
0
int s6rc_sanitize_dir (stralloc *sa, char const *fn, unsigned int *dirlen)
{
  int wasnull = !sa->s ;
  unsigned int base = sa->len ;
  unsigned int fnlen = str_len(fn) ;
  unsigned int ddirlen ;
  if (!sadirname(sa, fn, fnlen)) return 0 ;
  if (sa->len != base + 1 || sa->s[base] != '/')
    if (!stralloc_catb(sa, "/", 1)) goto err ;
  ddirlen = sa->len ;
  if (!sabasename(sa, fn, fnlen)) goto err ;
  *dirlen = ddirlen ;
  return 1 ;

 err:
  if (wasnull) stralloc_free(sa) ;
  else sa->len = base ;
  return 0 ;
}
Example #21
0
/* evaluates backquoted command list, while writing stdout to a stralloc 
 * ----------------------------------------------------------------------- */
union node *expand_command(struct nargcmd *cmd, union node **nptr, int flags) {
  union node *n = *nptr;
  struct vartab vars;
  struct fd fd;
  struct fdstack fdst;
  struct env sh;
  stralloc sa;
  stralloc_init(&sa);

  /* do this in a new i/o context so we can redirect stdout */
  vartab_push(&vars);
  
  /* make the output buffer write to the stralloc */
  fdstack_push(&fdst);
  fd_push(&fd, STDOUT_FILENO, FD_WRITE);
  fd_subst(&fd, &sa);

  /* evaluate the command tree in a subshell */
  sh_push(&sh);
  sh_subshell(cmd->list, E_EXIT);
  sh_pop(&sh);

  fdstack_pop(&fdst);

  vartab_pop(&vars);

  /* split trailing newlines */
  while(sa.len && sa.s[sa.len - 1] == '\n')
    sa.len--;

  /* expand the output of the command 
   
     FIXME: we could do this much nicer by doing an
            expand_write() which is set as buffer op 
            on the output fd.
   
            so we won't have to alloc all the stuff twice!
   */
  n = expand_cat(sa.s, sa.len, nptr, flags);
  stralloc_free(&sa);

  return n;
}
void unixmessage_sender_free (unixmessage_sender_t *b)
{
  unsigned int n = genalloc_len(int, &b->fds) ;
  if (n)
  {
    unsigned int i = genalloc_s(diuint, &b->offsets)[b->head].right ;
    for (; i < n ; i++)
    {
      register int fd = genalloc_s(int, &b->fds)[i] ;
      if (fd < 0) fd_close(-(fd+1)) ;
#ifdef SKALIBS_HASANCILAUTOCLOSE
      else fd_close(fd) ;
#endif
    }
  }
  genalloc_free(diuint, &b->offsets) ;
  genalloc_free(int, &b->fds) ;
  stralloc_free(&b->data) ;
  *b = unixmessage_sender_zero ;
}
Example #23
0
/* set a variable
 * ----------------------------------------------------------------------- */
struct var *var_set(char *v, int flags) {
  struct var *var;
  
  /* find/create the variable */
  if((var = var_create(v, flags)) == NULL)
    return var;
  
  /* free if it was a previously allocated string */
  if(var->sa.a)
    stralloc_free(&var->sa);
    
  stralloc_init(&var->sa);
  
  var->sa.s = v;
  var->sa.len = str_len(v);
  var->offset = var->len;
  
  if(var->len < var->sa.len)
    var->offset++;
  
  return var;
}
Example #24
0
char *whirlpool_digest(const char *str)
{
	whirlpool_t ctx;
	stralloc_t sa;
	char *buf;
	uint8_t digest[DIGESTBYTES];
	int i;

	whirlpool_init(&ctx);
	whirlpool_add(&ctx, (const unsigned char * const) str, str_len(str)*8);
	whirlpool_finalize(&ctx, digest);

	stralloc_init(&sa);

	for (i = 0; i < DIGESTBYTES; i++)
		stralloc_catf(&sa, "%02X", digest[i]);

	buf = stralloc_finalize(&sa);

	stralloc_free(&sa);

	return buf;
}
Example #25
0
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;
}
Example #26
0
union node*
expand_param(struct nargparam* param, union node** nptr, struct vartab* varstack, char* argv[], int exitcode, int flags) {
  union node* n = *nptr;
  stralloc value;
  char* str = NULL;
  const char *v = NULL;
  unsigned long argc, vlen = 0;

        for(argc = 0; argv[argc]; ++argc)
          ;
  stralloc_init(&value);

  /* treat special arguments */
  if(param->flag & S_SPECIAL) {
    switch(param->flag & S_SPECIAL) {
      /* $# substitution */
      case S_ARGC: {
        stralloc_catulong0(&value, argc, 0);
        break;
      }

      /* $* substitution */
      case S_ARGV: {
        char** s;

        for(s = argv; *s;) {
          stralloc_cats(&n->narg.stra, *s);
          if(*++s) stralloc_catc(&n->narg.stra, ' ');
        }
        break;
      }

      /* $@ substitution */
      case S_ARGVS: {
        unsigned int i = 0;

        while(i < argc) {
          param->flag &= ~S_SPECIAL;
          param->flag |= S_ARG;
          param->numb = 1 + i;

          n = expand_param(param, nptr, varstack, argv, exitcode,flags);

          if(++i < argc) nptr = &n->list.next;
        }

        return n;
      }

        /* $? substitution */
      case S_EXITCODE: {
        stralloc_catulong0(&value, exitcode, 0);
        break;
      }

      /* $- substitution */
      case S_FLAGS: break;

      /* $! substitution */
      case S_BGEXCODE:
        break;

        /* $[0-9] arg subst */
      case S_ARG: {
        if(param->numb == 0) {
        /*  stralloc_cats(&value, sh_argv0); */
        } else if(param->numb - 1 < argc) {
          stralloc_cats(&value, argv[param->numb - 1]);
        }
        break;
      }

        /* $$ arg subst */
      case S_PID: {
        stralloc_catulong0(&value, getpid(), 0);
        break;
      }
    }

    /* special parameters are always set */
    if(value.len) {
      stralloc_nul(&value);
      v = value.s;
    }

    vlen = value.len;
  }
  /* ..and variable substitutions */
  else {
    size_t offset;

    /* look for the variable.
       if the S_NULL flag is set and we have a var which is null
       set v to NULL */
    if((v = var_get(varstack, param->name, &offset))) {
      if(v[offset] == '\0' && (param->flag & S_NULL)) {
        v = NULL;
        vlen = 0;
      } else {
        v = &v[offset];
        vlen = str_len(v);
      }
    }
  }

  /* check for S_STRLEN substitution */
  if(param->flag & S_STRLEN) {
    char lstr[FMT_ULONG];

    n = expand_cat(lstr, fmt_ulong(lstr, vlen), nptr, varstack, flags);

    stralloc_free(&value);

    return n;
  }

  str = str_ndup(v, vlen);

  /* otherwise expand the apropriate variable/word subst */
  switch(param->flag & S_VAR) {
    /* return word if parameter unset (or null) */
    case S_DEFAULT: {
      if(v) n = expand_cat(v, vlen, nptr, varstack, flags);
      /* unset, substitute */
      else
        n = expand_arg(&param->word->narg, nptr, varstack, argv, exitcode, flags);
      break;
    }
    /* if parameter unset (or null) then expand word to it
       and substitute paramter */
    case S_ASGNDEF: {
      if(v)
        n = expand_cat(v, vlen, nptr, varstack, flags);
      else {
        n = expand_arg(&param->word->narg, nptr, varstack, argv, exitcode, flags | X_NOSPLIT);
        var_setvsa(param->name, /* BUG */ &n->narg.stra, V_DEFAULT);
      }
      break;
    }

    /* indicate error if null or unset */
    case S_ERRNULL: {
      if(v)
        n = expand_cat(v, vlen, nptr, varstack, flags);
      else {
        union node* tmpnode = NULL;

        n = expand_arg(&param->word->narg, &tmpnode, varstack, argv, exitcode, flags);
       errmsg_warn((n && n->narg.stra.s) ? n->narg.stra.s : "parameter null or not set", 0);
        if(tmpnode) tree_free(tmpnode);
      }
      break;
    }

      /* if parameter unset (or null) then substitute null,
         otherwise substitute word */
    case S_ALTERNAT: {
      if(v) n = expand_arg(&param->word->narg, nptr, varstack, argv, exitcode, flags);
      break;

        /* remove smallest matching suffix */
      case S_RSSFX: {
        int i;
        stralloc sa;

        if(v && vlen) {
          expand_copysa(param->word, &sa, varstack, argv, exitcode, 0);
          stralloc_nul(&sa);

          for(i = vlen - 1; i >= 0; i--)
            if(fnmatch(sa.s, str + i, FNM_PERIOD) == 0) break;

          n = expand_cat(v, (i < 0 ? vlen : i), nptr, varstack, flags);
        }
        break;
      }
    }

      /* remove largest matching suffix */
    case S_RLSFX: {
      unsigned int i;
      stralloc sa;

      if(v && vlen) {
        expand_copysa(param->word, &sa, varstack, argv, exitcode, 0);
        stralloc_nul(&sa);

        for(i = 0; i <= vlen; i++)
          if(fnmatch(sa.s,  str + i,  FNM_PERIOD) == 0) break;

        n = expand_cat(v, (i > vlen ? vlen : i), nptr, varstack, flags);
      }

      break;
    }

      /* remove smallest matching prefix */
    case S_RSPFX: {
      unsigned int i;
      stralloc sa;

      if(v && vlen) {
        expand_copysa(param->word, &sa, varstack, argv, exitcode, 0);
        stralloc_nul(&sa);

        for(i = 1; i <= vlen; i++) {
          str_copyn(str, v, i);
          if(fnmatch(sa.s, (char*)v, FNM_PERIOD) == 0) break;
        }

        if(i > vlen) i = 0;

        n = expand_cat(v + i, vlen - i, nptr, varstack, flags);
        str_copy(str, v);
      }
      break;
    }

      /* remove largest matching prefix */
    case S_RLPFX: {
      unsigned int i;
      stralloc sa;

      if(v && vlen) {
        expand_copysa(param->word, &sa, varstack, argv, exitcode, 0);
        stralloc_nul(&sa);

        for(i = vlen; i > 0; i--) {
          str_copyn(str, v, i);
          if(fnmatch(sa.s, (char*)v, FNM_PERIOD) == 0) break;
        }

        if(i == 0) i = vlen;

        n = expand_cat(v + i, vlen - i, nptr, varstack, flags);
        str_copy(str, v);
      }
      break;
    }
  }

  free(str);

  stralloc_free(&value);
  return n;
}
Example #27
0
int main (int argc, char const *const *argv)
{
  unsigned int count = 0 ;
  flags_t flags = FLAGS_ZERO ;
  PROG = "s6-grep" ;
  {
    subgetopt_t l = SUBGETOPT_ZERO ;
    for (;;)
    {
      register int opt = subgetopt_r(argc, argv, "Fcnqv", &l) ;
      if (opt == -1) break ;
      switch (opt)
      {
        case 'F': flags.fixed = 1 ; break ;
        case 'c': flags.count = 1 ; break ;
        case 'n': flags.num = 1 ; break ;
        case 'q': flags.quiet = 1 ; break ;
        case 'v': flags.not = 1 ; break ;
        default : strerr_dieusage(100, USAGE) ;
      }
    }
    argc -= l.ind ; argv += l.ind ;
  }
  if (!argc) strerr_dieusage(100, USAGE) ;
  {
    stralloc line = STRALLOC_ZERO ;
    struct sredfa *re = 0 ;
    unsigned int num = 0 ;
    unsigned int arglen = 0 ;
    if (flags.fixed) arglen = str_len(argv[0]) ;
    else
    {
      re = sredfa_new() ;
      if (!re) strerr_diefu1sys(111, "sredfa_new") ;
      if (!sredfa_from_regexp(re, argv[0]))
        strerr_diefu1sys(111, "compile regular expression") ;
    }

    for (;;)
    {
      register int r ;
      line.len = 0 ;
      r = skagetln(buffer_0f1, &line, '\n') ;
      if (!r) break ;
      if (r < 0)
      {
        if ((errno != EPIPE) || !stralloc_catb(&line, "\n", 1))
          strerr_diefu1sys(111, "read from stdin") ;
      }
      num++ ;
      r = flags.fixed ?
        (str_strn(line.s, line.len-1, argv[0], arglen) < line.len - 1) :
        sredfa_match(re, line.s, line.len-1) ;
      if (r < 0)
      {
        int e = errno ;
        buffer_flush(buffer_1) ;
        errno = e ;
        strerr_diefu1sys(111, "match line against pattern") ;
      }
      if (r ^ flags.not)
      {
        count++ ;
        if (!flags.quiet && !flags.count)
        {
          if (flags.num)
          {
            char fmt[UINT_FMT] ;
            register unsigned int n = uint_fmt(fmt, num) ;
            fmt[n++] = ':' ;
            if (buffer_putalign(buffer_1, fmt, n) < (int)n)
              strerr_diefu1sys(111, "write to stdout") ;
          }
          if (buffer_putalign(buffer_1, line.s, line.len) < (int)line.len)
            strerr_diefu1sys(111, "write to stdout") ;
        }
      }
    }
    if (flags.quiet) return !count ;
    stralloc_free(&line) ;
    if (!flags.fixed) sredfa_delete(re) ;
  }
  if (flags.count)
  {
    char fmt[UINT_FMT] ;
    register unsigned int n = uint_fmt(fmt, count) ;
    fmt[n++] = '\n' ;
    if (buffer_putalign(buffer_1, fmt, n) < (int)n)
      strerr_diefu1sys(111, "write to stdout") ;
  }
  return !count ;
}
Example #28
0
int
main (int argc, char * const argv[])
{
    PROG = "aa-start";
    const char *path_repo = "/run/services";
    const char *path_list = NULL;
    int i;

    aa_secs_timeout = DEFAULT_TIMEOUT_SECS;
    for (;;)
    {
        struct option longopts[] = {
            { "double-output",      no_argument,        NULL,   'D' },
            { "help",               no_argument,        NULL,   'h' },
            { "listdir",            required_argument,  NULL,   'l' },
            { "dry-list",           no_argument,        NULL,   'n' },
            { "repodir",            required_argument,  NULL,   'r' },
            { "timeout",            required_argument,  NULL,   't' },
            { "version",            no_argument,        NULL,   'V' },
            { "verbose",            no_argument,        NULL,   'v' },
            { "no-wants",           no_argument,        NULL,   'W' },
            { NULL, 0, 0, 0 }
        };
        int c;

        c = getopt_long (argc, argv, "Dhl:nr:t:VvW", longopts, NULL);
        if (c == -1)
            break;
        switch (c)
        {
            case 'D':
                aa_set_double_output (1);
                break;

            case 'h':
                dieusage (0);

            case 'l':
                unslash (optarg);
                path_list = optarg;
                break;

            case 'n':
                if (mode & AA_MODE_IS_DRY)
                    mode |= AA_MODE_IS_DRY_FULL;
                else
                    mode |= AA_MODE_IS_DRY;
                break;

            case 'r':
                unslash (optarg);
                path_repo = optarg;
                break;

            case 't':
                if (!uint0_scan (optarg, &aa_secs_timeout))
                    aa_strerr_diefu2sys (ERR_IO, "set default timeout to ", optarg);
                break;

            case 'V':
                aa_die_version ();

            case 'v':
                verbose = 1;
                break;

            case 'W':
                no_wants = 1;
                break;

            default:
                dieusage (1);
        }
    }
    argc -= optind;
    argv += optind;

    cols = get_cols (1);
    is_utf8 = is_locale_utf8 ();

    if (!path_list && argc < 1)
        dieusage (1);

    if (aa_init_repo (path_repo, (mode & AA_MODE_IS_DRY) ? AA_REPO_READ : AA_REPO_WRITE) < 0)
        aa_strerr_diefu2sys (ERR_IO, "init repository ", path_repo);

    if (path_list)
    {
        stralloc sa = STRALLOC_ZERO;
        int r;

        if (*path_list != '/' && *path_list != '.')
            stralloc_cats (&sa, LISTDIR_PREFIX);
        stralloc_catb (&sa, path_list, strlen (path_list) + 1);
        r = aa_scan_dir (&sa, 1, it_start, NULL);
        stralloc_free (&sa);
        if (r < 0)
            aa_strerr_diefu3sys (-r, "read list directory ",
                    (*path_list != '/' && *path_list != '.') ? LISTDIR_PREFIX : path_list,
                    (*path_list != '/' && *path_list != '.') ? path_list : "");
    }

    tain_now_g ();

    for (i = 0; i < argc; ++i)
        if (str_equal (argv[i], "-"))
        {
            if (process_names_from_stdin ((names_cb) add_service, NULL) < 0)
                aa_strerr_diefu1sys (ERR_IO, "process names from stdin");
        }
        else
            add_service (argv[i], NULL);

    mainloop (mode, scan_cb);

    if (!(mode & AA_MODE_IS_DRY))
    {
        aa_bs_noflush (AA_OUT, "\n");
        put_title (1, PROG, "Completed.", 1);
        aa_show_stat_nb (nb_already, "Already up", ANSI_HIGHLIGHT_GREEN_ON);
        aa_show_stat_nb (nb_done, "Started", ANSI_HIGHLIGHT_GREEN_ON);
        show_stat_service_names (&ga_timedout, "Timed out", ANSI_HIGHLIGHT_RED_ON);
        show_stat_service_names (&ga_failed, "Failed", ANSI_HIGHLIGHT_RED_ON);
        show_stat_service_names (&ga_depend, "Dependency failed", ANSI_HIGHLIGHT_RED_ON);
        aa_show_stat_names (aa_names.s, &ga_io, "I/O error", ANSI_HIGHLIGHT_RED_ON);
        aa_show_stat_names (aa_names.s, &ga_unknown, "Unknown", ANSI_HIGHLIGHT_RED_ON);
        aa_show_stat_names (aa_names.s, &ga_skipped, "Skipped", ANSI_HIGHLIGHT_YELLOW_ON);
    }

    genalloc_free (int, &ga_timedout);
    genalloc_free (int, &ga_failed);
    genalloc_free (int, &ga_depend);
    genalloc_free (size_t, &ga_io);
    genalloc_free (size_t, &ga_unknown);
    genalloc_free (size_t, &ga_skipped);
    genalloc_free (pid_t, &ga_pid);
    genalloc_free (int, &aa_tmp_list);
    genalloc_free (int, &aa_main_list);
    stralloc_free (&aa_names);
    genalloc_deepfree (struct progress, &ga_progress, free_progress);
    aa_free_services (close_fd);
    genalloc_free (iopause_fd, &ga_iop);
    return rc;
}
Example #29
0
int
main (int argc, char * const argv[])
{
    PROG = "aa-kill";

    for (;;)
    {
        struct option longopts[] = {
            { "double-output",      no_argument,        NULL,   'D' },
            { "help",               no_argument,        NULL,   'h' },
            { "kill",               no_argument,        NULL,   'k' },
            { "skip-at",            no_argument,        NULL,   's' },
            { "term",               no_argument,        NULL,   't' },
            { "hup",                no_argument,        NULL,   'u' },
            { "version",            no_argument,        NULL,   'V' },
            { NULL, 0, 0, 0 }
        };
        int c;

        c = getopt_long (argc, argv, "DhkstuV", longopts, NULL);
        if (c == -1)
            break;
        switch (c)
        {
            case 'D':
                aa_set_double_output (1);
                break;

            case 'h':
                dieusage (0);

            case 'k':
                send.kill = 1;
                break;

            case 's':
                send.skip_at = 1;
                break;

            case 't':
                send.term = 1;
                break;

            case 'u':
                send.hup = 1;
                break;

            case 'V':
                aa_die_version ();

            default:
                dieusage (1);
        }
    }
    argc -= optind;
    argv += optind;

    if (argc > 0 || (!send.hup && !send.term && !send.kill))
        dieusage (1);

    if (send.skip_at)
    {
        stralloc sa = STRALLOC_ZERO;
        unsigned int u;

        u = (unsigned int) getpid ();
        ownpid[uint_fmt (ownpid, u)] = '\0';

        if (!stralloc_catb (&sa, "/proc", sizeof ("/proc")))
            aa_strerr_diefu1sys (1, "stralloc_catb");
        if (aa_scan_dir (&sa, 0, it_kill, &sa) < 0)
            aa_strerr_diefu1sys (1, "scan /proc");
        stralloc_free (&sa);
    }
    else
    {
        if (send.hup)
        {
            sig_ignore (SIGHUP);
            _kill (-1, SIGHUP);
        }

        if (send.term)
        {
            sig_ignore (SIGTERM);
            _kill (-1, SIGTERM);
            _kill (-1, SIGCONT);
        }

        if (send.kill)
            _kill (-1, SIGKILL);
    }

    return 0;
}
Example #30
0
/* 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;
}