Debian Codegraph @

contrib/mod_rewrite.c

raw symbols SCIP
1 /*
2 * ProFTPD: mod_rewrite -- a module for rewriting FTP commands
3 * Copyright (c) 2001-2026 TJ Saunders
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA.
18 *
19 * As a special exemption, TJ Saunders gives permission to link this program
20 * with OpenSSL, and distribute the resulting executable, without including
21 * the source code for OpenSSL in the source distribution.
22 *
23 * This is mod_rewrite, contrib software for proftpd 1.2 and above.
24 * For more information contact TJ Saunders <[email protected]>.
25 */
26
27 #include "conf.h"
28 #include "privs.h"
29
30 #if defined(HAVE_IDNA_H)
31 # include <idna.h>
32 #endif /* HAVE_IDNA_H */
33
34 #if defined(HAVE_IDN2_H)
35 # include <idn2.h>
36 #endif /* HAVE_IDN2_H */
37
38 #define MOD_REWRITE_VERSION "mod_rewrite/1.2"
39
40 /* Make sure the version of proftpd is as necessary. */
41 #if PROFTPD_VERSION_NUMBER < 0x0001030701
42 # error "ProFTPD 1.3.7rc1 or later required"
43 #endif
44
45 #ifdef PR_USE_REGEX
46
47 #define REWRITE_FIFO_MAXLEN 256
48 #define REWRITE_LOG_MODE 0640
49 #define REWRITE_MAX_MATCHES 10
50 #define REWRITE_U32_BITS 0xffffffff
51
52 /* RewriteCondition operations */
53 typedef enum {
54 REWRITE_COND_OP_REGEX = 1,
55 REWRITE_COND_OP_LEX_LT,
56 REWRITE_COND_OP_LEX_GT,
57 REWRITE_COND_OP_LEX_EQ,
58 REWRITE_COND_OP_TEST_DIR,
59 REWRITE_COND_OP_TEST_FILE,
60 REWRITE_COND_OP_TEST_SYMLINK,
61 REWRITE_COND_OP_TEST_SIZE
62 } rewrite_cond_op_t;
63
64 /* RewriteCondition flags */
65 #define REWRITE_COND_FLAG_NOCASE 0x001 /* nocase|NC */
66 #define REWRITE_COND_FLAG_ORNEXT 0x002 /* ornext|OR */
67
68 /* RewriteRule flags */
69 #define REWRITE_RULE_FLAG_NOCASE 0x001 /* nocase|NC */
70 #define REWRITE_RULE_FLAG_LAST 0x002 /* last|L */
71
72 /* Module structures */
73 typedef struct {
74 pool *map_pool;
75 char *map_name;
76 char *map_lookup_key;
77 char *map_default_value;
78 void *map_string;
79 } rewrite_map_t;
80
81 typedef struct {
82 char *match_string;
83 regmatch_t match_groups[REWRITE_MAX_MATCHES];
84 } rewrite_match_t;
85
86 typedef struct {
87 pool *txt_pool;
88 char *txt_path;
89 time_t txt_mtime;
90 char **txt_keys;
91 char **txt_values;
92 unsigned int txt_nents;
93 } rewrite_map_txt_t;
94
95 module rewrite_module;
96
97 /* Module variables */
98 static unsigned char rewrite_engine = FALSE;
99 static char *rewrite_logfile = NULL;
100 static int rewrite_logfd = -1;
101 static pool *rewrite_pool = NULL;
102 static pool *rewrite_cond_pool = NULL;
103
104 static unsigned int rewrite_nrules = 0;
105 static array_header *rewrite_conds = NULL;
106 static rewrite_match_t rewrite_cond_matches;
107 static rewrite_match_t rewrite_rule_matches;
108
109 static unsigned int rewrite_max_replace = PR_STR_MAX_REPLACEMENTS;
110
111 static const char *trace_channel = "rewrite";
112
113 #define REWRITE_MAX_VARS 23
114
115 static char rewrite_vars[REWRITE_MAX_VARS][13] = {
116 "%a", /* Remote IP address */
117 "%c", /* Session class */
118 "%F", /* Full path */
119 "%f", /* Filename */
120 "%G", /* Additional groups */
121 "%g", /* Primary group */
122 "%h", /* Remote DNS name */
123 "%m", /* FTP command (e.g. USER, RETR) */
124 "%P", /* Current PID */
125 "%p", /* Local port */
126 "%t", /* Unix time */
127 "%U", /* Original username */
128 "%u", /* Resolved/real username */
129 "%v", /* Server name */
130 "%w", /* Rename from (whence) */
131 "%{TIME}", /* Timestamp: YYYYMMDDHHmmss */
132 "%{TIME_YEAR}", /* Year: YYYY */
133 "%{TIME_MON}", /* Month: MM (1-12) */
134 "%{TIME_DAY}", /* Day: DD (1-31, depending on month) */
135 "%{TIME_WDAY}", /* Week day: 0-6, 0 = Sunday */
136 "%{TIME_HOUR}", /* Hour: HH (0-23) */
137 "%{TIME_MIN}", /* Minute: mm (0-59) */
138 "%{TIME_SEC}" /* Second: ss (0-60) */
139 };
140
141 /* Necessary prototypes */
142 static char *rewrite_argsep(char **);
143 static void rewrite_closelog(void);
144 static const char *rewrite_expand_var(cmd_rec *, const char *, const char *);
145 static const char *rewrite_get_cmd_name(cmd_rec *);
146 static void rewrite_log(char *format, ...);
147 static unsigned char rewrite_match_cond(cmd_rec *, config_rec *);
148 static void rewrite_openlog(void);
149 static int rewrite_open_fifo(config_rec *);
150 static unsigned int rewrite_parse_cond_flags(pool *, const char *);
151 static unsigned char rewrite_parse_map_str(char *, rewrite_map_t *);
152 static unsigned char rewrite_parse_map_txt(rewrite_map_txt_t *);
153 static unsigned int rewrite_parse_rule_flags(pool *, const char *);
154 static int rewrite_read_fifo(int, char *, size_t);
155 static unsigned char rewrite_regexec(const char *, pr_regex_t *, unsigned char,
156 rewrite_match_t *);
157 static void rewrite_replace_cmd_arg(cmd_rec *, char *);
158 static int rewrite_sess_init(void);
159 static const char *rewrite_subst(cmd_rec *c, const char *);
160 static const char *rewrite_subst_backrefs(cmd_rec *, const char *,
161 rewrite_match_t *);
162 static const char *rewrite_subst_env(cmd_rec *, const char *);
163 static const char *rewrite_subst_maps(cmd_rec *, const char *);
164 static const char *rewrite_subst_maps_fifo(cmd_rec *, config_rec *,
165 rewrite_map_t *);
166 static const char *rewrite_subst_maps_int(cmd_rec *, config_rec *,
167 rewrite_map_t *);
168 static const char *rewrite_subst_maps_txt(cmd_rec *, config_rec *,
169 rewrite_map_t *);
170 static const char *rewrite_subst_vars(cmd_rec *, const char *);
171 static void rewrite_wait_fifo(int);
172 static int rewrite_write_fifo(int, char *, size_t);
173
174 /* Support functions
175 */
176
177 #define REWRITE_CHECK_VAR(p, m) \
178 if (p == NULL) rewrite_log("rewrite_expand_var(): %" m " expands to NULL")
179
180 static const char *rewrite_expand_var(cmd_rec *cmd, const char *subst_pattern,
181 const char *var) {
182 size_t varlen;
183
184 varlen = strlen(var);
185
186 if (strncmp(var, "%c", 3) == 0) {
187 REWRITE_CHECK_VAR(session.conn_class, "%c");
188 return (session.conn_class ? session.conn_class->cls_name : NULL);
189
190 } else if (strncmp(var, "%F", 3) == 0) {
191 const char *cmd_name;
192
193 cmd_name = rewrite_get_cmd_name(cmd);
194
195 /* This variable is only valid for commands that operate on paths.
196 * mod_log uses the session.xfer.xfer_path variable, but that is not yet
197 * set at this stage in the command dispatch cycle.
198 */
199 if (pr_cmd_cmp(cmd, PR_CMD_APPE_ID) == 0 ||
200 pr_cmd_cmp(cmd, PR_CMD_RETR_ID) == 0 ||
201 pr_cmd_cmp(cmd, PR_CMD_STOR_ID) == 0 ||
202 pr_cmd_cmp(cmd, PR_CMD_DELE_ID) == 0 ||
203 pr_cmd_cmp(cmd, PR_CMD_MKD_ID) == 0 ||
204 pr_cmd_cmp(cmd, PR_CMD_MDTM_ID) == 0 ||
205 pr_cmd_cmp(cmd, PR_CMD_RMD_ID) == 0 ||
206 pr_cmd_cmp(cmd, PR_CMD_SIZE_ID) == 0 ||
207 pr_cmd_cmp(cmd, PR_CMD_STOU_ID) == 0 ||
208 pr_cmd_cmp(cmd, PR_CMD_XMKD_ID) == 0 ||
209 pr_cmd_cmp(cmd, PR_CMD_XRMD_ID) == 0) {
210 return dir_abs_path(cmd->tmp_pool, cmd->arg, FALSE);
211
212 } else if (cmd->argc >= 3 &&
213 (strcasecmp(cmd_name, "SITE CHGRP") == 0 ||
214 strcasecmp(cmd_name, "SITE CHMOD") == 0)) {
215 register unsigned int i;
216 char *tmp = "";
217
218 for (i = 2; i <= cmd->argc-1; i++) {
219 tmp = pstrcat(cmd->tmp_pool, tmp, *tmp ? " " : "", cmd->argv[i], NULL);
220 }
221
222 return dir_abs_path(cmd->tmp_pool, tmp, FALSE);
223
224 } else {
225 rewrite_log("rewrite_expand_var(): %%F not valid for this command ('%s')",
226 cmd_name);
227 return NULL;
228 }
229
230 } else if (strncmp(var, "%f", 3) == 0) {
231 REWRITE_CHECK_VAR(cmd->arg, "%f");
232 return cmd->arg;
233
234 } else if (strncmp(var, "%m", 3) == 0) {
235 return rewrite_get_cmd_name(cmd);
236
237 } else if (strncmp(var, "%p", 3) == 0) {
238 char *port = pcalloc(cmd->tmp_pool, 8 * sizeof(char));
239 pr_snprintf(port, 8, "%d", main_server->ServerPort);
240 port[7] = '\0';
241 return port;
242
243 } else if (strncmp(var, "%U", 3) == 0) {
244 return pr_table_get(session.notes, "mod_auth.orig-user", NULL);
245
246 } else if (strncmp(var, "%P", 3) == 0) {
247 char *pid = pcalloc(cmd->tmp_pool, 8 * sizeof(char));
248 pr_snprintf(pid, 8, "%lu", (unsigned long) getpid());
249 pid[7] = '\0';
250 return pid;
251
252 } else if (strncmp(var, "%g", 3) == 0) {
253 REWRITE_CHECK_VAR(session.group, "%g");
254 return session.group;
255
256 } else if (strncmp(var, "%u", 3) == 0) {
257 REWRITE_CHECK_VAR(session.user, "%u");
258 return session.user;
259
260 } else if (strncmp(var, "%a", 3) == 0) {
261 return pr_netaddr_get_ipstr(session.c->remote_addr);
262
263 } else if (strncmp(var, "%h", 3) == 0) {
264 return session.c->remote_name;
265
266 } else if (strncmp(var, "%v", 3) == 0) {
267 return main_server->ServerName;
268
269 } else if (strncmp(var, "%G", 3) == 0) {
270
271 if (session.groups != NULL) {
272 register unsigned int i = 0;
273 const char *suppl_groups;
274 char **groups;
275
276 suppl_groups = pstrcat(cmd->tmp_pool, "", NULL);
277
278 groups = (char **) session.groups->elts;
279 for (i = 0; i < session.groups->nelts; i++) {
280 suppl_groups = pstrcat(cmd->tmp_pool, suppl_groups,
281 i != 0 ? "," : "", groups[i], NULL);
282 }
283
284 return suppl_groups;
285
286 } else {
287 REWRITE_CHECK_VAR(session.groups, "%G");
288 return NULL;
289 }
290
291 } else if (strncmp(var, "%w", 3) == 0) {
292
293 if (pr_cmd_cmp(cmd, PR_CMD_RNTO_ID) == 0) {
294 return pr_table_get(session.notes, "mod_core.rnfr-path", NULL);
295
296 } else {
297 const char *cmd_name;
298
299 cmd_name = rewrite_get_cmd_name(cmd);
300 rewrite_log("rewrite_expand_var(): %%w not valid for this command ('%s')",
301 cmd_name);
302 return NULL;
303 }
304
305 } else if (strncmp(var, "%t", 3) == 0) {
306 char *timestr = pcalloc(cmd->tmp_pool, 80 * sizeof(char));
307 pr_snprintf(timestr, 80, "%lu", (unsigned long) time(NULL));
308 timestr[79] = '\0';
309 return timestr;
310
311 } else if (varlen > 7 &&
312 strncmp(var, "%{ENV:", 6) == 0 &&
313 var[varlen-1] == '}') {
314 char *env, *str;
315
316 str = pstrdup(cmd->tmp_pool, var);
317 str[varlen-1] = '\0';
318
319 env = pr_env_get(cmd->tmp_pool, str + 6);
320 return env ? pstrdup(cmd->tmp_pool, env) : "";
321
322 } else if (varlen >= 7 &&
323 strncmp(var, "%{TIME", 6) == 0 &&
324 var[varlen-1] == '}') {
325 char time_str[32];
326 time_t now;
327 struct tm *tm;
328
329 /* Always use localtime(3) here. */
330 time(&now);
331 memset(time_str, '\0', sizeof(time_str));
332
333 tm = pr_localtime(cmd->tmp_pool, &now);
334 if (tm != NULL) {
335 if (varlen == 7) {
336 /* %{TIME} */
337 pr_snprintf(time_str, sizeof(time_str)-1, "%04d%02d%02d%02d%02d%02d",
338 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour,
339 tm->tm_min, tm->tm_sec);
340
341 } else {
342 switch (var[7]) {
343 case 'D':
344 /* %{TIME_DAY} */
345 pr_snprintf(time_str, sizeof(time_str)-1, "%02d", tm->tm_mday);
346 break;
347
348 case 'H':
349 /* %{TIME_HOUR} */
350 pr_snprintf(time_str, sizeof(time_str)-1, "%02d", tm->tm_hour);
351 break;
352
353 case 'M':
354 if (var[8] == 'I') {
355 /* %{TIME_MIN} */
356 pr_snprintf(time_str, sizeof(time_str)-1, "%02d", tm->tm_min);
357
358 } else if (var[8] == 'O') {
359 /* %{TIME_MON} */
360 pr_snprintf(time_str, sizeof(time_str)-1, "%02d", tm->tm_mon + 1);
361 }
362 break;
363
364 case 'S':
365 /* %{TIME_SEC} */
366 pr_snprintf(time_str, sizeof(time_str)-1, "%02d", tm->tm_sec);
367 break;
368
369 case 'W':
370 /* %{TIME_WDAY} */
371 pr_snprintf(time_str, sizeof(time_str)-1, "%02d", tm->tm_wday);
372 break;
373
374 case 'Y':
375 /* %{TIME_YEAR} */
376 pr_snprintf(time_str, sizeof(time_str)-1, "%04d",
377 tm->tm_year + 1900);
378 break;
379
380 default:
381 rewrite_log("unknown variable: '%s'", var);
382 return NULL;
383 }
384 }
385 }
386
387 return pstrdup(cmd->tmp_pool, time_str);
388
389 } else {
390 pr_trace_msg(trace_channel, 1, "error obtaining local timestamp: %s",
391 strerror(errno));
392 }
393
394 rewrite_log("unknown variable: '%s'", var);
395 return NULL;
396 }
397
398 static char *rewrite_argsep(char **arg) {
399 char *res = NULL, *dst = NULL;
400 char quote_mode = 0;
401
402 if (!arg || !*arg || !**arg)
403 return NULL;
404
405 while (**arg && PR_ISSPACE(**arg)) {
406 (*arg)++;
407 }
408
409 if (!**arg)
410 return NULL;
411
412 res = dst = *arg;
413
414 if (**arg == '\"') {
415 quote_mode++;
416 (*arg)++;
417 }
418
419 while (**arg && **arg != ',' &&
420 (quote_mode ? (**arg != '\"') : (!PR_ISSPACE(**arg)))) {
421
422 if (**arg == '\\' && quote_mode) {
423
424 /* escaped char */
425 if (*((*arg) + 1))
426 *dst = *(++(*arg));
427 }
428
429 *dst++ = **arg;
430 ++(*arg);
431 }
432
433 if (**arg)
434 (*arg)++;
435
436 *dst = '\0';
437 return res;
438 }
439
440 static const char *rewrite_get_cmd_name(cmd_rec *cmd) {
441 if (pr_cmd_cmp(cmd, PR_CMD_SITE_ID) != 0) {
442 return cmd->argv[0];
443 }
444
445 if (strcasecmp(cmd->argv[1], "CHGRP") == 0 ||
446 strcasecmp(cmd->argv[1], "CHMOD") == 0) {
447 return pstrcat(cmd->pool, cmd->argv[0], " ", cmd->argv[1], NULL);
448 }
449
450 return cmd->argv[0];
451 }
452
453 static unsigned int rewrite_parse_cond_flags(pool *p, const char *flags_str) {
454 char *opt = NULL, *str = NULL, **opts;
455 array_header *opt_list = NULL;
456 unsigned int flags = 0;
457 register unsigned int i = 0;
458
459 opt_list = make_array(p, 0, sizeof(char **));
460
461 /* Make a duplicate of the given string, as the argsep() function consumes
462 * the string.
463 */
464 str = pstrdup(p, flags_str);
465
466 /* Skip past the first [ in the string, and trim the last ]. */
467 str++;
468 str[strlen(str)-1] = '\0';
469
470 while ((opt = rewrite_argsep(&str)) != NULL)
471 *((char **) push_array(opt_list)) = pstrdup(p, opt);
472
473 opts = opt_list->elts;
474 for (i = 0; i < opt_list->nelts; i++) {
475 if (strcmp(opts[i], "nocase") == 0 ||
476 strcmp(opts[i], "NC") == 0) {
477 flags |= REWRITE_COND_FLAG_NOCASE;
478
479 } else if (strcmp(opts[i], "ornext") == 0 ||
480 strcmp(opts[i], "OR") == 0) {
481 flags |= REWRITE_COND_FLAG_ORNEXT;
482 }
483 }
484
485 return flags;
486 }
487
488 static unsigned int rewrite_parse_rule_flags(pool *p, const char *flags_str) {
489 char *opt = NULL, *str = NULL, **opts;
490 array_header *opt_list = NULL;
491 unsigned int flags = 0;
492 register unsigned int i = 0;
493
494 opt_list = make_array(p, 0, sizeof(char **));
495
496 /* Make a duplicate of the given string, as the argsep() function consumes
497 * the string.
498 */
499 str = pstrdup(p, flags_str);
500
501 /* Skip past the first [ in the string, and trim the last ]. */
502 str++;
503 str[strlen(str)-1] = '\0';
504
505 while ((opt = rewrite_argsep(&str)) != NULL)
506 *((char **) push_array(opt_list)) = pstrdup(p, opt);
507
508 opts = opt_list->elts;
509 for (i = 0; i < opt_list->nelts; i++) {
510 if (strcmp(opts[i], "nocase") == 0 ||
511 strcmp(opts[i], "NC") == 0) {
512 flags |= REWRITE_RULE_FLAG_NOCASE;
513
514 } else if (strcmp(opts[i], "last") == 0 ||
515 strcmp(opts[i], "L") == 0) {
516 flags |= REWRITE_RULE_FLAG_LAST;
517 }
518 }
519
520 return flags;
521 }
522
523 static unsigned char rewrite_match_cond(cmd_rec *cmd, config_rec *cond) {
524 const char *cond_str = cond->argv[0];
525 unsigned char negated = *((unsigned char *) cond->argv[2]);
526 rewrite_cond_op_t cond_op = *((rewrite_cond_op_t *) cond->argv[3]);
527
528 rewrite_log("rewrite_match_cond(): original cond: '%s'", cond_str);
529
530 cond_str = rewrite_subst(cmd, cond->argv[0]);
531 rewrite_log("rewrite_match_cond: subst'd cond: '%s'", cond_str);
532
533 /* Check the condition */
534 switch (cond_op) {
535 case REWRITE_COND_OP_LEX_LT: {
536 int res;
537
538 res = strcmp(cond_str, (char *) cond->argv[1]);
539 rewrite_log("rewrite_match_cond(): checked lexical LT cond: %s > %s: %d",
540 cond_str, (char *) cond->argv[1], res);
541
542 if (!negated) {
543 return (res < 0 ? TRUE : FALSE);
544
545 } else {
546 return (res < 0 ? FALSE : TRUE);
547 }
548 }
549
550 case REWRITE_COND_OP_LEX_GT: {
551 int res;
552
553 res = strcmp(cond_str, (char *) cond->argv[1]);
554 rewrite_log("rewrite_match_cond(): checked lexical GT cond: %s < %s: %d",
555 cond_str, (char *) cond->argv[1], res);
556
557 if (!negated) {
558 return (res > 0 ? TRUE : FALSE);
559
560 } else {
561 return (res > 0 ? FALSE : TRUE);
562 }
563 }
564
565 case REWRITE_COND_OP_LEX_EQ: {
566 int res;
567
568 res = strcmp(cond_str, (char *) cond->argv[1]);
569 rewrite_log("rewrite_match_cond(): checked lexical EQ cond: %s == %s: %d",
570 cond_str, (char *) cond->argv[1], res);
571
572 if (!negated) {
573 return (res == 0 ? TRUE : FALSE);
574
575 } else {
576 return (res == 0 ? FALSE : TRUE);
577 }
578 }
579
580 case REWRITE_COND_OP_REGEX: {
581 rewrite_log("rewrite_match_cond(): checking regex cond against '%s'",
582 cond_str);
583
584 memset(&rewrite_cond_matches, '\0', sizeof(rewrite_cond_matches));
585 rewrite_cond_matches.match_string = (char *) cond_str;
586 return rewrite_regexec(cond_str, cond->argv[1], negated,
587 &rewrite_cond_matches);
588 }
589
590 case REWRITE_COND_OP_TEST_DIR: {
591 int res = FALSE;
592 struct stat st;
593 rewrite_log("rewrite_match_cond(): checking dir test cond against "
594 "path '%s'", cond_str);
595
596 pr_fs_clear_cache2(cond_str);
597 if (pr_fsio_lstat(cond_str, &st) >= 0 &&
598 S_ISDIR(st.st_mode)) {
599 res = TRUE;
600 }
601
602 if (!negated)
603 return res;
604 else
605 return (res == TRUE ? FALSE : TRUE);
606 }
607
608 case REWRITE_COND_OP_TEST_FILE: {
609 int res = FALSE;
610 struct stat st;
611 rewrite_log("rewrite_match_cond(): checking file test cond against "
612 "path '%s'", cond_str);
613
614 pr_fs_clear_cache2(cond_str);
615 if (pr_fsio_lstat(cond_str, &st) >= 0 &&
616 S_ISREG(st.st_mode)) {
617 res = TRUE;
618 }
619
620 if (!negated)
621 return res;
622 else
623 return (res == TRUE ? FALSE : TRUE);
624 }
625
626 case REWRITE_COND_OP_TEST_SYMLINK: {
627 int res = FALSE;
628 struct stat st;
629 rewrite_log("rewrite_match_cond(): checking symlink test cond against "
630 "path '%s'", cond_str);
631
632 pr_fs_clear_cache2(cond_str);
633 if (pr_fsio_lstat(cond_str, &st) >= 0 &&
634 S_ISLNK(st.st_mode)) {
635 res = TRUE;
636 }
637
638 if (!negated)
639 return res;
640 else
641 return (res == TRUE ? FALSE : TRUE);
642 }
643
644 case REWRITE_COND_OP_TEST_SIZE: {
645 int res = FALSE;
646 struct stat st;
647 rewrite_log("rewrite_match_cond(): checking size test cond against "
648 "path '%s'", cond_str);
649
650 pr_fs_clear_cache2(cond_str);
651 if (pr_fsio_lstat(cond_str, &st) >= 0 &&
652 S_ISREG(st.st_mode) &&
653 st.st_size > 0) {
654 res = TRUE;
655 }
656
657 if (!negated)
658 return res;
659 else
660 return (res == TRUE ? FALSE : TRUE);
661 }
662
663 default:
664 rewrite_log("rewrite_match_cond(): unknown cond op: %d", cond_op);
665 break;
666 }
667
668 return FALSE;
669 }
670
671 static unsigned char rewrite_parse_map_str(char *str, rewrite_map_t *map) {
672 static char *substr = NULL;
673 char *ptr = NULL;
674
675 /* A NULL string is used to set/reset this function. */
676 if (str == NULL) {
677 substr = NULL;
678 return FALSE;
679 }
680
681 if (substr == NULL) {
682 substr = str;
683 }
684
685 /* Format: ${map-name:lookup-key[|default-value]} */
686 rewrite_log("rewrite_parse_map_str(): parsing '%s'", substr);
687 if (substr != NULL &&
688 (ptr = strstr(substr, "${")) != NULL) {
689 char twiddle;
690 char *map_start = ptr + 2;
691 char *map_end = strchr(map_start, '}');
692
693 if (!map_end) {
694 rewrite_log("rewrite_parse_mapstr(): error: badly formatted map string");
695 return FALSE;
696 }
697
698 /* This fiddling is needed to preserve a copy of the complete map string. */
699 twiddle = map_end[1];
700 map_end[1] = '\0';
701 map->map_string = pstrdup(map->map_pool, ptr);
702 map_end[1] = twiddle;
703
704 /* OK, now back to our regular schedule parsing... */
705 *map_end = '\0';
706
707 ptr = strchr(map_start, ':');
708 if (ptr == NULL) {
709 rewrite_log("rewrite_parse_mapstr(): notice: badly formatted map string");
710 return FALSE;
711 }
712 *ptr = '\0';
713
714 /* We've teased out the map name. */
715 map->map_name = map_start;
716
717 /* Advance the pointer so that the rest of the components can be parsed. */
718 map_start = ++ptr;
719
720 map->map_lookup_key = map_start;
721
722 ptr = strchr(map_start, '|');
723 if (ptr != NULL) {
724 *ptr = '\0';
725
726 /* We've got the default value. */
727 map->map_default_value = ++ptr;
728
729 } else {
730 map->map_default_value = "";
731 }
732
733 substr = ++map_end;
734 return TRUE;
735 }
736
737 return FALSE;
738 }
739
740 static unsigned char rewrite_parse_map_txt(rewrite_map_txt_t *txtmap) {
741 struct stat st;
742 pool *tmp_pool = NULL;
743 char *linebuf = NULL;
744 array_header *keys = NULL, *vals = NULL;
745 unsigned int lineno = 0, i = 0;
746 pr_fh_t *ftxt = NULL;
747
748 /* Make sure the file exists. */
749 if (pr_fsio_stat(txtmap->txt_path, &st) < 0) {
750 rewrite_log("rewrite_parse_map_txt(): unable to stat %s: %s",
751 txtmap->txt_path, strerror(errno));
752 return FALSE;
753 }
754
755 if (S_ISDIR(st.st_mode)) {
756 errno = EISDIR;
757 rewrite_log("rewrite_parse_map_txt(): unable to use %s: %s",
758 txtmap->txt_path, strerror(errno));
759 return FALSE;
760 }
761
762 /* Compare the modification time of the file against what's cached. Unless
763 * the file is newer, do not parse it in again.
764 */
765 if (st.st_mtime <= txtmap->txt_mtime) {
766 rewrite_log("rewrite_parse_map_txt(): cached map cache up to date");
767 return TRUE;
768 }
769
770 /* Open the file. */
771 ftxt = pr_fsio_open(txtmap->txt_path, O_RDONLY);
772 if (ftxt == NULL) {
773 rewrite_log("rewrite_parse_map_txt(): unable to open %s: %s",
774 txtmap->txt_path, strerror(errno));
775 return FALSE;
776 }
777
778 /* Populate the optimal file IO size hint. */
779 ftxt->fh_iosz = st.st_blksize;
780
781 txtmap->txt_mtime = st.st_mtime;
782
783 tmp_pool = make_sub_pool(txtmap->txt_pool);
784 linebuf = pcalloc(tmp_pool, PR_TUNABLE_BUFFER_SIZE * sizeof(char));
785 keys = make_array(tmp_pool, 0, sizeof(char *));
786 vals = make_array(tmp_pool, 0, sizeof(char *));
787
788 while (pr_fsio_getline(linebuf, PR_TUNABLE_BUFFER_SIZE, ftxt, &i)) {
789 register unsigned int pos = 0;
790 size_t linelen = strlen(linebuf);
791 unsigned int key_so = 0, key_eo = 0;
792 unsigned int val_so = 0, val_eo = 0;
793
794 pr_signals_handle();
795
796 /* Skip leading whitespace. */
797 for (pos = 0; pos < linelen && PR_ISSPACE(linebuf[pos]); pos++);
798
799 /* Ignore comments and blank lines. */
800 if (linebuf[pos] == '#') {
801 continue;
802 }
803
804 if (pos == linelen) {
805 continue;
806 }
807
808 /* Only parse the first two non-whitespace strings. Ignore everything
809 * else.
810 */
811 key_so = pos;
812 for (; pos < linelen; pos++) {
813
814 if (PR_ISSPACE(linebuf[pos])) {
815 if (!key_eo) {
816 key_eo = pos;
817
818 } else if (val_so && !val_eo) {
819 val_eo = pos;
820 break;
821 }
822
823 } else {
824 if (key_eo && !val_so) {
825 val_so = pos;
826 }
827 }
828 }
829
830 if (key_eo && val_eo) {
831 linebuf[key_eo] = '\0';
832 *((char **) push_array(keys)) = pstrdup(txtmap->txt_pool,
833 &linebuf[key_so]);
834
835 linebuf[val_eo] = '\0';
836 *((char **) push_array(vals)) = pstrdup(txtmap->txt_pool,
837 &linebuf[val_so]);
838
839 } else {
840 rewrite_log("rewrite_parse_map_txt(): error: %s, line %d",
841 txtmap->txt_path, lineno);
842 rewrite_log("rewrite_parse_map_txt(): bad line: '%s'", linebuf);
843 }
844 }
845
846 txtmap->txt_keys = (char **) pcalloc(txtmap->txt_pool,
847 keys->nelts * sizeof(char *));
848 for (i = 0; i < keys->nelts; i++) {
849 txtmap->txt_keys[i] = ((char **) keys->elts)[i];
850 }
851
852 txtmap->txt_values = (char **) pcalloc(txtmap->txt_pool,
853 vals->nelts * sizeof(char *));
854 for (i = 0; i < vals->nelts; i++) {
855 txtmap->txt_values[i] = ((char **) vals->elts)[i];
856 }
857
858 txtmap->txt_nents = vals->nelts;
859
860 destroy_pool(tmp_pool);
861 pr_fsio_close(ftxt);
862 return TRUE;
863 }
864
865 static unsigned char rewrite_regexec(const char *string, pr_regex_t *pre,
866 unsigned char negated, rewrite_match_t *matches) {
867 int res = -1;
868 char *tmpstr = (char *) string;
869 unsigned char have_match = FALSE;
870
871 /* Sanity checks */
872 if (string == NULL ||
873 pre == NULL) {
874 return FALSE;
875 }
876
877 /* Prepare the given match group array. */
878 memset(matches->match_groups, '\0', sizeof(regmatch_t) * REWRITE_MAX_MATCHES);
879
880 /* Execute the given regex. */
881 while ((res = pr_regexp_exec(pre, tmpstr, REWRITE_MAX_MATCHES,
882 matches->match_groups, 0, 0, 0)) == 0) {
883 have_match = TRUE;
884 break;
885 }
886
887 /* Invert the return value if necessary. */
888 if (negated)
889 have_match = !have_match;
890
891 return have_match;
892 }
893
894 static void rewrite_replace_cmd_arg(cmd_rec *cmd, char *new_arg) {
895 if (pr_cmd_cmp(cmd, PR_CMD_SITE_ID) != 0) {
896 cmd->arg = new_arg;
897
898 } else {
899 if (strcasecmp(cmd->argv[1], "CHGRP") == 0 ||
900 strcasecmp(cmd->argv[1], "CHMOD") == 0) {
901 cmd->arg = pstrcat(cmd->pool, cmd->argv[1], " ", new_arg, NULL);
902
903 } else {
904 /* Not one of the handled SITE commands. */
905 cmd->arg = new_arg;
906 }
907 }
908 }
909
910 static const char *rewrite_subst(cmd_rec *cmd, const char *pattern) {
911 int have_cond_backrefs = FALSE;
912 const char *new_pattern = NULL;
913
914 rewrite_log("rewrite_subst(): original pattern: '%s'", pattern);
915
916 /* Before we do any substitution, check first to see if we have any
917 * RewriteCondition backreferences in the original pattern. Later
918 * substitutions may add sequences which look like RewriteCondition
919 * backreferences (e.g. the 'unescape' RewriteMap builtin function),
920 * we want to try to disambiguate these situations.
921 */
922 if (strchr(pattern, '%') != NULL) {
923 if (strstr(pattern, "%0") != NULL ||
924 strstr(pattern, "%1") != NULL ||
925 strstr(pattern, "%2") != NULL ||
926 strstr(pattern, "%3") != NULL ||
927 strstr(pattern, "%4") != NULL ||
928 strstr(pattern, "%5") != NULL ||
929 strstr(pattern, "%6") != NULL ||
930 strstr(pattern, "%7") != NULL ||
931 strstr(pattern, "%8") != NULL ||
932 strstr(pattern, "%9") != NULL) {
933
934 have_cond_backrefs = TRUE;
935 }
936 }
937
938 /* Expand any RewriteRule backreferences in the substitution pattern. */
939 new_pattern = rewrite_subst_backrefs(cmd, pattern, &rewrite_rule_matches);
940 rewrite_log("rewrite_subst(): rule backref subst'd pattern: '%s'",
941 new_pattern);
942
943 if (have_cond_backrefs) {
944 /* Expand any RewriteCondition backreferences in the substitution
945 * pattern.
946 */
947 new_pattern = rewrite_subst_backrefs(cmd, new_pattern,
948 &rewrite_cond_matches);
949 rewrite_log("rewrite_subst(): cond backref subst'd pattern: '%s'",
950 new_pattern);
951
952 } else {
953 rewrite_log("rewrite_subst(): pattern '%s' had no cond backrefs", pattern);
954 }
955
956 /* Next, rewrite the arg, substituting in the values. */
957 new_pattern = rewrite_subst_vars(cmd, new_pattern);
958 rewrite_log("rewrite_subst(): var subst'd pattern: '%s'", new_pattern);
959
960 /* Now, perform any map substitutions in the pattern. */
961 new_pattern = rewrite_subst_maps(cmd, new_pattern);
962 rewrite_log("rewrite_subst(): maps subst'd pattern: '%s'", new_pattern);
963
964 /* Expand any environment variables. */
965 new_pattern = rewrite_subst_env(cmd, new_pattern);
966 rewrite_log("rewrite_subst(): env subst'd pattern: '%s'", new_pattern);
967
968 return new_pattern;
969 }
970
971 static const char *rewrite_subst_backrefs(cmd_rec *cmd, const char *pattern,
972 rewrite_match_t *matches) {
973 register unsigned int i = 0;
974 const char *replacement_pattern = NULL;
975 int use_notes = TRUE;
976
977 /* We do NOT stash the backrefs in the cmd->notes table for sensitive
978 * data, e.g. PASS or ADAT commands.
979 */
980 if (pr_cmd_cmp(cmd, PR_CMD_PASS_ID) == 0 ||
981 pr_cmd_cmp(cmd, PR_CMD_ADAT_ID) == 0) {
982 use_notes = FALSE;
983 }
984
985 for (i = 0; i < REWRITE_MAX_MATCHES; i++) {
986 char buf[3] = {'\0'}, *ptr;
987
988 memset(buf, '\0', sizeof(buf));
989
990 if (matches == &rewrite_rule_matches) {
991 /* Substitute "$N" backreferences for RewriteRule matches */
992 pr_snprintf(buf, sizeof(buf), "$%u", i);
993
994 } else if (matches == &rewrite_cond_matches) {
995 /* Substitute "%N" backreferences for RewriteCondition matches */
996 pr_snprintf(buf, sizeof(buf), "%%%u", i);
997 }
998
999 if (replacement_pattern == NULL) {
1000 replacement_pattern = pstrdup(cmd->pool, pattern);
1001 }
1002
1003 /* Make sure there's a backreference for this in the substitution
1004 * pattern.
1005 */
1006 ptr = strstr(replacement_pattern, buf);
1007 if (ptr == NULL) {
1008
1009 /* Even if there is no backref in the substitution pattern, we
1010 * want to stash the backrefs in the cmd->notes table.
1011 */
1012 if (use_notes == TRUE &&
1013 matches->match_groups[i].rm_so != -1) {
1014 char *key, *value, tmp;
1015
1016 tmp = (matches->match_string)[matches->match_groups[i].rm_eo];
1017 (matches->match_string)[matches->match_groups[i].rm_eo] = '\0';
1018
1019 value = &(matches->match_string)[matches->match_groups[i].rm_so];
1020 key = pstrcat(cmd->pool, "mod_rewrite.", buf, NULL);
1021
1022 if (pr_table_add_dup(cmd->notes, key, value, 0) < 0) {
1023 /* Ignore dups. */
1024 if (errno != EEXIST) {
1025 pr_trace_msg(trace_channel, 3,
1026 "error stashing '%s' in cmd->notes: %s", key, strerror(errno));
1027 }
1028
1029 } else {
1030 pr_trace_msg(trace_channel, 9,
1031 "stashing value '%s' under key '%s' in cmd->notes", value, key);
1032 }
1033
1034 /* Undo the twiddling of the NUL character. */
1035 (matches->match_string)[matches->match_groups[i].rm_eo] = tmp;
1036 }
1037
1038 continue;
1039 }
1040
1041 /* Check for escaped backrefs. */
1042 if (ptr > replacement_pattern) {
1043 if (matches == &rewrite_rule_matches) {
1044 /* If the character before ptr is itself a '$', then this is
1045 * an escaped sequence and NOT a RewriteRule backref. For example,
1046 * it might be "$$1". In which case, silently replace the escaped
1047 * string with the literal string.
1048 */
1049 if (*(ptr - 1) == '$') {
1050 const char *res;
1051 char *var;
1052 size_t var_len = sizeof(buf) + 1;
1053
1054 var = pcalloc(cmd->tmp_pool, var_len);
1055 var[0] = '$';
1056 sstrcat(var, buf, var_len);
1057
1058 res = pr_str_replace(cmd->pool, rewrite_max_replace,
1059 replacement_pattern, var, buf, NULL);
1060 if (res == NULL) {
1061 pr_trace_msg(trace_channel, 3,
1062 "error replacing '%s' with '%s' in '%s': %s", var, buf,
1063 replacement_pattern, strerror(errno));
1064
1065 } else {
1066 replacement_pattern = res;
1067 }
1068
1069 continue;
1070 }
1071
1072 } else if (matches == &rewrite_cond_matches) {
1073 /* If the character before ptr is itself a '%', then this is
1074 * an escaped sequence and NOT a RewriteCondition backref. For example,
1075 * it might be "%%1". In which case, silently replace the escaped
1076 * string with the literal string.
1077 */
1078 if (*(ptr - 1) == '%') {
1079 const char *res;
1080 char *var;
1081 size_t var_len = sizeof(buf) + 1;
1082
1083 var = pcalloc(cmd->tmp_pool, var_len);
1084 var[0] = '%';
1085 sstrcat(var, buf, var_len);
1086
1087 res = pr_str_replace(cmd->pool, rewrite_max_replace,
1088 replacement_pattern, var, buf, NULL);
1089 if (res == NULL) {
1090 pr_trace_msg(trace_channel, 3,
1091 "error replacing '%s' with '%s' in '%s': %s", var, buf,
1092 replacement_pattern, strerror(errno));
1093
1094 } else {
1095 replacement_pattern = res;
1096 }
1097
1098 continue;
1099 }
1100 }
1101 }
1102
1103 if (matches->match_groups[i].rm_so != -1) {
1104 const char *res;
1105 char *value, tmp;
1106
1107 /* There's a match for the backref in the string, substitute in
1108 * the backreferenced value.
1109 */
1110
1111 tmp = (matches->match_string)[matches->match_groups[i].rm_eo];
1112 (matches->match_string)[matches->match_groups[i].rm_eo] = '\0';
1113
1114 value = &(matches->match_string)[matches->match_groups[i].rm_so];
1115
1116 rewrite_log("rewrite_subst_backrefs(): replacing backref '%s' with '%s'",
1117 buf, value);
1118
1119 if (use_notes) {
1120 char *key;
1121
1122 /* Stash the backref in the cmd->notes table, for use by other
1123 * modules, e.g. mod_sql.
1124 */
1125
1126 key = pstrcat(cmd->pool, "mod_rewrite.", buf, NULL);
1127
1128 if (pr_table_add_dup(cmd->notes, key, value, 0) < 0) {
1129 /* Ignore dups. */
1130 if (errno != EEXIST) {
1131 pr_trace_msg(trace_channel, 3,
1132 "error stashing '%s' in cmd->notes: %s", key, strerror(errno));
1133 }
1134
1135 } else {
1136 pr_trace_msg(trace_channel, 9,
1137 "stashing value '%s' under key '%s' in cmd->notes", value, key);
1138 }
1139 }
1140
1141 res = pr_str_replace(cmd->pool, rewrite_max_replace,
1142 replacement_pattern, buf, value, NULL);
1143 if (res == NULL) {
1144 pr_trace_msg(trace_channel, 3,
1145 "error replacing '%s' with '%s' in '%s': %s", buf, value,
1146 replacement_pattern, strerror(errno));
1147
1148 } else {
1149 replacement_pattern = res;
1150 }
1151
1152 /* Undo the twiddling of the NUL character. */
1153 (matches->match_string)[matches->match_groups[i].rm_eo] = tmp;
1154
1155 } else {
1156 const char *res;
1157
1158 /* There's backreference in the string, but there no matching
1159 * group (i.e. backreferenced value). Substitute in an empty string
1160 * for the backref.
1161 */
1162
1163 rewrite_log("rewrite_subst_backrefs(): replacing backref '%s' with "
1164 "empty string", buf);
1165
1166 if (use_notes) {
1167 char *key;
1168
1169 /* Stash the backref in the cmd->notes table, for use by other
1170 * modules, e.g. mod_sql.
1171 */
1172
1173 key = pstrcat(cmd->pool, "mod_rewrite.", buf, NULL);
1174
1175 if (pr_table_add_dup(cmd->notes, key, "", 0) < 0) {
1176 /* Ignore dups. */
1177 if (errno != EEXIST) {
1178 pr_trace_msg(trace_channel, 3,
1179 "error stashing '%s' in cmd->notes: %s", key, strerror(errno));
1180 }
1181
1182 } else {
1183 pr_trace_msg(trace_channel, 9,
1184 "stashing empty string under key '%s' in cmd->notes", key);
1185 }
1186 }
1187
1188 res = pr_str_replace(cmd->pool, rewrite_max_replace, replacement_pattern,
1189 buf, "", NULL);
1190 if (res == NULL) {
1191 pr_trace_msg(trace_channel, 3,
1192 "error replacing '%s' with '' in '%s': %s", buf,
1193 replacement_pattern, strerror(errno));
1194
1195 } else {
1196 replacement_pattern = res;
1197 }
1198 }
1199 }
1200
1201 return (replacement_pattern ? replacement_pattern : pattern);
1202 }
1203
1204 static const char *rewrite_subst_env(cmd_rec *cmd, const char *pattern) {
1205 const char *new_pattern = NULL;
1206 char *pat, *ptr;
1207
1208 /* We need to make a duplicate of the given pattern, since we twiddle some
1209 * of its bytes.
1210 */
1211 pat = pstrdup(cmd->tmp_pool, pattern);
1212
1213 ptr = strstr(pat, "%{ENV:");
1214 while (ptr != NULL) {
1215 const char *val, *res;
1216 char ch, *ptr2, *key;
1217
1218 pr_signals_handle();
1219
1220 ptr2 = strchr(ptr, '}');
1221 if (ptr2 == NULL) {
1222 break;
1223 }
1224
1225 ch = *(ptr2 + 1);
1226 *(ptr2 + 1) = '\0';
1227
1228 key = pstrdup(cmd->tmp_pool, ptr);
1229 *(ptr2 + 1) = ch;
1230
1231 val = rewrite_expand_var(cmd, pat, key);
1232 if (val != NULL) {
1233 rewrite_log("rewrite_subst_env(): replacing variable '%s' with '%s'",
1234 key, val);
1235
1236 if (new_pattern == NULL) {
1237 new_pattern = pstrdup(cmd->pool, pat);
1238 }
1239
1240 res = pr_str_replace(cmd->pool, rewrite_max_replace, new_pattern, key,
1241 val, NULL);
1242 if (res == NULL) {
1243 pr_trace_msg(trace_channel, 3,
1244 "error replacing '%s' with '%s' in '%s': %s", key, val, new_pattern,
1245 strerror(errno));
1246
1247 } else {
1248 new_pattern = res;
1249 }
1250 }
1251
1252 /* Look for the next environment variable to process. */
1253 ptr = strstr(ptr2 + 1, "%{ENV:");
1254 }
1255
1256 return (new_pattern ? new_pattern : pattern);
1257 }
1258
1259 static const char *rewrite_subst_maps(cmd_rec *cmd, const char *pattern) {
1260 rewrite_map_t map;
1261 const char *tmp_pattern, *new_pattern = NULL;
1262
1263 tmp_pattern = pstrdup(cmd->pool, pattern);
1264 map.map_pool = cmd->tmp_pool;
1265
1266 while (rewrite_parse_map_str((char *) tmp_pattern, &map)) {
1267 config_rec *c = NULL;
1268 unsigned char have_map = FALSE;
1269
1270 rewrite_log("rewrite_subst_maps(): map name: '%s'",
1271 map.map_name);
1272 rewrite_log("rewrite_subst_maps(): lookup key: '%s'",
1273 map.map_lookup_key);
1274 rewrite_log("rewrite_subst_maps(): default value: '%s'",
1275 map.map_default_value);
1276
1277 /* Check the configured maps for this server, to see if the given map
1278 * name is actually valid.
1279 */
1280 c = find_config(main_server->conf, CONF_PARAM, "RewriteMap", FALSE);
1281 while (c != NULL) {
1282 pr_signals_handle();
1283
1284 if (strcmp(c->argv[0], map.map_name) == 0) {
1285 const char *lookup_value = NULL, *res;
1286 have_map = TRUE;
1287
1288 rewrite_log("rewrite_subst_maps(): mapping '%s' using '%s'",
1289 map.map_lookup_key, map.map_name);
1290
1291 /* Handle FIFO maps */
1292 if (strcmp(c->argv[1], "fifo") == 0) {
1293 lookup_value = rewrite_subst_maps_fifo(cmd, c, &map);
1294 if (lookup_value != NULL) {
1295 rewrite_log("rewrite_subst_maps(): fifo map '%s' returned '%s'",
1296 map.map_name, lookup_value);
1297
1298 } else {
1299 rewrite_log("rewrite_subst_maps(): fifo map '%s' returned NULL: %s",
1300 map.map_name, strerror(errno));
1301 }
1302
1303 /* Handle maps of internal functions */
1304 } else if (strcmp(c->argv[1], "int") == 0) {
1305 lookup_value = rewrite_subst_maps_int(cmd, c, &map);
1306 if (lookup_value != NULL) {
1307 rewrite_log("rewrite_subst_maps(): internal map '%s' returned '%s'",
1308 map.map_name, lookup_value);
1309
1310 } else {
1311 rewrite_log("rewrite_subst_maps(): internal map '%s' "
1312 "returned NULL: %s", map.map_name, strerror(errno));
1313 }
1314
1315 /* Handle external file maps */
1316 } else if (strcmp(c->argv[1], "txt") == 0) {
1317 lookup_value = rewrite_subst_maps_txt(cmd, c, &map);
1318 if (lookup_value != NULL) {
1319 rewrite_log("rewrite_subst_maps(): txt map '%s' returned '%s'",
1320 map.map_name, lookup_value);
1321
1322 } else {
1323 rewrite_log("rewrite_subst_maps(): txt map '%s' returned NULL: %s",
1324 map.map_name, strerror(errno));
1325 }
1326 }
1327
1328 /* Substitute the looked-up value into the substitution pattern,
1329 * if indeed a map (and value) have been found.
1330 */
1331 if (lookup_value != NULL) {
1332 rewrite_log("rewrite_subst_maps(): substituting '%s' for '%s'",
1333 lookup_value, (char *) map.map_string);
1334
1335 if (new_pattern == NULL) {
1336 new_pattern = pstrdup(cmd->pool, pattern);
1337 }
1338
1339 res = pr_str_replace(cmd->pool, rewrite_max_replace, new_pattern,
1340 map.map_string, lookup_value, NULL);
1341 if (res == NULL) {
1342 pr_trace_msg(trace_channel, 3,
1343 "error replacing '%s' with '%s' in '%s': %s",
1344 (char *) map.map_string, lookup_value, new_pattern,
1345 strerror(errno));
1346
1347 } else {
1348 new_pattern = res;
1349 }
1350 }
1351 }
1352
1353 c = find_config_next(c, c->next, CONF_PARAM, "RewriteMap", FALSE);
1354 }
1355
1356 if (!have_map)
1357 rewrite_log("rewrite_subst_maps(): warning: no such RewriteMap '%s'",
1358 map.map_name);
1359 }
1360
1361 /* Don't forget to reset the parsing function when done. */
1362 rewrite_parse_map_str(NULL, NULL);
1363
1364 return (new_pattern ? new_pattern : pattern);
1365 }
1366
1367 static const char *rewrite_subst_maps_fifo(cmd_rec *cmd, config_rec *c,
1368 rewrite_map_t *map) {
1369 int fifo_fd = -1, fifo_lockfd = -1, res;
1370 char *value = NULL, *fifo_lockname = NULL;
1371 const char *fifo = (char *) c->argv[2];
1372 size_t map_lookup_keylen;
1373
1374 #ifndef HAVE_FLOCK
1375 struct flock lock;
1376 #endif /* HAVE_FLOCK */
1377
1378 /* The FIFO file descriptor should already be open. */
1379 fifo_fd = *((int *) c->argv[3]);
1380 if (fifo_fd == -1) {
1381 rewrite_log("rewrite_subst_maps_fifo(): missing necessary FIFO file "
1382 "descriptor");
1383 return map->map_default_value;
1384 }
1385
1386 /* No interruptions, please. */
1387 pr_signals_block();
1388
1389 /* See if a RewriteLock has been configured. */
1390 fifo_lockname = get_param_ptr(main_server->conf, "RewriteLock", FALSE);
1391 if (fifo_lockname != NULL) {
1392 /* Make sure the file exists. */
1393 fifo_lockfd = open(fifo_lockname, O_RDWR|O_CREAT, 0666);
1394 if (fifo_lockfd < 0) {
1395 rewrite_log("rewrite_subst_maps_fifo(): error creating '%s': %s",
1396 fifo_lockname, strerror(errno));
1397 }
1398 }
1399
1400 /* Obtain a write lock on the lock file, if configured */
1401 if (fifo_lockfd != -1) {
1402 #ifdef HAVE_FLOCK
1403 if (flock(fifo_lockfd, LOCK_EX) < 0) {
1404 rewrite_log("rewrite_subst_maps_fifo(): error obtaining lock: %s",
1405 strerror(errno));
1406 }
1407 #else
1408 lock.l_type = F_WRLCK;
1409 lock.l_whence = 0;
1410 lock.l_start = lock.l_len = 0;
1411
1412 while (fcntl(fifo_lockfd, F_SETLKW, &lock) < 0) {
1413 if (errno == EINTR) {
1414 pr_signals_handle();
1415 continue;
1416 }
1417
1418 rewrite_log("rewrite_subst_maps_fifo(): error obtaining lock: %s",
1419 strerror(errno));
1420 break;
1421 }
1422 #endif /* HAVE_FLOCK */
1423 }
1424
1425 /* Write the lookup key to the FIFO. There is no need to restrict the size
1426 * of data written to the FIFO to the PIPE_BUF length; the advisory lock on
1427 * the FIFO is used to coordinate I/O on the FIFO, which means that only one
1428 * child process will be talking to the FIFO at a given time, obviating the
1429 * possibility of interleaved reads/writes.
1430 *
1431 * Note that at present (1.2.6rc1), proftpd ignores SIGPIPE. For the most
1432 * part this is not a concern. However, when dealing with FIFOs, it can be:
1433 * a process that attempts to write to a FIFO that is not opened for reading
1434 * on the other side will receive a SIGPIPE from the kernel. The above
1435 * open()s try to prevent this case, but it can happen that the FIFO-reading
1436 * process might end after the writing file descriptor has been opened.
1437 * Hmmm.
1438 */
1439
1440 pr_signals_unblock();
1441 map_lookup_keylen = strlen(map->map_lookup_key);
1442 res = rewrite_write_fifo(fifo_fd,
1443 pstrcat(cmd->tmp_pool, map->map_lookup_key, "\n", NULL),
1444 map_lookup_keylen + 1);
1445 if ((size_t) res != (map_lookup_keylen + 1)) {
1446 rewrite_log("rewrite_subst_maps_fifo(): error writing lookup key '%s' to "
1447 "FIFO '%s': %s", map->map_lookup_key, fifo, strerror(errno));
1448
1449 if (fifo_lockfd != -1) {
1450 #ifdef HAVE_FLOCK
1451 if (flock(fifo_lockfd, LOCK_UN) < 0) {
1452 rewrite_log("rewrite_subst_maps_fifo(): error releasing lock: %s",
1453 strerror(errno));
1454 }
1455 #else
1456 lock.l_type = F_UNLCK;
1457 lock.l_whence = 0;
1458 lock.l_start = lock.l_len = 0;
1459
1460 while (fcntl(fifo_lockfd, F_SETLKW, &lock) < 0) {
1461 if (errno == EINTR) {
1462 pr_signals_handle();
1463 continue;
1464 }
1465
1466 rewrite_log("rewrite_subst_maps_fifo(): error releasing lock: %s",
1467 strerror(errno));
1468 break;
1469 }
1470 #endif /* HAVE_FLOCK */
1471
1472 (void) close(fifo_lockfd);
1473 }
1474
1475 /* Return the default value */
1476 return map->map_default_value;
1477 }
1478 pr_signals_block();
1479
1480 /* Make sure the data in the write buffer has been flushed into the FIFO. */
1481 if (fsync(fifo_fd) < 0) {
1482 rewrite_log("rewrite_subst_maps_fifo(): error flushing data to FIFO %d: %s",
1483 fifo_fd, strerror(errno));
1484 }
1485
1486 /* And make sure that the data has been read from the buffer by the other
1487 * end.
1488 */
1489 rewrite_wait_fifo(fifo_fd);
1490
1491 /* Allocate memory into which to read the lookup value. */
1492 value = pcalloc(cmd->pool, sizeof(char) * REWRITE_FIFO_MAXLEN);
1493
1494 /* Read the value from the FIFO, if any. Unblock signals before doing so. */
1495 pr_signals_unblock();
1496 res = rewrite_read_fifo(fifo_fd, value, REWRITE_FIFO_MAXLEN);
1497 if (res <= 0) {
1498 if (res < 0) {
1499 rewrite_log("rewrite_subst_maps_fifo(): error reading value from FIFO "
1500 "'%s': %s", fifo, strerror(errno));
1501 }
1502
1503 /* Use the default value */
1504 value = map->map_default_value;
1505
1506 } else {
1507 register unsigned int i = 0;
1508
1509 /* Find the terminating newline in the returned value */
1510 for (i = 0; i < REWRITE_FIFO_MAXLEN; i++) {
1511 if (value[i] == '\n') {
1512 value[i] = '\0';
1513 break;
1514 }
1515 }
1516
1517 if (i == REWRITE_FIFO_MAXLEN) {
1518 rewrite_log("rewrite_subst_maps_fifo(): FIFO returned too long value, "
1519 "using default value");
1520 value = map->map_default_value;
1521 }
1522 }
1523 pr_signals_block();
1524
1525 /* Make sure the data from the read buffer is completely flushed. */
1526 if (fsync(fifo_fd) < 0) {
1527 rewrite_log("rewrite_subst_maps_fifo(): error flushing data to FIFO %d: %s",
1528 fifo_fd, strerror(errno));
1529 }
1530
1531 if (fifo_lockfd != -1) {
1532 #ifdef HAVE_FLOCK
1533 if (flock(fifo_lockfd, LOCK_UN) < 0) {
1534 rewrite_log("rewrite_subst_maps_fifo(): error releasing lock: %s",
1535 strerror(errno));
1536 }
1537 #else
1538 lock.l_type = F_UNLCK;
1539 lock.l_whence = 0;
1540 lock.l_start = lock.l_len = 0;
1541
1542 while (fcntl(fifo_lockfd, F_SETLKW, &lock) < 0) {
1543 if (errno == EINTR) {
1544 pr_signals_handle();
1545 continue;
1546 }
1547
1548 rewrite_log("rewrite_subst_maps_fifo(): error releasing lock: %s",
1549 strerror(errno));
1550 break;
1551 }
1552 #endif /* HAVE_FLOCK */
1553
1554 (void) close(fifo_lockfd);
1555 }
1556
1557 pr_signals_unblock();
1558 return value;
1559 }
1560
1561 static const char *rewrite_subst_maps_int(cmd_rec *cmd, config_rec *c,
1562 rewrite_map_t *map) {
1563 const char *value = NULL;
1564 char *(*map_func)(pool *, char *) = (char *(*)(pool *, char *)) c->argv[2];
1565
1566 value = map_func(cmd->tmp_pool, map->map_lookup_key);
1567 if (value == NULL) {
1568 value = map->map_default_value;
1569 }
1570
1571 return value;
1572 }
1573
1574 static const char *rewrite_subst_maps_txt(cmd_rec *cmd, config_rec *c,
1575 rewrite_map_t *map) {
1576 rewrite_map_txt_t *txtmap = c->argv[2];
1577 const char *value = NULL;
1578 char **txt_keys = NULL, **txt_vals = NULL;
1579 register unsigned int i = 0;
1580
1581 /* Make sure this map is up-to-date. */
1582 if (!rewrite_parse_map_txt(txtmap)) {
1583 rewrite_log("rewrite_subst_maps_txt(): error parsing txt file");
1584 }
1585
1586 txt_keys = (char **) txtmap->txt_keys;
1587 txt_vals = (char **) txtmap->txt_values;
1588
1589 for (i = 0; i < txtmap->txt_nents; i++) {
1590 if (strcmp(txt_keys[i], map->map_lookup_key) == 0) {
1591 value = txt_vals[i];
1592 }
1593 }
1594
1595 if (value == NULL) {
1596 value = map->map_default_value;
1597 }
1598
1599 return value;
1600 }
1601
1602 static const char *rewrite_subst_vars(cmd_rec *cmd, const char *pattern) {
1603 register unsigned int i = 0;
1604 const char *new_pattern = NULL;
1605
1606 for (i = 0; i < REWRITE_MAX_VARS; i++) {
1607 const char *val = NULL, *res;
1608
1609 pr_signals_handle();
1610
1611 /* Does this variable occur in the substitution pattern? */
1612 if (strstr(pattern, rewrite_vars[i]) == NULL) {
1613 continue;
1614 }
1615
1616 val = rewrite_expand_var(cmd, pattern, rewrite_vars[i]);
1617 if (val != NULL) {
1618 rewrite_log("rewrite_subst_vars(): replacing variable '%s' with '%s'",
1619 rewrite_vars[i], val);
1620 if (new_pattern == NULL) {
1621 new_pattern = pstrdup(cmd->pool, pattern);
1622 }
1623
1624 res = pr_str_replace(cmd->pool, rewrite_max_replace, new_pattern,
1625 rewrite_vars[i], val, NULL);
1626 if (res == NULL) {
1627 pr_trace_msg(trace_channel, 3,
1628 "error replacing '%s' with '%s' in '%s': %s", rewrite_vars[i], val,
1629 new_pattern, strerror(errno));
1630
1631 } else {
1632 new_pattern = res;
1633 }
1634 }
1635 }
1636
1637 return (new_pattern ? new_pattern : pattern);
1638 }
1639
1640 static char rewrite_hex_to_char(const char *what) {
1641 register char digit;
1642
1643 /* NOTE: this assumes a non-EBCDIC system... */
1644 digit = ((what[0] >= 'A') ? ((what[0] & 0xdf) - 'A') + 10 : (what[0] - '0'));
1645 digit *= 16;
1646 digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A') + 10 : (what[1] - '0'));
1647
1648 return digit;
1649 }
1650
1651 #define REWRITE_VALID_UTF8_BYTE(b) (((b) & 0x80) ? TRUE : FALSE)
1652
1653 /* Converts a UTF8 encoded string to a UCS4 encoded string (which just
1654 * happens to coincide with ISO-8859-1). On success, the length of the
1655 * populated long array (which must be allocated by the caller) will be
1656 * returned. -1 will be returned on error, signalling an incorrectly
1657 * formatted UTF8 string. The majority of this code is contained
1658 * in RFC 2640 "Internationalization of the File Transfer Protocol".
1659 */
1660 static int rewrite_utf8_to_ucs4(unsigned long *ucs4_buf,
1661 size_t utf8_len, unsigned char *utf8_buf) {
1662 const unsigned char *utf8_endbuf = utf8_buf + utf8_len;
1663 int ucs_len = 0;
1664
1665 while (utf8_buf != utf8_endbuf) {
1666 pr_signals_handle();
1667
1668 /* ASCII chars - no conversion needed */
1669 if ((*utf8_buf & 0x80) == 0x00) {
1670 *ucs4_buf++ = (unsigned long) *utf8_buf;
1671 utf8_buf++;
1672 ucs_len++;
1673
1674 /* In the 2-byte UTF-8 range... */
1675 } else if ((*utf8_buf & 0xE0)== 0xC0) {
1676
1677 /* Make sure the next byte is a valid UTF8 byte. */
1678 if (!REWRITE_VALID_UTF8_BYTE(*(utf8_buf + 1)))
1679 return -1;
1680
1681 *ucs4_buf++ = (unsigned long) (((*utf8_buf - 0xC0) * 0x40)
1682 + (*(utf8_buf+1) - 0x80));
1683 utf8_buf += 2;
1684 ucs_len++;
1685
1686 /* In the 3-byte UTF-8 range... */
1687 } else if ((*utf8_buf & 0xF0) == 0xE0) {
1688 register unsigned int i;
1689
1690 /* Make sure the next 2 bytes are valid UTF8 bytes. */
1691 for (i = 1; i <= 2; i++)
1692 if (!REWRITE_VALID_UTF8_BYTE(*(utf8_buf + i)))
1693 return -1;
1694
1695 *ucs4_buf++ = (unsigned long) (((*utf8_buf - 0xE0) * 0x1000)
1696 + ((*(utf8_buf+1) - 0x80) * 0x40)
1697 + (*(utf8_buf+2) - 0x80));
1698 utf8_buf+=3;
1699 ucs_len++;
1700
1701 /* In the 4-byte UTF-8 range... */
1702 } else if ((*utf8_buf & 0xF8) == 0xF0) {
1703 register unsigned int i;
1704
1705 /* Make sure the next 3 bytes are valid UTF8 bytes. */
1706 for (i = 1; i <= 3; i++)
1707 if (!REWRITE_VALID_UTF8_BYTE(*(utf8_buf + i)))
1708 return -1;
1709
1710 *ucs4_buf++ = (unsigned long)
1711 (((*utf8_buf - 0xF0) * 0x040000)
1712 + ((*(utf8_buf+1) - 0x80) * 0x1000)
1713 + ((*(utf8_buf+2) - 0x80) * 0x40)
1714 + (*(utf8_buf+3) - 0x80));
1715 utf8_buf+=4;
1716 ucs_len++;
1717
1718 /* In the 5-byte UTF-8 range... */
1719 } else if ((*utf8_buf & 0xFC) == 0xF8) {
1720 register unsigned int i;
1721
1722 /* Make sure the next 4 bytes are valid UTF8 bytes. */
1723 for (i = 1; i <= 4; i++)
1724 if (!REWRITE_VALID_UTF8_BYTE(*(utf8_buf + i)))
1725 return -1;
1726
1727 *ucs4_buf++ = (unsigned long)
1728 (((*utf8_buf - 0xF8) * 0x01000000)
1729 + ((*(utf8_buf+1) - 0x80) * 0x040000)
1730 + ((*(utf8_buf+2) - 0x80) * 0x1000)
1731 + ((*(utf8_buf+3) - 0x80) * 0x40)
1732 + (*(utf8_buf+4) - 0x80));
1733 utf8_buf+=5;
1734 ucs_len++;
1735
1736 /* In the 6-byte UTF-8 range... */
1737 } else if ((*utf8_buf & 0xFE) == 0xFC) {
1738 register unsigned int i;
1739
1740 /* make sure the next 5 bytes are valid UTF8 bytes */
1741 for (i = 1; i <= 5; i++)
1742 if (!REWRITE_VALID_UTF8_BYTE(*(utf8_buf + i)))
1743 return -1;
1744
1745 *ucs4_buf++ = (unsigned long)
1746 (((*utf8_buf - 0xFC) * 0x40000000)
1747 + ((*(utf8_buf+1) - 0x80) * 0x010000000)
1748 + ((*(utf8_buf+2) - 0x80) * 0x040000)
1749 + ((*(utf8_buf+3) - 0x80) * 0x1000)
1750 + ((*(utf8_buf+4) - 0x80) * 0x40)
1751 + (*(utf8_buf+5) - 0x80));
1752 utf8_buf+=6;
1753 ucs_len++;
1754
1755 /* Badly formatted UTF8 string, with escape sequences that are interpreted
1756 * ambiguously. If this is the case, just copy the non-ASCII, non-UTF8
1757 * char into the UCS4 buffer, and assume the string creator knew what they
1758 * were doing...
1759 */
1760 } else {
1761 *ucs4_buf++ = (unsigned long) *utf8_buf;
1762 utf8_buf++;
1763 ucs_len++;
1764 }
1765 }
1766
1767 return ucs_len;
1768 }
1769
1770 /* RewriteMap internal functions. Note that these functions may (and
1771 * probably will) modify their key arguments.
1772 */
1773
1774 static const char *rewrite_map_int_replaceall(pool *map_pool, char *key) {
1775 char sep = *key;
1776 char *value = NULL, *src = NULL, *dst = NULL;
1777 const char *res = NULL;
1778 char *ptr = NULL, *str;
1779
1780 /* Due to the way in which this internal function works, the first
1781 * character of the given key is used as a delimiter separating
1782 * the given key, and the sequences to replace for this function.
1783 */
1784 str = pstrdup(map_pool, key + 1);
1785
1786 ptr = strchr(str, sep);
1787 if (ptr == NULL) {
1788 rewrite_log("rewrite_map_int_replaceall(): badly formatted input key");
1789 return NULL;
1790 }
1791
1792 *ptr = '\0';
1793 value = str;
1794 rewrite_log("rewrite_map_int_replaceall(): actual key: '%s'", value);
1795
1796 str = ptr + 1;
1797
1798 ptr = strchr(str, sep);
1799 if (ptr == NULL) {
1800 rewrite_log("rewrite_map_int_replaceall(): badly formatted input key");
1801 return NULL;
1802 }
1803
1804 *ptr = '\0';
1805 src = str;
1806 dst = ptr + 1;
1807
1808 rewrite_log("rewrite_map_int_replaceall(): replacing '%s' with '%s'", src,
1809 dst);
1810
1811 /* Make sure the source sequence is present in the given key. */
1812 if (strstr(value, src) == NULL) {
1813 rewrite_log("rewrite_map_int_replaceall(): '%s' does not occur in given "
1814 "key '%s'", src, value);
1815 return NULL;
1816 }
1817
1818 res = pr_str_replace(map_pool, rewrite_max_replace, value, src, dst, NULL);
1819 if (res == NULL) {
1820 int xerrno = errno;
1821
1822 rewrite_log("rewrite_map_int_replaceall(): error replacing "
1823 "'%s' with '%s' in '%s': %s", src, dst, value, strerror(xerrno));
1824
1825 errno = xerrno;
1826
1827 } else {
1828 rewrite_log("rewrite_map_int_replaceall(): returning '%s'", res);
1829 }
1830
1831 return res;
1832 }
1833
1834 static const char *rewrite_map_int_tolower(pool *map_pool, char *key) {
1835 register unsigned int i = 0;
1836 char *value;
1837 size_t valuelen;
1838
1839 value = pstrdup(map_pool, key);
1840 valuelen = strlen(value);
1841
1842 for (i = 0; i < valuelen; i++) {
1843 if (PR_ISALPHA((int) value[i])) {
1844 value[i] = tolower(value[i]);
1845 }
1846 }
1847
1848 return value;
1849 }
1850
1851 static const char *rewrite_map_int_toupper(pool *map_pool, char *key) {
1852 register unsigned int i = 0;
1853 char *value;
1854 size_t valuelen;
1855
1856 value = pstrdup(map_pool, key);
1857 valuelen = strlen(value);
1858
1859 for (i = 0; i < valuelen; i++) {
1860 if (PR_ISALPHA((int) value[i])) {
1861 value[i] = toupper(value[i]);
1862 }
1863 }
1864
1865 return value;
1866 }
1867
1868 /* Unescapes the hex escape sequences in the given string (typically a URL-like
1869 * path). Returns the escaped string on success, NULL on error; failures can
1870 * be caused by: bad % escape sequences, decoding %00, or a special character.
1871 */
1872 static const char *rewrite_map_int_unescape(pool *map_pool, char *key) {
1873 register int i, j;
1874 char *value;
1875
1876 value = pcalloc(map_pool, strlen(key) + 1);
1877 for (i = 0, j = 0; key[j]; ++i, ++j) {
1878 if (key[j] != '%') {
1879 value[i] = key[j];
1880
1881 } else {
1882 if (!PR_ISXDIGIT(key[j+1]) ||
1883 !PR_ISXDIGIT(key[j+2])) {
1884 rewrite_log("rewrite_map_int_unescape(): bad escape sequence '%c%c%c'",
1885 key[j], key[j+1], key[j+2]);
1886 return NULL;
1887 }
1888
1889 value[i] = rewrite_hex_to_char(&key[j+1]);
1890 if (value[i] == '/' ||
1891 value[i] == '\0') {
1892 rewrite_log("rewrite_map_int_unescape(): bad path due to '%c'",
1893 value[i]);
1894 errno = EPERM;
1895 return NULL;
1896 }
1897
1898 j += 2;
1899 }
1900 }
1901 value[i] = '\0';
1902
1903 return value;
1904 }
1905
1906 static int rewrite_open_fifo(config_rec *c) {
1907 int fd = -1, flags = -1;
1908 char *fifo = c->argv[2];
1909
1910 /* No interruptions, please. */
1911 pr_signals_block();
1912
1913 fd = open(fifo, O_RDWR|O_NONBLOCK);
1914 if (fd < 0) {
1915 int xerrno = errno;
1916
1917 pr_signals_unblock();
1918 rewrite_log("rewrite_open_fifo(): unable to open FIFO '%s': %s", fifo,
1919 strerror(xerrno));
1920
1921 errno = xerrno;
1922 return -1;
1923 }
1924
1925 /* Set this descriptor for blocking. */
1926 flags = fcntl(fd, F_GETFL);
1927 if (fcntl(fd, F_SETFL, flags & (REWRITE_U32_BITS^O_NONBLOCK)) < 0) {
1928 rewrite_log("rewrite_open_fifo(): error setting FIFO "
1929 "blocking mode: %s", strerror(errno));
1930 }
1931
1932 /* Add the file descriptor into the config_rec. */
1933 *((int *) c->argv[3]) = fd;
1934
1935 pr_signals_unblock();
1936 return 0;
1937 }
1938
1939 static int rewrite_read_fifo(int fd, char *buf, size_t buflen) {
1940 int res = 0;
1941 fd_set rset;
1942
1943 FD_ZERO(&rset);
1944 FD_SET(fd, &rset);
1945
1946 /* Blocking select for reading, handling interruptions appropriately. */
1947 while ((res = select(fd + 1, &rset, NULL, NULL, NULL)) < 0) {
1948 if (errno == EINTR) {
1949 pr_signals_handle();
1950 continue;
1951 }
1952
1953 return res;
1954 }
1955
1956 /* Now, read from the FIFO, again handling interruptions. */
1957 while ((res = read(fd, buf, buflen)) < 0) {
1958 if (errno == EINTR) {
1959 pr_signals_handle();
1960 continue;
1961 }
1962
1963 break;
1964 }
1965
1966 return res;
1967 }
1968
1969 #define REWRITE_WAIT_MAX_ATTEMPTS 10
1970
1971 static void rewrite_wait_fifo(int fd) {
1972 unsigned int nattempts = 0;
1973 int size = 0;
1974 struct timeval tv;
1975
1976 rewrite_log("rewrite_wait_fifo: waiting on FIFO (fd %d)", fd);
1977
1978 /* Wait for the data written to the FIFO buffer to be read. Use
1979 * ioctl(2) (yuck) to poll the buffer, waiting for the number of bytes
1980 * to be read to drop to zero. When that happens, we'll know that the
1981 * process on the other end of the FIFO has read the data, and has
1982 * hopefully written a response back. We select(2) when reading from
1983 * the FIFO, so we won't need to poll the buffer similarly there.
1984 */
1985
1986 if (ioctl(fd, FIONREAD, &size) < 0) {
1987 rewrite_log("rewrite_wait_fifo(): ioctl error: %s", strerror(errno));
1988 return;
1989 }
1990
1991 if (size == 0) {
1992 rewrite_log("rewrite_wait_fifo(): found %d bytes waiting in FIFO (fd %d)",
1993 size, fd);
1994 }
1995
1996 while (size != 0) {
1997 rewrite_log("rewrite_wait_fifo(): waiting for buffer to be read "
1998 "(%d bytes remaining)", size);
1999
2000 /* Handling signals is always a Good Thing in a while() loop. */
2001 pr_signals_handle();
2002
2003 /* Poll every half second. */
2004 tv.tv_sec = 0;
2005 tv.tv_usec = 500000;
2006
2007 select(0, NULL, NULL, NULL, &tv);
2008
2009 if (ioctl(fd, FIONREAD, &size) < 0) {
2010 rewrite_log("rewrite_wait_fifo(): ioctl error: %s", strerror(errno));
2011 }
2012
2013 nattempts++;
2014 if (nattempts >= REWRITE_WAIT_MAX_ATTEMPTS) {
2015 rewrite_log("rewrite_wait_fifo(): exceeded max poll attempts (%d), "
2016 "returning", REWRITE_WAIT_MAX_ATTEMPTS);
2017 break;
2018 }
2019 }
2020 }
2021
2022 static int rewrite_write_fifo(int fd, char *buf, size_t buflen) {
2023 int res = 0;
2024
2025 while ((res = write(fd, buf, buflen)) < 0) {
2026 if (errno == EINTR) {
2027 pr_signals_handle();
2028 continue;
2029 }
2030
2031 break;
2032 }
2033
2034 return res;
2035 }
2036
2037 static char *rewrite_map_int_utf8trans(pool *map_pool, char *key) {
2038 int ucs4strlen = 0;
2039 static unsigned char utf8_val[PR_TUNABLE_BUFFER_SIZE] = {'\0'};
2040 static unsigned long ucs4_longs[PR_TUNABLE_BUFFER_SIZE] = {0L};
2041
2042 /* If the key is NULL or empty, do nothing. */
2043 if (key == NULL ||
2044 strlen(key) == 0) {
2045 return NULL;
2046 }
2047
2048 /* Always make sure the buffers are clear for this run. */
2049 memset(utf8_val, '\0', sizeof(utf8_val));
2050 memset(ucs4_longs, 0, sizeof(ucs4_longs));
2051
2052 ucs4strlen = rewrite_utf8_to_ucs4(ucs4_longs, strlen(key),
2053 (unsigned char *) key);
2054 if (ucs4strlen < 0) {
2055
2056 /* The key is not a properly formatted UTF-8 string. */
2057 rewrite_log("rewrite_map_int_utf8trans(): not a proper UTF-8 string: '%s'",
2058 key);
2059 return NULL;
2060
2061 } else if (ucs4strlen > 1) {
2062 register int i = 0;
2063
2064 /* Cast the UTF-8 longs to unsigned chars. NOTE: this is an assumption
2065 * about casts; it just so happens, quite nicely, that UCS4 maps one-to-one
2066 * to ISO-8859-1 (Latin-1).
2067 */
2068 for (i = 0; i < ucs4strlen; i++) {
2069 utf8_val[i] = (unsigned char) ucs4_longs[i];
2070 }
2071
2072 return pstrdup(map_pool, (const char *) utf8_val);
2073 }
2074
2075 return NULL;
2076 }
2077
2078 #if (defined(HAVE_IDNA_H) && defined(HAVE_IDNA_TO_ASCII_8Z)) || \
2079 (defined(HAVE_IDN2_H) && defined(HAVE_IDN2_TO_ASCII_8Z))
2080 static char *rewrite_map_int_idnatrans(pool *map_pool, char *key) {
2081 int flags = 0, res;
2082 char *ascii_val = NULL, *map_val = NULL;
2083
2084 /* If the key is NULL or empty, do nothing. */
2085 if (key == NULL ||
2086 strlen(key) == 0) {
2087 return NULL;
2088 }
2089
2090 # if defined(HAVE_IDN2_H) && defined(HAVE_IDN2_TO_ASCII_8Z)
2091 flags = IDN2_NFC_INPUT|IDN2_NONTRANSITIONAL;
2092 res = idn2_to_ascii_8z(key, &ascii_val, flags);
2093 if (res != IDN2_OK) {
2094 rewrite_log("rewrite_map_int_idnatrans(): failed transforming IDN2 "
2095 "'%s' to ASCII: %s", key, idn2_strerror(res));
2096 return NULL;
2097 }
2098
2099 # elif defined(HAVE_IDNA_H) && defined(HAVE_IDNA_TO_ASCII_8Z)
2100 /* TODO: Should we enforce the use of e.g. the IDNA_USE_STD3_ASCII_RULES
2101 * flag?
2102 */
2103 res = idna_to_ascii_8z(key, &ascii_val, flags);
2104 if (res != IDNA_SUCCESS) {
2105 rewrite_log("rewrite_map_int_idnatrans(): failed transforming IDNA "
2106 "'%s' to ASCII: %s", key, idna_strerror(res));
2107 return NULL;
2108 }
2109 # endif /* IDNA support. */
2110
2111 map_val = pstrdup(map_pool, ascii_val);
2112 free(ascii_val);
2113
2114 return map_val;
2115 }
2116 #endif /* IDNA or IDN2 support */
2117
2118 /* Rewrite logging functions */
2119
2120 static void rewrite_openlog(void) {
2121 int res = 0, xerrno = 0;
2122
2123 /* Sanity checks */
2124 if (rewrite_logfd >= 0) {
2125 return;
2126 }
2127
2128 rewrite_logfile = get_param_ptr(main_server->conf, "RewriteLog", FALSE);
2129 if (rewrite_logfile == NULL) {
2130 rewrite_logfd = -2;
2131 return;
2132 }
2133
2134 if (strcasecmp(rewrite_logfile, "none") == 0) {
2135 rewrite_logfd = -1;
2136 rewrite_logfile = NULL;
2137 return;
2138 }
2139
2140 pr_signals_block();
2141 PRIVS_ROOT
2142 res = pr_log_openfile(rewrite_logfile, &rewrite_logfd, REWRITE_LOG_MODE);
2143 xerrno = errno;
2144 PRIVS_RELINQUISH
2145 pr_signals_unblock();
2146
2147 if (res < 0) {
2148 switch (res) {
2149 case -1:
2150 pr_log_pri(PR_LOG_NOTICE, MOD_REWRITE_VERSION
2151 ": error: unable to open RewriteLog '%s': %s", rewrite_logfile,
2152 strerror(xerrno));
2153 break;
2154
2155 case PR_LOG_WRITABLE_DIR:
2156 pr_log_pri(PR_LOG_WARNING, MOD_REWRITE_VERSION
2157 ": error: unable to open RewriteLog '%s': %s", rewrite_logfile,
2158 "parent directory is world-writable");
2159 break;
2160
2161 case PR_LOG_SYMLINK:
2162 pr_log_pri(PR_LOG_WARNING, MOD_REWRITE_VERSION
2163 ": error: unable to open RewriteLog '%s': %s", rewrite_logfile,
2164 "cannot log to a symbolic link");
2165 break;
2166 }
2167 }
2168
2169 return;
2170 }
2171
2172 static void rewrite_closelog(void) {
2173 /* Sanity check */
2174 if (rewrite_logfd < 0)
2175 return;
2176
2177 if (close(rewrite_logfd) < 0) {
2178 pr_log_pri(PR_LOG_ALERT, MOD_REWRITE_VERSION
2179 ": error closing RewriteLog '%s': %s", rewrite_logfile, strerror(errno));
2180 return;
2181 }
2182
2183 rewrite_logfile = NULL;
2184 rewrite_logfd = -1;
2185
2186 return;
2187 }
2188
2189 static void rewrite_log(char *fmt, ...) {
2190 va_list msg;
2191
2192 va_start(msg, fmt);
2193 (void) pr_log_vwritefile(rewrite_logfd, MOD_REWRITE_VERSION, fmt, msg);
2194 va_end(msg);
2195
2196 return;
2197 }
2198
2199 /* Configuration directive handlers
2200 */
2201
2202 /* usage: RewriteCondition condition pattern [flags] */
2203 MODRET set_rewritecondition(cmd_rec *cmd) {
2204 config_rec *c = NULL;
2205 pool *cond_pool = NULL;
2206 void *cond_data = NULL;
2207 unsigned int cond_flags = 0;
2208 unsigned char negated = FALSE;
2209 rewrite_cond_op_t cond_op = 0;
2210 int regex_flags = REG_EXTENDED, res = -1;
2211 char *pattern;
2212
2213 if (cmd->argc-1 < 2 ||
2214 cmd->argc-1 > 3) {
2215 CONF_ERROR(cmd, "bad number of parameters");
2216 }
2217
2218 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON|CONF_DIR);
2219
2220 /* The following variables are not allowed in RewriteConditions:
2221 * %P (PID), and %t (Unix epoch). Check for them.
2222 */
2223 if (strstr(cmd->argv[2], "%P") != NULL ||
2224 strstr(cmd->argv[2], "%t") != NULL) {
2225 CONF_ERROR(cmd, "illegal RewriteCondition variable used");
2226 }
2227
2228 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON|CONF_DIR);
2229
2230 /* Make sure that, if present, the flags parameter is correctly formatted. */
2231 if (cmd->argc-1 == 3) {
2232 char *flags_str;
2233
2234 flags_str = cmd->argv[3];
2235
2236 if (flags_str[0] != '[' ||
2237 flags_str[strlen(flags_str)-1] != ']') {
2238 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
2239 ": badly formatted flags parameter: '", flags_str, "'", NULL));
2240 }
2241
2242 /* We need to parse the flags parameter here, to see if any flags which
2243 * affect the compilation of the regex (e.g. NC) are present.
2244 */
2245 cond_flags = rewrite_parse_cond_flags(cmd->tmp_pool, flags_str);
2246 if (cond_flags == 0) {
2247 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
2248 ": unknown RewriteCondition flags '", flags_str, "'", NULL));
2249 }
2250
2251 if (cond_flags & REWRITE_COND_FLAG_NOCASE) {
2252 regex_flags |= REG_ICASE;
2253 }
2254 }
2255
2256 if (rewrite_conds == NULL) {
2257 if (rewrite_cond_pool != NULL) {
2258 destroy_pool(rewrite_cond_pool);
2259 }
2260
2261 rewrite_cond_pool = make_sub_pool(rewrite_pool);
2262 pr_pool_tag(rewrite_cond_pool, "RewriteCondition pool");
2263
2264 rewrite_conds = make_array(rewrite_cond_pool, 0, sizeof(config_rec *));
2265 }
2266
2267 /* Check for a leading '!' negation prefix to the regex pattern */
2268 pattern = cmd->argv[2];
2269 if (pattern[0] == '!') {
2270 pattern++;
2271 negated = TRUE;
2272 }
2273
2274 /* Check the next character in the given pattern. It may be a lexical
2275 * or a file test pattern...
2276 */
2277 if (*pattern == '>') {
2278 cond_op = REWRITE_COND_OP_LEX_LT;
2279 cond_data = pstrdup(rewrite_pool, ++pattern);
2280
2281 } else if (*pattern == '<') {
2282 cond_op = REWRITE_COND_OP_LEX_GT;
2283 cond_data = pstrdup(rewrite_pool, ++pattern);
2284
2285 } else if (*pattern == '=') {
2286 cond_op = REWRITE_COND_OP_LEX_EQ;
2287 cond_data = pstrdup(rewrite_pool, ++pattern);
2288
2289 } else if (strncmp(pattern, "-d", 3) == 0) {
2290 cond_op = REWRITE_COND_OP_TEST_DIR;
2291
2292 } else if (strncmp(pattern, "-f", 3) == 0) {
2293 cond_op = REWRITE_COND_OP_TEST_FILE;
2294
2295 } else if (strncmp(pattern, "-l", 3) == 0) {
2296 cond_op = REWRITE_COND_OP_TEST_SYMLINK;
2297
2298 } else if (strncmp(pattern, "-s", 3) == 0) {
2299 cond_op = REWRITE_COND_OP_TEST_SIZE;
2300
2301 } else {
2302 cond_op = REWRITE_COND_OP_REGEX;
2303 cond_data = pr_regexp_alloc(&rewrite_module);
2304
2305 res = pr_regexp_compile(cond_data, pattern, regex_flags);
2306 if (res != 0) {
2307 char errstr[200] = {'\0'};
2308
2309 pr_regexp_error(res, cond_data, errstr, sizeof(errstr));
2310 regfree(cond_data);
2311
2312 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unable to compile '",
2313 pattern, "' regex: ", errstr, NULL));
2314 }
2315 }
2316
2317 /* Make sure the variables used, if any, are valid. Environment variables
2318 * are handled later.
2319 */
2320 if (strncmp(cmd->argv[1], "%{ENV:", 6) != 0) {
2321 char *var;
2322
2323 var = cmd->argv[1];
2324
2325 while (*var != '\0' &&
2326 (var = strchr(var, '%')) != NULL && strlen(var) > 1 &&
2327 !PR_ISDIGIT(*(var+1))) {
2328 register unsigned int i = 0;
2329 unsigned char is_valid_var = FALSE;
2330
2331 for (i = 0; i < REWRITE_MAX_VARS; i++) {
2332 if (strcmp(var, rewrite_vars[i]) == 0) {
2333 is_valid_var = TRUE;
2334 break;
2335 }
2336 }
2337
2338 if (is_valid_var == FALSE) {
2339 pr_log_debug(DEBUG0, "invalid RewriteCondition variable '%s' used",
2340 var);
2341 }
2342
2343 var += 2;
2344 }
2345 }
2346
2347 /* Do this manually -- no need to clutter up the configuration tree
2348 * with config_recs that really don't belong in that contextualized
2349 * arrangement. These config_recs will be tracked/retrieved via
2350 * a RewriteRule config_rec, not via the normal configuration tree
2351 * retrieval functions.
2352 */
2353
2354 cond_pool = make_sub_pool(rewrite_pool);
2355 c = pcalloc(cond_pool, sizeof(config_rec));
2356 c->pool = cond_pool;
2357 c->name = pstrdup(c->pool, cmd->argv[0]);
2358 c->config_type = CONF_PARAM;
2359 c->argc = 5;
2360 c->argv = pcalloc(c->pool, (c->argc+1) * sizeof(void *));
2361 c->argv[0] = pstrdup(c->pool, cmd->argv[1]);
2362 c->argv[1] = (void *) cond_data;
2363
2364 c->argv[2] = palloc(c->pool, sizeof(unsigned char));
2365 *((unsigned char *) c->argv[2]) = negated;
2366
2367 c->argv[3] = pcalloc(c->pool, sizeof(rewrite_cond_op_t));
2368 *((rewrite_cond_op_t *) c->argv[3]) = cond_op;
2369
2370 c->argv[4] = pcalloc(c->pool, sizeof(unsigned int));
2371 *((unsigned int *) c->argv[4]) = cond_flags;
2372
2373 /* Add this config_rec to an array, to be added to the RewriteRule when
2374 * (if?) it appears.
2375 */
2376 *((config_rec **) push_array(rewrite_conds)) = c;
2377
2378 return PR_HANDLED(cmd);
2379 }
2380
2381 /* usage: RewriteEngine on|off */
2382 MODRET set_rewriteengine(cmd_rec *cmd) {
2383 int engine = FALSE;
2384 config_rec *c = NULL;
2385
2386 CHECK_ARGS(cmd, 1);
2387 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
2388
2389 engine = get_boolean(cmd, 1);
2390 if (engine == -1) {
2391 CONF_ERROR(cmd, "expecting Boolean parameter");
2392 }
2393
2394 /* Check for duplicates */
2395 if (get_param_ptr(cmd->server->conf, cmd->argv[0], FALSE) != NULL) {
2396 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, cmd->argv[0], ": multiple "
2397 "instances not allowed for same server", NULL));
2398 }
2399
2400 c = add_config_param(cmd->argv[0], 1, NULL);
2401 c->argv[0] = pcalloc(c->pool, sizeof(unsigned char));
2402 *((unsigned char *) c->argv[0]) = engine;
2403
2404 return PR_HANDLED(cmd);
2405 }
2406
2407 /* usage: RewriteLock file */
2408 MODRET set_rewritelock(cmd_rec *cmd) {
2409 char *path;
2410
2411 CHECK_ARGS(cmd, 1);
2412 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
2413
2414 /* Check for non-absolute paths */
2415 path = cmd->argv[1];
2416 if (*path != '/') {
2417 CONF_ERROR(cmd, "absolute path required");
2418 }
2419
2420 add_config_param_str(cmd->argv[0], 1, path);
2421 return PR_HANDLED(cmd);
2422 }
2423
2424 /* usage: RewriteMaxReplace count */
2425 MODRET set_rewritemaxreplace(cmd_rec *cmd) {
2426 int max_replace = -1;
2427 config_rec *c;
2428
2429 CHECK_ARGS(cmd, 1);
2430 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
2431
2432 max_replace = atoi(cmd->argv[1]);
2433 if (max_replace <= 0) {
2434 CONF_ERROR(cmd, "count must be greater than zero");
2435 }
2436
2437 c = add_config_param(cmd->argv[0], 1, NULL);
2438 c->argv[0] = palloc(c->pool, sizeof(unsigned int));
2439 *((unsigned int *) c->argv[0]) = max_replace;
2440
2441 return PR_HANDLED(cmd);
2442 }
2443
2444 /* usage: RewriteLog file|"none" */
2445 MODRET set_rewritelog(cmd_rec *cmd) {
2446 char *path;
2447
2448 CHECK_ARGS(cmd, 1);
2449 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
2450
2451 /* Check for non-absolute paths */
2452 path = cmd->argv[1];
2453 if (strcasecmp(path, "none") != 0 &&
2454 *path != '/') {
2455 CONF_ERROR(cmd, "absolute path required");
2456 }
2457
2458 add_config_param_str(cmd->argv[0], 1, path);
2459 return PR_HANDLED(cmd);
2460 }
2461
2462 /* usage: RewriteMap map-name map-type:map-source */
2463 MODRET set_rewritemap(cmd_rec *cmd) {
2464 config_rec *c = NULL;
2465 char *mapsrc = NULL;
2466 void *map = NULL;
2467
2468 CHECK_ARGS(cmd, 2);
2469 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
2470
2471 /* Check the configured map types */
2472 mapsrc = strchr(cmd->argv[2], ':');
2473 if (mapsrc == NULL) {
2474 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "invalid RewriteMap parameter: '",
2475 cmd->argv[2], "'", NULL));
2476 }
2477
2478 *mapsrc = '\0';
2479 mapsrc++;
2480
2481 if (strcmp(cmd->argv[2], "int") == 0) {
2482 c = add_config_param(cmd->argv[0], 3, NULL, NULL, NULL);
2483
2484 /* Check that the given function is a valid internal mapping function. */
2485 if (strcmp(mapsrc, "replaceall") == 0) {
2486 map = (void *) rewrite_map_int_replaceall;
2487
2488 } else if (strcmp(mapsrc, "tolower") == 0) {
2489 map = (void *) rewrite_map_int_tolower;
2490
2491 } else if (strcmp(mapsrc, "toupper") == 0) {
2492 map = (void *) rewrite_map_int_toupper;
2493
2494 } else if (strcmp(mapsrc, "unescape") == 0) {
2495 map = (void *) rewrite_map_int_unescape;
2496
2497 } else if (strcmp(mapsrc, "utf8trans") == 0) {
2498 map = (void *) rewrite_map_int_utf8trans;
2499
2500 } else if (strcmp(mapsrc, "idnatrans") == 0) {
2501 #if (defined(HAVE_IDNA_H) && defined(HAVE_IDNA_TO_ASCII_8Z)) || \
2502 (defined(HAVE_IDN2_H) && defined(HAVE_IDN2_TO_ASCII_8Z))
2503 map = (void *) rewrite_map_int_idnatrans;
2504 #else
2505 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
2506 "unsupported internal map function requested: '", mapsrc, "'", NULL));
2507 #endif /* IDNA support */
2508
2509 } else {
2510 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
2511 "unknown internal map function requested: '", mapsrc, "'", NULL));
2512 }
2513
2514 } else if (strcmp(cmd->argv[2], "fifo") == 0) {
2515 struct stat st;
2516
2517 c = add_config_param(cmd->argv[0], 4, NULL, NULL, NULL, NULL);
2518
2519 /* Make sure the given path is absolute. */
2520 if (*mapsrc != '/') {
2521 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, cmd->argv[0],
2522 ": fifo: absolute path required", NULL));
2523 }
2524
2525 /* Stat the path, to make sure it is indeed a FIFO. */
2526 if (pr_fsio_stat(mapsrc, &st) < 0) {
2527 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, cmd->argv[0],
2528 ": fifo: error stat'ing '", mapsrc, "': ", strerror(errno), NULL));
2529 }
2530
2531 if (!S_ISFIFO(st.st_mode)) {
2532 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, cmd->argv[0],
2533 ": fifo: error: '", mapsrc, "' is not a FIFO", NULL));
2534 }
2535
2536 map = (void *) pstrdup(c->pool, mapsrc);
2537
2538 /* Initialize the FIFO file descriptor slot. */
2539 c->argv[3] = pcalloc(c->pool, sizeof(int));
2540 *((int *) c->argv[3]) = -1;
2541
2542 } else if (strcmp(cmd->argv[2], "txt") == 0) {
2543 pool *txt_pool = NULL;
2544 rewrite_map_txt_t *txtmap = NULL;
2545
2546 c = add_config_param(cmd->argv[0], 3, NULL, NULL, NULL);
2547 txt_pool = make_sub_pool(c->pool);
2548 txtmap = pcalloc(txt_pool, sizeof(rewrite_map_txt_t));
2549
2550 /* Make sure the given path is absolute. */
2551 if (*mapsrc != '/') {
2552 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, (char *) cmd->argv[0],
2553 ": txt: absolute path required", NULL));
2554 }
2555
2556 txtmap->txt_pool = txt_pool;
2557 txtmap->txt_path = pstrdup(txt_pool, mapsrc);
2558
2559 if (!rewrite_parse_map_txt(txtmap)) {
2560 pr_log_debug(DEBUG3, "%s: error parsing map file", (char *) cmd->argv[0]);
2561 pr_log_debug(DEBUG3, "%s: check the RewriteLog for details",
2562 (char *) cmd->argv[0]);
2563 }
2564
2565 map = (void *) txtmap;
2566
2567 } else
2568 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "invalid RewriteMap map type: '",
2569 cmd->argv[2], "'", NULL));
2570
2571 /* A defined map name is available within the scope of the server in
2572 * which it was defined.
2573 */
2574
2575 c->argv[0] = pstrdup(c->pool, cmd->argv[1]);
2576 c->argv[1] = pstrdup(c->pool, cmd->argv[2]);
2577 c->argv[2] = map;
2578
2579 return PR_HANDLED(cmd);
2580 }
2581
2582 /* usage: RewriteRule pattern substitution [flags] */
2583 MODRET set_rewriterule(cmd_rec *cmd) {
2584 config_rec *c = NULL;
2585 pr_regex_t *pre = NULL;
2586 unsigned int rule_flags = 0;
2587 unsigned char negated = FALSE;
2588 int regex_flags = REG_EXTENDED, res = -1;
2589 register unsigned int i = 0;
2590 char *pattern;
2591
2592 if (cmd->argc-1 < 2 ||
2593 cmd->argc-1 > 3) {
2594 CONF_ERROR(cmd, "bad number of parameters");
2595 }
2596
2597 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON|CONF_DIR);
2598
2599 /* Make sure that, if present, the flags parameter is correctly formatted. */
2600 if (cmd->argc-1 == 3) {
2601 char *flags_str;
2602
2603 flags_str = cmd->argv[3];
2604 if (flags_str[0] != '[' ||
2605 flags_str[strlen(flags_str)-1] != ']') {
2606 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
2607 ": badly formatted flags parameter: '", flags_str, "'", NULL));
2608 }
2609
2610 /* We need to parse the flags parameter here, to see if any flags which
2611 * affect the compilation of the regex (e.g. NC) are present.
2612 */
2613 rule_flags = rewrite_parse_rule_flags(cmd->tmp_pool, flags_str);
2614
2615 if (rule_flags & REWRITE_RULE_FLAG_NOCASE) {
2616 regex_flags |= REG_ICASE;
2617 }
2618 }
2619
2620 pre = pr_regexp_alloc(&rewrite_module);
2621
2622 /* Check for a leading '!' prefix, signifying regex negation */
2623 pattern = cmd->argv[1];
2624 if (*pattern == '!') {
2625 negated = TRUE;
2626 pattern++;
2627 }
2628
2629 res = pr_regexp_compile(pre, pattern, regex_flags);
2630 if (res != 0) {
2631 char errstr[200] = {'\0'};
2632
2633 pr_regexp_error(res, pre, errstr, sizeof(errstr));
2634 pr_regexp_free(NULL, pre);
2635
2636 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unable to compile '",
2637 pattern, "' regex: ", errstr, NULL));
2638 }
2639
2640 c = add_config_param(cmd->argv[0], 6, pre, NULL, NULL, NULL, NULL, NULL);
2641
2642 /* Note: how to handle the substitution expression? Later? */
2643 c->argv[1] = pstrdup(c->pool, cmd->argv[2]);
2644
2645 c->argv[2] = palloc(c->pool, sizeof(unsigned char));
2646 *((unsigned char *) c->argv[2]) = negated;
2647
2648 /* Attach the list of conditions to the config_rec. Don't forget to
2649 * clear/reset the list when done.
2650 */
2651 if (rewrite_conds != NULL) {
2652 config_rec **arg_conds = NULL, **conf_conds = NULL;
2653
2654 /* Allocate space for an array of rewrite_conds->nelts + 1. The extra
2655 * pointer is for NULL-terminating the array
2656 */
2657 c->argv[3] = pcalloc(c->pool,
2658 (rewrite_conds->nelts + 1) * sizeof(config_rec *));
2659
2660 arg_conds = (config_rec **) c->argv[3];
2661 conf_conds = (config_rec **) rewrite_conds->elts;
2662
2663 for (i = 0; i <= rewrite_conds->nelts; i++) {
2664 arg_conds[i] = conf_conds[i];
2665 }
2666
2667 arg_conds[rewrite_conds->nelts] = NULL;
2668
2669 destroy_pool(rewrite_cond_pool);
2670 rewrite_cond_pool = NULL;
2671 rewrite_conds = NULL;
2672
2673 } else {
2674 /* If there are no preceding RewriteConditions, consider this a
2675 * configuration error; see Bug#4495.
2676 *
2677 * For the case where a RewriteRule is deliberately intended to be
2678 * applied to any/all commands, then it needs a RewriteCondition explicitly
2679 * allowing this.
2680 */
2681 CONF_ERROR(cmd, "missing required preceding RewriteCondition");
2682 }
2683
2684 c->argv[4] = pcalloc(c->pool, sizeof(unsigned int));
2685 *((unsigned int *) c->argv[4]) = rule_flags;
2686
2687 /* The very last slot is to be filled by a unique ID (just a counter
2688 * value).
2689 */
2690 c->argv[5] = pcalloc(c->pool, sizeof(unsigned int));
2691 *((unsigned int *) c->argv[5]) = rewrite_nrules++;
2692
2693 c->flags |= CF_MERGEDOWN_MULTI;
2694 return PR_HANDLED(cmd);
2695 }
2696
2697 /* Command handlers
2698 */
2699
2700 MODRET rewrite_fixup(cmd_rec *cmd) {
2701 config_rec *c = NULL;
2702 array_header *seen_rules = NULL;
2703 char *cmd_name, *cmd_arg;
2704
2705 /* Is RewriteEngine on? */
2706 if (!rewrite_engine)
2707 return PR_DECLINED(cmd);
2708
2709 /* If this command has no argument(s), the module has nothing on which to
2710 * operate.
2711 */
2712 if (cmd->argc == 1) {
2713 rewrite_log("rewrite_fixup(): skipping %s (no arg)", (char *) cmd->argv[0]);
2714 return PR_DECLINED(cmd);
2715 }
2716
2717 /* If this is a SITE command, handle things a little differently, so that
2718 * the rest of the rewrite machinery works properly.
2719 */
2720 if (pr_cmd_cmp(cmd, PR_CMD_SITE_ID) != 0) {
2721 cmd_name = cmd->argv[0];
2722 cmd_arg = cmd->arg;
2723
2724 } else {
2725 if (strcasecmp(cmd->argv[1], "CHGRP") == 0 ||
2726 strcasecmp(cmd->argv[1], "CHMOD") == 0) {
2727 register unsigned int i;
2728 char *tmp = "";
2729
2730 if (cmd->argc < 3) {
2731 rewrite_log("%s %s has too few parameters (%d)", (char *) cmd->argv[0],
2732 (char *) cmd->argv[1], cmd->argc);
2733 return PR_DECLINED(cmd);
2734 }
2735
2736 cmd_name = pstrcat(cmd->pool, cmd->argv[0], " ", cmd->argv[1], NULL);
2737
2738 for (i = 2; i <= cmd->argc-1; i++) {
2739 tmp = pstrcat(cmd->pool, tmp, *tmp ? " " : "", cmd->argv[i], NULL);
2740 }
2741
2742 cmd_arg = tmp;
2743
2744 } else {
2745 cmd_name = cmd->argv[0];
2746 cmd_arg = cmd->arg;
2747 }
2748 }
2749
2750 /* Create an array that will contain the IDs of the RewriteRules we've
2751 * already processed.
2752 */
2753 seen_rules = make_array(cmd->tmp_pool, 0, sizeof(unsigned int));
2754
2755 /* Find all RewriteRules in effect. */
2756 c = find_config(CURRENT_CONF, CONF_PARAM, "RewriteRule", FALSE);
2757
2758 while (c) {
2759 unsigned char exec_rule = FALSE;
2760 rewrite_log("rewrite_fixup(): found RewriteRule");
2761
2762 pr_signals_handle();
2763
2764 /* If we've already seen this Rule, skip on to the next Rule. */
2765 if (seen_rules->nelts > 0) {
2766 register unsigned int i = 0;
2767 unsigned char saw_rule = FALSE;
2768 unsigned int id = *((unsigned int *) c->argv[5]), *ids = seen_rules->elts;
2769
2770 for (i = 0; i < seen_rules->nelts; i++) {
2771 if (ids[i] == id) {
2772 saw_rule = TRUE;
2773 break;
2774 }
2775 }
2776
2777 if (saw_rule) {
2778 rewrite_log("rewrite_fixup(): already saw this RewriteRule, skipping");
2779 c = find_config_next(c, c->next, CONF_PARAM, "RewriteRule", FALSE);
2780 continue;
2781 }
2782 }
2783
2784 /* Add this Rule's ID to the list of seen Rules. */
2785 *((unsigned int *) push_array(seen_rules)) = *((unsigned int *) c->argv[5]);
2786
2787 /* Make sure the given RewriteRule regex matches the command argument. */
2788 memset(&rewrite_rule_matches, '\0', sizeof(rewrite_rule_matches));
2789 rewrite_rule_matches.match_string = cmd_arg;
2790 if (!rewrite_regexec(cmd_arg, c->argv[0],
2791 *((unsigned char *) c->argv[2]), &rewrite_rule_matches)) {
2792 rewrite_log("rewrite_fixup(): %s arg '%s' does not match RewriteRule "
2793 "regex", cmd_name, cmd_arg);
2794 c = find_config_next(c, c->next, CONF_PARAM, "RewriteRule", FALSE);
2795 continue;
2796
2797 } else {
2798
2799 /* The command matches the RewriteRule's regex. If there are conditions
2800 * attached to the RewriteRule, make sure those are met as well.
2801 */
2802 if (c->argv[3]) {
2803 register unsigned int i = 0;
2804 config_rec **conds = (config_rec **) c->argv[3];
2805
2806 rewrite_log("rewrite_fixup(): examining RewriteRule conditions");
2807 exec_rule = TRUE;
2808
2809 for (i = 0; conds[i] != NULL; i++) {
2810 unsigned int cond_flags = *((unsigned int *) conds[i]->argv[4]);
2811
2812 if (!rewrite_match_cond(cmd, conds[i])) {
2813
2814 /* If this is the last condition, fail the Rule. */
2815 if (conds[i+1] == NULL) {
2816 exec_rule = FALSE;
2817 rewrite_log("rewrite_fixup(): last condition not met, skipping "
2818 "this RewriteRule");
2819 break;
2820 }
2821
2822 /* If this condition is OR'd with the next condition, just
2823 * continue on to the next condition.
2824 */
2825 if (cond_flags & REWRITE_COND_FLAG_ORNEXT) {
2826 rewrite_log("rewrite_fixup(): condition not met but 'ornext' "
2827 "flag in effect, continue to next condition");
2828 continue;
2829 }
2830
2831 /* Otherwise, fail the Rule. */
2832 exec_rule = FALSE;
2833 rewrite_log("rewrite_fixup(): condition not met, skipping this "
2834 "RewriteRule");
2835 break;
2836
2837 } else {
2838 rewrite_log("rewrite_fixup(): condition met");
2839 exec_rule = TRUE;
2840
2841 if (cond_flags & REWRITE_COND_FLAG_ORNEXT) {
2842 break;
2843 }
2844 }
2845 }
2846
2847 } else {
2848 /* There are no conditions. */
2849 exec_rule = TRUE;
2850 }
2851 }
2852
2853 if (exec_rule) {
2854 const char *new_arg = NULL;
2855 unsigned int rule_flags = *((unsigned int *) c->argv[4]);
2856
2857 rewrite_log("rewrite_fixup(): executing RewriteRule");
2858 new_arg = rewrite_subst(cmd, (char *) c->argv[1]);
2859
2860 if (strlen(new_arg) > 0) {
2861 int flags = PR_STR_FL_PRESERVE_COMMENTS;
2862 char *param, *dup_arg;
2863 array_header *list;
2864
2865 rewrite_replace_cmd_arg(cmd, (char *) new_arg);
2866 rewrite_log("rewrite_fixup(): %s arg now '%s'", cmd_name, new_arg);
2867
2868 /* Be sure to overwrite the entire cmd->argv array, not just
2869 * cmd->arg.
2870 */
2871 cmd->argc = 0;
2872 list = make_array(cmd->pool, 2, sizeof(char *));
2873
2874 *((char **) push_array(list)) = pstrdup(cmd->pool, cmd->argv[0]);
2875 cmd->argc++;
2876
2877 /* Note: The "SYMLINK" test is for handling the SFTP SYMLINK request
2878 * e.g from mod_sftp. There is no SYMLINK FTP command.
2879 */
2880 if (pr_cmd_cmp(cmd, PR_CMD_SITE_ID) == 0 ||
2881 pr_cmd_strcmp(cmd, "SYMLINK") == 0) {
2882 flags |= PR_STR_FL_PRESERVE_WHITESPACE;
2883
2884 if (strcasecmp(cmd->argv[1], "CHGRP") == 0 ||
2885 strcasecmp(cmd->argv[1], "CHMOD") == 0) {
2886 *((char **) push_array(list)) = pstrdup(cmd->pool, cmd->argv[1]);
2887 cmd->argc++;
2888 }
2889 }
2890
2891 dup_arg = pstrdup(cmd->tmp_pool, new_arg);
2892 while ((param = pr_str_get_word(&dup_arg, flags)) != NULL) {
2893 pr_signals_handle();
2894
2895 *((char **) push_array(list)) = pstrdup(cmd->pool, param);
2896 cmd->argc++;
2897 }
2898
2899 /* NULL-terminate the list. */
2900 *((char **) push_array(list)) = NULL;
2901
2902 cmd->argv = list->elts;
2903 pr_cmd_clear_cache(cmd);
2904
2905 } else {
2906 rewrite_log("rewrite_fixup(): error processing RewriteRule: generated "
2907 "empty command argument, which is not allowed");
2908 }
2909
2910 /* If this Rule is marked as "last", break out of the loop. */
2911 if (rule_flags & REWRITE_RULE_FLAG_LAST) {
2912 rewrite_log("rewrite_fixup(): Rule marked as 'last', done processing "
2913 "Rules");
2914 break;
2915 }
2916 }
2917
2918 /* When processing multiple RewriteRules, we may have changed cmd->arg.
2919 * Thus we need to update the locally cached version of it.
2920 */
2921 cmd_arg = cmd->arg;
2922
2923 c = find_config_next(c, c->next, CONF_PARAM, "RewriteRule", FALSE);
2924 }
2925
2926 return PR_DECLINED(cmd);
2927 }
2928
2929 /* Events handlers
2930 */
2931
2932 static void rewrite_exit_ev(const void *event_data, void *user_data) {
2933 rewrite_closelog();
2934 return;
2935 }
2936
2937 #if defined(PR_SHARED_MODULE)
2938 static void rewrite_mod_unload_ev(const void *event_data, void *user_data) {
2939 if (strcmp("mod_rewrite.c", (const char *) event_data) == 0) {
2940 pr_event_unregister(&rewrite_module, NULL, NULL);
2941 pr_regexp_free(&rewrite_module, NULL);
2942 if (rewrite_pool) {
2943 destroy_pool(rewrite_pool);
2944 rewrite_pool = NULL;
2945 }
2946 }
2947 }
2948 #endif /* PR_SHARED_MODULE */
2949
2950 static void rewrite_restart_ev(const void *event_data, void *user_data) {
2951 pr_regexp_free(&rewrite_module, NULL);
2952
2953 if (rewrite_pool != NULL) {
2954 destroy_pool(rewrite_pool);
2955 rewrite_cond_pool = NULL;
2956 rewrite_conds = NULL;
2957
2958 /* Re-allocate a pool for this module's use. */
2959 rewrite_pool = make_sub_pool(permanent_pool);
2960 pr_pool_tag(rewrite_pool, MOD_REWRITE_VERSION);
2961 }
2962 }
2963
2964 static void rewrite_rewrite_home_ev(const void *event_data, void *user_data) {
2965 const char *pw_dir;
2966 pool *tmp_pool;
2967 cmd_rec *cmd;
2968 modret_t *mr;
2969
2970 rewrite_log("handling 'mod_auth.rewrite-home' event");
2971 pw_dir = pr_table_get(session.notes, "mod_auth.home-dir", NULL);
2972 if (pw_dir == NULL) {
2973 /* Nothing to be done. */
2974 rewrite_log("no 'mod_auth.home-dir' found in session.notes");
2975 return;
2976 }
2977
2978 tmp_pool = pr_pool_create_sz(rewrite_pool, 128);
2979 pr_pool_tag(tmp_pool, "rewrite home pool");
2980
2981 cmd = pr_cmd_alloc(tmp_pool, 2, pstrdup(tmp_pool, "REWRITE_HOME"), pw_dir);
2982 cmd->arg = pstrdup(tmp_pool, pw_dir);
2983 cmd->tmp_pool = tmp_pool;
2984
2985 /* Call rewrite_fixup() directly, rather than going through the entire
2986 * command dispatch mechanism.
2987 */
2988 mr = rewrite_fixup(cmd);
2989 if (MODRET_ISERROR(mr)) {
2990 rewrite_log("unable to rewrite home '%s'", pw_dir);
2991 destroy_pool(tmp_pool);
2992 return;
2993 }
2994
2995 if (strcmp(pw_dir, cmd->arg) != 0) {
2996 rewrite_log("rewrote home to be '%s'", cmd->arg);
2997
2998 /* Make sure to use a pool whose lifetime is longer/outside of the pools
2999 * used here.
3000 */
3001 if (pr_table_set(session.notes, "mod_auth.home-dir",
3002 pstrdup(session.pool, cmd->arg), 0) < 0) {
3003 pr_trace_msg("auth", 3, MOD_REWRITE_VERSION
3004 ": error stashing home directory in session.notes: %s",
3005 strerror(errno));
3006 destroy_pool(tmp_pool);
3007 return;
3008 }
3009
3010 } else {
3011 rewrite_log("home directory '%s' not changed by RewriteHome", pw_dir);
3012 }
3013
3014 destroy_pool(tmp_pool);
3015 }
3016
3017 static void rewrite_sess_reinit_ev(const void *event_data, void *user_data) {
3018 int res;
3019 config_rec *c;
3020
3021 /* A HOST command changed the main_server pointer; reinitialize ourselves. */
3022
3023 pr_event_unregister(&rewrite_module, "core.exit", rewrite_exit_ev);
3024 pr_event_unregister(&rewrite_module, "core.session-reinit",
3025 rewrite_sess_reinit_ev);
3026 pr_event_unregister(&rewrite_module, "mod_auth.rewrite-home",
3027 rewrite_rewrite_home_ev);
3028
3029 /* Reset defaults. */
3030 rewrite_engine = FALSE;
3031 (void) close(rewrite_logfd);
3032 rewrite_logfd = -1;
3033 rewrite_logfile = NULL;
3034 rewrite_max_replace = PR_STR_MAX_REPLACEMENTS;
3035
3036 /* Close any opened FIFO RewriteMaps. */
3037 c = find_config(session.prev_server->conf, CONF_PARAM, "RewriteMap", FALSE);
3038 while (c != NULL) {
3039 pr_signals_handle();
3040
3041 if (strcmp(c->argv[1], "fifo") == 0) {
3042 int fd;
3043
3044 fd = *((int *) c->argv[3]);
3045 (void) close(fd);
3046 *((int *) c->argv[3]) = -1;
3047 }
3048
3049 c = find_config_next(c, c->next, CONF_PARAM, "RewriteMap", FALSE);
3050 }
3051
3052 res = rewrite_sess_init();
3053 if (res < 0) {
3054 pr_session_disconnect(&rewrite_module,
3055 PR_SESS_DISCONNECT_SESSION_INIT_FAILED, NULL);
3056 }
3057 }
3058
3059
3060 /* Initialization functions
3061 */
3062
3063 static int rewrite_init(void) {
3064
3065 /* Allocate a pool for this module's use. */
3066 if (rewrite_pool == NULL) {
3067 rewrite_pool = make_sub_pool(permanent_pool);
3068 pr_pool_tag(rewrite_pool, MOD_REWRITE_VERSION);
3069 }
3070
3071 #if defined(PR_SHARED_MODULE)
3072 pr_event_register(&rewrite_module, "core.module-unload",
3073 rewrite_mod_unload_ev, NULL);
3074 #endif /* PR_SHARED_MODULE */
3075
3076 /* Add a restart handler. */
3077 pr_event_register(&rewrite_module, "core.restart", rewrite_restart_ev,
3078 NULL);
3079
3080 return 0;
3081 }
3082
3083 static int rewrite_sess_init(void) {
3084 config_rec *c = NULL;
3085 unsigned char *engine = NULL;
3086
3087 pr_event_register(&rewrite_module, "core.session-reinit",
3088 rewrite_sess_reinit_ev, NULL);
3089
3090 /* Is RewriteEngine on? */
3091 engine = get_param_ptr(main_server->conf, "RewriteEngine", FALSE);
3092 if (engine == NULL ||
3093 *engine == FALSE) {
3094 rewrite_engine = FALSE;
3095 return 0;
3096 }
3097
3098 rewrite_engine = TRUE;
3099
3100 /* Open the RewriteLog, if present. */
3101 rewrite_openlog();
3102
3103 /* Make sure proper cleanup is done when a child exits. */
3104 pr_event_register(&rewrite_module, "core.exit", rewrite_exit_ev, NULL);
3105
3106 /* Loop through all the RewriteMap config_recs for this server, and for
3107 * all FIFO maps, open FIFO file descriptors. This has to be done here,
3108 * before any possible chroot occurs.
3109 */
3110
3111 c = find_config(main_server->conf, CONF_PARAM, "RewriteMap", FALSE);
3112 while (c) {
3113 pr_signals_handle();
3114
3115 if (strcmp(c->argv[1], "fifo") == 0) {
3116 PRIVS_ROOT
3117 if (rewrite_open_fifo(c) < 0) {
3118 rewrite_log("error preparing FIFO RewriteMap");
3119 }
3120 PRIVS_RELINQUISH
3121 }
3122
3123 c = find_config_next(c, c->next, CONF_PARAM, "RewriteMap", FALSE);
3124 }
3125
3126 /* See if we need to register an event handler for the RewriteHome event. */
3127 c = find_config(main_server->conf, CONF_PARAM, "RewriteHome", FALSE);
3128 if (c &&
3129 *((int *) c->argv[0]) == TRUE) {
3130 pr_event_register(&rewrite_module, "mod_auth.rewrite-home",
3131 rewrite_rewrite_home_ev, NULL);
3132 }
3133
3134 /* Check for the configured number of max replacements */
3135 c = find_config(main_server->conf, CONF_PARAM, "RewriteMaxReplace", FALSE);
3136 if (c) {
3137 rewrite_max_replace = *((unsigned int *) c->argv[0]);
3138 }
3139
3140 return 0;
3141 }
3142
3143 /* Module API Tables
3144 */
3145
3146 static conftable rewrite_conftab[] = {
3147 { "RewriteCondition", set_rewritecondition, NULL },
3148 { "RewriteEngine", set_rewriteengine, NULL },
3149 { "RewriteLock", set_rewritelock, NULL },
3150 { "RewriteMaxReplace", set_rewritemaxreplace, NULL },
3151 { "RewriteLog", set_rewritelog, NULL },
3152 { "RewriteMap", set_rewritemap, NULL },
3153 { "RewriteRule", set_rewriterule, NULL },
3154 { NULL }
3155 };
3156
3157 static cmdtable rewrite_cmdtab[] = {
3158 { PRE_CMD, C_ANY, G_NONE, rewrite_fixup, FALSE, FALSE },
3159 { 0, NULL }
3160 };
3161
3162 module rewrite_module = {
3163
3164 /* Always NULL */
3165 NULL, NULL,
3166
3167 /* Module API version 2.0 */
3168 0x20,
3169
3170 /* Module name */
3171 "rewrite",
3172
3173 /* Module configuration handler table */
3174 rewrite_conftab,
3175
3176 /* Module command handler table */
3177 rewrite_cmdtab,
3178
3179 /* Module authentication handler table */
3180 NULL,
3181
3182 /* Module initialization function */
3183 rewrite_init,
3184
3185 /* Session initialization function */
3186 rewrite_sess_init,
3187
3188 /* Module version */
3189 MOD_REWRITE_VERSION
3190 };
3191 #endif /* regex support */