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