summaryrefslogtreecommitdiff
path: root/src/child.c
blob: da8213908950325b94ebcd5ed9868af5189503c1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
/* tinyproxy - A fast light-weight HTTP proxy
 * Copyright (C) 2000 Robert James Kaes <rjkaes@users.sourceforge.net>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

/* Handles the creation/destruction of the various children required for
 * processing incoming connections.
 */

#include "main.h"

#include "child.h"
#include "daemon.h"
#include "filter.h"
#include "heap.h"
#include "log.h"
#include "reqs.h"
#include "sock.h"
#include "utils.h"
#include "conf.h"

static vector_t listen_fds;

/*
 * Stores the internal data needed for each child (connection)
 */
enum child_status_t { T_EMPTY, T_WAITING, T_CONNECTED };
struct child_s {
        pid_t tid;
        unsigned int connects;
        enum child_status_t status;
};

/*
 * A pointer to an array of children. A certain number of children are
 * created when the program is started.
 */
static struct child_s *child_ptr;

static struct child_config_s {
        unsigned int maxclients, maxrequestsperchild;
        unsigned int maxspareservers, minspareservers, startservers;
} child_config;

static unsigned int *servers_waiting;   /* servers waiting for a connection */

/*
 * Lock/Unlock the "servers_waiting" variable so that two children cannot
 * modify it at the same time.
 */
#define SERVER_COUNT_LOCK()   _child_lock_wait()
#define SERVER_COUNT_UNLOCK() _child_lock_release()

/* START OF LOCKING SECTION */

/*
 * These variables are required for the locking mechanism.  Also included
 * are the "private" functions for locking/unlocking.
 */
static struct flock lock_it, unlock_it;
static int lock_fd = -1;

static void _child_lock_init (void)
{
        char lock_file[] = "/tmp/tinyproxy.servers.lock.XXXXXX";

        /* Only allow u+rw bits. This may be required for some versions
         * of glibc so that mkstemp() doesn't make us vulnerable.
         */
        umask (0177);

        lock_fd = mkstemp (lock_file);
        unlink (lock_file);

        lock_it.l_type = F_WRLCK;
        lock_it.l_whence = SEEK_SET;
        lock_it.l_start = 0;
        lock_it.l_len = 0;

        unlock_it.l_type = F_UNLCK;
        unlock_it.l_whence = SEEK_SET;
        unlock_it.l_start = 0;
        unlock_it.l_len = 0;
}

static void _child_lock_wait (void)
{
        int rc;

        while ((rc = fcntl (lock_fd, F_SETLKW, &lock_it)) < 0) {
                if (errno == EINTR)
                        continue;
                else
                        return;
        }
}

static void _child_lock_release (void)
{
        if (fcntl (lock_fd, F_SETLKW, &unlock_it) < 0)
                return;
}

/* END OF LOCKING SECTION */

#define SERVER_INC() do { \
    SERVER_COUNT_LOCK(); \
    ++(*servers_waiting); \
    DEBUG2("INC: servers_waiting: %d", *servers_waiting); \
    SERVER_COUNT_UNLOCK(); \
} while (0)

#define SERVER_DEC() do { \
    SERVER_COUNT_LOCK(); \
    assert(*servers_waiting > 0); \
    --(*servers_waiting); \
    DEBUG2("DEC: servers_waiting: %d", *servers_waiting); \
    SERVER_COUNT_UNLOCK(); \
} while (0)

/*
 * Set the configuration values for the various child related settings.
 */
short int child_configure (child_config_t type, unsigned int val)
{
        switch (type) {
        case CHILD_MAXCLIENTS:
                child_config.maxclients = val;
                break;
        case CHILD_MAXSPARESERVERS:
                child_config.maxspareservers = val;
                break;
        case CHILD_MINSPARESERVERS:
                child_config.minspareservers = val;
                break;
        case CHILD_STARTSERVERS:
                child_config.startservers = val;
                break;
        case CHILD_MAXREQUESTSPERCHILD:
                child_config.maxrequestsperchild = val;
                break;
        default:
                DEBUG2 ("Invalid type (%d)", type);
                return -1;
        }

        return 0;
}

/**
 * child signal handler for sighup
 */
static void child_sighup_handler (int sig)
{
        if (sig == SIGHUP) {
                /*
                 * Ignore the return value of reload_config for now.
                 * This should actually be handled somehow...
                 */
                reload_config ();

#ifdef FILTER_ENABLE
                filter_reload ();
#endif /* FILTER_ENABLE */
        }
}

/*
 * This is the main (per child) loop.
 */
static void child_main (struct child_s *ptr)
{
        int connfd;
        struct sockaddr *cliaddr;
        socklen_t clilen;
        fd_set rfds;
        int maxfd = 0;
        ssize_t i;
        int ret;

        cliaddr = (struct sockaddr *)
                        safemalloc (sizeof(struct sockaddr_storage));
        if (!cliaddr) {
                log_message (LOG_CRIT,
                             "Could not allocate memory for child address.");
                exit (0);
        }

        ptr->connects = 0;

        /*
         * We have to wait for connections on multiple fds,
         * so use select.
         */

        FD_ZERO(&rfds);

        for (i = 0; i < vector_length(listen_fds); i++) {
                int *fd = (int *) vector_getentry(listen_fds, i, NULL);

                ret = socket_nonblocking(*fd);
                if (ret != 0) {
                        log_message(LOG_ERR, "Failed to set the listening "
                                    "socket %d to non-blocking: %s",
                                    fd, strerror(errno));
                        exit(1);
                }

                FD_SET(*fd, &rfds);
                maxfd = max(maxfd, *fd);
        }

        while (!config.quit) {
                int listenfd = -1;

                ptr->status = T_WAITING;

                clilen = sizeof(struct sockaddr_storage);

                ret = select(maxfd + 1, &rfds, NULL, NULL, NULL);
                if (ret == -1) {
                        log_message (LOG_ERR, "error calling select: %s",
                                     strerror(errno));
                        exit(1);
                } else if (ret == 0) {
                        log_message (LOG_WARNING, "Strange: select returned 0 "
                                     "but we did not specify a timeout...");
                        continue;
                }

                for (i = 0; i < vector_length(listen_fds); i++) {
                        int *fd = (int *) vector_getentry(listen_fds, i, NULL);

                        if (FD_ISSET(*fd, &rfds)) {
                                /*
                                 * only accept the connection on the first
                                 * fd that we find readable. - fair?
                                 */
                                listenfd = *fd;
                                break;
                        }
                }

                if (listenfd == -1) {
                        log_message(LOG_WARNING, "Strange: None of our listen "
                                    "fds was readable after select");
                        continue;
                }

                ret = socket_blocking(listenfd);
                if (ret != 0) {
                        log_message(LOG_ERR, "Failed to set listening "
                                    "socket %d to blocking for accept: %s",
                                    listenfd, strerror(errno));
                        exit(1);
                }

                /*
                 * We have a socket that is readable.
                 * Continue handling this connection.
                 */

                connfd = accept (listenfd, cliaddr, &clilen);

#ifndef NDEBUG
                /*
                 * Enable the TINYPROXY_DEBUG environment variable if you
                 * want to use the GDB debugger.
                 */
                if (getenv ("TINYPROXY_DEBUG")) {
                        /* Pause for 10 seconds to allow us to connect debugger */
                        fprintf (stderr,
                                 "Process has accepted connection: %ld\n",
                                 (long int) ptr->tid);
                        sleep (10);
                        fprintf (stderr, "Continuing process: %ld\n",
                                 (long int) ptr->tid);
                }
#endif

                /*
                 * Make sure no error occurred...
                 */
                if (connfd < 0) {
                        log_message (LOG_ERR,
                                     "Accept returned an error (%s) ... retrying.",
                                     strerror (errno));
                        continue;
                }

                ptr->status = T_CONNECTED;

                SERVER_DEC ();

                handle_connection (connfd);
                ptr->connects++;

                if (child_config.maxrequestsperchild != 0) {
                        DEBUG2 ("%u connections so far...", ptr->connects);

                        if (ptr->connects == child_config.maxrequestsperchild) {
                                log_message (LOG_NOTICE,
                                             "Child has reached MaxRequestsPerChild (%u). "
                                             "Killing child.", ptr->connects);
                                break;
                        }
                }

                SERVER_COUNT_LOCK ();
                if (*servers_waiting > child_config.maxspareservers) {
                        /*
                         * There are too many spare children, kill ourself
                         * off.
                         */
                        log_message (LOG_NOTICE,
                                     "Waiting servers (%d) exceeds MaxSpareServers (%d). "
                                     "Killing child.",
                                     *servers_waiting,
                                     child_config.maxspareservers);
                        SERVER_COUNT_UNLOCK ();

                        break;
                } else {
                        SERVER_COUNT_UNLOCK ();
                }

                SERVER_INC ();
        }

        ptr->status = T_EMPTY;

        safefree (cliaddr);
        exit (0);
}

/*
 * Fork a child "child" (or in our case a process) and then start up the
 * child_main() function.
 */
static pid_t child_make (struct child_s *ptr)
{
        pid_t pid;

        if ((pid = fork ()) > 0)
                return pid;     /* parent */

        /*
         * Reset the SIGNALS so that the child can be reaped.
         */
        set_signal_handler (SIGCHLD, SIG_DFL);
        set_signal_handler (SIGTERM, SIG_DFL);
        set_signal_handler (SIGHUP, child_sighup_handler);

        child_main (ptr);       /* never returns */
        return -1;
}

/*
 * Create a pool of children to handle incoming connections
 */
short int child_pool_create (void)
{
        unsigned int i;

        /*
         * Make sure the number of MaxClients is not zero, since this
         * variable determines the size of the array created for children
         * later on.
         */
        if (child_config.maxclients == 0) {
                log_message (LOG_ERR,
                             "child_pool_create: \"MaxClients\" must be "
                             "greater than zero.");
                return -1;
        }
        if (child_config.startservers == 0) {
                log_message (LOG_ERR,
                             "child_pool_create: \"StartServers\" must be "
                             "greater than zero.");
                return -1;
        }

        child_ptr =
            (struct child_s *) calloc_shared_memory (child_config.maxclients,
                                                     sizeof (struct child_s));
        if (!child_ptr) {
                log_message (LOG_ERR,
                             "Could not allocate memory for children.");
                return -1;
        }

        servers_waiting =
            (unsigned int *) malloc_shared_memory (sizeof (unsigned int));
        if (servers_waiting == MAP_FAILED) {
                log_message (LOG_ERR,
                             "Could not allocate memory for child counting.");
                return -1;
        }
        *servers_waiting = 0;

        /*
         * Create a "locking" file for use around the servers_waiting
         * variable.
         */
        _child_lock_init ();

        if (child_config.startservers > child_config.maxclients) {
                log_message (LOG_WARNING,
                             "Can not start more than \"MaxClients\" servers. "
                             "Starting %u servers instead.",
                             child_config.maxclients);
                child_config.startservers = child_config.maxclients;
        }

        for (i = 0; i != child_config.maxclients; i++) {
                child_ptr[i].status = T_EMPTY;
                child_ptr[i].connects = 0;
        }

        for (i = 0; i != child_config.startservers; i++) {
                DEBUG2 ("Trying to create child %d of %d", i + 1,
                        child_config.startservers);
                child_ptr[i].status = T_WAITING;
                child_ptr[i].tid = child_make (&child_ptr[i]);

                if (child_ptr[i].tid < 0) {
                        log_message (LOG_WARNING,
                                     "Could not create child number %d of %d",
                                     i, child_config.startservers);
                        return -1;
                } else {
                        log_message (LOG_INFO,
                                     "Creating child number %d of %d ...",
                                     i + 1, child_config.startservers);

                        SERVER_INC ();
                }
        }

        log_message (LOG_INFO, "Finished creating all children.");

        return 0;
}

/*
 * Keep the proper number of servers running. This is the birth of the
 * servers. It monitors this at least once a second.
 */
void child_main_loop (void)
{
        unsigned int i;

        while (1) {
                if (config.quit)
                        return;

                /* If there are not enough spare servers, create more */
                SERVER_COUNT_LOCK ();
                if (*servers_waiting < child_config.minspareservers) {
                        log_message (LOG_NOTICE,
                                     "Waiting servers (%d) is less than MinSpareServers (%d). "
                                     "Creating new child.",
                                     *servers_waiting,
                                     child_config.minspareservers);

                        SERVER_COUNT_UNLOCK ();

                        for (i = 0; i != child_config.maxclients; i++) {
                                if (child_ptr[i].status == T_EMPTY) {
                                        child_ptr[i].status = T_WAITING;
                                        child_ptr[i].tid =
                                            child_make (&child_ptr[i]);
                                        if (child_ptr[i].tid < 0) {
                                                log_message (LOG_NOTICE,
                                                             "Could not create child");

                                                child_ptr[i].status = T_EMPTY;
                                                break;
                                        }

                                        SERVER_INC ();

                                        break;
                                }
                        }
                } else {
                        SERVER_COUNT_UNLOCK ();
                }

                sleep (5);

                /* Handle log rotation if it was requested */
                if (received_sighup) {
                        /*
                         * Ignore the return value of reload_config for now.
                         * This should actually be handled somehow...
                         */
                        reload_config ();

#ifdef FILTER_ENABLE
                        filter_reload ();
#endif /* FILTER_ENABLE */

                        /* propagate filter reload to all children */
                        child_kill_children (SIGHUP);

                        received_sighup = FALSE;
                }
        }
}

/*
 * Go through all the non-empty children and cancel them.
 */
void child_kill_children (int sig)
{
        unsigned int i;

        for (i = 0; i != child_config.maxclients; i++) {
                if (child_ptr[i].status != T_EMPTY)
                        kill (child_ptr[i].tid, sig);
        }
}


/**
 * Listen on the various configured interfaces
 */
int child_listening_sockets(vector_t listen_addrs, uint16_t port)
{
        int ret;
        ssize_t i;

        assert (port > 0);

        if (listen_fds == NULL) {
                listen_fds = vector_create();
                if (listen_fds == NULL) {
                        log_message (LOG_ERR, "Could not create the list "
                                     "of listening fds");
                        return -1;
                }
        }

        if ((listen_addrs == NULL) ||
            (vector_length(config.listen_addrs) == 0))
        {
                /*
                 * no Listen directive:
                 * listen on the wildcard address(es)
                 */
                ret = listen_sock(NULL, port, listen_fds);
                return ret;
        }

        for (i = 0; i < vector_length(config.listen_addrs); i++) {
                const char *addr;

                addr = (char *)vector_getentry(config.listen_addrs, i, NULL);
                if (addr == NULL) {
                        log_message(LOG_WARNING,
                                    "got NULL from listen_addrs - skipping");
                        continue;
                }

                ret = listen_sock(addr, port, listen_fds);
                if (ret != 0) {
                        return ret;
                }
        }

        return 0;
}

void child_close_sock (void)
{
        ssize_t i;

        for (i = 0; i < vector_length(listen_fds); i++) {
                int *fd = (int *) vector_getentry(listen_fds, i, NULL);
                close (*fd);
        }

        vector_delete(listen_fds);

        listen_fds = NULL;
}