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