forked from systemd/systemd
/
manager.c
4762 lines (3633 loc) · 165 KB
/
manager.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* SPDX-License-Identifier: LGPL-2.1+ */
#include <errno.h>
#include <fcntl.h>
#include <linux/kd.h>
#include <sys/epoll.h>
#include <sys/inotify.h>
#include <sys/ioctl.h>
#include <sys/reboot.h>
#include <sys/timerfd.h>
#include <sys/wait.h>
#include <unistd.h>
#if HAVE_AUDIT
#include <libaudit.h>
#endif
#include "sd-daemon.h"
#include "sd-messages.h"
#include "sd-path.h"
#include "all-units.h"
#include "alloc-util.h"
#include "audit-fd.h"
#include "boot-timestamps.h"
#include "bus-common-errors.h"
#include "bus-error.h"
#include "bus-kernel.h"
#include "bus-util.h"
#include "clean-ipc.h"
#include "clock-util.h"
#include "core-varlink.h"
#include "dbus-job.h"
#include "dbus-manager.h"
#include "dbus-unit.h"
#include "dbus.h"
#include "def.h"
#include "dirent-util.h"
#include "env-util.h"
#include "escape.h"
#include "exec-util.h"
#include "execute.h"
#include "exit-status.h"
#include "fd-util.h"
#include "fileio.h"
#include "fs-util.h"
#include "generator-setup.h"
#include "hashmap.h"
#include "install.h"
#include "io-util.h"
#include "label.h"
#include "locale-setup.h"
#include "log.h"
#include "macro.h"
#include "manager.h"
#include "memory-util.h"
#include "mkdir.h"
#include "parse-util.h"
#include "path-lookup.h"
#include "path-util.h"
#include "process-util.h"
#include "ratelimit.h"
#include "rlimit-util.h"
#include "rm-rf.h"
#include "serialize.h"
#include "signal-util.h"
#include "socket-util.h"
#include "special.h"
#include "stat-util.h"
#include "string-table.h"
#include "string-util.h"
#include "strv.h"
#include "strxcpyx.h"
#include "sysctl-util.h"
#include "syslog-util.h"
#include "terminal-util.h"
#include "time-util.h"
#include "transaction.h"
#include "umask-util.h"
#include "unit-name.h"
#include "user-util.h"
#include "virt.h"
#include "watchdog.h"
#define NOTIFY_RCVBUF_SIZE (8*1024*1024)
#define CGROUPS_AGENT_RCVBUF_SIZE (8*1024*1024)
/* Initial delay and the interval for printing status messages about running jobs */
#define JOBS_IN_PROGRESS_WAIT_USEC (2*USEC_PER_SEC)
#define JOBS_IN_PROGRESS_QUIET_WAIT_USEC (25*USEC_PER_SEC)
#define JOBS_IN_PROGRESS_PERIOD_USEC (USEC_PER_SEC / 3)
#define JOBS_IN_PROGRESS_PERIOD_DIVISOR 3
/* If there are more than 1K bus messages queue across our API and direct buses, then let's not add more on top until
* the queue gets more empty. */
#define MANAGER_BUS_BUSY_THRESHOLD 1024LU
/* How many units and jobs to process of the bus queue before returning to the event loop. */
#define MANAGER_BUS_MESSAGE_BUDGET 100U
static int manager_dispatch_notify_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
static int manager_dispatch_cgroups_agent_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
static int manager_dispatch_signal_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
static int manager_dispatch_time_change_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
static int manager_dispatch_idle_pipe_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
static int manager_dispatch_user_lookup_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
static int manager_dispatch_jobs_in_progress(sd_event_source *source, usec_t usec, void *userdata);
static int manager_dispatch_run_queue(sd_event_source *source, void *userdata);
static int manager_dispatch_sigchld(sd_event_source *source, void *userdata);
static int manager_dispatch_timezone_change(sd_event_source *source, const struct inotify_event *event, void *userdata);
static int manager_run_environment_generators(Manager *m);
static int manager_run_generators(Manager *m);
static usec_t manager_watch_jobs_next_time(Manager *m) {
return usec_add(now(CLOCK_MONOTONIC),
show_status_on(m->show_status) ? JOBS_IN_PROGRESS_WAIT_USEC :
JOBS_IN_PROGRESS_QUIET_WAIT_USEC);
}
static void manager_watch_jobs_in_progress(Manager *m) {
usec_t next;
int r;
assert(m);
/* We do not want to show the cylon animation if the user
* needs to confirm service executions otherwise confirmation
* messages will be screwed by the cylon animation. */
if (!manager_is_confirm_spawn_disabled(m))
return;
if (m->jobs_in_progress_event_source)
return;
next = manager_watch_jobs_next_time(m);
r = sd_event_add_time(
m->event,
&m->jobs_in_progress_event_source,
CLOCK_MONOTONIC,
next, 0,
manager_dispatch_jobs_in_progress, m);
if (r < 0)
return;
(void) sd_event_source_set_description(m->jobs_in_progress_event_source, "manager-jobs-in-progress");
}
#define CYLON_BUFFER_EXTRA (2*STRLEN(ANSI_RED) + STRLEN(ANSI_HIGHLIGHT_RED) + 2*STRLEN(ANSI_NORMAL))
static void draw_cylon(char buffer[], size_t buflen, unsigned width, unsigned pos) {
char *p = buffer;
assert(buflen >= CYLON_BUFFER_EXTRA + width + 1);
assert(pos <= width+1); /* 0 or width+1 mean that the center light is behind the corner */
if (pos > 1) {
if (pos > 2)
p = mempset(p, ' ', pos-2);
if (log_get_show_color())
p = stpcpy(p, ANSI_RED);
*p++ = '*';
}
if (pos > 0 && pos <= width) {
if (log_get_show_color())
p = stpcpy(p, ANSI_HIGHLIGHT_RED);
*p++ = '*';
}
if (log_get_show_color())
p = stpcpy(p, ANSI_NORMAL);
if (pos < width) {
if (log_get_show_color())
p = stpcpy(p, ANSI_RED);
*p++ = '*';
if (pos < width-1)
p = mempset(p, ' ', width-1-pos);
if (log_get_show_color())
strcpy(p, ANSI_NORMAL);
}
}
void manager_flip_auto_status(Manager *m, bool enable, const char *reason) {
assert(m);
if (enable) {
if (m->show_status == SHOW_STATUS_AUTO)
manager_set_show_status(m, SHOW_STATUS_TEMPORARY, reason);
} else {
if (m->show_status == SHOW_STATUS_TEMPORARY)
manager_set_show_status(m, SHOW_STATUS_AUTO, reason);
}
}
static void manager_print_jobs_in_progress(Manager *m) {
_cleanup_free_ char *job_of_n = NULL;
Iterator i;
Job *j;
unsigned counter = 0, print_nr;
char cylon[6 + CYLON_BUFFER_EXTRA + 1];
unsigned cylon_pos;
char time[FORMAT_TIMESPAN_MAX], limit[FORMAT_TIMESPAN_MAX] = "no limit";
uint64_t x;
assert(m);
assert(m->n_running_jobs > 0);
manager_flip_auto_status(m, true, "delay");
print_nr = (m->jobs_in_progress_iteration / JOBS_IN_PROGRESS_PERIOD_DIVISOR) % m->n_running_jobs;
HASHMAP_FOREACH(j, m->jobs, i)
if (j->state == JOB_RUNNING && counter++ == print_nr)
break;
/* m->n_running_jobs must be consistent with the contents of m->jobs,
* so the above loop must have succeeded in finding j. */
assert(counter == print_nr + 1);
assert(j);
cylon_pos = m->jobs_in_progress_iteration % 14;
if (cylon_pos >= 8)
cylon_pos = 14 - cylon_pos;
draw_cylon(cylon, sizeof(cylon), 6, cylon_pos);
m->jobs_in_progress_iteration++;
if (m->n_running_jobs > 1) {
if (asprintf(&job_of_n, "(%u of %u) ", counter, m->n_running_jobs) < 0)
job_of_n = NULL;
}
format_timespan(time, sizeof(time), now(CLOCK_MONOTONIC) - j->begin_usec, 1*USEC_PER_SEC);
if (job_get_timeout(j, &x) > 0)
format_timespan(limit, sizeof(limit), x - j->begin_usec, 1*USEC_PER_SEC);
manager_status_printf(m, STATUS_TYPE_EPHEMERAL, cylon,
"%sA %s job is running for %s (%s / %s)",
strempty(job_of_n),
job_type_to_string(j->type),
unit_status_string(j->unit),
time, limit);
}
static int have_ask_password(void) {
_cleanup_closedir_ DIR *dir;
struct dirent *de;
dir = opendir("/run/systemd/ask-password");
if (!dir) {
if (errno == ENOENT)
return false;
else
return -errno;
}
FOREACH_DIRENT_ALL(de, dir, return -errno) {
if (startswith(de->d_name, "ask."))
return true;
}
return false;
}
static int manager_dispatch_ask_password_fd(sd_event_source *source,
int fd, uint32_t revents, void *userdata) {
Manager *m = userdata;
assert(m);
(void) flush_fd(fd);
m->have_ask_password = have_ask_password();
if (m->have_ask_password < 0)
/* Log error but continue. Negative have_ask_password
* is treated as unknown status. */
log_error_errno(m->have_ask_password, "Failed to list /run/systemd/ask-password: %m");
return 0;
}
static void manager_close_ask_password(Manager *m) {
assert(m);
m->ask_password_event_source = sd_event_source_unref(m->ask_password_event_source);
m->ask_password_inotify_fd = safe_close(m->ask_password_inotify_fd);
m->have_ask_password = -EINVAL;
}
static int manager_check_ask_password(Manager *m) {
int r;
assert(m);
if (!m->ask_password_event_source) {
assert(m->ask_password_inotify_fd < 0);
(void) mkdir_p_label("/run/systemd/ask-password", 0755);
m->ask_password_inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
if (m->ask_password_inotify_fd < 0)
return log_error_errno(errno, "Failed to create inotify object: %m");
r = inotify_add_watch_and_warn(m->ask_password_inotify_fd,
"/run/systemd/ask-password",
IN_CREATE|IN_DELETE|IN_MOVE);
if (r < 0) {
manager_close_ask_password(m);
return r;
}
r = sd_event_add_io(m->event, &m->ask_password_event_source,
m->ask_password_inotify_fd, EPOLLIN,
manager_dispatch_ask_password_fd, m);
if (r < 0) {
log_error_errno(r, "Failed to add event source for /run/systemd/ask-password: %m");
manager_close_ask_password(m);
return r;
}
(void) sd_event_source_set_description(m->ask_password_event_source, "manager-ask-password");
/* Queries might have been added meanwhile... */
manager_dispatch_ask_password_fd(m->ask_password_event_source,
m->ask_password_inotify_fd, EPOLLIN, m);
}
return m->have_ask_password;
}
static int manager_watch_idle_pipe(Manager *m) {
int r;
assert(m);
if (m->idle_pipe_event_source)
return 0;
if (m->idle_pipe[2] < 0)
return 0;
r = sd_event_add_io(m->event, &m->idle_pipe_event_source, m->idle_pipe[2], EPOLLIN, manager_dispatch_idle_pipe_fd, m);
if (r < 0)
return log_error_errno(r, "Failed to watch idle pipe: %m");
(void) sd_event_source_set_description(m->idle_pipe_event_source, "manager-idle-pipe");
return 0;
}
static void manager_close_idle_pipe(Manager *m) {
assert(m);
m->idle_pipe_event_source = sd_event_source_unref(m->idle_pipe_event_source);
safe_close_pair(m->idle_pipe);
safe_close_pair(m->idle_pipe + 2);
}
static int manager_setup_time_change(Manager *m) {
int r;
assert(m);
if (MANAGER_IS_TEST_RUN(m))
return 0;
m->time_change_event_source = sd_event_source_unref(m->time_change_event_source);
m->time_change_fd = safe_close(m->time_change_fd);
m->time_change_fd = time_change_fd();
if (m->time_change_fd < 0)
return log_error_errno(m->time_change_fd, "Failed to create timer change timer fd: %m");
r = sd_event_add_io(m->event, &m->time_change_event_source, m->time_change_fd, EPOLLIN, manager_dispatch_time_change_fd, m);
if (r < 0)
return log_error_errno(r, "Failed to create time change event source: %m");
/* Schedule this slightly earlier than the .timer event sources */
r = sd_event_source_set_priority(m->time_change_event_source, SD_EVENT_PRIORITY_NORMAL-1);
if (r < 0)
return log_error_errno(r, "Failed to set priority of time change event sources: %m");
(void) sd_event_source_set_description(m->time_change_event_source, "manager-time-change");
log_debug("Set up TFD_TIMER_CANCEL_ON_SET timerfd.");
return 0;
}
static int manager_read_timezone_stat(Manager *m) {
struct stat st;
bool changed;
assert(m);
/* Read the current stat() data of /etc/localtime so that we detect changes */
if (lstat("/etc/localtime", &st) < 0) {
log_debug_errno(errno, "Failed to stat /etc/localtime, ignoring: %m");
changed = m->etc_localtime_accessible;
m->etc_localtime_accessible = false;
} else {
usec_t k;
k = timespec_load(&st.st_mtim);
changed = !m->etc_localtime_accessible || k != m->etc_localtime_mtime;
m->etc_localtime_mtime = k;
m->etc_localtime_accessible = true;
}
return changed;
}
static int manager_setup_timezone_change(Manager *m) {
_cleanup_(sd_event_source_unrefp) sd_event_source *new_event = NULL;
int r;
assert(m);
if (MANAGER_IS_TEST_RUN(m))
return 0;
/* We watch /etc/localtime for three events: change of the link count (which might mean removal from /etc even
* though another link might be kept), renames, and file close operations after writing. Note we don't bother
* with IN_DELETE_SELF, as that would just report when the inode is removed entirely, i.e. after the link count
* went to zero and all fds to it are closed.
*
* Note that we never follow symlinks here. This is a simplification, but should cover almost all cases
* correctly.
*
* Note that we create the new event source first here, before releasing the old one. This should optimize
* behaviour as this way sd-event can reuse the old watch in case the inode didn't change. */
r = sd_event_add_inotify(m->event, &new_event, "/etc/localtime",
IN_ATTRIB|IN_MOVE_SELF|IN_CLOSE_WRITE|IN_DONT_FOLLOW, manager_dispatch_timezone_change, m);
if (r == -ENOENT) {
/* If the file doesn't exist yet, subscribe to /etc instead, and wait until it is created either by
* O_CREATE or by rename() */
log_debug_errno(r, "/etc/localtime doesn't exist yet, watching /etc instead.");
r = sd_event_add_inotify(m->event, &new_event, "/etc",
IN_CREATE|IN_MOVED_TO|IN_ONLYDIR, manager_dispatch_timezone_change, m);
}
if (r < 0)
return log_error_errno(r, "Failed to create timezone change event source: %m");
/* Schedule this slightly earlier than the .timer event sources */
r = sd_event_source_set_priority(new_event, SD_EVENT_PRIORITY_NORMAL-1);
if (r < 0)
return log_error_errno(r, "Failed to set priority of timezone change event sources: %m");
sd_event_source_unref(m->timezone_change_event_source);
m->timezone_change_event_source = TAKE_PTR(new_event);
return 0;
}
static int enable_special_signals(Manager *m) {
_cleanup_close_ int fd = -1;
assert(m);
if (MANAGER_IS_TEST_RUN(m))
return 0;
/* Enable that we get SIGINT on control-alt-del. In containers
* this will fail with EPERM (older) or EINVAL (newer), so
* ignore that. */
if (reboot(RB_DISABLE_CAD) < 0 && !IN_SET(errno, EPERM, EINVAL))
log_warning_errno(errno, "Failed to enable ctrl-alt-del handling: %m");
fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
if (fd < 0) {
/* Support systems without virtual console */
if (fd != -ENOENT)
log_warning_errno(errno, "Failed to open /dev/tty0: %m");
} else {
/* Enable that we get SIGWINCH on kbrequest */
if (ioctl(fd, KDSIGACCEPT, SIGWINCH) < 0)
log_warning_errno(errno, "Failed to enable kbrequest handling: %m");
}
return 0;
}
#define RTSIG_IF_AVAILABLE(signum) (signum <= SIGRTMAX ? signum : -1)
static int manager_setup_signals(Manager *m) {
struct sigaction sa = {
.sa_handler = SIG_DFL,
.sa_flags = SA_NOCLDSTOP|SA_RESTART,
};
sigset_t mask;
int r;
assert(m);
assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
/* We make liberal use of realtime signals here. On
* Linux/glibc we have 30 of them (with the exception of Linux
* on hppa, see below), between SIGRTMIN+0 ... SIGRTMIN+30
* (aka SIGRTMAX). */
assert_se(sigemptyset(&mask) == 0);
sigset_add_many(&mask,
SIGCHLD, /* Child died */
SIGTERM, /* Reexecute daemon */
SIGHUP, /* Reload configuration */
SIGUSR1, /* systemd/upstart: reconnect to D-Bus */
SIGUSR2, /* systemd: dump status */
SIGINT, /* Kernel sends us this on control-alt-del */
SIGWINCH, /* Kernel sends us this on kbrequest (alt-arrowup) */
SIGPWR, /* Some kernel drivers and upsd send us this on power failure */
SIGRTMIN+0, /* systemd: start default.target */
SIGRTMIN+1, /* systemd: isolate rescue.target */
SIGRTMIN+2, /* systemd: isolate emergency.target */
SIGRTMIN+3, /* systemd: start halt.target */
SIGRTMIN+4, /* systemd: start poweroff.target */
SIGRTMIN+5, /* systemd: start reboot.target */
SIGRTMIN+6, /* systemd: start kexec.target */
/* ... space for more special targets ... */
SIGRTMIN+13, /* systemd: Immediate halt */
SIGRTMIN+14, /* systemd: Immediate poweroff */
SIGRTMIN+15, /* systemd: Immediate reboot */
SIGRTMIN+16, /* systemd: Immediate kexec */
/* ... space for more immediate system state changes ... */
SIGRTMIN+20, /* systemd: enable status messages */
SIGRTMIN+21, /* systemd: disable status messages */
SIGRTMIN+22, /* systemd: set log level to LOG_DEBUG */
SIGRTMIN+23, /* systemd: set log level to LOG_INFO */
SIGRTMIN+24, /* systemd: Immediate exit (--user only) */
/* .. one free signal here ... */
/* Apparently Linux on hppa had fewer RT signals until v3.18,
* SIGRTMAX was SIGRTMIN+25, and then SIGRTMIN was lowered,
* see commit v3.17-7614-g1f25df2eff.
*
* We cannot unconditionally make use of those signals here,
* so let's use a runtime check. Since these commands are
* accessible by different means and only really a safety
* net, the missing functionality on hppa shouldn't matter.
*/
RTSIG_IF_AVAILABLE(SIGRTMIN+26), /* systemd: set log target to journal-or-kmsg */
RTSIG_IF_AVAILABLE(SIGRTMIN+27), /* systemd: set log target to console */
RTSIG_IF_AVAILABLE(SIGRTMIN+28), /* systemd: set log target to kmsg */
RTSIG_IF_AVAILABLE(SIGRTMIN+29), /* systemd: set log target to syslog-or-kmsg (obsolete) */
/* ... one free signal here SIGRTMIN+30 ... */
-1);
assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
m->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
if (m->signal_fd < 0)
return -errno;
r = sd_event_add_io(m->event, &m->signal_event_source, m->signal_fd, EPOLLIN, manager_dispatch_signal_fd, m);
if (r < 0)
return r;
(void) sd_event_source_set_description(m->signal_event_source, "manager-signal");
/* Process signals a bit earlier than the rest of things, but later than notify_fd processing, so that the
* notify processing can still figure out to which process/service a message belongs, before we reap the
* process. Also, process this before handling cgroup notifications, so that we always collect child exit
* status information before detecting that there's no process in a cgroup. */
r = sd_event_source_set_priority(m->signal_event_source, SD_EVENT_PRIORITY_NORMAL-6);
if (r < 0)
return r;
if (MANAGER_IS_SYSTEM(m))
return enable_special_signals(m);
return 0;
}
static char** sanitize_environment(char **l) {
/* Let's remove some environment variables that we need ourselves to communicate with our clients */
strv_env_unset_many(
l,
"EXIT_CODE",
"EXIT_STATUS",
"INVOCATION_ID",
"JOURNAL_STREAM",
"LISTEN_FDNAMES",
"LISTEN_FDS",
"LISTEN_PID",
"MAINPID",
"MANAGERPID",
"NOTIFY_SOCKET",
"PIDFILE",
"REMOTE_ADDR",
"REMOTE_PORT",
"SERVICE_RESULT",
"WATCHDOG_PID",
"WATCHDOG_USEC",
NULL);
/* Let's order the environment alphabetically, just to make it pretty */
strv_sort(l);
return l;
}
int manager_default_environment(Manager *m) {
int r;
assert(m);
m->transient_environment = strv_free(m->transient_environment);
if (MANAGER_IS_SYSTEM(m)) {
/* The system manager always starts with a clean
* environment for its children. It does not import
* the kernel's or the parents' exported variables.
*
* The initial passed environment is untouched to keep
* /proc/self/environ valid; it is used for tagging
* the init process inside containers. */
m->transient_environment = strv_new("PATH=" DEFAULT_PATH);
if (!m->transient_environment)
return log_oom();
/* Import locale variables LC_*= from configuration */
(void) locale_setup(&m->transient_environment);
} else {
_cleanup_free_ char *k = NULL;
/* The user manager passes its own environment
* along to its children, except for $PATH. */
m->transient_environment = strv_copy(environ);
if (!m->transient_environment)
return log_oom();
k = strdup("PATH=" DEFAULT_USER_PATH);
if (!k)
return log_oom();
r = strv_env_replace(&m->transient_environment, k);
if (r < 0)
return log_oom();
TAKE_PTR(k);
}
sanitize_environment(m->transient_environment);
return 0;
}
static int manager_setup_prefix(Manager *m) {
struct table_entry {
uint64_t type;
const char *suffix;
};
static const struct table_entry paths_system[_EXEC_DIRECTORY_TYPE_MAX] = {
[EXEC_DIRECTORY_RUNTIME] = { SD_PATH_SYSTEM_RUNTIME, NULL },
[EXEC_DIRECTORY_STATE] = { SD_PATH_SYSTEM_STATE_PRIVATE, NULL },
[EXEC_DIRECTORY_CACHE] = { SD_PATH_SYSTEM_STATE_CACHE, NULL },
[EXEC_DIRECTORY_LOGS] = { SD_PATH_SYSTEM_STATE_LOGS, NULL },
[EXEC_DIRECTORY_CONFIGURATION] = { SD_PATH_SYSTEM_CONFIGURATION, NULL },
};
static const struct table_entry paths_user[_EXEC_DIRECTORY_TYPE_MAX] = {
[EXEC_DIRECTORY_RUNTIME] = { SD_PATH_USER_RUNTIME, NULL },
[EXEC_DIRECTORY_STATE] = { SD_PATH_USER_CONFIGURATION, NULL },
[EXEC_DIRECTORY_CACHE] = { SD_PATH_USER_STATE_CACHE, NULL },
[EXEC_DIRECTORY_LOGS] = { SD_PATH_USER_CONFIGURATION, "log" },
[EXEC_DIRECTORY_CONFIGURATION] = { SD_PATH_USER_CONFIGURATION, NULL },
};
const struct table_entry *p;
ExecDirectoryType i;
int r;
assert(m);
if (MANAGER_IS_SYSTEM(m))
p = paths_system;
else
p = paths_user;
for (i = 0; i < _EXEC_DIRECTORY_TYPE_MAX; i++) {
r = sd_path_lookup(p[i].type, p[i].suffix, &m->prefix[i]);
if (r < 0)
return r;
}
return 0;
}
static void manager_free_unit_name_maps(Manager *m) {
m->unit_id_map = hashmap_free(m->unit_id_map);
m->unit_name_map = hashmap_free(m->unit_name_map);
m->unit_path_cache = set_free_free(m->unit_path_cache);
m->unit_cache_mtime = 0;
}
static int manager_setup_run_queue(Manager *m) {
int r;
assert(m);
assert(!m->run_queue_event_source);
r = sd_event_add_defer(m->event, &m->run_queue_event_source, manager_dispatch_run_queue, m);
if (r < 0)
return r;
r = sd_event_source_set_priority(m->run_queue_event_source, SD_EVENT_PRIORITY_IDLE);
if (r < 0)
return r;
r = sd_event_source_set_enabled(m->run_queue_event_source, SD_EVENT_OFF);
if (r < 0)
return r;
(void) sd_event_source_set_description(m->run_queue_event_source, "manager-run-queue");
return 0;
}
static int manager_setup_sigchld_event_source(Manager *m) {
int r;
assert(m);
assert(!m->sigchld_event_source);
r = sd_event_add_defer(m->event, &m->sigchld_event_source, manager_dispatch_sigchld, m);
if (r < 0)
return r;
r = sd_event_source_set_priority(m->sigchld_event_source, SD_EVENT_PRIORITY_NORMAL-7);
if (r < 0)
return r;
r = sd_event_source_set_enabled(m->sigchld_event_source, SD_EVENT_OFF);
if (r < 0)
return r;
(void) sd_event_source_set_description(m->sigchld_event_source, "manager-sigchld");
return 0;
}
int manager_new(UnitFileScope scope, ManagerTestRunFlags test_run_flags, Manager **_m) {
_cleanup_(manager_freep) Manager *m = NULL;
int r;
assert(_m);
assert(IN_SET(scope, UNIT_FILE_SYSTEM, UNIT_FILE_USER));
m = new(Manager, 1);
if (!m)
return -ENOMEM;
*m = (Manager) {
.unit_file_scope = scope,
.objective = _MANAGER_OBJECTIVE_INVALID,
.status_unit_format = STATUS_UNIT_FORMAT_DEFAULT,
.default_timer_accuracy_usec = USEC_PER_MINUTE,
.default_memory_accounting = MEMORY_ACCOUNTING_DEFAULT,
.default_tasks_accounting = true,
.default_tasks_max = TASKS_MAX_UNSET,
.default_timeout_start_usec = DEFAULT_TIMEOUT_USEC,
.default_timeout_stop_usec = DEFAULT_TIMEOUT_USEC,
.default_restart_usec = DEFAULT_RESTART_USEC,
.original_log_level = -1,
.original_log_target = _LOG_TARGET_INVALID,
.notify_fd = -1,
.cgroups_agent_fd = -1,
.signal_fd = -1,
.time_change_fd = -1,
.user_lookup_fds = { -1, -1 },
.private_listen_fd = -1,
.dev_autofs_fd = -1,
.cgroup_inotify_fd = -1,
.pin_cgroupfs_fd = -1,
.ask_password_inotify_fd = -1,
.idle_pipe = { -1, -1, -1, -1},
/* start as id #1, so that we can leave #0 around as "null-like" value */
.current_job_id = 1,
.have_ask_password = -EINVAL, /* we don't know */
.first_boot = -1,
.test_run_flags = test_run_flags,
.default_oom_policy = OOM_STOP,
};
#if ENABLE_EFI
if (MANAGER_IS_SYSTEM(m) && detect_container() <= 0)
boot_timestamps(m->timestamps + MANAGER_TIMESTAMP_USERSPACE,
m->timestamps + MANAGER_TIMESTAMP_FIRMWARE,
m->timestamps + MANAGER_TIMESTAMP_LOADER);
#endif
/* Prepare log fields we can use for structured logging */
if (MANAGER_IS_SYSTEM(m)) {
m->unit_log_field = "UNIT=";
m->unit_log_format_string = "UNIT=%s";
m->invocation_log_field = "INVOCATION_ID=";
m->invocation_log_format_string = "INVOCATION_ID=%s";
} else {
m->unit_log_field = "USER_UNIT=";
m->unit_log_format_string = "USER_UNIT=%s";
m->invocation_log_field = "USER_INVOCATION_ID=";
m->invocation_log_format_string = "USER_INVOCATION_ID=%s";
}
/* Reboot immediately if the user hits C-A-D more often than 7x per 2s */
m->ctrl_alt_del_ratelimit = (RateLimit) { .interval = 2 * USEC_PER_SEC, .burst = 7 };
r = manager_default_environment(m);
if (r < 0)
return r;
r = hashmap_ensure_allocated(&m->units, &string_hash_ops);
if (r < 0)
return r;
r = hashmap_ensure_allocated(&m->jobs, NULL);
if (r < 0)
return r;
r = hashmap_ensure_allocated(&m->cgroup_unit, &path_hash_ops);
if (r < 0)
return r;
r = hashmap_ensure_allocated(&m->watch_bus, &string_hash_ops);
if (r < 0)
return r;
r = prioq_ensure_allocated(&m->run_queue, compare_job_priority);
if (r < 0)
return r;
r = manager_setup_prefix(m);
if (r < 0)
return r;
r = sd_event_default(&m->event);
if (r < 0)
return r;
r = manager_setup_run_queue(m);
if (r < 0)
return r;
if (test_run_flags == MANAGER_TEST_RUN_MINIMAL) {
m->cgroup_root = strdup("");
if (!m->cgroup_root)
return -ENOMEM;
} else {
r = manager_setup_signals(m);
if (r < 0)
return r;
r = manager_setup_cgroup(m);
if (r < 0)
return r;
r = manager_setup_time_change(m);
if (r < 0)
return r;
r = manager_read_timezone_stat(m);
if (r < 0)
return r;
(void) manager_setup_timezone_change(m);
r = manager_setup_sigchld_event_source(m);
if (r < 0)
return r;
}
if (test_run_flags == 0) {
if (MANAGER_IS_SYSTEM(m))
r = mkdir_label("/run/systemd/units", 0755);
else {
_cleanup_free_ char *units_path = NULL;
r = xdg_user_runtime_dir(&units_path, "/systemd/units");
if (r < 0)
return r;
r = mkdir_p_label(units_path, 0755);
}
if (r < 0 && r != -EEXIST)
return r;
}
m->taint_usr =
!in_initrd() &&
dir_is_empty("/usr") > 0;
/* Note that we do not set up the notify fd here. We do that after deserialization,
* since they might have gotten serialized across the reexec. */
*_m = TAKE_PTR(m);
return 0;
}
static int manager_setup_notify(Manager *m) {
int r;
if (MANAGER_IS_TEST_RUN(m))
return 0;
if (m->notify_fd < 0) {
_cleanup_close_ int fd = -1;
union sockaddr_union sa;
socklen_t sa_len;
/* First free all secondary fields */
m->notify_socket = mfree(m->notify_socket);
m->notify_event_source = sd_event_source_unref(m->notify_event_source);
fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
if (fd < 0)
return log_error_errno(errno, "Failed to allocate notification socket: %m");
fd_inc_rcvbuf(fd, NOTIFY_RCVBUF_SIZE);
m->notify_socket = path_join(m->prefix[EXEC_DIRECTORY_RUNTIME], "systemd/notify");
if (!m->notify_socket)
return log_oom();
r = sockaddr_un_set_path(&sa.un, m->notify_socket);
if (r < 0)
return log_error_errno(r, "Notify socket '%s' not valid for AF_UNIX socket address, refusing.",
m->notify_socket);
sa_len = r;
(void) mkdir_parents_label(m->notify_socket, 0755);
(void) sockaddr_un_unlink(&sa.un);
r = bind(fd, &sa.sa, sa_len);
if (r < 0)
return log_error_errno(errno, "bind(%s) failed: %m", m->notify_socket);
r = setsockopt_int(fd, SOL_SOCKET, SO_PASSCRED, true);
if (r < 0)
return log_error_errno(r, "SO_PASSCRED failed: %m");
m->notify_fd = TAKE_FD(fd);
log_debug("Using notification socket %s", m->notify_socket);
}
if (!m->notify_event_source) {
r = sd_event_add_io(m->event, &m->notify_event_source, m->notify_fd, EPOLLIN, manager_dispatch_notify_fd, m);
if (r < 0)
return log_error_errno(r, "Failed to allocate notify event source: %m");
/* Process notification messages a bit earlier than SIGCHLD, so that we can still identify to which
* service an exit message belongs. */
r = sd_event_source_set_priority(m->notify_event_source, SD_EVENT_PRIORITY_NORMAL-8);
if (r < 0)
return log_error_errno(r, "Failed to set priority of notify event source: %m");
(void) sd_event_source_set_description(m->notify_event_source, "manager-notify");
}
return 0;
}
static int manager_setup_cgroups_agent(Manager *m) {
static const union sockaddr_union sa = {
.un.sun_family = AF_UNIX,
.un.sun_path = "/run/systemd/cgroups-agent",
};
int r;
/* This creates a listening socket we receive cgroups agent messages on. We do not use D-Bus for delivering
* these messages from the cgroups agent binary to PID 1, as the cgroups agent binary is very short-living, and
* each instance of it needs a new D-Bus connection. Since D-Bus connections are SOCK_STREAM/AF_UNIX, on
* overloaded systems the backlog of the D-Bus socket becomes relevant, as not more than the configured number
* of D-Bus connections may be queued until the kernel will start dropping further incoming connections,
* possibly resulting in lost cgroups agent messages. To avoid this, we'll use a private SOCK_DGRAM/AF_UNIX
* socket, where no backlog is relevant as communication may take place without an actual connect() cycle, and
* we thus won't lose messages.
*