dropbar: Update to version 2013.60.1.
[tomato.git] / release / src / router / dropbear / svr-main.c
blob461aeaf51d92e1d0b66b9582d829dc9d44a7fb8c
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 "random.h"
33 static size_t listensockets(int *sock, size_t sockcount, int *maxfd);
34 static void sigchld_handler(int dummy);
35 static void sigsegv_handler(int);
36 static void sigintterm_handler(int fish);
37 #ifdef INETD_MODE
38 static void main_inetd();
39 #endif
40 #ifdef NON_INETD_MODE
41 static void main_noinetd();
42 #endif
43 static void commonsetup();
45 #if defined(DBMULTI_dropbear) || !defined(DROPBEAR_MULTI)
46 #if defined(DBMULTI_dropbear) && defined(DROPBEAR_MULTI)
47 int dropbear_main(int argc, char ** argv)
48 #else
49 int main(int argc, char ** argv)
50 #endif
52 _dropbear_exit = svr_dropbear_exit;
53 _dropbear_log = svr_dropbear_log;
55 disallow_core();
57 /* get commandline options */
58 svr_getopts(argc, argv);
60 #ifdef INETD_MODE
61 /* service program mode */
62 if (svr_opts.inetdmode) {
63 main_inetd();
64 /* notreached */
66 #endif
68 #ifdef NON_INETD_MODE
69 main_noinetd();
70 /* notreached */
71 #endif
73 dropbear_exit("Compiled without normal mode, can't run without -i\n");
74 return -1;
76 #endif
78 #ifdef INETD_MODE
79 static void main_inetd() {
80 char *host, *port = NULL;
82 /* Set up handlers, syslog, seed random */
83 commonsetup();
85 /* In case our inetd was lax in logging source addresses */
86 get_socket_address(0, NULL, NULL, &host, &port, 0);
87 dropbear_log(LOG_INFO, "Child connection from %s:%s", host, port);
88 m_free(host);
89 m_free(port);
91 /* Don't check the return value - it may just fail since inetd has
92 * already done setsid() after forking (xinetd on Darwin appears to do
93 * this */
94 setsid();
96 /* Start service program
97 * -1 is a dummy childpipe, just something we can close() without
98 * mattering. */
99 svr_session(0, -1);
101 /* notreached */
103 #endif /* INETD_MODE */
105 #ifdef NON_INETD_MODE
106 void main_noinetd() {
107 fd_set fds;
108 unsigned int i, j;
109 int val;
110 int maxsock = -1;
111 int listensocks[MAX_LISTEN_ADDR];
112 size_t listensockcount = 0;
113 FILE *pidfile = NULL;
115 int childpipes[MAX_UNAUTH_CLIENTS];
116 char * preauth_addrs[MAX_UNAUTH_CLIENTS];
118 int childsock;
119 int childpipe[2];
121 /* Note: commonsetup() must happen before we daemon()ise. Otherwise
122 daemon() will chdir("/"), and we won't be able to find local-dir
123 hostkeys. */
124 commonsetup();
126 /* sockets to identify pre-authenticated clients */
127 for (i = 0; i < MAX_UNAUTH_CLIENTS; i++) {
128 childpipes[i] = -1;
130 memset(preauth_addrs, 0x0, sizeof(preauth_addrs));
132 /* Set up the listening sockets */
133 listensockcount = listensockets(listensocks, MAX_LISTEN_ADDR, &maxsock);
134 if (listensockcount == 0)
136 dropbear_exit("No listening ports available.");
139 /* fork */
140 if (svr_opts.forkbg) {
141 int closefds = 0;
142 #ifndef DEBUG_TRACE
143 if (!svr_opts.usingsyslog) {
144 closefds = 1;
146 #endif
147 if (daemon(0, closefds) < 0) {
148 dropbear_exit("Failed to daemonize: %s", strerror(errno));
152 /* should be done after syslog is working */
153 if (svr_opts.forkbg) {
154 dropbear_log(LOG_INFO, "Running in background");
155 } else {
156 dropbear_log(LOG_INFO, "Not backgrounding");
159 /* create a PID file so that we can be killed easily */
160 pidfile = fopen(svr_opts.pidfile, "w");
161 if (pidfile) {
162 fprintf(pidfile, "%d\n", getpid());
163 fclose(pidfile);
166 /* incoming connection select loop */
167 for(;;) {
169 FD_ZERO(&fds);
171 /* listening sockets */
172 for (i = 0; i < listensockcount; i++) {
173 FD_SET(listensocks[i], &fds);
176 /* pre-authentication clients */
177 for (i = 0; i < MAX_UNAUTH_CLIENTS; i++) {
178 if (childpipes[i] >= 0) {
179 FD_SET(childpipes[i], &fds);
180 maxsock = MAX(maxsock, childpipes[i]);
184 val = select(maxsock+1, &fds, NULL, NULL, NULL);
186 if (exitflag) {
187 unlink(svr_opts.pidfile);
188 dropbear_exit("Terminated by signal");
191 if (val == 0) {
192 /* timeout reached - shouldn't happen. eh */
193 continue;
196 if (val < 0) {
197 if (errno == EINTR) {
198 continue;
200 dropbear_exit("Listening socket error");
203 /* close fds which have been authed or closed - svr-auth.c handles
204 * closing the auth sockets on success */
205 for (i = 0; i < MAX_UNAUTH_CLIENTS; i++) {
206 if (childpipes[i] >= 0 && FD_ISSET(childpipes[i], &fds)) {
207 m_close(childpipes[i]);
208 childpipes[i] = -1;
209 m_free(preauth_addrs[i]);
213 /* handle each socket which has something to say */
214 for (i = 0; i < listensockcount; i++) {
215 size_t num_unauthed_for_addr = 0;
216 size_t num_unauthed_total = 0;
217 char *remote_host = NULL, *remote_port = NULL;
218 pid_t fork_ret = 0;
219 size_t conn_idx = 0;
220 struct sockaddr_storage remoteaddr;
221 socklen_t remoteaddrlen;
223 if (!FD_ISSET(listensocks[i], &fds))
224 continue;
226 remoteaddrlen = sizeof(remoteaddr);
227 childsock = accept(listensocks[i],
228 (struct sockaddr*)&remoteaddr, &remoteaddrlen);
230 if (childsock < 0) {
231 /* accept failed */
232 continue;
235 /* Limit the number of unauthenticated connections per IP */
236 getaddrstring(&remoteaddr, &remote_host, NULL, 0);
238 num_unauthed_for_addr = 0;
239 num_unauthed_total = 0;
240 for (j = 0; j < MAX_UNAUTH_CLIENTS; j++) {
241 if (childpipes[j] >= 0) {
242 num_unauthed_total++;
243 if (strcmp(remote_host, preauth_addrs[j]) == 0) {
244 num_unauthed_for_addr++;
246 } else {
247 /* a free slot */
248 conn_idx = j;
252 if (num_unauthed_total >= MAX_UNAUTH_CLIENTS
253 || num_unauthed_for_addr >= MAX_UNAUTH_PER_IP) {
254 goto out;
257 seedrandom();
259 if (pipe(childpipe) < 0) {
260 TRACE(("error creating child pipe"))
261 goto out;
264 #ifdef DEBUG_NOFORK
265 fork_ret = 0;
266 #else
267 fork_ret = fork();
268 #endif
269 if (fork_ret < 0) {
270 dropbear_log(LOG_WARNING, "Error forking: %s", strerror(errno));
271 goto out;
274 addrandom((void*)&fork_ret, sizeof(fork_ret));
276 if (fork_ret > 0) {
278 /* parent */
279 childpipes[conn_idx] = childpipe[0];
280 m_close(childpipe[1]);
281 preauth_addrs[conn_idx] = remote_host;
282 remote_host = NULL;
284 } else {
286 /* child */
287 #ifdef DEBUG_FORKGPROF
288 extern void _start(void), etext(void);
289 monstartup((u_long)&_start, (u_long)&etext);
290 #endif /* DEBUG_FORKGPROF */
292 getaddrstring(&remoteaddr, NULL, &remote_port, 0);
293 dropbear_log(LOG_INFO, "Child connection from %s:%s", remote_host, remote_port);
294 m_free(remote_host);
295 m_free(remote_port);
297 #ifndef DEBUG_NOFORK
298 if (setsid() < 0) {
299 dropbear_exit("setsid: %s", strerror(errno));
301 #endif
303 /* make sure we close sockets */
304 for (i = 0; i < listensockcount; i++) {
305 m_close(listensocks[i]);
308 m_close(childpipe[0]);
310 /* start the session */
311 svr_session(childsock, childpipe[1]);
312 /* don't return */
313 dropbear_assert(0);
316 out:
317 /* This section is important for the parent too */
318 m_close(childsock);
319 if (remote_host) {
320 m_free(remote_host);
323 } /* for(;;) loop */
325 /* don't reach here */
327 #endif /* NON_INETD_MODE */
330 /* catch + reap zombie children */
331 static void sigchld_handler(int UNUSED(unused)) {
332 struct sigaction sa_chld;
334 while(waitpid(-1, NULL, WNOHANG) > 0);
336 sa_chld.sa_handler = sigchld_handler;
337 sa_chld.sa_flags = SA_NOCLDSTOP;
338 if (sigaction(SIGCHLD, &sa_chld, NULL) < 0) {
339 dropbear_exit("signal() error");
343 /* catch any segvs */
344 static void sigsegv_handler(int UNUSED(unused)) {
345 fprintf(stderr, "Aiee, segfault! You should probably report "
346 "this as a bug to the developer\n");
347 exit(EXIT_FAILURE);
350 /* catch ctrl-c or sigterm */
351 static void sigintterm_handler(int UNUSED(unused)) {
353 exitflag = 1;
356 /* Things used by inetd and non-inetd modes */
357 static void commonsetup() {
359 struct sigaction sa_chld;
360 #ifndef DISABLE_SYSLOG
361 if (svr_opts.usingsyslog) {
362 startsyslog();
364 #endif
366 /* set up cleanup handler */
367 if (signal(SIGINT, sigintterm_handler) == SIG_ERR ||
368 #ifndef DEBUG_VALGRIND
369 signal(SIGTERM, sigintterm_handler) == SIG_ERR ||
370 #endif
371 signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
372 dropbear_exit("signal() error");
375 /* catch and reap zombie children */
376 sa_chld.sa_handler = sigchld_handler;
377 sa_chld.sa_flags = SA_NOCLDSTOP;
378 sigemptyset(&sa_chld.sa_mask);
379 if (sigaction(SIGCHLD, &sa_chld, NULL) < 0) {
380 dropbear_exit("signal() error");
382 if (signal(SIGSEGV, sigsegv_handler) == SIG_ERR) {
383 dropbear_exit("signal() error");
386 /* Now we can setup the hostkeys - needs to be after logging is on,
387 * otherwise we might end up blatting error messages to the socket */
388 loadhostkeys();
390 seedrandom();
393 /* Set up listening sockets for all the requested ports */
394 static size_t listensockets(int *sock, size_t sockcount, int *maxfd) {
396 unsigned int i;
397 char* errstring = NULL;
398 size_t sockpos = 0;
399 int nsock;
401 TRACE(("listensockets: %d to try\n", svr_opts.portcount))
403 for (i = 0; i < svr_opts.portcount; i++) {
405 TRACE(("listening on '%s:%s'", svr_opts.addresses[i], svr_opts.ports[i]))
407 nsock = dropbear_listen(svr_opts.addresses[i], svr_opts.ports[i], &sock[sockpos],
408 sockcount - sockpos,
409 &errstring, maxfd);
411 if (nsock < 0) {
412 dropbear_log(LOG_WARNING, "Failed listening on '%s': %s",
413 svr_opts.ports[i], errstring);
414 m_free(errstring);
415 continue;
418 sockpos += nsock;
421 return sockpos;