summaryrefslogtreecommitdiff
path: root/tftpd/remap.c
blob: 6f5b409ac8a6e2a47607e7f3f89cc4b0d13c530f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
/* ----------------------------------------------------------------------- *
 *
 *   Copyright 2001-2014 H. Peter Anvin - All Rights Reserved
 *
 *   This program is free software available under the same license
 *   as the "OpenBSD" operating system, distributed at
 *   http://www.openbsd.org/.
 *
 * ----------------------------------------------------------------------- */

/*
 * remap.c
 *
 * Perform regular-expression based filename remapping.
 */

#include "config.h"             /* Must be included first! */
#include <ctype.h>
#include <syslog.h>
#include <regex.h>

#include "tftpd.h"
#include "remap.h"

#define DEADMAN_MAX_STEPS	1024    /* Timeout after this many steps */
#define MAXLINE			16384   /* Truncate a line at this many bytes */

#define RULE_REWRITE	0x01    /* This is a rewrite rule */
#define RULE_GLOBAL	0x02    /* Global rule (repeat until no match) */
#define RULE_EXIT	0x04    /* Exit after matching this rule */
#define RULE_RESTART	0x08    /* Restart at the top after matching this rule */
#define RULE_ABORT	0x10    /* Terminate processing with an error */
#define RULE_INVERSE	0x20    /* Execute if regex *doesn't* match */
#define RULE_IPV4	0x40	/* IPv4 only */
#define RULE_IPV6	0x80	/* IPv6 only */

struct rule {
    struct rule *next;
    int nrule;
    int rule_flags;
    char rule_mode;
    regex_t rx;
    const char *pattern;
};

static int xform_null(int c)
{
    return c;
}

static int xform_toupper(int c)
{
    return toupper(c);
}

static int xform_tolower(int c)
{
    return tolower(c);
}

/* Do \-substitution.  Call with string == NULL to get length only. */
static int genmatchstring(char *string, const char *pattern,
                          const char *input, const regmatch_t * pmatch,
                          match_pattern_callback macrosub)
{
    int (*xform) (int) = xform_null;
    int len = 0;
    int n, mlen, sublen;
    int endbytes;

    /* Get section before match; note pmatch[0] is the whole match */
    endbytes = strlen(input) - pmatch[0].rm_eo;
    len = pmatch[0].rm_so + endbytes;
    if (string) {
        memcpy(string, input, pmatch[0].rm_so);
        string += pmatch[0].rm_so;
    }

    /* Transform matched section */
    while (*pattern) {
        mlen = 0;

        if (*pattern == '\\' && pattern[1] != '\0') {
            char macro = pattern[1];
            switch (macro) {
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                n = pattern[1] - '0';

                if (pmatch[n].rm_so != -1) {
                    mlen = pmatch[n].rm_eo - pmatch[n].rm_so;
                    len += mlen;
                    if (string) {
                        const char *p = input + pmatch[n].rm_so;
                        while (mlen--)
                            *string++ = xform(*p++);
                    }
                }
                break;

            case 'L':
                xform = xform_tolower;
                break;

            case 'U':
                xform = xform_toupper;
                break;

            case 'E':
                xform = xform_null;
                break;

            default:
                if (macrosub && (sublen = macrosub(macro, string)) >= 0) {
                    while (sublen--) {
                        len++;
                        if (string) {
                            *string = xform(*string);
                            string++;
                        }
                    }
                } else {
                    len++;
                    if (string)
                        *string++ = xform(pattern[1]);
                }
            }
            pattern += 2;
        } else {
            len++;
            if (string)
                *string++ = xform(*pattern);
            pattern++;
        }
    }

    /* Copy section after match */
    if (string) {
        memcpy(string, input + pmatch[0].rm_eo, endbytes);
        string[endbytes] = '\0';
    }

    return len;
}

/*
 * Extract a string terminated by non-escaped whitespace; ignoring
 * leading whitespace.  Consider an unescaped # to be a comment marker,
 * functionally \n.
 */
static int readescstring(char *buf, char **str)
{
    char *p = *str;
    int wasbs = 0, len = 0;

    while (*p && isspace(*p))
        p++;

    if (!*p) {
        *buf = '\0';
        *str = p;
        return 0;
    }

    while (*p) {
        if (!wasbs && (isspace(*p) || *p == '#')) {
            *buf = '\0';
            *str = p;
            return len;
        }
        /* Important: two backslashes leave us in the !wasbs state! */
        wasbs = !wasbs && (*p == '\\');
        *buf++ = *p++;
        len++;
    }

    *buf = '\0';
    *str = p;
    return len;
}

/* Parse a line into a set of instructions */
static int parseline(char *line, struct rule *r, int lineno)
{
    char buffer[MAXLINE];
    char *p;
    int rv;
    int rxflags = REG_EXTENDED;
    static int nrule;

    memset(r, 0, sizeof *r);
    r->nrule = nrule;

    if (!readescstring(buffer, &line))
        return 0;               /* No rule found */

    for (p = buffer; *p; p++) {
        switch (*p) {
        case 'r':
            r->rule_flags |= RULE_REWRITE;
            break;
        case 'g':
            r->rule_flags |= RULE_GLOBAL;
            break;
        case 'e':
            r->rule_flags |= RULE_EXIT;
            break;
        case 's':
            r->rule_flags |= RULE_RESTART;
            break;
        case 'a':
            r->rule_flags |= RULE_ABORT;
            break;
        case 'i':
            rxflags |= REG_ICASE;
            break;
        case '~':
            r->rule_flags |= RULE_INVERSE;
            break;
	case '4':
	    r->rule_flags |= RULE_IPV4;
	    break;
	case '6':
	    r->rule_flags |= RULE_IPV6;
	    break;
	case 'G':
	case 'P':
            r->rule_mode = *p;
            break;
        default:
            syslog(LOG_ERR,
                   "Remap command \"%s\" on line %d contains invalid char \"%c\"",
                   buffer, lineno, *p);
            return -1;          /* Error */
            break;
        }
    }

    /* RULE_GLOBAL only applies when RULE_REWRITE specified */
    if (!(r->rule_flags & RULE_REWRITE))
        r->rule_flags &= ~RULE_GLOBAL;

    if ((r->rule_flags & (RULE_INVERSE | RULE_REWRITE)) ==
        (RULE_INVERSE | RULE_REWRITE)) {
        syslog(LOG_ERR, "r rules cannot be inverted, line %d: %s\n",
               lineno, line);
        return -1;              /* Error */
    }

    /* Read and compile the regex */
    if (!readescstring(buffer, &line)) {
        syslog(LOG_ERR, "No regex on remap line %d: %s\n", lineno, line);
        return -1;              /* Error */
    }

    if ((rv = regcomp(&r->rx, buffer, rxflags)) != 0) {
        char errbuf[BUFSIZ];
        regerror(rv, &r->rx, errbuf, BUFSIZ);
        syslog(LOG_ERR, "Bad regex in remap line %d: %s\n", lineno,
               errbuf);
        return -1;              /* Error */
    }

    /* Read the rewrite pattern, if any */
    if (readescstring(buffer, &line)) {
        r->pattern = tfstrdup(buffer);
    } else {
        r->pattern = "";
    }

    nrule++;
    return 1;                   /* Rule found */
}

/* Read a rule file */
struct rule *parserulefile(FILE * f)
{
    char line[MAXLINE];
    struct rule *first_rule = NULL;
    struct rule **last_rule = &first_rule;
    struct rule *this_rule = tfmalloc(sizeof(struct rule));
    int rv;
    int lineno = 0;
    int err = 0;

    while (lineno++, fgets(line, MAXLINE, f)) {
        rv = parseline(line, this_rule, lineno);
        if (rv < 0)
            err = 1;
        if (rv > 0) {
            *last_rule = this_rule;
            last_rule = &this_rule->next;
            this_rule = tfmalloc(sizeof(struct rule));
        }
    }

    free(this_rule);            /* Last one is always unused */

    if (err) {
        /* Bail on error, we have already logged an error message */
        exit(EX_CONFIG);
    }

    return first_rule;
}

/* Destroy a rule file data structure */
void freerules(struct rule *r)
{
    struct rule *next;

    while (r) {
        next = r->next;

        regfree(&r->rx);

        /* "" patterns aren't allocated by malloc() */
        if (r->pattern && *r->pattern)
            free((void *)r->pattern);

        free(r);

        r = next;
    }
}

/* Execute a rule set on a string; returns a malloc'd new string. */
char *rewrite_string(const char *input, const struct rule *rules,
                     char mode, int af, match_pattern_callback macrosub,
                     const char **errmsg)
{
    char *current = tfstrdup(input);
    char *newstr;
    const struct rule *ruleptr = rules;
    regmatch_t pmatch[10];
    int len;
    int was_match = 0;
    int deadman = DEADMAN_MAX_STEPS;

    /* Default error */
    *errmsg = "Remap table failure";

    if (verbosity >= 3) {
        syslog(LOG_INFO, "remap: input: %s", current);
    }

    for (ruleptr = rules; ruleptr; ruleptr = ruleptr->next) {
	if (ruleptr->rule_mode && ruleptr->rule_mode != mode)
            continue;           /* Rule not applicable, try next */

	if ((ruleptr->rule_flags & RULE_IPV4) && (af != AF_INET))
            continue;           /* Rule not applicable, try next */

	if ((ruleptr->rule_flags & RULE_IPV6) && (af != AF_INET6))
            continue;           /* Rule not applicable, try next */

        if (!deadman--) {
            syslog(LOG_WARNING,
                   "remap: Breaking loop, input = %s, last = %s", input,
                   current);
            free(current);
            return NULL;        /* Did not terminate! */
        }

        do {
            if (regexec(&ruleptr->rx, current, 10, pmatch, 0) ==
                (ruleptr->rule_flags & RULE_INVERSE ? REG_NOMATCH : 0)) {
                /* Match on this rule */
                was_match = 1;

                if (ruleptr->rule_flags & RULE_INVERSE) {
                    /* No actual match, so clear out the pmatch array */
                    int i;
                    for (i = 0; i < 10; i++)
                        pmatch[i].rm_so = pmatch[i].rm_eo = -1;
                }

                if (ruleptr->rule_flags & RULE_ABORT) {
                    if (verbosity >= 3) {
                        syslog(LOG_INFO, "remap: rule %d: abort: %s",
                               ruleptr->nrule, current);
                    }
                    if (ruleptr->pattern[0]) {
                        /* Custom error message */
                        len =
                            genmatchstring(NULL, ruleptr->pattern, current,
                                           pmatch, macrosub);
                        newstr = tfmalloc(len + 1);
                        genmatchstring(newstr, ruleptr->pattern, current,
                                       pmatch, macrosub);
                        *errmsg = newstr;
                    } else {
                        *errmsg = NULL;
                    }
                    free(current);
                    return (NULL);
                }

                if (ruleptr->rule_flags & RULE_REWRITE) {
                    len = genmatchstring(NULL, ruleptr->pattern, current,
                                         pmatch, macrosub);
                    newstr = tfmalloc(len + 1);
                    genmatchstring(newstr, ruleptr->pattern, current,
                                   pmatch, macrosub);
                    free(current);
                    current = newstr;
                    if (verbosity >= 3) {
                        syslog(LOG_INFO, "remap: rule %d: rewrite: %s",
                               ruleptr->nrule, current);
                    }
                }
            } else {
                break;          /* No match, terminate unconditionally */
            }
            /* If the rule is global, keep going until no match */
        } while (ruleptr->rule_flags & RULE_GLOBAL);

        if (was_match) {
            was_match = 0;

            if (ruleptr->rule_flags & RULE_EXIT) {
                if (verbosity >= 3) {
                    syslog(LOG_INFO, "remap: rule %d: exit",
                           ruleptr->nrule);
                }
                return current; /* Exit here, we're done */
            } else if (ruleptr->rule_flags & RULE_RESTART) {
                ruleptr = rules;        /* Start from the top */
                if (verbosity >= 3) {
                    syslog(LOG_INFO, "remap: rule %d: restart",
                           ruleptr->nrule);
                }
            }
        }
    }

    if (verbosity >= 3) {
        syslog(LOG_INFO, "remap: done");
    }
    return current;
}