summaryrefslogtreecommitdiffstats
path: root/src/tools/common/sss_tools.c
blob: a78a5ba19f09ac1d6d2bcb8ffb17d99aecb56d44 (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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
/*
    Authors:
        Pavel Březina <pbrezina@redhat.com>

    Copyright (C) 2015 Red Hat

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <talloc.h>
#include <stdlib.h>
#include <string.h>
#include <popt.h>

#include "config.h"
#include "util/util.h"
#include "confdb/confdb.h"
#include "confdb/confdb_setup.h"
#include "db/sysdb.h"
#include "tools/common/sss_tools.h"

struct sss_cmdline {
    const char *exec; /* argv[0] */
    const char *command; /* command name */
    int argc; /* rest of arguments */
    const char **argv;
};

static void sss_tool_print_common_opts(int min_len)
{
    fprintf(stderr, _("Common options:\n"));
    fprintf(stderr, "  %-*s\t %s\n", min_len, "--debug=INT",
                    _("The debug level to run with"));
    fprintf(stderr, "\n");
    fprintf(stderr, _("Help options:\n"));
    fprintf(stderr, "  %-*s\t %s\n", min_len, "-?, --help",
                    _("Show this for a command"));
    fprintf(stderr, "  %-*s\t %s\n", min_len, "--usage",
                    _("Show brief usage message for a command"));
}

static struct poptOption *sss_tool_common_opts_table(void)
{
    static struct poptOption common_opts[] = {
        {"debug", '\0', POPT_ARG_INT, NULL,
            0, NULL, NULL },
        POPT_TABLEEND
    };

    common_opts[0].descrip = _("The debug level to run with");

    return common_opts;
}

static void sss_tool_common_opts(struct sss_tool_ctx *tool_ctx,
                                 int *argc, const char **argv)
{
    poptContext pc;
    int debug = SSSDBG_DEFAULT;
    int orig_argc = *argc;
    int opt;

    struct poptOption options[] = {
        {"debug", '\0', POPT_ARG_INT | POPT_ARGFLAG_STRIP, &debug,
            0, _("The debug level to run with"), NULL },
        POPT_TABLEEND
    };

    pc = poptGetContext(argv[0], orig_argc, argv, options, 0);
    while ((opt = poptGetNextOpt(pc)) != -1) {
        /* do nothing */
    }

    /* Strip common options from arguments. We will discard_const here,
     * since it is not worth the trouble to convert it back and forth. */
    *argc = poptStrippedArgv(pc, orig_argc, discard_const_p(char *, argv));

    DEBUG_CLI_INIT(debug);

    poptFreeContext(pc);
}

static errno_t sss_tool_confdb_init(TALLOC_CTX *mem_ctx,
                                    struct confdb_ctx **_confdb)
{
    struct confdb_ctx *confdb;
    char *path;
    errno_t ret;

    path = talloc_asprintf(mem_ctx, "%s/%s", DB_PATH, CONFDB_FILE);
    if (path == NULL) {
        return ENOMEM;
    }

    ret = confdb_setup(mem_ctx, path,
                       SSSD_CONFIG_FILE, CONFDB_DEFAULT_CONFIG_DIR,
                       &confdb);
    talloc_zfree(path);
    if (ret != EOK) {
        DEBUG(SSSDBG_FATAL_FAILURE, "Unable to setup ConfDB [%d]: %s\n",
              ret, sss_strerror(ret));
        return ret;
    }

    if (_confdb != NULL) {
        *_confdb = confdb;
    }

    return EOK;
}

static errno_t sss_tool_domains_init(TALLOC_CTX *mem_ctx,
                                     struct confdb_ctx *confdb,
                                     struct sss_domain_info **_domains)
{
    struct sss_domain_info *domains;
    struct sss_domain_info *dom;
    errno_t ret;

    ret = confdb_get_domains(confdb, &domains);
    if (ret != EOK) {
        DEBUG(SSSDBG_CRIT_FAILURE, "Unable to setup domains [%d]: %s\n",
                                   ret, sss_strerror(ret));
        return ret;
    }

    ret = sysdb_init(mem_ctx, domains);
    SYSDB_VERSION_ERROR(ret);
    if (ret != EOK) {
        DEBUG(SSSDBG_CRIT_FAILURE,
              "Could not initialize connection to the sysdb\n");
        return ret;
    }

    for (dom = domains; dom != NULL;
            dom = get_next_domain(dom, SSS_GND_DESCEND)) {
        if (!IS_SUBDOMAIN(dom)) {
            /* Get flat name and domain ID (SID) from the cache
             * if available */
            ret = sysdb_master_domain_update(dom);
            if (ret != EOK) {
                DEBUG(SSSDBG_MINOR_FAILURE, "Failed to update domain %s.\n",
                                            dom->name);
            }

            /* Update list of subdomains for this domain */
            ret = sysdb_update_subdomains(dom);
            if (ret != EOK) {
                DEBUG(SSSDBG_MINOR_FAILURE,
                      "Failed to update subdomains for domain %s.\n",
                      dom->name);
            }
        }
    }

    for (dom = domains; dom != NULL;
            dom = get_next_domain(dom, SSS_GND_DESCEND)) {
        ret = sss_names_init(mem_ctx, confdb, dom->name, &dom->names);
        if (ret != EOK) {
            DEBUG(SSSDBG_CRIT_FAILURE, "sss_names_init() failed\n");
            return ret;
        }
    }

    *_domains = domains;

    return ret;
}

struct sss_tool_ctx *sss_tool_init(TALLOC_CTX *mem_ctx,
                                   int *argc, const char **argv)
{
    struct sss_tool_ctx *tool_ctx;
    errno_t ret;

    tool_ctx = talloc_zero(mem_ctx, struct sss_tool_ctx);
    if (tool_ctx == NULL) {
        DEBUG(SSSDBG_CRIT_FAILURE, "talloc_zero() failed\n");
        return NULL;
    }

    sss_tool_common_opts(tool_ctx, argc, argv);

    /* Connect to confdb. */
    ret = sss_tool_confdb_init(tool_ctx, &tool_ctx->confdb);
    if (ret != EOK) {
        DEBUG(SSSDBG_CRIT_FAILURE, "Unable to open confdb [%d]: %s\n",
                                   ret, sss_strerror(ret));
        goto done;
    }

    /* Setup domains. */
    ret = sss_tool_domains_init(tool_ctx, tool_ctx->confdb, &tool_ctx->domains);
    if (ret != EOK) {
        DEBUG(SSSDBG_CRIT_FAILURE, "Unable to setup domains [%d]: %s\n",
                                   ret, sss_strerror(ret));
        goto done;
    }

    ret = confdb_get_string(tool_ctx->confdb, tool_ctx,
                            CONFDB_MONITOR_CONF_ENTRY,
                            CONFDB_MONITOR_DEFAULT_DOMAIN,
                            NULL, &tool_ctx->default_domain);
    if (ret != EOK) {
        DEBUG(SSSDBG_OP_FAILURE, "Cannot get the default domain [%d]: %s\n",
                                 ret, strerror(ret));
        goto done;
    }

    ret = EOK;

done:
    if (ret != EOK) {
        talloc_zfree(tool_ctx);
    }

    return tool_ctx;
}

static bool sss_tool_is_delimiter(struct sss_route_cmd *command)
{
    if (command->command != NULL && command->command[0] == '\0') {
        return true;
    }

    return false;
}

static size_t sss_tool_max_length(struct sss_route_cmd *commands)
{
    size_t max = 0;
    size_t len;
    int i;

    for (i = 0; commands[i].command != NULL; i++) {
        if (sss_tool_is_delimiter(&commands[i])) {
            continue;
        }

        len = strlen(commands[i].command);
        if (max < len) {
            max = len;
        }
    }

    return max;
}

void sss_tool_usage(const char *tool_name, struct sss_route_cmd *commands)
{
    int min_len;
    int i;

    fprintf(stderr, _("Usage:\n%s COMMAND COMMAND-ARGS\n\n"), tool_name);
    fprintf(stderr, _("Available commands:\n"));

    min_len = sss_tool_max_length(commands);

    for (i = 0; commands[i].command != NULL; i++) {
        if (sss_tool_is_delimiter(&commands[i])) {
            fprintf(stderr, "\n%s\n", commands[i].description);
            continue;
        }

        if (commands[i].description == NULL) {
            fprintf(stderr, "* %40s\n", commands[i].command);
        } else {
            fprintf(stderr, "* %-*s\t %s\n",
                    min_len, commands[i].command, commands[i].description);
        }
    }

    fprintf(stderr, _("\n"));
    sss_tool_print_common_opts(min_len);
}

errno_t sss_tool_route(int argc, const char **argv,
                       struct sss_tool_ctx *tool_ctx,
                       struct sss_route_cmd *commands,
                       void *pvt)
{
    struct sss_cmdline cmdline;
    const char *cmd;
    int i;

    if (commands == NULL) {
        DEBUG(SSSDBG_CRIT_FAILURE, "Bug: commands can't be NULL!\n");
        return EINVAL;
    }

    if (argc < 2) {
        sss_tool_usage(argv[0], commands);
        return EINVAL;
    }

    cmd = argv[1];
    for (i = 0; commands[i].command != NULL; i++) {
        if (sss_tool_is_delimiter(&commands[i])) {
            continue;
        }

        if (strcmp(commands[i].command, cmd) == 0) {
            cmdline.exec = argv[0];
            cmdline.command = argv[1];
            cmdline.argc = argc - 2;
            cmdline.argv = argv + 2;

            return commands[i].fn(&cmdline, tool_ctx, pvt);
        }
    }

    sss_tool_usage(argv[0], commands);
    return EINVAL;
}

static struct poptOption *nonnull_popt_table(struct poptOption *options)
{
    static struct poptOption empty[] = {
        POPT_TABLEEND
    };

    if (options == NULL) {
        return empty;
    }

    return options;
}

errno_t sss_tool_popt_ex(struct sss_cmdline *cmdline,
                         struct poptOption *options,
                         enum sss_tool_opt require_option,
                         sss_popt_fn popt_fn,
                         void *popt_fn_pvt,
                         const char *fopt_name,
                         const char *fopt_help,
                         const char **_fopt,
                         bool *_opt_set)
{
    struct poptOption opts_table[] = {
        {NULL, '\0', POPT_ARG_INCLUDE_TABLE, nonnull_popt_table(options), \
         0, _("Command options:"), NULL },
        {NULL, '\0', POPT_ARG_INCLUDE_TABLE, sss_tool_common_opts_table(), \
         0, _("Common options:"), NULL },
        POPT_AUTOHELP
        POPT_TABLEEND
    };
    const char *fopt;
    char *help;
    poptContext pc;
    bool opt_set;
    int ret;

    /* Create help option string. We always need to append command name since
     * we use POPT_CONTEXT_KEEP_FIRST. */
    if (fopt_name == NULL) {
        help = talloc_asprintf(NULL, "%s %s %s", cmdline->exec,
                               cmdline->command, _("[OPTIONS...]"));
    } else {
        help = talloc_asprintf(NULL, "%s %s %s %s", cmdline->exec,
                               cmdline->command, fopt_name, _("[OPTIONS...]"));
    }
    if (help == NULL) {
        DEBUG(SSSDBG_CRIT_FAILURE, "talloc_asprintf() failed\n");
        return ENOMEM;
    }

    /* Create popt context. This function is supposed to be called on
     * command argv which does not contain executable (argv[0]), therefore
     * we need to use KEEP_FIRST that ensures argv[0] is also processed. */
    pc = poptGetContext(cmdline->exec, cmdline->argc, cmdline->argv,
                        opts_table, POPT_CONTEXT_KEEP_FIRST);

    poptSetOtherOptionHelp(pc, help);

    /* Parse options. Invoke custom function if provided. If no parsing
     * function is provided, print error on unknown option. */
    while ((ret = poptGetNextOpt(pc)) != -1) {
        if (popt_fn != NULL) {
            ret = popt_fn(pc, ret, popt_fn_pvt);
            if (ret != EOK) {
                goto done;
            }
        } else {
            fprintf(stderr, _("Invalid option %s: %s\n\n"),
                    poptBadOption(pc, 0), poptStrerror(ret));
            poptPrintHelp(pc, stderr, 0);
            ret = EINVAL;
            goto done;
        }
    }

    /* Parse free option which is always required if requested. */
    fopt = poptGetArg(pc);
    if (_fopt != NULL) {
        if (fopt == NULL) {
            fprintf(stderr, _("Missing option: %s\n\n"), fopt_help);
            poptPrintHelp(pc, stderr, 0);
            ret = EINVAL;
            goto done;
        }

        /* No more arguments expected. If something follows it is an error. */
        if (poptGetArg(pc)) {
            fprintf(stderr, _("Only one free argument is expected!\n\n"));
            poptPrintHelp(pc, stderr, 0);
            ret = EINVAL;
            goto done;
        }

        *_fopt = fopt;
    } else if (_fopt == NULL && fopt != NULL) {
        /* Unexpected free argument. */
        fprintf(stderr, _("Unexpected parameter: %s\n\n"), fopt);
        poptPrintHelp(pc, stderr, 0);
        ret = EINVAL;
        goto done;
    }

    opt_set = true;
    if ((_fopt != NULL && cmdline->argc < 2) || cmdline->argc < 1) {
        opt_set = false;

        /* If at least one option is required and not provided, print error. */
        if (require_option == SSS_TOOL_OPT_REQUIRED) {
            fprintf(stderr, _("At least one option is required!\n\n"));
            poptPrintHelp(pc, stderr, 0);
            ret = EINVAL;
            goto done;
        }
    }

    if (_opt_set != NULL) {
        *_opt_set = opt_set;
    }

    ret = EOK;

done:
    poptFreeContext(pc);
    talloc_free(help);
    return ret;
}

errno_t sss_tool_popt(struct sss_cmdline *cmdline,
                      struct poptOption *options,
                      enum sss_tool_opt require_option,
                      sss_popt_fn popt_fn,
                      void *popt_fn_pvt)
{
    return sss_tool_popt_ex(cmdline, options, require_option,
                            popt_fn, popt_fn_pvt, NULL, NULL, NULL, NULL);
}

int sss_tool_main(int argc, const char **argv,
                  struct sss_route_cmd *commands,
                  void *pvt)
{
    struct sss_tool_ctx *tool_ctx;
    uid_t uid;
    errno_t ret;

    uid = getuid();
    if (uid != 0) {
        DEBUG(SSSDBG_CRIT_FAILURE, "Running under %d, must be root\n", uid);
        ERROR("%1$s must be run as root\n", argv[0]);
        return EXIT_FAILURE;
    }

    tool_ctx = sss_tool_init(NULL, &argc, argv);
    if (tool_ctx == NULL) {
        DEBUG(SSSDBG_CRIT_FAILURE, "Unable to create tool context\n");
        return EXIT_FAILURE;
    }

    ret = sss_tool_route(argc, argv, tool_ctx, commands, pvt);
    talloc_free(tool_ctx);

    if (ret != EOK) {
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

errno_t sss_tool_parse_name(TALLOC_CTX *mem_ctx,
                            struct sss_tool_ctx *tool_ctx,
                            const char *input,
                            const char **_username,
                            struct sss_domain_info **_domain)
{
    char *username = NULL;
    char *domname = NULL;
    struct sss_domain_info *domain;
    int ret;

    ret = sss_parse_name_for_domains(mem_ctx, tool_ctx->domains,
                                     tool_ctx->default_domain, input,
                                     &domname, &username);
    if (ret == EAGAIN) {
        DEBUG(SSSDBG_CRIT_FAILURE, "Unable to find domain. The domain name may "
              "be a subdomain that was not yet found.\n");
        goto done;
    } else if (ret != EOK) {
        DEBUG(SSSDBG_CRIT_FAILURE, "Unable to parse name [%d]: %s\n",
              ret, sss_strerror(ret));
        goto done;
    }

    domain = find_domain_by_name(tool_ctx->domains, domname, true);

    *_username = username;
    *_domain = domain;

    ret = EOK;

done:
    if (ret != EOK) {
        talloc_zfree(username);
        talloc_zfree(domname);
    }

    return ret;
}