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; } }
int scan_pathchk(const char *path, struct cli_ftw_cbdata *data) { struct scan_cb_data *scandata = data->data; const struct optstruct *opt; STATBUF statbuf; if((opt = optget(scandata->opts, "ExcludePath"))->enabled) { while(opt) { if(match_regex(path, opt->strarg) == 1) { if(scandata->type != TYPE_MULTISCAN) conn_reply_single(scandata->conn, path, "Excluded"); return 1; } opt = (const struct optstruct *) opt->nextarg; } } if(!optget(scandata->opts, "CrossFilesystems")->enabled) { if(CLAMSTAT(path, &statbuf) == 0) { if(statbuf.st_dev != scandata->dev) { if(scandata->type != TYPE_MULTISCAN) conn_reply_single(scandata->conn, path, "Excluded (another filesystem)"); return 1; } } } return 0; }
/** * Return true if word is in dictionary, or if word is matched by * regex. */ bool find_word_in_dict(const Dictionary dict, const char * word) { const char * regex_name; if (boolean_dictionary_lookup (dict, word)) return true; regex_name = match_regex(dict->regex_root, word); if (NULL == regex_name) return false; return boolean_dictionary_lookup(dict, regex_name); }
std::string machine_info_display_height() { std::string v_mode_desc = wmi_value(L"Win32_VideoController", L"VideoModeDescription"); if (v_mode_desc == exc_value) { return exc_value; } return match_regex(v_mode_desc, "\\d+ x (\\d+) x \\d+ colors"); }
/*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ bool CWinInetEvents::RegexMatch(CString str, CString regex) { bool matched = false; if (str.GetLength()) { if (!regex.GetLength() || !regex.Compare(_T("*")) || !str.CompareNoCase(regex)) { matched = true; } else if (regex.GetLength()) { std::tr1::regex match_regex(CT2A(regex), std::tr1::regex_constants::icase | std::tr1::regex_constants::ECMAScript); matched = std::tr1::regex_match((LPCSTR)CT2A(str), match_regex); } } return matched; }
/* 0: scan, 1: skip */ static int chkpath(const char *path) { const struct optstruct *opt; if((opt = optget(clamdopts, "ExcludePath"))->enabled) { while(opt) { if(match_regex(path, opt->strarg) == 1) { logg("~%s: Excluded\n", path); return 1; } opt = opt->nextarg; } } return 0; }
static ret_t match (cherokee_rule_header_t *rule, cherokee_connection_t *conn, cherokee_config_entry_t *ret_conf) { switch (rule->type) { case rule_header_type_regex: return match_regex (rule, conn, ret_conf); case rule_header_type_provided: return match_provided (rule, conn, ret_conf); } SHOULDNT_HAPPEN; return ret_error; }
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); }
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; }
void check_correctness() { const prb_t p(dims, dir, dt, tag, axis, group); char pstr[max_prb_len]; prb2str(&p, pstr); if (pattern && !match_regex(pstr, pattern)) return; print(1, "run: %s\n", pstr); res_t res{}; const int status = shuffle::doit(&p, &res); bool want_perf_report = false; parse_result(res, want_perf_report, allow_unimpl, status, pstr); if (want_perf_report && bench_mode & PERF) perf_report(&p, &res, pstr); benchdnn_stat.tests++; }
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; }
void check_correctness(const desc_t *c) { const prb_t p(*c, dir, cfg, alg, attr, mb); char pstr[max_prb_len]; prb2str(&p, pstr); if (pattern && !match_regex(pstr, pattern)) return; print(1, "run: %s\n", pstr); res_t res{}; const int status = conv::doit(&p, &res); (void)status; bool want_perf_report = false; parse_result(res, want_perf_report, allow_unimpl, status, pstr); if (want_perf_report && bench_mode & PERF) perf_report(&p, &res, pstr); benchdnn_stat.tests++; }
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; }
static bool morpheme_match(Sentence sent, const char *word, int l, p_list pl) { Dictionary afdict = sent->dict->affix_table; anysplit_params *as = afdict->anysplit; int pos = 0; int p; Regex_node *re; char *prefix_string = alloca(l+1); lgdebug(+2, "word=%s: ", word); for (p = 0; p < as->nparts; p++) { strncpy(prefix_string, &word[pos], pl[p]-pos); prefix_string[pl[p]-pos] = '\0'; /* For flexibility, REGRPE is matched only to the prefix part, * REGMID only to the middle suffixes, and REGSUF only to the suffix part - * which cannot be the prefix. */ if (0 == p) re = as->regpre; else if (pl[p] == l) re = as->regsuf; else re = as->regmid; lgdebug(2, "re=%s part%d=%s: ", re->name, p, prefix_string); /* A NULL regex always matches */ if ((NULL != re) && (NULL == match_regex(re ,prefix_string))) { lgdebug(2, "No match\n"); return false; } pos = pl[p]; if (pos == l) break; } lgdebug(2, "Match\n"); return true; }
static void scandirs(const char *dirname, struct cl_engine *engine, const struct optstruct *opts, unsigned int options, unsigned int depth, dev_t dev) { DIR *dd; struct dirent *dent; STATBUF sb; char *fname; int included; const struct optstruct *opt; unsigned int dirlnk, filelnk; if((opt = optget(opts, "exclude-dir"))->enabled) { while(opt) { if(match_regex(dirname, opt->strarg) == 1) { if(!printinfected) logg("~%s: Excluded\n", dirname); return; } opt = opt->nextarg; } } if((opt = optget(opts, "include-dir"))->enabled) { included = 0; while(opt) { if(match_regex(dirname, opt->strarg) == 1) { included = 1; break; } opt = opt->nextarg; } if(!included) { if(!printinfected) logg("~%s: Excluded\n", dirname); return; } } if(depth > (unsigned int) optget(opts, "max-dir-recursion")->numarg) return; dirlnk = optget(opts, "follow-dir-symlinks")->numarg; filelnk = optget(opts, "follow-file-symlinks")->numarg; if((dd = opendir(dirname)) != NULL) { info.dirs++; depth++; while((dent = readdir(dd))) { if(dent->d_ino) { if(strcmp(dent->d_name, ".") && strcmp(dent->d_name, "..")) { /* build the full name */ fname = malloc(strlen(dirname) + strlen(dent->d_name) + 2); if (fname == NULL) { /* oops, malloc() failed, print warning and return */ logg("!scandirs: Memory allocation failed for fname\n"); break; } if(!strcmp(dirname, PATHSEP)) sprintf(fname, PATHSEP"%s", dent->d_name); else sprintf(fname, "%s"PATHSEP"%s", dirname, dent->d_name); /* stat the file */ if(LSTAT(fname, &sb) != -1) { if(!optget(opts, "cross-fs")->enabled) { if(sb.st_dev != dev) { if(!printinfected) logg("~%s: Excluded\n", fname); free(fname); continue; } } if(S_ISLNK(sb.st_mode)) { if(dirlnk != 2 && filelnk != 2) { if(!printinfected) logg("%s: Symbolic link\n", fname); } else if(CLAMSTAT(fname, &sb) != -1) { if(S_ISREG(sb.st_mode) && filelnk == 2) { scanfile(fname, engine, opts, options); } else if(S_ISDIR(sb.st_mode) && dirlnk == 2) { if(recursion) scandirs(fname, engine, opts, options, depth, dev); } else { if(!printinfected) logg("%s: Symbolic link\n", fname); } } } else if(S_ISREG(sb.st_mode)) { scanfile(fname, engine, opts, options); } else if(S_ISDIR(sb.st_mode) && recursion) { scandirs(fname, engine, opts, options, depth, dev); } } free(fname); } } } closedir(dd); } else { if(!printinfected) logg("~%s: Can't open directory.\n", dirname); info.errors++; } }
bool sane_linkage_morphism(Sentence sent, Linkage lkg, Parse_Options opts) { Wordgraph_pathpos *wp_new = NULL; Wordgraph_pathpos *wp_old = NULL; Wordgraph_pathpos *wpp; Gword **next; /* next Wordgraph words of the current word */ size_t i; Linkage_info * const lifo = &lkg->lifo; bool match_found = true; /* if all the words are null - it's still a match */ Gword **lwg_path; Dictionary afdict = sent->dict->affix_table; /* for SANEMORPHISM */ char *const affix_types = alloca(sent->length*2 + 1); /* affix types */ affix_types[0] = '\0'; /* Populate the path word queue, initializing the path to NULL. */ for (next = sent->wordgraph->next; *next; next++) { wordgraph_path_append(&wp_new, /*path*/NULL, /*add_word*/NULL, *next); } assert(NULL != wp_new, "Path word queue is empty"); for (i = 0; i < lkg->num_words; i++) { Disjunct *cdj; /* chosen disjunct */ lgdebug(D_SLM, "%p Word %zu: ", lkg, i); if (NULL == wp_new) { lgdebug(+D_SLM, "- No more words in the wordgraph\n"); match_found = false; break; } if (wp_old != wp_new) { wordgraph_path_free(wp_old, true); wp_old = wp_new; } wp_new = NULL; //wordgraph_pathpos_print(wp_old); cdj = lkg->chosen_disjuncts[i]; /* Handle null words */ if (NULL == cdj) { lgdebug(D_SLM, "- Null word\n"); /* A null word matches any word in the Wordgraph - * so, unconditionally proceed in all paths in parallel. */ match_found = false; for (wpp = wp_old; NULL != wpp->word; wpp++) { if (NULL == wpp->word->next) continue; /* This path encountered the Wordgraph end */ /* The null words cannot be marked here because wpp->path consists * of pointers to the Wordgraph words, and these words are common to * all the linkages, with potentially different null words in each * of them. However, the position of the null words can be inferred * from the null words in the word array of the Linkage structure. */ for (next = wpp->word->next; NULL != *next; next++) { match_found = true; wordgraph_path_append(&wp_new, wpp->path, wpp->word, *next); } } continue; } if (!match_found) { const char *e = "Internal error: Too many words in the linkage\n"; lgdebug(D_SLM, "- %s", e); prt_error("Error: %s.", e); break; } assert(MT_EMPTY != cdj->word[0]->morpheme_type); /* already discarded */ if (debug_level(D_SLM)) print_with_subscript_dot(cdj->string); match_found = false; /* Proceed in all the paths in which the word is found. */ for (wpp = wp_old; NULL != wpp->word; wpp++) { const Gword **wlp; /* disjunct word list */ for (wlp = cdj->word; *wlp; wlp++) { if (*wlp == wpp->word) { match_found = true; for (next = wpp->word->next; NULL != *next; next++) { wordgraph_path_append(&wp_new, wpp->path, wpp->word, *next); } break; } } } if (!match_found) { /* FIXME? A message can be added here if there are too many words * in the linkage (can happen only if there is an internal error). */ lgdebug(D_SLM, "- No Wordgraph match\n"); break; } lgdebug(D_SLM, "\n"); } if (match_found) { match_found = false; /* Validate that there are no missing words in the linkage. It is so if * the dummy termination word is found in the new pathpos queue. */ if (NULL != wp_new) { for (wpp = wp_new; NULL != wpp->word; wpp++) { if (MT_INFRASTRUCTURE == wpp->word->morpheme_type) { match_found = true; /* Exit the loop with with wpp of the termination word. */ break; } } } if (!match_found) lgdebug(D_SLM, "%p Missing word(s) at the end of the linkage.\n", lkg); } #define DEBUG_morpheme_type 0 /* Check the morpheme type combination. * If null_count > 0, the morpheme type combination may be invalid * due to null subwords, so skip this check. */ if (match_found && (0 == sent->null_count) && (NULL != afdict) && (NULL != afdict->regex_root)) { const Gword **w; char *affix_types_p = affix_types; /* Construct the affix_types string. */ #if DEBUG_morpheme_type print_lwg_path(wpp->path); #endif i = 0; for (w = wpp->path; *w; w++) { i++; if (MT_EMPTY == (*w)->morpheme_type) continue; /* really a null word */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wswitch-enum" switch ((*w)->morpheme_type) { #pragma GCC diagnostic pop default: /* What to do with the rest? */ case MT_WORD: *affix_types_p = AFFIXTYPE_WORD; break; case MT_PREFIX: *affix_types_p = AFFIXTYPE_PREFIX; break; case MT_STEM: *affix_types_p = AFFIXTYPE_STEM; break; case MT_MIDDLE: *affix_types_p = AFFIXTYPE_MIDDLE; break; case MT_SUFFIX: *affix_types_p = AFFIXTYPE_SUFFIX; break; } #if DEBUG_morpheme_type lgdebug(D_SLM, "Word %zu: %s affixtype=%c\n", i, (*w)->subword, *affix_types_p); #endif affix_types_p++; } *affix_types_p = '\0'; #ifdef WORD_BOUNDARIES /* not yet implemented */ { const Gword *uw; /* If w is an "end subword", return its unsplit word, else NULL. */ uw = word_boundary(w); /* word_boundary() unimplemented */ if (NULL != uw) { *affix_types_p++ = AFFIXTYPE_END; lgdebug(D_SLM, "%p End of Gword %s\n", lkg, uw->subword); } } #endif /* Check if affix_types is valid according to SANEMORPHISM. */ if (('\0' != affix_types[0]) && (NULL == match_regex(afdict->regex_root, affix_types))) { /* Morpheme type combination is invalid */ match_found = false; /* Notify to stdout, so it will be shown along with the result. * XXX We should have a better way to notify. */ if (0 < opts->verbosity) printf("Warning: Invalid morpheme type combination '%s', " "run with !bad and !verbosity=4 to debug\n", affix_types); } } if (match_found) lwg_path = (Gword **)wpp->path; /* OK to modify */ wordgraph_path_free(wp_old, true); wordgraph_path_free(wp_new, !match_found); if (match_found) { if ('\0' != affix_types[0]) { lgdebug(D_SLM, "%p Morpheme type combination '%s'\n", lkg, affix_types); } lgdebug(+D_SLM, "%p SUCCEEDED\n", lkg); lkg->wg_path = lwg_path; return true; } /* Oh no ... invalid morpheme combination! */ sent->num_valid_linkages --; lifo->N_violations++; lifo->pp_violation_msg = "Invalid morphism construction."; lkg->wg_path = NULL; lifo->discarded = true; lgdebug(D_SLM, "%p FAILED\n", lkg); return false; }
int pkg_info(struct pkg_info info) { unsigned int cur; int retval; struct pkg **pkgs; retval = 1; pkgs = NULL; /* -e package name */ if (info.check_package != NULL) { struct pkg *pkg; pkg = pkg_db_get_package(info.db, info.check_package); if (pkg != NULL) { pkg_free(pkg); return 0; } return 1; } /* -W <filename> */ if (info.search_file != NULL) { struct stat sb; if (stat(info.search_file, &sb) != 0) { /* XXX */ return 1; } pkgs = pkg_db_get_installed_match_count(info.db, pkg_match_by_file, 1, (const void *)info.search_file); if (info.quiet == 0) printf("The following installed package(s) has %s " "origin:\n", info.origin); printf("%s\n", pkg_get_name(pkgs[0])); return 0; } /* -O <origin> */ if (info.origin != NULL) { unsigned int pos; pkgs = pkg_db_get_installed_match(info.db, pkg_match_by_origin, (const void *)info.origin); if (info.quiet == 0) printf("The following installed package(s) has %s " "origin:\n", info.origin); for (pos = 0; pkgs[pos] != NULL; pos++) { printf("%s\n", pkg_get_name(pkgs[pos])); } return 0; } switch(info.match_type) { case MATCH_ALL: case MATCH_GLOB: case MATCH_NGLOB: case MATCH_REGEX: case MATCH_EREGEX: /* Display all packages installed */ if (info.match_type == MATCH_ALL) pkgs = pkg_db_get_installed(info.db); else if (info.match_type == MATCH_REGEX || info.match_type == MATCH_EREGEX) pkgs = match_regex(info.db, (const char**)info.pkgs, (info.match_type == MATCH_EREGEX)); else if (info.match_type == MATCH_GLOB || info.match_type == MATCH_NGLOB) pkgs = match_glob(info.db, (const char**)info.pkgs, (info.match_type == MATCH_GLOB)); else errx(1, "ERROR: Inconsistancy in pkg_info"); /* Sort the packages and display them */ if (pkgs == NULL) { /* XXX Error message */ return 1; } for (cur = 0; pkgs[cur] != NULL; cur++) continue; qsort(pkgs, cur, sizeof(struct pkg *), pkg_compare); for (cur = 0; pkgs[cur] != NULL; cur++) { show(info.db, pkgs[cur], info.flags, info.quiet, info.seperator, info.use_blocksize); } retval = 0; break; case MATCH_EXACT: /* Only match the exact names given */ retval = 0; for (cur = 0; info.pkgs[cur] != NULL; cur++) { struct pkg *pkg; pkg = pkg_db_get_package(info.db, info.pkgs[cur]); if (pkg != NULL) show(info.db, pkg, info.flags, info.quiet, info.seperator, info.use_blocksize); else { warnx("pkg_info: can't find package '%s' " "installed or in a file!", info.pkgs[cur]); retval = 1; } } break; } if (pkgs != NULL) pkg_list_free(pkgs); return retval; }
int pkg_info(struct pkg_info info) { unsigned int cur; int retval; struct pkg **pkgs; retval = 1; pkgs = NULL; switch(info.match_type) { case MATCH_ALL: /* Display all packages installed */ pkgs = pkg_db_get_installed(info.db); if (pkgs == NULL) { /* XXX Error message */ return 1; } for (cur = 0; pkgs[cur] != NULL; cur++) continue; qsort(pkgs, cur, sizeof(struct pkg *), pkg_compare); for (cur = 0; pkgs[cur] != NULL; cur++) { show(info.db, pkgs[cur], info.flags, info.quiet); } retval = 0; break; case MATCH_REGEX: case MATCH_EREGEX: /* Match all packages that match one of the [e]regex given */ { char *prev; //pkgs = pkg_db_get_installed(info.db); //if (pkgs == NULL) { /* XXX Error message */ // break; //} pkgs = match_regex(info.db, info.pkgs, (info.match_type == MATCH_EREGEX)); /* Display all packages that matches atleast one regex */ prev = NULL; for (cur = 0; pkgs[cur] != NULL; cur++) { /* Only show one instance of each package */ if (prev == NULL || strcmp(prev, pkg_get_name(pkgs[cur])) != 0) { show(info.db, pkgs[cur], info.flags, info.quiet); } prev = pkg_get_name(pkgs[cur]); } } retval = 0; break; case MATCH_GLOB: case MATCH_NGLOB: errx(1, "Unsupported match type (use -x or -X)"); break; case MATCH_EXACT: /* Only match the exact names given */ retval = 0; for (cur = 0; info.pkgs[cur] != NULL; cur++) { struct pkg *pkg; pkg = pkg_db_get_package(info.db, info.pkgs[cur]); if (pkg != NULL) show(info.db, pkg, info.flags, info.quiet); else retval = 1; } break; } if (pkgs != NULL) pkg_list_free(pkgs); return retval; }
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); }
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; }
static void scanfile(const char *filename, struct cl_engine *engine, const struct optstruct *opts, unsigned int options) { int ret = 0, fd, included; unsigned i; const struct optstruct *opt; const char *virname; STATBUF sb; struct metachain chain; struct clamscan_cb_data data; if((opt = optget(opts, "exclude"))->enabled) { while(opt) { if(match_regex(filename, opt->strarg) == 1) { if(!printinfected) logg("~%s: Excluded\n", filename); return; } opt = opt->nextarg; } } if((opt = optget(opts, "include"))->enabled) { included = 0; while(opt) { if(match_regex(filename, opt->strarg) == 1) { included = 1; break; } opt = opt->nextarg; } if(!included) { if(!printinfected) logg("~%s: Excluded\n", filename); return; } } /* argh, don't scan /proc files */ if(CLAMSTAT(filename, &sb) != -1) { #ifdef C_LINUX if(procdev && sb.st_dev == procdev) { if(!printinfected) logg("~%s: Excluded (/proc)\n", filename); return; } #endif if(!sb.st_size) { if(!printinfected) logg("~%s: Empty file\n", filename); return; } info.rblocks += sb.st_size / CL_COUNT_PRECISION; } #ifndef _WIN32 if(geteuid()) { if(checkaccess(filename, NULL, R_OK) != 1) { if(!printinfected) logg("~%s: Access denied\n", filename); info.errors++; return; } } #endif memset(&chain, 0, sizeof(chain)); if(optget(opts, "archive-verbose")->enabled) { chain.chains = malloc(sizeof(char **)); if (chain.chains) { chain.chains[0] = strdup(filename); if (!chain.chains[0]) { free(chain.chains); logg("Unable to allocate memory in scanfile()\n"); info.errors++; return; } chain.nchains = 1; } } logg("*Scanning %s\n", filename); if((fd = safe_open(filename, O_RDONLY|O_BINARY)) == -1) { logg("^Can't open file %s: %s\n", filename, strerror(errno)); info.errors++; return; } data.chain = &chain; data.filename = filename; if((ret = cl_scandesc_callback(fd, &virname, &info.blocks, engine, options, &data)) == CL_VIRUS) { if(optget(opts, "archive-verbose")->enabled) { if (chain.nchains > 1) { char str[128]; int toolong = print_chain(&chain, str, sizeof(str)); logg("~%s%s!(%llu)%s: %s FOUND\n", str, toolong ? "..." : "", (long long unsigned)(chain.lastvir-1), chain.chains[chain.nchains-1], virname); } else if (chain.lastvir) { logg("~%s!(%llu): %s FOUND\n", filename, (long long unsigned)(chain.lastvir-1), virname); } } info.files++; info.ifiles++; if(bell) fprintf(stderr, "\007"); } else if(ret == CL_CLEAN) { if(!printinfected && printclean) mprintf("~%s: OK\n", filename); info.files++; } else { if(!printinfected) logg("~%s: %s ERROR\n", filename, cl_strerror(ret)); info.errors++; } for (i=0;i<chain.nchains;i++) free(chain.chains[i]); free(chain.chains); close(fd); if(ret == CL_VIRUS && action) action(filename); }
int main(int argc, char **argv) { int cnt, x, y, i = 0, verbose = 0; Window win = 0; Bool keysymMappingInitialized = False; int rc = 0; int inputEvents[100]; int inputEventsIndex = 0; int iEvent = 0; if (argc == 1) usage(argv[0]); const char* log_file = NULL; if (streq(argv[1],"-o") || streq(argv[1],"--logfile")) { i++; if (++i > argc) usage(argv[0]); log_file = argv[i]; } report_init(log_file); if (!xhandler_init(getenv("DISPLAY"))) exit(1); report_add_message(xhandler_get_server_time(), "Startup\n"); /* initialize subsystems */ xemu_init(xhandler.display); scheduler_init(xhandler.display); window_init(xhandler.display); application_init(); /* * Process the command line options. * Skip emulation options (--click, --drag, --key, --type), but remember they index * and process them later. */ while (++i < argc) { if (streq(argv[i],"-v") || streq(argv[i],"--verbose")) { verbose = 1; continue; } if (streq(argv[i], "-id") || streq(argv[i], "--id")) { char name[PATH_MAX]; if (++i >= argc) usage(argv[0]); cnt = sscanf(argv[i], "0x%lx", &win); if (cnt < 1) { cnt = sscanf(argv[i], "%lu", &win); } if (cnt < 1) { fprintf(stderr, "*** invalid window id '%s'\n", argv[i]); usage(argv[0]); } sprintf(name, "0x%lx", win); if (!window_add(win, application_monitor(name))) { fprintf(stderr, "Could not setup damage monitoring for window 0x%lx!\n", win); exit(1); } if (verbose) report_add_message(REPORT_LAST_TIMESTAMP, "Monitoring window 0x%lx\n", win); continue; } if (streq(argv[i], "-a") || streq(argv[i], "--application")) { if (++i >= argc) usage(argv[0]); response.application = application_monitor(argv[i]); if (response.application && verbose) { report_add_message(REPORT_LAST_TIMESTAMP, "Monitoring application '%s'\n", argv[i]); } if (!strcmp(argv[i], "*")) { application_set_monitor_all(true); } continue; } if (streq("-c", argv[i]) || streq("--click", argv[i])) { if (!xemu.pointer.dev) { fprintf(stderr, "Failed to open pointer device, unable to simulate pointer events.\n"); exit(-1); } if (inputEventsIndex == ASIZE(inputEvents)) { fprintf(stderr, "Too many input events specified\n"); exit(-1); } if (!argv[i + 1] || !match_regex(argv[i + 1], "^[0-9]+x[0-9]+(,[0-9]+)?$")) { fprintf(stderr, "Failed to parse --c options: %s\n", argv[i + 1]); exit(-1); } inputEvents[inputEventsIndex++] = i; if (++i >= argc) usage(argv[0]); continue; } if (streq("-l", argv[i]) || streq("--level", argv[i])) { if (++i >= argc) usage(argv[0]); if (!strcmp(argv[i], "raw")) { window_set_damage_level(XDamageReportRawRectangles); } else if (!strcmp(argv[i], "delta")) { window_set_damage_level(XDamageReportDeltaRectangles); } else if (!strcmp(argv[i], "box")) { window_set_damage_level(XDamageReportDeltaRectangles); } else if (!strcmp(argv[i], "nonempty")) { window_set_damage_level(XDamageReportNonEmpty); } else { fprintf(stderr, "Unrecongnized damage level: %s\n", argv[i]); usage(argv[0]); } if (verbose) report_add_message(REPORT_LAST_TIMESTAMP, "Setting damage report level to %s\n", argv[i]); continue; } if (streq("-x", argv[i]) || streq("--exclude", argv[i])) { char* exclude[] = { "none", "less", "greater" }; if (options.exclude_rules != EXCLUDE_NONE) { fprintf(stderr, "Duplicated --exclude parameter detected. Aborting\n"); exit(-1); } if (++i >= argc) usage(argv[0]); char rules[32] = ""; if ((cnt = sscanf(argv[i], "%ux%u,%s", &options.exclude_rect.width, &options.exclude_rect.height, rules)) >= 2) { options.exclude_size = 0; } else if ((cnt = sscanf(argv[i], "%u,%s", &options.exclude_size, rules)) >= 1) { options.exclude_rect.width = 0; options.exclude_rect.height = 0; } else { fprintf(stderr, "*** failed to parse '%s'\n", argv[i]); usage(argv[0]); } options.exclude_rules = *rules && !strcmp(rules, "greater") ? EXCLUDE_GREATER : EXCLUDE_LESS; if (verbose) { if (options.exclude_size) { report_add_message(REPORT_LAST_TIMESTAMP, "Excluding damage areas %s than %d pixels\n", exclude[options.exclude_rules], options.exclude_size); } else { report_add_message(REPORT_LAST_TIMESTAMP, "Excluding damage areas %s than (%dx%d)\n", exclude[options.exclude_rules], options.exclude_rect.width, options.exclude_rect.height); } } continue; } if (streq("-m", argv[i]) || streq("--monitor", argv[i])) { if (options.interested_damage_rect.width || options.interested_damage_rect.height || options.interested_damage_rect.x || options.interested_damage_rect.y) { fprintf(stderr, "Duplicated --monitor parameter detected. Aborting\n"); exit(-1); } if (++i >= argc) usage(argv[0]); if ((cnt = sscanf(argv[i], "%ux%u+%u+%u", &options.interested_damage_rect.width, &options.interested_damage_rect.height, &options.interested_damage_rect.x, &options.interested_damage_rect.y)) != 4) { fprintf(stderr, "*** failed to parse '%s'\n", argv[i]); usage(argv[0]); } if (verbose) { report_add_message(REPORT_LAST_TIMESTAMP, "Set monitor rect to %ix%i+%i+%i\n", options.interested_damage_rect.width, options.interested_damage_rect.height, options.interested_damage_rect.x, options.interested_damage_rect.y); } continue; } if (streq("-w", argv[i]) || streq("--wait", argv[i])) { if (++i >= argc) usage(argv[0]); if (options.damage_wait_secs >= 0) { fprintf(stderr, "Duplicate -w(--wait) option detected. Discarding the previous value\n"); } if ((options.damage_wait_secs = atoi(argv[i])) < 0) { fprintf(stderr, "*** failed to parse '%s'\n", argv[i]); usage(argv[0]); } if (verbose) report_add_message(REPORT_LAST_TIMESTAMP, "Set event timeout to %isecs\n", options.damage_wait_secs); continue; } if (streq("-b", argv[i]) || streq("--break", argv[i])) { if (options.break_timeout || options.break_on_damage) { fprintf(stderr, "Duplicate -b(--break)option detected. Discarding the previous value\n"); options.break_timeout = 0; options.break_on_damage = 0; } if (++i >= argc) usage(argv[0]); if (!strncmp(argv[i], "damage", 6)) { sscanf(argv[i] + 6, ",%d", &options.break_on_damage); if (!options.break_on_damage) options.break_on_damage = 1; if (verbose) report_add_message(REPORT_LAST_TIMESTAMP, "Break wait on the %d damage event\n", options.break_on_damage); } else { if ((options.break_timeout = atoi(argv[i])) < 0) { fprintf(stderr, "*** failed to parse '%s'\n", argv[i]); usage(argv[0]); } if (verbose) report_add_message(REPORT_LAST_TIMESTAMP, "Set break timout to %imsecs\n", options.break_timeout); } continue; } if (streq("-d", argv[i]) || streq("--drag", argv[i])) { if (!xemu.pointer.dev) { fprintf(stderr, "Failed to open pointer device, unable to simulate pointer events.\n"); exit(-1); } if (inputEventsIndex == ASIZE(inputEvents)) { fprintf(stderr, "Too many input events specified\n"); exit(-1); } if (!argv[i + 1] || (!match_regex(argv[i + 1], "^([0-9]+,)?(([0-9]+x[0-9]+,([0-9]+,)?)+[0-9]+x[0-9]+)$") && (!match_regex(argv[i + 1], "[0-9]+x[0-9]+-[0-9]+x[0-9]+") || !match_regex(argv[i + 1], "^(((([0-9]+,)?([0-9]+x[0-9]+)|([0-9]+x[0-9]+-[0-9]+x[0-9]+(\\*[0-9]+)?(\\+[1-9][0-9]*)?)),?)+)$") ) ) ) { fprintf(stderr, "Failed to parse --drag options: %s\n", argv[i + 1]); exit(-1); } inputEvents[inputEventsIndex++] = i; if (++i >= argc) usage(argv[0]); continue; } if (streq("-k", argv[i]) || streq("--key", argv[i])) { if (!xemu.keyboard.dev) { fprintf(stderr, "Failed to open keyboard device, unable to simulate keyboard events.\n"); exit(-1); } if (inputEventsIndex == ASIZE(inputEvents)) { fprintf(stderr, "Too many input events specified\n"); exit(-1); } inputEvents[inputEventsIndex++] = i; if (++i >= argc) usage(argv[0]); continue; } if (streq("-t", argv[i]) || streq("--type", argv[i])) { if (!xemu.keyboard.dev) { fprintf(stderr, "Failed to open keyboard device, unable to simulate keyboard events.\n"); exit(-1); } if (inputEventsIndex == ASIZE(inputEvents)) { fprintf(stderr, "Too many input events specified\n"); exit(-1); } inputEvents[inputEventsIndex++] = i; if (++i >= argc) usage(argv[0]); if (!keysymMappingInitialized) { xemu_load_keycodes(); keysymMappingInitialized = True; } continue; } /* since moving from command sequence approach the inspect parameter is deprecated */ if (streq("-i", argv[i]) || streq("--inspect", argv[i])) { if (verbose) report_add_message(REPORT_LAST_TIMESTAMP, "Just displaying damage events until timeout\n"); continue; } /* */ if (streq("-u", argv[i]) || streq("--user", argv[i]) || (xrecord.motion = (streq("-U", argv[i]) || streq("--user-all", argv[i])) ) ) { xinput_init(xhandler.display); if (verbose) report_add_message(REPORT_LAST_TIMESTAMP, "Reporting user input events\n"); continue; } if (streq(argv[i], "-r") || streq(argv[i], "--response")) { if (++i >= argc) usage(argv[0]); char option[500]; cnt = sscanf(argv[i], "%u,%s", &response.timeout, option); if (cnt < 1) { fprintf(stderr, "*** invalid response timeout value '%s'\n", argv[i]); usage(argv[0]); } if (cnt < 2) { report_set_silent(true); } else { if (strcmp(option, "verbose")) { fprintf(stderr, "*** invalid response option '%s'\n", argv[i]); usage(argv[0]); } } application_monitor_screen(); xinput_init(xhandler.display); if (verbose) report_add_message(REPORT_LAST_TIMESTAMP, "Monitoring application response time\n"); continue; } fprintf(stderr, "*** Dont understand %s\n", argv[i]); usage(argv[0]); } /* start monitoring the root window if no targets are specified */ if ((window_empty() && application_empty()) || response.timeout) { application_monitor(ROOT_WINDOW_RESOURCE); } window_monitor_all(); application_start_monitor(); /* eat first damage event when options.break_on_damage set */ if (options.break_on_damage) xhandler_eat_damage(); /* monitor the whole screen of no area is specified */ if (!options.interested_damage_rect.width && !options.interested_damage_rect.height && !options.interested_damage_rect.x && !options.interested_damage_rect.y) { options.interested_damage_rect.x = 0; options.interested_damage_rect.y = 0; options.interested_damage_rect.width = DisplayWidth(xhandler.display, DefaultScreen(xhandler.display)); options.interested_damage_rect.height = DisplayHeight(xhandler.display, DefaultScreen(xhandler.display)); } /* emulate user input */ for (iEvent = 0; iEvent < inputEventsIndex; iEvent++) { i = inputEvents[iEvent]; if (!strcmp("-c", argv[i]) || !strcmp("--click", argv[i])) { unsigned long delay = 0; Time start = 0; cnt = sscanf(argv[++i], "%ux%u,%lu", &x, &y, &delay); if (cnt == 2) { start = xhandler_get_server_time(); report_add_message(start, "Using no delay between press/release\n"); delay = 0; } else if (cnt != 3) { fprintf(stderr, "cnt: %d\n", cnt); fprintf(stderr, "*** failed to parse '%s'\n", argv[i]); usage(argv[0]); } /* Send the event */ start = xemu_button_event(x, y, delay); report_add_message(start, "Clicked %ix%i\n", x, y); continue; } if (!strcmp("-d", argv[i]) || !strcmp("--drag", argv[i])) { Time drag_time; char *s = NULL, *p = NULL; int button_state = XR_BUTTON_STATE_PRESS; s = p = argv[++i]; int delay = DEFAULT_DRAG_DELAY; int x1, y1, x2, y2; while (p) { p = strchr(s, ','); if (p) { *p++ = '\0'; } int count = DEFAULT_DRAG_COUNT; cnt = sscanf(s, "%ix%i-%ix%i*%i+%i", &x1, &y1, &x2, &y2, &delay, &count); if (cnt >= 4) { drag_time = xemu_drag_event(x1, y1, button_state, delay); button_state = XR_BUTTON_STATE_NONE; report_add_message(drag_time, "Dragged to %ix%i\n", x1, y1); int xdev = (x2 - x1) / (count + 1); int ydev = (y2 - y1) / (count + 1); for (i = 1; i <= count; i++) { x = x1 + xdev * i; y = y1 + ydev * i; drag_time = xemu_drag_event(x, y, button_state, delay); report_add_message(drag_time, "Dragged to %ix%i\n", x, y); } if (!p) button_state = XR_BUTTON_STATE_RELEASE; drag_time = xemu_drag_event(x2, y2, button_state, delay); report_add_message(drag_time, "Dragged to %ix%i\n", x2, y2); } else if (cnt == 2) { /* Send the event */ if (!p) { if (button_state == XR_BUTTON_STATE_PRESS) { fprintf(stderr, "*** Need at least 2 drag points!\n"); usage(argv[0]); } button_state = XR_BUTTON_STATE_RELEASE; } drag_time = xemu_drag_event(x1, y1, button_state, delay); report_add_message(drag_time, "Dragged to %ix%i\n", x1, y1); /* Make sure button state set to none after first point */ button_state = XR_BUTTON_STATE_NONE; /* reset the delay to default value */ delay = DEFAULT_DRAG_DELAY; } else if (cnt == 1) { delay = x1; } else { fprintf(stderr, "*** failed to parse '%s'\n", argv[i]); usage(argv[0]); } s = p; } continue; } if (!strcmp("-k", argv[i]) || !strcmp("--key", argv[i])) { char *key = NULL; char separator; unsigned long delay = 0; Time start = 0; cnt = sscanf(argv[++i], "%a[^,]%c%lu", &key, &separator, &delay); if (cnt == 1) { report_add_message(REPORT_LAST_TIMESTAMP, "Using default delay between press/release\n", delay); delay = DEFAULT_KEY_DELAY; } else if (cnt != 3 || separator != ',') { fprintf(stderr, "cnt: %d\n", cnt); fprintf(stderr, "*** failed to parse '%s'\n", argv[i]); if (key != NULL) free(key); usage(argv[0]); } start = xemu_send_key(key, delay); report_add_message(start, "Simulating keypress/-release pair (keycode '%s')\n", key); free(key); continue; } if (!strcmp("-t", argv[i]) || !strcmp("--type", argv[i])) { Time start = xemu_send_string(argv[++i]); report_add_message(start, "Simulated keys for '%s'\n", argv[i]); continue; } } /* setting the default wait period */ if (options.damage_wait_secs < 0) { options.damage_wait_secs = 5; } signal(SIGINT, abort_wait); /* wait for damage events */ rc = wait_response(); scheduler_fini(); report_flush_queue(); report_fini(); xinput_fini(); xemu_fini(); window_fini(); application_fini(); xhandler_fini(); return rc; }