/* dfa.c - deterministic extended regexp routines for GNU Copyright (C) 1988, 1998, 2000, 2002, 2004-2005, 2007-2018 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA */ /* Written June, 1988 by Mike Haertel Modified July, 1988 by Arthur David Olson to assist BMG speedups */ #include #include #include #ifndef VMS #include #else #define SIZE_MAX __INT32_MAX #define PTRDIFF_MAX __INT32_MAX #endif #include #ifndef VMS #include #else #include #endif #include #include #include #if HAVE_SETLOCALE #include #endif #include "dfa.h" // gets stdbool.h for us static bool streq (char const *a, char const *b) { return strcmp (a, b) == 0; } static bool isasciidigit (char c) { return '0' <= c && c <= '9'; } /* Gawk doesn't use Gnulib, so don't assume that setlocale is present. */ #ifndef LC_ALL # define setlocale(category, locale) NULL #endif #include "gettext.h" #define _(str) gettext (str) #include #include "intprops.h" #include "xalloc.h" #include "localeinfo.h" #ifndef FALLTHROUGH # if __GNUC__ < 7 # define FALLTHROUGH ((void) 0) # else # define FALLTHROUGH __attribute__ ((__fallthrough__)) # endif #endif #ifndef MIN # define MIN(a,b) ((a) < (b) ? (a) : (b)) #endif #if defined(__DJGPP__) #include "mbsupport.h" #endif #ifdef GAWK static int is_blank (int c) { return (c == ' ' || c == '\t'); } #endif /* GAWK */ /* HPUX defines these as macros in sys/param.h. */ #ifdef setbit # undef setbit #endif #ifdef clrbit # undef clrbit #endif /* First integer value that is greater than any character code. */ enum { NOTCHAR = 1 << CHAR_BIT }; /* This represents part of a character class. It must be unsigned and at least CHARCLASS_WORD_BITS wide. Any excess bits are zero. */ typedef unsigned long int charclass_word; /* CHARCLASS_WORD_BITS is the number of bits used in a charclass word. CHARCLASS_PAIR (LO, HI) is part of a charclass initializer, and represents 64 bits' worth of a charclass, where LO and HI are the low and high-order 32 bits of the 64-bit quantity. */ #if ULONG_MAX >> 31 >> 31 < 3 enum { CHARCLASS_WORD_BITS = 32 }; # define CHARCLASS_PAIR(lo, hi) lo, hi #else enum { CHARCLASS_WORD_BITS = 64 }; # define CHARCLASS_PAIR(lo, hi) (((charclass_word) (hi) << 32) + (lo)) #endif /* An initializer for a charclass whose 32-bit words are A through H. */ #define CHARCLASS_INIT(a, b, c, d, e, f, g, h) \ {{ \ CHARCLASS_PAIR (a, b), CHARCLASS_PAIR (c, d), \ CHARCLASS_PAIR (e, f), CHARCLASS_PAIR (g, h) \ }} /* The maximum useful value of a charclass_word; all used bits are 1. */ static charclass_word const CHARCLASS_WORD_MASK = ((charclass_word) 1 << (CHARCLASS_WORD_BITS - 1) << 1) - 1; /* Number of words required to hold a bit for every character. */ enum { CHARCLASS_WORDS = (NOTCHAR + CHARCLASS_WORD_BITS - 1) / CHARCLASS_WORD_BITS }; /* Sets of unsigned characters are stored as bit vectors in arrays of ints. */ typedef struct { charclass_word w[CHARCLASS_WORDS]; } charclass; /* Convert a possibly-signed character to an unsigned character. This is a bit safer than casting to unsigned char, since it catches some type errors that the cast doesn't. */ static unsigned char to_uchar (char ch) { return ch; } /* Contexts tell us whether a character is a newline or a word constituent. Word-constituent characters are those that satisfy iswalnum, plus '_'. Each character has a single CTX_* value; bitmasks of CTX_* values denote a particular character class. A state also stores a context value, which is a bitmask of CTX_* values. A state's context represents a set of characters that the state's predecessors must match. For example, a state whose context does not include CTX_LETTER will never have transitions where the previous character is a word constituent. A state whose context is CTX_ANY might have transitions from any character. */ enum { CTX_NONE = 1, CTX_LETTER = 2, CTX_NEWLINE = 4, CTX_ANY = 7 }; /* Sometimes characters can only be matched depending on the surrounding context. Such context decisions depend on what the previous character was, and the value of the current (lookahead) character. Context dependent constraints are encoded as 9-bit integers. Each bit that is set indicates that the constraint succeeds in the corresponding context. bit 6-8 - valid contexts when next character is CTX_NEWLINE bit 3-5 - valid contexts when next character is CTX_LETTER bit 0-2 - valid contexts when next character is CTX_NONE succeeds_in_context determines whether a given constraint succeeds in a particular context. Prev is a bitmask of possible context values for the previous character, curr is the (single-bit) context value for the lookahead character. */ static int newline_constraint (int constraint) { return (constraint >> 6) & 7; } static int letter_constraint (int constraint) { return (constraint >> 3) & 7; } static int other_constraint (int constraint) { return constraint & 7; } static bool succeeds_in_context (int constraint, int prev, int curr) { return !! (((curr & CTX_NONE ? other_constraint (constraint) : 0) \ | (curr & CTX_LETTER ? letter_constraint (constraint) : 0) \ | (curr & CTX_NEWLINE ? newline_constraint (constraint) : 0)) \ & prev); } /* The following describe what a constraint depends on. */ static bool prev_newline_dependent (int constraint) { return ((constraint ^ constraint >> 2) & 0111) != 0; } static bool prev_letter_dependent (int constraint) { return ((constraint ^ constraint >> 1) & 0111) != 0; } /* Tokens that match the empty string subject to some constraint actually work by applying that constraint to determine what may follow them, taking into account what has gone before. The following values are the constraints corresponding to the special tokens previously defined. */ enum { NO_CONSTRAINT = 0777, BEGLINE_CONSTRAINT = 0444, ENDLINE_CONSTRAINT = 0700, BEGWORD_CONSTRAINT = 0050, ENDWORD_CONSTRAINT = 0202, LIMWORD_CONSTRAINT = 0252, NOTLIMWORD_CONSTRAINT = 0525 }; /* The regexp is parsed into an array of tokens in postfix form. Some tokens are operators and others are terminal symbols. Most (but not all) of these codes are returned by the lexical analyzer. */ typedef ptrdiff_t token; static ptrdiff_t const TOKEN_MAX = PTRDIFF_MAX; /* States are indexed by state_num values. These are normally nonnegative but -1 is used as a special value. */ typedef ptrdiff_t state_num; /* Predefined token values. */ enum { END = -1, /* END is a terminal symbol that matches the end of input; any value of END or less in the parse tree is such a symbol. Accepting states of the DFA are those that would have a transition on END. This is -1, not some more-negative value, to tweak the speed of comparisons to END. */ /* Ordinary character values are terminal symbols that match themselves. */ /* CSET must come last in the following list of special tokens. Otherwise, the list order matters only for performance. Related special tokens should have nearby values so that code like (t == ANYCHAR || t == MBCSET || CSET <= t) can be done with a single machine-level comparison. */ EMPTY = NOTCHAR, /* EMPTY is a terminal symbol that matches the empty string. */ QMARK, /* QMARK is an operator of one argument that matches zero or one occurrences of its argument. */ STAR, /* STAR is an operator of one argument that matches the Kleene closure (zero or more occurrences) of its argument. */ PLUS, /* PLUS is an operator of one argument that matches the positive closure (one or more occurrences) of its argument. */ REPMN, /* REPMN is a lexical token corresponding to the {m,n} construct. REPMN never appears in the compiled token vector. */ CAT, /* CAT is an operator of two arguments that matches the concatenation of its arguments. CAT is never returned by the lexical analyzer. */ OR, /* OR is an operator of two arguments that matches either of its arguments. */ LPAREN, /* LPAREN never appears in the parse tree, it is only a lexeme. */ RPAREN, /* RPAREN never appears in the parse tree. */ WCHAR, /* Only returned by lex. wctok contains the wide character representation. */ ANYCHAR, /* ANYCHAR is a terminal symbol that matches a valid multibyte (or single byte) character. It is used only if MB_CUR_MAX > 1. */ BEG, /* BEG is an initial symbol that matches the beginning of input. */ BEGLINE, /* BEGLINE is a terminal symbol that matches the empty string at the beginning of a line. */ ENDLINE, /* ENDLINE is a terminal symbol that matches the empty string at the end of a line. */ BEGWORD, /* BEGWORD is a terminal symbol that matches the empty string at the beginning of a word. */ ENDWORD, /* ENDWORD is a terminal symbol that matches the empty string at the end of a word. */ LIMWORD, /* LIMWORD is a terminal symbol that matches the empty string at the beginning or the end of a word. */ NOTLIMWORD, /* NOTLIMWORD is a terminal symbol that matches the empty string not at the beginning or end of a word. */ BACKREF, /* BACKREF is generated by \ or by any other construct that is not completely handled. If the scanner detects a transition on backref, it returns a kind of "semi-success" indicating that the match will have to be verified with a backtracking matcher. */ MBCSET, /* MBCSET is similar to CSET, but for multibyte characters. */ CSET /* CSET and (and any value greater) is a terminal symbol that matches any of a class of characters. */ }; /* States of the recognizer correspond to sets of positions in the parse tree, together with the constraints under which they may be matched. So a position is encoded as an index into the parse tree together with a constraint. */ typedef struct { size_t index; /* Index into the parse array. */ unsigned int constraint; /* Constraint for matching this position. */ } position; /* Sets of positions are stored as arrays. */ typedef struct { position *elems; /* Elements of this position set. */ ptrdiff_t nelem; /* Number of elements in this set. */ ptrdiff_t alloc; /* Number of elements allocated in ELEMS. */ } position_set; /* A state of the dfa consists of a set of positions, some flags, and the token value of the lowest-numbered position of the state that contains an END token. */ typedef struct { size_t hash; /* Hash of the positions of this state. */ position_set elems; /* Positions this state could match. */ unsigned char context; /* Context from previous state. */ unsigned short constraint; /* Constraint for this state to accept. */ token first_end; /* Token value of the first END in elems. */ position_set mbps; /* Positions which can match multibyte characters or the follows, e.g., period. Used only if MB_CUR_MAX > 1. */ state_num mb_trindex; /* Index of this state in MB_TRANS, or negative if the state does not have ANYCHAR. */ } dfa_state; /* Maximum for any transition table count. This should be at least 3, for the initial state setup. */ enum { MAX_TRCOUNT = 1024 }; /* A bracket operator. e.g., [a-c], [[:alpha:]], etc. */ struct mb_char_classes { ptrdiff_t cset; bool invert; wchar_t *chars; /* Normal characters. */ ptrdiff_t nchars; ptrdiff_t nchars_alloc; }; struct regex_syntax { /* Syntax bits controlling the behavior of the lexical analyzer. */ reg_syntax_t syntax_bits; bool syntax_bits_set; /* Flag for case-folding letters into sets. */ bool case_fold; /* True if ^ and $ match only the start and end of data, and do not match end-of-line within data. */ bool anchor; /* End-of-line byte in data. */ unsigned char eolbyte; /* Cache of char-context values. */ char sbit[NOTCHAR]; /* If never_trail[B], the byte B cannot be a non-initial byte in a multibyte character. */ bool never_trail[NOTCHAR]; /* Set of characters considered letters. */ charclass letters; /* Set of characters that are newline. */ charclass newline; }; /* Lexical analyzer. All the dross that deals with the obnoxious GNU Regex syntax bits is located here. The poor, suffering reader is referred to the GNU Regex documentation for the meaning of the @#%!@#%^!@ syntax bits. */ struct lexer_state { char const *ptr; /* Pointer to next input character. */ size_t left; /* Number of characters remaining. */ token lasttok; /* Previous token returned; initially END. */ size_t parens; /* Count of outstanding left parens. */ int minrep, maxrep; /* Repeat counts for {m,n}. */ /* Wide character representation of the current multibyte character, or WEOF if there was an encoding error. Used only if MB_CUR_MAX > 1. */ wint_t wctok; /* Length of the multibyte representation of wctok. */ int cur_mb_len; /* The most recently analyzed multibyte bracket expression. */ struct mb_char_classes brack; /* We're separated from beginning or (, | only by zero-width characters. */ bool laststart; }; /* Recursive descent parser for regular expressions. */ struct parser_state { token tok; /* Lookahead token. */ size_t depth; /* Current depth of a hypothetical stack holding deferred productions. This is used to determine the depth that will be required of the real stack later on in dfaanalyze. */ }; /* A compiled regular expression. */ struct dfa { /* Syntax configuration */ struct regex_syntax syntax; /* Fields filled by the scanner. */ charclass *charclasses; /* Array of character sets for CSET tokens. */ ptrdiff_t cindex; /* Index for adding new charclasses. */ ptrdiff_t calloc; /* Number of charclasses allocated. */ size_t canychar; /* Index of anychar class, or (size_t) -1. */ /* Scanner state */ struct lexer_state lex; /* Parser state */ struct parser_state parse; /* Fields filled by the parser. */ token *tokens; /* Postfix parse array. */ size_t tindex; /* Index for adding new tokens. */ size_t talloc; /* Number of tokens currently allocated. */ size_t depth; /* Depth required of an evaluation stack used for depth-first traversal of the parse tree. */ size_t nleaves; /* Number of leaves on the parse tree. */ size_t nregexps; /* Count of parallel regexps being built with dfaparse. */ bool fast; /* The DFA is fast. */ token utf8_anychar_classes[5]; /* To lower ANYCHAR in UTF-8 locales. */ mbstate_t mbs; /* Multibyte conversion state. */ /* The following are valid only if MB_CUR_MAX > 1. */ /* The value of multibyte_prop[i] is defined by following rule. if tokens[i] < NOTCHAR bit 0 : tokens[i] is the first byte of a character, including single-byte characters. bit 1 : tokens[i] is the last byte of a character, including single-byte characters. e.g. tokens = 'single_byte_a', 'multi_byte_A', single_byte_b' = 'sb_a', 'mb_A(1st byte)', 'mb_A(2nd byte)', 'mb_A(3rd byte)', 'sb_b' multibyte_prop = 3 , 1 , 0 , 2 , 3 */ char *multibyte_prop; /* Fields filled by the superset. */ struct dfa *superset; /* Hint of the dfa. */ /* Fields filled by the state builder. */ dfa_state *states; /* States of the dfa. */ state_num sindex; /* Index for adding new states. */ ptrdiff_t salloc; /* Number of states currently allocated. */ /* Fields filled by the parse tree->NFA conversion. */ position_set *follows; /* Array of follow sets, indexed by position index. The follow of a position is the set of positions containing characters that could conceivably follow a character matching the given position in a string matching the regexp. Allocated to the maximum possible position index. */ bool searchflag; /* We are supposed to build a searching as opposed to an exact matcher. A searching matcher finds the first and shortest string matching a regexp anywhere in the buffer, whereas an exact matcher finds the longest string matching, but anchored to the beginning of the buffer. */ /* Fields filled by dfaanalyze. */ int *constraints; /* Array of union of accepting constraints in the follow of a position. */ int *separates; /* Array of contexts on follow of a position. */ /* Fields filled by dfaexec. */ state_num tralloc; /* Number of transition tables that have slots so far, not counting trans[-1] and trans[-2]. */ int trcount; /* Number of transition tables that have been built, other than for initial states. */ int min_trcount; /* Number of initial states. Equivalently, the minimum state number for which trcount counts transitions. */ state_num **trans; /* Transition tables for states that can never accept. If the transitions for a state have not yet been computed, or the state could possibly accept, its entry in this table is NULL. This points to two past the start of the allocated array, and trans[-1] and trans[-2] are always NULL. */ state_num **fails; /* Transition tables after failing to accept on a state that potentially could do so. If trans[i] is non-null, fails[i] must be null. */ char *success; /* Table of acceptance conditions used in dfaexec and computed in build_state. */ state_num *newlines; /* Transitions on newlines. The entry for a newline in any transition table is always -1 so we can count lines without wasting too many cycles. The transition for a newline is stored separately and handled as a special case. Newline is also used as a sentinel at the end of the buffer. */ state_num initstate_notbol; /* Initial state for CTX_LETTER and CTX_NONE context in multibyte locales, in which we do not distinguish between their contexts, as not supported word. */ position_set mb_follows; /* Follow set added by ANYCHAR on demand. */ state_num **mb_trans; /* Transition tables for states with ANYCHAR. */ state_num mb_trcount; /* Number of transition tables for states with ANYCHAR that have actually been built. */ /* Information derived from the locale. This is at the end so that a quick memset need not clear it specially. */ /* dfaexec implementation. */ char *(*dfaexec) (struct dfa *, char const *, char *, bool, size_t *, bool *); /* The locale is simple, like the C locale. These locales can be processed more efficiently, as they are single-byte, their native character set is in collating-sequence order, and they do not have multi-character collating elements. */ bool simple_locale; /* Other cached information derived from the locale. */ struct localeinfo localeinfo; }; /* User access to dfa internals. */ /* S could possibly be an accepting state of R. */ static bool accepting (state_num s, struct dfa const *r) { return r->states[s].constraint != 0; } /* STATE accepts in the specified context. */ static bool accepts_in_context (int prev, int curr, state_num state, struct dfa const *dfa) { return succeeds_in_context (dfa->states[state].constraint, prev, curr); } static void regexp (struct dfa *dfa); /* Store into *PWC the result of converting the leading bytes of the multibyte buffer S of length N bytes, using D->localeinfo.sbctowc and updating the conversion state in *D. On conversion error, convert just a single byte, to WEOF. Return the number of bytes converted. This differs from mbrtowc (PWC, S, N, &D->mbs) as follows: * PWC points to wint_t, not to wchar_t. * The last arg is a dfa *D instead of merely a multibyte conversion state D->mbs. * N must be at least 1. * S[N - 1] must be a sentinel byte. * Shift encodings are not supported. * The return value is always in the range 1..N. * D->mbs is always valid afterwards. * *PWC is always set to something. */ static size_t mbs_to_wchar (wint_t *pwc, char const *s, size_t n, struct dfa *d) { unsigned char uc = s[0]; wint_t wc = d->localeinfo.sbctowc[uc]; if (wc == WEOF) { wchar_t wch; size_t nbytes = mbrtowc (&wch, s, n, &d->mbs); if (0 < nbytes && nbytes < (size_t) -2) { *pwc = wch; return nbytes; } memset (&d->mbs, 0, sizeof d->mbs); } *pwc = wc; return 1; } #ifdef DEBUG static void prtok (token t) { if (t <= END) fprintf (stderr, "END"); else if (0 <= t && t < NOTCHAR) { unsigned int ch = t; fprintf (stderr, "0x%02x", ch); } else { char const *s; switch (t) { case BEG: s = "BEG"; break; case EMPTY: s = "EMPTY"; break; case BACKREF: s = "BACKREF"; break; case BEGLINE: s = "BEGLINE"; break; case ENDLINE: s = "ENDLINE"; break; case BEGWORD: s = "BEGWORD"; break; case ENDWORD: s = "ENDWORD"; break; case LIMWORD: s = "LIMWORD"; break; case NOTLIMWORD: s = "NOTLIMWORD"; break; case QMARK: s = "QMARK"; break; case STAR: s = "STAR"; break; case PLUS: s = "PLUS"; break; case CAT: s = "CAT"; break; case OR: s = "OR"; break; case LPAREN: s = "LPAREN"; break; case RPAREN: s = "RPAREN"; break; case ANYCHAR: s = "ANYCHAR"; break; case MBCSET: s = "MBCSET"; break; default: s = "CSET"; break; } fprintf (stderr, "%s", s); } } #endif /* DEBUG */ /* Stuff pertaining to charclasses. */ static bool tstbit (unsigned int b, charclass const *c) { return c->w[b / CHARCLASS_WORD_BITS] >> b % CHARCLASS_WORD_BITS & 1; } static void setbit (unsigned int b, charclass *c) { charclass_word one = 1; c->w[b / CHARCLASS_WORD_BITS] |= one << b % CHARCLASS_WORD_BITS; } static void clrbit (unsigned int b, charclass *c) { charclass_word one = 1; c->w[b / CHARCLASS_WORD_BITS] &= ~(one << b % CHARCLASS_WORD_BITS); } static void zeroset (charclass *s) { memset (s, 0, sizeof *s); } static void fillset (charclass *s) { for (int i = 0; i < CHARCLASS_WORDS; i++) s->w[i] = CHARCLASS_WORD_MASK; } static void notset (charclass *s) { for (int i = 0; i < CHARCLASS_WORDS; ++i) s->w[i] = CHARCLASS_WORD_MASK & ~s->w[i]; } static bool equal (charclass const *s1, charclass const *s2) { charclass_word w = 0; for (int i = 0; i < CHARCLASS_WORDS; i++) w |= s1->w[i] ^ s2->w[i]; return w == 0; } static bool emptyset (charclass const *s) { charclass_word w = 0; for (int i = 0; i < CHARCLASS_WORDS; i++) w |= s->w[i]; return w == 0; } /* Grow PA, which points to an array of *NITEMS items, and return the location of the reallocated array, updating *NITEMS to reflect its new size. The new array will contain at least NITEMS_INCR_MIN more items, but will not contain more than NITEMS_MAX items total. ITEM_SIZE is the size of each item, in bytes. ITEM_SIZE and NITEMS_INCR_MIN must be positive. *NITEMS must be nonnegative. If NITEMS_MAX is -1, it is treated as if it were infinity. If PA is null, then allocate a new array instead of reallocating the old one. Thus, to grow an array A without saving its old contents, do { free (A); A = xpalloc (NULL, &AITEMS, ...); }. */ static void * xpalloc (void *pa, ptrdiff_t *nitems, ptrdiff_t nitems_incr_min, ptrdiff_t nitems_max, ptrdiff_t item_size) { ptrdiff_t n0 = *nitems; /* The approximate size to use for initial small allocation requests. This is the largest "small" request for the GNU C library malloc. */ enum { DEFAULT_MXFAST = 64 * sizeof (size_t) / 4 }; /* If the array is tiny, grow it to about (but no greater than) DEFAULT_MXFAST bytes. Otherwise, grow it by about 50%. Adjust the growth according to three constraints: NITEMS_INCR_MIN, NITEMS_MAX, and what the C language can represent safely. */ ptrdiff_t n, nbytes; if (INT_ADD_WRAPV (n0, n0 >> 1, &n)) n = PTRDIFF_MAX; if (0 <= nitems_max && nitems_max < n) n = nitems_max; ptrdiff_t adjusted_nbytes = ((INT_MULTIPLY_WRAPV (n, item_size, &nbytes) || SIZE_MAX < nbytes) ? MIN (PTRDIFF_MAX, SIZE_MAX) : nbytes < DEFAULT_MXFAST ? DEFAULT_MXFAST : 0); if (adjusted_nbytes) { n = adjusted_nbytes / item_size; nbytes = adjusted_nbytes - adjusted_nbytes % item_size; } if (! pa) *nitems = 0; if (n - n0 < nitems_incr_min && (INT_ADD_WRAPV (n0, nitems_incr_min, &n) || (0 <= nitems_max && nitems_max < n) || INT_MULTIPLY_WRAPV (n, item_size, &nbytes))) xalloc_die (); pa = xrealloc (pa, nbytes); *nitems = n; return pa; } /* Ensure that the array addressed by PA holds at least I + 1 items. Either return PA, or reallocate the array and return its new address. Although PA may be null, the returned value is never null. The array holds *NITEMS items, where 0 <= I <= *NITEMS; *NITEMS is updated on reallocation. If PA is null, *NITEMS must be zero. Do not allocate more than NITEMS_MAX items total; -1 means no limit. ITEM_SIZE is the size of one item; it must be positive. Avoid O(N**2) behavior on arrays growing linearly. */ static void * maybe_realloc (void *pa, ptrdiff_t i, ptrdiff_t *nitems, ptrdiff_t nitems_max, ptrdiff_t item_size) { if (i < *nitems) return pa; return xpalloc (pa, nitems, 1, nitems_max, item_size); } /* In DFA D, find the index of charclass S, or allocate a new one. */ static ptrdiff_t charclass_index (struct dfa *d, charclass *s) { ptrdiff_t i; for (i = 0; i < d->cindex; ++i) if (equal (s, &d->charclasses[i])) return i; d->charclasses = maybe_realloc (d->charclasses, d->cindex, &d->calloc, TOKEN_MAX - CSET, sizeof *d->charclasses); ++d->cindex; d->charclasses[i] = *s; return i; } static bool unibyte_word_constituent (struct dfa const *dfa, unsigned char c) { return dfa->localeinfo.sbctowc[c] != WEOF && (isalnum (c) || (c) == '_'); } static int char_context (struct dfa const *dfa, unsigned char c) { if (c == dfa->syntax.eolbyte && !dfa->syntax.anchor) return CTX_NEWLINE; if (unibyte_word_constituent (dfa, c)) return CTX_LETTER; return CTX_NONE; } /* Copy the syntax settings from one dfa instance to another. Saves considerable computation time if compiling many regular expressions based on the same setting. */ void dfacopysyntax (struct dfa *to, const struct dfa *from) { to->dfaexec = from->dfaexec; to->simple_locale = from->simple_locale; to->localeinfo = from->localeinfo; to->fast = from->fast; to->canychar = from->canychar; to->lex.cur_mb_len = from->lex.cur_mb_len; to->syntax = from->syntax; } /* Set a bit in the charclass for the given wchar_t. Do nothing if WC is represented by a multi-byte sequence. Even for MB_CUR_MAX == 1, this may happen when folding case in weird Turkish locales where dotless i/dotted I are not included in the chosen character set. Return whether a bit was set in the charclass. */ static bool setbit_wc (wint_t wc, charclass *c) { int b = wctob (wc); if (b < 0) return false; setbit (b, c); return true; } /* Set a bit for B and its case variants in the charclass C. MB_CUR_MAX must be 1. */ static void setbit_case_fold_c (int b, charclass *c) { int ub = toupper (b); for (int i = 0; i < NOTCHAR; i++) if (toupper (i) == ub) setbit (i, c); } /* Return true if the locale compatible with the C locale. */ static bool using_simple_locale (bool multibyte) { /* The native character set is known to be compatible with the C locale. The following test isn't perfect, but it's good enough in practice, as only ASCII and EBCDIC are in common use and this test correctly accepts ASCII and rejects EBCDIC. */ enum { native_c_charset = ('\b' == 8 && '\t' == 9 && '\n' == 10 && '\v' == 11 && '\f' == 12 && '\r' == 13 && ' ' == 32 && '!' == 33 && '"' == 34 && '#' == 35 && '%' == 37 && '&' == 38 && '\'' == 39 && '(' == 40 && ')' == 41 && '*' == 42 && '+' == 43 && ',' == 44 && '-' == 45 && '.' == 46 && '/' == 47 && '0' == 48 && '9' == 57 && ':' == 58 && ';' == 59 && '<' == 60 && '=' == 61 && '>' == 62 && '?' == 63 && 'A' == 65 && 'Z' == 90 && '[' == 91 && '\\' == 92 && ']' == 93 && '^' == 94 && '_' == 95 && 'a' == 97 && 'z' == 122 && '{' == 123 && '|' == 124 && '}' == 125 && '~' == 126) }; if (!native_c_charset || multibyte) return false; else { /* Treat C and POSIX locales as being compatible. Also, treat errors as compatible, as these are invariably from stubs. */ char const *loc = setlocale (LC_ALL, NULL); return !loc || streq (loc, "C") || streq (loc, "POSIX"); } } /* Fetch the next lexical input character from the pattern. There must at least one byte of pattern input. Set DFA->lex.wctok to the value of the character or to WEOF depending on whether the input is a valid multibyte character (possibly of length 1). Then return the next input byte value, except return EOF if the input is a multibyte character of length greater than 1. */ static int fetch_wc (struct dfa *dfa) { size_t nbytes = mbs_to_wchar (&dfa->lex.wctok, dfa->lex.ptr, dfa->lex.left, dfa); dfa->lex.cur_mb_len = nbytes; int c = nbytes == 1 ? to_uchar (dfa->lex.ptr[0]) : EOF; dfa->lex.ptr += nbytes; dfa->lex.left -= nbytes; return c; } /* If there is no more input, report an error about unbalanced brackets. Otherwise, behave as with fetch_wc (DFA). */ static int bracket_fetch_wc (struct dfa *dfa) { if (! dfa->lex.left) dfaerror (_("unbalanced [")); return fetch_wc (dfa); } typedef int predicate (int); /* The following list maps the names of the Posix named character classes to predicate functions that determine whether a given character is in the class. The leading [ has already been eaten by the lexical analyzer. */ struct dfa_ctype { const char *name; predicate *func; bool single_byte_only; }; static const struct dfa_ctype prednames[] = { {"alpha", isalpha, false}, {"upper", isupper, false}, {"lower", islower, false}, {"digit", isdigit, true}, {"xdigit", isxdigit, false}, {"space", isspace, false}, {"punct", ispunct, false}, {"alnum", isalnum, false}, {"print", isprint, false}, {"graph", isgraph, false}, {"cntrl", iscntrl, false}, {"blank", is_blank, false}, {NULL, NULL, false} }; static const struct dfa_ctype *_GL_ATTRIBUTE_PURE find_pred (const char *str) { for (unsigned int i = 0; prednames[i].name; ++i) if (streq (str, prednames[i].name)) return &prednames[i]; return NULL; } /* Parse a bracket expression, which possibly includes multibyte characters. */ static token parse_bracket_exp (struct dfa *dfa) { /* This is a bracket expression that dfaexec is known to process correctly. */ bool known_bracket_exp = true; /* Used to warn about [:space:]. Bit 0 = first character is a colon. Bit 1 = last character is a colon. Bit 2 = includes any other character but a colon. Bit 3 = includes ranges, char/equiv classes or collation elements. */ int colon_warning_state; dfa->lex.brack.nchars = 0; charclass ccl; zeroset (&ccl); int c = bracket_fetch_wc (dfa); bool invert = c == '^'; if (invert) { c = bracket_fetch_wc (dfa); known_bracket_exp = dfa->simple_locale; } wint_t wc = dfa->lex.wctok; int c1; wint_t wc1; colon_warning_state = (c == ':'); do { c1 = NOTCHAR; /* Mark c1 as not initialized. */ colon_warning_state &= ~2; /* Note that if we're looking at some other [:...:] construct, we just treat it as a bunch of ordinary characters. We can do this because we assume regex has checked for syntax errors before dfa is ever called. */ if (c == '[') { c1 = bracket_fetch_wc (dfa); wc1 = dfa->lex.wctok; if ((c1 == ':' && (dfa->syntax.syntax_bits & RE_CHAR_CLASSES)) || c1 == '.' || c1 == '=') { enum { MAX_BRACKET_STRING_LEN = 32 }; char str[MAX_BRACKET_STRING_LEN + 1]; size_t len = 0; for (;;) { c = bracket_fetch_wc (dfa); if (dfa->lex.left == 0 || (c == c1 && dfa->lex.ptr[0] == ']')) break; if (len < MAX_BRACKET_STRING_LEN) str[len++] = c; else /* This is in any case an invalid class name. */ str[0] = '\0'; } str[len] = '\0'; /* Fetch bracket. */ c = bracket_fetch_wc (dfa); wc = dfa->lex.wctok; if (c1 == ':') /* Build character class. POSIX allows character classes to match multicharacter collating elements, but the regex code does not support that, so do not worry about that possibility. */ { char const *class = (dfa->syntax.case_fold && (streq (str, "upper") || streq (str, "lower")) ? "alpha" : str); const struct dfa_ctype *pred = find_pred (class); if (!pred) dfaerror (_("invalid character class")); if (dfa->localeinfo.multibyte && !pred->single_byte_only) known_bracket_exp = false; else for (int c2 = 0; c2 < NOTCHAR; ++c2) if (pred->func (c2)) setbit (c2, &ccl); } else known_bracket_exp = false; colon_warning_state |= 8; /* Fetch new lookahead character. */ c1 = bracket_fetch_wc (dfa); wc1 = dfa->lex.wctok; continue; } /* We treat '[' as a normal character here. c/c1/wc/wc1 are already set up. */ } if (c == '\\' && (dfa->syntax.syntax_bits & RE_BACKSLASH_ESCAPE_IN_LISTS)) { c = bracket_fetch_wc (dfa); wc = dfa->lex.wctok; } if (c1 == NOTCHAR) { c1 = bracket_fetch_wc (dfa); wc1 = dfa->lex.wctok; } if (c1 == '-') /* build range characters. */ { int c2 = bracket_fetch_wc (dfa); wint_t wc2 = dfa->lex.wctok; /* A bracket expression like [a-[.aa.]] matches an unknown set. Treat it like [-a[.aa.]] while parsing it, and remember that the set is unknown. */ if (c2 == '[' && dfa->lex.ptr[0] == '.') { known_bracket_exp = false; c2 = ']'; } if (c2 == ']') { /* In the case [x-], the - is an ordinary hyphen, which is left in c1, the lookahead character. */ dfa->lex.ptr -= dfa->lex.cur_mb_len; dfa->lex.left += dfa->lex.cur_mb_len; } else { if (c2 == '\\' && (dfa->syntax.syntax_bits & RE_BACKSLASH_ESCAPE_IN_LISTS)) { c2 = bracket_fetch_wc (dfa); wc2 = dfa->lex.wctok; } colon_warning_state |= 8; c1 = bracket_fetch_wc (dfa); wc1 = dfa->lex.wctok; /* Treat [x-y] as a range if x != y. */ if (wc != wc2 || wc == WEOF) { if (dfa->simple_locale || (isasciidigit (c) & isasciidigit (c2))) { for (int ci = c; ci <= c2; ci++) if (dfa->syntax.case_fold && isalpha (ci)) setbit_case_fold_c (ci, &ccl); else setbit (ci, &ccl); } else known_bracket_exp = false; continue; } } } colon_warning_state |= (c == ':') ? 2 : 4; if (!dfa->localeinfo.multibyte) { if (dfa->syntax.case_fold && isalpha (c)) setbit_case_fold_c (c, &ccl); else setbit (c, &ccl); continue; } if (wc == WEOF) known_bracket_exp = false; else { wchar_t folded[CASE_FOLDED_BUFSIZE + 1]; unsigned int n = (dfa->syntax.case_fold ? case_folded_counterparts (wc, folded + 1) + 1 : 1); folded[0] = wc; for (unsigned int i = 0; i < n; i++) if (!setbit_wc (folded[i], &ccl)) { dfa->lex.brack.chars = maybe_realloc (dfa->lex.brack.chars, dfa->lex.brack.nchars, &dfa->lex.brack.nchars_alloc, -1, sizeof *dfa->lex.brack.chars); dfa->lex.brack.chars[dfa->lex.brack.nchars++] = folded[i]; } } } while ((wc = wc1, (c = c1) != ']')); if (colon_warning_state == 7) dfawarn (_("character class syntax is [[:space:]], not [:space:]")); if (! known_bracket_exp) return BACKREF; if (dfa->localeinfo.multibyte && (invert || dfa->lex.brack.nchars != 0)) { dfa->lex.brack.invert = invert; dfa->lex.brack.cset = emptyset (&ccl) ? -1 : charclass_index (dfa, &ccl); return MBCSET; } if (invert) { notset (&ccl); if (dfa->syntax.syntax_bits & RE_HAT_LISTS_NOT_NEWLINE) clrbit ('\n', &ccl); } return CSET + charclass_index (dfa, &ccl); } struct lexptr { char const *ptr; size_t left; }; static void push_lex_state (struct dfa *dfa, struct lexptr *ls, char const *s) { ls->ptr = dfa->lex.ptr; ls->left = dfa->lex.left; dfa->lex.ptr = s; dfa->lex.left = strlen (s); } static void pop_lex_state (struct dfa *dfa, struct lexptr const *ls) { dfa->lex.ptr = ls->ptr; dfa->lex.left = ls->left; } static token lex (struct dfa *dfa) { bool backslash = false; /* Basic plan: We fetch a character. If it's a backslash, we set the backslash flag and go through the loop again. On the plus side, this avoids having a duplicate of the main switch inside the backslash case. On the minus side, it means that just about every case begins with "if (backslash) ...". */ for (int i = 0; i < 2; ++i) { if (! dfa->lex.left) return dfa->lex.lasttok = END; int c = fetch_wc (dfa); switch (c) { case '\\': if (backslash) goto normal_char; if (dfa->lex.left == 0) dfaerror (_("unfinished \\ escape")); backslash = true; break; case '^': if (backslash) goto normal_char; if (dfa->syntax.syntax_bits & RE_CONTEXT_INDEP_ANCHORS || dfa->lex.lasttok == END || dfa->lex.lasttok == LPAREN || dfa->lex.lasttok == OR) return dfa->lex.lasttok = BEGLINE; goto normal_char; case '$': if (backslash) goto normal_char; if (dfa->syntax.syntax_bits & RE_CONTEXT_INDEP_ANCHORS || dfa->lex.left == 0 || ((dfa->lex.left > !(dfa->syntax.syntax_bits & RE_NO_BK_PARENS)) && (dfa->lex.ptr[!(dfa->syntax.syntax_bits & RE_NO_BK_PARENS) & (dfa->lex.ptr[0] == '\\')] == ')')) || ((dfa->lex.left > !(dfa->syntax.syntax_bits & RE_NO_BK_VBAR)) && (dfa->lex.ptr[!(dfa->syntax.syntax_bits & RE_NO_BK_VBAR) & (dfa->lex.ptr[0] == '\\')] == '|')) || ((dfa->syntax.syntax_bits & RE_NEWLINE_ALT) && dfa->lex.left > 0 && dfa->lex.ptr[0] == '\n')) return dfa->lex.lasttok = ENDLINE; goto normal_char; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (backslash && !(dfa->syntax.syntax_bits & RE_NO_BK_REFS)) { dfa->lex.laststart = false; return dfa->lex.lasttok = BACKREF; } goto normal_char; case '`': if (backslash && !(dfa->syntax.syntax_bits & RE_NO_GNU_OPS)) { /* FIXME: should be beginning of string */ return dfa->lex.lasttok = BEGLINE; } goto normal_char; case '\'': if (backslash && !(dfa->syntax.syntax_bits & RE_NO_GNU_OPS)) { /* FIXME: should be end of string */ return dfa->lex.lasttok = ENDLINE; } goto normal_char; case '<': if (backslash && !(dfa->syntax.syntax_bits & RE_NO_GNU_OPS)) return dfa->lex.lasttok = BEGWORD; goto normal_char; case '>': if (backslash && !(dfa->syntax.syntax_bits & RE_NO_GNU_OPS)) return dfa->lex.lasttok = ENDWORD; goto normal_char; case 'b': if (backslash && !(dfa->syntax.syntax_bits & RE_NO_GNU_OPS)) return dfa->lex.lasttok = LIMWORD; goto normal_char; case 'B': if (backslash && !(dfa->syntax.syntax_bits & RE_NO_GNU_OPS)) return dfa->lex.lasttok = NOTLIMWORD; goto normal_char; case '?': if (dfa->syntax.syntax_bits & RE_LIMITED_OPS) goto normal_char; if (backslash != ((dfa->syntax.syntax_bits & RE_BK_PLUS_QM) != 0)) goto normal_char; if (!(dfa->syntax.syntax_bits & RE_CONTEXT_INDEP_OPS) && dfa->lex.laststart) goto normal_char; return dfa->lex.lasttok = QMARK; case '*': if (backslash) goto normal_char; if (!(dfa->syntax.syntax_bits & RE_CONTEXT_INDEP_OPS) && dfa->lex.laststart) goto normal_char; return dfa->lex.lasttok = STAR; case '+': if (dfa->syntax.syntax_bits & RE_LIMITED_OPS) goto normal_char; if (backslash != ((dfa->syntax.syntax_bits & RE_BK_PLUS_QM) != 0)) goto normal_char; if (!(dfa->syntax.syntax_bits & RE_CONTEXT_INDEP_OPS) && dfa->lex.laststart) goto normal_char; return dfa->lex.lasttok = PLUS; case '{': if (!(dfa->syntax.syntax_bits & RE_INTERVALS)) goto normal_char; if (backslash != ((dfa->syntax.syntax_bits & RE_NO_BK_BRACES) == 0)) goto normal_char; if (!(dfa->syntax.syntax_bits & RE_CONTEXT_INDEP_OPS) && dfa->lex.laststart) goto normal_char; /* Cases: {M} - exact count {M,} - minimum count, maximum is infinity {,N} - 0 through N {,} - 0 to infinity (same as '*') {M,N} - M through N */ { char const *p = dfa->lex.ptr; char const *lim = p + dfa->lex.left; dfa->lex.minrep = dfa->lex.maxrep = -1; for (; p != lim && isasciidigit (*p); p++) dfa->lex.minrep = (dfa->lex.minrep < 0 ? *p - '0' : MIN (RE_DUP_MAX + 1, dfa->lex.minrep * 10 + *p - '0')); if (p != lim) { if (*p != ',') dfa->lex.maxrep = dfa->lex.minrep; else { if (dfa->lex.minrep < 0) dfa->lex.minrep = 0; while (++p != lim && isasciidigit (*p)) dfa->lex.maxrep = (dfa->lex.maxrep < 0 ? *p - '0' : MIN (RE_DUP_MAX + 1, dfa->lex.maxrep * 10 + *p - '0')); } } if (! ((! backslash || (p != lim && *p++ == '\\')) && p != lim && *p++ == '}' && 0 <= dfa->lex.minrep && (dfa->lex.maxrep < 0 || dfa->lex.minrep <= dfa->lex.maxrep))) { if (dfa->syntax.syntax_bits & RE_INVALID_INTERVAL_ORD) goto normal_char; dfaerror (_("invalid content of \\{\\}")); } if (RE_DUP_MAX < dfa->lex.maxrep) dfaerror (_("regular expression too big")); dfa->lex.ptr = p; dfa->lex.left = lim - p; } dfa->lex.laststart = false; return dfa->lex.lasttok = REPMN; case '|': if (dfa->syntax.syntax_bits & RE_LIMITED_OPS) goto normal_char; if (backslash != ((dfa->syntax.syntax_bits & RE_NO_BK_VBAR) == 0)) goto normal_char; dfa->lex.laststart = true; return dfa->lex.lasttok = OR; case '\n': if (dfa->syntax.syntax_bits & RE_LIMITED_OPS || backslash || !(dfa->syntax.syntax_bits & RE_NEWLINE_ALT)) goto normal_char; dfa->lex.laststart = true; return dfa->lex.lasttok = OR; case '(': if (backslash != ((dfa->syntax.syntax_bits & RE_NO_BK_PARENS) == 0)) goto normal_char; dfa->lex.parens++; dfa->lex.laststart = true; return dfa->lex.lasttok = LPAREN; case ')': if (backslash != ((dfa->syntax.syntax_bits & RE_NO_BK_PARENS) == 0)) goto normal_char; if (dfa->lex.parens == 0 && dfa->syntax.syntax_bits & RE_UNMATCHED_RIGHT_PAREN_ORD) goto normal_char; dfa->lex.parens--; dfa->lex.laststart = false; return dfa->lex.lasttok = RPAREN; case '.': if (backslash) goto normal_char; if (dfa->canychar == (size_t) -1) { charclass ccl; fillset (&ccl); if (!(dfa->syntax.syntax_bits & RE_DOT_NEWLINE)) clrbit ('\n', &ccl); if (dfa->syntax.syntax_bits & RE_DOT_NOT_NULL) clrbit ('\0', &ccl); if (dfa->localeinfo.multibyte) for (int c2 = 0; c2 < NOTCHAR; c2++) if (dfa->localeinfo.sbctowc[c2] == WEOF) clrbit (c2, &ccl); dfa->canychar = charclass_index (dfa, &ccl); } dfa->lex.laststart = false; return dfa->lex.lasttok = (dfa->localeinfo.multibyte ? ANYCHAR : CSET + dfa->canychar); case 's': case 'S': if (!backslash || (dfa->syntax.syntax_bits & RE_NO_GNU_OPS)) goto normal_char; if (!dfa->localeinfo.multibyte) { charclass ccl; zeroset (&ccl); for (int c2 = 0; c2 < NOTCHAR; ++c2) if (isspace (c2)) setbit (c2, &ccl); if (c == 'S') notset (&ccl); dfa->lex.laststart = false; return dfa->lex.lasttok = CSET + charclass_index (dfa, &ccl); } /* FIXME: see if optimizing this, as is done with ANYCHAR and add_utf8_anychar, makes sense. */ /* \s and \S are documented to be equivalent to [[:space:]] and [^[:space:]] respectively, so tell the lexer to process those strings, each minus its "already processed" '['. */ { struct lexptr ls; push_lex_state (dfa, &ls, &"^[:space:]]"[c == 's']); dfa->lex.lasttok = parse_bracket_exp (dfa); pop_lex_state (dfa, &ls); } dfa->lex.laststart = false; return dfa->lex.lasttok; case 'w': case 'W': if (!backslash || (dfa->syntax.syntax_bits & RE_NO_GNU_OPS)) goto normal_char; if (!dfa->localeinfo.multibyte) { charclass ccl; zeroset (&ccl); for (int c2 = 0; c2 < NOTCHAR; ++c2) if (dfa->syntax.sbit[c2] == CTX_LETTER) setbit (c2, &ccl); if (c == 'W') notset (&ccl); dfa->lex.laststart = false; return dfa->lex.lasttok = CSET + charclass_index (dfa, &ccl); } /* FIXME: see if optimizing this, as is done with ANYCHAR and add_utf8_anychar, makes sense. */ /* \w and \W are documented to be equivalent to [_[:alnum:]] and [^_[:alnum:]] respectively, so tell the lexer to process those strings, each minus its "already processed" '['. */ { struct lexptr ls; push_lex_state (dfa, &ls, &"^_[:alnum:]]"[c == 'w']); dfa->lex.lasttok = parse_bracket_exp (dfa); pop_lex_state (dfa, &ls); } dfa->lex.laststart = false; return dfa->lex.lasttok; case '[': if (backslash) goto normal_char; dfa->lex.laststart = false; return dfa->lex.lasttok = parse_bracket_exp (dfa); default: normal_char: dfa->lex.laststart = false; /* For multibyte character sets, folding is done in atom. Always return WCHAR. */ if (dfa->localeinfo.multibyte) return dfa->lex.lasttok = WCHAR; if (dfa->syntax.case_fold && isalpha (c)) { charclass ccl; zeroset (&ccl); setbit_case_fold_c (c, &ccl); return dfa->lex.lasttok = CSET + charclass_index (dfa, &ccl); } return dfa->lex.lasttok = c; } } /* The above loop should consume at most a backslash and some other character. */ abort (); return END; /* keeps pedantic compilers happy. */ } static void addtok_mb (struct dfa *dfa, token t, char mbprop) { if (dfa->talloc == dfa->tindex) { dfa->tokens = x2nrealloc (dfa->tokens, &dfa->talloc, sizeof *dfa->tokens); if (dfa->localeinfo.multibyte) dfa->multibyte_prop = xnrealloc (dfa->multibyte_prop, dfa->talloc, sizeof *dfa->multibyte_prop); } if (dfa->localeinfo.multibyte) dfa->multibyte_prop[dfa->tindex] = mbprop; dfa->tokens[dfa->tindex++] = t; switch (t) { case QMARK: case STAR: case PLUS: break; case CAT: case OR: dfa->parse.depth--; break; case BACKREF: dfa->fast = false; FALLTHROUGH; default: dfa->nleaves++; FALLTHROUGH; case EMPTY: dfa->parse.depth++; break; } if (dfa->parse.depth > dfa->depth) dfa->depth = dfa->parse.depth; } static void addtok_wc (struct dfa *dfa, wint_t wc); /* Add the given token to the parse tree, maintaining the depth count and updating the maximum depth if necessary. */ static void addtok (struct dfa *dfa, token t) { if (dfa->localeinfo.multibyte && t == MBCSET) { bool need_or = false; /* Extract wide characters into alternations for better performance. This does not require UTF-8. */ for (ptrdiff_t i = 0; i < dfa->lex.brack.nchars; i++) { addtok_wc (dfa, dfa->lex.brack.chars[i]); if (need_or) addtok (dfa, OR); need_or = true; } dfa->lex.brack.nchars = 0; /* Wide characters have been handled above, so it is possible that the set is empty now. Do nothing in that case. */ if (dfa->lex.brack.cset != -1) { addtok (dfa, CSET + dfa->lex.brack.cset); if (need_or) addtok (dfa, OR); } } else { addtok_mb (dfa, t, 3); } } /* We treat a multibyte character as a single atom, so that DFA can treat a multibyte character as a single expression. e.g., we construct the following tree from "". */ static void addtok_wc (struct dfa *dfa, wint_t wc) { unsigned char buf[MB_LEN_MAX]; mbstate_t s = { 0 }; size_t stored_bytes = wcrtomb ((char *) buf, wc, &s); if (stored_bytes != (size_t) -1) dfa->lex.cur_mb_len = stored_bytes; else { /* This is merely stop-gap. buf[0] is undefined, yet skipping the addtok_mb call altogether can corrupt the heap. */ dfa->lex.cur_mb_len = 1; buf[0] = 0; } addtok_mb (dfa, buf[0], dfa->lex.cur_mb_len == 1 ? 3 : 1); for (int i = 1; i < dfa->lex.cur_mb_len; i++) { addtok_mb (dfa, buf[i], i == dfa->lex.cur_mb_len - 1 ? 2 : 0); addtok (dfa, CAT); } } static void add_utf8_anychar (struct dfa *dfa) { static charclass const utf8_classes[5] = { /* 80-bf: non-leading bytes. */ CHARCLASS_INIT (0, 0, 0, 0, 0xffffffff, 0xffffffff, 0, 0), /* 00-7f: 1-byte sequence. */ CHARCLASS_INIT (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0, 0, 0, 0), /* c2-df: 2-byte sequence. */ CHARCLASS_INIT (0, 0, 0, 0, 0, 0, 0xfffffffc, 0), /* e0-ef: 3-byte sequence. */ CHARCLASS_INIT (0, 0, 0, 0, 0, 0, 0, 0xffff), /* f0-f7: 4-byte sequence. */ CHARCLASS_INIT (0, 0, 0, 0, 0, 0, 0, 0xff0000) }; const unsigned int n = sizeof (utf8_classes) / sizeof (utf8_classes[0]); /* Define the five character classes that are needed below. */ if (dfa->utf8_anychar_classes[0] == 0) for (unsigned int i = 0; i < n; i++) { charclass c = utf8_classes[i]; if (i == 1) { if (!(dfa->syntax.syntax_bits & RE_DOT_NEWLINE)) clrbit ('\n', &c); if (dfa->syntax.syntax_bits & RE_DOT_NOT_NULL) clrbit ('\0', &c); } dfa->utf8_anychar_classes[i] = CSET + charclass_index (dfa, &c); } /* A valid UTF-8 character is ([0x00-0x7f] |[0xc2-0xdf][0x80-0xbf] |[0xe0-0xef[0x80-0xbf][0x80-0xbf] |[0xf0-f7][0x80-0xbf][0x80-0xbf][0x80-0xbf]) which I'll write more concisely "B|CA|DAA|EAAA". Factor the [0x00-0x7f] and you get "B|(C|(D|EA)A)A". And since the token buffer is in reverse Polish notation, you get "B C D E A CAT OR A CAT OR A CAT OR". */ unsigned int i; for (i = 1; i < n; i++) addtok (dfa, dfa->utf8_anychar_classes[i]); while (--i > 1) { addtok (dfa, dfa->utf8_anychar_classes[0]); addtok (dfa, CAT); addtok (dfa, OR); } } /* The grammar understood by the parser is as follows. regexp: regexp OR branch branch branch: branch closure closure closure: closure QMARK closure STAR closure PLUS closure REPMN atom atom: ANYCHAR MBCSET CSET BACKREF BEGLINE ENDLINE BEGWORD ENDWORD LIMWORD NOTLIMWORD LPAREN regexp RPAREN The parser builds a parse tree in postfix form in an array of tokens. */ static void atom (struct dfa *dfa) { if ((0 <= dfa->parse.tok && dfa->parse.tok < NOTCHAR) || dfa->parse.tok >= CSET || dfa->parse.tok == BEG || dfa->parse.tok == BACKREF || dfa->parse.tok == BEGLINE || dfa->parse.tok == ENDLINE || dfa->parse.tok == BEGWORD || dfa->parse.tok == ENDWORD || dfa->parse.tok == LIMWORD || dfa->parse.tok == NOTLIMWORD || dfa->parse.tok == ANYCHAR || dfa->parse.tok == MBCSET) { if (dfa->parse.tok == ANYCHAR && dfa->localeinfo.using_utf8) { /* For UTF-8 expand the period to a series of CSETs that define a valid UTF-8 character. This avoids using the slow multibyte path. I'm pretty sure it would be both profitable and correct to do it for any encoding; however, the optimization must be done manually as it is done above in add_utf8_anychar. So, let's start with UTF-8: it is the most used, and the structure of the encoding makes the correctness more obvious. */ add_utf8_anychar (dfa); } else addtok (dfa, dfa->parse.tok); dfa->parse.tok = lex (dfa); } else if (dfa->parse.tok == WCHAR) { if (dfa->lex.wctok == WEOF) addtok (dfa, BACKREF); else { addtok_wc (dfa, dfa->lex.wctok); if (dfa->syntax.case_fold) { wchar_t folded[CASE_FOLDED_BUFSIZE]; unsigned int n = case_folded_counterparts (dfa->lex.wctok, folded); for (unsigned int i = 0; i < n; i++) { addtok_wc (dfa, folded[i]); addtok (dfa, OR); } } } dfa->parse.tok = lex (dfa); } else if (dfa->parse.tok == LPAREN) { dfa->parse.tok = lex (dfa); regexp (dfa); if (dfa->parse.tok != RPAREN) dfaerror (_("unbalanced (")); dfa->parse.tok = lex (dfa); } else addtok (dfa, EMPTY); } /* Return the number of tokens in the given subexpression. */ static size_t _GL_ATTRIBUTE_PURE nsubtoks (struct dfa const *dfa, size_t tindex) { switch (dfa->tokens[tindex - 1]) { default: return 1; case QMARK: case STAR: case PLUS: return 1 + nsubtoks (dfa, tindex - 1); case CAT: case OR: { size_t ntoks1 = nsubtoks (dfa, tindex - 1); return 1 + ntoks1 + nsubtoks (dfa, tindex - 1 - ntoks1); } } } /* Copy the given subexpression to the top of the tree. */ static void copytoks (struct dfa *dfa, size_t tindex, size_t ntokens) { if (dfa->localeinfo.multibyte) for (size_t i = 0; i < ntokens; ++i) addtok_mb (dfa, dfa->tokens[tindex + i], dfa->multibyte_prop[tindex + i]); else for (size_t i = 0; i < ntokens; ++i) addtok_mb (dfa, dfa->tokens[tindex + i], 3); } static void closure (struct dfa *dfa) { atom (dfa); while (dfa->parse.tok == QMARK || dfa->parse.tok == STAR || dfa->parse.tok == PLUS || dfa->parse.tok == REPMN) if (dfa->parse.tok == REPMN && (dfa->lex.minrep || dfa->lex.maxrep)) { size_t ntokens = nsubtoks (dfa, dfa->tindex); size_t tindex = dfa->tindex - ntokens; if (dfa->lex.maxrep < 0) addtok (dfa, PLUS); if (dfa->lex.minrep == 0) addtok (dfa, QMARK); int i; for (i = 1; i < dfa->lex.minrep; i++) { copytoks (dfa, tindex, ntokens); addtok (dfa, CAT); } for (; i < dfa->lex.maxrep; i++) { copytoks (dfa, tindex, ntokens); addtok (dfa, QMARK); addtok (dfa, CAT); } dfa->parse.tok = lex (dfa); } else if (dfa->parse.tok == REPMN) { dfa->tindex -= nsubtoks (dfa, dfa->tindex); dfa->parse.tok = lex (dfa); closure (dfa); } else { addtok (dfa, dfa->parse.tok); dfa->parse.tok = lex (dfa); } } static void branch (struct dfa* dfa) { closure (dfa); while (dfa->parse.tok != RPAREN && dfa->parse.tok != OR && dfa->parse.tok >= 0) { closure (dfa); addtok (dfa, CAT); } } static void regexp (struct dfa *dfa) { branch (dfa); while (dfa->parse.tok == OR) { dfa->parse.tok = lex (dfa); branch (dfa); addtok (dfa, OR); } } /* Main entry point for the parser. S is a string to be parsed, len is the length of the string, so s can include NUL characters. D is a pointer to the struct dfa to parse into. */ static void dfaparse (char const *s, size_t len, struct dfa *d) { d->lex.ptr = s; d->lex.left = len; d->lex.lasttok = END; d->lex.laststart = true; if (!d->syntax.syntax_bits_set) dfaerror (_("no syntax specified")); if (!d->nregexps) addtok (d, BEG); d->parse.tok = lex (d); d->parse.depth = d->depth; regexp (d); if (d->parse.tok != END) dfaerror (_("unbalanced )")); addtok (d, END - d->nregexps); addtok (d, CAT); if (d->nregexps) addtok (d, OR); ++d->nregexps; } /* Some primitives for operating on sets of positions. */ /* Copy one set to another. */ static void copy (position_set const *src, position_set *dst) { if (dst->alloc < src->nelem) { free (dst->elems); dst->elems = xpalloc (NULL, &dst->alloc, src->nelem - dst->alloc, -1, sizeof *dst->elems); } dst->nelem = src->nelem; if (src->nelem != 0) memcpy (dst->elems, src->elems, src->nelem * sizeof *dst->elems); } static void alloc_position_set (position_set *s, size_t size) { s->elems = xnmalloc (size, sizeof *s->elems); s->alloc = size; s->nelem = 0; } /* Insert position P in set S. S is maintained in sorted order on decreasing index. If there is already an entry in S with P.index then merge (logically-OR) P's constraints into the one in S. S->elems must point to an array large enough to hold the resulting set. */ static void insert (position p, position_set *s) { ptrdiff_t count = s->nelem; ptrdiff_t lo = 0, hi = count; while (lo < hi) { ptrdiff_t mid = (lo + hi) >> 1; if (s->elems[mid].index < p.index) lo = mid + 1; else if (s->elems[mid].index == p.index) { s->elems[mid].constraint |= p.constraint; return; } else hi = mid; } s->elems = maybe_realloc (s->elems, count, &s->alloc, -1, sizeof *s->elems); for (ptrdiff_t i = count; i > lo; i--) s->elems[i] = s->elems[i - 1]; s->elems[lo] = p; ++s->nelem; } static void append (position p, position_set *s) { ptrdiff_t count = s->nelem; s->elems = maybe_realloc (s->elems, count, &s->alloc, -1, sizeof *s->elems); s->elems[s->nelem++] = p; } /* Merge S1 and S2 (with the additional constraint C2) into M. The result is as if the positions of S1, and of S2 with the additional constraint C2, were inserted into an initially empty set. */ static void merge_constrained (position_set const *s1, position_set const *s2, unsigned int c2, position_set *m) { ptrdiff_t i = 0, j = 0; if (m->alloc - s1->nelem < s2->nelem) { free (m->elems); m->alloc = s1->nelem; m->elems = xpalloc (NULL, &m->alloc, s2->nelem, -1, sizeof *m->elems); } m->nelem = 0; while (i < s1->nelem || j < s2->nelem) if (! (j < s2->nelem) || (i < s1->nelem && s1->elems[i].index <= s2->elems[j].index)) { unsigned int c = ((i < s1->nelem && j < s2->nelem && s1->elems[i].index == s2->elems[j].index) ? s2->elems[j++].constraint & c2 : 0); m->elems[m->nelem].index = s1->elems[i].index; m->elems[m->nelem++].constraint = s1->elems[i++].constraint | c; } else { if (s2->elems[j].constraint & c2) { m->elems[m->nelem].index = s2->elems[j].index; m->elems[m->nelem++].constraint = s2->elems[j].constraint & c2; } j++; } } /* Merge two sets of positions into a third. The result is exactly as if the positions of both sets were inserted into an initially empty set. */ static void merge (position_set const *s1, position_set const *s2, position_set *m) { merge_constrained (s1, s2, -1, m); } static void merge2 (position_set *dst, position_set const *src, position_set *m) { if (src->nelem < 4) { for (ptrdiff_t i = 0; i < src->nelem; ++i) insert (src->elems[i], dst); } else { merge (src, dst, m); copy (m, dst); } } /* Delete a position from a set. Return the nonzero constraint of the deleted position, or zero if there was no such position. */ static unsigned int delete (size_t del, position_set *s) { size_t count = s->nelem; size_t lo = 0, hi = count; while (lo < hi) { size_t mid = (lo + hi) >> 1; if (s->elems[mid].index < del) lo = mid + 1; else if (s->elems[mid].index == del) { unsigned int c = s->elems[mid].constraint; size_t i; for (i = mid; i + 1 < count; i++) s->elems[i] = s->elems[i + 1]; s->nelem = i; return c; } else hi = mid; } return 0; } /* Replace a position with the followed set. */ static void replace (position_set *dst, size_t del, position_set *add, unsigned int constraint, position_set *tmp) { unsigned int c = delete (del, dst) & constraint; if (c) { copy (dst, tmp); merge_constrained (tmp, add, c, dst); } } /* Find the index of the state corresponding to the given position set with the given preceding context, or create a new state if there is no such state. Context tells whether we got here on a newline or letter. */ static state_num state_index (struct dfa *d, position_set const *s, int context) { size_t hash = 0; int constraint = 0; state_num i; token first_end = 0; for (i = 0; i < s->nelem; ++i) hash ^= s->elems[i].index + s->elems[i].constraint; /* Try to find a state that exactly matches the proposed one. */ for (i = 0; i < d->sindex; ++i) { if (hash != d->states[i].hash || s->nelem != d->states[i].elems.nelem || context != d->states[i].context) continue; state_num j; for (j = 0; j < s->nelem; ++j) if (s->elems[j].constraint != d->states[i].elems.elems[j].constraint || s->elems[j].index != d->states[i].elems.elems[j].index) break; if (j == s->nelem) return i; } #ifdef DEBUG fprintf (stderr, "new state %zd\n nextpos:", i); for (state_num j = 0; j < s->nelem; j++) { fprintf (stderr, " %zu:", s->elems[j].index); prtok (d->tokens[s->elems[j].index]); } fprintf (stderr, "\n context:"); if (context ^ CTX_ANY) { if (context & CTX_NONE) fprintf (stderr, " CTX_NONE"); if (context & CTX_LETTER) fprintf (stderr, " CTX_LETTER"); if (context & CTX_NEWLINE) fprintf (stderr, " CTX_NEWLINE"); } else fprintf (stderr, " CTX_ANY"); fprintf (stderr, "\n"); #endif for (state_num j = 0; j < s->nelem; j++) { int c = d->constraints[s->elems[j].index]; if (c != 0) { if (succeeds_in_context (c, context, CTX_ANY)) constraint |= c; if (!first_end) first_end = d->tokens[s->elems[j].index]; } else if (d->tokens[s->elems[j].index] == BACKREF) constraint = NO_CONSTRAINT; } /* Create a new state. */ d->states = maybe_realloc (d->states, d->sindex, &d->salloc, -1, sizeof *d->states); d->states[i].hash = hash; alloc_position_set (&d->states[i].elems, s->nelem); copy (s, &d->states[i].elems); d->states[i].context = context; d->states[i].constraint = constraint; d->states[i].first_end = first_end; d->states[i].mbps.nelem = 0; d->states[i].mbps.elems = NULL; d->states[i].mb_trindex = -1; ++d->sindex; return i; } /* Find the epsilon closure of a set of positions. If any position of the set contains a symbol that matches the empty string in some context, replace that position with the elements of its follow labeled with an appropriate constraint. Repeat exhaustively until no funny positions are left. S->elems must be large enough to hold the result. */ static void epsclosure (struct dfa const *d) { position_set tmp; alloc_position_set (&tmp, d->nleaves); for (size_t i = 0; i < d->tindex; ++i) if (d->follows[i].nelem > 0 && d->tokens[i] >= NOTCHAR && d->tokens[i] != BACKREF && d->tokens[i] != ANYCHAR && d->tokens[i] != MBCSET && d->tokens[i] < CSET) { unsigned int constraint; switch (d->tokens[i]) { case BEGLINE: constraint = BEGLINE_CONSTRAINT; break; case ENDLINE: constraint = ENDLINE_CONSTRAINT; break; case BEGWORD: constraint = BEGWORD_CONSTRAINT; break; case ENDWORD: constraint = ENDWORD_CONSTRAINT; break; case LIMWORD: constraint = LIMWORD_CONSTRAINT; break; case NOTLIMWORD: constraint = NOTLIMWORD_CONSTRAINT; break; default: constraint = NO_CONSTRAINT; break; } delete (i, &d->follows[i]); for (size_t j = 0; j < d->tindex; j++) if (i != j && d->follows[j].nelem > 0) replace (&d->follows[j], i, &d->follows[i], constraint, &tmp); } free (tmp.elems); } /* Returns the contexts on which the position set S depends. Each context in the set of returned contexts (let's call it SC) may have a different follow set than other contexts in SC, and also different from the follow set of the complement set (sc ^ CTX_ANY). However, all contexts in the complement set will have the same follow set. */ static int _GL_ATTRIBUTE_PURE state_separate_contexts (struct dfa *d, position_set const *s) { int separate_contexts = 0; for (size_t j = 0; j < s->nelem; j++) separate_contexts |= d->separates[s->elems[j].index]; return separate_contexts; } enum { /* Single token is repeated. It is distinguished from non-repeated. */ OPT_REPEAT = (1 << 0), /* Multiple tokens are repeated. This flag is on at head of tokens. The node is not merged. */ OPT_LPAREN = (1 << 1), /* Multiple branches are joined. The node is not merged. */ OPT_RPAREN = (1 << 2), /* The node is walked. If the node is found in walking again, OPT_RPAREN flag is turned on. */ OPT_WALKED = (1 << 3), /* The node is queued. The node is not queued again. */ OPT_QUEUED = (1 << 4) }; static void merge_nfa_state (struct dfa *d, size_t tindex, char *flags, position_set *merged) { position_set *follows = d->follows; ptrdiff_t nelem = 0; d->constraints[tindex] = 0; for (ptrdiff_t i = 0; i < follows[tindex].nelem; i++) { size_t sindex = follows[tindex].elems[i].index; /* Skip the node as pruned in future. */ unsigned int iconstraint = follows[tindex].elems[i].constraint; if (iconstraint == 0) continue; if (d->tokens[follows[tindex].elems[i].index] <= END) { d->constraints[tindex] |= follows[tindex].elems[i].constraint; continue; } if (!(flags[sindex] & (OPT_LPAREN | OPT_RPAREN))) { ptrdiff_t j; for (j = 0; j < nelem; j++) { size_t dindex = follows[tindex].elems[j].index; if (follows[tindex].elems[j].constraint != iconstraint) continue; if (flags[dindex] & (OPT_LPAREN | OPT_RPAREN)) continue; if (d->tokens[sindex] != d->tokens[dindex]) continue; if ((flags[sindex] ^ flags[dindex]) & OPT_REPEAT) continue; if (flags[sindex] & OPT_REPEAT) delete (sindex, &follows[sindex]); merge2 (&follows[dindex], &follows[sindex], merged); break; } if (j < nelem) continue; } follows[tindex].elems[nelem++] = follows[tindex].elems[i]; flags[sindex] |= OPT_QUEUED; } follows[tindex].nelem = nelem; } static int compare (const void *a, const void *b) { int aindex; int bindex; aindex = (int) ((position *) a)->index; bindex = (int) ((position *) b)->index; return aindex - bindex; } static void reorder_tokens (struct dfa *d) { ptrdiff_t nleaves; ptrdiff_t *map; token *tokens; position_set *follows; int *constraints; char *multibyte_prop; nleaves = 0; map = xnmalloc (d->tindex, sizeof *map); map[0] = nleaves++; for (ptrdiff_t i = 1; i < d->tindex; i++) map[i] = -1; tokens = xnmalloc (d->nleaves, sizeof *tokens); follows = xnmalloc (d->nleaves, sizeof *follows); constraints = xnmalloc (d->nleaves, sizeof *constraints); if (d->localeinfo.multibyte) multibyte_prop = xnmalloc (d->nleaves, sizeof *multibyte_prop); else multibyte_prop = NULL; for (ptrdiff_t i = 0; i < d->tindex; i++) { if (map[i] == -1) { free (d->follows[i].elems); d->follows[i].elems = NULL; d->follows[i].nelem = 0; continue; } tokens[map[i]] = d->tokens[i]; follows[map[i]] = d->follows[i]; constraints[map[i]] = d->constraints[i]; if (multibyte_prop != NULL) multibyte_prop[map[i]] = d->multibyte_prop[i]; for (ptrdiff_t j = 0; j < d->follows[i].nelem; j++) { if (map[d->follows[i].elems[j].index] == -1) map[d->follows[i].elems[j].index] = nleaves++; d->follows[i].elems[j].index = map[d->follows[i].elems[j].index]; } qsort (d->follows[i].elems, d->follows[i].nelem, sizeof *d->follows[i].elems, compare); } for (ptrdiff_t i = 0; i < nleaves; i++) { d->tokens[i] = tokens[i]; d->follows[i] = follows[i]; d->constraints[i] = constraints[i]; if (multibyte_prop != NULL) d->multibyte_prop[i] = multibyte_prop[i]; } d->tindex = d->nleaves = nleaves; free (tokens); free (follows); free (constraints); free (multibyte_prop); free (map); } static void dfaoptimize (struct dfa *d) { char *flags; position_set merged0; position_set *merged; flags = xmalloc (d->tindex * sizeof *flags); memset (flags, 0, d->tindex * sizeof *flags); for (size_t i = 0; i < d->tindex; i++) { for (ptrdiff_t j = 0; j < d->follows[i].nelem; j++) { if (d->follows[i].elems[j].index == i) flags[d->follows[i].elems[j].index] |= OPT_REPEAT; else if (d->follows[i].elems[j].index < i) flags[d->follows[i].elems[j].index] |= OPT_LPAREN; else if (flags[d->follows[i].elems[j].index] &= OPT_WALKED) flags[d->follows[i].elems[j].index] |= OPT_RPAREN; else flags[d->follows[i].elems[j].index] |= OPT_WALKED; } } flags[0] |= OPT_QUEUED; merged = &merged0; alloc_position_set (merged, d->nleaves); d->constraints = xnmalloc (d->tindex, sizeof *d->constraints); for (ptrdiff_t i = 0; i < d->tindex; i++) if (flags[i] & OPT_QUEUED) merge_nfa_state (d, i, flags, merged); reorder_tokens (d); free (merged->elems); free (flags); } /* Perform bottom-up analysis on the parse tree, computing various functions. Note that at this point, we're pretending constructs like \< are real characters rather than constraints on what can follow them. Nullable: A node is nullable if it is at the root of a regexp that can match the empty string. * EMPTY leaves are nullable. * No other leaf is nullable. * A QMARK or STAR node is nullable. * A PLUS node is nullable if its argument is nullable. * A CAT node is nullable if both its arguments are nullable. * An OR node is nullable if either argument is nullable. Firstpos: The firstpos of a node is the set of positions (nonempty leaves) that could correspond to the first character of a string matching the regexp rooted at the given node. * EMPTY leaves have empty firstpos. * The firstpos of a nonempty leaf is that leaf itself. * The firstpos of a QMARK, STAR, or PLUS node is the firstpos of its argument. * The firstpos of a CAT node is the firstpos of the left argument, union the firstpos of the right if the left argument is nullable. * The firstpos of an OR node is the union of firstpos of each argument. Lastpos: The lastpos of a node is the set of positions that could correspond to the last character of a string matching the regexp at the given node. * EMPTY leaves have empty lastpos. * The lastpos of a nonempty leaf is that leaf itself. * The lastpos of a QMARK, STAR, or PLUS node is the lastpos of its argument. * The lastpos of a CAT node is the lastpos of its right argument, union the lastpos of the left if the right argument is nullable. * The lastpos of an OR node is the union of the lastpos of each argument. Follow: The follow of a position is the set of positions that could correspond to the character following a character matching the node in a string matching the regexp. At this point we consider special symbols that match the empty string in some context to be just normal characters. Later, if we find that a special symbol is in a follow set, we will replace it with the elements of its follow, labeled with an appropriate constraint. * Every node in the firstpos of the argument of a STAR or PLUS node is in the follow of every node in the lastpos. * Every node in the firstpos of the second argument of a CAT node is in the follow of every node in the lastpos of the first argument. Because of the postfix representation of the parse tree, the depth-first analysis is conveniently done by a linear scan with the aid of a stack. Sets are stored as arrays of the elements, obeying a stack-like allocation scheme; the number of elements in each set deeper in the stack can be used to determine the address of a particular set's array. */ static void dfaanalyze (struct dfa *d, bool searchflag) { /* Array allocated to hold position sets. */ position *posalloc = xnmalloc (d->nleaves, 2 * sizeof *posalloc); /* Firstpos and lastpos elements. */ position *firstpos = posalloc; position *lastpos = firstpos + d->nleaves; position pos; position_set tmp; /* Stack for element counts and nullable flags. */ struct { /* Whether the entry is nullable. */ bool nullable; /* Counts of firstpos and lastpos sets. */ size_t nfirstpos; size_t nlastpos; } *stkalloc = xnmalloc (d->depth, sizeof *stkalloc), *stk = stkalloc; position_set merged; /* Result of merging sets. */ addtok (d, CAT); #ifdef DEBUG fprintf (stderr, "dfaanalyze:\n"); for (size_t i = 0; i < d->tindex; ++i) { fprintf (stderr, " %zu:", i); prtok (d->tokens[i]); } putc ('\n', stderr); #endif d->searchflag = searchflag; alloc_position_set (&merged, d->nleaves); d->follows = xcalloc (d->tindex, sizeof *d->follows); for (size_t i = 0; i < d->tindex; ++i) { switch (d->tokens[i]) { case EMPTY: /* The empty set is nullable. */ stk->nullable = true; /* The firstpos and lastpos of the empty leaf are both empty. */ stk->nfirstpos = stk->nlastpos = 0; stk++; break; case STAR: case PLUS: /* Every element in the firstpos of the argument is in the follow of every element in the lastpos. */ { tmp.elems = firstpos - stk[-1].nfirstpos; tmp.nelem = stk[-1].nfirstpos; position *pos = lastpos - stk[-1].nlastpos; for (size_t j = 0; j < stk[-1].nlastpos; j++) { merge (&tmp, &d->follows[pos[j].index], &merged); copy (&merged, &d->follows[pos[j].index]); } } FALLTHROUGH; case QMARK: /* A QMARK or STAR node is automatically nullable. */ if (d->tokens[i] != PLUS) stk[-1].nullable = true; break; case CAT: /* Every element in the firstpos of the second argument is in the follow of every element in the lastpos of the first argument. */ { tmp.nelem = stk[-1].nfirstpos; tmp.elems = firstpos - stk[-1].nfirstpos; position *pos = lastpos - stk[-1].nlastpos - stk[-2].nlastpos; for (size_t j = 0; j < stk[-2].nlastpos; j++) { merge (&tmp, &d->follows[pos[j].index], &merged); copy (&merged, &d->follows[pos[j].index]); } } /* The firstpos of a CAT node is the firstpos of the first argument, union that of the second argument if the first is nullable. */ if (stk[-2].nullable) stk[-2].nfirstpos += stk[-1].nfirstpos; else firstpos -= stk[-1].nfirstpos; /* The lastpos of a CAT node is the lastpos of the second argument, union that of the first argument if the second is nullable. */ if (stk[-1].nullable) stk[-2].nlastpos += stk[-1].nlastpos; else { position *pos = lastpos - stk[-1].nlastpos - stk[-2].nlastpos; for (size_t j = 0; j < stk[-1].nlastpos; j++) pos[j] = pos[j + stk[-2].nlastpos]; lastpos -= stk[-2].nlastpos; stk[-2].nlastpos = stk[-1].nlastpos; } /* A CAT node is nullable if both arguments are nullable. */ stk[-2].nullable &= stk[-1].nullable; stk--; break; case OR: /* The firstpos is the union of the firstpos of each argument. */ stk[-2].nfirstpos += stk[-1].nfirstpos; /* The lastpos is the union of the lastpos of each argument. */ stk[-2].nlastpos += stk[-1].nlastpos; /* An OR node is nullable if either argument is nullable. */ stk[-2].nullable |= stk[-1].nullable; stk--; break; default: /* Anything else is a nonempty position. (Note that special constructs like \< are treated as nonempty strings here; an "epsilon closure" effectively makes them nullable later. Backreferences have to get a real position so we can detect transitions on them later. But they are nullable. */ stk->nullable = d->tokens[i] == BACKREF; /* This position is in its own firstpos and lastpos. */ stk->nfirstpos = stk->nlastpos = 1; stk++; firstpos->index = lastpos->index = i; firstpos->constraint = lastpos->constraint = NO_CONSTRAINT; firstpos++, lastpos++; break; } #ifdef DEBUG /* ... balance the above nonsyntactic #ifdef goo... */ fprintf (stderr, "node %zu:", i); prtok (d->tokens[i]); putc ('\n', stderr); fprintf (stderr, stk[-1].nullable ? " nullable: yes\n" : " nullable: no\n"); fprintf (stderr, " firstpos:"); for (size_t j = 0; j < stk[-1].nfirstpos; j++) { fprintf (stderr, " %zu:", firstpos[j - stk[-1].nfirstpos].index); prtok (d->tokens[firstpos[j - stk[-1].nfirstpos].index]); } fprintf (stderr, "\n lastpos:"); for (size_t j = 0; j < stk[-1].nlastpos; j++) { fprintf (stderr, " %zu:", lastpos[j - stk[-1].nlastpos].index); prtok (d->tokens[lastpos[j - stk[-1].nlastpos].index]); } putc ('\n', stderr); #endif } /* For each follow set that is the follow set of a real position, replace it with its epsilon closure. */ epsclosure (d); dfaoptimize (d); #ifdef DEBUG for (size_t i = 0; i < d->tindex; ++i) if (d->tokens[i] == BEG || d->tokens[i] < NOTCHAR || d->tokens[i] == BACKREF || d->tokens[i] == ANYCHAR || d->tokens[i] == MBCSET || d->tokens[i] >= CSET) { fprintf (stderr, "follows(%zu:", i); prtok (d->tokens[i]); fprintf (stderr, "):"); for (size_t j = 0; j < d->follows[i].nelem; j++) { fprintf (stderr, " %zu:", d->follows[i].elems[j].index); prtok (d->tokens[d->follows[i].elems[j].index]); } putc ('\n', stderr); } #endif pos.index = 0; pos.constraint = NO_CONSTRAINT; alloc_position_set (&tmp, 1); append (pos, &tmp); d->separates = xnmalloc (d->tindex, sizeof *d->separates); for (ptrdiff_t i = 0; i < d->tindex; i++) { d->separates[i] = 0; if (prev_newline_dependent (d->constraints[i])) d->separates[i] |= CTX_NEWLINE; if (prev_letter_dependent (d->constraints[i])) d->separates[i] |= CTX_LETTER; for (ptrdiff_t j = 0; j < d->follows[i].nelem; j++) { if (prev_newline_dependent (d->follows[i].elems[j].constraint)) d->separates[i] |= CTX_NEWLINE; if (prev_letter_dependent (d->follows[i].elems[j].constraint)) d->separates[i] |= CTX_LETTER; } } /* Context wanted by some position. */ int separate_contexts = state_separate_contexts (d, &tmp); /* Build the initial state. */ if (separate_contexts & CTX_NEWLINE) state_index (d, &tmp, CTX_NEWLINE); d->initstate_notbol = d->min_trcount = state_index (d, &tmp, separate_contexts ^ CTX_ANY); if (separate_contexts & CTX_LETTER) d->min_trcount = state_index (d, &tmp, CTX_LETTER); d->min_trcount++; d->trcount = 0; free (posalloc); free (stkalloc); free (merged.elems); free (tmp.elems); } /* Make sure D's state arrays are large enough to hold NEW_STATE. */ static void realloc_trans_if_necessary (struct dfa *d) { state_num oldalloc = d->tralloc; if (oldalloc < d->sindex) { state_num **realtrans = d->trans ? d->trans - 2 : NULL; ptrdiff_t newalloc1 = realtrans ? d->tralloc + 2 : 0; realtrans = xpalloc (realtrans, &newalloc1, d->sindex - oldalloc, -1, sizeof *realtrans); realtrans[0] = realtrans[1] = NULL; d->trans = realtrans + 2; ptrdiff_t newalloc = d->tralloc = newalloc1 - 2; d->fails = xnrealloc (d->fails, newalloc, sizeof *d->fails); d->success = xnrealloc (d->success, newalloc, sizeof *d->success); d->newlines = xnrealloc (d->newlines, newalloc, sizeof *d->newlines); if (d->localeinfo.multibyte) { realtrans = d->mb_trans ? d->mb_trans - 2 : NULL; realtrans = xnrealloc (realtrans, newalloc1, sizeof *realtrans); if (oldalloc == 0) realtrans[0] = realtrans[1] = NULL; d->mb_trans = realtrans + 2; } for (; oldalloc < newalloc; oldalloc++) { d->trans[oldalloc] = NULL; d->fails[oldalloc] = NULL; if (d->localeinfo.multibyte) d->mb_trans[oldalloc] = NULL; } } } /* Calculate the transition table for a new state derived from state s for a compiled dfa d after input character uc, and return the new state number. Do not worry about all possible input characters; calculate just the group of positions that match uc. Label it with the set of characters that every position in the group matches (taking into account, if necessary, preceding context information of s). Then find the union of these positions' follows, i.e., the set of positions of the new state. For each character in the group's label, set the transition on this character to be to a state corresponding to the set's positions, and its associated backward context information, if necessary. When building a searching matcher, include the positions of state 0 in every state. The group is constructed by building an equivalence-class partition of the positions of s. For each position, find the set of characters C that it matches. Eliminate any characters from C that fail on grounds of backward context. Check whether the group's label L has nonempty intersection with C. If L - C is nonempty, create a new group labeled L - C and having the same positions as the current group, and set L to the intersection of L and C. Insert the position in the group, set C = C - L, and resume scanning. If after comparing with every group there are characters remaining in C, create a new group labeled with the characters of C and insert this position in that group. */ static state_num build_state (state_num s, struct dfa *d, unsigned char uc) { position_set follows; /* Union of the follows for each position of the current state. */ position_set group; /* Positions that match the input char. */ position_set tmp; /* Temporary space for merging sets. */ state_num state; /* New state. */ state_num state_newline; /* New state on a newline transition. */ state_num state_letter; /* New state on a letter transition. */ #ifdef DEBUG fprintf (stderr, "build state %td\n", s); #endif /* A pointer to the new transition table, and the table itself. */ state_num **ptrans = (accepting (s, d) ? d->fails : d->trans) + s; state_num *trans = *ptrans; if (!trans) { /* MAX_TRCOUNT is an arbitrary upper limit on the number of transition tables that can exist at once, other than for initial states. Often-used transition tables are quickly rebuilt, whereas rarely-used ones are cleared away. */ if (MAX_TRCOUNT <= d->trcount) { for (state_num i = d->min_trcount; i < d->tralloc; i++) { free (d->trans[i]); free (d->fails[i]); d->trans[i] = d->fails[i] = NULL; } d->trcount = 0; } d->trcount++; *ptrans = trans = xmalloc (NOTCHAR * sizeof *trans); /* Fill transition table with a default value which means that the transited state has not been calculated yet. */ for (int i = 0; i < NOTCHAR; i++) trans[i] = -2; } /* Set up the success bits for this state. */ d->success[s] = 0; if (accepts_in_context (d->states[s].context, CTX_NEWLINE, s, d)) d->success[s] |= CTX_NEWLINE; if (accepts_in_context (d->states[s].context, CTX_LETTER, s, d)) d->success[s] |= CTX_LETTER; if (accepts_in_context (d->states[s].context, CTX_NONE, s, d)) d->success[s] |= CTX_NONE; alloc_position_set (&follows, d->nleaves); /* Find the union of the follows of the positions of the group. This is a hideously inefficient loop. Fix it someday. */ for (size_t j = 0; j < d->states[s].elems.nelem; ++j) for (size_t k = 0; k < d->follows[d->states[s].elems.elems[j].index].nelem; ++k) insert (d->follows[d->states[s].elems.elems[j].index].elems[k], &follows); /* Positions that match the input char. */ alloc_position_set (&group, d->nleaves); /* The group's label. */ charclass label; fillset (&label); for (size_t i = 0; i < follows.nelem; ++i) { charclass matches; /* Set of matching characters. */ position pos = follows.elems[i]; bool matched = false; if (d->tokens[pos.index] >= 0 && d->tokens[pos.index] < NOTCHAR) { zeroset (&matches); setbit (d->tokens[pos.index], &matches); if (d->tokens[pos.index] == uc) matched = true; } else if (d->tokens[pos.index] >= CSET) { matches = d->charclasses[d->tokens[pos.index] - CSET]; if (tstbit (uc, &matches)) matched = true; } else if (d->tokens[pos.index] == ANYCHAR) { matches = d->charclasses[d->canychar]; if (tstbit (uc, &matches)) matched = true; /* ANYCHAR must match with a single character, so we must put it to D->states[s].mbps which contains the positions which can match with a single character not a byte. If all positions which has ANYCHAR does not depend on context of next character, we put the follows instead of it to D->states[s].mbps to optimize. */ if (succeeds_in_context (pos.constraint, d->states[s].context, CTX_NONE)) { if (d->states[s].mbps.nelem == 0) alloc_position_set (&d->states[s].mbps, 1); insert (pos, &d->states[s].mbps); } } else continue; /* Some characters may need to be eliminated from matches because they fail in the current context. */ if (pos.constraint != NO_CONSTRAINT) { if (!succeeds_in_context (pos.constraint, d->states[s].context, CTX_NEWLINE)) for (size_t j = 0; j < CHARCLASS_WORDS; ++j) matches.w[j] &= ~d->syntax.newline.w[j]; if (!succeeds_in_context (pos.constraint, d->states[s].context, CTX_LETTER)) for (size_t j = 0; j < CHARCLASS_WORDS; ++j) matches.w[j] &= ~d->syntax.letters.w[j]; if (!succeeds_in_context (pos.constraint, d->states[s].context, CTX_NONE)) for (size_t j = 0; j < CHARCLASS_WORDS; ++j) matches.w[j] &= d->syntax.letters.w[j] | d->syntax.newline.w[j]; /* If there are no characters left, there's no point in going on. */ if (emptyset (&matches)) continue; /* If we have reset the bit that made us declare "matched", reset that indicator, too. This is required to avoid an infinite loop with this command: echo cx | LC_ALL=C grep -E 'c\b[x ]' */ if (!tstbit (uc, &matches)) matched = false; } #ifdef DEBUG fprintf (stderr, " nextpos %zu:", pos.index); prtok (d->tokens[pos.index]); fprintf (stderr, " of"); for (size_t j = 0; j < NOTCHAR; j++) if (tstbit (j, &matches)) fprintf (stderr, " 0x%02zx", j); fprintf (stderr, "\n"); #endif if (matched) { for (size_t k = 0; k < CHARCLASS_WORDS; ++k) label.w[k] &= matches.w[k]; append (pos, &group); } else { for (size_t k = 0; k < CHARCLASS_WORDS; ++k) label.w[k] &= ~matches.w[k]; } } alloc_position_set (&tmp, d->nleaves); if (group.nelem > 0) { /* If we are building a searching matcher, throw in the positions of state 0 as well, if possible. */ if (d->searchflag) { /* If a token in follows.elems is not 1st byte of a multibyte character, or the states of follows must accept the bytes which are not 1st byte of the multibyte character. Then, if a state of follows encounters a byte, it must not be a 1st byte of a multibyte character nor a single byte character. In this case, do not add state[0].follows to next state, because state[0] must accept 1st-byte. For example, suppose is a certain single byte character, is a certain multibyte character, and the codepoint of equals the 2nd byte of the codepoint of . When state[0] accepts , state[i] transits to state[i+1] by accepting the 1st byte of , and state[i+1] accepts the 2nd byte of , if state[i+1] encounters the codepoint of , it must not be but the 2nd byte of , so do not add state[0]. */ bool mergeit = !d->localeinfo.multibyte; if (!mergeit) { mergeit = true; for (size_t j = 0; mergeit && j < group.nelem; j++) mergeit &= d->multibyte_prop[group.elems[j].index]; } if (mergeit) { merge (&d->states[0].elems, &group, &tmp); copy (&tmp, &group); } } /* Find out if the new state will want any context information, by calculating possible contexts that the group can match, and separate contexts that the new state wants to know. */ int separate_contexts = state_separate_contexts (d, &group); /* Find the state(s) corresponding to the union of the follows. */ if (d->syntax.sbit[uc] & separate_contexts & CTX_NEWLINE) state = state_index (d, &group, CTX_NEWLINE); else if (d->syntax.sbit[uc] & separate_contexts & CTX_LETTER) state = state_index (d, &group, CTX_LETTER); else state = state_index (d, &group, separate_contexts ^ CTX_ANY); state_newline = state; state_letter = state; /* Reallocate now, to reallocate any newline transition properly. */ realloc_trans_if_necessary (d); } /* If we are a searching matcher, the default transition is to a state containing the positions of state 0, otherwise the default transition is to fail miserably. */ else if (d->searchflag) { state_newline = 0; state_letter = d->min_trcount - 1; state = d->initstate_notbol; } else { state_newline = -1; state_letter = -1; state = -1; } /* Set the transitions for each character in the label. */ for (size_t i = 0; i < NOTCHAR; i++) if (tstbit (i, &label)) switch (d->syntax.sbit[i]) { case CTX_NEWLINE: trans[i] = state_newline; break; case CTX_LETTER: trans[i] = state_letter; break; default: trans[i] = state; break; } #ifdef DEBUG fprintf (stderr, "trans table %td", s); for (size_t i = 0; i < NOTCHAR; ++i) { if (!(i & 0xf)) fprintf (stderr, "\n"); fprintf (stderr, " %2td", trans[i]); } fprintf (stderr, "\n"); #endif free (group.elems); free (follows.elems); free (tmp.elems); /* Keep the newline transition in a special place so we can use it as a sentinel. */ if (tstbit (d->syntax.eolbyte, &label)) { d->newlines[s] = trans[d->syntax.eolbyte]; trans[d->syntax.eolbyte] = -1; } return trans[uc]; } /* Multibyte character handling sub-routines for dfaexec. */ /* Consume a single byte and transit state from 's' to '*next_state'. This function is almost same as the state transition routin in dfaexec. But state transition is done just once, otherwise matching succeed or reach the end of the buffer. */ static state_num transit_state_singlebyte (struct dfa *d, state_num s, unsigned char const **pp) { state_num *t; if (d->trans[s]) t = d->trans[s]; else if (d->fails[s]) t = d->fails[s]; else { build_state (s, d, **pp); if (d->trans[s]) t = d->trans[s]; else { t = d->fails[s]; assert (t); } } if (t[**pp] == -2) build_state (s, d, **pp); return t[*(*pp)++]; } /* Transit state from s, then return new state and update the pointer of the buffer. This function is for a period operator which can match a multi-byte character. */ static state_num transit_state (struct dfa *d, state_num s, unsigned char const **pp, unsigned char const *end) { wint_t wc; int mbclen = mbs_to_wchar (&wc, (char const *) *pp, end - *pp, d); /* This state has some operators which can match a multibyte character. */ d->mb_follows.nelem = 0; /* Calculate the state which can be reached from the state 's' by consuming 'mbclen' single bytes from the buffer. */ state_num s1 = s; int mbci; for (mbci = 0; mbci < mbclen && (mbci == 0 || d->min_trcount <= s); mbci++) s = transit_state_singlebyte (d, s, pp); *pp += mbclen - mbci; if (wc == WEOF) { /* It is an invalid character, so ANYCHAR is not accepted. */ return s; } /* If all positions which have ANYCHAR do not depend on the context of the next character, calculate the next state with pre-calculated follows and cache the result. */ if (d->states[s1].mb_trindex < 0) { if (MAX_TRCOUNT <= d->mb_trcount) { state_num s3; for (s3 = -1; s3 < d->tralloc; s3++) { free (d->mb_trans[s3]); d->mb_trans[s3] = NULL; } for (state_num i = 0; i < d->sindex; i++) d->states[i].mb_trindex = -1; d->mb_trcount = 0; } d->states[s1].mb_trindex = d->mb_trcount++; } if (! d->mb_trans[s]) { enum { TRANSPTR_SIZE = sizeof *d->mb_trans[s] }; enum { TRANSALLOC_SIZE = MAX_TRCOUNT * TRANSPTR_SIZE }; d->mb_trans[s] = xmalloc (TRANSALLOC_SIZE); for (int i = 0; i < MAX_TRCOUNT; i++) d->mb_trans[s][i] = -1; } else if (d->mb_trans[s][d->states[s1].mb_trindex] >= 0) return d->mb_trans[s][d->states[s1].mb_trindex]; if (s == -1) copy (&d->states[s1].mbps, &d->mb_follows); else merge (&d->states[s1].mbps, &d->states[s].elems, &d->mb_follows); int separate_contexts = state_separate_contexts (d, &d->mb_follows); state_num s2 = state_index (d, &d->mb_follows, separate_contexts ^ CTX_ANY); realloc_trans_if_necessary (d); d->mb_trans[s][d->states[s1].mb_trindex] = s2; return s2; } /* The initial state may encounter a byte which is not a single byte character nor the first byte of a multibyte character. But it is incorrect for the initial state to accept such a byte. For example, in Shift JIS the regular expression "\\" accepts the codepoint 0x5c, but should not accept the second byte of the codepoint 0x815c. Then the initial state must skip the bytes that are not a single byte character nor the first byte of a multibyte character. Given DFA state d, use mbs_to_wchar to advance MBP until it reaches or exceeds P, and return the advanced MBP. If WCP is non-NULL and the result is greater than P, set *WCP to the final wide character processed, or to WEOF if no wide character is processed. Otherwise, if WCP is non-NULL, *WCP may or may not be updated. Both P and MBP must be no larger than END. */ static unsigned char const * skip_remains_mb (struct dfa *d, unsigned char const *p, unsigned char const *mbp, char const *end) { if (d->syntax.never_trail[*p]) return p; while (mbp < p) { wint_t wc; mbp += mbs_to_wchar (&wc, (char const *) mbp, end - (char const *) mbp, d); } return mbp; } /* Search through a buffer looking for a match to the struct dfa *D. Find the first occurrence of a string matching the regexp in the buffer, and the shortest possible version thereof. Return a pointer to the first character after the match, or NULL if none is found. BEGIN points to the beginning of the buffer, and END points to the first byte after its end. Note however that we store a sentinel byte (usually newline) in *END, so the actual buffer must be one byte longer. When ALLOW_NL, newlines may appear in the matching string. If COUNT is non-NULL, increment *COUNT once for each newline processed. If MULTIBYTE, the input consists of multibyte characters and/or encoding-error bytes. Otherwise, it consists of single-byte characters. Here is the list of features that make this DFA matcher punt: - [M-N] range in non-simple locale: regex is up to 25% faster on [a-z] - [^...] in non-simple locale - [[=foo=]] or [[.foo.]] - [[:alpha:]] etc. in multibyte locale (except [[:digit:]] works OK) - back-reference: (.)\1 - word-delimiter in multibyte locale: \<, \>, \b, \B See using_simple_locale for the definition of "simple locale". */ static inline char * dfaexec_main (struct dfa *d, char const *begin, char *end, bool allow_nl, size_t *count, bool multibyte) { if (MAX_TRCOUNT <= d->sindex) { for (state_num s = d->min_trcount; s < d->sindex; s++) { free (d->states[s].elems.elems); free (d->states[s].mbps.elems); } d->sindex = d->min_trcount; if (d->trans) { for (state_num s = 0; s < d->tralloc; s++) { free (d->trans[s]); free (d->fails[s]); d->trans[s] = d->fails[s] = NULL; } d->trcount = 0; } if (d->localeinfo.multibyte && d->mb_trans) { for (state_num s = -1; s < d->tralloc; s++) { free (d->mb_trans[s]); d->mb_trans[s] = NULL; } for (state_num s = 0; s < d->min_trcount; s++) d->states[s].mb_trindex = -1; d->mb_trcount = 0; } } if (!d->tralloc) realloc_trans_if_necessary (d); /* Current state. */ state_num s = 0, s1 = 0; /* Current input character. */ unsigned char const *p = (unsigned char const *) begin; unsigned char const *mbp = p; /* Copy of d->trans so it can be optimized into a register. */ state_num **trans = d->trans; unsigned char eol = d->syntax.eolbyte; /* Likewise for eolbyte. */ unsigned char saved_end = *(unsigned char *) end; *end = eol; if (multibyte) { memset (&d->mbs, 0, sizeof d->mbs); if (d->mb_follows.alloc == 0) alloc_position_set (&d->mb_follows, d->nleaves); } size_t nlcount = 0; for (;;) { state_num *t; while ((t = trans[s]) != NULL) { if (s < d->min_trcount) { if (!multibyte || d->states[s].mbps.nelem == 0) { while (t[*p] == s) p++; } if (multibyte) p = mbp = skip_remains_mb (d, p, mbp, end); } if (multibyte) { s1 = s; if (d->states[s].mbps.nelem == 0 || d->localeinfo.sbctowc[*p] != WEOF || (char *) p >= end) { /* If an input character does not match ANYCHAR, do it like a single-byte character. */ s = t[*p++]; } else { s = transit_state (d, s, &p, (unsigned char *) end); mbp = p; trans = d->trans; } } else { s1 = t[*p++]; t = trans[s1]; if (! t) { state_num tmp = s; s = s1; s1 = tmp; /* swap */ break; } if (s < d->min_trcount) { while (t[*p] == s1) p++; } s = t[*p++]; } } if (s < 0) { if (s == -2) { s = build_state (s1, d, p[-1]); trans = d->trans; } else if ((char *) p <= end && p[-1] == eol && 0 <= d->newlines[s1]) { /* The previous character was a newline. Count it, and skip checking of multibyte character boundary until here. */ nlcount++; mbp = p; s = (allow_nl ? d->newlines[s1] : d->syntax.sbit[eol] == CTX_NEWLINE ? 0 : d->syntax.sbit[eol] == CTX_LETTER ? d->min_trcount - 1 : d->initstate_notbol); } else { p = NULL; goto done; } } else if (d->fails[s]) { if ((d->success[s] & d->syntax.sbit[*p]) || ((char *) p == end && accepts_in_context (d->states[s].context, CTX_NEWLINE, s, d))) goto done; if (multibyte && s < d->min_trcount) p = mbp = skip_remains_mb (d, p, mbp, end); s1 = s; if (!multibyte || d->states[s].mbps.nelem == 0 || d->localeinfo.sbctowc[*p] != WEOF || (char *) p >= end) { /* If a input character does not match ANYCHAR, do it like a single-byte character. */ s = d->fails[s][*p++]; } else { s = transit_state (d, s, &p, (unsigned char *) end); mbp = p; trans = d->trans; } } else { build_state (s, d, p[0]); trans = d->trans; } } done: if (count) *count += nlcount; *end = saved_end; return (char *) p; } /* Specialized versions of dfaexec for multibyte and single-byte cases. This is for performance, as dfaexec_main is an inline function. */ static char * dfaexec_mb (struct dfa *d, char const *begin, char *end, bool allow_nl, size_t *count, bool *backref) { return dfaexec_main (d, begin, end, allow_nl, count, true); } static char * dfaexec_sb (struct dfa *d, char const *begin, char *end, bool allow_nl, size_t *count, bool *backref) { return dfaexec_main (d, begin, end, allow_nl, count, false); } /* Always set *BACKREF and return BEGIN. Use this wrapper for any regexp that uses a construct not supported by this code. */ static char * dfaexec_noop (struct dfa *d, char const *begin, char *end, bool allow_nl, size_t *count, bool *backref) { *backref = true; return (char *) begin; } /* Like dfaexec_main (D, BEGIN, END, ALLOW_NL, COUNT, D->localeinfo.multibyte), but faster and set *BACKREF if the DFA code does not support this regexp usage. */ char * dfaexec (struct dfa *d, char const *begin, char *end, bool allow_nl, size_t *count, bool *backref) { return d->dfaexec (d, begin, end, allow_nl, count, backref); } struct dfa * dfasuperset (struct dfa const *d) { return d->superset; } bool dfaisfast (struct dfa const *d) { return d->fast; } static void free_mbdata (struct dfa *d) { free (d->multibyte_prop); free (d->lex.brack.chars); free (d->mb_follows.elems); if (d->mb_trans) { state_num s; for (s = -1; s < d->tralloc; s++) free (d->mb_trans[s]); free (d->mb_trans - 2); } } /* Return true if every construct in D is supported by this DFA matcher. */ static bool _GL_ATTRIBUTE_PURE dfa_supported (struct dfa const *d) { for (size_t i = 0; i < d->tindex; i++) { switch (d->tokens[i]) { case BEGWORD: case ENDWORD: case LIMWORD: case NOTLIMWORD: if (!d->localeinfo.multibyte) continue; FALLTHROUGH; case BACKREF: case MBCSET: return false; } } return true; } /* Disable use of the superset DFA if it is not likely to help performance. */ static void maybe_disable_superset_dfa (struct dfa *d) { if (!d->localeinfo.using_utf8) return; bool have_backref = false; for (size_t i = 0; i < d->tindex; ++i) { switch (d->tokens[i]) { case ANYCHAR: /* Lowered. */ abort (); case BACKREF: have_backref = true; break; case MBCSET: /* Requires multi-byte algorithm. */ return; default: break; } } if (!have_backref && d->superset) { /* The superset DFA is not likely to be much faster, so remove it. */ dfafree (d->superset); free (d->superset); d->superset = NULL; } free_mbdata (d); d->localeinfo.multibyte = false; d->dfaexec = dfaexec_sb; d->fast = true; } static void dfassbuild (struct dfa *d) { struct dfa *sup = dfaalloc (); *sup = *d; sup->localeinfo.multibyte = false; sup->dfaexec = dfaexec_sb; sup->multibyte_prop = NULL; sup->superset = NULL; sup->states = NULL; sup->sindex = 0; sup->constraints = NULL; sup->separates = NULL; sup->follows = NULL; sup->tralloc = 0; sup->trans = NULL; sup->fails = NULL; sup->success = NULL; sup->newlines = NULL; sup->charclasses = xnmalloc (sup->calloc, sizeof *sup->charclasses); if (d->cindex) { memcpy (sup->charclasses, d->charclasses, d->cindex * sizeof *sup->charclasses); } sup->tokens = xnmalloc (d->tindex, 2 * sizeof *sup->tokens); sup->talloc = d->tindex * 2; bool have_achar = false; bool have_nchar = false; size_t j; for (size_t i = j = 0; i < d->tindex; i++) { switch (d->tokens[i]) { case ANYCHAR: case MBCSET: case BACKREF: { charclass ccl; fillset (&ccl); sup->tokens[j++] = CSET + charclass_index (sup, &ccl); sup->tokens[j++] = STAR; if (d->tokens[i + 1] == QMARK || d->tokens[i + 1] == STAR || d->tokens[i + 1] == PLUS) i++; have_achar = true; } break; case BEGWORD: case ENDWORD: case LIMWORD: case NOTLIMWORD: if (d->localeinfo.multibyte) { /* These constraints aren't supported in a multibyte locale. Ignore them in the superset DFA. */ sup->tokens[j++] = EMPTY; break; } FALLTHROUGH; default: sup->tokens[j++] = d->tokens[i]; if ((0 <= d->tokens[i] && d->tokens[i] < NOTCHAR) || d->tokens[i] >= CSET) have_nchar = true; break; } } sup->tindex = j; if (have_nchar && (have_achar || d->localeinfo.multibyte)) d->superset = sup; else { dfafree (sup); free (sup); } } /* Parse and analyze a single string of the given length. */ void dfacomp (char const *s, size_t len, struct dfa *d, bool searchflag) { dfaparse (s, len, d); dfassbuild (d); if (dfa_supported (d)) { maybe_disable_superset_dfa (d); dfaanalyze (d, searchflag); } else { d->dfaexec = dfaexec_noop; } if (d->superset) { d->fast = true; dfaanalyze (d->superset, searchflag); } } /* Free the storage held by the components of a dfa. */ void dfafree (struct dfa *d) { free (d->charclasses); free (d->tokens); if (d->localeinfo.multibyte) free_mbdata (d); free (d->constraints); free (d->separates); for (size_t i = 0; i < d->sindex; ++i) { free (d->states[i].elems.elems); free (d->states[i].mbps.elems); } free (d->states); if (d->follows) { for (size_t i = 0; i < d->tindex; ++i) free (d->follows[i].elems); free (d->follows); } if (d->trans) { for (size_t i = 0; i < d->tralloc; ++i) { free (d->trans[i]); free (d->fails[i]); } free (d->trans - 2); free (d->fails); free (d->newlines); free (d->success); } if (d->superset) { dfafree (d->superset); free (d->superset); } } /* Having found the postfix representation of the regular expression, try to find a long sequence of characters that must appear in any line containing the r.e. Finding a "longest" sequence is beyond the scope here; we take an easy way out and hope for the best. (Take "(ab|a)b"--please.) We do a bottom-up calculation of sequences of characters that must appear in matches of r.e.'s represented by trees rooted at the nodes of the postfix representation: sequences that must appear at the left of the match ("left") sequences that must appear at the right of the match ("right") lists of sequences that must appear somewhere in the match ("in") sequences that must constitute the match ("is") When we get to the root of the tree, we use one of the longest of its calculated "in" sequences as our answer. The sequences calculated for the various types of node (in pseudo ANSI c) are shown below. "p" is the operand of unary operators (and the left-hand operand of binary operators); "q" is the right-hand operand of binary operators. "ZERO" means "a zero-length sequence" below. Type left right is in ---- ---- ----- -- -- char c # c # c # c # c ANYCHAR ZERO ZERO ZERO ZERO MBCSET ZERO ZERO ZERO ZERO CSET ZERO ZERO ZERO ZERO STAR ZERO ZERO ZERO ZERO QMARK ZERO ZERO ZERO ZERO PLUS p->left p->right ZERO p->in CAT (p->is==ZERO)? (q->is==ZERO)? (p->is!=ZERO && p->in plus p->left : q->right : q->is!=ZERO) ? q->in plus p->is##q->left p->right##q->is p->is##q->is : p->right##q->left ZERO OR longest common longest common (do p->is and substrings common leading trailing to q->is have same p->in and (sub)sequence (sub)sequence q->in length and content) ? of p->left of p->right and q->left and q->right p->is : NULL If there's anything else we recognize in the tree, all four sequences get set to zero-length sequences. If there's something we don't recognize in the tree, we just return a zero-length sequence. Break ties in favor of infrequent letters (choosing 'zzz' in preference to 'aaa')? And ... is it here or someplace that we might ponder "optimizations" such as egrep 'psi|epsilon' -> egrep 'psi' egrep 'pepsi|epsilon' -> egrep 'epsi' (Yes, we now find "epsi" as a "string that must occur", but we might also simplify the *entire* r.e. being sought) grep '[c]' -> grep 'c' grep '(ab|a)b' -> grep 'ab' grep 'ab*' -> grep 'a' grep 'a*b' -> grep 'b' There are several issues: Is optimization easy (enough)? Does optimization actually accomplish anything, or is the automaton you get from "psi|epsilon" (for example) the same as the one you get from "psi" (for example)? Are optimizable r.e.'s likely to be used in real-life situations (something like 'ab*' is probably unlikely; something like is 'psi|epsilon' is likelier)? */ static char * icatalloc (char *old, char const *new) { size_t newsize = strlen (new); if (newsize == 0) return old; size_t oldsize = strlen (old); char *result = xrealloc (old, oldsize + newsize + 1); memcpy (result + oldsize, new, newsize + 1); return result; } static void freelist (char **cpp) { while (*cpp) free (*cpp++); } static char ** enlist (char **cpp, char *new, size_t len) { new = memcpy (xmalloc (len + 1), new, len); new[len] = '\0'; /* Is there already something in the list that's new (or longer)? */ size_t i; for (i = 0; cpp[i] != NULL; ++i) if (strstr (cpp[i], new) != NULL) { free (new); return cpp; } /* Eliminate any obsoleted strings. */ for (size_t j = 0; cpp[j] != NULL; ) if (strstr (new, cpp[j]) == NULL) ++j; else { free (cpp[j]); if (--i == j) break; cpp[j] = cpp[i]; cpp[i] = NULL; } /* Add the new string. */ cpp = xnrealloc (cpp, i + 2, sizeof *cpp); cpp[i] = new; cpp[i + 1] = NULL; return cpp; } /* Given pointers to two strings, return a pointer to an allocated list of their distinct common substrings. */ static char ** comsubs (char *left, char const *right) { char **cpp = xzalloc (sizeof *cpp); for (char *lcp = left; *lcp != '\0'; lcp++) { size_t len = 0; char *rcp = strchr (right, *lcp); while (rcp != NULL) { size_t i; for (i = 1; lcp[i] != '\0' && lcp[i] == rcp[i]; ++i) continue; if (i > len) len = i; rcp = strchr (rcp + 1, *lcp); } if (len != 0) cpp = enlist (cpp, lcp, len); } return cpp; } static char ** addlists (char **old, char **new) { for (; *new; new++) old = enlist (old, *new, strlen (*new)); return old; } /* Given two lists of substrings, return a new list giving substrings common to both. */ static char ** inboth (char **left, char **right) { char **both = xzalloc (sizeof *both); for (size_t lnum = 0; left[lnum] != NULL; ++lnum) { for (size_t rnum = 0; right[rnum] != NULL; ++rnum) { char **temp = comsubs (left[lnum], right[rnum]); both = addlists (both, temp); freelist (temp); free (temp); } } return both; } typedef struct must must; struct must { char **in; char *left; char *right; char *is; bool begline; bool endline; must *prev; }; static must * allocmust (must *mp, size_t size) { must *new_mp = xmalloc (sizeof *new_mp); new_mp->in = xzalloc (sizeof *new_mp->in); new_mp->left = xzalloc (size); new_mp->right = xzalloc (size); new_mp->is = xzalloc (size); new_mp->begline = false; new_mp->endline = false; new_mp->prev = mp; return new_mp; } static void resetmust (must *mp) { freelist (mp->in); mp->in[0] = NULL; mp->left[0] = mp->right[0] = mp->is[0] = '\0'; mp->begline = false; mp->endline = false; } static void freemust (must *mp) { freelist (mp->in); free (mp->in); free (mp->left); free (mp->right); free (mp->is); free (mp); } struct dfamust * dfamust (struct dfa const *d) { must *mp = NULL; char const *result = ""; bool exact = false; bool begline = false; bool endline = false; bool need_begline = false; bool need_endline = false; bool case_fold_unibyte = d->syntax.case_fold && MB_CUR_MAX == 1; for (size_t ri = 1; ri + 1 < d->tindex; ri++) { token t = d->tokens[ri]; switch (t) { case BEGLINE: mp = allocmust (mp, 2); mp->begline = true; need_begline = true; break; case ENDLINE: mp = allocmust (mp, 2); mp->endline = true; need_endline = true; break; case LPAREN: case RPAREN: assert (!"neither LPAREN nor RPAREN may appear here"); case EMPTY: case BEGWORD: case ENDWORD: case LIMWORD: case NOTLIMWORD: case BACKREF: case ANYCHAR: case MBCSET: mp = allocmust (mp, 2); break; case STAR: case QMARK: resetmust (mp); break; case OR: { char **new; must *rmp = mp; must *lmp = mp = mp->prev; size_t j, ln, rn, n; /* Guaranteed to be. Unlikely, but ... */ if (streq (lmp->is, rmp->is)) { lmp->begline &= rmp->begline; lmp->endline &= rmp->endline; } else { lmp->is[0] = '\0'; lmp->begline = false; lmp->endline = false; } /* Left side--easy */ size_t i = 0; while (lmp->left[i] != '\0' && lmp->left[i] == rmp->left[i]) ++i; lmp->left[i] = '\0'; /* Right side */ ln = strlen (lmp->right); rn = strlen (rmp->right); n = ln; if (n > rn) n = rn; for (i = 0; i < n; ++i) if (lmp->right[ln - i - 1] != rmp->right[rn - i - 1]) break; for (j = 0; j < i; ++j) lmp->right[j] = lmp->right[(ln - i) + j]; lmp->right[j] = '\0'; new = inboth (lmp->in, rmp->in); freelist (lmp->in); free (lmp->in); lmp->in = new; freemust (rmp); } break; case PLUS: mp->is[0] = '\0'; break; case END: assert (!mp->prev); for (size_t i = 0; mp->in[i] != NULL; ++i) if (strlen (mp->in[i]) > strlen (result)) result = mp->in[i]; if (streq (result, mp->is)) { if ((!need_begline || mp->begline) && (!need_endline || mp->endline)) exact = true; begline = mp->begline; endline = mp->endline; } goto done; case CAT: { must *rmp = mp; must *lmp = mp = mp->prev; /* In. Everything in left, plus everything in right, plus concatenation of left's right and right's left. */ lmp->in = addlists (lmp->in, rmp->in); if (lmp->right[0] != '\0' && rmp->left[0] != '\0') { size_t lrlen = strlen (lmp->right); size_t rllen = strlen (rmp->left); char *tp = xmalloc (lrlen + rllen); memcpy (tp, lmp->right, lrlen); memcpy (tp + lrlen, rmp->left, rllen); lmp->in = enlist (lmp->in, tp, lrlen + rllen); free (tp); } /* Left-hand */ if (lmp->is[0] != '\0') lmp->left = icatalloc (lmp->left, rmp->left); /* Right-hand */ if (rmp->is[0] == '\0') lmp->right[0] = '\0'; lmp->right = icatalloc (lmp->right, rmp->right); /* Guaranteed to be */ if ((lmp->is[0] != '\0' || lmp->begline) && (rmp->is[0] != '\0' || rmp->endline)) { lmp->is = icatalloc (lmp->is, rmp->is); lmp->endline = rmp->endline; } else { lmp->is[0] = '\0'; lmp->begline = false; lmp->endline = false; } freemust (rmp); } break; case '\0': /* Not on *my* shift. */ goto done; default: if (CSET <= t) { /* If T is a singleton, or if case-folding in a unibyte locale and T's members all case-fold to the same char, convert T to one of its members. Otherwise, do nothing further with T. */ charclass *ccl = &d->charclasses[t - CSET]; int j; for (j = 0; j < NOTCHAR; j++) if (tstbit (j, ccl)) break; if (! (j < NOTCHAR)) { mp = allocmust (mp, 2); break; } t = j; while (++j < NOTCHAR) if (tstbit (j, ccl) && ! (case_fold_unibyte && toupper (j) == toupper (t))) break; if (j < NOTCHAR) { mp = allocmust (mp, 2); break; } } size_t rj = ri + 2; if (d->tokens[ri + 1] == CAT) { for (; rj < d->tindex - 1; rj += 2) { if ((rj != ri && (d->tokens[rj] <= 0 || NOTCHAR <= d->tokens[rj])) || d->tokens[rj + 1] != CAT) break; } } mp = allocmust (mp, ((rj - ri) >> 1) + 1); mp->is[0] = mp->left[0] = mp->right[0] = case_fold_unibyte ? toupper (t) : t; size_t i; for (i = 1; ri + 2 < rj; i++) { ri += 2; t = d->tokens[ri]; mp->is[i] = mp->left[i] = mp->right[i] = case_fold_unibyte ? toupper (t) : t; } mp->is[i] = mp->left[i] = mp->right[i] = '\0'; mp->in = enlist (mp->in, mp->is, i); break; } } done:; struct dfamust *dm = NULL; if (*result) { dm = xmalloc (sizeof *dm); dm->exact = exact; dm->begline = begline; dm->endline = endline; dm->must = xstrdup (result); } while (mp) { must *prev = mp->prev; freemust (mp); mp = prev; } return dm; } void dfamustfree (struct dfamust *dm) { free (dm->must); free (dm); } struct dfa * dfaalloc (void) { return xzalloc (sizeof (struct dfa)); } /* Initialize DFA. */ void dfasyntax (struct dfa *dfa, struct localeinfo const *linfo, reg_syntax_t bits, int dfaopts) { memset (dfa, 0, offsetof (struct dfa, dfaexec)); dfa->dfaexec = linfo->multibyte ? dfaexec_mb : dfaexec_sb; dfa->simple_locale = using_simple_locale (linfo->multibyte); dfa->localeinfo = *linfo; dfa->fast = !dfa->localeinfo.multibyte; dfa->canychar = -1; dfa->lex.cur_mb_len = 1; dfa->syntax.syntax_bits_set = true; dfa->syntax.case_fold = (bits & RE_ICASE) != 0; dfa->syntax.anchor = (dfaopts & DFA_ANCHOR) != 0; dfa->syntax.eolbyte = dfaopts & DFA_EOL_NUL ? '\0' : '\n'; dfa->syntax.syntax_bits = bits; for (int i = CHAR_MIN; i <= CHAR_MAX; ++i) { unsigned char uc = i; dfa->syntax.sbit[uc] = char_context (dfa, uc); switch (dfa->syntax.sbit[uc]) { case CTX_LETTER: setbit (uc, &dfa->syntax.letters); break; case CTX_NEWLINE: setbit (uc, &dfa->syntax.newline); break; } /* POSIX requires that the five bytes in "\n\r./" (including the terminating NUL) cannot occur inside a multibyte character. */ dfa->syntax.never_trail[uc] = (dfa->localeinfo.using_utf8 ? (uc & 0xc0) != 0x80 : strchr ("\n\r./", uc) != NULL); } } /* vim:set shiftwidth=2: */ 09' href='#n3709'>3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409
This is gawkinet.info, produced by makeinfo version 6.7 from
gawkinet.texi.

This is Edition 1.5 of 'TCP/IP Internetworking with 'gawk'', for the
5.1.0 (or later) version of the GNU implementation of AWK.


   Copyright (C) 2000, 2001, 2002, 2004, 2009, 2010, 2016, 2019, 2020
Free Software Foundation, Inc.


   Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with the
Invariant Sections being "GNU General Public License", the Front-Cover
texts being (a) (see below), and with the Back-Cover Texts being (b)
(see below).  A copy of the license is included in the section entitled
"GNU Free Documentation License".

  a. "A GNU Manual"

  b. "You have the freedom to copy and modify this GNU manual.  Buying
     copies from the FSF supports it in developing GNU and promoting
     software freedom."
INFO-DIR-SECTION Network applications
START-INFO-DIR-ENTRY
* awkinet: (gawkinet).          TCP/IP Internetworking With 'gawk'.
END-INFO-DIR-ENTRY


File: gawkinet.info,  Node: Top,  Next: Preface,  Prev: (dir),  Up: (dir)

General Introduction
********************

This file documents the networking features in GNU Awk ('gawk') version
4.0 and later.

   This is Edition 1.5 of 'TCP/IP Internetworking with 'gawk'', for the
5.1.0 (or later) version of the GNU implementation of AWK.


   Copyright (C) 2000, 2001, 2002, 2004, 2009, 2010, 2016, 2019, 2020
Free Software Foundation, Inc.


   Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with the
Invariant Sections being "GNU General Public License", the Front-Cover
texts being (a) (see below), and with the Back-Cover Texts being (b)
(see below).  A copy of the license is included in the section entitled
"GNU Free Documentation License".

  a. "A GNU Manual"

  b. "You have the freedom to copy and modify this GNU manual.  Buying
     copies from the FSF supports it in developing GNU and promoting
     software freedom."

* Menu:

* Preface::                          About this document.
* Introduction::                     About networking.
* Using Networking::                 Some examples.
* Some Applications and Techniques:: More extended examples.
* Links::                            Where to find the stuff mentioned in this
                                     document.
* GNU Free Documentation License::   The license for this document.
* Index::                            The index.

* Stream Communications::          Sending data streams.
* Datagram Communications::        Sending self-contained messages.
* The TCP/IP Protocols::           How these models work in the Internet.
* Basic Protocols::                The basic protocols.
* Ports::                          The idea behind ports.
* Making Connections::             Making TCP/IP connections.
* Gawk Special Files::             How to do 'gawk' networking.
* Special File Fields::            The fields in the special file name.
* Comparing Protocols::            Differences between the protocols.
* File /inet/tcp::                 The TCP special file.
* File /inet/udp::                 The UDP special file.
* TCP Connecting::                 Making a TCP connection.
* Troubleshooting::                Troubleshooting TCP/IP connections.
* Interacting::                    Interacting with a service.
* Setting Up::                     Setting up a service.
* Email::                          Reading email.
* Web page::                       Reading a Web page.
* Primitive Service::              A primitive Web service.
* Interacting Service::            A Web service with interaction.
* CGI Lib::                        A simple CGI library.
* Simple Server::                  A simple Web server.
* Caveats::                        Network programming caveats.
* Challenges::                     Where to go from here.
* PANIC::                          An Emergency Web Server.
* GETURL::                         Retrieving Web Pages.
* REMCONF::                        Remote Configuration Of Embedded Systems.
* URLCHK::                         Look For Changed Web Pages.
* WEBGRAB::                        Extract Links From A Page.
* STATIST::                        Graphing A Statistical Distribution.
* MAZE::                           Walking Through A Maze In Virtual Reality.
* MOBAGWHO::                       A Simple Mobile Agent.
* STOXPRED::                       Stock Market Prediction As A Service.
* PROTBASE::                       Searching Through A Protein Database.


File: gawkinet.info,  Node: Preface,  Next: Introduction,  Prev: Top,  Up: Top

Preface
*******

In May of 1997, Jürgen Kahrs felt the need for network access from
'awk', and, with a little help from me, set about adding features to do
this for 'gawk'.  At that time, he wrote the bulk of this Info file.

   The code and documentation were added to the 'gawk' 3.1 development
tree, and languished somewhat until I could finally get down to some
serious work on that version of 'gawk'.  This finally happened in the
middle of 2000.

   Meantime, Jürgen wrote an article about the Internet special files
and '|&' operator for 'Linux Journal', and made a networking patch for
the production versions of 'gawk' available from his home page.  In
August of 2000 (for 'gawk' 3.0.6), this patch also made it to the main
GNU 'ftp' distribution site.

   For release with 'gawk', I edited Jürgen's prose for English grammar
and style, as he is not a native English speaker.  I also rearranged the
material somewhat for what I felt was a better order of presentation,
and (re)wrote some of the introductory material.

   The majority of this document and the code are his work, and the high
quality and interesting ideas speak for themselves.  It is my hope that
these features will be of significant value to the 'awk' community.


Arnold Robbins
Nof Ayalon, ISRAEL
March, 2001


File: gawkinet.info,  Node: Introduction,  Next: Using Networking,  Prev: Preface,  Up: Top

1 Networking Concepts
*********************

This major node provides a (necessarily) brief introduction to computer
networking concepts.  For many applications of 'gawk' to TCP/IP
networking, we hope that this is enough.  For more advanced tasks, you
will need deeper background, and it may be necessary to switch to
lower-level programming in C or C++.

   There are two real-life models for the way computers send messages to
each other over a network.  While the analogies are not perfect, they
are close enough to convey the major concepts.  These two models are the
phone system (reliable byte-stream communications), and the postal
system (best-effort datagrams).

* Menu:

* Stream Communications::       Sending data streams.
* Datagram Communications::     Sending self-contained messages.
* The TCP/IP Protocols::        How these models work in the Internet.
* Making Connections::          Making TCP/IP connections.


File: gawkinet.info,  Node: Stream Communications,  Next: Datagram Communications,  Prev: Introduction,  Up: Introduction

1.1 Reliable Byte-streams (Phone Calls)
=======================================

When you make a phone call, the following steps occur:

  1. You dial a number.

  2. The phone system connects to the called party, telling them there
     is an incoming call.  (Their phone rings.)

  3. The other party answers the call, or, in the case of a computer
     network, refuses to answer the call.

  4. Assuming the other party answers, the connection between you is now
     a "duplex" (two-way), "reliable" (no data lost), sequenced (data
     comes out in the order sent) data stream.

  5. You and your friend may now talk freely, with the phone system
     moving the data (your voices) from one end to the other.  From your
     point of view, you have a direct end-to-end connection with the
     person on the other end.

   The same steps occur in a duplex reliable computer networking
connection.  There is considerably more overhead in setting up the
communications, but once it's done, data moves in both directions,
reliably, in sequence.


File: gawkinet.info,  Node: Datagram Communications,  Next: The TCP/IP Protocols,  Prev: Stream Communications,  Up: Introduction

1.2 Best-effort Datagrams (Mailed Letters)
==========================================

Suppose you mail three different documents to your office on the other
side of the country on two different days.  Doing so entails the
following.

  1. Each document travels in its own envelope.

  2. Each envelope contains both the sender and the recipient address.

  3. Each envelope may travel a different route to its destination.

  4. The envelopes may arrive in a different order from the one in which
     they were sent.

  5. One or more may get lost in the mail.  (Although, fortunately, this
     does not occur very often.)

  6. In a computer network, one or more "packets" may also arrive
     multiple times.  (This doesn't happen with the postal system!)

   The important characteristics of datagram communications, like those
of the postal system are thus:

   * Delivery is "best effort;" the data may never get there.

   * Each message is self-contained, including the source and
     destination addresses.

   * Delivery is _not_ sequenced; packets may arrive out of order,
     and/or multiple times.

   * Unlike the phone system, overhead is considerably lower.  It is not
     necessary to set up the call first.

   The price the user pays for the lower overhead of datagram
communications is exactly the lower reliability; it is often necessary
for user-level protocols that use datagram communications to add their
own reliability features on top of the basic communications.


File: gawkinet.info,  Node: The TCP/IP Protocols,  Next: Making Connections,  Prev: Datagram Communications,  Up: Introduction

1.3 The Internet Protocols
==========================

The Internet Protocol Suite (usually referred to as just TCP/IP)(1)
consists of a number of different protocols at different levels or
"layers."  For our purposes, three protocols provide the fundamental
communications mechanisms.  All other defined protocols are referred to
as user-level protocols (e.g., HTTP, used later in this Info file).

* Menu:

* Basic Protocols::             The basic protocols.
* Ports::                       The idea behind ports.

   ---------- Footnotes ----------

   (1) It should be noted that although the Internet seems to have
conquered the world, there are other networking protocol suites in
existence and in use.


File: gawkinet.info,  Node: Basic Protocols,  Next: Ports,  Prev: The TCP/IP Protocols,  Up: The TCP/IP Protocols

1.3.1 The Basic Internet Protocols
----------------------------------

IP
     The Internet Protocol.  This protocol is almost never used directly
     by applications.  It provides the basic packet delivery and routing
     infrastructure of the Internet.  Much like the phone company's
     switching centers or the Post Office's trucks, it is not of much
     day-to-day interest to the regular user (or programmer).  It
     happens to be a best effort datagram protocol.  In the early
     twenty-first century, there are two versions of this protocol in
     use:

     IPv4
          The original version of the Internet Protocol, with 32-bit
          addresses, on which most of the current Internet is based.

     IPv6
          The "next generation" of the Internet Protocol, with 128-bit
          addresses.  This protocol is in wide use in certain parts of
          the world, but has not yet replaced IPv4.(1)

     Versions of the other protocols that sit "atop" IP exist for both
     IPv4 and IPv6.  However, as the IPv6 versions are fundamentally the
     same as the original IPv4 versions, we will not distinguish further
     between them.

UDP
     The User Datagram Protocol.  This is a best effort datagram
     protocol.  It provides a small amount of extra reliability over IP,
     and adds the notion of "ports", described in *note TCP and UDP
     Ports: Ports.

TCP
     The Transmission Control Protocol.  This is a duplex, reliable,
     sequenced byte-stream protocol, again layered on top of IP, and
     also providing the notion of ports.  This is the protocol that you
     will most likely use when using 'gawk' for network programming.

   All other user-level protocols use either TCP or UDP to do their
basic communications.  Examples are SMTP (Simple Mail Transfer
Protocol), FTP (File Transfer Protocol), and HTTP (HyperText Transfer
Protocol).

   ---------- Footnotes ----------

   (1) There isn't an IPv5.


File: gawkinet.info,  Node: Ports,  Prev: Basic Protocols,  Up: The TCP/IP Protocols

1.3.2 TCP and UDP Ports
-----------------------

In the postal system, the address on an envelope indicates a physical
location, such as a residence or office building.  But there may be more
than one person at the location; thus you have to further quantify the
recipient by putting a person or company name on the envelope.

   In the phone system, one phone number may represent an entire
company, in which case you need a person's extension number in order to
reach that individual directly.  Or, when you call a home, you have to
say, "May I please speak to ..."  before talking to the person directly.

   IP networking provides the concept of addressing.  An IP address
represents a particular computer, but no more.  In order to reach the
mail service on a system, or the FTP or WWW service on a system, you
must have some way to further specify which service you want.  In the
Internet Protocol suite, this is done with "port numbers", which
represent the services, much like an extension number used with a phone
number.

   Port numbers are 16-bit integers.  Unix and Unix-like systems reserve
ports below 1024 for "well known" services, such as SMTP, FTP, and HTTP.
Numbers 1024 and above may be used by any application, although there is
no promise made that a particular port number is always available.


File: gawkinet.info,  Node: Making Connections,  Prev: The TCP/IP Protocols,  Up: Introduction

1.4 Making TCP/IP Connections (And Some Terminology)
====================================================

Two terms come up repeatedly when discussing networking: "client" and
"server".  For now, we'll discuss these terms at the "connection level",
when first establishing connections between two processes on different
systems over a network.  (Once the connection is established, the higher
level, or "application level" protocols, such as HTTP or FTP, determine
who is the client and who is the server.  Often, it turns out that the
client and server are the same in both roles.)

   The "server" is the system providing the service, such as the web
server or email server.  It is the "host" (system) which is _connected
to_ in a transaction.  For this to work though, the server must be
expecting connections.  Much as there has to be someone at the office
building to answer the phone(1), the server process (usually) has to be
started first and be waiting for a connection.

   The "client" is the system requesting the service.  It is the system
_initiating the connection_ in a transaction.  (Just as when you pick up
the phone to call an office or store.)

   In the TCP/IP framework, each end of a connection is represented by a
pair of (ADDRESS, PORT) pairs.  For the duration of the connection, the
ports in use at each end are unique, and cannot be used simultaneously
by other processes on the same system.  (Only after closing a connection
can a new one be built up on the same port.  This is contrary to the
usual behavior of fully developed web servers which have to avoid
situations in which they are not reachable.  We have to pay this price
in order to enjoy the benefits of a simple communication paradigm in
'gawk'.)

   Furthermore, once the connection is established, communications are
"synchronous".(2)  I.e., each end waits on the other to finish
transmitting, before replying.  This is much like two people in a phone
conversation.  While both could talk simultaneously, doing so usually
doesn't work too well.

   In the case of TCP, the synchronicity is enforced by the protocol
when sending data.  Data writes "block" until the data have been
received on the other end.  For both TCP and UDP, data reads block until
there is incoming data waiting to be read.  This is summarized in the
following table, where an "X" indicates that the given action blocks.

TCP        X       X
UDP        X

   ---------- Footnotes ----------

   (1) In the days before voice mail systems!

   (2) For the technically savvy, data reads block--if there's no
incoming data, the program is made to wait until there is, instead of
receiving a "there's no data" error return.


File: gawkinet.info,  Node: Using Networking,  Next: Some Applications and Techniques,  Prev: Introduction,  Up: Top

2 Networking With 'gawk'
************************

The 'awk' programming language was originally developed as a
pattern-matching language for writing short programs to perform data
manipulation tasks.  'awk''s strength is the manipulation of textual
data that is stored in files.  It was never meant to be used for
networking purposes.  To exploit its features in a networking context,
it's necessary to use an access mode for network connections that
resembles the access of files as closely as possible.

   'awk' is also meant to be a prototyping language.  It is used to
demonstrate feasibility and to play with features and user interfaces.
This can be done with file-like handling of network connections.  'gawk'
trades the lack of many of the advanced features of the TCP/IP family of
protocols for the convenience of simple connection handling.  The
advanced features are available when programming in C or Perl.  In fact,
the network programming in this major node is very similar to what is
described in books such as 'Internet Programming with Python', 'Advanced
Perl Programming', or 'Web Client Programming with Perl'.

   However, you can do the programming here without first having to
learn object-oriented ideology; underlying languages such as Tcl/Tk,
Perl, Python; or all of the libraries necessary to extend these
languages before they are ready for the Internet.

   This major node demonstrates how to use the TCP protocol.  The UDP
protocol is much less important for most users.

* Menu:

* Gawk Special Files::          How to do 'gawk' networking.
* TCP Connecting::              Making a TCP connection.
* Troubleshooting::             Troubleshooting TCP/IP connections.
* Interacting::                 Interacting with a service.
* Setting Up::                  Setting up a service.
* Email::                       Reading email.
* Web page::                    Reading a Web page.
* Primitive Service::           A primitive Web service.
* Interacting Service::         A Web service with interaction.
* Simple Server::               A simple Web server.
* Caveats::                     Network programming caveats.
* Challenges::                  Where to go from here.


File: gawkinet.info,  Node: Gawk Special Files,  Next: TCP Connecting,  Prev: Using Networking,  Up: Using Networking

2.1 'gawk''s Networking Mechanisms
==================================

The '|&' operator for use in communicating with a "coprocess" is
described in *note Two-way Communications With Another Process:
(gawk)Two-way I/O. It shows how to do two-way I/O to a separate process,
sending it data with 'print' or 'printf' and reading data with
'getline'.  If you haven't read it already, you should detour there to
do so.

   'gawk' transparently extends the two-way I/O mechanism to simple
networking through the use of special file names.  When a "coprocess"
that matches the special files we are about to describe is started,
'gawk' creates the appropriate network connection, and then two-way I/O
proceeds as usual.

   At the C, C++, and Perl level, networking is accomplished via
"sockets", an Application Programming Interface (API) originally
developed at the University of California at Berkeley that is now used
almost universally for TCP/IP networking.  Socket level programming,
while fairly straightforward, requires paying attention to a number of
details, as well as using binary data.  It is not well-suited for use
from a high-level language like 'awk'.  The special files provided in
'gawk' hide the details from the programmer, making things much simpler
and easier to use.

   The special file name for network access is made up of several
fields, all of which are mandatory:

     /NET-TYPE/PROTOCOL/LOCALPORT/HOSTNAME/REMOTEPORT

   The NET-TYPE field lets you specify IPv4 versus IPv6, or lets you
allow the system to choose.

* Menu:

* Special File Fields::         The fields in the special file name.
* Comparing Protocols::         Differences between the protocols.


File: gawkinet.info,  Node: Special File Fields,  Next: Comparing Protocols,  Prev: Gawk Special Files,  Up: Gawk Special Files

2.1.1 The Fields of the Special File Name
-----------------------------------------

This node explains the meaning of all the other fields, as well as the
range of values and the defaults.  All of the fields are mandatory.  To
let the system pick a value, or if the field doesn't apply to the
protocol, specify it as '0':

NET-TYPE
     This is one of 'inet4' for IPv4, 'inet6' for IPv6, or 'inet' to use
     the system default (which is likely to be IPv4).  For the rest of
     this document, we will use the generic '/inet' in our descriptions
     of how 'gawk''s networking works.

PROTOCOL
     Determines which member of the TCP/IP family of protocols is
     selected to transport the data across the network.  There are two
     possible values (always written in lowercase): 'tcp' and 'udp'.
     The exact meaning of each is explained later in this node.

LOCALPORT
     Determines which port on the local machine is used to communicate
     across the network.  Application-level clients usually use '0' to
     indicate they do not care which local port is used--instead they
     specify a remote port to connect to.  It is vital for
     application-level servers to use a number different from '0' here
     because their service has to be available at a specific publicly
     known port number.  It is possible to use a name from
     '/etc/services' here.

HOSTNAME
     Determines which remote host is to be at the other end of the
     connection.  Application-level servers must fill this field with a
     '0' to indicate their being open for all other hosts to connect to
     them and enforce connection level server behavior this way.  It is
     not possible for an application-level server to restrict its
     availability to one remote host by entering a host name here.
     Application-level clients must enter a name different from '0'.
     The name can be either symbolic (e.g., 'jpl-devvax.jpl.nasa.gov')
     or numeric (e.g., '128.149.1.143').

REMOTEPORT
     Determines which port on the remote machine is used to communicate
     across the network.  For '/inet/tcp' and '/inet/udp',
     application-level clients _must_ use a number other than '0' to
     indicate to which port on the remote machine they want to connect.
     Application-level servers must not fill this field with a '0'.
     Instead they specify a local port to which clients connect.  It is
     possible to use a name from '/etc/services' here.

   Experts in network programming will notice that the usual
client/server asymmetry found at the level of the socket API is not
visible here.  This is for the sake of simplicity of the high-level
concept.  If this asymmetry is necessary for your application, use
another language.  For 'gawk', it is more important to enable users to
write a client program with a minimum of code.  What happens when first
accessing a network connection is seen in the following pseudocode:

     if ((name of remote host given) && (other side accepts connection)) {
       rendez-vous successful; transmit with getline or print
     } else {
       if ((other side did not accept) && (localport == 0))
         exit unsuccessful
       if (TCP) {
         set up a server accepting connections
         this means waiting for the client on the other side to connect
       } else
         ready
     }

   The exact behavior of this algorithm depends on the values of the
fields of the special file name.  When in doubt, *note Table 2.1:
table-inet-components. gives you the combinations of values and their
meaning.  If this table is too complicated, focus on the three lines
printed in *bold*.  All the examples in *note Networking With 'gawk':
Using Networking, use only the patterns printed in bold letters.

PROTOCOL    LOCAL       HOST NAME   REMOTE      RESULTING CONNECTION-LEVEL
            PORT                    PORT        BEHAVIOR
------------------------------------------------------------------------------
*tcp*       *0*         *x*         *x*         *Dedicated client, fails if
                                                immediately connecting to a
                                                server on the other side
                                                fails*
udp         0           x           x           Dedicated client
*tcp,       *x*         *x*         *x*         *Client, switches to
udp*                                            dedicated server if
                                                necessary*
*tcp,       *x*         *0*         *0*         *Dedicated server*
udp*
tcp, udp    x           x           0           Invalid
tcp, udp    0           0           x           Invalid
tcp, udp    x           0           x           Invalid
tcp, udp    0           0           0           Invalid
tcp, udp    0           x           0           Invalid

Table 2.1: '/inet' Special File Components

   In general, TCP is the preferred mechanism to use.  It is the
simplest protocol to understand and to use.  Use UDP only if
circumstances demand low-overhead.


File: gawkinet.info,  Node: Comparing Protocols,  Prev: Special File Fields,  Up: Gawk Special Files

2.1.2 Comparing Protocols
-------------------------

This node develops a pair of programs (sender and receiver) that do
nothing but send a timestamp from one machine to another.  The sender
and the receiver are implemented with each of the two protocols
available and demonstrate the differences between them.

* Menu:

* File /inet/tcp::              The TCP special file.
* File /inet/udp::              The UDP special file.


File: gawkinet.info,  Node: File /inet/tcp,  Next: File /inet/udp,  Prev: Comparing Protocols,  Up: Comparing Protocols

2.1.2.1 '/inet/tcp'
...................

Once again, always use TCP. (Use UDP when low overhead is a necessity.)
The first example is the sender program:

     # Server
     BEGIN {
       print strftime() |& "/inet/tcp/8888/0/0"
       close("/inet/tcp/8888/0/0")
     }

   The receiver is very simple:

     # Client
     BEGIN {
       "/inet/tcp/0/localhost/8888" |& getline
       print $0
       close("/inet/tcp/0/localhost/8888")
     }

   TCP guarantees that the bytes arrive at the receiving end in exactly
the same order that they were sent.  No byte is lost (except for broken
connections), doubled, or out of order.  Some overhead is necessary to
accomplish this, but this is the price to pay for a reliable service.
It does matter which side starts first.  The sender/server has to be
started first, and it waits for the receiver to read a line.


File: gawkinet.info,  Node: File /inet/udp,  Prev: File /inet/tcp,  Up: Comparing Protocols

2.1.2.2 '/inet/udp'
...................

The server and client programs that use UDP are almost identical to
their TCP counterparts; only the PROTOCOL has changed.  As before, it
does matter which side starts first.  The receiving side blocks and
waits for the sender.  In this case, the receiver/client has to be
started first:

     # Server
     BEGIN {
       print strftime() |& "/inet/udp/8888/0/0"
       close("/inet/udp/8888/0/0")
     }

   The receiver is almost identical to the TCP receiver:

     # Client
     BEGIN {
       print "hi!" |& "/inet/udp/0/localhost/8888"
       "/inet/udp/0/localhost/8888" |& getline
       print $0
       close("/inet/udp/0/localhost/8888")
     }

   In the case of UDP, the initial 'print' command is the one that
actually sends data so that there is a connection.  UDP and "connection"
sounds strange to anyone who has learned that UDP is a connectionless
protocol.  Here, "connection" means that the 'connect()' system call has
completed its work and completed the "association" between a certain
socket and an IP address.  Thus there are subtle differences between
'connect()' for TCP and UDP; see the man page for details.(1)

   UDP cannot guarantee that the datagrams at the receiving end will
arrive in exactly the same order they were sent.  Some datagrams could
be lost, some doubled, and some out of order.  But no overhead is
necessary to accomplish this.  This unreliable behavior is good enough
for tasks such as data acquisition, logging, and even stateless services
like the original versions of NFS.

   ---------- Footnotes ----------

   (1) This subtlety is just one of many details that are hidden in the
socket API, invisible and intractable for the 'gawk' user.  The
developers are currently considering how to rework the network
facilities to make them easier to understand and use.


File: gawkinet.info,  Node: TCP Connecting,  Next: Troubleshooting,  Prev: Gawk Special Files,  Up: Using Networking

2.2 Establishing a TCP Connection
=================================

Let's observe a network connection at work.  Type in the following
program and watch the output.  Within a second, it connects via TCP
('/inet/tcp') to the machine it is running on ('localhost') and asks the
service 'daytime' on the machine what time it is:

     BEGIN {
       "/inet/tcp/0/localhost/daytime" |& getline
       print $0
       close("/inet/tcp/0/localhost/daytime")
     }

   Even experienced 'awk' users will find the second line strange in two
respects:

   * A special file is used as a shell command that pipes its output
     into 'getline'.  One would rather expect to see the special file
     being read like any other file ('getline <
     "/inet/tcp/0/localhost/daytime")'.

   * The operator '|&' has not been part of any 'awk' implementation
     (until now).  It is actually the only extension of the 'awk'
     language needed (apart from the special files) to introduce network
     access.

   The '|&' operator was introduced in 'gawk' 3.1 in order to overcome
the crucial restriction that access to files and pipes in 'awk' is
always unidirectional.  It was formerly impossible to use both access
modes on the same file or pipe.  Instead of changing the whole concept
of file access, the '|&' operator behaves exactly like the usual pipe
operator except for two additions:

   * Normal shell commands connected to their 'gawk' program with a '|&'
     pipe can be accessed bidirectionally.  The '|&' turns out to be a
     quite general, useful, and natural extension of 'awk'.

   * Pipes that consist of a special file name for network connections
     are not executed as shell commands.  Instead, they can be read and
     written to, just like a full-duplex network connection.

   In the earlier example, the '|&' operator tells 'getline' to read a
line from the special file '/inet/tcp/0/localhost/daytime'.  We could
also have printed a line into the special file.  But instead we just
read a line with the time, printed it, and closed the connection.
(While we could just let 'gawk' close the connection by finishing the
program, in this Info file we are pedantic and always explicitly close
the connections.)


File: gawkinet.info,  Node: Troubleshooting,  Next: Interacting,  Prev: TCP Connecting,  Up: Using Networking

2.3 Troubleshooting Connection Problems
=======================================

It may well be that for some reason the program shown in the previous
example does not run on your machine.  When looking at possible reasons
for this, you will learn much about typical problems that arise in
network programming.  First of all, your implementation of 'gawk' may
not support network access because it is a pre-3.1 version or you do not
have a network interface in your machine.  Perhaps your machine uses
some other protocol, such as DECnet or Novell's IPX. For the rest of
this major node, we will assume you work on a Unix machine that supports
TCP/IP. If the previous example program does not run on your machine, it
may help to replace the name 'localhost' with the name of your machine
or its IP address.  If it does, you could replace 'localhost' with the
name of another machine in your vicinity--this way, the program connects
to another machine.  Now you should see the date and time being printed
by the program, otherwise your machine may not support the 'daytime'
service.  Try changing the service to 'chargen' or 'ftp'.  This way, the
program connects to other services that should give you some response.
If you are curious, you should have a look at your '/etc/services' file.
It could look like this:

     # /etc/services:
     #
     # Network services, Internet style
     #
     # Name     Number/Protocol  Alternate name # Comments

     echo        7/tcp
     echo        7/udp
     discard     9/tcp         sink null
     discard     9/udp         sink null
     daytime     13/tcp
     daytime     13/udp
     chargen     19/tcp        ttytst source
     chargen     19/udp        ttytst source
     ftp         21/tcp
     telnet      23/tcp
     smtp        25/tcp        mail
     finger      79/tcp
     www         80/tcp        http      # WorldWideWeb HTTP
     www         80/udp        # HyperText Transfer Protocol
     pop-2       109/tcp       postoffice    # POP version 2
     pop-2       109/udp
     pop-3       110/tcp       # POP version 3
     pop-3       110/udp
     nntp        119/tcp       readnews untp  # USENET News
     irc         194/tcp       # Internet Relay Chat
     irc         194/udp
     ...

   Here, you find a list of services that traditional Unix machines
usually support.  If your GNU/Linux machine does not do so, it may be
that these services are switched off in some startup script.  Systems
running some flavor of Microsoft Windows usually do _not_ support these
services.  Nevertheless, it _is_ possible to do networking with 'gawk'
on Microsoft Windows.(1)  The first column of the file gives the name of
the service, and the second column gives a unique number and the
protocol that one can use to connect to this service.  The rest of the
line is treated as a comment.  You see that some services ('echo')
support TCP as well as UDP.

   ---------- Footnotes ----------

   (1) Microsoft preferred to ignore the TCP/IP family of protocols
until 1995.  Then came the rise of the Netscape browser as a landmark
"killer application."  Microsoft added TCP/IP support and their own
browser to Microsoft Windows 95 at the last minute.  They even
back-ported their TCP/IP implementation to Microsoft Windows for
Workgroups 3.11, but it was a rather rudimentary and half-hearted
implementation.  Nevertheless, the equivalent of '/etc/services' resides
under 'C:\WINNT\system32\drivers\etc\services' on Microsoft Windows 2000
and Microsoft Windows XP.


File: gawkinet.info,  Node: Interacting,  Next: Setting Up,  Prev: Troubleshooting,  Up: Using Networking

2.4 Interacting with a Network Service
======================================

The next program makes use of the possibility to really interact with a
network service by printing something into the special file.  It asks
the so-called 'finger' service if a user of the machine is logged in.
When testing this program, try to change 'localhost' to some other
machine name in your local network:

     BEGIN {
       NetService = "/inet/tcp/0/localhost/finger"
       print "NAME" |& NetService
       while ((NetService |& getline) > 0)
         print $0
       close(NetService)
     }

   After telling the service on the machine which user to look for, the
program repeatedly reads lines that come as a reply.  When no more lines
are coming (because the service has closed the connection), the program
also closes the connection.  Try replacing '"NAME"' with your login name
(or the name of someone else logged in).  For a list of all users
currently logged in, replace NAME with an empty string ('""').

   The final 'close()' command could be safely deleted from the above
script, because the operating system closes any open connection by
default when a script reaches the end of execution.  In order to avoid
portability problems, it is best to always close connections explicitly.
With the Linux kernel, for example, proper closing results in flushing
of buffers.  Letting the close happen by default may result in
discarding buffers.

   When looking at '/etc/services' you may have noticed that the
'daytime' service is also available with 'udp'.  In the earlier example,
change 'tcp' to 'udp', and change 'finger' to 'daytime'.  After starting
the modified program, you see the expected day and time message.  The
program then hangs, because it waits for more lines coming from the
service.  However, they never come.  This behavior is a consequence of
the differences between TCP and UDP. When using UDP, neither party is
automatically informed about the other closing the connection.
Continuing to experiment this way reveals many other subtle differences
between TCP and UDP. To avoid such trouble, one should always remember
the advice Douglas E. Comer and David Stevens give in Volume III of
their series 'Internetworking With TCP' (page 14):

     When designing client-server applications, beginners are strongly
     advised to use TCP because it provides reliable,
     connection-oriented communication.  Programs only use UDP if the
     application protocol handles reliability, the application requires
     hardware broadcast or multicast, or the application cannot tolerate
     virtual circuit overhead.


File: gawkinet.info,  Node: Setting Up,  Next: Email,  Prev: Interacting,  Up: Using Networking

2.5 Setting Up a Service
========================

The preceding programs behaved as clients that connect to a server
somewhere on the Internet and request a particular service.  Now we set
up such a service to mimic the behavior of the 'daytime' service.  Such
a server does not know in advance who is going to connect to it over the
network.  Therefore, we cannot insert a name for the host to connect to
in our special file name.

   Start the following program in one window.  Notice that the service
does not have the name 'daytime', but the number '8888'.  From looking
at '/etc/services', you know that names like 'daytime' are just
mnemonics for predetermined 16-bit integers.  Only the system
administrator ('root') could enter our new service into '/etc/services'
with an appropriate name.  Also notice that the service name has to be
entered into a different field of the special file name because we are
setting up a server, not a client:

     BEGIN {
       print strftime() |& "/inet/tcp/8888/0/0"
       close("/inet/tcp/8888/0/0")
     }

   Now open another window on the same machine.  Copy the client program
given as the first example (*note Establishing a TCP Connection: TCP
Connecting.) to a new file and edit it, changing the name 'daytime' to
'8888'.  Then start the modified client.  You should get a reply like
this:

     Sat Sep 27 19:08:16 CEST 1997

Both programs explicitly close the connection.

   Now we will intentionally make a mistake to see what happens when the
name '8888' (the so-called port) is already used by another service.
Start the server program in both windows.  The first one works, but the
second one complains that it could not open the connection.  Each port
on a single machine can only be used by one server program at a time.
Now terminate the server program and change the name '8888' to 'echo'.
After restarting it, the server program does not run any more, and you
know why: there is already an 'echo' service running on your machine.
But even if this isn't true, you would not get your own 'echo' server
running on a Unix machine, because the ports with numbers smaller than
1024 ('echo' is at port 7) are reserved for 'root'.  On machines running
some flavor of Microsoft Windows, there is no restriction that reserves
ports 1 to 1024 for a privileged user; hence, you can start an 'echo'
server there.

   Turning this short server program into something really useful is
simple.  Imagine a server that first reads a file name from the client
through the network connection, then does something with the file and
sends a result back to the client.  The server-side processing could be:

     BEGIN {
       NetService = "/inet/tcp/8888/0/0"
       NetService |& getline
       CatPipe    = ("cat " $1)    # sets $0 and the fields
       while ((CatPipe | getline) > 0)
         print $0 |& NetService
       close(NetService)
     }

and we would have a remote copying facility.  Such a server reads the
name of a file from any client that connects to it and transmits the
contents of the named file across the net.  The server-side processing
could also be the execution of a command that is transmitted across the
network.  From this example, you can see how simple it is to open up a
security hole on your machine.  If you allow clients to connect to your
machine and execute arbitrary commands, anyone would be free to do 'rm
-rf *'.


File: gawkinet.info,  Node: Email,  Next: Web page,  Prev: Setting Up,  Up: Using Networking

2.6 Reading Email
=================

The distribution of email is usually done by dedicated email servers
that communicate with your machine using special protocols.  To receive
email, we will use the Post Office Protocol (POP). Sending can be done
with the much older Simple Mail Transfer Protocol (SMTP).

   When you type in the following program, replace the EMAILHOST by the
name of your local email server.  Ask your administrator if the server
has a POP service, and then use its name or number in the program below.
Now the program is ready to connect to your email server, but it will
not succeed in retrieving your mail because it does not yet know your
login name or password.  Replace them in the program and it shows you
the first email the server has in store:

     BEGIN {
       POPService  = "/inet/tcp/0/EMAILHOST/pop3"
       RS = ORS = "\r\n"
       print "user NAME"            |& POPService
       POPService                    |& getline
       print "pass PASSWORD"         |& POPService
       POPService                    |& getline
       print "retr 1"                |& POPService
       POPService                    |& getline
       if ($1 != "+OK") exit
       print "quit"                  |& POPService
       RS = "\r\n\\.\r\n"
       POPService |& getline
       print $0
       close(POPService)
     }

   The record separators 'RS' and 'ORS' are redefined because the
protocol (POP) requires CR-LF to separate lines.  After identifying
yourself to the email service, the command 'retr 1' instructs the
service to send the first of all your email messages in line.  If the
service replies with something other than '+OK', the program exits;
maybe there is no email.  Otherwise, the program first announces that it
intends to finish reading email, and then redefines 'RS' in order to
read the entire email as multiline input in one record.  From the POP
RFC, we know that the body of the email always ends with a single line
containing a single dot.  The program looks for this using 'RS =
"\r\n\\.\r\n"'.  When it finds this sequence in the mail message, it
quits.  You can invoke this program as often as you like; it does not
delete the message it reads, but instead leaves it on the server.


File: gawkinet.info,  Node: Web page,  Next: Primitive Service,  Prev: Email,  Up: Using Networking

2.7 Reading a Web Page
======================

Retrieving a web page from a web server is as simple as retrieving email
from an email server.  We only have to use a similar, but not identical,
protocol and a different port.  The name of the protocol is HyperText
Transfer Protocol (HTTP) and the port number is usually 80.  As in the
preceding node, ask your administrator about the name of your local web
server or proxy web server and its port number for HTTP requests.

   The following program employs a rather crude approach toward
retrieving a web page.  It uses the prehistoric syntax of HTTP 0.9,
which almost all web servers still support.  The most noticeable thing
about it is that the program directs the request to the local proxy
server whose name you insert in the special file name (which in turn
calls 'www.yahoo.com'):

     BEGIN {
       RS = ORS = "\r\n"
       HttpService = "/inet/tcp/0/PROXY/80"
       print "GET http://www.yahoo.com"     |& HttpService
       while ((HttpService |& getline) > 0)
          print $0
       close(HttpService)
     }

   Again, lines are separated by a redefined 'RS' and 'ORS'.  The 'GET'
request that we send to the server is the only kind of HTTP request that
existed when the web was created in the early 1990s.  HTTP calls this
'GET' request a "method," which tells the service to transmit a web page
(here the home page of the Yahoo!  search engine).  Version 1.0 added
the request methods 'HEAD' and 'POST'.  The current version of HTTP is
1.1,(1) and knows the additional request methods 'OPTIONS', 'PUT',
'DELETE', and 'TRACE'.  You can fill in any valid web address, and the
program prints the HTML code of that page to your screen.

   Notice the similarity between the responses of the POP and HTTP
services.  First, you get a header that is terminated by an empty line,
and then you get the body of the page in HTML. The lines of the headers
also have the same form as in POP. There is the name of a parameter,
then a colon, and finally the value of that parameter.

   Images ('.png' or '.gif' files) can also be retrieved this way, but
then you get binary data that should be redirected into a file.  Another
application is calling a CGI (Common Gateway Interface) script on some
server.  CGI scripts are used when the contents of a web page are not
constant, but generated instantly at the moment you send a request for
the page.  For example, to get a detailed report about the current
quotes of Motorola stock shares, call a CGI script at Yahoo!  with the
following:

     get = "GET http://quote.yahoo.com/q?s=MOT&d=t"
     print get |& HttpService

   You can also request weather reports this way.

   ---------- Footnotes ----------

   (1) Version 1.0 of HTTP was defined in RFC 1945.  HTTP 1.1 was
initially specified in RFC 2068.  In June 1999, RFC 2068 was made
obsolete by RFC 2616, an update without any substantial changes.


File: gawkinet.info,  Node: Primitive Service,  Next: Interacting Service,  Prev: Web page,  Up: Using Networking

2.8 A Primitive Web Service
===========================

Now we know enough about HTTP to set up a primitive web service that
just says '"Hello, world"' when someone connects to it with a browser.
Compared to the situation in the preceding node, our program changes the
role.  It tries to behave just like the server we have observed.  Since
we are setting up a server here, we have to insert the port number in
the 'localport' field of the special file name.  The other two fields
(HOSTNAME and REMOTEPORT) have to contain a '0' because we do not know
in advance which host will connect to our service.

   In the early 1990s, all a server had to do was send an HTML document
and close the connection.  Here, we adhere to the modern syntax of HTTP.
The steps are as follows:

  1. Send a status line telling the web browser that everything is okay.

  2. Send a line to tell the browser how many bytes follow in the body
     of the message.  This was not necessary earlier because both
     parties knew that the document ended when the connection closed.
     Nowadays it is possible to stay connected after the transmission of
     one web page.  This is to avoid the network traffic necessary for
     repeatedly establishing TCP connections for requesting several
     images.  Thus, there is the need to tell the receiving party how
     many bytes will be sent.  The header is terminated as usual with an
     empty line.

  3. Send the '"Hello, world"' body in HTML. The useless 'while' loop
     swallows the request of the browser.  We could actually omit the
     loop, and on most machines the program would still work.  First,
     start the following program:

     BEGIN {
       RS = ORS = "\r\n"
       HttpService = "/inet/tcp/8080/0/0"
       Hello = "<HTML><HEAD>" \
               "<TITLE>A Famous Greeting</TITLE></HEAD>" \
               "<BODY><H1>Hello, world</H1></BODY></HTML>"
       Len = length(Hello) + length(ORS)
       print "HTTP/1.0 200 OK"          |& HttpService
       print "Content-Length: " Len ORS |& HttpService
       print Hello                      |& HttpService
       while ((HttpService |& getline) > 0)
          continue;
       close(HttpService)
     }

   Now, on the same machine, start your favorite browser and let it
point to <http://localhost:8080> (the browser needs to know on which
port our server is listening for requests).  If this does not work, the
browser probably tries to connect to a proxy server that does not know
your machine.  If so, change the browser's configuration so that the
browser does not try to use a proxy to connect to your machine.


File: gawkinet.info,  Node: Interacting Service,  Next: Simple Server,  Prev: Primitive Service,  Up: Using Networking

2.9 A Web Service with Interaction
==================================

This node shows how to set up a simple web server.  The subnode is a
library file that we will use with all the examples in *note Some
Applications and Techniques::.

* Menu:

* CGI Lib::                     A simple CGI library.

   Setting up a web service that allows user interaction is more
difficult and shows us the limits of network access in 'gawk'.  In this
node, we develop a main program (a 'BEGIN' pattern and its action) that
will become the core of event-driven execution controlled by a graphical
user interface (GUI). Each HTTP event that the user triggers by some
action within the browser is received in this central procedure.
Parameters and menu choices are extracted from this request, and an
appropriate measure is taken according to the user's choice.  For
example:

     BEGIN {
       if (MyHost == "") {
          "uname -n" | getline MyHost
          close("uname -n")
       }
       if (MyPort ==  0) MyPort = 8080
       HttpService = "/inet/tcp/" MyPort "/0/0"
       MyPrefix    = "http://" MyHost ":" MyPort
       SetUpServer()
       while ("awk" != "complex") {
         # header lines are terminated this way
         RS = ORS = "\r\n"
         Status   = 200          # this means OK
         Reason   = "OK"
         Header   = TopHeader
         Document = TopDoc
         Footer   = TopFooter
         if        (GETARG["Method"] == "GET") {
             HandleGET()
         } else if (GETARG["Method"] == "HEAD") {
             # not yet implemented
         } else if (GETARG["Method"] != "") {
             print "bad method", GETARG["Method"]
         }
         Prompt = Header Document Footer
         print "HTTP/1.0", Status, Reason       |& HttpService
         print "Connection: Close"              |& HttpService
         print "Pragma: no-cache"               |& HttpService
         len = length(Prompt) + length(ORS)
         print "Content-length:", len           |& HttpService
         print ORS Prompt                       |& HttpService
         # ignore all the header lines
         while ((HttpService |& getline) > 0)
             ;
         # stop talking to this client
         close(HttpService)
         # wait for new client request
         HttpService |& getline
         # do some logging
         print systime(), strftime(), $0
         # read request parameters
         CGI_setup($1, $2, $3)
       }
     }

   This web server presents menu choices in the form of HTML links.
Therefore, it has to tell the browser the name of the host it is
residing on.  When starting the server, the user may supply the name of
the host from the command line with 'gawk -v MyHost="Rumpelstilzchen"'.
If the user does not do this, the server looks up the name of the host
it is running on for later use as a web address in HTML documents.  The
same applies to the port number.  These values are inserted later into
the HTML content of the web pages to refer to the home system.

   Each server that is built around this core has to initialize some
application-dependent variables (such as the default home page) in a
procedure 'SetUpServer()', which is called immediately before entering
the infinite loop of the server.  For now, we will write an instance
that initiates a trivial interaction.  With this home page, the client
user can click on two possible choices, and receive the current date
either in human-readable format or in seconds since 1970:

     function SetUpServer() {
       TopHeader = "<HTML><HEAD>"
       TopHeader = TopHeader \
          "<title>My name is GAWK, GNU AWK</title></HEAD>"
       TopDoc    = "<BODY><h2>\
         Do you prefer your date <A HREF=" MyPrefix \
         "/human>human</A> or \
         <A HREF=" MyPrefix "/POSIX>POSIXed</A>?</h2>" ORS ORS
       TopFooter = "</BODY></HTML>"
     }

   On the first run through the main loop, the default line terminators
are set and the default home page is copied to the actual home page.
Since this is the first run, 'GETARG["Method"]' is not initialized yet,
hence the case selection over the method does nothing.  Now that the
home page is initialized, the server can start communicating to a client
browser.

   It does so by printing the HTTP header into the network connection
('print ... |& HttpService').  This command blocks execution of the
server script until a client connects.  If this server script is
compared with the primitive one we wrote before, you will notice two
additional lines in the header.  The first instructs the browser to
close the connection after each request.  The second tells the browser
that it should never try to _remember_ earlier requests that had
identical web addresses (no caching).  Otherwise, it could happen that
the browser retrieves the time of day in the previous example just once,
and later it takes the web page from the cache, always displaying the
same time of day although time advances each second.

   Having supplied the initial home page to the browser with a valid
document stored in the parameter 'Prompt', it closes the connection and
waits for the next request.  When the request comes, a log line is
printed that allows us to see which request the server receives.  The
final step in the loop is to call the function 'CGI_setup()', which
reads all the lines of the request (coming from the browser), processes
them, and stores the transmitted parameters in the array 'PARAM'.  The
complete text of these application-independent functions can be found in
*note A Simple CGI Library: CGI Lib.  For now, we use a simplified
version of 'CGI_setup()':

     function CGI_setup(   method, uri, version, i) {
       delete GETARG;         delete MENU;        delete PARAM
       GETARG["Method"] = $1
       GETARG["URI"] = $2
       GETARG["Version"] = $3
       i = index($2, "?")
       # is there a "?" indicating a CGI request?
       if (i > 0) {
         split(substr($2, 1, i-1), MENU, "[/:]")
         split(substr($2, i+1), PARAM, "&")
         for (i in PARAM) {
           j = index(PARAM[i], "=")
           GETARG[substr(PARAM[i], 1, j-1)] = \
                                       substr(PARAM[i], j+1)
         }
       } else {    # there is no "?", no need for splitting PARAMs
         split($2, MENU, "[/:]")
       }
     }

   At first, the function clears all variables used for global storage
of request parameters.  The rest of the function serves the purpose of
filling the global parameters with the extracted new values.  To
accomplish this, the name of the requested resource is split into parts
and stored for later evaluation.  If the request contains a '?', then
the request has CGI variables seamlessly appended to the web address.
Everything in front of the '?' is split up into menu items, and
everything behind the '?' is a list of 'VARIABLE=VALUE' pairs (separated
by '&') that also need splitting.  This way, CGI variables are isolated
and stored.  This procedure lacks recognition of special characters that
are transmitted in coded form(1).  Here, any optional request header and
body parts are ignored.  We do not need header parameters and the
request body.  However, when refining our approach or working with the
'POST' and 'PUT' methods, reading the header and body becomes
inevitable.  Header parameters should then be stored in a global array
as well as the body.

   On each subsequent run through the main loop, one request from a
browser is received, evaluated, and answered according to the user's
choice.  This can be done by letting the value of the HTTP method guide
the main loop into execution of the procedure 'HandleGET()', which
evaluates the user's choice.  In this case, we have only one
hierarchical level of menus, but in the general case, menus are nested.
The menu choices at each level are separated by '/', just as in file
names.  Notice how simple it is to construct menus of arbitrary depth:

     function HandleGET() {
       if (       MENU[2] == "human") {
         Footer = strftime() TopFooter
       } else if (MENU[2] == "POSIX") {
         Footer = systime()  TopFooter
       }
     }

   The disadvantage of this approach is that our server is slow and can
handle only one request at a time.  Its main advantage, however, is that
the server consists of just one 'gawk' program.  No need for installing
an 'httpd', and no need for static separate HTML files, CGI scripts, or
'root' privileges.  This is rapid prototyping.  This program can be
started on the same host that runs your browser.  Then let your browser
point to <http://localhost:8080>.

   It is also possible to include images into the HTML pages.  Most
browsers support the not very well-known '.xbm' format, which may
contain only monochrome pictures but is an ASCII format.  Binary images
are possible but not so easy to handle.  Another way of including images
is to generate them with a tool such as GNUPlot, by calling the tool
with the 'system()' function or through a pipe.

   ---------- Footnotes ----------

   (1) As defined in RFC 2068.


File: gawkinet.info,  Node: CGI Lib,  Prev: Interacting Service,  Up: Interacting Service

2.9.1 A Simple CGI Library
--------------------------

     HTTP is like being married: you have to be able to handle whatever
     you're given, while being very careful what you send back.
     Phil Smith III,
     <http://www.netfunny.com/rhf/jokes/99/Mar/http.html>

   In *note A Web Service with Interaction: Interacting Service, we saw
the function 'CGI_setup()' as part of the web server "core logic"
framework.  The code presented there handles almost everything necessary
for CGI requests.  One thing it doesn't do is handle encoded characters
in the requests.  For example, an '&' is encoded as a percent sign
followed by the hexadecimal value: '%26'.  These encoded values should
be decoded.  Following is a simple library to perform these tasks.  This
code is used for all web server examples used throughout the rest of
this Info file.  If you want to use it for your own web server, store
the source code into a file named 'inetlib.awk'.  Then you can include
these functions into your code by placing the following statement into
your program (on the first line of your script):

     @include inetlib.awk

But beware, this mechanism is only possible if you invoke your web
server script with 'igawk' instead of the usual 'awk' or 'gawk'.  Here
is the code:

     # CGI Library and core of a web server
     # Global arrays
     #   GETARG --- arguments to CGI GET command
     #   MENU   --- menu items (path names)
     #   PARAM  --- parameters of form x=y

     # Optional variable MyHost contains host address
     # Optional variable MyPort contains port number
     # Needs TopHeader, TopDoc, TopFooter
     # Sets MyPrefix, HttpService, Status, Reason

     BEGIN {
       if (MyHost == "") {
          "uname -n" | getline MyHost
          close("uname -n")
       }
       if (MyPort ==  0) MyPort = 8080
       HttpService = "/inet/tcp/" MyPort "/0/0"
       MyPrefix    = "http://" MyHost ":" MyPort
       SetUpServer()
       while ("awk" != "complex") {
         # header lines are terminated this way
         RS = ORS    = "\r\n"
         Status      = 200             # this means OK
         Reason      = "OK"
         Header      = TopHeader
         Document    = TopDoc
         Footer      = TopFooter
         if        (GETARG["Method"] == "GET") {
             HandleGET()
         } else if (GETARG["Method"] == "HEAD") {
             # not yet implemented
         } else if (GETARG["Method"] != "") {
             print "bad method", GETARG["Method"]
         }
         Prompt = Header Document Footer
         print "HTTP/1.0", Status, Reason     |& HttpService
         print "Connection: Close"            |& HttpService
         print "Pragma: no-cache"             |& HttpService
         len = length(Prompt) + length(ORS)
         print "Content-length:", len         |& HttpService
         print ORS Prompt                     |& HttpService
         # ignore all the header lines
         while ((HttpService |& getline) > 0)
             continue
         # stop talking to this client
         close(HttpService)
         # wait for new client request
         HttpService |& getline
         # do some logging
         print systime(), strftime(), $0
         CGI_setup($1, $2, $3)
       }
     }

     function CGI_setup(   method, uri, version, i)
     {
         delete GETARG
         delete MENU
         delete PARAM
         GETARG["Method"] = method
         GETARG["URI"] = uri
         GETARG["Version"] = version

         i = index(uri, "?")
         if (i > 0) {  # is there a "?" indicating a CGI request?
             split(substr(uri, 1, i-1), MENU, "[/:]")
             split(substr(uri, i+1), PARAM, "&")
             for (i in PARAM) {
                 PARAM[i] = _CGI_decode(PARAM[i])
                 j = index(PARAM[i], "=")
                 GETARG[substr(PARAM[i], 1, j-1)] = \
                                              substr(PARAM[i], j+1)
             }
         } else { # there is no "?", no need for splitting PARAMs
             split(uri, MENU, "[/:]")
         }
         for (i in MENU)     # decode characters in path
             if (i > 4)      # but not those in host name
                 MENU[i] = _CGI_decode(MENU[i])
     }

   This isolates details in a single function, 'CGI_setup()'.  Decoding
of encoded characters is pushed off to a helper function,
'_CGI_decode()'.  The use of the leading underscore ('_') in the
function name is intended to indicate that it is an "internal" function,
although there is nothing to enforce this:

     function _CGI_decode(str,   hexdigs, i, pre, code1, code2,
                                 val, result)
     {
        hexdigs = "123456789abcdef"

        i = index(str, "%")
        if (i == 0) # no work to do
           return str

        do {
           pre = substr(str, 1, i-1)   # part before %xx
           code1 = substr(str, i+1, 1) # first hex digit
           code2 = substr(str, i+2, 1) # second hex digit
           str = substr(str, i+3)      # rest of string

           code1 = tolower(code1)
           code2 = tolower(code2)
           val = index(hexdigs, code1) * 16 \
                 + index(hexdigs, code2)

           result = result pre sprintf("%c", val)
           i = index(str, "%")
        } while (i != 0)
        if (length(str) > 0)
           result = result str
        return result
     }

   This works by splitting the string apart around an encoded character.
The two digits are converted to lowercase characters and looked up in a
string of hex digits.  Note that '0' is not in the string on purpose;
'index()' returns zero when it's not found, automatically giving the
correct value!  Once the hexadecimal value is converted from characters
in a string into a numerical value, 'sprintf()' converts the value back
into a real character.  The following is a simple test harness for the
above functions:

     BEGIN {
       CGI_setup("GET",
       "http://www.gnu.org/cgi-bin/foo?p1=stuff&p2=stuff%26junk" \
            "&percent=a %25 sign",
       "1.0")
       for (i in MENU)
           printf "MENU[\"%s\"] = %s\n", i, MENU[i]
       for (i in PARAM)
           printf "PARAM[\"%s\"] = %s\n", i, PARAM[i]
       for (i in GETARG)
           printf "GETARG[\"%s\"] = %s\n", i, GETARG[i]
     }

   And this is the result when we run it:

     $ gawk -f testserv.awk
     -| MENU["4"] = www.gnu.org
     -| MENU["5"] = cgi-bin
     -| MENU["6"] = foo
     -| MENU["1"] = http
     -| MENU["2"] =
     -| MENU["3"] =
     -| PARAM["1"] = p1=stuff
     -| PARAM["2"] = p2=stuff&junk
     -| PARAM["3"] = percent=a % sign
     -| GETARG["p1"] = stuff
     -| GETARG["percent"] = a % sign
     -| GETARG["p2"] = stuff&junk
     -| GETARG["Method"] = GET
     -| GETARG["Version"] = 1.0
     -| GETARG["URI"] = http://www.gnu.org/cgi-bin/foo?p1=stuff&
     p2=stuff%26junk&percent=a %25 sign


File: gawkinet.info,  Node: Simple Server,  Next: Caveats,  Prev: Interacting Service,  Up: Using Networking

2.10 A Simple Web Server
========================

In the preceding node, we built the core logic for event-driven GUIs.
In this node, we finally extend the core to a real application.  No one
would actually write a commercial web server in 'gawk', but it is
instructive to see that it is feasible in principle.

   The application is ELIZA, the famous program by Joseph Weizenbaum
that mimics the behavior of a professional psychotherapist when talking
to you.  Weizenbaum would certainly object to this description, but this
is part of the legend around ELIZA. Take the site-independent core logic
and append the following code:

     function SetUpServer() {
       SetUpEliza()
       TopHeader = \
         "<HTML><title>An HTTP-based System with GAWK</title>\
         <HEAD><META HTTP-EQUIV=\"Content-Type\"\
         CONTENT=\"text/html; charset=iso-8859-1\"></HEAD>\
         <BODY BGCOLOR=\"#ffffff\" TEXT=\"#000000\"\
         LINK=\"#0000ff\" VLINK=\"#0000ff\"\
         ALINK=\"#0000ff\"> <A NAME=\"top\">"
       TopDoc    = "\
        <h2>Please choose one of the following actions:</h2>\
        <UL>\
        <LI>\
        <A HREF=" MyPrefix "/AboutServer>About this server</A>\
        </LI><LI>\
        <A HREF=" MyPrefix "/AboutELIZA>About Eliza</A></LI>\
        <LI>\
        <A HREF=" MyPrefix \
           "/StartELIZA>Start talking to Eliza</A></LI></UL>"
       TopFooter = "</BODY></HTML>"
     }

   'SetUpServer()' is similar to the previous example, except for
calling another function, 'SetUpEliza()'.  This approach can be used to
implement other kinds of servers.  The only changes needed to do so are
hidden in the functions 'SetUpServer()' and 'HandleGET()'.  Perhaps it
might be necessary to implement other HTTP methods.  The 'igawk' program
that comes with 'gawk' may be useful for this process.

   When extending this example to a complete application, the first
thing to do is to implement the function 'SetUpServer()' to initialize
the HTML pages and some variables.  These initializations determine the
way your HTML pages look (colors, titles, menu items, etc.).

   The function 'HandleGET()' is a nested case selection that decides
which page the user wants to see next.  Each nesting level refers to a
menu level of the GUI. Each case implements a certain action of the
menu.  On the deepest level of case selection, the handler essentially
knows what the user wants and stores the answer into the variable that
holds the HTML page contents:

     function HandleGET() {
       # A real HTTP server would treat some parts of the URI as a file name.
       # We take parts of the URI as menu choices and go on accordingly.
       if (MENU[2] == "AboutServer") {
         Document    = "This is not a CGI script.\
           This is an httpd, an HTML file, and a CGI script all \
           in one GAWK script. It needs no separate www-server, \
           no installation, and no root privileges.\
           <p>To run it, do this:</p><ul>\
           <li> start this script with \"gawk -f httpserver.awk\",</li>\
           <li> and on the same host let your www browser open location\
                \"http://localhost:8080\"</li>\
           </ul>\<p>\ Details of HTTP come from:</p><ul>\
                 <li>Hethmon:  Illustrated Guide to HTTP</p>\
                 <li>RFC 2068</li></ul><p>JK 14.9.1997</p>"
       } else if (MENU[2] == "AboutELIZA") {
         Document    = "This is an implementation of the famous ELIZA\
             program by Joseph Weizenbaum. It is written in GAWK and\
             uses an HTML GUI."
       } else if (MENU[2] == "StartELIZA") {
         gsub(/\+/, " ", GETARG["YouSay"])
         # Here we also have to substitute coded special characters
         Document    = "<form method=GET>" \
           "<h3>" ElizaSays(GETARG["YouSay"]) "</h3>\
           <p><input type=text name=YouSay value=\"\" size=60>\
           <br><input type=submit value=\"Tell her about it\"></p></form>"
       }
     }

   Now we are down to the heart of ELIZA, so you can see how it works.
Initially the user does not say anything; then ELIZA resets its money
counter and asks the user to tell what comes to mind open heartedly.
The subsequent answers are converted to uppercase characters and stored
for later comparison.  ELIZA presents the bill when being confronted
with a sentence that contains the phrase "shut up."  Otherwise, it looks
for keywords in the sentence, conjugates the rest of the sentence,
remembers the keyword for later use, and finally selects an answer from
the set of possible answers:

     function ElizaSays(YouSay) {
       if (YouSay == "") {
         cost = 0
         answer = "HI, IM ELIZA, TELL ME YOUR PROBLEM"
       } else {
         q = toupper(YouSay)
         gsub("'", "", q)
         if (q == qold) {
           answer = "PLEASE DONT REPEAT YOURSELF !"
         } else {
           if (index(q, "SHUT UP") > 0) {
             answer = "WELL, PLEASE PAY YOUR BILL. ITS EXACTLY ... $"\
                      int(100*rand()+30+cost/100)
           } else {
             qold = q
             w = "-"                 # no keyword recognized yet
             for (i in k) {          # search for keywords
               if (index(q, i) > 0) {
                 w = i
                 break
               }
             }
             if (w == "-") {         # no keyword, take old subject
               w    = wold
               subj = subjold
             } else {                # find subject
               subj = substr(q, index(q, w) + length(w)+1)
               wold = w
               subjold = subj        #  remember keyword and subject
             }
             for (i in conj)
                gsub(i, conj[i], q)   # conjugation
             # from all answers to this keyword, select one randomly
             answer = r[indices[int(split(k[w], indices) * rand()) + 1]]
             # insert subject into answer
             gsub("_", subj, answer)
           }
         }
       }
       cost += length(answer) # for later payment : 1 cent per character
       return answer
     }

   In the long but simple function 'SetUpEliza()', you can see tables
for conjugation, keywords, and answers.(1)  The associative array 'k'
contains indices into the array of answers 'r'.  To choose an answer,
ELIZA just picks an index randomly:

     function SetUpEliza() {
       srand()
       wold = "-"
       subjold = " "

       # table for conjugation
       conj[" ARE "     ] = " AM "
       conj["WERE "     ] = "WAS "
       conj[" YOU "     ] = " I "
       conj["YOUR "     ] = "MY "
       conj[" IVE "     ] =\
       conj[" I HAVE "  ] = " YOU HAVE "
       conj[" YOUVE "   ] =\
       conj[" YOU HAVE "] = " I HAVE "
       conj[" IM "      ] =\
       conj[" I AM "    ] = " YOU ARE "
       conj[" YOURE "   ] =\
       conj[" YOU ARE " ] = " I AM "

       # table of all answers
       r[1]   = "DONT YOU BELIEVE THAT I CAN  _"
       r[2]   = "PERHAPS YOU WOULD LIKE TO BE ABLE TO _ ?"
       ...

       # table for looking up answers that
       # fit to a certain keyword
       k["CAN YOU"]      = "1 2 3"
       k["CAN I"]        = "4 5"
       k["YOU ARE"]      =\
       k["YOURE"]        = "6 7 8 9"
       ...
     }

   Some interesting remarks and details (including the original source
code of ELIZA) are found on Mark Humphrys' home page.  Yahoo!  also has
a page with a collection of ELIZA-like programs.  Many of them are
written in Java, some of them disclosing the Java source code, and a few
even explain how to modify the Java source code.

   ---------- Footnotes ----------

   (1) The version shown here is abbreviated.  The full version comes
with the 'gawk' distribution.


File: gawkinet.info,  Node: Caveats,  Next: Challenges,  Prev: Simple Server,  Up: Using Networking

2.11 Network Programming Caveats
================================

By now it should be clear that debugging a networked application is more
complicated than debugging a single-process single-hosted application.
The behavior of a networked application sometimes looks noncausal
because it is not reproducible in a strong sense.  Whether a network
application works or not sometimes depends on the following:

   * How crowded the underlying network is

   * If the party at the other end is running or not

   * The state of the party at the other end

   The most difficult problems for a beginner arise from the hidden
states of the underlying network.  After closing a TCP connection, it's
often necessary to wait a short while before reopening the connection.
Even more difficult is the establishment of a connection that previously
ended with a "broken pipe."  Those connections have to "time out" for a
minute or so before they can reopen.  Check this with the command
'netstat -a', which provides a list of still "active" connections.


File: gawkinet.info,  Node: Challenges,  Prev: Caveats,  Up: Using Networking

2.12 Where To Go From Here
==========================

Now, you have learned enough to build your own application.  You could,
for example, take part in the Loebner Contest to win $100,000.  The
Loebner Prize is the first formal instantiation of a Turing Test.  Hugh
Loebner agreed with The Cambridge Center for Behavioral Studies to
underwrite a contest designed to implement the Turing Test.  Dr. Loebner
pledged a Grand Prize of $100,000 for the first computer whose responses
were indistinguishable from a human's.  Each year an annual prize of
$2000 and a bronze medal is awarded to the _most_ human computer.  The
winner of the annual contest is the best entry relative to other entries
that year, irrespective of how good it is in an absolute sense.  Here is
an example of a conversation with the winning program of 1997:

     (c)1997 Cambridge Center For Behavioral Studies all rights reserved [CONVERSE]
     [Intelligent Research Ltd.] Start at: [1997/04/29 08:59:40]
     PROGRAM[10:39:20]Hi, my name is Catherine, what's yours?
     JUDGE02[10:39:36]My name is Nathan.
     PROGRAM[10:39:37]Well, it's nice to meet you, Nathan.
     PROGRAM[10:39:45]Did you see that story on CNN last night about the lesbian
     PROGRAM[10:40:03]couple who came out at a White House party on Sunday?
     JUDGE02[10:40:45]No.  I'm sorry I missed that.  How did the Prez take it?
     PROGRAM[10:40:47]Ellen Degeneres was one of them - she was kissing her lover
     PROGRAM[10:41:08]in front of Bill Clinton. Do you think he was very
     PROGRAM[10:41:21]embarrassed?
     JUDGE02[10:41:37]You tell me.  I didn't see it.
     PROGRAM[10:41:38]Are you still a Friend of Bill Clinton?
     JUDGE02[10:42:22]Yes.  I would like to talk about something else.  Do you know anything about sculpture.
     PROGRAM[10:42:24]Well, I suppose he's doing his best like most of us, but he
     PROGRAM[10:42:35]does seem to attract an UNUSUAL amount of bad publicity,
     PROGRAM[10:42:51]wouldnt you say--can it all be bad luck?
     JUDGE02[10:43:20]I asked you if you knew anything about sculpture.
     PROGRAM[10:43:21]OK, but what happens now--does it all drift on, with
     PROGRAM[10:43:36]everyone waiting to see how much his friends have said about
     PROGRAM[10:43:47]him under threat of lots and lots of jail-or will something
     PROGRAM[10:44:01]dramatic actually happen?
     JUDGE02[10:44:19]Do you know what sculpture is?
     PROGRAM[10:44:20]Well, youre more a fan of his than I am I guess---though I
     PROGRAM[10:44:34]cant SWEAR what Id have done in that locked hotel room, I
     PROGRAM[10:44:51]must say.
     JUDGE02[10:45:26]Have you ever been to the Salmagundi Club?
     PROGRAM[10:45:29]Never. to go back to the original discussion Time to get
     PROGRAM[10:45:43]off this one I think and onto something more down to earth!
     JUDGE02[10:46:20]What is more down to earth than art?
     PROGRAM[10:46:21]I don't know what -- to be honest. -
     PROGRAM[10:46:30]I suppose it depends on where you're coming from, but as the
     PROGRAM[10:46:46]song goes in My Fair Lady, "Why can't a woman be more like a
     PROGRAM[10:47:03]man? "
     JUDGE02[10:47:52]I liked that song but I prefer "Why can't children be more like we are"
     JUDGE02[10:48:10]from another play the name of which I cannot remember.
     PROGRAM[10:48:12]What, if anything, do you enjoy about being a man?
     JUDGE02[10:49:01]I would enjoy all aspects of life no matter what my gender.
     PROGRAM[10:49:02]Do you think of yourself as being attractive?

   This program insists on always speaking about the same story around
Bill Clinton.  You see, even a program with a rather narrow mind can
behave so much like a human being that it can win this prize.  It is
quite common to let these programs talk to each other via network
connections.  But during the competition itself, the program and its
computer have to be present at the place the competition is held.  We
all would love to see a 'gawk' program win in such an event.  Maybe it
is up to you to accomplish this?

   Some other ideas for useful networked applications:
   * Read the file 'doc/awkforai.txt' in earlier 'gawk'
     distributions.(1)  It was written by Ronald P. Loui (at the time,
     Associate Professor of Computer Science, at Washington University
     in St.  Louis, <loui@ai.wustl.edu>) and summarizes why he taught
     'gawk' to students of Artificial Intelligence.  Here are some
     passages from the text:

          The GAWK manual can be consumed in a single lab session and
          the language can be mastered by the next morning by the
          average student.  GAWK's automatic initialization, implicit
          coercion, I/O support and lack of pointers forgive many of the
          mistakes that young programmers are likely to make.  Those who
          have seen C but not mastered it are happy to see that GAWK
          retains some of the same sensibilities while adding what must
          be regarded as spoonsful of syntactic sugar.
          ...
          There are further simple answers.  Probably the best is the
          fact that increasingly, undergraduate AI programming is
          involving the Web.  Oren Etzioni (University of Washington,
          Seattle) has for a while been arguing that the "softbot" is
          replacing the mechanical engineers' robot as the most
          glamorous AI testbed.  If the artifact whose behavior needs to
          be controlled in an intelligent way is the software agent,
          then a language that is well-suited to controlling the
          software environment is the appropriate language.  That would
          imply a scripting language.  If the robot is KAREL, then the
          right language is "turn left; turn right."  If the robot is
          Netscape, then the right language is something that can
          generate 'netscape -remote
          'openURL(http://cs.wustl.edu/~loui)'' with elan.
          ...
          AI programming requires high-level thinking.  There have
          always been a few gifted programmers who can write high-level
          programs in assembly language.  Most however need the ambient
          abstraction to have a higher floor.
          ...
          Second, inference is merely the expansion of notation.  No
          matter whether the logic that underlies an AI program is
          fuzzy, probabilistic, deontic, defeasible, or deductive, the
          logic merely defines how strings can be transformed into other
          strings.  A language that provides the best support for string
          processing in the end provides the best support for logic, for
          the exploration of various logics, and for most forms of
          symbolic processing that AI might choose to call "reasoning"
          instead of "logic."  The implication is that PROLOG, which
          saves the AI programmer from having to write a unifier, saves
          perhaps two dozen lines of GAWK code at the expense of
          strongly biasing the logic and representational expressiveness
          of any approach.

     Now that 'gawk' itself can connect to the Internet, it should be
     obvious that it is suitable for writing intelligent web agents.

   * 'awk' is strong at pattern recognition and string processing.  So,
     it is well suited to the classic problem of language translation.
     A first try could be a program that knows the 100 most frequent
     English words and their counterparts in German or French.  The
     service could be implemented by regularly reading email with the
     program above, replacing each word by its translation and sending
     the translation back via SMTP. Users would send English email to
     their translation service and get back a translated email message
     in return.  As soon as this works, more effort can be spent on a
     real translation program.

   * Another dialogue-oriented application (on the verge of ridicule) is
     the email "support service."  Troubled customers write an email to
     an automatic 'gawk' service that reads the email.  It looks for
     keywords in the mail and assembles a reply email accordingly.  By
     carefully investigating the email header, and repeating these
     keywords through the reply email, it is rather simple to give the
     customer a feeling that someone cares.  Ideally, such a service
     would search a database of previous cases for solutions.  If none
     exists, the database could, for example, consist of all the
     newsgroups, mailing lists and FAQs on the Internet.

   ---------- Footnotes ----------

   (1) The file is no longer distributed with 'gawk', since the
copyright on the file is not clear.


File: gawkinet.info,  Node: Some Applications and Techniques,  Next: Links,  Prev: Using Networking,  Up: Top

3 Some Applications and Techniques
**********************************

In this major node, we look at a number of self-contained scripts, with
an emphasis on concise networking.  Along the way, we work towards
creating building blocks that encapsulate often needed functions of the
networking world, show new techniques that broaden the scope of problems
that can be solved with 'gawk', and explore leading edge technology that
may shape the future of networking.

   We often refer to the site-independent core of the server that we
built in *note A Simple Web Server: Simple Server.  When building new
and nontrivial servers, we always copy this building block and append
new instances of the two functions 'SetUpServer()' and 'HandleGET()'.

   This makes a lot of sense, since this scheme of event-driven
execution provides 'gawk' with an interface to the most widely accepted
standard for GUIs: the web browser.  Now, 'gawk' can rival even Tcl/Tk.

   Tcl and 'gawk' have much in common.  Both are simple scripting
languages that allow us to quickly solve problems with short programs.
But Tcl has Tk on top of it, and 'gawk' had nothing comparable up to
now.  While Tcl needs a large and ever-changing library (Tk, which was
bound to the X Window System until recently), 'gawk' needs just the
networking interface and some kind of browser on the client's side.
Besides better portability, the most important advantage of this
approach (embracing well-established standards such HTTP and HTML) is
that _we do not need to change the language_.  We let others do the work
of fighting over protocols and standards.  We can use HTML, JavaScript,
VRML, or whatever else comes along to do our work.

* Menu:

* PANIC::                       An Emergency Web Server.
* GETURL::                      Retrieving Web Pages.
* REMCONF::                     Remote Configuration Of Embedded Systems.
* URLCHK::                      Look For Changed Web Pages.
* WEBGRAB::                     Extract Links From A Page.
* STATIST::                     Graphing A Statistical Distribution.
* MAZE::                        Walking Through A Maze In Virtual Reality.
* MOBAGWHO::                    A Simple Mobile Agent.
* STOXPRED::                    Stock Market Prediction As A Service.
* PROTBASE::                    Searching Through A Protein Database.


File: gawkinet.info,  Node: PANIC,  Next: GETURL,  Prev: Some Applications and Techniques,  Up: Some Applications and Techniques

3.1 PANIC: An Emergency Web Server
==================================

At first glance, the '"Hello, world"' example in *note A Primitive Web
Service: Primitive Service, seems useless.  By adding just a few lines,
we can turn it into something useful.

   The PANIC program tells everyone who connects that the local site is
not working.  When a web server breaks down, it makes a difference if
customers get a strange "network unreachable" message, or a short
message telling them that the server has a problem.  In such an
emergency, the hard disk and everything on it (including the regular web
service) may be unavailable.  Rebooting the web server off a diskette
makes sense in this setting.

   To use the PANIC program as an emergency web server, all you need are
the 'gawk' executable and the program below on a diskette.  By default,
it connects to port 8080.  A different value may be supplied on the
command line:

     BEGIN {
       RS = ORS = "\r\n"
       if (MyPort ==  0) MyPort = 8080
       HttpService = "/inet/tcp/" MyPort "/0/0"
       Hello = "<HTML><HEAD><TITLE>Out Of Service</TITLE>" \
          "</HEAD><BODY><H1>" \
          "This site is temporarily out of service." \
          "</H1></BODY></HTML>"
       Len = length(Hello) + length(ORS)
       while ("awk" != "complex") {
         print "HTTP/1.0 200 OK"          |& HttpService
         print "Content-Length: " Len ORS |& HttpService
         print Hello                      |& HttpService
         while ((HttpService |& getline) > 0)
            continue;
         close(HttpService)
       }
     }


File: gawkinet.info,  Node: GETURL,  Next: REMCONF,  Prev: PANIC,  Up: Some Applications and Techniques

3.2 GETURL: Retrieving Web Pages
================================

GETURL is a versatile building block for shell scripts that need to
retrieve files from the Internet.  It takes a web address as a
command-line parameter and tries to retrieve the contents of this
address.  The contents are printed to standard output, while the header
is printed to '/dev/stderr'.  A surrounding shell script could analyze
the contents and extract the text or the links.  An ASCII browser could
be written around GETURL. But more interestingly, web robots are
straightforward to write on top of GETURL. On the Internet, you can find
several programs of the same name that do the same job.  They are
usually much more complex internally and at least 10 times longer.

   At first, GETURL checks if it was called with exactly one web
address.  Then, it checks if the user chose to use a special proxy
server whose name is handed over in a variable.  By default, it is
assumed that the local machine serves as proxy.  GETURL uses the 'GET'
method by default to access the web page.  By handing over the name of a
different method (such as 'HEAD'), it is possible to choose a different
behavior.  With the 'HEAD' method, the user does not receive the body of
the page content, but does receive the header:

     BEGIN {
       if (ARGC != 2) {
         print "GETURL - retrieve Web page via HTTP 1.0"
         print "IN:\n    the URL as a command-line parameter"
         print "PARAM(S):\n    -v Proxy=MyProxy"
         print "OUT:\n    the page content on stdout"
         print "    the page header on stderr"
         print "JK 16.05.1997"
         print "ADR 13.08.2000"
         exit
       }
       URL = ARGV[1]; ARGV[1] = ""
       if (Proxy     == "")  Proxy     = "127.0.0.1"
       if (ProxyPort ==  0)  ProxyPort = 80
       if (Method    == "")  Method    = "GET"
       HttpService = "/inet/tcp/0/" Proxy "/" ProxyPort
       ORS = RS = "\r\n\r\n"
       print Method " " URL " HTTP/1.0" |& HttpService
       HttpService                      |& getline Header
       print Header > "/dev/stderr"
       while ((HttpService |& getline) > 0)
         printf "%s", $0
       close(HttpService)
     }

   This program can be changed as needed, but be careful with the last
lines.  Make sure transmission of binary data is not corrupted by
additional line breaks.  Even as it is now, the byte sequence
'"\r\n\r\n"' would disappear if it were contained in binary data.  Don't
get caught in a trap when trying a quick fix on this one.


File: gawkinet.info,  Node: REMCONF,  Next: URLCHK,  Prev: GETURL,  Up: Some Applications and Techniques

3.3 REMCONF: Remote Configuration of Embedded Systems
=====================================================

Today, you often find powerful processors in embedded systems.
Dedicated network routers and controllers for all kinds of machinery are
examples of embedded systems.  Processors like the Intel 80x86 or the
AMD Elan are able to run multitasking operating systems, such as XINU or
GNU/Linux in embedded PCs.  These systems are small and usually do not
have a keyboard or a display.  Therefore it is difficult to set up their
configuration.  There are several widespread ways to set them up:

   * DIP switches

   * Read Only Memories such as EPROMs

   * Serial lines or some kind of keyboard

   * Network connections via 'telnet' or SNMP

   * HTTP connections with HTML GUIs

   In this node, we look at a solution that uses HTTP connections to
control variables of an embedded system that are stored in a file.
Since embedded systems have tight limits on resources like memory, it is
difficult to employ advanced techniques such as SNMP and HTTP servers.
'gawk' fits in quite nicely with its single executable which needs just
a short script to start working.  The following program stores the
variables in a file, and a concurrent process in the embedded system may
read the file.  The program uses the site-independent part of the simple
web server that we developed in *note A Web Service with Interaction:
Interacting Service.  As mentioned there, all we have to do is to write
two new procedures 'SetUpServer()' and 'HandleGET()':

     function SetUpServer() {
       TopHeader = "<HTML><title>Remote Configuration</title>"
       TopDoc = "<BODY>\
         <h2>Please choose one of the following actions:</h2>\
         <UL>\
           <LI><A HREF=" MyPrefix "/AboutServer>About this server</A></LI>\
           <LI><A HREF=" MyPrefix "/ReadConfig>Read Configuration</A></LI>\
           <LI><A HREF=" MyPrefix "/CheckConfig>Check Configuration</A></LI>\
           <LI><A HREF=" MyPrefix "/ChangeConfig>Change Configuration</A></LI>\
           <LI><A HREF=" MyPrefix "/SaveConfig>Save Configuration</A></LI>\
         </UL>"
       TopFooter  = "</BODY></HTML>"
       if (ConfigFile == "") ConfigFile = "config.asc"
     }

   The function 'SetUpServer()' initializes the top level HTML texts as
usual.  It also initializes the name of the file that contains the
configuration parameters and their values.  In case the user supplies a
name from the command line, that name is used.  The file is expected to
contain one parameter per line, with the name of the parameter in column
one and the value in column two.

   The function 'HandleGET()' reflects the structure of the menu tree as
usual.  The first menu choice tells the user what this is all about.
The second choice reads the configuration file line by line and stores
the parameters and their values.  Notice that the record separator for
this file is '"\n"', in contrast to the record separator for HTTP. The
third menu choice builds an HTML table to show the contents of the
configuration file just read.  The fourth choice does the real work of
changing parameters, and the last one just saves the configuration into
a file:

     function HandleGET() {
       if (MENU[2] == "AboutServer") {
         Document  = "This is a GUI for remote configuration of an\
           embedded system. It is is implemented as one GAWK script."
       } else if (MENU[2] == "ReadConfig") {
         RS = "\n"
         while ((getline < ConfigFile) > 0)
            config[$1] = $2;
         close(ConfigFile)
         RS = "\r\n"
         Document = "Configuration has been read."
       } else if (MENU[2] == "CheckConfig") {
         Document = "<TABLE BORDER=1 CELLPADDING=5>"
         for (i in config)
           Document = Document "<TR><TD>" i "</TD>" \
             "<TD>" config[i] "</TD></TR>"
         Document = Document "</TABLE>"
       } else if (MENU[2] == "ChangeConfig") {
         if ("Param" in GETARG) {            # any parameter to set?
           if (GETARG["Param"] in config) {  # is  parameter valid?
             config[GETARG["Param"]] = GETARG["Value"]
             Document = (GETARG["Param"] " = " GETARG["Value"] ".")
           } else {
             Document = "Parameter <b>" GETARG["Param"] "</b> is invalid."
           }
         } else {
           Document = "<FORM method=GET><h4>Change one parameter</h4>\
             <TABLE BORDER CELLPADDING=5>\
             <TR><TD>Parameter</TD><TD>Value</TD></TR>\
             <TR><TD><input type=text name=Param value=\"\" size=20></TD>\
                 <TD><input type=text name=Value value=\"\" size=40></TD>\
             </TR></TABLE><input type=submit value=\"Set\"></FORM>"
         }
       } else if (MENU[2] == "SaveConfig") {
         for (i in config)
           printf("%s %s\n", i, config[i]) > ConfigFile
         close(ConfigFile)
         Document = "Configuration has been saved."
       }
     }

   We could also view the configuration file as a database.  From this
point of view, the previous program acts like a primitive database
server.  Real SQL database systems also make a service available by
providing a TCP port that clients can connect to.  But the application
level protocols they use are usually proprietary and also change from
time to time.  This is also true for the protocol that MiniSQL uses.


File: gawkinet.info,  Node: URLCHK,  Next: WEBGRAB,  Prev: REMCONF,  Up: Some Applications and Techniques

3.4 URLCHK: Look for Changed Web Pages
======================================

Most people who make heavy use of Internet resources have a large
bookmark file with pointers to interesting web sites.  It is impossible
to regularly check by hand if any of these sites have changed.  A
program is needed to automatically look at the headers of web pages and
tell which ones have changed.  URLCHK does the comparison after using
GETURL with the 'HEAD' method to retrieve the header.

   Like GETURL, this program first checks that it is called with exactly
one command-line parameter.  URLCHK also takes the same command-line
variables 'Proxy' and 'ProxyPort' as GETURL, because these variables are
handed over to GETURL for each URL that gets checked.  The one and only
parameter is the name of a file that contains one line for each URL. In
the first column, we find the URL, and the second and third columns hold
the length of the URL's body when checked for the two last times.  Now,
we follow this plan:

  1. Read the URLs from the file and remember their most recent lengths

  2. Delete the contents of the file

  3. For each URL, check its new length and write it into the file

  4. If the most recent and the new length differ, tell the user

   It may seem a bit peculiar to read the URLs from a file together with
their two most recent lengths, but this approach has several advantages.
You can call the program again and again with the same file.  After
running the program, you can regenerate the changed URLs by extracting
those lines that differ in their second and third columns:

     BEGIN {
       if (ARGC != 2) {
         print "URLCHK - check if URLs have changed"
         print "IN:\n    the file with URLs as a command-line parameter"
         print "    file contains URL, old length, new length"
         print "PARAMS:\n    -v Proxy=MyProxy -v ProxyPort=8080"
         print "OUT:\n    same as file with URLs"
         print "JK 02.03.1998"
         exit
       }
       URLfile = ARGV[1]; ARGV[1] = ""
       if (Proxy     != "") Proxy     = " -v Proxy="     Proxy
       if (ProxyPort != "") ProxyPort = " -v ProxyPort=" ProxyPort
       while ((getline < URLfile) > 0)
          Length[$1] = $3 + 0
       close(URLfile)      # now, URLfile is read in and can be updated
       GetHeader = "gawk " Proxy ProxyPort " -v Method=\"HEAD\" -f geturl.awk "
       for (i in Length) {
         GetThisHeader = GetHeader i " 2>&1"
         while ((GetThisHeader | getline) > 0)
           if (toupper($0) ~ /CONTENT-LENGTH/) NewLength = $2 + 0
         close(GetThisHeader)
         print i, Length[i], NewLength > URLfile
         if (Length[i] != NewLength)  # report only changed URLs
           print i, Length[i], NewLength
       }
       close(URLfile)
     }

   Another thing that may look strange is the way GETURL is called.
Before calling GETURL, we have to check if the proxy variables need to
be passed on.  If so, we prepare strings that will become part of the
command line later.  In 'GetHeader()', we store these strings together
with the longest part of the command line.  Later, in the loop over the
URLs, 'GetHeader()' is appended with the URL and a redirection operator
to form the command that reads the URL's header over the Internet.
GETURL always produces the headers over '/dev/stderr'.  That is the
reason why we need the redirection operator to have the header piped in.

   This program is not perfect because it assumes that changing URLs
results in changed lengths, which is not necessarily true.  A more
advanced approach is to look at some other header line that holds time
information.  But, as always when things get a bit more complicated,
this is left as an exercise to the reader.


File: gawkinet.info,  Node: WEBGRAB,  Next: STATIST,  Prev: URLCHK,  Up: Some Applications and Techniques

3.5 WEBGRAB: Extract Links from a Page
======================================

Sometimes it is necessary to extract links from web pages.  Browsers do
it, web robots do it, and sometimes even humans do it.  Since we have a
tool like GETURL at hand, we can solve this problem with some help from
the Bourne shell:

     BEGIN { RS = "https?://[#%&\\+\\-\\./0-9\\:;\\?A-Z_a-z\\~]*" }
     RT != "" {
        command = ("gawk -v Proxy=MyProxy -f geturl.awk " RT \
                    " > doc" NR ".html")
        print command
     }

   Notice that the regular expression for URLs is rather crude.  A
precise regular expression is much more complex.  But this one works
rather well.  One problem is that it is unable to find internal links of
an HTML document.  Another problem is that 'ftp', 'telnet', 'news',
'mailto', and other kinds of links are missing in the regular
expression.  However, it is straightforward to add them, if doing so is
necessary for other tasks.

   This program reads an HTML file and prints all the HTTP links that it
finds.  It relies on 'gawk''s ability to use regular expressions as
record separators.  With 'RS' set to a regular expression that matches
links, the second action is executed each time a non-empty link is
found.  We can find the matching link itself in 'RT'.

   The action could use the 'system()' function to let another GETURL
retrieve the page, but here we use a different approach.  This simple
program prints shell commands that can be piped into 'sh' for execution.
This way it is possible to first extract the links, wrap shell commands
around them, and pipe all the shell commands into a file.  After editing
the file, execution of the file retrieves exactly those files that we
really need.  In case we do not want to edit, we can retrieve all the
pages like this:

     gawk -f geturl.awk http://www.suse.de | gawk -f webgrab.awk | sh

   After this, you will find the contents of all referenced documents in
files named 'doc*.html' even if they do not contain HTML code.  The most
annoying thing is that we always have to pass the proxy to GETURL. If
you do not like to see the headers of the web pages appear on the
screen, you can redirect them to '/dev/null'.  Watching the headers
appear can be quite interesting, because it reveals interesting details
such as which web server the companies use.  Now, it is clear how the
clever marketing people use web robots to determine the market shares of
Microsoft and Netscape in the web server market.

   Port 80 of any web server is like a small hole in a repellent
firewall.  After attaching a browser to port 80, we usually catch a
glimpse of the bright side of the server (its home page).  With a tool
like GETURL at hand, we are able to discover some of the more concealed
or even "indecent" services (i.e., lacking conformity to standards of
quality).  It can be exciting to see the fancy CGI scripts that lie
there, revealing the inner workings of the server, ready to be called:

   * With a command such as:

          gawk -f geturl.awk http://any.host.on.the.net/cgi-bin/

     some servers give you a directory listing of the CGI files.
     Knowing the names, you can try to call some of them and watch for
     useful results.  Sometimes there are executables in such
     directories (such as Perl interpreters) that you may call remotely.
     If there are subdirectories with configuration data of the web
     server, this can also be quite interesting to read.

   * The well-known Apache web server usually has its CGI files in the
     directory '/cgi-bin'.  There you can often find the scripts
     'test-cgi' and 'printenv'.  Both tell you some things about the
     current connection and the installation of the web server.  Just
     call:

          gawk -f geturl.awk http://any.host.on.the.net/cgi-bin/test-cgi
          gawk -f geturl.awk http://any.host.on.the.net/cgi-bin/printenv

   * Sometimes it is even possible to retrieve system files like the web
     server's log file--possibly containing customer data--or even the
     file '/etc/passwd'.  (We don't recommend this!)

   *Caution:* Although this may sound funny or simply irrelevant, we are
talking about severe security holes.  Try to explore your own system
this way and make sure that none of the above reveals too much
information about your system.


File: gawkinet.info,  Node: STATIST,  Next: MAZE,  Prev: WEBGRAB,  Up: Some Applications and Techniques

3.6 STATIST: Graphing a Statistical Distribution
================================================