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