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 1
mgt_DumpOptions(void)
87
{
88 1
        printf(".. _opt_n:\n\n");
89 1
        printf("-n workdir\n\n");
90 1
        printf("  Runtime directory for the shared memory, "
91
               "compiled VCLs etc.\n\n");
92 1
        printf("  In performance critical applications, this directory "
93
               "should be on a RAM backed filesystem.\n\n");
94 1
        printf("  When running multiple varnishd instances, separate "
95
               "directories need to be used.\n\n");
96 1
        VIN_DumpDefaults();
97 1
}
98
99
static void
100 2
usage(void)
101
{
102
        char *p;
103
104
#define FMT_NONL "  %-35s # %s"
105
#define FMT FMT_NONL "\n"
106
107 2
        printf( "Usage: varnishd [options]\n");
108
109 2
        printf("\nBasic options:\n");
110
111 2
        printf(FMT, "[-a [name=][listen_address",
112
            "HTTP listen address, protocol, options.");
113 2
        printf(FMT, "     [,PROTO|,option=value,...]]",
114
            "Can be specified multiple times.");
115 2
        printf(FMT, "",
116
            "  default: \":80,HTTP\"");
117 2
        printf(FMT, "  options:",
118
            "Proto can be \"PROXY\" or \"HTTP\" (default)");
119 2
        printf(FMT, "    [,user=<u>][,group=<g>]",
120
            "user, group and mode set permissions for");
121 2
        printf(FMT, "    [,mode=<m>]",
122
            "  a Unix domain socket.");
123 2
        printf(FMT, "-b none", "No backend");
124 2
        printf(FMT, "-b [addr[:port]|path]", "Backend address and port");
125 2
        printf(FMT, "", "  or socket file path");
126 2
        printf(FMT, "", "  default: \":80\"");
127 2
        printf(FMT, "-f vclfile", "VCL program");
128 2
        printf(FMT, "", "Can be specified multiple times.");
129 2
        printf(FMT, "-n dir", "Working directory");
130
131 2
        p = VIN_n_Arg(NULL);
132 2
        AN(p);
133 2
        printf(FMT_NONL "  default: %s\n", "", "", p);
134 2
        free(p);
135
136 2
        printf("\n-b can be used only once, and not together with -f\n");
137
138 2
        printf("\nDocumentation options:\n");
139 2
        printf(FMT, "-?", "Prints this usage message");
140 2
        printf(FMT, "-x parameter", "Parameter documentation");
141 2
        printf(FMT, "-x vsl", "VSL record documentation");
142 2
        printf(FMT, "-x cli", "CLI command documentation");
143 2
        printf(FMT, "-x builtin", "Builtin VCL program");
144 2
        printf(FMT, "-x optstring", "List of getopt options");
145 2
        printf(FMT, "-x options", "Dynamic options documentation");
146
147 2
        printf("\nOperations options:\n");
148
149 2
        printf(FMT, "-F", "Run in foreground");
150 2
        printf(FMT, "-T address[:port]", "CLI address");
151 2
        printf(FMT, "", "Can be specified multiple times.");
152 2
        printf(FMT, "-M address:port", "Reverse CLI destination");
153 2
        printf(FMT, "", "Can be specified multiple times.");
154 2
        printf(FMT, "-P file", "PID file");
155 2
        printf(FMT, "-i identity", "Identity of varnish instance");
156 2
        printf(FMT, "-I clifile", "Initialization CLI commands");
157 2
        printf(FMT, "-E extension", "Load extension");
158
159 2
        printf("\nTuning options:\n");
160
161 2
        printf(FMT, "-t TTL", "Default TTL");
162 2
        printf(FMT, "-p param=value", "set parameter");
163 2
        printf(FMT, "", "Can be specified multiple times.");
164
165 2
        printf(FMT, "-s [name=]kind[,options]", "Storage specification");
166 2
        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 2
        printf(FMT, "", "  -s default (=malloc)");
172
#endif
173 2
        printf(FMT, "", "  -s malloc");
174 2
        printf(FMT, "", "  -s file");
175
176 2
        printf(FMT, "-l vsl", "Size of shared memory log");
177 2
        printf(FMT, "", "  vsl: space for VSL records [80m]");
178
179 2
        printf("\nSecurity options:\n");
180
181 2
        printf(FMT, "-r param[,param...]", "Set parameters read-only from CLI");
182 2
        printf(FMT, "", "Can be specified multiple times.");
183 2
        printf(FMT, "-S secret-file", "Secret file for CLI authentication");
184 2
        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 2
        printf(FMT, "", "  -j unix");
192 2
        printf(FMT, "", "  -j none");
193
194 2
        printf("\nAdvanced/Dev/Debug options:\n");
195
196 2
        printf(FMT, "-d", "debug mode");
197 2
        printf(FMT, "", "Stay in foreground, CLI on stdin.");
198 2
        printf(FMT, "-C", "Output VCL code compiled to C language");
199 2
        printf(FMT, "-V", "version");
200 2
        printf(FMT, "-h kind[,options]", "Hash specification");
201 2
        printf(FMT, "-W waiter", "Waiter implementation");
202 2
}
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 13782
arg_list_add(const char arg, const char *val)
219
{
220
        struct arg_list *alp;
221
222 13782
        ALLOC_OBJ(alp, ARG_LIST_MAGIC);
223 13782
        AN(alp);
224 13782
        alp->arg[0] = arg;
225 13782
        alp->arg[1] = '\0';
226 13782
        REPLACE(alp->val, val);
227 13782
        VTAILQ_INSERT_TAIL(&arglist, alp, list);
228 13782
        return (alp);
229
}
230
231
static unsigned
232 4101
arg_list_count(const char *arg)
233
{
234 4101
        unsigned retval = 0;
235
        struct arg_list *alp;
236
237 53642
        VTAILQ_FOREACH(alp, &arglist, list) {
238 49541
                if (!strcmp(alp->arg, arg))
239 168
                        retval++;
240 49541
        }
241 4101
        return (retval);
242
}
243
244
/*--------------------------------------------------------------------*/
245
246
static void
247 13787
cli_check(const struct cli *cli)
248
{
249 13787
        if (cli->result == CLIS_OK || cli->result == CLIS_TRUNCATED) {
250 13785
                AZ(VSB_finish(cli->sb));
251 13785
                if (VSB_len(cli->sb) > 0)
252 2
                        fprintf(stderr, "Warnings:\n%s\n", VSB_data(cli->sb));
253 13785
                VSB_clear(cli->sb);
254 13785
                return;
255
        }
256 2
        AZ(VSB_finish(cli->sb));
257 2
        fprintf(stderr, "Error:\n%s\n", VSB_data(cli->sb));
258 2
        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 948
mgt_stdin_close(void *priv)
267
{
268
269 948
        (void)priv;
270 948
        return (-42);
271
}
272
273
/*--------------------------------------------------------------------
274
 * Autogenerate a -S file using strong random bits from the kernel.
275
 */
276
277
static void
278 4577
mgt_secret_atexit(void)
279
{
280
281
        /* Only master process */
282 4577
        if (getpid() != heritage.mgt_pid)
283 3615
                return;
284 962
        VJ_master(JAIL_MASTER_FILE);
285 962
        (void)unlink("_.secret");
286 962
        VJ_master(JAIL_MASTER_LOW);
287 4577
}
288
289
static const char *
290 963
make_secret(const char *dirname)
291
{
292
        char *fn;
293
        int fdo;
294
        int i;
295
        unsigned char b;
296
297 963
        assert(asprintf(&fn, "%s/_.secret", dirname) > 0);
298
299 963
        VJ_master(JAIL_MASTER_FILE);
300 963
        if (unlink(fn) < 0 && errno != ENOENT) {
301 1
                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 247234
        for (i = 0; i < 256; i++) {
312 246272
                AZ(VRND_RandomCrypto(&b, 1));
313 246272
                assert(1 == write(fdo, &b, 1));
314 246272
        }
315 962
        closefd(&fdo);
316 962
        VJ_master(JAIL_MASTER_LOW);
317 962
        AZ(atexit(mgt_secret_atexit));
318 962
        return (fn);
319
}
320
321
static void
322 12
mgt_Cflag_atexit(void)
323
{
324
325
        /* Only master process */
326 12
        if (getpid() != heritage.mgt_pid)
327 8
                return;
328 4
        if (arg_list_count("E")) {
329 0
                vext_cleanup(1);
330 0
                VJ_rmdir("vext_cache");
331 0
        }
332 4
        VJ_rmdir("vmod_cache");
333 4
        VJ_rmdir("worker_tmpdir");
334 4
        (void)chdir("/");
335 4
        VJ_rmdir(workdir);
336 12
}
337
338
/*--------------------------------------------------------------------*/
339
340
static void
341 1041
mgt_tests(void)
342
{
343 1041
        assert(VTIM_parse("Sun, 06 Nov 1994 08:49:37 GMT") == 784111777);
344 1041
        assert(VTIM_parse("Sunday, 06-Nov-94 08:49:37 GMT") == 784111777);
345 1041
        assert(VTIM_parse("Sun Nov  6 08:49:37 1994") == 784111777);
346
347
        /* Check that our VSHA256 works */
348 1041
        VSHA256_Test();
349 1041
}
350
351
static void
352 1041
mgt_initialize(struct cli *cli)
353
{
354
        static unsigned clilim = 32768;
355
356
        /* for ASSERT_MGT() */
357 1041
        heritage.mgt_pid = getpid();
358
359
        /* Create a cli for convenience in otherwise CLI functions */
360 1041
        INIT_OBJ(cli, CLI_MAGIC);
361 1041
        cli[0].sb = VSB_new_auto();
362 1041
        AN(cli[0].sb);
363 1041
        cli[0].result = CLIS_OK;
364 1041
        cli[0].limit = &clilim;
365
366 1041
        mgt_cli_init_cls();             // CLI commands can be registered
367
368 1041
        MCF_InitParams(cli);
369
370 1041
        VCC_VCL_Range(&heritage.min_vcl_version, &heritage.max_vcl_version);
371
372 1041
        cli_check(cli);
373 1041
}
374
375
static void
376 9
mgt_x_arg(const char *x_arg)
377
{
378 9
        if (!strcmp(x_arg, "parameter"))
379 2
                MCF_DumpRstParam();
380 7
        else if (!strcmp(x_arg, "vsl"))
381 1
                mgt_DumpRstVsl();
382 6
        else if (!strcmp(x_arg, "cli"))
383 2
                mgt_DumpRstCli();
384 4
        else if (!strcmp(x_arg, "builtin"))
385 1
                mgt_DumpBuiltin();
386 3
        else if (!strcmp(x_arg, "optstring"))
387 1
                (void)printf("%s\n", opt_spec);
388 2
        else if (!strcmp(x_arg, "options"))
389 1
                mgt_DumpOptions();
390
        else
391 1
                ARGV_ERR("Invalid -x argument\n");
392 8
}
393
394
/*--------------------------------------------------------------------*/
395
396
#define ERIC_MAGIC 0x2246988a           /* Eric is not random */
397
398
static int
399 23
mgt_eric(void)
400
{
401
        int eric_pipes[2];
402
        unsigned u;
403
        ssize_t sz;
404
405 23
        AZ(pipe(eric_pipes));
406
407 23
        switch (fork()) {
408
        case -1:
409 0
                fprintf(stderr, "Fork() failed: %s\n", VAS_errtxt(errno));
410 0
                exit(-1);
411
        case 0:
412 23
                closefd(&eric_pipes[0]);
413 23
                assert(setsid() > 1);
414
415 23
                VFIL_null_fd(STDIN_FILENO);
416 23
                return (eric_pipes[1]);
417
        default:
418 23
                break;
419
        }
420 23
        closefd(&eric_pipes[1]);
421 23
        sz = read(eric_pipes[0], &u, sizeof u);
422 23
        if (sz == sizeof u && u == ERIC_MAGIC)
423 0
                exit(0);
424 8
        else if (sz == sizeof u && u != 0)
425 8
                exit(u);
426
        else
427 15
                exit(-1);
428
}
429
430
static void
431 8
mgt_eric_im_done(int eric_fd, unsigned u)
432
{
433
434 8
        if (u == 0)
435 0
                u = ERIC_MAGIC;
436
437 8
        VFIL_null_fd(STDIN_FILENO);
438 8
        VFIL_null_fd(STDOUT_FILENO);
439 8
        VFIL_null_fd(STDERR_FILENO);
440
441 8
        assert(write(eric_fd, &u, sizeof u) == sizeof u);
442 8
        closefd(&eric_fd);
443 8
}
444
445
/*--------------------------------------------------------------------*/
446
447
static int v_matchproto_(vev_cb_f)
448 4
mgt_sigint(const struct vev *e, int what)
449
{
450
451 4
        (void)what;
452 4
        MGT_Complain(C_ERR, "Manager got %s from PID %jd", e->name, (intmax_t)e->siginfo->si_pid);
453 4
        (void)fflush(stdout);
454 4
        if (MCH_Running())
455 3
                MCH_Stop_Child();
456 4
        return (-42);
457
}
458
459
/*--------------------------------------------------------------------*/
460
461
static int v_matchproto_(vev_cb_f)
462 1794
mgt_uptime(const struct vev *e, int what)
463
{
464
        static double mgt_uptime_t0 = 0;
465
466 1794
        (void)e;
467 1794
        (void)what;
468 1794
        AN(VSC_C_mgt);
469 1794
        if (mgt_uptime_t0 == 0)
470 914
                mgt_uptime_t0 = VTIM_real();
471 1794
        VSC_C_mgt->uptime = (uint64_t)(VTIM_real() - mgt_uptime_t0);
472 1794
        return (0);
473
}
474
475
/*--------------------------------------------------------------------*/
476
477
static int v_matchproto_(mgt_cli_close_f)
478 1
mgt_I_close(void *priv)
479
{
480 1
        (void)priv;
481 1
        fprintf(stderr, "END of -I file processing\n");
482 1
        I_fd = -1;
483 1
        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 13
mgt_f_read(const char *fn)
497
{
498
        struct f_arg *fa;
499
        char *f, *fnp;
500
501 13
        ALLOC_OBJ(fa, F_ARG_MAGIC);
502 13
        AN(fa);
503 13
        REPLACE(fa->farg, fn);
504 13
        VFIL_setpath(&vcl_path, mgt_vcl_path);
505 13
        if (VFIL_searchpath(vcl_path, NULL, &f, fn, &fnp) || f == NULL) {
506 3
                ARGV_ERR("Cannot read -f file '%s' (%s)\n",
507
                    fnp != NULL ? fnp : fn, VAS_errtxt(errno));
508 0
        }
509 10
        free(fa->farg);
510 10
        fa->farg = fnp;
511 10
        fa->src = f;
512 10
        return (fa);
513
}
514
515
static void
516 28
mgt_b_conv(const char *b_arg)
517
{
518
        struct f_arg *fa;
519
        struct vsb *vsb;
520
521 28
        ALLOC_OBJ(fa, F_ARG_MAGIC);
522 28
        AN(fa);
523 28
        REPLACE(fa->farg, "<-b argument>");
524 28
        vsb = VSB_new_auto();
525 28
        AN(vsb);
526 28
        VSB_cat(vsb, "vcl 4.1;\n");
527 28
        VSB_cat(vsb, "backend default ");
528 28
        if (!strcasecmp(b_arg, "none"))
529 16
                VSB_cat(vsb, "none;\n");
530 12
        else if (VUS_is(b_arg))
531 1
                VSB_printf(vsb, "{\n    .path = \"%s\";\n}\n", b_arg);
532
        else
533 11
                VSB_printf(vsb, "{\n    .host = \"%s\";\n}\n", b_arg);
534 28
        AZ(VSB_finish(vsb));
535 28
        fa->src = strdup(VSB_data(vsb));
536 28
        AN(fa->src);
537 28
        VSB_destroy(&vsb);
538 28
        AZ(arg_list_count("f"));
539 28
        arg_list_add('f', "")->priv = fa;
540 28
}
541
542
static int
543 31
mgt_process_f_arg(struct cli *cli, unsigned C_flag, void **fap)
544
{
545 31
        int retval = 0;
546
        struct f_arg *fa;
547 31
        const char *name = NULL;
548
549 31
        TAKE_OBJ_NOTNULL(fa, fap, F_ARG_MAGIC);
550 31
        if (arg_list_count("f") == 1)
551 29
                name = "boot";
552 31
        mgt_vcl_startup(cli, fa->src, name, fa->farg, C_flag);
553 31
        if (C_flag) {
554 4
                if (cli->result != CLIS_OK &&
555 0
                    cli->result != CLIS_TRUNCATED)
556 0
                        retval = 2;
557 4
                AZ(VSB_finish(cli->sb));
558 4
                fprintf(stderr, "%s\n", VSB_data(cli->sb));
559 4
                VSB_clear(cli->sb);
560 4
        } else {
561 27
                cli_check(cli);
562
        }
563 31
        free(fa->farg);
564 31
        free(fa->src);
565 31
        FREE_OBJ(fa);
566 30
        return (retval);
567
}
568
569
static char *
570 0
create_bogo_n_arg(void)
571
{
572
        struct vsb *vsb;
573
        char *p;
574
575 0
        vsb = VSB_new_auto();
576 0
        AN(vsb);
577 0
        if (getenv("TMPDIR") != NULL)
578 0
                VSB_printf(vsb, "%s", getenv("TMPDIR"));
579
        else
580 0
                VSB_cat(vsb, "/tmp");
581 0
        VSB_cat(vsb, "/varnishd_C_XXXXXXX");
582 0
        AZ(VSB_finish(vsb));
583 0
        p = strdup(VSB_data(vsb));
584 0
        AN(p);
585 0
        VSB_destroy(&vsb);
586 0
        AN(mkdtemp(p));
587 0
        AZ(chmod(p, 0750));
588 0
        return (p);
589
}
590
591
static struct vpf_fh *
592 1914
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 1914
        va_start(ap, fmt);
599 1914
        vsb = VSB_new_auto();
600 1914
        AN(vsb);
601 1914
        VSB_vprintf(vsb, fmt, ap);
602 1914
        AZ(VSB_finish(vsb));
603 1914
        VJ_master(JAIL_MASTER_FILE);
604 1914
        pfh = VPF_Open(VSB_data(vsb), 0644, ppid);
605 1914
        if (pfh == NULL && errno == EEXIST)
606 3
                ARGV_ERR(
607
                    "Varnishd is already running (pid=%jd) (pidfile=%s)\n",
608
                    (intmax_t)*ppid, VSB_data(vsb));
609 1
        if (pfh == NULL)
610 1
                ARGV_ERR("Could not open pid-file (%s): %s\n",
611
                    VSB_data(vsb), VAS_errtxt(errno));
612 1910
        VJ_master(JAIL_MASTER_LOW);
613 1910
        VSB_destroy(&vsb);
614 1910
        va_end(ap);
615 1910
        return (pfh);
616
}
617
618
int
619 1042
main(int argc, char * const *argv)
620
{
621 1042
        int o, eric_fd = -1;
622 1042
        unsigned C_flag = 0;
623 1042
        unsigned F_flag = 0;
624 1042
        const char *b_arg = NULL;
625 1042
        const char *i_arg = NULL;
626 1042
        const char *j_arg = NULL;
627 1042
        const char *h_arg = "critbit";
628 1042
        const char *n_arg = getenv("VARNISH_DEFAULT_N");
629 1042
        const char *S_arg = NULL;
630 1042
        const char *s_arg = "default,100m";
631 1042
        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 1042
        int first_arg = 1;
642
        struct vsb *vsb;
643
644 1042
        if (argc == 2 && !strcmp(argv[1], "--optstring")) {
645 1
                printf("%s\n", opt_spec);
646 1
                exit(0);
647
        }
648
649 1041
        heritage.argc = argc;
650 1041
        heritage.argv = argv;
651
652 1041
        setbuf(stdout, NULL);
653 1041
        setbuf(stderr, NULL);
654
655 1041
        mgt_tests();
656
657 1041
        mgt_initialize(cli);
658
659 15786
        for (; (o = getopt(argc, argv, opt_spec)) != -1; first_arg = 0) {
660 14761
                switch (o) {
661
                case 'V':
662 3
                        if (!first_arg)
663 1
                                ARGV_ERR("-V must be the first argument\n");
664 1
                        if (argc != 2)
665 1
                                ARGV_ERR("Too many arguments for -V\n");
666 1
                        VCS_Message("varnishd");
667 1
                        exit(0);
668
                case 'x':
669 11
                        if (!first_arg)
670 1
                                ARGV_ERR("-x must be the first argument\n");
671 1
                        if (argc != 3)
672 1
                                ARGV_ERR("Too many arguments for -x\n");
673 9
                        mgt_x_arg(optarg);
674 9
                        exit(0);
675
                case 'b':
676 31
                        b_arg = optarg;
677 31
                        break;
678
                case 'C':
679 7
                        C_flag = 1;
680 7
                        break;
681
                case 'd':
682 982
                        d_flag++;
683 982
                        break;
684
                case 'F':
685 14
                        F_flag = 1;
686 14
                        break;
687
                case 'j':
688 10
                        j_arg = optarg;
689 10
                        break;
690
                case 'h':
691 4
                        h_arg = optarg;
692 4
                        break;
693
                case 'i':
694 950
                        i_arg = optarg;
695 950
                        break;
696
                case 'l':
697 952
                        arg_list_add('p', "vsl_space")->priv = optarg;
698 952
                        break;
699
                case 'n':
700 968
                        n_arg = optarg;
701 968
                        break;
702
                case 'S':
703 1
                        S_arg = optarg;
704 1
                        break;
705
                case 't':
706 1
                        arg_list_add('p', "default_ttl")->priv = optarg;
707 1
                        break;
708
                case 'W':
709 6
                        W_arg = optarg;
710 6
                        break;
711
                case 'a':
712
                case 'E':
713
                case 'f':
714
                case 'I':
715
                case 'p':
716
                case 'P':
717
                case 'M':
718
                case 'r':
719
                case 's':
720
                case 'T':
721 10819
                        (void)arg_list_add(o, optarg);
722 10819
                        break;
723
                default:
724 2
                        usage();
725 2
                        exit(2);
726
                }
727 14745
        }
728
729 1025
        if (argc != optind)
730 1
                ARGV_ERR("Too many arguments (%s...)\n", argv[optind]);
731
732 31
        if (b_arg != NULL && arg_list_count("f"))
733 1
                ARGV_ERR("Only one of -b or -f can be specified\n");
734
735 980
        if (d_flag && F_flag)
736 1
                ARGV_ERR("Only one of -d or -F can be specified\n");
737
738 7
        if (C_flag && b_arg == NULL && !arg_list_count("f"))
739 1
                ARGV_ERR("-C needs either -b <backend> or -f <vcl_file>\n");
740
741 979
        if (d_flag && C_flag)
742 1
                ARGV_ERR("-d makes no sense with -C\n");
743
744 13
        if (F_flag && C_flag)
745 1
                ARGV_ERR("-F makes no sense with -C\n");
746
747 41
        if (!d_flag && b_arg == NULL && !arg_list_count("f"))
748 1
                ARGV_ERR("Neither -b nor -f given. (use -f '' to override)\n");
749
750 1
        if (arg_list_count("I") > 1)
751 1
                ARGV_ERR("\tOnly one -I allowed\n");
752
753 39
        if (d_flag || F_flag)
754 990
                complain_to_stderr = 1;
755
756 1017
        if (!arg_list_count("T"))
757 1017
                (void)arg_list_add('T', "localhost:0");
758
759
        /*
760
         * Start out by closing all unwanted file descriptors we might
761
         * have inherited from sloppy process control daemons.
762
         */
763 1021
        VSUB_closefrom(STDERR_FILENO + 1);
764 1021
        MCH_TrackHighFd(STDERR_FILENO);
765
766
        /*
767
         * Have Eric Daemonize us if need be
768
         */
769 1021
        if (!C_flag && !d_flag && !F_flag) {
770 23
                eric_fd = mgt_eric();
771 23
                MCH_TrackHighFd(eric_fd);
772 23
                heritage.mgt_pid = getpid();
773 23
        }
774
775 1017
        VRND_SeedAll();
776
777 1017
        vident = mgt_BuildVident();
778
779
        /* Various initializations */
780 1017
        VTAILQ_INIT(&heritage.socks);
781 1017
        VCA_Config();
782 1017
        mgt_evb = VEV_New();
783 1017
        AN(mgt_evb);
784
785
        /* Initialize transport protocols */
786 1017
        XPORT_Init();
787
788 1017
        VJ_Init(j_arg);
789
790
        /* Initialize the bogo-IP VSA */
791 1017
        VSA_Init();
792
793 1017
        if (b_arg != NULL)
794 28
                mgt_b_conv(b_arg);
795
796
        /* Process delayed arguments */
797 13730
        VTAILQ_FOREACH(alp, &arglist, list) {
798 12756
                switch(alp->arg[0]) {
799
                case 'a':
800 1010
                        VCA_Arg(alp->val);
801 1010
                        break;
802
                case 'f':
803 47
                        if (*alp->val != '\0')
804 13
                                alp->priv = mgt_f_read(alp->val);
805 44
                        break;
806
                case 'E':
807 1
                        vext_argument(alp->val);
808 1
                        break;
809
                case 'I':
810 5
                        VJ_master(JAIL_MASTER_FILE);
811 5
                        I_fd = open(alp->val, O_RDONLY);
812 5
                        if (I_fd < 0)
813 1
                                ARGV_ERR("\tCan't open %s: %s\n",
814
                                    alp->val, VAS_errtxt(errno));
815 4
                        VJ_master(JAIL_MASTER_LOW);
816 4
                        break;
817
                case 'p':
818 8717
                        if (alp->priv) {
819 953
                                MCF_ParamSet(cli, alp->val, alp->priv);
820 953
                        } else {
821 7764
                                p = strchr(alp->val, '=');
822 7764
                                if (p == NULL)
823 0
                                        ARGV_ERR("\t-p lacks '='\n");
824 7764
                                AN(p);
825 7764
                                *p++ = '\0';
826 7764
                                MCF_ParamSet(cli, alp->val, p);
827
                        }
828 8717
                        break;
829
                case 'r':
830 3
                        MCF_ParamProtect(cli, alp->val);
831 3
                        break;
832
                case 's':
833 104
                        STV_Config(alp->val);
834 104
                        break;
835
                default:
836 2869
                        break;
837
                }
838 12752
                cli_check(cli);
839 12752
        }
840
841 973
        VCLS_SetLimit(mgt_cls, &mgt_param.cli_limit);
842
843 973
        assert(d_flag == 0 || F_flag == 0);
844
845 973
        p = NULL;
846 973
        if (C_flag && n_arg == NULL) {
847 0
                p = create_bogo_n_arg();
848 0
                n_arg = p;
849 0
        }
850
851 1
        if (S_arg != NULL && !strcmp(S_arg, "none")) {
852 0
                fprintf(stderr,
853
                    "Warning: CLI authentication disabled.\n");
854 1
        } else if (S_arg != NULL) {
855 1
                VJ_master(JAIL_MASTER_FILE);
856 1
                o = open(S_arg, O_RDONLY, 0);
857 1
                if (o < 0)
858 1
                        ARGV_ERR("Cannot open -S file (%s): %s\n",
859
                            S_arg, VAS_errtxt(errno));
860 0
                closefd(&o);
861 0
                VJ_master(JAIL_MASTER_LOW);
862 0
        }
863
864 972
        workdir = VIN_n_Arg(n_arg);
865 972
        AN(workdir);
866 972
        if (p != NULL)
867 0
                free(p);
868
869 947
        if (i_arg == NULL || *i_arg == '\0')
870 25
                i_arg = mgt_HostName();
871 2859
        else for (c = i_arg; *c != '\0'; c++) {
872 1912
                if (!vct_istchar(*c))
873 0
                        ARGV_ERR("Invalid character '%c' for -i\n", *c);
874 1912
        }
875 972
        heritage.identity = i_arg;
876
877 972
        mgt_ProcTitle("Mgt");
878
879 972
        openlog("varnishd", LOG_PID, LOG_LOCAL0);
880
881 972
        vsb = VSB_new_auto();
882 972
        AN(vsb);
883 972
        o = VJ_make_workdir(workdir, vsb);
884 972
        MGT_ComplainVSB(o ? C_ERR : C_INFO, vsb);
885 972
        if (o)
886 0
                ARGV_EXIT;
887
888 972
        VJ_master(JAIL_MASTER_SYSTEM);
889
#ifdef RLIMIT_MEMLOCK
890
        /* try to raise to max (ignore error), then set _cur to whatever we got */
891
        struct rlimit rlim;
892 972
        rlim.rlim_cur = 0;
893 972
        rlim.rlim_max = RLIM_INFINITY;
894 972
        (void)setrlimit(RLIMIT_MEMLOCK, &rlim);
895 972
        AZ(getrlimit(RLIMIT_MEMLOCK, &rlim));
896 972
        rlim.rlim_cur = rlim.rlim_max;
897 972
        AZ(setrlimit(RLIMIT_MEMLOCK, &rlim));
898
#endif
899
900 972
        AZ(system("rm -rf vmod_cache vext_cache worker_tmpdir"));
901 972
        VJ_master(JAIL_MASTER_LOW);
902
903 972
        VSB_clear(vsb);
904 1944
        o = VJ_make_subdir("vmod_cache", "VMOD cache", vsb) ||
905 972
            VJ_make_subdir("worker_tmpdir",
906 3888
                "TMPDIR for the worker process", vsb) ||
907 972
            (arg_list_count("E") &&
908 1
                VJ_make_subdir("vext_cache", "VEXT cache", vsb));
909 1944
        MGT_ComplainVSB(o ? C_ERR : C_INFO, vsb);
910 1944
        VSB_destroy(&vsb);
911 1944
        if (o)
912 0
                ARGV_EXIT;
913
914 972
        o = open("worker_tmpdir", O_RDONLY);
915 972
        VJ_master(JAIL_MASTER_SYSTEM);
916 972
        VJ_fix_fd(o, JAIL_FIXFD_WRKTMP);
917 972
        VJ_master(JAIL_MASTER_LOW);
918 972
        closefd(&o);
919
920 972
        if (C_flag)
921 4
                AZ(atexit(mgt_Cflag_atexit));
922
923
        /* If no -s argument specified, process default -s argument */
924 900
        if (!arg_list_count("s"))
925 900
                STV_Config(s_arg);
926
927
        /* Configure CLI and Transient storage, if user did not */
928 972
        STV_Config_Final();
929
930 972
        mgt_vcl_init();
931
932 972
        vext_copyin(vident);
933
934 972
        u = 0;
935 13662
        VTAILQ_FOREACH(alp, &arglist, list) {
936 12691
                if (!strcmp(alp->arg, "f") && alp->priv != NULL)
937 31
                        u |= mgt_process_f_arg(cli, C_flag, &alp->priv);
938 12690
        }
939 971
        if (C_flag)
940 4
                exit(u);
941
942 13639
        VTAILQ_FOREACH(alp, &arglist, list) {
943 12674
                if (!strcmp(alp->arg, "P"))
944 949
                        alp->priv = create_pid_file(&pid, "%s", alp->val);
945 12672
        }
946
947
        /* Implicit -P argument */
948 965
        alp = arg_list_add('P', NULL);
949 965
        alp->priv = create_pid_file(&pid, "%s/_.pid", workdir);
950
951 965
        if (VTAILQ_EMPTY(&heritage.socks))
952 0
                VCA_Arg(":80\0");       // XXX: extra NUL for FlexeLint
953
954 963
        assert(!VTAILQ_EMPTY(&heritage.socks));
955
956 963
        HSH_config(h_arg);
957
958 963
        Wait_config(W_arg);
959
960 963
        mgt_SHM_Init();
961
962 963
        mgt_SHM_static_alloc(i_arg, strlen(i_arg) + 1L, "Arg", "-i");
963 963
        VSC_C_mgt = VSC_mgt_New(NULL, NULL, "");
964
965 14592
        VTAILQ_FOREACH(alp, &arglist, list) {
966 13629
                if (!strcmp(alp->arg, "M"))
967 947
                        mgt_cli_master(alp->val);
968 12682
                else if (!strcmp(alp->arg, "T") && strcmp(alp->val, "none"))
969 963
                        mgt_cli_telnet(alp->val);
970 1910
                else if (!strcmp(alp->arg, "P"))
971 1910
                        VPF_Write(alp->priv);
972 13629
        }
973
974 963
        AZ(VSB_finish(vident));
975
976 963
        if (S_arg == NULL)
977 963
                S_arg = make_secret(workdir);
978 964
        AN(S_arg);
979
980 962
        MGT_Complain(C_DEBUG, "Version: %s", VCS_String("V"));
981 962
        MGT_Complain(C_DEBUG, "Platform: %s", VSB_data(vident) + 1);
982
983 962
        if (d_flag)
984 950
                mgt_cli_setup(0, 1, 1, "debug", mgt_stdin_close, NULL);
985
986 962
        if (strcmp(S_arg, "none"))
987 962
                mgt_cli_secret(S_arg);
988
989 962
        memset(&sac, 0, sizeof sac);
990 962
        sac.sa_handler = SIG_IGN;
991 962
        sac.sa_flags = SA_RESTART;
992
993 962
        AZ(sigaction(SIGPIPE, &sac, NULL));
994 962
        AZ(sigaction(SIGHUP, &sac, NULL));
995
996 962
        MCH_Init();
997
998 962
        if (I_fd >= 0) {
999 4
                fprintf(stderr, "BEGIN of -I file processing\n");
1000
                /* We must dup stderr, because VCLS closes the output fd */
1001 4
                mgt_cli_setup(I_fd, dup(2), 1, "-I file", mgt_I_close, stderr);
1002 8
                while (I_fd >= 0) {
1003 7
                        o = VEV_Once(mgt_evb);
1004 7
                        if (o != 1)
1005 0
                                MGT_Complain(C_ERR,
1006 0
                                    "VEV_Once() = %d", o);
1007
                }
1008 1
        }
1009 959
        assert(I_fd == -1);
1010
1011 959
        err = mgt_has_vcl();
1012 959
        if (!d_flag && err != NULL && !arg_list_count("f"))
1013 0
                MGT_Complain(C_ERR, "%s", err);
1014
1015 21
        if (err == NULL && !d_flag)
1016 9
                u = MCH_Start_Child();
1017
        else
1018 950
                u = 0;
1019
1020 959
        if (eric_fd >= 0)
1021 8
                mgt_eric_im_done(eric_fd, u);
1022
1023 959
        if (u)
1024 8
                exit(u);
1025
1026
        /* Failure is no longer an option */
1027
1028 951
        if (F_flag)
1029 3
                VFIL_null_fd(STDIN_FILENO);
1030
1031 951
        e = VEV_Alloc();
1032 951
        AN(e);
1033 951
        e->callback = mgt_uptime;
1034 951
        e->timeout = 1.0;
1035 951
        e->name = "mgt_uptime";
1036 951
        AZ(VEV_Start(mgt_evb, e));
1037
1038 951
        e = VEV_Alloc();
1039 951
        AN(e);
1040 951
        e->sig = SIGTERM;
1041 951
        e->callback = mgt_sigint;
1042 951
        e->name = "SIGTERM";
1043 951
        AZ(VEV_Start(mgt_evb, e));
1044
1045 951
        e = VEV_Alloc();
1046 951
        AN(e);
1047 951
        e->sig = SIGINT;
1048 951
        e->callback = mgt_sigint;
1049 951
        e->name = "SIGINT";
1050 951
        AZ(VEV_Start(mgt_evb, e));
1051
1052 951
        o = VEV_Loop(mgt_evb);
1053 951
        if (o != 0 && o != -42)
1054 0
                MGT_Complain(C_ERR, "VEV_Loop() = %d", o);
1055
1056 951
        MGT_Complain(C_INFO, "manager stopping child");
1057 951
        MCH_Stop_Child();
1058 951
        MGT_Complain(C_INFO, "manager dies");
1059 951
        mgt_cli_close_all();
1060 951
        VEV_Destroy(&mgt_evb);
1061 951
        VJ_master(JAIL_MASTER_SYSTEM);
1062
        /*lint -e(730)*/
1063 951
        vext_cleanup(! MGT_DO_DEBUG(DBG_VMOD_SO_KEEP));
1064 951
        (void)rmdir("vext_cache");
1065 951
        VJ_master(JAIL_MASTER_LOW);
1066 14518
        VTAILQ_FOREACH(alp, &arglist, list) {
1067 13567
                if (!strcmp(alp->arg, "P"))
1068 1898
                        VPF_Remove(alp->priv);
1069 13567
        }
1070 951
        exit(exit_status);
1071
}