blob: 047136422a3921e3c58d79538479eb1fff3faea7 [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{
258 struct task *t, *tnext;
259 struct session *s;
260
261 tnext = ((struct task *)LIST_HEAD(wait_queue[0]))->next;
262 while ((t = tnext) != LIST_HEAD(wait_queue[0])) { /* we haven't looped ? */
263 tnext = t->next;
264 s = t->context;
265 qfprintf(stderr,"[dump] wq: task %p, still %ld ms, "
266 "cli=%d, srv=%d, cr=%d, cw=%d, sr=%d, sw=%d, "
267 "req=%d, rep=%d, clifd=%d\n",
268 s, tv_remain(&now, &t->expire),
269 s->cli_state,
270 s->srv_state,
Willy Tarreau2a429502006-10-15 14:52:29 +0200271 MY_FD_ISSET(s->cli_fd, StaticReadEvent),
272 MY_FD_ISSET(s->cli_fd, StaticWriteEvent),
273 MY_FD_ISSET(s->srv_fd, StaticReadEvent),
274 MY_FD_ISSET(s->srv_fd, StaticWriteEvent),
Willy Tarreaubaaee002006-06-26 02:48:02 +0200275 s->req->l, s->rep?s->rep->l:0, s->cli_fd
276 );
277 }
278}
279
280#ifdef DEBUG_MEMORY
281static void fast_stop(void)
282{
283 struct proxy *p;
284 p = proxy;
285 while (p) {
286 p->grace = 0;
287 p = p->next;
288 }
289 soft_stop();
290}
291
292void sig_int(int sig)
293{
294 /* This would normally be a hard stop,
295 but we want to be sure about deallocation,
296 and so on, so we do a soft stop with
297 0 GRACE time
298 */
299 fast_stop();
300 /* If we are killed twice, we decide to die*/
301 signal(sig, SIG_DFL);
302}
303
304void sig_term(int sig)
305{
306 /* This would normally be a hard stop,
307 but we want to be sure about deallocation,
308 and so on, so we do a soft stop with
309 0 GRACE time
310 */
311 fast_stop();
312 /* If we are killed twice, we decide to die*/
313 signal(sig, SIG_DFL);
314}
315#endif
316
317
318/*
319 * This function initializes all the necessary variables. It only returns
320 * if everything is OK. If something fails, it exits.
321 */
322void init(int argc, char **argv)
323{
324 int i;
325 int arg_mode = 0; /* MODE_DEBUG, ... */
326 char *old_argv = *argv;
327 char *tmp;
328 char *cfg_pidfile = NULL;
329
330 if (1<<INTBITS != sizeof(int)*8) {
331 fprintf(stderr,
332 "Error: wrong architecture. Recompile so that sizeof(int)=%d\n",
333 (int)(sizeof(int)*8));
334 exit(1);
335 }
336
337 /*
338 * Initialize the previously static variables.
339 */
340
341 totalconn = actconn = maxfd = listeners = stopping = 0;
342
343
344#ifdef HAPROXY_MEMMAX
345 global.rlimit_memmax = HAPROXY_MEMMAX;
346#endif
347
348 /* initialize the libc's localtime structures once for all so that we
349 * won't be missing memory if we want to send alerts under OOM conditions.
Willy Tarreau2b35c952006-10-15 15:25:48 +0200350 * Also, the Alert() and Warning() functions need <now> to be initialized.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200351 */
352 tv_now(&now);
Willy Tarreaubf736132006-10-15 22:54:47 +0200353 localtime((time_t *)&now.tv_sec);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200354 start_date = now;
355
356 init_log();
Willy Tarreau80587432006-12-24 17:47:20 +0100357 init_proto_http();
Willy Tarreaubaaee002006-06-26 02:48:02 +0200358
359 cfg_polling_mechanism = POLL_USE_SELECT; /* select() is always available */
360#if defined(ENABLE_POLL)
361 cfg_polling_mechanism |= POLL_USE_POLL;
362#endif
363#if defined(ENABLE_EPOLL)
364 cfg_polling_mechanism |= POLL_USE_EPOLL;
365#endif
366
367 pid = getpid();
368 progname = *argv;
369 while ((tmp = strchr(progname, '/')) != NULL)
370 progname = tmp + 1;
371
372 argc--; argv++;
373 while (argc > 0) {
374 char *flag;
375
376 if (**argv == '-') {
377 flag = *argv+1;
378
379 /* 1 arg */
380 if (*flag == 'v') {
381 display_version();
382 exit(0);
383 }
384#if defined(ENABLE_EPOLL)
385 else if (*flag == 'd' && flag[1] == 'e')
386 cfg_polling_mechanism &= ~POLL_USE_EPOLL;
387#endif
388#if defined(ENABLE_POLL)
389 else if (*flag == 'd' && flag[1] == 'p')
390 cfg_polling_mechanism &= ~POLL_USE_POLL;
391#endif
392 else if (*flag == 'V')
393 arg_mode |= MODE_VERBOSE;
394 else if (*flag == 'd' && flag[1] == 'b')
395 arg_mode |= MODE_FOREGROUND;
396 else if (*flag == 'd')
397 arg_mode |= MODE_DEBUG;
398 else if (*flag == 'c')
399 arg_mode |= MODE_CHECK;
400 else if (*flag == 'D')
401 arg_mode |= MODE_DAEMON | MODE_QUIET;
402 else if (*flag == 'q')
403 arg_mode |= MODE_QUIET;
404 else if (*flag == 's' && (flag[1] == 'f' || flag[1] == 't')) {
405 /* list of pids to finish ('f') or terminate ('t') */
406
407 if (flag[1] == 'f')
408 oldpids_sig = SIGUSR1; /* finish then exit */
409 else
410 oldpids_sig = SIGTERM; /* terminate immediately */
411 argv++; argc--;
412
413 if (argc > 0) {
414 oldpids = calloc(argc, sizeof(int));
415 while (argc > 0) {
416 oldpids[nb_oldpids] = atol(*argv);
417 if (oldpids[nb_oldpids] <= 0)
418 usage(old_argv);
419 argc--; argv++;
420 nb_oldpids++;
421 }
422 }
423 }
424 else { /* >=2 args */
425 argv++; argc--;
426 if (argc == 0)
427 usage(old_argv);
428
429 switch (*flag) {
430 case 'n' : cfg_maxconn = atol(*argv); break;
431 case 'm' : global.rlimit_memmax = atol(*argv); break;
432 case 'N' : cfg_maxpconn = atol(*argv); break;
433 case 'f' : cfg_cfgfile = *argv; break;
434 case 'p' : cfg_pidfile = *argv; break;
435 default: usage(old_argv);
436 }
437 }
438 }
439 else
440 usage(old_argv);
441 argv++; argc--;
442 }
443
444 global.mode = MODE_STARTING | /* during startup, we want most of the alerts */
445 (arg_mode & (MODE_DAEMON | MODE_FOREGROUND | MODE_VERBOSE
446 | MODE_QUIET | MODE_CHECK | MODE_DEBUG));
447
448 if (!cfg_cfgfile)
449 usage(old_argv);
450
451 gethostname(hostname, MAX_HOSTNAME_LEN);
452
453 have_appsession = 0;
454 global.maxsock = 10; /* reserve 10 fds ; will be incremented by socket eaters */
455 if (readcfgfile(cfg_cfgfile) < 0) {
456 Alert("Error reading configuration file : %s\n", cfg_cfgfile);
457 exit(1);
458 }
459 if (have_appsession)
460 appsession_init();
461
462 if (global.mode & MODE_CHECK) {
463 qfprintf(stdout, "Configuration file is valid : %s\n", cfg_cfgfile);
464 exit(0);
465 }
466
467 if (cfg_maxconn > 0)
468 global.maxconn = cfg_maxconn;
469
470 if (cfg_pidfile) {
471 if (global.pidfile)
472 free(global.pidfile);
473 global.pidfile = strdup(cfg_pidfile);
474 }
475
476 if (global.maxconn == 0)
477 global.maxconn = DEFAULT_MAXCONN;
478
479 global.maxsock += global.maxconn * 2; /* each connection needs two sockets */
480
481 if (arg_mode & (MODE_DEBUG | MODE_FOREGROUND)) {
482 /* command line debug mode inhibits configuration mode */
483 global.mode &= ~(MODE_DAEMON | MODE_QUIET);
484 }
485 global.mode |= (arg_mode & (MODE_DAEMON | MODE_FOREGROUND | MODE_QUIET |
486 MODE_VERBOSE | MODE_DEBUG | MODE_STATS | MODE_LOG));
487
488 if ((global.mode & MODE_DEBUG) && (global.mode & (MODE_DAEMON | MODE_QUIET))) {
489 Warning("<debug> mode incompatible with <quiet> and <daemon>. Keeping <debug> only.\n");
490 global.mode &= ~(MODE_DAEMON | MODE_QUIET);
491 }
492
493 if ((global.nbproc > 1) && !(global.mode & MODE_DAEMON)) {
494 if (!(global.mode & (MODE_FOREGROUND | MODE_DEBUG)))
495 Warning("<nbproc> is only meaningful in daemon mode. Setting limit to 1 process.\n");
496 global.nbproc = 1;
497 }
498
499 if (global.nbproc < 1)
500 global.nbproc = 1;
501
502 StaticReadEvent = (fd_set *)calloc(1,
503 sizeof(fd_set) *
504 (global.maxsock + FD_SETSIZE - 1) / FD_SETSIZE);
505 StaticWriteEvent = (fd_set *)calloc(1,
506 sizeof(fd_set) *
507 (global.maxsock + FD_SETSIZE - 1) / FD_SETSIZE);
508
509 fdtab = (struct fdtab *)calloc(1,
510 sizeof(struct fdtab) * (global.maxsock));
511 for (i = 0; i < global.maxsock; i++) {
512 fdtab[i].state = FD_STCLOSE;
513 }
514}
515
516void deinit(void)
517{
518 struct proxy *p = proxy;
519 struct cap_hdr *h,*h_next;
520 struct server *s,*s_next;
521 struct listener *l,*l_next;
522
523 while (p) {
524 if (p->id)
525 free(p->id);
526
527 if (p->check_req)
528 free(p->check_req);
529
530 if (p->cookie_name)
531 free(p->cookie_name);
532
533 if (p->capture_name)
534 free(p->capture_name);
535
536 /* only strup if the user have set in config.
537 When should we free it?!
538 if (p->errmsg.msg400) free(p->errmsg.msg400);
539 if (p->errmsg.msg403) free(p->errmsg.msg403);
540 if (p->errmsg.msg408) free(p->errmsg.msg408);
541 if (p->errmsg.msg500) free(p->errmsg.msg500);
542 if (p->errmsg.msg502) free(p->errmsg.msg502);
543 if (p->errmsg.msg503) free(p->errmsg.msg503);
544 if (p->errmsg.msg504) free(p->errmsg.msg504);
545 */
546 if (p->appsession_name)
547 free(p->appsession_name);
548
549 h = p->req_cap;
550 while (h) {
551 h_next = h->next;
552 if (h->name)
553 free(h->name);
554 pool_destroy(h->pool);
555 free(h);
556 h = h_next;
557 }/* end while(h) */
558
559 h = p->rsp_cap;
560 while (h) {
561 h_next = h->next;
562 if (h->name)
563 free(h->name);
564
565 pool_destroy(h->pool);
566 free(h);
567 h = h_next;
568 }/* end while(h) */
569
570 s = p->srv;
571 while (s) {
572 s_next = s->next;
573 if (s->id)
574 free(s->id);
575
576 if (s->cookie)
577 free(s->cookie);
578
579 free(s);
580 s = s_next;
581 }/* end while(s) */
582
583 l = p->listen;
584 while (l) {
585 l_next = l->next;
586 free(l);
587 l = l_next;
588 }/* end while(l) */
589
590 pool_destroy((void **) p->req_cap_pool);
591 pool_destroy((void **) p->rsp_cap_pool);
592 p = p->next;
593 }/* end while(p) */
594
595 if (global.chroot) free(global.chroot);
596 if (global.pidfile) free(global.pidfile);
597
598 if (StaticReadEvent) free(StaticReadEvent);
599 if (StaticWriteEvent) free(StaticWriteEvent);
600 if (fdtab) free(fdtab);
601
602 pool_destroy(pool_session);
603 pool_destroy(pool_buffer);
604 pool_destroy(pool_requri);
605 pool_destroy(pool_task);
606 pool_destroy(pool_capture);
607 pool_destroy(pool_appsess);
608
609 if (have_appsession) {
610 pool_destroy(apools.serverid);
611 pool_destroy(apools.sessid);
612 }
613} /* end deinit() */
614
615/* sends the signal <sig> to all pids found in <oldpids> */
616static void tell_old_pids(int sig)
617{
618 int p;
619 for (p = 0; p < nb_oldpids; p++)
620 kill(oldpids[p], sig);
621}
622
623int main(int argc, char **argv)
624{
625 int err, retry;
626 struct rlimit limit;
627 FILE *pidfile = NULL;
628 init(argc, argv);
629
630 signal(SIGQUIT, dump);
631 signal(SIGUSR1, sig_soft_stop);
632 signal(SIGHUP, sig_dump_state);
633#ifdef DEBUG_MEMORY
634 signal(SIGINT, sig_int);
635 signal(SIGTERM, sig_term);
636#endif
637
638 /* on very high loads, a sigpipe sometimes happen just between the
639 * getsockopt() which tells "it's OK to write", and the following write :-(
640 */
641#ifndef MSG_NOSIGNAL
642 signal(SIGPIPE, SIG_IGN);
643#endif
644
645 /* We will loop at most 100 times with 10 ms delay each time.
646 * That's at most 1 second. We only send a signal to old pids
647 * if we cannot grab at least one port.
648 */
649 retry = MAX_START_RETRIES;
650 err = ERR_NONE;
651 while (retry >= 0) {
652 struct timeval w;
653 err = start_proxies(retry == 0 || nb_oldpids == 0);
654 if (err != ERR_RETRYABLE)
655 break;
656 if (nb_oldpids == 0)
657 break;
658
659 /* FIXME-20060514: Solaris and OpenBSD do not support shutdown() on
660 * listening sockets. So on those platforms, it would be wiser to
661 * simply send SIGUSR1, which will not be undoable.
662 */
663 tell_old_pids(SIGTTOU);
664 /* give some time to old processes to stop listening */
665 w.tv_sec = 0;
666 w.tv_usec = 10*1000;
667 select(0, NULL, NULL, NULL, &w);
668 retry--;
669 }
670
671 /* Note: start_proxies() sends an alert when it fails. */
672 if (err != ERR_NONE) {
673 if (retry != MAX_START_RETRIES && nb_oldpids)
674 tell_old_pids(SIGTTIN);
675 exit(1);
676 }
677
678 if (listeners == 0) {
679 Alert("[%s.main()] No enabled listener found (check the <listen> keywords) ! Exiting.\n", argv[0]);
680 /* Note: we don't have to send anything to the old pids because we
681 * never stopped them. */
682 exit(1);
683 }
684
685 /* prepare pause/play signals */
686 signal(SIGTTOU, sig_pause);
687 signal(SIGTTIN, sig_listen);
688
689 if (global.mode & MODE_DAEMON) {
690 global.mode &= ~MODE_VERBOSE;
691 global.mode |= MODE_QUIET;
692 }
693
694 /* MODE_QUIET can inhibit alerts and warnings below this line */
695
696 global.mode &= ~MODE_STARTING;
697 if ((global.mode & MODE_QUIET) && !(global.mode & MODE_VERBOSE)) {
698 /* detach from the tty */
699 fclose(stdin); fclose(stdout); fclose(stderr);
700 close(0); close(1); close(2);
701 }
702
703 /* open log & pid files before the chroot */
704 if (global.mode & MODE_DAEMON && global.pidfile != NULL) {
705 int pidfd;
706 unlink(global.pidfile);
707 pidfd = open(global.pidfile, O_CREAT | O_WRONLY | O_TRUNC, 0644);
708 if (pidfd < 0) {
709 Alert("[%s.main()] Cannot create pidfile %s\n", argv[0], global.pidfile);
710 if (nb_oldpids)
711 tell_old_pids(SIGTTIN);
712 exit(1);
713 }
714 pidfile = fdopen(pidfd, "w");
715 }
716
717 /* chroot if needed */
718 if (global.chroot != NULL) {
719 if (chroot(global.chroot) == -1) {
720 Alert("[%s.main()] Cannot chroot(%s).\n", argv[0], global.chroot);
721 if (nb_oldpids)
722 tell_old_pids(SIGTTIN);
723 }
724 chdir("/");
725 }
726
727 /* ulimits */
728 if (!global.rlimit_nofile)
729 global.rlimit_nofile = global.maxsock;
730
731 if (global.rlimit_nofile) {
732 limit.rlim_cur = limit.rlim_max = global.rlimit_nofile;
733 if (setrlimit(RLIMIT_NOFILE, &limit) == -1) {
734 Warning("[%s.main()] Cannot raise FD limit to %d.\n", argv[0], global.rlimit_nofile);
735 }
736 }
737
738 if (global.rlimit_memmax) {
739 limit.rlim_cur = limit.rlim_max =
740 global.rlimit_memmax * 1048576 / global.nbproc;
741#ifdef RLIMIT_AS
742 if (setrlimit(RLIMIT_AS, &limit) == -1) {
743 Warning("[%s.main()] Cannot fix MEM limit to %d megs.\n",
744 argv[0], global.rlimit_memmax);
745 }
746#else
747 if (setrlimit(RLIMIT_DATA, &limit) == -1) {
748 Warning("[%s.main()] Cannot fix MEM limit to %d megs.\n",
749 argv[0], global.rlimit_memmax);
750 }
751#endif
752 }
753
754 if (nb_oldpids)
755 tell_old_pids(oldpids_sig);
756
757 /* Note that any error at this stage will be fatal because we will not
758 * be able to restart the old pids.
759 */
760
761 /* setgid / setuid */
762 if (global.gid && setgid(global.gid) == -1) {
763 Alert("[%s.main()] Cannot set gid %d.\n", argv[0], global.gid);
764 exit(1);
765 }
766
767 if (global.uid && setuid(global.uid) == -1) {
768 Alert("[%s.main()] Cannot set uid %d.\n", argv[0], global.uid);
769 exit(1);
770 }
771
772 /* check ulimits */
773 limit.rlim_cur = limit.rlim_max = 0;
774 getrlimit(RLIMIT_NOFILE, &limit);
775 if (limit.rlim_cur < global.maxsock) {
776 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",
777 argv[0], limit.rlim_cur, global.maxconn, global.maxsock, global.maxsock);
778 }
779
780 if (global.mode & MODE_DAEMON) {
781 int ret = 0;
782 int proc;
783
784 /* the father launches the required number of processes */
785 for (proc = 0; proc < global.nbproc; proc++) {
786 ret = fork();
787 if (ret < 0) {
788 Alert("[%s.main()] Cannot fork.\n", argv[0]);
789 if (nb_oldpids)
790 exit(1); /* there has been an error */
791 }
792 else if (ret == 0) /* child breaks here */
793 break;
794 if (pidfile != NULL) {
795 fprintf(pidfile, "%d\n", ret);
796 fflush(pidfile);
797 }
798 }
799 /* close the pidfile both in children and father */
800 if (pidfile != NULL)
801 fclose(pidfile);
802 free(global.pidfile);
803
804 if (proc == global.nbproc)
805 exit(0); /* parent must leave */
806
807 /* if we're NOT in QUIET mode, we should now close the 3 first FDs to ensure
808 * that we can detach from the TTY. We MUST NOT do it in other cases since
809 * it would have already be done, and 0-2 would have been affected to listening
810 * sockets
811 */
812 if (!(global.mode & MODE_QUIET)) {
813 /* detach from the tty */
814 fclose(stdin); fclose(stdout); fclose(stderr);
815 close(0); close(1); close(2); /* close all fd's */
816 global.mode |= MODE_QUIET; /* ensure that we won't say anything from now */
817 }
818 pid = getpid(); /* update child's pid */
819 setsid();
820 }
821
822#if defined(ENABLE_EPOLL)
823 if (cfg_polling_mechanism & POLL_USE_EPOLL) {
824 if (epoll_loop(POLL_LOOP_ACTION_INIT)) {
825 epoll_loop(POLL_LOOP_ACTION_RUN);
826 epoll_loop(POLL_LOOP_ACTION_CLEAN);
827 cfg_polling_mechanism &= POLL_USE_EPOLL;
828 }
829 else {
830 Warning("epoll() is not available. Using poll()/select() instead.\n");
831 cfg_polling_mechanism &= ~POLL_USE_EPOLL;
832 }
833 }
834#endif
835
836#if defined(ENABLE_POLL)
837 if (cfg_polling_mechanism & POLL_USE_POLL) {
838 if (poll_loop(POLL_LOOP_ACTION_INIT)) {
839 poll_loop(POLL_LOOP_ACTION_RUN);
840 poll_loop(POLL_LOOP_ACTION_CLEAN);
841 cfg_polling_mechanism &= POLL_USE_POLL;
842 }
843 else {
844 Warning("poll() is not available. Using select() instead.\n");
845 cfg_polling_mechanism &= ~POLL_USE_POLL;
846 }
847 }
848#endif
849 if (cfg_polling_mechanism & POLL_USE_SELECT) {
850 if (select_loop(POLL_LOOP_ACTION_INIT)) {
851 select_loop(POLL_LOOP_ACTION_RUN);
852 select_loop(POLL_LOOP_ACTION_CLEAN);
853 cfg_polling_mechanism &= POLL_USE_SELECT;
854 }
855 }
856
857
858 /* Free all Hash Keys and all Hash elements */
859 appsession_cleanup();
860 /* Do some cleanup */
861 deinit();
862
863 exit(0);
864}
865
866
867/*
868 * Local variables:
869 * c-indent-level: 8
870 * c-basic-offset: 8
871 * End:
872 */