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