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