DWORD RegGetMatchingFilePathsInFolder( PCSTR pszDirPath, PCSTR pszFileNameRegExp, PSTR** pppszHostFilePaths, PDWORD pdwNPaths ) { typedef struct __PATHNODE { PSTR pszPath; struct __PATHNODE *pNext; } *PPATHNODE; DWORD dwError = 0; DIR* pDir = NULL; struct dirent* pDirEntry = NULL; regex_t rx; BOOLEAN rxAllocated = FALSE; regmatch_t* pResult = NULL; size_t nMatch = 1; DWORD dwNPaths = 0; DWORD iPath = 0; PSTR* ppszHostFilePaths = NULL; CHAR szBuf[PATH_MAX+1]; struct stat statbuf; PPATHNODE pPathList = NULL; PPATHNODE pPathNode = NULL; BOOLEAN bDirExists = FALSE; dwError = RegCheckDirectoryExists(pszDirPath, &bDirExists); BAIL_ON_REG_ERROR(dwError); if(!bDirExists) { dwError = ENOENT; BAIL_ON_REG_ERROR(dwError); } if (regcomp(&rx, pszFileNameRegExp, REG_EXTENDED) != 0) { dwError = LWREG_ERROR_REGEX_COMPILE_FAILED; BAIL_ON_REG_ERROR(dwError); } rxAllocated = TRUE; dwError = RegAllocateMemory(sizeof(*pResult), (PVOID*)&pResult); BAIL_ON_REG_ERROR(dwError); pDir = opendir(pszDirPath); if (!pDir) { dwError = errno; BAIL_ON_REG_ERROR(dwError); } while ((pDirEntry = readdir(pDir)) != NULL) { int copied = snprintf( szBuf, sizeof(szBuf), "%s/%s", pszDirPath, pDirEntry->d_name); if (copied >= sizeof(szBuf)) { //Skip pathnames that are too long continue; } memset(&statbuf, 0, sizeof(struct stat)); if (lstat(szBuf, &statbuf) < 0) { if(errno == ENOENT) { //This occurs when there is a symbolic link pointing to a //location that doesn't exist, because stat looks at the final //file, not the link. Since this file doesn't exist anyway, //just skip it. continue; } dwError = errno; BAIL_ON_REG_ERROR(dwError); } /* * For now, we are searching only for regular files * This may be enhanced in the future to support additional * file system entry types */ if (((statbuf.st_mode & S_IFMT) == S_IFREG) && (regexec(&rx, pDirEntry->d_name, nMatch, pResult, 0) == 0)) { dwNPaths++; dwError = RegAllocateMemory(sizeof(*pPathNode), (PVOID*)&pPathNode); BAIL_ON_REG_ERROR(dwError); dwError = RegCStringDuplicate(&pPathNode->pszPath, szBuf); BAIL_ON_REG_ERROR(dwError); pPathNode->pNext = pPathList; pPathList = pPathNode; pPathNode = NULL; } } if (pPathList) { dwError = RegAllocateMemory(sizeof(*ppszHostFilePaths)*dwNPaths, (PVOID*)&ppszHostFilePaths); BAIL_ON_REG_ERROR(dwError); /* * The linked list is in reverse. * Assign values in reverse to get it right */ iPath = dwNPaths-1; pPathNode = pPathList; while (pPathNode) { *(ppszHostFilePaths+iPath) = pPathNode->pszPath; pPathNode->pszPath = NULL; pPathNode = pPathNode->pNext; iPath--; } } *pppszHostFilePaths = ppszHostFilePaths; *pdwNPaths = dwNPaths; cleanup: if (pPathNode) { LWREG_SAFE_FREE_STRING(pPathNode->pszPath); RegMemoryFree(pPathNode); } while(pPathList) { pPathNode = pPathList; pPathList = pPathList->pNext; LWREG_SAFE_FREE_STRING(pPathNode->pszPath); RegMemoryFree(pPathNode); } if (rxAllocated) { regfree(&rx); } LWREG_SAFE_FREE_MEMORY(pResult); if (pDir) { closedir(pDir); } return dwError; error: if (ppszHostFilePaths) { RegFreeStringArray(ppszHostFilePaths, dwNPaths); } goto cleanup; }
/* * Validate the entered configuration. Display and error message * if required. */ static int parse_config_gui(E_Config_Dialog_Data *cfdata) { E_Dialog *error_popup; char error_message[1024]; int config_ok = 1; char *end_pointer; float parsed_float; const char *text_value; regex_t *reg_expression; int regex_result; char *viewpos_file; float lat, lon; sprintf(error_message, "The configuration you have entered is invalid:<br>"); if (cfdata->local_xplanet.source_type == SOURCE_ORIGIN) cfdata->local_xplanet.origin = strdup(e_widget_ilist_selected_value_get(cfdata->gui.o_source_ilist)); else cfdata->local_xplanet.projection = strdup(e_widget_ilist_selected_value_get(cfdata->gui.o_source_ilist)); if (cfdata->local_xplanet.source_type == SOURCE_ORIGIN) { if (strcmp(cfdata->local_xplanet.body, "random") && !strcmp(cfdata->local_xplanet.body, cfdata->local_xplanet.origin)) { sprintf(error_message + strlen(error_message), "<br>* Target and origin cannot be the same."); config_ok = 0; } } switch (cfdata->local_xplanet.viewpos_type) { case VIEWPOS_LATLON: { end_pointer = (char *)e_widget_entry_text_get(cfdata->gui.o_viewpos_lat); if (strlen(end_pointer) == 0) { sprintf(error_message + strlen(error_message), "<br>* You must enter a latitude."); config_ok = 0; } else { parsed_float = strtof(e_widget_entry_text_get(cfdata->gui.o_viewpos_lat), &end_pointer); if (*end_pointer != '\0' || parsed_float < -90.0 || parsed_float > 90.0) { sprintf(error_message + strlen(error_message), "<br>* The entered latitude is invalid - must be in the range -90 to 90."); config_ok = 0; } else cfdata->local_xplanet.viewpos_lat = parsed_float; } end_pointer = (char *)e_widget_entry_text_get(cfdata->gui.o_viewpos_lon); if (strlen(end_pointer) == 0) { sprintf(error_message + strlen(error_message), "<br>* You must enter a longitude."); config_ok = 0; } else { parsed_float = strtof(e_widget_entry_text_get(cfdata->gui.o_viewpos_lon), &end_pointer); if (*end_pointer != '\0' || parsed_float < -180.0 || parsed_float > 360.0) { sprintf(error_message + strlen(error_message), "<br>* The entered longitude is invalid - must be in the range 0 to 360 or -180 to 180"); config_ok = 0; } else cfdata->local_xplanet.viewpos_lon = parsed_float; } break; } case VIEWPOS_FILE: { lat = INVALID_COORD; lon = INVALID_COORD; viewpos_file = (char *)e_widget_entry_text_get(cfdata->gui.o_viewpos_file_val); switch(read_viewpos_file(viewpos_file, &lat, &lon)) { case VIEWPOS_FILE_NO_PERM: { sprintf(error_message + strlen(error_message), "<br>* No permissions to read viewing position file"); config_ok = 0; break; } case VIEWPOS_FILE_NOT_FOUND: { sprintf(error_message + strlen(error_message), "<br>* The viewing position file cannot be found"); config_ok = 0; break; } case VIEWPOS_FILE_IS_DIR: { sprintf(error_message + strlen(error_message), "<br>* The viewing position file is a directory"); config_ok = 0; break; } case VIEWPOS_FILE_FORMAT_ERROR: { sprintf(error_message + strlen(error_message), "<br>* The viewing position file is in the wrong format (must be 2 numbers, lat then lon)"); config_ok = 0; break; } case VIEWPOS_FILE_OK: cfdata->local_xplanet.viewpos_file = (char *)eina_stringshare_add(viewpos_file); break; } break; } default: break; } cfdata->local_xplanet.use_localtime = e_widget_check_checked_get(cfdata->gui.o_use_localtime); cfdata->local_xplanet.localtime = cfdata->gui.o_localtime; cfdata->local_xplanet.show_label = e_widget_check_checked_get(cfdata->gui.o_show_label); cfdata->local_xplanet.label_text = strdup(e_widget_entry_text_get(cfdata->gui.o_label_text)); text_value = strdup(e_widget_entry_text_get(cfdata->gui.o_label_pos_other_text)); if (!text_value || strlen(text_value) == 0) { cfdata->local_xplanet.label_pos_other = ""; if (cfdata->local_xplanet.label_pos == LABEL_POS_OTHER) { sprintf(error_message + strlen(error_message), "<br>* You have not entered a label position"); config_ok = 0; } } else { reg_expression = E_NEW(regex_t, 1); regcomp(reg_expression, "^[+-][0-9][0-9]*[+-][0-9][0-9]*$", 0); regex_result = regexec(reg_expression, text_value, 0, NULL, 0); if (regex_result) { sprintf(error_message + strlen(error_message), "<br>* The entered label position is invalid - must be of the form -15+15"); config_ok = 0; } else cfdata->local_xplanet.label_pos_other = text_value; regfree(reg_expression); free(reg_expression); } cfdata->local_xplanet.use_config = e_widget_check_checked_get(cfdata->gui.o_config_check); cfdata->local_xplanet.config_name = strdup(e_widget_entry_text_get(cfdata->gui.o_config_name)); cfdata->local_xplanet.extra_options = strdup(e_widget_entry_text_get(cfdata->gui.o_extra_options)); if (!config_ok) { error_popup = e_dialog_new(e_container_current_get( e_manager_current_get()), "eplanet_error", "eplanet/error"); e_dialog_title_set(error_popup, "Configuration error"); e_dialog_text_set(error_popup, (const char *) &error_message); e_dialog_button_add(error_popup, D_("OK"), NULL, NULL, NULL); e_dialog_show(error_popup); } return config_ok; }
BPatch_Vector<BPatch_function *> * BPatch_module::findFunctionInt(const char *name, BPatch_Vector<BPatch_function *> & funcs, bool notify_on_failure, bool regex_case_sensitive, bool incUninstrumentable, bool dont_use_regex) { if (hasBeenRemoved_) return NULL; unsigned size = funcs.size(); if (!name) { char msg[512]; sprintf(msg, "%s[%d]: Module %s: findFunction(NULL)... failing", __FILE__, __LINE__, mod->fileName().c_str()); BPatch_reportError(BPatchSerious, 100, msg); return NULL; } // Do we want regex? if (dont_use_regex || (NULL == strpbrk(name, REGEX_CHARSET))) { pdvector<int_function *> int_funcs; if (mod->findFuncVectorByPretty(name, int_funcs)) { for (unsigned piter = 0; piter < int_funcs.size(); piter++) { if (incUninstrumentable || int_funcs[piter]->isInstrumentable()) { BPatch_function * bpfunc = proc->findOrCreateBPFunc(int_funcs[piter], this); funcs.push_back(bpfunc); } } } else { if (mod->findFuncVectorByMangled(name, int_funcs)) { for (unsigned miter = 0; miter < int_funcs.size(); miter++) { if (incUninstrumentable || int_funcs[miter]->isInstrumentable()) { BPatch_function * bpfunc = proc->findOrCreateBPFunc(int_funcs[miter], this); funcs.push_back(bpfunc); } } } } if (size != funcs.size()) return &funcs; } else { // Regular expression search. As with BPatch_image, we handle it here #if !defined(i386_unknown_nt4_0) && !defined(mips_unknown_ce2_11) // no regex for M$ // REGEX falls through: regex_t comp_pat; int err, cflags = REG_NOSUB | REG_EXTENDED; if( !regex_case_sensitive ) cflags |= REG_ICASE; //cerr << "compiling regex: " <<name<<endl; if (0 != (err = regcomp( &comp_pat, name, cflags ))) { char errbuf[80]; regerror( err, &comp_pat, errbuf, 80 ); if (notify_on_failure) { cerr << __FILE__ << ":" << __LINE__ << ": REGEXEC ERROR: "<< errbuf << endl; pdstring msg = pdstring("Image: Unable to find function pattern: ") + pdstring(name) + ": regex error --" + pdstring(errbuf); BPatch_reportError(BPatchSerious, 100, msg.c_str()); } // remove this line //cerr << __FILE__ << ":" << __LINE__ << ": REGEXEC ERROR: "<< errbuf << endl; return NULL; } // Regular expression search. This used to be handled at the image // class level, but was moved up here to simplify semantics. We // have to iterate over every function known to the process at some // point, so it might as well be top-level. This is also an // excellent candidate for a "value-added" library. const pdvector<int_function *> &int_funcs = mod->getAllFunctions(); for (unsigned ai = 0; ai < int_funcs.size(); ai++) { int_function *func = int_funcs[ai]; // If it matches, push onto the vector // Check all pretty names (and then all mangled names if there is no match) bool found_match = false; for (unsigned piter = 0; piter < func->prettyNameVector().size(); piter++) { const pdstring &pName = func->prettyNameVector()[piter]; int err; if (0 == (err = regexec(&comp_pat, pName.c_str(), 1, NULL, 0 ))){ if (func->isInstrumentable() || incUninstrumentable) { BPatch_function *foo = proc->findOrCreateBPFunc(func, NULL); funcs.push_back(foo); } found_match = true; break; } } if (found_match) continue; // Don't check mangled names for (unsigned miter = 0; miter < func->symTabNameVector().size(); miter++) { const pdstring &mName = func->symTabNameVector()[miter]; int err; if (0 == (err = regexec(&comp_pat, mName.c_str(), 1, NULL, 0 ))){ if (func->isInstrumentable() || incUninstrumentable) { BPatch_function *foo = proc->findOrCreateBPFunc(func, NULL); funcs.push_back(foo); } found_match = true; break; } } } regfree(&comp_pat); if (funcs.size() != size) { return &funcs; } if (notify_on_failure) { pdstring msg = pdstring("Unable to find pattern: ") + pdstring(name); BPatch_reportError(BPatchSerious, 100, msg.c_str()); } #endif } if(notify_on_failure) { char msg[1024]; sprintf(msg, "%s[%d]: Module %s: unable to find function %s", __FILE__, __LINE__, mod->fileName().c_str(), name); BPatch_reportError(BPatchSerious, 100, msg); } return &funcs; }
/* mknod in /dev based on a path like "/sys/block/hda/hda1" */ static void make_device(char *path) { char *device_name,*s; int major,minor,type,len,fd; int mode=0660; uid_t uid=0; gid_t gid=0; RESERVE_CONFIG_BUFFER(temp,PATH_MAX); /* Try to read major/minor string */ snprintf(temp, PATH_MAX, "%s/dev", path); fd = open(temp, O_RDONLY); len = read(fd, temp, PATH_MAX-1); if (len<1) goto end; temp[len] = 0; close(fd); /* Determine device name, type, major and minor */ device_name = strrchr(path, '/') + 1; type = strncmp(path+5, "block/" ,6) ? S_IFCHR : S_IFBLK; major = minor = 0; for (s = temp; *s; s++) { if (*s == ':') { major = minor; minor = 0; } else { minor *= 10; minor += (*s) - '0'; } } /* If we have a config file, look up permissions for this device */ if (ENABLE_FEATURE_MDEV_CONF) { char *conf,*pos,*end; /* mmap the config file */ if (-1!=(fd=open("/etc/mdev.conf",O_RDONLY))) { len=lseek(fd,0,SEEK_END); conf=mmap(NULL,len,PROT_READ,MAP_PRIVATE,fd,0); if (conf) { int line=0; /* Loop through lines in mmaped file*/ for (pos=conf;pos-conf<len;) { int field; char *end2; line++; /* find end of this line */ for(end=pos;end-conf<len && *end!='\n';end++); /* Three fields: regex, uid:gid, mode */ for (field=3;field;field--) { /* Skip whitespace */ while (pos<end && isspace(*pos)) pos++; if (pos==end || *pos=='#') break; for (end2=pos; end2<end && !isspace(*end2) && *end2!='#'; end2++); switch(field) { /* Regex to match this device */ case 3: { char *regex=strndupa(pos,end2-pos); regex_t match; regmatch_t off; int result; /* Is this it? */ xregcomp(&match,regex,REG_EXTENDED); result=regexec(&match,device_name,1,&off,0); regfree(&match); /* If not this device, skip rest of line */ if(result || off.rm_so || off.rm_eo!=strlen(device_name)) goto end_line; break; } /* uid:gid */ case 2: { char *s2; /* Find : */ for(s=pos;s<end2 && *s!=':';s++); if(s==end2) goto end_line; /* Parse UID */ uid=strtoul(pos,&s2,10); if(s!=s2) { struct passwd *pass; pass=getpwnam(strndupa(pos,s-pos)); if(!pass) goto end_line; uid=pass->pw_uid; } s++; /* parse GID */ gid=strtoul(s,&s2,10); if(end2!=s2) { struct group *grp; grp=getgrnam(strndupa(s,end2-s)); if(!grp) goto end_line; gid=grp->gr_gid; } break; } /* mode */ case 1: { mode=strtoul(pos,&pos,8); if(pos!=end2) goto end_line; goto found_device; } } pos=end2; } end_line: /* Did everything parse happily? */ if (field && field!=3) bb_error_msg_and_die("Bad line %d",line); /* Next line */ pos=++end; } found_device: munmap(conf,len); } close(fd); } } sprintf(temp, "%s/%s", DEV_PATH, device_name); umask(0); if (mknod(temp, mode | type, makedev(major, minor)) && errno != EEXIST) bb_perror_msg_and_die("mknod %s failed", temp); if (ENABLE_FEATURE_MDEV_CONF) chown(temp,uid,gid); end: RELEASE_CONFIG_BUFFER(temp); }
/* get_compiled_regex: Return pointer to compiled regex from command buffer. */ regex_t * get_compiled_regex (unsigned dc, int re_type, ed_buffer_t *ed) { static const char *compile_err = NULL; static regex_t *re_search = NULL; /* search regex */ static regex_t *re_subst = NULL; /* substitution regex */ regex_t *re = NULL; #ifndef HAVE_REG_SYNTAX_T static char re_err[BUFSIZ]; /* regex error message buffer */ #endif char *pattern; size_t len = 0; #ifndef HAVE_REG_SYNTAX_T int status; #endif if (isspace (dc) && dc != '\n') { ed->exec->err = _("Invalid pattern delimiter"); return NULL; } /* Assert: spl1 () */ /* Use previous pattern. */ if (dc == '\n' || *++ed->input == '\n' || *ed->input == dc) { /* * For a substitution command, there may be two patterns * available: one from previous search and one from previous * substitution. In the case of an empty pattern (e.g., ed * command `s///'), the previous substitution pattern is used * only if there was no previous search. In the case of a * repeated substitution, (e.g., `s' => dc == '\n'), the * previous search pattern is used only if explicitly requested * via `r' modifier (i.e., `sr' => r_f). * * Some cases to consider... * * I. Sequences beginning: Effect: * s/abc/ * 1) * s s/abc/ - by definition. * 2) * s// s/abc/ - no previous search. * 3) * sr s/abc/ - no previous search. (?) * 4) * // /abc/ - no previous search. * 5) * //s /abc/s/abc/ - by (I.4) and (I.1). * 6) * //s// /abc/s/abc/ - by (I.4) and definition * of `s//'. * 7) * //sr /abc/s/abc/ - by (I.4) and defintion * of `sr'. * * II. Sequences beginning: * /xyz/ * 1) * s s/xyz/ - no previous substitution. * 2) * s// s/xyz/ - by definition. * 3) * sr s/xyz/ - by definition. * 4) * // /xyz/ - by definition. * 5) * //s /xyz/s/xyz/ - by (II.4) and (II.1). * 6) * //s// /xyz/s/xyz/ - by (II.4) and definition * of `s//'. * 7) * //sr /xyz/s/xyz/ - by (II.4) and definition * of `sr'. * * III. Sequences beginning: * s/abc/ * /xyz/ * 1) * s s/abc/ - by (I.1). * 2) * s// s/xyz/ - by (II.2). * 3) * sr s/xyz/ - by (II.3). * 4) * // /xyz/ - by (II.4). * 5) * //s /xyz/s/abc/ - by (II.4) and (I.1). * 6) * //s// /xyz/s/xyz/ - by (II.4) and (II.2). * 7) * //sr /xyz/s/xyz/ - by (II.4) and (II.3). * * IV. Sequences beginning: * /xyz/ * s/abc/ * 1) * s s/abc/ - by (I.1). * 2) * s// s/xyz/ - by (II.2). * 3) * sr s/xyz/ - by (II.3). * 4) * // /xyz/ - by (II.4). * 5) * //s /xyz/s/abc/ - by (II.4) and (I.1). * 6) * //s// /xyz/s/xyz/ - by (II.4) and (II.2). * 7) * //sr /xyz/s/xyz/ - by (II.4) and (II.3). * */ switch (re_type) { case RE_SUBST: re = ((dc != '\n' && re_search) || ed->exec->subst->r_f ? re_search : re_subst); if (!re_subst) re_subst = re; break; case RE_SEARCH: re = re_search ? re_search : re_subst; if (!re_search) re_search = re; break; } if (!re) ed->exec->err = _("No previous pattern"); return re; } if (!(pattern = regular_expression (dc, &len, ed))) return NULL; if (!(re = (regex_t *) malloc (sizeof (regex_t)))) { fprintf (stderr, "%s\n", strerror (errno)); ed->exec->err = _("Memory exhausted"); return NULL; } #ifdef HAVE_REG_SYNTAX_T /* GNU regcomp () has no hooks for setting re_syntax_options, and pattern cannot contain NUL chars, so use re_compile_pattern (). */ re->translate = NULL; re->fastmap = NULL; re->buffer = NULL; re->allocated = 0; if ((compile_err = re_compile_pattern (pattern, len, re))) { regfree (re); free (re); ed->exec->err = compile_err; return NULL; } #else # ifdef REG_ENHANCED /* Darwin regcomp () supports enhanced basic and extended regular expressions. */ re->re_endp = pattern + len; if (status = regcomp (re, pattern, (REG_PEND | REG_ENHANCED | (ed->exec->opt & REGEX_EXTENDED ? REG_EXTENDED : 0)))) # else # ifdef REG_PEND /* BSD regcomp () accepts pattern with NUL chars via REG_PEND, but has no equivalent of GNU's re_syntax_options. */ re->re_endp = pattern + len; if (status = regcomp (re, pattern, (REG_PEND | (ed->exec->opt & REGEX_EXTENDED ? REG_EXTENDED : 0)))) # else /* Use generic POSIX regular expression library. */ if (status = regcomp (re, pattern, (ed->exec->opt & REGEX_EXTENDED ? REG_EXTENDED : 0))) # endif /* !defined (REG_PEND) */ # endif /* !defined (REG_ENHANCED) */ { regerror (status, re, re_err, sizeof re_err); ed->exec->err = re_err; free (re); return NULL; } #endif /* !defined (HAVE_REG_SYNTAX_T) */ switch (re_type) { case RE_SUBST: if (re_subst && re_subst != re_search) { regfree (re_subst); free (re_subst); } re_subst = re; break; case RE_SEARCH: if (re_search && re_search != re_subst) { regfree (re_search); free (re_search); } re_search = re; break; } return re; }
void gen(Node *n) { Node *l, nod; Prog *sp, *spc, *spb; Case *cn; long sbc, scc; int snbreak, sncontin; int f, o, oldreach; loop: if(n == Z) return; nearln = n->lineno; o = n->op; if(debug['G']) if(o != OLIST) print("%L %O\n", nearln, o); if(!canreach) { switch(o) { case OLABEL: case OCASE: case OLIST: case OBREAK: case OFOR: case OWHILE: case ODWHILE: /* all handled specially - see switch body below */ break; default: if(warnreach) { warn(n, "unreachable code %O", o); warnreach = 0; } } } switch(o) { default: complex(n); cgen(n, Z); break; case OLIST: gen(n->left); rloop: n = n->right; goto loop; case ORETURN: canreach = 0; warnreach = !suppress; complex(n); if(n->type == T) break; l = n->left; if(l == Z) { noretval(3); gbranch(ORETURN); break; } if(typecmplx[n->type->etype]) { sugen(l, nodret, n->type->width); noretval(3); gbranch(ORETURN); break; } regret(&nod, n); cgen(l, &nod); regfree(&nod); if(typefd[n->type->etype]) noretval(1); else noretval(2); gbranch(ORETURN); break; case OLABEL: canreach = 1; l = n->left; if(l) { l->pc = pc; if(l->label) patch(l->label, pc); } gbranch(OGOTO); /* prevent self reference in reg */ patch(p, pc); goto rloop; case OGOTO: canreach = 0; warnreach = !suppress; n = n->left; if(n == Z) return; if(n->complex == 0) { diag(Z, "label undefined: %s", n->sym->name); return; } if(suppress) return; gbranch(OGOTO); if(n->pc) { patch(p, n->pc); return; } if(n->label) patch(n->label, pc-1); n->label = p; return; case OCASE: canreach = 1; l = n->left; if(cases == C) diag(n, "case/default outside a switch"); if(l == Z) { newcase(); cases->val = 0; cases->def = 1; cases->label = pc; cases->isv = 0; goto rloop; } complex(l); if(l->type == T) goto rloop; if(l->op == OCONST) if(typeword[l->type->etype] && l->type->etype != TIND) { newcase(); cases->val = l->vconst; cases->def = 0; cases->label = pc; cases->isv = typev[l->type->etype]; goto rloop; } diag(n, "case expression must be integer constant"); goto rloop; case OSWITCH: l = n->left; complex(l); if(l->type == T) break; if(!typechlvp[l->type->etype] || l->type->etype == TIND) { diag(n, "switch expression must be integer"); break; } gbranch(OGOTO); /* entry */ sp = p; cn = cases; cases = C; newcase(); sbc = breakpc; breakpc = pc; snbreak = nbreak; nbreak = 0; gbranch(OGOTO); spb = p; gen(n->right); /* body */ if(canreach){ gbranch(OGOTO); patch(p, breakpc); nbreak++; } patch(sp, pc); doswit(l); patch(spb, pc); cases = cn; breakpc = sbc; canreach = nbreak!=0; if(canreach == 0) warnreach = !suppress; nbreak = snbreak; break; case OWHILE: case ODWHILE: l = n->left; gbranch(OGOTO); /* entry */ sp = p; scc = continpc; continpc = pc; gbranch(OGOTO); spc = p; sbc = breakpc; breakpc = pc; snbreak = nbreak; nbreak = 0; gbranch(OGOTO); spb = p; patch(spc, pc); if(n->op == OWHILE) patch(sp, pc); bcomplex(l, Z); /* test */ patch(p, breakpc); if(l->op != OCONST || vconst(l) == 0) nbreak++; if(n->op == ODWHILE) patch(sp, pc); gen(n->right); /* body */ gbranch(OGOTO); patch(p, continpc); patch(spb, pc); continpc = scc; breakpc = sbc; canreach = nbreak!=0; if(canreach == 0) warnreach = !suppress; nbreak = snbreak; break; case OFOR: l = n->left; if(!canreach && l->right->left && warnreach) { warn(n, "unreachable code FOR"); warnreach = 0; } gen(l->right->left); /* init */ gbranch(OGOTO); /* entry */ sp = p; /* * if there are no incoming labels in the * body and the top's not reachable, warn */ if(!canreach && warnreach && deadheads(n)) { warn(n, "unreachable code %O", o); warnreach = 0; } scc = continpc; continpc = pc; gbranch(OGOTO); spc = p; sbc = breakpc; breakpc = pc; snbreak = nbreak; nbreak = 0; sncontin = ncontin; ncontin = 0; gbranch(OGOTO); spb = p; patch(spc, pc); gen(l->right->right); /* inc */ patch(sp, pc); if(l->left != Z) { /* test */ bcomplex(l->left, Z); patch(p, breakpc); if(l->left->op != OCONST || vconst(l->left) == 0) nbreak++; } canreach = 1; gen(n->right); /* body */ if(canreach){ gbranch(OGOTO); patch(p, continpc); ncontin++; } if(!ncontin && l->right->right && warnreach) { warn(l->right->right, "unreachable FOR inc"); warnreach = 0; } patch(spb, pc); continpc = scc; breakpc = sbc; canreach = nbreak!=0; if(canreach == 0) warnreach = !suppress; nbreak = snbreak; ncontin = sncontin; break; case OCONTINUE: if(continpc < 0) { diag(n, "continue not in a loop"); break; } gbranch(OGOTO); patch(p, continpc); ncontin++; canreach = 0; warnreach = !suppress; break; case OBREAK: if(breakpc < 0) { diag(n, "break not in a loop"); break; } /* * Don't complain about unreachable break statements. * There are breaks hidden in yacc's output and some people * write return; break; in their switch statements out of habit. * However, don't confuse the analysis by inserting an * unreachable reference to breakpc either. */ if(!canreach) break; gbranch(OGOTO); patch(p, breakpc); nbreak++; canreach = 0; warnreach = !suppress; break; case OIF: l = n->left; if(bcomplex(l, n->right)) { if(typefd[l->type->etype]) f = !l->fconst; else f = !l->vconst; if(debug['c']) print("%L const if %s\n", nearln, f ? "false" : "true"); if(f) { canreach = 1; supgen(n->right->left); oldreach = canreach; canreach = 1; gen(n->right->right); /* * treat constant ifs as regular ifs for * reachability warnings. */ if(!canreach && oldreach && debug['w'] < 2) warnreach = 0; } else { canreach = 1; gen(n->right->left); oldreach = canreach; canreach = 1; supgen(n->right->right); /* * treat constant ifs as regular ifs for * reachability warnings. */ if(!oldreach && canreach && debug['w'] < 2) warnreach = 0; canreach = oldreach; } } else { sp = p; canreach = 1; if(n->right->left != Z) gen(n->right->left); oldreach = canreach; canreach = 1; if(n->right->right != Z) { gbranch(OGOTO); patch(sp, pc); sp = p; gen(n->right->right); } patch(sp, pc); canreach = canreach || oldreach; if(canreach == 0) warnreach = !suppress; } break; case OSET: case OUSED: usedset(n->left, o); break; } }
void regicide(char * spec, char * s) { regex_t regex; int reti; char msgbuf[100]; regmatch_t matches[NUMM]; /* Compile regular expression */ reti = regcomp(®ex, spec, 0); if (reti) { regerror(reti, ®ex, msgbuf, sizeof(msgbuf)); fprintf(stderr, "Could not compile regex: %s\n", msgbuf); exit(1); } /* Execute regular expression */ reti = regexec(®ex, s, NUMM, matches, 0); if (!reti) { if (DETAIL) { puts("MATCH"); puts("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv"); } puts("---------"); int j; for (j = matches[2].rm_so; j < matches[2].rm_eo; j++) { putchar(s[j]); } printf("\n"); puts(s); if (DETAIL) { /* show matches */ int i; for (i = 1; i < NUMM; i++) { printf("%d%d%d%d%d%d%d%d%d%d%d\n",i,i,i,i,i,i,i,i,i,i,i); printf("%d %d\n", matches[i].rm_so, matches[i].rm_eo); int j; for (j = matches[i].rm_so; j < matches[i].rm_eo; j++) { putchar(s[j]); } printf("\n"); } puts("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"); } } else if (reti == REG_NOMATCH) { puts("NOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO"); puts("NOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO"); puts("NOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO"); puts("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv"); puts(s); puts("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"); } else { regerror(reti, ®ex, msgbuf, sizeof(msgbuf)); fprintf(stderr, "Regex match failed: %s\n", msgbuf); exit(1); } /* Free compiled regular expression if you want to use the regex_t again */ regfree(®ex); }
void retr_handler(int id_msg, char * sortie){ if(sortie != NULL) sortie[0]='\0'; char buff_req[64]; sprintf(buff_req, "RETR %d\r\n", id_msg); if(fwrite(buff_req, strlen(buff_req), sizeof(char), fsock) == -1){ perror("Error write in socket"); exit(EXIT_FAILURE); } regex_t r; int status= regcomp(&r, regex_content_type, REG_EXTENDED | REG_NEWLINE); if(status != 0){ printf("Error: regcomp regex\n"); exit(EXIT_FAILURE); } char* ext= (char*) malloc(sizeof(char) * MAXEXTLENGTH); strcpy(ext, "txt"); char buff_ans[128]; char* boundary=(char*) malloc(sizeof(char) * LINELENGTH); boundary[0]='-'; boundary[1]='-'; //recuperation reponse bool multipart=annalyser_Entete(r, ext, boundary+2); FILE* out=NULL; char name_file[LINELENGTH]; char dir_name[LINELENGTH]; dir_name[0]='\0'; if(multipart == true){ sprintf(dir_name, "%d", id_msg); mkdir(dir_name, 0744); // pas de verification, si le dossier est absent, // on le cree sinon on peut deja ajouter les fichiers sprintf(dir_name,"%s/", dir_name); int size_tmp= strlen(boundary); boundary[size_tmp]= '-'; // on ajouter les caracteres au bondary pour boundary[size_tmp+1]= '-'; // avoir chaine delimitant la fin du mail boundary[size_tmp+2]= '\r'; boundary[size_tmp+3]= '\n'; boundary[size_tmp+4]= '\0'; int premier_bound=0; while(strcmp(fgets(buff_ans, 128, fsock), boundary)!=0){ // on parcours toutes parties if(strncmp(buff_ans, boundary, strlen(boundary) - 4) == 0){ if(out != NULL) fclose(out); char* uselessBoundary=NULL; multipart= annalyser_Entete(r, ext, uselessBoundary); if(multipart){ printf("Error email format\n"); exit(EXIT_FAILURE); } sprintf(name_file, "%s%d.%s", dir_name, id_msg, ext); out= fopen(name_file, "w+"); if(out == NULL){ perror("Error open file out RETR"); exit(EXIT_FAILURE); } if(strcmp(ext,"asc") != 0 && strcmp(ext,"txt") != 0){ premier_bound++; } premier_bound++; } else{ if( out!= NULL) fprintf(out, "%s", buff_ans); if( sortie != NULL && premier_bound == 1){ strcat(sortie, buff_ans); } } } while(strcmp(fgets(buff_ans, 128, fsock), ".\r\n")!=0){} // vide la fin du mail qui ne contient plus de fichier } else{ //si c'est un mail simple sprintf(name_file, "%s%d.%s", dir_name, id_msg, ext); out= fopen(name_file, "w+"); if(out == NULL){ perror("Error open file out RETR"); exit(EXIT_FAILURE); } while(strcmp(fgets(buff_ans, 128, fsock), ".\r\n")!=0){ fprintf(out, "%s", buff_ans); if(sortie != NULL){ strcat(sortie, buff_ans); } } fclose(out); } free(ext); regfree(&r); }
int main(int argc, char** argv) { FILE* fp = NULL; // file pointer for input file char* line = NULL; // line of input size_t len = 0; // length of input read ssize_t read = 0; // length of line int regex_error = 0; // regex error in execution regmatch_t pm[6]; // regex matches long offset = 0; // offset of regex match int r_len = 0; // length of matched object char result[256]; // buffer to hold match char* end; // end pointer used in string conversions // false: OFF; true: ON // also works with enum Command long lights[1000][1000] = { 0 }; // lights 2D array long start_pos[2]; // starting position of command long end_pos[2]; // ending position of command long i = 0; // temp ; x-axis long j = 0; // temp ; y-axis long brightness = 0; // counter for brightness Command command = OFF; // parsed command // Compile regex if (regcomp(&r_compiled, pattern, REG_EXTENDED)) { printf("Regex compilation error.\n"); return -1; } // open and read file line by line fp = fopen("./input.txt", "r"); while((read=getline(&line, &len, fp)) != -1) { // execute regex to extract matches // if there's any error, exit the program regex_error = regexec(&r_compiled, line, 6, pm, REG_EXTENDED); if (regex_error == REG_NOMATCH) { printf("No matches.\n"); return -1; } // COMMAND // get length of command, and copy to buffer. r_len = pm[1].rm_eo - pm[1].rm_so; memcpy(result, line + pm[1].rm_so, r_len); result[len] = '\0'; // set // parse result into enum Command command = parse_command(result); // START POS (x) len = pm[2].rm_eo - pm[2].rm_so; start_pos[0] = strtol(line + pm[2].rm_so, &end, 10); // START POS (y) len = pm[3].rm_eo - pm[3].rm_so; start_pos[1] = strtol(line + pm[3].rm_so, &end, 10); // END POS (x) len = pm[4].rm_eo - pm[4].rm_so; end_pos[0] = strtol(line + pm[4].rm_so, &end, 10); // END POS (y) len = pm[5].rm_eo - pm[5].rm_so; end_pos[1] = strtol(line + pm[5].rm_so, &end, 10); // Set lights brightness for (i=start_pos[0]; i<=end_pos[0]; i++) { for (j=start_pos[1]; j<=end_pos[1]; j++) { if (command == OFF) { if (lights[i][j] > 0) { lights[i][j] -= 1; } } else if (command == ON) { lights[i][j] += 1; } else if (command == TOGGLE) { lights[i][j] += 2; } } } } // Calculate the total brightness of lights for (i=0, brightness=0; i<1000; i++) { for (j=0; j<1000; j++) { brightness += lights[i][j]; } } printf("%ld\n", brightness); regfree(&r_compiled); fclose(fp); return 0; }
void printSourceFileAndLine ( Ostream& os, const fileName& filename, Dl_info *info, void *addr ) { uintptr_t address = uintptr_t(addr); word myAddress = addressToWord(address); #if ! defined(darwin64) if (filename.ext() == "so") { // Convert address into offset into dynamic library uintptr_t offset = uintptr_t(info->dli_fbase); intptr_t relativeAddress = address - offset; myAddress = addressToWord(relativeAddress); } #endif if (filename[0] == '/') { string line = pOpen ( #if ! defined(darwin64) "addr2line -f --demangle=auto --exe " + filename + " " + myAddress, 1 #else "echo 'image lookup -a " + myAddress + " " + filename + "'" + " | xcrun lldb " + "-O 'target create --no-dependents -a x86_64 " + filename + "' -o '" + "target modules load -f " + filename + " __TEXT " + addressToWord(reinterpret_cast<const uintptr_t>(info->dli_fbase)) + "'" + " | tail -1" #endif ); #if defined(darwin64) { const char *buf = line.c_str(); regex_t re; regmatch_t mt[3]; int st; regcomp(&re, ".\\+at \\(.\\+\\):\\(\\d\\+\\)", REG_ENHANCED); st = regexec(&re, buf, 3, mt, 0); if (st == REG_NOMATCH) { line = "??:0"; } else { size_t len = mt[1].rm_eo - mt[1].rm_so; string fname(buf + mt[1].rm_so, len); len = mt[2].rm_eo - mt[2].rm_so; string lnum(buf + mt[2].rm_so, len); line = fname + ":" + lnum; } regfree(&re); } #endif if (line == "") { os << " addr2line failed"; } else if (line == "??:0") { line = filename; string cwdLine(line.replaceAll(cwd() + '/', "")); string homeLine(cwdLine.replaceAll(home(), '~')); os << " in " << homeLine.c_str(); } else { string cwdLine(line.replaceAll(cwd() + '/', "")); string homeLine(cwdLine.replaceAll(home(), '~')); os << " at " << homeLine.c_str(); } } }
void deinit_parse_uri(regex_t * preg) { regfree(preg); }
/** 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(®, check->vp_strvalue, REG_EXTENDED); if (compare != 0) { char buffer[256]; regerror(compare, ®, 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(®, value, REQUEST_MAX_REGEX + 1, rxmatch, 0); regfree(®); 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(®, check->vp_strvalue, REG_EXTENDED); if (compare != 0) { char buffer[256]; regerror(compare, ®, buffer, sizeof(buffer)); RDEBUG("Invalid regular expression %s: %s", check->vp_strvalue, buffer); return -2; } compare = regexec(®, value, REQUEST_MAX_REGEX + 1, rxmatch, 0); regfree(®); 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; }
time_t CDBThread::Datetime2time_t(int fmt, char* str) { static char *ptmFmt1 = "([0-9]{4})\\.([0-9]{2})\\.([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})"; //yyyy.mm.dd hh:mm:ss static char *ptmFmt2 = "([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})"; //yyyy-mm-dd hh:mm:ss if(NULL == str || 0 == strlen(str)) return 0; //使用正则表达式 struct tm tm; memset(&tm, 0, sizeof(struct tm)); regex_t tmFmtReg; int ii = 1; bool parseOK = true; int iRet = -1;; if(fmt == 1) { iRet = regcomp(&tmFmtReg, ptmFmt1, REG_EXTENDED); } else if(fmt == 2) { iRet = regcomp(&tmFmtReg, ptmFmt2, REG_EXTENDED); } if(iRet >= 0) { regmatch_t match[8]; size_t matchLen = 0; char resultBuf[8] = {0}; iRet = regexec(&tmFmtReg, str, 8, &match[0], 0); if(0 == iRet) { for(;ii < 8; ++ii) { if(match[ii].rm_so >= 0) { memset(resultBuf, 0, sizeof(resultBuf)); memcpy(resultBuf, str+match[ii].rm_so, match[ii].rm_eo - match[ii].rm_so); switch(ii) { case 1: //year tm.tm_year=atoi(resultBuf); if(tm.tm_year < 1900) parseOK = false; else tm.tm_year -= 1900; break; case 2: //month tm.tm_mon=atoi(resultBuf); if(tm.tm_mon < 0 || tm.tm_mon > 11) parseOK = false; else tm.tm_mon -= 1; break; case 3: //day tm.tm_mday=atoi(resultBuf); if(tm.tm_mday < 1 || tm.tm_mday > 31) parseOK = false; break; case 4: //hour tm.tm_hour=atoi(resultBuf); if(tm.tm_hour < 0 || tm.tm_hour > 23) parseOK = false; break; case 5: //minute tm.tm_min=atoi(resultBuf); if(tm.tm_min < 0 || tm.tm_min > 59) parseOK = false; break; case 6: //second tm.tm_sec=atoi(resultBuf); if(tm.tm_sec < 0 || tm.tm_sec > 59) parseOK = false; break; } } else { break; } } } else { //char errorbuf[256] = {0}; //regerror(iRet, &tmFmtReg, errorbuf, 256); //printf("%s\n", errorbuf); } regfree(&tmFmtReg); if(ii < 7 || !parseOK) return 0; time_t ct; ct = mktime(&tm); return ct; } ////////////////////////////////////////////////// return 0; }
void* ThreadRoutine(void* arg) { connection con = *((connection*)arg); char buffer[BUFSIZE] = "\0"; char retMsg[BUFSIZE] = "\0"; int n, found; regex_t getFile; regmatch_t matches[2]; char filename[BUFSIZE] = "\0"; FILE* temp; struct stat st; char tempStr[BUFSIZE] = "\0"; //ensure that request starts with / and not .. QA( regcomp(&getFile, "^GET /(.+) HTTP/1\\.1", REG_EXTENDED | REG_ICASE) == 0 ); //receive data n = recv(con.sock, buffer, BUFSIZE-1, 0); QAP(n >= 0, "Error reading from socket.\n", NULL); buffer[n] = '\0'; //make sure 0 is set at the end //write to weblog fputs("REMOTE ADDRESS: ", weblog); fputs(inet_ntoa(con.from.sin_addr), weblog); fputs("\n", weblog); fputs(buffer, weblog); fflush(weblog); //get file info regexec(&getFile, buffer, 2, matches, 0); strncpy(filename, buffer + matches[1].rm_so, matches[1].rm_eo - matches[1].rm_so); //handle "GET / HTTP/1.1" if( strcmp(filename, "") == 0 ) { sprintf(tempStr, "ls %s > .temp", filename); system(tempStr); strcpy(filename, ".temp"); } //get file info found = stat(filename, &st); //build return header strcpy(retMsg, "HTTP/1.1 "); if( found == -1 ) { strncat(retMsg, "404 NOT FOUND\r\n", BUFSIZE - strlen(retMsg)); strncat(retMsg, "Status: 404 NOT FOUND\r\n", BUFSIZE - strlen(retMsg)); strncat(retMsg, "\r\n", BUFSIZE - strlen(retMsg)); } else { strncat(retMsg, "200 OK\r\n", BUFSIZE - strlen(retMsg)); strncat(retMsg, "Status: 200 OK\r\n", BUFSIZE - strlen(retMsg)); strncat(retMsg, "Content-length: ", BUFSIZE - strlen(retMsg)); sprintf(retMsg, "%s%u\r\n", retMsg, st.st_size); strncat(retMsg, "Content-type: ", BUFSIZE - strlen(retMsg)); sprintf(retMsg, "%s%s\r\n", retMsg, "text/html"); strncat(retMsg, "\r\n", BUFSIZE - strlen(retMsg)); } //send headers n = send(con.sock, retMsg, strlen(retMsg), 0); QAP(n == strlen(retMsg), "Error sending headers.\n", NULL); //send body if( found == 0 ) { temp = fopen(filename, "r"); //send chunks at a time while( !feof(temp) ) { memset(retMsg, 0, BUFSIZE); fread(retMsg, 1, BUFSIZE, temp); n = send(con.sock, retMsg, strlen(retMsg), 0); QAP(n == strlen(retMsg), "Error sending body.\n", NULL); } fclose(temp); } else { //print a text body for the user strcpy(retMsg, "404 File not found"); n = send(con.sock, retMsg, strlen(retMsg), 0); QAP(n == strlen(retMsg), "Error sending body.\n", NULL); } //delete .temp file if( strcmp(filename, ".temp") ) { system("rm .temp"); } //close the connection close(con.sock); regfree(&getFile); free(arg); return 0; }
// Insert diffs in-between lines in a rebase picklist static int insert_diffs(FILE *in, FILE *out) { regex_t pick; bool regex_inited = false; int ret = 0; char *line = NULL; // we'll use this to look for lines representing commits in the input ret = regcomp(&pick, "^(pick|fixup|squash) ([[:xdigit:]]+) ", REG_EXTENDED); if (ret != 0) goto end; regex_inited = true; size_t line_sz; for (;;) { errno = 0; ssize_t r = getline(&line, &line_sz, in); if (r < 0) { ret = -errno; if (feof(in)) break; goto end; } regmatch_t match[3]; if (regexec(&pick, line, sizeof match / sizeof match[0], match, 0) == 0) { // this line is a commit assert(match[2].rm_so != -1); // Lop off the newline if there is one if (line[r - 1] == '\n') r--; // Write the line with a Vim marker to indicate the start of a fold if (fprintf(out, "%.*s {{{\n", (int)r, line) < 0) { ret = -1; goto end; } // Create a Git command to get a diff of this commit char *command; if (asprintf(&command, "git show %.*s", (int)(match[2].rm_eo - match[2].rm_so), &line[match[2].rm_so]) < 0) { ret = -ENOMEM; goto end; } // Retrieve the diff and write it to the output errno = 0; FILE *pipe = popen(command, "r"); if (pipe == NULL) ret = errno == 0 ? -ENOMEM : -errno; free(command); if (ret != 0) goto end; char *l = NULL; size_t l_sz; for (;;) { errno = 0; if (getline(&l, &l_sz, pipe) < 0) { ret = -errno; if (feof(pipe)) break; free(l); pclose(pipe); goto end; } if (fprintf(out, " # %s", l) < 0) { ret = -1; free(l); pclose(pipe); goto end; } } free(l); int status = pclose(pipe); if (status == -1) { ret = -1; goto end; } if (WEXITSTATUS(status) != EXIT_SUCCESS) { ret = WEXITSTATUS(status); goto end; } // write a fold close marker if (fputs(" # }}}\n", out) < 0) { ret = -1; goto end; } } else { // normal line; write it out as-is size_t w = fwrite(line, 1, (size_t)r, out); if (w != (size_t)r) { ret = -1; goto end; } } } end: free(line); if (regex_inited) regfree(&pick); return ret; }
/** * 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; }
static bool regex_find_jobids(JCR *jcr, idpkt *ids, const char *query1, const char *query2, const char *type) { dlist *item_chain; uitem *item = NULL; uitem *last_item = NULL; regex_t preg; char prbuf[500]; int rc; bool ok = false; POOL_MEM query(PM_MESSAGE); item_chain = New(dlist(item, &item->link)); if (!jcr->job->selection_pattern) { Jmsg(jcr, M_FATAL, 0, _("No %s %s selection pattern specified.\n"), jcr->get_OperationName(), type); goto bail_out; } Dmsg1(dbglevel, "regex-sel-pattern=%s\n", jcr->job->selection_pattern); /* Basic query for names */ Mmsg(query, query1, jcr->rpool->name()); Dmsg1(dbglevel, "get name query1=%s\n", query.c_str()); if (!db_sql_query(jcr->db, query.c_str(), unique_name_handler, (void *)item_chain)) { Jmsg(jcr, M_FATAL, 0, _("SQL to get %s failed. ERR=%s\n"), type, db_strerror(jcr->db)); goto bail_out; } Dmsg1(dbglevel, "query1 returned %d names\n", item_chain->size()); if (item_chain->size() == 0) { Jmsg(jcr, M_INFO, 0, _("Query of Pool \"%s\" returned no Jobs to %s.\n"), jcr->rpool->name(), jcr->get_ActionName(0)); ok = true; goto bail_out; /* skip regex match */ } else { /* Compile regex expression */ rc = regcomp(&preg, jcr->job->selection_pattern, REG_EXTENDED); if (rc != 0) { regerror(rc, &preg, prbuf, sizeof(prbuf)); Jmsg(jcr, M_FATAL, 0, _("Could not compile regex pattern \"%s\" ERR=%s\n"), jcr->job->selection_pattern, prbuf); goto bail_out; } /* Now apply the regex to the names and remove any item not matched */ foreach_dlist(item, item_chain) { const int nmatch = 30; regmatch_t pmatch[nmatch]; if (last_item) { Dmsg1(dbglevel, "Remove item %s\n", last_item->item); free(last_item->item); item_chain->remove(last_item); } Dmsg1(dbglevel, "get name Item=%s\n", item->item); rc = regexec(&preg, item->item, nmatch, pmatch, 0); if (rc == 0) { last_item = NULL; /* keep this one */ } else { last_item = item; } } if (last_item) { free(last_item->item); Dmsg1(dbglevel, "Remove item %s\n", last_item->item); item_chain->remove(last_item); } regfree(&preg); } if (item_chain->size() == 0) { Jmsg(jcr, M_INFO, 0, _("Regex pattern matched no Jobs to %s.\n"), jcr->get_ActionName(0)); ok = true; goto bail_out; /* skip regex match */ } /* * At this point, we have a list of items in item_chain * that have been matched by the regex, so now we need * to look up their jobids. */ ids->count = 0; foreach_dlist(item, item_chain) { Dmsg2(dbglevel, "Got %s: %s\n", type, item->item); Mmsg(query, query2, item->item, jcr->rpool->name()); Dmsg1(dbglevel, "get id from name query2=%s\n", query.c_str()); if (!db_sql_query(jcr->db, query.c_str(), unique_dbid_handler, (void *)ids)) { Jmsg(jcr, M_FATAL, 0, _("SQL failed. ERR=%s\n"), db_strerror(jcr->db)); goto bail_out; } }
int ooCleanCall(OOH323CallData *call) { OOCTXT *pctxt; OOTRACEWARN4 ("Cleaning Call (%s, %s)- reason:%s\n", call->callType, call->callToken, ooGetReasonCodeText (call->callEndReason)); /* First clean all the logical channels, if not already cleaned. */ if(call->logicalChans) ooClearAllLogicalChannels(call); /* Close H.245 connection, if not already closed */ if(call->h245SessionState != OO_H245SESSION_CLOSED) ooCloseH245Connection(call); else{ if(call->pH245Channel && call->pH245Channel->outQueue.count > 0) { dListFreeAll(call->pctxt, &(call->pH245Channel->outQueue)); memFreePtr(call->pctxt, call->pH245Channel); } } /* Close H.245 listener, if not already closed */ if(call->h245listener) { ooCloseH245Listener(call); } /* Close H225 connection, if not already closed. */ if (0 != call->pH225Channel && 0 != call->pH225Channel->sock) { ooCloseH225Connection(call); } /* Clean timers */ if(call->timerList.count > 0) { dListFreeAll(call->pctxt, &(call->timerList)); } if(gH323ep.gkClient && !OO_TESTFLAG(call->flags, OO_M_DISABLEGK)) { ooGkClientCleanCall(gH323ep.gkClient, call); } ooRemoveCallFromList (call); OOTRACEINFO3("Removed call (%s, %s) from list\n", call->callType, call->callToken); if(call->pCallFwdData && call->pCallFwdData->fwdedByRemote) { if(gH323ep.h323Callbacks.onCallForwarded) gH323ep.h323Callbacks.onCallForwarded(call); if(ooH323HandleCallFwdRequest(call)!= OO_OK) { OOTRACEERR3("Error:Failed to forward call (%s, %s)\n", call->callType, call->callToken); } } else { if(gH323ep.h323Callbacks.onCallCleared) gH323ep.h323Callbacks.onCallCleared(call); } if (call->rtpMask) { ast_mutex_lock(&call->rtpMask->lock); call->rtpMask->inuse--; ast_mutex_unlock(&call->rtpMask->lock); if ((call->rtpMask->inuse) == 0) { regfree(&call->rtpMask->regex); ast_mutex_destroy(&call->rtpMask->lock); free(call->rtpMask); } } if ((pctxt = call->msgctxt) != NULL) { freeContext(pctxt); free(pctxt); call->msgctxt = NULL; } /* May !!!! Fix it !! */ /* free(pctxt); */ return OO_OK; }
/* ---------------- read_class -------------------------------- * We have the overview of the classification, now read up the * description of each class. buf is just a line buffer for us to * use. aa_clssfcn is the main classification. * n_class is the number of the class we are reading. * n_val is the number of values a descriptor can have. For this * function, it is always 20, the number of amino acids. */ static int read_class (FILE *fp, char *buf, const int bufsiz, struct aa_clssfcn *aa_clssfcn, const size_t n_class, const size_t num_aa) { float wt; int want_new_att = 1; int att_num = -1; int ret = EXIT_SUCCESS; /* On error, set this and go to escape */ unsigned aa_seen = 0; unsigned att_seen = 0; regex_t new_att, next_aa, three_num, get_att_num; const char *this_sub = "read_class"; const char *heading1 = " numb t mtt description I-jk"; /* 00 02 D SM aa 2 ............... 0.116 h .................. -1.79e+00 3.84e-03 2.30e-02 */ const char *s_class_wt = "normalized weight "; const char *s_new_att = "[0-9]+ [0-9]+ .+M +.+[.]+.+[.]+ -*[0-9]"; /* n .................. -1.02e+00 1.53e-02 4.26e-02 */ /* const char *s_next_aa = "[a-zA-Z] [.]{13}"; */ const char *s_next_aa = "[a-zA-Z] [ .]{13}"; const char *s_three_num = "-*[0-9][.][0-9]+e[+-][0-9]+"; /* const char *s_get_att_num = "[0-9]{2,} [DR] +S.+[a-zA-Z0-9] [.]{13}"; */ const char *s_get_att_num = "[0-9]{2,} [DR] +S.+aa"; const char *broke_ijk = "Broke looking for I-jk value in \"%s\"\n"; if ( ! find_line (buf, bufsiz, fp, s_class_wt)) return EXIT_FAILURE; if ((wt = get_class_wt (buf)) < 0) { err_printf (this_sub, "Failed finding class weight on %s\n", buf); return EXIT_FAILURE; } aa_clssfcn->class_wt[n_class] = wt; if ( ! find_line (buf, bufsiz, fp, heading1)) return EXIT_FAILURE; if (m_regcomp (&new_att, s_new_att) == EXIT_FAILURE) return EXIT_FAILURE; if (m_regcomp (&next_aa, s_next_aa) == EXIT_FAILURE) return EXIT_FAILURE; if (m_regcomp (&three_num, s_three_num) == EXIT_FAILURE) return EXIT_FAILURE; if (m_regcomp (&get_att_num, s_get_att_num) == EXIT_FAILURE) return EXIT_FAILURE; while ( fgets (buf, bufsiz, fp) && (att_seen < aa_clssfcn->n_att)) { char *p = buf; regmatch_t pmatch[1]; const size_t nmatch = 1; int r; const int eflags = 0; char aa; unsigned char t_aa; float f1, f2, f3; if (want_new_att) { aa_seen = 0; r = regexec (&get_att_num, p, nmatch, pmatch, eflags); if (r != 0) /* This is a new attribute, so */ continue; /* first we get the attribute */ p += pmatch->rm_so; /* number into att_num */ att_num = (int) strtol (p, NULL, 0); if (r !=0) { err_printf (this_sub, broke_ijk, buf); ret = EXIT_FAILURE; goto escape; } want_new_att = 0; } r = regexec (&next_aa, p, nmatch, pmatch, eflags); if (r != 0) /* Now we are looking for the substring */ break; /* which contains the amino acid letter */ p += pmatch->rm_so; aa = *p++; t_aa = std2thomas_char (aa); if (get_three_num (p, &three_num, &f1, &f2, &f3) == EXIT_FAILURE) { ret = EXIT_FAILURE; goto escape; } aa_clssfcn->log_pp [n_class] [att_num] [t_aa] = f1; if (++aa_seen >= num_aa) { want_new_att = 1; att_seen++; } } escape: regfree (&get_att_num); regfree (&next_aa); regfree (&new_att); regfree (&three_num); return ret; }
int regex_subst(STRBUF *buf, const char *regex, int regopt, const void *subst) { int r; const char *bufp; size_t off = 0; const int i = 0; int match_count = 0; regex_t rx; const size_t nmatches = 10; regmatch_t matches[10]; r = regcomp(&rx, regex, REG_EXTENDED); if (r) { print_regexp_err(r, &rx); exit(EXIT_FAILURE); } do { if (off > strbuf_len(buf)) break; bufp = strbuf_get(buf) + off; #ifdef REG_STARTEND matches[0].rm_so = 0; matches[0].rm_eo = strbuf_len(buf) - off; if (0 != regexec(&rx, bufp, nmatches, matches, REG_STARTEND)) #else if (0 != regexec(&rx, bufp, nmatches, matches, 0)) #endif break; if (matches[i].rm_so != -1) { char *s; int subst_len; if (regopt & _REG_EXEC) { s = (*(char *(*) (const char *buf, regmatch_t matches[], size_t nmatch, size_t off))subst) (strbuf_get(buf), matches, nmatches, off); } else s = (char*)subst; subst_len = strbuf_subst(buf, matches[i].rm_so + off, matches[i].rm_eo + off, s); match_count++; if (regopt & _REG_EXEC) yfree(s); off += matches[i].rm_so; if (subst_len >= 0) off += subst_len + 1; } } while (regopt & _REG_GLOBAL); regfree(&rx); return match_count; }
int gk_strstr_replace(char *str, char *pattern, char *replacement, char *options, char **new_str) { gk_idx_t i; int j, rc, flags, global, nmatches; size_t len, rlen, nlen, offset, noffset; regex_t re; regmatch_t matches[10]; /* Parse the options */ flags = REG_EXTENDED; if (strchr(options, 'i') != NULL) flags = flags | REG_ICASE; global = (strchr(options, 'g') != NULL ? 1 : 0); /* Compile the regex */ if ((rc = regcomp(&re, pattern, flags)) != 0) { len = regerror(rc, &re, NULL, 0); *new_str = gk_cmalloc(len, "gk_strstr_replace: new_str"); regerror(rc, &re, *new_str, len); return 0; } /* Prepare the output string */ len = strlen(str); nlen = 2*len; noffset = 0; *new_str = gk_cmalloc(nlen+1, "gk_strstr_replace: new_str"); /* Get into the matching-replacing loop */ rlen = strlen(replacement); offset = 0; nmatches = 0; do { rc = regexec(&re, str+offset, 10, matches, 0); if (rc == REG_ESPACE) { gk_free((void **)new_str, LTERM); *new_str = gk_strdup("regexec ran out of memory."); regfree(&re); return 0; } else if (rc == REG_NOMATCH) { if (nlen-noffset < len-offset) { nlen += (len-offset) - (nlen-noffset); *new_str = (char *)gk_realloc(*new_str, (nlen+1)*sizeof(char), "gk_strstr_replace: new_str"); } strcpy(*new_str+noffset, str+offset); noffset += (len-offset); break; } else { /* A match was found! */ nmatches++; /* Copy the left unmatched portion of the string */ if (matches[0].rm_so > 0) { if (nlen-noffset < matches[0].rm_so) { nlen += matches[0].rm_so - (nlen-noffset); *new_str = (char *)gk_realloc(*new_str, (nlen+1)*sizeof(char), "gk_strstr_replace: new_str"); } strncpy(*new_str+noffset, str+offset, matches[0].rm_so); noffset += matches[0].rm_so; } /* Go and append the replacement string */ for (i=0; i<rlen; i++) { switch (replacement[i]) { case '\\': if (i+1 < rlen) { if (nlen-noffset < 1) { nlen += nlen + 1; *new_str = (char *)gk_realloc(*new_str, (nlen+1)*sizeof(char), "gk_strstr_replace: new_str"); } *new_str[noffset++] = replacement[++i]; } else { gk_free((void **)new_str, LTERM); *new_str = gk_strdup("Error in replacement string. Missing character following '\'."); regfree(&re); return 0; } break; case '$': if (i+1 < rlen) { j = (int)(replacement[++i] - '0'); if (j < 0 || j > 9) { gk_free((void **)new_str, LTERM); *new_str = gk_strdup("Error in captured subexpression specification."); regfree(&re); return 0; } if (nlen-noffset < matches[j].rm_eo-matches[j].rm_so) { nlen += nlen + (matches[j].rm_eo-matches[j].rm_so); *new_str = (char *)gk_realloc(*new_str, (nlen+1)*sizeof(char), "gk_strstr_replace: new_str"); } strncpy(*new_str+noffset, str+offset+matches[j].rm_so, matches[j].rm_eo); noffset += matches[j].rm_eo-matches[j].rm_so; } else { gk_free((void **)new_str, LTERM); *new_str = gk_strdup("Error in replacement string. Missing subexpression number folloing '$'."); regfree(&re); return 0; } break; default: if (nlen-noffset < 1) { nlen += nlen + 1; *new_str = (char *)gk_realloc(*new_str, (nlen+1)*sizeof(char), "gk_strstr_replace: new_str"); } (*new_str)[noffset++] = replacement[i]; } } /* Update the offset of str for the next match */ offset += matches[0].rm_eo; if (!global) { /* Copy the right portion of the string if no 'g' option */ if (nlen-noffset < len-offset) { nlen += (len-offset) - (nlen-noffset); *new_str = (char *)gk_realloc(*new_str, (nlen+1)*sizeof(char), "gk_strstr_replace: new_str"); } strcpy(*new_str+noffset, str+offset); noffset += (len-offset); } } } while (global); (*new_str)[noffset] = '\0'; regfree(&re); return nmatches + 1; }
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(®ex, 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; }
/* - main - do the simple case, hand off to regress() for regression */ int main(int argc, char *argv[]) { regex_t re; # define NS 10 regmatch_t subs[NS]; char erbuf[100]; int err; size_t len; int c; int errflg = 0; register int i; extern int optind; extern char *optarg; progname = argv[0]; while ((c = getopt(argc, argv, "c:E:e:S:x")) != -1) switch (c) { case 'c': /* compile options */ copts = options('c', optarg); break; case 'E': /* end offset */ endoff = (regoff_t)atoi(optarg); break; case 'e': /* execute options */ eopts = options('e', optarg); break; case 'S': /* start offset */ startoff = (regoff_t)atoi(optarg); break; case 'x': /* Debugging. */ debug++; break; case '?': default: errflg++; break; } if (errflg) { fprintf(stderr, "usage: %s ", progname); fprintf(stderr, "[-x] [-c copt] [-E endoff] [-e eopt] [-S startoff] [re]\n"); exit(2); } if (optind >= argc) { regress(stdin); exit(status); } err = regcomp(&re, argv[optind++], copts); if (err) { len = regerror(err, &re, erbuf, sizeof(erbuf)); fprintf(stderr, "error %s, %zu/%zu `%s'\n", eprint(err), len, sizeof(erbuf), erbuf); exit(status); } regprint(&re, stdout); if (optind >= argc) { regfree(&re); exit(status); } if (eopts®_STARTEND) { subs[0].rm_so = startoff; subs[0].rm_eo = strlen(argv[optind]) - endoff; } err = regexec(&re, argv[optind], (size_t)NS, subs, eopts); if (err) { len = regerror(err, &re, erbuf, sizeof(erbuf)); fprintf(stderr, "error %s, %zu/%zu `%s'\n", eprint(err), len, sizeof(erbuf), erbuf); exit(status); } if (!(copts®_NOSUB)) { len = (size_t)(subs[0].rm_eo - subs[0].rm_so); if (subs[0].rm_so != -1) { if (len != 0) printf("match `%.*s'\n", (int)len, argv[optind] + subs[0].rm_so); else printf("match `'@%.1s\n", argv[optind] + subs[0].rm_so); } for (i = 1; i < NS; i++) if (subs[i].rm_so != -1) printf("(%d) `%.*s'\n", i, (int)(subs[i].rm_eo - subs[i].rm_so), argv[optind] + subs[i].rm_so); } exit(status); }
void dir___::dir__(int*err1,char*buf,long siz,char*dir,char*tongpei,char*opt1, const char* src,void*ce,void*qu,callback2_2___ cb) { string oldir; { #define MAXDIR 260 char cwd[MAXDIR]; oldir=getcwd(cwd,MAXDIR); } dir_opt___ opt; opt.a_file_=opt.a_lnk_=true; for(;*opt1;opt1++){ switch(*opt1){ case's': opt.subdir_=true; continue; /* T(头匹配) A(全匹配) */ case'T': case'A': opt.tongpei_=*opt1; continue; case'l': opt.icase_=!opt.icase_; continue; case'd': opt.dir_=!opt.dir_; continue; case'n': opt.lnk_=!opt.lnk_; continue; case'o': opt.sort_=*++opt1-'0'; if(!(opt.sort_>=0&&opt.sort_<=3)) break; continue; case'a': switch(*++opt1){ case'h': opt.a_hidden_=!opt.a_hidden_; continue; case'd': opt.a_dir_=!opt.a_dir_; continue; case'f': opt.a_file_=!opt.a_file_; continue; case'l': opt.a_lnk_=!opt.a_lnk_; continue; } } buf[0]=*opt1; buf[1]=0; *err1='o'; return; } regex_t reg; switch(opt.tongpei_){ case 0: { int cflags=REG_EXTENDED|REG_NEWLINE|REG_NOSUB; if(opt.icase_) cflags|=REG_ICASE; int err=regcomp(®, tongpei, cflags); if(err){ regerror(err, ®, buf, siz); *err1='r'; return; } break; } } *err1=dir2__(dir,0,"",®,tongpei,&opt,src,false,ce,qu,cb); chdir(oldir.c_str()); switch(opt.tongpei_){ case 0: regfree(®); break; } sort__(opt.sort_); }
static void xx(char* pattern, char* str, int from, int to, int mem, int not) { int r; #ifdef POSIX_TEST regex_t reg; char buf[200]; regmatch_t pmatch[25]; r = regcomp(®, pattern, REG_EXTENDED | REG_NEWLINE); if (r) { regerror(r, ®, buf, sizeof(buf)); fprintf(err_file, "ERROR: %s\n", buf); nerror++; return ; } r = regexec(®, str, reg.re_nsub + 1, pmatch, 0); if (r != 0 && r != REG_NOMATCH) { regerror(r, ®, buf, sizeof(buf)); fprintf(err_file, "ERROR: %s\n", buf); nerror++; return ; } if (r == REG_NOMATCH) { if (not) { fprintf(stdout, "OK(N): /%s/ '%s'\n", pattern, str); nsucc++; } else { fprintf(stdout, "FAIL: /%s/ '%s'\n", pattern, str); nfail++; } } else { if (not) { fprintf(stdout, "FAIL(N): /%s/ '%s'\n", pattern, str); nfail++; } else { if (pmatch[mem].rm_so == from && pmatch[mem].rm_eo == to) { fprintf(stdout, "OK: /%s/ '%s'\n", pattern, str); nsucc++; } else { fprintf(stdout, "FAIL: /%s/ '%s' %d-%d : %d-%d\n", pattern, str, from, to, pmatch[mem].rm_so, pmatch[mem].rm_eo); nfail++; } } } regfree(®); #else regex_t* reg; OnigErrorInfo einfo; r = onig_new(®, (UChar* )pattern, (UChar* )(pattern + strlen(pattern)), ONIG_OPTION_DEFAULT, ONIG_ENCODING_SJIS, ONIG_SYNTAX_DEFAULT, &einfo); if (r) { char s[ONIG_MAX_ERROR_MESSAGE_LEN]; onig_error_code_to_str((UChar* )s, r, &einfo); fprintf(err_file, "ERROR: %s\n", s); nerror++; return ; } r = onig_search(reg, (UChar* )str, (UChar* )(str + strlen(str)), (UChar* )str, (UChar* )(str + strlen(str)), region, ONIG_OPTION_NONE); if (r < ONIG_MISMATCH) { char s[ONIG_MAX_ERROR_MESSAGE_LEN]; onig_error_code_to_str((UChar* )s, r); fprintf(err_file, "ERROR: %s\n", s); nerror++; return ; } if (r == ONIG_MISMATCH) { if (not) { fprintf(stdout, "OK(N): /%s/ '%s'\n", pattern, str); nsucc++; } else { fprintf(stdout, "FAIL: /%s/ '%s'\n", pattern, str); nfail++; } } else { if (not) { fprintf(stdout, "FAIL(N): /%s/ '%s'\n", pattern, str); nfail++; } else { if (region->beg[mem] == from && region->end[mem] == to) { fprintf(stdout, "OK: /%s/ '%s'\n", pattern, str); nsucc++; } else { fprintf(stdout, "FAIL: /%s/ '%s' %d-%d : %d-%d\n", pattern, str, from, to, region->beg[mem], region->end[mem]); nfail++; } } } onig_free(reg); #endif }
static int zcond_regex_match(char **a, int id) { regex_t re; regmatch_t *m, *matches = NULL; size_t matchessz = 0; char *lhstr, *lhstr_zshmeta, *rhre, *rhre_zshmeta, *s, **arr, **x; int r, n, return_value, rcflags, reflags, nelem, start; lhstr_zshmeta = cond_str(a,0,0); rhre_zshmeta = cond_str(a,1,0); rcflags = reflags = 0; return_value = 0; /* 1 => matched successfully */ lhstr = ztrdup(lhstr_zshmeta); unmetafy(lhstr, NULL); rhre = ztrdup(rhre_zshmeta); unmetafy(rhre, NULL); switch(id) { case ZREGEX_EXTENDED: rcflags |= REG_EXTENDED; if (!isset(CASEMATCH)) rcflags |= REG_ICASE; r = regcomp(&re, rhre, rcflags); if (r) { zregex_regerrwarn(r, &re, "failed to compile regex"); break; } /* re.re_nsub is number of parenthesized groups, we also need * 1 for the 0 offset, which is the entire matched portion */ if ((int)re.re_nsub < 0) { zwarn("INTERNAL ERROR: regcomp() returned " "negative subpattern count %d", (int)re.re_nsub); break; } matchessz = (re.re_nsub + 1) * sizeof(regmatch_t); matches = zalloc(matchessz); r = regexec(&re, lhstr, re.re_nsub+1, matches, reflags); if (r == REG_NOMATCH) ; /* We do nothing when we fail to match. */ else if (r == 0) { return_value = 1; if (isset(BASHREMATCH)) { start = 0; nelem = re.re_nsub + 1; } else { start = 1; nelem = re.re_nsub; } arr = NULL; /* bogus gcc warning of used uninitialised */ /* entire matched portion + re_nsub substrings + NULL */ if (nelem) { arr = x = (char **) zalloc(sizeof(char *) * (nelem + 1)); for (m = matches + start, n = start; n <= (int)re.re_nsub; ++n, ++m, ++x) { *x = metafy(lhstr + m->rm_so, m->rm_eo - m->rm_so, META_DUP); } *x = NULL; } if (isset(BASHREMATCH)) { assignaparam("BASH_REMATCH", arr, 0); } else { zlong offs; char *ptr; int clen, leftlen; m = matches; s = metafy(lhstr + m->rm_so, m->rm_eo - m->rm_so, META_DUP); assignsparam("MATCH", s, 0); /* * Count the characters before the match. */ ptr = lhstr; leftlen = m->rm_so; offs = 0; MB_CHARINIT(); while (leftlen) { offs++; clen = MB_CHARLEN(ptr, leftlen); ptr += clen; leftlen -= clen; } assigniparam("MBEGIN", offs + !isset(KSHARRAYS), 0); /* * Add on the characters in the match. */ leftlen = m->rm_eo - m->rm_so; while (leftlen) { offs++; clen = MB_CHARLEN(ptr, leftlen); ptr += clen; leftlen -= clen; } assigniparam("MEND", offs + !isset(KSHARRAYS) - 1, 0); if (nelem) { char **mbegin, **mend, **bptr, **eptr; bptr = mbegin = (char **)zalloc(sizeof(char *)*(nelem+1)); eptr = mend = (char **)zalloc(sizeof(char *)*(nelem+1)); for (m = matches + start, n = 0; n < nelem; ++n, ++m, ++bptr, ++eptr) { char buf[DIGBUFSIZE]; if (m->rm_so < 0 || m->rm_eo < 0) { *bptr = ztrdup("-1"); *eptr = ztrdup("-1"); continue; } ptr = lhstr; leftlen = m->rm_so; offs = 0; /* Find the start offset */ MB_CHARINIT(); while (leftlen) { offs++; clen = MB_CHARLEN(ptr, leftlen); ptr += clen; leftlen -= clen; } convbase(buf, offs + !isset(KSHARRAYS), 10); *bptr = ztrdup(buf); /* Continue to the end offset */ leftlen = m->rm_eo - m->rm_so; while (leftlen ) { offs++; clen = MB_CHARLEN(ptr, leftlen); ptr += clen; leftlen -= clen; } convbase(buf, offs + !isset(KSHARRAYS) - 1, 10); *eptr = ztrdup(buf); } *bptr = *eptr = NULL; setaparam("match", arr); setaparam("mbegin", mbegin); setaparam("mend", mend); } } } else zregex_regerrwarn(r, &re, "regex matching error"); break; default: DPUTS(1, "bad regex option"); return_value = 0; goto CLEAN_BASEMETA; } if (matches) zfree(matches, matchessz); regfree(&re); CLEAN_BASEMETA: free(lhstr); free(rhre); return return_value; }
void nco_ppc_set_var (const char * const var_nm, /* I [sng] Variable name to find */ const char * const ppc_arg, /* I [sng] User input for precision-preserving compression */ trv_tbl_sct * const trv_tbl) /* I/O [sct] Traversal table */ { const char sls_chr='/'; /* [chr] Slash character */ char *sng_cnv_rcd=NULL_CEWI; /* [sng] strtol()/strtoul() return code */ int mch_nbr=0; int ppc_val; nco_bool flg_nsd=True; /* [flg] PPC is NSD */ if(ppc_arg[0] == '.'){ /* DSD */ flg_nsd=False; ppc_val=(int)strtol(ppc_arg+1L,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(ppc_arg+1L,"strtol",sng_cnv_rcd); }else{ /* NSD */ ppc_val=(int)strtol(ppc_arg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(ppc_arg,"strtol",sng_cnv_rcd); if(ppc_val <= 0){ (void)fprintf(stdout,"%s ERROR Number of Significant Digits (NSD) must be positive. Specified value for %s is %d. HINT: Decimal Significant Digit (DSD) rounding does accept negative arguments (number of digits in front of the decimal point). However, the DSD argument must be prefixed by a period or \"dot\", e.g., \"--ppc foo=.-2\", to distinguish it from NSD quantization.\n",nco_prg_nm_get(),var_nm,ppc_val); nco_exit(EXIT_FAILURE); } /* endif */ } /* end else */ if(strpbrk(var_nm,".*^$\\[]()<>+?|{}")){ /* Regular expression ... */ #ifdef NCO_HAVE_REGEX_FUNCTIONALITY regmatch_t *result; regex_t *rx; size_t rx_prn_sub_xpr_nbr; rx=(regex_t *)nco_malloc(sizeof(regex_t)); if(strchr(var_nm,sls_chr)){ /* Full name is used */ /* Important difference between full- and short-name matching: Prepend carat to RX so full name matches must start at beginning of variable name */ char *sng2mch; sng2mch=(char *)nco_malloc(NC_MAX_VARS*sizeof(char *)); sng2mch[0]='\0'; strcat(sng2mch,"^"); strcat(sng2mch,var_nm); if(regcomp(rx,sng2mch,(REG_EXTENDED | REG_NEWLINE))){ /* Compile regular expression */ (void)fprintf(stdout,"%s: ERROR trv_tbl_set_ppc() error in regular expression \"%s\"\n",nco_prg_nm_get(),var_nm); nco_exit(EXIT_FAILURE); } /* endif */ rx_prn_sub_xpr_nbr=rx->re_nsub+1L; /* Number of parenthesized sub-expressions */ result=(regmatch_t *)nco_malloc(sizeof(regmatch_t)*rx_prn_sub_xpr_nbr); for(unsigned idx_tbl=0;idx_tbl<trv_tbl->nbr;idx_tbl++){ if(trv_tbl->lst[idx_tbl].nco_typ == nco_obj_typ_var){ if(!regexec(rx,trv_tbl->lst[idx_tbl].nm_fll,rx_prn_sub_xpr_nbr,result,0)){ trv_tbl->lst[idx_tbl].ppc=ppc_val; trv_tbl->lst[idx_tbl].flg_nsd=flg_nsd; mch_nbr++; } /* endif */ } /* endif */ } /* endfor */ sng2mch=(char *)nco_free(sng2mch); }else{ /* Relative name is used */ if(regcomp(rx,var_nm,(REG_EXTENDED | REG_NEWLINE))){ /* Compile regular expression */ (void)fprintf(stdout,"%s: ERROR trv_tbl_set_ppc() error in regular expression \"%s\"\n",nco_prg_nm_get(),var_nm); nco_exit(EXIT_FAILURE); } /* endif */ rx_prn_sub_xpr_nbr=rx->re_nsub+1L; /* Number of parenthesized sub-expressions */ result=(regmatch_t *)nco_malloc(sizeof(regmatch_t)*rx_prn_sub_xpr_nbr); for(unsigned idx_tbl=0;idx_tbl<trv_tbl->nbr;idx_tbl++){ if(trv_tbl->lst[idx_tbl].nco_typ == nco_obj_typ_var){ if(!regexec(rx,trv_tbl->lst[idx_tbl].nm,rx_prn_sub_xpr_nbr,result,0)){ trv_tbl->lst[idx_tbl].ppc=ppc_val; trv_tbl->lst[idx_tbl].flg_nsd=flg_nsd; mch_nbr++; } /* endif */ } /* endif */ } /* endfor */ } /* end Full name */ regfree(rx); /* Free regular expression data structure */ rx=(regex_t *)nco_free(rx); result=(regmatch_t *)nco_free(result); #else /* !NCO_HAVE_REGEX_FUNCTIONALITY */ (void)fprintf(stdout,"%s: ERROR: Sorry, wildcarding (extended regular expression matches to variables) was not built into this NCO executable, so unable to compile regular expression \"%s\".\nHINT: Make sure libregex.a is on path and re-build NCO.\n",nco_prg_nm_get(),var_nm); nco_exit(EXIT_FAILURE); #endif /* !NCO_HAVE_REGEX_FUNCTIONALITY */ }else if(strchr(var_nm,sls_chr)){ /* Full name */ for(unsigned idx_tbl=0;idx_tbl<trv_tbl->nbr;idx_tbl++){ if(trv_tbl->lst[idx_tbl].nco_typ == nco_obj_typ_var){ if(!strcmp(var_nm,trv_tbl->lst[idx_tbl].nm_fll)){ trv_tbl->lst[idx_tbl].ppc=ppc_val; trv_tbl->lst[idx_tbl].flg_nsd=flg_nsd; mch_nbr++; break; /* Only one match with full name */ } /* endif */ } /* endif */ } /* endfor */ }else{ /* Not full name so set all matching vars */ for(unsigned idx_tbl=0;idx_tbl<trv_tbl->nbr;idx_tbl++){ if(trv_tbl->lst[idx_tbl].nco_typ == nco_obj_typ_var){ if(!strcmp(var_nm,trv_tbl->lst[idx_tbl].nm)){ trv_tbl->lst[idx_tbl].ppc=ppc_val; trv_tbl->lst[idx_tbl].flg_nsd=flg_nsd; mch_nbr++; } /* endif */ } /* endif */ } /* endfor */ } /* end Full name */ if(mch_nbr == 0){ (void)fprintf(stdout,"%s: ERROR nco_ppc_set_var() reports user specified variable (or, possibly, regular expression) = \"%s\" does not match any variables in input file\n",nco_prg_nm_get(),var_nm); nco_exit(EXIT_FAILURE); } /* endif */ return; } /* end nco_ppc_set_var() */
void exec(const char * s) const { regex_t rgx; regcomp(&rgx, s, REG_EXTENDED); regfree(&rgx); }
int cmd_main(int argc, const char **argv) { char *method = getenv("REQUEST_METHOD"); char *dir; struct service_cmd *cmd = NULL; char *cmd_arg = NULL; int i; set_die_routine(die_webcgi); set_die_is_recursing_routine(die_webcgi_recursing); if (!method) die("No REQUEST_METHOD from server"); if (!strcmp(method, "HEAD")) method = "GET"; dir = getdir(); for (i = 0; i < ARRAY_SIZE(services); i++) { struct service_cmd *c = &services[i]; regex_t re; regmatch_t out[1]; if (regcomp(&re, c->pattern, REG_EXTENDED)) die("Bogus regex in service table: %s", c->pattern); if (!regexec(&re, dir, 1, out, 0)) { size_t n; if (strcmp(method, c->method)) { const char *proto = getenv("SERVER_PROTOCOL"); if (proto && !strcmp(proto, "HTTP/1.1")) { http_status(405, "Method Not Allowed"); hdr_str("Allow", !strcmp(c->method, "GET") ? "GET, HEAD" : c->method); } else http_status(400, "Bad Request"); hdr_nocache(); end_headers(); return 0; } cmd = c; n = out[0].rm_eo - out[0].rm_so; cmd_arg = xmemdupz(dir + out[0].rm_so + 1, n - 1); dir[out[0].rm_so] = 0; break; } regfree(&re); } if (!cmd) not_found("Request not supported: '%s'", dir); setup_path(); if (!enter_repo(dir, 0)) not_found("Not a git repository: '%s'", dir); if (!getenv("GIT_HTTP_EXPORT_ALL") && access("git-daemon-export-ok", F_OK) ) not_found("Repository not exported: '%s'", dir); http_config(); max_request_buffer = git_env_ulong("GIT_HTTP_MAX_REQUEST_BUFFER", max_request_buffer); cmd->imp(cmd_arg); return 0; }
/* 主程序 */ int main(int argc, char** argv) { char * pattern; int x, z, z1, lno = 0, cflags = 0; char ebuf[128], lbuf[256]; regex_t reg, reg1; regmatch_t pm[10]; const size_t nmatch = 10; sqlite3 *db = NULL; char *zErrMsg = 0; int rc = 0; rc = sqlite3_open("wubi.db",&db); if( rc ) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); exit(1); } char *sql = "CREATE TABLE word (cn VARCHAR(3) NOT NULL, first VARCHAR(4) NOT NULL, sec VARCHAR(4), pri SMALLINT DEFAULT 0)"; sqlite3_exec( db, sql, 0, 0, &zErrMsg ); sql = "CREATE TABLE wordgroup (cn VARCHAR(12) NOT NULL, first VARCHAR(4) NOT NULL)"; sqlite3_exec( db, sql, 0, 0, &zErrMsg ); /* 编译正则表达式*/ pattern = argv[1]; //获取正则表达式 z = regcomp(®, pattern, REG_EXTENDED); //如果编译成功返回0,其它返回说明有错误产生 z1 = regcomp(®1, "[a-y]*$", REG_EXTENDED); if (z != 0 && !z1) { regerror(z, ®, ebuf, sizeof(ebuf)); fprintf(stderr, "%s: pattern '%s' \n",ebuf, pattern); return 1; } /* 逐行处理输入的数据 */ while(fgets(lbuf, sizeof(lbuf), stdin)) { ++lno; //取得读取字符串的长度,并判断字符串结尾字符是否为回车符'\n'。如果是,将结尾字符改为0 if ((z = strlen(lbuf)) > 0 && lbuf[z-1]== '\n') lbuf[z - 1] = 0; /* 对每一行应用正则表达式进行匹配 */ z = regexec(®, lbuf, nmatch, pm, REG_NOTBOL); if (z == REG_NOMATCH) continue; //如果没有匹配的,则继续下一次循环 else if (z != 0) { regerror(z, ®, ebuf, sizeof(ebuf)); fprintf(stderr, "%s: regcom('%s')\n",ebuf, lbuf); return 2; } /* 输出处理结果 */ for (x = 0; x < nmatch && pm[x].rm_so != -1; ++ x) { if (!x) printf("%04d: %s\n", lno, lbuf); printf(" $%d='%s'\n", x, substr(lbuf,pm[x].rm_so,pm[x].rm_eo)); } } /* 释放正则表达式 */ regfree(®); sqlite3_close(db); //关闭数据库 return 0; }