Beispiel #1
0
void find(const bfs::path& cdb_path, const options& opt)
{
    config cfg = load_config(cdb_path / "config");

    const bfs::path cdb_root = cdb_path.parent_path();
    const bfs::path search_root = bfs::initial_path();

    std::size_t prefix_size = 0;
    std::string file_match;
    if(opt.m_options.count("-a") == 0 && search_root != cdb_root)
    {
        file_match = "^" + escape_regex(
            search_root.generic_string().substr(cdb_root.string().size() + 1) + "/") + ".*";
        prefix_size = search_root.string().size() - cdb_root.string().size();
    }

    file_lock lock(cdb_path / "lock");
    lock.lock_sharable();

    const char* find_regex_options =
        opt.m_options.count("-i") ? "i" : "";
    const char* file_regex_options =
        cfg.get_value("nocase-file-match") == "on" ? "i" : "";

    bool trim = cfg.get_value("find-trim-ws") == "on";
    unsigned thread_count = get_thread_count(cfg);
    unsigned buffer_count = get_buffer_count(thread_count);

    for(unsigned i = 0; i != opt.m_args.size(); ++i)
    {
        database_ptr db = open_database(cdb_path / "db");

        std::string pattern = opt.m_args[i];
        if(opt.m_options.count("-v"))
            pattern = escape_regex(pattern);

        mt_search mts(*db, trim, prefix_size, buffer_count);

        auto worker = [&]
        {
            mts.search_db(compile_regex(pattern, 0, find_regex_options),
                          compile_regex(file_match, 0, file_regex_options));
        };

        boost::thread_group workers;
        for(unsigned i = 0; i != thread_count-1; ++i)
            workers.create_thread(worker);

        worker();

        workers.join_all();
    }
}
Beispiel #2
0
int main(int arc, char *argv[])
{
    aes_digest_s *tmp;
    
    compile_regex("^(a|bc)*(hello(bob|(a|b)))?[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$");
    
    return 0;
    print_aesdigest(tmp = aes_encrypt(clear, sizeof(clear)-1, key));
    puts("\n");
    print_aesdigest(aes_decrypt(tmp->data, tmp->size, key));
    
    return 0;
    
    
    
    
    puts("Welcome to SA Bot");
    sha512_s digest;
    
    sha512(argv[1], strlen(argv[1]), &digest);

    print_sha512digest(&digest);
    //store_account();
    //authenticate();
    /*for(i = 0; i < N_TESTS; i++) {
        time = clock();
        sha512(argv[1], strlen(argv[1]), &digest);
        accum += (clock() - time);
    }
    
    print_digest(&digest);*/
   // printf("\naverage time: %f ticks\n", accum/(double)N_TESTS);
    
    exit(EXIT_SUCCESS);
}
char *create_file(const char *msg) {
	const int deep = 2;
	regex_t r;
	char filename[MAX_MESSAGE_LEN + 1];
	char org_length_str[MAX_LENGTH_NUM + 1];
	char content[MAX_MESSAGE_LEN + 1];

	const char * create_regex_text = "CREATE[[:blank:]]+([[:graph:]|[:blank:]]+)[[:blank:]]+([[:digit:]]+)[[:cntrl:]]+([[:graph:]|[:blank:]]+)";
	compile_regex(&r, create_regex_text);
	int retCode = match_regex(&r, msg, filename, org_length_str, content);
	regfree(&r);
	if (!retCode) {
		error(deep, "Message '%s' does not match to regex!", msg);
		return ANSWER_UNKOWN;
	}
	int orig_length = atoi(org_length_str);
	debug(deep, "Filename: %s", filename);
	debug(deep, "Length: %d", orig_length);
	debug(deep, "Content: %s", content);

	info(deep, "Create file %s", filename);
	int length = strlen(content) + 1;
	if (length != orig_length) {
		error(deep, "Message length is not correct! (length: %d, original: %d)", length, orig_length);
		return ANSWER_INVALID;
	}

	if (add_memory_file(filename, length, content)) {
		return ANSWER_SUCCESS_CREATE;
	} else {
		debug(deep, "File '%s' already exist", filename);
		return ANSWER_FAILED_CREATE;
	}
}
/* Match a string against the given regular expression.
 * Returns true on a successful match.
 */
bool d_match(dstr line, const char *regex)
{
   re_cache_t *re;
   TRexMatch match;
   int i;

   re = compile_regex(regex);

   if (!trex_search(re->reg, line, NULL, NULL)) {
      return false;
   }

   trex_getsubexp(re->reg, 0, &match);
   d_assignn(d_before_match, line, match.begin - line);
   d_assign(d_after_match, match.begin + match.len);

   for (i = 0; i < MAX_MATCH; i++) {
      if (trex_getsubexp(re->reg, i, &match)) {
         strncpy(d_submatches[i], match.begin, match.len);
         d_submatches[i][match.len] = '\0';
      }
      else {
         d_submatches[i][0] = '\0';
      }
   }

   return true;
}
Beispiel #5
0
int main(int argc, char *argv[])
{
	//dir count and list initialize
	dir_count=split(argv[1]);

    //traverse directories	
	DIR *check_dir;
	compile_regex();
	for (int i = 0; i < dir_count; ++i)
	{
		printf("%s",dir[i]);
		check_dir=opendir(dir[i]);
		if (check_dir==NULL) //if it's a file
		{
			printf("%s\n"," not a directory...");
			org_cp(i);
		}
		else { // in case of dir
			printf(" direcotry opened.\n");
			char command[100];
			sprintf(command,"orgcpy %s/%s",argv[2],dir[i]);
			printf("command :::\"%s\"\n",command );
			system(command);
			printf("......[%s orgcpy'ed].......\n",dir[i]);

			}	
	}
	
	printf("%s\n",argv[2]);
    return 0;
}
bool
NicInterfaceFilterRegex::match( const std::string& nic )
{
    if( is_regex_out_of_date() )
        compile_regex();
    
    return boost::regex_match( nic, *regex_ );
}
Beispiel #7
0
bool			ft_rcompile(t_regex *dst, t_sub pattern, t_regex_err *err)
{
	t_parse_reg		parser;

	parser = (t_parse_reg){pattern.str, pattern.length, 0, 0, NULL, 0, SUB0()};
	dst->reg = compile_regex(&parser);
	dst->capture_count = parser.capture_index;
	if (dst->reg == NULL && err != NULL)
		*err = (t_regex_err){parser.err_str, parser.err_offset};
	destroy_parser(&parser);
	return (BOOL_OF(dst->reg != NULL));
}
Beispiel #8
0
int
match(const char *text, const char *regex_str)
{
	// APP_DEBUG_FNAME;

	int out;
	regex_t reg;

	compile_regex(&reg, regex_str);
	out = (regexec(&reg, text, 0, NULL, 0) == 0);
	regfree(&reg);

	return (out);
}
void ExtractCondition_Clause(char *query)
{
    regex_t r;
    const char * regex_text;
    const char * find_text;
    
        regex_text = "([a-z|A-Z|]+)([=|<|>|&|!])([a-z|A-Z|0-9]+)";
        find_text = query;
    
    
    compile_regex(& r, regex_text);
    match_regex(& r, find_text);
    regfree (& r);
   
}
Beispiel #10
0
static int  mod_rewrite_request(calipso_request_t *request)
{
	regex_t r;
	TRACE("Start\n");

	compile_regex (&r, "^/dokuwiki/(data|conf|bin|inc)/");

	if ( match(&r, request->uri) ) {
		//test just deny
		calipso_reply_set_status(request->reply, HTTP_FORBIDDEN);
	} 

	regfree (& r);
	return CPO_OK;
}
Beispiel #11
0
int main(int argc, char ** argv)
{
    regex_t r;
    const char * regex_text;
    const char * find_text;
    if (argc != 3) {
        regex_text = "([[:digit:]]+)[^[:digit:]]+([[:digit:]]+)";
        find_text = "This 1 is nice 2 so 33 for 4254";
    }
    else {
        regex_text = argv[1];
        find_text = argv[2];
    }
    printf ("Trying to find '%s' in '%s'\n", regex_text, find_text);
    compile_regex(& r, regex_text);
    match_regex(& r, find_text);
    regfree (& r);
    return 0;
}
char *delete_file(const char *msg) {
	const int deep = 2;
	regex_t r;
	char filename[MAX_MESSAGE_LEN + 1];

	const char *delete_regex_text = "DELETE[[:blank:]]+([[:graph:]|[:blank:]]+)[[:cntrl:]]+";
	compile_regex(&r, delete_regex_text);
	int retCode = match_regex(&r, msg, filename, NULL, NULL);
	regfree(&r);
	if (!retCode) {
		error(deep, "Message '%s' does not match to regex!", msg);
		return ANSWER_UNKOWN;
	}

	info(deep, "Delete file %s", filename);
	if (delete_memory_file(filename)) {
		return ANSWER_SUCCESS_DELETE;
	}
	return ANSWER_FAILED_DELETE;
}
Beispiel #13
0
size_t
run_r(const char *regex_str, char *text)
{
	// APP_DEBUG_FNAME;

	if (!match(text, regex_str)) {
		ERR("!match(regex)");
		myabort();
	}

	regex_t reg;
	regmatch_t match;

	compile_regex(&reg, regex_str);
	regexec(&reg, text, 1, &match, 0);
	text[match.rm_eo - 1] = '\0';
	regfree(&reg);

	return (match.rm_eo);
}
Beispiel #14
0
int command_check(int argc, char **argv, int optind, int flags) {
  int ret = EXIT_SUCCESS;
  int i = optind-1;
  int  ci, ti;
  uint32_t compcrc, matchcrc;
  char *string;
  char results[9];
  regmatch_t rmatch;
  regex_t regex;

  while(argv[++i]) {
    if(check_access_flags_v(argv[i], F_OK | R_OK, 1) != 0) {
      log_info(argv[i], "Inaccessbile file, skipping.");
      continue;
    }
    string = get_basename((char*)argv[i]);
    compile_regex(&regex, crcregex, REG_ICASE);
    switch(regexec((const regex_t*) &regex, string, 1, &rmatch, 0)) {
      case 0:
        for(ci = rmatch.rm_so, ti = 0; ci < rmatch.rm_eo; ++ci)
            results[ti++] = string[ci];
        results[ti] = '\0';
        break;
      case REG_NOMATCH:
        log_info(argv[i], "Does not contain a hexstring, ignoring.");
        continue;
    }
    regfree(&regex);
    compcrc = compute_crc32(argv[i]);
    matchcrc = (uint32_t) strtol(results, NULL, 16);
    if(compcrc == matchcrc)
      log_success(argv[i], "OK");
    else {
      log_failure(argv[i], "Mismatch: %08X is really %08X", matchcrc, compcrc);
      ret = EXIT_FAILURE;
    }
  } /* while */

  return ret;
}
char *read_file(const char *msg) {
	const int deep = 2;
	regex_t r;
	char filename[MAX_MESSAGE_LEN + 1];
	char *returnValue;

	const char *read_regex_text = "READ[[:blank:]]+([[:graph:]|[:blank:]]+)[[:cntrl:]]+";
	compile_regex(&r, read_regex_text);
	int retCode = match_regex(&r, msg, filename, NULL, NULL);
	regfree(&r);
	if (!retCode) {
		error(deep, "Message '%s' does not match to regex!", msg);
		append_strings("", ANSWER_UNKOWN, &returnValue);
		return returnValue;
	}

	char *content;
	if (read_memory_file(filename, &content)) {
		debug(deep, "Content of file: %s", content);
		int length = strlen(content) + 1;
		char len_string[15];
		sprintf(len_string, " %d\n", length);
		char *rv_with_name;
		append_strings(ANSWER_SUCCESS_READ, filename, &rv_with_name);
		char *rv_with_len;
		append_strings(rv_with_name, len_string, &rv_with_len);
		free(rv_with_name);
		char *rv_with_content;
		append_strings(rv_with_len, content, &rv_with_content);
		free(rv_with_len);
		append_strings(rv_with_content, "\n", &returnValue);
		free(rv_with_content);
		free(content);
	} else {
		append_strings("", ANSWER_FAILED_READ, &returnValue);
	}

	return returnValue;
}
char *list_files(const char *msg) {
	const int deep = 2;
	regex_t r;
	char *rv;

	const char *list_regex_text = "LIST[[:cntrl:]]+";
	compile_regex(&r, list_regex_text);
	int retCode = match_regex(&r, msg, NULL, NULL, NULL);
	regfree(&r);
	if (!retCode) {
		error(deep, "Message '%s' does not match to regex!", msg);
		append_strings("", ANSWER_UNKOWN, &rv);
		return rv;
	}

	info(deep, "List files");
	char *file_list;
	int file_counter = list_memory_file(&file_list);

	char str[15];
	sprintf(str, "%d", file_counter);
	char *rv_wit_num;
	append_strings(ANSWER_SUCCESS_LIST, str, &rv_wit_num);
	char *rv_first_line;
	append_strings(rv_wit_num, "\n", &rv_first_line);
	free(rv_wit_num);
	if (file_counter > 0) {
		char *rv_with_list;
		append_strings(rv_first_line, file_list, &rv_with_list);
		free(rv_first_line);
		append_strings(rv_with_list, "\n", &rv);
		free(rv_with_list);
	} else {
		rv = rv_first_line;
	}

	free(file_list);
	return rv;
}
Beispiel #17
0
static const char *
filter_querystring(struct filter_context *context)
{
	const char *uri = context->uri;
	const char *query_string;
	const char *filtered_uri;

	if (uri == NULL) {
		return NULL;
	}

	query_string = strchr(uri, '?');

	if (query_string == NULL) {
		return uri;
	}

	if (query_string[1] == '\0') {
		return truncate_querystring(context->ws, uri, query_string);
	}

	if (context->type == regfilter) {
		void *re = compile_regex(context->params.regfilter.regex);
		if (re == NULL) {
			return uri;
		}
		context->params.regfilter.re = re;
	}

	context->query_string = query_string;
	filtered_uri = apply_filter(context);

	if (context->type == regfilter) {
		VRT_re_fini(context->params.regfilter.re);
	}

	return filtered_uri;
}
Beispiel #18
0
int do_restore_server(const char *basedir, enum action act, const char *client, int srestore, char **dir_for_notify, struct cntr *p1cntr, struct cntr *cntr, struct config *cconf)
{
	int a=0;
	int i=0;
	int ret=0;
	int found=0;
	struct bu *arr=NULL;
	unsigned long index=0;
	char *tmppath1=NULL;
	char *tmppath2=NULL;
	regex_t *regex=NULL;

	logp("in do_restore\n");

	if(compile_regex(&regex, cconf->regex)) return -1;

	if(!(tmppath1=prepend_s(basedir, "tmp1", strlen("tmp1")))
	  || !(tmppath2=prepend_s(basedir, "tmp2", strlen("tmp2"))))
	{
		if(tmppath1) free(tmppath1);
		if(regex) { regfree(regex); free(regex); }
		return -1;
	}

	if(get_current_backups(basedir, &arr, &a, 1))
	{
		if(tmppath1) free(tmppath1);
		if(tmppath2) free(tmppath2);
		if(regex) { regfree(regex); free(regex); }
		return -1;
	}

	if(!(index=strtoul(cconf->backup, NULL, 10)) && a>0)
	{
		// No backup specified, do the most recent.
		ret=restore_manifest(arr, a, a-1,
			tmppath1, tmppath2, regex, srestore, act, client,
			dir_for_notify,
			p1cntr, cntr, cconf);
		found=TRUE;
	}

	if(!found) for(i=0; i<a; i++)
	{
		if(!strcmp(arr[i].timestamp, cconf->backup)
			|| arr[i].index==index)
		{
			found=TRUE;
			//logp("got: %s\n", arr[i].path);
			ret|=restore_manifest(arr, a, i,
				tmppath1, tmppath2, regex,
				srestore, act, client, dir_for_notify,
				p1cntr, cntr, cconf);
			break;
		}
	}

	free_current_backups(&arr, a);

	if(!found)
	{
		logp("backup not found\n");
		async_write_str(CMD_ERROR, "backup not found");
		ret=-1;
	}
	if(tmppath1)
	{
		unlink(tmppath1);
		free(tmppath1);
	}
	if(tmppath2)
	{
		unlink(tmppath2);
		free(tmppath2);
	}
	if(regex)
	{
		regfree(regex);
		free(regex);
	}
	return ret;
}
Beispiel #19
0
void
substitute(const char *text, struct list *variables, char *substitued)
{
	APP_DEBUG_FNAME;

	regex_t reg;
	regmatch_t match;
	char *regstr;	// stored regexp '\$VAR'
	size_t n;
	size_t maxlength;
	struct variable *v;
	struct {
		char *buff;
		char *ptr;
	} read, write;

#define	subst_buff_check(size) \
	if ((size) > CONF_SUBSTITUTION_MAXLENGTH) { \
		ERR("substitution buffer overflow"); \
		myabort(); \
	}

	subst_buff_check(strlen(text));

	regstr = alloc_string_size(max_var_name_len(variables));
	strcpy(regstr, "\\$");

	read.buff = alloc_string_size(CONF_SUBSTITUTION_MAXLENGTH);
	write.buff = alloc_string_size(CONF_SUBSTITUTION_MAXLENGTH);

	strcpy(read.buff, text);

	while (variables) {
		v = variables->item;
		maxlength = CONF_SUBSTITUTION_MAXLENGTH;
		read.ptr = read.buff;
		write.ptr = write.buff;
		strcpy(regstr + 2, v->name);
		compile_regex(&reg, regstr);

		while (regexec(&reg, read.ptr, 1, &match, 0) == 0) {
			// copy string before $VAR
			n = min(match.rm_so, maxlength);
			strncpy(write.ptr, read.ptr, n);
			write.ptr[n] = '\0';
			write.ptr += n;
			read.ptr += match.rm_eo;	// go after $VAR
			maxlength -= n;

			// copy $VAR substitution
			n = min(strlen(v->substitution), maxlength);
			subst_buff_check(n);
			strncpy(write.ptr, v->substitution, n);
			write.ptr[n] = '\0';
			write.ptr += n;
			maxlength -= n;
		}

		n = min(strlen(read.ptr), maxlength);
		subst_buff_check(n);
		strncpy(write.ptr, read.ptr, n);
		write.ptr[n] = '\0';

		swap_ptr((void **)&write.buff, (void **)&read.buff);

		variables = variables->next;
	}

	DEBUG("substitued '%s' ~> '%s'", text, read.buff);
	strcpy(substitued, read.buff);

	free(read.buff);
	free(write.buff);
}
Beispiel #20
0
/*
 * load the filter from a file 
 */
int filter_load_file(char *filename, struct filter_list **list)
{
   int fd;
   void *file;
   size_t size, ret;
   struct filter_env *fenv;
   struct filter_header fh;

   DEBUG_MSG("filter_load_file (%s)", filename);

  /* open the file */
   if ((fd = open(filename, O_RDONLY | O_BINARY)) == -1)
      FATAL_MSG("File not found or permission denied");

   /* read the header */
   if (read(fd, &fh, sizeof(struct filter_header)) != sizeof(struct filter_header))
      FATAL_MSG("The file is corrupted");

   /* sanity checks */
   if (fh.magic != htons(EC_FILTER_MAGIC))
      FATAL_MSG("Bad magic in filter file\nMake sure to compile the filter with etterfilter");
  
   /* which version has compiled the filter ? */
   if (strcmp(fh.version, EC_VERSION))
      FATAL_MSG("Filter compiled for a different version");
   
   /* get the size */
   size = lseek(fd, 0, SEEK_END);

   /* load the file in memory */
   SAFE_CALLOC(file, size, sizeof(char));
 
   /* rewind the pointer */
   lseek(fd, 0, SEEK_SET);
   
   ret = read(fd, file, size);
   
   close(fd);
   
   if (ret != size)
      FATAL_MSG("Cannot read the file into memory");

   FILTERS_LOCK;

   /* advance to the end of the filter list */
   while (*list) list = &(*list)->next;

   /* allocate memory for the list entry */
   SAFE_CALLOC(*list, 1, sizeof(struct filter_list));
   fenv = &(*list)->env;
   
   /* set the global variables */
   fenv->map = file;
   fenv->chain = (struct filter_op *)(file + fh.code);
   fenv->len = size - sizeof(struct filter_header) - fh.code;

   /* 
    * adjust all the string pointers 
    * they must point to the data segment
    */
   reconstruct_strings(fenv, &fh);

   /* save the name of the loaded filter */
   (*list)->name = strdup(filename);

   /* enable the filter */
   (*list)->enabled = 1;

   FILTERS_UNLOCK;

   /* compile the regex to speed up the matching */
   if (compile_regex(fenv, &fh) != ESUCCESS)
      return -EFATAL;
   
   USER_MSG("Content filters loaded from %s...\n", filename);
   
   return ESUCCESS;
}
Beispiel #21
0
void ut_parser(void)
{
  printf("Unit Testing Parser!\n");

  // setting up
  regex_t r;
  const char * find_text;

  char ** input_args = (char **) malloc(MAX_ARG_NUM * sizeof(char *));
  for(int i=0; i<MAX_ARG_NUM; i++) {
      input_args[i] = (char *)malloc(MAX_INPUT_BYTES*sizeof(char));
  }
  compile_regex(& r, PASER_STR);

  // execution
  find_text = "select(C,10,20)";
  printf ("PARSER: '%s'\n", PASER_STR);

  printf ("Parsing '%s'\n", find_text);
  match_regex(& r, find_text,input_args);

  assert(strncmp(input_args[1],"select",5)==0);
  assert(strncmp(input_args[2],"C",1)==0);
  assert(strncmp(input_args[3],"10",2)==0);
  assert(strncmp(input_args[4],"20",2)==0);

  // execution
  find_text = "inter=select(C,x)";
  printf ("Parsing '%s'\n", find_text);
  match_regex(& r, find_text,input_args);

  assert(strncmp(input_args[0],"inter",5)==0);
  assert(strncmp(input_args[1],"select",5)==0);
  assert(strncmp(input_args[2],"C",1)==0);
  assert(strncmp(input_args[3],"x",1)==0);


  // execution
  find_text = "select(hi,var)";
  printf ("Parsing '%s'\n", find_text);
  match_regex(& r, find_text,input_args);
  assert(strncmp(input_args[1],"select",5)==0);
  assert(strncmp(input_args[2],"hi",2)==0);
  assert(strncmp(input_args[3],"var",3)==0);
  printf("success!\n\n");

  // execution
  find_text = "load(6)";
  printf ("Parsing '%s'\n", find_text);
  match_regex(& r, find_text,input_args);
  assert(strncmp(input_args[1],"load",4)==0);
  assert(strncmp(input_args[2],"6",1)==0);


  // execution
  find_text = "create(friends,\"unsorted\")";
  printf ("Parsing '%s'\n", find_text);
  match_regex(& r, find_text,input_args);
  assert(strncmp(input_args[1],"create", 5)==0);
  assert(strncmp(input_args[2],"friends", 5)==0);
  assert(strncmp(input_args[3],"unsorted", 8)==0);
  printf("success!\n\n");

  // execution
  find_text = "create(friends,\"sorted\")";
  printf ("Parsing '%s'\n", find_text);
  match_regex(& r, find_text,input_args);
  assert(strncmp(input_args[1],"create", 5)==0);
  assert(strncmp(input_args[2],"friends", 5)==0);
  assert(strncmp(input_args[3],"sorted", 6)==0);
  printf("success!\n\n");

  // execution
  find_text = "create(friends,\"unsorted\")";
  printf ("Parsing '%s'\n", find_text);
  match_regex(& r, find_text,input_args);
  assert(strncmp(input_args[1],"create",5)==0);
  assert(strncmp(input_args[2],"friends",5)==0);
  assert(strncmp(input_args[3],"unsorted",8)==0);
  printf("success!\n\n");

  // execution
  find_text = "insert(friends,10)";
  printf ("Parsing '%s'\n", find_text);
  match_regex(& r, find_text,input_args);
  assert(strncmp(input_args[1],"insert",5)==0);
  assert(strncmp(input_args[2],"friends",5)==0);
  assert(strncmp(input_args[3],"10",2)==0);
  printf("success!\n\n");

  // execution
  find_text = "select(C,20,30)";
  printf ("Parsing '%s'\n", find_text);
  match_regex(& r, find_text,input_args);
  assert(strncmp(input_args[1],"select",5)==0);
  assert(strncmp(input_args[2],"C",1)==0);
  assert(strncmp(input_args[3],"20",2)==0);
  assert(strncmp(input_args[4],"30",2)==0);
  printf("success!\n\n");

  // execution
  find_text = "create(t2a,\"b+tree\")";
  printf ("Parsing '%s'\n", find_text);
  match_regex(& r, find_text,input_args);
  assert(strncmp(input_args[1],"create",5)==0);
  assert(strncmp(input_args[2],"t2a",1)==0);
  assert(strncmp(input_args[3],"b+tree",6)==0);
  printf("success!\n\n");


  // execution
  find_text = "add(t2,t3)";
  printf ("Parsing '%s'\n", find_text);
  match_regex(& r, find_text,input_args);
  assert(strncmp(input_args[1],"add",3)==0);
  assert(strncmp(input_args[2],"t2",2)==0);
  assert(strncmp(input_args[3],"t3",2)==0);
  printf("success!\n\n");


  // execution
  find_text = "r_results,s_results=hashjoin(join_input1,join_input2)";
  printf ("Parsing '%s'\n", find_text);
  match_regex(& r, find_text,input_args);
  assert(strncmp(input_args[0],"r_results,s_results", 19)==0);
  assert(strncmp(input_args[1],"hashjoin", 8)==0);
  assert(strncmp(input_args[2],"join_input1",11)==0);
  assert(strncmp(input_args[3],"join_input2",11)==0);
  printf("success!\n\n");


  regfree (& r);

  // prevent memory leak!
  for(int i=0;i<4;i++) {
    free(input_args[i]);
  }
  free(input_args);

  printf("SUCCESS!\n");

  return;

}
Beispiel #22
0
static struct selabel_lookup_rec *lookup(struct selabel_handle *rec,
        const char *key, int type)
{
    struct saved_data *data = (struct saved_data *)rec->data;
    spec_t *spec_arr = data->spec_arr;
    int i, rc, file_stem;
    mode_t mode = (mode_t)type;
    const char *buf;
    struct selabel_lookup_rec *ret = NULL;
    char *clean_key = NULL;
    const char *prev_slash, *next_slash;
    unsigned int sofar = 0;

    if (!data->nspec) {
        errno = ENOENT;
        goto finish;
    }

    /* Remove duplicate slashes */
    if ((next_slash = strstr(key, "//"))) {
        clean_key = malloc(strlen(key) + 1);
        if (!clean_key)
            goto finish;
        prev_slash = key;
        while (next_slash) {
            memcpy(clean_key + sofar, prev_slash, next_slash - prev_slash);
            sofar += next_slash - prev_slash;
            prev_slash = next_slash + 1;
            next_slash = strstr(prev_slash, "//");
        }
        strcpy(clean_key + sofar, prev_slash);
        key = clean_key;
    }

    buf = key;
    file_stem = find_stem_from_file(data, &buf);
    mode &= S_IFMT;

    /*
     * Check for matching specifications in reverse order, so that
     * the last matching specification is used.
     */
    for (i = data->nspec - 1; i >= 0; i--) {
        /* if the spec in question matches no stem or has the same
         * stem as the file AND if the spec in question has no mode
         * specified or if the mode matches the file mode then we do
         * a regex check        */
        if ((spec_arr[i].stem_id == -1
                || spec_arr[i].stem_id == file_stem)
                && (!mode || !spec_arr[i].mode
                    || mode == spec_arr[i].mode)) {
            if (compile_regex(data, &spec_arr[i], NULL) < 0)
                goto finish;
            if (spec_arr[i].stem_id == -1)
                rc = regexec(&spec_arr[i].regex, key, 0, 0, 0);
            else
                rc = regexec(&spec_arr[i].regex, buf, 0, 0, 0);

            if (rc == 0) {
                spec_arr[i].matches++;
                break;
            }
            if (rc == REG_NOMATCH)
                continue;
            /* else it's an error */
            goto finish;
        }
    }

    if (i < 0 || strcmp(spec_arr[i].lr.ctx_raw, "<<none>>") == 0) {
        /* No matching specification. */
        errno = ENOENT;
        goto finish;
    }

    ret = &spec_arr[i].lr;

finish:
    free(clean_key);
    return ret;
}
Beispiel #23
0
static int process_line(struct selabel_handle *rec,
                        const char *path, const char *prefix,
                        char *line_buf, int pass, unsigned lineno)
{
    int items, len;
    char *buf_p, *regex, *type, *context;
    struct saved_data *data = (struct saved_data *)rec->data;
    spec_t *spec_arr = data->spec_arr;
    unsigned int nspec = data->nspec;

    len = strlen(line_buf);
    if (line_buf[len - 1] == '\n')
        line_buf[len - 1] = 0;
    buf_p = line_buf;
    while (isspace(*buf_p))
        buf_p++;
    /* Skip comment lines and empty lines. */
    if (*buf_p == '#' || *buf_p == 0)
        return 0;
    items = sscanf(line_buf, "%as %as %as", &regex, &type, &context);
    if (items < 2) {
        COMPAT_LOG(SELINUX_WARNING,
                   "%s:  line %d is missing fields, skipping\n", path,
                   lineno);
        if (items == 1)
            free(regex);
        return 0;
    } else if (items == 2) {
        /* The type field is optional. */
        free(context);
        context = type;
        type = 0;
    }

    len = get_stem_from_spec(regex);
    if (len && prefix && strncmp(prefix, regex, len)) {
        /* Stem of regex does not match requested prefix, discard. */
        free(regex);
        free(type);
        free(context);
        return 0;
    }

    if (pass == 1) {
        /* On the second pass, process and store the specification in spec. */
        char *errbuf = NULL;
        spec_arr[nspec].stem_id = find_stem_from_spec(data, regex);
        spec_arr[nspec].regex_str = regex;
        if (rec->validating && compile_regex(data, &spec_arr[nspec], &errbuf)) {
            COMPAT_LOG(SELINUX_WARNING,
                       "%s:  line %d has invalid regex %s:  %s\n",
                       path, lineno, regex,
                       (errbuf ? errbuf : "out of memory"));
        }

        /* Convert the type string to a mode format */
        spec_arr[nspec].type_str = type;
        spec_arr[nspec].mode = 0;
        if (!type)
            goto skip_type;
        len = strlen(type);
        if (type[0] != '-' || len != 2) {
            COMPAT_LOG(SELINUX_WARNING,
                       "%s:  line %d has invalid file type %s\n",
                       path, lineno, type);
            return 0;
        }
        switch (type[1]) {
        case 'b':
            spec_arr[nspec].mode = S_IFBLK;
            break;
        case 'c':
            spec_arr[nspec].mode = S_IFCHR;
            break;
        case 'd':
            spec_arr[nspec].mode = S_IFDIR;
            break;
        case 'p':
            spec_arr[nspec].mode = S_IFIFO;
            break;
        case 'l':
            spec_arr[nspec].mode = S_IFLNK;
            break;
        case 's':
            spec_arr[nspec].mode = S_IFSOCK;
            break;
        case '-':
            spec_arr[nspec].mode = S_IFREG;
            break;
        default:
            COMPAT_LOG(SELINUX_WARNING,
                       "%s:  line %d has invalid file type %s\n",
                       path, lineno, type);
            return 0;
        }

skip_type:
        spec_arr[nspec].lr.ctx_raw = context;

        /* Determine if specification has
         * any meta characters in the RE */
        spec_hasMetaChars(&spec_arr[nspec]);

        if (strcmp(context, "<<none>>") && rec->validating)
            compat_validate(rec, &spec_arr[nspec].lr, path, lineno);
    }

    data->nspec = ++nspec;
    if (pass == 0) {
        free(regex);
        if (type)
            free(type);
        free(context);
    }
    return 0;
}
Beispiel #24
0
int do_list_server(struct asfd *asfd, struct sdirs *sdirs, struct conf *conf,
	const char *backup, const char *listregex, const char *browsedir)
{
	int ret=-1;
	uint8_t found=0;
	unsigned long bno=0;
	regex_t *regex=NULL;
	struct bu *bu=NULL;
	struct bu *bu_list=NULL;

	printf("in do_list_server\n");

	if(compile_regex(&regex, listregex)
	  || bu_list_get(sdirs, &bu_list)
	  || write_status(STATUS_LISTING, NULL, conf))
		goto end;

	if(backup && *backup) bno=strtoul(backup, NULL, 10);

	for(bu=bu_list; bu; bu=bu->next)
	{
		// Search all backups for things matching the regex.
		if(listregex && backup && *backup=='a')
		{
			found=1;
			if(write_wrapper_str(asfd,
				CMD_TIMESTAMP, bu->timestamp)
			  || list_manifest(asfd, bu->path,
				regex, browsedir, conf)) goto end;
		}
		// Search or list a particular backup.
		else if(backup && *backup)
		{
			if(!found
			  && (!strcmp(bu->timestamp, backup)
				|| bu->bno==bno))
			{
				found=1;
				if(send_backup_name_to_client(asfd, bu, conf)
				  || list_manifest(asfd, bu->path, regex,
					browsedir, conf)) goto end;
			}
		}
		// List the backups.
		else
		{
			found=1;
			if(send_backup_name_to_client(asfd, bu, conf))
				goto end;
		}
	}

	if(backup && *backup && !found)
	{
		write_wrapper_str(asfd, CMD_ERROR, "backup not found");
		goto end;
	}

	if(flush_asio(asfd)) goto end;
	
	ret=0;
end:
	if(regex) { regfree(regex); free(regex); }
	bu_list_free(&bu);
	return ret;
}
Beispiel #25
0
int do_restore_server(const char *basedir, const char *backup, const char *restoreregex, enum action act, const char *client, struct cntr *p1cntr, struct cntr *cntr, struct config *cconf)
{
	int a=0;
	int i=0;
	int ret=0;
	int found=0;
	struct bu *arr=NULL;
	unsigned long index=0;
	char *tmppath1=NULL;
	char *tmppath2=NULL;
	regex_t *regex=NULL;
	bool all=FALSE;

	logp("in do_restore\n");

	if(compile_regex(&regex, restoreregex)) return -1;

	if(!(tmppath1=prepend_s(basedir, "tmp1", strlen("tmp1")))
	  || !(tmppath2=prepend_s(basedir, "tmp2", strlen("tmp2"))))
	{
		if(tmppath1) free(tmppath1);
		if(regex) { regfree(regex); free(regex); }
		return -1;
	}

	if(get_current_backups(basedir, &arr, &a, 1))
	{
		if(tmppath1) free(tmppath1);
		if(tmppath2) free(tmppath2);
		if(regex) { regfree(regex); free(regex); }
		return -1;
	}

	if(backup && *backup=='a')
	{
		all=TRUE;
	}
	else if(!(index=strtoul(backup, NULL, 10)) && a>0)
	{
		// No backup specified, do the most recent.
		ret=restore_manifest(arr, a, a-1,
			tmppath1, tmppath2, regex, act, client,
			p1cntr, cntr, cconf, all);
		found=TRUE;
	}

	if(!found) for(i=0; i<a; i++)
	{
		if(all || !strcmp(arr[i].timestamp, backup)
			|| arr[i].index==index)
		{
			found=TRUE;
			//logp("got: %s\n", arr[i].path);
			ret|=restore_manifest(arr, a, i,
				tmppath1, tmppath2, regex, act, client,
				p1cntr, cntr, cconf, all);
			if(!all) break;
		}
	}

	// If doing all backups, send restore end.
	if(!ret && all && found)
		ret=do_restore_end(act, cntr);

	free_current_backups(&arr, a);

	if(!found)
	{
		logp("backup not found\n");
		async_write_str(CMD_ERROR, "backup not found");
		ret=-1;
	}
	if(tmppath1)
	{
		unlink(tmppath1);
		free(tmppath1);
	}
	if(tmppath2)
	{
		unlink(tmppath2);
		free(tmppath2);
	}
	if(regex)
	{
		regfree(regex);
		free(regex);
	}
	return ret;
}
Beispiel #26
0
// Main compiler dispatch system
void compile(compiler_wrapper *cw, ast_node *root)
{
    switch(root->type)
    {
        case ABINARY_EXPRESSION:
            compile_binary(cw, root);
        break;
        case AUNARY_EXPRESSION:
            compile_unary(cw, root);
        break;
        case AVALUE:
            compile_value(cw, root);
        break;
        case AUNIT:
            compile_unit_value(cw, root);
        break;
        case ACOND_CHAIN:
            compile_cond(cw, root);
        break;
        case AIF:
            compile_if(cw, root);
        break;
        case ALOOP:
            compile_loop(cw, root);
        break;
        case AITERLOOP:
            compile_iter_loop(cw, root);
        break;
        case AFUNC_DECL:
            compile_function(cw, root);
        break;
        case AFUNC_CALL:
            compile_function_call(cw, root);
        break;
        case ACLASS_DECL:
            compile_class_decl(cw, root);
        break;
        case ATERNARY:
            compile_ternary(cw, root);
        break;
        case AMEMBER_ACCESS:
            compile_member_access(cw, root);
        break;
        case AARRAY:
            compile_array(cw, root);
        break;
        case ATABLE:
            compile_table(cw, root);
        break;
        case AOBJDECL:
            compile_object(cw, root);
        break;
        case AINDEX:
            compile_indx(cw, root);
        break;
        case ATRIPLESET:
            compile_triple_set(cw, root);
        break;
        case ATRYCATCH:
            compile_try_catch(cw, root);
        break;
        case AONEOFF:
            compile_one_off(cw, root);
        break;
        case ALOAD:
            compile_load(cw, root);
        break;
        case AREGEX:
            compile_regex(cw, root);
        break;
        default:
        break;
    }
}
NicInterfaceFilterRegex::NicInterfaceFilterRegex( const NicInterfaceRegexes& nic_interface_regexes ):
nic_interface_regexes_(nic_interface_regexes),
regex_(new boost::regex())
{
    compile_regex();
}
Beispiel #28
0
int main()
{
  int i, n,
      cport_nr=16,        /* /dev/ttyUSB0 (COM1 on windows) */
      bdrate=9600;       /* 9600 baud */

  unsigned char buf[ARDUINOBUFFER];
  char mode[]={'8','N','1',0};


  if(RS232_OpenComport(cport_nr, bdrate, mode))
  {
    putError("Can not open serial port");
    return(0);
  }

  char* result[2];
  result[0] = malloc(BUFFER_SIZE);
  result[1] = malloc(BUFFER_SIZE);

  regex_t r;
  const char * regex_text;
  regex_text = "([[:digit:]]+)[^[:digit:]]+([[:digit:]]+)";
  int cr = compile_regex(& r, regex_text);
  if (cr != 0)
  {
     return cr;
  }

  float humidities[COUNTPERMINUTE];
  float temperatures[COUNTPERMINUTE];

  long attempts = 0; 
  char t[16], h[16];
  char currentMeasurement[64];

  while(1)
  {
    n = RS232_PollComport(cport_nr, buf, ARDUINOBUFFER-1);

    if(n > 0)
    {
      buf[n] = 0;   /* always put a "null" at the end of a string! */

      for(i=0; i < n; i++)
      {
        if(buf[i] < 32)  /* replace unreadable control-codes by dots */
        {
          buf[i] = '.';
        }
      }

      //printf("received %i bytes: %s\n", n, (char *)buf);
      int success =  match_regex(& r, (char*)buf, result);
    if (success == 0)
    {
       attempts++;
       sprintf(currentMeasurement, "Temperature %s Humidity %s", result[0], result[1]);

       //puts(currentMeasurement);
       syslog(LOG_INFO, currentMeasurement);

       int idx = attempts %  COUNTPERMINUTE;
	humidities[idx] = atof(result[1]);
	temperatures[idx] = atof(result[0]);
	if (idx == 0 && attempts>=COUNTPERMINUTE)
	{
	   float sumTemp, sumHum;
	   int u = 0;
	   for (u=0; u< COUNTPERMINUTE; u++)
	   {
	     sumTemp += temperatures[u];
	     sumHum += humidities[u];
	   }
           sprintf(t, "%.2lf",sumTemp/COUNTPERMINUTE);
	   sprintf(h, "%.2lf",sumHum/COUNTPERMINUTE);
	   // printf("Avg Temperature %s Humidity %s\r\n", t, h);
	   postWeather(t,h,"AF993B68-0EF7-4842-8A36-8FD03A695456");
	   sumTemp = 0;
	   sumHum = 0;
	}
    }
     else
     {
       putError("Can not parse response");
       putError((char*)buf);
     }

    }
    usleep(100000);  /* sleep for 100 milliSeconds */
  }
  regfree (& r);
  return(0);
}
Beispiel #29
0
/* Replaces possibly existing regular expression with the new one. */
static void
reset_regex(filter_t *filter, const char value[])
{
	free_regex(filter);
	compile_regex(filter, value);
}
Beispiel #30
0
int do_list_server(const char *basedir, const char *backup, const char *listregex, const char *browsedir, const char *client, struct cntr *p1cntr, struct cntr *cntr)
{
	int a=0;
	int i=0;
	int ret=0;
	int found=0;
	struct bu *arr=NULL;
	unsigned long index=0;
	regex_t *regex=NULL;

	logp("in do_list\n");

	if(compile_regex(&regex, listregex)) return -1;

	if(get_current_backups(basedir, &arr, &a, 1))
	{
		if(regex) { regfree(regex); free(regex); }
		return -1;
	}

	write_status(client, STATUS_LISTING, NULL, p1cntr, cntr);

	if(backup && *backup) index=strtoul(backup, NULL, 10);

	for(i=0; i<a; i++)
	{
		// Search all backups for things matching the regex.
		if(listregex && backup && *backup=='a')
		{
			found=TRUE;
			async_write(CMD_TIMESTAMP,
				arr[i].timestamp, strlen(arr[i].timestamp));
			ret+=list_manifest(arr[i].path, regex, browsedir,
				client, p1cntr, cntr);
		}
		// Search or list a particular backup.
		else if(backup && *backup)
		{
			if(!found
			  && (!strcmp(arr[i].timestamp, backup)
				|| arr[i].index==index))
			{
				found=TRUE;
				async_write(CMD_TIMESTAMP,
				  arr[i].timestamp, strlen(arr[i].timestamp));
				ret=list_manifest(arr[i].path, regex,
					browsedir, client, p1cntr, cntr);
			}
		}
		// List the backups.
		else
		{
			found=TRUE;
			async_write(CMD_TIMESTAMP,
				arr[i].timestamp, strlen(arr[i].timestamp));
		}
	}
	free_current_backups(&arr, a);

	if(backup && *backup && !found)
	{
		async_write_str(CMD_ERROR, "backup not found");
		ret=-1;
	}
	if(regex) { regfree(regex); free(regex); }
	return ret;
}