varnish-cache/bin/varnishd/mgt/mgt_main.c
0
/*-
1
 * Copyright (c) 2006 Verdens Gang AS
2
 * Copyright (c) 2006-2017 Varnish Software AS
3
 * All rights reserved.
4
 *
5
 * Author: Poul-Henning Kamp <phk@phk.freebsd.dk>
6
 *
7
 * SPDX-License-Identifier: BSD-2-Clause
8
 *
9
 * Redistribution and use in source and binary forms, with or without
10
 * modification, are permitted provided that the following conditions
11
 * are met:
12
 * 1. Redistributions of source code must retain the above copyright
13
 *    notice, this list of conditions and the following disclaimer.
14
 * 2. Redistributions in binary form must reproduce the above copyright
15
 *    notice, this list of conditions and the following disclaimer in the
16
 *    documentation and/or other materials provided with the distribution.
17
 *
18
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21
 * ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
22
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28
 * SUCH DAMAGE.
29
 *
30
 * The management process and CLI handling
31
 */
32
33
#include "config.h"
34
35
#include <ctype.h>
36
#include <fcntl.h>
37
#include <signal.h>
38
#include <stdarg.h>
39
#include <stdio.h>
40
#include <stdlib.h>
41
#include <string.h>
42
#include <syslog.h>
43
#include <unistd.h>
44
#include <sys/resource.h>
45
#include <sys/stat.h>
46
#include <sys/socket.h>
47
48
#include "mgt/mgt.h"
49
#include "acceptor/cache_acceptor.h"
50
#include "acceptor/mgt_acceptor.h"
51
#include "common/heritage.h"
52
53
#include "hash/hash_slinger.h"
54
#include "libvcc.h"
55
#include "vcli_serve.h"
56
#include "vct.h"
57
#include "vev.h"
58
#include "vfil.h"
59
#include "vin.h"
60
#include "vpf.h"
61
#include "vrnd.h"
62
#include "vsha256.h"
63
#include "vsub.h"
64
#include "vtim.h"
65
#include "waiter/mgt_waiter.h"
66
#include "vsa.h"
67
#include "vus.h"
68
69
struct heritage         heritage;
70
unsigned                d_flag = 0;
71
struct vev_root         *mgt_evb;
72
int                     exit_status = 0;
73
struct vsb              *vident;
74
struct VSC_mgt          *VSC_C_mgt;
75
static int              I_fd = -1;
76
static char             *workdir;
77
78
static struct vfil_path *vcl_path = NULL;
79
80
static const char opt_spec[] = "?a:b:CdE:f:Fh:i:I:j:l:M:n:P:p:r:S:s:T:t:VW:x:";
81
82
/*--------------------------------------------------------------------*/
83
84
// Basic options documentation with compile time dependencies
85
static void
86 40
mgt_DumpOptions(void)
87
{
88 40
        printf(".. _opt_n:\n\n");
89 40
        printf("-n workdir\n\n");
90 40
        printf("  Runtime directory for the shared memory, "
91
               "compiled VCLs etc.\n\n");
92 40
        printf("  In performance critical applications, this directory "
93
               "should be on a RAM backed filesystem.\n\n");
94 40
        printf("  When running multiple varnishd instances, separate "
95
               "directories need to be used.\n\n");
96 40
        VIN_DumpDefaults();
97 40
}
98
99
static void
100 80
usage(void)
101
{
102
        char *p;
103
104
#define FMT_NONL "  %-35s # %s"
105
#define FMT FMT_NONL "\n"
106
107 80
        printf( "Usage: varnishd [options]\n");
108
109 80
        printf("\nBasic options:\n");
110
111 80
        printf(FMT, "[-a [name=][listen_address",
112
            "HTTP listen address, protocol, options.");
113 80
        printf(FMT, "     [,PROTO|,option=value,...]]",
114
            "Can be specified multiple times.");
115 80
        printf(FMT, "",
116
            "  default: \":80,HTTP\"");
117 80
        printf(FMT, "  options:",
118
            "Proto can be \"PROXY\" or \"HTTP\" (default)");
119 80
        printf(FMT, "    [,user=<u>][,group=<g>]",
120
            "user, group and mode set permissions for");
121 80
        printf(FMT, "    [,mode=<m>]",
122
            "  a Unix domain socket.");
123 80
        printf(FMT, "-b none", "No backend");
124 80
        printf(FMT, "-b [addr[:port]|path]", "Backend address and port");
125 80
        printf(FMT, "", "  or socket file path");
126 80
        printf(FMT, "", "  default: \":80\"");
127 80
        printf(FMT, "-f vclfile", "VCL program");
128 80
        printf(FMT, "", "Can be specified multiple times.");
129 80
        printf(FMT, "-n dir", "Working directory");
130
131 80
        p = VIN_n_Arg(NULL);
132 80
        AN(p);
133 80
        printf(FMT_NONL "  default: %s\n", "", "", p);
134 80
        free(p);
135
136 80
        printf("\n-b can be used only once, and not together with -f\n");
137
138 80
        printf("\nDocumentation options:\n");
139 80
        printf(FMT, "-?", "Prints this usage message");
140 80
        printf(FMT, "-x parameter", "Parameter documentation");
141 80
        printf(FMT, "-x vsl", "VSL record documentation");
142 80
        printf(FMT, "-x cli", "CLI command documentation");
143 80
        printf(FMT, "-x builtin", "Builtin VCL program");
144 80
        printf(FMT, "-x optstring", "List of getopt options");
145 80
        printf(FMT, "-x options", "Dynamic options documentation");
146
147 80
        printf("\nOperations options:\n");
148
149 80
        printf(FMT, "-F", "Run in foreground");
150 80
        printf(FMT, "-T address[:port]", "CLI address");
151 80
        printf(FMT, "", "Can be specified multiple times.");
152 80
        printf(FMT, "-M address:port", "Reverse CLI destination");
153 80
        printf(FMT, "", "Can be specified multiple times.");
154 80
        printf(FMT, "-P file", "PID file");
155 80
        printf(FMT, "-i identity", "Identity of varnish instance");
156 80
        printf(FMT, "-I clifile", "Initialization CLI commands");
157 80
        printf(FMT, "-E extension", "Load extension");
158
159 80
        printf("\nTuning options:\n");
160
161 80
        printf(FMT, "-t TTL", "Default TTL");
162 80
        printf(FMT, "-p param=value", "set parameter");
163 80
        printf(FMT, "", "Can be specified multiple times.");
164
165 80
        printf(FMT, "-s [name=]kind[,options]", "Storage specification");
166 80
        printf(FMT, "", "Can be specified multiple times.");
167
#ifdef HAVE_UMEM_H
168
        printf(FMT, "", "  -s default (=umem)");
169
        printf(FMT, "", "  -s umem");
170
#else
171 80
        printf(FMT, "", "  -s default (=malloc)");
172
#endif
173 80
        printf(FMT, "", "  -s malloc");
174 80
        printf(FMT, "", "  -s file");
175
176 80
        printf(FMT, "-l vsl", "Size of shared memory log");
177 80
        printf(FMT, "", "  vsl: space for VSL records [80m]");
178
179 80
        printf("\nSecurity options:\n");
180
181 80
        printf(FMT, "-r param[,param...]", "Set parameters read-only from CLI");
182 80
        printf(FMT, "", "Can be specified multiple times.");
183 80
        printf(FMT, "-S secret-file", "Secret file for CLI authentication");
184 80
        printf(FMT, "-j jail[,options]", "Jail specification");
185
#ifdef HAVE_SETPPRIV
186
        printf(FMT, "", "  -j solaris");
187
#endif
188
#ifdef __linux__
189
        printf(FMT, "", "  -j linux");
190
#endif
191 80
        printf(FMT, "", "  -j unix");
192 80
        printf(FMT, "", "  -j none");
193
194 80
        printf("\nAdvanced/Dev/Debug options:\n");
195
196 80
        printf(FMT, "-d", "debug mode");
197 80
        printf(FMT, "", "Stay in foreground, CLI on stdin.");
198 80
        printf(FMT, "-C", "Output VCL code compiled to C language");
199 80
        printf(FMT, "-V", "version");
200 80
        printf(FMT, "-h kind[,options]", "Hash specification");
201 80
        printf(FMT, "-W waiter", "Waiter implementation");
202 80
}
203
204
/*--------------------------------------------------------------------*/
205
206
struct arg_list {
207
        unsigned                magic;
208
#define ARG_LIST_MAGIC          0x7b0d1bc4
209
        char                    arg[2];
210
        char                    *val;
211
        VTAILQ_ENTRY(arg_list)  list;
212
        void                    *priv;
213
};
214
215
static VTAILQ_HEAD(, arg_list) arglist = VTAILQ_HEAD_INITIALIZER(arglist);
216
217
static struct arg_list *
218 540160
arg_list_add(const char arg, const char *val)
219
{
220
        struct arg_list *alp;
221
222 540160
        ALLOC_OBJ(alp, ARG_LIST_MAGIC);
223 540160
        AN(alp);
224 540160
        alp->arg[0] = arg;
225 540160
        alp->arg[1] = '\0';
226 540160
        REPLACE(alp->val, val);
227 540160
        VTAILQ_INSERT_TAIL(&arglist, alp, list);
228 540160
        return (alp);
229
}
230
231
static unsigned
232 160240
arg_list_count(const char *arg)
233
{
234 160240
        unsigned retval = 0;
235
        struct arg_list *alp;
236
237 2101720
        VTAILQ_FOREACH(alp, &arglist, list) {
238 1941480
                if (!strcmp(alp->arg, arg))
239 6360
                        retval++;
240 1941480
        }
241 160240
        return (retval);
242
}
243
244
/*--------------------------------------------------------------------*/
245
246
static void
247 540240
cli_check(const struct cli *cli)
248
{
249 540240
        if (cli->result == CLIS_OK || cli->result == CLIS_TRUNCATED) {
250 540200
                AZ(VSB_finish(cli->sb));
251 540200
                if (VSB_len(cli->sb) > 0)
252 80
                        fprintf(stderr, "Warnings:\n%s\n", VSB_data(cli->sb));
253 540200
                VSB_clear(cli->sb);
254 540200
                return;
255
        }
256 40
        AZ(VSB_finish(cli->sb));
257 40
        fprintf(stderr, "Error:\n%s\n", VSB_data(cli->sb));
258 40
        exit(2);
259
}
260
261
/*--------------------------------------------------------------------
262
 * This function is called when the CLI on stdin is closed.
263
 */
264
265
static int v_matchproto_(mgt_cli_close_f)
266 37200
mgt_stdin_close(void *priv)
267
{
268
269 37200
        (void)priv;
270 37200
        return (-42);
271
}
272
273
/*--------------------------------------------------------------------
274
 * Autogenerate a -S file using strong random bits from the kernel.
275
 */
276
277
static void
278 179400
mgt_secret_atexit(void)
279
{
280
281
        /* Only master process */
282 179400
        if (getpid() != heritage.mgt_pid)
283 141760
                return;
284 37640
        VJ_master(JAIL_MASTER_FILE);
285 37640
        (void)unlink("_.secret");
286 37640
        VJ_master(JAIL_MASTER_LOW);
287 179400
}
288
289
static const char *
290 37680
make_secret(const char *dirname)
291
{
292
        char *fn;
293
        int fdo;
294
        int i;
295
        unsigned char b;
296
297 37680
        assert(asprintf(&fn, "%s/_.secret", dirname) > 0);
298
299 37680
        VJ_master(JAIL_MASTER_FILE);
300 37680
        if (unlink(fn) < 0 && errno != ENOENT) {
301 40
                ARGV_ERR("Cannot remove preexisting secret-file in %s (%s)\n",
302
                    dirname, VAS_errtxt(errno));
303 0
        }
304
305 0
        fdo = open(fn, O_RDWR|O_CREAT|O_EXCL, 0640);
306 0
        if (fdo < 0) {
307 0
                ARGV_ERR("Cannot create secret-file in %s (%s)\n",
308
                    dirname, VAS_errtxt(errno));
309 0
        }
310
311 9673480
        for (i = 0; i < 256; i++) {
312 9635840
                AZ(VRND_RandomCrypto(&b, 1));
313 9635840
                assert(1 == write(fdo, &b, 1));
314 9635840
        }
315 37640
        closefd(&fdo);
316 37640
        VJ_master(JAIL_MASTER_LOW);
317 37640
        AZ(atexit(mgt_secret_atexit));
318 37640
        return (fn);
319
}
320
321
static void
322 480
mgt_Cflag_atexit(void)
323
{
324
325
        /* Only master process */
326 480
        if (getpid() != heritage.mgt_pid)
327 320
                return;
328 160
        if (arg_list_count("E")) {
329 0
                vext_cleanup(1);
330 0
                VJ_rmdir("vext_cache");
331 0
        }
332 160
        VJ_rmdir("vmod_cache");
333 160
        VJ_rmdir("worker_tmpdir");
334 160
        (void)chdir("/");
335 160
        VJ_rmdir(workdir);
336 480
}
337
338
/*--------------------------------------------------------------------*/
339
340
static void
341 40760
mgt_tests(void)
342
{
343 40760
        assert(VTIM_parse("Sun, 06 Nov 1994 08:49:37 GMT") == 784111777);
344 40760
        assert(VTIM_parse("Sunday, 06-Nov-94 08:49:37 GMT") == 784111777);
345 40760
        assert(VTIM_parse("Sun Nov  6 08:49:37 1994") == 784111777);
346
347
        /* Check that our VSHA256 works */
348 40760
        VSHA256_Test();
349 40760
}
350
351
static void
352 40760
mgt_initialize(struct cli *cli)
353
{
354
        static unsigned clilim = 32768;
355
356
        /* for ASSERT_MGT() */
357 40760
        heritage.mgt_pid = getpid();
358
359
        /* Create a cli for convenience in otherwise CLI functions */
360 40760
        INIT_OBJ(cli, CLI_MAGIC);
361 40760
        cli[0].sb = VSB_new_auto();
362 40760
        AN(cli[0].sb);
363 40760
        cli[0].result = CLIS_OK;
364 40760
        cli[0].limit = &clilim;
365
366 40760
        mgt_cli_init_cls();             // CLI commands can be registered
367
368 40760
        MCF_InitParams(cli);
369
370 40760
        VCC_VCL_Range(&heritage.min_vcl_version, &heritage.max_vcl_version);
371
372 40760
        cli_check(cli);
373 40760
}
374
375
static void
376 360
mgt_x_arg(const char *x_arg)
377
{
378 360
        if (!strcmp(x_arg, "parameter"))
379 80
                MCF_DumpRstParam();
380 280
        else if (!strcmp(x_arg, "vsl"))
381 40
                mgt_DumpRstVsl();
382 240
        else if (!strcmp(x_arg, "cli"))
383 80
                mgt_DumpRstCli();
384 160
        else if (!strcmp(x_arg, "builtin"))
385 40
                mgt_DumpBuiltin();
386 120
        else if (!strcmp(x_arg, "optstring"))
387 40
                (void)printf("%s\n", opt_spec);
388 80
        else if (!strcmp(x_arg, "options"))
389 40
                mgt_DumpOptions();
390
        else
391 40
                ARGV_ERR("Invalid -x argument\n");
392 320
}
393
394
/*--------------------------------------------------------------------*/
395
396
#define ERIC_MAGIC 0x2246988a           /* Eric is not random */
397
398
static int
399 800
mgt_eric(void)
400
{
401
        int eric_pipes[2];
402
        unsigned u;
403
        ssize_t sz;
404
405 800
        AZ(pipe(eric_pipes));
406
407 800
        switch (fork()) {
408
        case -1:
409 0
                fprintf(stderr, "Fork() failed: %s\n", VAS_errtxt(errno));
410 0
                exit(-1);
411
        case 0:
412 800
                closefd(&eric_pipes[0]);
413 800
                assert(setsid() > 1);
414
415 800
                VFIL_null_fd(STDIN_FILENO);
416 800
                return (eric_pipes[1]);
417
        default:
418 800
                break;
419
        }
420 800
        closefd(&eric_pipes[1]);
421 800
        sz = read(eric_pipes[0], &u, sizeof u);
422 800
        if (sz == sizeof u && u == ERIC_MAGIC)
423 0
                exit(0);
424 200
        else if (sz == sizeof u && u != 0)
425 200
                exit(u);
426
        else
427 600
                exit(-1);
428
}
429
430
static void
431 200
mgt_eric_im_done(int eric_fd, unsigned u)
432
{
433
434 200
        if (u == 0)
435 0
                u = ERIC_MAGIC;
436
437 200
        VFIL_null_fd(STDIN_FILENO);
438 200
        VFIL_null_fd(STDOUT_FILENO);
439 200
        VFIL_null_fd(STDERR_FILENO);
440
441 200
        assert(write(eric_fd, &u, sizeof u) == sizeof u);
442 200
        closefd(&eric_fd);
443 200
}
444
445
/*--------------------------------------------------------------------*/
446
447
static int v_matchproto_(vev_cb_f)
448 160
mgt_sigint(const struct vev *e, int what)
449
{
450
451 160
        (void)what;
452 160
        MGT_Complain(C_ERR, "Manager got %s from PID %jd", e->name, (intmax_t)e->siginfo->si_pid);
453 160
        (void)fflush(stdout);
454 160
        if (MCH_Running())
455 120
                MCH_Stop_Child();
456 160
        return (-42);
457
}
458
459
/*--------------------------------------------------------------------*/
460
461
static int v_matchproto_(vev_cb_f)
462 71630
mgt_uptime(const struct vev *e, int what)
463
{
464
        static double mgt_uptime_t0 = 0;
465
466 71630
        (void)e;
467 71630
        (void)what;
468 71630
        AN(VSC_C_mgt);
469 71630
        if (mgt_uptime_t0 == 0)
470 35990
                mgt_uptime_t0 = VTIM_real();
471 71630
        VSC_C_mgt->uptime = (uint64_t)(VTIM_real() - mgt_uptime_t0);
472 71630
        return (0);
473
}
474
475
/*--------------------------------------------------------------------*/
476
477
static int v_matchproto_(mgt_cli_close_f)
478 40
mgt_I_close(void *priv)
479
{
480 40
        (void)priv;
481 40
        fprintf(stderr, "END of -I file processing\n");
482 40
        I_fd = -1;
483 40
        return (0);
484
}
485
486
/*--------------------------------------------------------------------*/
487
488
struct f_arg {
489
        unsigned                magic;
490
#define F_ARG_MAGIC             0x840649a8
491
        char                    *farg;
492
        char                    *src;
493
};
494
495
static struct f_arg *
496 520
mgt_f_read(const char *fn)
497
{
498
        struct f_arg *fa;
499
        char *f, *fnp;
500
501 520
        ALLOC_OBJ(fa, F_ARG_MAGIC);
502 520
        AN(fa);
503 520
        REPLACE(fa->farg, fn);
504 520
        VFIL_setpath(&vcl_path, mgt_vcl_path);
505 520
        if (VFIL_searchpath(vcl_path, NULL, &f, fn, &fnp) || f == NULL) {
506 120
                ARGV_ERR("Cannot read -f file '%s' (%s)\n",
507
                    fnp != NULL ? fnp : fn, VAS_errtxt(errno));
508 0
        }
509 400
        free(fa->farg);
510 400
        fa->farg = fnp;
511 400
        fa->src = f;
512 400
        return (fa);
513
}
514
515
static void
516 1000
mgt_b_conv(const char *b_arg)
517
{
518
        struct f_arg *fa;
519
        struct vsb *vsb;
520
521 1000
        ALLOC_OBJ(fa, F_ARG_MAGIC);
522 1000
        AN(fa);
523 1000
        REPLACE(fa->farg, "<-b argument>");
524 1000
        vsb = VSB_new_auto();
525 1000
        AN(vsb);
526 1000
        VSB_cat(vsb, "vcl 4.1;\n");
527 1000
        VSB_cat(vsb, "backend default ");
528 1000
        if (!strcasecmp(b_arg, "none"))
529 520
                VSB_cat(vsb, "none;\n");
530 480
        else if (VUS_is(b_arg))
531 40
                VSB_printf(vsb, "{\n    .path = \"%s\";\n}\n", b_arg);
532
        else
533 440
                VSB_printf(vsb, "{\n    .host = \"%s\";\n}\n", b_arg);
534 1000
        AZ(VSB_finish(vsb));
535 1000
        fa->src = strdup(VSB_data(vsb));
536 1000
        AN(fa->src);
537 1000
        VSB_destroy(&vsb);
538 1000
        AZ(arg_list_count("f"));
539 1000
        arg_list_add('f', "")->priv = fa;
540 1000
}
541
542
static int
543 1120
mgt_process_f_arg(struct cli *cli, unsigned C_flag, void **fap)
544
{
545 1120
        int retval = 0;
546
        struct f_arg *fa;
547 1120
        const char *name = NULL;
548
549 1120
        TAKE_OBJ_NOTNULL(fa, fap, F_ARG_MAGIC);
550 1120
        if (arg_list_count("f") == 1)
551 1040
                name = "boot";
552 1120
        mgt_vcl_startup(cli, fa->src, name, fa->farg, C_flag);
553 1120
        if (C_flag) {
554 160
                if (cli->result != CLIS_OK &&
555 0
                    cli->result != CLIS_TRUNCATED)
556 0
                        retval = 2;
557 160
                AZ(VSB_finish(cli->sb));
558 160
                fprintf(stderr, "%s\n", VSB_data(cli->sb));
559 160
                VSB_clear(cli->sb);
560 160
        } else {
561 960
                cli_check(cli);
562
        }
563 1120
        free(fa->farg);
564 1120
        free(fa->src);
565 1120
        FREE_OBJ(fa);
566 1080
        return (retval);
567
}
568
569
static const char *
570 80
create_bogo_n_arg(void)
571
{
572
        struct vsb *vsb;
573
        char *p;
574
575 80
        vsb = VSB_new_auto();
576 80
        AN(vsb);
577 80
        if (getenv("TMPDIR") != NULL)
578 80
                VSB_printf(vsb, "%s", getenv("TMPDIR"));
579
        else
580 0
                VSB_cat(vsb, "/tmp");
581 80
        VSB_cat(vsb, "/varnishd_C_XXXXXXX");
582 80
        AZ(VSB_finish(vsb));
583 80
        p = strdup(VSB_data(vsb));
584 80
        AN(p);
585 80
        VSB_destroy(&vsb);
586 80
        AN(mkdtemp(p));
587 80
        AZ(chmod(p, 0750));
588 80
        return (p);
589
}
590
591
static struct vpf_fh *
592 75000
create_pid_file(pid_t *ppid, const char *fmt, ...)
593
{
594
        struct vsb *vsb;
595
        va_list ap;
596
        struct vpf_fh *pfh;
597
598 75000
        va_start(ap, fmt);
599 75000
        vsb = VSB_new_auto();
600 75000
        AN(vsb);
601 75000
        VSB_vprintf(vsb, fmt, ap);
602 75000
        AZ(VSB_finish(vsb));
603 75000
        VJ_master(JAIL_MASTER_FILE);
604 75000
        pfh = VPF_Open(VSB_data(vsb), 0644, ppid);
605 75000
        if (pfh == NULL && errno == EEXIST)
606 120
                ARGV_ERR(
607
                    "Varnishd is already running (pid=%jd) (pidfile=%s)\n",
608
                    (intmax_t)*ppid, VSB_data(vsb));
609 40
        if (pfh == NULL)
610 40
                ARGV_ERR("Could not open pid-file (%s): %s\n",
611
                    VSB_data(vsb), VAS_errtxt(errno));
612 74840
        VJ_master(JAIL_MASTER_LOW);
613 74840
        VSB_destroy(&vsb);
614 74840
        va_end(ap);
615 74840
        return (pfh);
616
}
617
618
int
619 40800
main(int argc, char * const *argv)
620
{
621 40800
        int o, eric_fd = -1;
622 40800
        unsigned C_flag = 0;
623 40800
        unsigned F_flag = 0;
624 40800
        const char *b_arg = NULL;
625 40800
        const char *i_arg = NULL;
626 40800
        const char *j_arg = NULL;
627 40800
        const char *h_arg = "critbit";
628 40800
        const char *n_arg = getenv("VARNISH_DEFAULT_N");
629 40800
        const char *S_arg = NULL;
630 40800
        const char *s_arg = "default,100m";
631 40800
        const char *W_arg = NULL;
632
        const char *c;
633
        char *p;
634
        struct cli cli[1];
635
        const char *err;
636
        unsigned u;
637
        struct sigaction sac;
638
        struct vev *e;
639
        pid_t pid;
640
        struct arg_list *alp;
641 40800
        int first_arg = 1;
642
643 40800
        if (argc == 2 && !strcmp(argv[1], "--optstring")) {
644 40
                printf("%s\n", opt_spec);
645 40
                exit(0);
646
        }
647
648 40760
        heritage.argc = argc;
649 40760
        heritage.argv = argv;
650
651 40760
        setbuf(stdout, NULL);
652 40760
        setbuf(stderr, NULL);
653
654 40760
        mgt_tests();
655
656 40760
        mgt_initialize(cli);
657
658 619440
        for (; (o = getopt(argc, argv, opt_spec)) != -1; first_arg = 0) {
659 579320
                switch (o) {
660
                case 'V':
661 120
                        if (!first_arg)
662 40
                                ARGV_ERR("-V must be the first argument\n");
663 40
                        if (argc != 2)
664 40
                                ARGV_ERR("Too many arguments for -V\n");
665 40
                        VCS_Message("varnishd");
666 40
                        exit(0);
667
                case 'x':
668 440
                        if (!first_arg)
669 40
                                ARGV_ERR("-x must be the first argument\n");
670 40
                        if (argc != 3)
671 40
                                ARGV_ERR("Too many arguments for -x\n");
672 360
                        mgt_x_arg(optarg);
673 360
                        exit(0);
674
                case 'b':
675 1120
                        b_arg = optarg;
676 1120
                        break;
677
                case 'C':
678 280
                        C_flag = 1;
679 280
                        break;
680
                case 'd':
681 38520
                        d_flag++;
682 38520
                        break;
683
                case 'F':
684 560
                        F_flag = 1;
685 560
                        break;
686
                case 'j':
687 400
                        j_arg = optarg;
688 400
                        break;
689
                case 'h':
690 160
                        h_arg = optarg;
691 160
                        break;
692
                case 'i':
693 37280
                        i_arg = optarg;
694 37280
                        break;
695
                case 'l':
696 37360
                        arg_list_add('p', "vsl_space")->priv = optarg;
697 37360
                        break;
698
                case 'n':
699 38480
                        n_arg = optarg;
700 38480
                        break;
701
                case 'S':
702 40
                        S_arg = optarg;
703 40
                        break;
704
                case 't':
705 40
                        arg_list_add('p', "default_ttl")->priv = optarg;
706 40
                        break;
707
                case 'W':
708 240
                        W_arg = optarg;
709 240
                        break;
710
                case 'a':
711
                case 'E':
712
                case 'f':
713
                case 'I':
714
                case 'p':
715
                case 'P':
716
                case 'M':
717
                case 'r':
718
                case 's':
719
                case 'T':
720 424200
                        (void)arg_list_add(o, optarg);
721 424200
                        break;
722
                default:
723 80
                        usage();
724 80
                        exit(2);
725
                }
726 578680
        }
727
728 40120
        if (argc != optind)
729 40
                ARGV_ERR("Too many arguments (%s...)\n", argv[optind]);
730
731 1120
        if (b_arg != NULL && arg_list_count("f"))
732 40
                ARGV_ERR("Only one of -b or -f can be specified\n");
733
734 38440
        if (d_flag && F_flag)
735 40
                ARGV_ERR("Only one of -d or -F can be specified\n");
736
737 280
        if (C_flag && b_arg == NULL && !arg_list_count("f"))
738 40
                ARGV_ERR("-C needs either -b <backend> or -f <vcl_file>\n");
739
740 38400
        if (d_flag && C_flag)
741 40
                ARGV_ERR("-d makes no sense with -C\n");
742
743 520
        if (F_flag && C_flag)
744 40
                ARGV_ERR("-F makes no sense with -C\n");
745
746 1520
        if (!d_flag && b_arg == NULL && !arg_list_count("f"))
747 40
                ARGV_ERR("Neither -b nor -f given. (use -f '' to override)\n");
748
749 40
        if (arg_list_count("I") > 1)
750 40
                ARGV_ERR("\tOnly one -I allowed\n");
751
752 1440
        if (d_flag || F_flag)
753 38840
                complain_to_stderr = 1;
754
755 39800
        if (!arg_list_count("T"))
756 39800
                (void)arg_list_add('T', "localhost:0");
757
758
        /*
759
         * Start out by closing all unwanted file descriptors we might
760
         * have inherited from sloppy process control daemons.
761
         */
762 39960
        VSUB_closefrom(STDERR_FILENO + 1);
763 39960
        MCH_TrackHighFd(STDERR_FILENO);
764
765
        /*
766
         * Have Eric Daemonize us if need be
767
         */
768 39960
        if (!C_flag && !d_flag && !F_flag) {
769 800
                eric_fd = mgt_eric();
770 800
                MCH_TrackHighFd(eric_fd);
771 800
                heritage.mgt_pid = getpid();
772 800
        }
773
774 39800
        VRND_SeedAll();
775
776 39800
        vident = mgt_BuildVident();
777
778
        /* Various initializations */
779 39800
        VTAILQ_INIT(&heritage.socks);
780 39800
        VCA_Config();
781 39800
        mgt_evb = VEV_New();
782 39800
        AN(mgt_evb);
783
784
        /* Initialize transport protocols */
785 39800
        XPORT_Init();
786
787 39800
        VJ_Init(j_arg);
788
789
        /* Initialize the bogo-IP VSA */
790 39800
        VSA_Init();
791
792 39800
        if (b_arg != NULL)
793 1000
                mgt_b_conv(b_arg);
794
795
        /* Process delayed arguments */
796 538080
        VTAILQ_FOREACH(alp, &arglist, list) {
797 500000
                switch(alp->arg[0]) {
798
                case 'a':
799 39560
                        VCA_Arg(alp->val);
800 39560
                        break;
801
                case 'f':
802 1760
                        if (*alp->val != '\0')
803 520
                                alp->priv = mgt_f_read(alp->val);
804 1640
                        break;
805
                case 'E':
806 40
                        vext_argument(alp->val);
807 40
                        break;
808
                case 'I':
809 200
                        VJ_master(JAIL_MASTER_FILE);
810 200
                        I_fd = open(alp->val, O_RDONLY);
811 200
                        if (I_fd < 0)
812 40
                                ARGV_ERR("\tCan't open %s: %s\n",
813
                                    alp->val, VAS_errtxt(errno));
814 160
                        VJ_master(JAIL_MASTER_LOW);
815 160
                        break;
816
                case 'p':
817 342000
                        if (alp->priv) {
818 37400
                                MCF_ParamSet(cli, alp->val, alp->priv);
819 37400
                        } else {
820 304600
                                p = strchr(alp->val, '=');
821 304600
                                if (p == NULL)
822 0
                                        ARGV_ERR("\t-p lacks '='\n");
823 304600
                                AN(p);
824 304600
                                *p++ = '\0';
825 304600
                                MCF_ParamSet(cli, alp->val, p);
826
                        }
827 342000
                        break;
828
                case 'r':
829 40
                        MCF_ParamProtect(cli, alp->val);
830 40
                        break;
831
                case 's':
832 3920
                        STV_Config(alp->val);
833 3920
                        break;
834
                default:
835 112480
                        break;
836
                }
837 499840
                cli_check(cli);
838 499840
        }
839
840 38080
        VCLS_SetLimit(mgt_cls, &mgt_param.cli_limit);
841
842 38080
        assert(d_flag == 0 || F_flag == 0);
843
844 38080
        if (C_flag && n_arg == NULL)
845 80
                n_arg = create_bogo_n_arg();
846
847 120
        if (S_arg != NULL && !strcmp(S_arg, "none")) {
848 0
                fprintf(stderr,
849
                    "Warning: CLI authentication disabled.\n");
850 40
        } else if (S_arg != NULL) {
851 40
                VJ_master(JAIL_MASTER_FILE);
852 40
                o = open(S_arg, O_RDONLY, 0);
853 40
                if (o < 0)
854 40
                        ARGV_ERR("Cannot open -S file (%s): %s\n",
855
                            S_arg, VAS_errtxt(errno));
856 0
                closefd(&o);
857 0
                VJ_master(JAIL_MASTER_LOW);
858 0
        }
859
860 38040
        workdir = VIN_n_Arg(n_arg);
861 38040
        AN(workdir);
862
863 38040
        if (i_arg == NULL || *i_arg == '\0')
864 880
                i_arg = mgt_HostName();
865 112200
        else for (c = i_arg; *c != '\0'; c++) {
866 75040
                if (!vct_istchar(*c))
867 0
                        ARGV_ERR("Invalid character '%c' for -i\n", *c);
868 75040
        }
869 38040
        heritage.identity = i_arg;
870
871 38040
        mgt_ProcTitle("Mgt");
872
873 38040
        openlog("varnishd", LOG_PID, LOG_LOCAL0);
874
875 38040
        if (VJ_make_workdir(workdir))
876 0
                ARGV_ERR("Cannot create working directory (%s): %s\n",
877
                    workdir, VAS_errtxt(errno));
878
879 38040
        VJ_master(JAIL_MASTER_SYSTEM);
880
#ifdef RLIMIT_MEMLOCK
881
        /* try to raise to max (ignore error), then set _cur to whatever we got */
882
        struct rlimit rlim;
883 38040
        rlim.rlim_cur = 0;
884 38040
        rlim.rlim_max = RLIM_INFINITY;
885 38040
        (void)setrlimit(RLIMIT_MEMLOCK, &rlim);
886 38040
        AZ(getrlimit(RLIMIT_MEMLOCK, &rlim));
887 38040
        rlim.rlim_cur = rlim.rlim_max;
888 38040
        AZ(setrlimit(RLIMIT_MEMLOCK, &rlim));
889
#endif
890
891 38040
        AZ(system("rm -rf vmod_cache vext_cache worker_tmpdir"));
892 38040
        VJ_master(JAIL_MASTER_LOW);
893
894 38040
        if (VJ_make_subdir("vmod_cache", "VMOD cache", NULL)) {
895 0
                ARGV_ERR(
896
                    "Cannot create vmod directory (%s/vmod_cache): %s\n",
897
                    workdir, VAS_errtxt(errno));
898 0
        }
899
900 40
        if (arg_list_count("E") &&
901 40
            VJ_make_subdir("vext_cache", "VEXT cache", NULL)) {
902 0
                ARGV_ERR(
903
                    "Cannot create vmod directory (%s/vext_cache): %s\n",
904
                    workdir, VAS_errtxt(errno));
905 0
        }
906
907 0
        if (VJ_make_subdir("worker_tmpdir",
908
            "TMPDIR for the worker process", NULL)) {
909 0
                ARGV_ERR(
910
                    "Cannot create vmod directory (%s/worker_tmpdir): %s\n",
911
                    workdir, VAS_errtxt(errno));
912 0
        }
913
914 38040
        o = open("worker_tmpdir", O_RDONLY);
915 38040
        VJ_master(JAIL_MASTER_SYSTEM);
916 38040
        VJ_fix_fd(o, JAIL_FIXFD_WRKTMP);
917 38040
        VJ_master(JAIL_MASTER_LOW);
918 38040
        closefd(&o);
919
920 38040
        if (C_flag)
921 160
                AZ(atexit(mgt_Cflag_atexit));
922
923
        /* If no -s argument specified, process default -s argument */
924 35360
        if (!arg_list_count("s"))
925 35360
                STV_Config(s_arg);
926
927
        /* Configure CLI and Transient storage, if user did not */
928 38040
        STV_Config_Final();
929
930 38040
        mgt_vcl_init();
931
932 38040
        vext_copyin(vident);
933
934 38040
        u = 0;
935 535440
        VTAILQ_FOREACH(alp, &arglist, list) {
936 497440
                if (!strcmp(alp->arg, "f") && alp->priv != NULL)
937 1120
                        u |= mgt_process_f_arg(cli, C_flag, &alp->priv);
938 497400
        }
939 38000
        if (C_flag)
940 160
                exit(u);
941
942 534520
        VTAILQ_FOREACH(alp, &arglist, list) {
943 496760
                if (!strcmp(alp->arg, "P"))
944 37240
                        alp->priv = create_pid_file(&pid, "%s", alp->val);
945 496680
        }
946
947
        /* Implicit -P argument */
948 37760
        alp = arg_list_add('P', NULL);
949 37760
        alp->priv = create_pid_file(&pid, "%s/_.pid", workdir);
950
951 37760
        if (VTAILQ_EMPTY(&heritage.socks))
952 0
                VCA_Arg(":80\0");       // XXX: extra NUL for FlexeLint
953
954 37680
        assert(!VTAILQ_EMPTY(&heritage.socks));
955
956 37680
        HSH_config(h_arg);
957
958 37680
        Wait_config(W_arg);
959
960 37680
        mgt_SHM_Init();
961
962 37680
        mgt_SHM_static_alloc(i_arg, strlen(i_arg) + 1L, "Arg", "-i");
963 37680
        VSC_C_mgt = VSC_mgt_New(NULL, NULL, "");
964
965 571800
        VTAILQ_FOREACH(alp, &arglist, list) {
966 534120
                if (!strcmp(alp->arg, "M"))
967 37160
                        mgt_cli_master(alp->val);
968 496960
                else if (!strcmp(alp->arg, "T") && strcmp(alp->val, "none"))
969 37680
                        mgt_cli_telnet(alp->val);
970 74840
                else if (!strcmp(alp->arg, "P"))
971 74840
                        VPF_Write(alp->priv);
972 534120
        }
973
974 37680
        AZ(VSB_finish(vident));
975
976 37680
        if (S_arg == NULL)
977 37680
                S_arg = make_secret(workdir);
978 37720
        AN(S_arg);
979
980 37640
        MGT_Complain(C_DEBUG, "Version: %s", VCS_String("V"));
981 37640
        MGT_Complain(C_DEBUG, "Platform: %s", VSB_data(vident) + 1);
982
983 37640
        if (d_flag)
984 37280
                mgt_cli_setup(0, 1, 1, "debug", mgt_stdin_close, NULL);
985
986 37640
        if (strcmp(S_arg, "none"))
987 37640
                mgt_cli_secret(S_arg);
988
989 37640
        memset(&sac, 0, sizeof sac);
990 37640
        sac.sa_handler = SIG_IGN;
991 37640
        sac.sa_flags = SA_RESTART;
992
993 37640
        AZ(sigaction(SIGPIPE, &sac, NULL));
994 37640
        AZ(sigaction(SIGHUP, &sac, NULL));
995
996 37640
        MCH_Init();
997
998 37640
        if (I_fd >= 0) {
999 160
                fprintf(stderr, "BEGIN of -I file processing\n");
1000
                /* We must dup stderr, because VCLS closes the output fd */
1001 160
                mgt_cli_setup(I_fd, dup(2), 1, "-I file", mgt_I_close, stderr);
1002 320
                while (I_fd >= 0) {
1003 280
                        o = VEV_Once(mgt_evb);
1004 280
                        if (o != 1)
1005 0
                                MGT_Complain(C_ERR,
1006 0
                                    "VEV_Once() = %d", o);
1007
                }
1008 40
        }
1009 37520
        assert(I_fd == -1);
1010
1011 37520
        err = mgt_has_vcl();
1012 37520
        if (!d_flag && err != NULL && !arg_list_count("f"))
1013 0
                MGT_Complain(C_ERR, "%s", err);
1014
1015 720
        if (err == NULL && !d_flag)
1016 240
                u = MCH_Start_Child();
1017
        else
1018 37280
                u = 0;
1019
1020 37520
        if (eric_fd >= 0)
1021 200
                mgt_eric_im_done(eric_fd, u);
1022
1023 37520
        if (u)
1024 200
                exit(u);
1025
1026
        /* Failure is no longer an option */
1027
1028 37320
        if (F_flag)
1029 120
                VFIL_null_fd(STDIN_FILENO);
1030
1031 37320
        e = VEV_Alloc();
1032 37320
        AN(e);
1033 37320
        e->callback = mgt_uptime;
1034 37320
        e->timeout = 1.0;
1035 37320
        e->name = "mgt_uptime";
1036 37320
        AZ(VEV_Start(mgt_evb, e));
1037
1038 37320
        e = VEV_Alloc();
1039 37320
        AN(e);
1040 37320
        e->sig = SIGTERM;
1041 37320
        e->callback = mgt_sigint;
1042 37320
        e->name = "SIGTERM";
1043 37320
        AZ(VEV_Start(mgt_evb, e));
1044
1045 37320
        e = VEV_Alloc();
1046 37320
        AN(e);
1047 37320
        e->sig = SIGINT;
1048 37320
        e->callback = mgt_sigint;
1049 37320
        e->name = "SIGINT";
1050 37320
        AZ(VEV_Start(mgt_evb, e));
1051
1052 37320
        o = VEV_Loop(mgt_evb);
1053 37320
        if (o != 0 && o != -42)
1054 0
                MGT_Complain(C_ERR, "VEV_Loop() = %d", o);
1055
1056 37320
        MGT_Complain(C_INFO, "manager stopping child");
1057 37320
        MCH_Stop_Child();
1058 37320
        MGT_Complain(C_INFO, "manager dies");
1059 37320
        mgt_cli_close_all();
1060 37320
        VEV_Destroy(&mgt_evb);
1061 37320
        VJ_master(JAIL_MASTER_SYSTEM);
1062
        /*lint -e(730)*/
1063 37320
        vext_cleanup(! MGT_DO_DEBUG(DBG_VMOD_SO_KEEP));
1064 37320
        (void)rmdir("vext_cache");
1065 37320
        VJ_master(JAIL_MASTER_LOW);
1066 569600
        VTAILQ_FOREACH(alp, &arglist, list) {
1067 532280
                if (!strcmp(alp->arg, "P"))
1068 74480
                        VPF_Remove(alp->priv);
1069 532280
        }
1070 37320
        exit(exit_status);
1071
}