blob: 4a303573007ecc4ad672e99dcae5af759fddea7c [file] [log] [blame]
Willy Tarreaubaaee002006-06-26 02:48:02 +02001/*
2 * HA-Proxy : High Availability-enabled HTTP/TCP proxy
3 * Copyright 2000-2006 Willy Tarreau <w@1wt.eu>.
4 *
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version
8 * 2 of the License, or (at your option) any later version.
9 *
10 * Please refer to RFC2068 or RFC2616 for informations about HTTP protocol, and
11 * RFC2965 for informations about cookies usage. More generally, the IETF HTTP
12 * Working Group's web site should be consulted for protocol related changes :
13 *
14 * http://ftp.ics.uci.edu/pub/ietf/http/
15 *
16 * Pending bugs (may be not fixed because never reproduced) :
17 * - solaris only : sometimes, an HTTP proxy with only a dispatch address causes
18 * the proxy to terminate (no core) if the client breaks the connection during
19 * the response. Seen on 1.1.8pre4, but never reproduced. May not be related to
20 * the snprintf() bug since requests were simple (GET / HTTP/1.0), but may be
21 * related to missing setsid() (fixed in 1.1.15)
22 * - a proxy with an invalid config will prevent the startup even if disabled.
23 *
24 * ChangeLog has moved to the CHANGELOG file.
25 *
26 * TODO:
27 * - handle properly intermediate incomplete server headers. Done ?
28 * - handle hot-reconfiguration
29 * - fix client/server state transition when server is in connect or headers state
30 * and client suddenly disconnects. The server *should* switch to SHUT_WR, but
31 * still handle HTTP headers.
32 * - remove MAX_NEWHDR
33 * - cut this huge file into several ones
34 *
35 */
36
37#include <stdio.h>
38#include <stdlib.h>
39#include <unistd.h>
40#include <string.h>
41#include <ctype.h>
42#include <sys/time.h>
43#include <sys/types.h>
44#include <sys/socket.h>
45#include <netinet/tcp.h>
46#include <netinet/in.h>
47#include <arpa/inet.h>
48#include <netdb.h>
49#include <fcntl.h>
50#include <errno.h>
51#include <signal.h>
52#include <stdarg.h>
53#include <sys/resource.h>
54#include <time.h>
55#include <syslog.h>
56
57#ifdef DEBUG_FULL
58#include <assert.h>
59#endif
60
Willy Tarreau2dd0d472006-06-29 17:53:05 +020061#include <common/appsession.h>
62#include <common/base64.h>
63#include <common/cfgparse.h>
64#include <common/compat.h>
65#include <common/config.h>
66#include <common/defaults.h>
67#include <common/memory.h>
68#include <common/mini-clist.h>
69#include <common/regex.h>
70#include <common/standard.h>
71#include <common/time.h>
72#include <common/uri_auth.h>
73#include <common/version.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020074
75#include <types/capture.h>
76#include <types/global.h>
77#include <types/httperr.h>
78#include <types/proto_http.h>
79
80#include <proto/backend.h>
81#include <proto/buffers.h>
82#include <proto/client.h>
83#include <proto/fd.h>
84#include <proto/log.h>
85#include <proto/polling.h>
Willy Tarreau80587432006-12-24 17:47:20 +010086#include <proto/proto_http.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020087#include <proto/proxy.h>
88#include <proto/queue.h>
89#include <proto/server.h>
90#include <proto/stream_sock.h>
91#include <proto/task.h>
92
93/*********************************************************************/
94
95/*********************************************************************/
96
97char *cfg_cfgfile = NULL; /* configuration file */
98char *progname = NULL; /* program name */
99int pid; /* current process id */
100
101/* global options */
102struct global global = {
103 logfac1 : -1,
104 logfac2 : -1,
105 loglev1 : 7, /* max syslog level : debug */
106 loglev2 : 7,
107 /* others NULL OK */
108};
109
110/*********************************************************************/
111
112int stopping; /* non zero means stopping in progress */
113
114/* Here we store informations about the pids of the processes we may pause
115 * or kill. We will send them a signal every 10 ms until we can bind to all
116 * our ports. With 200 retries, that's about 2 seconds.
117 */
118#define MAX_START_RETRIES 200
119static int nb_oldpids = 0;
120static int *oldpids = NULL;
121static int oldpids_sig; /* use USR1 or TERM */
122
123/* this is used to drain data, and as a temporary buffer for sprintf()... */
124char trash[BUFSIZE];
125
126const int zero = 0;
127const int one = 1;
128
129/*
130 * Syslog facilities and levels. Conforming to RFC3164.
131 */
132
133#define MAX_HOSTNAME_LEN 32
134static char hostname[MAX_HOSTNAME_LEN] = "";
135
136
137/*********************************************************************/
138/* general purpose functions ***************************************/
139/*********************************************************************/
140
141void display_version()
142{
143 printf("HA-Proxy version " HAPROXY_VERSION " " HAPROXY_DATE"\n");
144 printf("Copyright 2000-2006 Willy Tarreau <w@1wt.eu>\n\n");
145}
146
147/*
148 * This function prints the command line usage and exits
149 */
150void usage(char *name)
151{
152 display_version();
153 fprintf(stderr,
154 "Usage : %s -f <cfgfile> [ -vdV"
155 "D ] [ -n <maxconn> ] [ -N <maxpconn> ]\n"
156 " [ -p <pidfile> ] [ -m <max megs> ]\n"
157 " -v displays version\n"
158 " -d enters debug mode ; -db only disables background mode.\n"
159 " -V enters verbose mode (disables quiet mode)\n"
160 " -D goes daemon ; implies -q\n"
161 " -q quiet mode : don't display messages\n"
162 " -c check mode : only check config file and exit\n"
163 " -n sets the maximum total # of connections (%d)\n"
164 " -m limits the usable amount of memory (in MB)\n"
165 " -N sets the default, per-proxy maximum # of connections (%d)\n"
166 " -p writes pids of all children to this file\n"
167#if defined(ENABLE_EPOLL)
168 " -de disables epoll() usage even when available\n"
169#endif
170#if defined(ENABLE_POLL)
171 " -dp disables poll() usage even when available\n"
172#endif
173 " -sf/-st [pid ]* finishes/terminates old pids. Must be last arguments.\n"
174 "\n",
175 name, DEFAULT_MAXCONN, cfg_maxpconn);
176 exit(1);
177}
178
179
180
181/*********************************************************************/
182/* more specific functions ***************************************/
183/*********************************************************************/
184
185/*
186 * upon SIGUSR1, let's have a soft stop.
187 */
188void sig_soft_stop(int sig)
189{
190 soft_stop();
191 signal(sig, SIG_IGN);
192}
193
194/*
195 * upon SIGTTOU, we pause everything
196 */
197void sig_pause(int sig)
198{
199 pause_proxies();
200 signal(sig, sig_pause);
201}
202
203/*
204 * upon SIGTTIN, let's have a soft stop.
205 */
206void sig_listen(int sig)
207{
208 listen_proxies();
209 signal(sig, sig_listen);
210}
211
212/*
213 * this function dumps every server's state when the process receives SIGHUP.
214 */
215void sig_dump_state(int sig)
216{
217 struct proxy *p = proxy;
218
219 Warning("SIGHUP received, dumping servers states.\n");
220 while (p) {
221 struct server *s = p->srv;
222
223 send_log(p, LOG_NOTICE, "SIGHUP received, dumping servers states for proxy %s.\n", p->id);
224 while (s) {
225 snprintf(trash, sizeof(trash),
226 "SIGHUP: Server %s/%s is %s. Conn: %d act, %d pend, %d tot.",
227 p->id, s->id,
228 (s->state & SRV_RUNNING) ? "UP" : "DOWN",
229 s->cur_sess, s->nbpend, s->cum_sess);
230 Warning("%s\n", trash);
231 send_log(p, LOG_NOTICE, "%s\n", trash);
232 s = s->next;
233 }
234
235 if (p->srv_act == 0) {
236 snprintf(trash, sizeof(trash),
Willy Tarreauf1221aa2006-12-17 22:14:12 +0100237 "SIGHUP: Proxy %s %s ! Conn: act(FE+BE): %d+%d, %d pend (%d unass), tot(FE+BE): %d+%d.",
Willy Tarreaubaaee002006-06-26 02:48:02 +0200238 p->id,
239 (p->srv_bck) ? "is running on backup servers" : "has no server available",
Willy Tarreauf1221aa2006-12-17 22:14:12 +0100240 p->feconn, p->beconn, p->totpend, p->nbpend, p->cum_feconn, p->cum_beconn);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200241 } else {
242 snprintf(trash, sizeof(trash),
243 "SIGHUP: Proxy %s has %d active servers and %d backup servers available."
Willy Tarreauf1221aa2006-12-17 22:14:12 +0100244 " Conn: act(FE+BE): %d+%d, %d pend (%d unass), tot(FE+BE): %d+%d.",
Willy Tarreaubaaee002006-06-26 02:48:02 +0200245 p->id, p->srv_act, p->srv_bck,
Willy Tarreauf1221aa2006-12-17 22:14:12 +0100246 p->feconn, p->beconn, p->totpend, p->nbpend, p->cum_feconn, p->cum_beconn);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200247 }
248 Warning("%s\n", trash);
249 send_log(p, LOG_NOTICE, "%s\n", trash);
250
251 p = p->next;
252 }
253 signal(sig, sig_dump_state);
254}
255
256void dump(int sig)
257{
Willy Tarreau964c9362007-01-07 00:38:00 +0100258 struct task *t;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200259 struct session *s;
Willy Tarreau964c9362007-01-07 00:38:00 +0100260 struct rb_node *node;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200261
Willy Tarreau964c9362007-01-07 00:38:00 +0100262 for(node = rb_first(&wait_queue[0]);
263 node != NULL; node = rb_next(node)) {
264 t = rb_entry(node, struct task, rb_node);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200265 s = t->context;
266 qfprintf(stderr,"[dump] wq: task %p, still %ld ms, "
267 "cli=%d, srv=%d, cr=%d, cw=%d, sr=%d, sw=%d, "
268 "req=%d, rep=%d, clifd=%d\n",
269 s, tv_remain(&now, &t->expire),
270 s->cli_state,
271 s->srv_state,
Willy Tarreau2a429502006-10-15 14:52:29 +0200272 MY_FD_ISSET(s->cli_fd, StaticReadEvent),
273 MY_FD_ISSET(s->cli_fd, StaticWriteEvent),
274 MY_FD_ISSET(s->srv_fd, StaticReadEvent),
275 MY_FD_ISSET(s->srv_fd, StaticWriteEvent),
Willy Tarreaubaaee002006-06-26 02:48:02 +0200276 s->req->l, s->rep?s->rep->l:0, s->cli_fd
277 );
278 }
279}
280
281#ifdef DEBUG_MEMORY
282static void fast_stop(void)
283{
284 struct proxy *p;
285 p = proxy;
286 while (p) {
287 p->grace = 0;
288 p = p->next;
289 }
290 soft_stop();
291}
292
293void sig_int(int sig)
294{
295 /* This would normally be a hard stop,
296 but we want to be sure about deallocation,
297 and so on, so we do a soft stop with
298 0 GRACE time
299 */
300 fast_stop();
301 /* If we are killed twice, we decide to die*/
302 signal(sig, SIG_DFL);
303}
304
305void sig_term(int sig)
306{
307 /* This would normally be a hard stop,
308 but we want to be sure about deallocation,
309 and so on, so we do a soft stop with
310 0 GRACE time
311 */
312 fast_stop();
313 /* If we are killed twice, we decide to die*/
314 signal(sig, SIG_DFL);
315}
316#endif
317
318
319/*
320 * This function initializes all the necessary variables. It only returns
321 * if everything is OK. If something fails, it exits.
322 */
323void init(int argc, char **argv)
324{
325 int i;
326 int arg_mode = 0; /* MODE_DEBUG, ... */
327 char *old_argv = *argv;
328 char *tmp;
329 char *cfg_pidfile = NULL;
330
331 if (1<<INTBITS != sizeof(int)*8) {
332 fprintf(stderr,
333 "Error: wrong architecture. Recompile so that sizeof(int)=%d\n",
334 (int)(sizeof(int)*8));
335 exit(1);
336 }
337
338 /*
339 * Initialize the previously static variables.
340 */
341
342 totalconn = actconn = maxfd = listeners = stopping = 0;
343
344
345#ifdef HAPROXY_MEMMAX
346 global.rlimit_memmax = HAPROXY_MEMMAX;
347#endif
348
349 /* initialize the libc's localtime structures once for all so that we
350 * won't be missing memory if we want to send alerts under OOM conditions.
Willy Tarreau2b35c952006-10-15 15:25:48 +0200351 * Also, the Alert() and Warning() functions need <now> to be initialized.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200352 */
353 tv_now(&now);
Willy Tarreaubf736132006-10-15 22:54:47 +0200354 localtime((time_t *)&now.tv_sec);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200355 start_date = now;
356
357 init_log();
Willy Tarreau80587432006-12-24 17:47:20 +0100358 init_proto_http();
Willy Tarreaubaaee002006-06-26 02:48:02 +0200359
360 cfg_polling_mechanism = POLL_USE_SELECT; /* select() is always available */
361#if defined(ENABLE_POLL)
362 cfg_polling_mechanism |= POLL_USE_POLL;
363#endif
364#if defined(ENABLE_EPOLL)
365 cfg_polling_mechanism |= POLL_USE_EPOLL;
366#endif
367
368 pid = getpid();
369 progname = *argv;
370 while ((tmp = strchr(progname, '/')) != NULL)
371 progname = tmp + 1;
372
373 argc--; argv++;
374 while (argc > 0) {
375 char *flag;
376
377 if (**argv == '-') {
378 flag = *argv+1;
379
380 /* 1 arg */
381 if (*flag == 'v') {
382 display_version();
383 exit(0);
384 }
385#if defined(ENABLE_EPOLL)
386 else if (*flag == 'd' && flag[1] == 'e')
387 cfg_polling_mechanism &= ~POLL_USE_EPOLL;
388#endif
389#if defined(ENABLE_POLL)
390 else if (*flag == 'd' && flag[1] == 'p')
391 cfg_polling_mechanism &= ~POLL_USE_POLL;
392#endif
393 else if (*flag == 'V')
394 arg_mode |= MODE_VERBOSE;
395 else if (*flag == 'd' && flag[1] == 'b')
396 arg_mode |= MODE_FOREGROUND;
397 else if (*flag == 'd')
398 arg_mode |= MODE_DEBUG;
399 else if (*flag == 'c')
400 arg_mode |= MODE_CHECK;
401 else if (*flag == 'D')
402 arg_mode |= MODE_DAEMON | MODE_QUIET;
403 else if (*flag == 'q')
404 arg_mode |= MODE_QUIET;
405 else if (*flag == 's' && (flag[1] == 'f' || flag[1] == 't')) {
406 /* list of pids to finish ('f') or terminate ('t') */
407
408 if (flag[1] == 'f')
409 oldpids_sig = SIGUSR1; /* finish then exit */
410 else
411 oldpids_sig = SIGTERM; /* terminate immediately */
412 argv++; argc--;
413
414 if (argc > 0) {
415 oldpids = calloc(argc, sizeof(int));
416 while (argc > 0) {
417 oldpids[nb_oldpids] = atol(*argv);
418 if (oldpids[nb_oldpids] <= 0)
419 usage(old_argv);
420 argc--; argv++;
421 nb_oldpids++;
422 }
423 }
424 }
425 else { /* >=2 args */
426 argv++; argc--;
427 if (argc == 0)
428 usage(old_argv);
429
430 switch (*flag) {
431 case 'n' : cfg_maxconn = atol(*argv); break;
432 case 'm' : global.rlimit_memmax = atol(*argv); break;
433 case 'N' : cfg_maxpconn = atol(*argv); break;
434 case 'f' : cfg_cfgfile = *argv; break;
435 case 'p' : cfg_pidfile = *argv; break;
436 default: usage(old_argv);
437 }
438 }
439 }
440 else
441 usage(old_argv);
442 argv++; argc--;
443 }
444
445 global.mode = MODE_STARTING | /* during startup, we want most of the alerts */
446 (arg_mode & (MODE_DAEMON | MODE_FOREGROUND | MODE_VERBOSE
447 | MODE_QUIET | MODE_CHECK | MODE_DEBUG));
448
449 if (!cfg_cfgfile)
450 usage(old_argv);
451
452 gethostname(hostname, MAX_HOSTNAME_LEN);
453
454 have_appsession = 0;
455 global.maxsock = 10; /* reserve 10 fds ; will be incremented by socket eaters */
456 if (readcfgfile(cfg_cfgfile) < 0) {
457 Alert("Error reading configuration file : %s\n", cfg_cfgfile);
458 exit(1);
459 }
460 if (have_appsession)
461 appsession_init();
462
463 if (global.mode & MODE_CHECK) {
464 qfprintf(stdout, "Configuration file is valid : %s\n", cfg_cfgfile);
465 exit(0);
466 }
467
468 if (cfg_maxconn > 0)
469 global.maxconn = cfg_maxconn;
470
471 if (cfg_pidfile) {
472 if (global.pidfile)
473 free(global.pidfile);
474 global.pidfile = strdup(cfg_pidfile);
475 }
476
477 if (global.maxconn == 0)
478 global.maxconn = DEFAULT_MAXCONN;
479
480 global.maxsock += global.maxconn * 2; /* each connection needs two sockets */
481
482 if (arg_mode & (MODE_DEBUG | MODE_FOREGROUND)) {
483 /* command line debug mode inhibits configuration mode */
484 global.mode &= ~(MODE_DAEMON | MODE_QUIET);
485 }
486 global.mode |= (arg_mode & (MODE_DAEMON | MODE_FOREGROUND | MODE_QUIET |
487 MODE_VERBOSE | MODE_DEBUG | MODE_STATS | MODE_LOG));
488
489 if ((global.mode & MODE_DEBUG) && (global.mode & (MODE_DAEMON | MODE_QUIET))) {
490 Warning("<debug> mode incompatible with <quiet> and <daemon>. Keeping <debug> only.\n");
491 global.mode &= ~(MODE_DAEMON | MODE_QUIET);
492 }
493
494 if ((global.nbproc > 1) && !(global.mode & MODE_DAEMON)) {
495 if (!(global.mode & (MODE_FOREGROUND | MODE_DEBUG)))
496 Warning("<nbproc> is only meaningful in daemon mode. Setting limit to 1 process.\n");
497 global.nbproc = 1;
498 }
499
500 if (global.nbproc < 1)
501 global.nbproc = 1;
502
503 StaticReadEvent = (fd_set *)calloc(1,
504 sizeof(fd_set) *
505 (global.maxsock + FD_SETSIZE - 1) / FD_SETSIZE);
506 StaticWriteEvent = (fd_set *)calloc(1,
507 sizeof(fd_set) *
508 (global.maxsock + FD_SETSIZE - 1) / FD_SETSIZE);
509
510 fdtab = (struct fdtab *)calloc(1,
511 sizeof(struct fdtab) * (global.maxsock));
512 for (i = 0; i < global.maxsock; i++) {
513 fdtab[i].state = FD_STCLOSE;
514 }
515}
516
517void deinit(void)
518{
519 struct proxy *p = proxy;
520 struct cap_hdr *h,*h_next;
521 struct server *s,*s_next;
522 struct listener *l,*l_next;
523
524 while (p) {
525 if (p->id)
526 free(p->id);
527
528 if (p->check_req)
529 free(p->check_req);
530
531 if (p->cookie_name)
532 free(p->cookie_name);
533
534 if (p->capture_name)
535 free(p->capture_name);
536
537 /* only strup if the user have set in config.
538 When should we free it?!
539 if (p->errmsg.msg400) free(p->errmsg.msg400);
540 if (p->errmsg.msg403) free(p->errmsg.msg403);
541 if (p->errmsg.msg408) free(p->errmsg.msg408);
542 if (p->errmsg.msg500) free(p->errmsg.msg500);
543 if (p->errmsg.msg502) free(p->errmsg.msg502);
544 if (p->errmsg.msg503) free(p->errmsg.msg503);
545 if (p->errmsg.msg504) free(p->errmsg.msg504);
546 */
547 if (p->appsession_name)
548 free(p->appsession_name);
549
550 h = p->req_cap;
551 while (h) {
552 h_next = h->next;
553 if (h->name)
554 free(h->name);
555 pool_destroy(h->pool);
556 free(h);
557 h = h_next;
558 }/* end while(h) */
559
560 h = p->rsp_cap;
561 while (h) {
562 h_next = h->next;
563 if (h->name)
564 free(h->name);
565
566 pool_destroy(h->pool);
567 free(h);
568 h = h_next;
569 }/* end while(h) */
570
571 s = p->srv;
572 while (s) {
573 s_next = s->next;
574 if (s->id)
575 free(s->id);
576
577 if (s->cookie)
578 free(s->cookie);
579
580 free(s);
581 s = s_next;
582 }/* end while(s) */
583
584 l = p->listen;
585 while (l) {
586 l_next = l->next;
587 free(l);
588 l = l_next;
589 }/* end while(l) */
590
591 pool_destroy((void **) p->req_cap_pool);
592 pool_destroy((void **) p->rsp_cap_pool);
593 p = p->next;
594 }/* end while(p) */
595
596 if (global.chroot) free(global.chroot);
597 if (global.pidfile) free(global.pidfile);
598
599 if (StaticReadEvent) free(StaticReadEvent);
600 if (StaticWriteEvent) free(StaticWriteEvent);
601 if (fdtab) free(fdtab);
602
603 pool_destroy(pool_session);
604 pool_destroy(pool_buffer);
605 pool_destroy(pool_requri);
606 pool_destroy(pool_task);
607 pool_destroy(pool_capture);
608 pool_destroy(pool_appsess);
609
610 if (have_appsession) {
611 pool_destroy(apools.serverid);
612 pool_destroy(apools.sessid);
613 }
614} /* end deinit() */
615
616/* sends the signal <sig> to all pids found in <oldpids> */
617static void tell_old_pids(int sig)
618{
619 int p;
620 for (p = 0; p < nb_oldpids; p++)
621 kill(oldpids[p], sig);
622}
623
624int main(int argc, char **argv)
625{
626 int err, retry;
627 struct rlimit limit;
628 FILE *pidfile = NULL;
629 init(argc, argv);
630
631 signal(SIGQUIT, dump);
632 signal(SIGUSR1, sig_soft_stop);
633 signal(SIGHUP, sig_dump_state);
634#ifdef DEBUG_MEMORY
635 signal(SIGINT, sig_int);
636 signal(SIGTERM, sig_term);
637#endif
638
639 /* on very high loads, a sigpipe sometimes happen just between the
640 * getsockopt() which tells "it's OK to write", and the following write :-(
641 */
642#ifndef MSG_NOSIGNAL
643 signal(SIGPIPE, SIG_IGN);
644#endif
645
646 /* We will loop at most 100 times with 10 ms delay each time.
647 * That's at most 1 second. We only send a signal to old pids
648 * if we cannot grab at least one port.
649 */
650 retry = MAX_START_RETRIES;
651 err = ERR_NONE;
652 while (retry >= 0) {
653 struct timeval w;
654 err = start_proxies(retry == 0 || nb_oldpids == 0);
655 if (err != ERR_RETRYABLE)
656 break;
657 if (nb_oldpids == 0)
658 break;
659
660 /* FIXME-20060514: Solaris and OpenBSD do not support shutdown() on
661 * listening sockets. So on those platforms, it would be wiser to
662 * simply send SIGUSR1, which will not be undoable.
663 */
664 tell_old_pids(SIGTTOU);
665 /* give some time to old processes to stop listening */
666 w.tv_sec = 0;
667 w.tv_usec = 10*1000;
668 select(0, NULL, NULL, NULL, &w);
669 retry--;
670 }
671
672 /* Note: start_proxies() sends an alert when it fails. */
673 if (err != ERR_NONE) {
674 if (retry != MAX_START_RETRIES && nb_oldpids)
675 tell_old_pids(SIGTTIN);
676 exit(1);
677 }
678
679 if (listeners == 0) {
680 Alert("[%s.main()] No enabled listener found (check the <listen> keywords) ! Exiting.\n", argv[0]);
681 /* Note: we don't have to send anything to the old pids because we
682 * never stopped them. */
683 exit(1);
684 }
685
686 /* prepare pause/play signals */
687 signal(SIGTTOU, sig_pause);
688 signal(SIGTTIN, sig_listen);
689
690 if (global.mode & MODE_DAEMON) {
691 global.mode &= ~MODE_VERBOSE;
692 global.mode |= MODE_QUIET;
693 }
694
695 /* MODE_QUIET can inhibit alerts and warnings below this line */
696
697 global.mode &= ~MODE_STARTING;
698 if ((global.mode & MODE_QUIET) && !(global.mode & MODE_VERBOSE)) {
699 /* detach from the tty */
700 fclose(stdin); fclose(stdout); fclose(stderr);
701 close(0); close(1); close(2);
702 }
703
704 /* open log & pid files before the chroot */
705 if (global.mode & MODE_DAEMON && global.pidfile != NULL) {
706 int pidfd;
707 unlink(global.pidfile);
708 pidfd = open(global.pidfile, O_CREAT | O_WRONLY | O_TRUNC, 0644);
709 if (pidfd < 0) {
710 Alert("[%s.main()] Cannot create pidfile %s\n", argv[0], global.pidfile);
711 if (nb_oldpids)
712 tell_old_pids(SIGTTIN);
713 exit(1);
714 }
715 pidfile = fdopen(pidfd, "w");
716 }
717
718 /* chroot if needed */
719 if (global.chroot != NULL) {
720 if (chroot(global.chroot) == -1) {
721 Alert("[%s.main()] Cannot chroot(%s).\n", argv[0], global.chroot);
722 if (nb_oldpids)
723 tell_old_pids(SIGTTIN);
724 }
725 chdir("/");
726 }
727
728 /* ulimits */
729 if (!global.rlimit_nofile)
730 global.rlimit_nofile = global.maxsock;
731
732 if (global.rlimit_nofile) {
733 limit.rlim_cur = limit.rlim_max = global.rlimit_nofile;
734 if (setrlimit(RLIMIT_NOFILE, &limit) == -1) {
735 Warning("[%s.main()] Cannot raise FD limit to %d.\n", argv[0], global.rlimit_nofile);
736 }
737 }
738
739 if (global.rlimit_memmax) {
740 limit.rlim_cur = limit.rlim_max =
741 global.rlimit_memmax * 1048576 / global.nbproc;
742#ifdef RLIMIT_AS
743 if (setrlimit(RLIMIT_AS, &limit) == -1) {
744 Warning("[%s.main()] Cannot fix MEM limit to %d megs.\n",
745 argv[0], global.rlimit_memmax);
746 }
747#else
748 if (setrlimit(RLIMIT_DATA, &limit) == -1) {
749 Warning("[%s.main()] Cannot fix MEM limit to %d megs.\n",
750 argv[0], global.rlimit_memmax);
751 }
752#endif
753 }
754
755 if (nb_oldpids)
756 tell_old_pids(oldpids_sig);
757
758 /* Note that any error at this stage will be fatal because we will not
759 * be able to restart the old pids.
760 */
761
762 /* setgid / setuid */
763 if (global.gid && setgid(global.gid) == -1) {
764 Alert("[%s.main()] Cannot set gid %d.\n", argv[0], global.gid);
765 exit(1);
766 }
767
768 if (global.uid && setuid(global.uid) == -1) {
769 Alert("[%s.main()] Cannot set uid %d.\n", argv[0], global.uid);
770 exit(1);
771 }
772
773 /* check ulimits */
774 limit.rlim_cur = limit.rlim_max = 0;
775 getrlimit(RLIMIT_NOFILE, &limit);
776 if (limit.rlim_cur < global.maxsock) {
777 Warning("[%s.main()] FD limit (%d) too low for maxconn=%d/maxsock=%d. Please raise 'ulimit-n' to %d or more to avoid any trouble.\n",
778 argv[0], limit.rlim_cur, global.maxconn, global.maxsock, global.maxsock);
779 }
780
781 if (global.mode & MODE_DAEMON) {
782 int ret = 0;
783 int proc;
784
785 /* the father launches the required number of processes */
786 for (proc = 0; proc < global.nbproc; proc++) {
787 ret = fork();
788 if (ret < 0) {
789 Alert("[%s.main()] Cannot fork.\n", argv[0]);
790 if (nb_oldpids)
791 exit(1); /* there has been an error */
792 }
793 else if (ret == 0) /* child breaks here */
794 break;
795 if (pidfile != NULL) {
796 fprintf(pidfile, "%d\n", ret);
797 fflush(pidfile);
798 }
799 }
800 /* close the pidfile both in children and father */
801 if (pidfile != NULL)
802 fclose(pidfile);
803 free(global.pidfile);
804
805 if (proc == global.nbproc)
806 exit(0); /* parent must leave */
807
808 /* if we're NOT in QUIET mode, we should now close the 3 first FDs to ensure
809 * that we can detach from the TTY. We MUST NOT do it in other cases since
810 * it would have already be done, and 0-2 would have been affected to listening
811 * sockets
812 */
813 if (!(global.mode & MODE_QUIET)) {
814 /* detach from the tty */
815 fclose(stdin); fclose(stdout); fclose(stderr);
816 close(0); close(1); close(2); /* close all fd's */
817 global.mode |= MODE_QUIET; /* ensure that we won't say anything from now */
818 }
819 pid = getpid(); /* update child's pid */
820 setsid();
821 }
822
823#if defined(ENABLE_EPOLL)
824 if (cfg_polling_mechanism & POLL_USE_EPOLL) {
825 if (epoll_loop(POLL_LOOP_ACTION_INIT)) {
826 epoll_loop(POLL_LOOP_ACTION_RUN);
827 epoll_loop(POLL_LOOP_ACTION_CLEAN);
828 cfg_polling_mechanism &= POLL_USE_EPOLL;
829 }
830 else {
831 Warning("epoll() is not available. Using poll()/select() instead.\n");
832 cfg_polling_mechanism &= ~POLL_USE_EPOLL;
833 }
834 }
835#endif
836
837#if defined(ENABLE_POLL)
838 if (cfg_polling_mechanism & POLL_USE_POLL) {
839 if (poll_loop(POLL_LOOP_ACTION_INIT)) {
840 poll_loop(POLL_LOOP_ACTION_RUN);
841 poll_loop(POLL_LOOP_ACTION_CLEAN);
842 cfg_polling_mechanism &= POLL_USE_POLL;
843 }
844 else {
845 Warning("poll() is not available. Using select() instead.\n");
846 cfg_polling_mechanism &= ~POLL_USE_POLL;
847 }
848 }
849#endif
850 if (cfg_polling_mechanism & POLL_USE_SELECT) {
851 if (select_loop(POLL_LOOP_ACTION_INIT)) {
852 select_loop(POLL_LOOP_ACTION_RUN);
853 select_loop(POLL_LOOP_ACTION_CLEAN);
854 cfg_polling_mechanism &= POLL_USE_SELECT;
855 }
856 }
857
858
859 /* Free all Hash Keys and all Hash elements */
860 appsession_cleanup();
861 /* Do some cleanup */
862 deinit();
863
864 exit(0);
865}
866
867
868/*
869 * Local variables:
870 * c-indent-level: 8
871 * c-basic-offset: 8
872 * End:
873 */