~ubuntu-branches/ubuntu/hardy/haproxy/hardy

« back to all changes in this revision

Viewing changes to src/haproxy.c

  • Committer: Bazaar Package Importer
  • Author(s): Arnaud Cornet
  • Date: 2007-08-17 09:33:41 UTC
  • Revision ID: james.westby@ubuntu.com-20070817093341-h0t6aeeoyzo25z3r
Tags: upstream-1.3.12.dfsg
ImportĀ upstreamĀ versionĀ 1.3.12.dfsg

Show diffs side-by-side

added added

removed removed

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