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

systemd / systemd / 13935887515

18 Mar 2025 07:10PM UTC coverage: 71.913% (-0.03%) from 71.946%
13935887515

push

github

web-flow
Several fixes and cleanups around sd_listen_fds() (#36788)

15 of 24 new or added lines in 5 files covered. (62.5%)

993 existing lines in 54 files now uncovered.

296157 of 411825 relevant lines covered (71.91%)

710024.94 hits per line

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

73.61
/src/run/run.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <getopt.h>
4
#include <stdio.h>
5
#include <fcntl.h>
6
#include <sys/stat.h>
7
#include <sys/types.h>
8

9
#include "sd-bus.h"
10
#include "sd-event.h"
11
#include "sd-json.h"
12

13
#include "alloc-util.h"
14
#include "ask-password-agent.h"
15
#include "build.h"
16
#include "bus-error.h"
17
#include "bus-locator.h"
18
#include "bus-map-properties.h"
19
#include "bus-message-util.h"
20
#include "bus-unit-util.h"
21
#include "bus-wait-for-jobs.h"
22
#include "calendarspec.h"
23
#include "capsule-util.h"
24
#include "chase.h"
25
#include "env-util.h"
26
#include "escape.h"
27
#include "event-util.h"
28
#include "exec-util.h"
29
#include "exit-status.h"
30
#include "fd-util.h"
31
#include "format-util.h"
32
#include "fs-util.h"
33
#include "hostname-setup.h"
34
#include "hostname-util.h"
35
#include "main-func.h"
36
#include "osc-context.h"
37
#include "parse-argument.h"
38
#include "parse-util.h"
39
#include "path-util.h"
40
#include "polkit-agent.h"
41
#include "pretty-print.h"
42
#include "process-util.h"
43
#include "ptyfwd.h"
44
#include "signal-util.h"
45
#include "special.h"
46
#include "string-table.h"
47
#include "strv.h"
48
#include "terminal-util.h"
49
#include "uid-classification.h"
50
#include "unit-def.h"
51
#include "unit-name.h"
52
#include "user-util.h"
53

54
static bool arg_ask_password = true;
55
static bool arg_scope = false;
56
static bool arg_remain_after_exit = false;
57
static bool arg_no_block = false;
58
static bool arg_wait = false;
59
static const char *arg_unit = NULL;
60
static char *arg_description = NULL;
61
static const char *arg_slice = NULL;
62
static bool arg_slice_inherit = false;
63
static bool arg_expand_environment = true;
64
static bool arg_send_sighup = false;
65
static BusTransport arg_transport = BUS_TRANSPORT_LOCAL;
66
static const char *arg_host = NULL;
67
static RuntimeScope arg_runtime_scope = RUNTIME_SCOPE_SYSTEM;
68
static const char *arg_service_type = NULL;
69
static const char *arg_exec_user = NULL;
70
static const char *arg_exec_group = NULL;
71
static int arg_nice = 0;
72
static bool arg_nice_set = false;
73
static char **arg_environment = NULL;
74
static char **arg_property = NULL;
75
static enum {
76
        ARG_STDIO_NONE   = 0,      /* The default, as it is for normal services, stdin connected to
77
                                    * /dev/null, and stdout+stderr to the journal */
78
        ARG_STDIO_PTY    = 1 << 0, /* Interactive behaviour, requested by --pty/--pty-late: we allocate a pty
79
                                    * and connect it to the TTY we are invoked from */
80
        ARG_STDIO_DIRECT = 1 << 1, /* Directly pass our stdin/stdout/stderr to the activated service, useful
81
                                    * for usage in shell pipelines, requested by --pipe */
82
        ARG_STDIO_AUTO   = ARG_STDIO_PTY | ARG_STDIO_DIRECT,
83
                                   /* If --pipe and --pty/--pty-late are used together we use --pty/--pty-late
84
                                    * when invoked on a TTY, and --pipe otherwise */
85
} arg_stdio = ARG_STDIO_NONE;
86
static int arg_pty_late = -1; /* tristate */
87
static char **arg_path_property = NULL;
88
static char **arg_socket_property = NULL;
89
static char **arg_timer_property = NULL;
90
static bool arg_with_timer = false;
91
static bool arg_quiet = false;
92
static bool arg_aggressive_gc = false;
93
static char *arg_working_directory = NULL;
94
static bool arg_shell = false;
95
static JobMode arg_job_mode = JOB_FAIL;
96
static char **arg_cmdline = NULL;
97
static char *arg_exec_path = NULL;
98
static bool arg_ignore_failure = false;
99
static char *arg_background = NULL;
100
static sd_json_format_flags_t arg_json_format_flags = SD_JSON_FORMAT_OFF;
101
static char *arg_shell_prompt_prefix = NULL;
102
static int arg_lightweight = -1;
103
static char *arg_area = NULL;
104

105
STATIC_DESTRUCTOR_REGISTER(arg_description, freep);
1,107✔
106
STATIC_DESTRUCTOR_REGISTER(arg_environment, strv_freep);
1,107✔
107
STATIC_DESTRUCTOR_REGISTER(arg_property, strv_freep);
1,107✔
108
STATIC_DESTRUCTOR_REGISTER(arg_path_property, strv_freep);
1,107✔
109
STATIC_DESTRUCTOR_REGISTER(arg_socket_property, strv_freep);
1,107✔
110
STATIC_DESTRUCTOR_REGISTER(arg_timer_property, strv_freep);
1,107✔
111
STATIC_DESTRUCTOR_REGISTER(arg_working_directory, freep);
1,107✔
112
STATIC_DESTRUCTOR_REGISTER(arg_cmdline, strv_freep);
1,107✔
113
STATIC_DESTRUCTOR_REGISTER(arg_exec_path, freep);
1,107✔
114
STATIC_DESTRUCTOR_REGISTER(arg_background, freep);
1,107✔
115
STATIC_DESTRUCTOR_REGISTER(arg_shell_prompt_prefix, freep);
1,107✔
116
STATIC_DESTRUCTOR_REGISTER(arg_area, freep);
1,107✔
117

118
static int help(void) {
1✔
119
        _cleanup_free_ char *link = NULL;
1✔
120
        int r;
1✔
121

122
        r = terminal_urlify_man("systemd-run", "1", &link);
1✔
123
        if (r < 0)
1✔
124
                return log_oom();
×
125

126
        printf("%1$s [OPTIONS...] COMMAND [ARGUMENTS...]\n"
2✔
127
               "\n%5$sRun the specified command in a transient scope or service.%6$s\n\n"
128
               "  -h --help                       Show this help\n"
129
               "     --version                    Show package version\n"
130
               "     --no-ask-password            Do not prompt for password\n"
131
               "     --user                       Run as user unit\n"
132
               "  -H --host=[USER@]HOST           Operate on remote host\n"
133
               "  -M --machine=CONTAINER          Operate on local container\n"
134
               "     --scope                      Run this as scope rather than service\n"
135
               "  -u --unit=UNIT                  Run under the specified unit name\n"
136
               "  -p --property=NAME=VALUE        Set service or scope unit property\n"
137
               "     --description=TEXT           Description for unit\n"
138
               "     --slice=SLICE                Run in the specified slice\n"
139
               "     --slice-inherit              Inherit the slice from the caller\n"
140
               "     --expand-environment=BOOL    Control expansion of environment variables\n"
141
               "     --no-block                   Do not wait until operation finished\n"
142
               "  -r --remain-after-exit          Leave service around until explicitly stopped\n"
143
               "     --wait                       Wait until service stopped again\n"
144
               "     --send-sighup                Send SIGHUP when terminating\n"
145
               "     --service-type=TYPE          Service type\n"
146
               "     --uid=USER                   Run as system user\n"
147
               "     --gid=GROUP                  Run as system group\n"
148
               "     --nice=NICE                  Nice level\n"
149
               "     --working-directory=PATH     Set working directory\n"
150
               "  -d --same-dir                   Inherit working directory from caller\n"
151
               "  -E --setenv=NAME[=VALUE]        Set environment variable\n"
152
               "  -t --pty                        Run service on pseudo TTY as STDIN/STDOUT/\n"
153
               "                                  STDERR\n"
154
               "  -T --pty-late                   Just like --pty, but leave TTY access to\n"
155
               "                                  agents until unit is started up\n"
156
               "  -P --pipe                       Pass STDIN/STDOUT/STDERR directly to service\n"
157
               "  -q --quiet                      Suppress information messages during runtime\n"
158
               "     --json=pretty|short|off      Print unit name and invocation id as JSON\n"
159
               "  -G --collect                    Unload unit after it ran, even when failed\n"
160
               "  -S --shell                      Invoke a $SHELL interactively\n"
161
               "     --job-mode=MODE              Specify how to deal with already queued jobs,\n"
162
               "                                  when queueing a new job\n"
163
               "     --ignore-failure             Ignore the exit status of the invoked process\n"
164
               "     --background=COLOR           Set ANSI color for background\n"
165
               "\n%3$sPath options:%4$s\n"
166
               "     --path-property=NAME=VALUE   Set path unit property\n"
167
               "\n%3$sSocket options:%4$s\n"
168
               "     --socket-property=NAME=VALUE Set socket unit property\n"
169
               "\n%3$sTimer options:%4$s\n"
170
               "     --on-active=SECONDS          Run after SECONDS delay\n"
171
               "     --on-boot=SECONDS            Run SECONDS after machine was booted up\n"
172
               "     --on-startup=SECONDS         Run SECONDS after systemd activation\n"
173
               "     --on-unit-active=SECONDS     Run SECONDS after the last activation\n"
174
               "     --on-unit-inactive=SECONDS   Run SECONDS after the last deactivation\n"
175
               "     --on-calendar=SPEC           Realtime timer\n"
176
               "     --on-timezone-change         Run when the timezone changes\n"
177
               "     --on-clock-change            Run when the realtime clock jumps\n"
178
               "     --timer-property=NAME=VALUE  Set timer unit property\n"
179
               "\nSee the %2$s for details.\n",
180
               program_invocation_short_name,
181
               link,
182
               ansi_underline(), ansi_normal(),
183
               ansi_highlight(), ansi_normal());
184

185
        return 0;
186
}
187

188
static int help_sudo_mode(void) {
×
189
        _cleanup_free_ char *link = NULL;
×
190
        int r;
×
191

192
        r = terminal_urlify_man("run0", "1", &link);
×
193
        if (r < 0)
×
194
                return log_oom();
×
195

196
        /* NB: Let's not go overboard with short options: we try to keep a modicum of compatibility with
197
         * sudo's short switches, hence please do not introduce new short switches unless they have a roughly
198
         * equivalent purpose on sudo. Use long options for everything private to run0. */
199

200
        printf("%s [OPTIONS...] COMMAND [ARGUMENTS...]\n"
×
201
               "\n%sElevate privileges interactively.%s\n\n"
202
               "  -h --help                       Show this help\n"
203
               "  -V --version                    Show package version\n"
204
               "     --no-ask-password            Do not prompt for password\n"
205
               "     --machine=CONTAINER          Operate on local container\n"
206
               "     --unit=UNIT                  Run under the specified unit name\n"
207
               "     --property=NAME=VALUE        Set service or scope unit property\n"
208
               "     --description=TEXT           Description for unit\n"
209
               "     --slice=SLICE                Run in the specified slice\n"
210
               "     --slice-inherit              Inherit the slice\n"
211
               "  -u --user=USER                  Run as system user\n"
212
               "  -g --group=GROUP                Run as system group\n"
213
               "     --nice=NICE                  Nice level\n"
214
               "  -D --chdir=PATH                 Set working directory\n"
215
               "     --setenv=NAME[=VALUE]        Set environment variable\n"
216
               "     --background=COLOR           Set ANSI color for background\n"
217
               "     --pty                        Request allocation of a pseudo TTY for stdio\n"
218
               "     --pty-late                   Just like --pty, but leave TTY access to agents\n"
219
               "                                  until unit is started up\n"
220
               "     --pipe                       Request direct pipe for stdio\n"
221
               "     --shell-prompt-prefix=PREFIX Set $SHELL_PROMPT_PREFIX\n"
222
               "     --lightweight=BOOLEAN        Control whether to register a session with service manager\n"
223
               "                                  or without\n"
224
               "  -a --area=AREA                  Home area to log into\n"
225
               "\nSee the %s for details.\n",
226
               program_invocation_short_name,
227
               ansi_highlight(),
228
               ansi_normal(),
229
               link);
230

231
        return 0;
232
}
233

234
static bool privileged_execution(void) {
99✔
235
        if (arg_runtime_scope != RUNTIME_SCOPE_SYSTEM)
99✔
236
                return false;
99✔
237

238
        return !arg_exec_user || STR_IN_SET(arg_exec_user, "root", "0");
108✔
239
}
240

241
static int add_timer_property(const char *name, const char *val) {
23✔
242
        char *p;
23✔
243

244
        assert(name);
23✔
245
        assert(val);
23✔
246

247
        p = strjoin(name, "=", val);
23✔
248
        if (!p)
23✔
249
                return log_oom();
×
250

251
        if (strv_consume(&arg_timer_property, p) < 0)
23✔
252
                return log_oom();
×
253

254
        return 0;
255
}
256

257
static char **make_login_shell_cmdline(const char *shell) {
×
258
        _cleanup_free_ char *argv0 = NULL;
×
259

260
        assert(shell);
×
261

262
        argv0 = strjoin("-", shell); /* The - is how shells determine if they shall be consider login shells */
×
263
        if (!argv0)
×
264
                return NULL;
265

266
        return strv_new(argv0);
×
267
}
268

269
static int parse_argv(int argc, char *argv[]) {
1,000✔
270

271
        enum {
1,000✔
272
                ARG_VERSION = 0x100,
273
                ARG_USER,
274
                ARG_SYSTEM,
275
                ARG_SCOPE,
276
                ARG_DESCRIPTION,
277
                ARG_SLICE,
278
                ARG_SLICE_INHERIT,
279
                ARG_EXPAND_ENVIRONMENT,
280
                ARG_SEND_SIGHUP,
281
                ARG_SERVICE_TYPE,
282
                ARG_EXEC_USER,
283
                ARG_EXEC_GROUP,
284
                ARG_NICE,
285
                ARG_ON_ACTIVE,
286
                ARG_ON_BOOT,
287
                ARG_ON_STARTUP,
288
                ARG_ON_UNIT_ACTIVE,
289
                ARG_ON_UNIT_INACTIVE,
290
                ARG_ON_CALENDAR,
291
                ARG_ON_TIMEZONE_CHANGE,
292
                ARG_ON_CLOCK_CHANGE,
293
                ARG_TIMER_PROPERTY,
294
                ARG_PATH_PROPERTY,
295
                ARG_SOCKET_PROPERTY,
296
                ARG_NO_BLOCK,
297
                ARG_NO_ASK_PASSWORD,
298
                ARG_WAIT,
299
                ARG_WORKING_DIRECTORY,
300
                ARG_SHELL,
301
                ARG_JOB_MODE,
302
                ARG_IGNORE_FAILURE,
303
                ARG_BACKGROUND,
304
                ARG_JSON,
305
        };
306

307
        static const struct option options[] = {
1,000✔
308
                { "help",               no_argument,       NULL, 'h'                    },
309
                { "version",            no_argument,       NULL, ARG_VERSION            },
310
                { "user",               no_argument,       NULL, ARG_USER               },
311
                { "system",             no_argument,       NULL, ARG_SYSTEM             },
312
                { "capsule",            required_argument, NULL, 'C'                    },
313
                { "scope",              no_argument,       NULL, ARG_SCOPE              },
314
                { "unit",               required_argument, NULL, 'u'                    },
315
                { "description",        required_argument, NULL, ARG_DESCRIPTION        },
316
                { "slice",              required_argument, NULL, ARG_SLICE              },
317
                { "slice-inherit",      no_argument,       NULL, ARG_SLICE_INHERIT      },
318
                { "remain-after-exit",  no_argument,       NULL, 'r'                    },
319
                { "expand-environment", required_argument, NULL, ARG_EXPAND_ENVIRONMENT },
320
                { "send-sighup",        no_argument,       NULL, ARG_SEND_SIGHUP        },
321
                { "host",               required_argument, NULL, 'H'                    },
322
                { "machine",            required_argument, NULL, 'M'                    },
323
                { "service-type",       required_argument, NULL, ARG_SERVICE_TYPE       },
324
                { "wait",               no_argument,       NULL, ARG_WAIT               },
325
                { "uid",                required_argument, NULL, ARG_EXEC_USER          },
326
                { "gid",                required_argument, NULL, ARG_EXEC_GROUP         },
327
                { "nice",               required_argument, NULL, ARG_NICE               },
328
                { "setenv",             required_argument, NULL, 'E'                    },
329
                { "property",           required_argument, NULL, 'p'                    },
330
                { "tty",                no_argument,       NULL, 't'                    }, /* deprecated alias */
331
                { "pty",                no_argument,       NULL, 't'                    },
332
                { "pty-late",           no_argument,       NULL, 'T'                    },
333
                { "pipe",               no_argument,       NULL, 'P'                    },
334
                { "quiet",              no_argument,       NULL, 'q'                    },
335
                { "on-active",          required_argument, NULL, ARG_ON_ACTIVE          },
336
                { "on-boot",            required_argument, NULL, ARG_ON_BOOT            },
337
                { "on-startup",         required_argument, NULL, ARG_ON_STARTUP         },
338
                { "on-unit-active",     required_argument, NULL, ARG_ON_UNIT_ACTIVE     },
339
                { "on-unit-inactive",   required_argument, NULL, ARG_ON_UNIT_INACTIVE   },
340
                { "on-calendar",        required_argument, NULL, ARG_ON_CALENDAR        },
341
                { "on-timezone-change", no_argument,       NULL, ARG_ON_TIMEZONE_CHANGE },
342
                { "on-clock-change",    no_argument,       NULL, ARG_ON_CLOCK_CHANGE    },
343
                { "timer-property",     required_argument, NULL, ARG_TIMER_PROPERTY     },
344
                { "path-property",      required_argument, NULL, ARG_PATH_PROPERTY      },
345
                { "socket-property",    required_argument, NULL, ARG_SOCKET_PROPERTY    },
346
                { "no-block",           no_argument,       NULL, ARG_NO_BLOCK           },
347
                { "no-ask-password",    no_argument,       NULL, ARG_NO_ASK_PASSWORD    },
348
                { "collect",            no_argument,       NULL, 'G'                    },
349
                { "working-directory",  required_argument, NULL, ARG_WORKING_DIRECTORY  },
350
                { "same-dir",           no_argument,       NULL, 'd'                    },
351
                { "shell",              no_argument,       NULL, 'S'                    },
352
                { "job-mode",           required_argument, NULL, ARG_JOB_MODE           },
353
                { "ignore-failure",     no_argument,       NULL, ARG_IGNORE_FAILURE     },
354
                { "background",         required_argument, NULL, ARG_BACKGROUND         },
355
                { "json",               required_argument, NULL, ARG_JSON               },
356
                {},
357
        };
358

359
        bool with_trigger = false;
1,000✔
360
        int r, c;
1,000✔
361

362
        assert(argc >= 0);
1,000✔
363
        assert(argv);
1,000✔
364

365
        /* Resetting to 0 forces the invocation of an internal initialization routine of getopt_long()
366
         * that checks for GNU extensions in optstring ('-' or '+' at the beginning). */
367
        optind = 0;
1,000✔
368
        while ((c = getopt_long(argc, argv, "+hrC:H:M:E:p:tTPqGdSu:", options, NULL)) >= 0)
5,397✔
369

370
                switch (c) {
4,408✔
371

372
                case 'h':
1✔
373
                        return help();
11✔
374

375
                case ARG_VERSION:
1✔
376
                        return version();
1✔
377

378
                case ARG_NO_ASK_PASSWORD:
1✔
379
                        arg_ask_password = false;
1✔
380
                        break;
4,397✔
381

382
                case ARG_USER:
61✔
383
                        arg_runtime_scope = RUNTIME_SCOPE_USER;
61✔
384
                        break;
61✔
385

386
                case ARG_SYSTEM:
2✔
387
                        arg_runtime_scope = RUNTIME_SCOPE_SYSTEM;
2✔
388
                        break;
2✔
389

390
                case 'C':
1✔
391
                        r = capsule_name_is_valid(optarg);
1✔
392
                        if (r < 0)
1✔
393
                                return log_error_errno(r, "Unable to validate capsule name '%s': %m", optarg);
×
394
                        if (r == 0)
1✔
395
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid capsule name: %s", optarg);
×
396

397
                        arg_host = optarg;
1✔
398
                        arg_transport = BUS_TRANSPORT_CAPSULE;
1✔
399
                        arg_runtime_scope = RUNTIME_SCOPE_USER;
1✔
400
                        break;
1✔
401

402
                case ARG_SCOPE:
19✔
403
                        arg_scope = true;
19✔
404
                        break;
19✔
405

406
                case 'u':
522✔
407
                        arg_unit = optarg;
522✔
408
                        break;
522✔
409

410
                case ARG_DESCRIPTION:
2✔
411
                        r = free_and_strdup_warn(&arg_description, optarg);
2✔
412
                        if (r < 0)
2✔
413
                                return r;
414
                        break;
415

416
                case ARG_SLICE:
30✔
417
                        arg_slice = optarg;
30✔
418
                        break;
30✔
419

420
                case ARG_SLICE_INHERIT:
4✔
421
                        arg_slice_inherit = true;
4✔
422
                        break;
4✔
423

424
                case ARG_EXPAND_ENVIRONMENT:
1✔
425
                        r = parse_boolean_argument("--expand-environment=", optarg, &arg_expand_environment);
1✔
426
                        if (r < 0)
1✔
427
                                return r;
428
                        break;
429

430
                case ARG_SEND_SIGHUP:
1✔
431
                        arg_send_sighup = true;
1✔
432
                        break;
1✔
433

434
                case 'r':
26✔
435
                        arg_remain_after_exit = true;
26✔
436
                        break;
26✔
437

438
                case 'H':
×
439
                        arg_transport = BUS_TRANSPORT_REMOTE;
×
440
                        arg_host = optarg;
×
441
                        break;
×
442

443
                case 'M':
36✔
444
                        arg_transport = BUS_TRANSPORT_MACHINE;
36✔
445
                        arg_host = optarg;
36✔
446
                        break;
36✔
447

448
                case ARG_SERVICE_TYPE:
23✔
449
                        arg_service_type = optarg;
23✔
450
                        break;
23✔
451

452
                case ARG_EXEC_USER:
11✔
453
                        arg_exec_user = optarg;
11✔
454
                        break;
11✔
455

456
                case ARG_EXEC_GROUP:
2✔
457
                        arg_exec_group = optarg;
2✔
458
                        break;
2✔
459

460
                case ARG_NICE:
3✔
461
                        r = parse_nice(optarg, &arg_nice);
3✔
462
                        if (r < 0)
3✔
463
                                return log_error_errno(r, "Failed to parse nice value: %s", optarg);
2✔
464

465
                        arg_nice_set = true;
1✔
466
                        break;
1✔
467

468
                case 'E':
8✔
469
                        r = strv_env_replace_strdup_passthrough(&arg_environment, optarg);
8✔
470
                        if (r < 0)
8✔
471
                                return log_error_errno(r, "Cannot assign environment variable %s: %m", optarg);
2✔
472

473
                        break;
474

475
                case 'p':
2,269✔
476
                        if (strv_extend(&arg_property, optarg) < 0)
2,269✔
477
                                return log_oom();
×
478

479
                        break;
480

481
                case 'T': /* --pty-late */
8✔
482
                case 't': /* --pty */
483
                        arg_stdio |= ARG_STDIO_PTY;
8✔
484
                        arg_pty_late = c == 'T';
8✔
485
                        break;
8✔
486

487
                case 'P': /* --pipe */
226✔
488
                        arg_stdio |= ARG_STDIO_DIRECT;
226✔
489
                        break;
226✔
490

491
                case 'q':
341✔
492
                        arg_quiet = true;
341✔
493
                        break;
341✔
494

495
                case ARG_ON_ACTIVE:
4✔
496
                        r = add_timer_property("OnActiveSec", optarg);
4✔
497
                        if (r < 0)
4✔
498
                                return r;
499

500
                        arg_with_timer = true;
4✔
501
                        break;
4✔
502

503
                case ARG_ON_BOOT:
3✔
504
                        r = add_timer_property("OnBootSec", optarg);
3✔
505
                        if (r < 0)
3✔
506
                                return r;
507

508
                        arg_with_timer = true;
3✔
509
                        break;
3✔
510

511
                case ARG_ON_STARTUP:
3✔
512
                        r = add_timer_property("OnStartupSec", optarg);
3✔
513
                        if (r < 0)
3✔
514
                                return r;
515

516
                        arg_with_timer = true;
3✔
517
                        break;
3✔
518

519
                case ARG_ON_UNIT_ACTIVE:
3✔
520
                        r = add_timer_property("OnUnitActiveSec", optarg);
3✔
521
                        if (r < 0)
3✔
522
                                return r;
523

524
                        arg_with_timer = true;
3✔
525
                        break;
3✔
526

527
                case ARG_ON_UNIT_INACTIVE:
3✔
528
                        r = add_timer_property("OnUnitInactiveSec", optarg);
3✔
529
                        if (r < 0)
3✔
530
                                return r;
531

532
                        arg_with_timer = true;
3✔
533
                        break;
3✔
534

535
                case ARG_ON_CALENDAR: {
4✔
536
                        _cleanup_(calendar_spec_freep) CalendarSpec *cs = NULL;
2✔
537

538
                        r = calendar_spec_from_string(optarg, &cs);
4✔
539
                        if (r < 0)
4✔
540
                                return log_error_errno(r, "Failed to parse calendar event specification: %m");
2✔
541

542
                        /* Let's make sure the given calendar event is not in the past */
543
                        r = calendar_spec_next_usec(cs, now(CLOCK_REALTIME), NULL);
2✔
544
                        if (r == -ENOENT)
2✔
545
                                /* The calendar event is in the past — let's warn about this, but install it
546
                                 * anyway as is. The service manager will trigger the service right away.
547
                                 * Moreover, the server side might have a different clock or timezone than we
548
                                 * do, hence it should decide when or whether to run something. */
549
                                log_warning("Specified calendar expression is in the past, proceeding anyway.");
×
550
                        else if (r < 0)
2✔
551
                                return log_error_errno(r, "Failed to calculate next time calendar expression elapses: %m");
×
552

553
                        r = add_timer_property("OnCalendar", optarg);
2✔
554
                        if (r < 0)
2✔
555
                                return r;
556

557
                        arg_with_timer = true;
2✔
558
                        break;
2✔
559
                }
560

561
                case ARG_ON_TIMEZONE_CHANGE:
2✔
562
                        r = add_timer_property("OnTimezoneChange", "yes");
2✔
563
                        if (r < 0)
2✔
564
                                return r;
565

566
                        arg_with_timer = true;
2✔
567
                        break;
2✔
568

569
                case ARG_ON_CLOCK_CHANGE:
3✔
570
                        r = add_timer_property("OnClockChange", "yes");
3✔
571
                        if (r < 0)
3✔
572
                                return r;
573

574
                        arg_with_timer = true;
3✔
575
                        break;
3✔
576

577
                case ARG_TIMER_PROPERTY:
2✔
578

579
                        if (strv_extend(&arg_timer_property, optarg) < 0)
2✔
580
                                return log_oom();
×
581

582
                        arg_with_timer = arg_with_timer ||
3✔
583
                                STARTSWITH_SET(optarg,
1✔
584
                                               "OnActiveSec=",
585
                                               "OnBootSec=",
586
                                               "OnStartupSec=",
587
                                               "OnUnitActiveSec=",
588
                                               "OnUnitInactiveSec=",
589
                                               "OnCalendar=");
590
                        break;
2✔
591

592
                case ARG_PATH_PROPERTY:
3✔
593

594
                        if (strv_extend(&arg_path_property, optarg) < 0)
3✔
595
                                return log_oom();
×
596

597
                        break;
598

599
                case ARG_SOCKET_PROPERTY:
4✔
600

601
                        if (strv_extend(&arg_socket_property, optarg) < 0)
4✔
602
                                return log_oom();
×
603

604
                        break;
605

606
                case ARG_NO_BLOCK:
4✔
607
                        arg_no_block = true;
4✔
608
                        break;
4✔
609

610
                case ARG_WAIT:
756✔
611
                        arg_wait = true;
756✔
612
                        break;
756✔
613

614
                case ARG_WORKING_DIRECTORY:
2✔
615
                        r = parse_path_argument(optarg, true, &arg_working_directory);
2✔
616
                        if (r < 0)
2✔
617
                                return r;
618

619
                        break;
620

621
                case 'd': {
1✔
622
                        _cleanup_free_ char *p = NULL;
1✔
623

624
                        r = safe_getcwd(&p);
1✔
625
                        if (r < 0)
1✔
626
                                return log_error_errno(r, "Failed to get current working directory: %m");
×
627

628
                        if (empty_or_root(p))
1✔
629
                                arg_working_directory = mfree(arg_working_directory);
1✔
630
                        else
631
                                free_and_replace(arg_working_directory, p);
×
632
                        break;
1✔
633
                }
634

635
                case 'G':
2✔
636
                        arg_aggressive_gc = true;
2✔
637
                        break;
2✔
638

639
                case 'S':
3✔
640
                        arg_shell = true;
3✔
641
                        break;
3✔
642

643
                case ARG_JOB_MODE:
4✔
644
                        if (streq(optarg, "help"))
4✔
645
                                return DUMP_STRING_TABLE(job_mode, JobMode, _JOB_MODE_MAX);
10✔
646

647
                        r = job_mode_from_string(optarg);
3✔
648
                        if (r < 0)
3✔
649
                                return log_error_errno(r, "Invalid job mode: %s", optarg);
1✔
650

651
                        arg_job_mode = r;
2✔
652
                        break;
2✔
653

654
                case ARG_IGNORE_FAILURE:
×
655
                        arg_ignore_failure = true;
×
656
                        break;
×
657

658
                case ARG_BACKGROUND:
×
659
                        r = free_and_strdup_warn(&arg_background, optarg);
×
660
                        if (r < 0)
×
661
                                return r;
662
                        break;
663

664
                case ARG_JSON:
2✔
665
                        r = parse_json_argument(optarg, &arg_json_format_flags);
2✔
666
                        if (r <= 0)
2✔
667
                                return r;
668
                        break;
669

670
                case '?':
671
                        return -EINVAL;
672

673
                default:
×
674
                        assert_not_reached();
×
675
                }
676

677
        /* If we are talking to the per-user instance PolicyKit isn't going to help */
678
        if (arg_runtime_scope == RUNTIME_SCOPE_USER)
989✔
679
                arg_ask_password = false;
62✔
680

681
        with_trigger = !!arg_path_property || !!arg_socket_property || arg_with_timer;
989✔
682

683
        /* currently, only single trigger (path, socket, timer) unit can be created simultaneously */
684
        if ((int) !!arg_path_property + (int) !!arg_socket_property + (int) arg_with_timer > 1)
989✔
685
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
686
                                       "Only single trigger (path, socket, timer) unit can be created.");
687

688
        if (arg_shell) {
989✔
689
                /* If --shell is imply --pty --pipe --same-dir --service-type=exec --wait --collect, unless otherwise
690
                 * specified. */
691

692
                if (!arg_scope) {
3✔
693
                        if (arg_stdio == ARG_STDIO_NONE)
2✔
694
                                arg_stdio = ARG_STDIO_AUTO;
2✔
695

696
                        if (!arg_working_directory) {
2✔
697
                                r = safe_getcwd(&arg_working_directory);
2✔
698
                                if (r < 0)
2✔
699
                                        return log_error_errno(r, "Failed to get current working directory: %m");
×
700
                        }
701

702
                        if (!arg_service_type)
2✔
703
                                arg_service_type = "exec";
2✔
704

705
                        arg_wait = true;
2✔
706
                }
707

708
                arg_aggressive_gc = true;
3✔
709
        }
710

711
        if (arg_stdio == ARG_STDIO_AUTO)
989✔
712
                /* If we both --pty/--pty-late and --pipe are specified we'll automatically pick --pty/--pty-late if we
713
                 * are connected fully to a TTY and pick direct fd passing otherwise. This way, we
714
                 * automatically adapt to usage in a shell pipeline, but we are neatly interactive with
715
                 * tty-level isolation otherwise. */
716
                arg_stdio = isatty_safe(STDIN_FILENO) && isatty_safe(STDOUT_FILENO) && isatty_safe(STDERR_FILENO) ?
4✔
717
                        ARG_STDIO_PTY :
2✔
718
                        ARG_STDIO_DIRECT;
719

720
        if (arg_pty_late < 0)
989✔
721
                arg_pty_late = false; /* For systemd-run this defaults to false, for compat reasons */
981✔
722

723
        if (argc > optind) {
989✔
724
                char **l;
985✔
725

726
                if (arg_shell)
985✔
727
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "If --shell is used, no command line is expected.");
1,000✔
728

729
                l = strv_copy(argv + optind);
985✔
730
                if (!l)
985✔
731
                        return log_oom();
×
732

733
                strv_free_and_replace(arg_cmdline, l);
985✔
734

735
        } else if (arg_shell) {
4✔
736
                _cleanup_free_ char *s = NULL;
3✔
737
                char **l;
3✔
738

739
                r = get_shell(&s);
3✔
740
                if (r < 0)
3✔
741
                        return log_error_errno(r, "Failed to determine shell: %m");
×
742

743
                l = strv_new(s);
3✔
744
                if (!l)
3✔
745
                        return log_oom();
×
746

747
                strv_free_and_replace(arg_cmdline, l);
3✔
748

749
        } else if (!arg_unit || !with_trigger)
1✔
750
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Command line to execute required.");
1✔
751

752
        if (arg_runtime_scope == RUNTIME_SCOPE_USER && arg_transport == BUS_TRANSPORT_REMOTE)
988✔
753
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
754
                                       "Execution in user context is not supported on remote systems.");
755

756
        if (arg_scope && arg_transport == BUS_TRANSPORT_REMOTE)
988✔
757
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
758
                                       "Scope execution is not supported on remote systems.");
759

760
        if (arg_scope && (arg_remain_after_exit || arg_service_type))
988✔
761
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
762
                                       "--remain-after-exit and --service-type= are not supported in --scope mode.");
763

764
        if (arg_stdio != ARG_STDIO_NONE) {
988✔
765
                if (with_trigger || arg_scope)
236✔
766
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
767
                                               "--pty/--pty-late/--pipe is not compatible in trigger (path/socket/timer units) or --scope mode.");
768

769
                if (arg_transport == BUS_TRANSPORT_REMOTE)
236✔
770
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
771
                                               "--pty/--pty-late/--pipe is only supported when connecting to the local system or containers.");
772

773
                if (arg_no_block)
236✔
774
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
775
                                               "--pty/--pty-late/--pipe is not compatible with --no-block.");
776
        }
777

778
        if (arg_stdio == ARG_STDIO_PTY && arg_pty_late && streq_ptr(arg_service_type, "oneshot"))
988✔
779
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
780
                                       "--pty-late is not compatible with --service-type=oneshot.");
781

782
        if (arg_scope && with_trigger)
988✔
783
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
784
                                       "Path, socket or timer options are not supported in --scope mode.");
785

786
        if (arg_timer_property && !arg_with_timer)
988✔
787
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
788
                                       "--timer-property= has no effect without any other timer options.");
789

790
        if (arg_wait) {
988✔
791
                if (arg_no_block)
758✔
792
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
793
                                               "--wait may not be combined with --no-block.");
794

795
                if (with_trigger)
758✔
796
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
797
                                               "--wait may not be combined with path, socket or timer operations.");
798

799
                if (arg_scope)
758✔
800
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
801
                                               "--wait may not be combined with --scope.");
802
        }
803

804
        return 1;
805
}
806

807
static int parse_argv_sudo_mode(int argc, char *argv[]) {
124✔
808

809
        enum {
124✔
810
                ARG_NO_ASK_PASSWORD = 0x100,
811
                ARG_HOST,
812
                ARG_MACHINE,
813
                ARG_UNIT,
814
                ARG_PROPERTY,
815
                ARG_DESCRIPTION,
816
                ARG_SLICE,
817
                ARG_SLICE_INHERIT,
818
                ARG_NICE,
819
                ARG_SETENV,
820
                ARG_BACKGROUND,
821
                ARG_PTY,
822
                ARG_PTY_LATE,
823
                ARG_PIPE,
824
                ARG_SHELL_PROMPT_PREFIX,
825
                ARG_LIGHTWEIGHT,
826
        };
827

828
        /* If invoked as "run0" binary, let's expose a more sudo-like interface. We add various extensions
829
         * though (but limit the extension to long options). */
830

831
        static const struct option options[] = {
124✔
832
                { "help",                no_argument,       NULL, 'h'                     },
833
                { "version",             no_argument,       NULL, 'V'                     },
834
                { "no-ask-password",     no_argument,       NULL, ARG_NO_ASK_PASSWORD     },
835
                { "machine",             required_argument, NULL, ARG_MACHINE             },
836
                { "unit",                required_argument, NULL, ARG_UNIT                },
837
                { "property",            required_argument, NULL, ARG_PROPERTY            },
838
                { "description",         required_argument, NULL, ARG_DESCRIPTION         },
839
                { "slice",               required_argument, NULL, ARG_SLICE               },
840
                { "slice-inherit",       no_argument,       NULL, ARG_SLICE_INHERIT       },
841
                { "user",                required_argument, NULL, 'u'                     },
842
                { "group",               required_argument, NULL, 'g'                     },
843
                { "nice",                required_argument, NULL, ARG_NICE                },
844
                { "chdir",               required_argument, NULL, 'D'                     },
845
                { "setenv",              required_argument, NULL, ARG_SETENV              },
846
                { "background",          required_argument, NULL, ARG_BACKGROUND          },
847
                { "pty",                 no_argument,       NULL, ARG_PTY                 },
848
                { "pty-late",            no_argument,       NULL, ARG_PTY_LATE            },
849
                { "pipe",                no_argument,       NULL, ARG_PIPE                },
850
                { "shell-prompt-prefix", required_argument, NULL, ARG_SHELL_PROMPT_PREFIX },
851
                { "lightweight",         required_argument, NULL, ARG_LIGHTWEIGHT         },
852
                { "area",                required_argument, NULL, 'a'                     },
853
                {},
854
        };
855

856
        int r, c;
124✔
857

858
        assert(argc >= 0);
124✔
859
        assert(argv);
124✔
860

861
        /* Resetting to 0 forces the invocation of an internal initialization routine of getopt_long()
862
         * that checks for GNU extensions in optstring ('-' or '+' at the beginning). */
863
        optind = 0;
124✔
864
        while ((c = getopt_long(argc, argv, "+hVu:g:D:a:", options, NULL)) >= 0)
275✔
865

866
                switch (c) {
151✔
867

868
                case 'h':
×
869
                        return help_sudo_mode();
124✔
870

871
                case 'V':
×
872
                        return version();
×
873

874
                case ARG_NO_ASK_PASSWORD:
×
875
                        arg_ask_password = false;
×
876
                        break;
×
877

878
                case ARG_MACHINE:
×
879
                        arg_transport = BUS_TRANSPORT_MACHINE;
×
880
                        arg_host = optarg;
×
881
                        break;
×
882

883
                case ARG_UNIT:
4✔
884
                        arg_unit = optarg;
4✔
885
                        break;
4✔
886

887
                case ARG_PROPERTY:
38✔
888
                        if (strv_extend(&arg_property, optarg) < 0)
38✔
889
                                return log_oom();
×
890

891
                        break;
892

893
                case ARG_DESCRIPTION:
×
894
                        r = free_and_strdup_warn(&arg_description, optarg);
×
895
                        if (r < 0)
×
896
                                return r;
897
                        break;
898

899
                case ARG_SLICE:
×
900
                        arg_slice = optarg;
×
901
                        break;
×
902

903
                case ARG_SLICE_INHERIT:
×
904
                        arg_slice_inherit = true;
×
905
                        break;
×
906

907
                case 'u':
65✔
908
                        arg_exec_user = optarg;
65✔
909
                        break;
65✔
910

911
                case 'g':
×
912
                        arg_exec_group = optarg;
×
913
                        break;
×
914

915
                case ARG_NICE:
×
916
                        r = parse_nice(optarg, &arg_nice);
×
917
                        if (r < 0)
×
918
                                return log_error_errno(r, "Failed to parse nice value: %s", optarg);
×
919

920
                        arg_nice_set = true;
×
921
                        break;
×
922

923
                case 'D':
4✔
924
                        /* Root will be manually suppressed later. */
925
                        r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_working_directory);
4✔
926
                        if (r < 0)
4✔
927
                                return r;
928

929
                        break;
930

931
                case ARG_SETENV:
×
932
                        r = strv_env_replace_strdup_passthrough(&arg_environment, optarg);
×
933
                        if (r < 0)
×
934
                                return log_error_errno(r, "Cannot assign environment variable %s: %m", optarg);
×
935

936
                        break;
937

938
                case ARG_BACKGROUND:
×
939
                        r = free_and_strdup_warn(&arg_background, optarg);
×
940
                        if (r < 0)
×
941
                                return r;
942

943
                        break;
944

945
                case ARG_PTY:
3✔
946
                case ARG_PTY_LATE:
947
                        arg_stdio |= ARG_STDIO_PTY;
3✔
948
                        arg_pty_late = c == ARG_PTY_LATE;
3✔
949
                        break;
3✔
950

951
                case ARG_PIPE:
8✔
952
                        arg_stdio |= ARG_STDIO_DIRECT;
8✔
953
                        break;
8✔
954

955
                case ARG_SHELL_PROMPT_PREFIX:
×
956
                        r = free_and_strdup_warn(&arg_shell_prompt_prefix, optarg);
×
957
                        if (r < 0)
×
958
                                return r;
959
                        break;
960

961
                case ARG_LIGHTWEIGHT:
2✔
962
                        r = parse_tristate_argument("--lightweight=", optarg, &arg_lightweight);
2✔
963
                        if (r < 0)
2✔
964
                                return r;
965
                        break;
966

967
                case 'a':
27✔
968
                        /* We allow an empty --area= specification to allow logging into the primary home directory */
969
                        if (!isempty(optarg) && !filename_is_valid(optarg))
54✔
970
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid area name, refusing: %s", optarg);
×
971

972
                        r = free_and_strdup_warn(&arg_area, optarg);
27✔
973
                        if (r < 0)
27✔
974
                                return r;
975

976
                        break;
977

978
                case '?':
979
                        return -EINVAL;
980

981
                default:
×
982
                        assert_not_reached();
×
983
                }
984

985
        if (!arg_exec_user && arg_area) {
124✔
986
                /* If the user specifies --area= but not --user= then consider this an area switch request,
987
                 * and default to logging into our own account */
988
                arg_exec_user = getusername_malloc();
×
989
                if (!arg_exec_user)
×
990
                        return log_oom();
×
991
        }
992

993
        if (!arg_working_directory) {
124✔
994
                if (arg_exec_user) {
120✔
995
                        /* When switching to a specific user, also switch to its home directory. */
996
                        arg_working_directory = strdup("~");
63✔
997
                        if (!arg_working_directory)
63✔
998
                                return log_oom();
×
999
                } else {
1000
                        /* When switching to root without this being specified, then stay in the current directory */
1001
                        r = safe_getcwd(&arg_working_directory);
57✔
1002
                        if (r < 0)
57✔
1003
                                return log_error_errno(r, "Failed to get current working directory: %m");
×
1004
                }
1005
        } else {
1006
                /* Root was not suppressed earlier, to allow the above check to work properly. */
1007
                if (empty_or_root(arg_working_directory))
4✔
1008
                        arg_working_directory = mfree(arg_working_directory);
2✔
1009
        }
1010

1011
        arg_service_type = "exec";
124✔
1012
        arg_quiet = true;
124✔
1013
        arg_wait = true;
124✔
1014
        arg_aggressive_gc = true;
124✔
1015

1016
        if (IN_SET(arg_stdio, ARG_STDIO_NONE, ARG_STDIO_AUTO))
124✔
1017
                arg_stdio = isatty_safe(STDIN_FILENO) && isatty_safe(STDOUT_FILENO) && isatty_safe(STDERR_FILENO) ? ARG_STDIO_PTY : ARG_STDIO_DIRECT;
115✔
1018
        log_debug("Using %s stdio mode.", arg_stdio == ARG_STDIO_PTY ? "pty" : "direct");
181✔
1019
        if (arg_pty_late < 0)
124✔
1020
                arg_pty_late = arg_ask_password; /* for run0 this defaults to on, except if --no-ask-pasword is used */
121✔
1021

1022
        arg_expand_environment = false;
124✔
1023
        arg_send_sighup = true;
124✔
1024

1025
        _cleanup_strv_free_ char **l = NULL;
124✔
1026
        if (argc > optind)
124✔
1027
                l = strv_copy(argv + optind);
124✔
1028
        else {
1029
                const char *e;
×
1030

1031
                e = strv_env_get(arg_environment, "SHELL");
×
1032
                if (e)
×
1033
                        arg_exec_path = strdup(e);
×
1034
                else {
1035
                        if (arg_transport == BUS_TRANSPORT_LOCAL) {
×
1036
                                r = get_shell(&arg_exec_path);
×
1037
                                if (r < 0)
×
1038
                                        return log_error_errno(r, "Failed to determine shell: %m");
×
1039
                        } else
1040
                                arg_exec_path = strdup("/bin/sh");
×
1041
                }
1042
                if (!arg_exec_path)
×
1043
                        return log_oom();
×
1044

1045
                l = make_login_shell_cmdline(arg_exec_path);
×
1046
        }
1047
        if (!l)
124✔
1048
                return log_oom();
×
1049

1050
        strv_free_and_replace(arg_cmdline, l);
124✔
1051

1052
        if (!arg_slice) {
124✔
1053
                arg_slice = strdup(SPECIAL_USER_SLICE);
124✔
1054
                if (!arg_slice)
124✔
1055
                        return log_oom();
×
1056
        }
1057

1058
        _cleanup_free_ char *un = NULL;
124✔
1059
        un = getusername_malloc();
124✔
1060
        if (!un)
124✔
1061
                return log_oom();
×
1062

1063
        /* Set a bunch of environment variables in a roughly sudo-compatible way */
1064
        r = strv_env_assign(&arg_environment, "SUDO_USER", un);
124✔
1065
        if (r < 0)
124✔
1066
                return log_error_errno(r, "Failed to set $SUDO_USER environment variable: %m");
×
1067

1068
        r = strv_env_assignf(&arg_environment, "SUDO_UID", UID_FMT, getuid());
124✔
1069
        if (r < 0)
124✔
1070
                return log_error_errno(r, "Failed to set $SUDO_UID environment variable: %m");
×
1071

1072
        r = strv_env_assignf(&arg_environment, "SUDO_GID", GID_FMT, getgid());
124✔
1073
        if (r < 0)
124✔
1074
                return log_error_errno(r, "Failed to set $SUDO_GID environment variable: %m");
×
1075

1076
        if (strv_extendf(&arg_property, "LogExtraFields=ELEVATED_UID=" UID_FMT, getuid()) < 0)
124✔
1077
                return log_oom();
×
1078

1079
        if (strv_extendf(&arg_property, "LogExtraFields=ELEVATED_GID=" GID_FMT, getgid()) < 0)
124✔
1080
                return log_oom();
×
1081

1082
        if (strv_extendf(&arg_property, "LogExtraFields=ELEVATED_USER=%s", un) < 0)
124✔
1083
                return log_oom();
×
1084

1085
        if (strv_extend(&arg_property, "PAMName=systemd-run0") < 0)
124✔
1086
                return log_oom();
×
1087

1088
        if (!arg_background && arg_stdio == ARG_STDIO_PTY && shall_tint_background()) {
124✔
1089
                double hue;
2✔
1090

1091
                if (privileged_execution())
2✔
1092
                        hue = 0; /* red */
1093
                else
1094
                        hue = 60 /* yellow */;
×
1095

1096
                r = terminal_tint_color(hue, &arg_background);
2✔
1097
                if (r < 0)
2✔
1098
                        log_debug_errno(r, "Unable to get terminal background color, not tinting background: %m");
2✔
1099
        }
1100

1101
        if (!arg_shell_prompt_prefix) {
124✔
1102
                const char *e = secure_getenv("SYSTEMD_RUN_SHELL_PROMPT_PREFIX");
124✔
1103
                if (e) {
124✔
1104
                        arg_shell_prompt_prefix = strdup(e);
×
1105
                        if (!arg_shell_prompt_prefix)
×
1106
                                return log_oom();
×
1107
                } else if (emoji_enabled()) {
124✔
1108
                        arg_shell_prompt_prefix = strjoin(glyph(privileged_execution() ? GLYPH_SUPERHERO : GLYPH_IDCARD), " ");
×
1109
                        if (!arg_shell_prompt_prefix)
×
1110
                                return log_oom();
×
1111
                }
1112
        }
1113

1114
        if (!isempty(arg_shell_prompt_prefix)) {
124✔
1115
                r = strv_env_assign(&arg_environment, "SHELL_PROMPT_PREFIX", arg_shell_prompt_prefix);
×
1116
                if (r < 0)
×
1117
                        return log_error_errno(r, "Failed to set $SHELL_PROMPT_PREFIX environment variable: %m");
×
1118
        }
1119

1120
        if (!strv_env_get(arg_environment, "XDG_SESSION_CLASS")) {
124✔
1121

1122
                /* If logging into an area, imply lightweight mode */
1123
                if (arg_lightweight < 0 && !isempty(arg_area))
124✔
1124
                        arg_lightweight = true;
27✔
1125

1126
                /* When using run0 to acquire privileges temporarily, let's not pull in session manager by
1127
                 * default. Note that pam_logind/systemd-logind doesn't distinguish between run0-style privilege
1128
                 * escalation on a TTY and first class (getty-style) TTY logins (and thus gives root a per-session
1129
                 * manager for interactive TTY sessions), hence let's override the logic explicitly here. We only do
1130
                 * this for root though, under the assumption that if a regular user temporarily transitions into
1131
                 * another regular user it's a better default that the full user environment is uniformly
1132
                 * available. */
1133
                if (arg_lightweight < 0 && privileged_execution())
124✔
1134
                        arg_lightweight = true;
68✔
1135

1136
                if (arg_lightweight >= 0) {
124✔
1137
                        const char *class =
194✔
1138
                                arg_lightweight ? (arg_stdio == ARG_STDIO_PTY ? (privileged_execution() ? "user-early-light" : "user-light") : "background-light") :
97✔
1139
                                                  (arg_stdio == ARG_STDIO_PTY ? (privileged_execution() ? "user-early" : "user") : "background");
1✔
1140

1141
                        log_debug("Setting XDG_SESSION_CLASS to '%s'.", class);
97✔
1142

1143
                        r = strv_env_assign(&arg_environment, "XDG_SESSION_CLASS", class);
97✔
1144
                        if (r < 0)
97✔
1145
                                return log_error_errno(r, "Failed to set $XDG_SESSION_CLASS environment variable: %m");
×
1146
                }
1147
        }
1148

1149
        if (arg_area) {
124✔
1150
                r = strv_env_assign(&arg_environment, "XDG_AREA", arg_area);
27✔
1151
                if (r < 0)
27✔
1152
                        return log_error_errno(r, "Failed to set $XDG_AREA environment variable: %m");
×
1153
        }
1154

1155
        return 1;
1156
}
1157

1158
static int transient_unit_set_properties(sd_bus_message *m, UnitType t, char **properties) {
1,120✔
1159
        int r;
1,120✔
1160

1161
        assert(m);
1,120✔
1162

1163
        r = sd_bus_message_append(m, "(sv)", "Description", "s", arg_description);
1,120✔
1164
        if (r < 0)
1,120✔
1165
                return bus_log_create_error(r);
×
1166

1167
        if (arg_aggressive_gc) {
1,120✔
1168
                r = sd_bus_message_append(m, "(sv)", "CollectMode", "s", "inactive-or-failed");
129✔
1169
                if (r < 0)
129✔
1170
                        return bus_log_create_error(r);
×
1171
        }
1172

1173
        r = sd_bus_is_bus_client(sd_bus_message_get_bus(m));
1,120✔
1174
        if (r < 0)
1,120✔
1175
                return log_error_errno(r, "Can't determine if bus connection is direct or to broker: %m");
×
1176
        if (r > 0) {
1,120✔
1177
                /* Pin the object as least as long as we are around. Note that AddRef (currently) only works
1178
                 * if we talk via the bus though. */
1179
                r = sd_bus_message_append(m, "(sv)", "AddRef", "b", 1);
945✔
1180
                if (r < 0)
945✔
1181
                        return bus_log_create_error(r);
×
1182
        }
1183

1184
        return bus_append_unit_property_assignment_many(m, t, properties);
1,120✔
1185
}
1186

1187
static int transient_cgroup_set_properties(sd_bus_message *m) {
1,098✔
1188
        _cleanup_free_ char *name = NULL;
2,196✔
1189
        _cleanup_free_ char *slice = NULL;
1,098✔
1190
        int r;
1,098✔
1191

1192
        assert(m);
1,098✔
1193

1194
        if (arg_slice_inherit) {
1,098✔
1195
                char *end;
4✔
1196

1197
                switch (arg_runtime_scope) {
4✔
1198

1199
                case RUNTIME_SCOPE_USER:
×
1200
                        r = cg_pid_get_user_slice(0, &name);
×
1201
                        break;
1202

1203
                case RUNTIME_SCOPE_SYSTEM:
4✔
1204
                        r = cg_pid_get_slice(0, &name);
4✔
1205
                        break;
1206

1207
                default:
×
1208
                        assert_not_reached();
×
1209
                }
1210

1211
                if (r < 0)
4✔
1212
                        return log_error_errno(r, "Failed to get PID slice: %m");
×
1213

1214
                end = endswith(name, ".slice");
4✔
1215
                if (!end)
4✔
1216
                        return -ENXIO;
1217
                *end = 0;
4✔
1218
        }
1219

1220
        if (!isempty(arg_slice) && !strextend_with_separator(&name, "-", arg_slice))
1,252✔
1221
                return log_oom();
×
1222

1223
        if (!name)
1,098✔
1224
                return 0;
1225

1226
        r = unit_name_mangle_with_suffix(name, "as slice",
156✔
1227
                                         arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN,
156✔
1228
                                         ".slice", &slice);
1229
        if (r < 0)
156✔
1230
                return log_error_errno(r, "Failed to mangle name '%s': %m", arg_slice);
×
1231

1232
        r = sd_bus_message_append(m, "(sv)", "Slice", "s", slice);
156✔
1233
        if (r < 0)
156✔
1234
                return bus_log_create_error(r);
×
1235

1236
        return 0;
1237
}
1238

1239
static int transient_kill_set_properties(sd_bus_message *m) {
1,098✔
1240
        int r;
1,098✔
1241

1242
        assert(m);
1,098✔
1243

1244
        if (arg_send_sighup) {
1,098✔
1245
                r = sd_bus_message_append(m, "(sv)", "SendSIGHUP", "b", arg_send_sighup);
125✔
1246
                if (r < 0)
125✔
1247
                        return bus_log_create_error(r);
×
1248
        }
1249

1250
        return 0;
1251
}
1252

1253
static int transient_service_set_properties(sd_bus_message *m, const char *pty_path, int pty_fd) {
1,083✔
1254
        int r, send_term; /* tri-state */
1,083✔
1255

1256
        /* We disable environment expansion on the server side via ExecStartEx=:.
1257
         * ExecStartEx was added relatively recently (v243), and some bugs were fixed only later.
1258
         * So use that feature only if required. It will fail with older systemds. */
1259
        bool use_ex_prop = !arg_expand_environment;
1,083✔
1260

1261
        assert(m);
1,083✔
1262
        assert((!!pty_path) == (pty_fd >= 0));
1,083✔
1263

1264
        r = transient_unit_set_properties(m, UNIT_SERVICE, arg_property);
1,083✔
1265
        if (r < 0)
1,083✔
1266
                return r;
1267

1268
        r = transient_kill_set_properties(m);
1,079✔
1269
        if (r < 0)
1,079✔
1270
                return r;
1271

1272
        r = transient_cgroup_set_properties(m);
1,079✔
1273
        if (r < 0)
1,079✔
1274
                return r;
1275

1276
        if (arg_remain_after_exit) {
1,079✔
1277
                r = sd_bus_message_append(m, "(sv)", "RemainAfterExit", "b", arg_remain_after_exit);
26✔
1278
                if (r < 0)
26✔
1279
                        return bus_log_create_error(r);
×
1280
        }
1281

1282
        if (arg_service_type) {
1,079✔
1283
                r = sd_bus_message_append(m, "(sv)", "Type", "s", arg_service_type);
148✔
1284
                if (r < 0)
148✔
1285
                        return bus_log_create_error(r);
×
1286
        }
1287

1288
        if (arg_exec_user) {
1,079✔
1289
                r = sd_bus_message_append(m, "(sv)", "User", "s", arg_exec_user);
75✔
1290
                if (r < 0)
75✔
1291
                        return bus_log_create_error(r);
×
1292
        }
1293

1294
        if (arg_exec_group) {
1,079✔
1295
                r = sd_bus_message_append(m, "(sv)", "Group", "s", arg_exec_group);
2✔
1296
                if (r < 0)
2✔
1297
                        return bus_log_create_error(r);
×
1298
        }
1299

1300
        if (arg_nice_set) {
1,079✔
1301
                r = sd_bus_message_append(m, "(sv)", "Nice", "i", arg_nice);
1✔
1302
                if (r < 0)
1✔
1303
                        return bus_log_create_error(r);
×
1304
        }
1305

1306
        if (arg_working_directory) {
1,079✔
1307
                r = sd_bus_message_append(m, "(sv)", "WorkingDirectory", "s", arg_working_directory);
125✔
1308
                if (r < 0)
125✔
1309
                        return bus_log_create_error(r);
×
1310
        }
1311

1312
        if (pty_path) {
1,079✔
1313
                r = sd_bus_message_append(m, "(sv)(sv)(sv)(sv)",
10✔
1314
                                          "TTYPath", "s", pty_path,
1315
                                          "StandardInputFileDescriptor", "h", pty_fd,
1316
                                          "StandardOutputFileDescriptor", "h", pty_fd,
1317
                                          "StandardErrorFileDescriptor", "h", pty_fd);
1318
                if (r < 0)
10✔
1319
                        return bus_log_create_error(r);
×
1320

1321
                send_term = true;
1322

1323
        } else if (arg_stdio == ARG_STDIO_DIRECT) {
1,069✔
1324
                r = sd_bus_message_append(m,
346✔
1325
                                          "(sv)(sv)(sv)",
1326
                                          "StandardInputFileDescriptor", "h", STDIN_FILENO,
1327
                                          "StandardOutputFileDescriptor", "h", STDOUT_FILENO,
1328
                                          "StandardErrorFileDescriptor", "h", STDERR_FILENO);
1329
                if (r < 0)
346✔
1330
                        return bus_log_create_error(r);
×
1331

1332
                send_term = -1;
1333
        } else
1334
                send_term = false;
1335

1336
        if (send_term != 0) {
1337
                const char *e, *colorterm = NULL, *no_color = NULL;
356✔
1338

1339
                /* Propagate $TERM + $COLORTERM + $NO_COLOR if we are actually connected to a TTY */
1340
                if (isatty_safe(STDIN_FILENO) || isatty_safe(STDOUT_FILENO) || isatty_safe(STDERR_FILENO)) {
356✔
1341
                        e = strv_find_prefix(environ, "TERM=");
×
1342
                        send_term = !!e;
×
1343

1344
                        if (send_term) {
×
1345
                                /* If we send $TERM along, then also propagate $COLORTERM + $NO_COLOR right with it */
1346
                                colorterm = strv_find_prefix(environ, "COLORTERM=");
×
1347
                                no_color = strv_find_prefix(environ, "NO_COLOR=");
×
1348
                        }
1349
                } else
1350
                        /* If we are not connected to any TTY ourselves, then send TERM=dumb, but only if we
1351
                         * really need to (because we actually allocated a TTY for the service) */
1352
                        e = "TERM=dumb";
1353

1354
                if (send_term > 0) {
356✔
1355
                        r = sd_bus_message_append(
10✔
1356
                                        m,
1357
                                        "(sv)",
1358
                                        "Environment", "as", 1, e);
1359
                        if (r < 0)
10✔
1360
                                return bus_log_create_error(r);
×
1361

1362
                        if (colorterm) {
10✔
1363
                                r = sd_bus_message_append(
×
1364
                                                m,
1365
                                                "(sv)",
1366
                                                "Environment", "as", 1, colorterm);
1367
                                if (r < 0)
×
1368
                                        return bus_log_create_error(r);
×
1369
                        }
1370

1371
                        if (no_color) {
10✔
1372
                                r = sd_bus_message_append(
×
1373
                                                m,
1374
                                                "(sv)",
1375
                                                "Environment", "as", 1, no_color);
1376
                                if (r < 0)
×
1377
                                        return bus_log_create_error(r);
×
1378
                        }
1379
                }
1380
        }
1381

1382
        if (!strv_isempty(arg_environment)) {
1,079✔
1383
                r = sd_bus_message_open_container(m, 'r', "sv");
126✔
1384
                if (r < 0)
126✔
1385
                        return bus_log_create_error(r);
×
1386

1387
                r = sd_bus_message_append(m, "s", "Environment");
126✔
1388
                if (r < 0)
126✔
1389
                        return bus_log_create_error(r);
×
1390

1391
                r = sd_bus_message_open_container(m, 'v', "as");
126✔
1392
                if (r < 0)
126✔
1393
                        return bus_log_create_error(r);
×
1394

1395
                r = sd_bus_message_append_strv(m, arg_environment);
126✔
1396
                if (r < 0)
126✔
1397
                        return bus_log_create_error(r);
×
1398

1399
                r = sd_bus_message_close_container(m);
126✔
1400
                if (r < 0)
126✔
1401
                        return bus_log_create_error(r);
×
1402

1403
                r = sd_bus_message_close_container(m);
126✔
1404
                if (r < 0)
126✔
1405
                        return bus_log_create_error(r);
×
1406
        }
1407

1408
        /* Exec container */
1409
        if (!strv_isempty(arg_cmdline)) {
2,162✔
1410
                r = sd_bus_message_open_container(m, 'r', "sv");
1,079✔
1411
                if (r < 0)
1,079✔
1412
                        return bus_log_create_error(r);
×
1413

1414
                r = sd_bus_message_append(m, "s",
2,033✔
1415
                                          use_ex_prop ? "ExecStartEx" : "ExecStart");
1416
                if (r < 0)
1,079✔
1417
                        return bus_log_create_error(r);
×
1418

1419
                r = sd_bus_message_open_container(m, 'v',
2,033✔
1420
                                                  use_ex_prop ? "a(sasas)" : "a(sasb)");
1421
                if (r < 0)
1,079✔
1422
                        return bus_log_create_error(r);
×
1423

1424
                r = sd_bus_message_open_container(m, 'a',
2,033✔
1425
                                                  use_ex_prop ? "(sasas)" : "(sasb)");
1426
                if (r < 0)
1,079✔
1427
                        return bus_log_create_error(r);
×
1428

1429
                r = sd_bus_message_open_container(m, 'r',
2,033✔
1430
                                                  use_ex_prop ? "sasas" : "sasb");
1431
                if (r < 0)
1,079✔
1432
                        return bus_log_create_error(r);
×
1433

1434
                r = sd_bus_message_append(m, "s", arg_exec_path ?: arg_cmdline[0]);
1,079✔
1435
                if (r < 0)
1,079✔
1436
                        return bus_log_create_error(r);
×
1437

1438
                r = sd_bus_message_append_strv(m, arg_cmdline);
1,079✔
1439
                if (r < 0)
1,079✔
1440
                        return bus_log_create_error(r);
×
1441

1442
                if (use_ex_prop) {
1,079✔
1443
                        _cleanup_strv_free_ char **opts = NULL;
×
1444

1445
                        r = exec_command_flags_to_strv(
375✔
1446
                                        (arg_expand_environment ? 0 : EXEC_COMMAND_NO_ENV_EXPAND)|(arg_ignore_failure ? EXEC_COMMAND_IGNORE_FAILURE : 0),
250✔
1447
                                        &opts);
1448
                        if (r < 0)
125✔
1449
                                return log_error_errno(r, "Failed to format execute flags: %m");
×
1450

1451
                        r = sd_bus_message_append_strv(m, opts);
125✔
1452
                } else
1453
                        r = sd_bus_message_append(m, "b", arg_ignore_failure);
954✔
1454
                if (r < 0)
1,079✔
1455
                        return bus_log_create_error(r);
×
1456

1457
                r = sd_bus_message_close_container(m);
1,079✔
1458
                if (r < 0)
1,079✔
1459
                        return bus_log_create_error(r);
×
1460

1461
                r = sd_bus_message_close_container(m);
1,079✔
1462
                if (r < 0)
1,079✔
1463
                        return bus_log_create_error(r);
×
1464

1465
                r = sd_bus_message_close_container(m);
1,079✔
1466
                if (r < 0)
1,079✔
1467
                        return bus_log_create_error(r);
×
1468

1469
                r = sd_bus_message_close_container(m);
1,079✔
1470
                if (r < 0)
1,079✔
1471
                        return bus_log_create_error(r);
×
1472
        }
1473

1474
        return 0;
1475
}
1476

1477
static int transient_scope_set_properties(sd_bus_message *m, bool allow_pidfd) {
19✔
1478
        int r;
19✔
1479

1480
        assert(m);
19✔
1481

1482
        r = transient_unit_set_properties(m, UNIT_SCOPE, arg_property);
19✔
1483
        if (r < 0)
19✔
1484
                return r;
19✔
1485

1486
        r = transient_kill_set_properties(m);
19✔
1487
        if (r < 0)
19✔
1488
                return r;
1489

1490
        r = transient_cgroup_set_properties(m);
19✔
1491
        if (r < 0)
19✔
1492
                return r;
1493

1494
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
19✔
1495

1496
        r = pidref_set_self(&pidref);
19✔
1497
        if (r < 0)
19✔
1498
                return r;
1499

1500
        r = bus_append_scope_pidref(m, &pidref, allow_pidfd);
19✔
1501
        if (r < 0)
19✔
1502
                return bus_log_create_error(r);
×
1503

1504
        return 0;
1505
}
1506

1507
static int transient_timer_set_properties(sd_bus_message *m) {
15✔
1508
        int r;
15✔
1509

1510
        assert(m);
15✔
1511

1512
        r = transient_unit_set_properties(m, UNIT_TIMER, arg_timer_property);
15✔
1513
        if (r < 0)
15✔
1514
                return r;
1515

1516
        /* Automatically clean up our transient timers */
1517
        r = sd_bus_message_append(m, "(sv)", "RemainAfterElapse", "b", false);
10✔
1518
        if (r < 0)
10✔
1519
                return bus_log_create_error(r);
×
1520

1521
        return 0;
1522
}
1523

1524
static int make_unit_name(UnitType t, char **ret) {
581✔
1525
        int r;
581✔
1526

1527
        assert(t >= 0);
581✔
1528
        assert(t < _UNIT_TYPE_MAX);
581✔
1529
        assert(ret);
581✔
1530

1531
        /* Preferably use our PID + pidfd ID as identifier, if available. It's a boot time unique identifier
1532
         * managed by the kernel. Unfortunately only new kernels support this, hence we keep some fallback
1533
         * logic in place. */
1534

1535
        _cleanup_(pidref_done) PidRef self = PIDREF_NULL;
581✔
1536
        r = pidref_set_self(&self);
581✔
1537
        if (r < 0)
581✔
1538
                return log_error_errno(r, "Failed to get reference to my own process: %m");
×
1539

1540
        r = pidref_acquire_pidfd_id(&self);
581✔
1541
        if (r < 0) {
581✔
1542
                log_debug_errno(r, "Failed to acquire pidfd ID of myself, defaulting to randomized unit name: %m");
467✔
1543

1544
                /* We couldn't get the pidfd id. In that case, just pick a random uuid as name */
1545
                sd_id128_t rnd;
467✔
1546
                r = sd_id128_randomize(&rnd);
467✔
1547
                if (r < 0)
467✔
1548
                        return log_error_errno(r, "Failed to generate random run unit name: %m");
×
1549

1550
                r = asprintf(ret, "run-r" SD_ID128_FORMAT_STR ".%s", SD_ID128_FORMAT_VAL(rnd), unit_type_to_string(t));
467✔
1551
        } else
1552
                r = asprintf(ret, "run-p" PID_FMT "-i%" PRIu64 ".%s", self.pid, self.fd_id, unit_type_to_string(t));
114✔
1553
        if (r < 0)
581✔
1554
                return log_oom();
×
1555

1556
        return 0;
1557
}
1558

1559
static int connect_bus(sd_bus **ret) {
1,111✔
1560
        _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1,111✔
1561
        int r;
1,111✔
1562

1563
        assert(ret);
1,111✔
1564

1565
        /* If --wait is used connect via the bus, unconditionally, as ref/unref is not supported via the
1566
         * limited direct connection */
1567
        if (arg_wait ||
1,111✔
1568
            arg_stdio != ARG_STDIO_NONE ||
229✔
1569
            (arg_runtime_scope == RUNTIME_SCOPE_USER && !IN_SET(arg_transport, BUS_TRANSPORT_LOCAL, BUS_TRANSPORT_CAPSULE)))
164✔
1570
                r = bus_connect_transport(arg_transport, arg_host, arg_runtime_scope, &bus);
949✔
1571
        else
1572
                r = bus_connect_transport_systemd(arg_transport, arg_host, arg_runtime_scope, &bus);
162✔
1573
        if (r < 0)
1,111✔
1574
                return bus_log_connect_error(r, arg_transport, arg_runtime_scope);
1,111✔
1575

1576
        (void) sd_bus_set_allow_interactive_authorization(bus, arg_ask_password);
1,107✔
1577

1578
        *ret = TAKE_PTR(bus);
1,107✔
1579
        return 0;
1,107✔
1580
}
1581

1582
typedef struct RunContext {
1583
        sd_event *event;
1584
        PTYForward *forward;
1585
        char *unit;
1586
        char *bus_path;
1587
        char *start_job;
1588
        int pty_fd;
1589

1590
        /* Bus objects */
1591
        sd_bus *bus;
1592
        sd_bus_slot *match_properties_changed;
1593
        sd_bus_slot *match_disconnected;
1594
        sd_event_source *retry_timer;
1595

1596
        /* Current state of the unit */
1597
        char *active_state;
1598
        char *job;
1599

1600
        /* The exit data of the unit */
1601
        uint64_t inactive_exit_usec;
1602
        uint64_t inactive_enter_usec;
1603
        char *result;
1604
        uint64_t cpu_usage_nsec;
1605
        uint64_t memory_peak;
1606
        uint64_t memory_swap_peak;
1607
        uint64_t ip_ingress_bytes;
1608
        uint64_t ip_egress_bytes;
1609
        uint64_t io_read_bytes;
1610
        uint64_t io_write_bytes;
1611
        uint32_t exit_code;
1612
        uint32_t exit_status;
1613
} RunContext;
1614

1615
static int run_context_update(RunContext *c);
1616
static int run_context_attach_bus(RunContext *c, sd_bus *bus);
1617
static void run_context_detach_bus(RunContext *c);
1618
static int run_context_reconnect(RunContext *c);
1619
static int run_context_setup_ptyfwd(RunContext *c);
1620

1621
static void run_context_done(RunContext *c) {
1,070✔
1622
        assert(c);
1,070✔
1623

1624
        run_context_detach_bus(c);
1,070✔
1625

1626
        c->retry_timer = sd_event_source_disable_unref(c->retry_timer);
1,070✔
1627
        c->forward = pty_forward_free(c->forward);
1,070✔
1628
        c->event = sd_event_unref(c->event);
1,070✔
1629

1630
        free(c->active_state);
1,070✔
1631
        free(c->job);
1,070✔
1632
        free(c->result);
1,070✔
1633
        free(c->unit);
1,070✔
1634
        free(c->bus_path);
1,070✔
1635
        free(c->start_job);
1,070✔
1636

1637
        safe_close(c->pty_fd);
1,070✔
1638
}
1,070✔
1639

1640
static int on_retry_timer(sd_event_source *s, uint64_t usec, void *userdata) {
×
1641
        RunContext *c = ASSERT_PTR(userdata);
×
1642

1643
        c->retry_timer = sd_event_source_disable_unref(c->retry_timer);
×
1644

1645
        return run_context_reconnect(c);
×
1646
}
1647

1648
static int run_context_reconnect(RunContext *c) {
×
1649
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
×
UNCOV
1650
        _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
×
1651
        int r;
×
1652

1653
        assert(c);
×
1654

1655
        run_context_detach_bus(c);
×
1656

1657
        r = connect_bus(&bus);
×
1658
        if (r < 0)
×
UNCOV
1659
                goto retry_timer;
×
1660

UNCOV
1661
        r = sd_bus_call_method(bus,
×
1662
                               "org.freedesktop.systemd1",
UNCOV
1663
                               c->bus_path,
×
1664
                               "org.freedesktop.systemd1.Unit",
1665
                               "Ref",
1666
                               &error,
1667
                               /* reply = */ NULL, NULL);
UNCOV
1668
        if (r < 0) {
×
1669
                /* Hmm, the service manager probably hasn't finished reexecution just yet? Try again later. */
1670
                if (sd_bus_error_has_names(&error,
×
1671
                                           SD_BUS_ERROR_NO_REPLY,
1672
                                           SD_BUS_ERROR_DISCONNECTED,
1673
                                           SD_BUS_ERROR_TIMED_OUT,
1674
                                           SD_BUS_ERROR_SERVICE_UNKNOWN,
1675
                                           SD_BUS_ERROR_NAME_HAS_NO_OWNER))
UNCOV
1676
                        goto retry_timer;
×
1677

1678
                if (sd_bus_error_has_name(&error, SD_BUS_ERROR_UNKNOWN_OBJECT))
×
1679
                        log_warning_errno(r, "Unit deactivated during reconnection to the bus, exiting.");
×
1680
                else
UNCOV
1681
                        log_error_errno(r, "Failed to re-add reference to unit: %s", bus_error_message(&error, r));
×
1682

1683
                (void) sd_event_exit(c->event, EXIT_FAILURE);
×
1684
                return r;
1685
        }
1686

UNCOV
1687
        r = run_context_attach_bus(c, bus);
×
UNCOV
1688
        if (r < 0) {
×
UNCOV
1689
                (void) sd_event_exit(c->event, EXIT_FAILURE);
×
1690
                return r;
1691
        }
1692

UNCOV
1693
        log_info("Reconnected to bus.");
×
1694

UNCOV
1695
        return run_context_update(c);
×
1696

UNCOV
1697
retry_timer:
×
UNCOV
1698
        log_warning_errno(r, "Failed to reconnect, retrying in 2s: %m");
×
1699

UNCOV
1700
        r = event_reset_time_relative(
×
1701
                        c->event,
1702
                        &c->retry_timer,
1703
                        CLOCK_MONOTONIC,
1704
                        2 * USEC_PER_SEC, /* accuracy= */ 0,
1705
                        on_retry_timer, c,
1706
                        SD_EVENT_PRIORITY_NORMAL,
1707
                        "retry-timeout",
1708
                        /* force_reset= */ false);
UNCOV
1709
        if (r < 0) {
×
UNCOV
1710
                (void) sd_event_exit(c->event, EXIT_FAILURE);
×
UNCOV
1711
                return log_error_errno(r, "Failed to install retry timer: %m");
×
1712
        }
1713

1714
        return 0;
1715
}
1716

1717
static int run_context_check_started(RunContext *c) {
5,695✔
1718
        int r;
5,695✔
1719

1720
        assert(c);
5,695✔
1721

1722
        if (!c->start_job)
5,695✔
1723
                return 0; /* Already started? */
1724

1725
        if (streq_ptr(c->start_job, c->job))
1,773✔
1726
                return 0; /* The start job is still active. */
1727

1728
        /* The start job is finished. */
1729
        c->start_job = mfree(c->start_job);
355✔
1730

1731
        /* Setup ptyfwd now if --pty-late is specified. */
1732
        r = run_context_setup_ptyfwd(c);
355✔
1733
        if (r < 0) {
355✔
UNCOV
1734
                (void) sd_event_exit(c->event, EXIT_FAILURE);
×
UNCOV
1735
                return r;
×
1736
        }
1737

1738
        if (STRPTR_IN_SET(c->active_state, "inactive", "failed"))
355✔
1739
                return 0; /* Already finished or failed? */
31✔
1740

1741
        /* Notify our caller that the service is now running, just in case. */
1742
        (void) sd_notifyf(/* unset_environment= */ false,
324✔
1743
                          "READY=1\n"
1744
                          "RUN_UNIT=%s",
1745
                          c->unit);
1746
        return 0;
324✔
1747
}
1748

1749
static void run_context_check_done(RunContext *c) {
5,705✔
1750
        assert(c);
5,705✔
1751

1752
        bool done = STRPTR_IN_SET(c->active_state, "inactive", "failed") &&
5,705✔
1753
                !c->start_job &&   /* our start job */
1,013✔
1754
                !c->job;           /* any other job */
938✔
1755

1756
        if (done && c->forward) /* If the service is gone, it's time to drain the output */
938✔
1757
                done = pty_forward_drain(c->forward);
20✔
1758

1759
        if (done)
938✔
1760
                (void) sd_event_exit(c->event, EXIT_SUCCESS);
937✔
1761
}
5,705✔
1762

1763
static int map_job(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
5,695✔
1764
        char **p = ASSERT_PTR(userdata);
5,695✔
1765
        const char *job;
5,695✔
1766
        uint32_t id;
5,695✔
1767
        int r;
5,695✔
1768

1769
        assert(m);
5,695✔
1770

1771
        r = sd_bus_message_read(m, "(uo)", &id, &job);
5,695✔
1772
        if (r < 0)
5,695✔
1773
                return r;
5,695✔
1774

1775
        return free_and_strdup(p, id == 0 ? NULL : job);
5,695✔
1776
}
1777

1778
static int run_context_update(RunContext *c) {
5,695✔
1779

1780
        static const struct bus_properties_map map[] = {
5,695✔
1781
                { "ActiveState",                     "s",    NULL,    offsetof(RunContext, active_state)        },
1782
                { "InactiveExitTimestampMonotonic",  "t",    NULL,    offsetof(RunContext, inactive_exit_usec)  },
1783
                { "InactiveEnterTimestampMonotonic", "t",    NULL,    offsetof(RunContext, inactive_enter_usec) },
1784
                { "Result",                          "s",    NULL,    offsetof(RunContext, result)              },
1785
                { "ExecMainCode",                    "i",    NULL,    offsetof(RunContext, exit_code)           },
1786
                { "ExecMainStatus",                  "i",    NULL,    offsetof(RunContext, exit_status)         },
1787
                { "CPUUsageNSec",                    "t",    NULL,    offsetof(RunContext, cpu_usage_nsec)      },
1788
                { "MemoryPeak",                      "t",    NULL,    offsetof(RunContext, memory_peak)         },
1789
                { "MemorySwapPeak",                  "t",    NULL,    offsetof(RunContext, memory_swap_peak)    },
1790
                { "IPIngressBytes",                  "t",    NULL,    offsetof(RunContext, ip_ingress_bytes)    },
1791
                { "IPEgressBytes",                   "t",    NULL,    offsetof(RunContext, ip_egress_bytes)     },
1792
                { "IOReadBytes",                     "t",    NULL,    offsetof(RunContext, io_read_bytes)       },
1793
                { "IOWriteBytes",                    "t",    NULL,    offsetof(RunContext, io_write_bytes)      },
1794
                { "Job",                             "(uo)", map_job, offsetof(RunContext, job)                 },
1795
                {}
1796
        };
1797

1798
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5,695✔
1799
        int r;
5,695✔
1800

1801
        assert(c);
5,695✔
1802
        assert(c->bus);
5,695✔
1803

1804
        r = bus_map_all_properties(
11,390✔
1805
                        c->bus,
1806
                        "org.freedesktop.systemd1",
1807
                        c->bus_path,
5,695✔
1808
                        map,
1809
                        BUS_MAP_STRDUP,
1810
                        &error,
1811
                        NULL,
1812
                        c);
1813
        if (r < 0) {
5,695✔
1814
                /* If this is a connection error, then try to reconnect. This might be because the service
1815
                 * manager is being restarted. Handle this gracefully. */
1816
                if (sd_bus_error_has_names(
×
1817
                                    &error,
1818
                                    SD_BUS_ERROR_NO_REPLY,
1819
                                    SD_BUS_ERROR_DISCONNECTED,
1820
                                    SD_BUS_ERROR_TIMED_OUT,
1821
                                    SD_BUS_ERROR_SERVICE_UNKNOWN,
1822
                                    SD_BUS_ERROR_NAME_HAS_NO_OWNER)) {
1823

UNCOV
1824
                        log_info_errno(r, "Bus call failed due to connection problems. Trying to reconnect...");
×
1825
                        /* Not propagating error, because we handled it already, by reconnecting. */
UNCOV
1826
                        return run_context_reconnect(c);
×
1827
                }
1828

UNCOV
1829
                (void) sd_event_exit(c->event, EXIT_FAILURE);
×
UNCOV
1830
                return log_error_errno(r, "Failed to query unit state: %s", bus_error_message(&error, r));
×
1831
        }
1832

1833
        r = run_context_check_started(c);
5,695✔
1834
        if (r < 0)
5,695✔
1835
                return r;
1836

1837
        run_context_check_done(c);
5,695✔
1838
        return 0;
1839
}
1840

1841
static int on_properties_changed(sd_bus_message *m, void *userdata, sd_bus_error *error) {
4,767✔
1842
        return run_context_update(ASSERT_PTR(userdata));
4,767✔
1843
}
1844

UNCOV
1845
static int on_disconnected(sd_bus_message *m, void *userdata, sd_bus_error *error) {
×
1846
        /* If our connection gets terminated, then try to reconnect. This might be because the service
1847
         * manager is being restarted. Handle this gracefully. */
UNCOV
1848
        log_info("Got disconnected from bus connection. Trying to reconnect...");
×
UNCOV
1849
        return run_context_reconnect(ASSERT_PTR(userdata));
×
1850
}
1851

1852
static int run_context_attach_bus(RunContext *c, sd_bus *bus) {
928✔
1853
        int r;
928✔
1854

1855
        assert(c);
928✔
1856
        assert(bus);
928✔
1857

1858
        assert(!c->bus);
928✔
1859
        assert(!c->match_properties_changed);
928✔
1860
        assert(!c->match_disconnected);
928✔
1861

1862
        c->bus = sd_bus_ref(bus);
928✔
1863

1864
        r = sd_bus_match_signal_async(
1,856✔
1865
                        c->bus,
1866
                        &c->match_properties_changed,
1867
                        "org.freedesktop.systemd1",
1868
                        c->bus_path,
928✔
1869
                        "org.freedesktop.DBus.Properties",
1870
                        "PropertiesChanged",
1871
                        on_properties_changed, NULL, c);
1872
        if (r < 0)
928✔
UNCOV
1873
                return log_error_errno(r, "Failed to request PropertiesChanged signal match: %m");
×
1874

1875
        r = sd_bus_match_signal_async(
928✔
1876
                        bus,
1877
                        &c->match_disconnected,
1878
                        "org.freedesktop.DBus.Local",
1879
                        /* path= */ NULL,
1880
                        "org.freedesktop.DBus.Local",
1881
                        "Disconnected",
1882
                        on_disconnected, NULL, c);
1883
        if (r < 0)
928✔
1884
                return log_error_errno(r, "Failed to request Disconnected signal match: %m");
×
1885

1886
        r = sd_bus_attach_event(c->bus, c->event, SD_EVENT_PRIORITY_NORMAL);
928✔
1887
        if (r < 0)
928✔
UNCOV
1888
                return log_error_errno(r, "Failed to attach bus to event loop: %m");
×
1889

1890
        return 0;
1891
}
1892

1893
static void run_context_detach_bus(RunContext *c) {
1,070✔
1894
        assert(c);
1,070✔
1895

1896
        if (c->bus) {
1,070✔
1897
                (void) sd_bus_detach_event(c->bus);
928✔
1898
                c->bus = sd_bus_unref(c->bus);
928✔
1899
        }
1900

1901
        c->match_properties_changed = sd_bus_slot_unref(c->match_properties_changed);
1,070✔
1902
        c->match_disconnected = sd_bus_slot_unref(c->match_disconnected);
1,070✔
1903
}
1,070✔
1904

1905
static int pty_forward_handler(PTYForward *f, int rcode, void *userdata) {
10✔
1906
        RunContext *c = ASSERT_PTR(userdata);
10✔
1907

1908
        assert(f);
10✔
1909

1910
        if (rcode == -ECANCELED) {
10✔
UNCOV
1911
                log_debug_errno(rcode, "PTY forwarder disconnected.");
×
UNCOV
1912
                if (!arg_wait)
×
1913
                        return sd_event_exit(c->event, EXIT_SUCCESS);
×
1914

1915
                /* If --wait is specified, we'll only exit the pty forwarding, but will continue to wait
1916
                 * for the service to end. If the user hits ^C we'll exit too. */
1917
        } else if (rcode < 0) {
10✔
1918
                (void) sd_event_exit(c->event, EXIT_FAILURE);
×
UNCOV
1919
                return log_error_errno(rcode, "Error on PTY forwarding logic: %m");
×
1920
        }
1921

1922
        run_context_check_done(c);
10✔
1923
        return 0;
10✔
1924
}
1925

1926
static int make_transient_service_unit(
1,070✔
1927
                sd_bus *bus,
1928
                sd_bus_message **message,
1929
                const char *service,
1930
                const char *pty_path,
1931
                int pty_fd) {
1932

1933
        _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1,070✔
1934
        int r;
1,070✔
1935

1936
        assert(bus);
1,070✔
1937
        assert(message);
1,070✔
1938
        assert(service);
1,070✔
1939

1940
        r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, "StartTransientUnit");
1,070✔
1941
        if (r < 0)
1,070✔
UNCOV
1942
                return bus_log_create_error(r);
×
1943

1944
        /* Name and mode */
1945
        r = sd_bus_message_append(m, "ss", service, job_mode_to_string(arg_job_mode));
1,070✔
1946
        if (r < 0)
1,070✔
UNCOV
1947
                return bus_log_create_error(r);
×
1948

1949
        /* Properties */
1950
        r = sd_bus_message_open_container(m, 'a', "(sv)");
1,070✔
1951
        if (r < 0)
1,070✔
UNCOV
1952
                return bus_log_create_error(r);
×
1953

1954
        r = transient_service_set_properties(m, pty_path, pty_fd);
1,070✔
1955
        if (r < 0)
1,070✔
1956
                return r;
1957

1958
        r = sd_bus_message_close_container(m);
1,066✔
1959
        if (r < 0)
1,066✔
UNCOV
1960
                return bus_log_create_error(r);
×
1961

1962
        /* Auxiliary units */
1963
        r = sd_bus_message_append(m, "a(sa(sv))", 0);
1,066✔
1964
        if (r < 0)
1,066✔
UNCOV
1965
                return bus_log_create_error(r);
×
1966

1967
        *message = TAKE_PTR(m);
1,066✔
1968
        return 0;
1,066✔
1969
}
1970

1971
static int bus_call_with_hint(
1,079✔
1972
                sd_bus *bus,
1973
                sd_bus_message *message,
1974
                const char *name,
1975
                sd_bus_message **reply) {
1976

1977
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
×
1978
        int r;
1,079✔
1979

1980
        r = sd_bus_call(bus, message, 0, &error, reply);
1,079✔
1981
        if (r < 0) {
1,079✔
1982
                log_error_errno(r, "Failed to start transient %s unit: %s", name, bus_error_message(&error, r));
18✔
1983

1984
                if (!arg_expand_environment &&
18✔
UNCOV
1985
                    sd_bus_error_has_names(&error,
×
1986
                                           SD_BUS_ERROR_UNKNOWN_PROPERTY,
1987
                                           SD_BUS_ERROR_PROPERTY_READ_ONLY))
UNCOV
1988
                        log_notice_errno(r, "Hint: --expand-environment=no is not supported by old systemd");
×
1989
        }
1990

1991
        return r;
1,079✔
1992
}
1993

1994
static int acquire_invocation_id(sd_bus *bus, const char *unit, sd_id128_t *ret) {
601✔
UNCOV
1995
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
×
1996
        _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
601✔
1997
        _cleanup_free_ char *object = NULL;
601✔
1998
        int r;
601✔
1999

2000
        assert(bus);
601✔
2001
        assert(ret);
601✔
2002

2003
        if (unit) {
601✔
2004
                object = unit_dbus_path_from_name(unit);
584✔
2005
                if (!object)
584✔
UNCOV
2006
                        return log_oom();
×
2007
        }
2008

2009
        r = sd_bus_get_property(bus,
601✔
2010
                                "org.freedesktop.systemd1",
2011
                                object ?: "/org/freedesktop/systemd1/unit/self",
2012
                                "org.freedesktop.systemd1.Unit",
2013
                                "InvocationID",
2014
                                &error,
2015
                                &reply,
2016
                                "ay");
2017
        if (r < 0)
601✔
UNCOV
2018
                return log_error_errno(r, "Failed to request invocation ID for unit: %s", bus_error_message(&error, r));
×
2019

2020
        r = bus_message_read_id128(reply, ret);
601✔
2021
        if (r < 0)
601✔
UNCOV
2022
                return bus_log_parse_error(r);
×
2023

2024
        return r; /* Return true when we get a non-null invocation ID. */
2025
}
2026

2027
static void set_window_title(PTYForward *f) {
10✔
2028
        _cleanup_free_ char *hn = NULL, *cl = NULL, *dot = NULL;
10✔
2029

2030
        assert(f);
10✔
2031

2032
        if (!shall_set_terminal_title())
10✔
2033
                return;
2034

2035
        if (!arg_host)
10✔
2036
                (void) gethostname_strict(&hn);
9✔
2037

2038
        cl = strv_join(arg_cmdline, " ");
10✔
2039
        if (!cl)
10✔
2040
                return (void) log_oom();
×
2041

2042
        if (emoji_enabled())
10✔
2043
                dot = strjoin(glyph(privileged_execution() ? GLYPH_RED_CIRCLE : GLYPH_YELLOW_CIRCLE), " ");
×
2044

2045
        if (arg_host || hn)
10✔
2046
                (void) pty_forward_set_titlef(f, "%s%s on %s", strempty(dot), cl, arg_host ?: hn);
20✔
2047
        else
UNCOV
2048
                (void) pty_forward_set_titlef(f, "%s%s", strempty(dot), cl);
×
2049

2050
        (void) pty_forward_set_title_prefix(f, dot);
10✔
2051
}
2052

UNCOV
2053
static int fchown_to_capsule(int fd, const char *capsule) {
×
UNCOV
2054
        _cleanup_free_ char *p = NULL;
×
UNCOV
2055
        int r;
×
2056

UNCOV
2057
        assert(fd >= 0);
×
UNCOV
2058
        assert(capsule);
×
2059

UNCOV
2060
        p = path_join("/run/capsules/", capsule);
×
UNCOV
2061
        if (!p)
×
2062
                return -ENOMEM;
2063

UNCOV
2064
        struct stat st;
×
UNCOV
2065
        r = chase_and_stat(p, /* root= */ NULL, CHASE_SAFE|CHASE_PROHIBIT_SYMLINKS, /* ret_path= */ NULL, &st);
×
UNCOV
2066
        if (r < 0)
×
2067
                return r;
2068

UNCOV
2069
        if (uid_is_system(st.st_uid) || gid_is_system(st.st_gid)) /* paranoid safety check */
×
UNCOV
2070
                return -EPERM;
×
2071

UNCOV
2072
        return fchmod_and_chown(fd, 0600, st.st_uid, st.st_gid);
×
2073
}
2074

2075
static int print_unit_invocation(const char *unit, sd_id128_t invocation_id) {
601✔
2076
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
601✔
2077
        int r;
601✔
2078

2079
        assert(unit);
601✔
2080

2081
        if (!sd_json_format_enabled(arg_json_format_flags)) {
601✔
2082
                if (sd_id128_is_null(invocation_id))
599✔
2083
                        log_info("Running as unit: %s", unit);
103✔
2084
                else
2085
                        log_info("Running as unit: %s; invocation ID: " SD_ID128_FORMAT_STR, unit, SD_ID128_FORMAT_VAL(invocation_id));
496✔
2086
                return 0;
599✔
2087
        }
2088

2089
        r = sd_json_variant_set_field_string(&v, "unit", unit);
2✔
2090
        if (r < 0)
2✔
2091
                return r;
2092

2093
        if (!sd_id128_is_null(invocation_id)) {
2✔
2094
                r = sd_json_variant_set_field_id128(&v, "invocation_id", invocation_id);
2✔
2095
                if (r < 0)
2✔
2096
                        return r;
2097
        }
2098

2099
        return sd_json_variant_dump(v, arg_json_format_flags, stdout, NULL);
2✔
2100
}
2101

2102
static int run_context_setup_ptyfwd(RunContext *c) {
365✔
2103
        int r;
365✔
2104

2105
        assert(c);
365✔
2106

2107
        if (c->pty_fd < 0 || c->forward)
365✔
2108
                return 0;
2109

2110
        /* Stop agents now that we are online, to avoid TTY conflicts */
2111
        polkit_agent_close();
10✔
2112
        ask_password_agent_close();
10✔
2113

2114
        if (!arg_quiet)
10✔
2115
                log_info("Press ^] three times within 1s to disconnect TTY.");
7✔
2116

2117
        r = pty_forward_new(c->event, c->pty_fd, PTY_FORWARD_IGNORE_INITIAL_VHANGUP, &c->forward);
10✔
2118
        if (r < 0)
10✔
UNCOV
2119
                return log_error_errno(r, "Failed to create PTY forwarder: %m");
×
2120

2121
        pty_forward_set_hangup_handler(c->forward, pty_forward_handler, c);
10✔
2122

2123
        /* Make sure to process any TTY events before we process bus events */
2124
        (void) pty_forward_set_priority(c->forward, SD_EVENT_PRIORITY_IMPORTANT);
10✔
2125

2126
        if (!isempty(arg_background))
10✔
UNCOV
2127
                (void) pty_forward_set_background_color(c->forward, arg_background);
×
2128

2129
        set_window_title(c->forward);
10✔
2130
        return 0;
10✔
2131
}
2132

2133
static int start_transient_service(sd_bus *bus) {
1,070✔
2134
        _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
2,136✔
2135
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1,070✔
UNCOV
2136
        _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
×
2137
        _cleanup_free_ char *pty_path = NULL;
1,070✔
2138
        _cleanup_close_ int peer_fd = -EBADF;
1,070✔
2139
        int r;
1,070✔
2140

2141
        assert(bus);
1,070✔
2142

2143
        (void) polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1,070✔
2144
        (void) ask_password_agent_open_if_enabled(arg_transport, arg_ask_password);
1,070✔
2145

2146
        _cleanup_(run_context_done) RunContext c = {
1,070✔
2147
                .pty_fd = -EBADF,
2148
                .cpu_usage_nsec = NSEC_INFINITY,
2149
                .memory_peak = UINT64_MAX,
2150
                .memory_swap_peak = UINT64_MAX,
2151
                .ip_ingress_bytes = UINT64_MAX,
2152
                .ip_egress_bytes = UINT64_MAX,
2153
                .io_read_bytes = UINT64_MAX,
2154
                .io_write_bytes = UINT64_MAX,
2155
                .inactive_exit_usec = USEC_INFINITY,
2156
                .inactive_enter_usec = USEC_INFINITY,
2157
        };
2158

2159
        if (arg_stdio == ARG_STDIO_PTY) {
1,070✔
2160

2161
                if (IN_SET(arg_transport, BUS_TRANSPORT_LOCAL, BUS_TRANSPORT_CAPSULE)) {
10✔
2162
                        c.pty_fd = openpt_allocate(O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK, &pty_path);
9✔
2163
                        if (c.pty_fd < 0)
9✔
UNCOV
2164
                                return log_error_errno(c.pty_fd, "Failed to acquire pseudo tty: %m");
×
2165

2166
                        peer_fd = pty_open_peer(c.pty_fd, O_RDWR|O_NOCTTY|O_CLOEXEC);
9✔
2167
                        if (peer_fd < 0)
9✔
UNCOV
2168
                                return log_error_errno(peer_fd, "Failed to open pty peer: %m");
×
2169

2170
                        if (arg_transport == BUS_TRANSPORT_CAPSULE) {
9✔
2171
                                /* If we are in capsule mode, we must give the capsule UID/GID access to the PTY we just allocated first. */
2172

UNCOV
2173
                                r = fchown_to_capsule(peer_fd, arg_host);
×
UNCOV
2174
                                if (r < 0)
×
2175
                                        return log_error_errno(r, "Failed to chown tty to capsule UID/GID: %m");
×
2176
                        }
2177

2178
                } else if (arg_transport == BUS_TRANSPORT_MACHINE) {
1✔
2179
                        _cleanup_(sd_bus_unrefp) sd_bus *system_bus = NULL;
1✔
2180
                        _cleanup_(sd_bus_message_unrefp) sd_bus_message *pty_reply = NULL;
1✔
2181
                        const char *s;
1✔
2182

2183
                        r = sd_bus_default_system(&system_bus);
1✔
2184
                        if (r < 0)
1✔
2185
                                return log_error_errno(r, "Failed to connect to system bus: %m");
×
2186

2187
                        (void) sd_bus_set_allow_interactive_authorization(system_bus, arg_ask_password);
1✔
2188

2189
                        r = bus_call_method(system_bus,
1✔
2190
                                            bus_machine_mgr,
2191
                                            "OpenMachinePTY",
2192
                                            &error,
2193
                                            &pty_reply,
2194
                                            "s", arg_host);
2195
                        if (r < 0)
1✔
2196
                                return log_error_errno(r, "Failed to get machine PTY: %s", bus_error_message(&error, r));
×
2197

2198
                        r = sd_bus_message_read(pty_reply, "hs", &c.pty_fd, &s);
1✔
2199
                        if (r < 0)
1✔
UNCOV
2200
                                return bus_log_parse_error(r);
×
2201

2202
                        c.pty_fd = fcntl(c.pty_fd, F_DUPFD_CLOEXEC, 3);
1✔
2203
                        if (c.pty_fd < 0)
1✔
UNCOV
2204
                                return log_error_errno(errno, "Failed to duplicate master fd: %m");
×
2205

2206
                        pty_path = strdup(s);
1✔
2207
                        if (!pty_path)
1✔
UNCOV
2208
                                return log_oom();
×
2209

2210
                        peer_fd = pty_open_peer(c.pty_fd, O_RDWR|O_NOCTTY|O_CLOEXEC);
1✔
2211
                        if (peer_fd < 0)
1✔
UNCOV
2212
                                return log_error_errno(peer_fd, "Failed to open PTY peer: %m");
×
2213
                } else
UNCOV
2214
                        assert_not_reached();
×
2215
        }
2216

2217
        if (arg_unit) {
1,070✔
2218
                r = unit_name_mangle_with_suffix(
514✔
2219
                                arg_unit,
2220
                                "as unit",
2221
                                arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN,
514✔
2222
                                ".service",
2223
                                &c.unit);
2224
                if (r < 0)
514✔
2225
                        return log_error_errno(r, "Failed to mangle unit name: %m");
×
2226
        } else {
2227
                r = make_unit_name(UNIT_SERVICE, &c.unit);
556✔
2228
                if (r < 0)
556✔
2229
                        return r;
2230
        }
2231

2232
        /* Optionally, wait for the start job to complete. If we are supposed to read the service's stdin
2233
         * lets skip this however, because we should start that already when the start job is running, and
2234
         * there's little point in waiting for the start job to complete in that case anyway, as we'll wait
2235
         * for EOF anyway, which is going to be much later. */
2236
        if (!arg_no_block && arg_stdio == ARG_STDIO_NONE) {
1,070✔
2237
                r = bus_wait_for_jobs_new(bus, &w);
710✔
2238
                if (r < 0)
710✔
UNCOV
2239
                        return log_error_errno(r, "Could not watch jobs: %m");
×
2240
        }
2241

2242
        r = make_transient_service_unit(bus, &m, c.unit, pty_path, peer_fd);
1,070✔
2243
        if (r < 0)
1,070✔
2244
                return r;
2245
        peer_fd = safe_close(peer_fd);
1,066✔
2246

2247
        r = bus_call_with_hint(bus, m, "service", &reply);
1,066✔
2248
        if (r < 0)
1,066✔
2249
                return r;
2250

2251
        const char *object;
1,053✔
2252
        r = sd_bus_message_read(reply, "o", &object);
1,053✔
2253
        if (r < 0)
1,053✔
UNCOV
2254
                return bus_log_parse_error(r);
×
2255

2256
        if (w) {
1,053✔
2257
                r = bus_wait_for_jobs_one(
2,082✔
2258
                                w,
2259
                                object,
2260
                                arg_quiet ? 0 : BUS_WAIT_JOBS_LOG_ERROR,
694✔
2261
                                arg_runtime_scope == RUNTIME_SCOPE_USER ? STRV_MAKE_CONST("--user") : NULL);
694✔
2262
                if (r < 0)
694✔
2263
                        return r;
8✔
2264
        } else if (!arg_no_block) {
359✔
2265
                c.start_job = strdup(object);
355✔
2266
                if (!c.start_job)
355✔
2267
                        return log_oom();
×
2268
        }
2269

2270
        if (!arg_quiet) {
1,045✔
2271
                sd_id128_t invocation_id;
584✔
2272

2273
                r = acquire_invocation_id(bus, c.unit, &invocation_id);
584✔
2274
                if (r < 0)
584✔
UNCOV
2275
                        return r;
×
2276

2277
                r = print_unit_invocation(c.unit, invocation_id);
584✔
2278
                if (r < 0)
584✔
2279
                        return r;
2280
        }
2281

2282
        if (arg_wait || arg_stdio != ARG_STDIO_NONE) {
1,045✔
2283
                c.bus_path = unit_dbus_path_from_name(c.unit);
928✔
2284
                if (!c.bus_path)
928✔
UNCOV
2285
                        return log_oom();
×
2286

2287
                r = sd_event_default(&c.event);
928✔
2288
                if (r < 0)
928✔
UNCOV
2289
                        return log_error_errno(r, "Failed to get event loop: %m");
×
2290

2291
                _cleanup_(osc_context_closep) sd_id128_t osc_context_id = SD_ID128_NULL;
928✔
2292
                if (c.pty_fd >= 0) {
928✔
2293
                        if (arg_exec_user && !terminal_is_dumb()) {
10✔
UNCOV
2294
                                r = osc_context_open_chpriv(arg_exec_user, /* ret_seq= */ NULL, &osc_context_id);
×
UNCOV
2295
                                if (r < 0)
×
UNCOV
2296
                                        return log_error_errno(r, "Failed to set OSC context: %m");
×
2297
                        }
2298

2299
                        (void) sd_event_set_signal_exit(c.event, true);
10✔
2300

2301
                        assert(arg_pty_late >= 0);
10✔
2302
                        if (!arg_pty_late) { /* If late PTY mode is off, start pty forwarder immediately */
10✔
2303
                                r = run_context_setup_ptyfwd(&c);
10✔
2304
                                if (r < 0)
10✔
2305
                                        return r;
2306
                        }
2307
                }
2308

2309
                r = run_context_attach_bus(&c, bus);
928✔
2310
                if (r < 0)
928✔
2311
                        return r;
2312

2313
                r = run_context_update(&c);
928✔
2314
                if (r < 0)
928✔
2315
                        return r;
2316

2317
                r = sd_event_loop(c.event);
928✔
2318
                if (r < 0)
928✔
UNCOV
2319
                        return log_error_errno(r, "Failed to run event loop: %m");
×
2320

2321
                if (arg_wait && !arg_quiet) {
928✔
2322

2323
                        if (!isempty(c.result))
405✔
2324
                                log_info("Finished with result: %s", strna(c.result));
405✔
2325

2326
                        if (c.exit_code > 0)
405✔
2327
                                log_info("Main processes terminated with: code=%s, status=%u/%s",
808✔
2328
                                         sigchld_code_to_string(c.exit_code),
2329
                                         c.exit_status,
2330
                                         strna(c.exit_code == CLD_EXITED ?
2331
                                               exit_status_to_string(c.exit_status, EXIT_STATUS_FULL) :
2332
                                               signal_to_string(c.exit_status)));
2333

2334
                        if (timestamp_is_set(c.inactive_enter_usec) &&
405✔
2335
                            timestamp_is_set(c.inactive_exit_usec) &&
405✔
2336
                            c.inactive_enter_usec > c.inactive_exit_usec)
2337
                                log_info("Service runtime: %s",
405✔
2338
                                         FORMAT_TIMESPAN(c.inactive_enter_usec - c.inactive_exit_usec, USEC_PER_MSEC));
2339

2340
                        if (c.cpu_usage_nsec != NSEC_INFINITY)
405✔
2341
                                log_info("CPU time consumed: %s",
405✔
2342
                                         FORMAT_TIMESPAN(DIV_ROUND_UP(c.cpu_usage_nsec, NSEC_PER_USEC), USEC_PER_MSEC));
2343

2344
                        if (c.memory_peak != UINT64_MAX) {
405✔
2345
                                const char *swap;
405✔
2346

2347
                                if (c.memory_swap_peak != UINT64_MAX)
405✔
2348
                                        swap = strjoina(" (swap: ", FORMAT_BYTES(c.memory_swap_peak), ")");
2,835✔
2349
                                else
2350
                                        swap = "";
2351

2352
                                log_info("Memory peak: %s%s", FORMAT_BYTES(c.memory_peak), swap);
405✔
2353
                        }
2354

2355
                        const char *ip_ingress = NULL, *ip_egress = NULL;
405✔
2356

2357
                        if (!IN_SET(c.ip_ingress_bytes, 0, UINT64_MAX))
405✔
UNCOV
2358
                                ip_ingress = strjoina(" received: ", FORMAT_BYTES(c.ip_ingress_bytes));
×
2359
                        if (!IN_SET(c.ip_egress_bytes, 0, UINT64_MAX))
405✔
UNCOV
2360
                                ip_egress = strjoina(" sent: ", FORMAT_BYTES(c.ip_egress_bytes));
×
2361

2362
                        if (ip_ingress || ip_egress)
405✔
UNCOV
2363
                                log_info("IP traffic%s%s", strempty(ip_ingress), strempty(ip_egress));
×
2364

2365
                        const char *io_read = NULL, *io_write = NULL;
405✔
2366

2367
                        if (!IN_SET(c.io_read_bytes, 0, UINT64_MAX))
405✔
UNCOV
2368
                                io_read = strjoina(" read: ", FORMAT_BYTES(c.io_read_bytes));
×
2369
                        if (!IN_SET(c.io_write_bytes, 0, UINT64_MAX))
405✔
UNCOV
2370
                                io_write = strjoina(" written: ", FORMAT_BYTES(c.io_write_bytes));
×
2371

2372
                        if (io_read || io_write)
405✔
UNCOV
2373
                                log_info("IO bytes%s%s", strempty(io_read), strempty(io_write));
×
2374
                }
2375

2376
                /* Try to propagate the service's return value. But if the service defines
2377
                 * e.g. SuccessExitStatus, honour this, and return 0 to mean "success". */
2378
                if (streq_ptr(c.result, "success"))
928✔
2379
                        return EXIT_SUCCESS;
2380
                if (streq_ptr(c.result, "exit-code") && c.exit_status > 0)
103✔
2381
                        return c.exit_status;
101✔
2382
                if (streq_ptr(c.result, "signal"))
2✔
2383
                        return EXIT_EXCEPTION;
2384
                return EXIT_FAILURE;
1✔
2385
        }
2386

2387
        return EXIT_SUCCESS;
2388
}
2389

2390
static int start_transient_scope(sd_bus *bus) {
19✔
2391
        _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
2✔
2392
        _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
2✔
2393
        _cleanup_strv_free_ char **env = NULL, **user_env = NULL;
2✔
2394
        _cleanup_free_ char *scope = NULL;
2✔
2395
        const char *object = NULL;
19✔
2396
        sd_id128_t invocation_id;
19✔
2397
        bool allow_pidfd = true;
19✔
2398
        int r;
19✔
2399

2400
        assert(bus);
19✔
2401
        assert(!strv_isempty(arg_cmdline));
19✔
2402

2403
        r = bus_wait_for_jobs_new(bus, &w);
19✔
2404
        if (r < 0)
19✔
UNCOV
2405
                return log_error_errno(r, "Could not watch jobs: %m");
×
2406

2407
        if (arg_unit) {
19✔
2408
                r = unit_name_mangle_with_suffix(arg_unit, "as unit",
6✔
2409
                                                 arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN,
6✔
2410
                                                 ".scope", &scope);
2411
                if (r < 0)
6✔
UNCOV
2412
                        return log_error_errno(r, "Failed to mangle scope name: %m");
×
2413
        } else {
2414
                r = make_unit_name(UNIT_SCOPE, &scope);
13✔
2415
                if (r < 0)
13✔
2416
                        return r;
2417
        }
2418

2419
        (void) polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
19✔
2420
        (void) ask_password_agent_open_if_enabled(arg_transport, arg_ask_password);
19✔
2421

2422
        for (;;) {
×
UNCOV
2423
                _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
×
2424
                _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
19✔
2425

2426
                r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, "StartTransientUnit");
19✔
2427
                if (r < 0)
19✔
2428
                        return bus_log_create_error(r);
×
2429

2430
                /* Name and Mode */
2431
                r = sd_bus_message_append(m, "ss", scope, job_mode_to_string(arg_job_mode));
19✔
2432
                if (r < 0)
19✔
UNCOV
2433
                        return bus_log_create_error(r);
×
2434

2435
                /* Properties */
2436
                r = sd_bus_message_open_container(m, 'a', "(sv)");
19✔
2437
                if (r < 0)
19✔
UNCOV
2438
                        return bus_log_create_error(r);
×
2439

2440
                r = transient_scope_set_properties(m, allow_pidfd);
19✔
2441
                if (r < 0)
19✔
2442
                        return r;
2443

2444
                r = sd_bus_message_close_container(m);
19✔
2445
                if (r < 0)
19✔
UNCOV
2446
                        return bus_log_create_error(r);
×
2447

2448
                /* Auxiliary units */
2449
                r = sd_bus_message_append(m, "a(sa(sv))", 0);
19✔
2450
                if (r < 0)
19✔
2451
                        return bus_log_create_error(r);
×
2452

2453
                r = sd_bus_call(bus, m, 0, &error, &reply);
19✔
2454
                if (r < 0) {
19✔
2455
                        if (sd_bus_error_has_names(&error, SD_BUS_ERROR_UNKNOWN_PROPERTY, SD_BUS_ERROR_PROPERTY_READ_ONLY) && allow_pidfd) {
2✔
UNCOV
2456
                                log_debug("Retrying with classic PIDs.");
×
UNCOV
2457
                                allow_pidfd = false;
×
2458
                                continue;
×
2459
                        }
2460

2461
                        return log_error_errno(r, "Failed to start transient scope unit: %s", bus_error_message(&error, r));
2✔
2462
                }
2463

2464
                break;
17✔
2465
        }
2466

2467
        r = sd_bus_message_read(reply, "o", &object);
17✔
2468
        if (r < 0)
17✔
2469
                return bus_log_parse_error(r);
×
2470

2471
        r = bus_wait_for_jobs_one(w, object, arg_quiet ? 0 : BUS_WAIT_JOBS_LOG_ERROR,
17✔
2472
                                  arg_runtime_scope == RUNTIME_SCOPE_USER ? STRV_MAKE_CONST("--user") : NULL);
17✔
2473
        if (r < 0)
17✔
2474
                return r;
2475

2476
        r = acquire_invocation_id(bus, NULL, &invocation_id);
17✔
2477
        if (r < 0)
17✔
2478
                return r;
2479
        if (r == 0)
17✔
UNCOV
2480
                log_debug("No invocation ID set.");
×
2481
        else {
2482
                if (strv_extendf(&user_env, "INVOCATION_ID=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(invocation_id)) < 0)
17✔
UNCOV
2483
                        return log_oom();
×
2484
        }
2485

2486
        if (arg_nice_set) {
17✔
UNCOV
2487
                if (setpriority(PRIO_PROCESS, 0, arg_nice) < 0)
×
UNCOV
2488
                        return log_error_errno(errno, "Failed to set nice level: %m");
×
2489
        }
2490

2491
        if (arg_exec_group) {
17✔
2492
                gid_t gid;
×
2493

UNCOV
2494
                r = get_group_creds(&arg_exec_group, &gid, 0);
×
UNCOV
2495
                if (r < 0)
×
UNCOV
2496
                        return log_error_errno(r, "Failed to resolve group %s: %m", arg_exec_group);
×
2497

UNCOV
2498
                if (setresgid(gid, gid, gid) < 0)
×
UNCOV
2499
                        return log_error_errno(errno, "Failed to change GID to " GID_FMT ": %m", gid);
×
2500
        }
2501

2502
        if (arg_exec_user) {
17✔
2503
                const char *home, *shell;
1✔
2504
                uid_t uid;
1✔
2505
                gid_t gid;
1✔
2506

2507
                r = get_user_creds(&arg_exec_user, &uid, &gid, &home, &shell,
1✔
2508
                                   USER_CREDS_CLEAN|USER_CREDS_SUPPRESS_PLACEHOLDER|USER_CREDS_PREFER_NSS);
2509
                if (r < 0)
1✔
UNCOV
2510
                        return log_error_errno(r, "Failed to resolve user %s: %m", arg_exec_user);
×
2511

2512
                if (home) {
1✔
2513
                        r = strv_extendf(&user_env, "HOME=%s", home);
1✔
2514
                        if (r < 0)
1✔
UNCOV
2515
                                return log_oom();
×
2516
                }
2517

2518
                if (shell) {
1✔
2519
                        r = strv_extendf(&user_env, "SHELL=%s", shell);
1✔
2520
                        if (r < 0)
1✔
UNCOV
2521
                                return log_oom();
×
2522
                }
2523

2524
                r = strv_extendf(&user_env, "USER=%s", arg_exec_user);
1✔
2525
                if (r < 0)
1✔
UNCOV
2526
                        return log_oom();
×
2527

2528
                r = strv_extendf(&user_env, "LOGNAME=%s", arg_exec_user);
1✔
2529
                if (r < 0)
1✔
2530
                        return log_oom();
×
2531

2532
                if (!arg_exec_group) {
1✔
2533
                        if (setresgid(gid, gid, gid) < 0)
1✔
UNCOV
2534
                                return log_error_errno(errno, "Failed to change GID to " GID_FMT ": %m", gid);
×
2535
                }
2536

2537
                if (setresuid(uid, uid, uid) < 0)
1✔
UNCOV
2538
                        return log_error_errno(errno, "Failed to change UID to " UID_FMT ": %m", uid);
×
2539
        }
2540

2541
        if (arg_working_directory && chdir(arg_working_directory) < 0)
17✔
UNCOV
2542
                return log_error_errno(errno, "Failed to change directory to '%s': %m", arg_working_directory);
×
2543

2544
        env = strv_env_merge(environ, user_env, arg_environment);
17✔
2545
        if (!env)
17✔
UNCOV
2546
                return log_oom();
×
2547

2548
        if (!arg_quiet) {
17✔
2549
                r = print_unit_invocation(scope, invocation_id);
17✔
2550
                if (r < 0)
17✔
2551
                        return r;
2552
        }
2553

2554
        if (arg_expand_environment) {
17✔
2555
                _cleanup_strv_free_ char **expanded_cmdline = NULL, **unset_variables = NULL, **bad_variables = NULL;
17✔
2556

2557
                r = replace_env_argv(arg_cmdline, env, &expanded_cmdline, &unset_variables, &bad_variables);
17✔
2558
                if (r < 0)
17✔
UNCOV
2559
                        return log_error_errno(r, "Failed to expand environment variables: %m");
×
2560

2561
                free_and_replace(arg_cmdline, expanded_cmdline);
17✔
2562

2563
                if (!strv_isempty(unset_variables)) {
17✔
UNCOV
2564
                        _cleanup_free_ char *ju = strv_join(unset_variables, ", ");
×
UNCOV
2565
                        log_warning("Referenced but unset environment variable evaluates to an empty string: %s", strna(ju));
×
2566
                }
2567

2568
                if (!strv_isempty(bad_variables)) {
17✔
UNCOV
2569
                        _cleanup_free_ char *jb = strv_join(bad_variables, ", ");
×
UNCOV
2570
                        log_warning("Invalid environment variable name evaluates to an empty string: %s", strna(jb));
×
2571
                }
2572
        }
2573

2574
        /* Stop agents before we pass control away, to avoid TTY conflicts */
2575
        polkit_agent_close();
17✔
2576
        ask_password_agent_close();
17✔
2577

2578
        execvpe(arg_cmdline[0], arg_cmdline, env);
17✔
2579

UNCOV
2580
        return log_error_errno(errno, "Failed to execute: %m");
×
2581
}
2582

2583
static int make_transient_trigger_unit(
18✔
2584
                sd_bus *bus,
2585
                sd_bus_message **message,
2586
                const char *suffix,
2587
                const char *trigger,
2588
                const char *service) {
2589

2590
        _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
18✔
2591
        int r;
18✔
2592

2593
        assert(bus);
18✔
2594
        assert(message);
18✔
2595
        assert(suffix);
18✔
2596
        assert(trigger);
18✔
2597
        assert(service);
18✔
2598

2599
        r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, "StartTransientUnit");
18✔
2600
        if (r < 0)
18✔
2601
                return bus_log_create_error(r);
×
2602

2603
        /* Name and Mode */
2604
        r = sd_bus_message_append(m, "ss", trigger, job_mode_to_string(arg_job_mode));
18✔
2605
        if (r < 0)
18✔
2606
                return bus_log_create_error(r);
×
2607

2608
        /* Properties */
2609
        r = sd_bus_message_open_container(m, 'a', "(sv)");
18✔
2610
        if (r < 0)
18✔
UNCOV
2611
                return bus_log_create_error(r);
×
2612

2613
        if (streq(suffix, ".path"))
18✔
2614
                r = transient_unit_set_properties(m, UNIT_PATH, arg_path_property);
1✔
2615
        else if (streq(suffix, ".socket"))
17✔
2616
                r = transient_unit_set_properties(m, UNIT_SOCKET, arg_socket_property);
2✔
2617
        else if (streq(suffix, ".timer"))
15✔
2618
                r = transient_timer_set_properties(m);
15✔
2619
        else
UNCOV
2620
                assert_not_reached();
×
2621
        if (r < 0)
18✔
2622
                return r;
2623

2624
        r = sd_bus_message_close_container(m);
13✔
2625
        if (r < 0)
13✔
2626
                return bus_log_create_error(r);
×
2627

2628
        r = sd_bus_message_open_container(m, 'a', "(sa(sv))");
13✔
2629
        if (r < 0)
13✔
UNCOV
2630
                return bus_log_create_error(r);
×
2631

2632
        if (!strv_isempty(arg_cmdline)) {
13✔
2633
                r = sd_bus_message_open_container(m, 'r', "sa(sv)");
13✔
2634
                if (r < 0)
13✔
UNCOV
2635
                        return bus_log_create_error(r);
×
2636

2637
                r = sd_bus_message_append(m, "s", service);
13✔
2638
                if (r < 0)
13✔
2639
                        return bus_log_create_error(r);
×
2640

2641
                r = sd_bus_message_open_container(m, 'a', "(sv)");
13✔
2642
                if (r < 0)
13✔
UNCOV
2643
                        return bus_log_create_error(r);
×
2644

2645
                r = transient_service_set_properties(m, /* pty_path = */ NULL, /* pty_fd = */ -EBADF);
13✔
2646
                if (r < 0)
13✔
2647
                        return r;
2648

2649
                r = sd_bus_message_close_container(m);
13✔
2650
                if (r < 0)
13✔
UNCOV
2651
                        return bus_log_create_error(r);
×
2652

2653
                r = sd_bus_message_close_container(m);
13✔
2654
                if (r < 0)
13✔
UNCOV
2655
                        return bus_log_create_error(r);
×
2656
        }
2657

2658
        r = sd_bus_message_close_container(m);
13✔
2659
        if (r < 0)
13✔
UNCOV
2660
                return bus_log_create_error(r);
×
2661

2662
        *message = TAKE_PTR(m);
13✔
2663
        return 0;
13✔
2664
}
2665

2666
static int start_transient_trigger(sd_bus *bus, const char *suffix) {
18✔
2667
        _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
31✔
UNCOV
2668
        _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
×
2669
        _cleanup_free_ char *trigger = NULL, *service = NULL;
18✔
2670
        const char *object = NULL;
18✔
2671
        int r;
18✔
2672

2673
        assert(bus);
18✔
2674
        assert(suffix);
18✔
2675

2676
        r = bus_wait_for_jobs_new(bus, &w);
18✔
2677
        if (r < 0)
18✔
UNCOV
2678
                return log_error_errno(r, "Could not watch jobs: %m");
×
2679

2680
        if (arg_unit) {
18✔
2681
                switch (unit_name_to_type(arg_unit)) {
6✔
2682

2683
                case UNIT_SERVICE:
1✔
2684
                        service = strdup(arg_unit);
1✔
2685
                        if (!service)
1✔
UNCOV
2686
                                return log_oom();
×
2687

2688
                        r = unit_name_change_suffix(service, suffix, &trigger);
1✔
2689
                        if (r < 0)
1✔
UNCOV
2690
                                return log_error_errno(r, "Failed to change unit suffix: %m");
×
2691
                        break;
2692

UNCOV
2693
                case UNIT_TIMER:
×
UNCOV
2694
                        trigger = strdup(arg_unit);
×
UNCOV
2695
                        if (!trigger)
×
2696
                                return log_oom();
×
2697

UNCOV
2698
                        r = unit_name_change_suffix(trigger, ".service", &service);
×
UNCOV
2699
                        if (r < 0)
×
UNCOV
2700
                                return log_error_errno(r, "Failed to change unit suffix: %m");
×
2701
                        break;
2702

2703
                default:
5✔
2704
                        r = unit_name_mangle_with_suffix(arg_unit, "as unit",
5✔
2705
                                                         arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN,
5✔
2706
                                                         ".service", &service);
2707
                        if (r < 0)
5✔
UNCOV
2708
                                return log_error_errno(r, "Failed to mangle unit name: %m");
×
2709

2710
                        r = unit_name_mangle_with_suffix(arg_unit, "as trigger",
5✔
2711
                                                         arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN,
5✔
2712
                                                         suffix, &trigger);
2713
                        if (r < 0)
5✔
UNCOV
2714
                                return log_error_errno(r, "Failed to mangle unit name: %m");
×
2715

2716
                        break;
2717
                }
2718
        } else {
2719
                r = make_unit_name(UNIT_SERVICE, &service);
12✔
2720
                if (r < 0)
12✔
2721
                        return r;
2722

2723
                r = unit_name_change_suffix(service, suffix, &trigger);
12✔
2724
                if (r < 0)
12✔
UNCOV
2725
                        return log_error_errno(r, "Failed to change unit suffix: %m");
×
2726
        }
2727

2728
        r = make_transient_trigger_unit(bus, &m, suffix, trigger, service);
18✔
2729
        if (r < 0)
18✔
2730
                return r;
2731

2732
        (void) polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
13✔
2733
        (void) ask_password_agent_open_if_enabled(arg_transport, arg_ask_password);
13✔
2734

2735
        r = bus_call_with_hint(bus, m, suffix + 1, &reply);
13✔
2736
        if (r < 0)
13✔
2737
                return r;
2738

2739
        r = sd_bus_message_read(reply, "o", &object);
8✔
2740
        if (r < 0)
8✔
UNCOV
2741
                return bus_log_parse_error(r);
×
2742

2743
        r = bus_wait_for_jobs_one(w, object, arg_quiet ? 0 : BUS_WAIT_JOBS_LOG_ERROR,
8✔
2744
                                  arg_runtime_scope == RUNTIME_SCOPE_USER ? STRV_MAKE_CONST("--user") : NULL);
8✔
2745
        if (r < 0)
8✔
2746
                return r;
2747

2748
        if (!arg_quiet) {
8✔
2749
                log_info("Running %s as unit: %s", suffix + 1, trigger);
8✔
2750
                if (!strv_isempty(arg_cmdline))
8✔
2751
                        log_info("Will run service as unit: %s", service);
18✔
2752
        }
2753

2754
        return EXIT_SUCCESS;
2755
}
2756

2757
static bool shall_make_executable_absolute(void) {
1,112✔
2758
        if (arg_exec_path)
1,112✔
2759
                return false;
2760
        if (strv_isempty(arg_cmdline))
1,112✔
2761
                return false;
2762
        if (arg_transport != BUS_TRANSPORT_LOCAL)
1,112✔
2763
                return false;
2764

2765
        FOREACH_STRING(f, "RootDirectory=", "RootImage=", "ExecSearchPath=", "MountImages=", "ExtensionImages=")
6,182✔
2766
                if (strv_find_startswith(arg_property, f))
5,178✔
2767
                        return false;
71✔
2768

2769
        return true;
1,004✔
2770
}
2771

2772
static int run(int argc, char* argv[]) {
1,124✔
2773
        _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1,107✔
2774
        int r;
1,124✔
2775

2776
        log_setup();
1,124✔
2777

2778
        if (invoked_as(argv, "run0"))
1,124✔
2779
                r = parse_argv_sudo_mode(argc, argv);
124✔
2780
        else
2781
                r = parse_argv(argc, argv);
1,000✔
2782
        if (r <= 0)
1,124✔
2783
                return r;
2784

2785
        if (shall_make_executable_absolute()) {
1,112✔
2786
                /* Patch in an absolute path to fail early for user convenience, but only when we can do it
2787
                 * (i.e. we will be running from the same file system). This also uses the user's $PATH,
2788
                 * while we use a fixed search path in the manager. */
2789

2790
                _cleanup_free_ char *command = NULL;
1,004✔
2791
                r = find_executable(arg_cmdline[0], &command);
1,004✔
2792
                if (ERRNO_IS_NEG_PRIVILEGE(r))
1,004✔
2793
                        log_debug_errno(r, "Failed to find executable '%s' due to permission problems, leaving path as is: %m", arg_cmdline[0]);
1,003✔
2794
                else if (r < 0)
1,004✔
2795
                        return log_error_errno(r, "Failed to find executable %s: %m", arg_cmdline[0]);
1✔
2796
                else
2797
                        free_and_replace(arg_cmdline[0], command);
1,003✔
2798
        }
2799

2800
        if (!arg_description) {
1,111✔
2801
                _cleanup_free_ char *t = NULL;
1,110✔
2802

2803
                if (strv_isempty(arg_cmdline))
1,110✔
UNCOV
2804
                        t = strdup(arg_unit);
×
2805
                else if (startswith(arg_cmdline[0], "-")) {
1,110✔
2806
                        /* Drop the login shell marker from the command line when generating the description,
2807
                         * in order to minimize user confusion. */
2808
                        _cleanup_strv_free_ char **l = strv_copy(arg_cmdline);
1✔
2809
                        if (!l)
1✔
UNCOV
2810
                                return log_oom();
×
2811

2812
                        r = free_and_strdup_warn(l + 0, l[0] + 1);
1✔
2813
                        if (r < 0)
1✔
2814
                                return r;
2815

2816
                        t = quote_command_line(l, SHELL_ESCAPE_EMPTY);
1✔
2817
                } else
2818
                        t = quote_command_line(arg_cmdline, SHELL_ESCAPE_EMPTY);
1,109✔
2819
                if (!t)
1,110✔
UNCOV
2820
                        return log_oom();
×
2821

2822
                arg_description = strjoin("[", program_invocation_short_name, "] ", t);
1,110✔
2823
                if (!arg_description)
1,110✔
UNCOV
2824
                        return log_oom();
×
2825
        }
2826

2827
        r = connect_bus(&bus);
1,111✔
2828
        if (r < 0)
1,111✔
2829
                return r;
2830

2831
        if (arg_scope)
1,107✔
2832
                return start_transient_scope(bus);
19✔
2833
        if (arg_path_property)
1,088✔
2834
                return start_transient_trigger(bus, ".path");
1✔
2835
        if (arg_socket_property)
1,087✔
2836
                return start_transient_trigger(bus, ".socket");
2✔
2837
        if (arg_with_timer)
1,085✔
2838
                return start_transient_trigger(bus, ".timer");
15✔
2839
        return start_transient_service(bus);
1,070✔
2840
}
2841

2842
DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);
2,248✔
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