Changes to update Tomato RAF.
[tomato.git] / release / src / router / dropbear / svr-main.c
blobb7258e5fb0ecd4c4e4ccae1a4a9088f2495696f8
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 if (pipe(childpipe) < 0) {
258 TRACE(("error creating child pipe"))
259 goto out;
262 #ifdef DEBUG_NOFORK
263 fork_ret = 0;
264 #else
265 fork_ret = fork();
266 #endif
267 if (fork_ret < 0) {
268 dropbear_log(LOG_WARNING, "Error forking: %s", strerror(errno));
269 goto out;
271 } else if (fork_ret > 0) {
273 /* parent */
274 childpipes[conn_idx] = childpipe[0];
275 m_close(childpipe[1]);
276 preauth_addrs[conn_idx] = remote_host;
277 remote_host = NULL;
279 } else {
281 /* child */
282 #ifdef DEBUG_FORKGPROF
283 extern void _start(void), etext(void);
284 monstartup((u_long)&_start, (u_long)&etext);
285 #endif /* DEBUG_FORKGPROF */
287 getaddrstring(&remoteaddr, NULL, &remote_port, 0);
288 dropbear_log(LOG_INFO, "Child connection from %s:%s", remote_host, remote_port);
289 m_free(remote_host);
290 m_free(remote_port);
292 #ifndef DEBUG_NOFORK
293 if (setsid() < 0) {
294 dropbear_exit("setsid: %s", strerror(errno));
296 #endif
298 /* make sure we close sockets */
299 for (i = 0; i < listensockcount; i++) {
300 m_close(listensocks[i]);
303 m_close(childpipe[0]);
305 /* start the session */
306 svr_session(childsock, childpipe[1]);
307 /* don't return */
308 dropbear_assert(0);
311 out:
312 /* This section is important for the parent too */
313 m_close(childsock);
314 if (remote_host) {
315 m_free(remote_host);
318 } /* for(;;) loop */
320 /* don't reach here */
322 #endif /* NON_INETD_MODE */
325 /* catch + reap zombie children */
326 static void sigchld_handler(int UNUSED(unused)) {
327 struct sigaction sa_chld;
329 while(waitpid(-1, NULL, WNOHANG) > 0);
331 sa_chld.sa_handler = sigchld_handler;
332 sa_chld.sa_flags = SA_NOCLDSTOP;
333 if (sigaction(SIGCHLD, &sa_chld, NULL) < 0) {
334 dropbear_exit("signal() error");
338 /* catch any segvs */
339 static void sigsegv_handler(int UNUSED(unused)) {
340 fprintf(stderr, "Aiee, segfault! You should probably report "
341 "this as a bug to the developer\n");
342 exit(EXIT_FAILURE);
345 /* catch ctrl-c or sigterm */
346 static void sigintterm_handler(int UNUSED(unused)) {
348 exitflag = 1;
351 /* Things used by inetd and non-inetd modes */
352 static void commonsetup() {
354 struct sigaction sa_chld;
355 #ifndef DISABLE_SYSLOG
356 if (svr_opts.usingsyslog) {
357 startsyslog();
359 #endif
361 /* set up cleanup handler */
362 if (signal(SIGINT, sigintterm_handler) == SIG_ERR ||
363 #ifndef DEBUG_VALGRIND
364 signal(SIGTERM, sigintterm_handler) == SIG_ERR ||
365 #endif
366 signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
367 dropbear_exit("signal() error");
370 /* catch and reap zombie children */
371 sa_chld.sa_handler = sigchld_handler;
372 sa_chld.sa_flags = SA_NOCLDSTOP;
373 sigemptyset(&sa_chld.sa_mask);
374 if (sigaction(SIGCHLD, &sa_chld, NULL) < 0) {
375 dropbear_exit("signal() error");
377 if (signal(SIGSEGV, sigsegv_handler) == SIG_ERR) {
378 dropbear_exit("signal() error");
381 /* Now we can setup the hostkeys - needs to be after logging is on,
382 * otherwise we might end up blatting error messages to the socket */
383 loadhostkeys();
385 seedrandom();
388 /* Set up listening sockets for all the requested ports */
389 static size_t listensockets(int *sock, size_t sockcount, int *maxfd) {
391 unsigned int i;
392 char* errstring = NULL;
393 size_t sockpos = 0;
394 int nsock;
396 TRACE(("listensockets: %d to try\n", svr_opts.portcount))
398 for (i = 0; i < svr_opts.portcount; i++) {
400 TRACE(("listening on '%s:%s'", svr_opts.addresses[i], svr_opts.ports[i]))
402 nsock = dropbear_listen(svr_opts.addresses[i], svr_opts.ports[i], &sock[sockpos],
403 sockcount - sockpos,
404 &errstring, maxfd);
406 if (nsock < 0) {
407 dropbear_log(LOG_WARNING, "Failed listening on '%s': %s",
408 svr_opts.ports[i], errstring);
409 m_free(errstring);
410 continue;
413 sockpos += nsock;
416 return sockpos;