1/*	$NetBSD: kadm_conn.c,v 1.2 2017/01/28 21:31:44 christos Exp $	*/
2
3/*
4 * Copyright (c) 2000 - 2004 Kungliga Tekniska H��gskolan
5 * (Royal Institute of Technology, Stockholm, Sweden).
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions and the following disclaimer.
14 *
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 *
19 * 3. Neither the name of the Institute nor the names of its contributors
20 *    may be used to endorse or promote products derived from this software
21 *    without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 */
35
36#include "kadmin_locl.h"
37#ifdef HAVE_SYS_WAIT_H
38#include <sys/wait.h>
39#endif
40
41extern int daemon_child;
42
43struct kadm_port {
44    char *port;
45    unsigned short def_port;
46    struct kadm_port *next;
47} *kadm_ports;
48
49static void
50add_kadm_port(krb5_context contextp, const char *service, unsigned int port)
51{
52    struct kadm_port *p;
53    p = malloc(sizeof(*p));
54    if(p == NULL) {
55	krb5_warnx(contextp, "failed to allocate %lu bytes\n",
56		   (unsigned long)sizeof(*p));
57	return;
58    }
59
60    p->port = strdup(service);
61    p->def_port = port;
62
63    p->next = kadm_ports;
64    kadm_ports = p;
65}
66
67static void
68add_standard_ports (krb5_context contextp)
69{
70    add_kadm_port(contextp, "kerberos-adm", 749);
71}
72
73/*
74 * parse the set of space-delimited ports in `str' and add them.
75 * "+" => all the standard ones
76 * otherwise it's port|service[/protocol]
77 */
78
79void
80parse_ports(krb5_context contextp, const char *str)
81{
82    char p[128];
83
84    while(strsep_copy(&str, " \t", p, sizeof(p)) != -1) {
85	if(strcmp(p, "+") == 0)
86	    add_standard_ports(contextp);
87	else
88	    add_kadm_port(contextp, p, 0);
89    }
90}
91
92static pid_t pgrp;
93sig_atomic_t term_flag, doing_useful_work;
94
95static RETSIGTYPE
96sigchld(int sig)
97{
98    int status;
99    /*
100     * waitpid() is async safe. will return -1 or 0 on no more zombie
101     * children
102     */
103    while ((waitpid(-1, &status, WNOHANG)) > 0)
104	;
105    SIGRETURN(0);
106}
107
108static RETSIGTYPE
109terminate(int sig)
110{
111    if(getpid() == pgrp) {
112	/* parent */
113	term_flag = 1;
114	signal(sig, SIG_IGN);
115	killpg(pgrp, sig);
116    } else {
117	/* child */
118	if(doing_useful_work)
119	    term_flag = 1;
120	else
121	    exit(0);
122    }
123    SIGRETURN(0);
124}
125
126static int
127spawn_child(krb5_context contextp, int *socks,
128	    unsigned int num_socks, int this_sock)
129{
130    int e;
131    size_t i;
132    struct sockaddr_storage __ss;
133    struct sockaddr *sa = (struct sockaddr *)&__ss;
134    socklen_t sa_size = sizeof(__ss);
135    krb5_socket_t s;
136    pid_t pid;
137    krb5_address addr;
138    char buf[128];
139    size_t buf_len;
140
141    s = accept(socks[this_sock], sa, &sa_size);
142    if(rk_IS_BAD_SOCKET(s)) {
143	krb5_warn(contextp, rk_SOCK_ERRNO, "accept");
144	return 1;
145    }
146    e = krb5_sockaddr2address(contextp, sa, &addr);
147    if(e)
148	krb5_warn(contextp, e, "krb5_sockaddr2address");
149    else {
150	e = krb5_print_address (&addr, buf, sizeof(buf),
151				&buf_len);
152	if(e)
153	    krb5_warn(contextp, e, "krb5_print_address");
154	else
155	    krb5_warnx(contextp, "connection from %s", buf);
156	krb5_free_address(contextp, &addr);
157    }
158
159    pid = fork();
160    if(pid == 0) {
161	for(i = 0; i < num_socks; i++)
162	    rk_closesocket(socks[i]);
163	dup2(s, STDIN_FILENO);
164	dup2(s, STDOUT_FILENO);
165	if(s != STDIN_FILENO && s != STDOUT_FILENO)
166	    rk_closesocket(s);
167	return 0;
168    } else {
169	rk_closesocket(s);
170    }
171    return 1;
172}
173
174static void
175wait_for_connection(krb5_context contextp,
176		    krb5_socket_t *socks, unsigned int num_socks)
177{
178    unsigned int i;
179    int e;
180    fd_set orig_read_set, read_set;
181    int status, max_fd = -1;
182
183    FD_ZERO(&orig_read_set);
184
185    for(i = 0; i < num_socks; i++) {
186#ifdef FD_SETSIZE
187	if (socks[i] >= FD_SETSIZE)
188	    errx (1, "fd too large");
189#endif
190	FD_SET(socks[i], &orig_read_set);
191	max_fd = max(max_fd, socks[i]);
192    }
193
194    pgrp = getpid();
195
196    /* systemd may cause setpgid to fail with EPERM */
197    if(setpgid(0, pgrp) < 0 && errno != EPERM)
198	err(1, "setpgid");
199
200    signal(SIGTERM, terminate);
201    signal(SIGINT, terminate);
202    signal(SIGCHLD, sigchld);
203
204    while (term_flag == 0) {
205	read_set = orig_read_set;
206	e = select(max_fd + 1, &read_set, NULL, NULL, NULL);
207	if(rk_IS_SOCKET_ERROR(e)) {
208	    if(rk_SOCK_ERRNO != EINTR)
209		krb5_warn(contextp, rk_SOCK_ERRNO, "select");
210	} else if(e == 0)
211	    krb5_warnx(contextp, "select returned 0");
212	else {
213	    for(i = 0; i < num_socks; i++) {
214		if(FD_ISSET(socks[i], &read_set))
215		    if(spawn_child(contextp, socks, num_socks, i) == 0)
216			return;
217	    }
218	}
219    }
220    signal(SIGCHLD, SIG_IGN);
221
222    while ((waitpid(-1, &status, WNOHANG)) > 0)
223	;
224
225    exit(0);
226}
227
228
229void
230start_server(krb5_context contextp, const char *port_str)
231{
232    int e;
233    struct kadm_port *p;
234
235    krb5_socket_t *socks = NULL, *tmp;
236    unsigned int num_socks = 0;
237    int i;
238
239    if (port_str == NULL)
240	port_str = "+";
241
242    parse_ports(contextp, port_str);
243
244    for(p = kadm_ports; p; p = p->next) {
245	struct addrinfo hints, *ai, *ap;
246	char portstr[32];
247	memset (&hints, 0, sizeof(hints));
248	hints.ai_flags    = AI_PASSIVE;
249	hints.ai_socktype = SOCK_STREAM;
250
251	e = getaddrinfo(NULL, p->port, &hints, &ai);
252	if(e) {
253	    snprintf(portstr, sizeof(portstr), "%u", p->def_port);
254	    e = getaddrinfo(NULL, portstr, &hints, &ai);
255	}
256
257	if(e) {
258	    krb5_warn(contextp, krb5_eai_to_heim_errno(e, errno),
259		      "%s", portstr);
260	    continue;
261	}
262	i = 0;
263	for(ap = ai; ap; ap = ap->ai_next)
264	    i++;
265	tmp = realloc(socks, (num_socks + i) * sizeof(*socks));
266	if(tmp == NULL) {
267	    krb5_warnx(contextp, "failed to reallocate %lu bytes",
268		       (unsigned long)(num_socks + i) * sizeof(*socks));
269            freeaddrinfo(ai);
270	    continue;
271	}
272	socks = tmp;
273	for(ap = ai; ap; ap = ap->ai_next) {
274	    krb5_socket_t s = socket(ap->ai_family, ap->ai_socktype, ap->ai_protocol);
275	    if(rk_IS_BAD_SOCKET(s)) {
276		krb5_warn(contextp, rk_SOCK_ERRNO, "socket");
277		continue;
278	    }
279
280	    socket_set_reuseaddr(s, 1);
281	    socket_set_ipv6only(s, 1);
282
283	    if (rk_IS_SOCKET_ERROR(bind (s, ap->ai_addr, ap->ai_addrlen))) {
284		krb5_warn(contextp, rk_SOCK_ERRNO, "bind");
285		rk_closesocket(s);
286		continue;
287	    }
288	    if (rk_IS_SOCKET_ERROR(listen (s, SOMAXCONN))) {
289		krb5_warn(contextp, rk_SOCK_ERRNO, "listen");
290		rk_closesocket(s);
291		continue;
292	    }
293	    socks[num_socks++] = s;
294	}
295	freeaddrinfo (ai);
296    }
297    if(num_socks == 0)
298	krb5_errx(contextp, 1, "no sockets to listen to - exiting");
299
300    roken_detach_finish(NULL, daemon_child);
301
302    wait_for_connection(contextp, socks, num_socks);
303    free(socks);
304}
305