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