summaryrefslogtreecommitdiffstats
path: root/modules/md/md_cmd_main.c
blob: bff4e13ad377c27ae1b446daf6287bb24b9595e7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
/* Copyright 2015 greenbytes GmbH (https://www.greenbytes.de)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

#include <apr_lib.h>
#include <apr_buckets.h>
#include <apr_getopt.h>
#include <apr_hash.h>
#include <apr_strings.h>

#include "md.h"
#include "md_acme.h"
#include "md_json.h"
#include "md_http.h"
#include "md_log.h"
#include "md_reg.h"
#include "md_store.h"
#include "md_store_fs.h"
#include "md_util.h"
#include "md_version.h"

#include "md_cmd.h"
#include "md_cmd_acme.h"
#include "md_cmd_reg.h"
#include "md_cmd_store.h"
#include "md_curl.h"


/**************************************************************************************************/
/* command infrastructure */

apr_getopt_option_t MD_NoOptions [] = {
    { NULL, 0, 0, NULL }
};

apr_status_t usage(const md_cmd_t *cmd, const char *msg) 
{
    const apr_getopt_option_t *opt;
    int i;

    if (msg) {
        fprintf(stderr, "%s\n", msg);
    }
    fprintf(stderr, "usage: %s\n", cmd->synopsis);
    if (cmd->description) {
        fprintf(stderr, "\t%s\n", cmd->description);
    }
    if (cmd->opts[0].name) {
        fprintf(stderr, "  with the following options:\n");
    
        opt = NULL;
        for (i = 0; !opt || opt->optch; ++i) {
            opt = cmd->opts + i;
            if (opt->optch) {
                fprintf(stderr, "  -%c | --%s    %s\t%s\n", 
                        opt->optch, opt->name, opt->has_arg? "arg" : "", opt->description);
                
            }
        }
    }
    if (cmd->sub_cmds && cmd->sub_cmds[0]) {
        fprintf(stderr, "  using one of the following commands:\n");
        for (i = 0; cmd->sub_cmds[i]; ++i) {
            fprintf(stderr, "  \t%s\n", cmd->sub_cmds[i]->synopsis);
            fprintf(stderr, "  \t\t%s\n", cmd->sub_cmds[i]->description);
        }
    }
    
    exit(msg? 1 : 2);
}

static apr_status_t md_cmd_ctx_init(md_cmd_ctx *ctx, apr_pool_t *p, 
                                    int argc, const char *const *argv)
{
    ctx->p = p;
    ctx->argc = argc;
    ctx->argv = argv;
    ctx->options = apr_table_make(p, 5);
    
    return ctx->options? APR_SUCCESS : APR_ENOMEM;
}

void md_cmd_ctx_set_option(md_cmd_ctx *ctx, const char *key, const char *value)
{
    apr_table_setn(ctx->options, key, value);
}

int md_cmd_ctx_has_option(md_cmd_ctx *ctx, const char *option)
{
    return NULL != apr_table_get(ctx->options, option);
}

const char *md_cmd_ctx_get_option(md_cmd_ctx *ctx, const char *key)
{
    return apr_table_get(ctx->options, key);
}

static const md_cmd_t *find_cmd(const md_cmd_t **cmds, const char *name) 
{
    int i;
    if (cmds) {
        for (i = 0; cmds[i]; ++i) {
            if (!strcmp(name, cmds[i]->name)) {
                return cmds[i];
            }
        }
    }
    return NULL;
}

static apr_status_t cmd_process(md_cmd_ctx *ctx, const md_cmd_t *cmd)
{
    apr_getopt_t *os;
    const char *optarg;
    int opt;
    apr_status_t rv = APR_SUCCESS;

    md_log_perror(MD_LOG_MARK, MD_LOG_TRACE4, 0, ctx->p, 
                  "start processing cmd %s", cmd->name); 

    apr_getopt_init(&os, ctx->p, ctx->argc, ctx->argv);
    while ((rv = apr_getopt_long(os, cmd->opts, &opt, &optarg)) == APR_SUCCESS) {
        if (!cmd->opt_fn) {
            return usage(cmd, NULL);
        }
        else if (APR_SUCCESS != (rv = cmd->opt_fn(ctx, opt, optarg))) {
            return usage(cmd, NULL);
        }
    }
    if (rv != APR_EOF) {
        return usage(cmd, NULL);
    }
    
    if (md_cmd_ctx_has_option(ctx, "help")) {
        return usage(cmd, NULL);
    }
    if (md_cmd_ctx_has_option(ctx, "version")) {
        fprintf(stdout, "version: %s\n", MOD_MD_VERSION);
        exit(0);
    }
    
    ctx->argv = os->argv + os->ind;
    ctx->argc -= os->ind;
    
    md_log_perror(MD_LOG_MARK, MD_LOG_TRACE4, 0, ctx->p, "args remaining: %d", ctx->argc);
                   
    if (cmd->needs & (MD_CTX_STORE|MD_CTX_REG|MD_CTX_ACME) && !ctx->store) {
        if (!ctx->base_dir) {
            fprintf(stderr, "need store directory for command: %s\n", cmd->name);
            return APR_EINVAL;
        }
        if (APR_SUCCESS != (rv = md_store_fs_init(&ctx->store, ctx->p, ctx->base_dir))) {
            fprintf(stderr, "error %d creating store for: %s\n", rv, ctx->base_dir);
            return APR_EINVAL;
        }
    }
    if (cmd->needs & MD_CTX_REG && !ctx->reg) {
        if (!ctx->store) {
            fprintf(stderr, "need store for registry: %s\n", cmd->name);
            return APR_EINVAL;
        }
        if (APR_SUCCESS != (rv = md_reg_init(&ctx->reg, ctx->p, ctx->store,
                                             md_cmd_ctx_get_option(ctx, MD_CMD_OPT_PROXY_URL)))) {
            fprintf(stderr, "error %d creating registry from store: %s\n", rv, ctx->base_dir);
            return APR_EINVAL;
        }
    }
    if (cmd->needs & MD_CTX_ACME && !ctx->acme) {
        if (!ctx->store) {
            fprintf(stderr, "need store for ACME: %s\n", cmd->name);
            return APR_EINVAL;
        }
        rv = md_acme_create(&ctx->acme, ctx->p, ctx->ca_url, 
                            md_cmd_ctx_get_option(ctx, MD_CMD_OPT_PROXY_URL));
        if (APR_SUCCESS != rv) {
            fprintf(stderr, "error creating acme instance %s (%s)\n", 
                    ctx->ca_url, ctx->base_dir);
            return rv;
        }
        rv = md_acme_setup(ctx->acme);
        if (rv != APR_SUCCESS) {
            md_log_perror(MD_LOG_MARK, MD_LOG_ERR, rv, ctx->p, "contacting %s", ctx->ca_url);
            return rv;
        }
    }
    
    if (cmd->sub_cmds && cmd->sub_cmds[0]) {
        const md_cmd_t *sub_cmd;
        
        if (!ctx->argc) {
            return usage(cmd, "sub command is missing");
        }
        
        md_log_perror(MD_LOG_MARK, MD_LOG_TRACE4, 0, ctx->p, "sub command %s", ctx->argv[0]);
        
        sub_cmd = find_cmd(cmd->sub_cmds, ctx->argv[0]);
        if (sub_cmd) {
            return cmd_process(ctx, sub_cmd);
        }
        else if (!cmd->do_fn) {
            fprintf(stderr, "unknown cmd: %s\n", ctx->argv[0]);
            return APR_EINVAL;
        }
    }
    
    if (cmd->do_fn) {
        md_log_perror(MD_LOG_MARK, MD_LOG_TRACE4, 0, ctx->p, "%s->do_fn", cmd->name);
        return cmd->do_fn(ctx, cmd);
    }
    return APR_EINVAL;
}

/**************************************************************************************************/
/* logging setup */

static md_log_level_t active_level = MD_LOG_INFO;

static int log_is_level(void *baton, apr_pool_t *p, md_log_level_t level)
{
    return level <= active_level;
}

#define LOG_BUF_LEN 16*1024

static void log_print(const char *file, int line, md_log_level_t level, 
                      apr_status_t rv, void *baton, apr_pool_t *p, const char *fmt, va_list ap)
{
    if (log_is_level(baton, p, level)) {
        char buffer[LOG_BUF_LEN];
        char errbuff[32];
        
        apr_vsnprintf(buffer, LOG_BUF_LEN-1, fmt, ap);
        buffer[LOG_BUF_LEN-1] = '\0';
        
        if (rv) {
            fprintf(stderr, "[%s:%d %s][%d(%s)] %s\n", file, line, 
                    md_log_level_name(level), rv, 
                    apr_strerror(rv, errbuff, sizeof(errbuff)/sizeof(errbuff[0])), 
                    buffer);
        }
        else if (active_level == MD_LOG_INFO) {
            fprintf(stderr, "%s\n", buffer);
        }
        else {
            fprintf(stderr, "[%s:%d %s][ok] %s\n", file, line, 
                    md_log_level_name(level), buffer);
        }
    }
}

/**************************************************************************************************/
/* utils */

void md_cmd_print_md(md_cmd_ctx *ctx, const md_t *md)
{
    assert(md);
    if (ctx->json_out) {
        md_json_t *json = md_to_json(md, ctx->p);
        md_json_addj(json, ctx->json_out, "output", NULL);
    }
    else {
        int i;
        fprintf(stdout, "md: %s [", md->name);
        for (i = 0; i < md->domains->nelts; ++i) {
            const char *domain = APR_ARRAY_IDX(md->domains, i, const char*);
            fprintf(stdout, "%s%s", (i? ", " : ""), domain);
        }
        fprintf(stdout, "]\n");
    }
}

static int pool_abort(int rv)
{
    abort();
}

apr_array_header_t *md_cmd_gather_args(md_cmd_ctx *ctx, int index)
{
    int i;
    
    apr_array_header_t *args = apr_array_make(ctx->p, 5, sizeof(const char *));
    for (i = index; i < ctx->argc; ++i) {
        APR_ARRAY_PUSH(args, const char *) = ctx->argv[i];
    }
    return args;
}

/**************************************************************************************************/
/* command: main() */

static void init_json_out(md_cmd_ctx *ctx) 
{
    apr_array_header_t *empty = apr_array_make(ctx->p, 1, sizeof(char*));
    
    ctx->json_out = md_json_create(ctx->p);
    
    md_json_setsa(empty, ctx->json_out, "output", NULL);
    md_json_setl(0, ctx->json_out, "status", NULL);
}

static apr_status_t main_opts(md_cmd_ctx *ctx, int option, const char *optarg)
{
    switch (option) {
        case 'a':
            ctx->ca_url = optarg;
            break;
        case 'd':
            ctx->base_dir = optarg;
            break;
        case 'h':
            md_cmd_ctx_set_option(ctx, "help", "1");
            break;
        case 'j':
            init_json_out(ctx);
            break;
        case 'p':
            md_cmd_ctx_set_option(ctx, MD_CMD_OPT_PROXY_URL, optarg);
            break;
        case 'q':
            if (active_level > 0) {
                --active_level;
            }
            break;
        case 'v':
            if (active_level < MD_LOG_TRACE8) {
                ++active_level;
            }
            break;
        case 'V':
            md_cmd_ctx_set_option(ctx, "version", "1");
            break;
        case 't':
            ctx->tos = optarg;
            break;
        default:
            return APR_EINVAL;
    }
    return APR_SUCCESS;
}

static const md_cmd_t *MainSubCmds[] = {
    &MD_AcmeCmd,
    &MD_RegAddCmd,
    &MD_RegUpdateCmd, 
    &MD_RegDriveCmd,
    &MD_RegListCmd,
    &MD_StoreCmd,
    NULL
};

static apr_getopt_option_t MainOptions [] = {
    { "acme",    'a', 1, "the url of the ACME server directory"},
    { "dir",     'd', 1, "directory for file data"},
    { "help",    'h', 0, "print usage information"},
    { "json",    'j', 0, "produce json output"},
    { "proxy",   'p', 1, "use the HTTP proxy url"},
    { "quiet",   'q', 0, "produce less output"},
    { "terms",   't', 1, "you agree to the terms of services (url)" },
    { "verbose", 'v', 0, "produce more output" },
    { "version", 'V', 0, "print version" },
    { NULL,       0,  0, NULL }
};

static md_cmd_t MainCmd = {
    "a2md", MD_CTX_NONE, 
    main_opts, NULL,
    MainOptions, MainSubCmds,
    "a2md [options] cmd [cmd options] [args]", 
    "Show and manipulate Apache Manged Domains", 
};

#define BASE_VERSION "apachemd/" MOD_MD_VERSION

int main(int argc, const char *const *argv)
{
    apr_allocator_t *allocator;
    apr_status_t rv;
    apr_pool_t *p;
    md_cmd_ctx ctx;

    rv = apr_app_initialize(&argc, &argv, NULL);
    if (rv != APR_SUCCESS) {
        fprintf(stderr, "error initializing APR (error code %d)\n", (int) rv);
        return 1;
    }

    if (atexit(apr_terminate)) {
        perror("error registering atexit");
        return 1;
    }
    
    memset(&ctx, 0, sizeof(ctx));
    md_log_set(log_is_level, log_print, NULL);
    
    apr_allocator_create(&allocator);
    rv = apr_pool_create_ex(&p, NULL, pool_abort, allocator);
    if (rv != APR_SUCCESS) {
        fprintf(stderr, "error initializing pool\n");
        return 1;
    }
    
    md_http_use_implementation(md_curl_get_impl(p));
    md_acme_init(p, BASE_VERSION);
    md_cmd_ctx_init(&ctx, p, argc, argv);
    
    rv = cmd_process(&ctx, &MainCmd);
    
    if (ctx.json_out) {
        const char *out;

        md_json_setl(rv, ctx.json_out, "status", NULL);
        if (APR_SUCCESS != rv) {
            char errbuff[32];
            
            apr_strerror(rv, errbuff, sizeof(errbuff)/sizeof(errbuff[0]));
            md_json_sets(apr_pstrdup(p, errbuff), ctx.json_out, "description", NULL);
        }

        out = md_json_writep(ctx.json_out, p, MD_JSON_FMT_INDENT);
        if (!out) {
            rv = APR_EINVAL;
        }

        fprintf(stdout, "%s\n", out ? out : "<failed to serialize!>");
    }
    
    return (rv == APR_SUCCESS)? 0 : 1;
}