Beispiel #1
0
/* binary operator expression */
Expr *
binaryExpr(int op, Expr *arg1, Expr *arg2)
{
    Expr	*x;
    Expr	*arg = arg1;
    int		sts = 0;

    /* error guard */
    if (arg1 == NULL) return NULL;

    if (arg1 != NULL && arg2 != NULL) {
	if (op != CND_MATCH && op != CND_NOMATCH) {
	    /* check domains */
	    sts = checkDoms(arg1, arg2);

	    /* decide primary argument for inheritance of Expr attributes */
	    arg = primary(arg1, arg2);
	}
	else {
	    regex_t	*pat;

	    pat = alloc(sizeof(*pat));
	    if (regcomp(pat, (char *)arg2->ring, REG_EXTENDED|REG_NOSUB) != 0) {
		/* bad pattern */
		fprintf(stderr, "illegal regular expression \"%s\"\n", (char *)arg2->ring);
		free(pat);
		return NULL;
	    }
#if PCP_DEBUG
	    if (pmDebug & DBG_TRACE_APPL1) {
		fprintf(stderr, "binaryExpr: regex=\"%s\" handle=" PRINTF_P_PFX "%p\n", (char *)arg2->ring, pat);
	    }
#endif
	    /*
	     * change operand from the string form of the pattern to the
	     * compiled regex
	     */
	    free(arg2->ring);
	    arg2->tspan = 1;
	    arg2->ring = pat;
	    arg2->sem = SEM_REGEX;
	    sts = 1;
	}
    }

    /* construct expression node */
    x = newExpr(op, arg1, arg2, arg->hdom, arg->e_idom, arg->tdom, abs(arg->tdom), arg->sem);
#if PCP_DEBUG
    if (sts == 0 && (pmDebug & DBG_TRACE_APPL1)) {
	fprintf(stderr, "binaryExpr: checkDoms(" PRINTF_P_PFX "%p, " PRINTF_P_PFX "%p) failed ...\n", arg1, arg2);
	__dumpTree(1, x);
    }
#endif
    newRingBfr(x);
    findEval(x);

    /* evaluate constant expression now */
    evalConst(x);

    return x;
}
Beispiel #2
0
/* event parsing loop freely stolen from Zarf's glk example code */
void debug_monitor() {
    char commandbuf[256], lastcommand[256];
    char *cx, *cmd;
    int gotline, len, monitor, match;
    event_t ev;
    char *parser = "^([cfghlnoqsx])( +([0-9a-f]+))?";
    // char *parser = "\\([cghlnqsx]\\)\\( 0\\)?";
    char *matched;
    regex_t preg;
    size_t nmatch = 4;
    regmatch_t pmatch[4];
    
    monitor = TRUE;
    while(monitor) {
        glk_put_string("\nmonitor>");
        // if (cmd)
        //     strncpy(lastcommand, cmd, 256);
        glk_request_line_event(mainwin, commandbuf, 255, 0);
        gotline = FALSE;
        while (!gotline) {
            glk_select(&ev);
            if (ev.type == evtype_LineInput)
                gotline = TRUE;
        }

        len = ev.val1;
        commandbuf[len] = '\0';

        for (cx = commandbuf; *cx; cx++) { 
            *cx = glk_char_to_lower(*cx);
        }
        
        /* strip whitespace */
        for (cx = commandbuf; *cx == ' '; cx++) { };
        cmd = cx;
        for (cx = commandbuf+len-1; cx >= cmd && *cx == ' '; cx--) { };
        *(cx+1) = '\0';
        
        if (*cmd == '\0') {
            monitor = FALSE;
            continue;
        }
        
        if ((match = regcomp(&preg, parser, REG_EXTENDED | REG_ICASE)) != 0) {
            fatal_error("Bad regex\n");
        }

        if ((match = regexec(&preg, cmd, nmatch, pmatch, 0)) != 0) {
            glk_put_string("pardon? - try 'h' for help\n");
        } else {
            if(match_command("c")) {
                monitor = FALSE;
            } else if (match_command("f")) {
                match_args_and_call(debug_print_callstack, 0xffff)
            } else if (match_command("g")) {
                match_args_and_call(debug_print_global, 0xff)
            } else if (match_command("h")) {
                debug_print_help();
            } else if (match_command("l")) {
                match_args_and_call(debug_print_local, 0xff)
            } else if (match_command("n")) {
                monitor = FALSE;                
            } else if (match_command("o")) {
                match_args_and_call(debug_print_object, 1);         
            } else if (match_command("x")) {
                match_args_and_call(debug_print_memory, 0xdeadbeef)
            } else if (match_command("")) {
                match_args_and_call(debug_print_zstring, 0)
            } else if (match_command("q")) {
                fatal_error("Debugger terminated game.");
            } else if (match_command("s")) {
                debug_print_stack();
            } else if (match_command("x")) {
                match_args_and_call(debug_print_memory, 0xdeadbeef)
            }
        }
        regfree(&preg);
    }
}
Beispiel #3
0
int cfg_load(unsigned char *filename, unsigned int level)
{
    FILE *f;
    unsigned char readbuf[BUF_SIZE], *p;
#define MAX_CFG_TOKENS 16
    unsigned char *tokenv[MAX_CFG_TOKENS];
    unsigned int tokenc, i;
    unsigned int curline;
    unsigned int bool_val;

    curline = 0;

    if (level == 0)
    {
        if (cfg_f == NULL || fseek(cfg_f, 0, SEEK_SET) != 0)
        {
            if ((f = fopen(filename, "r")) == NULL) {
                fprintf(stderr, "Unable to open config file '%s': %s\n", filename, strerror(errno));
                return -1;
            }
            cfg_f = f;
        } else
        {
            f = cfg_f;
        }
    } else
    {
        if ((f = fopen(filename, "r")) == NULL) {
            fprintf(stderr, "Unable to open config file '%s': %s\n", filename, strerror(errno));
            return -1;
        }
    }
    while (fgets(readbuf, sizeof(readbuf) - 1, f) != NULL)
    {
        curline ++;
        if ((p = strpbrk(readbuf, "\n\r")) != NULL) *p = 0;
        tokenc = 0;
        p = readbuf;
        while (*p == ' ' || *p == '\t') p ++;
        if (*p == '#') continue;
        bool_val = 1;
        DEBUGF("cfg line %s:%u [%s]", filename, curline, p);
        if (*p == 0) continue;
        p = strtok(p, " \t");
        while (tokenc < MAX_CFG_TOKENS && p != NULL && *p != '#')
        {
            /* handle !foo / no foo */
            if (tokenc == 0)
            {
                if (*p == '!') {
                    bool_val = 0;
                    p ++;
                }
                else if (strcasecmp(p, "no") == 0) {
                    bool_val = 0;
                    p = NULL;
                }
            }
            if (p != NULL && *p != 0) tokenv[tokenc ++] = strdup(p);
            p = strtok(NULL, " \t");
        }
        if (tokenc == 0) continue;
        for (i = 0; hypercube_config_tokens[i].key != NULL; i ++) if (strcasecmp(hypercube_config_tokens[i].key, tokenv[0]) == 0) break;
        if (hypercube_config_tokens[i].key == NULL) {
            CFG_ERR_HDR();
            fprintf(stderr, "Unknown key '%s'\n", tokenv[0]);
            return -1;
        }
        if (hypercube_config_tokens[i].type == CFG_BOOL)
        {
            if (tokenc != 1) {
                CFG_ERR_HDR();
                fprintf(stderr, "Invalid number of arguments (expected [!]%s)\n", tokenv[0]);
                return -1;
            }
            DEBUGF("bool value '%s' = %u", hypercube_config_tokens[i].key, bool_val);
            *(int *)hypercube_config_tokens[i].val = bool_val;
        } else if (bool_val != 0) switch (hypercube_config_tokens[i].type)
            {
            case CFG_NONE:
                break;
            case CFG_INT:
            {
                if (tokenc != 2) {
                    CFG_ERR_HDR();
                    fprintf(stderr, "Invalid number of arguments (expected %s <number>)\n", tokenv[0]);
                    return -1;
                }
                *(int *)hypercube_config_tokens[i].val = atoi(tokenv[1]);
                break;
            }
            case CFG_STR:
            {
                unsigned char **dest;

                if (tokenc != 2) {
                    CFG_ERR_HDR();
                    fprintf(stderr, "Invalid number of arguments (expected %s <string>)\n", tokenv[0]);
                    return -1;
                }
                dest = hypercube_config_tokens[i].val;
                *dest = strdup(tokenv[1]);
                break;
            }
            case CFG_TABLE:
            {
                akbuf_table *tbl;
                unsigned char **dest;

                if (tokenc != 3) {
                    CFG_ERR_HDR();
                    fprintf(stderr, "Invalid number of arguments (expected %s <key> <value>)\n", tokenv[0]);
                    return -1;
                }
                dest = hypercube_config_tokens[i].val;
                tbl = (akbuf_table *)*dest;
                akbuf_table_entry_add_str(cfg_ctx, tbl, tokenv[1], tokenv[2]);
                break;
            }
            case CFG_REGEX_TABLE:
            {
                akbuf_table *tbl;
                unsigned char **dest;
                akbuf *compbuf, *valbuf;
                int ret;

                if (tokenc != 2 && tokenc != 3) {
                    CFG_ERR_HDR();
                    fprintf(stderr, "Invalid number of arguments (expected %s <regex> [arg])\n", tokenv[0]);
                    return -1;
                }
                compbuf = akbuf_init(cfg_ctx, sizeof(regex_t));
                if ((ret = regcomp((regex_t *)akbuf_data(compbuf), tokenv[1], REG_EXTENDED)) != 0)
                {
                    unsigned char errbuf[BUF_SIZE];

                    regerror(ret, (regex_t *)akbuf_data(compbuf), errbuf, sizeof(errbuf));
                    fprintf(stderr, "Parsing of regex '%s' failed: %s\n", tokenv[1], errbuf);
                    return -1;
                }
                akbuf_set_idx(compbuf, sizeof(regex_t));
                valbuf = akbuf_init(cfg_ctx, 0);
                akbuf_strcpy(valbuf, tokenv[2]);
                dest = hypercube_config_tokens[i].val;
                tbl = (akbuf_table *)*dest;
                akbuf_table_entry_add_buf(cfg_ctx, tbl, compbuf, valbuf);
                akbuf_free(cfg_ctx, valbuf);
                break;
            }
            case CFG_INADDR:
            {
                struct in_addr *addr;

                if (tokenc != 2) {
                    CFG_ERR_HDR();
                    fprintf(stderr, "Invalid number of arguments (expected %s <IP address>)\n", tokenv[0]);
                    return -1;
                }
                addr = hypercube_config_tokens[i].val;
                if ((addr->s_addr = inet_addr(tokenv[1])) == -1) {
                    CFG_ERR_HDR();
                    fprintf(stderr, "Invalid IP address '%s'\n", tokenv[1]);
                    return -1;
                }
                break;
            }
            case CFG_FUNC:
            {
                int (*func)();
                func = hypercube_config_tokens[i].val;
                if (func != NULL) if (func(filename, curline, tokenv, tokenc) != 0) return -1;
                break;
            }
            }
    }
    return 0;
}
Beispiel #4
0
/* Main function */
int main(int argc, char *argv[]){

  /* Variable declaration . */
  char *regex_str_par;
  char *regex_str_vri;
  char *regex_str_vre;
  char *regex_str_var;
  char *regex_str_set;
  char *regex_str_equ;
  char *regex_str_oth;
  char *regex_str_loo;
  char *regex_str_sum;
  char *regex_str_rep;
  char *regex_str_com;
  char *regex_str_irr;

  char *regex_str_loo_sub;
  char *regex_str_sum_sol;
  char *regex_str_sum_mod;
  char *regex_str_rep_sub;
  char *regex_str_rep_sub2;
  char *regex_str_par_sub;
  char *regex_str_vri_sub;
  char *regex_str_vre_sub;

  char *regex_str_emp;
  char *regex_str_tmp1;
  char *regex_str_tmp2;

  char line[PAGEW];
  FILE *fin;
  FILE *fout;

  regex_t preg_par;
  regex_t preg_vri;
  regex_t preg_vre;
  regex_t preg_var;
  regex_t preg_set;
  regex_t preg_equ;
  regex_t preg_oth;
  regex_t preg_loo;
  regex_t preg_sum;
  regex_t preg_rep;
  regex_t preg_com;
  regex_t preg_irr;

  regex_t preg_loo_sub;
  regex_t preg_sum_sol;
  regex_t preg_sum_mod;
  regex_t preg_rep_sub;
  regex_t preg_rep_sub2;
  regex_t preg_par_sub;
  regex_t preg_vri_sub;
  regex_t preg_vre_sub;

  regex_t preg_emp;
  regex_t preg_tmp1;
  regex_t preg_tmp2;

  regmatch_t pmatch[10];

  int linum, count, flag;

  linum=0;
  count=0;
  flag=1;
  
  /*   Regular expressions. */
  regex_str_par
    = "^----[ ]+[0-9]+ PARAMETER[ ]+([^ \n\r]+)[ ]+([^\n\r]*)";
  regex_str_par_sub
    = "^[ ]+PARAMETER[ ]+([^ \n\r]+)[ ]+([^\n\r]*)";
  regex_str_vri = "^----[ ]+[0-9]+ VARIABLE[ ]+([^ \n\r]+)[ ]+([^\n\r]*)";
  regex_str_vri_sub = "^[ \t]+VARIABLE[ ]+([^ \n\r]+)[ ]+([^\n\r]*)";
  regex_str_vre = "^----[ ]+[0-9]+ EQUATION[ ]+([^ \n\r]+)[ ]+([^\n\r]*)";
  regex_str_vre_sub = "^[ \t]+EQUATION[ ]+([^ \n\r]+)[ ]+([^\n\r]*)";
  regex_str_set = "^----[ ]+[0-9]+ SET[ ]+([^ \n\r]+)[ ]*([^\n\r]*)";
  regex_str_var = "^----[ ]+VAR[ ]+([^ \n\r]+)[ ]*([^\n\r]*)";
  regex_str_equ = "^----[ ]+EQU[ ]+([^ \n\r]+)[ ]*([^\n\r]*)";
  regex_str_oth = "^----[ ]+[0-9]+[ ]+([^\n\r]*)";
  regex_str_loo = "^[ ]+L O O P S[ ]+([^ \n\r]+)[ ]+([^\n\r]+)";
  regex_str_loo_sub = "^[ ]+([^ \n\r]+)[ ]+([^\n\r]+)";
  regex_str_rep = "REPORT SUMMARY :[ ]+([0-9])";
  regex_str_rep_sub = "^[ ]+([0-9]+)[ ]+[^\n\r]+";
  regex_str_rep_sub2 = "^[ ]+([A-Za-z]+)[ ]+";
  regex_str_sum = "^               S O L V E      S U M M A R Y";
  regex_str_sum_sol = " SOLVER STATUS[ ]+([0-9]*)";
  regex_str_sum_mod = " MODEL STATUS[ ]+([0-9]*)";
  regex_str_com = "^----[ ]+[0-9]+[ ]+com:[ ]*([^\n\r]*)";
  regex_str_irr = "^[A-Za-z0-9\n\r\f]+";
  regex_str_emp = "^[\n\r\f\r]";
  regex_str_tmp1 = "^[^ *-]+";
  regex_str_tmp2 = "^----[ ]+";

  /* Determin from where to read */
  if (argc!=3 && argc!=2){
    usage();
    exit(1);
  }
  if((fin=fopen(argv[1],"r"))==NULL){
    printf("Cannot open the input file.\n");
    exit(1);
  }
  if(argc==3 && (fout=fopen(argv[2],"w"))==NULL){
    printf("Cannot open the output file.\n");
    exit(1);
  }
  if (argc == 2) {
    fout=stdout;
  }
  
  /* Compile regular expression */
  regcomp(&preg_par, regex_str_par, REG_EXTENDED);
  regcomp(&preg_vri, regex_str_vri, REG_EXTENDED);
  regcomp(&preg_vre, regex_str_vre, REG_EXTENDED);
  regcomp(&preg_var, regex_str_var, REG_EXTENDED);
  regcomp(&preg_set, regex_str_set, REG_EXTENDED);
  regcomp(&preg_equ, regex_str_equ, REG_EXTENDED);
  regcomp(&preg_oth, regex_str_oth, REG_EXTENDED);
  regcomp(&preg_loo, regex_str_loo, REG_EXTENDED);
  regcomp(&preg_sum, regex_str_sum, REG_EXTENDED);
  regcomp(&preg_rep, regex_str_rep, REG_EXTENDED);
  regcomp(&preg_com, regex_str_com, REG_EXTENDED);
  regcomp(&preg_irr, regex_str_irr, REG_EXTENDED);
  regcomp(&preg_loo_sub, regex_str_loo_sub, REG_EXTENDED);
  regcomp(&preg_sum_sol, regex_str_sum_sol, REG_EXTENDED);
  regcomp(&preg_sum_mod, regex_str_sum_mod, REG_EXTENDED);
  regcomp(&preg_rep_sub, regex_str_rep_sub, REG_EXTENDED);
  regcomp(&preg_rep_sub2, regex_str_rep_sub2, REG_EXTENDED);
  regcomp(&preg_par_sub, regex_str_par_sub, REG_EXTENDED);
  regcomp(&preg_vri_sub, regex_str_vri_sub, REG_EXTENDED);
  regcomp(&preg_vre_sub, regex_str_vre_sub, REG_EXTENDED);
  regcomp(&preg_emp, regex_str_emp, REG_EXTENDED);
  regcomp(&preg_tmp1, regex_str_tmp1, REG_EXTENDED);
  regcomp(&preg_tmp2, regex_str_tmp2, REG_EXTENDED);
  
  fprintf(fout,"(setq gams-ol-alist-temp-alist '(\n");
  
  /* */
  while(NULL != fgets(line, PAGEW, fin)){
    linum++;
    if((0 == regexec(&preg_irr, line, 1, pmatch, 0))
       || (0 == regexec(&preg_tmp1, line, 1, pmatch, 0))) {
      /*       Do nothing */
      ;
    } else if(0 == regexec(&preg_tmp2, line, 9, pmatch, REG_NOTEOL)) {
      /*       Matched ^---- */
      if(0 == regexec(&preg_var, line, 9, pmatch, REG_NOTEOL)){
	count++;
	fprintf(fout,"(%i %i \"VAR\" \"%.*s\" \"%.*s\")\n",
		count, linum, pmatch[1].rm_eo-pmatch[1].rm_so, &line[pmatch[1].rm_so],
		pmatch[2].rm_eo-pmatch[2].rm_so, &line[pmatch[2].rm_so]);

      } else if(0 == regexec(&preg_equ, line, 9, pmatch, REG_NOTEOL)){
	count++;
	fprintf(fout,"(%i %i \"EQU\" \"%.*s\" \"%.*s\")\n",
		count, linum, pmatch[1].rm_eo-pmatch[1].rm_so, &line[pmatch[1].rm_so],
		pmatch[2].rm_eo-pmatch[2].rm_so, &line[pmatch[2].rm_so]);

      } else if(0 == regexec(&preg_par, line, 9, pmatch, REG_NOTEOL)){
	count++;
	fprintf(fout,"(%i %i \"PAR\" \"%.*s\" \"%.*s\")\n",
		count, linum, pmatch[1].rm_eo-pmatch[1].rm_so, &line[pmatch[1].rm_so],
		pmatch[2].rm_eo-pmatch[2].rm_so, &line[pmatch[2].rm_so]);
	/* sub process */
	while(flag == 1) {
	  fgets(line, PAGEW, fin);
	  linum++;
	  if(0 == regexec(&preg_par_sub, line, 9, pmatch, REG_NOTEOL)){
	    count++;
	    fprintf(fout,"(%i %i \"PAR\" \"%.*s\" \"%.*s\")\n",
		    count, linum, pmatch[1].rm_eo-pmatch[1].rm_so, &line[pmatch[1].rm_so],
		    pmatch[2].rm_eo-pmatch[2].rm_so, &line[pmatch[2].rm_so]);
	  } else if(0 != regexec(&preg_emp, line, 0, pmatch, 0)) {
	    ;
	  } else { flag = 0; }
	}
	flag = 1;

      } else if(0 == regexec(&preg_vri, line, 9, pmatch, REG_NOTEOL)){
	count++;
	fprintf(fout,"(%i %i \"VRI\" \"%.*s\" \"%.*s\")\n",
		count, linum, pmatch[1].rm_eo-pmatch[1].rm_so, &line[pmatch[1].rm_so],
		pmatch[2].rm_eo-pmatch[2].rm_so, &line[pmatch[2].rm_so]);
	/* sub process */
	while(flag == 1) {
	  fgets(line, PAGEW, fin);
	  linum++;
	  if(0 == regexec(&preg_vri_sub, line, 9, pmatch, REG_NOTEOL)){
	    count++;
	    fprintf(fout,"(%i %i \"VRI\" \"%.*s\" \"%.*s\")\n",
		    count, linum, pmatch[1].rm_eo-pmatch[1].rm_so, &line[pmatch[1].rm_so],
		    pmatch[2].rm_eo-pmatch[2].rm_so, &line[pmatch[2].rm_so]);
	  } else if(0 != regexec(&preg_emp, line, 0, pmatch, 0)) {
	    ;
	  } else { flag = 0; }
	}
	flag = 1;

      } else if(0 == regexec(&preg_vre, line, 9, pmatch, REG_NOTEOL)){
	count++;
	fprintf(fout,"(%i %i \"VRI\" \"%.*s\" \"%.*s\")\n",
		count, linum, pmatch[1].rm_eo-pmatch[1].rm_so, &line[pmatch[1].rm_so],
		pmatch[2].rm_eo-pmatch[2].rm_so, &line[pmatch[2].rm_so]);
	/* sub process */
	while(flag == 1) {
	  fgets(line, PAGEW, fin);
	  linum++;
	  if(0 == regexec(&preg_vre_sub, line, 9, pmatch, REG_NOTEOL)){
	    count++;
	    fprintf(fout,"(%i %i \"VRI\" \"%.*s\" \"%.*s\")\n",
		    count, linum, pmatch[1].rm_eo-pmatch[1].rm_so, &line[pmatch[1].rm_so],
		    pmatch[2].rm_eo-pmatch[2].rm_so, &line[pmatch[2].rm_so]);
	  } else if(0 != regexec(&preg_emp, line, 0, pmatch, 0)) {
	    ;
	  } else { flag = 0; }
	}
	flag = 1;

      } else if(0 == regexec(&preg_set, line, 9, pmatch, REG_NOTEOL)){
	count++;
	fprintf(fout,"(%i %i \"SET\" \"%.*s\" \"%.*s\")\n",
		count, linum, pmatch[1].rm_eo-pmatch[1].rm_so, &line[pmatch[1].rm_so],
		pmatch[2].rm_eo-pmatch[2].rm_so, &line[pmatch[2].rm_so]);

      } else if(0 == regexec(&preg_com, line, 4, pmatch, 0)){
	count++;
	fprintf(fout,"(%i %i \"COM\" \"%.*s\")\n",
		count, linum, pmatch[1].rm_eo-pmatch[1].rm_so, &line[pmatch[1].rm_so]);

      } else if(0 == regexec(&preg_oth, line, 9, pmatch, REG_NOTEOL)){
	count++;
	fprintf(fout,"(%i %i \"OTH\" \"\" \"%.*s\")\n",
		count, linum, pmatch[1].rm_eo-pmatch[1].rm_so, &line[pmatch[1].rm_so]);
      }

    } else if(0 == regexec(&preg_loo, line, 9, pmatch, REG_NOTEOL)){
      count++;
      fprintf(fout,"(%i %i \"LOO\" \"%.*s\" \"%.*s\")\n",
	      count, linum, pmatch[1].rm_eo-pmatch[1].rm_so, &line[pmatch[1].rm_so],
	      pmatch[2].rm_eo-pmatch[2].rm_so, &line[pmatch[2].rm_so]);
      /* sub process */
      while(flag == 1) {
	fgets(line, PAGEW, fin);
	linum++;
	if(0 == regexec(&preg_loo_sub, line, 9, pmatch, REG_NOTEOL)){
	  count++;
	  fprintf(fout,"(%i %i \"LOO\" \"%.*s\" \"%.*s\")\n",
		  count, linum, pmatch[1].rm_eo-pmatch[1].rm_so, &line[pmatch[1].rm_so],
		  pmatch[2].rm_eo-pmatch[2].rm_so, &line[pmatch[2].rm_so]);
	} else { flag = 0; }
      }
      flag = 1;

    } else if(0 == regexec(&preg_sum, line, 0, pmatch, 0)){
      count++;
      fprintf(fout,"(%i %i ", count, linum);
      while(flag == 1) {
	fgets(line, PAGEW, fin);
	linum++;
	if(0 == regexec(&preg_sum_sol, line, 9, pmatch, REG_NOTEOL)){
	  fprintf(fout,"\"SUM\" \"SOLVE SUMMARY\" \"SOLVER STATUS = %.*s, ",
		  pmatch[1].rm_eo-pmatch[1].rm_so, &line[pmatch[1].rm_so]);
	  
	} else if(0 == regexec(&preg_sum_mod, line, 9, pmatch, REG_NOTEOL)){
	  fprintf(fout,"MODEL STATUS = %.*s\")\n",
		  pmatch[1].rm_eo-pmatch[1].rm_so, &line[pmatch[1].rm_so]);
	  flag = 0;
	}
      }
      flag = 1;

    } else if(0 == regexec(&preg_rep, line, 9, pmatch, REG_NOTEOL)){
      count++;
      fprintf(fout,"(%i %i \"SUM\" \"REPORT SUMMARY\" \"[%.*s",
	      count,linum,pmatch[1].rm_eo-pmatch[1].rm_so, &line[pmatch[1].rm_so]);
      while(flag == 1) {
	fgets(line, PAGEW, fin);
	linum++;
	if(0 == regexec(&preg_rep_sub, line, 9, pmatch, REG_NOTEOL)){
	  fprintf(fout,", %.*s",
		  pmatch[1].rm_eo-pmatch[1].rm_so, &line[pmatch[1].rm_so]);
	} else if (0 == regexec(&preg_rep_sub2, line, 0, pmatch, REG_NOTEOL)) {
	  ;
	} else {
	  fprintf(fout,"]\")\n");
	  flag = 0;
	}
      }
      flag = 1;
    }
  }
  fprintf(fout,"))\n");
  fclose(fin);
  fclose(fout);
  return (0);
}
Beispiel #5
0
/******************************************************************************
 * This function attempts to parse genomic coordinates from the
 * current sequence header. If successful it will return the 
 * chromosome name, name length and starting position.
 *
 * There are two supported formats.
 * The first is the UCSC/fastaFromBed style: name:start-stop[(+|-)][_id]
 * e.g., ">chr1:1000-1010(-)_xyz"
 * The second is the Galaxy "Fetch sequence" style: genome_name_start_stop_strand
 * where strand is +|-.
 * e.g., ">mm9_chr18_75759530_7575972>mm9_chr18_75759530_757597299"
 *
 * Returns TRUE if it was able to find genomic coordinates, FALSE otherwise.
 *****************************************************************************/
BOOLEAN_T parse_genomic_coordinates_helper(
  char*  header,	  // sequence name 
  char** chr_name_ptr,    // chromosome name ((chr[^:]))
  size_t * chr_name_len_ptr,// number of characters in chromosome name
  int *  start_ptr,	  // start position of sequence (chr:(\d+)-)
  int *  end_ptr	  // end position of sequence (chr:\d+-(\d+))
) {

  #define NUM_SUBMATCHES 6
  #define ERROR_MESSAGE_SIZE 100
  #define BUFFER_SIZE 512

  static BOOLEAN_T first_time = TRUE;
  static regex_t ucsc_header_regex;
  static regex_t galaxy_header_regex;
  static regmatch_t matches[NUM_SUBMATCHES];

  char error_message[ERROR_MESSAGE_SIZE];
  int status = 0;

  if (first_time == TRUE) {

    // Initialize regular express for extracting chromsome coordinates;

    status = regcomp(
      &ucsc_header_regex, 
      "([^[:space:]:]+):([[:digit:]]+)-([[:digit:]]+)(\\([+-]\\))?(_[^[:space:]]+)?", 
      REG_EXTENDED | REG_ICASE | REG_NEWLINE
    );

    if (status != 0) {
      regerror(status, &ucsc_header_regex, error_message, ERROR_MESSAGE_SIZE);
      die(
        "Error while intitializing regular expression\n"
        "for parsing UCSC style genome coordinates from FASTA header: %s\n", 
        error_message
      );
    }

    status = regcomp(
      &galaxy_header_regex, 
      "([^[:space:]_]+_[^[:space:]_]+)_([[:digit:]]+)_([[:digit:]]+)(_[+-])?", 
      REG_EXTENDED | REG_ICASE | REG_NEWLINE
    );

    if (status != 0) {
      regerror(status, &galaxy_header_regex, error_message, ERROR_MESSAGE_SIZE);
      die(
        "Error while intitializing regular expression\n"
        "for parsing Galaxy style genome coordinates from FASTA header: %s\n", 
        error_message
      );
    }

    first_time = FALSE;
  }

  BOOLEAN_T found_coordinates = FALSE;

  // Try UCSC style first
  status = regexec(&ucsc_header_regex, header, NUM_SUBMATCHES, matches, 0);
  if(status && status != REG_NOMATCH ){
    regerror(status, &ucsc_header_regex, error_message, 100);
    die("Error trying to parse UCSC style genome coordinates from sequence header: %s\n"
        "error message is %s\n",
        header, 
        error_message
    );
  }

  if (status == REG_NOMATCH) {
    // UCSC didn't work, try GALAXY style
    status = regexec(&galaxy_header_regex, header, NUM_SUBMATCHES, matches, 0);
    if(status && status != REG_NOMATCH ){
      regerror(status, &ucsc_header_regex, error_message, 100);
      die("Error trying to parse GALAXY style genome coordinates from sequence header: %s\n"
          "error message is %s\n",
          header, 
          error_message
      );
    }
  }

  if(!status) {

    // The sequence header contains genomic coordinates
    found_coordinates = TRUE;

    // Get chromosome name (required)
    char buffer[BUFFER_SIZE];
    int chr_name_len = matches[1].rm_eo - matches[1].rm_so;
    strncpy(buffer, header + matches[1].rm_so, chr_name_len);
    buffer[chr_name_len] = 0;
    char *chr_name = strdup(buffer);
    if (chr_name == NULL) {
      die("Unable to allocate memory while parsing sequence header.\n");
    }
    *chr_name_ptr = chr_name;
    *chr_name_len_ptr = chr_name_len;

    // Get chromosome start position (required)
    size_t pos_len = matches[2].rm_eo - matches[2].rm_so;
    strncpy(buffer, header + matches[2].rm_so, pos_len);
    buffer[pos_len] = 0;
    *start_ptr = atol(buffer) - 1;

    // Get chromosome end position (required)
    pos_len = matches[3].rm_eo - matches[3].rm_so;
    strncpy(buffer, header + matches[3].rm_so, pos_len);
    buffer[pos_len] = 0;
    *end_ptr = atol(buffer) - 1;

    // Get the strand (optional)
    if (matches[4].rm_so >= 0) {
      pos_len = matches[4].rm_eo - matches[4].rm_so;
      char strand = *(header + matches[4].rm_so + 1);
    }

    // Get the id tag (optional)
    if (matches[5].rm_so >= 0) {
      pos_len = matches[5].rm_eo - matches[5].rm_so;
      strncpy(buffer, header + matches[5].rm_so + 1, pos_len);
      buffer[pos_len] = 0;
    }

  }

  return found_coordinates;

  #undef NUM_SUBMATCHES
  #undef ERROR_MESSAGE_SIZE
  #undef BUFFER_SIZE
}
Beispiel #6
0
void add_to_patterns(char *pattern)
{
  char first[MAX_BUFF];
  char second[MAX_BUFF];
  char type[MAX_BUFF];
  char accel[MAX_BUFF];
  regex_t compiled;
  struct REGEX_pattern rpattern;
  int abort_type = 0;
  int parenthesis;
  int stored;
  
  /*  The regex_flags that we use are:
      REG_EXTENDED 
      REG_NOSUB 
      REG_ICASE; */

  int regex_flags = REG_NOSUB;
  
  rpattern.type = NORMAL;
  rpattern.case_sensitive = 1;
  
  stored = sscanf(pattern, "%s %s %s %s", type, first, second, accel);
  
  
  if((stored < 2) || (stored > 4)) {
    log(LOG_ERROR, 
	"unable to get a pair of patterns in add_to_patterns() "
	"for [%s]\n", pattern);
    dodo_mode = 1;
    return;
  }
  
  if(stored == 2)
    strcpy(second, "");
  
  if(strcmp(type, "abort") == 0) {
    rpattern.type = ABORT;
    abort_type = 1;
  }
  
  if(strcmp(type, "regexi") == 0) {
    regex_flags |= REG_ICASE;
    rpattern.case_sensitive = 0;
  }

  
  if(!abort_type) {

    parenthesis = count_parenthesis (first);

    if (parenthesis < 0) {
      
      /* The function returned an invalid result, 
	 indicating an invalid string */
      
      log (LOG_ERROR, "count_parenthesis() returned "
	   "left count did not match right count for line: [%s]\n",
	   pattern);
      dodo_mode = 1;
      return;

    } else if (parenthesis > 0) {

      regex_flags |= REG_EXTENDED;
      rpattern.type = EXTENDED;
      regex_flags ^= REG_NOSUB;

    }
  }
  
  
  if(regcomp(&compiled, first, regex_flags)) {
    log(LOG_ERROR, "Invalid regex [%s] in pattern file\n", first);
    dodo_mode = 1;
    return;
  }
  
  
  rpattern.cpattern = compiled;

  
  rpattern.pattern = (char *)malloc(sizeof(char) * (strlen(first) +1));
  if(rpattern.pattern == NULL) {
    log(LOG_ERROR, "unable to allocate memory in add_to_patterns()\n");
    dodo_mode = 1;
    return;
  }
  strcpy(rpattern.pattern, first);
  

  rpattern.replacement = (char *)malloc(sizeof(char) * (strlen(second) +1));
  if(rpattern.replacement == NULL) {
    log(LOG_ERROR, "unable to allocate memory in add_to_patterns()\n");
    dodo_mode = 1;
    return;
  }
  strcpy(rpattern.replacement, second);
  

  /* use accelerator string if it exists */
  if(stored == 4) {

    rpattern.has_accel = 1;
    rpattern.accel = get_accel(accel, &rpattern.accel_type, 
			       rpattern.case_sensitive);
  }


  /* use accelerator string if it exists */
  if(stored == 4) {

    rpattern.has_accel = 1;
    rpattern.accel = get_accel(accel, &rpattern.accel_type, 
			       rpattern.case_sensitive);


    if(rpattern.accel == NULL) {
      log(LOG_ERROR, "unable to allocate memory from get_accel()\n");
      dodo_mode = 1;
      return;
    }

  } else {
    rpattern.has_accel = 0;
    rpattern.accel = NULL;
  }
  
  add_to_plist(rpattern);
}
Beispiel #7
0
Datei: kill.c Projekt: jheiss/nn
int
init_kill(void)
{
    FILE           *killf;
    comp_kill_header header;
    comp_kill_entry entry;
    register kill_list_entry *kl;
    register kill_group_regexp *tb;
    register group_header *gh;
    time_t          kill_age, comp_age;
    register long   n;
    int             first_try = 1;

    Loop_Groups_Header(gh)
    gh->kill_list = NULL;

    kill_age = file_exist(relative(nn_directory, KILL_FILE), "frw");
    if (kill_age == 0)
        return 0;

    comp_age = file_exist(relative(nn_directory, COMPILED_KILL), "fr");
again:
    if (comp_age < kill_age && !compile_kill_file())
        return 0;

    kill_tab = NULL;
    kill_patterns = NULL;
    group_regexp_table = NULL;
    regexp_table_size = 0;

    killf = open_file(relative(nn_directory, COMPILED_KILL), OPEN_READ);
    if (killf == NULL)
        return 0;

    if (fread((char *) &header, sizeof(header), 1, killf) != 1)
        goto err;
    /* MAGIC check: format changed or using different hardware */
    if (header.ckh_magic != COMP_KILL_MAGIC)
        goto err;

#ifndef NOV
    /* DB check: if database is rebuilt, group numbers may change */
    if (header.ckh_db_check != master.db_created)
        goto err;
#else
    /* ugly hack for NOV as there isn't a master to check */
    if (first_try)
        goto err;
#endif

    if (header.ckh_entries == 0) {
        fclose(killf);
        kill_file_loaded = 1;
        return 0;
    }
    if (header.ckh_pattern_size > 0) {
        kill_patterns = newstr(header.ckh_pattern_size);
        fseek(killf, header.ckh_entries * sizeof(entry), 1);
        if (fread(kill_patterns, sizeof(char), (int) header.ckh_pattern_size, killf)
                != header.ckh_pattern_size)
            goto err;
    } else
        kill_patterns = newstr(1);

    kill_tab = newobj(kill_list_entry, header.ckh_entries);
    if ((regexp_table_size = header.ckh_regexp_size))
        group_regexp_table = newobj(kill_group_regexp, header.ckh_regexp_size);

    tb = group_regexp_table;

    fseek(killf, sizeof(header), 0);
    for (n = header.ckh_entries, kl = kill_tab; --n >= 0; kl++) {
        if (fread((char *) &entry, sizeof(entry), 1, killf) != 1)
            goto err;
        if (header.ckh_pattern_size <= entry.ck_pattern_index ||
                entry.ck_pattern_index < 0)
            goto err;

        kl->kill_pattern = kill_patterns + entry.ck_pattern_index;
        kl->kill_flag = entry.ck_flag;

        if (kl->kill_flag & KILL_ON_REGEXP)
            kl->kill_regexp = regcomp(kl->kill_pattern);
        else
            kl->kill_regexp = NULL;

        if (kl->kill_flag & GROUP_REGEXP) {
            if (kl->kill_flag & GROUP_REGEXP_HDR) {
                if (header.ckh_pattern_size <= entry.ck_group ||
                        entry.ck_group < 0)
                    goto err;
                tb->group_regexp = regcomp(kill_patterns + entry.ck_group);
            } else
                tb->group_regexp = NULL;
            tb->kill_entry = kl;
            tb++;
        } else if (entry.ck_group >= 0) {
            gh = ACTIVE_GROUP(entry.ck_group);
            kl->next_kill = (kill_list_entry *) (gh->kill_list);
            gh->kill_list = (char *) kl;
        } else {
            kl->next_kill = global_kill_list;
            global_kill_list = kl;
        }
    }

    fclose(killf);

    kill_file_loaded = 1;
    return 1;

err:
    if (group_regexp_table != NULL)
        freeobj(group_regexp_table);
    if (kill_patterns != NULL)
        freeobj(kill_patterns);
    if (kill_tab != NULL)
        freeobj(kill_tab);

    fclose(killf);
    rm_kill_file();
    if (first_try) {
        first_try = 0;
        comp_age = 0;
        goto again;
    }
    strcpy(delayed_msg, "Error in compiled kill file (ignored)");

    Loop_Groups_Header(gh)
    gh->kill_list = NULL;

    global_kill_list = NULL;
    group_regexp_table = NULL;

    return 0;
}
Beispiel #8
0
static path *palloc(char *cline, int lno)
{
	int c;
	char *s;
	char *key;
	path *p;
	char **ap;

	/*
	 * Implement comment chars
	 */
	s = strchr(cline, '#');
	if (s)
		*s = 0;

	/*
	 * Do a pass through the string to count the number
	 * of arguments
	 */
	c = 0;
	key = strdup(cline);
	for (s = key; s != NULL; ) {
		char *val;
		while ((val = strsep(&s, " \t\n")) != NULL && *val == '\0')
			;
		if (val)
			c++;
	}
	c++;
	free(key);

	if (c <= 1)
		return (0);

	/*
	 * Now do another pass and generate a new path structure
	 */
	p = ALLOC(path);
	p->p_argc = 0;
	p->p_argv = xmalloc(c * sizeof(char *));
	p->p_args = strdup(cline);
	ap = p->p_argv;
	for (s = p->p_args; s != NULL; ) {
		char *val;
		while ((val = strsep(&s, " \t\n")) != NULL && *val == '\0')
			;
		if (val) {
			*ap++ = val;
			p->p_argc++;
		}
	}
	*ap = 0;

#ifdef DEBUG
	for (c = 0; c < p->p_argc; c++)
		printf("%sv[%d] = %s\n", c?"\t":"", c, p->p_argv[c]);
#endif

	p->p_key = p->p_argv[0];
	if (strpbrk(p->p_key, RE_CHARS)) {
		int val;

		curp = p;			/* XXX */
		val = regcomp(&p->p_rx, p->p_key, REG_EXTENDED | REG_NOSUB);
		if (val) {
			char errbuf[_POSIX2_LINE_MAX];
			regerror(val, &p->p_rx, errbuf, sizeof errbuf);
			syslog(LOG_ERR, "%s:%d: regcomp %s: %s",
			       conf_file, curp->p_lno, curp->p_key, errbuf);
			regfree(&p->p_rx);
			p->p_rxvalid = 0;
		} else {
			p->p_rxvalid = 1;
		}
		curp = 0;			/* XXX */
	} else {
		p->p_rxvalid = 0;
	}
	p->p_lno = lno;

	return (p);
}
Beispiel #9
0
/**
 * virStringSearch:
 * @str: string to search
 * @regexp: POSIX Extended regular expression pattern used for matching
 * @max_matches: maximum number of substrings to return
 * @result: pointer to an array to be filled with NULL terminated list of matches
 *
 * Performs a POSIX extended regex search against a string and return all matching substrings.
 * The @result value should be freed with virStringFreeList() when no longer
 * required.
 *
 * @code
 *  char *source = "6853a496-1c10-472e-867a-8244937bd6f0
 *                  773ab075-4cd7-4fc2-8b6e-21c84e9cb391
 *                  bbb3c75c-d60f-43b0-b802-fd56b84a4222
 *                  60c04aa1-0375-4654-8d9f-e149d9885273
 *                  4548d465-9891-4c34-a184-3b1c34a26aa8";
 *  char **matches = NULL;
 *  virStringSearch(source,
 *                  "([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})",
 *                  3,
 *                  &matches);
 *
 *  // matches[0] == "6853a496-1c10-472e-867a-8244937bd6f0";
 *  // matches[1] == "773ab075-4cd7-4fc2-8b6e-21c84e9cb391";
 *  // matches[2] == "bbb3c75c-d60f-43b0-b802-fd56b84a4222"
 *  // matches[3] == NULL;
 *
 *  virStringFreeList(matches);
 * @endcode
 *
 * Returns: -1 on error, or number of matches
 */
ssize_t
virStringSearch(const char *str,
                const char *regexp,
                size_t max_matches,
                char ***matches)
{
    regex_t re;
    regmatch_t rem;
    size_t nmatches = 0;
    ssize_t ret = -1;
    int rv = -1;

    *matches = NULL;

    VIR_DEBUG("search '%s' for '%s'", str, regexp);

    if ((rv = regcomp(&re, regexp, REG_EXTENDED)) != 0) {
        char error[100];
        regerror(rv, &re, error, sizeof(error));
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Error while compiling regular expression '%s': %s"),
                       regexp, error);
        return -1;
    }

    if (re.re_nsub != 1) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Regular expression '%s' must have exactly 1 match group, not %zu"),
                       regexp, re.re_nsub);
        goto cleanup;
    }

    /* '*matches' must always be NULL terminated in every iteration
     * of the loop, so start by allocating 1 element
     */
    if (VIR_EXPAND_N(*matches, nmatches, 1) < 0)
        goto cleanup;

    while ((nmatches - 1) < max_matches) {
        char *match;

        if (regexec(&re, str, 1, &rem, 0) != 0)
            break;

        if (VIR_EXPAND_N(*matches, nmatches, 1) < 0)
            goto cleanup;

        if (VIR_STRNDUP(match, str + rem.rm_so,
                        rem.rm_eo - rem.rm_so) < 0)
            goto cleanup;

        VIR_DEBUG("Got '%s'", match);

        (*matches)[nmatches-2] = match;

        str = str + rem.rm_eo;
    }

    ret = nmatches - 1; /* don't count the trailing null */

 cleanup:
    regfree(&re);
    if (ret < 0) {
        virStringFreeList(*matches);
        *matches = NULL;
    }
    return ret;
}
Beispiel #10
0
/*
 *	Move attributes from one list to the other
 *	if not already present.
 */
void pairmove(VALUE_PAIR **to, VALUE_PAIR **from)
{
	VALUE_PAIR **tailto, *i, *j, *next;
	VALUE_PAIR *tailfrom = NULL;
	VALUE_PAIR *found;
	int has_password = 0;

	/*
	 *	First, see if there are any passwords here, and
	 *	point "tailto" to the end of the "to" list.
	 */
	tailto = to;
	for(i = *to; i; i = i->next) {
		if (i->attribute == PW_USER_PASSWORD ||
		    i->attribute == PW_CRYPT_PASSWORD)
			has_password = 1;
		tailto = &i->next;
	}

	/*
	 *	Loop over the "from" list.
	 */
	for(i = *from; i; i = next) {
		next = i->next;

		/*
		 *	If there was a password in the "to" list,
		 *	do not move any other password from the
		 *	"from" to the "to" list.
		 */
		if (has_password &&
		    (i->attribute == PW_USER_PASSWORD ||
		     i->attribute == PW_CRYPT_PASSWORD)) {
			tailfrom = i;
			continue;
		}

		switch (i->operator) {
			/*
			 *	These are COMPARISON attributes
			 *	from a check list, and are not
			 *	supposed to be copied!
			 */
			case T_OP_NE:
			case T_OP_GE:
			case T_OP_GT:
			case T_OP_LE:
			case T_OP_LT:
			case T_OP_CMP_TRUE:
			case T_OP_CMP_FALSE:
			case T_OP_CMP_EQ:
			case T_OP_REG_EQ:
			case T_OP_REG_NE:
				tailfrom = i;
				continue;

			default:
				break;
		}

		/*
		 *	If the attribute is already present in "to",
		 *	do not move it from "from" to "to". We make
		 *	an exception for "Hint" which can appear multiple
		 *	times, and we never move "Fall-Through".
		 */
		if (i->attribute == PW_FALL_THROUGH ||
		    (i->attribute != PW_HINT && i->attribute != PW_FRAMED_ROUTE)) {

			found = pairfind(*to, i->attribute);
			switch (i->operator) {

			  /*
			   *	If matching attributes are found,
			   *	delete them.
			   */
			case T_OP_SUB:		/* -= */
				if (found) {
					if (!i->vp_strvalue[0] ||
					    (strcmp((char *)found->vp_strvalue,
						    (char *)i->vp_strvalue) == 0)){
						pairdelete(to, found->attribute);

						/*
						 *	'tailto' may have been
						 *	deleted...
						 */
						tailto = to;
						for(j = *to; j; j = j->next) {
							tailto = &j->next;
						}
					}
				}
				tailfrom = i;
				continue;
				break;

/* really HAVE_REGEX_H */
#if 0
				/*
				 *  Attr-Name =~ "s/find/replace/"
				 *
				 *  Very bad code.  Barely working,
				 *  if at all.
				 */

			case T_OP_REG_EQ:
			  if (found &&
			      (i->vp_strvalue[0] == 's')) {
			    regex_t		reg;
			    regmatch_t		match[1];

			    char *str;
			    char *p, *q;

			    p = i->vp_strvalue + 1;
			    q = strchr(p + 1, *p);
			    if (!q || (q[strlen(q) - 1] != *p)) {
			      tailfrom = i;
			      continue;
			    }
			    str = strdup(i->vp_strvalue + 2);
			    q = strchr(str, *p);
			    *(q++) = '\0';
			    q[strlen(q) - 1] = '\0';

			    regcomp(&reg, str, 0);
			    if (regexec(&reg, found->vp_strvalue,
					1, match, 0) == 0) {
			      fprintf(stderr, "\"%s\" will have %d to %d replaced with %s\n",
				      found->vp_strvalue, match[0].rm_so,
				      match[0].rm_eo, q);

			    }
			    regfree(&reg);
			    free(str);
			  }
			  tailfrom = i;	/* don't copy it over */
			  continue;
			  break;
#endif
			case T_OP_EQ:		/* = */
				/*
				 *  FIXME: Tunnel attributes with
				 *  different tags are different
				 *  attributes.
				 */
				if (found) {
					tailfrom = i;
					continue; /* with the loop */
				}
				break;

			  /*
			   *  If a similar attribute is found,
			   *  replace it with the new one.  Otherwise,
			   *  add the new one to the list.
			   */
			case T_OP_SET:		/* := */
				if (found) {
					VALUE_PAIR *mynext = found->next;

					/*
					 *	Do NOT call pairdelete()
					 *	here, due to issues with
					 *	re-writing "request->username".
					 *
					 *	Everybody calls pairmove,
					 *	and expects it to work.
					 *	We can't update request->username
					 *	here, so instead we over-write
					 *	the vp that it's pointing to.
					 */
					memcpy(found, i, sizeof(*found));
					found->next = mynext;

					pairdelete(&found->next, found->attribute);

					/*
					 *	'tailto' may have been
					 *	deleted...
					 */
					for(j = found; j; j = j->next) {
						tailto = &j->next;
					}
					continue;
				}
				break;

			  /*
			   *  Add the new element to the list, even
			   *  if similar ones already exist.
			   */
			default:
			case T_OP_ADD: /* += */
				break;
			}
		}
		if (tailfrom)
			tailfrom->next = next;
		else
			*from = next;

		/*
		 *	If ALL of the 'to' attributes have been deleted,
		 *	then ensure that the 'tail' is updated to point
		 *	to the head.
		 */
		if (!*to) {
			tailto = to;
		}
		*tailto = i;
		if (i) {
			i->next = NULL;
			tailto = &i->next;
		}
	}
}
Beispiel #11
0
int
main(int argc, char **argv)
{
	static const char *outfile = "tags";	/* output file */
	int	aflag;				/* -a: append to tags */
	int	uflag;				/* -u: update tags */
	int	exit_val;			/* exit value */
	int	step;				/* step through args */
	int	ch;				/* getopts char */

	setlocale(LC_ALL, "");

	aflag = uflag = NO;
	tflag = YES;
	while ((ch = getopt(argc, argv, "BFTadf:tuwvx")) != -1)
		switch(ch) {
		case 'B':
			searchar = '?';
			break;
		case 'F':
			searchar = '/';
			break;
		case 'T':
			tflag = NO;
			break;
		case 'a':
			aflag++;
			break;
		case 'd':
			dflag++;
			break;
		case 'f':
			outfile = optarg;
			break;
		case 't':
			tflag = YES;
			break;
		case 'u':
			uflag++;
			break;
		case 'w':
			wflag++;
			break;
		case 'v':
			vflag++;
		case 'x':
			xflag++;
			break;
		case '?':
		default:
			usage();
		}
	argv += optind;
	argc -= optind;
	if (!argc)
		usage();

	if (!xflag)
		setlocale(LC_COLLATE, "C");

	init();

	for (exit_val = step = 0; step < argc; ++step)
		if (!(inf = fopen(argv[step], "r"))) {
			warn("%s", argv[step]);
			exit_val = 1;
		}
		else {
			curfile = argv[step];
			find_entries(argv[step]);
			fclose(inf);
		}

	if (head) {
		if (xflag)
			put_entries(head);
		else {
			if (uflag) {
				FILE *oldf;
				regex_t *regx;

				if ((oldf = fopen(outfile, "r")) == NULL)
					err(1, "opening %s", outfile);
				if (unlink(outfile))
					err(1, "unlinking %s", outfile);
				if ((outf = fopen(outfile, "w")) == NULL)
					err(1, "recreating %s", outfile);
				if ((regx = calloc(argc, sizeof(regex_t))) == NULL)
					err(1, "RE alloc");
				for (step = 0; step < argc; step++) {
					strcpy(lbuf, "\t");
					strlcat(lbuf, argv[step], LINE_MAX);
					strlcat(lbuf, "\t", LINE_MAX);
					if (regcomp(regx + step, lbuf,
					    REG_NOSPEC))
						warn("RE compilation failed");
				}
nextline:
				while (fgets(lbuf, LINE_MAX, oldf)) {
					for (step = 0; step < argc; step++)
						if (regexec(regx + step,
						    lbuf, 0, NULL, 0) == 0)
							goto nextline;
					fputs(lbuf, outf);
				}
				for (step = 0; step < argc; step++)
					regfree(regx + step);
				free(regx);
				fclose(oldf);
				fclose(outf);
				++aflag;
			}
			if (!(outf = fopen(outfile, aflag ? "a" : "w")))
				err(1, "%s", outfile);
			put_entries(head);
			fclose(outf);
			if (uflag) {
				pid_t pid;

				if ((pid = fork()) == -1)
					err(1, "fork failed");
				else if (pid == 0) {
					execlp("sort", "sort", "-o", outfile,
					    outfile, NULL);
					err(1, "exec of sort failed");
				}
				/* Just assume the sort went OK. The old code
				   did not do any checks either. */
				wait(NULL);
			}
		}
	}
	exit(exit_val);
}
Beispiel #12
0
/*
 *	Compare two pairs, using the operator from "one".
 *
 *	i.e. given two attributes, it does:
 *
 *	(two->data) (one->operator) (one->data)
 *
 *	e.g. "foo" != "bar"
 *
 *	Returns true (comparison is true), or false (comparison is not true);
 *
 *	FIXME: Ignores tags!
 */
int paircmp(VALUE_PAIR *one, VALUE_PAIR *two)
{
	int compare;

	switch (one->operator) {
	case T_OP_CMP_TRUE:
		return (two != NULL);

	case T_OP_CMP_FALSE:
		return (two == NULL);

		/*
		 *	One is a regex, compile it, print two to a string,
		 *	and then do string comparisons.
		 */
	case T_OP_REG_EQ:
	case T_OP_REG_NE:
#ifndef HAVE_REGEX_H
		return -1;
#else
		{
			regex_t reg;
			char buffer[MAX_STRING_LEN * 4 + 1];

			compare = regcomp(&reg, one->vp_strvalue,
					  REG_EXTENDED);
			if (compare != 0) {
				regerror(compare, &reg, buffer, sizeof(buffer));
				fr_strerror_printf("Illegal regular expression in attribute: %s: %s",
					   one->name, buffer);
				return -1;
			}

			vp_prints_value(buffer, sizeof(buffer), two, 0);

			/*
			 *	Don't care about substring matches,
			 *	oh well...
			 */
			compare = regexec(&reg, buffer, 0, NULL, 0);

			regfree(&reg);
			if (one->operator == T_OP_REG_EQ) return (compare == 0);
			return (compare != 0);
		}
#endif

	default:		/* we're OK */
		break;
	}

	/*
	 *	After doing the previous check for special comparisons,
	 *	do the per-type comparison here.
	 */
	switch (one->type) {
	case PW_TYPE_ABINARY:
	case PW_TYPE_OCTETS:
	{
		size_t length;

		if (one->length < two->length) {
			length = one->length;
		} else {
			length = two->length;
		}

		if (length) {
			compare = memcmp(two->vp_octets, one->vp_octets,
					 length);
			if (compare != 0) break;
		}

		/*
		 *	Contents are the same.  The return code
		 *	is therefore the difference in lengths.
		 *
		 *	i.e. "0x00" is smaller than "0x0000"
		 */
		compare = two->length - one->length;
	}
		break;

	case PW_TYPE_STRING:
		compare = strcmp(two->vp_strvalue, one->vp_strvalue);
		break;

	case PW_TYPE_BYTE:
	case PW_TYPE_SHORT:
	case PW_TYPE_INTEGER:
	case PW_TYPE_DATE:
		if (two->vp_integer < one->vp_integer) {
			compare = -1;
		} else if (two->vp_integer == one ->vp_integer) {
			compare = 0;
		} else {
			compare = +1;
		}
		break;

	case PW_TYPE_IPADDR:
		if (ntohl(two->vp_ipaddr)  < ntohl(one->vp_ipaddr) ) {
			compare = -1;
		} else if (ntohl(two->vp_ipaddr)  == ntohl(one->vp_ipaddr) ) {
			compare = 0;
		} else {
			compare = +1;
		}
		break;

	case PW_TYPE_IPV6ADDR:
		compare = memcmp(&two->vp_ipv6addr, &one->vp_ipv6addr,
				 sizeof(two->vp_ipv6addr));
		break;

	case PW_TYPE_IPV6PREFIX:
		compare = memcmp(&two->vp_ipv6prefix, &one->vp_ipv6prefix,
				 sizeof(two->vp_ipv6prefix));
		break;

	case PW_TYPE_IFID:
		compare = memcmp(&two->vp_ifid, &one->vp_ifid,
				 sizeof(two->vp_ifid));
		break;

	default:
		return 0;	/* unknown type */
	}

	/*
	 *	Now do the operator comparison.
	 */
	switch (one->operator) {
	case T_OP_CMP_EQ:
		return (compare == 0);

	case T_OP_NE:
		return (compare != 0);

	case T_OP_LT:
		return (compare < 0);

	case T_OP_GT:
		return (compare > 0);

	case T_OP_LE:
		return (compare <= 0);

	case T_OP_GE:
		return (compare >= 0);

	default:
		return 0;
	}

	return 0;
}
Beispiel #13
0
/** Compares check and vp by value.
 *
 * Does not call any per-attribute comparison function, but does honour
 * check.operator. Basically does "vp.value check.op check.value".
 *
 * @param request Current request.
 * @param check rvalue, and operator.
 * @param vp lvalue.
 * @return 0 if check and vp are equal, -1 if vp value is less than check value, 1 is vp value is more than check
 *	value, -2 on error.
 */
int radius_compare_vps(REQUEST *request, VALUE_PAIR *check, VALUE_PAIR *vp)
{
	int ret = 0;

	/*
	 *      Check for =* and !* and return appropriately
	 */
	if (check->op == T_OP_CMP_TRUE)  return 0;
	if (check->op == T_OP_CMP_FALSE) return 1;

#ifdef HAVE_REGEX_H
	if (check->op == T_OP_REG_EQ) {
		int compare;
		regex_t reg;
		char value[1024];
		regmatch_t rxmatch[REQUEST_MAX_REGEX + 1];

		vp_prints_value(value, sizeof(value), vp, -1);

		/*
		 *	Include substring matches.
		 */
		compare = regcomp(&reg, check->vp_strvalue, REG_EXTENDED);
		if (compare != 0) {
			char buffer[256];
			regerror(compare, &reg, buffer, sizeof(buffer));

			RDEBUG("Invalid regular expression %s: %s", check->vp_strvalue, buffer);
			return -2;
		}

		memset(&rxmatch, 0, sizeof(rxmatch));	/* regexec does not seem to initialise unused elements */
		compare = regexec(&reg, value, REQUEST_MAX_REGEX + 1, rxmatch, 0);
		regfree(&reg);
		rad_regcapture(request, compare, value, rxmatch);

		ret = (compare == 0) ? 0 : -1;
		goto finish;
	}

	if (check->op == T_OP_REG_NE) {
		int compare;
		regex_t reg;
		char value[1024];
		regmatch_t rxmatch[REQUEST_MAX_REGEX + 1];

		vp_prints_value(value, sizeof(value), vp, -1);

		/*
		 *	Include substring matches.
		 */
		compare = regcomp(&reg, check->vp_strvalue, REG_EXTENDED);
		if (compare != 0) {
			char buffer[256];
			regerror(compare, &reg, buffer, sizeof(buffer));

			RDEBUG("Invalid regular expression %s: %s", check->vp_strvalue, buffer);
			return -2;
		}
		compare = regexec(&reg, value,  REQUEST_MAX_REGEX + 1, rxmatch, 0);
		regfree(&reg);

		ret = (compare != 0) ? 0 : -1;
	}
#endif

	/*
	 *	Attributes must be of the same type.
	 *
	 *	FIXME: deal with type mismatch properly if one side contain
	 *	ABINARY, OCTETS or STRING by converting the other side to
	 *	a string
	 *
	 */
	if (vp->da->type != check->da->type) return -1;

	/*
	 *	Tagged attributes are equal if and only if both the
	 *	tag AND value match.
	 */
	if (check->da->flags.has_tag) {
		ret = ((int) vp->tag) - ((int) check->tag);
		if (ret != 0) goto finish;
	}

	/*
	 *	Not a regular expression, compare the types.
	 */
	switch(check->da->type) {
#ifdef WITH_ASCEND_BINARY
		/*
		 *	Ascend binary attributes can be treated
		 *	as opaque objects, I guess...
		 */
		case PW_TYPE_ABINARY:
#endif
		case PW_TYPE_OCTETS:
			if (vp->length != check->length) {
				ret = 1; /* NOT equal */
				break;
			}
			ret = memcmp(vp->vp_strvalue, check->vp_strvalue,
				     vp->length);
			break;

		case PW_TYPE_STRING:
			ret = strcmp(vp->vp_strvalue,
				     check->vp_strvalue);
			break;

		case PW_TYPE_BYTE:
		case PW_TYPE_SHORT:
		case PW_TYPE_INTEGER:
			ret = vp->vp_integer - check->vp_integer;
			break;

		case PW_TYPE_INTEGER64:
			/*
			 *	Don't want integer overflow!
			 */
			if (vp->vp_integer64 < check->vp_integer64) {
				ret = -1;
			} else if (vp->vp_integer64 > check->vp_integer64) {
				ret = +1;
			} else {
				ret = 0;
			}
			break;

		case PW_TYPE_SIGNED:
			if (vp->vp_signed < check->vp_signed) {
				ret = -1;
			} else if (vp->vp_signed > check->vp_signed) {
				ret = +1;
			} else {
				ret = 0;
			}
			break;

		case PW_TYPE_DATE:
			ret = vp->vp_date - check->vp_date;
			break;

		case PW_TYPE_IPADDR:
			ret = ntohl(vp->vp_ipaddr) - ntohl(check->vp_ipaddr);
			break;

		case PW_TYPE_IPV6ADDR:
			ret = memcmp(&vp->vp_ipv6addr, &check->vp_ipv6addr,
				     sizeof(vp->vp_ipv6addr));
			break;

		case PW_TYPE_IPV6PREFIX:
			ret = memcmp(&vp->vp_ipv6prefix, &check->vp_ipv6prefix,
				     sizeof(vp->vp_ipv6prefix));
			break;

		case PW_TYPE_IFID:
			ret = memcmp(&vp->vp_ifid, &check->vp_ifid,
				     sizeof(vp->vp_ifid));
			break;

		default:
			break;
	}

	finish:
	if (ret > 0) {
		return 1;
	}
	if (ret < 0) {
		return -1;
	}
	return 0;
}
Beispiel #14
0
/*!
 * \internal
 * \brief Respond to a client update request
 *
 * \param[in] xml         Root of request XML
 *
 * \return void
 */
void
attrd_client_update(xmlNode *xml)
{
    attribute_t *a = NULL;
    char *host = crm_element_value_copy(xml, F_ATTRD_HOST);
    const char *attr = crm_element_value(xml, F_ATTRD_ATTRIBUTE);
    const char *value = crm_element_value(xml, F_ATTRD_VALUE);
    const char *regex = crm_element_value(xml, F_ATTRD_REGEX);

    /* If a regex was specified, broadcast a message for each match */
    if ((attr == NULL) && regex) {
        GHashTableIter aIter;
        regex_t *r_patt = calloc(1, sizeof(regex_t));

        crm_debug("Setting %s to %s", regex, value);
        if (regcomp(r_patt, regex, REG_EXTENDED|REG_NOSUB)) {
            crm_err("Bad regex '%s' for update", regex);

        } else {
            g_hash_table_iter_init(&aIter, attributes);
            while (g_hash_table_iter_next(&aIter, (gpointer *) & attr, NULL)) {
                int status = regexec(r_patt, attr, 0, NULL, 0);

                if (status == 0) {
                    crm_trace("Matched %s with %s", attr, regex);
                    crm_xml_add(xml, F_ATTRD_ATTRIBUTE, attr);
                    send_attrd_message(NULL, xml);
                }
            }
        }

        free(host);
        regfree(r_patt);
        free(r_patt);
        return;

    } else if (attr == NULL) {
        crm_err("Update request did not specify attribute or regular expression");
        free(host);
        return;
    }

    if (host == NULL) {
        crm_trace("Inferring host");
        host = strdup(attrd_cluster->uname);
        crm_xml_add(xml, F_ATTRD_HOST, host);
        crm_xml_add_int(xml, F_ATTRD_HOST_ID, attrd_cluster->nodeid);
    }

    a = g_hash_table_lookup(attributes, attr);

    /* If value was specified using ++ or += notation, expand to real value */
    if (value) {
        if (attrd_value_needs_expansion(value)) {
            int int_value;
            attribute_value_t *v = NULL;

            if (a) {
                v = g_hash_table_lookup(a->values, host);
            }
            int_value = attrd_expand_value(value, (v? v->current : NULL));

            crm_info("Expanded %s=%s to %d", attr, value, int_value);
            crm_xml_add_int(xml, F_ATTRD_VALUE, int_value);

            /* Replacing the value frees the previous memory, so re-query it */
            value = crm_element_value(xml, F_ATTRD_VALUE);
        }
    }

    crm_debug("Broadcasting %s[%s]=%s%s", attr, host, value,
              (attrd_election_won()? " (writer)" : ""));

    free(host);

    send_attrd_message(NULL, xml); /* ends up at attrd_peer_message() */
}
Beispiel #15
0
/*=export_func  optionUnstackArg
 * private:
 *
 * what:  Remove option args from a stack
 * arg:   + tOptions* + pOpts    + program options descriptor +
 * arg:   + tOptDesc* + pOptDesc + the descriptor for this arg +
 *
 * doc:
 *  Invoked for options that are equivalenced to stacked options.
=*/
void
optionUnstackArg(
    tOptions*  pOpts,
    tOptDesc*  pOptDesc )
{
    int       res;

    tArgList* pAL;

    if ((pOptDesc->fOptState & OPTST_RESET) != 0)
        return;
    pAL = (tArgList*)pOptDesc->optCookie;

    /*
     *  IF we don't have any stacked options,
     *  THEN indicate that we don't have any of these options
     */
    if (pAL == NULL) {
        pOptDesc->fOptState &= OPTST_PERSISTENT_MASK;
        if ( (pOptDesc->fOptState & OPTST_INITENABLED) == 0)
            pOptDesc->fOptState |= OPTST_DISABLED;
        return;
    }

#ifdef WITH_LIBREGEX
    {
        regex_t   re;
        int       i, ct, dIdx;

        if (regcomp( &re, pOptDesc->optArg.argString, REG_NOSUB ) != 0)
            return;

        /*
         *  search the list for the entry(s) to remove.  Entries that
         *  are removed are *not* copied into the result.  The source
         *  index is incremented every time.  The destination only when
         *  we are keeping a define.
         */
        for (i = 0, dIdx = 0, ct = pAL->useCt; --ct >= 0; i++) {
            tCC*      pzSrc = pAL->apzArgs[ i ];
            char*     pzEq  = strchr( pzSrc, '=' );

            if (pzEq != NULL)
                *pzEq = NUL;

            res = regexec( &re, pzSrc, (size_t)0, NULL, 0 );
            switch (res) {
            case 0:
                /*
                 *  Remove this entry by reducing the in-use count
                 *  and *not* putting the string pointer back into
                 *  the list.
                 */
                AGFREE(pzSrc);
                pAL->useCt--;
                break;

            default:
            case REG_NOMATCH:
                if (pzEq != NULL)
                    *pzEq = '=';

                /*
                 *  IF we have dropped an entry
                 *  THEN we have to move the current one.
                 */
                if (dIdx != i)
                    pAL->apzArgs[ dIdx ] = pzSrc;
                dIdx++;
            }
        }

        regfree( &re );
    }
#else  /* not WITH_LIBREGEX */
    {
        int i, ct, dIdx;

        /*
         *  search the list for the entry(s) to remove.  Entries that
         *  are removed are *not* copied into the result.  The source
         *  index is incremented every time.  The destination only when
         *  we are keeping a define.
         */
        for (i = 0, dIdx = 0, ct = pAL->useCt; --ct >= 0; i++) {
            tCC*      pzSrc = pAL->apzArgs[ i ];
            char*     pzEq  = strchr( pzSrc, '=' );

            if (pzEq != NULL)
                *pzEq = NUL;

            if (strcmp( pzSrc, pOptDesc->optArg.argString ) == 0) {
                /*
                 *  Remove this entry by reducing the in-use count
                 *  and *not* putting the string pointer back into
                 *  the list.
                 */
                AGFREE(pzSrc);
                pAL->useCt--;
            } else {
                if (pzEq != NULL)
                    *pzEq = '=';

                /*
                 *  IF we have dropped an entry
                 *  THEN we have to move the current one.
                 */
                if (dIdx != i)
                    pAL->apzArgs[ dIdx ] = pzSrc;
                dIdx++;
            }
        }
    }
#endif /* WITH_LIBREGEX */
    /*
     *  IF we have unstacked everything,
     *  THEN indicate that we don't have any of these options
     */
    if (pAL->useCt == 0) {
        pOptDesc->fOptState &= OPTST_PERSISTENT_MASK;
        if ( (pOptDesc->fOptState & OPTST_INITENABLED) == 0)
            pOptDesc->fOptState |= OPTST_DISABLED;
        AGFREE( pAL );
        pOptDesc->optCookie = NULL;
    }
}
Beispiel #16
0
int main(int argc, char **argv)
{
    /* I18n */
    setlocale(LC_ALL, "");
#if ENABLE_NLS
    bindtextdomain(PACKAGE, LOCALEDIR);
    textdomain(PACKAGE);
#endif

    abrt_init(argv);

    /* Can't keep these strings/structs static: _() doesn't support that */
    const char *program_usage_string = _(
        "& [-vusoxm] [-d DIR]/[-D] [FILE]\n"
        "\n"
        "Extract oops from FILE (or standard input)"
    );
    enum {
        OPT_v = 1 << 0,
        OPT_s = 1 << 1,
        OPT_o = 1 << 2,
        OPT_d = 1 << 3,
        OPT_D = 1 << 4,
        OPT_u = 1 << 5,
        OPT_x = 1 << 6,
        OPT_t = 1 << 7,
        OPT_m = 1 << 8,
    };
    char *problem_dir = NULL;
    char *dump_location = NULL;
    /* Keep enum above and order of options below in sync! */
    struct options program_options[] = {
        OPT__VERBOSE(&g_verbose),
        OPT_BOOL(  's', NULL, NULL, _("Log to syslog")),
        OPT_BOOL(  'o', NULL, NULL, _("Print found oopses on standard output")),
        /* oopses don't contain any sensitive info, and even
         * the old koops app was showing the oopses to all users
         */
        OPT_STRING('d', NULL, &dump_location, "DIR", _("Create new problem directory in DIR for every oops found")),
        OPT_BOOL(  'D', NULL, NULL, _("Same as -d DumpLocation, DumpLocation is specified in abrt.conf")),
        OPT_STRING('u', NULL, &problem_dir, "PROBLEM", _("Save the extracted information in PROBLEM")),
        OPT_BOOL(  'x', NULL, NULL, _("Make the problem directory world readable")),
        OPT_BOOL(  't', NULL, NULL, _("Throttle problem directory creation to 1 per second")),
        OPT_BOOL(  'm', NULL, NULL, _("Print search string(s) to stdout and exit")),
        OPT_END()
    };
    unsigned opts = parse_opts(argc, argv, program_options, program_usage_string);

    export_abrt_envvars(0);

    msg_prefix = g_progname;
    if ((opts & OPT_s) || getenv("ABRT_SYSLOG"))
    {
        logmode = LOGMODE_JOURNAL;
    }

    if (opts & OPT_m)
    {
        char *oops_string_filter_regex = abrt_oops_string_filter_regex();
        if (oops_string_filter_regex)
        {
            regex_t filter_re;
            if (regcomp(&filter_re, oops_string_filter_regex, REG_NOSUB) != 0)
                perror_msg_and_die(_("Failed to compile regex"));

            const regex_t *filter[] = { &filter_re, NULL };

            koops_print_suspicious_strings_filtered(filter);

            regfree(&filter_re);
            free(oops_string_filter_regex);
        }
        else
            koops_print_suspicious_strings();

        return 1;
    }

    if (opts & OPT_D)
    {
        if (opts & OPT_d)
            show_usage_and_die(program_usage_string, program_options);
        load_abrt_conf();
        dump_location = g_settings_dump_location;
        g_settings_dump_location = NULL;
        free_abrt_conf_data();
    }

    int oops_utils_flags = 0;
    if ((opts & OPT_x))
        oops_utils_flags |= ABRT_OOPS_WORLD_READABLE;

    if ((opts & OPT_t))
        oops_utils_flags |= ABRT_OOPS_THROTTLE_CREATION;

    if ((opts & OPT_o))
        oops_utils_flags |= ABRT_OOPS_PRINT_STDOUT;

    argv += optind;
    if (argv[0])
        xmove_fd(xopen(argv[0], O_RDONLY), STDIN_FILENO);

    GList *oops_list = NULL;
    scan_syslog_file(&oops_list, STDIN_FILENO);

    unsigned errors = 0;
    if (opts & OPT_u)
    {
        log("Updating problem directory");
        switch (g_list_length(oops_list))
        {
            case 0:
                {
                    error_msg(_("Can't update the problem: no oops found"));
                    errors = 1;
                    break;
                }
            default:
                {
                    log_notice(_("More oopses found: process only the first one"));
                }
                /* falls trought */
            case 1:
                {
                    struct dump_dir *dd = dd_opendir(problem_dir, /*open for writing*/0);
                    if (dd)
                    {
                        abrt_oops_save_data_in_dump_dir(dd, (char *)oops_list->data, /*no proc modules*/NULL);
                        dd_close(dd);
                    }
                }
        }
    }
    else
        errors = abrt_oops_process_list(oops_list, dump_location,
                                        ABRT_DUMP_OOPS_ANALYZER, oops_utils_flags);

    list_free_with_free(oops_list);
    //oops_list = NULL;

    return errors;
}
Beispiel #17
0
int
main (int argc, char *argv[])
{
  struct stat st;
  static const char *pat[] = {
    ".?.?.?.?.?.?.?argc",
    "(.?)(.?)(.?)(.?)(.?)(.?)(.?)argc",
    "((((((((((.?))))))))))((((((((((.?))))))))))((((((((((.?))))))))))"
    "((((((((((.?))))))))))((((((((((.?))))))))))((((((((((.?))))))))))"
    "((((((((((.?))))))))))argc" };

  size_t len;
  int fd;
  int testno, i, j, k, l;
  char *string;
  char *buf;

  if (argc < 2)
    abort ();

  fd = open (argv[1], O_RDONLY);
  if (fd < 0)
    {
      printf ("Couldn't open %s: %s\n", argv[1], strerror (errno));
      abort ();
    }

  if (fstat (fd, &st) < 0)
    {
      printf ("Couldn't fstat %s: %s\n", argv[1], strerror (errno));
      abort ();
    }

  buf = malloc (st.st_size + 1);
  if (buf == NULL)
    {
      printf ("Couldn't allocate buffer: %s\n", strerror (errno));
      abort ();
    }

  if (read (fd, buf, st.st_size) != (ssize_t) st.st_size)
    {
      printf ("Couldn't read %s", argv[1]);
      abort ();
    }

  close (fd);
  buf[st.st_size] = '\0';

  string = buf;
  len = st.st_size;

  for (testno = 0; testno < 4; ++testno)
    for (i = 0; i < sizeof (pat) / sizeof (pat[0]); ++i)
      {
	regex_t rbuf;
	struct re_pattern_buffer rpbuf;
	int err;

	printf ("test %d pattern %d", testno, i);
	if (testno < 2)
	  {
	    err = regcomp (&rbuf, pat[i],
			   REG_EXTENDED | (testno ? REG_NOSUB : 0));
	    if (err != 0)
	      {
		char errstr[300];
		putchar ('\n');
		regerror (err, &rbuf, errstr, sizeof (errstr));
		puts (errstr);
		return err;
	      }
	  }
	else
	  {
	    const char *s;
	    re_set_syntax (RE_SYNTAX_POSIX_EGREP
			   | (testno == 3 ? RE_NO_SUB : 0));

	    memset (&rpbuf, 0, sizeof (rpbuf));
	    s = re_compile_pattern (pat[i], strlen (pat[i]), &rpbuf);
	    if (s != NULL)
	      {
		printf ("\n%s\n", s);
		abort ();
	      }

	    /* Just so that this can be tested with earlier glibc as well.  */
	    if (testno == 3)
	      rpbuf.no_sub = 1;
	  }

      if (testno < 2)
	{
	  regmatch_t pmatch[71];
	  err = regexec (&rbuf, string, 71, pmatch, 0);
	  if (err == REG_NOMATCH)
	    {
	      puts ("\nregexec failed");
	      abort ();
	    }

	  if (testno == 0)
	    {
	      if (pmatch[0].rm_eo != pmatch[0].rm_so + 11
		  || pmatch[0].rm_eo > len
		  || string + pmatch[0].rm_so >= strchr (string, 'R')
		  || strncmp (string + pmatch[0].rm_so,
			      "n (int argc",
			      sizeof "n (int argc" - 1)
		     != 0)
		{
		  puts ("\nregexec without REG_NOSUB did not find the correct match");
		  abort ();
		}

	      if (i > 0)
		for (j = 0, l = 1; j < 7; ++j)
		  for (k = 0; k < (i == 1 ? 1 : 10); ++k, ++l)
		    if (pmatch[l].rm_so != pmatch[0].rm_so + j
			|| pmatch[l].rm_eo != pmatch[l].rm_so + 1)
		      {
			printf ("\npmatch[%d] incorrect\n", l);
			abort ();
		      }
	    }
	}
      else
	{
	  struct re_registers regs;
	  int match;

	  memset (&regs, 0, sizeof (regs));
	  match = re_search (&rpbuf, string, len, 0, len,
				 &regs);
	  if (match < 0)
	    {
	      puts ("\nre_search failed");
	      abort ();
	    }

	  if (match + 11 > len
	      || string + match >= strchr (string, 'R')
	      || strncmp (string + match,
			  "n (int argc",
			  sizeof "n (int argc" - 1)
		  != 0)
	    {
	      puts ("\nre_search did not find the correct match");
	      abort ();
	    }

	  if (testno == 2)
	    {
	      if (regs.num_regs != 2 + (i == 0 ? 0 : i == 1 ? 7 : 70))
		{
		  printf ("\nincorrect num_regs %d\n", regs.num_regs);
		  abort ();
		}

	      if (regs.start[0] != match || regs.end[0] != match + 11)
		{
		  printf ("\nincorrect regs.{start,end}[0] = { %d, %d}\n",
			  regs.start[0], regs.end[0]);
		  abort ();
		}

	      if (regs.start[regs.num_regs - 1] != -1
		  || regs.end[regs.num_regs - 1] != -1)
		{
		  puts ("\nincorrect regs.{start,end}[num_regs - 1]");
		  abort ();
		}

	      if (i > 0)
		for (j = 0, l = 1; j < 7; ++j)
		  for (k = 0; k < (i == 1 ? 1 : 10); ++k, ++l)
		    if (regs.start[l] != match + j
			|| regs.end[l] != regs.start[l] + 1)
		      {
			printf ("\nregs.{start,end}[%d] incorrect\n", l);
			abort ();
		      }
	    }
	}

      putchar ('\n');

      if (testno < 2)
	regfree (&rbuf);
      else
	regfree (&rpbuf);
    }

  exit (0);
}
Beispiel #18
0
/* process command-line arguments */
int
process_arguments (int argc, char **argv)
{
  int c, err;
  struct parameter_list *se;
  struct parameter_list *temp_list = NULL, *previous = NULL;
  struct parameter_list *temp_path_select_list = NULL;
  struct mount_entry *me, *temp_me;
  int result = OK;
  regex_t re;
  int cflags = REG_NOSUB | REG_EXTENDED;
  int default_cflags = cflags;
  char errbuf[MAX_INPUT_BUFFER];
  int fnd = 0;

  int option = 0;
  static struct option longopts[] = {
    {"timeout", required_argument, 0, 't'},
    {"warning", required_argument, 0, 'w'},
    {"critical", required_argument, 0, 'c'},
    {"iwarning", required_argument, 0, 'W'},
    /* Dang, -C is taken. We might want to reshuffle this. */
    {"icritical", required_argument, 0, 'K'},
    {"kilobytes", no_argument, 0, 'k'},
    {"megabytes", no_argument, 0, 'm'},
    {"units", required_argument, 0, 'u'},
    {"path", required_argument, 0, 'p'},
    {"partition", required_argument, 0, 'p'},
    {"exclude_device", required_argument, 0, 'x'},
    {"exclude-type", required_argument, 0, 'X'},
    {"group", required_argument, 0, 'g'},
    {"eregi-path", required_argument, 0, 'R'},
    {"eregi-partition", required_argument, 0, 'R'},
    {"ereg-path", required_argument, 0, 'r'},
    {"ereg-partition", required_argument, 0, 'r'},
    {"ignore-ereg-path", required_argument, 0, 'i'},
    {"ignore-ereg-partition", required_argument, 0, 'i'},
    {"ignore-eregi-path", required_argument, 0, 'I'},
    {"ignore-eregi-partition", required_argument, 0, 'I'},
    {"local", no_argument, 0, 'l'},
    {"stat-remote-fs", no_argument, 0, 'L'},
    {"mountpoint", no_argument, 0, 'M'},
    {"errors-only", no_argument, 0, 'e'},
    {"exact-match", no_argument, 0, 'E'},
    {"all", no_argument, 0, 'A'},
    {"verbose", no_argument, 0, 'v'},
    {"quiet", no_argument, 0, 'q'},
    {"clear", no_argument, 0, 'C'},
    {"version", no_argument, 0, 'V'},
    {"help", no_argument, 0, 'h'},
    {0, 0, 0, 0}
  };

  if (argc < 2)
    return ERROR;

  np_add_name(&fs_exclude_list, "iso9660");

  for (c = 1; c < argc; c++)
    if (strcmp ("-to", argv[c]) == 0)
      strcpy (argv[c], "-t");

  while (1) {
    c = getopt_long (argc, argv, "+?VqhveCt:c:w:K:W:u:p:x:X:mklLg:R:r:i:I:MEA", longopts, &option);

    if (c == -1 || c == EOF)
      break;

    switch (c) {
    case 't':                 /* timeout period */
      if (is_integer (optarg)) {
        timeout_interval = atoi (optarg);
        break;
      }
      else {
        usage2 (_("Timeout interval must be a positive integer"), optarg);
      }

    /* See comments for 'c' */
    case 'w':                 /* warning threshold */
      if (strstr(optarg, "%")) {
        if (*optarg == '@') {
          warn_freespace_percent = optarg;
        } else {
          xasprintf(&warn_freespace_percent, "@%s", optarg);
        }
      } else {
        if (*optarg == '@') {
          warn_freespace_units = optarg;
        } else {
          xasprintf(&warn_freespace_units, "@%s", optarg);
        }
      }
      break;

    /* Awful mistake where the range values do not make sense. Normally,
       you alert if the value is within the range, but since we are using
       freespace, we have to alert if outside the range. Thus we artifically
       force @ at the beginning of the range, so that it is backwards compatible
    */
    case 'c':                 /* critical threshold */
      if (strstr(optarg, "%")) {
        if (*optarg == '@') {
          crit_freespace_percent = optarg;
        } else {
          xasprintf(&crit_freespace_percent, "@%s", optarg);
        }
      } else {
        if (*optarg == '@') {
          crit_freespace_units = optarg;
        } else {
          xasprintf(&crit_freespace_units, "@%s", optarg);
        }
      }
      break;

    case 'W':			/* warning inode threshold */
      if (*optarg == '@') {
        warn_freeinodes_percent = optarg;
      } else {
        xasprintf(&warn_freeinodes_percent, "@%s", optarg);
      }
      break;
    case 'K':			/* critical inode threshold */
      if (*optarg == '@') {
        crit_freeinodes_percent = optarg;
      } else {
        xasprintf(&crit_freeinodes_percent, "@%s", optarg);
      }
      break;
    case 'u':
      if (units)
        free(units);
      if (! strcmp (optarg, "bytes")) {
        mult = (uintmax_t)1;
        units = strdup ("B");
      } else if (! strcmp (optarg, "kB")) {
        mult = (uintmax_t)1024;
        units = strdup ("kB");
      } else if (! strcmp (optarg, "MB")) {
        mult = (uintmax_t)1024 * 1024;
        units = strdup ("MB");
      } else if (! strcmp (optarg, "GB")) {
        mult = (uintmax_t)1024 * 1024 * 1024;
        units = strdup ("GB");
      } else if (! strcmp (optarg, "TB")) {
        mult = (uintmax_t)1024 * 1024 * 1024 * 1024;
        units = strdup ("TB");
      } else {
        die (STATE_UNKNOWN, _("unit type %s not known\n"), optarg);
      }
      if (units == NULL)
        die (STATE_UNKNOWN, _("failed allocating storage for '%s'\n"), "units");
      break;
    case 'k': /* display mountpoint */
      mult = 1024;
      if (units)
        free(units);
      units = strdup ("kB");
      break;
    case 'm': /* display mountpoint */
      mult = 1024 * 1024;
      if (units)
        free(units);
      units = strdup ("MB");
      break;
    case 'L':
      stat_remote_fs = 1;
    case 'l':
      show_local_fs = 1;
      break;
    case 'p':                 /* select path */
      if (! (warn_freespace_units || crit_freespace_units || warn_freespace_percent ||
             crit_freespace_percent || warn_usedspace_units || crit_usedspace_units ||
             warn_usedspace_percent || crit_usedspace_percent || warn_usedinodes_percent ||
             crit_usedinodes_percent || warn_freeinodes_percent || crit_freeinodes_percent )) {
        die (STATE_UNKNOWN, "DISK %s: %s", _("UNKNOWN"), _("Must set a threshold value before using -p\n"));
      }

      /* add parameter if not found. overwrite thresholds if path has already been added  */
      if (! (se = np_find_parameter(path_select_list, optarg))) {
          se = np_add_parameter(&path_select_list, optarg);
      }
      se->group = group;
      set_all_thresholds(se);

      /* With autofs, it is required to stat() the path before re-populating the mount_list */
      stat_path(se);
      /* NB: We can't free the old mount_list "just like that": both list pointers and struct
       * pointers are copied around. One of the reason it wasn't done yet is that other parts
       * of check_disk need the same kind of cleanup so it'd better be done as a whole */
      mount_list = read_file_system_list (0);
      np_set_best_match(se, mount_list, exact_match);

      path_selected = TRUE;
      break;
    case 'x':                 /* exclude path or partition */
      np_add_name(&dp_exclude_list, optarg);
      break;
    case 'X':                 /* exclude file system type */
      np_add_name(&fs_exclude_list, optarg);
      break;
    case 'v':                 /* verbose */
      verbose++;
      break;
    case 'q':                 /* TODO: this function should eventually go away (removed 2007-09-20) */
      /* verbose--; **replaced by line below**. -q was only a broken way of implementing -e */
      erronly = TRUE;
      break;
    case 'e':
      erronly = TRUE;
      break;
    case 'E':
      if (path_selected)
        die (STATE_UNKNOWN, "DISK %s: %s", _("UNKNOWN"), _("Must set -E before selecting paths\n"));
      exact_match = TRUE;
      break;
    case 'g':
      if (path_selected)
        die (STATE_UNKNOWN, "DISK %s: %s", _("UNKNOWN"), _("Must set group value before selecting paths\n"));
      group = optarg;
      break;
    case 'I':
      cflags |= REG_ICASE;
    case 'i':
      if (!path_selected)
        die (STATE_UNKNOWN, "DISK %s: %s\n", _("UNKNOWN"), _("Paths need to be selected before using -i/-I. Use -A to select all paths explicitly"));
      err = regcomp(&re, optarg, cflags);
      if (err != 0) {
        regerror (err, &re, errbuf, MAX_INPUT_BUFFER);
        die (STATE_UNKNOWN, "DISK %s: %s - %s\n",_("UNKNOWN"), _("Could not compile regular expression"), errbuf);
      }

      temp_list = path_select_list;

      previous = NULL;
      while (temp_list) {
        if (temp_list->best_match) {
          if (np_regex_match_mount_entry(temp_list->best_match, &re)) {

              if (verbose >=3)
                printf("ignoring %s matching regex\n", temp_list->name);

              temp_list = np_del_parameter(temp_list, previous);
              /* pointer to first element needs to be updated if first item gets deleted */
              if (previous == NULL)
                path_select_list = temp_list;
          } else {
            previous = temp_list;
            temp_list = temp_list->name_next;
          }
        } else {
          previous = temp_list;
          temp_list = temp_list->name_next;
        }
      }


      cflags = default_cflags;
      break;

    case 'A':
      optarg = strdup(".*");
    case 'R':
      cflags |= REG_ICASE;
    case 'r':
      if (! (warn_freespace_units || crit_freespace_units || warn_freespace_percent ||
             crit_freespace_percent || warn_usedspace_units || crit_usedspace_units ||
             warn_usedspace_percent || crit_usedspace_percent || warn_usedinodes_percent ||
             crit_usedinodes_percent || warn_freeinodes_percent || crit_freeinodes_percent )) {
        die (STATE_UNKNOWN, "DISK %s: %s", _("UNKNOWN"), _("Must set a threshold value before using -r/-R\n"));
      }

      err = regcomp(&re, optarg, cflags);
      if (err != 0) {
        regerror (err, &re, errbuf, MAX_INPUT_BUFFER);
        die (STATE_UNKNOWN, "DISK %s: %s - %s\n",_("UNKNOWN"), _("Could not compile regular expression"), errbuf);
      }

      for (me = mount_list; me; me = me->me_next) {
        if (np_regex_match_mount_entry(me, &re)) {
          fnd = TRUE;
          if (verbose >= 3)
            printf("%s %s matching expression %s\n", me->me_devname, me->me_mountdir, optarg);

          /* add parameter if not found. overwrite thresholds if path has already been added  */
          if (! (se = np_find_parameter(path_select_list, me->me_mountdir))) {
            se = np_add_parameter(&path_select_list, me->me_mountdir);
          }
          se->group = group;
          set_all_thresholds(se);
        }
      }

      if (!fnd)
        die (STATE_UNKNOWN, "DISK %s: %s - %s\n",_("UNKNOWN"),
            _("Regular expression did not match any path or disk"), optarg);

      fnd = FALSE;
      path_selected = TRUE;
      np_set_best_match(path_select_list, mount_list, exact_match);
      cflags = default_cflags;

      break;
    case 'M': /* display mountpoint */
      display_mntp = TRUE;
      break;
    case 'C':
       /* add all mount entries to path_select list if no partitions have been explicitly defined using -p */
       if (path_selected == FALSE) {
         struct parameter_list *path;
         for (me = mount_list; me; me = me->me_next) {
           if (! (path = np_find_parameter(path_select_list, me->me_mountdir)))
             path = np_add_parameter(&path_select_list, me->me_mountdir);
           path->best_match = me;
           path->group = group;
           set_all_thresholds(path);
         }
      }
      warn_freespace_units = NULL;
      crit_freespace_units = NULL;
      warn_usedspace_units = NULL;
      crit_usedspace_units = NULL;
      warn_freespace_percent = NULL;
      crit_freespace_percent = NULL;
      warn_usedspace_percent = NULL;
      crit_usedspace_percent = NULL;
      warn_usedinodes_percent = NULL;
      crit_usedinodes_percent = NULL;
      warn_freeinodes_percent = NULL;
      crit_freeinodes_percent = NULL;

      path_selected = FALSE;
      group = NULL;
      break;
    case 'V':                 /* version */
      print_revision (progname, NP_VERSION);
      exit (STATE_OK);
    case 'h':                 /* help */
      print_help ();
      exit (STATE_OK);
    case '?':                 /* help */
      usage (_("Unknown argument"));
    }
  }

  /* Support for "check_disk warn crit [fs]" with thresholds at used% level */
  c = optind;
  if (warn_usedspace_percent == NULL && argc > c && is_intnonneg (argv[c]))
    warn_usedspace_percent = argv[c++];

  if (crit_usedspace_percent == NULL && argc > c && is_intnonneg (argv[c]))
    crit_usedspace_percent = argv[c++];

  if (argc > c && path == NULL) {
    se = np_add_parameter(&path_select_list, strdup(argv[c++]));
    path_selected = TRUE;
    set_all_thresholds(se);
  }

  if (units == NULL) {
    units = strdup ("MB");
    mult = (uintmax_t)1024 * 1024;
  }

  return TRUE;
}
Beispiel #19
0
Datei: kill.c Projekt: jheiss/nn
void
enter_kill_file(group_header * gh, char *pattern, register flag_type flag, int days)
{
    FILE           *killf;
    register kill_list_entry *kl;
    regexp         *re;
    char           *str;

    str = copy_str(pattern);

    if ((flag & KILL_CASE_MATCH) == 0)
        fold_string(str);

    if (flag & KILL_ON_REGEXP) {
        re = regcomp(pattern);
        if (re == NULL)
            return;
    } else
        re = NULL;

    killf = open_file(relative(nn_directory, KILL_FILE), OPEN_APPEND);
    if (killf == NULL) {
        msg("cannot create kill file");
        return;
    }
    if (days >= 0) {
        if (days == 0)
            days = 30;
        fprintf(killf, "%ld:", (long) (cur_time() + days DAYS));
    }
    if (gh)
        fputs(gh->group_name, killf);
    fputc(':', killf);

    if (flag & KILL_UNLESS_MATCH)
        fputc(EXT_KILL_UNLESS_MATCH, killf);
    if (flag & AUTO_KILL)
        fputc(EXT_AUTO_KILL, killf);
    if (flag & AUTO_SELECT)
        fputc(EXT_AUTO_SELECT, killf);
    if (flag & ON_FOLLOW_UP)
        fputc(EXT_ON_FOLLOW_UP, killf);
    if (flag & ON_NOT_FOLLOW_UP)
        fputc(EXT_ON_NOT_FOLLOW_UP, killf);
    if (flag & ON_ANY_REFERENCES)
        fputc(EXT_ON_ANY_REFERENCES, killf);
    if (flag & ON_SENDER)
        fputc(EXT_ON_SENDER, killf);
    if (flag & ON_SUBJECT)
        fputc(EXT_ON_SUBJECT, killf);
    if (flag & KILL_CASE_MATCH)
        fputc(EXT_KILL_CASE_MATCH, killf);
    if (flag & KILL_ON_REGEXP)
        fputc(EXT_KILL_ON_REGEXP, killf);
    fputc(':', killf);

    fput_pattern(pattern, killf);
    fputc(NL, killf);

    fclose(killf);
    rm_kill_file();

    kl = newobj(kill_list_entry, 1);

    latest_kl_entry.kill_pattern = kl->kill_pattern = str;
    latest_kl_entry.kill_regexp = kl->kill_regexp = re;
    latest_kl_entry.kill_flag = kl->kill_flag = flag;
    latest_kl_entry.next_kill = NULL;

    if (gh) {
        kl->next_kill = (kill_list_entry *) (gh->kill_list);
        gh->kill_list = (char *) kl;
    } else {
        kl->next_kill = global_kill_list;
        global_kill_list = kl;
    }
}
Beispiel #20
0
int
pkg_create_staged(const char *outdir, pkg_formats format, const char *rootdir,
    const char *md_dir, char *plist, bool old)
{
	struct pkg	*pkg = NULL;
	struct pkg_file	*file = NULL;
	struct pkg_dir	*dir = NULL;
	struct packing	*pkg_archive = NULL;
	char		*manifest = NULL;
	char		 arch[BUFSIZ];
	int		 ret = ENOMEM;
	int		 i, mfd;
	regex_t		 preg;
	regmatch_t	 pmatch[2];
	size_t		 size;
	struct pkg_manifest_key *keys = NULL;

	mfd = -1;

	pkg_debug(1, "Creating package from stage directory: '%s'", rootdir);

	if ((mfd = open(md_dir, O_DIRECTORY)) == -1) {
		pkg_emit_errno("open", md_dir);
		goto cleanup;
	}

	if(pkg_new(&pkg, old ? PKG_OLD_FILE : PKG_FILE) != EPKG_OK) {
		ret = EPKG_FATAL;
		goto cleanup;
	}

	pkg_manifest_keys_new(&keys);
	/* Load the manifest from the metadata directory */
	if ((ret = pkg_parse_manifest_fileat(mfd, pkg, "+MANIFEST", keys))
	    != EPKG_OK) {
		ret = EPKG_FATAL;
		goto cleanup;
	}

	/* if no descriptions provided then try to get it from a file */
	if (pkg->desc == NULL)
		pkg_load_from_file(mfd, pkg, PKG_DESC, "+DESC");

	/* if no message try to get it from a file */
	if (pkg->message == NULL)
		pkg_load_from_file(mfd, pkg, PKG_MESSAGE, "+DISPLAY");

	/* if no arch autodetermine it */
	if (pkg->abi == NULL) {
		pkg_get_myarch(arch, BUFSIZ);
		pkg->abi = strdup(arch);
	}

	for (i = 0; scripts[i] != NULL; i++) {
		if (faccessat(mfd, scripts[i], F_OK, 0) == 0)
			pkg_addscript_fileat(mfd, pkg, scripts[i]);
	}

	if (plist != NULL &&
	    ports_parse_plist(pkg, plist, rootdir) != EPKG_OK) {
		ret = EPKG_FATAL;
		goto cleanup;
	}

	if (pkg->www == NULL) {
		if (pkg->desc == NULL) {
			pkg_emit_error("No www or desc defined in manifest");
			ret = EPKG_FATAL;
			goto cleanup;
		}
		regcomp(&preg, "^WWW:[[:space:]]*(.*)$",
		    REG_EXTENDED|REG_ICASE|REG_NEWLINE);
		if (regexec(&preg, pkg->desc, 2, pmatch, 0) == 0) {
			size = pmatch[1].rm_eo - pmatch[1].rm_so;
			pkg->www = strndup(&pkg->desc[pmatch[1].rm_so], size);
		} else {
			pkg->www = strdup("UNKNOWN");
		}
		regfree(&preg);
	}

	/* Create the archive */
	pkg_archive = pkg_create_archive(outdir, pkg, format, 0);
	if (pkg_archive == NULL) {
		ret = EPKG_FATAL; /* XXX do better */
		goto cleanup;
	}

	/* XXX: autoplist support doesn't work right with meta-ports */
	if (0 && pkg_files(pkg, &file) != EPKG_OK &&
	    pkg_dirs(pkg, &dir) != EPKG_OK) {
		/* Now traverse the file directories, adding to the archive */
		packing_append_tree(pkg_archive, md_dir, NULL);
		packing_append_tree(pkg_archive, rootdir, "/");
	} else {
		pkg_create_from_dir(pkg, rootdir, pkg_archive);
	}

	ret = EPKG_OK;

cleanup:
	if (mfd != -1)
		close(mfd);
	free(pkg);
	free(manifest);
	pkg_manifest_keys_free(keys);
	if (ret == EPKG_OK)
		ret = packing_finish(pkg_archive);
	return (ret);
}
Beispiel #21
0
/* Parse all CLI arguments */
int options_parse(struct options_t **opt, int argc, char **argv, int error_check, char **optarg) {
    int c = 0;
    int itmp = 0;
#ifndef __FreeBSD__
    char *mask;
    regex_t regex;
    int reti;
#endif

    char *ctmp = NULL;

    /* If have read all arguments, exit and reset */
    if(getOptPos>=(argc-1)) {
        getOptPos=0;
        if(*optarg) {
            sfree((void *)&*optarg);
            *optarg = NULL;
        }
        return -1;
    } else {
        getOptPos++;
        /* Reserve enough memory to store all variables */
        longarg = realloc(longarg, 4);
        shortarg = realloc(shortarg, 2);
        *optarg = realloc(*optarg, 4);

        if(!longarg) {
            logprintf(LOG_ERR, "out of memory");
            exit(EXIT_FAILURE);
        }
        if(!shortarg) {
            logprintf(LOG_ERR, "out of memory");
            exit(EXIT_FAILURE);
        }
        if(!*optarg) {
            logprintf(LOG_ERR, "out of memory");
            exit(EXIT_FAILURE);
        }

        /* The memory to null */
        memset(*optarg, '\0', 4);
        memset(shortarg, '\0', 2);
        memset(longarg, '\0', 4);

        /* Check if the CLI character contains an equals to (=) sign.
           If it does, we have probably encountered a long argument */
        if(strchr(argv[getOptPos],'=')) {
            /* Copy all characters until the equals to sign.
               This will probably be the name of the argument */
            longarg = realloc(longarg, strcspn(argv[getOptPos],"=")+1);
            if(!longarg) {
                logprintf(LOG_ERR, "out of memory");
                exit(EXIT_FAILURE);
            }
            memset(longarg, '\0', strcspn(argv[getOptPos],"=")+1);
            memcpy(longarg, &argv[getOptPos][0], strcspn(argv[getOptPos],"="));

            /* Then copy everything after the equals sign.
               This will probably be the value of the argument */
            size_t i = strlen(&argv[getOptPos][strcspn(argv[getOptPos],"=")+1]);
            *optarg = realloc(*optarg, i+1);
            if(!*optarg) {
                logprintf(LOG_ERR, "out of memory");
                exit(EXIT_FAILURE);
            }
            memset(*optarg, '\0', i+1);
            memcpy(*optarg, &argv[getOptPos][strcspn(argv[getOptPos],"=")+1], i);
        } else {
            /* If the argument does not contain a equals sign.
               Store the argument to check later if it's a long argument */
            longarg = realloc(longarg, strlen(argv[getOptPos])+1);
            if(!longarg) {
                logprintf(LOG_ERR, "out of memory");
                exit(EXIT_FAILURE);
            }
            strcpy(longarg, argv[getOptPos]);
        }

        /* A short argument only contains of two characters.
           So only store the first two characters */
        shortarg = realloc(shortarg, strlen(argv[getOptPos])+1);
        if(!shortarg) {
            logprintf(LOG_ERR, "out of memory");
            exit(EXIT_FAILURE);
        }
        memset(shortarg, '\0', 3);
        strncpy(shortarg, argv[getOptPos], 2);

        /* Check if the short argument and the long argument are equal,
           then we probably encountered a short argument. Only store the
           identifier character. If there are more CLI characters
           after the current one, store it as the CLI value. However, only
           do this if the first character of the argument doesn't contain*/
        if(strcmp(longarg, shortarg) == 0 && (getOptPos+1)<argc && argv[getOptPos+1][0] != '-') {
            *optarg = realloc(*optarg, strlen(argv[getOptPos+1])+1);
            if(!*optarg) {
                logprintf(LOG_ERR, "out of memory");
                exit(EXIT_FAILURE);
            }
            strcpy(*optarg, argv[getOptPos+1]);
            c = shortarg[1];
            getOptPos++;
        } else {
            /* If the short argument and the long argument are not equal,
                then we probably encountered a long argument. */
            if(longarg[0] == '-' && longarg[1] == '-') {
                gctmp = realloc(gctmp, strlen(&longarg[2])+1);
                if(!gctmp) {
                    logprintf(LOG_ERR, "out of memory");
                    exit(EXIT_FAILURE);
                }
                strcpy(gctmp, &longarg[2]);

                /* Retrieve the short identifier for the long argument */
                if(options_get_id(opt, gctmp, &itmp) == 0) {
                    c = itmp;
                } else if(argv[getOptPos][0] == '-') {
                    c = shortarg[1];
                }
            } else if(argv[getOptPos][0] == '-' && strstr(shortarg, longarg) != 0) {
                c = shortarg[1];
            }
        }

        /* Check if the argument was expected */
        if(options_get_name(opt, c, &ctmp) != 0 && c > 0) {
            if(error_check == 1) {
                if(strcmp(longarg,shortarg) == 0) {
                    if(shortarg[0] == '-') {
                        logprintf(LOG_ERR, "invalid option -- '-%c'", c);
                    } else {
                        logprintf(LOG_ERR, "invalid option -- '%s'", longarg);
                    }
                } else {
                    logprintf(LOG_ERR, "invalid option -- '%s'", longarg);
                }
                goto gc;
            } else {
                return 0;
            }
            /* Check if an argument cannot have an argument that was set */
        } else if(strlen(*optarg) != 0 && options_get_argtype(opt, c, &itmp) == 0 && itmp == 1) {
            if(error_check == 1) {
                if(strcmp(longarg,shortarg) == 0) {
                    logprintf(LOG_ERR, "option '-%c' doesn't take an argument", c);
                } else {
                    logprintf(LOG_ERR, "option '%s' doesn't take an argument", longarg);
                }
                goto gc;
            } else {
                return 0;
            }
            /* Check if an argument required a value that wasn't set */
        } else if(strlen(*optarg) == 0 && options_get_argtype(opt, c, &itmp) == 0 && itmp == 2) {
            if(error_check == 1) {
                if(strcmp(longarg, shortarg) == 0) {
                    logprintf(LOG_ERR, "option '-%c' requires an argument", c);
                } else {
                    logprintf(LOG_ERR, "option '%s' requires an argument", longarg);
                }
                goto gc;
            } else {
                return 0;
            }
            /* Check if we have a valid argument */
        } else if(c == 0) {
            if(error_check == 1) {
                if(shortarg[0] == '-' && strstr(shortarg, longarg) != 0) {
                    logprintf(LOG_ERR, "invalid option -- '-%c'", c);
                } else {
                    logprintf(LOG_ERR, "invalid option -- '%s'", longarg);
                }
                goto gc;
            } else {
                return 0;
            }
        } else {
            /* If the argument didn't have a value, set it to 1 */
            if(strlen(*optarg) == 0) {
                options_set_value(opt, c, "1");
            } else {
#ifndef __FreeBSD__
                if(error_check != 2) {
                    /* If the argument has a regex mask, check if it passes */
                    if(options_get_mask(opt, c, &mask) == 0) {
                        reti = regcomp(&regex, mask, REG_EXTENDED);
                        if(reti) {
                            logprintf(LOG_ERR, "could not compile regex");
                            goto gc;
                        }
                        reti = regexec(&regex, *optarg, 0, NULL, 0);
                        if(reti == REG_NOMATCH || reti != 0) {
                            if(error_check == 1) {
                                if(shortarg[0] == '-') {
                                    logprintf(LOG_ERR, "invalid format -- '-%c'", c);
                                } else {
                                    logprintf(LOG_ERR, "invalid format -- '%s'", longarg);
                                }
                                logprintf(LOG_ERR, "requires %s", mask);
                            }
                            regfree(&regex);
                            goto gc;
                        }
                        regfree(&regex);
                    }
                }
#endif
                options_set_value(opt, c, *optarg);
            }
            return c;
        }
    }

gc:
    getOptPos=0;
    sfree((void *)&*optarg);

    return -2;
}
Beispiel #22
0
int hl_regex(const char *regex, const char **hl_lines, const char **tlines,
             const int length, char **cur_line, int *sel_line,
             int *sel_rline, int *sel_col_rbeg, int *sel_col_rend,
             int opt, int direction, int icase) {
    regex_t t;                   /* Regular expression */
    regmatch_t pmatch[1];        /* Indexes of matches */
    int i = 0, result = 0;
    char *local_cur_line;
    int success = 0;
    int offset =  0;
    int config_wrapscan = cgdbrc_get (CGDBRC_WRAPSCAN)->variant.int_val;

    if (tlines == NULL || tlines[0] == NULL ||
            cur_line == NULL || sel_line == NULL ||
            sel_rline == NULL || sel_col_rbeg == NULL || sel_col_rend == NULL )
        return -1;

    /* Clear last highlighted line */
    if ( *cur_line != NULL ) {
        free ( *cur_line);
        *cur_line=NULL;
    }

    /* If regex is empty, set current line to original line */
    if ( regex == NULL || *regex == '\0' ) {
        *sel_line = *sel_rline;
        return -2;
    }

    /* Compile the regular expression */
    if ( regcomp(&t, regex, REG_EXTENDED & (icase)?REG_ICASE:0) != 0) {
        regfree(&t);
        return -3;
    }

    /* Forward search */
    if ( direction ) {
        int start = *sel_rline;
        int end   = length;
        offset = *sel_col_rend;
        while(!success) {
            for ( i = start; i < end; i++) {
                int local_cur_line_length;
                local_cur_line = (char *)tlines[i];
                local_cur_line_length = strlen ( local_cur_line );

                /* Add the position of the current line's last match */
                if ( i == *sel_rline )  {
                    if ( offset >= local_cur_line_length )
                        continue;
                    local_cur_line += offset;
                }

                /* Found a match */
                if ( ( result = regexec(&t, local_cur_line, 1, pmatch, 0)) == 0 ) {
                    success = 1;
                    break;
                }
            }

            if (success || start == 0 || !config_wrapscan) {
                break;
            }
            else {
                end = start;
                start = 0;
            }
        }

    } else { /* Reverse search */
        int j, pos;
        int start = *sel_rline;
        int end   = 0;
        offset = *sel_col_rbeg;

        /* Try each line */
        while(!success) {
            for ( i = start; i >= end; i--) {
                local_cur_line = (char *)tlines[i];
                pos = strlen(local_cur_line) - 1;
                if ( pos < 0 )
                    continue;

                if ( i == *sel_rline )
                    pos = offset - 1;

                /* Try each line, char by char starting from the end */
                for ( j = pos; j >= 0; j-- ) {
                    if ( ( result = regexec(&t, local_cur_line + j, 1, pmatch, 0)) == 0 ) {
                        if ( i == *sel_rline && pmatch[0].rm_so > pos - j)
                            continue;
                        /* Found a match */
                        success = 1;
                        offset = j;
                        break;
                    }
                }

                if ( success )
                    break;
            }

            if (success || start == length - 1 || !config_wrapscan) {
                break;
            }
            else {
                end = start;
                start = length - 1;
            }
        }

    }

    if ( success ) {
        /* The offset is 0 if the line was not on the original line */
        if ( direction && *sel_rline != i )
            offset = 0;

        /* If final match ( user hit enter ) make position perminant */
        if ( opt == 2 ) {
            *sel_col_rbeg = pmatch[0].rm_so + offset;
            *sel_col_rend = pmatch[0].rm_eo + offset;
            *sel_rline    = i;
        }

        /* Keep the new line as the selected line */
        *sel_line = i;

        /* If the match is not perminant then give cur_line highlighting */
        if ( opt != 2  && pmatch[0].rm_so != -1 && pmatch[0].rm_eo != -1 )
            *cur_line = highlight_line_segment(
                            hl_lines[i], pmatch[0].rm_so + offset, pmatch[0].rm_eo + offset);
    } else {
        /* On failure, the current line goes to the original line */
        *sel_line = *sel_rline;
    }

    regfree(&t);

    return success;
}
Beispiel #23
0
static int fixup_check_avp(void** param, int param_no)
{
	struct fis_param *ap;
	regex_t* re;
	char *s;

	s = (char*)*param;
	ap = 0;

	if (param_no==1)
	{
		ap = avpops_parse_pvar(s);
		if (ap==0)
		{
			LM_ERR(" unable to get pseudo-variable in P1\n");
			return E_OUT_OF_MEM;
		}
		/* attr name is mandatory */
		if (ap->u.sval.type==PVT_NULL)
		{
			LM_ERR("null pseudo-variable in P1\n");
			return E_UNSPEC;
		}
	} else if (param_no==2) {
		if ( (ap=parse_check_value(s))==0 )
		{
			LM_ERR(" failed to parse checked value \n");
			return E_UNSPEC;
		}
		/* if REGEXP op -> compile the expresion */
		if (ap->ops&AVPOPS_OP_RE)
		{
			if ( (ap->opd&AVPOPS_VAL_STR)==0 )
			{
				LM_ERR(" regexp operation requires string value\n");
				return E_UNSPEC;
			}
			re = pkg_malloc(sizeof(regex_t));
			if (re==0)
			{
				LM_ERR(" no more pkg mem\n");
				return E_OUT_OF_MEM;
			}
			LM_DBG("compiling regexp <%.*s>\n", ap->u.s.len, ap->u.s.s);
			if (regcomp(re, ap->u.s.s,
						REG_EXTENDED|REG_ICASE|REG_NEWLINE))
			{
				pkg_free(re);
				LM_ERR("bad re <%.*s>\n", ap->u.s.len, ap->u.s.s);
				return E_BAD_RE;
			}
			/* free the string and link the regexp */
			// pkg_free(ap->sval.p.s);
			ap->u.s.s = (char*)re;
		} else if (ap->ops&AVPOPS_OP_FM) {
			if ( !( ap->opd&AVPOPS_VAL_PVAR ||
			(!(ap->opd&AVPOPS_VAL_PVAR) && ap->opd&AVPOPS_VAL_STR) ) )
			{
				LM_ERR(" fast_match operation requires string value or "
						"avp name/alias (%d/%d)\n",	ap->opd, ap->ops);
				return E_UNSPEC;
			}
		}
	}

	*param=(void*)ap;
	return 0;
}
Beispiel #24
0
/** @brief Read's log data for defined timerange and stores the entries into entry_list struct
 *  @param [out] entry_list returns a filled entry list of requested log data
 *  @param [in] filter_list a list of filters of type logfilter struct
 *  @param [out] error_text returns a error string in case of an error execpt on READLOG_ERROR_MEMORY
 *  @param [in] search_string a string you are searching for
 *		Set to NULL to disable search function
 *  @param [in] reverse this bool defines which order the log entries should return
 *  @param [in] ts_start defines the start timestamp for log entries
 *	@arg >=0 means unix timestamp
 *  @param [in] ts_end defines the end timestamp for log entries
 *	@arg >=0 means unix timestamp
 *  @return
 *	@retval READLOG_OK
 *	@retval READLOG_ERROR_WARNING
 *	@retval READLOG_ERROR_FATAL
 *	@retval READLOG_ERROR_MEMORY
 *	@retval READLOG_ERROR_FILTER
 *  @author Ricardo Bartels
 *
 *  This functions reads a  \c log_file and and try's (if set) to filter for a search string.
 *  This search string uses regular expressions. The reverse option defines if you want
 *  have your log entries returned in normal or revers order. Normal order for returning
 *  would be from the newest entry to the oldest. You can also set a time "window". This
 *  defines if you want to exclude entries which are outside of these "window". Then only
 *  entries will be returned which are between start and end. Very useful if user has all
 *  entries in one log file.
**/
int get_log_entries(logentry **entry_list, logfilter **filter_list, char **error_text, char *search_string, int reverse, time_t ts_start, time_t ts_end) {
	char *input = NULL;
	char *temp_buffer = NULL;
	char *search_regex = NULL;
	char log_file_name[MAX_FILENAME_LENGTH];
	char ts_buffer[16];
	int type = 0;
	int regex_i = 0, i = 0, len = 0;
	int file_num = 1;
	int file = 0;
	int in_range = FALSE;
	int return_val = READLOG_OK;
	int data_found = FALSE;
	int open_read_failed = FALSE;
	// this is roughly 10 years of log files on hourly rotation
	int num_max_log_files = 87600;
	short keep_entry = TRUE;
	time_t timestamp = 0L;
	time_t last_timestamp = 0L;
	mmapfile *thefile = NULL;
	logentry *temp_entry = NULL;
	logentry *last_entry = NULL;
	regex_t preg;
	logfilter *temp_filter;
	DIR *dirp;
	struct dirent *dptr;
	struct file_data files[num_max_log_files + 1];
#ifdef HAVE_ZLIB_H
	gzFile gzfile = NULL;
	char gz_buffer[MAX_COMMAND_BUFFER * 2];
#else
	read_gzip_logs = FALSE;
#endif

	/* empty error_text */
	if (*error_text != NULL)
		my_free(*error_text);

	/* bail out if one timestamp is negative */
	if (ts_start < 0 || ts_end < 0) {
		*error_text = strdup("start or end timestamp are invalid. Check submited date information");
		return READLOG_ERROR_FATAL;
	}

	/* check if search_string is set */
	if (search_string != NULL) {

		/* allocate for 3 extra chars, ^, $ and \0 */
		search_regex = malloc(sizeof(char) * (strlen(search_string) * 2 + 3));
		len = strlen(search_string);
		for (i = 0; i < len; i++, regex_i++) {
			if (search_string[i] == '*') {
				search_regex[regex_i++] = '.';
				search_regex[regex_i] = '*';
			} else
				search_regex[regex_i] = search_string[i];
		}

		search_regex[regex_i] = '\0';

		/* check and compile regex, return error on failure */
		if (regcomp(&preg, search_regex, REG_ICASE | REG_NOSUB) != 0) {
			regfree(&preg);
			my_free(search_regex);
			*error_text = strdup("It seems like that reagular expressions don't like what you searched for. Please change your search string.");
			return READLOG_ERROR_FATAL;
		}

		my_free(search_regex);
	}

	/* initialize file data array */
	for (i=0;i<=num_max_log_files;i++) {
		files[i].file_name = NULL;
	}

	/* try to open log_archive_path, return if it fails */
	if ((dirp=opendir(log_archive_path)) == NULL){

		if (search_string != NULL)
			regfree(&preg);

		asprintf(&temp_buffer, "Unable to open \"log_archive_path\" -> \"%s\"!!!", log_archive_path);
		*error_text = strdup(temp_buffer);
		my_free(temp_buffer);

		return READLOG_ERROR_FATAL;

	} else {

		/* read every dir entry */
		while ((dptr=readdir(dirp)) != NULL) {

			/* filter dir for icinga / nagios log files */
			if ((strncmp("icinga-",dptr->d_name,7) == 0 || strncmp("nagios-",dptr->d_name,7) == 0 ) &&
			    ((strstr(dptr->d_name, ".log") && strlen(dptr->d_name) == 24 ) ||
			    (read_gzip_logs == TRUE && strstr(dptr->d_name, ".log.gz") && strlen(dptr->d_name) == 27 ))) {
				if ( file_num <= num_max_log_files ) {
					files[file_num++].file_name = strdup(dptr->d_name);
				} else {
					asprintf(&temp_buffer, "The amount of log files in the archive directory exceeds the maximum of \"%d\" readable log files! Consider deleting old log files.", num_max_log_files);
					*error_text = strdup(temp_buffer);
					my_free(temp_buffer);
					return_val = READLOG_ERROR_WARNING;
					break;
				}
			}
		}
		closedir(dirp);
	}

	/* sort log files, newest first */
	qsort((void *)files, file_num, sizeof(struct file_data), sort_icinga_logfiles_by_name);

	/* define which log files to use */
	for (i=0; i< file_num; i++) {

		/* first log file is always the current log file */
		if (i == 0) {
			strncpy(log_file_name, log_file, sizeof(log_file_name) -1);
			log_file_name[sizeof(log_file_name)-1] = '\x0';

		/* return full path of logfile and store first timestamp of last file */
		} else {
			snprintf(log_file_name, sizeof(log_file_name) -1, "%s%s",log_archive_path, files[i].file_name);
			log_file_name[sizeof(log_file_name)-1] = '\x0';

			last_timestamp = timestamp;
		}

		/* free file entry and set to NULL. if valid file is found, entry gets refilled */
		my_free(files[i].file_name);

		/* we found data and we are out of range again, file must be older then ts_start. stop checking files */
		if (data_found == TRUE && in_range == FALSE)
			continue;

		/* try to open log file, or throw error and try next log file */
		open_read_failed = FALSE;
		if (read_gzip_logs == TRUE && strstr(log_file_name, ".log.gz")) {
#ifdef HAVE_ZLIB_H
			if ((gzfile = gzopen(log_file_name, "r")) == NULL)
#endif
				open_read_failed = TRUE;
		} else {
			if((file=open(log_file_name, O_RDONLY)) < -1)
				open_read_failed = TRUE;
		}
		if(open_read_failed == TRUE) {

			if (*error_text == NULL) {
				asprintf(&temp_buffer, "Unable to open log file \"%s\" !!!", log_file_name);
				*error_text = strdup(temp_buffer);
				my_free(temp_buffer);
			}

			return_val = READLOG_ERROR_WARNING;

			continue;
		}

		/* read first 16 bytes to get first timestamp, or throw error if data is not 16 bytes log (empty file) */
		open_read_failed = FALSE;
		if (read_gzip_logs == TRUE && strstr(log_file_name, ".log.gz")) {
#ifdef HAVE_ZLIB_H
			if(gzread(gzfile,ts_buffer,16) != 16)
#endif
				open_read_failed = TRUE;
		} else {
			if(read(file,ts_buffer,16) != 16)
				open_read_failed = TRUE;
		}
		if(open_read_failed == TRUE) {

			if (*error_text == NULL) {
				asprintf(&temp_buffer, "Log file \"%s\" invalid! No timestamp found within first 16 bytes!", log_file_name);
				*error_text = strdup(temp_buffer);
				my_free(temp_buffer);
			}

			return_val = READLOG_ERROR_WARNING;

#ifdef HAVE_ZLIB_H
			if (read_gzip_logs == TRUE && strstr(log_file_name, ".log.gz"))
				gzclose(gzfile);
			else
#endif
				close(file);
			continue;
		}

#ifdef HAVE_ZLIB_H
		if (read_gzip_logs == TRUE && strstr(log_file_name, ".log.gz"))
			gzclose(gzfile);
		else
#endif
			close(file);

		/* get first timestamp */
		temp_buffer = strtok(ts_buffer, "]");
		timestamp = (temp_buffer == NULL) ? 0L : strtoul(temp_buffer + 1, NULL, 10);


		/* if first (oldest) timestamp in file is newer then ts_end, skip file */
		if (timestamp > ts_end)
			continue;

		in_range = TRUE;

		/* the priviouse file holds range for ts_start */
		if (last_timestamp != 0L && last_timestamp < ts_start)
			in_range = FALSE;

		/* keep file if in range */
		if(in_range == TRUE) {
			files[i].file_name = strdup(log_file_name);
			data_found = TRUE;
		}
	}

	/* read all log files we found earlier in reverse order, starting with the oldest */
	for (i=file_num; i >= 0; i--) {

		/* if file name is empty try next file */
		if (files[i].file_name == NULL)
			continue;

		/* try to open log file */
		if (read_gzip_logs == TRUE && strstr(files[i].file_name, ".log.gz")) {
#ifdef HAVE_ZLIB_H
			if ((gzfile = gzopen(files[i].file_name, "r")) == NULL)
#endif
				continue;
		} else {
			if ((thefile = mmap_fopen(files[i].file_name)) == NULL)
				continue;
		}

		while (1) {

			/* free memory */
			my_free(input);

			if (read_gzip_logs == TRUE && strstr(files[i].file_name, ".log.gz")) {
#ifdef HAVE_ZLIB_H
				if ((gzgets(gzfile, gz_buffer, MAX_COMMAND_BUFFER * 2 + 1)) == NULL)
#endif
					break;
			} else {
				if ((input = mmap_fgets(thefile)) == NULL)
					break;
			}

#ifdef HAVE_ZLIB_H
			if (read_gzip_logs == TRUE && strstr(files[i].file_name, ".log.gz")) {
				gz_buffer[MAX_COMMAND_BUFFER * 2 - 1] = '\0';
				input = strdup(gz_buffer);
			}
#endif
			strip(input);

			if ((int)strlen(input) == 0)
				continue;

			/* get timestamp */
			temp_buffer = strtok(input, "]");

			if (temp_buffer == NULL)
				continue;

			timestamp = strtoul(temp_buffer + 1, NULL, 10);

			/* skip line if out of range */
			if ((ts_end >= 0 && timestamp > ts_end) || (ts_start >= 0 && timestamp < ts_start))
				continue;

			/* get log entry text */
			temp_buffer = strtok(NULL, "\n");

			if (temp_buffer == NULL)
				continue;

			/* if we search for something, check if it entry matches search_string */
			if (search_string != NULL) {
				if (regexec(&preg, temp_buffer, 0, NULL, 0) == REG_NOMATCH)
					continue;
			}

			/* categorize log entry */
			if (strstr(temp_buffer, " starting..."))
				type = LOGENTRY_STARTUP;
			else if (strstr(temp_buffer, " shutting down..."))
				type = LOGENTRY_SHUTDOWN;
			else if (strstr(temp_buffer, "Bailing out"))
				type = LOGENTRY_BAILOUT;
			else if (strstr(temp_buffer, " restarting..."))
				type = LOGENTRY_RESTART;
			else if (strstr(temp_buffer, "HOST ALERT:") && strstr(temp_buffer, ";DOWN;"))
				type = LOGENTRY_HOST_DOWN;
			else if (strstr(temp_buffer, "HOST ALERT:") && strstr(temp_buffer, ";UNREACHABLE;"))
				type = LOGENTRY_HOST_UNREACHABLE;
			else if (strstr(temp_buffer, "HOST ALERT:") && strstr(temp_buffer, ";RECOVERY;"))
				type = LOGENTRY_HOST_RECOVERY;
			else if (strstr(temp_buffer, "HOST ALERT:") && strstr(temp_buffer, ";UP;"))
				type = LOGENTRY_HOST_UP;
			else if (strstr(temp_buffer, "HOST NOTIFICATION:"))
				type = LOGENTRY_HOST_NOTIFICATION;
			else if (strstr(temp_buffer, "SERVICE ALERT:") && strstr(temp_buffer, ";CRITICAL;"))
				type = LOGENTRY_SERVICE_CRITICAL;
			else if (strstr(temp_buffer, "SERVICE ALERT:") && strstr(temp_buffer, ";WARNING;"))
				type = LOGENTRY_SERVICE_WARNING;
			else if (strstr(temp_buffer, "SERVICE ALERT:") && strstr(temp_buffer, ";UNKNOWN;"))
				type = LOGENTRY_SERVICE_UNKNOWN;
			else if (strstr(temp_buffer, "SERVICE ALERT:") && strstr(temp_buffer, ";RECOVERY;"))
				type = LOGENTRY_SERVICE_RECOVERY;
			else if (strstr(temp_buffer, "SERVICE ALERT:") && strstr(temp_buffer, ";OK;"))
				type = LOGENTRY_SERVICE_OK;
			else if (strstr(temp_buffer, "SERVICE NOTIFICATION:"))
				type = LOGENTRY_SERVICE_NOTIFICATION;
			else if (strstr(temp_buffer, "SERVICE EVENT HANDLER:"))
				type = LOGENTRY_SERVICE_EVENT_HANDLER;
			else if (strstr(temp_buffer, "HOST EVENT HANDLER:"))
				type = LOGENTRY_HOST_EVENT_HANDLER;
			else if (strstr(temp_buffer, "EXTERNAL COMMAND:"))
				type = LOGENTRY_EXTERNAL_COMMAND;
			else if (strstr(temp_buffer, "PASSIVE SERVICE CHECK:"))
				type = LOGENTRY_PASSIVE_SERVICE_CHECK;
			else if (strstr(temp_buffer, "PASSIVE HOST CHECK:"))
				type = LOGENTRY_PASSIVE_HOST_CHECK;
			else if (strstr(temp_buffer, "LOG ROTATION:"))
				type = LOGENTRY_LOG_ROTATION;
			else if (strstr(temp_buffer, "active mode..."))
				type = LOGENTRY_ACTIVE_MODE;
			else if (strstr(temp_buffer, "standby mode..."))
				type = LOGENTRY_STANDBY_MODE;
			else if (strstr(temp_buffer, "SERVICE FLAPPING ALERT:") && strstr(temp_buffer, ";STARTED;"))
				type = LOGENTRY_SERVICE_FLAPPING_STARTED;
			else if (strstr(temp_buffer, "SERVICE FLAPPING ALERT:") && strstr(temp_buffer, ";STOPPED;"))
				type = LOGENTRY_SERVICE_FLAPPING_STOPPED;
			else if (strstr(temp_buffer, "SERVICE FLAPPING ALERT:") && strstr(temp_buffer, ";DISABLED;"))
				type = LOGENTRY_SERVICE_FLAPPING_DISABLED;
			else if (strstr(temp_buffer, "HOST FLAPPING ALERT:") && strstr(temp_buffer, ";STARTED;"))
				type = LOGENTRY_HOST_FLAPPING_STARTED;
			else if (strstr(temp_buffer, "HOST FLAPPING ALERT:") && strstr(temp_buffer, ";STOPPED;"))
				type = LOGENTRY_HOST_FLAPPING_STOPPED;
			else if (strstr(temp_buffer, "HOST FLAPPING ALERT:") && strstr(temp_buffer, ";DISABLED;"))
				type = LOGENTRY_HOST_FLAPPING_DISABLED;
			else if (strstr(temp_buffer, "SERVICE DOWNTIME ALERT:") && strstr(temp_buffer, ";STARTED;"))
				type = LOGENTRY_SERVICE_DOWNTIME_STARTED;
			else if (strstr(temp_buffer, "SERVICE DOWNTIME ALERT:") && strstr(temp_buffer, ";STOPPED;"))
				type = LOGENTRY_SERVICE_DOWNTIME_STOPPED;
			else if (strstr(temp_buffer, "SERVICE DOWNTIME ALERT:") && strstr(temp_buffer, ";CANCELLED;"))
				type = LOGENTRY_SERVICE_DOWNTIME_CANCELLED;
			else if (strstr(temp_buffer, "HOST DOWNTIME ALERT:") && strstr(temp_buffer, ";STARTED;"))
				type = LOGENTRY_HOST_DOWNTIME_STARTED;
			else if (strstr(temp_buffer, "HOST DOWNTIME ALERT:") && strstr(temp_buffer, ";STOPPED;"))
				type = LOGENTRY_HOST_DOWNTIME_STOPPED;
			else if (strstr(temp_buffer, "HOST DOWNTIME ALERT:") && strstr(temp_buffer, ";CANCELLED;"))
				type = LOGENTRY_HOST_DOWNTIME_CANCELLED;
			else if (strstr(temp_buffer, "INITIAL SERVICE STATE:"))
				type = LOGENTRY_SERVICE_INITIAL_STATE;
			else if (strstr(temp_buffer, "INITIAL HOST STATE:"))
				type = LOGENTRY_HOST_INITIAL_STATE;
			else if (strstr(temp_buffer, "CURRENT SERVICE STATE:"))
				type = LOGENTRY_SERVICE_CURRENT_STATE;
			else if (strstr(temp_buffer, "CURRENT HOST STATE:"))
				type = LOGENTRY_HOST_CURRENT_STATE;
			else if (strstr(temp_buffer, "error executing command"))
				type = LOGENTRY_ERROR_COMMAND_EXECUTION;
			else if (strstr(temp_buffer, "idomod:"))
				type = LOGENTRY_IDOMOD;
			else if (strstr(temp_buffer, "npcdmod:"))
				type = LOGENTRY_NPCDMOD;
			else if (strstr(temp_buffer, "Auto-save of"))
				type = LOGENTRY_AUTOSAVE;
			else if (strstr(temp_buffer, "Warning:"))
				type = LOGENTRY_SYSTEM_WARNING;
			else
				type = LOGENTRY_UNDEFINED;

			/* apply filters */
			if (*filter_list != NULL) {
				keep_entry = FALSE;
				for (temp_filter = *filter_list; temp_filter != NULL; temp_filter = temp_filter->next) {
					if (temp_filter->include != 0) {
						if (temp_filter->include == type) {
							keep_entry = TRUE;
							break;
						}
					} else if (temp_filter->exclude != 0) {
						if (temp_filter->exclude == type) {
							keep_entry = FALSE;
							break;
						} else
							keep_entry = TRUE;
					}
				}
				if (keep_entry == FALSE)
					continue;
			}

			/* initialzie */
			/* allocate memory for a new log entry */
			temp_entry = (logentry *)malloc(sizeof(logentry));
			if (temp_entry == NULL) {

				mmap_fclose(thefile);
				return READLOG_ERROR_MEMORY;
			}

			temp_entry->timestamp = 0L;
			temp_entry->type = 0;
			temp_entry->entry_text = NULL;
			temp_entry->next = NULL;


			temp_entry->timestamp = timestamp;
			temp_entry->type = type;
			temp_entry->entry_text = strdup(temp_buffer);

			if (reverse == TRUE) {
				if (*entry_list == NULL) {
					*entry_list = temp_entry;
					last_entry = *entry_list;
				} else {
					last_entry->next = temp_entry;
					last_entry = temp_entry;
				}
			} else {
				temp_entry->next = *entry_list;
				*entry_list = temp_entry;
			}
		}

#ifdef HAVE_ZLIB_H
		if (read_gzip_logs == TRUE && strstr(files[i].file_name, ".log.gz"))
			gzclose(gzfile);
		else
#endif
			mmap_fclose(thefile);
	}

	for (i=0; i< file_num;i++)
		my_free(files[i].file_name);

	if (search_string != NULL)
		regfree(&preg);

	return return_val;
}
Beispiel #25
0
/******************************************************************************
 * This function attempts to parse the sequence name from the
 * current sequence header. The sequence name is the string up to the first
 * white space in the sequence header.
 *
 * Returns TRUE if it was able to genomic coordinates, FALSE otherwise.
 *****************************************************************************/
static BOOLEAN_T parse_seq_name(
  SEQ_READER_FROM_FASTA_T *fasta_reader
) {

  #define NUM_SUBMATCHES 2
  #define ERROR_MESSAGE_SIZE 100
  #define BUFFER_SIZE 512

  static BOOLEAN_T first_time = TRUE;
  static regex_t ucsc_header_regex;
  static regmatch_t matches[NUM_SUBMATCHES];

  char error_message[ERROR_MESSAGE_SIZE];
  int status = 0;

  if (first_time == TRUE) {
    // Initialize regular express for extracting chromsome coordinates;
    // Expected format is based on fastaFromBed name:start-stop[(+|-)][_id]
    // e.g., ">chr1:1000-1010(-)_xyz"
    char *regexp_str = fasta_reader->parse_genomic_coord ?
      "([^[:space:]:]+)[[:space:]]*" : "([^[:space:]]+)[[:space:]]*";
    status = regcomp(
      &ucsc_header_regex,
      regexp_str,
      REG_EXTENDED | REG_ICASE | REG_NEWLINE
    );

    if (status != 0) {
      regerror(status, &ucsc_header_regex, error_message, ERROR_MESSAGE_SIZE);
      die(
        "Error while intitializing regular expression\n"
        "for parsing sequence name from FASTA header: %s\n", 
        error_message
      );
    }

    first_time = FALSE;
  }

  BOOLEAN_T found_name = FALSE;
  char* header = fasta_reader->sequence_header;
  status = regexec(
    &ucsc_header_regex, 
    header,
    NUM_SUBMATCHES, 
    matches, 
    0
  );
  if(!status) {
    // The sequence header contains genomic coordinates
    found_name = TRUE;

    // Copy sequence name to reader
    char buffer[BUFFER_SIZE];
    int name_len = matches[1].rm_eo - matches[1].rm_so;
    strncpy(buffer, header + matches[1].rm_so, name_len);
    buffer[name_len] = 0;
    if (fasta_reader->sequence_name) {
      myfree(fasta_reader->sequence_name);
      fasta_reader->sequence_name = NULL;
    }
    fasta_reader->sequence_name = strdup(buffer);
    if (fasta_reader->sequence_name == NULL) {
      die("Unable to allocate memory while parsing sequence header.\n");
    }
    fasta_reader->sequence_name_len = name_len;
  }
  else if(status != REG_NOMATCH ){
    regerror(status, &ucsc_header_regex, error_message, 100);
    die("Error trying to parse name from sequence header: %s\n"
        "error message is %s\n",
        header, 
        error_message
    );
  }
  else {
    found_name = FALSE;
  }

  return found_name;

  #undef NUM_SUBMATCHES
  #undef ERROR_MESSAGE_SIZE
  #undef BUFFER_SIZE
}
Beispiel #26
0
void cmd_fxp(int argc, char **argv)
{
	list *gl;
	listitem *fxp_tmp = 0;
	char *logfile = 0;
	char *fxp_output = 0;
#ifdef HAVE_REGEX
	int ret;
	char fxp_rx_errbuf[129];
#endif
	int c, opt = FXP_VERBOSE;
	struct option longopts[] = {
		{"append", no_argument, 0, 'a'},
		{"delete-after", no_argument, 0, 'D'},
		{"dir-mask", required_argument, 0, '3'},
#ifdef HAVE_REGEX
		{"dir-rx-mask", required_argument, 0, '4'},
#endif
		{"force", no_argument, 0, 'f'},
    {"force-newer", no_argument, 0, 'F'},
		{"nohup", no_argument, 0, 'H'},
		{"interactive", no_argument, 0, 'i'},
		{"logfile", required_argument, 0, 'L'},
		{"mask", required_argument, 0, 'm'},
#ifdef HAVE_REGEX
		{"rx-mask", required_argument, 0, 'M'},
#endif
		{"newer", no_argument, 0, 'n'},
		{"output", required_argument, 0, 'o'},
		{"preserve", no_argument, 0, 'p'},
		{"parents", no_argument, 0, 'P'},
		{"quiet", no_argument, 0, 'q'},
		{"recursive", no_argument, 0, 'r'},
		{"resume", no_argument, 0, 'R'},
		{"skip-existing", no_argument, 0, 's'},
		{"tagged", no_argument, 0, 't'},
		{"target", required_argument, 0, 'T'},
		{"type", required_argument, 0, '1'},
		{"unique", no_argument, 0, 'u'},
		{"verbose", no_argument, 0, 'v'},
		{"help", no_argument, 0, 'h'},
		{0, 0, 0, 0}
	};

	if(fxp_glob_mask) {
		free(fxp_glob_mask);
		fxp_glob_mask = 0;
	}
	if(fxp_dir_glob_mask) {
		free(fxp_dir_glob_mask);
		fxp_dir_glob_mask = 0;
	}
#ifdef HAVE_REGEX
	if(fxp_rx_mask_set) {
		fxp_rx_mask_set = 0;
	}
	if(fxp_dir_rx_mask_set) {
		regfree(&fxp_dir_rx_mask);
		fxp_dir_rx_mask_set = 0;
	}
#endif

	if(list_numitem(gvFtpList) == 2) {
		fxp_tmp = gvFtpList->first;
		if(fxp_tmp->data == ftp)
			fxp_target = fxp_tmp->next->data;
		else
			fxp_target = fxp_tmp->data;
	} else
		fxp_target = 0;

	fxp_skip_empty = false;

	optind = 0; /* force getopt() to re-initialize */
	while((c=getopt_long(argc, argv, "aDefHiL:M:no:pPqrRstT:uvh",
						 longopts, 0)) != EOF)
		{
			switch(c) {
			case 'a': /* --append */
				opt |= FXP_APPEND;
				break;
			case 'D': /* --delete-after */
				opt |= FXP_DELETE_AFTER;
				break;
			case 'f': /* --force */
				opt |= FXP_FORCE;
				break;
      case 'F':
        opt |= FXP_FORCE_NEWER;
        break;
			   case 'e': /* --skip-empty */
				  opt |= FXP_SKIP_EMPTY;
				  fxp_skip_empty = true;
				  break;
			case '3': /* --dir-mask=GLOB */
				free(fxp_dir_glob_mask);
				fxp_dir_glob_mask = xstrdup(optarg);
				unquote(fxp_dir_glob_mask);
				break;
#ifdef HAVE_REGEX
			case '4': /* --dir-rx-mask=REGEXP */
				if(fxp_dir_rx_mask_set) {
					regfree(&fxp_dir_rx_mask);
					fxp_dir_rx_mask_set = false;
				}
				unquote(optarg);
				ret = regcomp(&fxp_dir_rx_mask, optarg, REG_EXTENDED);
				if(ret != 0) {
					regerror(ret, &fxp_dir_rx_mask, fxp_rx_errbuf, 128);
					ftp_err(_("Regexp '%s' failed: %s\n"),
							optarg, fxp_rx_errbuf);
					return;
				} else
					fxp_dir_rx_mask_set = true;
				break;
#endif
			case 'H': /* --nohup */
				opt |= FXP_NOHUP;
				break;
			case 'i': /* --interactive */
				opt |= FXP_INTERACTIVE;
				break;
			case 'L': /* --logfile=FILE */
				free(logfile);
				logfile = xstrdup(optarg);
				unquote(logfile);
				break;
			case 'm': /* --mask=GLOB */
				free(fxp_glob_mask);
				fxp_glob_mask = xstrdup(optarg);
				unquote(fxp_glob_mask);
				break;
#ifdef HAVE_REGEX
			case 'M': /* --rx-mask=REGEXP */
				if(fxp_rx_mask_set) {
					regfree(&fxp_rx_mask);
					fxp_rx_mask_set = false;
				}

				unquote(optarg);
				ret = regcomp(&fxp_rx_mask, optarg, REG_EXTENDED);
				if(ret != 0) {
					regerror(ret, &fxp_rx_mask, fxp_rx_errbuf, 128);
					ftp_err(_("Regexp '%s' failed: %s\n"),
							optarg, fxp_rx_errbuf);
					return;
				} else
					fxp_rx_mask_set = true;
				break;
#endif
			case 'n': /* --newer */
				opt |= FXP_NEWER;
				break;
			case 'o': /* --output=DIRECTORY */
				if(fxp_target == 0) {
					printf(_("FxP target not set, use --target=NAME"
							 " (as first option)\n"));
					return;
				}
				fxp_output = tilde_expand_home(optarg, fxp_target->homedir);
				stripslash(fxp_output);
				unquote(fxp_output);
				break;
			case 'p': /* --preserve */
				opt |= FXP_PRESERVE;
				break;
			case 'P': /* --parents */
				opt |= FXP_PARENTS;
				break;
			case 'q': /* --quiet */
				opt &= ~FXP_VERBOSE;
				break;
			case 'r': /* --recursive */
				opt |= FXP_RECURSIVE;
				break;
			case 'R': /* --resume */
				opt |= FXP_RESUME;
				break;
			case 's':
				opt |= FXP_SKIP_EXISTING;
				break;
			case 't': /* --tagged */
				opt |= FXP_TAGGED;
				break;
			case '1': /* --type=[ascii|binary] */
				if(strncmp(optarg, "ascii", strlen(optarg)) == 0)
					opt |= FXP_ASCII;
				else if(strncmp(optarg, "binary", strlen(optarg)) == 0)
					opt |= FXP_BINARY;
				else {
					printf(_("Invalid option argument --type=%s\n"), optarg);
					return;
				}
				break;
			case 'T': /* --target=HOST */
				fxp_tmp = ftplist_search(optarg);
				if(!fxp_tmp)
					return;
				fxp_target = (Ftp *)fxp_tmp->data;
				break;
			case 'u': /* --unique */
				opt |= FXP_UNIQUE;
				break;
			case 'v': /* --verbose */
				opt |= FXP_VERBOSE;
				break;
			case 'h': /* --help */
				print_fxp_syntax();
				return;
			case '?':
			default:
				return;
			}
		}

	if(optind >= argc && !test(opt, FXP_TAGGED)) {
		minargs(optind);
		return;
	}

	need_connected();
	need_loggedin();

	if(fxp_target == 0) {
		ftp_err(_("No target specified, try '%s --help'"
				  " for more information\n"), argv[0]);
		return;
	}

#ifdef HAVE_LIBSSH
	if(ftp->session || fxp_target->session) {
		ftp_err("FxP for SSH connections no implemented\n");
		return;
	}
#endif

	gl = rglob_create();
	while(optind < argc) {
		stripslash(argv[optind]);
		if(rglob_glob(gl, argv[optind], true, true, fxp_exclude_func) == -1)
			fprintf(stderr, _("%s: no matches found\n"), argv[optind]);
		optind++;
	}
	if(list_numitem(gl) == 0 && !test(opt, FXP_TAGGED)) {
		rglob_destroy(gl);
		return;
	}
	if(test(opt, FXP_TAGGED)
	   && (!ftp->taglist || list_numitem(ftp->taglist) == 0))
	{
		printf(_("no tagged files\n"));
		if(list_numitem(gl) == 0) {
			rglob_destroy(gl);
			return;
		}
	}

	fxp_quit = false;
	fxp_batch = fxp_owbatch = fxp_delbatch = test(opt, FXP_FORCE);
	if(test(opt, FXP_FORCE))
		opt &= ~FXP_INTERACTIVE;

	if(fxp_output && !test(opt, FXP_RECURSIVE) && list_numitem(gl) +
	   (test(opt, FXP_TAGGED) ? list_numitem(ftp->taglist) : 0) == 1)
		{
			opt |= FXP_OUTPUT_FILE;
		}

	gvInTransfer = true;
	gvInterrupted = false;

	if(test(opt, FXP_NOHUP)) {
		int r = 0;
		pid_t pid = fork();

		if(pid == 0) {
			r = transfer_init_nohup(logfile);
			if(r != 0)
				exit(0);
		}

		if(r != 0)
			return;

		if(pid == 0) { /* child process */
			transfer_begin_nohup(argc, argv);

			if(!test(opt, FXP_FORCE) && !test(opt, FXP_RESUME))
				opt |= FXP_UNIQUE;
			opt |= FXP_FORCE;

			if(list_numitem(gl))
				fxpfiles(gl, opt, fxp_output);
			rglob_destroy(gl);

			if(ftp->taglist && test(opt, FXP_TAGGED))
				fxpfiles(ftp->taglist, opt, fxp_output);

			free(fxp_output);

			transfer_end_nohup();
		}
		if(pid == -1) {
			perror("fork()");
			return;
		}
		/* parent process */
		sleep(1);
		printf("%d\n", pid);
		input_save_history();
		gvars_destroy();
		reset_xterm_title();
		exit(0);
	}

	if(list_numitem(gl))
		fxpfiles(gl, opt, fxp_output);
	rglob_destroy(gl);

	if(ftp->taglist && test(opt, FXP_TAGGED))
		fxpfiles(ftp->taglist, opt, fxp_output);

	free(fxp_output);
	gvInTransfer = false;
}
Beispiel #27
0
void shellinit() {
  symtab = HashTableNewArrKey();
  nullstring = ASCIIZ("");
  regcomp(&varsubstpreg,"[^$]*(\\$[A-Za-z][A-Za-z0-9_.]*|\\$\\{[A-Za-z][A-Za-z0-9_.]*\\})?",REG_EXTENDED);
}
Beispiel #28
0
static int git_diff_driver_load(
	git_diff_driver **out, git_repository *repo, const char *driver_name)
{
	int error = 0;
	git_diff_driver_registry *reg;
	git_diff_driver *drv = NULL;
	size_t namelen = strlen(driver_name);
	khiter_t pos;
	git_config *cfg;
	git_buf name = GIT_BUF_INIT;
	const git_config_entry *ce;
	bool found_driver = false;

	if ((reg = git_repository_driver_registry(repo)) == NULL)
		return -1;

	pos = git_strmap_lookup_index(reg->drivers, driver_name);
	if (git_strmap_valid_index(reg->drivers, pos)) {
		*out = git_strmap_value_at(reg->drivers, pos);
		return 0;
	}

	drv = git__calloc(1, sizeof(git_diff_driver) + namelen + 1);
	GITERR_CHECK_ALLOC(drv);
	drv->type = DIFF_DRIVER_AUTO;
	memcpy(drv->name, driver_name, namelen);

	/* if you can't read config for repo, just use default driver */
	if (git_repository_config_snapshot(&cfg, repo) < 0) {
		giterr_clear();
		goto done;
	}

	if ((error = git_buf_printf(&name, "diff.%s.binary", driver_name)) < 0)
		goto done;

	switch (git_config__get_bool_force(cfg, name.ptr, -1)) {
	case true:
		/* if diff.<driver>.binary is true, just return the binary driver */
		*out = &global_drivers[DIFF_DRIVER_BINARY];
		goto done;
	case false:
		/* if diff.<driver>.binary is false, force binary checks off */
		/* but still may have custom function context patterns, etc. */
		drv->binary_flags = GIT_DIFF_FORCE_TEXT;
		found_driver = true;
		break;
	default:
		/* diff.<driver>.binary unspecified or "auto", so just continue */
		break;
	}

	/* TODO: warn if diff.<name>.command or diff.<name>.textconv are set */

	git_buf_truncate(&name, namelen + strlen("diff.."));
	git_buf_put(&name, "xfuncname", strlen("xfuncname"));
	if ((error = git_config_get_multivar_foreach(
			cfg, name.ptr, NULL, diff_driver_xfuncname, drv)) < 0) {
		if (error != GIT_ENOTFOUND)
			goto done;
		giterr_clear(); /* no diff.<driver>.xfuncname, so just continue */
	}

	git_buf_truncate(&name, namelen + strlen("diff.."));
	git_buf_put(&name, "funcname", strlen("funcname"));
	if ((error = git_config_get_multivar_foreach(
			cfg, name.ptr, NULL, diff_driver_funcname, drv)) < 0) {
		if (error != GIT_ENOTFOUND)
			goto done;
		giterr_clear(); /* no diff.<driver>.funcname, so just continue */
	}

	/* if we found any patterns, set driver type to use correct callback */
	if (git_array_size(drv->fn_patterns) > 0) {
		drv->type = DIFF_DRIVER_PATTERNLIST;
		found_driver = true;
	}

	git_buf_truncate(&name, namelen + strlen("diff.."));
	git_buf_put(&name, "wordregex", strlen("wordregex"));
	if ((error = git_config__lookup_entry(&ce, cfg, name.ptr, false)) < 0)
		goto done;
	if (!ce || !ce->value)
		/* no diff.<driver>.wordregex, so just continue */;
	else if (!(error = regcomp(&drv->word_pattern, ce->value, REG_EXTENDED)))
		found_driver = true;
	else {
		/* TODO: warn about bad regex instead of failure */
		error = giterr_set_regex(&drv->word_pattern, error);
		goto done;
	}

	/* TODO: look up diff.<driver>.algorithm to turn on minimal / patience
	 * diff in drv->other_flags
	 */

	/* if no driver config found at all, fall back on AUTO driver */
	if (!found_driver)
		goto done;

	/* store driver in registry */
	git_strmap_insert(reg->drivers, drv->name, drv, error);
	if (error < 0)
		goto done;
	error = 0;

	*out = drv;

done:
	git_buf_free(&name);
	git_config_free(cfg);

	if (!*out) {
		int error2 = git_diff_driver_builtin(out, reg, driver_name);
		if (!error)
			error = error2;
	}

	if (drv && drv != *out)
		git_diff_driver_free(drv);

	return error;
}
Beispiel #29
0
/*
 * Build expression list from search args
 */
static int
parse_expr(struct search_node **headp, char *argv[])
{
    struct search_node *sn, *newsn;
    char or = 0, not = 0, type, **av;

    sn = *headp;
    for (av = argv; *av; av++) {
	switch (av[0][0]) {
	case 'a': /* and (ignore) */
	    if (strncmp(*av, "and", strlen(*av)) != 0)
		goto bad;
	    continue;
	case 'o': /* or */
	    if (strncmp(*av, "or", strlen(*av)) != 0)
		goto bad;
	    or = 1;
	    continue;
	case '!': /* negate */
	    if (av[0][1] != '\0')
		goto bad;
	    not = 1;
	    continue;
	case 'c': /* command */
	    if (av[0][1] == '\0')
		errorx(1, "ambiguous expression \"%s\"", *av);
	    if (strncmp(*av, "cwd", strlen(*av)) == 0)
		type = ST_CWD;
	    else if (strncmp(*av, "command", strlen(*av)) == 0)
		type = ST_PATTERN;
	    else
		goto bad;
	    break;
	case 'f': /* from date */
	    if (strncmp(*av, "fromdate", strlen(*av)) != 0)
		goto bad;
	    type = ST_FROMDATE;
	    break;
	case 'g': /* runas group */
	    if (strncmp(*av, "group", strlen(*av)) != 0)
		goto bad;
	    type = ST_RUNASGROUP;
	    break;
	case 'r': /* runas user */
	    if (strncmp(*av, "runas", strlen(*av)) != 0)
		goto bad;
	    type = ST_RUNASUSER;
	    break;
	case 't': /* tty or to date */
	    if (av[0][1] == '\0')
		errorx(1, "ambiguous expression \"%s\"", *av);
	    if (strncmp(*av, "todate", strlen(*av)) == 0)
		type = ST_TODATE;
	    else if (strncmp(*av, "tty", strlen(*av)) == 0)
		type = ST_TTY;
	    else
		goto bad;
	    break;
	case 'u': /* user */
	    if (strncmp(*av, "user", strlen(*av)) != 0)
		goto bad;
	    type = ST_USER;
	    break;
	case '(': /* start sub-expression */
	    if (av[0][1] != '\0')
		goto bad;
	    if (stack_top + 1 == STACK_NODE_SIZE) {
		errorx(1, "too many parenthesized expressions, max %d",
		    STACK_NODE_SIZE);
	    }
	    node_stack[stack_top++] = sn;
	    type = ST_EXPR;
	    break;
	case ')': /* end sub-expression */
	    if (av[0][1] != '\0')
		goto bad;
	    /* pop */
	    if (--stack_top < 0)
		errorx(1, "unmatched ')' in expression");
	    if (node_stack[stack_top])
		sn->next = node_stack[stack_top]->next;
	    return av - argv + 1;
	bad:
	default:
	    errorx(1, "unknown search term \"%s\"", *av);
	    /* NOTREACHED */
	}

	/* Allocate new search node */
	newsn = emalloc(sizeof(*newsn));
	newsn->next = NULL;
	newsn->type = type;
	newsn->or = or;
	newsn->negated = not;
	if (type == ST_EXPR) {
	    av += parse_expr(&newsn->u.expr, av + 1);
	} else {
	    if (*(++av) == NULL)
		errorx(1, "%s requires an argument", av[-1]);
#ifdef HAVE_REGCOMP
	    if (type == ST_PATTERN) {
		if (regcomp(&newsn->u.cmdre, *av, REG_EXTENDED|REG_NOSUB) != 0)
		    errorx(1, "invalid regex: %s", *av);
	    } else
#endif
	    if (type == ST_TODATE || type == ST_FROMDATE) {
		newsn->u.tstamp = get_date(*av);
		if (newsn->u.tstamp == -1)
		    errorx(1, "could not parse date \"%s\"", *av);
	    } else {
		newsn->u.ptr = *av;
	    }
	}
	not = or = 0; /* reset state */
	if (sn)
	    sn->next = newsn;
	else
	    *headp = newsn;
	sn = newsn;
    }
    if (stack_top)
	errorx(1, "unmatched '(' in expression");
    if (or)
	errorx(1, "illegal trailing \"or\"");
    if (not)
	errorx(1, "illegal trailing \"!\"");

    return av - argv;
}
Beispiel #30
0
/*! \brief Parse DNS NAPTR record used in ENUM ---*/
static int parse_naptr(char *dst, int dstsize, char *tech, int techsize, unsigned char *answer, int len, char *naptrinput)
{
	char tech_return[80];
	unsigned char *oanswer = answer;
	char flags[512] = "";
	char services[512] = "";
	char *p;
	char regexp[512] = "";
	char repl[512] = "";
	char temp[512] = "";
	char delim;
	char *delim2;
	char *pattern, *subst, *d;
	int res;
	int regexp_len, size, backref;
	int d_len = sizeof(temp) - 1;
	regex_t preg;
	regmatch_t pmatch[9];

	tech_return[0] = '\0';

	dst[0] = '\0';

	if (len < sizeof(struct naptr)) {
		ast_log(LOG_WARNING, "NAPTR record length too short\n");
		return -1;
	}
	answer += sizeof(struct naptr);
	len -= sizeof(struct naptr);
	if ((res = parse_ie(flags, sizeof(flags) - 1, answer, len)) < 0) {
		ast_log(LOG_WARNING, "Failed to get flags from NAPTR record\n");
		return -1;
	} else {
		answer += res;
		len -= res;
	}
	if ((res = parse_ie(services, sizeof(services) - 1, answer, len)) < 0) {
		ast_log(LOG_WARNING, "Failed to get services from NAPTR record\n");
		return -1;
	} else {
		answer += res;
		len -= res;
	}
	if ((res = parse_ie(regexp, sizeof(regexp) - 1, answer, len)) < 0) {
		ast_log(LOG_WARNING, "Failed to get regexp from NAPTR record\n");
		return -1;
	} else {
		answer += res;
		len -= res;
	}

	if ((res = dn_expand(oanswer, answer + len, answer, repl, sizeof(repl) - 1)) < 0) {
		ast_log(LOG_WARNING, "Failed to expand hostname\n");
		return -1;
	}

	ast_debug(3, "NAPTR input='%s', flags='%s', services='%s', regexp='%s', repl='%s'\n",
		naptrinput, flags, services, regexp, repl);

	if (tolower(flags[0]) != 'u') {
		ast_log(LOG_WARNING, "NAPTR Flag must be 'U' or 'u'.\n");
		return -1;
	}

	p = strstr(services, "e2u+");
	if (p == NULL)
		p = strstr(services, "E2U+");
	if (p){
		p = p + 4;
		if (strchr(p, ':')){
			p = strchr(p, ':') + 1;
		}
		ast_copy_string(tech_return, p, sizeof(tech_return));
	} else {

		p = strstr(services, "+e2u");
		if (p == NULL)
			p = strstr(services, "+E2U");
		if (p) {
			*p = 0;
			p = strchr(services, ':');
			if (p)
				*p = 0;
			ast_copy_string(tech_return, services, sizeof(tech_return));
		}
	}

	/* DEDBUGGING STUB
	ast_copy_string(regexp, "!^\\+43(.*)$!\\[email protected]!", sizeof(regexp) - 1);
	*/

	regexp_len = strlen(regexp);
	if (regexp_len < 7) {
		ast_log(LOG_WARNING, "Regex too short to be meaningful.\n");
		return -1;
	}


	delim = regexp[0];
	delim2 = strchr(regexp + 1, delim);
	if ((delim2 == NULL) || (regexp[regexp_len - 1] != delim)) {
		ast_log(LOG_WARNING, "Regex delimiter error (on \"%s\").\n", regexp);
		return -1;
	}

	pattern = regexp + 1;
	*delim2 = 0;
	subst   = delim2 + 1;
	regexp[regexp_len - 1] = 0;

/*
 * now do the regex wizardry.
 */

	if (regcomp(&preg, pattern, REG_EXTENDED | REG_NEWLINE)) {
		ast_log(LOG_WARNING, "NAPTR Regex compilation error (regex = \"%s\").\n", regexp);
		return -1;
	}

	if (preg.re_nsub > 9) {
		ast_log(LOG_WARNING, "NAPTR Regex compilation error: too many subs.\n");
		regfree(&preg);
		return -1;
	}

	if (regexec(&preg, naptrinput, 9, pmatch, 0)) {
		ast_log(LOG_WARNING, "NAPTR Regex match failed.\n");
		regfree(&preg);
		return -1;
	}
	regfree(&preg);

	d = temp;
	d_len--;
	while (*subst && (d_len > 0)) {
		if ((subst[0] == '\\') && isdigit(subst[1]) && (pmatch[subst[1]-'0'].rm_so != -1)) {
			backref = subst[1]-'0';
			size = pmatch[backref].rm_eo - pmatch[backref].rm_so;
			if (size > d_len) {
				ast_log(LOG_WARNING, "Not enough space during NAPTR regex substitution.\n");
				return -1;
				}
			memcpy(d, naptrinput + pmatch[backref].rm_so, size);
			d += size;
			d_len -= size;
			subst += 2;
		} else if (isprint(*subst)) {
			*d++ = *subst++;
			d_len--;
		} else {
			ast_log(LOG_WARNING, "Error during regex substitution.\n");
			return -1;
		}
	}
	*d = 0;
	ast_copy_string(dst, temp, dstsize);
	dst[dstsize - 1] = '\0';

	if (*tech != '\0'){ /* check if it is requested NAPTR */
		if (!strncasecmp(tech, "ALL", techsize)){
			return 1; /* return or count any RR */
		}
		if (!strncasecmp(tech_return, tech, sizeof(tech_return)<techsize?sizeof(tech_return):techsize)){
			ast_copy_string(tech, tech_return, techsize);
			return 1; /* we got out RR */
		} else { /* go to the next RR in the DNS answer */
			return 0;
		}
	}

	/* tech was not specified, return first parsed RR */
	ast_copy_string(tech, tech_return, techsize);

	return 1;
}