• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 17844524571

18 Sep 2025 08:58PM UTC coverage: 72.326% (+0.09%) from 72.24%
17844524571

push

github

DaanDeMeyer
userdb: suppress creation of empty userdb dirs

13 of 16 new or added lines in 1 file covered. (81.25%)

3248 existing lines in 52 files now uncovered.

303003 of 418940 relevant lines covered (72.33%)

1051258.58 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

73.34
/src/userdb/userdbctl.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <getopt.h>
4
#include <stdlib.h>
5
#include <unistd.h>
6

7
#include "alloc-util.h"
8
#include "bitfield.h"
9
#include "build.h"
10
#include "copy.h"
11
#include "creds-util.h"
12
#include "dirent-util.h"
13
#include "errno-list.h"
14
#include "errno-util.h"
15
#include "escape.h"
16
#include "fd-util.h"
17
#include "fileio.h"
18
#include "format-table.h"
19
#include "format-util.h"
20
#include "fs-util.h"
21
#include "log.h"
22
#include "main-func.h"
23
#include "mkdir.h"
24
#include "pager.h"
25
#include "parse-argument.h"
26
#include "pretty-print.h"
27
#include "recurse-dir.h"
28
#include "socket-util.h"
29
#include "string-util.h"
30
#include "strv.h"
31
#include "uid-classification.h"
32
#include "uid-range.h"
33
#include "umask-util.h"
34
#include "user-record-show.h"
35
#include "user-util.h"
36
#include "userdb.h"
37
#include "verbs.h"
38
#include "virt.h"
39

40
static enum {
41
        OUTPUT_CLASSIC,
42
        OUTPUT_TABLE,
43
        OUTPUT_FRIENDLY,
44
        OUTPUT_JSON,
45
        _OUTPUT_INVALID = -EINVAL,
46
} arg_output = _OUTPUT_INVALID;
47

48
static PagerFlags arg_pager_flags = 0;
49
static bool arg_legend = true;
50
static char** arg_services = NULL;
51
static UserDBFlags arg_userdb_flags = 0;
52
static sd_json_format_flags_t arg_json_format_flags = SD_JSON_FORMAT_OFF;
53
static bool arg_chain = false;
54
static uint64_t arg_disposition_mask = UINT64_MAX;
55
static uid_t arg_uid_min = 0;
56
static uid_t arg_uid_max = UID_INVALID-1;
57
static bool arg_fuzzy = false;
58
static bool arg_boundaries = true;
59
static sd_json_variant *arg_from_file = NULL;
60

61
STATIC_DESTRUCTOR_REGISTER(arg_services, strv_freep);
313✔
62
STATIC_DESTRUCTOR_REGISTER(arg_from_file, sd_json_variant_unrefp);
313✔
63

64
static const char *user_disposition_to_color(UserDisposition d) {
520✔
65
        assert(d >= 0);
520✔
66
        assert(d < _USER_DISPOSITION_MAX);
520✔
67

68
        switch (d) {
520✔
69
        case USER_INTRINSIC:
70
                return ansi_red();
28✔
71

72
        case USER_SYSTEM:
73
        case USER_DYNAMIC:
74
                return ansi_green();
468✔
75

76
        case USER_CONTAINER:
77
        case USER_FOREIGN:
78
                return ansi_cyan();
10✔
79

80
        case USER_RESERVED:
81
                return ansi_red();
×
82

83
        default:
84
                return NULL;
85
        }
86
}
87

88
static const char* shell_to_color(const char *shell) {
232✔
89
        return !shell || is_nologin_shell(shell) ? ansi_grey() : NULL;
232✔
90
}
91

92
static int show_user(UserRecord *ur, Table *table) {
438✔
93
        int r;
438✔
94

95
        assert(ur);
438✔
96

97
        switch (arg_output) {
438✔
98

99
        case OUTPUT_CLASSIC:
26✔
100
                if (!uid_is_valid(ur->uid))
26✔
101
                        break;
102

103
                printf("%s:x:" UID_FMT ":" GID_FMT ":%s:%s:%s\n",
52✔
104
                       ur->user_name,
105
                       ur->uid,
106
                       user_record_gid(ur),
107
                       strempty(user_record_real_name(ur)),
26✔
108
                       user_record_home_directory(ur),
109
                       user_record_shell(ur));
110

111
                break;
26✔
112

113
        case OUTPUT_JSON:
96✔
114
                sd_json_variant_dump(ur->json, arg_json_format_flags, NULL, NULL);
96✔
115
                break;
96✔
116

117
        case OUTPUT_FRIENDLY:
84✔
118
                user_record_show(ur, true);
84✔
119

120
                if (ur->incomplete) {
84✔
121
                        fflush(stdout);
×
122
                        log_warning("Warning: lacking rights to acquire privileged fields of user record of '%s', output incomplete.", ur->user_name);
×
123
                }
124

125
                break;
126

127
        case OUTPUT_TABLE: {
232✔
128
                assert(table);
232✔
129
                UserDisposition d = user_record_disposition(ur);
232✔
130
                const char *sh = user_record_shell(ur);
232✔
131

132
                r = table_add_many(
400✔
133
                                table,
134
                                TABLE_STRING, "",
135
                                TABLE_STRING, ur->user_name,
136
                                TABLE_SET_COLOR, user_disposition_to_color(d),
137
                                TABLE_STRING, user_disposition_to_string(d),
138
                                TABLE_UID, ur->uid,
139
                                TABLE_GID, user_record_gid(ur),
140
                                TABLE_STRING, empty_to_null(ur->real_name),
141
                                TABLE_PATH, user_record_home_directory(ur),
142
                                TABLE_PATH, sh,
143
                                TABLE_SET_COLOR, shell_to_color(sh),
144
                                TABLE_INT, 0);
145
                if (r < 0)
232✔
146
                        return table_log_add_error(r);
×
147

148
                break;
149
        }
150

151
        default:
×
152
                assert_not_reached();
×
153
        }
154

155
        return 0;
156
}
157

158
static bool test_show_mapped(void) {
16✔
159
        /* Show mapped user range only in environments where user mapping is a thing. */
160
        return running_in_userns() > 0;
16✔
161
}
162

163
static const struct {
164
        uid_t first, last;
165
        const char *name;
166
        UserDisposition disposition;
167
        bool (*test)(void);
168
} uid_range_table[] = {
169
        {
170
                .first = 1,
171
                .last = SYSTEM_UID_MAX,
172
                .name = "system",
173
                .disposition = USER_SYSTEM,
174
        },
175
        {
176
                .first = GREETER_UID_MIN,
177
                .last = GREETER_UID_MAX,
178
                .name = "dynamic greeter",
179
                .disposition = USER_DYNAMIC,
180
        },
181
        {
182
                .first = DYNAMIC_UID_MIN,
183
                .last = DYNAMIC_UID_MAX,
184
                .name = "dynamic system",
185
                .disposition = USER_DYNAMIC,
186
        },
187
        {
188
                .first = CONTAINER_UID_MIN,
189
                .last = CONTAINER_UID_MAX,
190
                .name = "container",
191
                .disposition = USER_CONTAINER,
192
        },
193
        {
194
                .first = FOREIGN_UID_MIN,
195
                .last = FOREIGN_UID_MAX,
196
                .name = "foreign",
197
                .disposition = USER_FOREIGN,
198
        },
199
#if ENABLE_HOMED
200
        {
201
                .first = HOME_UID_MIN,
202
                .last = HOME_UID_MAX,
203
                .name = "systemd-homed",
204
                .disposition = USER_REGULAR,
205
        },
206
#endif
207
        {
208
                .first = MAP_UID_MIN,
209
                .last = MAP_UID_MAX,
210
                .name = "mapped",
211
                .disposition = USER_REGULAR,
212
                .test = test_show_mapped,
213
        },
214
};
215

216
static int table_add_uid_boundaries(Table *table, const UIDRange *p) {
13✔
217
        int r, n_added = 0;
13✔
218

219
        assert(table);
13✔
220

221
        FOREACH_ELEMENT(i, uid_range_table) {
104✔
222
                _cleanup_free_ char *name = NULL, *comment = NULL;
53✔
223

224
                if (!BIT_SET(arg_disposition_mask, i->disposition))
91✔
225
                        continue;
28✔
226

227
                if (!uid_range_covers(p, i->first, i->last - i->first + 1))
63✔
228
                        continue;
×
229

230
                if (i->test && !i->test())
63✔
231
                        continue;
10✔
232

233
                name = strjoin(glyph(GLYPH_ARROW_DOWN),
53✔
234
                               " begin ", i->name, " users ",
235
                               glyph(GLYPH_ARROW_DOWN));
236
                if (!name)
53✔
237
                        return log_oom();
×
238

239
                comment = strjoin("First ", i->name, " user");
53✔
240
                if (!comment)
53✔
241
                        return log_oom();
×
242

243
                r = table_add_many(
53✔
244
                                table,
245
                                TABLE_STRING, glyph(GLYPH_TREE_TOP),
246
                                TABLE_STRING, name,
247
                                TABLE_SET_COLOR, ansi_grey(),
248
                                TABLE_STRING, user_disposition_to_string(i->disposition),
249
                                TABLE_SET_COLOR, ansi_grey(),
250
                                TABLE_UID, i->first,
251
                                TABLE_SET_COLOR, ansi_grey(),
252
                                TABLE_EMPTY,
253
                                TABLE_STRING, comment,
254
                                TABLE_SET_COLOR, ansi_grey(),
255
                                TABLE_EMPTY,
256
                                TABLE_EMPTY,
257
                                TABLE_INT, -1); /* sort before any other entry with the same UID */
258
                if (r < 0)
53✔
259
                        return table_log_add_error(r);
×
260

261
                free(name);
53✔
262
                name = strjoin(glyph(GLYPH_ARROW_UP),
53✔
263
                               " end ", i->name, " users ",
264
                               glyph(GLYPH_ARROW_UP));
265
                if (!name)
53✔
266
                        return log_oom();
×
267

268
                free(comment);
53✔
269
                comment = strjoin("Last ", i->name, " user");
53✔
270
                if (!comment)
53✔
271
                        return log_oom();
×
272

273
                r = table_add_many(
53✔
274
                                table,
275
                                TABLE_STRING, glyph(GLYPH_TREE_RIGHT),
276
                                TABLE_STRING, name,
277
                                TABLE_SET_COLOR, ansi_grey(),
278
                                TABLE_STRING, user_disposition_to_string(i->disposition),
279
                                TABLE_SET_COLOR, ansi_grey(),
280
                                TABLE_UID, i->last,
281
                                TABLE_SET_COLOR, ansi_grey(),
282
                                TABLE_EMPTY,
283
                                TABLE_STRING, comment,
284
                                TABLE_SET_COLOR, ansi_grey(),
285
                                TABLE_EMPTY,
286
                                TABLE_EMPTY,
287
                                TABLE_INT, 1); /* sort after any other entry with the same UID */
288
                if (r < 0)
53✔
289
                        return table_log_add_error(r);
×
290

291
                n_added += 2;
53✔
292
        }
293

294
        return n_added;
295
}
296

297
static int add_unavailable_uid(Table *table, uid_t start, uid_t end) {
×
298
        _cleanup_free_ char *name = NULL;
×
299
        int r;
×
300

301
        assert(table);
×
302
        assert(start <= end);
×
303

304
        name = strjoin(glyph(GLYPH_ARROW_DOWN),
×
305
                       " begin unavailable users ",
306
                       glyph(GLYPH_ARROW_DOWN));
307
        if (!name)
×
308
                return log_oom();
×
309

310
        r = table_add_many(
×
311
                        table,
312
                        TABLE_STRING, glyph(GLYPH_TREE_TOP),
313
                        TABLE_STRING, name,
314
                        TABLE_SET_COLOR, ansi_grey(),
315
                        TABLE_EMPTY,
316
                        TABLE_UID, start,
317
                        TABLE_SET_COLOR, ansi_grey(),
318
                        TABLE_EMPTY,
319
                        TABLE_STRING, "First unavailable user",
320
                        TABLE_SET_COLOR, ansi_grey(),
321
                        TABLE_EMPTY,
322
                        TABLE_EMPTY,
323
                        TABLE_INT, -1); /* sort before an other entry with the same UID */
324
        if (r < 0)
×
325
                return table_log_add_error(r);
×
326

327
        free(name);
×
328
        name = strjoin(glyph(GLYPH_ARROW_UP),
×
329
                       " end unavailable users ",
330
                       glyph(GLYPH_ARROW_UP));
331
        if (!name)
×
332
                return log_oom();
×
333

334
        r = table_add_many(
×
335
                        table,
336
                        TABLE_STRING, glyph(GLYPH_TREE_RIGHT),
337
                        TABLE_STRING, name,
338
                        TABLE_SET_COLOR, ansi_grey(),
339
                        TABLE_EMPTY,
340
                        TABLE_UID, end,
341
                        TABLE_SET_COLOR, ansi_grey(),
342
                        TABLE_EMPTY,
343
                        TABLE_STRING, "Last unavailable user",
344
                        TABLE_SET_COLOR, ansi_grey(),
345
                        TABLE_EMPTY,
346
                        TABLE_EMPTY,
347
                        TABLE_INT, 1); /* sort after any other entry with the same UID */
348
        if (r < 0)
×
349
                return table_log_add_error(r);
×
350

351
        return 2;
352
}
353

354
static int table_add_uid_map(
22✔
355
                Table *table,
356
                const UIDRange *p,
357
                int (*add_unavailable)(Table *t, uid_t start, uid_t end)) {
358

359
        uid_t focus = 0;
22✔
360
        int n_added = 0, r;
22✔
361

362
        assert(table);
22✔
363
        assert(add_unavailable);
22✔
364

365
        if (!p)
22✔
366
                return 0;
367

368
        FOREACH_ARRAY(x, p->entries, p->n_entries) {
44✔
369
                if (focus < x->start) {
22✔
370
                        r = add_unavailable(table, focus, x->start-1);
×
371
                        if (r < 0)
×
372
                                return r;
373

374
                        n_added += r;
×
375
                }
376

377
                if (x->start > UINT32_MAX - x->nr) { /* overflow check */
22✔
378
                        focus = UINT32_MAX;
379
                        break;
380
                }
381

382
                focus = x->start + x->nr;
22✔
383
        }
384

385
        if (focus < UINT32_MAX-1) {
22✔
386
                r = add_unavailable(table, focus, UINT32_MAX-1);
×
387
                if (r < 0)
×
388
                        return r;
389

390
                n_added += r;
×
391
        }
392

393
        return n_added;
394
}
395

396
static int display_user(int argc, char *argv[], void *userdata) {
104✔
397
        _cleanup_(table_unrefp) Table *table = NULL;
104✔
398
        bool draw_separator = false;
104✔
399
        int ret = 0, r;
104✔
400

401
        if (arg_output < 0)
104✔
402
                arg_output = arg_from_file || (argc > 1 && !arg_fuzzy) ? OUTPUT_FRIENDLY : OUTPUT_TABLE;
94✔
403

404
        if (arg_output == OUTPUT_TABLE) {
104✔
405
                table = table_new(" ", "name", "disposition", "uid", "gid", "realname", "home", "shell", "order");
14✔
406
                if (!table)
14✔
407
                        return log_oom();
×
408

409
                (void) table_set_align_percent(table, table_get_cell(table, 0, 3), 100);
14✔
410
                (void) table_set_align_percent(table, table_get_cell(table, 0, 4), 100);
14✔
411
                table_set_ersatz_string(table, TABLE_ERSATZ_DASH);
14✔
412
                (void) table_set_sort(table, (size_t) 3, (size_t) 8);
14✔
413
                (void) table_hide_column_from_display(table, (size_t) 8);
14✔
414
                if (!arg_boundaries)
14✔
415
                        (void) table_hide_column_from_display(table, (size_t) 0);
1✔
416
        }
417

418
        _cleanup_(userdb_match_done) UserDBMatch match = {
104✔
419
                .disposition_mask = arg_disposition_mask,
420
                .uid_min = arg_uid_min,
421
                .uid_max = arg_uid_max,
422
        };
423

424
        if (arg_from_file) {
104✔
425
                if (argc > 1)
3✔
426
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No argument expected when invoked with --from-file=, refusing.");
×
427

428
                _cleanup_(user_record_unrefp) UserRecord *ur = user_record_new();
6✔
429
                if (!ur)
3✔
430
                        return log_oom();
×
431

432
                r = user_record_load(ur, arg_from_file, USER_RECORD_LOAD_MASK_SECRET|USER_RECORD_LOG);
3✔
433
                if (r < 0)
3✔
434
                        return r;
435

436
                r = show_user(ur, table);
3✔
437
                if (r < 0)
3✔
438
                        return r;
439

440
        } else if (argc > 1 && !arg_fuzzy)
101✔
441
                STRV_FOREACH(i, argv + 1) {
175✔
442
                        _cleanup_(user_record_unrefp) UserRecord *ur = NULL;
93✔
443

444
                        r = userdb_by_name(*i, &match, arg_userdb_flags|USERDB_PARSE_NUMERIC, &ur);
93✔
445
                        if (r < 0) {
93✔
446
                                if (r == -ESRCH)
20✔
447
                                        log_error_errno(r, "User %s does not exist.", *i);
16✔
448
                                else if (r == -EHOSTDOWN)
4✔
449
                                        log_error_errno(r, "Selected user database service is not available for this request.");
×
450
                                else if (r == -ENOEXEC)
4✔
451
                                        log_error_errno(r, "User '%s' exists but does not match specified filter.", *i);
×
452
                                else
453
                                        log_error_errno(r, "Failed to find user %s: %m", *i);
4✔
454

455
                                RET_GATHER(ret, r);
20✔
456
                        } else {
457
                                if (draw_separator && arg_output == OUTPUT_FRIENDLY)
73✔
458
                                        putchar('\n');
4✔
459

460
                                r = show_user(ur, table);
73✔
461
                                if (r < 0)
73✔
462
                                        return r;
×
463

464
                                draw_separator = true;
465
                        }
466
                }
467
        else {
468
                if (argc > 1) {
1✔
469
                        /* If there are further arguments, they are the fuzzy match strings. */
470
                        match.fuzzy_names = strv_copy(strv_skip(argv, 1));
1✔
471
                        if (!match.fuzzy_names)
1✔
472
                                return log_oom();
×
473
                }
474

475
                _cleanup_(userdb_iterator_freep) UserDBIterator *iterator = NULL;
×
476
                r = userdb_all(&match, arg_userdb_flags, &iterator);
19✔
477
                if (r == -ENOLINK) /* ENOLINK → Didn't find answer without Varlink, and didn't try Varlink because was configured to off. */
19✔
478
                        log_debug_errno(r, "No entries found. (Didn't check via Varlink.)");
×
479
                else if (r == -ESRCH) /* ESRCH → Couldn't find any suitable entry, but we checked all sources */
19✔
480
                        log_debug_errno(r, "No entries found.");
19✔
481
                else if (r < 0)
19✔
482
                        return log_error_errno(r, "Failed to enumerate users: %m");
×
483
                else {
484
                        for (;;) {
362✔
485
                                _cleanup_(user_record_unrefp) UserRecord *ur = NULL;
19✔
486

487
                                r = userdb_iterator_get(iterator, &match, &ur);
381✔
488
                                if (r == -ESRCH)
381✔
489
                                        break;
490
                                if (r == -EHOSTDOWN)
362✔
491
                                        return log_error_errno(r, "Selected user database service is not available for this request.");
×
492
                                if (r < 0)
362✔
493
                                        return log_error_errno(r, "Failed to acquire next user: %m");
×
494

495
                                if (draw_separator && arg_output == OUTPUT_FRIENDLY)
362✔
496
                                        putchar('\n');
25✔
497

498
                                r = show_user(ur, table);
362✔
499
                                if (r < 0)
362✔
500
                                        return r;
501

502
                                draw_separator = true;
362✔
503
                        }
504
                }
505
        }
506

507
        if (table) {
104✔
508
                int boundary_lines = 0, uid_map_lines = 0;
14✔
509

510
                if (arg_boundaries) {
14✔
511
                        _cleanup_(uid_range_freep) UIDRange *uid_range = NULL;
13✔
512

513
                        r = uid_range_load_userns(/* path = */ NULL, UID_RANGE_USERNS_INSIDE, &uid_range);
13✔
514
                        if (r < 0)
13✔
515
                                log_debug_errno(r, "Failed to load /proc/self/uid_map, ignoring: %m");
×
516

517
                        boundary_lines = table_add_uid_boundaries(table, uid_range);
13✔
518
                        if (boundary_lines < 0)
13✔
519
                                return boundary_lines;
520

521
                        uid_map_lines = table_add_uid_map(table, uid_range, add_unavailable_uid);
13✔
522
                        if (uid_map_lines < 0)
13✔
523
                                return uid_map_lines;
524
                }
525

526
                if (!table_isempty(table)) {
28✔
527
                        r = table_print_with_pager(table, arg_json_format_flags, arg_pager_flags, arg_legend);
14✔
528
                        if (r < 0)
14✔
529
                                return r;
530
                }
531

532
                if (arg_legend) {
14✔
533
                        size_t k;
12✔
534

535
                        k = table_get_rows(table) - 1 - boundary_lines - uid_map_lines;
12✔
536
                        if (k > 0)
12✔
537
                                printf("\n%zu users listed.\n", k);
10✔
538
                        else
539
                                printf("No users.\n");
2✔
540
                }
541
        }
542

543
        return ret;
544
}
545

546
static int show_group(GroupRecord *gr, Table *table) {
312✔
547
        int r;
312✔
548

549
        assert(gr);
312✔
550

551
        switch (arg_output) {
312✔
552

553
        case OUTPUT_CLASSIC: {
×
554
                _cleanup_free_ char *m = NULL;
×
555

556
                if (!gid_is_valid(gr->gid))
×
557
                        break;
558

559
                m = strv_join(gr->members, ",");
×
560
                if (!m)
×
561
                        return log_oom();
×
562

563
                printf("%s:x:" GID_FMT ":%s\n",
×
564
                       gr->group_name,
565
                       gr->gid,
566
                       m);
567
                break;
568
        }
569

570
        case OUTPUT_JSON:
5✔
571
                sd_json_variant_dump(gr->json, arg_json_format_flags, NULL, NULL);
5✔
572
                break;
5✔
573

574
        case OUTPUT_FRIENDLY:
19✔
575
                group_record_show(gr, true);
19✔
576

577
                if (gr->incomplete) {
19✔
578
                        fflush(stdout);
×
579
                        log_warning("Warning: lacking rights to acquire privileged fields of group record of '%s', output incomplete.", gr->group_name);
×
580
                }
581

582
                break;
583

584
        case OUTPUT_TABLE: {
288✔
585
                UserDisposition d;
288✔
586

587
                assert(table);
288✔
588
                d = group_record_disposition(gr);
288✔
589

590
                r = table_add_many(
288✔
591
                                table,
592
                                TABLE_STRING, "",
593
                                TABLE_STRING, gr->group_name,
594
                                TABLE_SET_COLOR, user_disposition_to_color(d),
595
                                TABLE_STRING, user_disposition_to_string(d),
596
                                TABLE_GID, gr->gid,
597
                                TABLE_STRING, gr->description,
598
                                TABLE_INT, 0);
599
                if (r < 0)
288✔
600
                        return table_log_add_error(r);
×
601

602
                break;
603
        }
604

605
        default:
×
606
                assert_not_reached();
×
607
        }
608

609
        return 0;
610
}
611

612
static int table_add_gid_boundaries(Table *table, const UIDRange *p) {
9✔
613
        int r, n_added = 0;
9✔
614

615
        assert(table);
9✔
616

617
        FOREACH_ELEMENT(i, uid_range_table) {
72✔
618
                _cleanup_free_ char *name = NULL, *comment = NULL;
29✔
619

620
                if (!BIT_SET(arg_disposition_mask, i->disposition))
63✔
621
                        continue;
28✔
622

623
                if (!uid_range_covers(p, i->first, i->last - i->first + 1))
35✔
624
                        continue;
×
625

626
                if (i->test && !i->test())
35✔
627
                        continue;
6✔
628

629
                name = strjoin(glyph(GLYPH_ARROW_DOWN),
29✔
630
                               " begin ", i->name, " groups ",
631
                               glyph(GLYPH_ARROW_DOWN));
632
                if (!name)
29✔
633
                        return log_oom();
×
634

635
                comment = strjoin("First ", i->name, " group");
29✔
636
                if (!comment)
29✔
637
                        return log_oom();
×
638

639
                r = table_add_many(
29✔
640
                                table,
641
                                TABLE_STRING, glyph(GLYPH_TREE_TOP),
642
                                TABLE_STRING, name,
643
                                TABLE_SET_COLOR, ansi_grey(),
644
                                TABLE_STRING, user_disposition_to_string(i->disposition),
645
                                TABLE_SET_COLOR, ansi_grey(),
646
                                TABLE_GID, i->first,
647
                                TABLE_SET_COLOR, ansi_grey(),
648
                                TABLE_STRING, comment,
649
                                TABLE_SET_COLOR, ansi_grey(),
650
                                TABLE_INT, -1); /* sort before any other entry with the same GID */
651
                if (r < 0)
29✔
652
                        return table_log_add_error(r);
×
653

654
                free(name);
29✔
655
                name = strjoin(glyph(GLYPH_ARROW_UP),
29✔
656
                               " end ", i->name, " groups ",
657
                               glyph(GLYPH_ARROW_UP));
658
                if (!name)
29✔
659
                        return log_oom();
×
660

661
                free(comment);
29✔
662
                comment = strjoin("Last ", i->name, " group");
29✔
663
                if (!comment)
29✔
664
                        return log_oom();
×
665

666
                r = table_add_many(
29✔
667
                                table,
668
                                TABLE_STRING, glyph(GLYPH_TREE_RIGHT),
669
                                TABLE_STRING, name,
670
                                TABLE_SET_COLOR, ansi_grey(),
671
                                TABLE_STRING, user_disposition_to_string(i->disposition),
672
                                TABLE_SET_COLOR, ansi_grey(),
673
                                TABLE_GID, i->last,
674
                                TABLE_SET_COLOR, ansi_grey(),
675
                                TABLE_STRING, comment,
676
                                TABLE_SET_COLOR, ansi_grey(),
677
                                TABLE_INT, 1); /* sort after any other entry with the same GID */
678
                if (r < 0)
29✔
679
                        return table_log_add_error(r);
×
680

681
                n_added += 2;
29✔
682
        }
683

684
        return n_added;
685
}
686

687
static int add_unavailable_gid(Table *table, uid_t start, uid_t end) {
×
688
        _cleanup_free_ char *name = NULL;
×
689
        int r;
×
690

691
        assert(table);
×
692
        assert(start <= end);
×
693

694
        name = strjoin(glyph(GLYPH_ARROW_DOWN),
×
695
                       " begin unavailable groups ",
696
                       glyph(GLYPH_ARROW_DOWN));
697
        if (!name)
×
698
                return log_oom();
×
699

700
        r = table_add_many(
×
701
                        table,
702
                        TABLE_STRING, glyph(GLYPH_TREE_TOP),
703
                        TABLE_STRING, name,
704
                        TABLE_SET_COLOR, ansi_grey(),
705
                        TABLE_EMPTY,
706
                        TABLE_GID, start,
707
                        TABLE_SET_COLOR, ansi_grey(),
708
                        TABLE_STRING, "First unavailable group",
709
                        TABLE_SET_COLOR, ansi_grey(),
710
                        TABLE_INT, -1); /* sort before any other entry with the same GID */
711
        if (r < 0)
×
712
                return table_log_add_error(r);
×
713

714
        free(name);
×
715
        name = strjoin(glyph(GLYPH_ARROW_UP),
×
716
                       " end unavailable groups ",
717
                       glyph(GLYPH_ARROW_UP));
718
        if (!name)
×
719
                return log_oom();
×
720

721
        r = table_add_many(
×
722
                        table,
723
                        TABLE_STRING, glyph(GLYPH_TREE_RIGHT),
724
                        TABLE_STRING, name,
725
                        TABLE_SET_COLOR, ansi_grey(),
726
                        TABLE_EMPTY,
727
                        TABLE_GID, end,
728
                        TABLE_SET_COLOR, ansi_grey(),
729
                        TABLE_STRING, "Last unavailable group",
730
                        TABLE_SET_COLOR, ansi_grey(),
731
                        TABLE_INT, 1); /* sort after any other entry with the same GID */
732
        if (r < 0)
×
733
                return table_log_add_error(r);
×
734

735
        return 2;
736
}
737

738
static int display_group(int argc, char *argv[], void *userdata) {
36✔
739
        _cleanup_(table_unrefp) Table *table = NULL;
36✔
740
        bool draw_separator = false;
36✔
741
        int ret = 0, r;
36✔
742

743
        if (arg_output < 0)
36✔
744
                arg_output = arg_from_file || (argc > 1 && !arg_fuzzy) ? OUTPUT_FRIENDLY : OUTPUT_TABLE;
42✔
745

746
        if (arg_output == OUTPUT_TABLE) {
36✔
747
                table = table_new(" ", "name", "disposition", "gid", "description", "order");
10✔
748
                if (!table)
10✔
749
                        return log_oom();
×
750

751
                (void) table_set_align_percent(table, table_get_cell(table, 0, 3), 100);
10✔
752
                table_set_ersatz_string(table, TABLE_ERSATZ_DASH);
10✔
753
                (void) table_set_sort(table, (size_t) 3, (size_t) 5);
10✔
754
                (void) table_hide_column_from_display(table, (size_t) 5);
10✔
755
                if (!arg_boundaries)
10✔
756
                        (void) table_hide_column_from_display(table, (size_t) 0);
1✔
757
        }
758

759
        _cleanup_(userdb_match_done) UserDBMatch match = {
36✔
760
                .disposition_mask = arg_disposition_mask,
761
                .gid_min = arg_uid_min,
762
                .gid_max = arg_uid_max,
763
        };
764

765
        if (arg_from_file) {
36✔
766
                if (argc > 1)
3✔
767
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No argument expected when invoked with --from-file=, refusing.");
×
768

769
                _cleanup_(group_record_unrefp) GroupRecord *gr = group_record_new();
6✔
770
                if (!gr)
3✔
771
                        return log_oom();
×
772

773
                r = group_record_load(gr, arg_from_file, USER_RECORD_LOAD_MASK_SECRET|USER_RECORD_LOG);
3✔
774
                if (r < 0)
3✔
775
                        return r;
776

777
                r = show_group(gr, table);
3✔
778
                if (r < 0)
3✔
779
                        return r;
780

781
        } else if (argc > 1 && !arg_fuzzy)
33✔
782
                STRV_FOREACH(i, argv + 1) {
56✔
783
                        _cleanup_(group_record_unrefp) GroupRecord *gr = NULL;
33✔
784

785
                        r = groupdb_by_name(*i, &match, arg_userdb_flags|USERDB_PARSE_NUMERIC, &gr);
33✔
786
                        if (r < 0) {
33✔
787
                                if (r == -ESRCH)
12✔
788
                                        log_error_errno(r, "Group %s does not exist.", *i);
10✔
789
                                else if (r == -EHOSTDOWN)
2✔
790
                                        log_error_errno(r, "Selected group database service is not available for this request.");
×
791
                                else if (r == -ENOEXEC)
2✔
792
                                        log_error_errno(r, "Group '%s' exists but does not match specified filter.", *i);
×
793
                                else
794
                                        log_error_errno(r, "Failed to find group %s: %m", *i);
2✔
795

796
                                RET_GATHER(ret, r);
12✔
797
                        } else {
798
                                if (draw_separator && arg_output == OUTPUT_FRIENDLY)
21✔
799
                                        putchar('\n');
4✔
800

801
                                r = show_group(gr, table);
21✔
802
                                if (r < 0)
21✔
803
                                        return r;
×
804

805
                                draw_separator = true;
806
                        }
807
                }
808
        else {
809
                if (argc > 1) {
1✔
810
                        match.fuzzy_names = strv_copy(strv_skip(argv, 1));
1✔
811
                        if (!match.fuzzy_names)
1✔
812
                                return log_oom();
×
813
                }
814

815
                _cleanup_(userdb_iterator_freep) UserDBIterator *iterator = NULL;
×
816
                r = groupdb_all(&match, arg_userdb_flags, &iterator);
10✔
817
                if (r == -ENOLINK)
10✔
818
                        log_debug_errno(r, "No entries found. (Didn't check via Varlink.)");
×
819
                else if (r == -ESRCH)
10✔
820
                        log_debug_errno(r, "No entries found.");
10✔
821
                else if (r < 0)
10✔
822
                        return log_error_errno(r, "Failed to enumerate groups: %m");
×
823
                else {
824
                        for (;;) {
288✔
825
                                _cleanup_(group_record_unrefp) GroupRecord *gr = NULL;
10✔
826

827
                                r = groupdb_iterator_get(iterator, &match, &gr);
298✔
828
                                if (r == -ESRCH)
298✔
829
                                        break;
830
                                if (r == -EHOSTDOWN)
288✔
831
                                        return log_error_errno(r, "Selected group database service is not available for this request.");
×
832
                                if (r < 0)
288✔
833
                                        return log_error_errno(r, "Failed to acquire next group: %m");
×
834

835
                                if (draw_separator && arg_output == OUTPUT_FRIENDLY)
288✔
836
                                        putchar('\n');
×
837

838
                                r = show_group(gr, table);
288✔
839
                                if (r < 0)
288✔
840
                                        return r;
841

842
                                draw_separator = true;
288✔
843
                        }
844
                }
845
        }
846

847
        if (table) {
36✔
848
                int boundary_lines = 0, gid_map_lines = 0;
10✔
849

850
                if (arg_boundaries) {
10✔
851
                        _cleanup_(uid_range_freep) UIDRange *gid_range = NULL;
9✔
852
                        r = uid_range_load_userns(/* path = */ NULL, GID_RANGE_USERNS_INSIDE, &gid_range);
9✔
853
                        if (r < 0)
9✔
854
                                log_debug_errno(r, "Failed to load /proc/self/gid_map, ignoring: %m");
×
855

856
                        boundary_lines = table_add_gid_boundaries(table, gid_range);
9✔
857
                        if (boundary_lines < 0)
9✔
858
                                return boundary_lines;
859

860
                        gid_map_lines = table_add_uid_map(table, gid_range, add_unavailable_gid);
9✔
861
                        if (gid_map_lines < 0)
9✔
862
                                return gid_map_lines;
863
                }
864

865
                if (!table_isempty(table)) {
20✔
866
                        r = table_print_with_pager(table, arg_json_format_flags, arg_pager_flags, arg_legend);
10✔
867
                        if (r < 0)
10✔
868
                                return r;
869
                }
870

871
                if (arg_legend) {
10✔
872
                        size_t k;
9✔
873

874
                        k = table_get_rows(table) - 1 - boundary_lines - gid_map_lines;
9✔
875
                        if (k > 0)
9✔
876
                                printf("\n%zu groups listed.\n", k);
7✔
877
                        else
878
                                printf("No groups.\n");
2✔
879
                }
880
        }
881

882
        return ret;
883
}
884

885
static int show_membership(const char *user, const char *group, Table *table) {
14✔
886
        int r;
14✔
887

888
        assert(user);
14✔
889
        assert(group);
14✔
890

891
        switch (arg_output) {
14✔
892

893
        case OUTPUT_CLASSIC:
×
894
                /* Strictly speaking there's no 'classic' output for this concept, but let's output it in
895
                 * similar style to the classic output for user/group info */
896

897
                printf("%s:%s\n", user, group);
×
898
                break;
×
899

900
        case OUTPUT_JSON: {
2✔
901
                _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
2✔
902

903
                r = sd_json_buildo(
2✔
904
                                &v,
905
                                SD_JSON_BUILD_PAIR("user", SD_JSON_BUILD_STRING(user)),
906
                                SD_JSON_BUILD_PAIR("group", SD_JSON_BUILD_STRING(group)));
907
                if (r < 0)
2✔
908
                        return log_error_errno(r, "Failed to build JSON object: %m");
×
909

910
                sd_json_variant_dump(v, arg_json_format_flags, NULL, NULL);
2✔
911
                break;
2✔
912
        }
913

914
        case OUTPUT_FRIENDLY:
×
915
                /* Hmm, this is not particularly friendly, but not sure how we could do this better */
916
                printf("%s: %s\n", group, user);
×
917
                break;
×
918

919
        case OUTPUT_TABLE:
12✔
920
                assert(table);
12✔
921

922
                r = table_add_many(
12✔
923
                                table,
924
                                TABLE_STRING, user,
925
                                TABLE_STRING, group);
926
                if (r < 0)
12✔
927
                        return table_log_add_error(r);
×
928

929
                break;
930

931
        default:
×
932
                assert_not_reached();
×
933
        }
934

935
        return 0;
936
}
937

938
static int display_memberships(int argc, char *argv[], void *userdata) {
14✔
939
        _cleanup_(table_unrefp) Table *table = NULL;
14✔
940
        int ret = 0, r;
14✔
941

942
        if (arg_from_file)
14✔
943
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--from-file= not supported when showing memberships, refusing.");
×
944

945
        if (arg_output < 0)
14✔
946
                arg_output = OUTPUT_TABLE;
12✔
947

948
        if (arg_output == OUTPUT_TABLE) {
14✔
949
                table = table_new("user", "group");
12✔
950
                if (!table)
12✔
951
                        return log_oom();
×
952

953
                (void) table_set_sort(table, (size_t) 0, (size_t) 1);
12✔
954
        }
955

956
        if (argc > 1)
14✔
957
                STRV_FOREACH(i, argv + 1) {
26✔
958
                        _cleanup_(userdb_iterator_freep) UserDBIterator *iterator = NULL;
4✔
959

960
                        if (streq(argv[0], "users-in-group")) {
18✔
961
                                r = membershipdb_by_group(*i, arg_userdb_flags, &iterator);
9✔
962
                                if (r < 0)
9✔
963
                                        return log_error_errno(r, "Failed to enumerate users in group: %m");
2✔
964
                        } else if (streq(argv[0], "groups-of-user")) {
9✔
965
                                r = membershipdb_by_user(*i, arg_userdb_flags, &iterator);
9✔
966
                                if (r < 0)
9✔
967
                                        return log_error_errno(r, "Failed to enumerate groups of user: %m");
2✔
968
                        } else
969
                                assert_not_reached();
×
970

971
                        for (;;) {
22✔
972
                                _cleanup_free_ char *user = NULL, *group = NULL;
18✔
973

974
                                r = membershipdb_iterator_get(iterator, &user, &group);
18✔
975
                                if (r == -ESRCH)
18✔
976
                                        break;
977
                                if (r == -EHOSTDOWN)
4✔
978
                                        return log_error_errno(r, "Selected membership database service is not available for this request.");
×
979
                                if (r < 0)
4✔
980
                                        return log_error_errno(r, "Failed to acquire next membership: %m");
×
981

982
                                r = show_membership(user, group, table);
4✔
983
                                if (r < 0)
4✔
984
                                        return r;
985
                        }
986
                }
987
        else {
988
                _cleanup_(userdb_iterator_freep) UserDBIterator *iterator = NULL;
×
989

990
                r = membershipdb_all(arg_userdb_flags, &iterator);
2✔
991
                if (r == -ENOLINK)
2✔
992
                        log_debug_errno(r, "No entries found. (Didn't check via Varlink.)");
×
993
                else if (r == -ESRCH)
2✔
994
                        log_debug_errno(r, "No entries found.");
2✔
995
                else if (r < 0)
2✔
996
                        return log_error_errno(r, "Failed to enumerate memberships: %m");
×
997
                else {
998
                        for (;;) {
22✔
999
                                _cleanup_free_ char *user = NULL, *group = NULL;
12✔
1000

1001
                                r = membershipdb_iterator_get(iterator, &user, &group);
12✔
1002
                                if (r == -ESRCH)
12✔
1003
                                        break;
1004
                                if (r == -EHOSTDOWN)
10✔
1005
                                        return log_error_errno(r, "Selected membership database service is not available for this request.");
×
1006
                                if (r < 0)
10✔
1007
                                        return log_error_errno(r, "Failed to acquire next membership: %m");
×
1008

1009
                                r = show_membership(user, group, table);
10✔
1010
                                if (r < 0)
10✔
1011
                                        return r;
1012
                        }
1013
                }
1014
        }
1015

1016
        if (table) {
10✔
1017
                if (!table_isempty(table)) {
8✔
1018
                        r = table_print_with_pager(table, arg_json_format_flags, arg_pager_flags, arg_legend);
4✔
1019
                        if (r < 0)
4✔
1020
                                return r;
1021
                }
1022

1023
                if (arg_legend) {
8✔
1024
                        if (table_isempty(table))
16✔
1025
                                printf("No memberships.\n");
4✔
1026
                        else
1027
                                printf("\n%zu memberships listed.\n", table_get_rows(table) - 1);
4✔
1028
                }
1029
        }
1030

1031
        return ret;
1032
}
1033

1034
static int display_services(int argc, char *argv[], void *userdata) {
2✔
1035
        _cleanup_(table_unrefp) Table *t = NULL;
×
1036
        _cleanup_closedir_ DIR *d = NULL;
2✔
1037
        int r;
2✔
1038

1039
        if (arg_from_file)
2✔
1040
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--from-file= not supported when showing services, refusing.");
×
1041

1042
        d = opendir("/run/systemd/userdb/");
2✔
1043
        if (!d) {
2✔
1044
                if (errno == ENOENT) {
×
1045
                        log_info("No services.");
×
1046
                        return 0;
×
1047
                }
1048

1049
                return log_error_errno(errno, "Failed to open %s: %m", "/run/systemd/userdb/");
×
1050
        }
1051

1052
        t = table_new("service", "listening");
2✔
1053
        if (!t)
2✔
1054
                return log_oom();
×
1055

1056
        (void) table_set_sort(t, (size_t) 0);
2✔
1057

1058
        FOREACH_DIRENT(de, d, return -errno) {
18✔
1059
                _cleanup_free_ char *j = NULL, *no = NULL;
12✔
1060
                _cleanup_close_ int fd = -EBADF;
12✔
1061

1062
                j = path_join("/run/systemd/userdb/", de->d_name);
12✔
1063
                if (!j)
12✔
1064
                        return log_oom();
×
1065

1066
                fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
12✔
1067
                if (fd < 0)
12✔
1068
                        return log_error_errno(errno, "Failed to allocate AF_UNIX/SOCK_STREAM socket: %m");
×
1069

1070
                r = connect_unix_path(fd, dirfd(d), de->d_name);
12✔
1071
                if (r < 0) {
12✔
1072
                        no = strjoin("No (", ERRNO_NAME(r), ")");
×
1073
                        if (!no)
×
1074
                                return log_oom();
×
1075
                }
1076

1077
                r = table_add_many(t,
24✔
1078
                                   TABLE_STRING, de->d_name,
1079
                                   TABLE_STRING, no ?: "yes",
1080
                                   TABLE_SET_COLOR, ansi_highlight_green_red(!no));
1081
                if (r < 0)
12✔
1082
                        return table_log_add_error(r);
×
1083
        }
1084

1085
        if (!table_isempty(t)) {
4✔
1086
                r = table_print_with_pager(t, arg_json_format_flags, arg_pager_flags, arg_legend);
2✔
1087
                if (r < 0)
2✔
1088
                        return r;
1089
        }
1090

1091
        if (arg_legend && arg_output != OUTPUT_JSON) {
2✔
1092
                if (table_isempty(t))
2✔
1093
                        printf("No services.\n");
×
1094
                else
1095
                        printf("\n%zu services listed.\n", table_get_rows(t) - 1);
1✔
1096
        }
1097

1098
        return 0;
1099
}
1100

1101
static int ssh_authorized_keys(int argc, char *argv[], void *userdata) {
10✔
1102
        _cleanup_(user_record_unrefp) UserRecord *ur = NULL;
×
1103
        char **chain_invocation;
10✔
1104
        int r;
10✔
1105

1106
        assert(argc >= 2);
10✔
1107

1108
        if (arg_from_file)
10✔
1109
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--from-file= not supported when showing SSH authorized keys, refusing.");
×
1110

1111
        if (arg_chain) {
10✔
1112
                /* If --chain is specified, the rest of the command line is the chain command */
1113

1114
                if (argc < 3)
4✔
1115
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1✔
1116
                                               "No chain command line specified, refusing.");
1117

1118
                /* Make similar restrictions on the chain command as OpenSSH itself makes on the primary command. */
1119
                if (!path_is_absolute(argv[2]))
3✔
1120
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1✔
1121
                                               "Chain invocation of ssh-authorized-keys commands requires an absolute binary path argument.");
1122

1123
                if (!path_is_normalized(argv[2]))
2✔
1124
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
1125
                                               "Chain invocation of ssh-authorized-keys commands requires an normalized binary path argument.");
1126

1127
                chain_invocation = argv + 2;
2✔
1128
        } else {
1129
                /* If --chain is not specified, then refuse any further arguments */
1130

1131
                if (argc > 2)
6✔
1132
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Too many arguments.");
×
1133

1134
                chain_invocation = NULL;
1135
        }
1136

1137
        r = userdb_by_name(argv[1], /* match= */ NULL, arg_userdb_flags, &ur);
8✔
1138
        if (r == -ESRCH)
8✔
1139
                log_error_errno(r, "User %s does not exist.", argv[1]);
2✔
1140
        else if (r == -EHOSTDOWN)
6✔
1141
                log_error_errno(r, "Selected user database service is not available for this request.");
×
1142
        else if (r == -EINVAL)
6✔
1143
                log_error_errno(r, "Failed to find user %s: %m (Invalid user name?)", argv[1]);
×
1144
        else if (r < 0)
6✔
1145
                log_error_errno(r, "Failed to find user %s: %m", argv[1]);
×
1146
        else {
1147
                if (strv_isempty(ur->ssh_authorized_keys))
6✔
1148
                        log_debug("User record for %s has no public SSH keys.", argv[1]);
×
1149
                else
1150
                        STRV_FOREACH(i, ur->ssh_authorized_keys)
14✔
1151
                                printf("%s\n", *i);
8✔
1152

1153
                if (ur->incomplete) {
6✔
1154
                        fflush(stdout);
×
1155
                        log_warning("Warning: lacking rights to acquire privileged fields of user record of '%s', output incomplete.", ur->user_name);
×
1156
                }
1157
        }
1158

1159
        if (chain_invocation) {
8✔
1160
                if (DEBUG_LOGGING) {
2✔
1161
                        _cleanup_free_ char *s = NULL;
1✔
1162

1163
                        s = quote_command_line(chain_invocation, SHELL_ESCAPE_EMPTY);
1✔
1164
                        if (!s)
1✔
1165
                                return log_oom();
×
1166

1167
                        log_debug("Chain invoking: %s", s);
1✔
1168
                }
1169

1170
                fflush(stdout);
2✔
1171
                execv(chain_invocation[0], chain_invocation);
×
1172
                if (errno == ENOENT) /* Let's handle ENOENT gracefully */
×
1173
                        log_warning_errno(errno, "Chain executable '%s' does not exist, ignoring chain invocation.", chain_invocation[0]);
8✔
1174
                else {
1175
                        log_error_errno(errno, "Failed to invoke chain executable '%s': %m", chain_invocation[0]);
×
1176
                        if (r >= 0)
×
1177
                                r = -errno;
×
1178
                }
1179
        }
1180

1181
        return r;
1182
}
1183

1184
static int load_credential_one(
236✔
1185
                int credential_dir_fd,
1186
                const char *name,
1187
                int *userdb_dir_persist_fd,
1188
                int *userdb_dir_transient_fd) {
1189

1190
        int r;
236✔
1191

1192
        assert(credential_dir_fd >= 0);
236✔
1193
        assert(name);
236✔
1194
        assert(userdb_dir_persist_fd);
236✔
1195
        assert(userdb_dir_transient_fd);
236✔
1196

1197
        const char *suffix = startswith(name, "userdb.");
236✔
1198
        if (!suffix)
236✔
1199
                return 0;
236✔
1200

1201
        const char *transient = startswith(suffix, "transient."),
236✔
1202
                *user = startswith(transient ?: suffix, "user."),
472✔
1203
                *group = startswith(transient ?: suffix, "group.");
236✔
1204
        if (!user && !group)
236✔
1205
                return 0;
1206

1207
        const char *userdb_dir = transient ? "/run/userdb" : "/etc/userdb";
236✔
1208

1209
        int *userdb_dir_fd = transient ? userdb_dir_transient_fd : userdb_dir_persist_fd;
236✔
1210
        if (*userdb_dir_fd == -EBADF) {
236✔
1211
                *userdb_dir_fd = xopenat_full(AT_FDCWD, userdb_dir,
118✔
1212
                                              /* open_flags= */ O_DIRECTORY|O_CREAT|O_CLOEXEC,
1213
                                              /* xopen_flags= */ XO_LABEL,
1214
                                              /* mode= */ 0755);
1215
                if (*userdb_dir_fd < 0)
118✔
NEW
1216
                        return log_error_errno(*userdb_dir_fd, "Failed to open '%s/': %m", userdb_dir);
×
1217
        } else if (*userdb_dir_fd < 0)
118✔
NEW
1218
                return log_debug_errno(*userdb_dir_fd, "Previous attempt to open '%s/' failed, skipping.", userdb_dir);
×
1219

1220
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
236✔
1221
        unsigned line = 0, column = 0;
236✔
1222
        r = sd_json_parse_file_at(NULL, credential_dir_fd, name, SD_JSON_PARSE_SENSITIVE, &v, &line, &column);
236✔
1223
        if (r < 0)
236✔
1224
                return log_error_errno(r, "Failed to parse credential '%s' as JSON at %u:%u: %m", name, line, column);
×
1225

1226
        _cleanup_(user_record_unrefp) UserRecord *ur = NULL, *ur_stripped = NULL, *ur_privileged = NULL;
236✔
1227
        _cleanup_(group_record_unrefp) GroupRecord *gr = NULL, *gr_stripped = NULL, *gr_privileged = NULL;
236✔
1228
        _cleanup_free_ char *fn = NULL, *link = NULL;
236✔
1229

1230
        if (user) {
236✔
1231
                ur = user_record_new();
118✔
1232
                if (!ur)
118✔
1233
                        return log_oom();
14✔
1234

1235
                r = user_record_load(ur, v, USER_RECORD_LOAD_MASK_SECRET|USER_RECORD_LOG);
118✔
1236
                if (r < 0)
118✔
1237
                        return r;
1238

1239
                if (user_record_is_root(ur))
118✔
1240
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Creating 'root' user from credentials is not supported.");
×
1241
                if (user_record_is_nobody(ur))
118✔
1242
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Creating 'nobody' user from credentials is not supported.");
×
1243

1244
                if (!streq_ptr(user, ur->user_name))
118✔
1245
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
1246
                                               "Credential suffix '%s' does not match user record name '%s'",
1247
                                               user, strna(ur->user_name));
1248

1249
                if (!uid_is_valid(ur->uid))
118✔
1250
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "JSON user record missing uid field");
×
1251

1252
                if (!gid_is_valid(user_record_gid(ur)))
118✔
1253
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "JSON user record missing gid field");
×
1254

1255
                _cleanup_(user_record_unrefp) UserRecord *m = NULL;
118✔
1256
                r = userdb_by_name(ur->user_name, /* match= */ NULL, USERDB_SUPPRESS_SHADOW, &m);
118✔
1257
                if (r >= 0) {
118✔
1258
                        if (m->uid != ur->uid)
14✔
1259
                                return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
×
1260
                                                       "Cannot create user %s from credential %s as it already exists with UID " UID_FMT " instead of " UID_FMT,
1261
                                                       ur->user_name, name, m->uid, ur->uid);
1262

1263
                        log_info("User with name %s and UID " UID_FMT " already exists, not creating user from credential %s", ur->user_name, ur->uid, name);
14✔
1264
                        return 0;
14✔
1265
                }
1266
                if (r != -ESRCH)
104✔
1267
                        return log_error_errno(r, "Failed to check if user with name %s already exists: %m", ur->user_name);
×
1268

1269
                m = user_record_unref(m);
104✔
1270
                r = userdb_by_uid(ur->uid, /* match= */ NULL, USERDB_SUPPRESS_SHADOW, &m);
104✔
1271
                if (r >= 0) {
104✔
1272
                        if (!streq_ptr(ur->user_name, m->user_name))
×
1273
                                return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
×
1274
                                                       "Cannot create user %s from credential %s as UID " UID_FMT " is already assigned to user %s",
1275
                                                       ur->user_name, name, ur->uid, m->user_name);
1276

1277
                        log_info("User with name %s and UID " UID_FMT " already exists, not creating user from credential %s", ur->user_name, ur->uid, name);
×
1278
                        return 0;
×
1279
                }
1280
                if (r != -ESRCH)
104✔
1281
                        return log_error_errno(r, "Failed to check if user with UID " UID_FMT " already exists: %m", ur->uid);
×
1282

1283
                r = user_record_clone(ur, USER_RECORD_LOAD_MASK_PRIVILEGED|USER_RECORD_LOG, &ur_stripped);
104✔
1284
                if (r < 0)
104✔
1285
                        return r;
1286

1287
                r = user_record_clone(ur, USER_RECORD_EXTRACT_PRIVILEGED|USER_RECORD_EMPTY_OK|USER_RECORD_LOG, &ur_privileged);
104✔
1288
                if (r < 0)
104✔
1289
                        return r;
1290

1291
                fn = strjoin(ur->user_name, ".user");
104✔
1292
                if (!fn)
104✔
1293
                        return log_oom();
×
1294

1295
                if (asprintf(&link, UID_FMT ".user", ur->uid) < 0)
104✔
1296
                        return log_oom();
×
1297
        } else {
1298
                assert(group);
118✔
1299

1300
                gr = group_record_new();
118✔
1301
                if (!gr)
118✔
1302
                        return log_oom();
14✔
1303

1304
                r = group_record_load(gr, v, USER_RECORD_LOAD_MASK_SECRET|USER_RECORD_LOG);
118✔
1305
                if (r < 0)
118✔
1306
                        return r;
1307

1308
                if (group_record_is_root(gr))
118✔
1309
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Creating 'root' group from credentials is not supported.");
×
1310
                if (group_record_is_nobody(gr))
118✔
1311
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Creating 'nobody' group from credentials is not supported.");
×
1312

1313
                if (!streq_ptr(group, gr->group_name))
118✔
1314
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
1315
                                               "Credential suffix '%s' does not match group record name '%s'",
1316
                                               group, strna(gr->group_name));
1317

1318
                if (!gid_is_valid(gr->gid))
118✔
1319
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "JSON group record missing gid field");
×
1320

1321
                _cleanup_(group_record_unrefp) GroupRecord *m = NULL;
118✔
1322
                r = groupdb_by_name(gr->group_name, /* match= */ NULL, USERDB_SUPPRESS_SHADOW, &m);
118✔
1323
                if (r >= 0) {
118✔
1324
                        if (m->gid != gr->gid)
14✔
1325
                                return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
×
1326
                                                       "Cannot create group %s from credential %s as it already exists with GID " GID_FMT " instead of " GID_FMT,
1327
                                                       gr->group_name, name, m->gid, gr->gid);
1328

1329
                        log_info("Group with name %s and GID " GID_FMT " already exists, not creating group from credential %s", gr->group_name, gr->gid, name);
14✔
1330
                        return 0;
14✔
1331
                }
1332
                if (r != -ESRCH)
104✔
1333
                        return log_error_errno(r, "Failed to check if group with name %s already exists: %m", gr->group_name);
×
1334

1335
                m = group_record_unref(m);
104✔
1336
                r = groupdb_by_gid(gr->gid, /* match= */ NULL, USERDB_SUPPRESS_SHADOW, &m);
104✔
1337
                if (r >= 0) {
104✔
1338
                        if (!streq_ptr(gr->group_name, m->group_name))
×
1339
                                return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
×
1340
                                                       "Cannot create group %s from credential %s as GID " GID_FMT " is already assigned to group %s",
1341
                                                       gr->group_name, name, gr->gid, m->group_name);
1342

1343
                        log_info("Group with name %s and GID " GID_FMT " already exists, not creating group from credential %s", gr->group_name, gr->gid, name);
×
1344
                        return 0;
×
1345
                }
1346
                if (r != -ESRCH)
104✔
1347
                        return log_error_errno(r, "Failed to check if group with GID " GID_FMT " already exists: %m", gr->gid);
×
1348

1349
                r = group_record_clone(gr, USER_RECORD_LOAD_MASK_PRIVILEGED|USER_RECORD_LOG, &gr_stripped);
104✔
1350
                if (r < 0)
104✔
1351
                        return r;
1352

1353
                r = group_record_clone(gr, USER_RECORD_EXTRACT_PRIVILEGED|USER_RECORD_EMPTY_OK|USER_RECORD_LOG, &gr_privileged);
104✔
1354
                if (r < 0)
104✔
1355
                        return r;
1356

1357
                fn = strjoin(gr->group_name, ".group");
104✔
1358
                if (!fn)
104✔
1359
                        return log_oom();
×
1360

1361
                if (asprintf(&link, GID_FMT ".group", gr->gid) < 0)
104✔
1362
                        return log_oom();
×
1363
        }
1364

1365
        if (!filename_is_valid(fn))
208✔
1366
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
1367
                                       "Passed credential '%s' would result in invalid filename '%s'.",
1368
                                       name, fn);
1369

1370
        _cleanup_free_ char *formatted = NULL;
208✔
1371
        r = sd_json_variant_format(ur ? ur_stripped->json : gr_stripped->json, SD_JSON_FORMAT_NEWLINE, &formatted);
208✔
1372
        if (r < 0)
208✔
1373
                return log_error_errno(r, "Failed to format JSON record: %m");
×
1374

1375
        r = write_string_file_at(*userdb_dir_fd, fn, formatted, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
208✔
1376
        if (r < 0)
208✔
1377
                return log_error_errno(r, "Failed to write JSON record to %s/%s: %m", userdb_dir, fn);
×
1378

1379
        if (symlinkat(fn, *userdb_dir_fd, link) < 0)
208✔
1380
                return log_error_errno(errno, "Failed to create symlink from %s to %s: %m", link, fn);
×
1381

1382
        log_info("Installed %s/%s from credential.", userdb_dir, fn);
208✔
1383

1384
        if ((ur && !sd_json_variant_is_blank_object(ur_privileged->json)) ||
208✔
1385
            (gr && !sd_json_variant_is_blank_object(gr_privileged->json))) {
104✔
1386
                fn = mfree(fn);
104✔
1387
                fn = strjoin(ur ? ur->user_name : gr->group_name, ur ? ".user-privileged" : ".group-privileged");
104✔
1388
                if (!fn)
104✔
1389
                        return log_oom();
×
1390

1391
                formatted = mfree(formatted);
104✔
1392
                r = sd_json_variant_format(ur ? ur_privileged->json : gr_privileged->json, SD_JSON_FORMAT_NEWLINE, &formatted);
104✔
1393
                if (r < 0)
104✔
1394
                        return log_error_errno(r, "Failed to format JSON record: %m");
×
1395

1396
                r = write_string_file_at(*userdb_dir_fd, fn, formatted, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC|WRITE_STRING_FILE_MODE_0600);
104✔
1397
                if (r < 0)
104✔
1398
                        return log_error_errno(r, "Failed to write JSON record to %s/%s: %m", userdb_dir, fn);
×
1399

1400
                link = mfree(link);
104✔
1401

1402
                if (ur) {
104✔
1403
                        if (asprintf(&link, UID_FMT ".user-privileged", ur->uid) < 0)
104✔
1404
                                return log_oom();
×
1405
                } else {
1406
                        if (asprintf(&link, GID_FMT ".group-privileged", gr->gid) < 0)
×
1407
                                return log_oom();
×
1408
                }
1409

1410
                if (symlinkat(fn, *userdb_dir_fd, link) < 0)
104✔
1411
                        return log_error_errno(errno, "Failed to create symlink from %s to %s: %m", link, fn);
×
1412

1413
                log_info("Installed %s/%s from credential.", userdb_dir, fn);
104✔
1414
        }
1415

1416
        if (ur)
208✔
1417
                STRV_FOREACH(g, ur->member_of) {
312✔
1418
                        _cleanup_free_ char *membership = strjoin(ur->user_name, ":", *g);
416✔
1419
                        if (!membership)
208✔
1420
                                return log_oom();
×
1421

1422
                        _cleanup_close_ int fd = openat(*userdb_dir_fd, membership, O_WRONLY|O_CREAT|O_CLOEXEC, 0644);
416✔
1423
                        if (fd < 0)
208✔
1424
                                return log_error_errno(errno, "Failed to create %s: %m", membership);
×
1425

1426
                        log_info("Installed %s/%s from credential.", userdb_dir, membership);
208✔
1427
                }
1428
        else
1429
                STRV_FOREACH(u, gr->members) {
104✔
1430
                        _cleanup_free_ char *membership = strjoin(*u, ":", gr->group_name);
×
1431
                        if (!membership)
×
1432
                                return log_oom();
×
1433

NEW
1434
                        _cleanup_close_ int fd = openat(*userdb_dir_fd, membership, O_WRONLY|O_CREAT|O_CLOEXEC, 0644);
×
1435
                        if (fd < 0)
×
1436
                                return log_error_errno(errno, "Failed to create %s: %m", membership);
×
1437

1438
                        log_info("Installed %s/%s from credential.", userdb_dir, membership);
×
1439
                }
1440

1441
        if (ur && user_record_disposition(ur) == USER_REGULAR) {
208✔
1442
                const char *hd = user_record_home_directory(ur);
104✔
1443

1444
                r = RET_NERRNO(access(hd, F_OK));
312✔
1445
                if (r < 0) {
104✔
1446
                        if (r != -ENOENT)
104✔
1447
                                return log_error_errno(r, "Failed to check if %s exists: %m", hd);
×
1448

1449
                        WITH_UMASK(0000) {
208✔
1450
                                r = mkdir_parents(hd, 0755);
104✔
1451
                                if (r < 0)
104✔
1452
                                        return log_error_errno(r, "Failed to create parent directories of %s: %m", hd);
×
1453

1454
                                if (mkdir(hd, 0700) < 0 && errno != EEXIST)
104✔
1455
                                        return log_error_errno(errno, "Failed to create %s: %m", hd);
×
1456
                        }
1457

1458
                        if (chown(hd, ur->uid, user_record_gid(ur)) < 0)
104✔
1459
                                return log_error_errno(errno, "Failed to chown %s: %m", hd);
×
1460

1461
                        r = copy_tree(user_record_skeleton_directory(ur), hd, ur->uid, user_record_gid(ur),
104✔
1462
                                      COPY_REFLINK|COPY_MERGE, /* denylist= */ NULL, /* subvolumes= */NULL);
1463
                        if (r < 0 && r != -ENOENT)
104✔
1464
                                return log_error_errno(r, "Failed to copy skeleton directory to %s: %m", hd);
×
1465
                }
1466
        }
1467

1468
        return 0;
1469
}
1470

1471
static int load_credentials(int argc, char *argv[], void *userdata) {
118✔
1472
        int r;
118✔
1473

1474
        _cleanup_close_ int credential_dir_fd = open_credentials_dir();
236✔
1475
        if (IN_SET(credential_dir_fd, -ENXIO, -ENOENT)) {
118✔
1476
                /* Credential env var not set, or dir doesn't exist. */
1477
                log_debug("No credentials found.");
×
1478
                return 0;
×
1479
        }
1480
        if (credential_dir_fd < 0)
118✔
1481
                return log_error_errno(credential_dir_fd, "Failed to open credentials directory: %m");
×
1482

1483
        _cleanup_free_ DirectoryEntries *des = NULL;
118✔
1484
        r = readdir_all(credential_dir_fd, RECURSE_DIR_SORT|RECURSE_DIR_IGNORE_DOT|RECURSE_DIR_ENSURE_TYPE, &des);
118✔
1485
        if (r < 0)
118✔
1486
                return log_error_errno(r, "Failed to enumerate credentials: %m");
×
1487

1488
        _cleanup_close_ int userdb_persist_dir_fd = -EBADF, userdb_transient_dir_fd = -EBADF;
236✔
1489

1490
        FOREACH_ARRAY(i, des->entries, des->n_entries) {
354✔
1491
                struct dirent *de = *i;
236✔
1492

1493
                if (de->d_type != DT_REG)
236✔
1494
                        continue;
×
1495

1496
                RET_GATHER(r, load_credential_one(
236✔
1497
                                credential_dir_fd,
1498
                                de->d_name,
1499
                                &userdb_persist_dir_fd,
1500
                                &userdb_transient_dir_fd));
1501
        }
1502

1503
        return r;
118✔
1504
}
1505

1506
static int help(int argc, char *argv[], void *userdata) {
1✔
1507
        _cleanup_free_ char *link = NULL;
1✔
1508
        int r;
1✔
1509

1510
        pager_open(arg_pager_flags);
1✔
1511

1512
        r = terminal_urlify_man("userdbctl", "1", &link);
1✔
1513
        if (r < 0)
1✔
1514
                return log_oom();
×
1515

1516
        printf("%s [OPTIONS...] COMMAND ...\n\n"
2✔
1517
               "%sShow user and group information.%s\n"
1518
               "\nCommands:\n"
1519
               "  user [USER…]               Inspect user\n"
1520
               "  group [GROUP…]             Inspect group\n"
1521
               "  users-in-group [GROUP…]    Show users that are members of specified groups\n"
1522
               "  groups-of-user [USER…]     Show groups the specified users are members of\n"
1523
               "  services                   Show enabled database services\n"
1524
               "  ssh-authorized-keys USER   Show SSH authorized keys for user\n"
1525
               "  load-credentials           Write static user/group records from credentials\n"
1526
               "\nOptions:\n"
1527
               "  -h --help                  Show this help\n"
1528
               "     --version               Show package version\n"
1529
               "     --no-pager              Do not pipe output into a pager\n"
1530
               "     --no-legend             Do not show the headers and footers\n"
1531
               "     --output=MODE           Select output mode (classic, friendly, table, json)\n"
1532
               "  -j                         Equivalent to --output=json\n"
1533
               "  -s --service=SERVICE[:SERVICE…]\n"
1534
               "                             Query the specified service\n"
1535
               "     --with-nss=BOOL         Control whether to include glibc NSS data\n"
1536
               "  -N                         Do not synthesize or include glibc NSS data\n"
1537
               "                             (Same as --synthesize=no --with-nss=no)\n"
1538
               "     --synthesize=BOOL       Synthesize root/nobody user\n"
1539
               "     --with-dropin=BOOL      Control whether to include drop-in records\n"
1540
               "     --with-varlink=BOOL     Control whether to talk to services at all\n"
1541
               "     --multiplexer=BOOL      Control whether to use the multiplexer\n"
1542
               "     --json=pretty|short     JSON output mode\n"
1543
               "     --chain                 Chain another command\n"
1544
               "     --uid-min=ID            Filter by minimum UID/GID (default 0)\n"
1545
               "     --uid-max=ID            Filter by maximum UID/GID (default 4294967294)\n"
1546
               "  -z --fuzzy                 Do a fuzzy name search\n"
1547
               "     --disposition=VALUE     Filter by disposition\n"
1548
               "  -I                         Equivalent to --disposition=intrinsic\n"
1549
               "  -S                         Equivalent to --disposition=system\n"
1550
               "  -R                         Equivalent to --disposition=regular\n"
1551
               "     --boundaries=BOOL       Show/hide UID/GID range boundaries in output\n"
1552
               "  -B                         Equivalent to --boundaries=no\n"
1553
               "  -F --from-file=PATH        Read JSON record from file\n"
1554
               "\nSee the %s for details.\n",
1555
               program_invocation_short_name,
1556
               ansi_highlight(),
1557
               ansi_normal(),
1558
               link);
1559

1560
        return 0;
1561
}
1562

1563
static int parse_argv(int argc, char *argv[]) {
315✔
1564

1565
        enum {
315✔
1566
                ARG_VERSION = 0x100,
1567
                ARG_NO_PAGER,
1568
                ARG_NO_LEGEND,
1569
                ARG_OUTPUT,
1570
                ARG_WITH_NSS,
1571
                ARG_WITH_DROPIN,
1572
                ARG_WITH_VARLINK,
1573
                ARG_SYNTHESIZE,
1574
                ARG_MULTIPLEXER,
1575
                ARG_JSON,
1576
                ARG_CHAIN,
1577
                ARG_UID_MIN,
1578
                ARG_UID_MAX,
1579
                ARG_DISPOSITION,
1580
                ARG_BOUNDARIES,
1581
        };
1582

1583
        static const struct option options[] = {
315✔
1584
                { "help",         no_argument,       NULL, 'h'              },
1585
                { "version",      no_argument,       NULL, ARG_VERSION      },
1586
                { "no-pager",     no_argument,       NULL, ARG_NO_PAGER     },
1587
                { "no-legend",    no_argument,       NULL, ARG_NO_LEGEND    },
1588
                { "output",       required_argument, NULL, ARG_OUTPUT       },
1589
                { "service",      required_argument, NULL, 's'              },
1590
                { "with-nss",     required_argument, NULL, ARG_WITH_NSS     },
1591
                { "with-dropin",  required_argument, NULL, ARG_WITH_DROPIN  },
1592
                { "with-varlink", required_argument, NULL, ARG_WITH_VARLINK },
1593
                { "synthesize",   required_argument, NULL, ARG_SYNTHESIZE   },
1594
                { "multiplexer",  required_argument, NULL, ARG_MULTIPLEXER  },
1595
                { "json",         required_argument, NULL, ARG_JSON         },
1596
                { "chain",        no_argument,       NULL, ARG_CHAIN        },
1597
                { "uid-min",      required_argument, NULL, ARG_UID_MIN      },
1598
                { "uid-max",      required_argument, NULL, ARG_UID_MAX      },
1599
                { "fuzzy",        no_argument,       NULL, 'z'              },
1600
                { "disposition",  required_argument, NULL, ARG_DISPOSITION  },
1601
                { "boundaries",   required_argument, NULL, ARG_BOUNDARIES   },
1602
                { "from-file",    required_argument, NULL, 'F'              },
1603
                {}
1604
        };
1605

1606
        const char *e;
315✔
1607
        int r;
315✔
1608

1609
        assert(argc >= 0);
315✔
1610
        assert(argv);
315✔
1611

1612
        /* We are going to update this environment variable with our own, hence let's first read what is already set */
1613
        e = getenv("SYSTEMD_ONLY_USERDB");
315✔
1614
        if (e) {
315✔
1615
                char **l;
×
1616

1617
                l = strv_split(e, ":");
×
1618
                if (!l)
×
1619
                        return log_oom();
×
1620

1621
                strv_free(arg_services);
×
1622
                arg_services = l;
×
1623
        }
1624

1625
        /* Resetting to 0 forces the invocation of an internal initialization routine of getopt_long()
1626
         * that checks for GNU extensions in optstring ('-' or '+' at the beginning). */
1627
        optind = 0;
315✔
1628

1629
        for (;;) {
412✔
1630
                int c;
412✔
1631

1632
                c = getopt_long(argc, argv,
412✔
1633
                                arg_chain ? "+hjs:NISRzBF:" : "hjs:NISRzBF:", /* When --chain was used disable parsing of further switches */
412✔
1634
                                options, NULL);
1635
                if (c < 0)
412✔
1636
                        break;
1637

1638
                switch (c) {
127✔
1639

1640
                case 'h':
1✔
1641
                        return help(0, NULL, NULL);
1✔
1642

1643
                case ARG_VERSION:
1✔
1644
                        return version();
1✔
1645

1646
                case ARG_NO_PAGER:
2✔
1647
                        arg_pager_flags |= PAGER_DISABLE;
2✔
1648
                        break;
2✔
1649

1650
                case ARG_NO_LEGEND:
3✔
1651
                        arg_legend = false;
3✔
1652
                        break;
3✔
1653

1654
                case ARG_OUTPUT:
8✔
1655
                        if (isempty(optarg))
8✔
1656
                                arg_output = _OUTPUT_INVALID;
×
1657
                        else if (streq(optarg, "classic"))
8✔
1658
                                arg_output = OUTPUT_CLASSIC;
1✔
1659
                        else if (streq(optarg, "friendly"))
7✔
1660
                                arg_output = OUTPUT_FRIENDLY;
1✔
1661
                        else if (streq(optarg, "json"))
6✔
1662
                                arg_output = OUTPUT_JSON;
1✔
1663
                        else if (streq(optarg, "table"))
5✔
1664
                                arg_output = OUTPUT_TABLE;
1✔
1665
                        else if (streq(optarg, "help")) {
4✔
1666
                                puts("classic\n"
×
1667
                                     "friendly\n"
1668
                                     "json\n"
1669
                                     "table");
1670
                                return 0;
×
1671
                        } else
1672
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid --output= mode: %s", optarg);
4✔
1673

1674
                        arg_json_format_flags = arg_output == OUTPUT_JSON ? SD_JSON_FORMAT_PRETTY|SD_JSON_FORMAT_COLOR_AUTO : SD_JSON_FORMAT_OFF;
4✔
1675
                        break;
4✔
1676

1677
                case ARG_JSON:
6✔
1678
                        r = parse_json_argument(optarg, &arg_json_format_flags);
6✔
1679
                        if (r <= 0)
6✔
1680
                                return r;
1681

1682
                        arg_output = sd_json_format_enabled(arg_json_format_flags) ? OUTPUT_JSON : _OUTPUT_INVALID;
2✔
1683
                        break;
2✔
1684

1685
                case 'j':
26✔
1686
                        arg_json_format_flags = SD_JSON_FORMAT_PRETTY|SD_JSON_FORMAT_COLOR_AUTO;
26✔
1687
                        arg_output = OUTPUT_JSON;
26✔
1688
                        break;
26✔
1689

1690
                case 's':
×
1691
                        if (isempty(optarg))
×
1692
                                arg_services = strv_free(arg_services);
×
1693
                        else {
1694
                                r = strv_split_and_extend(&arg_services, optarg, ":", /* filter_duplicates = */ true);
×
1695
                                if (r < 0)
×
1696
                                        return log_error_errno(r, "Failed to parse -s/--service= argument: %m");
×
1697
                        }
1698

1699
                        break;
1700

1701
                case 'N':
1✔
1702
                        arg_userdb_flags |= USERDB_EXCLUDE_NSS|USERDB_DONT_SYNTHESIZE_INTRINSIC|USERDB_DONT_SYNTHESIZE_FOREIGN;
1✔
1703
                        break;
1✔
1704

1705
                case ARG_WITH_NSS:
14✔
1706
                        r = parse_boolean_argument("--with-nss=", optarg, NULL);
14✔
1707
                        if (r < 0)
14✔
1708
                                return r;
1709

1710
                        SET_FLAG(arg_userdb_flags, USERDB_EXCLUDE_NSS, !r);
10✔
1711
                        break;
10✔
1712

1713
                case ARG_WITH_DROPIN:
8✔
1714
                        r = parse_boolean_argument("--with-dropin=", optarg, NULL);
8✔
1715
                        if (r < 0)
8✔
1716
                                return r;
1717

1718
                        SET_FLAG(arg_userdb_flags, USERDB_EXCLUDE_DROPIN, !r);
4✔
1719
                        break;
4✔
1720

1721
                case ARG_WITH_VARLINK:
7✔
1722
                        r = parse_boolean_argument("--with-varlink=", optarg, NULL);
7✔
1723
                        if (r < 0)
7✔
1724
                                return r;
1725

1726
                        SET_FLAG(arg_userdb_flags, USERDB_EXCLUDE_VARLINK, !r);
3✔
1727
                        break;
3✔
1728

1729
                case ARG_SYNTHESIZE:
12✔
1730
                        r = parse_boolean_argument("--synthesize=", optarg, NULL);
12✔
1731
                        if (r < 0)
12✔
1732
                                return r;
1733

1734
                        SET_FLAG(arg_userdb_flags, USERDB_DONT_SYNTHESIZE_INTRINSIC|USERDB_DONT_SYNTHESIZE_FOREIGN, !r);
8✔
1735
                        break;
8✔
1736

1737
                case ARG_MULTIPLEXER:
6✔
1738
                        r = parse_boolean_argument("--multiplexer=", optarg, NULL);
6✔
1739
                        if (r < 0)
6✔
1740
                                return r;
1741

1742
                        SET_FLAG(arg_userdb_flags, USERDB_AVOID_MULTIPLEXER, !r);
2✔
1743
                        break;
2✔
1744

1745
                case ARG_CHAIN:
4✔
1746
                        arg_chain = true;
4✔
1747
                        break;
4✔
1748

1749
                case ARG_DISPOSITION: {
4✔
1750
                        UserDisposition d = user_disposition_from_string(optarg);
4✔
1751
                        if (d < 0)
4✔
1752
                                return log_error_errno(d, "Unknown user disposition: %s", optarg);
×
1753

1754
                        if (arg_disposition_mask == UINT64_MAX)
4✔
1755
                                arg_disposition_mask = 0;
2✔
1756

1757
                        arg_disposition_mask |= UINT64_C(1) << d;
4✔
1758
                        break;
4✔
1759
                }
1760

1761
                case 'I':
2✔
1762
                        if (arg_disposition_mask == UINT64_MAX)
2✔
1763
                                arg_disposition_mask = 0;
2✔
1764

1765
                        arg_disposition_mask |= UINT64_C(1) << USER_INTRINSIC;
2✔
1766
                        break;
2✔
1767

1768
                case 'S':
6✔
1769
                        if (arg_disposition_mask == UINT64_MAX)
6✔
1770
                                arg_disposition_mask = 0;
4✔
1771

1772
                        arg_disposition_mask |= UINT64_C(1) << USER_SYSTEM;
6✔
1773
                        break;
6✔
1774

1775
                case 'R':
2✔
1776
                        if (arg_disposition_mask == UINT64_MAX)
2✔
1777
                                arg_disposition_mask = 0;
2✔
1778

1779
                        arg_disposition_mask |= UINT64_C(1) << USER_REGULAR;
2✔
1780
                        break;
2✔
1781

1782
                case ARG_UID_MIN:
2✔
1783
                        r = parse_uid(optarg, &arg_uid_min);
2✔
1784
                        if (r < 0)
2✔
1785
                                return log_error_errno(r, "Failed to parse --uid-min= value: %s", optarg);
×
1786
                        break;
1787

1788
                case ARG_UID_MAX:
2✔
1789
                        r = parse_uid(optarg, &arg_uid_max);
2✔
1790
                        if (r < 0)
2✔
1791
                                return log_error_errno(r, "Failed to parse --uid-max= value: %s", optarg);
×
1792
                        break;
1793

1794
                case 'z':
2✔
1795
                        arg_fuzzy = true;
2✔
1796
                        break;
2✔
1797

1798
                case ARG_BOUNDARIES:
×
1799
                        r = parse_boolean_argument("boundaries", optarg, &arg_boundaries);
×
1800
                        if (r < 0)
×
1801
                                return r;
1802
                        break;
1803

1804
                case 'B':
2✔
1805
                        arg_boundaries = false;
2✔
1806
                        break;
2✔
1807

1808
                case 'F': {
6✔
1809
                        if (isempty(optarg)) {
6✔
1810
                                arg_from_file = sd_json_variant_unref(arg_from_file);
×
1811
                                break;
6✔
1812
                        }
1813

1814
                        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
6✔
1815
                        const char *fn = streq(optarg, "-") ? NULL : optarg;
6✔
1816
                        unsigned line = 0;
6✔
1817
                        r = sd_json_parse_file(fn ? NULL : stdin, fn ?: "<stdin>", SD_JSON_PARSE_SENSITIVE, &v, &line, /* reterr_column= */ NULL);
6✔
1818
                        if (r < 0)
6✔
1819
                                return log_syntax(/* unit= */ NULL, LOG_ERR, fn ?: "<stdin>", line, r, "JSON parse failure.");
×
1820

1821
                        sd_json_variant_unref(arg_from_file);
6✔
1822
                        arg_from_file = TAKE_PTR(v);
6✔
1823
                        break;
6✔
1824
                }
1825

1826
                case '?':
1827
                        return -EINVAL;
1828

1829
                default:
×
1830
                        assert_not_reached();
×
1831
                }
1832
        }
1833

1834
        if (arg_uid_min > arg_uid_max)
285✔
1835
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Minimum UID/GID " UID_FMT " is above maximum UID/GID " UID_FMT ", refusing.", arg_uid_min, arg_uid_max);
×
1836

1837
        /* If not mask was specified, use the all bits on mask */
1838
        if (arg_disposition_mask == UINT64_MAX)
285✔
1839
                arg_disposition_mask = USER_DISPOSITION_MASK_ALL;
275✔
1840

1841
        if (arg_from_file)
285✔
1842
                arg_boundaries = false;
6✔
1843

1844
        return 1;
1845
}
1846

1847
static int run(int argc, char *argv[]) {
315✔
1848
        static const Verb verbs[] = {
315✔
1849
                { "help",                VERB_ANY, VERB_ANY, 0,            help                },
1850
                { "user",                VERB_ANY, VERB_ANY, VERB_DEFAULT, display_user        },
1851
                { "group",               VERB_ANY, VERB_ANY, 0,            display_group       },
1852
                { "users-in-group",      VERB_ANY, VERB_ANY, 0,            display_memberships },
1853
                { "groups-of-user",      VERB_ANY, VERB_ANY, 0,            display_memberships },
1854
                { "services",            VERB_ANY, 1,        0,            display_services    },
1855
                { "ssh-authorized-keys", 2,        VERB_ANY, 0,            ssh_authorized_keys },
1856
                { "load-credentials",    VERB_ANY, 1,        0,            load_credentials    },
1857
                {}
1858
        };
1859

1860
        int r;
315✔
1861

1862
        log_setup();
315✔
1863

1864
        r = parse_argv(argc, argv);
315✔
1865
        if (r <= 0)
315✔
1866
                return r;
1867

1868
        if (arg_services) {
285✔
1869
                _cleanup_free_ char *e = NULL;
×
1870

1871
                e = strv_join(arg_services, ":");
×
1872
                if (!e)
×
1873
                        return log_oom();
×
1874

1875
                if (setenv("SYSTEMD_ONLY_USERDB", e, true) < 0)
×
1876
                        return log_error_errno(r, "Failed to set $SYSTEMD_ONLY_USERDB: %m");
×
1877

1878
                log_info("Enabled services: %s", e);
×
1879
        } else
1880
                assert_se(unsetenv("SYSTEMD_ONLY_USERDB") == 0);
285✔
1881

1882
        return dispatch_verb(argc, argv, verbs, NULL);
285✔
1883
}
1884

1885
DEFINE_MAIN_FUNCTION(run);
315✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc