5 * Author: Tatu Ylonen <ylo@cs.hut.fi>
7 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
10 * Created: Thu Jun 22 01:17:50 1995 ylo
12 * Simple pattern matching, with '*' and '?' as wildcards.
22 * Returns true if the given string matches the pattern (which may contain ?
23 * and * as wildcards), and zero if it does not match.
27 match_pattern(const char *s, const char *pattern)
30 /* If at end of pattern, accept if also at end of string. */
34 if (*pattern == '*') {
35 /* Skip the asterisk. */
38 /* If at end of pattern, accept immediately. */
42 /* If next character in pattern is known, optimize. */
43 if (*pattern != '?' && *pattern != '*') {
45 * Look instances of the next character in
46 * pattern, and try to match starting from
51 match_pattern(s + 1, pattern + 1))
57 * Move ahead one character at a time and try to
58 * match at each position.
61 if (match_pattern(s, pattern))
67 * There must be at least one more character in the string.
68 * If we are at the end, fail.
73 /* Check if the next character of the string is acceptable. */
74 if (*pattern != '?' && *pattern != *s)
77 /* Move to the next character, both in string and in pattern. */
85 * Tries to match the host name (which must be in all lowercase) against the
86 * comma-separated sequence of subpatterns (each possibly preceded by ! to
87 * indicate negation). Returns -1 if negation matches, 1 if there is
88 * a positive match, 0 if there is no match at all.
92 match_hostname(const char *host, const char *pattern, unsigned int len)
100 for (i = 0; i < len;) {
101 /* Check if the subpattern is negated. */
102 if (pattern[i] == '!') {
109 * Extract the subpattern up to a comma or end. Convert the
110 * subpattern to lowercase.
113 i < len && subi < sizeof(sub) - 1 && pattern[i] != ',';
115 sub[subi] = isupper(pattern[i]) ? tolower(pattern[i]) : pattern[i];
116 /* If subpattern too long, return failure (no match). */
117 if (subi >= sizeof(sub) - 1)
120 /* If the subpattern was terminated by a comma, skip the comma. */
121 if (i < len && pattern[i] == ',')
124 /* Null-terminate the subpattern. */
127 /* Try to match the subpattern against the host name. */
128 if (match_pattern(host, sub)) {
130 return -1; /* Negative */
132 got_positive = 1; /* Positive */
137 * Return success if got a positive match. If there was a negative
138 * match, we have already returned -1 and never get here.