/* * Copyright (c) 2003 Sendmail, Inc. and its suppliers. * All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. */ #include "sm/generic.h" SM_RCSID("@(#)$Id: b-regex1.c,v 1.4 2003/04/22 23:50:16 ca Exp $") #include "sm/assert.h" #include "sm/magic.h" #include "sm/heap.h" #include "sm/test.h" #include "sm/ctype.h" #include "sm/regex.h" #include #include #define toseconds(x, y) (x.tv_sec - y.tv_sec) static int Verbose = 0; struct timeval t1, t2; #define GT(ti) do { \ if (gettimeofday((ti), NULL) < 0) \ perror("gettimeofday"); \ } while (0) #define START() GT(&t1) #define END() GT(&t2) #define DONE() if (Verbose > 0) \ do { fprintf(stderr, "function time: %ld seconds\n", toseconds(t2, t1));} while (0) #define MAX_STRLEN 1024 #define ERRBUF_SIZE 1024 #define MAX_MATCH 256 void prtstr(char *s) { int c; while ((c = *s++) != '\0') if (ISPRINT(c)) putchar(c); else printf(" %02x ", (int) c); } int b_regcomp(regex_t *preg, const char *pattern, int pflags) { int regerr; regerr = regcomp(preg, pattern, pflags); if (regerr != 0) { /* Errorhandling */ char errbuf[ERRBUF_SIZE]; (void) regerror(regerr, preg, errbuf, sizeof errbuf); fprintf(stderr, "pattern-compile-error: %s", errbuf); } return regerr; } int b_regmatch(const regex_t *preg, const char *string, int eflags) { int r; size_t nmatch; regmatch_t pmatch[MAX_MATCH]; nmatch = 0; r = regexec(preg, string, nmatch, pmatch, eflags); return r; } int main(int argc, char *argv[]) { int c, i, reps; int regopts; char *pattern; char string[MAX_STRLEN]; char *p; regex_t reg; regopts = REG_EXTENDED; pattern = "^(.+\\.)?sendmail\\.org$"; reps = 1; while ((c = getopt(argc, argv, "beip:r:sV")) != -1) { switch (c) { case 'b': #ifdef REG_BASIC regopts |= REG_BASIC; #endif /* REG_BASIC */ break; case 'e': regopts &= ~REG_EXTENDED; break; case 'i': regopts |= REG_ICASE; break; case 'p': pattern = optarg; break; case 'r': reps = atoi(optarg); if (reps <= 1) return 1; break; case 's': regopts |= REG_NOSUB; break; case 'V': ++Verbose; break; #if 0 default: usage(argv[0]); return 1; #endif /* 0 */ } } sm_test_begin(argc, argv, "test regex"); c = b_regcomp(®, pattern, regopts); if (Verbose > 2) { printf("pattern=\""); prtstr(pattern); printf("\"\n"); } else if (Verbose > 1) printf("pattern=\"%s\"\n", pattern); if (c == 0) { if (argc > optind) { for (i = optind; i < argc; i++) { c = b_regmatch(®, argv[i], 0); /* "Canonify" result */ if (Verbose == 0 && c > 0) c = 1; printf("match %s=%d\n", argv[i], c); } } else { START(); while (fgets(string, sizeof(string), stdin) != NULL) { p = strchr(string, '\n'); if (p != NULL) *p = '\0'; for (i = 0; i < reps; i++) c = b_regmatch(®, string, 0); /* "Canonify" result */ if (Verbose == 0 && c > 0) c = 1; printf("match %s=%d\n", string, c); } END(); DONE(); } regfree(®); } return sm_test_end(); }