dropbear: update to 2013.62
[tomato.git] / release / src / router / dropbear / svr-main.c
blob73b281baae7f622973c79ed9a65b57f8cd705985
1 /*
2 * Dropbear - a SSH2 server
3 *
4 * Copyright (c) 2002-2006 Matt Johnston
5 * All rights reserved.
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 * SOFTWARE. */
25 #include "includes.h"
26 #include "dbutil.h"
27 #include "session.h"
28 #include "buffer.h"
29 #include "signkey.h"
30 #include "runopts.h"
31 #include "dbrandom.h"
32 #include "crypto_desc.h"
34 static size_t listensockets(int *sock, size_t sockcount, int *maxfd);
35 static void sigchld_handler(int dummy);
36 static void sigsegv_handler(int);
37 static void sigintterm_handler(int fish);
38 #ifdef INETD_MODE
39 static void main_inetd();
40 #endif
41 #ifdef NON_INETD_MODE
42 static void main_noinetd();
43 #endif
44 static void commonsetup();
46 #if defined(DBMULTI_dropbear) || !defined(DROPBEAR_MULTI)
47 #if defined(DBMULTI_dropbear) && defined(DROPBEAR_MULTI)
48 int dropbear_main(int argc, char ** argv)
49 #else
50 int main(int argc, char ** argv)
51 #endif
53 _dropbear_exit = svr_dropbear_exit;
54 _dropbear_log = svr_dropbear_log;
56 disallow_core();
58 /* get commandline options */
59 svr_getopts(argc, argv);
61 #ifdef INETD_MODE
62 /* service program mode */
63 if (svr_opts.inetdmode) {
64 main_inetd();
65 /* notreached */
67 #endif
69 #ifdef NON_INETD_MODE
70 main_noinetd();
71 /* notreached */
72 #endif
74 dropbear_exit("Compiled without normal mode, can't run without -i\n");
75 return -1;
77 #endif
79 #ifdef INETD_MODE
80 static void main_inetd() {
81 char *host, *port = NULL;
83 /* Set up handlers, syslog, seed random */
84 commonsetup();
86 /* In case our inetd was lax in logging source addresses */
87 get_socket_address(0, NULL, NULL, &host, &port, 0);
88 dropbear_log(LOG_INFO, "Child connection from %s:%s", host, port);
89 m_free(host);
90 m_free(port);
92 /* Don't check the return value - it may just fail since inetd has
93 * already done setsid() after forking (xinetd on Darwin appears to do
94 * this */
95 setsid();
97 /* Start service program
98 * -1 is a dummy childpipe, just something we can close() without
99 * mattering. */
100 svr_session(0, -1);
102 /* notreached */
104 #endif /* INETD_MODE */
106 #ifdef NON_INETD_MODE
107 void main_noinetd() {
108 fd_set fds;
109 unsigned int i, j;
110 int val;
111 int maxsock = -1;
112 int listensocks[MAX_LISTEN_ADDR];
113 size_t listensockcount = 0;
114 FILE *pidfile = NULL;
116 int childpipes[MAX_UNAUTH_CLIENTS];
117 char * preauth_addrs[MAX_UNAUTH_CLIENTS];
119 int childsock;
120 int childpipe[2];
122 /* Note: commonsetup() must happen before we daemon()ise. Otherwise
123 daemon() will chdir("/"), and we won't be able to find local-dir
124 hostkeys. */
125 commonsetup();
127 /* sockets to identify pre-authenticated clients */
128 for (i = 0; i < MAX_UNAUTH_CLIENTS; i++) {
129 childpipes[i] = -1;
131 memset(preauth_addrs, 0x0, sizeof(preauth_addrs));
133 /* Set up the listening sockets */
134 listensockcount = listensockets(listensocks, MAX_LISTEN_ADDR, &maxsock);
135 if (listensockcount == 0)
137 dropbear_exit("No listening ports available.");
140 for (i = 0; i < listensockcount; i++) {
141 set_sock_priority(listensocks[i], DROPBEAR_PRIO_LOWDELAY);
142 FD_SET(listensocks[i], &fds);
145 /* fork */
146 if (svr_opts.forkbg) {
147 int closefds = 0;
148 #ifndef DEBUG_TRACE
149 if (!svr_opts.usingsyslog) {
150 closefds = 1;
152 #endif
153 if (daemon(0, closefds) < 0) {
154 dropbear_exit("Failed to daemonize: %s", strerror(errno));
158 /* should be done after syslog is working */
159 if (svr_opts.forkbg) {
160 dropbear_log(LOG_INFO, "Running in background");
161 } else {
162 dropbear_log(LOG_INFO, "Not backgrounding");
165 /* create a PID file so that we can be killed easily */
166 pidfile = fopen(svr_opts.pidfile, "w");
167 if (pidfile) {
168 fprintf(pidfile, "%d\n", getpid());
169 fclose(pidfile);
172 /* incoming connection select loop */
173 for(;;) {
175 FD_ZERO(&fds);
177 /* listening sockets */
178 for (i = 0; i < listensockcount; i++) {
179 FD_SET(listensocks[i], &fds);
182 /* pre-authentication clients */
183 for (i = 0; i < MAX_UNAUTH_CLIENTS; i++) {
184 if (childpipes[i] >= 0) {
185 FD_SET(childpipes[i], &fds);
186 maxsock = MAX(maxsock, childpipes[i]);
190 val = select(maxsock+1, &fds, NULL, NULL, NULL);
192 if (exitflag) {
193 unlink(svr_opts.pidfile);
194 dropbear_exit("Terminated by signal");
197 if (val == 0) {
198 /* timeout reached - shouldn't happen. eh */
199 continue;
202 if (val < 0) {
203 if (errno == EINTR) {
204 continue;
206 dropbear_exit("Listening socket error");
209 /* close fds which have been authed or closed - svr-auth.c handles
210 * closing the auth sockets on success */
211 for (i = 0; i < MAX_UNAUTH_CLIENTS; i++) {
212 if (childpipes[i] >= 0 && FD_ISSET(childpipes[i], &fds)) {
213 m_close(childpipes[i]);
214 childpipes[i] = -1;
215 m_free(preauth_addrs[i]);
219 /* handle each socket which has something to say */
220 for (i = 0; i < listensockcount; i++) {
221 size_t num_unauthed_for_addr = 0;
222 size_t num_unauthed_total = 0;
223 char *remote_host = NULL, *remote_port = NULL;
224 pid_t fork_ret = 0;
225 size_t conn_idx = 0;
226 struct sockaddr_storage remoteaddr;
227 socklen_t remoteaddrlen;
229 if (!FD_ISSET(listensocks[i], &fds))
230 continue;
232 remoteaddrlen = sizeof(remoteaddr);
233 childsock = accept(listensocks[i],
234 (struct sockaddr*)&remoteaddr, &remoteaddrlen);
236 if (childsock < 0) {
237 /* accept failed */
238 continue;
241 /* Limit the number of unauthenticated connections per IP */
242 getaddrstring(&remoteaddr, &remote_host, NULL, 0);
244 num_unauthed_for_addr = 0;
245 num_unauthed_total = 0;
246 for (j = 0; j < MAX_UNAUTH_CLIENTS; j++) {
247 if (childpipes[j] >= 0) {
248 num_unauthed_total++;
249 if (strcmp(remote_host, preauth_addrs[j]) == 0) {
250 num_unauthed_for_addr++;
252 } else {
253 /* a free slot */
254 conn_idx = j;
258 if (num_unauthed_total >= MAX_UNAUTH_CLIENTS
259 || num_unauthed_for_addr >= MAX_UNAUTH_PER_IP) {
260 goto out;
263 seedrandom();
265 if (pipe(childpipe) < 0) {
266 TRACE(("error creating child pipe"))
267 goto out;
270 #ifdef DEBUG_NOFORK
271 fork_ret = 0;
272 #else
273 fork_ret = fork();
274 #endif
275 if (fork_ret < 0) {
276 dropbear_log(LOG_WARNING, "Error forking: %s", strerror(errno));
277 goto out;
280 addrandom((void*)&fork_ret, sizeof(fork_ret));
282 if (fork_ret > 0) {
284 /* parent */
285 childpipes[conn_idx] = childpipe[0];
286 m_close(childpipe[1]);
287 preauth_addrs[conn_idx] = remote_host;
288 remote_host = NULL;
290 } else {
292 /* child */
293 #ifdef DEBUG_FORKGPROF
294 extern void _start(void), etext(void);
295 monstartup((u_long)&_start, (u_long)&etext);
296 #endif /* DEBUG_FORKGPROF */
298 getaddrstring(&remoteaddr, NULL, &remote_port, 0);
299 dropbear_log(LOG_INFO, "Child connection from %s:%s", remote_host, remote_port);
300 m_free(remote_host);
301 m_free(remote_port);
303 #ifndef DEBUG_NOFORK
304 if (setsid() < 0) {
305 dropbear_exit("setsid: %s", strerror(errno));
307 #endif
309 /* make sure we close sockets */
310 for (i = 0; i < listensockcount; i++) {
311 m_close(listensocks[i]);
314 m_close(childpipe[0]);
316 /* start the session */
317 svr_session(childsock, childpipe[1]);
318 /* don't return */
319 dropbear_assert(0);
322 out:
323 /* This section is important for the parent too */
324 m_close(childsock);
325 if (remote_host) {
326 m_free(remote_host);
329 } /* for(;;) loop */
331 /* don't reach here */
333 #endif /* NON_INETD_MODE */
336 /* catch + reap zombie children */
337 static void sigchld_handler(int UNUSED(unused)) {
338 struct sigaction sa_chld;
340 while(waitpid(-1, NULL, WNOHANG) > 0);
342 sa_chld.sa_handler = sigchld_handler;
343 sa_chld.sa_flags = SA_NOCLDSTOP;
344 if (sigaction(SIGCHLD, &sa_chld, NULL) < 0) {
345 dropbear_exit("signal() error");
349 /* catch any segvs */
350 static void sigsegv_handler(int UNUSED(unused)) {
351 fprintf(stderr, "Aiee, segfault! You should probably report "
352 "this as a bug to the developer\n");
353 exit(EXIT_FAILURE);
356 /* catch ctrl-c or sigterm */
357 static void sigintterm_handler(int UNUSED(unused)) {
359 exitflag = 1;
362 /* Things used by inetd and non-inetd modes */
363 static void commonsetup() {
365 struct sigaction sa_chld;
366 #ifndef DISABLE_SYSLOG
367 if (svr_opts.usingsyslog) {
368 startsyslog();
370 #endif
372 /* set up cleanup handler */
373 if (signal(SIGINT, sigintterm_handler) == SIG_ERR ||
374 #ifndef DEBUG_VALGRIND
375 signal(SIGTERM, sigintterm_handler) == SIG_ERR ||
376 #endif
377 signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
378 dropbear_exit("signal() error");
381 /* catch and reap zombie children */
382 sa_chld.sa_handler = sigchld_handler;
383 sa_chld.sa_flags = SA_NOCLDSTOP;
384 sigemptyset(&sa_chld.sa_mask);
385 if (sigaction(SIGCHLD, &sa_chld, NULL) < 0) {
386 dropbear_exit("signal() error");
388 if (signal(SIGSEGV, sigsegv_handler) == SIG_ERR) {
389 dropbear_exit("signal() error");
392 crypto_init();
394 /* Now we can setup the hostkeys - needs to be after logging is on,
395 * otherwise we might end up blatting error messages to the socket */
396 load_all_hostkeys();
398 seedrandom();
401 /* Set up listening sockets for all the requested ports */
402 static size_t listensockets(int *sock, size_t sockcount, int *maxfd) {
404 unsigned int i;
405 char* errstring = NULL;
406 size_t sockpos = 0;
407 int nsock;
409 TRACE(("listensockets: %d to try\n", svr_opts.portcount))
411 for (i = 0; i < svr_opts.portcount; i++) {
413 TRACE(("listening on '%s:%s'", svr_opts.addresses[i], svr_opts.ports[i]))
415 nsock = dropbear_listen(svr_opts.addresses[i], svr_opts.ports[i], &sock[sockpos],
416 sockcount - sockpos,
417 &errstring, maxfd);
419 if (nsock < 0) {
420 dropbear_log(LOG_WARNING, "Failed listening on '%s': %s",
421 svr_opts.ports[i], errstring);
422 m_free(errstring);
423 continue;
426 sockpos += nsock;
429 return sockpos;