1 /*
2  * percent_x() takes a string and performs %<char> expansions. It aborts the
3  * program when the expansion would overflow the output buffer. The result
4  * of %<char> expansion may be passed on to a shell process. For this
5  * reason, characters with a special meaning to shells are replaced by
6  * underscores.
7  *
8  * Diagnostics are reported through syslog(3).
9  *
10  * Author: Wietse Venema, Eindhoven University of Technology, The Netherlands.
11  */
12
13#ifndef lint
14static char sccsid[] = "@(#) percent_x.c 1.4 94/12/28 17:42:37";
15#endif
16
17/* System libraries. */
18
19#include <stdio.h>
20#include <syslog.h>
21#include <string.h>
22#include <unistd.h>
23
24extern void exit();
25
26/* Local stuff. */
27
28#include "tcpd.h"
29
30/* percent_x - do %<char> expansion, abort if result buffer is too small */
31
32char   *percent_x(char *result, int result_len, char *string,
33    struct request_info *request)
34{
35    char   *bp = result;
36    char   *end = result + result_len - 1;	/* end of result buffer */
37    char   *expansion;
38    int     expansion_len;
39    static char ok_chars[] = "1234567890!@%-_=+:,./\
40abcdefghijklmnopqrstuvwxyz\
41ABCDEFGHIJKLMNOPQRSTUVWXYZ";
42    char   *str = string;
43    char   *cp;
44    int     ch;
45
46    /*
47     * Warning: we may be called from a child process or after pattern
48     * matching, so we cannot use clean_exit() or tcpd_jump().
49     */
50
51    while (*str) {
52	if (*str == '%' && (ch = str[1]) != 0) {
53	    str += 2;
54	    expansion =
55		ch == 'a' ? eval_hostaddr(request->client) :
56		ch == 'A' ? eval_hostaddr(request->server) :
57		ch == 'c' ? eval_client(request) :
58		ch == 'd' ? eval_daemon(request) :
59		ch == 'h' ? eval_hostinfo(request->client) :
60		ch == 'H' ? eval_hostinfo(request->server) :
61		ch == 'n' ? eval_hostname(request->client) :
62		ch == 'N' ? eval_hostname(request->server) :
63		ch == 'p' ? eval_pid(request) :
64		ch == 's' ? eval_server(request) :
65		ch == 'u' ? eval_user(request) :
66		ch == '%' ? "%" : (tcpd_warn("unrecognized %%%c", ch), "");
67	    for (cp = expansion; *(cp += strspn(cp, ok_chars)); /* */ )
68		*cp = '_';
69	    expansion_len = cp - expansion;
70	} else {
71	    expansion = str++;
72	    expansion_len = 1;
73	}
74	if (bp + expansion_len >= end) {
75	    tcpd_warn("percent_x: expansion too long: %.30s...", result);
76	    sleep(5);
77	    exit(0);
78	}
79	memcpy(bp, expansion, expansion_len);
80	bp += expansion_len;
81    }
82    *bp = 0;
83    return (result);
84}
85