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