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