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