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