summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorMichael Stapelberg <michael@stapelberg.de>2014-04-26 10:08:46 +0200
committerMichael Stapelberg <michael@stapelberg.de>2014-04-26 10:08:46 +0200
commit663996b3bb3cdaa81ac830674fdda00e28a2485b (patch)
treeec5ccfae391a7cc7970f7618a58970c87dec770b /src
downloadsystemd-663996b3bb3cdaa81ac830674fdda00e28a2485b.tar.gz
Imported Upstream version 204
Diffstat (limited to 'src')
-rw-r--r--src/ac-power/ac-power.c37
-rw-r--r--src/activate/activate.c443
-rw-r--r--src/analyze/systemd-analyze.c1270
-rw-r--r--src/ask-password/ask-password.c184
-rw-r--r--src/binfmt/binfmt.c211
-rw-r--r--src/boot/boot-efi.c190
-rw-r--r--src/boot/boot-loader.c132
-rw-r--r--src/boot/boot-loader.h25
-rw-r--r--src/boot/boot.h64
-rw-r--r--src/boot/bootctl.c288
-rw-r--r--src/bootchart/bootchart.c481
-rw-r--r--src/bootchart/bootchart.conf20
-rw-r--r--src/bootchart/bootchart.h133
-rwxr-xr-xsrc/bootchart/store.c504
-rw-r--r--src/bootchart/store.h35
-rw-r--r--src/bootchart/svg.c1332
-rw-r--r--src/bootchart/svg.h27
-rw-r--r--src/cgls/cgls.c213
-rw-r--r--src/cgroups-agent/cgroups-agent.c101
-rw-r--r--src/cgtop/cgtop.c854
-rw-r--r--src/core/audit-fd.c73
-rw-r--r--src/core/audit-fd.h25
-rw-r--r--src/core/automount.c920
-rw-r--r--src/core/automount.h71
-rw-r--r--src/core/build.h84
-rw-r--r--src/core/bus-errors.h42
-rw-r--r--src/core/cgroup-attr.c132
-rw-r--r--src/core/cgroup-attr.h50
-rw-r--r--src/core/cgroup-semantics.c333
-rw-r--r--src/core/cgroup-semantics.h43
-rw-r--r--src/core/cgroup.c628
-rw-r--r--src/core/cgroup.h94
-rw-r--r--src/core/condition.c389
-rw-r--r--src/core/condition.h70
-rw-r--r--src/core/dbus-automount.c75
-rw-r--r--src/core/dbus-automount.h31
-rw-r--r--src/core/dbus-device.c68
-rw-r--r--src/core/dbus-device.h31
-rw-r--r--src/core/dbus-execute.c439
-rw-r--r--src/core/dbus-execute.h123
-rw-r--r--src/core/dbus-job.c373
-rw-r--r--src/core/dbus-job.h33
-rw-r--r--src/core/dbus-kill.c35
-rw-r--r--src/core/dbus-kill.h39
-rw-r--r--src/core/dbus-manager.c1912
-rw-r--r--src/core/dbus-manager.h28
-rw-r--r--src/core/dbus-mount.c170
-rw-r--r--src/core/dbus-mount.h31
-rw-r--r--src/core/dbus-path.c122
-rw-r--r--src/core/dbus-path.h32
-rw-r--r--src/core/dbus-service.c163
-rw-r--r--src/core/dbus-service.h31
-rw-r--r--src/core/dbus-snapshot.c84
-rw-r--r--src/core/dbus-snapshot.h30
-rw-r--r--src/core/dbus-socket.c215
-rw-r--r--src/core/dbus-socket.h31
-rw-r--r--src/core/dbus-swap.c117
-rw-r--r--src/core/dbus-swap.h32
-rw-r--r--src/core/dbus-target.c58
-rw-r--r--src/core/dbus-target.h30
-rw-r--r--src/core/dbus-timer.c191
-rw-r--r--src/core/dbus-timer.h31
-rw-r--r--src/core/dbus-unit.c1324
-rw-r--r--src/core/dbus-unit.h179
-rw-r--r--src/core/dbus.c1491
-rw-r--r--src/core/dbus.h50
-rw-r--r--src/core/device.c654
-rw-r--r--src/core/device.h56
-rw-r--r--src/core/execute.c2254
-rw-r--r--src/core/execute.h217
-rw-r--r--src/core/hostname-setup.c92
-rw-r--r--src/core/hostname-setup.h24
-rw-r--r--src/core/ima-setup.c110
-rw-r--r--src/core/ima-setup.h26
-rw-r--r--src/core/initreq.h77
-rw-r--r--src/core/job.c1143
-rw-r--r--src/core/job.h234
-rw-r--r--src/core/kill.c63
-rw-r--r--src/core/kill.h62
-rw-r--r--src/core/killall.c210
-rw-r--r--src/core/killall.h27
-rw-r--r--src/core/kmod-setup.c110
-rw-r--r--src/core/kmod-setup.h24
-rw-r--r--src/core/load-dropin.c223
-rw-r--r--src/core/load-dropin.h29
-rw-r--r--src/core/load-fragment-gperf.gperf.m4258
-rw-r--r--src/core/load-fragment.c2486
-rw-r--r--src/core/load-fragment.h84
-rw-r--r--src/core/locale-setup.c145
-rw-r--r--src/core/locale-setup.h24
-rw-r--r--src/core/loopback-setup.c308
-rw-r--r--src/core/loopback-setup.h24
-rw-r--r--src/core/machine-id-setup.c237
-rw-r--r--src/core/machine-id-setup.h24
-rw-r--r--src/core/macros.systemd.in73
-rw-r--r--src/core/main.c1958
-rw-r--r--src/core/manager.c2674
-rw-r--r--src/core/manager.h306
-rw-r--r--src/core/mount-setup.c417
-rw-r--r--src/core/mount-setup.h33
-rw-r--r--src/core/mount.c1932
-rw-r--r--src/core/mount.h123
-rw-r--r--src/core/namespace.c277
-rw-r--r--src/core/namespace.h33
-rw-r--r--src/core/org.freedesktop.systemd1.conf92
-rw-r--r--src/core/org.freedesktop.systemd1.policy.in.in41
-rw-r--r--src/core/org.freedesktop.systemd1.service11
-rw-r--r--src/core/path.c833
-rw-r--r--src/core/path.h108
-rw-r--r--src/core/securebits.h45
-rw-r--r--src/core/selinux-access.c439
-rw-r--r--src/core/selinux-access.h62
-rw-r--r--src/core/selinux-setup.c120
-rw-r--r--src/core/selinux-setup.h26
-rw-r--r--src/core/service.c3888
-rw-r--r--src/core/service.h225
-rw-r--r--src/core/shutdown.c332
-rw-r--r--src/core/smack-setup.c151
-rw-r--r--src/core/smack-setup.h26
-rw-r--r--src/core/snapshot.c309
-rw-r--r--src/core/snapshot.h50
-rw-r--r--src/core/socket.c2411
-rw-r--r--src/core/socket.h180
-rw-r--r--src/core/special.h115
-rw-r--r--src/core/swap.c1385
-rw-r--r--src/core/swap.h121
-rw-r--r--src/core/switch-root.c167
-rw-r--r--src/core/switch-root.h27
-rw-r--r--src/core/sync.c65
-rw-r--r--src/core/sync.h24
-rw-r--r--src/core/syscall-list.c57
-rw-r--r--src/core/syscall-list.h44
-rw-r--r--src/core/sysfs-show.h24
-rw-r--r--src/core/system.conf43
-rw-r--r--src/core/systemd.pc.in23
-rw-r--r--src/core/target.c239
-rw-r--r--src/core/target.h44
-rw-r--r--src/core/tcpwrap.c68
-rw-r--r--src/core/tcpwrap.h26
-rw-r--r--src/core/timer.c622
-rw-r--r--src/core/timer.h97
-rw-r--r--src/core/transaction.c1132
-rw-r--r--src/core/transaction.h57
-rw-r--r--src/core/umount.c639
-rw-r--r--src/core/umount.h30
-rw-r--r--src/core/unit-printf.c329
-rw-r--r--src/core/unit-printf.h28
-rw-r--r--src/core/unit.c3089
-rw-r--r--src/core/unit.h588
-rw-r--r--src/core/user.conf17
-rw-r--r--src/cryptsetup/cryptsetup-generator.c468
-rw-r--r--src/cryptsetup/cryptsetup.c591
-rw-r--r--src/delta/delta.c489
-rw-r--r--src/detect-virt/detect-virt.c171
-rw-r--r--src/efi-boot-generator/efi-boot-generator.c123
-rw-r--r--src/fsck/fsck.c412
-rw-r--r--src/fstab-generator/fstab-generator.c648
-rw-r--r--src/getty-generator/getty-generator.c181
-rwxr-xr-xsrc/gudev/gjs-example.js75
-rw-r--r--src/gudev/gudev-1.0.pc.in11
-rw-r--r--src/gudev/gudev.h32
-rw-r--r--src/gudev/gudevclient.c525
-rw-r--r--src/gudev/gudevclient.h99
-rw-r--r--src/gudev/gudevdevice.c961
-rw-r--r--src/gudev/gudevdevice.h127
-rw-r--r--src/gudev/gudevenumerator.c429
-rw-r--r--src/gudev/gudevenumerator.h106
-rw-r--r--src/gudev/gudevenums.h48
-rw-r--r--src/gudev/gudevenumtypes.c.template39
-rw-r--r--src/gudev/gudevenumtypes.h19
-rw-r--r--src/gudev/gudevenumtypes.h.template24
-rw-r--r--src/gudev/gudevmarshal.list1
-rw-r--r--src/gudev/gudevprivate.h40
-rw-r--r--src/gudev/gudevtypes.h50
-rwxr-xr-xsrc/gudev/seed-example-enum.js38
-rwxr-xr-xsrc/gudev/seed-example.js72
-rw-r--r--src/hostname/hostnamectl.c583
-rw-r--r--src/hostname/hostnamed.c740
-rw-r--r--src/hostname/org.freedesktop.hostname1.conf27
-rw-r--r--src/hostname/org.freedesktop.hostname1.policy.in50
-rw-r--r--src/hostname/org.freedesktop.hostname1.service12
-rw-r--r--src/initctl/initctl.c459
-rw-r--r--src/journal/browse.html544
-rw-r--r--src/journal/cat.c179
-rw-r--r--src/journal/catalog.c655
-rw-r--r--src/journal/catalog.h37
-rw-r--r--src/journal/compress.c216
-rw-r--r--src/journal/compress.h35
-rw-r--r--src/journal/coredump.c277
-rw-r--r--src/journal/coredumpctl.c587
-rw-r--r--src/journal/fsprg.c384
-rw-r--r--src/journal/fsprg.h66
-rw-r--r--src/journal/journal-authenticate.c563
-rw-r--r--src/journal/journal-authenticate.h44
-rw-r--r--src/journal/journal-def.h216
-rw-r--r--src/journal/journal-file.c2914
-rw-r--r--src/journal/journal-file.h195
-rw-r--r--src/journal/journal-gatewayd.c1069
-rw-r--r--src/journal/journal-internal.h141
-rw-r--r--src/journal/journal-qrcode.c138
-rw-r--r--src/journal/journal-qrcode.h30
-rw-r--r--src/journal/journal-send.c586
-rw-r--r--src/journal/journal-vacuum.c318
-rw-r--r--src/journal/journal-vacuum.h26
-rw-r--r--src/journal/journal-verify.c1163
-rw-r--r--src/journal/journal-verify.h26
-rw-r--r--src/journal/journalctl.c1356
-rw-r--r--src/journal/journald-console.c86
-rw-r--r--src/journal/journald-console.h26
-rw-r--r--src/journal/journald-gperf.gperf40
-rw-r--r--src/journal/journald-kmsg.c440
-rw-r--r--src/journal/journald-kmsg.h32
-rw-r--r--src/journal/journald-native.c423
-rw-r--r--src/journal/journald-native.h30
-rw-r--r--src/journal/journald-rate-limit.c260
-rw-r--r--src/journal/journald-rate-limit.h31
-rw-r--r--src/journal/journald-server.c1556
-rw-r--r--src/journal/journald-server.h158
-rw-r--r--src/journal/journald-stream.c458
-rw-r--r--src/journal/journald-stream.h30
-rw-r--r--src/journal/journald-syslog.c491
-rw-r--r--src/journal/journald-syslog.h36
-rw-r--r--src/journal/journald.c139
-rw-r--r--src/journal/journald.conf33
-rw-r--r--src/journal/libsystemd-journal.pc.in19
-rw-r--r--src/journal/libsystemd-journal.sym106
-rw-r--r--src/journal/lookup3.c1009
-rw-r--r--src/journal/lookup3.h24
-rw-r--r--src/journal/microhttpd-util.c37
-rw-r--r--src/journal/microhttpd-util.h28
-rw-r--r--src/journal/mmap-cache.c576
-rw-r--r--src/journal/mmap-cache.h36
-rw-r--r--src/journal/sd-journal.c2552
-rw-r--r--src/journal/test-catalog.c134
-rw-r--r--src/journal/test-journal-enum.c55
-rw-r--r--src/journal/test-journal-match.c76
-rw-r--r--src/journal/test-journal-send.c78
-rw-r--r--src/journal/test-journal-stream.c181
-rw-r--r--src/journal/test-journal-syslog.c44
-rw-r--r--src/journal/test-journal-verify.c147
-rw-r--r--src/journal/test-journal.c129
-rw-r--r--src/journal/test-mmap-cache.c79
-rw-r--r--src/kernel-install/50-depmod.install8
-rw-r--r--src/kernel-install/90-loaderentry.install77
-rw-r--r--src/kernel-install/kernel-install123
-rw-r--r--src/libsystemd-bus/bus-bloom.c93
-rw-r--r--src/libsystemd-bus/bus-bloom.h30
-rw-r--r--src/libsystemd-bus/bus-control.c378
-rw-r--r--src/libsystemd-bus/bus-control.h27
-rw-r--r--src/libsystemd-bus/bus-error.c177
-rw-r--r--src/libsystemd-bus/bus-error.h31
-rw-r--r--src/libsystemd-bus/bus-internal.c256
-rw-r--r--src/libsystemd-bus/bus-internal.h198
-rw-r--r--src/libsystemd-bus/bus-kernel.c618
-rw-r--r--src/libsystemd-bus/bus-kernel.h32
-rw-r--r--src/libsystemd-bus/bus-match.c994
-rw-r--r--src/libsystemd-bus/bus-match.h82
-rw-r--r--src/libsystemd-bus/bus-message.c3494
-rw-r--r--src/libsystemd-bus/bus-message.h198
-rw-r--r--src/libsystemd-bus/bus-signature.c153
-rw-r--r--src/libsystemd-bus/bus-signature.h31
-rw-r--r--src/libsystemd-bus/bus-socket.c1059
-rw-r--r--src/libsystemd-bus/bus-socket.h36
-rw-r--r--src/libsystemd-bus/bus-type.c163
-rw-r--r--src/libsystemd-bus/bus-type.h34
-rw-r--r--src/libsystemd-bus/busctl.c340
-rw-r--r--src/libsystemd-bus/kdbus.h418
-rw-r--r--src/libsystemd-bus/sd-bus.c2425
-rw-r--r--src/libsystemd-bus/test-bus-chat.c576
-rw-r--r--src/libsystemd-bus/test-bus-kernel.c162
-rw-r--r--src/libsystemd-bus/test-bus-marshal.c175
-rw-r--r--src/libsystemd-bus/test-bus-match.c114
-rw-r--r--src/libsystemd-bus/test-bus-server.c223
-rw-r--r--src/libsystemd-bus/test-bus-signature.c116
-rw-r--r--src/libsystemd-daemon/libsystemd-daemon.pc.in19
-rw-r--r--src/libsystemd-daemon/libsystemd-daemon.sym27
-rw-r--r--src/libsystemd-daemon/sd-daemon.c520
-rw-r--r--src/libsystemd-id128/libsystemd-id128.pc.in18
-rw-r--r--src/libsystemd-id128/libsystemd-id128.sym21
-rw-r--r--src/libsystemd-id128/sd-id128.c241
-rw-r--r--src/libudev/libudev-device-private.c192
-rw-r--r--src/libudev/libudev-device.c1871
-rw-r--r--src/libudev/libudev-enumerate.c958
-rw-r--r--src/libudev/libudev-hwdb-def.h74
-rw-r--r--src/libudev/libudev-hwdb.c392
-rw-r--r--src/libudev/libudev-list.c355
-rw-r--r--src/libudev/libudev-monitor.c782
-rw-r--r--src/libudev/libudev-private.h179
-rw-r--r--src/libudev/libudev-queue-private.c406
-rw-r--r--src/libudev/libudev-queue.c480
-rw-r--r--src/libudev/libudev-util.c659
-rw-r--r--src/libudev/libudev.c314
-rw-r--r--src/libudev/libudev.h205
-rw-r--r--src/libudev/libudev.pc.in18
-rw-r--r--src/libudev/libudev.sym113
-rw-r--r--src/locale/kbd-model-map77
-rw-r--r--src/locale/localectl.c936
-rw-r--r--src/locale/localed.c1405
-rw-r--r--src/locale/org.freedesktop.locale1.conf27
-rw-r--r--src/locale/org.freedesktop.locale1.policy.in40
-rw-r--r--src/locale/org.freedesktop.locale1.service12
-rw-r--r--src/login/70-power-switch.rules13
-rw-r--r--src/login/70-uaccess.rules74
-rw-r--r--src/login/71-seat.rules.in48
-rw-r--r--src/login/73-seat-late.rules.in17
-rw-r--r--src/login/inhibit.c310
-rw-r--r--src/login/libsystemd-login.pc.in18
-rw-r--r--src/login/libsystemd-login.sym77
-rw-r--r--src/login/loginctl.c1592
-rw-r--r--src/login/logind-acl.c248
-rw-r--r--src/login/logind-acl.h57
-rw-r--r--src/login/logind-action.c151
-rw-r--r--src/login/logind-action.h54
-rw-r--r--src/login/logind-button.c261
-rw-r--r--src/login/logind-button.h48
-rw-r--r--src/login/logind-dbus.c2446
-rw-r--r--src/login/logind-device.c96
-rw-r--r--src/login/logind-device.h45
-rw-r--r--src/login/logind-gperf.gperf34
-rw-r--r--src/login/logind-inhibit.c473
-rw-r--r--src/login/logind-inhibit.h95
-rw-r--r--src/login/logind-seat-dbus.c412
-rw-r--r--src/login/logind-seat.c543
-rw-r--r--src/login/logind-seat.h83
-rw-r--r--src/login/logind-session-dbus.c554
-rw-r--r--src/login/logind-session.c1080
-rw-r--r--src/login/logind-session.h148
-rw-r--r--src/login/logind-user-dbus.c411
-rw-r--r--src/login/logind-user.c667
-rw-r--r--src/login/logind-user.h84
-rw-r--r--src/login/logind.c1767
-rw-r--r--src/login/logind.conf28
-rw-r--r--src/login/logind.h189
-rw-r--r--src/login/multi-seat-x.c108
-rw-r--r--src/login/org.freedesktop.login1.conf150
-rw-r--r--src/login/org.freedesktop.login1.policy.in273
-rw-r--r--src/login/org.freedesktop.login1.service12
-rw-r--r--src/login/pam-module.c723
-rw-r--r--src/login/sd-login.c762
-rw-r--r--src/login/sysfs-show.c194
-rw-r--r--src/login/test-inhibit.c139
-rw-r--r--src/login/test-login.c220
-rw-r--r--src/login/user-sessions.c102
-rw-r--r--src/machine-id-setup/machine-id-setup-main.c101
-rw-r--r--src/modules-load/modules-load.c327
-rw-r--r--src/notify/notify.c228
-rw-r--r--src/nspawn/nspawn.c1750
-rw-r--r--src/nss-myhostname/ifconf.h73
-rw-r--r--src/nss-myhostname/netlink.c206
-rw-r--r--src/nss-myhostname/nss-myhostname.c533
-rw-r--r--src/python-systemd/__init__.py18
-rw-r--r--src/python-systemd/_daemon.c325
-rw-r--r--src/python-systemd/_journal.c158
-rw-r--r--src/python-systemd/_reader.c1131
-rw-r--r--src/python-systemd/daemon.py54
-rw-r--r--src/python-systemd/id128-constants.h32
-rw-r--r--src/python-systemd/id128.c161
-rw-r--r--src/python-systemd/journal.py541
-rw-r--r--src/python-systemd/login.c176
-rw-r--r--src/python-systemd/pyutil.c46
-rw-r--r--src/python-systemd/pyutil.h49
-rw-r--r--src/quotacheck/quotacheck.c122
-rw-r--r--src/random-seed/random-seed.c149
-rw-r--r--src/rc-local-generator/rc-local-generator.c115
-rw-r--r--src/readahead/readahead-analyze.c146
-rw-r--r--src/readahead/readahead-collect.c652
-rw-r--r--src/readahead/readahead-common.c414
-rw-r--r--src/readahead/readahead-common.h61
-rw-r--r--src/readahead/readahead-replay.c311
-rw-r--r--src/readahead/readahead.c158
-rw-r--r--src/readahead/sd-readahead.c89
-rw-r--r--src/remount-fs/remount-fs.c169
-rw-r--r--src/reply-password/reply-password.c109
-rw-r--r--src/shared/MurmurHash3.c349
-rw-r--r--src/shared/MurmurHash3.h38
-rw-r--r--src/shared/acl-util.c126
-rw-r--r--src/shared/acl-util.h27
-rw-r--r--src/shared/ask-password-api.c575
-rw-r--r--src/shared/ask-password-api.h30
-rw-r--r--src/shared/audit.c128
-rw-r--r--src/shared/audit.h32
-rw-r--r--src/shared/calendarspec.c927
-rw-r--r--src/shared/calendarspec.h57
-rw-r--r--src/shared/capability.c225
-rw-r--r--src/shared/capability.h33
-rw-r--r--src/shared/cgroup-label.c77
-rw-r--r--src/shared/cgroup-show.c300
-rw-r--r--src/shared/cgroup-show.h36
-rw-r--r--src/shared/cgroup-util.c1603
-rw-r--r--src/shared/cgroup-util.h115
-rw-r--r--src/shared/conf-files.c178
-rw-r--r--src/shared/conf-files.h32
-rw-r--r--src/shared/conf-parser.c920
-rw-r--r--src/shared/conf-parser.h151
-rw-r--r--src/shared/dbus-common.c1428
-rw-r--r--src/shared/dbus-common.h246
-rw-r--r--src/shared/dbus-loop.c249
-rw-r--r--src/shared/dbus-loop.h27
-rw-r--r--src/shared/def.h35
-rw-r--r--src/shared/dev-setup.c78
-rw-r--r--src/shared/dev-setup.h24
-rw-r--r--src/shared/efivars.c503
-rw-r--r--src/shared/efivars.h47
-rw-r--r--src/shared/env-util.c415
-rw-r--r--src/shared/env-util.h44
-rw-r--r--src/shared/exit-status.c192
-rw-r--r--src/shared/exit-status.h88
-rw-r--r--src/shared/fdset.c236
-rw-r--r--src/shared/fdset.h49
-rw-r--r--src/shared/fileio-label.c55
-rw-r--r--src/shared/fileio-label.h29
-rw-r--r--src/shared/fileio.c596
-rw-r--r--src/shared/fileio.h37
-rw-r--r--src/shared/hashmap.c862
-rw-r--r--src/shared/hashmap.h105
-rw-r--r--src/shared/hwclock.c160
-rw-r--r--src/shared/hwclock.h31
-rw-r--r--src/shared/install-printf.c132
-rw-r--r--src/shared/install-printf.h25
-rw-r--r--src/shared/install.c1945
-rw-r--r--src/shared/install.h97
-rw-r--r--src/shared/ioprio.h57
-rw-r--r--src/shared/label.c386
-rw-r--r--src/shared/label.h51
-rw-r--r--src/shared/linux/auto_dev-ioctl.h229
-rw-r--r--src/shared/linux/fanotify.h98
-rw-r--r--src/shared/linux/seccomp-bpf.h76
-rw-r--r--src/shared/linux/seccomp.h47
-rw-r--r--src/shared/list.h125
-rw-r--r--src/shared/log.c927
-rw-r--r--src/shared/log.h159
-rw-r--r--src/shared/logs-show.c985
-rw-r--r--src/shared/logs-show.h67
-rw-r--r--src/shared/macro.h285
-rw-r--r--src/shared/missing.h267
-rw-r--r--src/shared/mkdir.c147
-rw-r--r--src/shared/mkdir.h32
-rw-r--r--src/shared/output-mode.h44
-rw-r--r--src/shared/pager.c146
-rw-r--r--src/shared/pager.h30
-rw-r--r--src/shared/path-lookup.c426
-rw-r--r--src/shared/path-lookup.h45
-rw-r--r--src/shared/path-util.c428
-rw-r--r--src/shared/path-util.h45
-rw-r--r--src/shared/polkit.c174
-rw-r--r--src/shared/polkit.h33
-rw-r--r--src/shared/prioq.c305
-rw-r--r--src/shared/prioq.h40
-rw-r--r--src/shared/ratelimit.c57
-rw-r--r--src/shared/ratelimit.h57
-rw-r--r--src/shared/replace-var.c110
-rw-r--r--src/shared/replace-var.h24
-rw-r--r--src/shared/selinux-util.c42
-rw-r--r--src/shared/selinux-util.h27
-rw-r--r--src/shared/set.c137
-rw-r--r--src/shared/set.h83
-rw-r--r--src/shared/sleep-config.c179
-rw-r--r--src/shared/sleep-config.h26
-rw-r--r--src/shared/socket-label.c143
-rw-r--r--src/shared/socket-util.c635
-rw-r--r--src/shared/socket-util.h103
-rw-r--r--src/shared/sparse-endian.h87
-rw-r--r--src/shared/spawn-ask-password-agent.c67
-rw-r--r--src/shared/spawn-ask-password-agent.h25
-rw-r--r--src/shared/spawn-polkit-agent.c98
-rw-r--r--src/shared/spawn-polkit-agent.h28
-rw-r--r--src/shared/specifier.c147
-rw-r--r--src/shared/specifier.h38
-rw-r--r--src/shared/strbuf.c201
-rw-r--r--src/shared/strbuf.h56
-rw-r--r--src/shared/strv.c587
-rw-r--r--src/shared/strv.h87
-rw-r--r--src/shared/strxcpyx.c104
-rw-r--r--src/shared/strxcpyx.h31
-rw-r--r--src/shared/time-dst.c332
-rw-r--r--src/shared/time-dst.h26
-rw-r--r--src/shared/time-util.c772
-rw-r--r--src/shared/time-util.h85
-rw-r--r--src/shared/unit-name.c549
-rw-r--r--src/shared/unit-name.h97
-rw-r--r--src/shared/utf8.c322
-rw-r--r--src/shared/utf8.h34
-rw-r--r--src/shared/util.c5849
-rw-r--r--src/shared/util.h734
-rw-r--r--src/shared/utmp-wtmp.c410
-rw-r--r--src/shared/utmp-wtmp.h35
-rw-r--r--src/shared/virt.c272
-rw-r--r--src/shared/virt.h35
-rw-r--r--src/shared/watchdog.c169
-rw-r--r--src/shared/watchdog.h28
-rw-r--r--src/shutdownd/shutdownd.c471
-rw-r--r--src/sleep/sleep.c222
-rw-r--r--src/stdio-bridge/stdio-bridge.c231
-rw-r--r--src/sysctl/sysctl.c325
-rw-r--r--src/system-update-generator/system-update-generator.c81
-rw-r--r--src/systemctl/systemctl.c6063
-rw-r--r--src/systemd/sd-bus-protocol.h153
-rw-r--r--src/systemd/sd-bus.h210
-rw-r--r--src/systemd/sd-daemon.h282
-rw-r--r--src/systemd/sd-id128.h109
-rw-r--r--src/systemd/sd-journal.h170
-rw-r--r--src/systemd/sd-login.h183
-rw-r--r--src/systemd/sd-messages.h84
-rw-r--r--src/systemd/sd-readahead.h73
-rw-r--r--src/systemd/sd-shutdown.h108
-rw-r--r--src/test/test-calendarspec.c88
-rw-r--r--src/test/test-cgroup-util.c183
-rw-r--r--src/test/test-cgroup.c105
-rw-r--r--src/test/test-daemon.c37
-rw-r--r--src/test/test-date.c61
-rw-r--r--src/test/test-efivars.c47
-rw-r--r--src/test/test-engine.c99
-rw-r--r--src/test/test-env-replace.c218
-rw-r--r--src/test/test-fileio.c145
-rw-r--r--src/test/test-hashmap.c508
-rw-r--r--src/test/test-hostname.c38
-rw-r--r--src/test/test-id128.c75
-rw-r--r--src/test/test-install.c265
-rw-r--r--src/test/test-job-type.c105
-rw-r--r--src/test/test-libudev.c520
-rw-r--r--src/test/test-log.c53
-rw-r--r--src/test/test-loopback.c37
-rw-r--r--src/test/test-ns.c73
-rw-r--r--src/test/test-path-util.c89
-rw-r--r--src/test/test-prioq.c166
-rw-r--r--src/test/test-replace-var.c46
-rw-r--r--src/test/test-sched-prio.c92
-rw-r--r--src/test/test-sleep.c57
-rw-r--r--src/test/test-strbuf.c93
-rw-r--r--src/test/test-strip-tab-ansi.c52
-rw-r--r--src/test/test-strv.c265
-rw-r--r--src/test/test-strxcpyx.c101
-rw-r--r--src/test/test-time.c136
-rw-r--r--src/test/test-udev.c171
-rw-r--r--src/test/test-unit-file.c367
-rw-r--r--src/test/test-unit-name.c199
-rw-r--r--src/test/test-util.c472
-rw-r--r--src/test/test-watchdog.c51
-rw-r--r--src/timedate/org.freedesktop.timedate1.conf27
-rw-r--r--src/timedate/org.freedesktop.timedate1.policy.in62
-rw-r--r--src/timedate/org.freedesktop.timedate1.service12
-rw-r--r--src/timedate/timedatectl.c715
-rw-r--r--src/timedate/timedated.c1026
-rw-r--r--src/timestamp/timestamp.c39
-rw-r--r--src/tmpfiles/tmpfiles.c1425
-rw-r--r--src/tty-ask-password-agent/tty-ask-password-agent.c759
-rw-r--r--src/udev/accelerometer/accelerometer.c342
-rw-r--r--src/udev/ata_id/ata_id.c690
-rw-r--r--src/udev/cdrom_id/cdrom_id.c1097
-rw-r--r--src/udev/collect/collect.c492
-rw-r--r--src/udev/keymap/95-keyboard-force-release.rules57
-rw-r--r--src/udev/keymap/95-keymap.rules183
-rw-r--r--src/udev/keymap/README.keymap.txt97
-rwxr-xr-xsrc/udev/keymap/check-keymaps.sh38
-rwxr-xr-xsrc/udev/keymap/findkeyboards68
-rwxr-xr-xsrc/udev/keymap/keyboard-force-release.sh22
-rwxr-xr-xsrc/udev/keymap/keyboard-force-release.sh.in22
-rw-r--r--src/udev/keymap/keymap.c453
-rw-r--r--src/udev/mtd_probe/mtd_probe.c54
-rw-r--r--src/udev/mtd_probe/mtd_probe.h49
-rw-r--r--src/udev/mtd_probe/probe_smartmedia.c96
-rw-r--r--src/udev/scsi_id/README4
-rw-r--r--src/udev/scsi_id/scsi.h97
-rw-r--r--src/udev/scsi_id/scsi_id.c634
-rw-r--r--src/udev/scsi_id/scsi_id.h73
-rw-r--r--src/udev/scsi_id/scsi_serial.c968
-rw-r--r--src/udev/udev-builtin-blkid.c220
-rw-r--r--src/udev/udev-builtin-btrfs.c65
-rw-r--r--src/udev/udev-builtin-firmware.c157
-rw-r--r--src/udev/udev-builtin-hwdb.c162
-rw-r--r--src/udev/udev-builtin-input_id.c219
-rw-r--r--src/udev/udev-builtin-kmod.c134
-rw-r--r--src/udev/udev-builtin-net_id.c505
-rw-r--r--src/udev/udev-builtin-path_id.c593
-rw-r--r--src/udev/udev-builtin-uaccess.c98
-rw-r--r--src/udev/udev-builtin-usb_id.c482
-rw-r--r--src/udev/udev-builtin.c150
-rw-r--r--src/udev/udev-ctrl.c492
-rw-r--r--src/udev/udev-event.c914
-rw-r--r--src/udev/udev-node.c333
-rw-r--r--src/udev/udev-rules.c2577
-rw-r--r--src/udev/udev-watch.c161
-rw-r--r--src/udev/udev.conf3
-rw-r--r--src/udev/udev.h214
-rw-r--r--src/udev/udev.pc.in5
-rw-r--r--src/udev/udevadm-control.c175
-rw-r--r--src/udev/udevadm-hwdb.c609
-rw-r--r--src/udev/udevadm-info.c544
-rw-r--r--src/udev/udevadm-monitor.c297
-rw-r--r--src/udev/udevadm-settle.c232
-rw-r--r--src/udev/udevadm-test-builtin.c127
-rw-r--r--src/udev/udevadm-test.c172
-rw-r--r--src/udev/udevadm-trigger.c228
-rw-r--r--src/udev/udevadm.c152
-rw-r--r--src/udev/udevd.c1479
-rw-r--r--src/udev/v4l_id/v4l_id.c87
-rw-r--r--src/update-utmp/update-utmp.c385
-rw-r--r--src/vconsole/vconsole-setup.c308
598 files changed, 195918 insertions, 0 deletions
diff --git a/src/ac-power/ac-power.c b/src/ac-power/ac-power.c
new file mode 100644
index 0000000000..bd1b6ecc72
--- /dev/null
+++ b/src/ac-power/ac-power.c
@@ -0,0 +1,37 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "util.h"
+
+int main(int argc, char *argv[]) {
+ int r;
+
+ /* This is mostly intended to be used for scripts which want
+ * to detect whether AC power is plugged in or not. */
+
+ r = on_ac_power();
+ if (r < 0) {
+ log_error("Failed to read AC status: %s", strerror(-r));
+ return EXIT_FAILURE;
+ }
+
+ return r != 0 ? EXIT_SUCCESS : EXIT_FAILURE;
+}
diff --git a/src/activate/activate.c b/src/activate/activate.c
new file mode 100644
index 0000000000..87526d47cc
--- /dev/null
+++ b/src/activate/activate.c
@@ -0,0 +1,443 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Zbigniew Jędrzejewski-Szmek
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/epoll.h>
+#include <sys/prctl.h>
+#include <sys/socket.h>
+#include <sys/wait.h>
+#include <getopt.h>
+
+#include <systemd/sd-daemon.h>
+
+#include "socket-util.h"
+#include "build.h"
+#include "log.h"
+#include "strv.h"
+#include "macro.h"
+
+static char** arg_listen = NULL;
+static bool arg_accept = false;
+static char** arg_args = NULL;
+static char** arg_environ = NULL;
+
+static int add_epoll(int epoll_fd, int fd) {
+ int r;
+ struct epoll_event ev = {EPOLLIN};
+ ev.data.fd = fd;
+
+ assert(epoll_fd >= 0);
+ assert(fd >= 0);
+
+ r = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev);
+ if (r < 0)
+ log_error("Failed to add event on epoll fd:%d for fd:%d: %s",
+ epoll_fd, fd, strerror(-r));
+ return r;
+}
+
+static int set_nocloexec(int fd) {
+ int flags;
+
+ flags = fcntl(fd, F_GETFD);
+ if (flags < 0) {
+ log_error("Querying flags for fd:%d: %m", fd);
+ return -errno;
+ }
+
+ if (!(flags & FD_CLOEXEC))
+ return 0;
+
+ if (fcntl(fd, F_SETFD, flags & ~FD_CLOEXEC) < 0) {
+ log_error("Settings flags for fd:%d: %m", fd);
+ return -errno;
+ }
+
+ return 0;
+}
+
+static int print_socket(const char* desc, int fd) {
+ int r;
+ SocketAddress addr = {
+ .size = sizeof(union sockaddr_union),
+ .type = SOCK_STREAM,
+ };
+ int family;
+
+ r = getsockname(fd, &addr.sockaddr.sa, &addr.size);
+ if (r < 0) {
+ log_warning("Failed to query socket on fd:%d: %m", fd);
+ return 0;
+ }
+
+ family = socket_address_family(&addr);
+ switch(family) {
+ case AF_INET:
+ case AF_INET6: {
+ char* _cleanup_free_ a = NULL;
+ r = socket_address_print(&addr, &a);
+ if (r < 0)
+ log_warning("socket_address_print(): %s", strerror(-r));
+ else
+ log_info("%s %s address %s",
+ desc,
+ family == AF_INET ? "IP" : "IPv6",
+ a);
+ break;
+ }
+ default:
+ log_warning("Connection with unknown family %d", family);
+ }
+
+ return 0;
+}
+
+static int open_sockets(int *epoll_fd, bool accept) {
+ int n, fd;
+ int count = 0;
+ char **address;
+
+ n = sd_listen_fds(true);
+ if (n < 0) {
+ log_error("Failed to read listening file descriptors from environment: %s",
+ strerror(-n));
+ return n;
+ }
+ log_info("Received %d descriptors", n);
+
+ for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
+ log_debug("Received descriptor fd:%d", fd);
+ print_socket("Listening on", fd);
+
+ if (!arg_accept) {
+ int r = set_nocloexec(fd);
+ if (r < 0)
+ return r;
+ }
+
+ count ++;
+ }
+
+ /** Note: we leak some fd's on error here. I doesn't matter
+ * much, since the program will exit immediately anyway, but
+ * would be a pain to fix.
+ */
+
+ STRV_FOREACH(address, arg_listen) {
+ log_info("Opening address %s", *address);
+
+ fd = make_socket_fd(*address, SOCK_STREAM | (arg_accept*SOCK_CLOEXEC));
+ if (fd < 0) {
+ log_error("Failed to open '%s': %s", *address, strerror(-fd));
+ return fd;
+ }
+
+ count ++;
+ }
+
+ *epoll_fd = epoll_create1(EPOLL_CLOEXEC);
+ if (*epoll_fd < 0) {
+ log_error("Failed to create epoll object: %m");
+ return -errno;
+ }
+
+ for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + count; fd++) {
+ int r = add_epoll(*epoll_fd, fd);
+ if (r < 0)
+ return r;
+ }
+
+ return count;
+}
+
+static int launch(char* name, char **argv, char **env, int fds) {
+ unsigned n_env = 0, length;
+ _cleanup_strv_free_ char **envp = NULL;
+ char **s;
+ static const char* tocopy[] = {"TERM=", "PATH=", "USER=", "HOME="};
+ _cleanup_free_ char *tmp = NULL;
+ unsigned i;
+
+ length = strv_length(arg_environ);
+ /* PATH, TERM, HOME, USER, LISTEN_FDS, LISTEN_PID, NULL */
+ envp = new(char *, length + 7);
+
+ STRV_FOREACH(s, arg_environ) {
+ if (strchr(*s, '='))
+ envp[n_env++] = *s;
+ else {
+ _cleanup_free_ char *p = strappend(*s, "=");
+ if (!p)
+ return log_oom();
+ envp[n_env] = strv_find_prefix(env, p);
+ if (envp[n_env])
+ n_env ++;
+ }
+ }
+
+ for (i = 0; i < ELEMENTSOF(tocopy); i++) {
+ envp[n_env] = strv_find_prefix(env, tocopy[i]);
+ if (envp[n_env])
+ n_env ++;
+ }
+
+ if ((asprintf((char**)(envp + n_env++), "LISTEN_FDS=%d", fds) < 0) ||
+ (asprintf((char**)(envp + n_env++), "LISTEN_PID=%d", getpid()) < 0))
+ return log_oom();
+
+ tmp = strv_join(argv, " ");
+ if (!tmp)
+ return log_oom();
+
+ log_info("Execing %s (%s)", name, tmp);
+ execvpe(name, argv, envp);
+ log_error("Failed to execp %s (%s): %m", name, tmp);
+ return -errno;
+}
+
+static int launch1(const char* child, char** argv, char **env, int fd) {
+ pid_t parent_pid, child_pid;
+ int r;
+
+ _cleanup_free_ char *tmp = NULL;
+ tmp = strv_join(argv, " ");
+ if (!tmp)
+ return log_oom();
+
+ parent_pid = getpid();
+
+ child_pid = fork();
+ if (child_pid < 0) {
+ log_error("Failed to fork: %m");
+ return -errno;
+ }
+
+ /* In the child */
+ if (child_pid == 0) {
+ r = dup2(fd, STDIN_FILENO);
+ if (r < 0) {
+ log_error("Failed to dup connection to stdin: %m");
+ _exit(EXIT_FAILURE);
+ }
+
+ r = dup2(fd, STDOUT_FILENO);
+ if (r < 0) {
+ log_error("Failed to dup connection to stdout: %m");
+ _exit(EXIT_FAILURE);
+ }
+
+ r = close(fd);
+ if (r < 0) {
+ log_error("Failed to close dupped connection: %m");
+ _exit(EXIT_FAILURE);
+ }
+
+ /* Make sure the child goes away when the parent dies */
+ if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
+ _exit(EXIT_FAILURE);
+
+ /* Check whether our parent died before we were able
+ * to set the death signal */
+ if (getppid() != parent_pid)
+ _exit(EXIT_SUCCESS);
+
+ execvp(child, argv);
+ log_error("Failed to exec child %s: %m", child);
+ _exit(EXIT_FAILURE);
+ }
+
+ log_info("Spawned %s (%s) as PID %d", child, tmp, child_pid);
+
+ return 0;
+}
+
+static int do_accept(const char* name, char **argv, char **envp, int fd) {
+ SocketAddress addr = {
+ .size = sizeof(union sockaddr_union),
+ .type = SOCK_STREAM,
+ };
+ int fd2, r;
+
+ fd2 = accept(fd, &addr.sockaddr.sa, &addr.size);
+ if (fd2 < 0) {
+ log_error("Failed to accept connection on fd:%d: %m", fd);
+ return fd2;
+ }
+
+ print_socket("Connection from", fd2);
+
+ r = launch1(name, argv, envp, fd2);
+ return r;
+}
+
+/* SIGCHLD handler. */
+static void sigchld_hdl(int sig, siginfo_t *t, void *data)
+{
+ log_info("Child %d died with code %d", t->si_pid, t->si_status);
+ /* Wait for a dead child. */
+ waitpid(t->si_pid, NULL, 0);
+}
+
+static int install_chld_handler(void) {
+ int r;
+ struct sigaction act;
+ zero(act);
+ act.sa_flags = SA_SIGINFO;
+ act.sa_sigaction = sigchld_hdl;
+
+ r = sigaction(SIGCHLD, &act, 0);
+ if (r < 0)
+ log_error("Failed to install SIGCHLD handler: %m");
+ return r;
+}
+
+static int help(void) {
+ printf("%s [OPTIONS...]\n\n"
+ "Listen on sockets and launch child on connection.\n\n"
+ "Options:\n"
+ " -l --listen=ADDR Listen for raw connections at ADDR\n"
+ " -a --accept Spawn separate child for each connection\n"
+ " -h --help Show this help and exit\n"
+ " --version Print version string and exit\n"
+ "\n"
+ "Note: file descriptors from sd_listen_fds() will be passed through.\n"
+ , program_invocation_short_name
+ );
+
+ return 0;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+ enum {
+ ARG_VERSION = 0x100,
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "version", no_argument, NULL, ARG_VERSION },
+ { "listen", required_argument, NULL, 'l' },
+ { "accept", no_argument, NULL, 'a' },
+ { "environment", required_argument, NULL, 'E' },
+ { NULL, 0, NULL, 0 }
+ };
+
+ int c;
+
+ assert(argc >= 0);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "+hl:saE:", options, NULL)) >= 0)
+ switch(c) {
+ case 'h':
+ help();
+ return 0 /* done */;
+
+ case ARG_VERSION:
+ puts(PACKAGE_STRING);
+ puts(SYSTEMD_FEATURES);
+ return 0 /* done */;
+
+ case 'l': {
+ int r = strv_extend(&arg_listen, optarg);
+ if (r < 0)
+ return r;
+
+ break;
+ }
+
+ case 'a':
+ arg_accept = true;
+ break;
+
+ case 'E': {
+ int r = strv_extend(&arg_environ, optarg);
+ if (r < 0)
+ return r;
+
+ break;
+ }
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ log_error("Unknown option code %c", c);
+ return -EINVAL;
+ }
+
+ if (optind == argc) {
+ log_error("Usage: %s [OPTION...] PROGRAM [OPTION...]",
+ program_invocation_short_name);
+ return -EINVAL;
+ }
+
+ arg_args = argv + optind;
+
+ return 1 /* work to do */;
+}
+
+int main(int argc, char **argv, char **envp) {
+ int r, n;
+ int epoll_fd = -1;
+
+ log_set_max_level(LOG_DEBUG);
+ log_show_color(true);
+ log_parse_environment();
+
+ r = parse_argv(argc, argv);
+ if (r <= 0)
+ return r == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
+
+ r = install_chld_handler();
+ if (r < 0)
+ return EXIT_FAILURE;
+
+ n = open_sockets(&epoll_fd, arg_accept);
+ if (n < 0)
+ return EXIT_FAILURE;
+
+ while (true) {
+ struct epoll_event event;
+
+ r = epoll_wait(epoll_fd, &event, 1, -1);
+ if (r < 0) {
+ if (errno == EINTR)
+ continue;
+
+ log_error("epoll_wait() failed: %m");
+ return EXIT_FAILURE;
+ }
+
+ log_info("Communication attempt on fd:%d", event.data.fd);
+ if (arg_accept) {
+ r = do_accept(argv[optind], argv + optind, envp,
+ event.data.fd);
+ if (r < 0)
+ return EXIT_FAILURE;
+ } else
+ break;
+ }
+
+ launch(argv[optind], argv + optind, envp, n);
+
+ return EXIT_SUCCESS;
+}
diff --git a/src/analyze/systemd-analyze.c b/src/analyze/systemd-analyze.c
new file mode 100644
index 0000000000..bb86ec7da8
--- /dev/null
+++ b/src/analyze/systemd-analyze.c
@@ -0,0 +1,1270 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010-2013 Lennart Poettering
+ Copyright 2013 Simon Peeters
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <getopt.h>
+#include <locale.h>
+#include <sys/utsname.h>
+#include <fnmatch.h>
+
+#include "install.h"
+#include "log.h"
+#include "dbus-common.h"
+#include "build.h"
+#include "util.h"
+#include "strxcpyx.h"
+#include "fileio.h"
+#include "strv.h"
+#include "unit-name.h"
+#include "special.h"
+#include "hashmap.h"
+
+#define SCALE_X (0.1 / 1000.0) /* pixels per us */
+#define SCALE_Y 20.0
+
+#define compare(a, b) (((a) > (b))? 1 : (((b) > (a))? -1 : 0))
+
+#define svg(...) printf(__VA_ARGS__)
+
+#define svg_bar(class, x1, x2, y) \
+ svg(" <rect class=\"%s\" x=\"%.03f\" y=\"%.03f\" width=\"%.03f\" height=\"%.03f\" />\n", \
+ (class), \
+ SCALE_X * (x1), SCALE_Y * (y), \
+ SCALE_X * ((x2) - (x1)), SCALE_Y - 1.0)
+
+#define svg_text(b, x, y, format, ...) \
+ do { \
+ svg(" <text class=\"%s\" x=\"%.03f\" y=\"%.03f\">", (b) ? "left" : "right", SCALE_X * (x) + (b ? 5.0 : -5.0), SCALE_Y * (y) + 14.0); \
+ svg(format, ## __VA_ARGS__); \
+ svg("</text>\n"); \
+ } while(false)
+
+static UnitFileScope arg_scope = UNIT_FILE_SYSTEM;
+static enum dot {
+ DEP_ALL,
+ DEP_ORDER,
+ DEP_REQUIRE
+} arg_dot = DEP_ALL;
+static char** arg_dot_from_patterns = NULL;
+static char** arg_dot_to_patterns = NULL;
+
+usec_t arg_fuzz = 0;
+
+struct boot_times {
+ usec_t firmware_time;
+ usec_t loader_time;
+ usec_t kernel_time;
+ usec_t kernel_done_time;
+ usec_t initrd_time;
+ usec_t userspace_time;
+ usec_t finish_time;
+};
+struct unit_times {
+ char *name;
+ usec_t ixt;
+ usec_t iet;
+ usec_t axt;
+ usec_t aet;
+ usec_t time;
+};
+
+static int bus_get_uint64_property(DBusConnection *bus, const char *path, const char *interface, const char *property, uint64_t *val) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ DBusMessageIter iter, sub;
+ int r;
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.systemd1",
+ path,
+ "org.freedesktop.DBus.Properties",
+ "Get",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &interface,
+ DBUS_TYPE_STRING, &property,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+
+ if (!dbus_message_iter_init(reply, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_recurse(&iter, &sub);
+
+ if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT64) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_get_basic(&sub, val);
+
+ return 0;
+}
+
+static int compare_unit_time(const void *a, const void *b) {
+ return compare(((struct unit_times *)b)->time,
+ ((struct unit_times *)a)->time);
+}
+
+static int compare_unit_start(const void *a, const void *b) {
+ return compare(((struct unit_times *)a)->ixt,
+ ((struct unit_times *)b)->ixt);
+}
+
+static int get_os_name(char **_n) {
+ char *n = NULL;
+ int r;
+
+ r = parse_env_file("/etc/os-release", NEWLINE, "PRETTY_NAME", &n, NULL);
+ if (r < 0)
+ return r;
+
+ if (!n)
+ return -ENOENT;
+
+ *_n = n;
+ return 0;
+}
+
+static void free_unit_times(struct unit_times *t, unsigned n) {
+ struct unit_times *p;
+
+ for (p = t; p < t + n; p++)
+ free(p->name);
+
+ free(t);
+}
+
+static int acquire_time_data(DBusConnection *bus, struct unit_times **out) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ DBusMessageIter iter, sub;
+ int r, c = 0, n_units = 0;
+ struct unit_times *unit_times = NULL;
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "ListUnits",
+ &reply,
+ NULL,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ goto fail;
+
+ if (!dbus_message_iter_init(reply, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
+ dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
+ log_error("Failed to parse reply.");
+ r = -EIO;
+ goto fail;
+ }
+
+ for (dbus_message_iter_recurse(&iter, &sub);
+ dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID;
+ dbus_message_iter_next(&sub)) {
+ struct unit_info u;
+ struct unit_times *t;
+
+ if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
+ log_error("Failed to parse reply.");
+ r = -EIO;
+ goto fail;
+ }
+
+ if (c >= n_units) {
+ struct unit_times *w;
+
+ n_units = MAX(2*c, 16);
+ w = realloc(unit_times, sizeof(struct unit_times) * n_units);
+
+ if (!w) {
+ r = log_oom();
+ goto fail;
+ }
+
+ unit_times = w;
+ }
+ t = unit_times+c;
+ t->name = NULL;
+
+ r = bus_parse_unit_info(&sub, &u);
+ if (r < 0)
+ goto fail;
+
+ assert_cc(sizeof(usec_t) == sizeof(uint64_t));
+
+ if (bus_get_uint64_property(bus, u.unit_path,
+ "org.freedesktop.systemd1.Unit",
+ "InactiveExitTimestampMonotonic",
+ &t->ixt) < 0 ||
+ bus_get_uint64_property(bus, u.unit_path,
+ "org.freedesktop.systemd1.Unit",
+ "ActiveEnterTimestampMonotonic",
+ &t->aet) < 0 ||
+ bus_get_uint64_property(bus, u.unit_path,
+ "org.freedesktop.systemd1.Unit",
+ "ActiveExitTimestampMonotonic",
+ &t->axt) < 0 ||
+ bus_get_uint64_property(bus, u.unit_path,
+ "org.freedesktop.systemd1.Unit",
+ "InactiveEnterTimestampMonotonic",
+ &t->iet) < 0) {
+ r = -EIO;
+ goto fail;
+ }
+
+ if (t->aet >= t->ixt)
+ t->time = t->aet - t->ixt;
+ else if (t->iet >= t->ixt)
+ t->time = t->iet - t->ixt;
+ else
+ t->time = 0;
+
+ if (t->ixt == 0)
+ continue;
+
+ t->name = strdup(u.id);
+ if (t->name == NULL) {
+ r = log_oom();
+ goto fail;
+ }
+ c++;
+ }
+
+ *out = unit_times;
+ return c;
+
+fail:
+ free_unit_times(unit_times, (unsigned) c);
+ return r;
+}
+
+static int acquire_boot_times(DBusConnection *bus, struct boot_times **bt) {
+ static struct boot_times times;
+ static bool cached = false;
+
+ if (cached)
+ goto finish;
+
+ assert_cc(sizeof(usec_t) == sizeof(uint64_t));
+
+ if (bus_get_uint64_property(bus,
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "FirmwareTimestampMonotonic",
+ &times.firmware_time) < 0 ||
+ bus_get_uint64_property(bus,
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "LoaderTimestampMonotonic",
+ &times.loader_time) < 0 ||
+ bus_get_uint64_property(bus,
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "KernelTimestamp",
+ &times.kernel_time) < 0 ||
+ bus_get_uint64_property(bus,
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "InitRDTimestampMonotonic",
+ &times.initrd_time) < 0 ||
+ bus_get_uint64_property(bus,
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "UserspaceTimestampMonotonic",
+ &times.userspace_time) < 0 ||
+ bus_get_uint64_property(bus,
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "FinishTimestampMonotonic",
+ &times.finish_time) < 0)
+ return -EIO;
+
+ if (times.finish_time <= 0) {
+ log_error("Bootup is not yet finished. Please try again later.");
+ return -EAGAIN;
+ }
+
+ if (times.initrd_time)
+ times.kernel_done_time = times.initrd_time;
+ else
+ times.kernel_done_time = times.userspace_time;
+
+ cached = true;
+
+finish:
+ *bt = &times;
+ return 0;
+}
+
+static int pretty_boot_time(DBusConnection *bus, char **_buf) {
+ char ts[FORMAT_TIMESPAN_MAX];
+ struct boot_times *t;
+ static char buf[4096];
+ size_t size;
+ char *ptr;
+ int r;
+
+ r = acquire_boot_times(bus, &t);
+ if (r < 0)
+ return r;
+
+ ptr = buf;
+ size = sizeof(buf);
+
+ size = strpcpyf(&ptr, size, "Startup finished in ");
+ if (t->firmware_time)
+ size = strpcpyf(&ptr, size, "%s (firmware) + ", format_timespan(ts, sizeof(ts), t->firmware_time - t->loader_time, USEC_PER_MSEC));
+ if (t->loader_time)
+ size = strpcpyf(&ptr, size, "%s (loader) + ", format_timespan(ts, sizeof(ts), t->loader_time, USEC_PER_MSEC));
+ if (t->kernel_time)
+ size = strpcpyf(&ptr, size, "%s (kernel) + ", format_timespan(ts, sizeof(ts), t->kernel_done_time, USEC_PER_MSEC));
+ if (t->initrd_time > 0)
+ size = strpcpyf(&ptr, size, "%s (initrd) + ", format_timespan(ts, sizeof(ts), t->userspace_time - t->initrd_time, USEC_PER_MSEC));
+
+ size = strpcpyf(&ptr, size, "%s (userspace) ", format_timespan(ts, sizeof(ts), t->finish_time - t->userspace_time, USEC_PER_MSEC));
+ if (t->kernel_time > 0)
+ size = strpcpyf(&ptr, size, "= %s", format_timespan(ts, sizeof(ts), t->firmware_time + t->finish_time, USEC_PER_MSEC));
+ else
+ size = strpcpyf(&ptr, size, "= %s", format_timespan(ts, sizeof(ts), t->finish_time - t->userspace_time, USEC_PER_MSEC));
+
+ ptr = strdup(buf);
+ if (!ptr)
+ return log_oom();
+
+ *_buf = ptr;
+ return 0;
+}
+
+static void svg_graph_box(double height, double begin, double end) {
+ long long i;
+
+ /* outside box, fill */
+ svg("<rect class=\"box\" x=\"0\" y=\"0\" width=\"%.03f\" height=\"%.03f\" />\n",
+ SCALE_X * (end - begin), SCALE_Y * height);
+
+ for (i = ((long long) (begin / 100000)) * 100000; i <= end; i+=100000) {
+ /* lines for each second */
+ if (i % 5000000 == 0)
+ svg(" <line class=\"sec5\" x1=\"%.03f\" y1=\"0\" x2=\"%.03f\" y2=\"%.03f\" />\n"
+ " <text class=\"sec\" x=\"%.03f\" y=\"%.03f\" >%.01fs</text>\n",
+ SCALE_X * i, SCALE_X * i, SCALE_Y * height, SCALE_X * i, -5.0, 0.000001 * i);
+ else if (i % 1000000 == 0)
+ svg(" <line class=\"sec1\" x1=\"%.03f\" y1=\"0\" x2=\"%.03f\" y2=\"%.03f\" />\n"
+ " <text class=\"sec\" x=\"%.03f\" y=\"%.03f\" >%.01fs</text>\n",
+ SCALE_X * i, SCALE_X * i, SCALE_Y * height, SCALE_X * i, -5.0, 0.000001 * i);
+ else
+ svg(" <line class=\"sec01\" x1=\"%.03f\" y1=\"0\" x2=\"%.03f\" y2=\"%.03f\" />\n",
+ SCALE_X * i, SCALE_X * i, SCALE_Y * height);
+ }
+}
+
+static int analyze_plot(DBusConnection *bus) {
+ struct unit_times *times;
+ struct boot_times *boot;
+ struct utsname name;
+ int n, m = 1, y=0;
+ double width;
+ _cleanup_free_ char *pretty_times = NULL, *osname = NULL;
+ struct unit_times *u;
+
+ n = acquire_boot_times(bus, &boot);
+ if (n < 0)
+ return n;
+
+ n = pretty_boot_time(bus, &pretty_times);
+ if (n < 0)
+ return n;
+
+ get_os_name(&osname);
+ assert_se(uname(&name) >= 0);
+
+ n = acquire_time_data(bus, &times);
+ if (n <= 0)
+ return n;
+
+ qsort(times, n, sizeof(struct unit_times), compare_unit_start);
+
+ width = SCALE_X * (boot->firmware_time + boot->finish_time);
+ if (width < 800.0)
+ width = 800.0;
+
+ if (boot->firmware_time > boot->loader_time)
+ m++;
+ if (boot->loader_time) {
+ m++;
+ if (width < 1000.0)
+ width = 1000.0;
+ }
+ if (boot->initrd_time)
+ m++;
+ if (boot->kernel_time)
+ m++;
+
+ for (u = times; u < times + n; u++) {
+ double len;
+
+ if (u->ixt < boot->userspace_time ||
+ u->ixt > boot->finish_time) {
+ free(u->name);
+ u->name = NULL;
+ continue;
+ }
+ len = ((boot->firmware_time + u->ixt) * SCALE_X)
+ + (10.0 * strlen(u->name));
+ if (len > width)
+ width = len;
+
+ if (u->iet > u->ixt && u->iet <= boot->finish_time
+ && u->aet == 0 && u->axt == 0)
+ u->aet = u->axt = u->iet;
+ if (u->aet < u->ixt || u->aet > boot->finish_time)
+ u->aet = boot->finish_time;
+ if (u->axt < u->aet || u->aet > boot->finish_time)
+ u->axt = boot->finish_time;
+ if (u->iet < u->axt || u->iet > boot->finish_time)
+ u->iet = boot->finish_time;
+ m++;
+ }
+
+ svg("<?xml version=\"1.0\" standalone=\"no\"?>\n"
+ "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" "
+ "\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n");
+
+ svg("<svg width=\"%.0fpx\" height=\"%.0fpx\" version=\"1.1\" "
+ "xmlns=\"http://www.w3.org/2000/svg\">\n\n",
+ 80.0 + width, 150.0 + (m * SCALE_Y));
+
+ /* write some basic info as a comment, including some help */
+ svg("<!-- This file is a systemd-analyze SVG file. It is best rendered in a -->\n"
+ "<!-- browser such as Chrome, Chromium or Firefox. Other applications -->\n"
+ "<!-- that render these files properly but much slower are ImageMagick, -->\n"
+ "<!-- gimp, inkscape, etc. To display the files on your system, just -->\n"
+ "<!-- point your browser to this file. -->\n\n"
+ "<!-- This plot was generated by systemd-analyze version %-16.16s -->\n\n", VERSION);
+
+ /* style sheet */
+ svg("<defs>\n <style type=\"text/css\">\n <![CDATA[\n"
+ " rect { stroke-width: 1; stroke-opacity: 0; }\n"
+ " rect.activating { fill: rgb(255,0,0); fill-opacity: 0.7; }\n"
+ " rect.active { fill: rgb(200,150,150); fill-opacity: 0.7; }\n"
+ " rect.deactivating { fill: rgb(150,100,100); fill-opacity: 0.7; }\n"
+ " rect.kernel { fill: rgb(150,150,150); fill-opacity: 0.7; }\n"
+ " rect.initrd { fill: rgb(150,150,150); fill-opacity: 0.7; }\n"
+ " rect.firmware { fill: rgb(150,150,150); fill-opacity: 0.7; }\n"
+ " rect.loader { fill: rgb(150,150,150); fill-opacity: 0.7; }\n"
+ " rect.userspace { fill: rgb(150,150,150); fill-opacity: 0.7; }\n"
+ " rect.box { fill: rgb(240,240,240); stroke: rgb(192,192,192); }\n"
+ " line { stroke: rgb(64,64,64); stroke-width: 1; }\n"
+ "// line.sec1 { }\n"
+ " line.sec5 { stroke-width: 2; }\n"
+ " line.sec01 { stroke: rgb(224,224,224); stroke-width: 1; }\n"
+ " text { font-family: Verdana, Helvetica; font-size: 10; }\n"
+ " text.left { font-family: Verdana, Helvetica; font-size: 10; text-anchor: start; }\n"
+ " text.right { font-family: Verdana, Helvetica; font-size: 10; text-anchor: end; }\n"
+ " text.sec { font-size: 8; }\n"
+ " ]]>\n </style>\n</defs>\n\n");
+
+ svg("<text x=\"20\" y=\"50\">%s</text>", pretty_times);
+ svg("<text x=\"20\" y=\"30\">%s %s (%s %s) %s</text>",
+ isempty(osname) ? "Linux" : osname,
+ name.nodename, name.release, name.version, name.machine);
+ svg("<text x=\"20\" y=\"%.0f\">Legend: Red = Activating; Pink = Active; Dark Pink = Deactivating</text>",
+ 120.0 + (m *SCALE_Y));
+
+ svg("<g transform=\"translate(%.3f,100)\">\n", 20.0 + (SCALE_X * boot->firmware_time));
+ svg_graph_box(m, -boot->firmware_time, boot->finish_time);
+
+ if (boot->firmware_time) {
+ svg_bar("firmware", -(double) boot->firmware_time, -(double) boot->loader_time, y);
+ svg_text(true, -(double) boot->firmware_time, y, "firmware");
+ y++;
+ }
+ if (boot->loader_time) {
+ svg_bar("loader", -(double) boot->loader_time, 0, y);
+ svg_text(true, -(double) boot->loader_time, y, "loader");
+ y++;
+ }
+ if (boot->kernel_time) {
+ svg_bar("kernel", 0, boot->kernel_done_time, y);
+ svg_text(true, 0, y, "kernel");
+ y++;
+ }
+ if (boot->initrd_time) {
+ svg_bar("initrd", boot->initrd_time, boot->userspace_time, y);
+ svg_text(true, boot->initrd_time, y, "initrd");
+ y++;
+ }
+ svg_bar("userspace", boot->userspace_time, boot->finish_time, y);
+ svg_text("left", boot->userspace_time, y, "userspace");
+ y++;
+
+ for (u = times; u < times + n; u++) {
+ char ts[FORMAT_TIMESPAN_MAX];
+ bool b;
+
+ if (!u->name)
+ continue;
+
+ svg_bar("activating", u->ixt, u->aet, y);
+ svg_bar("active", u->aet, u->axt, y);
+ svg_bar("deactivating", u->axt, u->iet, y);
+
+ b = u->ixt * SCALE_X > width * 2 / 3;
+ if (u->time)
+ svg_text(b, u->ixt, y, "%s (%s)",
+ u->name, format_timespan(ts, sizeof(ts), u->time, USEC_PER_MSEC));
+ else
+ svg_text(b, u->ixt, y, "%s", u->name);
+ y++;
+ }
+ svg("</g>\n\n");
+
+ svg("</svg>");
+
+ free_unit_times(times, (unsigned) n);
+
+ return 0;
+}
+
+
+static int list_dependencies_print(const char *name, unsigned int level, unsigned int branches,
+ bool last, struct unit_times *times, struct boot_times *boot) {
+ unsigned int i;
+ char ts[FORMAT_TIMESPAN_MAX], ts2[FORMAT_TIMESPAN_MAX];
+
+ for (i = level; i != 0; i--)
+ printf("%s", draw_special_char(branches & (1 << (i-1)) ? DRAW_TREE_VERT : DRAW_TREE_SPACE));
+
+ printf("%s", draw_special_char(last ? DRAW_TREE_RIGHT : DRAW_TREE_BRANCH));
+
+ if (times) {
+ if (times->time)
+ printf("%s%s @%s +%s%s", ANSI_HIGHLIGHT_RED_ON, name,
+ format_timespan(ts, sizeof(ts), times->ixt - boot->userspace_time, USEC_PER_MSEC),
+ format_timespan(ts2, sizeof(ts2), times->time, USEC_PER_MSEC), ANSI_HIGHLIGHT_OFF);
+ else if (times->aet > boot->userspace_time)
+ printf("%s @%s", name, format_timespan(ts, sizeof(ts), times->aet - boot->userspace_time, USEC_PER_MSEC));
+ else
+ printf("%s", name);
+ } else printf("%s", name);
+ printf("\n");
+
+ return 0;
+}
+
+static int list_dependencies_get_dependencies(DBusConnection *bus, const char *name, char ***deps) {
+ static const char dependencies[] =
+ "After\0";
+
+ _cleanup_free_ char *path;
+ const char *interface = "org.freedesktop.systemd1.Unit";
+
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ DBusMessageIter iter, sub, sub2, sub3;
+
+ int r = 0;
+ char **ret = NULL;
+
+ assert(bus);
+ assert(name);
+ assert(deps);
+
+ path = unit_dbus_path_from_name(name);
+ if (path == NULL) {
+ r = -EINVAL;
+ goto finish;
+ }
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.systemd1",
+ path,
+ "org.freedesktop.DBus.Properties",
+ "GetAll",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &interface,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ goto finish;
+
+ if (!dbus_message_iter_init(reply, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
+ dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
+ log_error("Failed to parse reply.");
+ r = -EIO;
+ goto finish;
+ }
+
+ dbus_message_iter_recurse(&iter, &sub);
+
+ while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ const char *prop;
+
+ assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_DICT_ENTRY);
+ dbus_message_iter_recurse(&sub, &sub2);
+
+ if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
+ log_error("Failed to parse reply.");
+ r = -EIO;
+ goto finish;
+ }
+
+ if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
+ log_error("Failed to parse reply.");
+ r = -EIO;
+ goto finish;
+ }
+
+ dbus_message_iter_recurse(&sub2, &sub3);
+ dbus_message_iter_next(&sub);
+
+ if (!nulstr_contains(dependencies, prop))
+ continue;
+
+ if (dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_ARRAY) {
+ if (dbus_message_iter_get_element_type(&sub3) == DBUS_TYPE_STRING) {
+ DBusMessageIter sub4;
+ dbus_message_iter_recurse(&sub3, &sub4);
+
+ while (dbus_message_iter_get_arg_type(&sub4) != DBUS_TYPE_INVALID) {
+ const char *s;
+
+ assert(dbus_message_iter_get_arg_type(&sub4) == DBUS_TYPE_STRING);
+ dbus_message_iter_get_basic(&sub4, &s);
+
+ r = strv_extend(&ret, s);
+ if (r < 0) {
+ log_oom();
+ goto finish;
+ }
+
+ dbus_message_iter_next(&sub4);
+ }
+ }
+ }
+ }
+finish:
+ if (r < 0)
+ strv_free(ret);
+ else
+ *deps = ret;
+ return r;
+}
+
+static Hashmap *unit_times_hashmap;
+
+static int list_dependencies_compare(const void *_a, const void *_b) {
+ const char **a = (const char**) _a, **b = (const char**) _b;
+ usec_t usa = 0, usb = 0;
+ struct unit_times *times;
+
+ times = hashmap_get(unit_times_hashmap, *a);
+ if (times)
+ usa = times->aet;
+ times = hashmap_get(unit_times_hashmap, *b);
+ if (times)
+ usb = times->aet;
+
+ return usb - usa;
+}
+
+static int list_dependencies_one(DBusConnection *bus, const char *name, unsigned int level, char ***units,
+ unsigned int branches) {
+ _cleanup_strv_free_ char **deps = NULL;
+ char **c;
+ int r = 0;
+ usec_t service_longest = 0;
+ int to_print = 0;
+ struct unit_times *times;
+ struct boot_times *boot;
+
+ if(strv_extend(units, name))
+ return log_oom();
+
+ r = list_dependencies_get_dependencies(bus, name, &deps);
+ if (r < 0)
+ return r;
+
+ qsort(deps, strv_length(deps), sizeof (char*), list_dependencies_compare);
+
+ r = acquire_boot_times(bus, &boot);
+ if (r < 0)
+ return r;
+
+ STRV_FOREACH(c, deps) {
+ times = hashmap_get(unit_times_hashmap, *c);
+ if (times
+ && times->aet
+ && times->aet <= boot->finish_time
+ && (times->aet >= service_longest
+ || service_longest == 0)) {
+ service_longest = times->aet;
+ break;
+ }
+ }
+
+ if (service_longest == 0 )
+ return r;
+
+ STRV_FOREACH(c, deps) {
+ times = hashmap_get(unit_times_hashmap, *c);
+ if (times && times->aet
+ && times->aet <= boot->finish_time
+ && (service_longest - times->aet) <= arg_fuzz) {
+ to_print++;
+ }
+ }
+
+ if(!to_print)
+ return r;
+
+ STRV_FOREACH(c, deps) {
+ times = hashmap_get(unit_times_hashmap, *c);
+ if (!times
+ || !times->aet
+ || times->aet > boot->finish_time
+ || service_longest - times->aet > arg_fuzz)
+ continue;
+
+ to_print--;
+
+ r = list_dependencies_print(*c, level, branches, to_print == 0, times, boot);
+ if (r < 0)
+ return r;
+
+ if (strv_contains(*units, *c)) {
+ r = list_dependencies_print("...", level + 1, (branches << 1) | (to_print ? 1 : 0),
+ true, NULL, boot);
+ continue;
+ }
+
+ r = list_dependencies_one(bus, *c, level + 1, units,
+ (branches << 1) | (to_print ? 1 : 0));
+ if(r < 0)
+ return r;
+
+
+ if(!to_print)
+ break;
+
+ }
+ return 0;
+}
+
+static int list_dependencies(DBusConnection *bus) {
+ _cleanup_strv_free_ char **units = NULL;
+ char ts[FORMAT_TIMESPAN_MAX];
+ struct unit_times *times;
+ int r;
+ const char
+ *path, *id,
+ *interface = "org.freedesktop.systemd1.Unit",
+ *property = "Id";
+ DBusMessageIter iter, sub;
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ struct boot_times *boot;
+
+ assert(bus);
+
+ path = unit_dbus_path_from_name(SPECIAL_DEFAULT_TARGET);
+ if (path == NULL)
+ return -EINVAL;
+
+ r = bus_method_call_with_reply (
+ bus,
+ "org.freedesktop.systemd1",
+ path,
+ "org.freedesktop.DBus.Properties",
+ "Get",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &interface,
+ DBUS_TYPE_STRING, &property,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+
+ if (!dbus_message_iter_init(reply, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_recurse(&iter, &sub);
+
+ if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_get_basic(&sub, &id);
+
+ times = hashmap_get(unit_times_hashmap, id);
+
+ r = acquire_boot_times(bus, &boot);
+ if (r < 0)
+ return r;
+
+ if (times) {
+ if (times->time)
+ printf("%s%s +%s%s\n", ANSI_HIGHLIGHT_RED_ON, id,
+ format_timespan(ts, sizeof(ts), times->time, USEC_PER_MSEC), ANSI_HIGHLIGHT_OFF);
+ else if (times->aet > boot->userspace_time)
+ printf("%s @%s\n", id, format_timespan(ts, sizeof(ts), times->aet - boot->userspace_time, USEC_PER_MSEC));
+ else
+ printf("%s\n", id);
+ }
+
+ return list_dependencies_one(bus, SPECIAL_DEFAULT_TARGET, 0, &units, 0);
+}
+
+static int analyze_critical_chain(DBusConnection *bus) {
+ struct unit_times *times;
+ int n, r;
+ unsigned int i;
+ Hashmap *h;
+
+ n = acquire_time_data(bus, &times);
+ if (n <= 0)
+ return n;
+
+ h = hashmap_new(string_hash_func, string_compare_func);
+ if (!h)
+ return -ENOMEM;
+
+ for (i = 0; i < (unsigned)n; i++) {
+ r = hashmap_put(h, times[i].name, &times[i]);
+ if (r < 0)
+ return r;
+ }
+ unit_times_hashmap = h;
+
+ puts("The time after the unit is active or started is printed after the \"@\" character.\n"
+ "The time the unit takes to start is printed after the \"+\" character.\n");
+
+ list_dependencies(bus);
+
+ hashmap_free(h);
+ free_unit_times(times, (unsigned) n);
+ return 0;
+}
+
+static int analyze_blame(DBusConnection *bus) {
+ struct unit_times *times;
+ unsigned i;
+ int n;
+
+ n = acquire_time_data(bus, &times);
+ if (n <= 0)
+ return n;
+
+ qsort(times, n, sizeof(struct unit_times), compare_unit_time);
+
+ for (i = 0; i < (unsigned) n; i++) {
+ char ts[FORMAT_TIMESPAN_MAX];
+
+ if (times[i].time > 0)
+ printf("%16s %s\n", format_timespan(ts, sizeof(ts), times[i].time, USEC_PER_MSEC), times[i].name);
+ }
+
+ free_unit_times(times, (unsigned) n);
+ return 0;
+}
+
+static int analyze_time(DBusConnection *bus) {
+ _cleanup_free_ char *buf = NULL;
+ int r;
+
+ r = pretty_boot_time(bus, &buf);
+ if (r < 0)
+ return r;
+
+ puts(buf);
+ return 0;
+}
+
+static int graph_one_property(const char *name, const char *prop, DBusMessageIter *iter, char* patterns[]) {
+
+ static const char * const colors[] = {
+ "Requires", "[color=\"black\"]",
+ "RequiresOverridable", "[color=\"black\"]",
+ "Requisite", "[color=\"darkblue\"]",
+ "RequisiteOverridable", "[color=\"darkblue\"]",
+ "Wants", "[color=\"grey66\"]",
+ "Conflicts", "[color=\"red\"]",
+ "ConflictedBy", "[color=\"red\"]",
+ "After", "[color=\"green\"]"
+ };
+
+ const char *c = NULL;
+ unsigned i;
+
+ assert(name);
+ assert(prop);
+ assert(iter);
+
+ for (i = 0; i < ELEMENTSOF(colors); i += 2)
+ if (streq(colors[i], prop)) {
+ c = colors[i+1];
+ break;
+ }
+
+ if (!c)
+ return 0;
+
+ if (arg_dot != DEP_ALL)
+ if ((arg_dot == DEP_ORDER) != streq(prop, "After"))
+ return 0;
+
+ if (dbus_message_iter_get_arg_type(iter) == DBUS_TYPE_ARRAY &&
+ dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
+ DBusMessageIter sub;
+
+ dbus_message_iter_recurse(iter, &sub);
+
+ for (dbus_message_iter_recurse(iter, &sub);
+ dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID;
+ dbus_message_iter_next(&sub)) {
+ const char *s;
+ char **p;
+ bool match_found;
+
+ assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
+ dbus_message_iter_get_basic(&sub, &s);
+
+ if (!strv_isempty(arg_dot_from_patterns)) {
+ match_found = false;
+
+ STRV_FOREACH(p, arg_dot_from_patterns)
+ if (fnmatch(*p, name, 0) == 0) {
+ match_found = true;
+ break;
+ }
+
+ if (!match_found)
+ continue;
+ }
+
+ if (!strv_isempty(arg_dot_to_patterns)) {
+ match_found = false;
+
+ STRV_FOREACH(p, arg_dot_to_patterns)
+ if (fnmatch(*p, s, 0) == 0) {
+ match_found = true;
+ break;
+ }
+
+ if (!match_found)
+ continue;
+ }
+
+ if (!strv_isempty(patterns)) {
+ match_found = false;
+
+ STRV_FOREACH(p, patterns)
+ if (fnmatch(*p, name, 0) == 0 || fnmatch(*p, s, 0) == 0) {
+ match_found = true;
+ break;
+ }
+ if (!match_found)
+ continue;
+ }
+
+ printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
+ }
+ }
+
+ return 0;
+}
+
+static int graph_one(DBusConnection *bus, const struct unit_info *u, char *patterns[]) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ const char *interface = "org.freedesktop.systemd1.Unit";
+ int r;
+ DBusMessageIter iter, sub, sub2, sub3;
+
+ assert(bus);
+ assert(u);
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.systemd1",
+ u->unit_path,
+ "org.freedesktop.DBus.Properties",
+ "GetAll",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &interface,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+
+ if (!dbus_message_iter_init(reply, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
+ dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ for (dbus_message_iter_recurse(&iter, &sub);
+ dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID;
+ dbus_message_iter_next(&sub)) {
+ const char *prop;
+
+ assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_DICT_ENTRY);
+ dbus_message_iter_recurse(&sub, &sub2);
+
+ if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0 ||
+ dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_recurse(&sub2, &sub3);
+ r = graph_one_property(u->id, prop, &sub3, patterns);
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static int dot(DBusConnection *bus, char* patterns[]) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ DBusMessageIter iter, sub;
+ int r;
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "ListUnits",
+ &reply,
+ NULL,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+
+ if (!dbus_message_iter_init(reply, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
+ dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ printf("digraph systemd {\n");
+
+ for (dbus_message_iter_recurse(&iter, &sub);
+ dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID;
+ dbus_message_iter_next(&sub)) {
+ struct unit_info u;
+
+ r = bus_parse_unit_info(&sub, &u);
+ if (r < 0)
+ return -EIO;
+
+ r = graph_one(bus, &u, patterns);
+ if (r < 0)
+ return r;
+ }
+
+ printf("}\n");
+
+ log_info(" Color legend: black = Requires\n"
+ " dark blue = Requisite\n"
+ " dark grey = Wants\n"
+ " red = Conflicts\n"
+ " green = After\n");
+
+ if (on_tty())
+ log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
+ "-- Try a shell pipeline like 'systemd-analyze dot | dot -Tsvg > systemd.svg'!\n");
+
+ return 0;
+}
+
+static void analyze_help(void)
+{
+ printf("%s [OPTIONS...] {COMMAND} ...\n\n"
+ "Process systemd profiling information\n\n"
+ " -h --help Show this help\n"
+ " --version Show package version\n"
+ " --system Connect to system manager\n"
+ " --user Connect to user service manager\n"
+ " --order When generating a dependency graph, show only order\n"
+ " --require When generating a dependency graph, show only requirement\n"
+ " --from-pattern=GLOB, --to-pattern=GLOB\n"
+ " When generating a dependency graph, filter only origins\n"
+ " or destinations, respectively\n"
+ " --fuzz=TIMESPAN When printing the tree of the critical chain, print also\n"
+ " services, which finished TIMESPAN earlier, than the\n"
+ " latest in the branch. The unit of TIMESPAN is seconds\n"
+ " unless specified with a different unit, i.e. 50ms\n\n"
+ "Commands:\n"
+ " time Print time spent in the kernel before reaching userspace\n"
+ " blame Print list of running units ordered by time to init\n"
+ " critical-chain Print a tree of the time critical chain of units\n"
+ " plot Output SVG graphic showing service initialization\n"
+ " dot Dump dependency graph (in dot(1) format)\n\n",
+ program_invocation_short_name);
+
+ /* When updating this list, including descriptions, apply
+ * changes to shell-completion/bash/systemd and
+ * shell-completion/systemd-zsh-completion.zsh too. */
+}
+
+static int parse_argv(int argc, char *argv[])
+{
+ int r;
+
+ enum {
+ ARG_VERSION = 0x100,
+ ARG_ORDER,
+ ARG_REQUIRE,
+ ARG_USER,
+ ARG_SYSTEM,
+ ARG_DOT_FROM_PATTERN,
+ ARG_DOT_TO_PATTERN,
+ ARG_FUZZ
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "version", no_argument, NULL, ARG_VERSION },
+ { "order", no_argument, NULL, ARG_ORDER },
+ { "require", no_argument, NULL, ARG_REQUIRE },
+ { "user", no_argument, NULL, ARG_USER },
+ { "system", no_argument, NULL, ARG_SYSTEM },
+ { "from-pattern", required_argument, NULL, ARG_DOT_FROM_PATTERN},
+ { "to-pattern", required_argument, NULL, ARG_DOT_TO_PATTERN },
+ { "fuzz", required_argument, NULL, ARG_FUZZ },
+ { NULL, 0, NULL, 0 }
+ };
+
+ assert(argc >= 0);
+ assert(argv);
+
+ for (;;) {
+ switch (getopt_long(argc, argv, "h", options, NULL)) {
+
+ case 'h':
+ analyze_help();
+ return 0;
+
+ case ARG_VERSION:
+ puts(PACKAGE_STRING "\n" SYSTEMD_FEATURES);
+ return 0;
+
+ case ARG_USER:
+ arg_scope = UNIT_FILE_USER;
+ break;
+
+ case ARG_SYSTEM:
+ arg_scope = UNIT_FILE_SYSTEM;
+ break;
+
+ case ARG_ORDER:
+ arg_dot = DEP_ORDER;
+ break;
+
+ case ARG_REQUIRE:
+ arg_dot = DEP_REQUIRE;
+ break;
+
+ case ARG_DOT_FROM_PATTERN:
+ if (strv_extend(&arg_dot_from_patterns, optarg) < 0)
+ return log_oom();
+
+ break;
+
+ case ARG_DOT_TO_PATTERN:
+ if (strv_extend(&arg_dot_to_patterns, optarg) < 0)
+ return log_oom();
+
+ break;
+
+ case ARG_FUZZ:
+ r = parse_sec(optarg, &arg_fuzz);
+ if (r < 0)
+ return r;
+ break;
+
+ case -1:
+ return 1;
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ assert_not_reached("Unhandled option");
+ }
+ }
+}
+
+int main(int argc, char *argv[]) {
+ int r;
+ DBusConnection *bus = NULL;
+
+ setlocale(LC_ALL, "");
+ setlocale(LC_NUMERIC, "C"); /* we want to format/parse floats in C style */
+ log_parse_environment();
+ log_open();
+
+ r = parse_argv(argc, argv);
+ if (r < 0)
+ return EXIT_FAILURE;
+ else if (r <= 0)
+ return EXIT_SUCCESS;
+
+ bus = dbus_bus_get(arg_scope == UNIT_FILE_SYSTEM ? DBUS_BUS_SYSTEM : DBUS_BUS_SESSION, NULL);
+ if (!bus)
+ return EXIT_FAILURE;
+
+ if (!argv[optind] || streq(argv[optind], "time"))
+ r = analyze_time(bus);
+ else if (streq(argv[optind], "blame"))
+ r = analyze_blame(bus);
+ else if (streq(argv[optind], "critical-chain"))
+ r = analyze_critical_chain(bus);
+ else if (streq(argv[optind], "plot"))
+ r = analyze_plot(bus);
+ else if (streq(argv[optind], "dot"))
+ r = dot(bus, argv+optind+1);
+ else
+ log_error("Unknown operation '%s'.", argv[optind]);
+
+ strv_free(arg_dot_from_patterns);
+ strv_free(arg_dot_to_patterns);
+ dbus_connection_unref(bus);
+
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/src/ask-password/ask-password.c b/src/ask-password/ask-password.c
new file mode 100644
index 0000000000..238cf12080
--- /dev/null
+++ b/src/ask-password/ask-password.c
@@ -0,0 +1,184 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/socket.h>
+#include <sys/poll.h>
+#include <sys/types.h>
+#include <assert.h>
+#include <string.h>
+#include <errno.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/un.h>
+#include <sys/stat.h>
+#include <sys/signalfd.h>
+#include <getopt.h>
+#include <termios.h>
+#include <limits.h>
+#include <stddef.h>
+
+#include "log.h"
+#include "macro.h"
+#include "util.h"
+#include "strv.h"
+#include "ask-password-api.h"
+#include "def.h"
+
+static const char *arg_icon = NULL;
+static const char *arg_message = NULL;
+static bool arg_use_tty = true;
+static usec_t arg_timeout = DEFAULT_TIMEOUT_USEC;
+static bool arg_accept_cached = false;
+static bool arg_multiple = false;
+
+static int help(void) {
+
+ printf("%s [OPTIONS...] MESSAGE\n\n"
+ "Query the user for a system passphrase, via the TTY or an UI agent.\n\n"
+ " -h --help Show this help\n"
+ " --icon=NAME Icon name\n"
+ " --timeout=SEC Timeout in sec\n"
+ " --no-tty Ask question via agent even on TTY\n"
+ " --accept-cached Accept cached passwords\n"
+ " --multiple List multiple passwords if available\n",
+ program_invocation_short_name);
+
+ return 0;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+
+ enum {
+ ARG_ICON = 0x100,
+ ARG_TIMEOUT,
+ ARG_NO_TTY,
+ ARG_ACCEPT_CACHED,
+ ARG_MULTIPLE
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "icon", required_argument, NULL, ARG_ICON },
+ { "timeout", required_argument, NULL, ARG_TIMEOUT },
+ { "no-tty", no_argument, NULL, ARG_NO_TTY },
+ { "accept-cached", no_argument, NULL, ARG_ACCEPT_CACHED },
+ { "multiple", no_argument, NULL, ARG_MULTIPLE },
+ { NULL, 0, NULL, 0 }
+ };
+
+ int c;
+
+ assert(argc >= 0);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
+
+ switch (c) {
+
+ case 'h':
+ help();
+ return 0;
+
+ case ARG_ICON:
+ arg_icon = optarg;
+ break;
+
+ case ARG_TIMEOUT:
+ if (parse_sec(optarg, &arg_timeout) < 0) {
+ log_error("Failed to parse --timeout parameter %s", optarg);
+ return -EINVAL;
+ }
+ break;
+
+ case ARG_NO_TTY:
+ arg_use_tty = false;
+ break;
+
+ case ARG_ACCEPT_CACHED:
+ arg_accept_cached = true;
+ break;
+
+ case ARG_MULTIPLE:
+ arg_multiple = true;
+ break;
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ log_error("Unknown option code %c", c);
+ return -EINVAL;
+ }
+ }
+
+ if (optind != argc-1) {
+ help();
+ return -EINVAL;
+ }
+
+ arg_message = argv[optind];
+ return 1;
+}
+
+int main(int argc, char *argv[]) {
+ int r;
+ usec_t timeout;
+
+ log_parse_environment();
+ log_open();
+
+ if ((r = parse_argv(argc, argv)) <= 0)
+ goto finish;
+
+ if (arg_timeout > 0)
+ timeout = now(CLOCK_MONOTONIC) + arg_timeout;
+ else
+ timeout = 0;
+
+ if (arg_use_tty && isatty(STDIN_FILENO)) {
+ char *password = NULL;
+
+ if ((r = ask_password_tty(arg_message, timeout, NULL, &password)) >= 0) {
+ puts(password);
+ free(password);
+ }
+
+ } else {
+ char **l;
+
+ if ((r = ask_password_agent(arg_message, arg_icon, timeout, arg_accept_cached, &l)) >= 0) {
+ char **p;
+
+ STRV_FOREACH(p, l) {
+ puts(*p);
+
+ if (!arg_multiple)
+ break;
+ }
+
+ strv_free(l);
+ }
+ }
+
+finish:
+
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/src/binfmt/binfmt.c b/src/binfmt/binfmt.c
new file mode 100644
index 0000000000..5a42b3dbef
--- /dev/null
+++ b/src/binfmt/binfmt.c
@@ -0,0 +1,211 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdlib.h>
+#include <stdbool.h>
+#include <errno.h>
+#include <string.h>
+#include <stdio.h>
+#include <limits.h>
+#include <stdarg.h>
+#include <getopt.h>
+
+#include "log.h"
+#include "hashmap.h"
+#include "strv.h"
+#include "util.h"
+#include "conf-files.h"
+#include "fileio.h"
+
+static const char conf_file_dirs[] =
+ "/etc/binfmt.d\0"
+ "/run/binfmt.d\0"
+ "/usr/local/lib/binfmt.d\0"
+ "/usr/lib/binfmt.d\0"
+#ifdef HAVE_SPLIT_USR
+ "/lib/binfmt.d\0"
+#endif
+ ;
+
+static int delete_rule(const char *rule) {
+ _cleanup_free_ char *x = NULL, *fn = NULL;
+ char *e;
+
+ assert(rule[0]);
+
+ x = strdup(rule);
+ if (!x)
+ return log_oom();
+
+ e = strchrnul(x+1, x[0]);
+ *e = 0;
+
+ fn = strappend("/proc/sys/fs/binfmt_misc/", x+1);
+ if (!fn)
+ return log_oom();
+
+ return write_string_file(fn, "-1");
+}
+
+static int apply_rule(const char *rule) {
+ int r;
+
+ delete_rule(rule);
+
+ r = write_string_file("/proc/sys/fs/binfmt_misc/register", rule);
+ if (r < 0) {
+ log_error("Failed to add binary format: %s", strerror(-r));
+ return r;
+ }
+
+ return 0;
+}
+
+static int apply_file(const char *path, bool ignore_enoent) {
+ _cleanup_fclose_ FILE *f = NULL;
+ int r;
+
+ assert(path);
+
+ r = search_and_fopen_nulstr(path, "re", conf_file_dirs, &f);
+ if (r < 0) {
+ if (ignore_enoent && r == -ENOENT)
+ return 0;
+
+ log_error("Failed to open file '%s', ignoring: %s", path, strerror(-r));
+ return r;
+ }
+
+ log_debug("apply: %s\n", path);
+ for (;;) {
+ char l[LINE_MAX], *p;
+ int k;
+
+ if (!fgets(l, sizeof(l), f)) {
+ if (feof(f))
+ break;
+
+ log_error("Failed to read file '%s', ignoring: %m", path);
+ return -errno;
+ }
+
+ p = strstrip(l);
+ if (!*p)
+ continue;
+ if (strchr(COMMENTS "\n", *p))
+ continue;
+
+ k = apply_rule(p);
+ if (k < 0 && r == 0)
+ r = k;
+ }
+
+ return r;
+}
+
+static int help(void) {
+
+ printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
+ "Registers binary formats.\n\n"
+ " -h --help Show this help\n",
+ program_invocation_short_name);
+
+ return 0;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { NULL, 0, NULL, 0 }
+ };
+
+ int c;
+
+ assert(argc >= 0);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
+
+ switch (c) {
+
+ case 'h':
+ help();
+ return 0;
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ log_error("Unknown option code %c", c);
+ return -EINVAL;
+ }
+ }
+
+ return 1;
+}
+
+int main(int argc, char *argv[]) {
+ int r, k;
+
+ r = parse_argv(argc, argv);
+ if (r <= 0)
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+
+ log_set_target(LOG_TARGET_AUTO);
+ log_parse_environment();
+ log_open();
+
+ umask(0022);
+
+ r = 0;
+
+ if (argc > optind) {
+ int i;
+
+ for (i = optind; i < argc; i++) {
+ k = apply_file(argv[i], false);
+ if (k < 0 && r == 0)
+ r = k;
+ }
+ } else {
+ _cleanup_strv_free_ char **files = NULL;
+ char **f;
+
+ r = conf_files_list_nulstr(&files, ".conf", NULL, conf_file_dirs);
+ if (r < 0) {
+ log_error("Failed to enumerate binfmt.d files: %s", strerror(-r));
+ goto finish;
+ }
+
+ /* Flush out all rules */
+ write_string_file("/proc/sys/fs/binfmt_misc/status", "-1");
+
+ STRV_FOREACH(f, files) {
+ k = apply_file(*f, true);
+ if (k < 0 && r == 0)
+ r = k;
+ }
+ }
+
+finish:
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/src/boot/boot-efi.c b/src/boot/boot-efi.c
new file mode 100644
index 0000000000..9960c4d742
--- /dev/null
+++ b/src/boot/boot-efi.c
@@ -0,0 +1,190 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Kay Sievers
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdlib.h>
+#include <stdbool.h>
+#include <unistd.h>
+#include <getopt.h>
+#include <locale.h>
+#include <string.h>
+#include <fnmatch.h>
+#include <fcntl.h>
+#include <sys/timex.h>
+
+#include "boot.h"
+#include "boot-loader.h"
+#include "build.h"
+#include "util.h"
+#include "strv.h"
+#include "efivars.h"
+#include "conf-files.h"
+
+static char *tilt_slashes(char *s) {
+ char *p;
+
+ if (!s)
+ return NULL;
+
+ for (p = s; *p; p++)
+ if (*p == '\\')
+ *p = '/';
+ return s;
+}
+
+static int get_boot_entries(struct boot_info *info) {
+ uint16_t *list;
+ int i, n;
+ int err = 0;
+
+ n = efi_get_boot_options(&list);
+ if (n < 0)
+ return n;
+
+ for (i = 0; i < n; i++) {
+ struct boot_info_entry *e;
+
+ e = realloc(info->fw_entries, (info->fw_entries_count+1) * sizeof(struct boot_info_entry));
+ if (!e) {
+ err = -ENOMEM;
+ break;
+ }
+ info->fw_entries = e;
+
+ e = &info->fw_entries[info->fw_entries_count];
+ memset(e, 0, sizeof(struct boot_info_entry));
+ e->order = -1;
+
+ err = efi_get_boot_option(list[i], &e->title, &e->part_uuid, &e->path);
+ if (err < 0)
+ continue;
+
+ if (isempty(e->title)) {
+ free(e->title);
+ e->title = NULL;
+ }
+ tilt_slashes(e->path);
+
+ e->id = list[i];
+ info->fw_entries_count++;
+ }
+
+ free(list);
+ return err;
+}
+
+static int find_active_entry(struct boot_info *info) {
+ uint16_t boot_cur;
+ void *buf;
+ size_t l;
+ size_t i;
+ int err = -ENOENT;
+
+ err = efi_get_variable(EFI_VENDOR_GLOBAL, "BootCurrent", NULL, &buf, &l);
+ if (err < 0)
+ return err;
+
+ memcpy(&boot_cur, buf, sizeof(uint16_t));
+ for (i = 0; i < info->fw_entries_count; i++) {
+ if (info->fw_entries[i].id != boot_cur)
+ continue;
+ info->fw_entry_active = i;
+ err = 0;
+ break;
+ }
+ free(buf);
+ return err;
+}
+
+static int get_boot_order(struct boot_info *info) {
+ size_t i, k;
+ int r;
+
+ r = efi_get_boot_order(&info->fw_entries_order);
+ if (r < 0)
+ return r;
+
+ info->fw_entries_order_count = r;
+
+ for (i = 0; i < info->fw_entries_order_count; i++) {
+ for (k = 0; k < info->fw_entries_count; k++) {
+ if (info->fw_entries[k].id != info->fw_entries_order[i])
+ continue;
+ info->fw_entries[k].order = i;
+ break;
+ }
+ }
+
+ return 0;
+}
+
+static int entry_cmp(const void *a, const void *b) {
+ const struct boot_info_entry *e1 = a;
+ const struct boot_info_entry *e2 = b;
+
+ /* boot order of active entries */
+ if (e1->order > 0 && e2->order > 0)
+ return e1->order - e2->order;
+
+ /* sort active entries before inactive ones */
+ if (e1->order > 0)
+ return 1;
+ if (e2->order > 0)
+ return -1;
+
+ /* order of inactive entries */
+ return e1->id - e2->id;
+}
+
+int boot_info_query(struct boot_info *info) {
+ char str[64];
+ char buf[64];
+ char *loader_active = NULL;
+
+ info->fw_secure_boot = is_efi_secure_boot();
+ info->fw_secure_boot_setup_mode = is_efi_secure_boot_setup_mode();
+
+ efi_get_variable_string(EFI_VENDOR_LOADER, "LoaderInfo", &info->loader);
+
+ get_boot_entries(info);
+ if (info->fw_entries_count > 0) {
+ get_boot_order(info);
+ qsort(info->fw_entries, info->fw_entries_count, sizeof(struct boot_info_entry), entry_cmp);
+ find_active_entry(info);
+ }
+
+ efi_get_variable_string(EFI_VENDOR_LOADER, "LoaderFirmwareType", &info->fw_type);
+ efi_get_variable_string(EFI_VENDOR_LOADER, "LoaderFirmwareInfo", &info->fw_info);
+ efi_get_variable_string(EFI_VENDOR_LOADER, "LoaderImageIdentifier", &info->loader_image_path);
+ tilt_slashes(info->loader_image_path);
+ efi_get_loader_device_part_uuid(&info->loader_part_uuid);
+
+ boot_loader_read_entries(info);
+ efi_get_variable_string(EFI_VENDOR_LOADER, "LoaderEntrySelected", &loader_active);
+ if (loader_active) {
+ boot_loader_find_active_entry(info, loader_active);
+ free(loader_active);
+ }
+
+ snprintf(str, sizeof(str), "LoaderEntryOptions-%s", sd_id128_to_string(info->machine_id, buf));
+ efi_get_variable_string(EFI_VENDOR_LOADER, str, &info->loader_options_added);
+
+ return 0;
+}
diff --git a/src/boot/boot-loader.c b/src/boot/boot-loader.c
new file mode 100644
index 0000000000..d44fdb3aef
--- /dev/null
+++ b/src/boot/boot-loader.c
@@ -0,0 +1,132 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Kay Sievers
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdlib.h>
+#include <stdbool.h>
+#include <unistd.h>
+#include <getopt.h>
+#include <locale.h>
+#include <string.h>
+#include <ctype.h>
+#include <sys/timex.h>
+
+#include "boot.h"
+#include "boot-loader.h"
+#include "build.h"
+#include "util.h"
+#include "strv.h"
+#include "conf-files.h"
+
+static char *loader_fragment_read_title(const char *fragment) {
+ FILE *f;
+ char line[LINE_MAX];
+ char *title = NULL;
+
+ f = fopen(fragment, "re");
+ if (!f)
+ return NULL;
+
+ while (fgets(line, sizeof(line), f) != NULL) {
+ char *s;
+ size_t l;
+
+ l = strlen(line);
+ if (l < 1)
+ continue;
+ if (line[l-1] == '\n')
+ line[l-1] = '\0';
+
+ s = line;
+ while (isspace(s[0]))
+ s++;
+
+ if (s[0] == '#')
+ continue;
+
+ if (!startswith(s, "title"))
+ continue;
+
+ s += strlen("title");
+ if (!isspace(s[0]))
+ continue;
+ while (isspace(s[0]))
+ s++;
+
+ title = strdup(s);
+ break;
+ }
+
+ fclose(f);
+ return title;
+}
+
+int boot_loader_read_entries(struct boot_info *info) {
+ _cleanup_strv_free_ char **files = NULL;
+ static const char *loader_dir[] = { "/boot/loader/entries", NULL};
+ unsigned int count;
+ unsigned int i;
+ int err;
+
+ err = conf_files_list_strv(&files, ".conf", NULL, loader_dir);
+ if (err < 0)
+ return err;
+
+ count = strv_length(files);
+ info->loader_entries = new0(struct boot_info_entry, count);
+ if (!info->loader_entries)
+ return -ENOMEM;
+
+ for (i = 0; i < count; i++) {
+ info->loader_entries[i].title = loader_fragment_read_title(files[i]);
+ info->loader_entries[i].path = strdup(files[i]);
+ if (!info->loader_entries[i].title || !info->loader_entries[i].path) {
+ free(info->loader_entries[i].title);
+ free(info->loader_entries[i].path);
+ return -ENOMEM;
+ }
+ info->loader_entries_count++;
+ }
+
+ return 0;
+}
+
+int boot_loader_find_active_entry(struct boot_info *info, const char *loader_active) {
+ char *fn;
+ unsigned int i;
+
+ if (!loader_active)
+ return -ENOENT;
+ if (info->loader_entries_count == 0)
+ return -ENOENT;
+
+ if (asprintf(&fn, "/boot/loader/entries/%s.conf", loader_active) < 0)
+ return -ENOMEM;
+
+ for (i = 0; i < info->loader_entries_count; i++) {
+ if (streq(fn, info->loader_entries[i].path)) {
+ info->loader_entry_active = i;
+ break;
+ }
+ }
+
+ free(fn);
+ return 0;
+}
diff --git a/src/boot/boot-loader.h b/src/boot/boot-loader.h
new file mode 100644
index 0000000000..08827c30ad
--- /dev/null
+++ b/src/boot/boot-loader.h
@@ -0,0 +1,25 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Kay Sievers
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+int boot_loader_read_entries(struct boot_info *info);
+int boot_loader_find_active_entry(struct boot_info *info, const char *loader_active);
diff --git a/src/boot/boot.h b/src/boot/boot.h
new file mode 100644
index 0000000000..bd8dc69d3d
--- /dev/null
+++ b/src/boot/boot.h
@@ -0,0 +1,64 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Kay Sievers
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "sd-id128.h"
+
+/*
+ * Firmware and boot manager information to be filled in
+ * by the platform.
+ *
+ * This is partly EFI specific, if you add things, keep this
+ * as generic as possible to be able to re-use it on other
+ * platforms.
+ */
+
+struct boot_info_entry {
+ uint16_t id;
+ uint16_t order;
+ char *title;
+ sd_id128_t part_uuid;
+ char *path;
+};
+
+struct boot_info {
+ sd_id128_t machine_id;
+ sd_id128_t boot_id;
+ char *fw_type;
+ char *fw_info;
+ int fw_secure_boot;
+ int fw_secure_boot_setup_mode;
+ struct boot_info_entry *fw_entries;
+ size_t fw_entries_count;
+ uint16_t *fw_entries_order;
+ size_t fw_entries_order_count;
+ ssize_t fw_entry_active;
+ char *loader;
+ char *loader_image_path;
+ sd_id128_t loader_part_uuid;
+ struct boot_info_entry *loader_entries;
+ size_t loader_entries_count;
+ ssize_t loader_entry_active;
+ char *loader_options_added;
+};
+
+int boot_info_query(struct boot_info *info);
diff --git a/src/boot/bootctl.c b/src/boot/bootctl.c
new file mode 100644
index 0000000000..af694fdf64
--- /dev/null
+++ b/src/boot/bootctl.c
@@ -0,0 +1,288 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Kay Sievers
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdlib.h>
+#include <stdbool.h>
+#include <unistd.h>
+#include <getopt.h>
+#include <locale.h>
+#include <string.h>
+#include <sys/timex.h>
+
+#include "boot.h"
+#include "build.h"
+#include "util.h"
+#include "utf8.h"
+
+static int help(void) {
+ printf("%s [OPTIONS...] COMMAND ...\n\n"
+ "Query or change firmware and boot mananger settings.\n\n"
+ " -h --help Show this help\n"
+ " --version Show package version\n"
+ "Commands:\n"
+ " status Show current boot settings\n",
+ program_invocation_short_name);
+
+ return 0;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+ enum {
+ ARG_VERSION = 0x100,
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "version", no_argument, NULL, ARG_VERSION },
+ { NULL, 0, NULL, 0 }
+ };
+
+ int c;
+
+ assert(argc >= 0);
+ assert(argv);
+ while ((c = getopt_long(argc, argv, "+hH:P", options, NULL)) >= 0) {
+
+ switch (c) {
+
+ case 'h':
+ help();
+ return 0;
+
+ case ARG_VERSION:
+ puts(PACKAGE_STRING);
+ puts(SYSTEMD_FEATURES);
+ return 0;
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ log_error("Unknown option code %c", c);
+ return -EINVAL;
+ }
+ }
+
+ return 1;
+}
+
+static int boot_info_new(struct boot_info **info) {
+ struct boot_info *in;
+ int err;
+
+ in = new0(struct boot_info, 1);
+ if (!in)
+ return -ENOMEM;
+
+ err = sd_id128_get_machine(&in->machine_id);
+ if (err < 0)
+ goto err;
+
+ err = sd_id128_get_boot(&in->boot_id);
+ if (err < 0)
+ goto err;
+
+ in->fw_entry_active = -1;
+ in->loader_entry_active = -1;
+
+ *info = in;
+ return 0;
+err:
+ free(in);
+ return err;
+}
+
+static void boot_info_entries_free(struct boot_info_entry *entries, size_t n) {
+ size_t i;
+
+ for (i = 0; i < n; i++) {
+ free(entries[i].title);
+ free(entries[i].path);
+ }
+ free(entries);
+}
+
+static void boot_info_free(struct boot_info *info) {
+ free(info->fw_type);
+ free(info->fw_info);
+ boot_info_entries_free(info->fw_entries, info->fw_entries_count);
+ free(info->fw_entries_order);
+ free(info->loader);
+ free(info->loader_image_path);
+ free(info->loader_options_added);
+ boot_info_entries_free(info->loader_entries, info->loader_entries_count);
+ free(info);
+}
+
+static int show_status(char **args, unsigned n) {
+ char buf[64];
+ struct boot_info *info;
+ int err;
+
+ err = boot_info_new(&info);
+ if (err < 0)
+ return -ENOMEM;
+
+ err = boot_info_query(info);
+
+ printf("System:\n");
+ printf(" Machine ID: %s\n", sd_id128_to_string(info->machine_id, buf));
+ printf(" Boot ID: %s\n", sd_id128_to_string(info->boot_id, buf));
+ if (info->fw_type)
+ printf(" Firmware: %s (%s)\n", info->fw_type, strna(info->fw_info));
+ if (info->fw_secure_boot >= 0)
+ printf(" Secure Boot: %s\n", info->fw_secure_boot ? "enabled" : "disabled");
+ if (info->fw_secure_boot_setup_mode >= 0)
+ printf(" Setup Mode: %s\n", info->fw_secure_boot_setup_mode ? "setup" : "user");
+ printf("\n");
+
+ if (info->fw_entry_active >= 0) {
+ printf("Selected Firmware Entry:\n");
+ printf(" Title: %s\n", strna(info->fw_entries[info->fw_entry_active].title));
+ if (!sd_id128_equal(info->fw_entries[info->fw_entry_active].part_uuid, SD_ID128_NULL))
+ printf(" Partition: /dev/disk/by-partuuid/%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\n",
+ SD_ID128_FORMAT_VAL(info->fw_entries[info->fw_entry_active].part_uuid));
+ else
+ printf(" Partition: n/a\n");
+ if (info->fw_entries[info->fw_entry_active].path)
+ printf(" File: %s%s\n", draw_special_char(DRAW_TREE_RIGHT), info->fw_entries[info->fw_entry_active].path);
+ }
+ printf("\n");
+
+ if (info->loader) {
+ printf("Boot Loader:\n");
+ printf(" Product: %s\n", info->loader);
+ if (!sd_id128_equal(info->loader_part_uuid, SD_ID128_NULL))
+ printf(" Partition: /dev/disk/by-partuuid/%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\n",
+ SD_ID128_FORMAT_VAL(info->loader_part_uuid));
+ else
+ printf(" Partition: n/a\n");
+ printf(" File: %s%s\n", draw_special_char(DRAW_TREE_RIGHT), strna(info->loader_image_path));
+ printf("\n");
+
+ if (info->loader_entry_active >= 0) {
+ printf("Selected Boot Loader Entry:\n");
+ printf(" Title: %s\n", strna(info->loader_entries[info->loader_entry_active].title));
+ printf(" File: %s\n", info->loader_entries[info->loader_entry_active].path);
+ if (info->loader_options_added)
+ printf(" Options: %s\n", info->loader_options_added);
+ }
+ } else
+ printf("No suitable data is provided by the boot manager. See:\n"
+ " http://www.freedesktop.org/wiki/Software/systemd/BootLoaderInterface\n"
+ " http://www.freedesktop.org/wiki/Specifications/BootLoaderSpec\n"
+ "for details.\n");
+ printf("\n");
+
+ boot_info_free(info);
+ return err;
+}
+
+static int bootctl_main(int argc, char *argv[]) {
+ static const struct {
+ const char* verb;
+ const enum {
+ MORE,
+ LESS,
+ EQUAL
+ } argc_cmp;
+ const int argc;
+ int (* const dispatch)(char **args, unsigned n);
+ } verbs[] = {
+ { "status", LESS, 1, show_status },
+ };
+
+ int left;
+ unsigned i;
+
+ assert(argc >= 0);
+ assert(argv);
+
+ left = argc - optind;
+
+ if (left <= 0)
+ /* Special rule: no arguments means "status" */
+ i = 0;
+ else {
+ if (streq(argv[optind], "help")) {
+ help();
+ return 0;
+ }
+
+ for (i = 0; i < ELEMENTSOF(verbs); i++)
+ if (streq(argv[optind], verbs[i].verb))
+ break;
+
+ if (i >= ELEMENTSOF(verbs)) {
+ log_error("Unknown operation %s", argv[optind]);
+ return -EINVAL;
+ }
+ }
+
+ switch (verbs[i].argc_cmp) {
+
+ case EQUAL:
+ if (left != verbs[i].argc) {
+ log_error("Invalid number of arguments.");
+ return -EINVAL;
+ }
+ break;
+
+ case MORE:
+ if (left < verbs[i].argc) {
+ log_error("Too few arguments.");
+ return -EINVAL;
+ }
+ break;
+
+ case LESS:
+ if (left > verbs[i].argc) {
+ log_error("Too many arguments.");
+ return -EINVAL;
+ }
+ break;
+
+ default:
+ assert_not_reached("Unknown comparison operator.");
+ }
+
+ return verbs[i].dispatch(argv + optind, left);
+}
+
+int main(int argc, char *argv[]) {
+ int r, retval = EXIT_FAILURE;
+
+ log_parse_environment();
+ log_open();
+
+ r = parse_argv(argc, argv);
+ if (r < 0)
+ goto finish;
+ else if (r == 0) {
+ retval = EXIT_SUCCESS;
+ goto finish;
+ }
+
+ r = bootctl_main(argc, argv);
+ retval = r < 0 ? EXIT_FAILURE : r;
+finish:
+ return retval;
+}
diff --git a/src/bootchart/bootchart.c b/src/bootchart/bootchart.c
new file mode 100644
index 0000000000..8be5a27afa
--- /dev/null
+++ b/src/bootchart/bootchart.c
@@ -0,0 +1,481 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright (C) 2009-2013 Intel Coproration
+
+ Authors:
+ Auke Kok <auke-jan.h.kok@intel.com>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+ ***/
+
+/***
+
+ Many thanks to those who contributed ideas and code:
+ - Ziga Mahkovec - Original bootchart author
+ - Anders Norgaard - PyBootchartgui
+ - Michael Meeks - bootchart2
+ - Scott James Remnant - Ubuntu C-based logger
+ - Arjan van der Ven - for the idea to merge bootgraph.pl functionality
+
+ ***/
+
+#include <sys/time.h>
+#include <sys/types.h>
+#include <sys/resource.h>
+#include <sys/stat.h>
+#include <stdio.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <time.h>
+#include <getopt.h>
+#include <limits.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdbool.h>
+#include <systemd/sd-journal.h>
+
+#include "util.h"
+#include "fileio.h"
+#include "macro.h"
+#include "conf-parser.h"
+#include "strxcpyx.h"
+#include "path-util.h"
+#include "store.h"
+#include "svg.h"
+#include "bootchart.h"
+#include "list.h"
+
+double graph_start;
+double log_start;
+struct ps_struct *ps_first;
+int pscount;
+int cpus;
+double interval;
+FILE *of = NULL;
+int overrun = 0;
+static int exiting = 0;
+int sysfd=-1;
+
+/* graph defaults */
+bool arg_entropy = false;
+bool initcall = true;
+bool arg_relative = false;
+bool arg_filter = true;
+bool arg_show_cmdline = false;
+bool arg_pss = false;
+int samples;
+int arg_samples_len = 500; /* we record len+1 (1 start sample) */
+double arg_hz = 25.0; /* 20 seconds log time */
+double arg_scale_x = 100.0; /* 100px = 1sec */
+double arg_scale_y = 20.0; /* 16px = 1 process bar */
+static struct list_sample_data *sampledata;
+struct list_sample_data *head;
+
+char arg_init_path[PATH_MAX] = "/sbin/init";
+char arg_output_path[PATH_MAX] = "/run/log";
+
+static void signal_handler(int sig) {
+ if (sig++)
+ sig--;
+ exiting = 1;
+}
+
+#define BOOTCHART_CONF "/etc/systemd/bootchart.conf"
+
+#define BOOTCHART_MAX (16*1024*1024)
+
+static void parse_conf(void) {
+ char *init = NULL, *output = NULL;
+ const ConfigTableItem items[] = {
+ { "Bootchart", "Samples", config_parse_int, 0, &arg_samples_len },
+ { "Bootchart", "Frequency", config_parse_double, 0, &arg_hz },
+ { "Bootchart", "Relative", config_parse_bool, 0, &arg_relative },
+ { "Bootchart", "Filter", config_parse_bool, 0, &arg_filter },
+ { "Bootchart", "Output", config_parse_path, 0, &output },
+ { "Bootchart", "Init", config_parse_path, 0, &init },
+ { "Bootchart", "PlotMemoryUsage", config_parse_bool, 0, &arg_pss },
+ { "Bootchart", "PlotEntropyGraph", config_parse_bool, 0, &arg_entropy },
+ { "Bootchart", "ScaleX", config_parse_double, 0, &arg_scale_x },
+ { "Bootchart", "ScaleY", config_parse_double, 0, &arg_scale_y },
+ { NULL, NULL, NULL, 0, NULL }
+ };
+ _cleanup_fclose_ FILE *f;
+ int r;
+
+ f = fopen(BOOTCHART_CONF, "re");
+ if (!f)
+ return;
+
+ r = config_parse(NULL, BOOTCHART_CONF, f,
+ NULL, config_item_table_lookup, (void*) items, true, false, NULL);
+ if (r < 0)
+ log_warning("Failed to parse configuration file: %s", strerror(-r));
+
+ if (init != NULL)
+ strscpy(arg_init_path, sizeof(arg_init_path), init);
+ if (output != NULL)
+ strscpy(arg_output_path, sizeof(arg_output_path), output);
+}
+
+static int parse_args(int argc, char *argv[]) {
+ static struct option options[] = {
+ {"rel", no_argument, NULL, 'r'},
+ {"freq", required_argument, NULL, 'f'},
+ {"samples", required_argument, NULL, 'n'},
+ {"pss", no_argument, NULL, 'p'},
+ {"output", required_argument, NULL, 'o'},
+ {"init", required_argument, NULL, 'i'},
+ {"no-filter", no_argument, NULL, 'F'},
+ {"cmdline", no_argument, NULL, 'C'},
+ {"help", no_argument, NULL, 'h'},
+ {"scale-x", required_argument, NULL, 'x'},
+ {"scale-y", required_argument, NULL, 'y'},
+ {"entropy", no_argument, NULL, 'e'},
+ {NULL, 0, NULL, 0}
+ };
+ int c;
+
+ while ((c = getopt_long(argc, argv, "erpf:n:o:i:FChx:y:", options, NULL)) >= 0) {
+ int r;
+
+ switch (c) {
+ case 'r':
+ arg_relative = true;
+ break;
+ case 'f':
+ r = safe_atod(optarg, &arg_hz);
+ if (r < 0)
+ log_warning("failed to parse --freq/-f argument '%s': %s",
+ optarg, strerror(-r));
+ break;
+ case 'F':
+ arg_filter = false;
+ break;
+ case 'C':
+ arg_show_cmdline = true;
+ break;
+ case 'n':
+ r = safe_atoi(optarg, &arg_samples_len);
+ if (r < 0)
+ log_warning("failed to parse --samples/-n argument '%s': %s",
+ optarg, strerror(-r));
+ break;
+ case 'o':
+ path_kill_slashes(optarg);
+ strscpy(arg_output_path, sizeof(arg_output_path), optarg);
+ break;
+ case 'i':
+ path_kill_slashes(optarg);
+ strscpy(arg_init_path, sizeof(arg_init_path), optarg);
+ break;
+ case 'p':
+ arg_pss = true;
+ break;
+ case 'x':
+ r = safe_atod(optarg, &arg_scale_x);
+ if (r < 0)
+ log_warning("failed to parse --scale-x/-x argument '%s': %s",
+ optarg, strerror(-r));
+ break;
+ case 'y':
+ r = safe_atod(optarg, &arg_scale_y);
+ if (r < 0)
+ log_warning("failed to parse --scale-y/-y argument '%s': %s",
+ optarg, strerror(-r));
+ break;
+ case 'e':
+ arg_entropy = true;
+ break;
+ case 'h':
+ fprintf(stderr, "Usage: %s [OPTIONS]\n", argv[0]);
+ fprintf(stderr, " --rel, -r Record time relative to recording\n");
+ fprintf(stderr, " --freq, -f f Sample frequency [%f]\n", arg_hz);
+ fprintf(stderr, " --samples, -n N Stop sampling at [%d] samples\n", arg_samples_len);
+ fprintf(stderr, " --scale-x, -x N Scale the graph horizontally [%f] \n", arg_scale_x);
+ fprintf(stderr, " --scale-y, -y N Scale the graph vertically [%f] \n", arg_scale_y);
+ fprintf(stderr, " --pss, -p Enable PSS graph (CPU intensive)\n");
+ fprintf(stderr, " --entropy, -e Enable the entropy_avail graph\n");
+ fprintf(stderr, " --output, -o [PATH] Path to output files [%s]\n", arg_output_path);
+ fprintf(stderr, " --init, -i [PATH] Path to init executable [%s]\n", arg_init_path);
+ fprintf(stderr, " --no-filter, -F Disable filtering of processes from the graph\n");
+ fprintf(stderr, " that are of less importance or short-lived\n");
+ fprintf(stderr, " --cmdline, -C Display the full command line with arguments\n");
+ fprintf(stderr, " of processes, instead of only the process name\n");
+ fprintf(stderr, " --help, -h Display this message\n");
+ fprintf(stderr, "See bootchart.conf for more information.\n");
+ exit (EXIT_SUCCESS);
+ break;
+ default:
+ break;
+ }
+ }
+
+ if (arg_hz <= 0.0) {
+ fprintf(stderr, "Error: Frequency needs to be > 0\n");
+ return -EINVAL;
+ }
+
+ return 0;
+}
+
+static void do_journal_append(char *file)
+{
+ struct iovec iovec[5];
+ int r, f, j = 0;
+ ssize_t n;
+ _cleanup_free_ char *bootchart_file = NULL, *bootchart_message = NULL,
+ *p = NULL;
+
+ bootchart_file = strappend("BOOTCHART_FILE=", file);
+ if (bootchart_file)
+ IOVEC_SET_STRING(iovec[j++], bootchart_file);
+
+ IOVEC_SET_STRING(iovec[j++], "MESSAGE_ID=9f26aa562cf440c2b16c773d0479b518");
+ IOVEC_SET_STRING(iovec[j++], "PRIORITY=7");
+ bootchart_message = strjoin("MESSAGE=Bootchart created: ", file, NULL);
+ if (bootchart_message)
+ IOVEC_SET_STRING(iovec[j++], bootchart_message);
+
+ p = malloc(9 + BOOTCHART_MAX);
+ if (!p) {
+ r = log_oom();
+ return;
+ }
+
+ memcpy(p, "BOOTCHART=", 10);
+
+ f = open(file, O_RDONLY);
+ if (f < 0) {
+ log_error("Failed to read bootchart data: %m\n");
+ return;
+ }
+ n = loop_read(f, p + 10, BOOTCHART_MAX, false);
+ if (n < 0) {
+ log_error("Failed to read bootchart data: %s\n", strerror(-n));
+ close(f);
+ return;
+ }
+ close(f);
+
+ iovec[j].iov_base = p;
+ iovec[j].iov_len = 10 + n;
+ j++;
+
+ r = sd_journal_sendv(iovec, j);
+ if (r < 0)
+ log_error("Failed to send bootchart: %s", strerror(-r));
+}
+
+int main(int argc, char *argv[]) {
+ _cleanup_free_ char *build = NULL;
+ struct sigaction sig = {
+ .sa_handler = signal_handler,
+ };
+ struct ps_struct *ps;
+ char output_file[PATH_MAX];
+ char datestr[200];
+ time_t t = 0;
+ int r;
+ struct rlimit rlim;
+
+ parse_conf();
+
+ r = parse_args(argc, argv);
+ if (r < 0)
+ return EXIT_FAILURE;
+
+ /*
+ * If the kernel executed us through init=/usr/lib/systemd/systemd-bootchart, then
+ * fork:
+ * - parent execs executable specified via init_path[] (/sbin/init by default) as pid=1
+ * - child logs data
+ */
+ if (getpid() == 1) {
+ if (fork()) {
+ /* parent */
+ execl(arg_init_path, arg_init_path, NULL);
+ }
+ }
+ argv[0][0] = '@';
+
+ rlim.rlim_cur = 4096;
+ rlim.rlim_max = 4096;
+ (void) setrlimit(RLIMIT_NOFILE, &rlim);
+
+ /* start with empty ps LL */
+ ps_first = calloc(1, sizeof(struct ps_struct));
+ if (!ps_first) {
+ perror("calloc(ps_struct)");
+ exit(EXIT_FAILURE);
+ }
+
+ /* handle TERM/INT nicely */
+ sigaction(SIGHUP, &sig, NULL);
+
+ interval = (1.0 / arg_hz) * 1000000000.0;
+
+ log_uptime();
+
+ LIST_HEAD_INIT(struct list_sample_data, head);
+
+ /* main program loop */
+ for (samples = 0; !exiting && samples < arg_samples_len; samples++) {
+ int res;
+ double sample_stop;
+ struct timespec req;
+ time_t newint_s;
+ long newint_ns;
+ double elapsed;
+ double timeleft;
+
+ sampledata = new0(struct list_sample_data, 1);
+ if (sampledata == NULL) {
+ log_error("Failed to allocate memory for a node: %m");
+ return -1;
+ }
+
+ sampledata->sampletime = gettime_ns();
+ sampledata->counter = samples;
+
+ if (!of && (access(arg_output_path, R_OK|W_OK|X_OK) == 0)) {
+ t = time(NULL);
+ strftime(datestr, sizeof(datestr), "%Y%m%d-%H%M", localtime(&t));
+ snprintf(output_file, PATH_MAX, "%s/bootchart-%s.svg", arg_output_path, datestr);
+ of = fopen(output_file, "w");
+ }
+
+ if (sysfd < 0)
+ sysfd = open("/sys", O_RDONLY);
+
+ if (!build)
+ parse_env_file("/etc/os-release", NEWLINE,
+ "PRETTY_NAME", &build,
+ NULL);
+
+ /* wait for /proc to become available, discarding samples */
+ if (graph_start <= 0.0)
+ log_uptime();
+ else
+ log_sample(samples, &sampledata);
+
+ sample_stop = gettime_ns();
+
+ elapsed = (sample_stop - sampledata->sampletime) * 1000000000.0;
+ timeleft = interval - elapsed;
+
+ newint_s = (time_t)(timeleft / 1000000000.0);
+ newint_ns = (long)(timeleft - (newint_s * 1000000000.0));
+
+ /*
+ * check if we have not consumed our entire timeslice. If we
+ * do, don't sleep and take a new sample right away.
+ * we'll lose all the missed samples and overrun our total
+ * time
+ */
+ if (newint_ns > 0 || newint_s > 0) {
+ req.tv_sec = newint_s;
+ req.tv_nsec = newint_ns;
+
+ res = nanosleep(&req, NULL);
+ if (res) {
+ if (errno == EINTR) {
+ /* caught signal, probably HUP! */
+ break;
+ }
+ perror("nanosleep()");
+ exit (EXIT_FAILURE);
+ }
+ } else {
+ overrun++;
+ /* calculate how many samples we lost and scrap them */
+ arg_samples_len -= (int)(newint_ns / interval);
+ }
+ LIST_PREPEND(struct list_sample_data, link, head, sampledata);
+ }
+
+ /* do some cleanup, close fd's */
+ ps = ps_first;
+ while (ps->next_ps) {
+ ps = ps->next_ps;
+ if (ps->schedstat)
+ close(ps->schedstat);
+ if (ps->sched)
+ close(ps->sched);
+ if (ps->smaps)
+ fclose(ps->smaps);
+ }
+
+ if (!of) {
+ t = time(NULL);
+ strftime(datestr, sizeof(datestr), "%Y%m%d-%H%M", localtime(&t));
+ snprintf(output_file, PATH_MAX, "%s/bootchart-%s.svg", arg_output_path, datestr);
+ of = fopen(output_file, "w");
+ }
+
+ if (!of) {
+ fprintf(stderr, "opening output file '%s': %m\n", output_file);
+ exit (EXIT_FAILURE);
+ }
+
+ svg_do(build);
+
+ fprintf(stderr, "systemd-bootchart wrote %s\n", output_file);
+
+ do_journal_append(output_file);
+
+ if (of)
+ fclose(of);
+
+ closedir(proc);
+ if (sysfd >= 0)
+ close(sysfd);
+
+ /* nitpic cleanups */
+ ps = ps_first->next_ps;
+ while (ps->next_ps) {
+ struct ps_struct *old;
+
+ old = ps;
+ old->sample = ps->first;
+ ps = ps->next_ps;
+ while (old->sample->next) {
+ struct ps_sched_struct *oldsample = old->sample;
+
+ old->sample = old->sample->next;
+ free(oldsample);
+ }
+ free(old->sample);
+ free(old);
+ }
+ free(ps->sample);
+ free(ps);
+
+ sampledata = head;
+ while (sampledata->link_prev) {
+ struct list_sample_data *old_sampledata = sampledata;
+ sampledata = sampledata->link_prev;
+ free(old_sampledata);
+ }
+ free(sampledata);
+ /* don't complain when overrun once, happens most commonly on 1st sample */
+ if (overrun > 1)
+ fprintf(stderr, "systemd-boochart: Warning: sample time overrun %i times\n", overrun);
+
+ return 0;
+}
diff --git a/src/bootchart/bootchart.conf b/src/bootchart/bootchart.conf
new file mode 100644
index 0000000000..48fad02726
--- /dev/null
+++ b/src/bootchart/bootchart.conf
@@ -0,0 +1,20 @@
+# This file is part of systemd.
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 of the License, or
+# (at your option) any later version.
+#
+# See bootchart.conf(5) for details
+
+[Bootchart]
+#Samples=500
+#Frequency=25
+#Relative=no
+#Filter=yes
+#Output=<folder name, defaults to /run/log>
+#Init=/path/to/init-binary
+#PlotMemoryUsage=no
+#PlotEntropyGraph=no
+#ScaleX=100
+#ScaleY=20
diff --git a/src/bootchart/bootchart.h b/src/bootchart/bootchart.h
new file mode 100644
index 0000000000..d0273421de
--- /dev/null
+++ b/src/bootchart/bootchart.h
@@ -0,0 +1,133 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright (C) 2009-2013 Intel Coproration
+
+ Authors:
+ Auke Kok <auke-jan.h.kok@intel.com>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <dirent.h>
+#include <stdbool.h>
+#include "list.h"
+
+#define MAXCPUS 16
+#define MAXPIDS 65535
+
+struct block_stat_struct {
+ /* /proc/vmstat pgpgin & pgpgout */
+ int bi;
+ int bo;
+};
+
+struct cpu_stat_sample_struct {
+ /* /proc/schedstat fields 10 & 11 (after name) */
+ double runtime;
+ double waittime;
+};
+
+/* per process, per sample data we will log */
+struct ps_sched_struct {
+ /* /proc/<n>/schedstat fields 1 & 2 */
+ double runtime;
+ double waittime;
+ int pss;
+ struct list_sample_data *sampledata;
+ struct ps_sched_struct *next;
+ struct ps_sched_struct *prev;
+ struct ps_sched_struct *cross; /* cross pointer */
+ struct ps_struct *ps_new;
+};
+
+struct list_sample_data {
+ double runtime[MAXCPUS];
+ double waittime[MAXCPUS];
+ double sampletime;
+ int entropy_avail;
+ struct block_stat_struct blockstat;
+ LIST_FIELDS(struct list_sample_data, link); /* DLL */
+ int counter;
+};
+
+/* process info */
+struct ps_struct {
+ struct ps_struct *next_ps; /* SLL pointer */
+ struct ps_struct *parent; /* ppid ref */
+ struct ps_struct *children; /* children */
+ struct ps_struct *next; /* siblings */
+
+ /* must match - otherwise it's a new process with same PID */
+ char name[256];
+ int pid;
+ int ppid;
+
+ /* cache fd's */
+ int sched;
+ int schedstat;
+ FILE *smaps;
+
+ /* pointers to first/last seen timestamps */
+ struct ps_sched_struct *first;
+ struct ps_sched_struct *last;
+
+ /* records actual start time, may be way before bootchart runs */
+ double starttime;
+
+ /* record human readable total cpu time */
+ double total;
+
+ /* largest PSS size found */
+ int pss_max;
+
+ /* for drawing connection lines later */
+ double pos_x;
+ double pos_y;
+
+ struct ps_sched_struct *sample;
+};
+
+extern int entropy_avail[];
+
+extern double graph_start;
+extern double log_start;
+extern double sampletime[];
+extern struct ps_struct *ps_first;
+extern struct block_stat_struct blockstat[];
+extern int pscount;
+extern bool arg_relative;
+extern bool arg_filter;
+extern bool arg_show_cmdline;
+extern bool arg_pss;
+extern bool arg_entropy;
+extern bool initcall;
+extern int samples;
+extern int cpus;
+extern int arg_samples_len;
+extern double arg_hz;
+extern double arg_scale_x;
+extern double arg_scale_y;
+extern int overrun;
+extern double interval;
+
+extern char arg_output_path[PATH_MAX];
+extern char arg_init_path[PATH_MAX];
+
+extern FILE *of;
+extern int sysfd;
diff --git a/src/bootchart/store.c b/src/bootchart/store.c
new file mode 100755
index 0000000000..b2afb8d13b
--- /dev/null
+++ b/src/bootchart/store.c
@@ -0,0 +1,504 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright (C) 2009-2013 Intel Coproration
+
+ Authors:
+ Auke Kok <auke-jan.h.kok@intel.com>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+ ***/
+
+#include <unistd.h>
+#include <stdlib.h>
+#include <limits.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <stdio.h>
+#include <string.h>
+#include <dirent.h>
+#include <fcntl.h>
+#include <time.h>
+
+#include "util.h"
+#include "strxcpyx.h"
+#include "store.h"
+#include "bootchart.h"
+
+/*
+ * Alloc a static 4k buffer for stdio - primarily used to increase
+ * PSS buffering from the default 1k stdin buffer to reduce
+ * read() overhead.
+ */
+static char smaps_buf[4096];
+static int skip = 0;
+DIR *proc;
+int procfd = -1;
+
+double gettime_ns(void) {
+ struct timespec n;
+
+ clock_gettime(CLOCK_MONOTONIC, &n);
+
+ return (n.tv_sec + (n.tv_nsec / 1000000000.0));
+}
+
+void log_uptime(void) {
+ _cleanup_fclose_ FILE *f = NULL;
+ char str[32];
+ double uptime;
+
+ f = fopen("/proc/uptime", "r");
+
+ if (!f)
+ return;
+ if (!fscanf(f, "%s %*s", str))
+ return;
+
+ uptime = strtod(str, NULL);
+
+ log_start = gettime_ns();
+
+ /* start graph at kernel boot time */
+ if (arg_relative)
+ graph_start = log_start;
+ else
+ graph_start = log_start - uptime;
+}
+
+static char *bufgetline(char *buf) {
+ char *c;
+
+ if (!buf)
+ return NULL;
+
+ c = strchr(buf, '\n');
+ if (c)
+ c++;
+ return c;
+}
+
+static int pid_cmdline_strscpy(char *buffer, size_t buf_len, int pid) {
+ char filename[PATH_MAX];
+ _cleanup_close_ int fd=-1;
+ ssize_t n;
+
+ sprintf(filename, "%d/cmdline", pid);
+ fd = openat(procfd, filename, O_RDONLY);
+ if (fd < 0)
+ return -errno;
+
+ n = read(fd, buffer, buf_len-1);
+ if (n > 0) {
+ int i;
+ for (i = 0; i < n; i++)
+ if (buffer[i] == '\0')
+ buffer[i] = ' ';
+ buffer[n] = '\0';
+ }
+ return 0;
+}
+
+void log_sample(int sample, struct list_sample_data **ptr) {
+ static int vmstat;
+ static int schedstat;
+ char buf[4096];
+ char key[256];
+ char val[256];
+ char rt[256];
+ char wt[256];
+ char *m;
+ int c;
+ int p;
+ int mod;
+ static int e_fd;
+ ssize_t s;
+ ssize_t n;
+ struct dirent *ent;
+ int fd;
+ struct list_sample_data *sampledata;
+ struct ps_sched_struct *ps_prev = NULL;
+
+
+
+ sampledata = *ptr;
+
+ /* all the per-process stuff goes here */
+ if (!proc) {
+ /* find all processes */
+ proc = opendir("/proc");
+ if (!proc)
+ return;
+ procfd = dirfd(proc);
+ } else {
+ rewinddir(proc);
+ }
+
+ if (!vmstat) {
+ /* block stuff */
+ vmstat = openat(procfd, "vmstat", O_RDONLY);
+ if (vmstat == -1) {
+ perror("open /proc/vmstat");
+ exit (EXIT_FAILURE);
+ }
+ }
+
+ n = pread(vmstat, buf, sizeof(buf) - 1, 0);
+ if (n <= 0) {
+ close(vmstat);
+ return;
+ }
+ buf[n] = '\0';
+
+ m = buf;
+ while (m) {
+ if (sscanf(m, "%s %s", key, val) < 2)
+ goto vmstat_next;
+ if (streq(key, "pgpgin"))
+ sampledata->blockstat.bi = atoi(val);
+ if (streq(key, "pgpgout")) {
+ sampledata->blockstat.bo = atoi(val);
+ break;
+ }
+vmstat_next:
+ m = bufgetline(m);
+ if (!m)
+ break;
+ }
+
+ if (!schedstat) {
+ /* overall CPU utilization */
+ schedstat = openat(procfd, "schedstat", O_RDONLY);
+ if (schedstat == -1) {
+ perror("open /proc/schedstat");
+ exit (EXIT_FAILURE);
+ }
+ }
+
+ n = pread(schedstat, buf, sizeof(buf) - 1, 0);
+ if (n <= 0) {
+ close(schedstat);
+ return;
+ }
+ buf[n] = '\0';
+
+ m = buf;
+ while (m) {
+ if (sscanf(m, "%s %*s %*s %*s %*s %*s %*s %s %s", key, rt, wt) < 3)
+ goto schedstat_next;
+
+ if (strstr(key, "cpu")) {
+ c = atoi((const char*)(key+3));
+ if (c > MAXCPUS)
+ /* Oops, we only have room for MAXCPUS data */
+ break;
+ sampledata->runtime[c] = atoll(rt);
+ sampledata->waittime[c] = atoll(wt);
+
+ if (c == cpus)
+ cpus = c + 1;
+ }
+schedstat_next:
+ m = bufgetline(m);
+ if (!m)
+ break;
+ }
+
+ if (arg_entropy) {
+ if (!e_fd) {
+ e_fd = openat(procfd, "sys/kernel/random/entropy_avail", O_RDONLY);
+ }
+
+ if (e_fd) {
+ n = pread(e_fd, buf, sizeof(buf) - 1, 0);
+ if (n > 0) {
+ buf[n] = '\0';
+ sampledata->entropy_avail = atoi(buf);
+ }
+ }
+ }
+
+ while ((ent = readdir(proc)) != NULL) {
+ char filename[PATH_MAX];
+ int pid;
+ struct ps_struct *ps;
+
+ if ((ent->d_name[0] < '0') || (ent->d_name[0] > '9'))
+ continue;
+
+ pid = atoi(ent->d_name);
+
+ if (pid >= MAXPIDS)
+ continue;
+
+ ps = ps_first;
+ while (ps->next_ps) {
+ ps = ps->next_ps;
+ if (ps->pid == pid)
+ break;
+ }
+
+ /* end of our LL? then append a new record */
+ if (ps->pid != pid) {
+ _cleanup_fclose_ FILE *st = NULL;
+ char t[32];
+ struct ps_struct *parent;
+
+ ps->next_ps = calloc(1, sizeof(struct ps_struct));
+ if (!ps->next_ps) {
+ perror("calloc(ps_struct)");
+ exit (EXIT_FAILURE);
+ }
+ ps = ps->next_ps;
+ ps->pid = pid;
+
+ ps->sample = calloc(1, sizeof(struct ps_sched_struct));
+ if (!ps->sample) {
+ perror("calloc(ps_struct)");
+ exit (EXIT_FAILURE);
+ }
+ ps->sample->sampledata = sampledata;
+
+ pscount++;
+
+ /* mark our first sample */
+ ps->first = ps->sample;
+ ps->sample->runtime = atoll(rt);
+ ps->sample->waittime = atoll(wt);
+
+ /* get name, start time */
+ if (!ps->sched) {
+ sprintf(filename, "%d/sched", pid);
+ ps->sched = openat(procfd, filename, O_RDONLY);
+ if (ps->sched == -1)
+ continue;
+ }
+
+ s = pread(ps->sched, buf, sizeof(buf) - 1, 0);
+ if (s <= 0) {
+ close(ps->sched);
+ continue;
+ }
+ buf[s] = '\0';
+
+ if (!sscanf(buf, "%s %*s %*s", key))
+ continue;
+
+ strscpy(ps->name, sizeof(ps->name), key);
+
+ /* cmdline */
+ if (arg_show_cmdline)
+ pid_cmdline_strscpy(ps->name, sizeof(ps->name), pid);
+
+ /* discard line 2 */
+ m = bufgetline(buf);
+ if (!m)
+ continue;
+
+ m = bufgetline(m);
+ if (!m)
+ continue;
+
+ if (!sscanf(m, "%*s %*s %s", t))
+ continue;
+
+ ps->starttime = strtod(t, NULL) / 1000.0;
+
+ /* ppid */
+ sprintf(filename, "%d/stat", pid);
+ fd = openat(procfd, filename, O_RDONLY);
+ st = fdopen(fd, "r");
+ if (!st)
+ continue;
+ if (!fscanf(st, "%*s %*s %*s %i", &p)) {
+ continue;
+ }
+ ps->ppid = p;
+
+ /*
+ * setup child pointers
+ *
+ * these are used to paint the tree coherently later
+ * each parent has a LL of children, and a LL of siblings
+ */
+ if (pid == 1)
+ continue; /* nothing to do for init atm */
+
+ /* kthreadd has ppid=0, which breaks our tree ordering */
+ if (ps->ppid == 0)
+ ps->ppid = 1;
+
+ parent = ps_first;
+ while ((parent->next_ps && parent->pid != ps->ppid))
+ parent = parent->next_ps;
+
+ if ((!parent) || (parent->pid != ps->ppid)) {
+ /* orphan */
+ ps->ppid = 1;
+ parent = ps_first->next_ps;
+ }
+
+ ps->parent = parent;
+
+ if (!parent->children) {
+ /* it's the first child */
+ parent->children = ps;
+ } else {
+ /* walk all children and append */
+ struct ps_struct *children;
+ children = parent->children;
+ while (children->next)
+ children = children->next;
+ children->next = ps;
+ }
+ }
+
+ /* else -> found pid, append data in ps */
+
+ /* below here is all continuous logging parts - we get here on every
+ * iteration */
+
+ /* rt, wt */
+ if (!ps->schedstat) {
+ sprintf(filename, "%d/schedstat", pid);
+ ps->schedstat = openat(procfd, filename, O_RDONLY);
+ if (ps->schedstat == -1)
+ continue;
+ }
+ s = pread(ps->schedstat, buf, sizeof(buf) - 1, 0);
+ if (s <= 0) {
+ /* clean up our file descriptors - assume that the process exited */
+ close(ps->schedstat);
+ if (ps->sched)
+ close(ps->sched);
+ //if (ps->smaps)
+ // fclose(ps->smaps);
+ continue;
+ }
+ buf[s] = '\0';
+
+ if (!sscanf(buf, "%s %s %*s", rt, wt))
+ continue;
+
+ ps->sample->next = calloc(1, sizeof(struct ps_sched_struct));
+ if (!ps->sample) {
+ perror("calloc(ps_struct)");
+ exit (EXIT_FAILURE);
+ }
+ ps->sample->next->prev = ps->sample;
+ ps->sample = ps->sample->next;
+ ps->last = ps->sample;
+ ps->sample->runtime = atoll(rt);
+ ps->sample->waittime = atoll(wt);
+ ps->sample->sampledata = sampledata;
+ ps->sample->ps_new = ps;
+ if (ps_prev) {
+ ps_prev->cross = ps->sample;
+ }
+ ps_prev = ps->sample;
+ ps->total = (ps->last->runtime - ps->first->runtime)
+ / 1000000000.0;
+
+ if (!arg_pss)
+ goto catch_rename;
+
+ /* Pss */
+ if (!ps->smaps) {
+ sprintf(filename, "%d/smaps", pid);
+ fd = openat(procfd, filename, O_RDONLY);
+ ps->smaps = fdopen(fd, "r");
+ if (!ps->smaps)
+ continue;
+ setvbuf(ps->smaps, smaps_buf, _IOFBF, sizeof(smaps_buf));
+ }
+ else {
+ rewind(ps->smaps);
+ }
+ /* test to see if we need to skip another field */
+ if (skip == 0) {
+ if (fgets(buf, sizeof(buf), ps->smaps) == NULL) {
+ continue;
+ }
+ if (fread(buf, 1, 28 * 15, ps->smaps) != (28 * 15)) {
+ continue;
+ }
+ if (buf[392] == 'V') {
+ skip = 2;
+ }
+ else {
+ skip = 1;
+ }
+ rewind(ps->smaps);
+ }
+ while (1) {
+ int pss_kb;
+
+ /* skip one line, this contains the object mapped. */
+ if (fgets(buf, sizeof(buf), ps->smaps) == NULL) {
+ break;
+ }
+ /* then there's a 28 char 14 line block */
+ if (fread(buf, 1, 28 * 14, ps->smaps) != 28 * 14) {
+ break;
+ }
+ pss_kb = atoi(&buf[61]);
+ ps->sample->pss += pss_kb;
+
+ /* skip one more line if this is a newer kernel */
+ if (skip == 2) {
+ if (fgets(buf, sizeof(buf), ps->smaps) == NULL)
+ break;
+ }
+ }
+ if (ps->sample->pss > ps->pss_max)
+ ps->pss_max = ps->sample->pss;
+
+catch_rename:
+ /* catch process rename, try to randomize time */
+ mod = (arg_hz < 4.0) ? 4.0 : (arg_hz / 4.0);
+ if (((samples - ps->pid) + pid) % (int)(mod) == 0) {
+
+ /* re-fetch name */
+ /* get name, start time */
+ if (!ps->sched) {
+ sprintf(filename, "%d/sched", pid);
+ ps->sched = openat(procfd, filename, O_RDONLY);
+ if (ps->sched == -1)
+ continue;
+ }
+ s = pread(ps->sched, buf, sizeof(buf) - 1, 0);
+ if (s <= 0) {
+ /* clean up file descriptors */
+ close(ps->sched);
+ if (ps->schedstat)
+ close(ps->schedstat);
+ //if (ps->smaps)
+ // fclose(ps->smaps);
+ continue;
+ }
+ buf[s] = '\0';
+
+ if (!sscanf(buf, "%s %*s %*s", key))
+ continue;
+
+ strscpy(ps->name, sizeof(ps->name), key);
+
+ /* cmdline */
+ if (arg_show_cmdline)
+ pid_cmdline_strscpy(ps->name, sizeof(ps->name), pid);
+ }
+ }
+}
diff --git a/src/bootchart/store.h b/src/bootchart/store.h
new file mode 100644
index 0000000000..7c8ad284da
--- /dev/null
+++ b/src/bootchart/store.h
@@ -0,0 +1,35 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright (C) 2009-2013 Intel Coproration
+
+ Authors:
+ Auke Kok <auke-jan.h.kok@intel.com>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <dirent.h>
+#include "bootchart.h"
+
+extern DIR *proc;
+extern int procfd;
+
+double gettime_ns(void);
+void log_uptime(void);
+void log_sample(int sample, struct list_sample_data **ptr);
diff --git a/src/bootchart/svg.c b/src/bootchart/svg.c
new file mode 100644
index 0000000000..859cf81c22
--- /dev/null
+++ b/src/bootchart/svg.c
@@ -0,0 +1,1332 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright (C) 2009-2013 Intel Coproration
+
+ Authors:
+ Auke Kok <auke-jan.h.kok@intel.com>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+ ***/
+
+#include <stdio.h>
+#include <stdarg.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <limits.h>
+#include <unistd.h>
+#include <sys/utsname.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+
+#include "util.h"
+#include "macro.h"
+#include "store.h"
+#include "svg.h"
+#include "bootchart.h"
+#include "list.h"
+
+#define time_to_graph(t) ((t) * arg_scale_x)
+#define ps_to_graph(n) ((n) * arg_scale_y)
+#define kb_to_graph(m) ((m) * arg_scale_y * 0.0001)
+#define to_color(n) (192.0 - ((n) * 192.0))
+
+static char str[8092];
+
+#define svg(a...) do { snprintf(str, 8092, ## a); fputs(str, of); fflush(of); } while (0)
+
+static const char * const colorwheel[12] = {
+ "rgb(255,32,32)", // red
+ "rgb(32,192,192)", // cyan
+ "rgb(255,128,32)", // orange
+ "rgb(128,32,192)", // blue-violet
+ "rgb(255,255,32)", // yellow
+ "rgb(192,32,128)", // red-violet
+ "rgb(32,255,32)", // green
+ "rgb(255,64,32)", // red-orange
+ "rgb(32,32,255)", // blue
+ "rgb(255,192,32)", // yellow-orange
+ "rgb(192,32,192)", // violet
+ "rgb(32,192,32)" // yellow-green
+};
+
+static double idletime = -1.0;
+static int pfiltered = 0;
+static int pcount = 0;
+static int kcount = 0;
+static float psize = 0;
+static float ksize = 0;
+static float esize = 0;
+static struct list_sample_data *sampledata;
+static struct list_sample_data *prev_sampledata;
+extern struct list_sample_data *head;
+
+static void svg_header(void) {
+ float w;
+ float h;
+ struct list_sample_data *sampledata_last;
+
+ sampledata = head;
+ LIST_FIND_TAIL(struct list_sample_data, link, sampledata, head);
+ sampledata_last = head;
+ LIST_FOREACH_BEFORE(link, sampledata, head) {
+ sampledata_last = sampledata;
+ }
+
+ /* min width is about 1600px due to the label */
+ w = 150.0 + 10.0 + time_to_graph(sampledata_last->sampletime - graph_start);
+ w = ((w < 1600.0) ? 1600.0 : w);
+
+ /* height is variable based on pss, psize, ksize */
+ h = 400.0 + (arg_scale_y * 30.0) /* base graphs and title */
+ + (arg_pss ? (100.0 * arg_scale_y) + (arg_scale_y * 7.0) : 0.0) /* pss estimate */
+ + psize + ksize + esize;
+
+ svg("<?xml version=\"1.0\" standalone=\"no\"?>\n");
+ svg("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" ");
+ svg("\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n");
+
+ //svg("<g transform=\"translate(10,%d)\">\n", 1000 + 150 + (pcount * 20));
+ svg("<svg width=\"%.0fpx\" height=\"%.0fpx\" version=\"1.1\" ",
+ w, h);
+ svg("xmlns=\"http://www.w3.org/2000/svg\">\n\n");
+
+ /* write some basic info as a comment, including some help */
+ svg("<!-- This file is a bootchart SVG file. It is best rendered in a browser -->\n");
+ svg("<!-- such as Chrome, Chromium, or Firefox. Other applications that -->\n");
+ svg("<!-- render these files properly but more slowly are ImageMagick, gimp, -->\n");
+ svg("<!-- inkscape, etc. To display the files on your system, just point -->\n");
+ svg("<!-- your browser to file:///run/log/ and click. This bootchart was -->\n\n");
+
+ svg("<!-- generated by bootchart version %s, running with options: -->\n", VERSION);
+ svg("<!-- hz=\"%f\" n=\"%d\" -->\n", arg_hz, arg_samples_len);
+ svg("<!-- x=\"%f\" y=\"%f\" -->\n", arg_scale_x, arg_scale_y);
+ svg("<!-- rel=\"%d\" f=\"%d\" -->\n", arg_relative, arg_filter);
+ svg("<!-- p=\"%d\" e=\"%d\" -->\n", arg_pss, arg_entropy);
+ svg("<!-- o=\"%s\" i=\"%s\" -->\n\n", arg_output_path, arg_init_path);
+
+ /* style sheet */
+ svg("<defs>\n <style type=\"text/css\">\n <![CDATA[\n");
+
+ svg(" rect { stroke-width: 1; }\n");
+ svg(" rect.cpu { fill: rgb(64,64,240); stroke-width: 0; fill-opacity: 0.7; }\n");
+ svg(" rect.wait { fill: rgb(240,240,0); stroke-width: 0; fill-opacity: 0.7; }\n");
+ svg(" rect.bi { fill: rgb(240,128,128); stroke-width: 0; fill-opacity: 0.7; }\n");
+ svg(" rect.bo { fill: rgb(192,64,64); stroke-width: 0; fill-opacity: 0.7; }\n");
+ svg(" rect.ps { fill: rgb(192,192,192); stroke: rgb(128,128,128); fill-opacity: 0.7; }\n");
+ svg(" rect.krnl { fill: rgb(240,240,0); stroke: rgb(128,128,128); fill-opacity: 0.7; }\n");
+ svg(" rect.box { fill: rgb(240,240,240); stroke: rgb(192,192,192); }\n");
+ svg(" rect.clrw { stroke-width: 0; fill-opacity: 0.7;}\n");
+ svg(" line { stroke: rgb(64,64,64); stroke-width: 1; }\n");
+ svg("// line.sec1 { }\n");
+ svg(" line.sec5 { stroke-width: 2; }\n");
+ svg(" line.sec01 { stroke: rgb(224,224,224); stroke-width: 1; }\n");
+ svg(" line.dot { stroke-dasharray: 2 4; }\n");
+ svg(" line.idle { stroke: rgb(64,64,64); stroke-dasharray: 10 6; stroke-opacity: 0.7; }\n");
+
+ svg(" .run { font-size: 8; font-style: italic; }\n");
+ svg(" text { font-family: Verdana, Helvetica; font-size: 10; }\n");
+ svg(" text.sec { font-size: 8; }\n");
+ svg(" text.t1 { font-size: 24; }\n");
+ svg(" text.t2 { font-size: 12; }\n");
+ svg(" text.idle { font-size: 18; }\n");
+
+ svg(" ]]>\n </style>\n</defs>\n\n");
+}
+
+static void svg_title(const char *build) {
+ char cmdline[256] = "";
+ char filename[PATH_MAX];
+ char buf[256];
+ char rootbdev[16] = "Unknown";
+ char model[256] = "Unknown";
+ char date[256] = "Unknown";
+ char cpu[256] = "Unknown";
+ char *c;
+ FILE *f;
+ time_t t;
+ int fd;
+ struct utsname uts;
+
+ /* grab /proc/cmdline */
+ fd = openat(procfd, "cmdline", O_RDONLY);
+ f = fdopen(fd, "r");
+ if (f) {
+ if (!fgets(cmdline, 255, f))
+ sprintf(cmdline, "Unknown");
+ fclose(f);
+ }
+
+ /* extract root fs so we can find disk model name in sysfs */
+ /* FIXME: this works only in the simple case */
+ c = strstr(cmdline, "root=/dev/");
+ if (c) {
+ strncpy(rootbdev, &c[10], 3);
+ rootbdev[3] = '\0';
+ sprintf(filename, "block/%s/device/model", rootbdev);
+ fd = openat(sysfd, filename, O_RDONLY);
+ f = fdopen(fd, "r");
+ if (f) {
+ if (!fgets(model, 255, f))
+ fprintf(stderr, "Error reading disk model for %s\n", rootbdev);
+ fclose(f);
+ }
+ }
+
+ /* various utsname parameters */
+ if (uname(&uts))
+ fprintf(stderr, "Error getting uname info\n");
+
+ /* date */
+ t = time(NULL);
+ strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %z", localtime(&t));
+
+ /* CPU type */
+ fd = openat(procfd, "cpuinfo", O_RDONLY);
+ f = fdopen(fd, "r");
+ if (f) {
+ while (fgets(buf, 255, f)) {
+ if (strstr(buf, "model name")) {
+ strncpy(cpu, &buf[13], 255);
+ break;
+ }
+ }
+ fclose(f);
+ }
+
+ svg("<text class=\"t1\" x=\"0\" y=\"30\">Bootchart for %s - %s</text>\n",
+ uts.nodename, date);
+ svg("<text class=\"t2\" x=\"20\" y=\"50\">System: %s %s %s %s</text>\n",
+ uts.sysname, uts.release, uts.version, uts.machine);
+ svg("<text class=\"t2\" x=\"20\" y=\"65\">CPU: %s</text>\n",
+ cpu);
+ svg("<text class=\"t2\" x=\"20\" y=\"80\">Disk: %s</text>\n",
+ model);
+ svg("<text class=\"t2\" x=\"20\" y=\"95\">Boot options: %s</text>\n",
+ cmdline);
+ svg("<text class=\"t2\" x=\"20\" y=\"110\">Build: %s</text>\n",
+ build);
+ svg("<text class=\"t2\" x=\"20\" y=\"125\">Log start time: %.03fs</text>\n", log_start);
+ svg("<text class=\"t2\" x=\"20\" y=\"140\">Idle time: ");
+
+ if (idletime >= 0.0)
+ svg("%.03fs", idletime);
+ else
+ svg("Not detected");
+ svg("</text>\n");
+ svg("<text class=\"sec\" x=\"20\" y=\"155\">Graph data: %.03f samples/sec, recorded %i total, dropped %i samples, %i processes, %i filtered</text>\n",
+ arg_hz, arg_samples_len, overrun, pscount, pfiltered);
+}
+
+static void svg_graph_box(int height) {
+ double d = 0.0;
+ int i = 0;
+ double finalsample = 0.0;
+ struct list_sample_data *sampledata_last;
+
+ sampledata_last = head;
+ LIST_FOREACH_BEFORE(link, sampledata, head) {
+ sampledata_last = sampledata;
+ }
+
+ finalsample = sampledata_last->sampletime;
+
+ /* outside box, fill */
+ svg("<rect class=\"box\" x=\"%.03f\" y=\"0\" width=\"%.03f\" height=\"%.03f\" />\n",
+ time_to_graph(0.0),
+ time_to_graph(finalsample - graph_start),
+ ps_to_graph(height));
+
+ for (d = graph_start; d <= finalsample;
+ d += (arg_scale_x < 2.0 ? 60.0 : arg_scale_x < 10.0 ? 1.0 : 0.1)) {
+ /* lines for each second */
+ if (i % 50 == 0)
+ svg(" <line class=\"sec5\" x1=\"%.03f\" y1=\"0\" x2=\"%.03f\" y2=\"%.03f\" />\n",
+ time_to_graph(d - graph_start),
+ time_to_graph(d - graph_start),
+ ps_to_graph(height));
+ else if (i % 10 == 0)
+ svg(" <line class=\"sec1\" x1=\"%.03f\" y1=\"0\" x2=\"%.03f\" y2=\"%.03f\" />\n",
+ time_to_graph(d - graph_start),
+ time_to_graph(d - graph_start),
+ ps_to_graph(height));
+ else
+ svg(" <line class=\"sec01\" x1=\"%.03f\" y1=\"0\" x2=\"%.03f\" y2=\"%.03f\" />\n",
+ time_to_graph(d - graph_start),
+ time_to_graph(d - graph_start),
+ ps_to_graph(height));
+
+ /* time label */
+ if (i % 10 == 0)
+ svg(" <text class=\"sec\" x=\"%.03f\" y=\"%.03f\" >%.01fs</text>\n",
+ time_to_graph(d - graph_start),
+ -5.0,
+ d - graph_start);
+
+ i++;
+ }
+}
+
+/* xml comments must not contain "--" */
+static char* xml_comment_encode(const char* name) {
+ char *enc_name, *p;
+
+ enc_name = strdup(name);
+ if (!enc_name)
+ return NULL;
+
+ for (p = enc_name; *p; p++)
+ if (p[0] == '-' && p[1] == '-')
+ p[1] = '_';
+
+ return enc_name;
+}
+
+static void svg_pss_graph(void) {
+ struct ps_struct *ps;
+ int i;
+ struct list_sample_data *sampledata_last;
+
+ sampledata_last = head;
+ LIST_FOREACH_BEFORE(link, sampledata, head) {
+ sampledata_last = sampledata;
+ }
+
+
+ svg("\n\n<!-- Pss memory size graph -->\n");
+
+ svg("\n <text class=\"t2\" x=\"5\" y=\"-15\">Memory allocation - Pss</text>\n");
+
+ /* vsize 1000 == 1000mb */
+ svg_graph_box(100);
+ /* draw some hlines for usable memory sizes */
+ for (i = 100000; i < 1000000; i += 100000) {
+ svg(" <line class=\"sec01\" x1=\"%.03f\" y1=\"%.0f\" x2=\"%.03f\" y2=\"%.0f\"/>\n",
+ time_to_graph(.0),
+ kb_to_graph(i),
+ time_to_graph(sampledata_last->sampletime - graph_start),
+ kb_to_graph(i));
+ svg(" <text class=\"sec\" x=\"%.03f\" y=\"%.0f\">%dM</text>\n",
+ time_to_graph(sampledata_last->sampletime - graph_start) + 5,
+ kb_to_graph(i), (1000000 - i) / 1000);
+ }
+ svg("\n");
+
+ /* now plot the graph itself */
+ i = 1;
+ prev_sampledata = head;
+ LIST_FOREACH_BEFORE(link, sampledata, head) {
+ int bottom;
+ int top;
+ struct ps_sched_struct *cross_place;
+
+ bottom = 0;
+ top = 0;
+
+ /* put all the small pss blocks into the bottom */
+ ps = ps_first;
+ while (ps->next_ps) {
+ ps = ps->next_ps;
+ if (!ps)
+ continue;
+ ps->sample = ps->first;
+ while (ps->sample->next) {
+ ps->sample = ps->sample->next;
+ if (ps->sample->sampledata == sampledata)
+ break;
+ }
+ if (ps->sample->sampledata == sampledata) {
+ if (ps->sample->pss <= (100 * arg_scale_y))
+ top += ps->sample->pss;
+ break;
+ }
+ }
+ while (ps->sample->cross) {
+ cross_place = ps->sample->cross;
+ ps = ps->sample->cross->ps_new;
+ ps->sample = cross_place;
+ if (ps->sample->pss <= (100 * arg_scale_y))
+ top += ps->sample->pss;
+ }
+
+ svg(" <rect class=\"clrw\" style=\"fill: %s\" x=\"%.03f\" y=\"%.03f\" width=\"%.03f\" height=\"%.03f\" />\n",
+ "rgb(64,64,64)",
+ time_to_graph(prev_sampledata->sampletime - graph_start),
+ kb_to_graph(1000000.0 - top),
+ time_to_graph(sampledata->sampletime - prev_sampledata->sampletime),
+ kb_to_graph(top - bottom));
+ bottom = top;
+
+ /* now plot the ones that are of significant size */
+ ps = ps_first;
+ while (ps->next_ps) {
+ ps = ps->next_ps;
+ if (!ps)
+ continue;
+ ps->sample = ps->first;
+ while (ps->sample->next) {
+ ps->sample = ps->sample->next;
+ if (ps->sample->sampledata == sampledata)
+ break;
+ }
+ /* don't draw anything smaller than 2mb */
+ if (ps->sample->sampledata == sampledata) {
+ if (ps->sample->pss > (100 * arg_scale_y)) {
+ top = bottom + ps->sample->pss;
+ svg(" <rect class=\"clrw\" style=\"fill: %s\" x=\"%.03f\" y=\"%.03f\" width=\"%.03f\" height=\"%.03f\" />\n",
+ colorwheel[ps->pid % 12],
+ time_to_graph(prev_sampledata->sampletime - graph_start),
+ kb_to_graph(1000000.0 - top),
+ time_to_graph(sampledata->sampletime - prev_sampledata->sampletime),
+ kb_to_graph(top - bottom));
+ bottom = top;
+ }
+ break;
+ }
+ }
+ while ((cross_place = ps->sample->cross)) {
+ ps = ps->sample->cross->ps_new;
+ ps->sample = cross_place;
+ if (ps->sample->pss > (100 * arg_scale_y)) {
+ top = bottom + ps->sample->pss;
+ svg(" <rect class=\"clrw\" style=\"fill: %s\" x=\"%.03f\" y=\"%.03f\" width=\"%.03f\" height=\"%.03f\" />\n",
+ colorwheel[ps->pid % 12],
+ time_to_graph(prev_sampledata->sampletime - graph_start),
+ kb_to_graph(1000000.0 - top),
+ time_to_graph(sampledata->sampletime - prev_sampledata->sampletime),
+ kb_to_graph(top - bottom));
+ bottom = top;
+ }
+ }
+ prev_sampledata = sampledata;
+ i++;
+ }
+
+ /* overlay all the text labels */
+ i = 1;
+ LIST_FOREACH_BEFORE(link, sampledata, head) {
+ int bottom;
+ int top;
+ struct ps_sched_struct *prev_sample;
+ struct ps_sched_struct *cross_place;
+
+ bottom = 0;
+ top = 0;
+
+ /* put all the small pss blocks into the bottom */
+ ps = ps_first->next_ps;
+ while (ps->next_ps) {
+ ps = ps->next_ps;
+ if (!ps)
+ continue;
+ ps->sample = ps->first;
+ while (ps->sample->next) {
+ ps->sample = ps->sample->next;
+ if (ps->sample->sampledata == sampledata)
+ break;
+ }
+ if (ps->sample->sampledata == sampledata) {
+ if (ps->sample->pss <= (100 * arg_scale_y))
+ top += ps->sample->pss;
+ break;
+ }
+ }
+ while ((cross_place = ps->sample->cross)) {
+ ps = ps->sample->cross->ps_new;
+ ps->sample = cross_place;
+ if (ps->sample->pss <= (100 * arg_scale_y))
+ top += ps->sample->pss;
+ }
+ bottom = top;
+
+ /* now plot the ones that are of significant size */
+ ps = ps_first;
+ while (ps->next_ps) {
+ prev_sample = ps->sample;
+ ps = ps->next_ps;
+ if (!ps)
+ continue;
+ ps->sample = ps->first;
+ while (ps->sample->next) {
+ prev_sample = ps->sample;
+ ps->sample = ps->sample->next;
+ if (ps->sample->sampledata == sampledata)
+ break;
+ }
+ /* don't draw anything smaller than 2mb */
+ if (ps->sample->sampledata == sampledata) {
+ if (ps->sample->pss > (100 * arg_scale_y)) {
+ top = bottom + ps->sample->pss;
+ /* draw a label with the process / PID */
+ if ((i == 1) || (prev_sample->pss <= (100 * arg_scale_y)))
+ svg(" <text x=\"%.03f\" y=\"%.03f\"><![CDATA[%s]]> [%i]</text>\n",
+ time_to_graph(sampledata->sampletime - graph_start),
+ kb_to_graph(1000000.0 - bottom - ((top - bottom) / 2)),
+ ps->name,
+ ps->pid);
+ bottom = top;
+ }
+ break;
+ }
+ }
+ while ((cross_place = ps->sample->cross)) {
+ ps = ps->sample->cross->ps_new;
+ ps->sample = cross_place;
+ prev_sample = ps->sample->prev;
+ if (ps->sample->pss > (100 * arg_scale_y)) {
+ top = bottom + ps->sample->pss;
+ /* draw a label with the process / PID */
+ if ((i == 1) || (prev_sample->pss <= (100 * arg_scale_y)))
+ svg(" <text x=\"%.03f\" y=\"%.03f\"><![CDATA[%s]]> [%i]</text>\n",
+ time_to_graph(sampledata->sampletime - graph_start),
+ kb_to_graph(1000000.0 - bottom - ((top - bottom) / 2)),
+ ps->name,
+ ps->pid);
+ bottom = top;
+ }
+ }
+ i++;
+ }
+
+ /* debug output - full data dump */
+ svg("\n\n<!-- PSS map - csv format -->\n");
+ ps = ps_first;
+ while (ps->next_ps) {
+ _cleanup_free_ char *enc_name = NULL;
+ ps = ps->next_ps;
+ if (!ps)
+ continue;
+
+ enc_name = xml_comment_encode(ps->name);
+ if(!enc_name)
+ continue;
+
+ svg("<!-- %s [%d] pss=", enc_name, ps->pid);
+
+ ps->sample = ps->first;
+ while (ps->sample->next) {
+ ps->sample = ps->sample->next;
+ svg("%d," , ps->sample->pss);
+ }
+ svg(" -->\n");
+ }
+
+}
+
+static void svg_io_bi_bar(void) {
+ double max = 0.0;
+ double range;
+ int max_here = 0;
+ int i;
+ int k;
+ struct list_sample_data *start_sampledata = sampledata;
+ struct list_sample_data *stop_sampledata = sampledata;
+
+ svg("<!-- IO utilization graph - In -->\n");
+
+ svg("<text class=\"t2\" x=\"5\" y=\"-15\">IO utilization - read</text>\n");
+
+ /*
+ * calculate rounding range
+ *
+ * We need to round IO data since IO block data is not updated on
+ * each poll. Applying a smoothing function loses some burst data,
+ * so keep the smoothing range short.
+ */
+ range = 0.25 / (1.0 / arg_hz);
+ if (range < 2.0)
+ range = 2.0; /* no smoothing */
+
+ /* surrounding box */
+ svg_graph_box(5);
+
+ /* find the max IO first */
+ i = 1;
+ LIST_FOREACH_BEFORE(link, sampledata, head) {
+ int start;
+ int stop;
+ int diff;
+ double tot;
+
+ start = MAX(i - ((range / 2) - 1), 0);
+ stop = MIN(i + (range / 2), samples - 1);
+ diff = (stop - start);
+
+ start_sampledata = sampledata;
+ stop_sampledata = sampledata;
+
+ for (k=0;(k<((range/2)-1))&&(start_sampledata->link_next);k++)
+ start_sampledata = start_sampledata->link_next;
+ for (k=0;(k<(range/2))&&(stop_sampledata->link_prev);k++)
+ stop_sampledata = stop_sampledata->link_prev;
+
+ tot = (double)(stop_sampledata->blockstat.bi - start_sampledata->blockstat.bi)
+ / diff;
+
+ if (tot > max) {
+ max = tot;
+ max_here = i;
+ }
+
+ tot = (double)(stop_sampledata->blockstat.bo - start_sampledata->blockstat.bo)
+ / diff;
+
+ if (tot > max)
+ max = tot;
+
+ i++;
+ }
+
+ /* plot bi */
+ i = 1;
+ prev_sampledata = head;
+ LIST_FOREACH_BEFORE(link, sampledata, head) {
+ int start;
+ int stop;
+ int diff;
+ double tot;
+ double pbi;
+
+ tot = 0;
+ pbi = 0;
+
+ start = MAX(i - ((range / 2) - 1), 0);
+ stop = MIN(i + (range / 2), samples);
+ diff = (stop - start);
+
+ start_sampledata = sampledata;
+ stop_sampledata = sampledata;
+
+ for (k=0;(k<((range/2)-1))&&(start_sampledata->link_next);k++)
+ start_sampledata = start_sampledata->link_next;
+ for (k=0;(k<(range/2))&&(stop_sampledata->link_prev);k++)
+ stop_sampledata = stop_sampledata->link_prev;
+
+ tot = (double)(stop_sampledata->blockstat.bi - start_sampledata->blockstat.bi)
+ / diff;
+
+ if (max > 0)
+ pbi = tot / max;
+
+ if (pbi > 0.001)
+ svg("<rect class=\"bi\" x=\"%.03f\" y=\"%.03f\" width=\"%.03f\" height=\"%.03f\" />\n",
+ time_to_graph(prev_sampledata->sampletime - graph_start),
+ (arg_scale_y * 5) - (pbi * (arg_scale_y * 5)),
+ time_to_graph(sampledata->sampletime - prev_sampledata->sampletime),
+ pbi * (arg_scale_y * 5));
+
+ /* labels around highest value */
+ if (i == max_here) {
+ svg(" <text class=\"sec\" x=\"%.03f\" y=\"%.03f\">%0.2fmb/sec</text>\n",
+ time_to_graph(sampledata->sampletime - graph_start) + 5,
+ ((arg_scale_y * 5) - (pbi * (arg_scale_y * 5))) + 15,
+ max / 1024.0 / (interval / 1000000000.0));
+ }
+ i++;
+ prev_sampledata = sampledata;
+ }
+}
+
+static void svg_io_bo_bar(void) {
+ double max = 0.0;
+ double range;
+ int max_here = 0;
+ int i;
+ int k;
+ struct list_sample_data *start_sampledata = sampledata;
+ struct list_sample_data *stop_sampledata = sampledata;
+
+ svg("<!-- IO utilization graph - out -->\n");
+
+ svg("<text class=\"t2\" x=\"5\" y=\"-15\">IO utilization - write</text>\n");
+
+ /*
+ * calculate rounding range
+ *
+ * We need to round IO data since IO block data is not updated on
+ * each poll. Applying a smoothing function loses some burst data,
+ * so keep the smoothing range short.
+ */
+ range = 0.25 / (1.0 / arg_hz);
+ if (range < 2.0)
+ range = 2.0; /* no smoothing */
+
+ /* surrounding box */
+ svg_graph_box(5);
+
+ /* find the max IO first */
+ i = 0;
+ LIST_FOREACH_BEFORE(link, sampledata, head) {
+ int start;
+ int stop;
+ int diff;
+ double tot;
+
+ start = MAX(i - ((range / 2) - 1), 0);
+ stop = MIN(i + (range / 2), samples - 1);
+ diff = (stop - start);
+
+ start_sampledata = sampledata;
+ stop_sampledata = sampledata;
+
+ for (k=0;(k<((range/2)-1))&&(start_sampledata->link_next);k++)
+ start_sampledata = start_sampledata->link_next;
+ for (k=0;(k<(range/2))&&(stop_sampledata->link_prev);k++)
+ stop_sampledata = stop_sampledata->link_prev;
+
+ tot = (double)(stop_sampledata->blockstat.bi - start_sampledata->blockstat.bi)
+ / diff;
+ if (tot > max)
+ max = tot;
+ tot = (double)(stop_sampledata->blockstat.bo - start_sampledata->blockstat.bo)
+ / diff;
+ if (tot > max) {
+ max = tot;
+ max_here = i;
+ }
+ i++;
+ }
+
+ /* plot bo */
+ prev_sampledata = head;
+ i=1;
+ LIST_FOREACH_BEFORE(link, sampledata, head) {
+ int start;
+ int stop;
+ int diff;
+ double tot;
+ double pbo;
+
+ tot = 0;
+ pbo = 0;
+
+ start = MAX(i - ((range / 2) - 1), 0);
+ stop = MIN(i + (range / 2), samples);
+ diff = (stop - start);
+
+ start_sampledata = sampledata;
+ stop_sampledata = sampledata;
+
+ for (k=0;(k<((range/2)-1))&&(start_sampledata->link_next);k++)
+ start_sampledata = start_sampledata->link_next;
+ for (k=0;(k<(range/2))&&(stop_sampledata->link_prev);k++)
+ stop_sampledata = stop_sampledata->link_prev;
+
+ tot = (double)(stop_sampledata->blockstat.bo - start_sampledata->blockstat.bo)
+ / diff;
+
+ if (max > 0)
+ pbo = tot / max;
+
+ if (pbo > 0.001)
+ svg("<rect class=\"bo\" x=\"%.03f\" y=\"%.03f\" width=\"%.03f\" height=\"%.03f\" />\n",
+ time_to_graph(prev_sampledata->sampletime - graph_start),
+ (arg_scale_y * 5) - (pbo * (arg_scale_y * 5)),
+ time_to_graph(sampledata->sampletime - prev_sampledata->sampletime),
+ pbo * (arg_scale_y * 5));
+
+ /* labels around highest bo value */
+ if (i == max_here) {
+ svg(" <text class=\"sec\" x=\"%.03f\" y=\"%.03f\">%0.2fmb/sec</text>\n",
+ time_to_graph(sampledata->sampletime - graph_start) + 5,
+ ((arg_scale_y * 5) - (pbo * (arg_scale_y * 5))),
+ max / 1024.0 / (interval / 1000000000.0));
+ }
+ i++;
+ prev_sampledata = sampledata;
+ }
+}
+
+static void svg_cpu_bar(void) {
+
+ svg("<!-- CPU utilization graph -->\n");
+
+ svg("<text class=\"t2\" x=\"5\" y=\"-15\">CPU utilization</text>\n");
+ /* surrounding box */
+ svg_graph_box(5);
+
+ /* bars for each sample, proportional to the CPU util. */
+ prev_sampledata = head;
+ LIST_FOREACH_BEFORE(link, sampledata, head) {
+ int c;
+ double trt;
+ double ptrt;
+
+ ptrt = trt = 0.0;
+
+ for (c = 0; c < cpus; c++)
+ trt += sampledata->runtime[c] - prev_sampledata->runtime[c];
+
+ trt = trt / 1000000000.0;
+
+ trt = trt / (double)cpus;
+
+ if (trt > 0.0)
+ ptrt = trt / (sampledata->sampletime - prev_sampledata->sampletime);
+
+ if (ptrt > 1.0)
+ ptrt = 1.0;
+
+ if (ptrt > 0.001) {
+ svg("<rect class=\"cpu\" x=\"%.03f\" y=\"%.03f\" width=\"%.03f\" height=\"%.03f\" />\n",
+ time_to_graph(prev_sampledata->sampletime - graph_start),
+ (arg_scale_y * 5) - (ptrt * (arg_scale_y * 5)),
+ time_to_graph(sampledata->sampletime - prev_sampledata->sampletime),
+ ptrt * (arg_scale_y * 5));
+ }
+ prev_sampledata = sampledata;
+ }
+}
+
+static void svg_wait_bar(void) {
+
+ svg("<!-- Wait time aggregation box -->\n");
+
+ svg("<text class=\"t2\" x=\"5\" y=\"-15\">CPU wait</text>\n");
+
+ /* surrounding box */
+ svg_graph_box(5);
+
+ /* bars for each sample, proportional to the CPU util. */
+ prev_sampledata = head;
+ LIST_FOREACH_BEFORE(link, sampledata, head) {
+ int c;
+ double twt;
+ double ptwt;
+
+ ptwt = twt = 0.0;
+
+ for (c = 0; c < cpus; c++)
+ twt += sampledata->waittime[c] - prev_sampledata->waittime[c];
+
+ twt = twt / 1000000000.0;
+
+ twt = twt / (double)cpus;
+
+ if (twt > 0.0)
+ ptwt = twt / (sampledata->sampletime - prev_sampledata->sampletime);
+
+ if (ptwt > 1.0)
+ ptwt = 1.0;
+
+ if (ptwt > 0.001) {
+ svg("<rect class=\"wait\" x=\"%.03f\" y=\"%.03f\" width=\"%.03f\" height=\"%.03f\" />\n",
+ time_to_graph(prev_sampledata->sampletime - graph_start),
+ ((arg_scale_y * 5) - (ptwt * (arg_scale_y * 5))),
+ time_to_graph(sampledata->sampletime - prev_sampledata->sampletime),
+ ptwt * (arg_scale_y * 5));
+ }
+ prev_sampledata = sampledata;
+ }
+}
+
+
+static void svg_entropy_bar(void) {
+
+ svg("<!-- entropy pool graph -->\n");
+
+ svg("<text class=\"t2\" x=\"5\" y=\"-15\">Entropy pool size</text>\n");
+ /* surrounding box */
+ svg_graph_box(5);
+
+ /* bars for each sample, scale 0-4096 */
+ prev_sampledata = head;
+ LIST_FOREACH_BEFORE(link, sampledata, head) {
+ /* svg("<!-- entropy %.03f %i -->\n", sampletime[i], entropy_avail[i]); */
+ svg("<rect class=\"cpu\" x=\"%.03f\" y=\"%.03f\" width=\"%.03f\" height=\"%.03f\" />\n",
+ time_to_graph(prev_sampledata->sampletime - graph_start),
+ ((arg_scale_y * 5) - ((sampledata->entropy_avail / 4096.) * (arg_scale_y * 5))),
+ time_to_graph(sampledata->sampletime - prev_sampledata->sampletime),
+ (sampledata->entropy_avail / 4096.) * (arg_scale_y * 5));
+ prev_sampledata = sampledata;
+ }
+}
+
+static struct ps_struct *get_next_ps(struct ps_struct *ps) {
+ /*
+ * walk the list of processes and return the next one to be
+ * painted
+ */
+ if (ps == ps_first)
+ return ps->next_ps;
+
+ /* go deep */
+ if (ps->children)
+ return ps->children;
+
+ /* find siblings */
+ if (ps->next)
+ return ps->next;
+
+ /* go back for parent siblings */
+ while (1) {
+ if (ps->parent)
+ if (ps->parent->next)
+ return ps->parent->next;
+ ps = ps->parent;
+ if (!ps)
+ return ps;
+ }
+
+ return NULL;
+}
+
+static int ps_filter(struct ps_struct *ps) {
+ if (!arg_filter)
+ return 0;
+
+ /* can't draw data when there is only 1 sample (need start + stop) */
+ if (ps->first == ps->last)
+ return -1;
+
+ /* don't filter kthreadd */
+ if (ps->pid == 2)
+ return 0;
+
+ /* drop stuff that doesn't use any real CPU time */
+ if (ps->total <= 0.001)
+ return -1;
+
+ return 0;
+}
+
+static void svg_do_initcall(int count_only) {
+ _cleanup_pclose_ FILE *f = NULL;
+ double t;
+ char func[256];
+ int ret;
+ int usecs;
+
+ /* can't plot initcall when disabled or in relative mode */
+ if (!initcall || arg_relative) {
+ kcount = 0;
+ return;
+ }
+
+ if (!count_only) {
+ svg("<!-- initcall -->\n");
+
+ svg("<text class=\"t2\" x=\"5\" y=\"-15\">Kernel init threads</text>\n");
+ /* surrounding box */
+ svg_graph_box(kcount);
+ }
+
+ kcount = 0;
+
+ /*
+ * Initcall graphing - parses dmesg buffer and displays kernel threads
+ * This somewhat uses the same methods and scaling to show processes
+ * but looks a lot simpler. It's overlaid entirely onto the PS graph
+ * when appropriate.
+ */
+
+ f = popen("dmesg", "r");
+ if (!f)
+ return;
+
+ while (!feof(f)) {
+ int c;
+ int z = 0;
+ char l[256];
+
+ if (fgets(l, sizeof(l) - 1, f) == NULL)
+ continue;
+
+ c = sscanf(l, "[%lf] initcall %s %*s %d %*s %d %*s",
+ &t, func, &ret, &usecs);
+ if (c != 4) {
+ /* also parse initcalls done by module loading */
+ c = sscanf(l, "[%lf] initcall %s %*s %*s %d %*s %d %*s",
+ &t, func, &ret, &usecs);
+ if (c != 4)
+ continue;
+ }
+
+ /* chop the +0xXX/0xXX stuff */
+ while(func[z] != '+')
+ z++;
+ func[z] = 0;
+
+ if (count_only) {
+ /* filter out irrelevant stuff */
+ if (usecs >= 1000)
+ kcount++;
+ continue;
+ }
+
+ svg("<!-- thread=\"%s\" time=\"%.3f\" elapsed=\"%d\" result=\"%d\" -->\n",
+ func, t, usecs, ret);
+
+ if (usecs < 1000)
+ continue;
+
+ /* rect */
+ svg(" <rect class=\"krnl\" x=\"%.03f\" y=\"%.03f\" width=\"%.03f\" height=\"%.03f\" />\n",
+ time_to_graph(t - (usecs / 1000000.0)),
+ ps_to_graph(kcount),
+ time_to_graph(usecs / 1000000.0),
+ ps_to_graph(1));
+
+ /* label */
+ svg(" <text x=\"%.03f\" y=\"%.03f\">%s <tspan class=\"run\">%.03fs</tspan></text>\n",
+ time_to_graph(t - (usecs / 1000000.0)) + 5,
+ ps_to_graph(kcount) + 15,
+ func,
+ usecs / 1000000.0);
+
+ kcount++;
+ }
+}
+
+static void svg_ps_bars(void) {
+ struct ps_struct *ps;
+ int i = 0;
+ int j = 0;
+ int pid;
+ double w = 0.0;
+
+ svg("<!-- Process graph -->\n");
+
+ svg("<text class=\"t2\" x=\"5\" y=\"-15\">Processes</text>\n");
+
+ /* surrounding box */
+ svg_graph_box(pcount);
+
+ /* pass 2 - ps boxes */
+ ps = ps_first;
+ while ((ps = get_next_ps(ps))) {
+ _cleanup_free_ char *enc_name = NULL;
+ double endtime;
+ double starttime;
+ int t;
+
+ enc_name = xml_comment_encode(ps->name);
+ if(!enc_name)
+ continue;
+
+ /* leave some trace of what we actually filtered etc. */
+ svg("<!-- %s [%i] ppid=%i runtime=%.03fs -->\n", enc_name, ps->pid,
+ ps->ppid, ps->total);
+
+ starttime = ps->first->sampledata->sampletime;
+
+ if (!ps_filter(ps)) {
+ /* remember where _to_ our children need to draw a line */
+ ps->pos_x = time_to_graph(starttime - graph_start);
+ ps->pos_y = ps_to_graph(j+1); /* bottom left corner */
+ } else if (ps->parent){
+ /* hook children to our parent coords instead */
+ ps->pos_x = ps->parent->pos_x;
+ ps->pos_y = ps->parent->pos_y;
+
+ /* if this is the last child, we might still need to draw a connecting line */
+ if ((!ps->next) && (ps->parent))
+ svg(" <line class=\"dot\" x1=\"%.03f\" y1=\"%.03f\" x2=\"%.03f\" y2=\"%.03f\" />\n",
+ ps->parent->pos_x,
+ ps_to_graph(j-1) + 10.0, /* whee, use the last value here */
+ ps->parent->pos_x,
+ ps->parent->pos_y);
+ continue;
+ }
+
+ endtime = ps->last->sampledata->sampletime;
+ svg(" <rect class=\"ps\" x=\"%.03f\" y=\"%.03f\" width=\"%.03f\" height=\"%.03f\" />\n",
+ time_to_graph(starttime - graph_start),
+ ps_to_graph(j),
+ time_to_graph(ps->last->sampledata->sampletime - starttime),
+ ps_to_graph(1));
+
+ /* paint cpu load over these */
+ ps->sample = ps->first;
+ t = 1;
+ while (ps->sample->next) {
+ double rt, prt;
+ double wt, wrt;
+ struct ps_sched_struct *prev;
+
+ prev = ps->sample;
+ ps->sample = ps->sample->next;
+
+ /* calculate over interval */
+ rt = ps->sample->runtime - prev->runtime;
+ wt = ps->sample->waittime - prev->waittime;
+
+ prt = (rt / 1000000000) / (ps->sample->sampledata->sampletime - prev->sampledata->sampletime);
+ wrt = (wt / 1000000000) / (ps->sample->sampledata->sampletime - prev->sampledata->sampletime);
+
+ /* this can happen if timekeeping isn't accurate enough */
+ if (prt > 1.0)
+ prt = 1.0;
+ if (wrt > 1.0)
+ wrt = 1.0;
+
+ if ((prt < 0.1) && (wrt < 0.1)) /* =~ 26 (color threshold) */
+ continue;
+
+ svg(" <rect class=\"wait\" x=\"%.03f\" y=\"%.03f\" width=\"%.03f\" height=\"%.03f\" />\n",
+ time_to_graph(prev->sampledata->sampletime - graph_start),
+ ps_to_graph(j),
+ time_to_graph(ps->sample->sampledata->sampletime - prev->sampledata->sampletime),
+ ps_to_graph(wrt));
+
+ /* draw cpu over wait - TODO figure out how/why run + wait > interval */
+ svg(" <rect class=\"cpu\" x=\"%.03f\" y=\"%.03f\" width=\"%.03f\" height=\"%.03f\" />\n",
+ time_to_graph(prev->sampledata->sampletime - graph_start),
+ ps_to_graph(j + (1.0 - prt)),
+ time_to_graph(ps->sample->sampledata->sampletime - prev->sampledata->sampletime),
+ ps_to_graph(prt));
+ t++;
+ }
+
+ /* determine where to display the process name */
+ if ((endtime - starttime) < 1.5)
+ /* too small to fit label inside the box */
+ w = endtime;
+ else
+ w = starttime;
+
+ /* text label of process name */
+ svg(" <text x=\"%.03f\" y=\"%.03f\"><![CDATA[%s]]> [%i]<tspan class=\"run\">%.03fs</tspan></text>\n",
+ time_to_graph(w - graph_start) + 5.0,
+ ps_to_graph(j) + 14.0,
+ ps->name,
+ ps->pid,
+ (ps->last->runtime - ps->first->runtime) / 1000000000.0);
+ /* paint lines to the parent process */
+ if (ps->parent) {
+ /* horizontal part */
+ svg(" <line class=\"dot\" x1=\"%.03f\" y1=\"%.03f\" x2=\"%.03f\" y2=\"%.03f\" />\n",
+ time_to_graph(starttime - graph_start),
+ ps_to_graph(j) + 10.0,
+ ps->parent->pos_x,
+ ps_to_graph(j) + 10.0);
+
+ /* one vertical line connecting all the horizontal ones up */
+ if (!ps->next)
+ svg(" <line class=\"dot\" x1=\"%.03f\" y1=\"%.03f\" x2=\"%.03f\" y2=\"%.03f\" />\n",
+ ps->parent->pos_x,
+ ps_to_graph(j) + 10.0,
+ ps->parent->pos_x,
+ ps->parent->pos_y);
+ }
+
+ j++; /* count boxes */
+
+ svg("\n");
+ }
+
+ /* last pass - determine when idle */
+ pid = getpid();
+ /* make sure we start counting from the point where we actually have
+ * data: assume that bootchart's first sample is when data started
+ */
+
+ ps = ps_first;
+ while (ps->next_ps) {
+ ps = ps->next_ps;
+ if (ps->pid == pid)
+ break;
+ }
+
+ /* need to know last node first */
+ ps->sample = ps->first;
+ i = ps->sample->next->sampledata->counter;
+
+ while (ps->sample->next && i<(samples-(arg_hz/2))) {
+ double crt;
+ double brt;
+ int c;
+ int ii;
+ struct ps_sched_struct *sample_hz;
+
+ ps->sample = ps->sample->next;
+ sample_hz = ps->sample;
+ for (ii=0;((ii<(int)arg_hz/2)&&(ps->sample->next));ii++)
+ sample_hz = sample_hz->next;
+
+ /* subtract bootchart cpu utilization from total */
+ crt = 0.0;
+ for (c = 0; c < cpus; c++)
+ crt += sample_hz->sampledata->runtime[c] - ps->sample->sampledata->runtime[c];
+ brt = sample_hz->runtime - ps->sample->runtime;
+ /*
+ * our definition of "idle":
+ *
+ * if for (hz / 2) we've used less CPU than (interval / 2) ...
+ * defaults to 4.0%, which experimentally, is where atom idles
+ */
+ if ((crt - brt) < (interval / 2.0)) {
+ idletime = ps->sample->sampledata->sampletime - graph_start;
+ svg("\n<!-- idle detected at %.03f seconds -->\n",
+ idletime);
+ svg("<line class=\"idle\" x1=\"%.03f\" y1=\"%.03f\" x2=\"%.03f\" y2=\"%.03f\" />\n",
+ time_to_graph(idletime),
+ -arg_scale_y,
+ time_to_graph(idletime),
+ ps_to_graph(pcount) + arg_scale_y);
+ svg("<text class=\"idle\" x=\"%.03f\" y=\"%.03f\">%.01fs</text>\n",
+ time_to_graph(idletime) + 5.0,
+ ps_to_graph(pcount) + arg_scale_y,
+ idletime);
+ break;
+ }
+ i++;
+ }
+}
+
+static void svg_top_ten_cpu(void) {
+ struct ps_struct *top[10];
+ struct ps_struct emptyps = {};
+ struct ps_struct *ps;
+ int n, m;
+
+ for (n = 0; n < (int) ELEMENTSOF(top); n++)
+ top[n] = &emptyps;
+
+ /* walk all ps's and setup ptrs */
+ ps = ps_first;
+ while ((ps = get_next_ps(ps))) {
+ for (n = 0; n < 10; n++) {
+ if (ps->total <= top[n]->total)
+ continue;
+ /* cascade insert */
+ for (m = 9; m > n; m--)
+ top[m] = top[m-1];
+ top[n] = ps;
+ break;
+ }
+ }
+
+ svg("<text class=\"t2\" x=\"20\" y=\"0\">Top CPU consumers:</text>\n");
+ for (n = 0; n < 10; n++)
+ svg("<text class=\"t3\" x=\"20\" y=\"%d\">%3.03fs - <![CDATA[%s]]> [%d]</text>\n",
+ 20 + (n * 13),
+ top[n]->total,
+ top[n]->name,
+ top[n]->pid);
+}
+
+static void svg_top_ten_pss(void) {
+ struct ps_struct *top[10];
+ struct ps_struct emptyps = {};
+ struct ps_struct *ps;
+ int n, m;
+
+ for (n = 0; n < (int) ELEMENTSOF(top); n++)
+ top[n] = &emptyps;
+
+ /* walk all ps's and setup ptrs */
+ ps = ps_first;
+ while ((ps = get_next_ps(ps))) {
+ for (n = 0; n < 10; n++) {
+ if (ps->pss_max <= top[n]->pss_max)
+ continue;
+ /* cascade insert */
+ for (m = 9; m > n; m--)
+ top[m] = top[m-1];
+ top[n] = ps;
+ break;
+ }
+ }
+
+ svg("<text class=\"t2\" x=\"20\" y=\"0\">Top PSS consumers:</text>\n");
+ for (n = 0; n < 10; n++)
+ svg("<text class=\"t3\" x=\"20\" y=\"%d\">%dK - <![CDATA[%s]]> [%d]</text>\n",
+ 20 + (n * 13),
+ top[n]->pss_max,
+ top[n]->name,
+ top[n]->pid);
+}
+
+void svg_do(const char *build) {
+ struct ps_struct *ps;
+
+ memset(&str, 0, sizeof(str));
+
+ ps = ps_first;
+
+ /* count initcall thread count first */
+ svg_do_initcall(1);
+ ksize = (kcount ? ps_to_graph(kcount) + (arg_scale_y * 2) : 0);
+
+ /* then count processes */
+ while ((ps = get_next_ps(ps))) {
+ if (!ps_filter(ps))
+ pcount++;
+ else
+ pfiltered++;
+ }
+ psize = ps_to_graph(pcount) + (arg_scale_y * 2);
+
+ esize = (arg_entropy ? arg_scale_y * 7 : 0);
+
+ /* after this, we can draw the header with proper sizing */
+ svg_header();
+
+ svg("<g transform=\"translate(10,400)\">\n");
+ svg_io_bi_bar();
+ svg("</g>\n\n");
+
+ svg("<g transform=\"translate(10,%.03f)\">\n", 400.0 + (arg_scale_y * 7.0));
+ svg_io_bo_bar();
+ svg("</g>\n\n");
+
+ svg("<g transform=\"translate(10,%.03f)\">\n", 400.0 + (arg_scale_y * 14.0));
+ svg_cpu_bar();
+ svg("</g>\n\n");
+
+ svg("<g transform=\"translate(10,%.03f)\">\n", 400.0 + (arg_scale_y * 21.0));
+ svg_wait_bar();
+ svg("</g>\n\n");
+
+ if (kcount) {
+ svg("<g transform=\"translate(10,%.03f)\">\n", 400.0 + (arg_scale_y * 28.0));
+ svg_do_initcall(0);
+ svg("</g>\n\n");
+ }
+
+ svg("<g transform=\"translate(10,%.03f)\">\n", 400.0 + (arg_scale_y * 28.0) + ksize);
+ svg_ps_bars();
+ svg("</g>\n\n");
+
+ svg("<g transform=\"translate(10, 0)\">\n");
+ svg_title(build);
+ svg("</g>\n\n");
+
+ svg("<g transform=\"translate(10,200)\">\n");
+ svg_top_ten_cpu();
+ svg("</g>\n\n");
+
+ if (arg_entropy) {
+ svg("<g transform=\"translate(10,%.03f)\">\n", 400.0 + (arg_scale_y * 28.0) + ksize + psize);
+ svg_entropy_bar();
+ svg("</g>\n\n");
+ }
+
+ if (arg_pss) {
+ svg("<g transform=\"translate(10,%.03f)\">\n", 400.0 + (arg_scale_y * 28.0) + ksize + psize + esize);
+ svg_pss_graph();
+ svg("</g>\n\n");
+
+ svg("<g transform=\"translate(410,200)\">\n");
+ svg_top_ten_pss();
+ svg("</g>\n\n");
+ }
+
+ /* svg footer */
+ svg("\n</svg>\n");
+}
diff --git a/src/bootchart/svg.h b/src/bootchart/svg.h
new file mode 100644
index 0000000000..e7369f5111
--- /dev/null
+++ b/src/bootchart/svg.h
@@ -0,0 +1,27 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright (C) 2009-2013 Intel Coproration
+
+ Authors:
+ Auke Kok <auke-jan.h.kok@intel.com>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+void svg_do(const char *build);
diff --git a/src/cgls/cgls.c b/src/cgls/cgls.c
new file mode 100644
index 0000000000..ef3e5672ab
--- /dev/null
+++ b/src/cgls/cgls.c
@@ -0,0 +1,213 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <limits.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <errno.h>
+#include <getopt.h>
+#include <string.h>
+
+#include "cgroup-show.h"
+#include "cgroup-util.h"
+#include "log.h"
+#include "path-util.h"
+#include "util.h"
+#include "pager.h"
+#include "build.h"
+#include "output-mode.h"
+
+static bool arg_no_pager = false;
+static bool arg_kernel_threads = false;
+static bool arg_all = false;
+static int arg_full = -1;
+static char* arg_machine = NULL;
+
+static void help(void) {
+
+ printf("%s [OPTIONS...] [CGROUP...]\n\n"
+ "Recursively show control group contents.\n\n"
+ " -h --help Show this help\n"
+ " --version Show package version\n"
+ " --no-pager Do not pipe output into a pager\n"
+ " -a --all Show all groups, including empty\n"
+ " --full Do not ellipsize output\n"
+ " -k Include kernel threads in output\n"
+ " -M --machine Show container\n",
+ program_invocation_short_name);
+}
+
+static int parse_argv(int argc, char *argv[]) {
+
+ enum {
+ ARG_NO_PAGER = 0x100,
+ ARG_VERSION,
+ ARG_FULL,
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "version", no_argument, NULL, ARG_VERSION },
+ { "no-pager", no_argument, NULL, ARG_NO_PAGER },
+ { "all", no_argument, NULL, 'a' },
+ { "full", no_argument, NULL, ARG_FULL },
+ { "machine", required_argument, NULL, 'M' },
+ { NULL, 0, NULL, 0 }
+ };
+
+ int c;
+
+ assert(argc >= 1);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "hkaM:", options, NULL)) >= 0) {
+
+ switch (c) {
+
+ case 'h':
+ help();
+ return 0;
+
+ case ARG_VERSION:
+ puts(PACKAGE_STRING);
+ puts(SYSTEMD_FEATURES);
+ return 0;
+
+ case ARG_NO_PAGER:
+ arg_no_pager = true;
+ break;
+
+ case 'a':
+ arg_all = true;
+ break;
+
+ case ARG_FULL:
+ arg_full = true;
+ break;
+
+ case 'k':
+ arg_kernel_threads = true;
+ break;
+
+ case 'M':
+ arg_machine = optarg;
+ break;
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ log_error("Unknown option code %c", c);
+ return -EINVAL;
+ }
+ }
+
+ return 1;
+}
+
+int main(int argc, char *argv[]) {
+ int r = 0, retval = EXIT_FAILURE;
+ int output_flags;
+ char _cleanup_free_ *root = NULL;
+
+ log_parse_environment();
+ log_open();
+
+ r = parse_argv(argc, argv);
+ if (r < 0)
+ goto finish;
+ else if (r == 0) {
+ retval = EXIT_SUCCESS;
+ goto finish;
+ }
+
+ if (!arg_no_pager) {
+ r = pager_open(false);
+ if (r > 0) {
+ if (arg_full == -1)
+ arg_full = true;
+ }
+ }
+
+ output_flags =
+ arg_all * OUTPUT_SHOW_ALL |
+ (arg_full > 0) * OUTPUT_FULL_WIDTH;
+
+ if (optind < argc) {
+ int i;
+
+ for (i = optind; i < argc; i++) {
+ int q;
+ printf("%s:\n", argv[i]);
+
+ if (arg_machine)
+ root = strjoin("machine/", arg_machine, "/", argv[i], NULL);
+ else
+ root = strdup(argv[i]);
+ if (!root)
+ return log_oom();
+
+ q = show_cgroup_by_path(root, NULL, 0,
+ arg_kernel_threads, output_flags);
+ if (q < 0)
+ r = q;
+ }
+
+ } else {
+ _cleanup_free_ char *p;
+
+ p = get_current_dir_name();
+ if (!p) {
+ log_error("Cannot determine current working directory: %m");
+ goto finish;
+ }
+
+ if (path_startswith(p, "/sys/fs/cgroup") && !arg_machine) {
+ printf("Working Directory %s:\n", p);
+ r = show_cgroup_by_path(p, NULL, 0,
+ arg_kernel_threads, output_flags);
+ } else {
+ if (arg_machine)
+ r = cg_get_machine_path(arg_machine, &root);
+ else
+ r = cg_get_root_path(&root);
+ if (r < 0) {
+ log_error("Failed to get %s path: %s",
+ arg_machine ? "machine" : "root", strerror(-r));
+ goto finish;
+ }
+
+ r = show_cgroup(SYSTEMD_CGROUP_CONTROLLER, root, NULL, 0,
+ arg_kernel_threads, output_flags);
+ }
+ }
+
+ if (r < 0) {
+ log_error("Failed to list cgroup tree %s: %s", root, strerror(-r));
+ retval = EXIT_FAILURE;
+ } else
+ retval = EXIT_SUCCESS;
+
+finish:
+ pager_close();
+
+ return retval;
+}
diff --git a/src/cgroups-agent/cgroups-agent.c b/src/cgroups-agent/cgroups-agent.c
new file mode 100644
index 0000000000..7a6173e2a2
--- /dev/null
+++ b/src/cgroups-agent/cgroups-agent.c
@@ -0,0 +1,101 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <dbus/dbus.h>
+
+#include <stdlib.h>
+
+#include "log.h"
+#include "dbus-common.h"
+
+int main(int argc, char *argv[]) {
+ DBusError error;
+ DBusConnection *bus = NULL;
+ DBusMessage *m = NULL;
+ int r = EXIT_FAILURE;
+
+ dbus_error_init(&error);
+
+ if (argc != 2) {
+ log_error("Incorrect number of arguments.");
+ goto finish;
+ }
+
+ log_set_target(LOG_TARGET_AUTO);
+ log_parse_environment();
+ log_open();
+
+ /* We send this event to the private D-Bus socket and then the
+ * system instance will forward this to the system bus. We do
+ * this to avoid an activation loop when we start dbus when we
+ * are called when the dbus service is shut down. */
+
+ if (!(bus = dbus_connection_open_private("unix:path=/run/systemd/private", &error))) {
+#ifndef LEGACY
+ dbus_error_free(&error);
+
+ /* Retry with the pre v21 socket name, to ease upgrades */
+ if (!(bus = dbus_connection_open_private("unix:abstract=/org/freedesktop/systemd1/private", &error))) {
+#endif
+ log_error("Failed to get D-Bus connection: %s", bus_error_message(&error));
+ goto finish;
+ }
+#ifndef LEGACY
+ }
+#endif
+
+ if (bus_check_peercred(bus) < 0) {
+ log_error("Bus owner not root.");
+ goto finish;
+ }
+
+ if (!(m = dbus_message_new_signal("/org/freedesktop/systemd1/agent", "org.freedesktop.systemd1.Agent", "Released"))) {
+ log_error("Could not allocate signal message.");
+ goto finish;
+ }
+
+ if (!dbus_message_append_args(m,
+ DBUS_TYPE_STRING, &argv[1],
+ DBUS_TYPE_INVALID)) {
+ log_error("Could not attach group information to signal message.");
+ goto finish;
+ }
+
+ if (!dbus_connection_send(bus, m, NULL)) {
+ log_error("Failed to send signal message on private connection.");
+ goto finish;
+ }
+
+ r = EXIT_SUCCESS;
+
+finish:
+ if (bus) {
+ dbus_connection_flush(bus);
+ dbus_connection_close(bus);
+ dbus_connection_unref(bus);
+ }
+
+ if (m)
+ dbus_message_unref(m);
+
+ dbus_error_free(&error);
+ return r;
+}
diff --git a/src/cgtop/cgtop.c b/src/cgtop/cgtop.c
new file mode 100644
index 0000000000..1e21b0074d
--- /dev/null
+++ b/src/cgtop/cgtop.c
@@ -0,0 +1,854 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#define __STDC_FORMAT_MACROS
+#include <errno.h>
+#include <string.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <unistd.h>
+#include <alloca.h>
+#include <getopt.h>
+
+#include "path-util.h"
+#include "util.h"
+#include "hashmap.h"
+#include "cgroup-util.h"
+#include "build.h"
+#include "fileio.h"
+
+typedef struct Group {
+ char *path;
+
+ bool n_tasks_valid:1;
+ bool cpu_valid:1;
+ bool memory_valid:1;
+ bool io_valid:1;
+
+ unsigned n_tasks;
+
+ unsigned cpu_iteration;
+ uint64_t cpu_usage;
+ struct timespec cpu_timestamp;
+ double cpu_fraction;
+
+ uint64_t memory;
+
+ unsigned io_iteration;
+ uint64_t io_input, io_output;
+ struct timespec io_timestamp;
+ uint64_t io_input_bps, io_output_bps;
+} Group;
+
+static unsigned arg_depth = 3;
+static unsigned arg_iterations = 0;
+static bool arg_batch = false;
+static usec_t arg_delay = 1*USEC_PER_SEC;
+
+static enum {
+ ORDER_PATH,
+ ORDER_TASKS,
+ ORDER_CPU,
+ ORDER_MEMORY,
+ ORDER_IO
+} arg_order = ORDER_CPU;
+
+static enum {
+ CPU_PERCENT,
+ CPU_TIME,
+} arg_cpu_type = CPU_PERCENT;
+
+static void group_free(Group *g) {
+ assert(g);
+
+ free(g->path);
+ free(g);
+}
+
+static void group_hashmap_clear(Hashmap *h) {
+ Group *g;
+
+ while ((g = hashmap_steal_first(h)))
+ group_free(g);
+}
+
+static void group_hashmap_free(Hashmap *h) {
+ group_hashmap_clear(h);
+ hashmap_free(h);
+}
+
+static int process(const char *controller, const char *path, Hashmap *a, Hashmap *b, unsigned iteration) {
+ Group *g;
+ int r;
+ FILE *f;
+ pid_t pid;
+ unsigned n;
+
+ assert(controller);
+ assert(path);
+ assert(a);
+
+ g = hashmap_get(a, path);
+ if (!g) {
+ g = hashmap_get(b, path);
+ if (!g) {
+ g = new0(Group, 1);
+ if (!g)
+ return -ENOMEM;
+
+ g->path = strdup(path);
+ if (!g->path) {
+ group_free(g);
+ return -ENOMEM;
+ }
+
+ r = hashmap_put(a, g->path, g);
+ if (r < 0) {
+ group_free(g);
+ return r;
+ }
+ } else {
+ assert_se(hashmap_move_one(a, b, path) == 0);
+ g->cpu_valid = g->memory_valid = g->io_valid = g->n_tasks_valid = false;
+ }
+ }
+
+ /* Regardless which controller, let's find the maximum number
+ * of processes in any of it */
+
+ r = cg_enumerate_tasks(controller, path, &f);
+ if (r < 0)
+ return r;
+
+ n = 0;
+ while (cg_read_pid(f, &pid) > 0)
+ n++;
+ fclose(f);
+
+ if (n > 0) {
+ if (g->n_tasks_valid)
+ g->n_tasks = MAX(g->n_tasks, n);
+ else
+ g->n_tasks = n;
+
+ g->n_tasks_valid = true;
+ }
+
+ if (streq(controller, "cpuacct")) {
+ uint64_t new_usage;
+ char *p, *v;
+ struct timespec ts;
+
+ r = cg_get_path(controller, path, "cpuacct.usage", &p);
+ if (r < 0)
+ return r;
+
+ r = read_one_line_file(p, &v);
+ free(p);
+ if (r < 0)
+ return r;
+
+ r = safe_atou64(v, &new_usage);
+ free(v);
+ if (r < 0)
+ return r;
+
+ assert_se(clock_gettime(CLOCK_MONOTONIC, &ts) == 0);
+
+ if (g->cpu_iteration == iteration - 1) {
+ uint64_t x, y;
+
+ x = ((uint64_t) ts.tv_sec * 1000000000ULL + (uint64_t) ts.tv_nsec) -
+ ((uint64_t) g->cpu_timestamp.tv_sec * 1000000000ULL + (uint64_t) g->cpu_timestamp.tv_nsec);
+
+ y = new_usage - g->cpu_usage;
+
+ if (y > 0) {
+ g->cpu_fraction = (double) y / (double) x;
+ g->cpu_valid = true;
+ }
+ }
+
+ g->cpu_usage = new_usage;
+ g->cpu_timestamp = ts;
+ g->cpu_iteration = iteration;
+
+ } else if (streq(controller, "memory")) {
+ char *p, *v;
+
+ r = cg_get_path(controller, path, "memory.usage_in_bytes", &p);
+ if (r < 0)
+ return r;
+
+ r = read_one_line_file(p, &v);
+ free(p);
+ if (r < 0)
+ return r;
+
+ r = safe_atou64(v, &g->memory);
+ free(v);
+ if (r < 0)
+ return r;
+
+ if (g->memory > 0)
+ g->memory_valid = true;
+
+ } else if (streq(controller, "blkio")) {
+ char *p;
+ uint64_t wr = 0, rd = 0;
+ struct timespec ts;
+
+ r = cg_get_path(controller, path, "blkio.io_service_bytes", &p);
+ if (r < 0)
+ return r;
+
+ f = fopen(p, "re");
+ free(p);
+
+ if (!f)
+ return -errno;
+
+ for (;;) {
+ char line[LINE_MAX], *l;
+ uint64_t k, *q;
+
+ if (!fgets(line, sizeof(line), f))
+ break;
+
+ l = strstrip(line);
+ l += strcspn(l, WHITESPACE);
+ l += strspn(l, WHITESPACE);
+
+ if (first_word(l, "Read")) {
+ l += 4;
+ q = &rd;
+ } else if (first_word(l, "Write")) {
+ l += 5;
+ q = &wr;
+ } else
+ continue;
+
+ l += strspn(l, WHITESPACE);
+ r = safe_atou64(l, &k);
+ if (r < 0)
+ continue;
+
+ *q += k;
+ }
+
+ fclose(f);
+
+ assert_se(clock_gettime(CLOCK_MONOTONIC, &ts) == 0);
+
+ if (g->io_iteration == iteration - 1) {
+ uint64_t x, yr, yw;
+
+ x = ((uint64_t) ts.tv_sec * 1000000000ULL + (uint64_t) ts.tv_nsec) -
+ ((uint64_t) g->io_timestamp.tv_sec * 1000000000ULL + (uint64_t) g->io_timestamp.tv_nsec);
+
+ yr = rd - g->io_input;
+ yw = wr - g->io_output;
+
+ if (yr > 0 || yw > 0) {
+ g->io_input_bps = (yr * 1000000000ULL) / x;
+ g->io_output_bps = (yw * 1000000000ULL) / x;
+ g->io_valid = true;
+
+ }
+ }
+
+ g->io_input = rd;
+ g->io_output = wr;
+ g->io_timestamp = ts;
+ g->io_iteration = iteration;
+ }
+
+ return 0;
+}
+
+static int refresh_one(
+ const char *controller,
+ const char *path,
+ Hashmap *a,
+ Hashmap *b,
+ unsigned iteration,
+ unsigned depth) {
+
+ DIR *d = NULL;
+ int r;
+
+ assert(controller);
+ assert(path);
+ assert(a);
+
+ if (depth > arg_depth)
+ return 0;
+
+ r = process(controller, path, a, b, iteration);
+ if (r < 0)
+ return r;
+
+ r = cg_enumerate_subgroups(controller, path, &d);
+ if (r < 0) {
+ if (r == -ENOENT)
+ return 0;
+
+ return r;
+ }
+
+ for (;;) {
+ char *fn, *p;
+
+ r = cg_read_subgroup(d, &fn);
+ if (r <= 0)
+ goto finish;
+
+ p = strjoin(path, "/", fn, NULL);
+ free(fn);
+
+ if (!p) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ path_kill_slashes(p);
+
+ r = refresh_one(controller, p, a, b, iteration, depth + 1);
+ free(p);
+
+ if (r < 0)
+ goto finish;
+ }
+
+finish:
+ if (d)
+ closedir(d);
+
+ return r;
+}
+
+static int refresh(Hashmap *a, Hashmap *b, unsigned iteration) {
+ int r;
+
+ assert(a);
+
+ r = refresh_one("name=systemd", "/", a, b, iteration, 0);
+ if (r < 0)
+ if (r != -ENOENT)
+ return r;
+ r = refresh_one("cpuacct", "/", a, b, iteration, 0);
+ if (r < 0)
+ if (r != -ENOENT)
+ return r;
+ r = refresh_one("memory", "/", a, b, iteration, 0);
+ if (r < 0)
+ if (r != -ENOENT)
+ return r;
+
+ r = refresh_one("blkio", "/", a, b, iteration, 0);
+ if (r < 0)
+ if (r != -ENOENT)
+ return r;
+ return 0;
+}
+
+static int group_compare(const void*a, const void *b) {
+ const Group *x = *(Group**)a, *y = *(Group**)b;
+
+ if (path_startswith(y->path, x->path))
+ return -1;
+ if (path_startswith(x->path, y->path))
+ return 1;
+
+ if (arg_order == ORDER_CPU) {
+ if (arg_cpu_type == CPU_PERCENT) {
+ if (x->cpu_valid && y->cpu_valid) {
+ if (x->cpu_fraction > y->cpu_fraction)
+ return -1;
+ else if (x->cpu_fraction < y->cpu_fraction)
+ return 1;
+ } else if (x->cpu_valid)
+ return -1;
+ else if (y->cpu_valid)
+ return 1;
+ } else {
+ if (x->cpu_usage > y->cpu_usage)
+ return -1;
+ else if (x->cpu_usage < y->cpu_usage)
+ return 1;
+ }
+ }
+
+ if (arg_order == ORDER_TASKS) {
+
+ if (x->n_tasks_valid && y->n_tasks_valid) {
+ if (x->n_tasks > y->n_tasks)
+ return -1;
+ else if (x->n_tasks < y->n_tasks)
+ return 1;
+ } else if (x->n_tasks_valid)
+ return -1;
+ else if (y->n_tasks_valid)
+ return 1;
+ }
+
+ if (arg_order == ORDER_MEMORY) {
+ if (x->memory_valid && y->memory_valid) {
+ if (x->memory > y->memory)
+ return -1;
+ else if (x->memory < y->memory)
+ return 1;
+ } else if (x->memory_valid)
+ return -1;
+ else if (y->memory_valid)
+ return 1;
+ }
+
+ if (arg_order == ORDER_IO) {
+ if (x->io_valid && y->io_valid) {
+ if (x->io_input_bps + x->io_output_bps > y->io_input_bps + y->io_output_bps)
+ return -1;
+ else if (x->io_input_bps + x->io_output_bps < y->io_input_bps + y->io_output_bps)
+ return 1;
+ } else if (x->io_valid)
+ return -1;
+ else if (y->io_valid)
+ return 1;
+ }
+
+ return strcmp(x->path, y->path);
+}
+
+#define ON ANSI_HIGHLIGHT_ON
+#define OFF ANSI_HIGHLIGHT_OFF
+
+static int display(Hashmap *a) {
+ Iterator i;
+ Group *g;
+ Group **array;
+ signed path_columns;
+ unsigned rows, n = 0, j, maxtcpu = 0, maxtpath = 0;
+ char buffer[MAX3(21, FORMAT_BYTES_MAX, FORMAT_TIMESPAN_MAX)];
+
+ assert(a);
+
+ /* Set cursor to top left corner and clear screen */
+ if (on_tty())
+ fputs("\033[H"
+ "\033[2J", stdout);
+
+ array = alloca(sizeof(Group*) * hashmap_size(a));
+
+ HASHMAP_FOREACH(g, a, i)
+ if (g->n_tasks_valid || g->cpu_valid || g->memory_valid || g->io_valid)
+ array[n++] = g;
+
+ qsort(array, n, sizeof(Group*), group_compare);
+
+ /* Find the longest names in one run */
+ for (j = 0; j < n; j++) {
+ unsigned cputlen, pathtlen;
+
+ format_timespan(buffer, sizeof(buffer), (nsec_t) (array[j]->cpu_usage / NSEC_PER_USEC), 0);
+ cputlen = strlen(buffer);
+ maxtcpu = MAX(maxtcpu, cputlen);
+ pathtlen = strlen(array[j]->path);
+ maxtpath = MAX(maxtpath, pathtlen);
+ }
+
+ if (arg_cpu_type == CPU_PERCENT)
+ snprintf(buffer, sizeof(buffer), "%6s", "%CPU");
+ else
+ snprintf(buffer, sizeof(buffer), "%*s", maxtcpu, "CPU Time");
+
+ rows = lines();
+ if (rows <= 10)
+ rows = 10;
+
+ if (on_tty()) {
+ path_columns = columns() - 36 - strlen(buffer);
+ if (path_columns < 10)
+ path_columns = 10;
+
+ printf("%s%-*s%s %s%7s%s %s%s%s %s%8s%s %s%8s%s %s%8s%s\n\n",
+ arg_order == ORDER_PATH ? ON : "", path_columns, "Path",
+ arg_order == ORDER_PATH ? OFF : "",
+ arg_order == ORDER_TASKS ? ON : "", "Tasks",
+ arg_order == ORDER_TASKS ? OFF : "",
+ arg_order == ORDER_CPU ? ON : "", buffer,
+ arg_order == ORDER_CPU ? OFF : "",
+ arg_order == ORDER_MEMORY ? ON : "", "Memory",
+ arg_order == ORDER_MEMORY ? OFF : "",
+ arg_order == ORDER_IO ? ON : "", "Input/s",
+ arg_order == ORDER_IO ? OFF : "",
+ arg_order == ORDER_IO ? ON : "", "Output/s",
+ arg_order == ORDER_IO ? OFF : "");
+ } else
+ path_columns = maxtpath;
+
+ for (j = 0; j < n; j++) {
+ char *p;
+
+ if (on_tty() && j + 5 > rows)
+ break;
+
+ g = array[j];
+
+ p = ellipsize(g->path, path_columns, 33);
+ printf("%-*s", path_columns, p ? p : g->path);
+ free(p);
+
+ if (g->n_tasks_valid)
+ printf(" %7u", g->n_tasks);
+ else
+ fputs(" -", stdout);
+
+ if (arg_cpu_type == CPU_PERCENT) {
+ if (g->cpu_valid)
+ printf(" %6.1f", g->cpu_fraction*100);
+ else
+ fputs(" -", stdout);
+ } else
+ printf(" %*s", maxtcpu, format_timespan(buffer, sizeof(buffer), (nsec_t) (g->cpu_usage / NSEC_PER_USEC), 0));
+
+ if (g->memory_valid)
+ printf(" %8s", format_bytes(buffer, sizeof(buffer), g->memory));
+ else
+ fputs(" -", stdout);
+
+ if (g->io_valid) {
+ printf(" %8s",
+ format_bytes(buffer, sizeof(buffer), g->io_input_bps));
+ printf(" %8s",
+ format_bytes(buffer, sizeof(buffer), g->io_output_bps));
+ } else
+ fputs(" - -", stdout);
+
+ putchar('\n');
+ }
+
+ return 0;
+}
+
+static void help(void) {
+
+ printf("%s [OPTIONS...]\n\n"
+ "Show top control groups by their resource usage.\n\n"
+ " -h --help Show this help\n"
+ " --version Print version and exit\n"
+ " -p Order by path\n"
+ " -t Order by number of tasks\n"
+ " -c Order by CPU load\n"
+ " -m Order by memory load\n"
+ " -i Order by IO load\n"
+ " --cpu[=TYPE] Show CPU usage as time or percentage (default)\n"
+ " -d --delay=DELAY Delay between updates\n"
+ " -n --iterations=N Run for N iterations before exiting\n"
+ " -b --batch Run in batch mode, accepting no input\n"
+ " --depth=DEPTH Maximum traversal depth (default: %d)\n",
+ program_invocation_short_name, arg_depth);
+}
+
+static void version(void) {
+ puts(PACKAGE_STRING " cgtop");
+}
+
+static int parse_argv(int argc, char *argv[]) {
+
+ enum {
+ ARG_VERSION = 0x100,
+ ARG_DEPTH,
+ ARG_CPU_TYPE
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "version", no_argument, NULL, ARG_VERSION },
+ { "delay", required_argument, NULL, 'd' },
+ { "iterations", required_argument, NULL, 'n' },
+ { "batch", no_argument, NULL, 'b' },
+ { "depth", required_argument, NULL, ARG_DEPTH },
+ { "cpu", optional_argument, NULL, ARG_CPU_TYPE},
+ { NULL, 0, NULL, 0 }
+ };
+
+ int c;
+ int r;
+
+ assert(argc >= 1);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "hptcmin:bd:", options, NULL)) >= 0) {
+
+ switch (c) {
+
+ case 'h':
+ help();
+ return 0;
+
+ case ARG_VERSION:
+ version();
+ return 0;
+
+ case ARG_CPU_TYPE:
+ if (optarg) {
+ if (strcmp(optarg, "time") == 0)
+ arg_cpu_type = CPU_TIME;
+ else if (strcmp(optarg, "percentage") == 0)
+ arg_cpu_type = CPU_PERCENT;
+ else
+ return -EINVAL;
+ }
+ break;
+
+ case ARG_DEPTH:
+ r = safe_atou(optarg, &arg_depth);
+ if (r < 0) {
+ log_error("Failed to parse depth parameter.");
+ return -EINVAL;
+ }
+
+ break;
+
+ case 'd':
+ r = parse_sec(optarg, &arg_delay);
+ if (r < 0 || arg_delay <= 0) {
+ log_error("Failed to parse delay parameter.");
+ return -EINVAL;
+ }
+
+ break;
+
+ case 'n':
+ r = safe_atou(optarg, &arg_iterations);
+ if (r < 0) {
+ log_error("Failed to parse iterations parameter.");
+ return -EINVAL;
+ }
+
+ break;
+
+ case 'b':
+ arg_batch = true;
+ break;
+
+ case 'p':
+ arg_order = ORDER_PATH;
+ break;
+
+ case 't':
+ arg_order = ORDER_TASKS;
+ break;
+
+ case 'c':
+ arg_order = ORDER_CPU;
+ break;
+
+ case 'm':
+ arg_order = ORDER_MEMORY;
+ break;
+
+ case 'i':
+ arg_order = ORDER_IO;
+ break;
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ log_error("Unknown option code %c", c);
+ return -EINVAL;
+ }
+ }
+
+ if (optind < argc) {
+ log_error("Too many arguments.");
+ return -EINVAL;
+ }
+
+ return 1;
+}
+
+int main(int argc, char *argv[]) {
+ int r;
+ Hashmap *a = NULL, *b = NULL;
+ unsigned iteration = 0;
+ usec_t last_refresh = 0;
+ bool quit = false, immediate_refresh = false;
+
+ log_parse_environment();
+ log_open();
+
+ r = parse_argv(argc, argv);
+ if (r <= 0)
+ goto finish;
+
+ a = hashmap_new(string_hash_func, string_compare_func);
+ b = hashmap_new(string_hash_func, string_compare_func);
+ if (!a || !b) {
+ r = log_oom();
+ goto finish;
+ }
+
+ signal(SIGWINCH, columns_lines_cache_reset);
+
+ if (!on_tty())
+ arg_iterations = 1;
+
+ while (!quit) {
+ Hashmap *c;
+ usec_t t;
+ char key;
+ char h[FORMAT_TIMESPAN_MAX];
+
+ t = now(CLOCK_MONOTONIC);
+
+ if (t >= last_refresh + arg_delay || immediate_refresh) {
+
+ r = refresh(a, b, iteration++);
+ if (r < 0)
+ goto finish;
+
+ group_hashmap_clear(b);
+
+ c = a;
+ a = b;
+ b = c;
+
+ last_refresh = t;
+ immediate_refresh = false;
+ }
+
+ r = display(b);
+ if (r < 0)
+ goto finish;
+
+ if (arg_iterations && iteration >= arg_iterations)
+ break;
+
+ if (arg_batch) {
+ usleep(last_refresh + arg_delay - t);
+ } else {
+ r = read_one_char(stdin, &key,
+ last_refresh + arg_delay - t, NULL);
+ if (r == -ETIMEDOUT)
+ continue;
+ if (r < 0) {
+ log_error("Couldn't read key: %s", strerror(-r));
+ goto finish;
+ }
+ }
+
+ fputs("\r \r", stdout);
+ fflush(stdout);
+
+ if (arg_batch)
+ continue;
+
+ switch (key) {
+
+ case ' ':
+ immediate_refresh = true;
+ break;
+
+ case 'q':
+ quit = true;
+ break;
+
+ case 'p':
+ arg_order = ORDER_PATH;
+ break;
+
+ case 't':
+ arg_order = ORDER_TASKS;
+ break;
+
+ case 'c':
+ arg_order = ORDER_CPU;
+ break;
+
+ case 'm':
+ arg_order = ORDER_MEMORY;
+ break;
+
+ case 'i':
+ arg_order = ORDER_IO;
+ break;
+
+ case '%':
+ arg_cpu_type = arg_cpu_type == CPU_TIME ? CPU_PERCENT : CPU_TIME;
+ break;
+
+ case '+':
+ if (arg_delay < USEC_PER_SEC)
+ arg_delay += USEC_PER_MSEC*250;
+ else
+ arg_delay += USEC_PER_SEC;
+
+ fprintf(stdout, "\nIncreased delay to %s.", format_timespan(h, sizeof(h), arg_delay, 0));
+ fflush(stdout);
+ sleep(1);
+ break;
+
+ case '-':
+ if (arg_delay <= USEC_PER_MSEC*500)
+ arg_delay = USEC_PER_MSEC*250;
+ else if (arg_delay < USEC_PER_MSEC*1250)
+ arg_delay -= USEC_PER_MSEC*250;
+ else
+ arg_delay -= USEC_PER_SEC;
+
+ fprintf(stdout, "\nDecreased delay to %s.", format_timespan(h, sizeof(h), arg_delay, 0));
+ fflush(stdout);
+ sleep(1);
+ break;
+
+ case '?':
+ case 'h':
+ fprintf(stdout,
+ "\t<" ON "P" OFF "> By path; <" ON "T" OFF "> By tasks; <" ON "C" OFF "> By CPU; <" ON "M" OFF "> By memory; <" ON "I" OFF "> By I/O\n"
+ "\t<" ON "+" OFF "> Increase delay; <" ON "-" OFF "> Decrease delay; <" ON "%%" OFF "> Toggle time\n"
+ "\t<" ON "Q" OFF "> Quit; <" ON "SPACE" OFF "> Refresh");
+ fflush(stdout);
+ sleep(3);
+ break;
+
+ default:
+ fprintf(stdout, "\nUnknown key '%c'. Ignoring.", key);
+ fflush(stdout);
+ sleep(1);
+ break;
+ }
+ }
+
+ r = 0;
+
+finish:
+ group_hashmap_free(a);
+ group_hashmap_free(b);
+
+ if (r < 0) {
+ log_error("Exiting with failure: %s", strerror(-r));
+ return EXIT_FAILURE;
+ }
+
+ return EXIT_SUCCESS;
+}
diff --git a/src/core/audit-fd.c b/src/core/audit-fd.c
new file mode 100644
index 0000000000..5955bd846e
--- /dev/null
+++ b/src/core/audit-fd.c
@@ -0,0 +1,73 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+
+#include <errno.h>
+#include "audit-fd.h"
+
+#ifdef HAVE_AUDIT
+
+#include <stdbool.h>
+#include <libaudit.h>
+
+#include "log.h"
+#include "util.h"
+
+static bool initialized = false;
+static int audit_fd;
+
+int get_audit_fd(void) {
+
+ if (!initialized) {
+ audit_fd = audit_open();
+
+ if (audit_fd < 0) {
+ if (errno != EAFNOSUPPORT && errno != EPROTONOSUPPORT)
+ log_error("Failed to connect to audit log: %m");
+
+ audit_fd = errno ? -errno : -EINVAL;
+ }
+
+ initialized = true;
+ }
+
+ return audit_fd;
+}
+
+void close_audit_fd(void) {
+
+ if (initialized && audit_fd >= 0)
+ close_nointr_nofail(audit_fd);
+
+ initialized = true;
+ audit_fd = -ECONNRESET;
+}
+
+#else
+
+int get_audit_fd(void) {
+ return -EAFNOSUPPORT;
+}
+
+void close_audit_fd(void) {
+}
+
+#endif
diff --git a/src/core/audit-fd.h b/src/core/audit-fd.h
new file mode 100644
index 0000000000..8b58289dc5
--- /dev/null
+++ b/src/core/audit-fd.h
@@ -0,0 +1,25 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+int get_audit_fd(void);
+void close_audit_fd(void);
diff --git a/src/core/automount.c b/src/core/automount.c
new file mode 100644
index 0000000000..a20d5340f2
--- /dev/null
+++ b/src/core/automount.c
@@ -0,0 +1,920 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <limits.h>
+#include <sys/mount.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/epoll.h>
+#include <sys/stat.h>
+#include <linux/auto_fs4.h>
+#include <linux/auto_dev-ioctl.h>
+
+#include "unit.h"
+#include "automount.h"
+#include "mount.h"
+#include "load-fragment.h"
+#include "load-dropin.h"
+#include "unit-name.h"
+#include "dbus-automount.h"
+#include "bus-errors.h"
+#include "special.h"
+#include "label.h"
+#include "mkdir.h"
+#include "path-util.h"
+#include "dbus-common.h"
+
+static const UnitActiveState state_translation_table[_AUTOMOUNT_STATE_MAX] = {
+ [AUTOMOUNT_DEAD] = UNIT_INACTIVE,
+ [AUTOMOUNT_WAITING] = UNIT_ACTIVE,
+ [AUTOMOUNT_RUNNING] = UNIT_ACTIVE,
+ [AUTOMOUNT_FAILED] = UNIT_FAILED
+};
+
+static int open_dev_autofs(Manager *m);
+
+static void automount_init(Unit *u) {
+ Automount *a = AUTOMOUNT(u);
+
+ assert(u);
+ assert(u->load_state == UNIT_STUB);
+
+ a->pipe_watch.fd = a->pipe_fd = -1;
+ a->pipe_watch.type = WATCH_INVALID;
+
+ a->directory_mode = 0755;
+
+ UNIT(a)->ignore_on_isolate = true;
+}
+
+static void repeat_unmout(const char *path) {
+ assert(path);
+
+ for (;;) {
+ /* If there are multiple mounts on a mount point, this
+ * removes them all */
+
+ if (umount2(path, MNT_DETACH) >= 0)
+ continue;
+
+ if (errno != EINVAL)
+ log_error("Failed to unmount: %m");
+
+ break;
+ }
+}
+
+static void unmount_autofs(Automount *a) {
+ assert(a);
+
+ if (a->pipe_fd < 0)
+ return;
+
+ automount_send_ready(a, -EHOSTDOWN);
+
+ unit_unwatch_fd(UNIT(a), &a->pipe_watch);
+ close_nointr_nofail(a->pipe_fd);
+ a->pipe_fd = -1;
+
+ /* If we reload/reexecute things we keep the mount point
+ * around */
+ if (a->where &&
+ (UNIT(a)->manager->exit_code != MANAGER_RELOAD &&
+ UNIT(a)->manager->exit_code != MANAGER_REEXECUTE))
+ repeat_unmout(a->where);
+}
+
+static void automount_done(Unit *u) {
+ Automount *a = AUTOMOUNT(u);
+
+ assert(a);
+
+ unmount_autofs(a);
+
+ free(a->where);
+ a->where = NULL;
+
+ set_free(a->tokens);
+ a->tokens = NULL;
+}
+
+int automount_add_one_mount_link(Automount *a, Mount *m) {
+ int r;
+
+ assert(a);
+ assert(m);
+
+ if (UNIT(a)->load_state != UNIT_LOADED ||
+ UNIT(m)->load_state != UNIT_LOADED)
+ return 0;
+
+ if (!path_startswith(a->where, m->where))
+ return 0;
+
+ if (path_equal(a->where, m->where))
+ return 0;
+
+ r = unit_add_two_dependencies(UNIT(a), UNIT_AFTER, UNIT_REQUIRES, UNIT(m), true);
+ if (r < 0)
+ return r;
+
+ return 0;
+}
+
+static int automount_add_mount_links(Automount *a) {
+ Unit *other;
+ int r;
+
+ assert(a);
+
+ LIST_FOREACH(units_by_type, other, UNIT(a)->manager->units_by_type[UNIT_MOUNT]) {
+ r = automount_add_one_mount_link(a, MOUNT(other));
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static int automount_add_default_dependencies(Automount *a) {
+ int r;
+
+ assert(a);
+
+ if (UNIT(a)->manager->running_as != SYSTEMD_SYSTEM)
+ return 0;
+
+ r = unit_add_two_dependencies_by_name(UNIT(a), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_UMOUNT_TARGET, NULL, true);
+ if (r < 0)
+ return r;
+
+ return 0;
+}
+
+static int automount_verify(Automount *a) {
+ bool b;
+ char *e;
+ assert(a);
+
+ if (UNIT(a)->load_state != UNIT_LOADED)
+ return 0;
+
+ if (path_equal(a->where, "/")) {
+ log_error_unit(UNIT(a)->id, "Cannot have an automount unit for the root directory. Refusing.");
+ return -EINVAL;
+ }
+
+ e = unit_name_from_path(a->where, ".automount");
+ if (!e)
+ return -ENOMEM;
+
+ b = unit_has_name(UNIT(a), e);
+ free(e);
+
+ if (!b) {
+ log_error_unit(UNIT(a)->id, "%s's Where setting doesn't match unit name. Refusing.", UNIT(a)->id);
+ return -EINVAL;
+ }
+
+ return 0;
+}
+
+static int automount_load(Unit *u) {
+ Automount *a = AUTOMOUNT(u);
+ int r;
+
+ assert(u);
+ assert(u->load_state == UNIT_STUB);
+
+ /* Load a .automount file */
+ r = unit_load_fragment_and_dropin_optional(u);
+ if (r < 0)
+ return r;
+
+ if (u->load_state == UNIT_LOADED) {
+ Unit *x;
+
+ if (!a->where) {
+ a->where = unit_name_to_path(u->id);
+ if (!a->where)
+ return -ENOMEM;
+ }
+
+ path_kill_slashes(a->where);
+
+ r = unit_load_related_unit(u, ".mount", &x);
+ if (r < 0)
+ return r;
+
+ r = unit_add_two_dependencies(u, UNIT_BEFORE, UNIT_TRIGGERS, x, true);
+ if (r < 0)
+ return r;
+
+ r = automount_add_mount_links(a);
+ if (r < 0)
+ return r;
+
+ if (UNIT(a)->default_dependencies) {
+ r = automount_add_default_dependencies(a);
+ if (r < 0)
+ return r;
+ }
+ }
+
+ return automount_verify(a);
+}
+
+static void automount_set_state(Automount *a, AutomountState state) {
+ AutomountState old_state;
+ assert(a);
+
+ old_state = a->state;
+ a->state = state;
+
+ if (state != AUTOMOUNT_WAITING &&
+ state != AUTOMOUNT_RUNNING)
+ unmount_autofs(a);
+
+ if (state != old_state)
+ log_debug_unit(UNIT(a)->id,
+ "%s changed %s -> %s",
+ UNIT(a)->id,
+ automount_state_to_string(old_state),
+ automount_state_to_string(state));
+
+ unit_notify(UNIT(a), state_translation_table[old_state], state_translation_table[state], true);
+}
+
+static int automount_coldplug(Unit *u) {
+ Automount *a = AUTOMOUNT(u);
+ int r;
+
+ assert(a);
+ assert(a->state == AUTOMOUNT_DEAD);
+
+ if (a->deserialized_state != a->state) {
+
+ r = open_dev_autofs(u->manager);
+ if (r < 0)
+ return r;
+
+ if (a->deserialized_state == AUTOMOUNT_WAITING ||
+ a->deserialized_state == AUTOMOUNT_RUNNING) {
+
+ assert(a->pipe_fd >= 0);
+
+ r = unit_watch_fd(UNIT(a), a->pipe_fd, EPOLLIN, &a->pipe_watch);
+ if (r < 0)
+ return r;
+ }
+
+ automount_set_state(a, a->deserialized_state);
+ }
+
+ return 0;
+}
+
+static void automount_dump(Unit *u, FILE *f, const char *prefix) {
+ Automount *a = AUTOMOUNT(u);
+
+ assert(a);
+
+ fprintf(f,
+ "%sAutomount State: %s\n"
+ "%sResult: %s\n"
+ "%sWhere: %s\n"
+ "%sDirectoryMode: %04o\n",
+ prefix, automount_state_to_string(a->state),
+ prefix, automount_result_to_string(a->result),
+ prefix, a->where,
+ prefix, a->directory_mode);
+}
+
+static void automount_enter_dead(Automount *a, AutomountResult f) {
+ assert(a);
+
+ if (f != AUTOMOUNT_SUCCESS)
+ a->result = f;
+
+ automount_set_state(a, a->result != AUTOMOUNT_SUCCESS ? AUTOMOUNT_FAILED : AUTOMOUNT_DEAD);
+}
+
+static int open_dev_autofs(Manager *m) {
+ struct autofs_dev_ioctl param;
+
+ assert(m);
+
+ if (m->dev_autofs_fd >= 0)
+ return m->dev_autofs_fd;
+
+ label_fix("/dev/autofs", false, false);
+
+ m->dev_autofs_fd = open("/dev/autofs", O_CLOEXEC|O_RDONLY);
+ if (m->dev_autofs_fd < 0) {
+ log_error("Failed to open /dev/autofs: %s", strerror(errno));
+ return -errno;
+ }
+
+ init_autofs_dev_ioctl(&param);
+ if (ioctl(m->dev_autofs_fd, AUTOFS_DEV_IOCTL_VERSION, &param) < 0) {
+ close_nointr_nofail(m->dev_autofs_fd);
+ m->dev_autofs_fd = -1;
+ return -errno;
+ }
+
+ log_debug("Autofs kernel version %i.%i", param.ver_major, param.ver_minor);
+
+ return m->dev_autofs_fd;
+}
+
+static int open_ioctl_fd(int dev_autofs_fd, const char *where, dev_t devid) {
+ struct autofs_dev_ioctl *param;
+ size_t l;
+
+ assert(dev_autofs_fd >= 0);
+ assert(where);
+
+ l = sizeof(struct autofs_dev_ioctl) + strlen(where) + 1;
+ param = alloca(l);
+
+ init_autofs_dev_ioctl(param);
+ param->size = l;
+ param->ioctlfd = -1;
+ param->openmount.devid = devid;
+ strcpy(param->path, where);
+
+ if (ioctl(dev_autofs_fd, AUTOFS_DEV_IOCTL_OPENMOUNT, param) < 0)
+ return -errno;
+
+ if (param->ioctlfd < 0)
+ return -EIO;
+
+ fd_cloexec(param->ioctlfd, true);
+ return param->ioctlfd;
+}
+
+static int autofs_protocol(int dev_autofs_fd, int ioctl_fd) {
+ uint32_t major, minor;
+ struct autofs_dev_ioctl param;
+
+ assert(dev_autofs_fd >= 0);
+ assert(ioctl_fd >= 0);
+
+ init_autofs_dev_ioctl(&param);
+ param.ioctlfd = ioctl_fd;
+
+ if (ioctl(dev_autofs_fd, AUTOFS_DEV_IOCTL_PROTOVER, &param) < 0)
+ return -errno;
+
+ major = param.protover.version;
+
+ init_autofs_dev_ioctl(&param);
+ param.ioctlfd = ioctl_fd;
+
+ if (ioctl(dev_autofs_fd, AUTOFS_DEV_IOCTL_PROTOSUBVER, &param) < 0)
+ return -errno;
+
+ minor = param.protosubver.sub_version;
+
+ log_debug("Autofs protocol version %i.%i", major, minor);
+ return 0;
+}
+
+static int autofs_set_timeout(int dev_autofs_fd, int ioctl_fd, time_t sec) {
+ struct autofs_dev_ioctl param;
+
+ assert(dev_autofs_fd >= 0);
+ assert(ioctl_fd >= 0);
+
+ init_autofs_dev_ioctl(&param);
+ param.ioctlfd = ioctl_fd;
+ param.timeout.timeout = sec;
+
+ if (ioctl(dev_autofs_fd, AUTOFS_DEV_IOCTL_TIMEOUT, &param) < 0)
+ return -errno;
+
+ return 0;
+}
+
+static int autofs_send_ready(int dev_autofs_fd, int ioctl_fd, uint32_t token, int status) {
+ struct autofs_dev_ioctl param;
+
+ assert(dev_autofs_fd >= 0);
+ assert(ioctl_fd >= 0);
+
+ init_autofs_dev_ioctl(&param);
+ param.ioctlfd = ioctl_fd;
+
+ if (status) {
+ param.fail.token = token;
+ param.fail.status = status;
+ } else
+ param.ready.token = token;
+
+ if (ioctl(dev_autofs_fd, status ? AUTOFS_DEV_IOCTL_FAIL : AUTOFS_DEV_IOCTL_READY, &param) < 0)
+ return -errno;
+
+ return 0;
+}
+
+int automount_send_ready(Automount *a, int status) {
+ int ioctl_fd, r;
+ unsigned token;
+
+ assert(a);
+ assert(status <= 0);
+
+ if (set_isempty(a->tokens))
+ return 0;
+
+ ioctl_fd = open_ioctl_fd(UNIT(a)->manager->dev_autofs_fd, a->where, a->dev_id);
+ if (ioctl_fd < 0) {
+ r = ioctl_fd;
+ goto fail;
+ }
+
+ if (status)
+ log_debug_unit(UNIT(a)->id, "Sending failure: %s", strerror(-status));
+ else
+ log_debug_unit(UNIT(a)->id, "Sending success.");
+
+ r = 0;
+
+ /* Autofs thankfully does not hand out 0 as a token */
+ while ((token = PTR_TO_UINT(set_steal_first(a->tokens)))) {
+ int k;
+
+ /* Autofs fun fact II:
+ *
+ * if you pass a positive status code here, the kernel will
+ * freeze! Yay! */
+
+ k = autofs_send_ready(UNIT(a)->manager->dev_autofs_fd,
+ ioctl_fd,
+ token,
+ status);
+ if (k < 0)
+ r = k;
+ }
+
+fail:
+ if (ioctl_fd >= 0)
+ close_nointr_nofail(ioctl_fd);
+
+ return r;
+}
+
+static void automount_enter_waiting(Automount *a) {
+ int p[2] = { -1, -1 };
+ char name[32], options[128];
+ bool mounted = false;
+ int r, ioctl_fd = -1, dev_autofs_fd;
+ struct stat st;
+
+ assert(a);
+ assert(a->pipe_fd < 0);
+ assert(a->where);
+
+ if (a->tokens)
+ set_clear(a->tokens);
+
+ dev_autofs_fd = open_dev_autofs(UNIT(a)->manager);
+ if (dev_autofs_fd < 0) {
+ r = dev_autofs_fd;
+ goto fail;
+ }
+
+ /* We knowingly ignore the results of this call */
+ mkdir_p_label(a->where, 0555);
+
+ warn_if_dir_nonempty(a->meta.id, a->where);
+
+ if (pipe2(p, O_NONBLOCK|O_CLOEXEC) < 0) {
+ r = -errno;
+ goto fail;
+ }
+
+ snprintf(options, sizeof(options), "fd=%i,pgrp=%u,minproto=5,maxproto=5,direct", p[1], (unsigned) getpgrp());
+ char_array_0(options);
+
+ snprintf(name, sizeof(name), "systemd-%u", (unsigned) getpid());
+ char_array_0(name);
+
+ if (mount(name, a->where, "autofs", 0, options) < 0) {
+ r = -errno;
+ goto fail;
+ }
+
+ mounted = true;
+
+ close_nointr_nofail(p[1]);
+ p[1] = -1;
+
+ if (stat(a->where, &st) < 0) {
+ r = -errno;
+ goto fail;
+ }
+
+ ioctl_fd = open_ioctl_fd(dev_autofs_fd, a->where, st.st_dev);
+ if (ioctl_fd < 0) {
+ r = ioctl_fd;
+ goto fail;
+ }
+
+ r = autofs_protocol(dev_autofs_fd, ioctl_fd);
+ if (r < 0)
+ goto fail;
+
+ r = autofs_set_timeout(dev_autofs_fd, ioctl_fd, 300);
+ if (r < 0)
+ goto fail;
+
+ /* Autofs fun fact:
+ *
+ * Unless we close the ioctl fd here, for some weird reason
+ * the direct mount will not receive events from the
+ * kernel. */
+
+ close_nointr_nofail(ioctl_fd);
+ ioctl_fd = -1;
+
+ r = unit_watch_fd(UNIT(a), p[0], EPOLLIN, &a->pipe_watch);
+ if (r < 0)
+ goto fail;
+
+ a->pipe_fd = p[0];
+ a->dev_id = st.st_dev;
+
+ automount_set_state(a, AUTOMOUNT_WAITING);
+
+ return;
+
+fail:
+ assert_se(close_pipe(p) == 0);
+
+ if (ioctl_fd >= 0)
+ close_nointr_nofail(ioctl_fd);
+
+ if (mounted)
+ repeat_unmout(a->where);
+
+ log_error_unit(UNIT(a)->id,
+ "Failed to initialize automounter: %s", strerror(-r));
+ automount_enter_dead(a, AUTOMOUNT_FAILURE_RESOURCES);
+}
+
+static void automount_enter_runnning(Automount *a) {
+ _cleanup_dbus_error_free_ DBusError error;
+ struct stat st;
+ int r;
+
+ assert(a);
+
+ dbus_error_init(&error);
+
+ /* We don't take mount requests anymore if we are supposed to
+ * shut down anyway */
+ if (unit_stop_pending(UNIT(a))) {
+ log_debug_unit(UNIT(a)->id,
+ "Suppressing automount request on %s since unit stop is scheduled.", UNIT(a)->id);
+ automount_send_ready(a, -EHOSTDOWN);
+ return;
+ }
+
+ mkdir_p_label(a->where, a->directory_mode);
+
+ /* Before we do anything, let's see if somebody is playing games with us? */
+ if (lstat(a->where, &st) < 0) {
+ log_warning_unit(UNIT(a)->id,
+ "%s failed to stat automount point: %m", UNIT(a)->id);
+ goto fail;
+ }
+
+ if (!S_ISDIR(st.st_mode) || st.st_dev != a->dev_id)
+ log_info_unit(UNIT(a)->id,
+ "%s's automount point already active?", UNIT(a)->id);
+ else {
+ r = manager_add_job(UNIT(a)->manager, JOB_START, UNIT_TRIGGER(UNIT(a)),
+ JOB_REPLACE, true, &error, NULL);
+ if (r < 0) {
+ log_warning_unit(UNIT(a)->id,
+ "%s failed to queue mount startup job: %s",
+ UNIT(a)->id, bus_error(&error, r));
+ goto fail;
+ }
+ }
+
+ automount_set_state(a, AUTOMOUNT_RUNNING);
+ return;
+
+fail:
+ automount_enter_dead(a, AUTOMOUNT_FAILURE_RESOURCES);
+}
+
+static int automount_start(Unit *u) {
+ Automount *a = AUTOMOUNT(u);
+
+ assert(a);
+ assert(a->state == AUTOMOUNT_DEAD || a->state == AUTOMOUNT_FAILED);
+
+ if (path_is_mount_point(a->where, false)) {
+ log_error_unit(u->id,
+ "Path %s is already a mount point, refusing start for %s",
+ a->where, u->id);
+ return -EEXIST;
+ }
+
+ if (UNIT_TRIGGER(u)->load_state != UNIT_LOADED)
+ return -ENOENT;
+
+ a->result = AUTOMOUNT_SUCCESS;
+ automount_enter_waiting(a);
+ return 0;
+}
+
+static int automount_stop(Unit *u) {
+ Automount *a = AUTOMOUNT(u);
+
+ assert(a);
+ assert(a->state == AUTOMOUNT_WAITING || a->state == AUTOMOUNT_RUNNING);
+
+ automount_enter_dead(a, AUTOMOUNT_SUCCESS);
+ return 0;
+}
+
+static int automount_serialize(Unit *u, FILE *f, FDSet *fds) {
+ Automount *a = AUTOMOUNT(u);
+ void *p;
+ Iterator i;
+
+ assert(a);
+ assert(f);
+ assert(fds);
+
+ unit_serialize_item(u, f, "state", automount_state_to_string(a->state));
+ unit_serialize_item(u, f, "result", automount_result_to_string(a->result));
+ unit_serialize_item_format(u, f, "dev-id", "%u", (unsigned) a->dev_id);
+
+ SET_FOREACH(p, a->tokens, i)
+ unit_serialize_item_format(u, f, "token", "%u", PTR_TO_UINT(p));
+
+ if (a->pipe_fd >= 0) {
+ int copy;
+
+ copy = fdset_put_dup(fds, a->pipe_fd);
+ if (copy < 0)
+ return copy;
+
+ unit_serialize_item_format(u, f, "pipe-fd", "%i", copy);
+ }
+
+ return 0;
+}
+
+static int automount_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
+ Automount *a = AUTOMOUNT(u);
+ int r;
+
+ assert(a);
+ assert(fds);
+
+ if (streq(key, "state")) {
+ AutomountState state;
+
+ state = automount_state_from_string(value);
+ if (state < 0)
+ log_debug_unit(u->id, "Failed to parse state value %s", value);
+ else
+ a->deserialized_state = state;
+ } else if (streq(key, "result")) {
+ AutomountResult f;
+
+ f = automount_result_from_string(value);
+ if (f < 0)
+ log_debug_unit(u->id, "Failed to parse result value %s", value);
+ else if (f != AUTOMOUNT_SUCCESS)
+ a->result = f;
+
+ } else if (streq(key, "dev-id")) {
+ unsigned d;
+
+ if (safe_atou(value, &d) < 0)
+ log_debug_unit(u->id, "Failed to parse dev-id value %s", value);
+ else
+ a->dev_id = (unsigned) d;
+ } else if (streq(key, "token")) {
+ unsigned token;
+
+ if (safe_atou(value, &token) < 0)
+ log_debug_unit(u->id, "Failed to parse token value %s", value);
+ else {
+ if (!a->tokens)
+ if (!(a->tokens = set_new(trivial_hash_func, trivial_compare_func)))
+ return -ENOMEM;
+
+ r = set_put(a->tokens, UINT_TO_PTR(token));
+ if (r < 0)
+ return r;
+ }
+ } else if (streq(key, "pipe-fd")) {
+ int fd;
+
+ if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
+ log_debug_unit(u->id, "Failed to parse pipe-fd value %s", value);
+ else {
+ if (a->pipe_fd >= 0)
+ close_nointr_nofail(a->pipe_fd);
+
+ a->pipe_fd = fdset_remove(fds, fd);
+ }
+ } else
+ log_debug_unit(u->id, "Unknown serialization key '%s'", key);
+
+ return 0;
+}
+
+static UnitActiveState automount_active_state(Unit *u) {
+ assert(u);
+
+ return state_translation_table[AUTOMOUNT(u)->state];
+}
+
+static const char *automount_sub_state_to_string(Unit *u) {
+ assert(u);
+
+ return automount_state_to_string(AUTOMOUNT(u)->state);
+}
+
+static bool automount_check_gc(Unit *u) {
+ assert(u);
+
+ if (!UNIT_TRIGGER(u))
+ return false;
+
+ return UNIT_VTABLE(UNIT_TRIGGER(u))->check_gc(UNIT_TRIGGER(u));
+}
+
+static void automount_fd_event(Unit *u, int fd, uint32_t events, Watch *w) {
+ Automount *a = AUTOMOUNT(u);
+ union autofs_v5_packet_union packet;
+ ssize_t l;
+ int r;
+
+ assert(a);
+ assert(fd == a->pipe_fd);
+
+ if (events != EPOLLIN) {
+ log_error_unit(u->id, "Got invalid poll event on pipe.");
+ goto fail;
+ }
+
+ l = loop_read(a->pipe_fd, &packet, sizeof(packet), true);
+ if (l != sizeof(packet)) {
+ log_error_unit(u->id, "Invalid read from pipe: %s", l < 0 ? strerror(-l) : "short read");
+ goto fail;
+ }
+
+ switch (packet.hdr.type) {
+
+ case autofs_ptype_missing_direct:
+
+ if (packet.v5_packet.pid > 0) {
+ _cleanup_free_ char *p = NULL;
+
+ get_process_comm(packet.v5_packet.pid, &p);
+ log_debug_unit(u->id,
+ "Got direct mount request on %s, triggered by %lu (%s)",
+ a->where, (unsigned long) packet.v5_packet.pid, strna(p));
+ } else
+ log_debug_unit(u->id, "Got direct mount request on %s", a->where);
+
+ r = set_ensure_allocated(&a->tokens, trivial_hash_func, trivial_compare_func);
+ if (r < 0) {
+ log_error_unit(u->id, "Failed to allocate token set.");
+ goto fail;
+ }
+
+ r = set_put(a->tokens, UINT_TO_PTR(packet.v5_packet.wait_queue_token));
+ if (r < 0) {
+ log_error_unit(u->id, "Failed to remember token: %s", strerror(-r));
+ goto fail;
+ }
+
+ automount_enter_runnning(a);
+ break;
+
+ default:
+ log_error_unit(u->id, "Received unknown automount request %i", packet.hdr.type);
+ break;
+ }
+
+ return;
+
+fail:
+ automount_enter_dead(a, AUTOMOUNT_FAILURE_RESOURCES);
+}
+
+static void automount_shutdown(Manager *m) {
+ assert(m);
+
+ if (m->dev_autofs_fd >= 0)
+ close_nointr_nofail(m->dev_autofs_fd);
+}
+
+static void automount_reset_failed(Unit *u) {
+ Automount *a = AUTOMOUNT(u);
+
+ assert(a);
+
+ if (a->state == AUTOMOUNT_FAILED)
+ automount_set_state(a, AUTOMOUNT_DEAD);
+
+ a->result = AUTOMOUNT_SUCCESS;
+}
+
+static const char* const automount_state_table[_AUTOMOUNT_STATE_MAX] = {
+ [AUTOMOUNT_DEAD] = "dead",
+ [AUTOMOUNT_WAITING] = "waiting",
+ [AUTOMOUNT_RUNNING] = "running",
+ [AUTOMOUNT_FAILED] = "failed"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(automount_state, AutomountState);
+
+static const char* const automount_result_table[_AUTOMOUNT_RESULT_MAX] = {
+ [AUTOMOUNT_SUCCESS] = "success",
+ [AUTOMOUNT_FAILURE_RESOURCES] = "resources"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(automount_result, AutomountResult);
+
+const UnitVTable automount_vtable = {
+ .object_size = sizeof(Automount),
+ .sections =
+ "Unit\0"
+ "Automount\0"
+ "Install\0",
+
+ .no_alias = true,
+ .no_instances = true,
+
+ .init = automount_init,
+ .load = automount_load,
+ .done = automount_done,
+
+ .coldplug = automount_coldplug,
+
+ .dump = automount_dump,
+
+ .start = automount_start,
+ .stop = automount_stop,
+
+ .serialize = automount_serialize,
+ .deserialize_item = automount_deserialize_item,
+
+ .active_state = automount_active_state,
+ .sub_state_to_string = automount_sub_state_to_string,
+
+ .check_gc = automount_check_gc,
+
+ .fd_event = automount_fd_event,
+
+ .reset_failed = automount_reset_failed,
+
+ .bus_interface = "org.freedesktop.systemd1.Automount",
+ .bus_message_handler = bus_automount_message_handler,
+ .bus_invalidating_properties = bus_automount_invalidating_properties,
+
+ .shutdown = automount_shutdown,
+
+ .status_message_formats = {
+ .finished_start_job = {
+ [JOB_DONE] = "Set up automount %s.",
+ [JOB_FAILED] = "Failed to set up automount %s.",
+ [JOB_DEPENDENCY] = "Dependency failed for %s.",
+ },
+ .finished_stop_job = {
+ [JOB_DONE] = "Unset automount %s.",
+ [JOB_FAILED] = "Failed to unset automount %s.",
+ },
+ },
+};
diff --git a/src/core/automount.h b/src/core/automount.h
new file mode 100644
index 0000000000..0c6b8a72e9
--- /dev/null
+++ b/src/core/automount.h
@@ -0,0 +1,71 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+typedef struct Automount Automount;
+
+#include "unit.h"
+
+typedef enum AutomountState {
+ AUTOMOUNT_DEAD,
+ AUTOMOUNT_WAITING,
+ AUTOMOUNT_RUNNING,
+ AUTOMOUNT_FAILED,
+ _AUTOMOUNT_STATE_MAX,
+ _AUTOMOUNT_STATE_INVALID = -1
+} AutomountState;
+
+typedef enum AutomountResult {
+ AUTOMOUNT_SUCCESS,
+ AUTOMOUNT_FAILURE_RESOURCES,
+ _AUTOMOUNT_RESULT_MAX,
+ _AUTOMOUNT_RESULT_INVALID = -1
+} AutomountResult;
+
+struct Automount {
+ Unit meta;
+
+ AutomountState state, deserialized_state;
+
+ char *where;
+
+ int pipe_fd;
+ mode_t directory_mode;
+ Watch pipe_watch;
+ dev_t dev_id;
+
+ Set *tokens;
+
+ AutomountResult result;
+};
+
+extern const UnitVTable automount_vtable;
+
+int automount_send_ready(Automount *a, int status);
+
+int automount_add_one_mount_link(Automount *a, Mount *m);
+
+const char* automount_state_to_string(AutomountState i) _const_;
+AutomountState automount_state_from_string(const char *s) _pure_;
+
+const char* automount_result_to_string(AutomountResult i) _const_;
+AutomountResult automount_result_from_string(const char *s) _pure_;
diff --git a/src/core/build.h b/src/core/build.h
new file mode 100644
index 0000000000..4513a0bad7
--- /dev/null
+++ b/src/core/build.h
@@ -0,0 +1,84 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#ifdef HAVE_PAM
+#define _PAM_FEATURE_ "+PAM"
+#else
+#define _PAM_FEATURE_ "-PAM"
+#endif
+
+#ifdef HAVE_LIBWRAP
+#define _LIBWRAP_FEATURE_ "+LIBWRAP"
+#else
+#define _LIBWRAP_FEATURE_ "-LIBWRAP"
+#endif
+
+#ifdef HAVE_AUDIT
+#define _AUDIT_FEATURE_ "+AUDIT"
+#else
+#define _AUDIT_FEATURE_ "-AUDIT"
+#endif
+
+#ifdef HAVE_SELINUX
+#define _SELINUX_FEATURE_ "+SELINUX"
+#else
+#define _SELINUX_FEATURE_ "-SELINUX"
+#endif
+
+#ifdef HAVE_IMA
+#define _IMA_FEATURE_ "+IMA"
+#else
+#define _IMA_FEATURE_ "-IMA"
+#endif
+
+#ifdef HAVE_SYSV_COMPAT
+#define _SYSVINIT_FEATURE_ "+SYSVINIT"
+#else
+#define _SYSVINIT_FEATURE_ "-SYSVINIT"
+#endif
+
+#ifdef HAVE_LIBCRYPTSETUP
+#define _LIBCRYPTSETUP_FEATURE_ "+LIBCRYPTSETUP"
+#else
+#define _LIBCRYPTSETUP_FEATURE_ "-LIBCRYPTSETUP"
+#endif
+
+#ifdef HAVE_GCRYPT
+#define _GCRYPT_FEATURE_ "+GCRYPT"
+#else
+#define _GCRYPT_FEATURE_ "-GCRYPT"
+#endif
+
+#ifdef HAVE_ACL
+#define _ACL_FEATURE_ "+ACL"
+#else
+#define _ACL_FEATURE_ "-ACL"
+#endif
+
+#ifdef HAVE_XZ
+#define _XZ_FEATURE_ "+XZ"
+#else
+#define _XZ_FEATURE_ "-XZ"
+#endif
+
+#define SYSTEMD_FEATURES _PAM_FEATURE_ " " _LIBWRAP_FEATURE_ " " _AUDIT_FEATURE_ " " _SELINUX_FEATURE_ " " _IMA_FEATURE_ " " _SYSVINIT_FEATURE_ " " _LIBCRYPTSETUP_FEATURE_ " " _GCRYPT_FEATURE_ " " _ACL_FEATURE_ " " _XZ_FEATURE_
diff --git a/src/core/bus-errors.h b/src/core/bus-errors.h
new file mode 100644
index 0000000000..7a4084ea15
--- /dev/null
+++ b/src/core/bus-errors.h
@@ -0,0 +1,42 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#define BUS_ERROR_NO_SUCH_UNIT "org.freedesktop.systemd1.NoSuchUnit"
+#define BUS_ERROR_NO_SUCH_JOB "org.freedesktop.systemd1.NoSuchJob"
+#define BUS_ERROR_NOT_SUBSCRIBED "org.freedesktop.systemd1.NotSubscribed"
+#define BUS_ERROR_INVALID_PATH "org.freedesktop.systemd1.InvalidPath"
+#define BUS_ERROR_INVALID_NAME "org.freedesktop.systemd1.InvalidName"
+#define BUS_ERROR_UNIT_TYPE_MISMATCH "org.freedesktop.systemd1.UnitTypeMismatch"
+#define BUS_ERROR_UNIT_EXISTS "org.freedesktop.systemd1.UnitExists"
+#define BUS_ERROR_NOT_SUPPORTED "org.freedesktop.systemd1.NotSupported"
+#define BUS_ERROR_INVALID_JOB_MODE "org.freedesktop.systemd1.InvalidJobMode"
+#define BUS_ERROR_ONLY_BY_DEPENDENCY "org.freedesktop.systemd1.OnlyByDependency"
+#define BUS_ERROR_NO_ISOLATION "org.freedesktop.systemd1.NoIsolation"
+#define BUS_ERROR_LOAD_FAILED "org.freedesktop.systemd1.LoadFailed"
+#define BUS_ERROR_MASKED "org.freedesktop.systemd1.Masked"
+#define BUS_ERROR_JOB_TYPE_NOT_APPLICABLE "org.freedesktop.systemd1.JobTypeNotApplicable"
+#define BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE "org.freedesktop.systemd1.TransactionIsDestructive"
+#define BUS_ERROR_TRANSACTION_JOBS_CONFLICTING "org.freedesktop.systemd1.TransactionJobsConflicting"
+#define BUS_ERROR_TRANSACTION_ORDER_IS_CYCLIC "org.freedesktop.systemd1.TransactionOrderIsCyclic"
+#define BUS_ERROR_SHUTTING_DOWN "org.freedesktop.systemd1.ShuttingDown"
+#define BUS_ERROR_NO_SUCH_PROCESS "org.freedesktop.systemd1.NoSuchProcess"
diff --git a/src/core/cgroup-attr.c b/src/core/cgroup-attr.c
new file mode 100644
index 0000000000..7e3e08eabb
--- /dev/null
+++ b/src/core/cgroup-attr.c
@@ -0,0 +1,132 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "cgroup-attr.h"
+#include "cgroup-util.h"
+#include "list.h"
+#include "fileio.h"
+
+int cgroup_attribute_apply(CGroupAttribute *a, CGroupBonding *b) {
+ _cleanup_free_ char *path = NULL, *v = NULL;
+ int r;
+
+ assert(a);
+
+ b = cgroup_bonding_find_list(b, a->controller);
+ if (!b)
+ return 0;
+
+ if (a->semantics && a->semantics->map_write) {
+ r = a->semantics->map_write(a->semantics, a->value, &v);
+ if (r < 0)
+ return r;
+ }
+
+ r = cg_get_path(a->controller, b->path, a->name, &path);
+ if (r < 0)
+ return r;
+
+ r = write_string_file(path, v ? v : a->value);
+ if (r < 0)
+ log_warning("Failed to write '%s' to %s: %s", v ? v : a->value, path, strerror(-r));
+
+ return r;
+}
+
+int cgroup_attribute_apply_list(CGroupAttribute *first, CGroupBonding *b) {
+ CGroupAttribute *a;
+ int r = 0;
+
+ LIST_FOREACH(by_unit, a, first) {
+ int k;
+
+ k = cgroup_attribute_apply(a, b);
+ if (r == 0)
+ r = k;
+ }
+
+ return r;
+}
+
+bool cgroup_attribute_matches(CGroupAttribute *a, const char *controller, const char *name) {
+ assert(a);
+
+ if (controller) {
+ if (streq(a->controller, controller) && (!name || streq(a->name, name)))
+ return true;
+
+ } else if (!name)
+ return true;
+ else if (streq(a->name, name)) {
+ size_t x, y;
+ x = strlen(a->controller);
+ y = strlen(name);
+
+ if (y > x &&
+ memcmp(a->controller, name, x) == 0 &&
+ name[x] == '.')
+ return true;
+ }
+
+ return false;
+}
+
+CGroupAttribute *cgroup_attribute_find_list(
+ CGroupAttribute *first,
+ const char *controller,
+ const char *name) {
+ CGroupAttribute *a;
+
+ assert(name);
+
+ LIST_FOREACH(by_unit, a, first)
+ if (cgroup_attribute_matches(a, controller, name))
+ return a;
+
+ return NULL;
+}
+
+void cgroup_attribute_free(CGroupAttribute *a) {
+ assert(a);
+
+ if (a->unit)
+ LIST_REMOVE(CGroupAttribute, by_unit, a->unit->cgroup_attributes, a);
+
+ free(a->controller);
+ free(a->name);
+ free(a->value);
+ free(a);
+}
+
+void cgroup_attribute_free_list(CGroupAttribute *first) {
+ CGroupAttribute *a, *n;
+
+ LIST_FOREACH_SAFE(by_unit, a, n, first)
+ cgroup_attribute_free(a);
+}
+
+void cgroup_attribute_free_some(CGroupAttribute *first, const char *controller, const char *name) {
+ CGroupAttribute *a, *n;
+
+ LIST_FOREACH_SAFE(by_unit, a, n, first)
+ if (cgroup_attribute_matches(a, controller, name))
+ cgroup_attribute_free(a);
+}
diff --git a/src/core/cgroup-attr.h b/src/core/cgroup-attr.h
new file mode 100644
index 0000000000..3a13b7c92d
--- /dev/null
+++ b/src/core/cgroup-attr.h
@@ -0,0 +1,50 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+typedef struct CGroupAttribute CGroupAttribute;
+
+#include "unit.h"
+#include "cgroup.h"
+#include "cgroup-semantics.h"
+
+struct CGroupAttribute {
+ char *controller;
+ char *name;
+ char *value;
+
+ Unit *unit;
+
+ const CGroupSemantics *semantics;
+
+ LIST_FIELDS(CGroupAttribute, by_unit);
+};
+
+int cgroup_attribute_apply(CGroupAttribute *a, CGroupBonding *b);
+int cgroup_attribute_apply_list(CGroupAttribute *first, CGroupBonding *b);
+
+bool cgroup_attribute_matches(CGroupAttribute *a, const char *controller, const char *name) _pure_;
+CGroupAttribute *cgroup_attribute_find_list(CGroupAttribute *first, const char *controller, const char *name) _pure_;
+
+void cgroup_attribute_free(CGroupAttribute *a);
+void cgroup_attribute_free_list(CGroupAttribute *first);
+void cgroup_attribute_free_some(CGroupAttribute *first, const char *controller, const char *name);
diff --git a/src/core/cgroup-semantics.c b/src/core/cgroup-semantics.c
new file mode 100644
index 0000000000..82b02bbd78
--- /dev/null
+++ b/src/core/cgroup-semantics.c
@@ -0,0 +1,333 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "util.h"
+#include "strv.h"
+#include "path-util.h"
+#include "cgroup-util.h"
+
+#include "cgroup-semantics.h"
+
+static int parse_cpu_shares(const CGroupSemantics *s, const char *value, char **ret) {
+ unsigned long ul;
+
+ assert(s);
+ assert(value);
+ assert(ret);
+
+ if (safe_atolu(value, &ul) < 0 || ul < 1)
+ return -EINVAL;
+
+ if (asprintf(ret, "%lu", ul) < 0)
+ return -ENOMEM;
+
+ return 1;
+}
+
+static int parse_memory_limit(const CGroupSemantics *s, const char *value, char **ret) {
+ off_t sz;
+
+ assert(s);
+ assert(value);
+ assert(ret);
+
+ if (parse_bytes(value, &sz) < 0 || sz <= 0)
+ return -EINVAL;
+
+ if (asprintf(ret, "%llu", (unsigned long long) sz) < 0)
+ return -ENOMEM;
+
+ return 1;
+}
+
+static int parse_device(const CGroupSemantics *s, const char *value, char **ret) {
+ _cleanup_strv_free_ char **l = NULL;
+ char *x;
+ unsigned k;
+
+ assert(s);
+ assert(value);
+ assert(ret);
+
+ l = strv_split_quoted(value);
+ if (!l)
+ return -ENOMEM;
+
+ k = strv_length(l);
+ if (k < 1 || k > 2)
+ return -EINVAL;
+
+ if (!streq(l[0], "*") && !path_startswith(l[0], "/dev"))
+ return -EINVAL;
+
+ if (!isempty(l[1]) && !in_charset(l[1], "rwm"))
+ return -EINVAL;
+
+ x = strdup(value);
+ if (!x)
+ return -ENOMEM;
+
+ *ret = x;
+ return 1;
+}
+
+static int parse_blkio_weight(const CGroupSemantics *s, const char *value, char **ret) {
+ _cleanup_strv_free_ char **l = NULL;
+ unsigned long ul;
+
+ assert(s);
+ assert(value);
+ assert(ret);
+
+ l = strv_split_quoted(value);
+ if (!l)
+ return -ENOMEM;
+
+ if (strv_length(l) != 1)
+ return 0; /* Returning 0 will cause parse_blkio_weight_device() be tried instead */
+
+ if (safe_atolu(l[0], &ul) < 0 || ul < 10 || ul > 1000)
+ return -EINVAL;
+
+ if (asprintf(ret, "%lu", ul) < 0)
+ return -ENOMEM;
+
+ return 1;
+}
+
+static int parse_blkio_weight_device(const CGroupSemantics *s, const char *value, char **ret) {
+ _cleanup_strv_free_ char **l = NULL;
+ unsigned long ul;
+
+ assert(s);
+ assert(value);
+ assert(ret);
+
+ l = strv_split_quoted(value);
+ if (!l)
+ return -ENOMEM;
+
+ if (strv_length(l) != 2)
+ return -EINVAL;
+
+ if (!path_startswith(l[0], "/dev"))
+ return -EINVAL;
+
+ if (safe_atolu(l[1], &ul) < 0 || ul < 10 || ul > 1000)
+ return -EINVAL;
+
+ if (asprintf(ret, "%s %lu", l[0], ul) < 0)
+ return -ENOMEM;
+
+ return 1;
+}
+
+static int parse_blkio_bandwidth(const CGroupSemantics *s, const char *value, char **ret) {
+ _cleanup_strv_free_ char **l = NULL;
+ off_t bytes;
+
+ assert(s);
+ assert(value);
+ assert(ret);
+
+ l = strv_split_quoted(value);
+ if (!l)
+ return -ENOMEM;
+
+ if (strv_length(l) != 2)
+ return -EINVAL;
+
+ if (!path_startswith(l[0], "/dev")) {
+ return -EINVAL;
+ }
+
+ if (parse_bytes(l[1], &bytes) < 0 || bytes <= 0)
+ return -EINVAL;
+
+ if (asprintf(ret, "%s %llu", l[0], (unsigned long long) bytes) < 0)
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int map_device(const CGroupSemantics *s, const char *value, char **ret) {
+ _cleanup_strv_free_ char **l = NULL;
+ unsigned k;
+
+ assert(s);
+ assert(value);
+ assert(ret);
+
+ l = strv_split_quoted(value);
+ if (!l)
+ return -ENOMEM;
+
+ k = strv_length(l);
+ if (k < 1 || k > 2)
+ return -EINVAL;
+
+ if (streq(l[0], "*")) {
+
+ if (asprintf(ret, "a *:*%s%s",
+ isempty(l[1]) ? "" : " ", strempty(l[1])) < 0)
+ return -ENOMEM;
+ } else {
+ struct stat st;
+
+ if (stat(l[0], &st) < 0) {
+ log_warning("Couldn't stat device %s", l[0]);
+ return -errno;
+ }
+
+ if (!S_ISCHR(st.st_mode) && !S_ISBLK(st.st_mode)) {
+ log_warning("%s is not a device.", l[0]);
+ return -ENODEV;
+ }
+
+ if (asprintf(ret, "%c %u:%u%s%s",
+ S_ISCHR(st.st_mode) ? 'c' : 'b',
+ major(st.st_rdev), minor(st.st_rdev),
+ isempty(l[1]) ? "" : " ", strempty(l[1])) < 0)
+ return -ENOMEM;
+ }
+
+ return 0;
+}
+
+static int map_blkio(const CGroupSemantics *s, const char *value, char **ret) {
+ _cleanup_strv_free_ char **l = NULL;
+ struct stat st;
+ dev_t d;
+
+ assert(s);
+ assert(value);
+ assert(ret);
+
+ l = strv_split_quoted(value);
+ if (!l)
+ return log_oom();
+
+ if (strv_length(l) != 2)
+ return -EINVAL;
+
+ if (stat(l[0], &st) < 0) {
+ log_warning("Couldn't stat device %s", l[0]);
+ return -errno;
+ }
+
+ if (S_ISBLK(st.st_mode))
+ d = st.st_rdev;
+ else if (major(st.st_dev) != 0) {
+ /* If this is not a device node then find the block
+ * device this file is stored on */
+ d = st.st_dev;
+
+ /* If this is a partition, try to get the originating
+ * block device */
+ block_get_whole_disk(d, &d);
+ } else {
+ log_warning("%s is not a block device and file system block device cannot be determined or is not local.", l[0]);
+ return -ENODEV;
+ }
+
+ if (asprintf(ret, "%u:%u %s", major(d), minor(d), l[1]) < 0)
+ return -ENOMEM;
+
+ return 0;
+}
+
+static const CGroupSemantics semantics[] = {
+ { "cpu", "cpu.shares", "CPUShare", false, parse_cpu_shares, NULL, NULL },
+ { "memory", "memory.soft_limit_in_bytes", "MemorySoftLimit", false, parse_memory_limit, NULL, NULL },
+ { "memory", "memory.limit_in_bytes", "MemoryLimit", false, parse_memory_limit, NULL, NULL },
+ { "devices", "devices.allow", "DeviceAllow", true, parse_device, map_device, NULL },
+ { "devices", "devices.deny", "DeviceDeny", true, parse_device, map_device, NULL },
+ { "blkio", "blkio.weight", "BlockIOWeight", false, parse_blkio_weight, NULL, NULL },
+ { "blkio", "blkio.weight_device", "BlockIOWeight", true, parse_blkio_weight_device, map_blkio, NULL },
+ { "blkio", "blkio.read_bps_device", "BlockIOReadBandwidth", true, parse_blkio_bandwidth, map_blkio, NULL },
+ { "blkio", "blkio.write_bps_device", "BlockIOWriteBandwidth", true, parse_blkio_bandwidth, map_blkio, NULL }
+};
+
+int cgroup_semantics_find(
+ const char *controller,
+ const char *name,
+ const char *value,
+ char **ret,
+ const CGroupSemantics **_s) {
+
+ _cleanup_free_ char *c = NULL;
+ unsigned i;
+ int r;
+
+ assert(name);
+ assert(_s);
+ assert(!value == !ret);
+
+ if (!controller) {
+ r = cg_controller_from_attr(name, &c);
+ if (r < 0)
+ return r;
+
+ controller = c;
+ }
+
+ for (i = 0; i < ELEMENTSOF(semantics); i++) {
+ const CGroupSemantics *s = semantics + i;
+ bool matches_name, matches_pretty;
+
+ if (controller && s->controller && !streq(s->controller, controller))
+ continue;
+
+ matches_name = s->name && streq(s->name, name);
+ matches_pretty = s->pretty && streq(s->pretty, name);
+
+ if (!matches_name && !matches_pretty)
+ continue;
+
+ if (value) {
+ if (matches_pretty && s->map_pretty) {
+
+ r = s->map_pretty(s, value, ret);
+ if (r < 0)
+ return r;
+
+ if (r == 0)
+ continue;
+
+ } else {
+ char *x;
+
+ x = strdup(value);
+ if (!x)
+ return -ENOMEM;
+
+ *ret = x;
+ }
+ }
+
+ *_s = s;
+ return 1;
+ }
+
+ *ret = NULL;
+ *_s = NULL;
+ return 0;
+}
diff --git a/src/core/cgroup-semantics.h b/src/core/cgroup-semantics.h
new file mode 100644
index 0000000000..4f848f4bb7
--- /dev/null
+++ b/src/core/cgroup-semantics.h
@@ -0,0 +1,43 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+typedef struct CGroupSemantics CGroupSemantics;
+
+struct CGroupSemantics {
+ const char *controller;
+ const char *name;
+ const char *pretty;
+
+ bool multiple;
+
+ /* This call is used for parsing the pretty value to the actual attribute value */
+ int (*map_pretty)(const CGroupSemantics *semantics, const char *value, char **ret);
+
+ /* Right before writing this attribute the attribute value is converted to a low-level value */
+ int (*map_write)(const CGroupSemantics *semantics, const char *value, char **ret);
+
+ /* If this attribute takes a list, this call can be used to reset the list to empty */
+ int (*reset)(const CGroupSemantics *semantics, const char *group);
+};
+
+int cgroup_semantics_find(const char *controller, const char *name, const char *value, char **ret, const CGroupSemantics **semantics);
diff --git a/src/core/cgroup.c b/src/core/cgroup.c
new file mode 100644
index 0000000000..83df0f3c9a
--- /dev/null
+++ b/src/core/cgroup.c
@@ -0,0 +1,628 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <assert.h>
+#include <unistd.h>
+#include <sys/types.h>
+#include <signal.h>
+#include <sys/mount.h>
+#include <fcntl.h>
+
+#include "cgroup.h"
+#include "cgroup-util.h"
+#include "log.h"
+#include "strv.h"
+#include "path-util.h"
+
+int cgroup_bonding_realize(CGroupBonding *b) {
+ int r;
+
+ assert(b);
+ assert(b->path);
+ assert(b->controller);
+
+ r = cg_create(b->controller, b->path, NULL);
+ if (r < 0) {
+ log_warning("Failed to create cgroup %s:%s: %s", b->controller, b->path, strerror(-r));
+ return r;
+ }
+
+ b->realized = true;
+
+ return 0;
+}
+
+int cgroup_bonding_realize_list(CGroupBonding *first) {
+ CGroupBonding *b;
+ int r;
+
+ LIST_FOREACH(by_unit, b, first)
+ if ((r = cgroup_bonding_realize(b)) < 0 && b->essential)
+ return r;
+
+ return 0;
+}
+
+void cgroup_bonding_free(CGroupBonding *b, bool trim) {
+ assert(b);
+
+ if (b->unit) {
+ CGroupBonding *f;
+
+ LIST_REMOVE(CGroupBonding, by_unit, b->unit->cgroup_bondings, b);
+
+ if (streq(b->controller, SYSTEMD_CGROUP_CONTROLLER)) {
+ assert_se(f = hashmap_get(b->unit->manager->cgroup_bondings, b->path));
+ LIST_REMOVE(CGroupBonding, by_path, f, b);
+
+ if (f)
+ hashmap_replace(b->unit->manager->cgroup_bondings, b->path, f);
+ else
+ hashmap_remove(b->unit->manager->cgroup_bondings, b->path);
+ }
+ }
+
+ if (b->realized && b->ours && trim)
+ cg_trim(b->controller, b->path, false);
+
+ free(b->controller);
+ free(b->path);
+ free(b);
+}
+
+void cgroup_bonding_free_list(CGroupBonding *first, bool remove_or_trim) {
+ CGroupBonding *b, *n;
+
+ LIST_FOREACH_SAFE(by_unit, b, n, first)
+ cgroup_bonding_free(b, remove_or_trim);
+}
+
+void cgroup_bonding_trim(CGroupBonding *b, bool delete_root) {
+ assert(b);
+
+ if (b->realized && b->ours)
+ cg_trim(b->controller, b->path, delete_root);
+}
+
+void cgroup_bonding_trim_list(CGroupBonding *first, bool delete_root) {
+ CGroupBonding *b;
+
+ LIST_FOREACH(by_unit, b, first)
+ cgroup_bonding_trim(b, delete_root);
+}
+
+int cgroup_bonding_install(CGroupBonding *b, pid_t pid, const char *cgroup_suffix) {
+ _cleanup_free_ char *p = NULL;
+ const char *path;
+ int r;
+
+ assert(b);
+ assert(pid >= 0);
+
+ if (cgroup_suffix) {
+ p = strjoin(b->path, "/", cgroup_suffix, NULL);
+ if (!p)
+ return -ENOMEM;
+
+ path = p;
+ } else
+ path = b->path;
+
+ r = cg_create_and_attach(b->controller, path, pid);
+ if (r < 0)
+ return r;
+
+ b->realized = true;
+ return 0;
+}
+
+int cgroup_bonding_install_list(CGroupBonding *first, pid_t pid, const char *cgroup_suffix) {
+ CGroupBonding *b;
+ int r;
+
+ LIST_FOREACH(by_unit, b, first) {
+ r = cgroup_bonding_install(b, pid, cgroup_suffix);
+ if (r < 0 && b->essential)
+ return r;
+ }
+
+ return 0;
+}
+
+int cgroup_bonding_migrate(CGroupBonding *b, CGroupBonding *list) {
+ CGroupBonding *q;
+ int ret = 0;
+
+ LIST_FOREACH(by_unit, q, list) {
+ int r;
+
+ if (q == b)
+ continue;
+
+ if (!q->ours)
+ continue;
+
+ r = cg_migrate_recursive(q->controller, q->path, b->controller, b->path, true, false);
+ if (r < 0 && ret == 0)
+ ret = r;
+ }
+
+ return ret;
+}
+
+int cgroup_bonding_migrate_to(CGroupBonding *b, const char *target, bool rem) {
+ assert(b);
+ assert(target);
+
+ return cg_migrate_recursive(b->controller, b->path, b->controller, target, true, rem);
+}
+
+int cgroup_bonding_set_group_access(CGroupBonding *b, mode_t mode, uid_t uid, gid_t gid) {
+ assert(b);
+
+ if (!b->realized)
+ return -EINVAL;
+
+ return cg_set_group_access(b->controller, b->path, mode, uid, gid);
+}
+
+int cgroup_bonding_set_group_access_list(CGroupBonding *first, mode_t mode, uid_t uid, gid_t gid) {
+ CGroupBonding *b;
+ int r;
+
+ LIST_FOREACH(by_unit, b, first) {
+ r = cgroup_bonding_set_group_access(b, mode, uid, gid);
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+int cgroup_bonding_set_task_access(CGroupBonding *b, mode_t mode, uid_t uid, gid_t gid, int sticky) {
+ assert(b);
+
+ if (!b->realized)
+ return -EINVAL;
+
+ return cg_set_task_access(b->controller, b->path, mode, uid, gid, sticky);
+}
+
+int cgroup_bonding_set_task_access_list(CGroupBonding *first, mode_t mode, uid_t uid, gid_t gid, int sticky) {
+ CGroupBonding *b;
+ int r;
+
+ LIST_FOREACH(by_unit, b, first) {
+ r = cgroup_bonding_set_task_access(b, mode, uid, gid, sticky);
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+int cgroup_bonding_kill(CGroupBonding *b, int sig, bool sigcont, bool rem, Set *s, const char *cgroup_suffix) {
+ char *p = NULL;
+ const char *path;
+ int r;
+
+ assert(b);
+ assert(sig >= 0);
+
+ /* Don't kill cgroups that aren't ours */
+ if (!b->ours)
+ return 0;
+
+ if (cgroup_suffix) {
+ p = strjoin(b->path, "/", cgroup_suffix, NULL);
+ if (!p)
+ return -ENOMEM;
+
+ path = p;
+ } else
+ path = b->path;
+
+ r = cg_kill_recursive(b->controller, path, sig, sigcont, true, rem, s);
+ free(p);
+
+ return r;
+}
+
+int cgroup_bonding_kill_list(CGroupBonding *first, int sig, bool sigcont, bool rem, Set *s, const char *cgroup_suffix) {
+ CGroupBonding *b;
+ Set *allocated_set = NULL;
+ int ret = -EAGAIN, r;
+
+ if (!first)
+ return 0;
+
+ if (!s)
+ if (!(s = allocated_set = set_new(trivial_hash_func, trivial_compare_func)))
+ return -ENOMEM;
+
+ LIST_FOREACH(by_unit, b, first) {
+ r = cgroup_bonding_kill(b, sig, sigcont, rem, s, cgroup_suffix);
+ if (r < 0) {
+ if (r == -EAGAIN || r == -ESRCH)
+ continue;
+
+ ret = r;
+ goto finish;
+ }
+
+ if (ret < 0 || r > 0)
+ ret = r;
+ }
+
+finish:
+ if (allocated_set)
+ set_free(allocated_set);
+
+ return ret;
+}
+
+/* Returns 1 if the group is empty, 0 if it is not, -EAGAIN if we
+ * cannot know */
+int cgroup_bonding_is_empty(CGroupBonding *b) {
+ int r;
+
+ assert(b);
+
+ if ((r = cg_is_empty_recursive(b->controller, b->path, true)) < 0)
+ return r;
+
+ /* If it is empty it is empty */
+ if (r > 0)
+ return 1;
+
+ /* It's not only us using this cgroup, so we just don't know */
+ return b->ours ? 0 : -EAGAIN;
+}
+
+int cgroup_bonding_is_empty_list(CGroupBonding *first) {
+ CGroupBonding *b;
+
+ LIST_FOREACH(by_unit, b, first) {
+ int r;
+
+ if ((r = cgroup_bonding_is_empty(b)) < 0) {
+ /* If this returned -EAGAIN, then we don't know if the
+ * group is empty, so let's see if another group can
+ * tell us */
+
+ if (r != -EAGAIN)
+ return r;
+ } else
+ return r;
+ }
+
+ return -EAGAIN;
+}
+
+int manager_setup_cgroup(Manager *m) {
+ _cleanup_free_ char *current = NULL, *path = NULL;
+ char suffix_buffer[sizeof("/systemd-") + DECIMAL_STR_MAX(pid_t)];
+ const char *suffix;
+ int r;
+
+ assert(m);
+
+ /* 0. Be nice to Ingo Molnar #628004 */
+ if (path_is_mount_point("/sys/fs/cgroup/systemd", false) <= 0) {
+ log_warning("No control group support available, not creating root group.");
+ return 0;
+ }
+
+ /* 1. Determine hierarchy */
+ r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &current);
+ if (r < 0) {
+ log_error("Cannot determine cgroup we are running in: %s", strerror(-r));
+ return r;
+ }
+
+ if (m->running_as == SYSTEMD_SYSTEM)
+ suffix = "/system";
+ else {
+ sprintf(suffix_buffer, "/systemd-%lu", (unsigned long) getpid());
+ suffix = suffix_buffer;
+ }
+
+ free(m->cgroup_hierarchy);
+ if (endswith(current, suffix)) {
+ /* We probably got reexecuted and can continue to use our root cgroup */
+ m->cgroup_hierarchy = current;
+ current = NULL;
+ } else {
+ /* We need a new root cgroup */
+ if (streq(current, "/"))
+ m->cgroup_hierarchy = strdup(suffix);
+ else
+ m->cgroup_hierarchy = strappend(current, suffix);
+
+ if (!m->cgroup_hierarchy)
+ return log_oom();
+ }
+
+ /* 2. Show data */
+ r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_hierarchy, NULL, &path);
+ if (r < 0) {
+ log_error("Cannot find cgroup mount point: %s", strerror(-r));
+ return r;
+ }
+
+ log_debug("Using cgroup controller " SYSTEMD_CGROUP_CONTROLLER ". File system hierarchy is at %s.", path);
+
+ /* 3. Install agent */
+ if (m->running_as == SYSTEMD_SYSTEM) {
+ r = cg_install_release_agent(SYSTEMD_CGROUP_CONTROLLER, SYSTEMD_CGROUP_AGENT_PATH);
+ if (r < 0)
+ log_warning("Failed to install release agent, ignoring: %s", strerror(-r));
+ else if (r > 0)
+ log_debug("Installed release agent.");
+ else
+ log_debug("Release agent already installed.");
+ }
+
+ /* 4. Realize the group */
+ r = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_hierarchy, 0);
+ if (r < 0) {
+ log_error("Failed to create root cgroup hierarchy: %s", strerror(-r));
+ return r;
+ }
+
+ /* 5. And pin it, so that it cannot be unmounted */
+ if (m->pin_cgroupfs_fd >= 0)
+ close_nointr_nofail(m->pin_cgroupfs_fd);
+
+ m->pin_cgroupfs_fd = open(path, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOCTTY|O_NONBLOCK);
+ if (r < 0) {
+ log_error("Failed to open pin file: %m");
+ return -errno;
+ }
+
+ /* 6. Remove non-existing controllers from the default controllers list */
+ cg_shorten_controllers(m->default_controllers);
+
+ /* 7. Let's create the user and machine hierarchies
+ * right-away, so that people can inotify on them, if they
+ * wish, without this being racy. */
+ if (m->running_as == SYSTEMD_SYSTEM) {
+ cg_create(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_hierarchy, "../user");
+ cg_create(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_hierarchy, "../machine");
+ }
+
+ return 0;
+}
+
+void manager_shutdown_cgroup(Manager *m, bool delete) {
+ assert(m);
+
+ if (delete && m->cgroup_hierarchy)
+ cg_delete(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_hierarchy);
+
+ if (m->pin_cgroupfs_fd >= 0) {
+ close_nointr_nofail(m->pin_cgroupfs_fd);
+ m->pin_cgroupfs_fd = -1;
+ }
+
+ free(m->cgroup_hierarchy);
+ m->cgroup_hierarchy = NULL;
+}
+
+int cgroup_bonding_get(Manager *m, const char *cgroup, CGroupBonding **bonding) {
+ CGroupBonding *b;
+ char *p;
+
+ assert(m);
+ assert(cgroup);
+ assert(bonding);
+
+ b = hashmap_get(m->cgroup_bondings, cgroup);
+ if (b) {
+ *bonding = b;
+ return 1;
+ }
+
+ p = strdupa(cgroup);
+ if (!p)
+ return -ENOMEM;
+
+ for (;;) {
+ char *e;
+
+ e = strrchr(p, '/');
+ if (e == p || !e) {
+ *bonding = NULL;
+ return 0;
+ }
+
+ *e = 0;
+
+ b = hashmap_get(m->cgroup_bondings, p);
+ if (b) {
+ *bonding = b;
+ return 1;
+ }
+ }
+}
+
+int cgroup_notify_empty(Manager *m, const char *group) {
+ CGroupBonding *l, *b;
+ int r;
+
+ assert(m);
+ assert(group);
+
+ r = cgroup_bonding_get(m, group, &l);
+ if (r <= 0)
+ return r;
+
+ LIST_FOREACH(by_path, b, l) {
+ int t;
+
+ if (!b->unit)
+ continue;
+
+ t = cgroup_bonding_is_empty_list(b);
+ if (t < 0) {
+
+ /* If we don't know, we don't know */
+ if (t != -EAGAIN)
+ log_warning("Failed to check whether cgroup is empty: %s", strerror(errno));
+
+ continue;
+ }
+
+ if (t > 0) {
+ /* If it is empty, let's delete it */
+ cgroup_bonding_trim_list(b->unit->cgroup_bondings, true);
+
+ if (UNIT_VTABLE(b->unit)->cgroup_notify_empty)
+ UNIT_VTABLE(b->unit)->cgroup_notify_empty(b->unit);
+ }
+ }
+
+ return 0;
+}
+
+Unit* cgroup_unit_by_pid(Manager *m, pid_t pid) {
+ CGroupBonding *l, *b;
+ char *group = NULL;
+
+ assert(m);
+
+ if (pid <= 1)
+ return NULL;
+
+ if (cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &group) < 0)
+ return NULL;
+
+ l = hashmap_get(m->cgroup_bondings, group);
+
+ if (!l) {
+ char *slash;
+
+ while ((slash = strrchr(group, '/'))) {
+ if (slash == group)
+ break;
+
+ *slash = 0;
+
+ if ((l = hashmap_get(m->cgroup_bondings, group)))
+ break;
+ }
+ }
+
+ free(group);
+
+ LIST_FOREACH(by_path, b, l) {
+
+ if (!b->unit)
+ continue;
+
+ if (b->ours)
+ return b->unit;
+ }
+
+ return NULL;
+}
+
+CGroupBonding *cgroup_bonding_find_list(CGroupBonding *first, const char *controller) {
+ CGroupBonding *b;
+
+ if (!controller)
+ controller = SYSTEMD_CGROUP_CONTROLLER;
+
+ LIST_FOREACH(by_unit, b, first)
+ if (streq(b->controller, controller))
+ return b;
+
+ return NULL;
+}
+
+char *cgroup_bonding_to_string(CGroupBonding *b) {
+ char *r;
+
+ assert(b);
+
+ if (asprintf(&r, "%s:%s", b->controller, b->path) < 0)
+ return NULL;
+
+ return r;
+}
+
+pid_t cgroup_bonding_search_main_pid(CGroupBonding *b) {
+ FILE *f;
+ pid_t pid = 0, npid, mypid;
+
+ assert(b);
+
+ if (!b->ours)
+ return 0;
+
+ if (cg_enumerate_processes(b->controller, b->path, &f) < 0)
+ return 0;
+
+ mypid = getpid();
+
+ while (cg_read_pid(f, &npid) > 0) {
+ pid_t ppid;
+
+ if (npid == pid)
+ continue;
+
+ /* Ignore processes that aren't our kids */
+ if (get_parent_of_pid(npid, &ppid) >= 0 && ppid != mypid)
+ continue;
+
+ if (pid != 0) {
+ /* Dang, there's more than one daemonized PID
+ in this group, so we don't know what process
+ is the main process. */
+ pid = 0;
+ break;
+ }
+
+ pid = npid;
+ }
+
+ fclose(f);
+
+ return pid;
+}
+
+pid_t cgroup_bonding_search_main_pid_list(CGroupBonding *first) {
+ CGroupBonding *b;
+ pid_t pid;
+
+ /* Try to find a main pid from this cgroup, but checking if
+ * there's only one PID in the cgroup and returning it. Later
+ * on we might want to add additional, smarter heuristics
+ * here. */
+
+ LIST_FOREACH(by_unit, b, first)
+ if ((pid = cgroup_bonding_search_main_pid(b)) != 0)
+ return pid;
+
+ return 0;
+
+}
diff --git a/src/core/cgroup.h b/src/core/cgroup.h
new file mode 100644
index 0000000000..6555d89e37
--- /dev/null
+++ b/src/core/cgroup.h
@@ -0,0 +1,94 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+typedef struct CGroupBonding CGroupBonding;
+
+#include "unit.h"
+
+/* Binds a cgroup to a name */
+struct CGroupBonding {
+ char *controller;
+ char *path;
+
+ Unit *unit;
+
+ /* For the Unit::cgroup_bondings list */
+ LIST_FIELDS(CGroupBonding, by_unit);
+
+ /* For the Manager::cgroup_bondings hashmap */
+ LIST_FIELDS(CGroupBonding, by_path);
+
+ /* When shutting down, remove cgroup? Are our own tasks the
+ * only ones in this group?*/
+ bool ours:1;
+
+ /* If we cannot create this group, or add a process to it, is this fatal? */
+ bool essential:1;
+
+ /* This cgroup is realized */
+ bool realized:1;
+};
+
+int cgroup_bonding_realize(CGroupBonding *b);
+int cgroup_bonding_realize_list(CGroupBonding *first);
+
+void cgroup_bonding_free(CGroupBonding *b, bool trim);
+void cgroup_bonding_free_list(CGroupBonding *first, bool trim);
+
+int cgroup_bonding_install(CGroupBonding *b, pid_t pid, const char *suffix);
+int cgroup_bonding_install_list(CGroupBonding *first, pid_t pid, const char *suffix);
+
+int cgroup_bonding_migrate(CGroupBonding *b, CGroupBonding *list);
+int cgroup_bonding_migrate_to(CGroupBonding *b, const char *target, bool rem);
+
+int cgroup_bonding_set_group_access(CGroupBonding *b, mode_t mode, uid_t uid, gid_t gid);
+int cgroup_bonding_set_group_access_list(CGroupBonding *b, mode_t mode, uid_t uid, gid_t gid);
+
+int cgroup_bonding_set_task_access(CGroupBonding *b, mode_t mode, uid_t uid, gid_t gid, int sticky);
+int cgroup_bonding_set_task_access_list(CGroupBonding *b, mode_t mode, uid_t uid, gid_t gid, int sticky);
+
+int cgroup_bonding_kill(CGroupBonding *b, int sig, bool sigcont, bool rem, Set *s, const char *suffix);
+int cgroup_bonding_kill_list(CGroupBonding *first, int sig, bool sigcont, bool rem, Set *s, const char *suffix);
+
+void cgroup_bonding_trim(CGroupBonding *first, bool delete_root);
+void cgroup_bonding_trim_list(CGroupBonding *first, bool delete_root);
+
+int cgroup_bonding_is_empty(CGroupBonding *b);
+int cgroup_bonding_is_empty_list(CGroupBonding *first);
+
+CGroupBonding *cgroup_bonding_find_list(CGroupBonding *first, const char *controller) _pure_;
+
+char *cgroup_bonding_to_string(CGroupBonding *b);
+
+pid_t cgroup_bonding_search_main_pid(CGroupBonding *b);
+pid_t cgroup_bonding_search_main_pid_list(CGroupBonding *b);
+
+#include "manager.h"
+
+int manager_setup_cgroup(Manager *m);
+void manager_shutdown_cgroup(Manager *m, bool delete);
+
+int cgroup_bonding_get(Manager *m, const char *cgroup, CGroupBonding **bonding);
+int cgroup_notify_empty(Manager *m, const char *group);
+
+Unit* cgroup_unit_by_pid(Manager *m, pid_t pid);
diff --git a/src/core/condition.c b/src/core/condition.c
new file mode 100644
index 0000000000..16cae6d23b
--- /dev/null
+++ b/src/core/condition.c
@@ -0,0 +1,389 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdlib.h>
+#include <errno.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/capability.h>
+#include <sys/statvfs.h>
+#include <fnmatch.h>
+
+#ifdef HAVE_SELINUX
+#include <selinux/selinux.h>
+#endif
+
+#include <systemd/sd-id128.h>
+#include "util.h"
+#include "condition.h"
+#include "virt.h"
+#include "path-util.h"
+#include "fileio.h"
+
+Condition* condition_new(ConditionType type, const char *parameter, bool trigger, bool negate) {
+ Condition *c;
+
+ assert(type < _CONDITION_TYPE_MAX);
+
+ c = new0(Condition, 1);
+ if (!c)
+ return NULL;
+
+ c->type = type;
+ c->trigger = trigger;
+ c->negate = negate;
+
+ if (parameter) {
+ c->parameter = strdup(parameter);
+ if (!c->parameter) {
+ free(c);
+ return NULL;
+ }
+ }
+
+ return c;
+}
+
+void condition_free(Condition *c) {
+ assert(c);
+
+ free(c->parameter);
+ free(c);
+}
+
+void condition_free_list(Condition *first) {
+ Condition *c, *n;
+
+ LIST_FOREACH_SAFE(conditions, c, n, first)
+ condition_free(c);
+}
+
+static bool test_kernel_command_line(const char *parameter) {
+ char *line, *w, *state, *word = NULL;
+ bool equal;
+ int r;
+ size_t l, pl;
+ bool found = false;
+
+ assert(parameter);
+
+ if (detect_container(NULL) > 0)
+ return false;
+
+ r = read_one_line_file("/proc/cmdline", &line);
+ if (r < 0) {
+ log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
+ return false;
+ }
+
+ equal = !!strchr(parameter, '=');
+ pl = strlen(parameter);
+
+ FOREACH_WORD_QUOTED(w, l, line, state) {
+
+ free(word);
+ word = strndup(w, l);
+ if (!word)
+ break;
+
+ if (equal) {
+ if (streq(word, parameter)) {
+ found = true;
+ break;
+ }
+ } else {
+ if (startswith(word, parameter) && (word[pl] == '=' || word[pl] == 0)) {
+ found = true;
+ break;
+ }
+ }
+
+ }
+
+ free(word);
+ free(line);
+
+ return found;
+}
+
+static bool test_virtualization(const char *parameter) {
+ int b;
+ Virtualization v;
+ const char *id;
+
+ assert(parameter);
+
+ v = detect_virtualization(&id);
+ if (v < 0) {
+ log_warning("Failed to detect virtualization, ignoring: %s", strerror(-v));
+ return false;
+ }
+
+ /* First, compare with yes/no */
+ b = parse_boolean(parameter);
+
+ if (v > 0 && b > 0)
+ return true;
+
+ if (v == 0 && b == 0)
+ return true;
+
+ /* Then, compare categorization */
+ if (v == VIRTUALIZATION_VM && streq(parameter, "vm"))
+ return true;
+
+ if (v == VIRTUALIZATION_CONTAINER && streq(parameter, "container"))
+ return true;
+
+ /* Finally compare id */
+ return v > 0 && streq(parameter, id);
+}
+
+static bool test_security(const char *parameter) {
+#ifdef HAVE_SELINUX
+ if (streq(parameter, "selinux"))
+ return is_selinux_enabled() > 0;
+#endif
+ if (streq(parameter, "apparmor"))
+ return access("/sys/kernel/security/apparmor/", F_OK) == 0;
+ if (streq(parameter, "smack"))
+ return access("/sys/fs/smackfs", F_OK) == 0;
+ return false;
+}
+
+static bool test_capability(const char *parameter) {
+ cap_value_t value;
+ FILE *f;
+ char line[LINE_MAX];
+ unsigned long long capabilities = (unsigned long long) -1;
+
+ /* If it's an invalid capability, we don't have it */
+
+ if (cap_from_name(parameter, &value) < 0)
+ return false;
+
+ /* If it's a valid capability we default to assume
+ * that we have it */
+
+ f = fopen("/proc/self/status", "re");
+ if (!f)
+ return true;
+
+ while (fgets(line, sizeof(line), f)) {
+ truncate_nl(line);
+
+ if (startswith(line, "CapBnd:")) {
+ (void) sscanf(line+7, "%llx", &capabilities);
+ break;
+ }
+ }
+
+ fclose(f);
+
+ return !!(capabilities & (1ULL << value));
+}
+
+static bool test_host(const char *parameter) {
+ sd_id128_t x, y;
+ char *h;
+ int r;
+ bool b;
+
+ if (sd_id128_from_string(parameter, &x) >= 0) {
+
+ r = sd_id128_get_machine(&y);
+ if (r < 0)
+ return false;
+
+ return sd_id128_equal(x, y);
+ }
+
+ h = gethostname_malloc();
+ if (!h)
+ return false;
+
+ b = fnmatch(parameter, h, FNM_CASEFOLD) == 0;
+ free(h);
+
+ return b;
+}
+
+static bool test_ac_power(const char *parameter) {
+ int r;
+
+ r = parse_boolean(parameter);
+ if (r < 0)
+ return true;
+
+ return (on_ac_power() != 0) == !!r;
+}
+
+bool condition_test(Condition *c) {
+ assert(c);
+
+ switch(c->type) {
+
+ case CONDITION_PATH_EXISTS:
+ return (access(c->parameter, F_OK) >= 0) == !c->negate;
+
+ case CONDITION_PATH_EXISTS_GLOB:
+ return (glob_exists(c->parameter) > 0) == !c->negate;
+
+ case CONDITION_PATH_IS_DIRECTORY: {
+ struct stat st;
+
+ if (stat(c->parameter, &st) < 0)
+ return c->negate;
+ return S_ISDIR(st.st_mode) == !c->negate;
+ }
+
+ case CONDITION_PATH_IS_SYMBOLIC_LINK: {
+ struct stat st;
+
+ if (lstat(c->parameter, &st) < 0)
+ return c->negate;
+ return S_ISLNK(st.st_mode) == !c->negate;
+ }
+
+ case CONDITION_PATH_IS_MOUNT_POINT:
+ return (path_is_mount_point(c->parameter, true) > 0) == !c->negate;
+
+ case CONDITION_PATH_IS_READ_WRITE:
+ return (path_is_read_only_fs(c->parameter) > 0) == c->negate;
+
+ case CONDITION_DIRECTORY_NOT_EMPTY: {
+ int k;
+
+ k = dir_is_empty(c->parameter);
+ return !(k == -ENOENT || k > 0) == !c->negate;
+ }
+
+ case CONDITION_FILE_NOT_EMPTY: {
+ struct stat st;
+
+ if (stat(c->parameter, &st) < 0)
+ return c->negate;
+
+ return (S_ISREG(st.st_mode) && st.st_size > 0) == !c->negate;
+ }
+
+ case CONDITION_FILE_IS_EXECUTABLE: {
+ struct stat st;
+
+ if (stat(c->parameter, &st) < 0)
+ return c->negate;
+
+ return (S_ISREG(st.st_mode) && (st.st_mode & 0111)) == !c->negate;
+ }
+
+ case CONDITION_KERNEL_COMMAND_LINE:
+ return test_kernel_command_line(c->parameter) == !c->negate;
+
+ case CONDITION_VIRTUALIZATION:
+ return test_virtualization(c->parameter) == !c->negate;
+
+ case CONDITION_SECURITY:
+ return test_security(c->parameter) == !c->negate;
+
+ case CONDITION_CAPABILITY:
+ return test_capability(c->parameter) == !c->negate;
+
+ case CONDITION_HOST:
+ return test_host(c->parameter) == !c->negate;
+
+ case CONDITION_AC_POWER:
+ return test_ac_power(c->parameter) == !c->negate;
+
+ case CONDITION_NULL:
+ return !c->negate;
+
+ default:
+ assert_not_reached("Invalid condition type.");
+ }
+}
+
+bool condition_test_list(Condition *first) {
+ Condition *c;
+ int triggered = -1;
+
+ /* If the condition list is empty, then it is true */
+ if (!first)
+ return true;
+
+ /* Otherwise, if all of the non-trigger conditions apply and
+ * if any of the trigger conditions apply (unless there are
+ * none) we return true */
+ LIST_FOREACH(conditions, c, first) {
+ bool b;
+
+ b = condition_test(c);
+
+ if (!c->trigger && !b)
+ return false;
+
+ if (c->trigger && triggered <= 0)
+ triggered = b;
+ }
+
+ return triggered != 0;
+}
+
+void condition_dump(Condition *c, FILE *f, const char *prefix) {
+ assert(c);
+ assert(f);
+
+ if (!prefix)
+ prefix = "";
+
+ fprintf(f,
+ "%s\t%s: %s%s%s\n",
+ prefix,
+ condition_type_to_string(c->type),
+ c->trigger ? "|" : "",
+ c->negate ? "!" : "",
+ c->parameter);
+}
+
+void condition_dump_list(Condition *first, FILE *f, const char *prefix) {
+ Condition *c;
+
+ LIST_FOREACH(conditions, c, first)
+ condition_dump(c, f, prefix);
+}
+
+static const char* const condition_type_table[_CONDITION_TYPE_MAX] = {
+ [CONDITION_PATH_EXISTS] = "ConditionPathExists",
+ [CONDITION_PATH_EXISTS_GLOB] = "ConditionPathExistsGlob",
+ [CONDITION_PATH_IS_DIRECTORY] = "ConditionPathIsDirectory",
+ [CONDITION_PATH_IS_SYMBOLIC_LINK] = "ConditionPathIsSymbolicLink",
+ [CONDITION_PATH_IS_MOUNT_POINT] = "ConditionPathIsMountPoint",
+ [CONDITION_PATH_IS_READ_WRITE] = "ConditionPathIsReadWrite",
+ [CONDITION_DIRECTORY_NOT_EMPTY] = "ConditionDirectoryNotEmpty",
+ [CONDITION_FILE_NOT_EMPTY] = "ConditionFileNotEmpty",
+ [CONDITION_KERNEL_COMMAND_LINE] = "ConditionKernelCommandLine",
+ [CONDITION_VIRTUALIZATION] = "ConditionVirtualization",
+ [CONDITION_SECURITY] = "ConditionSecurity",
+ [CONDITION_HOST] = "ConditionHost",
+ [CONDITION_AC_POWER] = "ConditionACPower",
+ [CONDITION_NULL] = "ConditionNull"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(condition_type, ConditionType);
diff --git a/src/core/condition.h b/src/core/condition.h
new file mode 100644
index 0000000000..50ed955af9
--- /dev/null
+++ b/src/core/condition.h
@@ -0,0 +1,70 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdbool.h>
+
+#include "list.h"
+
+typedef enum ConditionType {
+ CONDITION_PATH_EXISTS,
+ CONDITION_PATH_EXISTS_GLOB,
+ CONDITION_PATH_IS_DIRECTORY,
+ CONDITION_PATH_IS_SYMBOLIC_LINK,
+ CONDITION_PATH_IS_MOUNT_POINT,
+ CONDITION_PATH_IS_READ_WRITE,
+ CONDITION_DIRECTORY_NOT_EMPTY,
+ CONDITION_FILE_NOT_EMPTY,
+ CONDITION_FILE_IS_EXECUTABLE,
+ CONDITION_KERNEL_COMMAND_LINE,
+ CONDITION_VIRTUALIZATION,
+ CONDITION_SECURITY,
+ CONDITION_CAPABILITY,
+ CONDITION_HOST,
+ CONDITION_AC_POWER,
+ CONDITION_NULL,
+ _CONDITION_TYPE_MAX,
+ _CONDITION_TYPE_INVALID = -1
+} ConditionType;
+
+typedef struct Condition {
+ ConditionType type;
+ char *parameter;
+
+ bool trigger:1;
+ bool negate:1;
+
+ LIST_FIELDS(struct Condition, conditions);
+} Condition;
+
+Condition* condition_new(ConditionType type, const char *parameter, bool trigger, bool negate);
+void condition_free(Condition *c);
+void condition_free_list(Condition *c);
+
+bool condition_test(Condition *c);
+bool condition_test_list(Condition *c);
+
+void condition_dump(Condition *c, FILE *f, const char *prefix);
+void condition_dump_list(Condition *c, FILE *f, const char *prefix);
+
+const char* condition_type_to_string(ConditionType t) _const_;
+int condition_type_from_string(const char *s) _pure_;
diff --git a/src/core/dbus-automount.c b/src/core/dbus-automount.c
new file mode 100644
index 0000000000..060cbf7707
--- /dev/null
+++ b/src/core/dbus-automount.c
@@ -0,0 +1,75 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+
+#include "dbus-unit.h"
+#include "dbus-automount.h"
+#include "dbus-common.h"
+#include "selinux-access.h"
+
+#define BUS_AUTOMOUNT_INTERFACE \
+ " <interface name=\"org.freedesktop.systemd1.Automount\">\n" \
+ " <property name=\"Where\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"DirectoryMode\" type=\"u\" access=\"read\"/>\n" \
+ " <property name=\"Result\" type=\"s\" access=\"read\"/>\n" \
+ " </interface>\n"
+
+#define INTROSPECTION \
+ DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE \
+ "<node>\n" \
+ BUS_UNIT_INTERFACE \
+ BUS_AUTOMOUNT_INTERFACE \
+ BUS_PROPERTIES_INTERFACE \
+ BUS_PEER_INTERFACE \
+ BUS_INTROSPECTABLE_INTERFACE \
+ "</node>\n"
+
+#define INTERFACES_LIST \
+ BUS_UNIT_INTERFACES_LIST \
+ "org.freedesktop.systemd1.Automount\0"
+
+const char bus_automount_interface[] _introspect_("Automount") = BUS_AUTOMOUNT_INTERFACE;
+
+const char bus_automount_invalidating_properties[] =
+ "Result\0";
+
+static DEFINE_BUS_PROPERTY_APPEND_ENUM(bus_automount_append_automount_result, automount_result, AutomountResult);
+
+static const BusProperty bus_automount_properties[] = {
+ { "Where", bus_property_append_string, "s", offsetof(Automount, where), true },
+ { "DirectoryMode", bus_property_append_mode, "u", offsetof(Automount, directory_mode) },
+ { "Result", bus_automount_append_automount_result, "s", offsetof(Automount, result) },
+ { NULL, }
+};
+
+DBusHandlerResult bus_automount_message_handler(Unit *u, DBusConnection *c, DBusMessage *message) {
+ Automount *am = AUTOMOUNT(u);
+ const BusBoundProperties bps[] = {
+ { "org.freedesktop.systemd1.Unit", bus_unit_properties, u },
+ { "org.freedesktop.systemd1.Automount", bus_automount_properties, am },
+ { NULL, }
+ };
+
+ SELINUX_UNIT_ACCESS_CHECK(u, c, message, "status");
+
+ return bus_default_message_handler(c, message, INTROSPECTION, INTERFACES_LIST, bps);
+}
diff --git a/src/core/dbus-automount.h b/src/core/dbus-automount.h
new file mode 100644
index 0000000000..b338e25fc1
--- /dev/null
+++ b/src/core/dbus-automount.h
@@ -0,0 +1,31 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <dbus/dbus.h>
+
+#include "unit.h"
+
+DBusHandlerResult bus_automount_message_handler(Unit *u, DBusConnection *c, DBusMessage *message);
+
+extern const char bus_automount_interface[];
+extern const char bus_automount_invalidating_properties[];
diff --git a/src/core/dbus-device.c b/src/core/dbus-device.c
new file mode 100644
index 0000000000..dbd91fe3db
--- /dev/null
+++ b/src/core/dbus-device.c
@@ -0,0 +1,68 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "dbus-unit.h"
+#include "dbus-device.h"
+#include "dbus-common.h"
+#include "selinux-access.h"
+
+#define BUS_DEVICE_INTERFACE \
+ " <interface name=\"org.freedesktop.systemd1.Device\">\n" \
+ " <property name=\"SysFSPath\" type=\"s\" access=\"read\"/>\n" \
+ " </interface>\n"
+
+#define INTROSPECTION \
+ DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE \
+ "<node>\n" \
+ BUS_UNIT_INTERFACE \
+ BUS_DEVICE_INTERFACE \
+ BUS_PROPERTIES_INTERFACE \
+ BUS_PEER_INTERFACE \
+ BUS_INTROSPECTABLE_INTERFACE \
+ "</node>\n"
+
+#define INTERFACES_LIST \
+ BUS_UNIT_INTERFACES_LIST \
+ "org.freedesktop.systemd1.Device\0"
+
+const char bus_device_interface[] _introspect_("Device") = BUS_DEVICE_INTERFACE;
+
+const char bus_device_invalidating_properties[] =
+ "SysFSPath\0";
+
+static const BusProperty bus_device_properties[] = {
+ { "SysFSPath", bus_property_append_string, "s", offsetof(Device, sysfs), true },
+ { NULL, }
+};
+
+
+DBusHandlerResult bus_device_message_handler(Unit *u, DBusConnection *c, DBusMessage *message) {
+ Device *d = DEVICE(u);
+ const BusBoundProperties bps[] = {
+ { "org.freedesktop.systemd1.Unit", bus_unit_properties, u },
+ { "org.freedesktop.systemd1.Device", bus_device_properties, d },
+ { NULL, }
+ };
+
+ SELINUX_UNIT_ACCESS_CHECK(u, c, message, "status");
+
+ return bus_default_message_handler(c, message, INTROSPECTION, INTERFACES_LIST, bps);
+}
diff --git a/src/core/dbus-device.h b/src/core/dbus-device.h
new file mode 100644
index 0000000000..311e0685d1
--- /dev/null
+++ b/src/core/dbus-device.h
@@ -0,0 +1,31 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <dbus/dbus.h>
+
+#include "unit.h"
+
+DBusHandlerResult bus_device_message_handler(Unit *u, DBusConnection *c, DBusMessage *message);
+
+extern const char bus_device_interface[];
+extern const char bus_device_invalidating_properties[];
diff --git a/src/core/dbus-execute.c b/src/core/dbus-execute.c
new file mode 100644
index 0000000000..2a8a0e1ac5
--- /dev/null
+++ b/src/core/dbus-execute.c
@@ -0,0 +1,439 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <dbus/dbus.h>
+#include <sys/prctl.h>
+
+#include "dbus-execute.h"
+#include "missing.h"
+#include "ioprio.h"
+#include "strv.h"
+#include "dbus-common.h"
+#include "syscall-list.h"
+#include "fileio.h"
+
+DEFINE_BUS_PROPERTY_APPEND_ENUM(bus_execute_append_input, exec_input, ExecInput);
+DEFINE_BUS_PROPERTY_APPEND_ENUM(bus_execute_append_output, exec_output, ExecOutput);
+
+int bus_execute_append_env_files(DBusMessageIter *i, const char *property, void *data) {
+ char **env_files = data, **j;
+ DBusMessageIter sub, sub2;
+
+ assert(i);
+ assert(property);
+
+ if (!dbus_message_iter_open_container(i, DBUS_TYPE_ARRAY, "(sb)", &sub))
+ return -ENOMEM;
+
+ STRV_FOREACH(j, env_files) {
+ dbus_bool_t b = false;
+ char *fn = *j;
+
+ if (fn[0] == '-') {
+ b = true;
+ fn++;
+ }
+
+ if (!dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, NULL, &sub2) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &fn) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_BOOLEAN, &b) ||
+ !dbus_message_iter_close_container(&sub, &sub2))
+ return -ENOMEM;
+ }
+
+ if (!dbus_message_iter_close_container(i, &sub))
+ return -ENOMEM;
+
+ return 0;
+}
+
+int bus_execute_append_oom_score_adjust(DBusMessageIter *i, const char *property, void *data) {
+ ExecContext *c = data;
+ int32_t n;
+
+ assert(i);
+ assert(property);
+ assert(c);
+
+ if (c->oom_score_adjust_set)
+ n = c->oom_score_adjust;
+ else {
+ char *t;
+
+ n = 0;
+ if (read_one_line_file("/proc/self/oom_score_adj", &t) >= 0) {
+ safe_atoi(t, &n);
+ free(t);
+ }
+ }
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_INT32, &n))
+ return -ENOMEM;
+
+ return 0;
+}
+
+int bus_execute_append_nice(DBusMessageIter *i, const char *property, void *data) {
+ ExecContext *c = data;
+ int32_t n;
+
+ assert(i);
+ assert(property);
+ assert(c);
+
+ if (c->nice_set)
+ n = c->nice;
+ else
+ n = getpriority(PRIO_PROCESS, 0);
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_INT32, &n))
+ return -ENOMEM;
+
+ return 0;
+}
+
+int bus_execute_append_ioprio(DBusMessageIter *i, const char *property, void *data) {
+ ExecContext *c = data;
+ int32_t n;
+
+ assert(i);
+ assert(property);
+ assert(c);
+
+ if (c->ioprio_set)
+ n = c->ioprio;
+ else
+ n = ioprio_get(IOPRIO_WHO_PROCESS, 0);
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_INT32, &n))
+ return -ENOMEM;
+
+ return 0;
+}
+
+int bus_execute_append_cpu_sched_policy(DBusMessageIter *i, const char *property, void *data) {
+ ExecContext *c = data;
+ int32_t n;
+
+ assert(i);
+ assert(property);
+ assert(c);
+
+ if (c->cpu_sched_set)
+ n = c->cpu_sched_policy;
+ else
+ n = sched_getscheduler(0);
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_INT32, &n))
+ return -ENOMEM;
+
+ return 0;
+}
+
+int bus_execute_append_cpu_sched_priority(DBusMessageIter *i, const char *property, void *data) {
+ ExecContext *c = data;
+ int32_t n;
+
+ assert(i);
+ assert(property);
+ assert(c);
+
+ if (c->cpu_sched_set)
+ n = c->cpu_sched_priority;
+ else {
+ struct sched_param p = {};
+
+ if (sched_getparam(0, &p) >= 0)
+ n = p.sched_priority;
+ else
+ n = 0;
+ }
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_INT32, &n))
+ return -ENOMEM;
+
+ return 0;
+}
+
+int bus_execute_append_affinity(DBusMessageIter *i, const char *property, void *data) {
+ ExecContext *c = data;
+ dbus_bool_t b;
+ DBusMessageIter sub;
+
+ assert(i);
+ assert(property);
+ assert(c);
+
+ if (!dbus_message_iter_open_container(i, DBUS_TYPE_ARRAY, "y", &sub))
+ return -ENOMEM;
+
+ if (c->cpuset)
+ b = dbus_message_iter_append_fixed_array(&sub, DBUS_TYPE_BYTE, &c->cpuset, CPU_ALLOC_SIZE(c->cpuset_ncpus));
+ else
+ b = dbus_message_iter_append_fixed_array(&sub, DBUS_TYPE_BYTE, &c->cpuset, 0);
+
+ if (!b)
+ return -ENOMEM;
+
+ if (!dbus_message_iter_close_container(i, &sub))
+ return -ENOMEM;
+
+ return 0;
+}
+
+int bus_execute_append_timer_slack_nsec(DBusMessageIter *i, const char *property, void *data) {
+ ExecContext *c = data;
+ uint64_t u;
+
+ assert(i);
+ assert(property);
+ assert(c);
+
+ if (c->timer_slack_nsec != (nsec_t) -1)
+ u = (uint64_t) c->timer_slack_nsec;
+ else
+ u = (uint64_t) prctl(PR_GET_TIMERSLACK);
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT64, &u))
+ return -ENOMEM;
+
+ return 0;
+}
+
+int bus_execute_append_capability_bs(DBusMessageIter *i, const char *property, void *data) {
+ ExecContext *c = data;
+ uint64_t normal, inverted;
+
+ assert(i);
+ assert(property);
+ assert(c);
+
+ /* We store this negated internally, to match the kernel, but
+ * we expose it normalized. */
+
+ normal = *(uint64_t*) data;
+ inverted = ~normal;
+
+ return bus_property_append_uint64(i, property, &inverted);
+}
+
+int bus_execute_append_capabilities(DBusMessageIter *i, const char *property, void *data) {
+ ExecContext *c = data;
+ char *t = NULL;
+ const char *s;
+ dbus_bool_t b;
+
+ assert(i);
+ assert(property);
+ assert(c);
+
+ if (c->capabilities)
+ s = t = cap_to_text(c->capabilities, NULL);
+ else
+ s = "";
+
+ if (!s)
+ return -ENOMEM;
+
+ b = dbus_message_iter_append_basic(i, DBUS_TYPE_STRING, &s);
+
+ if (t)
+ cap_free(t);
+
+ if (!b)
+ return -ENOMEM;
+
+ return 0;
+}
+
+int bus_execute_append_rlimits(DBusMessageIter *i, const char *property, void *data) {
+ ExecContext *c = data;
+ int r;
+ uint64_t u;
+
+ assert(i);
+ assert(property);
+ assert(c);
+
+ assert_se((r = rlimit_from_string(property)) >= 0);
+
+ if (c->rlimit[r])
+ u = (uint64_t) c->rlimit[r]->rlim_max;
+ else {
+ struct rlimit rl = {};
+
+ getrlimit(r, &rl);
+
+ u = (uint64_t) rl.rlim_max;
+ }
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT64, &u))
+ return -ENOMEM;
+
+ return 0;
+}
+
+int bus_execute_append_command(DBusMessageIter *i, const char *property, void *data) {
+ ExecCommand *c = data;
+ DBusMessageIter sub, sub2, sub3;
+
+ assert(i);
+ assert(property);
+
+ if (!dbus_message_iter_open_container(i, DBUS_TYPE_ARRAY, "(sasbttttuii)", &sub))
+ return -ENOMEM;
+
+ LIST_FOREACH(command, c, c) {
+ char **l;
+ uint32_t pid;
+ int32_t code, status;
+ dbus_bool_t b;
+
+ if (!c->path)
+ continue;
+
+ if (!dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, NULL, &sub2) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &c->path) ||
+ !dbus_message_iter_open_container(&sub2, DBUS_TYPE_ARRAY, "s", &sub3))
+ return -ENOMEM;
+
+ STRV_FOREACH(l, c->argv)
+ if (!dbus_message_iter_append_basic(&sub3, DBUS_TYPE_STRING, l))
+ return -ENOMEM;
+
+ pid = (uint32_t) c->exec_status.pid;
+ code = (int32_t) c->exec_status.code;
+ status = (int32_t) c->exec_status.status;
+
+ b = !!c->ignore;
+
+ if (!dbus_message_iter_close_container(&sub2, &sub3) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_BOOLEAN, &b) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_UINT64, &c->exec_status.start_timestamp.realtime) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_UINT64, &c->exec_status.start_timestamp.monotonic) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_UINT64, &c->exec_status.exit_timestamp.realtime) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_UINT64, &c->exec_status.exit_timestamp.monotonic) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_UINT32, &pid) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_INT32, &code) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_INT32, &status))
+ return -ENOMEM;
+
+ if (!dbus_message_iter_close_container(&sub, &sub2))
+ return -ENOMEM;
+ }
+
+ if (!dbus_message_iter_close_container(i, &sub))
+ return -ENOMEM;
+
+ return 0;
+}
+
+int bus_execute_append_syscall_filter(DBusMessageIter *i, const char *property, void *data) {
+ ExecContext *c = data;
+ dbus_bool_t b;
+ DBusMessageIter sub;
+
+ assert(i);
+ assert(property);
+ assert(c);
+
+ if (!dbus_message_iter_open_container(i, DBUS_TYPE_ARRAY, "u", &sub))
+ return -ENOMEM;
+
+ if (c->syscall_filter)
+ b = dbus_message_iter_append_fixed_array(&sub, DBUS_TYPE_UINT32, &c->syscall_filter, (syscall_max() + 31) >> 4);
+ else
+ b = dbus_message_iter_append_fixed_array(&sub, DBUS_TYPE_UINT32, &c->syscall_filter, 0);
+
+ if (!b)
+ return -ENOMEM;
+
+ if (!dbus_message_iter_close_container(i, &sub))
+ return -ENOMEM;
+
+ return 0;
+}
+
+const BusProperty bus_exec_context_properties[] = {
+ { "Environment", bus_property_append_strv, "as", offsetof(ExecContext, environment), true },
+ { "EnvironmentFiles", bus_execute_append_env_files, "a(sb)", offsetof(ExecContext, environment_files), true },
+ { "UMask", bus_property_append_mode, "u", offsetof(ExecContext, umask) },
+ { "LimitCPU", bus_execute_append_rlimits, "t", 0 },
+ { "LimitFSIZE", bus_execute_append_rlimits, "t", 0 },
+ { "LimitDATA", bus_execute_append_rlimits, "t", 0 },
+ { "LimitSTACK", bus_execute_append_rlimits, "t", 0 },
+ { "LimitCORE", bus_execute_append_rlimits, "t", 0 },
+ { "LimitRSS", bus_execute_append_rlimits, "t", 0 },
+ { "LimitNOFILE", bus_execute_append_rlimits, "t", 0 },
+ { "LimitAS", bus_execute_append_rlimits, "t", 0 },
+ { "LimitNPROC", bus_execute_append_rlimits, "t", 0 },
+ { "LimitMEMLOCK", bus_execute_append_rlimits, "t", 0 },
+ { "LimitLOCKS", bus_execute_append_rlimits, "t", 0 },
+ { "LimitSIGPENDING", bus_execute_append_rlimits, "t", 0 },
+ { "LimitMSGQUEUE", bus_execute_append_rlimits, "t", 0 },
+ { "LimitNICE", bus_execute_append_rlimits, "t", 0 },
+ { "LimitRTPRIO", bus_execute_append_rlimits, "t", 0 },
+ { "LimitRTTIME", bus_execute_append_rlimits, "t", 0 },
+ { "WorkingDirectory", bus_property_append_string, "s", offsetof(ExecContext, working_directory), true },
+ { "RootDirectory", bus_property_append_string, "s", offsetof(ExecContext, root_directory), true },
+ { "OOMScoreAdjust", bus_execute_append_oom_score_adjust, "i", 0 },
+ { "Nice", bus_execute_append_nice, "i", 0 },
+ { "IOScheduling", bus_execute_append_ioprio, "i", 0 },
+ { "CPUSchedulingPolicy", bus_execute_append_cpu_sched_policy, "i", 0 },
+ { "CPUSchedulingPriority", bus_execute_append_cpu_sched_priority, "i", 0 },
+ { "CPUAffinity", bus_execute_append_affinity, "ay", 0 },
+ { "TimerSlackNSec", bus_execute_append_timer_slack_nsec, "t", 0 },
+ { "CPUSchedulingResetOnFork", bus_property_append_bool, "b", offsetof(ExecContext, cpu_sched_reset_on_fork) },
+ { "NonBlocking", bus_property_append_bool, "b", offsetof(ExecContext, non_blocking) },
+ { "StandardInput", bus_execute_append_input, "s", offsetof(ExecContext, std_input) },
+ { "StandardOutput", bus_execute_append_output, "s", offsetof(ExecContext, std_output) },
+ { "StandardError", bus_execute_append_output, "s", offsetof(ExecContext, std_error) },
+ { "TTYPath", bus_property_append_string, "s", offsetof(ExecContext, tty_path), true },
+ { "TTYReset", bus_property_append_bool, "b", offsetof(ExecContext, tty_reset) },
+ { "TTYVHangup", bus_property_append_bool, "b", offsetof(ExecContext, tty_vhangup) },
+ { "TTYVTDisallocate", bus_property_append_bool, "b", offsetof(ExecContext, tty_vt_disallocate) },
+ { "SyslogPriority", bus_property_append_int, "i", offsetof(ExecContext, syslog_priority) },
+ { "SyslogIdentifier", bus_property_append_string, "s", offsetof(ExecContext, syslog_identifier), true },
+ { "SyslogLevelPrefix", bus_property_append_bool, "b", offsetof(ExecContext, syslog_level_prefix) },
+ { "Capabilities", bus_execute_append_capabilities, "s", 0 },
+ { "SecureBits", bus_property_append_int, "i", offsetof(ExecContext, secure_bits) },
+ { "CapabilityBoundingSet", bus_execute_append_capability_bs, "t", offsetof(ExecContext, capability_bounding_set_drop) },
+ { "User", bus_property_append_string, "s", offsetof(ExecContext, user), true },
+ { "Group", bus_property_append_string, "s", offsetof(ExecContext, group), true },
+ { "SupplementaryGroups", bus_property_append_strv, "as", offsetof(ExecContext, supplementary_groups), true },
+ { "TCPWrapName", bus_property_append_string, "s", offsetof(ExecContext, tcpwrap_name), true },
+ { "PAMName", bus_property_append_string, "s", offsetof(ExecContext, pam_name), true },
+ { "ReadWriteDirectories", bus_property_append_strv, "as", offsetof(ExecContext, read_write_dirs), true },
+ { "ReadOnlyDirectories", bus_property_append_strv, "as", offsetof(ExecContext, read_only_dirs), true },
+ { "InaccessibleDirectories", bus_property_append_strv, "as", offsetof(ExecContext, inaccessible_dirs), true },
+ { "MountFlags", bus_property_append_ul, "t", offsetof(ExecContext, mount_flags) },
+ { "PrivateTmp", bus_property_append_bool, "b", offsetof(ExecContext, private_tmp) },
+ { "PrivateNetwork", bus_property_append_bool, "b", offsetof(ExecContext, private_network) },
+ { "SameProcessGroup", bus_property_append_bool, "b", offsetof(ExecContext, same_pgrp) },
+ { "UtmpIdentifier", bus_property_append_string, "s", offsetof(ExecContext, utmp_id), true },
+ { "ControlGroupModify", bus_property_append_bool, "b", offsetof(ExecContext, control_group_modify) },
+ { "ControlGroupPersistent", bus_property_append_tristate_false, "b", offsetof(ExecContext, control_group_persistent) },
+ { "IgnoreSIGPIPE", bus_property_append_bool, "b", offsetof(ExecContext, ignore_sigpipe) },
+ { "NoNewPrivileges", bus_property_append_bool, "b", offsetof(ExecContext, no_new_privileges) },
+ { "SystemCallFilter", bus_execute_append_syscall_filter, "au", 0 },
+ { NULL, }
+};
diff --git a/src/core/dbus-execute.h b/src/core/dbus-execute.h
new file mode 100644
index 0000000000..91d70e535f
--- /dev/null
+++ b/src/core/dbus-execute.h
@@ -0,0 +1,123 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <dbus/dbus.h>
+
+#include "manager.h"
+#include "dbus-common.h"
+
+#define BUS_EXEC_STATUS_INTERFACE(prefix) \
+ " <property name=\"" prefix "StartTimestamp\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"" prefix "StartTimestampMonotonic\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"" prefix "ExitTimestamp\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"" prefix "ExitTimestampMonotonic\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"" prefix "PID\" type=\"u\" access=\"read\"/>\n" \
+ " <property name=\"" prefix "Code\" type=\"i\" access=\"read\"/>\n" \
+ " <property name=\"" prefix "Status\" type=\"i\" access=\"read\"/>\n"
+
+#define BUS_EXEC_CONTEXT_INTERFACE \
+ " <property name=\"Environment\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"EnvironmentFiles\" type=\"a(sb)\" access=\"read\"/>\n" \
+ " <property name=\"UMask\" type=\"u\" access=\"read\"/>\n" \
+ " <property name=\"LimitCPU\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"LimitFSIZE\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"LimitDATA\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"LimitSTACK\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"LimitCORE\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"LimitRSS\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"LimitNOFILE\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"LimitAS\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"LimitNPROC\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"LimitMEMLOCK\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"LimitLOCKS\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"LimitSIGPENDING\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"LimitMSGQUEUE\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"LimitNICE\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"LimitRTPRIO\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"LimitRTTIME\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"WorkingDirectory\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"RootDirectory\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"OOMScoreAdjust\" type=\"i\" access=\"read\"/>\n" \
+ " <property name=\"Nice\" type=\"i\" access=\"read\"/>\n" \
+ " <property name=\"IOScheduling\" type=\"i\" access=\"read\"/>\n" \
+ " <property name=\"CPUSchedulingPolicy\" type=\"i\" access=\"read\"/>\n" \
+ " <property name=\"CPUSchedulingPriority\" type=\"i\" access=\"read\"/>\n" \
+ " <property name=\"CPUAffinity\" type=\"ay\" access=\"read\"/>\n" \
+ " <property name=\"TimerSlackNS\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"CPUSchedulingResetOnFork\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"NonBlocking\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"StandardInput\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"StandardOutput\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"StandardError\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"TTYPath\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"TTYReset\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"TTYVHangup\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"TTYVTDisallocate\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"SyslogPriority\" type=\"i\" access=\"read\"/>\n" \
+ " <property name=\"SyslogIdentifier\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"SyslogLevelPrefix\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"Capabilities\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"SecureBits\" type=\"i\" access=\"read\"/>\n" \
+ " <property name=\"CapabilityBoundingSet\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"User\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"Group\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"SupplementaryGroups\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"TCPWrapName\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"PAMName\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"ReadWriteDirectories\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"ReadOnlyDirectories\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"InaccessibleDirectories\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"MountFlags\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"PrivateTmp\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"PrivateNetwork\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"SameProcessGroup\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"UtmpIdentifier\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"ControlGroupModify\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"ControlGroupPersistent\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"IgnoreSIGPIPE\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"NoNewPrivileges\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"SystemCallFilter\" type=\"au\" access=\"read\"/>\n"
+
+#define BUS_EXEC_COMMAND_INTERFACE(name) \
+ " <property name=\"" name "\" type=\"a(sasbttuii)\" access=\"read\"/>\n"
+
+extern const BusProperty bus_exec_context_properties[];
+
+#define BUS_EXEC_COMMAND_PROPERTY(name, command, indirect) \
+ { name, bus_execute_append_command, "a(sasbttttuii)", (command), (indirect), NULL }
+
+int bus_execute_append_output(DBusMessageIter *i, const char *property, void *data);
+int bus_execute_append_input(DBusMessageIter *i, const char *property, void *data);
+int bus_execute_append_oom_score_adjust(DBusMessageIter *i, const char *property, void *data);
+int bus_execute_append_nice(DBusMessageIter *i, const char *property, void *data);
+int bus_execute_append_ioprio(DBusMessageIter *i, const char *property, void *data);
+int bus_execute_append_cpu_sched_policy(DBusMessageIter *i, const char *property, void *data);
+int bus_execute_append_cpu_sched_priority(DBusMessageIter *i, const char *property, void *data);
+int bus_execute_append_affinity(DBusMessageIter *i, const char *property, void *data);
+int bus_execute_append_timer_slack_nsec(DBusMessageIter *i, const char *property, void *data);
+int bus_execute_append_capabilities(DBusMessageIter *i, const char *property, void *data);
+int bus_execute_append_capability_bs(DBusMessageIter *i, const char *property, void *data);
+int bus_execute_append_rlimits(DBusMessageIter *i, const char *property, void *data);
+int bus_execute_append_command(DBusMessageIter *u, const char *property, void *data);
+int bus_execute_append_env_files(DBusMessageIter *i, const char *property, void *data);
+int bus_execute_append_syscall_filter(DBusMessageIter *i, const char *property, void *data);
diff --git a/src/core/dbus-job.c b/src/core/dbus-job.c
new file mode 100644
index 0000000000..98ccfa62ec
--- /dev/null
+++ b/src/core/dbus-job.c
@@ -0,0 +1,373 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+
+#include "dbus.h"
+#include "log.h"
+#include "dbus-job.h"
+#include "dbus-common.h"
+#include "selinux-access.h"
+
+#define BUS_JOB_INTERFACE \
+ " <interface name=\"org.freedesktop.systemd1.Job\">\n" \
+ " <method name=\"Cancel\"/>\n" \
+ " <property name=\"Id\" type=\"u\" access=\"read\"/>\n" \
+ " <property name=\"Unit\" type=\"(so)\" access=\"read\"/>\n" \
+ " <property name=\"JobType\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"State\" type=\"s\" access=\"read\"/>\n" \
+ " </interface>\n"
+
+#define INTROSPECTION \
+ DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE \
+ "<node>\n" \
+ BUS_JOB_INTERFACE \
+ BUS_PROPERTIES_INTERFACE \
+ BUS_PEER_INTERFACE \
+ BUS_INTROSPECTABLE_INTERFACE \
+ "</node>\n"
+
+const char bus_job_interface[] _introspect_("Job") = BUS_JOB_INTERFACE;
+
+#define INTERFACES_LIST \
+ BUS_GENERIC_INTERFACES_LIST \
+ "org.freedesktop.systemd1.Job\0"
+
+#define INVALIDATING_PROPERTIES \
+ "State\0"
+
+static DEFINE_BUS_PROPERTY_APPEND_ENUM(bus_job_append_state, job_state, JobState);
+static DEFINE_BUS_PROPERTY_APPEND_ENUM(bus_job_append_type, job_type, JobType);
+
+static int bus_job_append_unit(DBusMessageIter *i, const char *property, void *data) {
+ Job *j = data;
+ DBusMessageIter sub;
+ char *p;
+
+ assert(i);
+ assert(property);
+ assert(j);
+
+ if (!dbus_message_iter_open_container(i, DBUS_TYPE_STRUCT, NULL, &sub))
+ return -ENOMEM;
+
+ p = unit_dbus_path(j->unit);
+ if (!p)
+ return -ENOMEM;
+
+ if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &j->unit->id) ||
+ !dbus_message_iter_append_basic(&sub, DBUS_TYPE_OBJECT_PATH, &p)) {
+ free(p);
+ return -ENOMEM;
+ }
+
+ free(p);
+
+ if (!dbus_message_iter_close_container(i, &sub))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static const BusProperty bus_job_properties[] = {
+ { "Id", bus_property_append_uint32, "u", offsetof(Job, id) },
+ { "State", bus_job_append_state, "s", offsetof(Job, state) },
+ { "JobType", bus_job_append_type, "s", offsetof(Job, type) },
+ { "Unit", bus_job_append_unit, "(so)", 0 },
+ { NULL, }
+};
+
+static DBusHandlerResult bus_job_message_dispatch(Job *j, DBusConnection *connection, DBusMessage *message) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+
+ if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Job", "Cancel")) {
+
+ SELINUX_UNIT_ACCESS_CHECK(j->unit, connection, message, "stop");
+ job_finish_and_invalidate(j, JOB_CANCELED, true);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ return DBUS_HANDLER_RESULT_NEED_MEMORY;
+ } else {
+ const BusBoundProperties bps[] = {
+ { "org.freedesktop.systemd1.Job", bus_job_properties, j },
+ { NULL, }
+ };
+
+ SELINUX_UNIT_ACCESS_CHECK(j->unit, connection, message, "status");
+ return bus_default_message_handler(connection, message, INTROSPECTION, INTERFACES_LIST, bps);
+ }
+
+ if (!bus_maybe_send_reply(connection, message, reply))
+ return DBUS_HANDLER_RESULT_NEED_MEMORY;
+
+ return DBUS_HANDLER_RESULT_HANDLED;
+}
+
+static DBusHandlerResult bus_job_message_handler(DBusConnection *connection, DBusMessage *message, void *data) {
+ Manager *m = data;
+ Job *j;
+ int r;
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+
+ assert(connection);
+ assert(message);
+ assert(m);
+
+ if (streq(dbus_message_get_path(message), "/org/freedesktop/systemd1/job")) {
+ /* Be nice to gdbus and return introspection data for our mid-level paths */
+
+ if (dbus_message_is_method_call(message, "org.freedesktop.DBus.Introspectable", "Introspect")) {
+ char *introspection = NULL;
+ FILE *f;
+ Iterator i;
+ size_t size;
+
+ SELINUX_ACCESS_CHECK(connection, message, "status");
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ /* We roll our own introspection code here, instead of
+ * relying on bus_default_message_handler() because we
+ * need to generate our introspection string
+ * dynamically. */
+
+ f = open_memstream(&introspection, &size);
+ if (!f)
+ goto oom;
+
+ fputs(DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE
+ "<node>\n", f);
+
+ fputs(BUS_INTROSPECTABLE_INTERFACE, f);
+ fputs(BUS_PEER_INTERFACE, f);
+
+ HASHMAP_FOREACH(j, m->jobs, i)
+ fprintf(f, "<node name=\"job/%lu\"/>", (unsigned long) j->id);
+
+ fputs("</node>\n", f);
+
+ if (ferror(f)) {
+ fclose(f);
+ free(introspection);
+ goto oom;
+ }
+
+ fclose(f);
+
+ if (!introspection)
+ goto oom;
+
+ if (!dbus_message_append_args(reply, DBUS_TYPE_STRING, &introspection, DBUS_TYPE_INVALID)) {
+ free(introspection);
+ goto oom;
+ }
+
+ free(introspection);
+
+ if (!bus_maybe_send_reply(connection, message, reply))
+ goto oom;
+
+ return DBUS_HANDLER_RESULT_HANDLED;
+ }
+
+ return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
+ }
+
+ r = manager_get_job_from_dbus_path(m, dbus_message_get_path(message), &j);
+ if (r == -ENOMEM)
+ goto oom;
+ if (r == -ENOENT) {
+ DBusError e;
+
+ dbus_error_init(&e);
+ dbus_set_error_const(&e, DBUS_ERROR_UNKNOWN_OBJECT, "Unknown job");
+ return bus_send_error_reply(connection, message, &e, r);
+ }
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ return bus_job_message_dispatch(j, connection, message);
+
+oom:
+ return DBUS_HANDLER_RESULT_NEED_MEMORY;
+}
+
+const DBusObjectPathVTable bus_job_vtable = {
+ .message_function = bus_job_message_handler
+};
+
+static int job_send_message(Job *j, DBusMessage* (*new_message)(Job *j)) {
+ _cleanup_dbus_message_unref_ DBusMessage *m = NULL;
+ int r;
+
+ assert(j);
+ assert(new_message);
+
+ if (bus_has_subscriber(j->manager) || j->forgot_bus_clients) {
+ m = new_message(j);
+ if (!m)
+ return -ENOMEM;
+
+ r = bus_broadcast(j->manager, m);
+ if (r < 0)
+ return r;
+
+ } else {
+ /* If nobody is subscribed, we just send the message
+ * to the client(s) which created the job */
+ JobBusClient *cl;
+ assert(j->bus_client_list);
+
+ LIST_FOREACH(client, cl, j->bus_client_list) {
+ assert(cl->bus);
+
+ m = new_message(j);
+ if (!m)
+ return -ENOMEM;
+
+ if (!dbus_message_set_destination(m, cl->name))
+ return -ENOMEM;
+
+ if (!dbus_connection_send(cl->bus, m, NULL))
+ return -ENOMEM;
+
+ dbus_message_unref(m);
+ m = NULL;
+ }
+ }
+
+ return 0;
+}
+
+static DBusMessage* new_change_signal_message(Job *j) {
+ DBusMessage *m = NULL;
+ char *p = NULL;
+
+ p = job_dbus_path(j);
+ if (!p)
+ goto oom;
+
+ if (j->sent_dbus_new_signal) {
+ /* Send a properties changed signal */
+ m = bus_properties_changed_new(p, "org.freedesktop.systemd1.Job", INVALIDATING_PROPERTIES);
+ if (!m)
+ goto oom;
+
+ } else {
+ /* Send a new signal */
+
+ m = dbus_message_new_signal("/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager", "JobNew");
+ if (!m)
+ goto oom;
+
+ if (!dbus_message_append_args(m,
+ DBUS_TYPE_UINT32, &j->id,
+ DBUS_TYPE_OBJECT_PATH, &p,
+ DBUS_TYPE_STRING, &j->unit->id,
+ DBUS_TYPE_INVALID))
+ goto oom;
+ }
+
+ return m;
+
+oom:
+ if (m)
+ dbus_message_unref(m);
+ free(p);
+ return NULL;
+}
+
+static DBusMessage* new_removed_signal_message(Job *j) {
+ DBusMessage *m = NULL;
+ char *p = NULL;
+ const char *r;
+
+ p = job_dbus_path(j);
+ if (!p)
+ goto oom;
+
+ m = dbus_message_new_signal("/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager", "JobRemoved");
+ if (!m)
+ goto oom;
+
+ r = job_result_to_string(j->result);
+
+ if (!dbus_message_append_args(m,
+ DBUS_TYPE_UINT32, &j->id,
+ DBUS_TYPE_OBJECT_PATH, &p,
+ DBUS_TYPE_STRING, &j->unit->id,
+ DBUS_TYPE_STRING, &r,
+ DBUS_TYPE_INVALID))
+ goto oom;
+
+ return m;
+
+oom:
+ if (m)
+ dbus_message_unref(m);
+ free(p);
+ return NULL;
+}
+
+void bus_job_send_change_signal(Job *j) {
+ assert(j);
+
+ if (j->in_dbus_queue) {
+ LIST_REMOVE(Job, dbus_queue, j->manager->dbus_job_queue, j);
+ j->in_dbus_queue = false;
+ }
+
+ if (!bus_has_subscriber(j->manager) && !j->bus_client_list && !j->forgot_bus_clients) {
+ j->sent_dbus_new_signal = true;
+ return;
+ }
+
+ if (job_send_message(j, new_change_signal_message) < 0)
+ goto oom;
+
+ j->sent_dbus_new_signal = true;
+
+ return;
+
+oom:
+ log_error("Failed to allocate job change signal.");
+}
+
+void bus_job_send_removed_signal(Job *j) {
+ assert(j);
+
+ if (!bus_has_subscriber(j->manager) && !j->bus_client_list && !j->forgot_bus_clients)
+ return;
+
+ if (!j->sent_dbus_new_signal)
+ bus_job_send_change_signal(j);
+
+ if (job_send_message(j, new_removed_signal_message) < 0)
+ goto oom;
+
+ return;
+
+oom:
+ log_error("Failed to allocate job remove signal.");
+}
diff --git a/src/core/dbus-job.h b/src/core/dbus-job.h
new file mode 100644
index 0000000000..a1b928fb16
--- /dev/null
+++ b/src/core/dbus-job.h
@@ -0,0 +1,33 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <dbus/dbus.h>
+
+#include "job.h"
+
+void bus_job_send_change_signal(Job *j);
+void bus_job_send_removed_signal(Job *j);
+
+extern const DBusObjectPathVTable bus_job_vtable;
+
+extern const char bus_job_interface[];
diff --git a/src/core/dbus-kill.c b/src/core/dbus-kill.c
new file mode 100644
index 0000000000..165f63074b
--- /dev/null
+++ b/src/core/dbus-kill.c
@@ -0,0 +1,35 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <dbus/dbus.h>
+
+#include "dbus-kill.h"
+#include "dbus-common.h"
+
+DEFINE_BUS_PROPERTY_APPEND_ENUM(bus_kill_append_mode, kill_mode, KillMode);
+
+const BusProperty bus_kill_context_properties[] = {
+ { "KillMode", bus_kill_append_mode, "s", offsetof(KillContext, kill_mode) },
+ { "KillSignal", bus_property_append_int, "i", offsetof(KillContext, kill_signal) },
+ { "SendSIGKILL", bus_property_append_bool, "b", offsetof(KillContext, send_sigkill) },
+ { NULL, }
+};
diff --git a/src/core/dbus-kill.h b/src/core/dbus-kill.h
new file mode 100644
index 0000000000..238fbd36d6
--- /dev/null
+++ b/src/core/dbus-kill.h
@@ -0,0 +1,39 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <dbus/dbus.h>
+
+#include "manager.h"
+#include "dbus-common.h"
+
+#define BUS_KILL_CONTEXT_INTERFACE \
+ " <property name=\"KillMode\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"KillSignal\" type=\"i\" access=\"read\"/>\n" \
+ " <property name=\"SendSIGKILL\" type=\"b\" access=\"read\"/>\n"
+
+#define BUS_KILL_COMMAND_INTERFACE(name) \
+ " <property name=\"" name "\" type=\"a(sasbttuii)\" access=\"read\"/>\n"
+
+extern const BusProperty bus_kill_context_properties[];
+
+int bus_kill_append_mode(DBusMessageIter *i, const char *property, void *data);
diff --git a/src/core/dbus-manager.c b/src/core/dbus-manager.c
new file mode 100644
index 0000000000..56b02a1cf5
--- /dev/null
+++ b/src/core/dbus-manager.c
@@ -0,0 +1,1912 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <unistd.h>
+
+#include "dbus.h"
+#include "log.h"
+#include "dbus-manager.h"
+#include "strv.h"
+#include "bus-errors.h"
+#include "build.h"
+#include "dbus-common.h"
+#include "install.h"
+#include "selinux-access.h"
+#include "watchdog.h"
+#include "hwclock.h"
+#include "path-util.h"
+#include "dbus-unit.h"
+#include "virt.h"
+#include "env-util.h"
+
+#define BUS_MANAGER_INTERFACE_BEGIN \
+ " <interface name=\"org.freedesktop.systemd1.Manager\">\n"
+
+#define BUS_MANAGER_INTERFACE_METHODS \
+ " <method name=\"GetUnit\">\n" \
+ " <arg name=\"name\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"unit\" type=\"o\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"GetUnitByPID\">\n" \
+ " <arg name=\"pid\" type=\"u\" direction=\"in\"/>\n" \
+ " <arg name=\"unit\" type=\"o\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"LoadUnit\">\n" \
+ " <arg name=\"name\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"unit\" type=\"o\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"StartUnit\">\n" \
+ " <arg name=\"name\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"mode\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"job\" type=\"o\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"StartUnitReplace\">\n" \
+ " <arg name=\"old_unit\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"new_unit\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"mode\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"job\" type=\"o\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"StopUnit\">\n" \
+ " <arg name=\"name\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"mode\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"job\" type=\"o\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"ReloadUnit\">\n" \
+ " <arg name=\"name\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"mode\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"job\" type=\"o\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"RestartUnit\">\n" \
+ " <arg name=\"name\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"mode\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"job\" type=\"o\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"TryRestartUnit\">\n" \
+ " <arg name=\"name\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"mode\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"job\" type=\"o\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"ReloadOrRestartUnit\">\n" \
+ " <arg name=\"name\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"mode\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"job\" type=\"o\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"ReloadOrTryRestartUnit\">\n" \
+ " <arg name=\"name\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"mode\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"job\" type=\"o\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"KillUnit\">\n" \
+ " <arg name=\"name\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"who\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"signal\" type=\"i\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"ResetFailedUnit\">\n" \
+ " <arg name=\"name\" type=\"s\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"SetUnitControlGroup\">\n" \
+ " <arg name=\"name\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"group\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"mode\" type=\"s\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"UnsetUnitControlGroup\">\n" \
+ " <arg name=\"name\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"group\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"mode\" type=\"s\" direction=\"in\"\n/>" \
+ " </method>\n" \
+ " <method name=\"GetUnitControlGroupAttribute\">\n" \
+ " <arg name=\"name\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"attribute\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"values\" type=\"as\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"SetUnitControlGroupAttribute\">\n" \
+ " <arg name=\"name\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"attribute\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"values\" type=\"as\" direction=\"in\"/>\n" \
+ " <arg name=\"mode\" type=\"s\" direction=\"in\"\n/>" \
+ " </method>\n" \
+ " <method name=\"UnsetUnitControlGroupAttributes\">\n" \
+ " <arg name=\"name\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"attribute\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"mode\" type=\"s\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"GetJob\">\n" \
+ " <arg name=\"id\" type=\"u\" direction=\"in\"/>\n" \
+ " <arg name=\"job\" type=\"o\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"CancelJob\">\n" \
+ " <arg name=\"id\" type=\"u\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"ClearJobs\"/>\n" \
+ " <method name=\"ResetFailed\"/>\n" \
+ " <method name=\"ListUnits\">\n" \
+ " <arg name=\"units\" type=\"a(ssssssouso)\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"ListJobs\">\n" \
+ " <arg name=\"jobs\" type=\"a(usssoo)\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"Subscribe\"/>\n" \
+ " <method name=\"Unsubscribe\"/>\n" \
+ " <method name=\"Dump\">\n" \
+ " <arg name=\"dump\" type=\"s\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"CreateSnapshot\">\n" \
+ " <arg name=\"name\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"cleanup\" type=\"b\" direction=\"in\"/>\n" \
+ " <arg name=\"unit\" type=\"o\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"RemoveSnapshot\">\n" \
+ " <arg name=\"name\" type=\"s\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"Reload\"/>\n" \
+ " <method name=\"Reexecute\"/>\n" \
+ " <method name=\"Exit\"/>\n" \
+ " <method name=\"Reboot\"/>\n" \
+ " <method name=\"PowerOff\"/>\n" \
+ " <method name=\"Halt\"/>\n" \
+ " <method name=\"KExec\"/>\n" \
+ " <method name=\"SwitchRoot\">\n" \
+ " <arg name=\"new_root\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"init\" type=\"s\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"SetEnvironment\">\n" \
+ " <arg name=\"names\" type=\"as\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"UnsetEnvironment\">\n" \
+ " <arg name=\"names\" type=\"as\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"UnsetAndSetEnvironment\">\n" \
+ " <arg name=\"unset\" type=\"as\" direction=\"in\"/>\n" \
+ " <arg name=\"set\" type=\"as\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"ListUnitFiles\">\n" \
+ " <arg name=\"files\" type=\"a(ss)\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"GetUnitFileState\">\n" \
+ " <arg name=\"file\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"state\" type=\"s\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"EnableUnitFiles\">\n" \
+ " <arg name=\"files\" type=\"as\" direction=\"in\"/>\n" \
+ " <arg name=\"runtime\" type=\"b\" direction=\"in\"/>\n" \
+ " <arg name=\"force\" type=\"b\" direction=\"in\"/>\n" \
+ " <arg name=\"carries_install_info\" type=\"b\" direction=\"out\"/>\n" \
+ " <arg name=\"changes\" type=\"a(sss)\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"DisableUnitFiles\">\n" \
+ " <arg name=\"files\" type=\"as\" direction=\"in\"/>\n" \
+ " <arg name=\"runtime\" type=\"b\" direction=\"in\"/>\n" \
+ " <arg name=\"changes\" type=\"a(sss)\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"ReenableUnitFiles\">\n" \
+ " <arg name=\"files\" type=\"as\" direction=\"in\"/>\n" \
+ " <arg name=\"runtime\" type=\"b\" direction=\"in\"/>\n" \
+ " <arg name=\"force\" type=\"b\" direction=\"in\"/>\n" \
+ " <arg name=\"carries_install_info\" type=\"b\" direction=\"out\"/>\n" \
+ " <arg name=\"changes\" type=\"a(sss)\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"LinkUnitFiles\">\n" \
+ " <arg name=\"files\" type=\"as\" direction=\"in\"/>\n" \
+ " <arg name=\"runtime\" type=\"b\" direction=\"in\"/>\n" \
+ " <arg name=\"force\" type=\"b\" direction=\"in\"/>\n" \
+ " <arg name=\"changes\" type=\"a(sss)\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"PresetUnitFiles\">\n" \
+ " <arg name=\"files\" type=\"as\" direction=\"in\"/>\n" \
+ " <arg name=\"runtime\" type=\"b\" direction=\"in\"/>\n" \
+ " <arg name=\"force\" type=\"b\" direction=\"in\"/>\n" \
+ " <arg name=\"carries_install_info\" type=\"b\" direction=\"out\"/>\n" \
+ " <arg name=\"changes\" type=\"a(sss)\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"MaskUnitFiles\">\n" \
+ " <arg name=\"files\" type=\"as\" direction=\"in\"/>\n" \
+ " <arg name=\"runtime\" type=\"b\" direction=\"in\"/>\n" \
+ " <arg name=\"force\" type=\"b\" direction=\"in\"/>\n" \
+ " <arg name=\"changes\" type=\"a(sss)\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"UnmaskUnitFiles\">\n" \
+ " <arg name=\"files\" type=\"as\" direction=\"in\"/>\n" \
+ " <arg name=\"runtime\" type=\"b\" direction=\"in\"/>\n" \
+ " <arg name=\"changes\" type=\"a(sss)\" direction=\"out\"/>\n" \
+ " </method>\n"
+
+#define BUS_MANAGER_INTERFACE_SIGNALS \
+ " <signal name=\"UnitNew\">\n" \
+ " <arg name=\"id\" type=\"s\"/>\n" \
+ " <arg name=\"unit\" type=\"o\"/>\n" \
+ " </signal>\n" \
+ " <signal name=\"UnitRemoved\">\n" \
+ " <arg name=\"id\" type=\"s\"/>\n" \
+ " <arg name=\"unit\" type=\"o\"/>\n" \
+ " </signal>\n" \
+ " <signal name=\"JobNew\">\n" \
+ " <arg name=\"id\" type=\"u\"/>\n" \
+ " <arg name=\"job\" type=\"o\"/>\n" \
+ " <arg name=\"unit\" type=\"s\"/>\n" \
+ " </signal>\n" \
+ " <signal name=\"JobRemoved\">\n" \
+ " <arg name=\"id\" type=\"u\"/>\n" \
+ " <arg name=\"job\" type=\"o\"/>\n" \
+ " <arg name=\"unit\" type=\"s\"/>\n" \
+ " <arg name=\"result\" type=\"s\"/>\n" \
+ " </signal>" \
+ " <signal name=\"StartupFinished\">\n" \
+ " <arg name=\"firmware\" type=\"t\"/>\n" \
+ " <arg name=\"loader\" type=\"t\"/>\n" \
+ " <arg name=\"kernel\" type=\"t\"/>\n" \
+ " <arg name=\"initrd\" type=\"t\"/>\n" \
+ " <arg name=\"userspace\" type=\"t\"/>\n" \
+ " <arg name=\"total\" type=\"t\"/>\n" \
+ " </signal>" \
+ " <signal name=\"UnitFilesChanged\"/>\n"
+
+#define BUS_MANAGER_INTERFACE_PROPERTIES_GENERAL \
+ " <property name=\"Version\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"Features\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"Tainted\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"FirmwareTimestamp\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"FirmwareTimestampMonotonic\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"LoaderTimestamp\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"LoaderTimestampMonotonic\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"KernelTimestamp\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"KernelTimestampMonotonic\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"InitRDTimestamp\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"InitRDTimestampMonotonic\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"UserspaceTimestamp\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"UserspaceTimestampMonotonic\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"FinishTimestamp\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"FinishTimestampMonotonic\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"LogLevel\" type=\"s\" access=\"readwrite\"/>\n" \
+ " <property name=\"LogTarget\" type=\"s\" access=\"readwrite\"/>\n" \
+ " <property name=\"NNames\" type=\"u\" access=\"read\"/>\n" \
+ " <property name=\"NJobs\" type=\"u\" access=\"read\"/>\n" \
+ " <property name=\"NInstalledJobs\" type=\"u\" access=\"read\"/>\n" \
+ " <property name=\"NFailedJobs\" type=\"u\" access=\"read\"/>\n" \
+ " <property name=\"Progress\" type=\"d\" access=\"read\"/>\n" \
+ " <property name=\"Environment\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"ConfirmSpawn\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"ShowStatus\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"UnitPath\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"ControlGroupHierarchy\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"DefaultControllers\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"DefaultStandardOutput\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"DefaultStandardError\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"RuntimeWatchdogUSec\" type=\"t\" access=\"readwrite\"/>\n" \
+ " <property name=\"ShutdownWatchdogUSec\" type=\"t\" access=\"readwrite\"/>\n" \
+ " <property name=\"Virtualization\" type=\"s\" access=\"read\"/>\n"
+
+#define BUS_MANAGER_INTERFACE_END \
+ " </interface>\n"
+
+#define BUS_MANAGER_INTERFACE \
+ BUS_MANAGER_INTERFACE_BEGIN \
+ BUS_MANAGER_INTERFACE_METHODS \
+ BUS_MANAGER_INTERFACE_SIGNALS \
+ BUS_MANAGER_INTERFACE_PROPERTIES_GENERAL \
+ BUS_MANAGER_INTERFACE_END
+
+#define INTROSPECTION_BEGIN \
+ DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE \
+ "<node>\n" \
+ BUS_MANAGER_INTERFACE \
+ BUS_PROPERTIES_INTERFACE \
+ BUS_PEER_INTERFACE \
+ BUS_INTROSPECTABLE_INTERFACE
+
+#define INTROSPECTION_END \
+ "</node>\n"
+
+#define INTERFACES_LIST \
+ BUS_GENERIC_INTERFACES_LIST \
+ "org.freedesktop.systemd1.Manager\0"
+
+const char bus_manager_interface[] _introspect_("Manager") = BUS_MANAGER_INTERFACE;
+
+static DEFINE_BUS_PROPERTY_APPEND_ENUM(bus_manager_append_exec_output, exec_output, ExecOutput);
+
+static int bus_manager_append_tainted(DBusMessageIter *i, const char *property, void *data) {
+ const char *t;
+ Manager *m = data;
+ char buf[LINE_MAX] = "", *e = buf, *p = NULL;
+
+ assert(i);
+ assert(property);
+ assert(m);
+
+ if (m->taint_usr)
+ e = stpcpy(e, "split-usr:");
+
+ if (readlink_malloc("/etc/mtab", &p) < 0)
+ e = stpcpy(e, "mtab-not-symlink:");
+ else
+ free(p);
+
+ if (access("/proc/cgroups", F_OK) < 0)
+ e = stpcpy(e, "cgroups-missing:");
+
+ if (hwclock_is_localtime() > 0)
+ e = stpcpy(e, "local-hwclock:");
+
+ /* remove the last ':' */
+ if (e != buf)
+ e[-1] = 0;
+
+ t = buf;
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_STRING, &t))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_manager_append_log_target(DBusMessageIter *i, const char *property, void *data) {
+ const char *t;
+
+ assert(i);
+ assert(property);
+
+ t = log_target_to_string(log_get_target());
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_STRING, &t))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_manager_set_log_target(DBusMessageIter *i, const char *property, void *data) {
+ const char *t;
+
+ assert(i);
+ assert(property);
+
+ dbus_message_iter_get_basic(i, &t);
+
+ return log_set_target_from_string(t);
+}
+
+static int bus_manager_append_log_level(DBusMessageIter *i, const char *property, void *data) {
+ char *t;
+ int r;
+
+ assert(i);
+ assert(property);
+
+ r = log_level_to_string_alloc(log_get_max_level(), &t);
+ if (r < 0)
+ return r;
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_STRING, &t))
+ r = -ENOMEM;
+
+ free(t);
+ return r;
+}
+
+static int bus_manager_set_log_level(DBusMessageIter *i, const char *property, void *data) {
+ const char *t;
+
+ assert(i);
+ assert(property);
+
+ dbus_message_iter_get_basic(i, &t);
+
+ return log_set_max_level_from_string(t);
+}
+
+static int bus_manager_append_n_names(DBusMessageIter *i, const char *property, void *data) {
+ Manager *m = data;
+ uint32_t u;
+
+ assert(i);
+ assert(property);
+ assert(m);
+
+ u = hashmap_size(m->units);
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT32, &u))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_manager_append_n_jobs(DBusMessageIter *i, const char *property, void *data) {
+ Manager *m = data;
+ uint32_t u;
+
+ assert(i);
+ assert(property);
+ assert(m);
+
+ u = hashmap_size(m->jobs);
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT32, &u))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_manager_append_progress(DBusMessageIter *i, const char *property, void *data) {
+ double d;
+ Manager *m = data;
+
+ assert(i);
+ assert(property);
+ assert(m);
+
+ if (dual_timestamp_is_set(&m->finish_timestamp))
+ d = 1.0;
+ else
+ d = 1.0 - ((double) hashmap_size(m->jobs) / (double) m->n_installed_jobs);
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_DOUBLE, &d))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_manager_append_virt(DBusMessageIter *i, const char *property, void *data) {
+ Manager *m = data;
+ const char *id = "";
+
+ assert(i);
+ assert(property);
+ assert(m);
+
+ detect_virtualization(&id);
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_STRING, &id))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static DBusMessage *message_from_file_changes(
+ DBusMessage *m,
+ UnitFileChange *changes,
+ unsigned n_changes,
+ int carries_install_info) {
+
+ DBusMessageIter iter, sub, sub2;
+ DBusMessage *reply;
+ unsigned i;
+
+ reply = dbus_message_new_method_return(m);
+ if (!reply)
+ return NULL;
+
+ dbus_message_iter_init_append(reply, &iter);
+
+ if (carries_install_info >= 0) {
+ dbus_bool_t b;
+
+ b = !!carries_install_info;
+ if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b))
+ goto oom;
+ }
+
+ if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "(sss)", &sub))
+ goto oom;
+
+ for (i = 0; i < n_changes; i++) {
+ const char *type, *path, *source;
+
+ type = unit_file_change_type_to_string(changes[i].type);
+ path = strempty(changes[i].path);
+ source = strempty(changes[i].source);
+
+ if (!dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, NULL, &sub2) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &type) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &path) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &source) ||
+ !dbus_message_iter_close_container(&sub, &sub2))
+ goto oom;
+ }
+
+ if (!dbus_message_iter_close_container(&iter, &sub))
+ goto oom;
+
+ return reply;
+
+oom:
+ dbus_message_unref(reply);
+ return NULL;
+}
+
+static int bus_manager_send_unit_files_changed(Manager *m) {
+ DBusMessage *s;
+ int r;
+
+ s = dbus_message_new_signal("/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager", "UnitFilesChanged");
+ if (!s)
+ return -ENOMEM;
+
+ r = bus_broadcast(m, s);
+ dbus_message_unref(s);
+
+ return r;
+}
+
+static int bus_manager_set_runtime_watchdog_usec(DBusMessageIter *i, const char *property, void *data) {
+ uint64_t *t = data;
+
+ assert(i);
+ assert(property);
+
+ dbus_message_iter_get_basic(i, t);
+
+ return watchdog_set_timeout(t);
+}
+
+static const char systemd_property_string[] =
+ PACKAGE_STRING "\0"
+ SYSTEMD_FEATURES;
+
+static const BusProperty bus_systemd_properties[] = {
+ { "Version", bus_property_append_string, "s", 0 },
+ { "Features", bus_property_append_string, "s", sizeof(PACKAGE_STRING) },
+ { NULL, }
+};
+
+static const BusProperty bus_manager_properties[] = {
+ { "Tainted", bus_manager_append_tainted, "s", 0 },
+ { "FirmwareTimestamp", bus_property_append_uint64, "t", offsetof(Manager, firmware_timestamp.realtime) },
+ { "FirmwareTimestampMonotonic", bus_property_append_uint64, "t", offsetof(Manager, firmware_timestamp.monotonic) },
+ { "LoaderTimestamp", bus_property_append_uint64, "t", offsetof(Manager, loader_timestamp.realtime) },
+ { "LoaderTimestampMonotonic", bus_property_append_uint64, "t", offsetof(Manager, loader_timestamp.monotonic) },
+ { "KernelTimestamp", bus_property_append_uint64, "t", offsetof(Manager, kernel_timestamp.realtime) },
+ { "KernelTimestampMonotonic", bus_property_append_uint64, "t", offsetof(Manager, kernel_timestamp.monotonic) },
+ { "InitRDTimestamp", bus_property_append_uint64, "t", offsetof(Manager, initrd_timestamp.realtime) },
+ { "InitRDTimestampMonotonic", bus_property_append_uint64, "t", offsetof(Manager, initrd_timestamp.monotonic) },
+ { "UserspaceTimestamp", bus_property_append_uint64, "t", offsetof(Manager, userspace_timestamp.realtime) },
+ { "UserspaceTimestampMonotonic", bus_property_append_uint64, "t", offsetof(Manager, userspace_timestamp.monotonic) },
+ { "FinishTimestamp", bus_property_append_uint64, "t", offsetof(Manager, finish_timestamp.realtime) },
+ { "FinishTimestampMonotonic", bus_property_append_uint64, "t", offsetof(Manager, finish_timestamp.monotonic) },
+ { "LogLevel", bus_manager_append_log_level, "s", 0, false, bus_manager_set_log_level },
+ { "LogTarget", bus_manager_append_log_target, "s", 0, false, bus_manager_set_log_target },
+ { "NNames", bus_manager_append_n_names, "u", 0 },
+ { "NJobs", bus_manager_append_n_jobs, "u", 0 },
+ { "NInstalledJobs", bus_property_append_uint32, "u", offsetof(Manager, n_installed_jobs) },
+ { "NFailedJobs", bus_property_append_uint32, "u", offsetof(Manager, n_failed_jobs) },
+ { "Progress", bus_manager_append_progress, "d", 0 },
+ { "Environment", bus_property_append_strv, "as", offsetof(Manager, environment), true },
+ { "ConfirmSpawn", bus_property_append_bool, "b", offsetof(Manager, confirm_spawn) },
+ { "ShowStatus", bus_property_append_bool, "b", offsetof(Manager, show_status) },
+ { "UnitPath", bus_property_append_strv, "as", offsetof(Manager, lookup_paths.unit_path), true },
+ { "ControlGroupHierarchy", bus_property_append_string, "s", offsetof(Manager, cgroup_hierarchy), true },
+ { "DefaultControllers", bus_property_append_strv, "as", offsetof(Manager, default_controllers), true },
+ { "DefaultStandardOutput", bus_manager_append_exec_output, "s", offsetof(Manager, default_std_output) },
+ { "DefaultStandardError", bus_manager_append_exec_output, "s", offsetof(Manager, default_std_error) },
+ { "RuntimeWatchdogUSec", bus_property_append_usec, "t", offsetof(Manager, runtime_watchdog), false, bus_manager_set_runtime_watchdog_usec },
+ { "ShutdownWatchdogUSec", bus_property_append_usec, "t", offsetof(Manager, shutdown_watchdog), false, bus_property_set_usec },
+ { "Virtualization", bus_manager_append_virt, "s", 0, },
+ { NULL, }
+};
+
+static DBusHandlerResult bus_manager_message_handler(DBusConnection *connection, DBusMessage *message, void *data) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ _cleanup_free_ char * path = NULL;
+ Manager *m = data;
+ int r;
+ DBusError error;
+ JobType job_type = _JOB_TYPE_INVALID;
+ bool reload_if_possible = false;
+ const char *member;
+
+ assert(connection);
+ assert(message);
+ assert(m);
+
+ dbus_error_init(&error);
+
+ member = dbus_message_get_member(message);
+
+ if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "GetUnit")) {
+ const char *name;
+ Unit *u;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ u = manager_get_unit(m, name);
+ if (!u) {
+ dbus_set_error(&error, BUS_ERROR_NO_SUCH_UNIT, "Unit %s is not loaded.", name);
+ return bus_send_error_reply(connection, message, &error, -ENOENT);
+ }
+
+ SELINUX_UNIT_ACCESS_CHECK(u, connection, message, "status");
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ path = unit_dbus_path(u);
+ if (!path)
+ goto oom;
+
+ if (!dbus_message_append_args(
+ reply,
+ DBUS_TYPE_OBJECT_PATH, &path,
+ DBUS_TYPE_INVALID))
+ goto oom;
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "GetUnitByPID")) {
+ Unit *u;
+ uint32_t pid;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_UINT32, &pid,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ u = cgroup_unit_by_pid(m, (pid_t) pid);
+ if (!u) {
+ dbus_set_error(&error, BUS_ERROR_NO_SUCH_UNIT, "No unit for PID %lu is loaded.", (unsigned long) pid);
+ return bus_send_error_reply(connection, message, &error, -ENOENT);
+ }
+
+ SELINUX_UNIT_ACCESS_CHECK(u, connection, message, "status");
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ path = unit_dbus_path(u);
+ if (!path)
+ goto oom;
+
+ if (!dbus_message_append_args(
+ reply,
+ DBUS_TYPE_OBJECT_PATH, &path,
+ DBUS_TYPE_INVALID))
+ goto oom;
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "LoadUnit")) {
+ const char *name;
+ Unit *u;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ r = manager_load_unit(m, name, NULL, &error, &u);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ SELINUX_UNIT_ACCESS_CHECK(u, connection, message, "status");
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ path = unit_dbus_path(u);
+ if (!path)
+ goto oom;
+
+ if (!dbus_message_append_args(
+ reply,
+ DBUS_TYPE_OBJECT_PATH, &path,
+ DBUS_TYPE_INVALID))
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "StartUnit"))
+ job_type = JOB_START;
+ else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "StartUnitReplace"))
+ job_type = JOB_START;
+ else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "StopUnit"))
+ job_type = JOB_STOP;
+ else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "ReloadUnit"))
+ job_type = JOB_RELOAD;
+ else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "RestartUnit"))
+ job_type = JOB_RESTART;
+ else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "TryRestartUnit"))
+ job_type = JOB_TRY_RESTART;
+ else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "ReloadOrRestartUnit")) {
+ reload_if_possible = true;
+ job_type = JOB_RESTART;
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "ReloadOrTryRestartUnit")) {
+ reload_if_possible = true;
+ job_type = JOB_TRY_RESTART;
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "KillUnit")) {
+ const char *name, *swho;
+ int32_t signo;
+ Unit *u;
+ KillWho who;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_STRING, &swho,
+ DBUS_TYPE_INT32, &signo,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ if (isempty(swho))
+ who = KILL_ALL;
+ else {
+ who = kill_who_from_string(swho);
+ if (who < 0)
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+ }
+
+ if (signo <= 0 || signo >= _NSIG)
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ u = manager_get_unit(m, name);
+ if (!u) {
+ dbus_set_error(&error, BUS_ERROR_NO_SUCH_UNIT, "Unit %s is not loaded.", name);
+ return bus_send_error_reply(connection, message, &error, -ENOENT);
+ }
+
+ SELINUX_UNIT_ACCESS_CHECK(u, connection, message, "stop");
+
+ r = unit_kill(u, who, signo, &error);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "GetJob")) {
+ uint32_t id;
+ Job *j;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_UINT32, &id,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ j = manager_get_job(m, id);
+ if (!j) {
+ dbus_set_error(&error, BUS_ERROR_NO_SUCH_JOB, "Job %u does not exist.", (unsigned) id);
+ return bus_send_error_reply(connection, message, &error, -ENOENT);
+ }
+
+ SELINUX_UNIT_ACCESS_CHECK(j->unit, connection, message, "status");
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ path = job_dbus_path(j);
+ if (!path)
+ goto oom;
+
+ if (!dbus_message_append_args(
+ reply,
+ DBUS_TYPE_OBJECT_PATH, &path,
+ DBUS_TYPE_INVALID))
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "CancelJob")) {
+ uint32_t id;
+ Job *j;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_UINT32, &id,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ j = manager_get_job(m, id);
+ if (!j) {
+ dbus_set_error(&error, BUS_ERROR_NO_SUCH_JOB, "Job %u does not exist.", (unsigned) id);
+ return bus_send_error_reply(connection, message, &error, -ENOENT);
+ }
+
+ SELINUX_UNIT_ACCESS_CHECK(j->unit, connection, message, "stop");
+ job_finish_and_invalidate(j, JOB_CANCELED, true);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "ClearJobs")) {
+
+ SELINUX_ACCESS_CHECK(connection, message, "reboot");
+ manager_clear_jobs(m);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "ResetFailed")) {
+
+ SELINUX_ACCESS_CHECK(connection, message, "reload");
+
+ manager_reset_failed(m);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "ResetFailedUnit")) {
+ const char *name;
+ Unit *u;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ u = manager_get_unit(m, name);
+ if (!u) {
+ dbus_set_error(&error, BUS_ERROR_NO_SUCH_UNIT, "Unit %s is not loaded.", name);
+ return bus_send_error_reply(connection, message, &error, -ENOENT);
+ }
+
+ SELINUX_UNIT_ACCESS_CHECK(u, connection, message, "reload");
+
+ unit_reset_failed(u);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "SetUnitControlGroup")) {
+ const char *name;
+ Unit *u;
+ DBusMessageIter iter;
+
+ if (!dbus_message_iter_init(message, &iter))
+ goto oom;
+
+ r = bus_iter_get_basic_and_next(&iter, DBUS_TYPE_STRING, &name, true);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ u = manager_get_unit(m, name);
+ if (!u) {
+ dbus_set_error(&error, BUS_ERROR_NO_SUCH_UNIT, "Unit %s is not loaded.", name);
+ return bus_send_error_reply(connection, message, &error, -ENOENT);
+ }
+
+ SELINUX_UNIT_ACCESS_CHECK(u, connection, message, "start");
+
+ r = bus_unit_cgroup_set(u, &iter);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "UnsetUnitControlGroup")) {
+ const char *name;
+ Unit *u;
+ DBusMessageIter iter;
+
+ if (!dbus_message_iter_init(message, &iter))
+ goto oom;
+
+ r = bus_iter_get_basic_and_next(&iter, DBUS_TYPE_STRING, &name, true);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ u = manager_get_unit(m, name);
+ if (!u) {
+ dbus_set_error(&error, BUS_ERROR_NO_SUCH_UNIT, "Unit %s is not loaded.", name);
+ return bus_send_error_reply(connection, message, &error, -ENOENT);
+ }
+
+ SELINUX_UNIT_ACCESS_CHECK(u, connection, message, "stop");
+
+ r = bus_unit_cgroup_unset(u, &iter);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "SetUnitControlGroupAttribute")) {
+ const char *name;
+ Unit *u;
+ DBusMessageIter iter;
+
+ if (!dbus_message_iter_init(message, &iter))
+ goto oom;
+
+ r = bus_iter_get_basic_and_next(&iter, DBUS_TYPE_STRING, &name, true);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ u = manager_get_unit(m, name);
+ if (!u) {
+ dbus_set_error(&error, BUS_ERROR_NO_SUCH_UNIT, "Unit %s is not loaded.", name);
+ return bus_send_error_reply(connection, message, &error, -ENOENT);
+ }
+
+ SELINUX_UNIT_ACCESS_CHECK(u, connection, message, "start");
+
+ r = bus_unit_cgroup_attribute_set(u, &iter);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "UnsetUnitControlGroupAttribute")) {
+ const char *name;
+ Unit *u;
+ DBusMessageIter iter;
+
+ if (!dbus_message_iter_init(message, &iter))
+ goto oom;
+
+ r = bus_iter_get_basic_and_next(&iter, DBUS_TYPE_STRING, &name, true);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ u = manager_get_unit(m, name);
+ if (!u) {
+ dbus_set_error(&error, BUS_ERROR_NO_SUCH_UNIT, "Unit %s is not loaded.", name);
+ return bus_send_error_reply(connection, message, &error, -ENOENT);
+ }
+
+ SELINUX_UNIT_ACCESS_CHECK(u, connection, message, "stop");
+
+ r = bus_unit_cgroup_attribute_unset(u, &iter);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "GetUnitControlGroupAttribute")) {
+ const char *name;
+ Unit *u;
+ DBusMessageIter iter;
+ _cleanup_strv_free_ char **list = NULL;
+
+ if (!dbus_message_iter_init(message, &iter))
+ goto oom;
+
+ r = bus_iter_get_basic_and_next(&iter, DBUS_TYPE_STRING, &name, true);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ u = manager_get_unit(m, name);
+ if (!u) {
+ dbus_set_error(&error, BUS_ERROR_NO_SUCH_UNIT, "Unit %s is not loaded.", name);
+ return bus_send_error_reply(connection, message, &error, -ENOENT);
+ }
+
+ SELINUX_UNIT_ACCESS_CHECK(u, connection, message, "status");
+
+ r = bus_unit_cgroup_attribute_get(u, &iter, &list);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ dbus_message_iter_init_append(reply, &iter);
+ if (bus_append_strv_iter(&iter, list) < 0)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "ListUnits")) {
+ DBusMessageIter iter, sub;
+ Iterator i;
+ Unit *u;
+ const char *k;
+
+ SELINUX_ACCESS_CHECK(connection, message, "status");
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ dbus_message_iter_init_append(reply, &iter);
+
+ if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "(ssssssouso)", &sub))
+ goto oom;
+
+ HASHMAP_FOREACH_KEY(u, k, m->units, i) {
+ char *u_path, *j_path;
+ const char *description, *load_state, *active_state, *sub_state, *sjob_type, *following;
+ DBusMessageIter sub2;
+ uint32_t job_id;
+ Unit *f;
+
+ if (k != u->id)
+ continue;
+
+ if (!dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, NULL, &sub2))
+ goto oom;
+
+ description = unit_description(u);
+ load_state = unit_load_state_to_string(u->load_state);
+ active_state = unit_active_state_to_string(unit_active_state(u));
+ sub_state = unit_sub_state_to_string(u);
+
+ f = unit_following(u);
+ following = f ? f->id : "";
+
+ u_path = unit_dbus_path(u);
+ if (!u_path)
+ goto oom;
+
+ if (u->job) {
+ job_id = (uint32_t) u->job->id;
+
+ if (!(j_path = job_dbus_path(u->job))) {
+ free(u_path);
+ goto oom;
+ }
+
+ sjob_type = job_type_to_string(u->job->type);
+ } else {
+ job_id = 0;
+ j_path = u_path;
+ sjob_type = "";
+ }
+
+ if (!dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &u->id) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &description) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &load_state) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &active_state) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &sub_state) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &following) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_OBJECT_PATH, &u_path) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_UINT32, &job_id) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &sjob_type) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_OBJECT_PATH, &j_path)) {
+ free(u_path);
+ if (u->job)
+ free(j_path);
+ goto oom;
+ }
+
+ free(u_path);
+ if (u->job)
+ free(j_path);
+
+ if (!dbus_message_iter_close_container(&sub, &sub2))
+ goto oom;
+ }
+
+ if (!dbus_message_iter_close_container(&iter, &sub))
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "ListJobs")) {
+ DBusMessageIter iter, sub;
+ Iterator i;
+ Job *j;
+
+ SELINUX_ACCESS_CHECK(connection, message, "status");
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ dbus_message_iter_init_append(reply, &iter);
+
+ if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "(usssoo)", &sub))
+ goto oom;
+
+ HASHMAP_FOREACH(j, m->jobs, i) {
+ char *u_path, *j_path;
+ const char *state, *type;
+ uint32_t id;
+ DBusMessageIter sub2;
+
+ if (!dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, NULL, &sub2))
+ goto oom;
+
+ id = (uint32_t) j->id;
+ state = job_state_to_string(j->state);
+ type = job_type_to_string(j->type);
+
+ j_path = job_dbus_path(j);
+ if (!j_path)
+ goto oom;
+
+ u_path = unit_dbus_path(j->unit);
+ if (!u_path) {
+ free(j_path);
+ goto oom;
+ }
+
+ if (!dbus_message_iter_append_basic(&sub2, DBUS_TYPE_UINT32, &id) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &j->unit->id) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &type) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &state) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_OBJECT_PATH, &j_path) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_OBJECT_PATH, &u_path)) {
+ free(j_path);
+ free(u_path);
+ goto oom;
+ }
+
+ free(j_path);
+ free(u_path);
+
+ if (!dbus_message_iter_close_container(&sub, &sub2))
+ goto oom;
+ }
+
+ if (!dbus_message_iter_close_container(&iter, &sub))
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "Subscribe")) {
+ char *client;
+ Set *s;
+
+ SELINUX_ACCESS_CHECK(connection, message, "status");
+
+ s = BUS_CONNECTION_SUBSCRIBED(m, connection);
+ if (!s) {
+ s = set_new(string_hash_func, string_compare_func);
+ if (!s)
+ goto oom;
+
+ if (!dbus_connection_set_data(connection, m->subscribed_data_slot, s, NULL)) {
+ set_free(s);
+ goto oom;
+ }
+ }
+
+ client = strdup(bus_message_get_sender_with_fallback(message));
+ if (!client)
+ goto oom;
+
+ r = set_consume(s, client);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "Unsubscribe")) {
+ char *client;
+
+ SELINUX_ACCESS_CHECK(connection, message, "status");
+
+ client = set_remove(BUS_CONNECTION_SUBSCRIBED(m, connection), (char*) bus_message_get_sender_with_fallback(message));
+ if (!client) {
+ dbus_set_error(&error, BUS_ERROR_NOT_SUBSCRIBED, "Client is not subscribed.");
+ return bus_send_error_reply(connection, message, &error, -ENOENT);
+ }
+
+ free(client);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "Dump")) {
+ FILE *f;
+ char *dump = NULL;
+ size_t size;
+
+ SELINUX_ACCESS_CHECK(connection, message, "status");
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ f = open_memstream(&dump, &size);
+ if (!f)
+ goto oom;
+
+ manager_dump_units(m, f, NULL);
+ manager_dump_jobs(m, f, NULL);
+
+ if (ferror(f)) {
+ fclose(f);
+ free(dump);
+ goto oom;
+ }
+
+ fclose(f);
+
+ if (!dbus_message_append_args(reply, DBUS_TYPE_STRING, &dump, DBUS_TYPE_INVALID)) {
+ free(dump);
+ goto oom;
+ }
+
+ free(dump);
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "CreateSnapshot")) {
+ const char *name;
+ dbus_bool_t cleanup;
+ Snapshot *s;
+
+ SELINUX_ACCESS_CHECK(connection, message, "start");
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_BOOLEAN, &cleanup,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ if (isempty(name))
+ name = NULL;
+
+ r = snapshot_create(m, name, cleanup, &error, &s);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ path = unit_dbus_path(UNIT(s));
+ if (!path)
+ goto oom;
+
+ if (!dbus_message_append_args(
+ reply,
+ DBUS_TYPE_OBJECT_PATH, &path,
+ DBUS_TYPE_INVALID))
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "RemoveSnapshot")) {
+ const char *name;
+ Unit *u;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ u = manager_get_unit(m, name);
+ if (!u) {
+ dbus_set_error(&error, BUS_ERROR_NO_SUCH_UNIT, "Unit %s does not exist.", name);
+ return bus_send_error_reply(connection, message, &error, -ENOENT);
+ }
+
+ if (u->type != UNIT_SNAPSHOT) {
+ dbus_set_error(&error, BUS_ERROR_NO_SUCH_UNIT, "Unit %s is not a snapshot.", name);
+ return bus_send_error_reply(connection, message, &error, -ENOENT);
+ }
+
+ SELINUX_UNIT_ACCESS_CHECK(u, connection, message, "stop");
+ snapshot_remove(SNAPSHOT(u));
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.DBus.Introspectable", "Introspect")) {
+ char *introspection = NULL;
+ FILE *f;
+ Iterator i;
+ Unit *u;
+ Job *j;
+ const char *k;
+ size_t size;
+
+ SELINUX_ACCESS_CHECK(connection, message, "status");
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ /* We roll our own introspection code here, instead of
+ * relying on bus_default_message_handler() because we
+ * need to generate our introspection string
+ * dynamically. */
+
+ f = open_memstream(&introspection, &size);
+ if (!f)
+ goto oom;
+
+ fputs(INTROSPECTION_BEGIN, f);
+
+ HASHMAP_FOREACH_KEY(u, k, m->units, i) {
+ char *p;
+
+ if (k != u->id)
+ continue;
+
+ p = bus_path_escape(k);
+ if (!p) {
+ fclose(f);
+ free(introspection);
+ goto oom;
+ }
+
+ fprintf(f, "<node name=\"unit/%s\"/>", p);
+ free(p);
+ }
+
+ HASHMAP_FOREACH(j, m->jobs, i)
+ fprintf(f, "<node name=\"job/%lu\"/>", (unsigned long) j->id);
+
+ fputs(INTROSPECTION_END, f);
+
+ if (ferror(f)) {
+ fclose(f);
+ free(introspection);
+ goto oom;
+ }
+
+ fclose(f);
+
+ if (!introspection)
+ goto oom;
+
+ if (!dbus_message_append_args(reply, DBUS_TYPE_STRING, &introspection, DBUS_TYPE_INVALID)) {
+ free(introspection);
+ goto oom;
+ }
+
+ free(introspection);
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "Reload")) {
+
+ SELINUX_ACCESS_CHECK(connection, message, "reload");
+
+ assert(!m->queued_message);
+
+ /* Instead of sending the reply back right away, we
+ * just remember that we need to and then send it
+ * after the reload is finished. That way the caller
+ * knows when the reload finished. */
+
+ m->queued_message = dbus_message_new_method_return(message);
+ if (!m->queued_message)
+ goto oom;
+
+ m->queued_message_connection = connection;
+ m->exit_code = MANAGER_RELOAD;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "Reexecute")) {
+
+ SELINUX_ACCESS_CHECK(connection, message, "reload");
+
+ /* We don't send a reply back here, the client should
+ * just wait for us disconnecting. */
+
+ m->exit_code = MANAGER_REEXECUTE;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "Exit")) {
+
+ SELINUX_ACCESS_CHECK(connection, message, "halt");
+
+ if (m->running_as == SYSTEMD_SYSTEM) {
+ dbus_set_error(&error, BUS_ERROR_NOT_SUPPORTED, "Exit is only supported for user service managers.");
+ return bus_send_error_reply(connection, message, &error, -ENOTSUP);
+ }
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ m->exit_code = MANAGER_EXIT;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "Reboot")) {
+
+ SELINUX_ACCESS_CHECK(connection, message, "reboot");
+
+ if (m->running_as != SYSTEMD_SYSTEM) {
+ dbus_set_error(&error, BUS_ERROR_NOT_SUPPORTED, "Reboot is only supported for system managers.");
+ return bus_send_error_reply(connection, message, &error, -ENOTSUP);
+ }
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ m->exit_code = MANAGER_REBOOT;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "PowerOff")) {
+
+ SELINUX_ACCESS_CHECK(connection, message, "halt");
+
+ if (m->running_as != SYSTEMD_SYSTEM) {
+ dbus_set_error(&error, BUS_ERROR_NOT_SUPPORTED, "Powering off is only supported for system managers.");
+ return bus_send_error_reply(connection, message, &error, -ENOTSUP);
+ }
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ m->exit_code = MANAGER_POWEROFF;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "Halt")) {
+
+ SELINUX_ACCESS_CHECK(connection, message, "halt");
+
+ if (m->running_as != SYSTEMD_SYSTEM) {
+ dbus_set_error(&error, BUS_ERROR_NOT_SUPPORTED, "Halting is only supported for system managers.");
+ return bus_send_error_reply(connection, message, &error, -ENOTSUP);
+ }
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ m->exit_code = MANAGER_HALT;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "KExec")) {
+
+ SELINUX_ACCESS_CHECK(connection, message, "reboot");
+
+ if (m->running_as != SYSTEMD_SYSTEM) {
+ dbus_set_error(&error, BUS_ERROR_NOT_SUPPORTED, "kexec is only supported for system managers.");
+ return bus_send_error_reply(connection, message, &error, -ENOTSUP);
+ }
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ m->exit_code = MANAGER_KEXEC;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "SwitchRoot")) {
+ const char *switch_root, *switch_root_init;
+ char *u, *v;
+ bool good;
+
+ SELINUX_ACCESS_CHECK(connection, message, "reboot");
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &switch_root,
+ DBUS_TYPE_STRING, &switch_root_init,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ if (path_equal(switch_root, "/") || !path_is_absolute(switch_root))
+ return bus_send_error_reply(connection, message, NULL, -EINVAL);
+
+ if (!isempty(switch_root_init) && !path_is_absolute(switch_root_init))
+ return bus_send_error_reply(connection, message, NULL, -EINVAL);
+
+ if (m->running_as != SYSTEMD_SYSTEM) {
+ dbus_set_error(&error, BUS_ERROR_NOT_SUPPORTED, "Switching root is only supported for system managers.");
+ return bus_send_error_reply(connection, message, &error, -ENOTSUP);
+ }
+
+ /* Safety check */
+ if (isempty(switch_root_init)) {
+ good = path_is_os_tree(switch_root);
+ if (!good)
+ log_error("Not switching root: %s does not seem to be an OS tree. /etc/os-release is missing.", switch_root);
+ }
+ else {
+ _cleanup_free_ char *p = NULL;
+
+ p = strjoin(switch_root, "/", switch_root_init, NULL);
+ if (!p)
+ goto oom;
+
+ good = access(p, X_OK) >= 0;
+ if (!good)
+ log_error("Not switching root: cannot execute new init %s", p);
+ }
+ if (!good)
+ return bus_send_error_reply(connection, message, NULL, -EINVAL);
+
+ u = strdup(switch_root);
+ if (!u)
+ goto oom;
+
+ if (!isempty(switch_root_init)) {
+ v = strdup(switch_root_init);
+ if (!v) {
+ free(u);
+ goto oom;
+ }
+ } else
+ v = NULL;
+
+ free(m->switch_root);
+ free(m->switch_root_init);
+ m->switch_root = u;
+ m->switch_root_init = v;
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ m->exit_code = MANAGER_SWITCH_ROOT;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "SetEnvironment")) {
+ _cleanup_strv_free_ char **l = NULL;
+ char **e = NULL;
+
+ SELINUX_ACCESS_CHECK(connection, message, "reboot");
+
+ r = bus_parse_strv(message, &l);
+ if (r == -ENOMEM)
+ goto oom;
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+ if (!strv_env_is_valid(l))
+ return bus_send_error_reply(connection, message, NULL, -EINVAL);
+
+ e = strv_env_merge(2, m->environment, l);
+ if (!e)
+ goto oom;
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply) {
+ strv_free(e);
+ goto oom;
+ }
+
+ strv_free(m->environment);
+ m->environment = e;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "UnsetEnvironment")) {
+ _cleanup_strv_free_ char **l = NULL;
+ char **e = NULL;
+
+ SELINUX_ACCESS_CHECK(connection, message, "reboot");
+
+ r = bus_parse_strv(message, &l);
+ if (r == -ENOMEM)
+ goto oom;
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+ if (!strv_env_name_or_assignment_is_valid(l))
+ return bus_send_error_reply(connection, message, NULL, -EINVAL);
+
+ e = strv_env_delete(m->environment, 1, l);
+ if (!e)
+ goto oom;
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply) {
+ strv_free(e);
+ goto oom;
+ }
+
+ strv_free(m->environment);
+ m->environment = e;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "UnsetAndSetEnvironment")) {
+ _cleanup_strv_free_ char **l_set = NULL, **l_unset = NULL, **e = NULL;
+ char **f = NULL;
+ DBusMessageIter iter;
+
+ SELINUX_ACCESS_CHECK(connection, message, "reboot");
+
+ if (!dbus_message_iter_init(message, &iter))
+ goto oom;
+
+ r = bus_parse_strv_iter(&iter, &l_unset);
+ if (r == -ENOMEM)
+ goto oom;
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+ if (!strv_env_name_or_assignment_is_valid(l_unset))
+ return bus_send_error_reply(connection, message, NULL, -EINVAL);
+
+ if (!dbus_message_iter_next(&iter))
+ return bus_send_error_reply(connection, message, NULL, -EINVAL);
+
+ r = bus_parse_strv_iter(&iter, &l_set);
+ if (r == -ENOMEM)
+ goto oom;
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+ if (!strv_env_is_valid(l_set))
+ return bus_send_error_reply(connection, message, NULL, -EINVAL);
+
+ e = strv_env_delete(m->environment, 1, l_unset);
+ if (!e)
+ goto oom;
+
+ f = strv_env_merge(2, e, l_set);
+ if (!f)
+ goto oom;
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply) {
+ strv_free(f);
+ goto oom;
+ }
+
+ strv_free(m->environment);
+ m->environment = f;
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "ListUnitFiles")) {
+ DBusMessageIter iter, sub, sub2;
+ Hashmap *h;
+ Iterator i;
+ UnitFileList *item;
+
+ SELINUX_ACCESS_CHECK(connection, message, "status");
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ h = hashmap_new(string_hash_func, string_compare_func);
+ if (!h)
+ goto oom;
+
+ r = unit_file_get_list(m->running_as == SYSTEMD_SYSTEM ? UNIT_FILE_SYSTEM : UNIT_FILE_USER, NULL, h);
+ if (r < 0) {
+ unit_file_list_free(h);
+ return bus_send_error_reply(connection, message, NULL, r);
+ }
+
+ dbus_message_iter_init_append(reply, &iter);
+
+ if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "(ss)", &sub)) {
+ unit_file_list_free(h);
+ goto oom;
+ }
+
+ HASHMAP_FOREACH(item, h, i) {
+ const char *state;
+
+ state = unit_file_state_to_string(item->state);
+ assert(state);
+
+ if (!dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, NULL, &sub2) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &item->path) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &state) ||
+ !dbus_message_iter_close_container(&sub, &sub2)) {
+ unit_file_list_free(h);
+ goto oom;
+ }
+ }
+
+ unit_file_list_free(h);
+
+ if (!dbus_message_iter_close_container(&iter, &sub))
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "GetUnitFileState")) {
+ const char *name;
+ UnitFileState state;
+ const char *s;
+
+ SELINUX_ACCESS_CHECK(connection, message, "status");
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ state = unit_file_get_state(m->running_as == SYSTEMD_SYSTEM ? UNIT_FILE_SYSTEM : UNIT_FILE_USER, NULL, name);
+ if (state < 0)
+ return bus_send_error_reply(connection, message, NULL, state);
+
+ s = unit_file_state_to_string(state);
+ assert(s);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ if (!dbus_message_append_args(
+ reply,
+ DBUS_TYPE_STRING, &s,
+ DBUS_TYPE_INVALID))
+ goto oom;
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "EnableUnitFiles") ||
+ dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "ReenableUnitFiles") ||
+ dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "LinkUnitFiles") ||
+ dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "PresetUnitFiles") ||
+ dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "MaskUnitFiles")) {
+
+ char **l = NULL;
+ DBusMessageIter iter;
+ UnitFileScope scope = m->running_as == SYSTEMD_SYSTEM ? UNIT_FILE_SYSTEM : UNIT_FILE_USER;
+ UnitFileChange *changes = NULL;
+ unsigned n_changes = 0;
+ dbus_bool_t runtime, force;
+ int carries_install_info = -1;
+
+ SELINUX_ACCESS_CHECK(connection, message, streq(member, "MaskUnitFiles") ? "disable" : "enable");
+
+ if (!dbus_message_iter_init(message, &iter))
+ goto oom;
+
+ r = bus_parse_strv_iter(&iter, &l);
+ if (r < 0) {
+ if (r == -ENOMEM)
+ goto oom;
+
+ return bus_send_error_reply(connection, message, NULL, r);
+ }
+
+ if (!dbus_message_iter_next(&iter) ||
+ bus_iter_get_basic_and_next(&iter, DBUS_TYPE_BOOLEAN, &runtime, true) < 0 ||
+ bus_iter_get_basic_and_next(&iter, DBUS_TYPE_BOOLEAN, &force, false) < 0) {
+ strv_free(l);
+ return bus_send_error_reply(connection, message, NULL, -EIO);
+ }
+
+ if (streq(member, "EnableUnitFiles")) {
+ r = unit_file_enable(scope, runtime, NULL, l, force, &changes, &n_changes);
+ carries_install_info = r;
+ } else if (streq(member, "ReenableUnitFiles")) {
+ r = unit_file_reenable(scope, runtime, NULL, l, force, &changes, &n_changes);
+ carries_install_info = r;
+ } else if (streq(member, "LinkUnitFiles"))
+ r = unit_file_link(scope, runtime, NULL, l, force, &changes, &n_changes);
+ else if (streq(member, "PresetUnitFiles")) {
+ r = unit_file_preset(scope, runtime, NULL, l, force, &changes, &n_changes);
+ carries_install_info = r;
+ } else if (streq(member, "MaskUnitFiles"))
+ r = unit_file_mask(scope, runtime, NULL, l, force, &changes, &n_changes);
+ else
+ assert_not_reached("Uh? Wrong method");
+
+ strv_free(l);
+ bus_manager_send_unit_files_changed(m);
+
+ if (r < 0) {
+ unit_file_changes_free(changes, n_changes);
+ return bus_send_error_reply(connection, message, NULL, r);
+ }
+
+ reply = message_from_file_changes(message, changes, n_changes, carries_install_info);
+ unit_file_changes_free(changes, n_changes);
+
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "DisableUnitFiles") ||
+ dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "UnmaskUnitFiles")) {
+
+ char **l = NULL;
+ DBusMessageIter iter;
+ UnitFileScope scope = m->running_as == SYSTEMD_SYSTEM ? UNIT_FILE_SYSTEM : UNIT_FILE_USER;
+ UnitFileChange *changes = NULL;
+ unsigned n_changes = 0;
+ dbus_bool_t runtime;
+
+ SELINUX_ACCESS_CHECK(connection, message, streq(member, "UnmaskUnitFiles") ? "enable" : "disable");
+
+ if (!dbus_message_iter_init(message, &iter))
+ goto oom;
+
+ r = bus_parse_strv_iter(&iter, &l);
+ if (r < 0) {
+ if (r == -ENOMEM)
+ goto oom;
+
+ return bus_send_error_reply(connection, message, NULL, r);
+ }
+
+ if (!dbus_message_iter_next(&iter) ||
+ bus_iter_get_basic_and_next(&iter, DBUS_TYPE_BOOLEAN, &runtime, false) < 0) {
+ strv_free(l);
+ return bus_send_error_reply(connection, message, NULL, -EIO);
+ }
+
+ if (streq(member, "DisableUnitFiles"))
+ r = unit_file_disable(scope, runtime, NULL, l, &changes, &n_changes);
+ else if (streq(member, "UnmaskUnitFiles"))
+ r = unit_file_unmask(scope, runtime, NULL, l, &changes, &n_changes);
+ else
+ assert_not_reached("Uh? Wrong method");
+
+ strv_free(l);
+ bus_manager_send_unit_files_changed(m);
+
+ if (r < 0) {
+ unit_file_changes_free(changes, n_changes);
+ return bus_send_error_reply(connection, message, NULL, r);
+ }
+
+ reply = message_from_file_changes(message, changes, n_changes, -1);
+ unit_file_changes_free(changes, n_changes);
+
+ if (!reply)
+ goto oom;
+
+ } else {
+ const BusBoundProperties bps[] = {
+ { "org.freedesktop.systemd1.Manager", bus_systemd_properties, systemd_property_string },
+ { "org.freedesktop.systemd1.Manager", bus_manager_properties, m },
+ { NULL, }
+ };
+
+ SELINUX_ACCESS_CHECK(connection, message, "status");
+
+ return bus_default_message_handler(connection, message, NULL, INTERFACES_LIST, bps);
+ }
+
+ if (job_type != _JOB_TYPE_INVALID) {
+ const char *name, *smode, *old_name = NULL;
+ JobMode mode;
+ Unit *u;
+ dbus_bool_t b;
+
+ if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Manager", "StartUnitReplace"))
+ b = dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &old_name,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_STRING, &smode,
+ DBUS_TYPE_INVALID);
+ else
+ b = dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_STRING, &smode,
+ DBUS_TYPE_INVALID);
+ if (!b)
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ if (old_name) {
+ u = manager_get_unit(m, old_name);
+ if (!u || !u->job || u->job->type != JOB_START) {
+ dbus_set_error(&error, BUS_ERROR_NO_SUCH_JOB, "No job queued for unit %s", old_name);
+ return bus_send_error_reply(connection, message, &error, -ENOENT);
+ }
+ }
+
+ mode = job_mode_from_string(smode);
+ if (mode < 0) {
+ dbus_set_error(&error, BUS_ERROR_INVALID_JOB_MODE, "Job mode %s is invalid.", smode);
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+ }
+
+ r = manager_load_unit(m, name, NULL, &error, &u);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ return bus_unit_queue_job(connection, message, u, job_type, mode, reload_if_possible);
+ }
+
+ if (reply)
+ if (!bus_maybe_send_reply(connection, message, reply))
+ goto oom;
+
+ return DBUS_HANDLER_RESULT_HANDLED;
+
+oom:
+ dbus_error_free(&error);
+
+ return DBUS_HANDLER_RESULT_NEED_MEMORY;
+}
+
+const DBusObjectPathVTable bus_manager_vtable = {
+ .message_function = bus_manager_message_handler
+};
diff --git a/src/core/dbus-manager.h b/src/core/dbus-manager.h
new file mode 100644
index 0000000000..f0dce5a2e9
--- /dev/null
+++ b/src/core/dbus-manager.h
@@ -0,0 +1,28 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <dbus/dbus.h>
+
+extern const DBusObjectPathVTable bus_manager_vtable;
+
+extern const char bus_manager_interface[];
diff --git a/src/core/dbus-mount.c b/src/core/dbus-mount.c
new file mode 100644
index 0000000000..0fcceb500d
--- /dev/null
+++ b/src/core/dbus-mount.c
@@ -0,0 +1,170 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+
+#include "dbus-unit.h"
+#include "dbus-mount.h"
+#include "dbus-kill.h"
+#include "dbus-execute.h"
+#include "dbus-common.h"
+#include "selinux-access.h"
+
+#define BUS_MOUNT_INTERFACE \
+ " <interface name=\"org.freedesktop.systemd1.Mount\">\n" \
+ " <property name=\"Where\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"What\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"Options\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"Type\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"TimeoutUSec\" type=\"t\" access=\"read\"/>\n" \
+ BUS_EXEC_COMMAND_INTERFACE("ExecMount") \
+ BUS_EXEC_COMMAND_INTERFACE("ExecUnmount") \
+ BUS_EXEC_COMMAND_INTERFACE("ExecRemount") \
+ BUS_EXEC_CONTEXT_INTERFACE \
+ BUS_KILL_CONTEXT_INTERFACE \
+ BUS_UNIT_CGROUP_INTERFACE \
+ " <property name=\"ControlPID\" type=\"u\" access=\"read\"/>\n" \
+ " <property name=\"DirectoryMode\" type=\"u\" access=\"read\"/>\n" \
+ " <property name=\"Result\" type=\"s\" access=\"read\"/>\n" \
+ " </interface>\n"
+
+#define INTROSPECTION \
+ DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE \
+ "<node>\n" \
+ BUS_UNIT_INTERFACE \
+ BUS_MOUNT_INTERFACE \
+ BUS_PROPERTIES_INTERFACE \
+ BUS_PEER_INTERFACE \
+ BUS_INTROSPECTABLE_INTERFACE \
+ "</node>\n"
+
+#define INTERFACES_LIST \
+ BUS_UNIT_INTERFACES_LIST \
+ "org.freedesktop.systemd1.Mount\0"
+
+const char bus_mount_interface[] _introspect_("Mount") = BUS_MOUNT_INTERFACE;
+
+const char bus_mount_invalidating_properties[] =
+ "What\0"
+ "Options\0"
+ "Type\0"
+ "ExecMount\0"
+ "ExecUnmount\0"
+ "ExecRemount\0"
+ "ControlPID\0"
+ "Result\0";
+
+static int bus_mount_append_what(DBusMessageIter *i, const char *property, void *data) {
+ Mount *m = data;
+ const char *d;
+
+ assert(i);
+ assert(property);
+ assert(m);
+
+ if (m->from_proc_self_mountinfo && m->parameters_proc_self_mountinfo.what)
+ d = m->parameters_proc_self_mountinfo.what;
+ else if (m->from_fragment && m->parameters_fragment.what)
+ d = m->parameters_fragment.what;
+ else
+ d = "";
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_STRING, &d))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_mount_append_options(DBusMessageIter *i, const char *property, void *data) {
+ Mount *m = data;
+ const char *d;
+
+ assert(i);
+ assert(property);
+ assert(m);
+
+ if (m->from_proc_self_mountinfo && m->parameters_proc_self_mountinfo.options)
+ d = m->parameters_proc_self_mountinfo.options;
+ else if (m->from_fragment && m->parameters_fragment.options)
+ d = m->parameters_fragment.options;
+ else
+ d = "";
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_STRING, &d))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_mount_append_type(DBusMessageIter *i, const char *property, void *data) {
+ Mount *m = data;
+ const char *d;
+
+ assert(i);
+ assert(property);
+ assert(m);
+
+ if (m->from_proc_self_mountinfo && m->parameters_proc_self_mountinfo.fstype)
+ d = m->parameters_proc_self_mountinfo.fstype;
+ else if (m->from_fragment && m->parameters_fragment.fstype)
+ d = m->parameters_fragment.fstype;
+ else
+ d = "";
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_STRING, &d))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static DEFINE_BUS_PROPERTY_APPEND_ENUM(bus_mount_append_mount_result, mount_result, MountResult);
+
+static const BusProperty bus_mount_properties[] = {
+ { "Where", bus_property_append_string, "s", offsetof(Mount, where), true },
+ { "What", bus_mount_append_what, "s", 0 },
+ { "Options", bus_mount_append_options, "s", 0 },
+ { "Type", bus_mount_append_type, "s", 0 },
+ { "TimeoutUSec", bus_property_append_usec, "t", offsetof(Mount, timeout_usec) },
+ BUS_EXEC_COMMAND_PROPERTY("ExecMount", offsetof(Mount, exec_command[MOUNT_EXEC_MOUNT]), false),
+ BUS_EXEC_COMMAND_PROPERTY("ExecUnmount", offsetof(Mount, exec_command[MOUNT_EXEC_UNMOUNT]), false),
+ BUS_EXEC_COMMAND_PROPERTY("ExecRemount", offsetof(Mount, exec_command[MOUNT_EXEC_REMOUNT]), false),
+ { "ControlPID", bus_property_append_pid, "u", offsetof(Mount, control_pid) },
+ { "DirectoryMode", bus_property_append_mode, "u", offsetof(Mount, directory_mode) },
+ { "Result", bus_mount_append_mount_result, "s", offsetof(Mount, result) },
+ { NULL, }
+};
+
+DBusHandlerResult bus_mount_message_handler(Unit *u, DBusConnection *c, DBusMessage *message) {
+ Mount *m = MOUNT(u);
+
+ const BusBoundProperties bps[] = {
+ { "org.freedesktop.systemd1.Unit", bus_unit_properties, u },
+ { "org.freedesktop.systemd1.Mount", bus_mount_properties, m },
+ { "org.freedesktop.systemd1.Mount", bus_exec_context_properties, &m->exec_context },
+ { "org.freedesktop.systemd1.Mount", bus_kill_context_properties, &m->kill_context },
+ { "org.freedesktop.systemd1.Mount", bus_unit_cgroup_properties, u },
+ { NULL, }
+ };
+
+ SELINUX_UNIT_ACCESS_CHECK(u, c, message, "status");
+
+ return bus_default_message_handler(c, message, INTROSPECTION, INTERFACES_LIST, bps );
+}
diff --git a/src/core/dbus-mount.h b/src/core/dbus-mount.h
new file mode 100644
index 0000000000..8597394373
--- /dev/null
+++ b/src/core/dbus-mount.h
@@ -0,0 +1,31 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <dbus/dbus.h>
+
+#include "unit.h"
+
+DBusHandlerResult bus_mount_message_handler(Unit *u, DBusConnection *c, DBusMessage *message);
+
+extern const char bus_mount_interface[];
+extern const char bus_mount_invalidating_properties[];
diff --git a/src/core/dbus-path.c b/src/core/dbus-path.c
new file mode 100644
index 0000000000..1e62083d9b
--- /dev/null
+++ b/src/core/dbus-path.c
@@ -0,0 +1,122 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+
+#include "dbus-unit.h"
+#include "dbus-path.h"
+#include "dbus-execute.h"
+#include "dbus-common.h"
+#include "selinux-access.h"
+
+#define BUS_PATH_INTERFACE \
+ " <interface name=\"org.freedesktop.systemd1.Path\">\n" \
+ " <property name=\"Unit\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"Paths\" type=\"a(ss)\" access=\"read\"/>\n" \
+ " <property name=\"MakeDirectory\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"DirectoryMode\" type=\"u\" access=\"read\"/>\n" \
+ " <property name=\"Result\" type=\"s\" access=\"read\"/>\n" \
+ " </interface>\n"
+
+#define INTROSPECTION \
+ DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE \
+ "<node>\n" \
+ BUS_UNIT_INTERFACE \
+ BUS_PATH_INTERFACE \
+ BUS_PROPERTIES_INTERFACE \
+ BUS_PEER_INTERFACE \
+ BUS_INTROSPECTABLE_INTERFACE \
+ "</node>\n"
+
+#define INTERFACES_LIST \
+ BUS_UNIT_INTERFACES_LIST \
+ "org.freedesktop.systemd1.Path\0"
+
+const char bus_path_interface[] _introspect_("Path") = BUS_PATH_INTERFACE;
+
+const char bus_path_invalidating_properties[] =
+ "Result\0";
+
+static int bus_path_append_paths(DBusMessageIter *i, const char *property, void *data) {
+ Path *p = data;
+ DBusMessageIter sub, sub2;
+ PathSpec *k;
+
+ assert(i);
+ assert(property);
+ assert(p);
+
+ if (!dbus_message_iter_open_container(i, DBUS_TYPE_ARRAY, "(ss)", &sub))
+ return -ENOMEM;
+
+ LIST_FOREACH(spec, k, p->specs) {
+ const char *t = path_type_to_string(k->type);
+
+ if (!dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, NULL, &sub2) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &t) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &k->path) ||
+ !dbus_message_iter_close_container(&sub, &sub2))
+ return -ENOMEM;
+ }
+
+ if (!dbus_message_iter_close_container(i, &sub))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_path_append_unit(DBusMessageIter *i, const char *property, void *data) {
+ Unit *u = data, *trigger;
+ const char *t;
+
+ assert(i);
+ assert(property);
+ assert(u);
+
+ trigger = UNIT_TRIGGER(u);
+ t = trigger ? trigger->id : "";
+
+ return dbus_message_iter_append_basic(i, DBUS_TYPE_STRING, &t) ? 0 : -ENOMEM;
+}
+
+static DEFINE_BUS_PROPERTY_APPEND_ENUM(bus_path_append_path_result, path_result, PathResult);
+
+static const BusProperty bus_path_properties[] = {
+ { "Unit", bus_path_append_unit, "s", 0 },
+ { "Paths", bus_path_append_paths, "a(ss)", 0 },
+ { "MakeDirectory", bus_property_append_bool, "b", offsetof(Path, make_directory) },
+ { "DirectoryMode", bus_property_append_mode, "u", offsetof(Path, directory_mode) },
+ { "Result", bus_path_append_path_result, "s", offsetof(Path, result) },
+ { NULL, }
+};
+
+DBusHandlerResult bus_path_message_handler(Unit *u, DBusConnection *c, DBusMessage *message) {
+ Path *p = PATH(u);
+ const BusBoundProperties bps[] = {
+ { "org.freedesktop.systemd1.Unit", bus_unit_properties, u },
+ { "org.freedesktop.systemd1.Path", bus_path_properties, p },
+ { NULL, }
+ };
+
+ SELINUX_UNIT_ACCESS_CHECK(u, c, message, "status");
+
+ return bus_default_message_handler(c, message, INTROSPECTION, INTERFACES_LIST, bps);
+}
diff --git a/src/core/dbus-path.h b/src/core/dbus-path.h
new file mode 100644
index 0000000000..c945f7d588
--- /dev/null
+++ b/src/core/dbus-path.h
@@ -0,0 +1,32 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <dbus/dbus.h>
+
+#include "unit.h"
+
+DBusHandlerResult bus_path_message_handler(Unit *u, DBusConnection *c, DBusMessage *message);
+
+extern const char bus_path_interface[];
+
+extern const char bus_path_invalidating_properties[];
diff --git a/src/core/dbus-service.c b/src/core/dbus-service.c
new file mode 100644
index 0000000000..e06a5dce97
--- /dev/null
+++ b/src/core/dbus-service.c
@@ -0,0 +1,163 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+
+#include "dbus-unit.h"
+#include "dbus-execute.h"
+#include "dbus-kill.h"
+#include "dbus-service.h"
+#include "dbus-common.h"
+#include "selinux-access.h"
+
+#define BUS_SERVICE_INTERFACE \
+ " <interface name=\"org.freedesktop.systemd1.Service\">\n" \
+ " <property name=\"Type\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"Restart\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"PIDFile\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"NotifyAccess\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"RestartUSec\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"TimeoutUSec\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"WatchdogUSec\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"WatchdogTimestamp\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"WatchdogTimestampMonotonic\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"StartLimitInterval\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"StartLimitBurst\" type=\"u\" access=\"read\"/>\n" \
+ " <property name=\"StartLimitAction\" type=\"s\" access=\"readwrite\"/>\n" \
+ BUS_EXEC_COMMAND_INTERFACE("ExecStartPre") \
+ BUS_EXEC_COMMAND_INTERFACE("ExecStart") \
+ BUS_EXEC_COMMAND_INTERFACE("ExecStartPost") \
+ BUS_EXEC_COMMAND_INTERFACE("ExecReload") \
+ BUS_EXEC_COMMAND_INTERFACE("ExecStop") \
+ BUS_EXEC_COMMAND_INTERFACE("ExecStopPost") \
+ BUS_EXEC_CONTEXT_INTERFACE \
+ BUS_KILL_CONTEXT_INTERFACE \
+ BUS_UNIT_CGROUP_INTERFACE \
+ " <property name=\"PermissionsStartOnly\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"RootDirectoryStartOnly\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"RemainAfterExit\" type=\"b\" access=\"read\"/>\n" \
+ BUS_EXEC_STATUS_INTERFACE("ExecMain") \
+ " <property name=\"MainPID\" type=\"u\" access=\"read\"/>\n" \
+ " <property name=\"ControlPID\" type=\"u\" access=\"read\"/>\n" \
+ " <property name=\"BusName\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"StatusText\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"Result\" type=\"s\" access=\"read\"/>\n" \
+ " </interface>\n"
+
+#define INTROSPECTION \
+ DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE \
+ "<node>\n" \
+ BUS_UNIT_INTERFACE \
+ BUS_SERVICE_INTERFACE \
+ BUS_PROPERTIES_INTERFACE \
+ BUS_PEER_INTERFACE \
+ BUS_INTROSPECTABLE_INTERFACE \
+ "</node>\n"
+
+#define INTERFACES_LIST \
+ BUS_UNIT_INTERFACES_LIST \
+ "org.freedesktop.systemd1.Service\0"
+
+const char bus_service_interface[] _introspect_("Service") = BUS_SERVICE_INTERFACE;
+
+const char bus_service_invalidating_properties[] =
+ "ExecStartPre\0"
+ "ExecStart\0"
+ "ExecStartPost\0"
+ "ExecReload\0"
+ "ExecStop\0"
+ "ExecStopPost\0"
+ "ExecMain\0"
+ "WatchdogTimestamp\0"
+ "WatchdogTimestampMonotonic\0"
+ "MainPID\0"
+ "ControlPID\0"
+ "StatusText\0"
+ "Result\0";
+
+static DEFINE_BUS_PROPERTY_APPEND_ENUM(bus_service_append_type, service_type, ServiceType);
+static DEFINE_BUS_PROPERTY_APPEND_ENUM(bus_service_append_restart, service_restart, ServiceRestart);
+static DEFINE_BUS_PROPERTY_APPEND_ENUM(bus_service_append_notify_access, notify_access, NotifyAccess);
+static DEFINE_BUS_PROPERTY_APPEND_ENUM(bus_service_append_service_result, service_result, ServiceResult);
+static DEFINE_BUS_PROPERTY_APPEND_ENUM(bus_service_append_start_limit_action, start_limit_action, StartLimitAction);
+static DEFINE_BUS_PROPERTY_SET_ENUM(bus_service_set_start_limit_action, start_limit_action, StartLimitAction);
+
+static const BusProperty bus_exec_main_status_properties[] = {
+ { "ExecMainStartTimestamp", bus_property_append_usec, "t", offsetof(ExecStatus, start_timestamp.realtime) },
+ { "ExecMainStartTimestampMonotonic",bus_property_append_usec, "t", offsetof(ExecStatus, start_timestamp.monotonic) },
+ { "ExecMainExitTimestamp", bus_property_append_usec, "t", offsetof(ExecStatus, start_timestamp.realtime) },
+ { "ExecMainExitTimestampMonotonic", bus_property_append_usec, "t", offsetof(ExecStatus, start_timestamp.monotonic) },
+ { "ExecMainPID", bus_property_append_pid, "u", offsetof(ExecStatus, pid) },
+ { "ExecMainCode", bus_property_append_int, "i", offsetof(ExecStatus, code) },
+ { "ExecMainStatus", bus_property_append_int, "i", offsetof(ExecStatus, status) },
+ { NULL, }
+};
+
+static const BusProperty bus_service_properties[] = {
+ { "Type", bus_service_append_type, "s", offsetof(Service, type) },
+ { "Restart", bus_service_append_restart, "s", offsetof(Service, restart) },
+ { "PIDFile", bus_property_append_string, "s", offsetof(Service, pid_file), true },
+ { "NotifyAccess", bus_service_append_notify_access, "s", offsetof(Service, notify_access) },
+ { "RestartUSec", bus_property_append_usec, "t", offsetof(Service, restart_usec) },
+ { "TimeoutUSec", bus_property_append_usec, "t", offsetof(Service, timeout_start_usec) },
+ { "TimeoutStartUSec", bus_property_append_usec, "t", offsetof(Service, timeout_start_usec) },
+ { "TimeoutStopUSec", bus_property_append_usec, "t", offsetof(Service, timeout_stop_usec) },
+ { "WatchdogUSec", bus_property_append_usec, "t", offsetof(Service, watchdog_usec) },
+ { "WatchdogTimestamp", bus_property_append_usec, "t", offsetof(Service, watchdog_timestamp.realtime) },
+ { "WatchdogTimestampMonotonic",bus_property_append_usec, "t", offsetof(Service, watchdog_timestamp.monotonic) },
+ { "StartLimitInterval", bus_property_append_usec, "t", offsetof(Service, start_limit.interval) },
+ { "StartLimitBurst", bus_property_append_uint32, "u", offsetof(Service, start_limit.burst) },
+ { "StartLimitAction", bus_service_append_start_limit_action,"s", offsetof(Service, start_limit_action), false, bus_service_set_start_limit_action},
+ BUS_EXEC_COMMAND_PROPERTY("ExecStartPre", offsetof(Service, exec_command[SERVICE_EXEC_START_PRE]), true ),
+ BUS_EXEC_COMMAND_PROPERTY("ExecStart", offsetof(Service, exec_command[SERVICE_EXEC_START]), true ),
+ BUS_EXEC_COMMAND_PROPERTY("ExecStartPost", offsetof(Service, exec_command[SERVICE_EXEC_START_POST]), true ),
+ BUS_EXEC_COMMAND_PROPERTY("ExecReload", offsetof(Service, exec_command[SERVICE_EXEC_RELOAD]), true ),
+ BUS_EXEC_COMMAND_PROPERTY("ExecStop", offsetof(Service, exec_command[SERVICE_EXEC_STOP]), true ),
+ BUS_EXEC_COMMAND_PROPERTY("ExecStopPost", offsetof(Service, exec_command[SERVICE_EXEC_STOP_POST]), true ),
+ { "PermissionsStartOnly", bus_property_append_bool, "b", offsetof(Service, permissions_start_only) },
+ { "RootDirectoryStartOnly", bus_property_append_bool, "b", offsetof(Service, root_directory_start_only) },
+ { "RemainAfterExit", bus_property_append_bool, "b", offsetof(Service, remain_after_exit) },
+ { "GuessMainPID", bus_property_append_bool, "b", offsetof(Service, guess_main_pid) },
+ { "MainPID", bus_property_append_pid, "u", offsetof(Service, main_pid) },
+ { "ControlPID", bus_property_append_pid, "u", offsetof(Service, control_pid) },
+ { "BusName", bus_property_append_string, "s", offsetof(Service, bus_name), true },
+ { "StatusText", bus_property_append_string, "s", offsetof(Service, status_text), true },
+ { "Result", bus_service_append_service_result,"s", offsetof(Service, result) },
+ { NULL, }
+};
+
+DBusHandlerResult bus_service_message_handler(Unit *u, DBusConnection *connection, DBusMessage *message) {
+ Service *s = SERVICE(u);
+
+ const BusBoundProperties bps[] = {
+ { "org.freedesktop.systemd1.Unit", bus_unit_properties, u },
+ { "org.freedesktop.systemd1.Service", bus_service_properties, s },
+ { "org.freedesktop.systemd1.Service", bus_exec_context_properties, &s->exec_context },
+ { "org.freedesktop.systemd1.Service", bus_kill_context_properties, &s->kill_context },
+ { "org.freedesktop.systemd1.Service", bus_exec_main_status_properties, &s->main_exec_status },
+ { "org.freedesktop.systemd1.Service", bus_unit_cgroup_properties, u },
+ { NULL, }
+ };
+
+ SELINUX_UNIT_ACCESS_CHECK(u, connection, message, "status");
+
+ return bus_default_message_handler(connection, message, INTROSPECTION, INTERFACES_LIST, bps);
+}
diff --git a/src/core/dbus-service.h b/src/core/dbus-service.h
new file mode 100644
index 0000000000..143aed7ae5
--- /dev/null
+++ b/src/core/dbus-service.h
@@ -0,0 +1,31 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <dbus/dbus.h>
+
+#include "unit.h"
+
+DBusHandlerResult bus_service_message_handler(Unit *u, DBusConnection *c, DBusMessage *message);
+
+extern const char bus_service_interface[];
+extern const char bus_service_invalidating_properties[];
diff --git a/src/core/dbus-snapshot.c b/src/core/dbus-snapshot.c
new file mode 100644
index 0000000000..2ae8574f59
--- /dev/null
+++ b/src/core/dbus-snapshot.c
@@ -0,0 +1,84 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "dbus-unit.h"
+#include "dbus-snapshot.h"
+#include "dbus-common.h"
+#include "selinux-access.h"
+
+#define BUS_SNAPSHOT_INTERFACE \
+ " <interface name=\"org.freedesktop.systemd1.Snapshot\">\n" \
+ " <method name=\"Remove\"/>\n" \
+ " <property name=\"Cleanup\" type=\"b\" access=\"read\"/>\n" \
+ " </interface>\n"
+
+#define INTROSPECTION \
+ DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE \
+ "<node>\n" \
+ BUS_UNIT_INTERFACE \
+ BUS_SNAPSHOT_INTERFACE \
+ BUS_PROPERTIES_INTERFACE \
+ BUS_PEER_INTERFACE \
+ BUS_INTROSPECTABLE_INTERFACE \
+ "</node>\n"
+
+#define INTERFACES_LIST \
+ BUS_UNIT_INTERFACES_LIST \
+ "org.freedesktop.systemd1.Snapshot\0"
+
+const char bus_snapshot_interface[] _introspect_("Snapshot") = BUS_SNAPSHOT_INTERFACE;
+
+static const BusProperty bus_snapshot_properties[] = {
+ { "Cleanup", bus_property_append_bool, "b", offsetof(Snapshot, cleanup) },
+ { NULL, }
+};
+
+DBusHandlerResult bus_snapshot_message_handler(Unit *u, DBusConnection *c, DBusMessage *message) {
+ Snapshot *s = SNAPSHOT(u);
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+
+ if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Snapshot", "Remove")) {
+
+ SELINUX_UNIT_ACCESS_CHECK(u, c, message, "stop");
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ return DBUS_HANDLER_RESULT_NEED_MEMORY;
+
+ snapshot_remove(SNAPSHOT(u));
+
+ } else {
+ const BusBoundProperties bps[] = {
+ { "org.freedesktop.systemd1.Unit", bus_unit_properties, u },
+ { "org.freedesktop.systemd1.Snapshot", bus_snapshot_properties, s },
+ { NULL, }
+ };
+
+ SELINUX_UNIT_ACCESS_CHECK(u, c, message, "status");
+
+ return bus_default_message_handler(c, message, INTROSPECTION, INTERFACES_LIST, bps);
+ }
+
+ if (!bus_maybe_send_reply(c, message, reply))
+ return DBUS_HANDLER_RESULT_NEED_MEMORY;
+
+ return DBUS_HANDLER_RESULT_HANDLED;
+}
diff --git a/src/core/dbus-snapshot.h b/src/core/dbus-snapshot.h
new file mode 100644
index 0000000000..1208aafff6
--- /dev/null
+++ b/src/core/dbus-snapshot.h
@@ -0,0 +1,30 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <dbus/dbus.h>
+
+#include "unit.h"
+
+DBusHandlerResult bus_snapshot_message_handler(Unit *u, DBusConnection *c, DBusMessage *message);
+
+extern const char bus_snapshot_interface[];
diff --git a/src/core/dbus-socket.c b/src/core/dbus-socket.c
new file mode 100644
index 0000000000..77d98ea0fd
--- /dev/null
+++ b/src/core/dbus-socket.c
@@ -0,0 +1,215 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+
+#include "dbus-unit.h"
+#include "dbus-socket.h"
+#include "dbus-execute.h"
+#include "dbus-kill.h"
+#include "dbus-common.h"
+#include "selinux-access.h"
+
+#define BUS_SOCKET_INTERFACE \
+ " <interface name=\"org.freedesktop.systemd1.Socket\">\n" \
+ " <property name=\"BindIPv6Only\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"Backlog\" type=\"u\" access=\"read\"/>\n" \
+ " <property name=\"TimeoutUSec\" type=\"t\" access=\"read\"/>\n" \
+ BUS_EXEC_COMMAND_INTERFACE("ExecStartPre") \
+ BUS_EXEC_COMMAND_INTERFACE("ExecStartPost") \
+ BUS_EXEC_COMMAND_INTERFACE("ExecStopPre") \
+ BUS_EXEC_COMMAND_INTERFACE("ExecStopPost") \
+ BUS_EXEC_CONTEXT_INTERFACE \
+ BUS_KILL_CONTEXT_INTERFACE \
+ BUS_UNIT_CGROUP_INTERFACE \
+ " <property name=\"ControlPID\" type=\"u\" access=\"read\"/>\n" \
+ " <property name=\"BindToDevice\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"DirectoryMode\" type=\"u\" access=\"read\"/>\n" \
+ " <property name=\"SocketMode\" type=\"u\" access=\"read\"/>\n" \
+ " <property name=\"Accept\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"KeepAlive\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"Priority\" type=\"i\" access=\"read\"/>\n" \
+ " <property name=\"ReceiveBuffer\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"SendBuffer\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"IPTOS\" type=\"i\" access=\"read\"/>\n" \
+ " <property name=\"IPTTL\" type=\"i\" access=\"read\"/>\n" \
+ " <property name=\"PipeSize\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"FreeBind\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"Transparent\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"Broadcast\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"PassCredentials\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"PassSecurity\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"Mark\" type=\"i\" access=\"read\"/>\n" \
+ " <property name=\"MaxConnections\" type=\"u\" access=\"read\"/>\n" \
+ " <property name=\"NAccepted\" type=\"u\" access=\"read\"/>\n" \
+ " <property name=\"NConnections\" type=\"u\" access=\"read\"/>\n" \
+ " <property name=\"MessageQueueMaxMessages\" type=\"x\" access=\"read\"/>\n" \
+ " <property name=\"MessageQueueMessageSize\" type=\"x\" access=\"read\"/>\n" \
+ " <property name=\"Listen\" type=\"a(ss)\" access=\"read\"/>\n" \
+ " <property name=\"Result\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"SmackLabel\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"SmackLabelIPIn\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"SmackLabelIPOut\" type=\"s\" access=\"read\"/>\n" \
+ " </interface>\n" \
+
+#define INTROSPECTION \
+ DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE \
+ "<node>\n" \
+ BUS_UNIT_INTERFACE \
+ BUS_SOCKET_INTERFACE \
+ BUS_PROPERTIES_INTERFACE \
+ BUS_PEER_INTERFACE \
+ BUS_INTROSPECTABLE_INTERFACE \
+ "</node>\n"
+
+#define INTERFACES_LIST \
+ BUS_UNIT_INTERFACES_LIST \
+ "org.freedesktop.systemd1.Socket\0"
+
+const char bus_socket_interface[] _introspect_("Socket") = BUS_SOCKET_INTERFACE;
+
+const char bus_socket_invalidating_properties[] =
+ "ExecStartPre\0"
+ "ExecStartPost\0"
+ "ExecStopPre\0"
+ "ExecStopPost\0"
+ "ControlPID\0"
+ "NAccepted\0"
+ "NConnections\0"
+ "Result\0";
+
+static DEFINE_BUS_PROPERTY_APPEND_ENUM(bus_socket_append_bind_ipv6_only, socket_address_bind_ipv6_only, SocketAddressBindIPv6Only);
+static DEFINE_BUS_PROPERTY_APPEND_ENUM(bus_socket_append_socket_result, socket_result, SocketResult);
+
+static int bus_socket_append_listen(DBusMessageIter *i, const char *property, void *data) {
+
+ Socket *s = SOCKET(data);
+ SocketPort *p;
+ DBusMessageIter array, stru;
+
+ assert(data);
+ assert(property);
+ assert(s);
+
+ if (!dbus_message_iter_open_container(i, DBUS_TYPE_ARRAY, "(ss)", &array))
+ return log_oom();
+
+ LIST_FOREACH(port, p, s->ports) {
+ const char *type = socket_port_type_to_string(p);
+ _cleanup_free_ char *address = NULL;
+ const char *a;
+
+ if (!dbus_message_iter_open_container(&array, DBUS_TYPE_STRUCT, NULL, &stru))
+ return log_oom();
+
+ if (!dbus_message_iter_append_basic(&stru, DBUS_TYPE_STRING, &type))
+ return log_oom();
+
+ switch (p->type) {
+ case SOCKET_SOCKET: {
+ int r;
+
+ r = socket_address_print(&p->address, &address);
+ if (r) {
+ log_error("socket_address_print failed: %s", strerror(-r));
+ return r;
+ }
+ a = address;
+ break;
+ }
+
+ case SOCKET_SPECIAL:
+ case SOCKET_MQUEUE:
+ case SOCKET_FIFO:
+ a = p->path;
+ break;
+
+ default:
+ a = type;
+ }
+
+ if (!dbus_message_iter_append_basic(&stru, DBUS_TYPE_STRING, &a))
+ return -ENOMEM;
+
+ if (!dbus_message_iter_close_container(&array, &stru))
+ return -ENOMEM;
+ }
+
+ if (!dbus_message_iter_close_container(i, &array))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static const BusProperty bus_socket_properties[] = {
+ { "BindIPv6Only", bus_socket_append_bind_ipv6_only, "s", offsetof(Socket, bind_ipv6_only) },
+ { "Backlog", bus_property_append_unsigned, "u", offsetof(Socket, backlog) },
+ { "TimeoutUSec", bus_property_append_usec, "t", offsetof(Socket, timeout_usec) },
+ BUS_EXEC_COMMAND_PROPERTY("ExecStartPre", offsetof(Socket, exec_command[SOCKET_EXEC_START_PRE]), true ),
+ BUS_EXEC_COMMAND_PROPERTY("ExecStartPost", offsetof(Socket, exec_command[SOCKET_EXEC_START_POST]), true ),
+ BUS_EXEC_COMMAND_PROPERTY("ExecStopPre", offsetof(Socket, exec_command[SOCKET_EXEC_STOP_PRE]), true ),
+ BUS_EXEC_COMMAND_PROPERTY("ExecStopPost", offsetof(Socket, exec_command[SOCKET_EXEC_STOP_POST]), true ),
+ { "ControlPID", bus_property_append_pid, "u", offsetof(Socket, control_pid) },
+ { "BindToDevice", bus_property_append_string, "s", offsetof(Socket, bind_to_device), true },
+ { "DirectoryMode", bus_property_append_mode, "u", offsetof(Socket, directory_mode) },
+ { "SocketMode", bus_property_append_mode, "u", offsetof(Socket, socket_mode) },
+ { "Accept", bus_property_append_bool, "b", offsetof(Socket, accept) },
+ { "KeepAlive", bus_property_append_bool, "b", offsetof(Socket, keep_alive) },
+ { "Priority", bus_property_append_int, "i", offsetof(Socket, priority) },
+ { "ReceiveBuffer", bus_property_append_size, "t", offsetof(Socket, receive_buffer) },
+ { "SendBuffer", bus_property_append_size, "t", offsetof(Socket, send_buffer) },
+ { "IPTOS", bus_property_append_int, "i", offsetof(Socket, ip_tos) },
+ { "IPTTL", bus_property_append_int, "i", offsetof(Socket, ip_ttl) },
+ { "PipeSize", bus_property_append_size, "t", offsetof(Socket, pipe_size) },
+ { "FreeBind", bus_property_append_bool, "b", offsetof(Socket, free_bind) },
+ { "Transparent", bus_property_append_bool, "b", offsetof(Socket, transparent) },
+ { "Broadcast", bus_property_append_bool, "b", offsetof(Socket, broadcast) },
+ { "PassCredentials",bus_property_append_bool, "b", offsetof(Socket, pass_cred) },
+ { "PassSecurity", bus_property_append_bool, "b", offsetof(Socket, pass_sec) },
+ { "Listen", bus_socket_append_listen, "a(ss)", 0, },
+ { "Mark", bus_property_append_int, "i", offsetof(Socket, mark) },
+ { "MaxConnections", bus_property_append_unsigned, "u", offsetof(Socket, max_connections) },
+ { "NConnections", bus_property_append_unsigned, "u", offsetof(Socket, n_connections) },
+ { "NAccepted", bus_property_append_unsigned, "u", offsetof(Socket, n_accepted) },
+ { "MessageQueueMaxMessages", bus_property_append_long, "x", offsetof(Socket, mq_maxmsg) },
+ { "MessageQueueMessageSize", bus_property_append_long, "x", offsetof(Socket, mq_msgsize) },
+ { "Result", bus_socket_append_socket_result, "s", offsetof(Socket, result) },
+ { "SmackLabel", bus_property_append_string, "s", offsetof(Socket, smack), true },
+ { "SmackLabelIPIn", bus_property_append_string, "s", offsetof(Socket, smack_ip_in), true },
+ { "SmackLabelIPOut",bus_property_append_string, "s", offsetof(Socket, smack_ip_out), true },
+ { NULL, }
+};
+
+DBusHandlerResult bus_socket_message_handler(Unit *u, DBusConnection *c, DBusMessage *message) {
+ Socket *s = SOCKET(u);
+ const BusBoundProperties bps[] = {
+ { "org.freedesktop.systemd1.Unit", bus_unit_properties, u },
+ { "org.freedesktop.systemd1.Socket", bus_socket_properties, s },
+ { "org.freedesktop.systemd1.Socket", bus_exec_context_properties, &s->exec_context },
+ { "org.freedesktop.systemd1.Socket", bus_kill_context_properties, &s->kill_context },
+ { "org.freedesktop.systemd1.Socket", bus_unit_properties, u },
+ { NULL, }
+ };
+
+ SELINUX_UNIT_ACCESS_CHECK(u, c, message, "status");
+
+ return bus_default_message_handler(c, message, INTROSPECTION, INTERFACES_LIST, bps);
+}
diff --git a/src/core/dbus-socket.h b/src/core/dbus-socket.h
new file mode 100644
index 0000000000..5369b22e5e
--- /dev/null
+++ b/src/core/dbus-socket.h
@@ -0,0 +1,31 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <dbus/dbus.h>
+
+#include "unit.h"
+
+DBusHandlerResult bus_socket_message_handler(Unit *u, DBusConnection *c, DBusMessage *message);
+
+extern const char bus_socket_interface[];
+extern const char bus_socket_invalidating_properties[];
diff --git a/src/core/dbus-swap.c b/src/core/dbus-swap.c
new file mode 100644
index 0000000000..2e99fba7db
--- /dev/null
+++ b/src/core/dbus-swap.c
@@ -0,0 +1,117 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+ Copyright 2010 Maarten Lankhorst
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+
+#include "dbus-unit.h"
+#include "dbus-swap.h"
+#include "dbus-execute.h"
+#include "dbus-kill.h"
+#include "dbus-common.h"
+#include "selinux-access.h"
+
+#define BUS_SWAP_INTERFACE \
+ " <interface name=\"org.freedesktop.systemd1.Swap\">\n" \
+ " <property name=\"What\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"Priority\" type=\"i\" access=\"read\"/>\n" \
+ " <property name=\"TimeoutUSec\" type=\"t\" access=\"read\"/>\n" \
+ BUS_EXEC_COMMAND_INTERFACE("ExecActivate") \
+ BUS_EXEC_COMMAND_INTERFACE("ExecDeactivate") \
+ BUS_EXEC_CONTEXT_INTERFACE \
+ BUS_KILL_CONTEXT_INTERFACE \
+ BUS_UNIT_CGROUP_INTERFACE \
+ " <property name=\"ControlPID\" type=\"u\" access=\"read\"/>\n" \
+ " <property name=\"Result\" type=\"s\" access=\"read\"/>\n" \
+ " </interface>\n"
+
+#define INTROSPECTION \
+ DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE \
+ "<node>\n" \
+ BUS_UNIT_INTERFACE \
+ BUS_SWAP_INTERFACE \
+ BUS_PROPERTIES_INTERFACE \
+ BUS_PEER_INTERFACE \
+ BUS_INTROSPECTABLE_INTERFACE \
+ "</node>\n"
+
+#define INTERFACES_LIST \
+ BUS_UNIT_INTERFACES_LIST \
+ "org.freedesktop.systemd1.Swap\0"
+
+const char bus_swap_interface[] _introspect_("Swap") = BUS_SWAP_INTERFACE;
+
+const char bus_swap_invalidating_properties[] =
+ "What\0"
+ "Priority\0"
+ "ExecActivate\0"
+ "ExecDeactivate\0"
+ "ControlPID\0"
+ "Result\0";
+
+static int bus_swap_append_priority(DBusMessageIter *i, const char *property, void *data) {
+ Swap *s = data;
+ dbus_int32_t j;
+
+ assert(i);
+ assert(property);
+ assert(s);
+
+ if (s->from_proc_swaps)
+ j = s->parameters_proc_swaps.priority;
+ else if (s->from_fragment)
+ j = s->parameters_fragment.priority;
+ else
+ j = -1;
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_INT32, &j))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static DEFINE_BUS_PROPERTY_APPEND_ENUM(bus_swap_append_swap_result, swap_result, SwapResult);
+
+static const BusProperty bus_swap_properties[] = {
+ { "What", bus_property_append_string, "s", offsetof(Swap, what), true },
+ { "Priority", bus_swap_append_priority, "i", 0 },
+ BUS_EXEC_COMMAND_PROPERTY("ExecActivate", offsetof(Swap, exec_command[SWAP_EXEC_ACTIVATE]), false),
+ BUS_EXEC_COMMAND_PROPERTY("ExecDeactivate", offsetof(Swap, exec_command[SWAP_EXEC_DEACTIVATE]), false),
+ { "ControlPID", bus_property_append_pid, "u", offsetof(Swap, control_pid) },
+ { "Result", bus_swap_append_swap_result,"s", offsetof(Swap, result) },
+ { NULL, }
+};
+
+DBusHandlerResult bus_swap_message_handler(Unit *u, DBusConnection *c, DBusMessage *message) {
+ Swap *s = SWAP(u);
+ const BusBoundProperties bps[] = {
+ { "org.freedesktop.systemd1.Unit", bus_unit_properties, u },
+ { "org.freedesktop.systemd1.Swap", bus_swap_properties, s },
+ { "org.freedesktop.systemd1.Swap", bus_exec_context_properties, &s->exec_context },
+ { "org.freedesktop.systemd1.Swap", bus_kill_context_properties, &s->kill_context },
+ { "org.freedesktop.systemd1.Swap", bus_unit_cgroup_properties, u },
+ { NULL, }
+ };
+
+ SELINUX_UNIT_ACCESS_CHECK(u, c, message, "status");
+
+ return bus_default_message_handler(c, message, INTROSPECTION, INTERFACES_LIST, bps);
+}
diff --git a/src/core/dbus-swap.h b/src/core/dbus-swap.h
new file mode 100644
index 0000000000..41fe4447ff
--- /dev/null
+++ b/src/core/dbus-swap.h
@@ -0,0 +1,32 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+ Copyright 2010 Maarten Lankhorst
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <dbus/dbus.h>
+
+#include "unit.h"
+
+DBusHandlerResult bus_swap_message_handler(Unit *u, DBusConnection *c, DBusMessage *message);
+
+extern const char bus_swap_interface[];
+extern const char bus_swap_invalidating_properties[];
diff --git a/src/core/dbus-target.c b/src/core/dbus-target.c
new file mode 100644
index 0000000000..6a775506cc
--- /dev/null
+++ b/src/core/dbus-target.c
@@ -0,0 +1,58 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+
+#include "dbus-unit.h"
+#include "dbus-target.h"
+#include "dbus-common.h"
+#include "selinux-access.h"
+
+#define BUS_TARGET_INTERFACE \
+ " <interface name=\"org.freedesktop.systemd1.Target\">\n" \
+ " </interface>\n"
+
+#define INTROSPECTION \
+ DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE \
+ "<node>\n" \
+ BUS_UNIT_INTERFACE \
+ BUS_TARGET_INTERFACE \
+ BUS_PROPERTIES_INTERFACE \
+ BUS_PEER_INTERFACE \
+ BUS_INTROSPECTABLE_INTERFACE \
+ "</node>\n"
+
+#define INTERFACES_LIST \
+ BUS_UNIT_INTERFACES_LIST \
+ "org.freedesktop.systemd1.Target\0"
+
+const char bus_target_interface[] _introspect_("Target") = BUS_TARGET_INTERFACE;
+
+DBusHandlerResult bus_target_message_handler(Unit *u, DBusConnection *c, DBusMessage *message) {
+ const BusBoundProperties bps[] = {
+ { "org.freedesktop.systemd1.Unit", bus_unit_properties, u },
+ { NULL, }
+ };
+
+ SELINUX_UNIT_ACCESS_CHECK(u, c, message, "status");
+
+ return bus_default_message_handler(c, message, INTROSPECTION, INTERFACES_LIST, bps);
+}
diff --git a/src/core/dbus-target.h b/src/core/dbus-target.h
new file mode 100644
index 0000000000..a8a0304c75
--- /dev/null
+++ b/src/core/dbus-target.h
@@ -0,0 +1,30 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <dbus/dbus.h>
+
+#include "unit.h"
+
+DBusHandlerResult bus_target_message_handler(Unit *u, DBusConnection *c, DBusMessage *message);
+
+extern const char bus_target_interface[];
diff --git a/src/core/dbus-timer.c b/src/core/dbus-timer.c
new file mode 100644
index 0000000000..4082f7f9b9
--- /dev/null
+++ b/src/core/dbus-timer.c
@@ -0,0 +1,191 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+
+#include "dbus-unit.h"
+#include "dbus-timer.h"
+#include "dbus-execute.h"
+#include "dbus-common.h"
+#include "selinux-access.h"
+
+#define BUS_TIMER_INTERFACE \
+ " <interface name=\"org.freedesktop.systemd1.Timer\">\n" \
+ " <property name=\"Unit\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"TimersMonotonic\" type=\"a(stt)\" access=\"read\"/>\n" \
+ " <property name=\"TimersCalendar\" type=\"a(sst)\" access=\"read\"/>\n" \
+ " <property name=\"NextElapseUSecRealtime\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"NextElapseUSecMonotonic\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"Result\" type=\"s\" access=\"read\"/>\n" \
+ " </interface>\n"
+
+#define INTROSPECTION \
+ DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE \
+ "<node>\n" \
+ BUS_UNIT_INTERFACE \
+ BUS_TIMER_INTERFACE \
+ BUS_PROPERTIES_INTERFACE \
+ BUS_PEER_INTERFACE \
+ BUS_INTROSPECTABLE_INTERFACE \
+ "</node>\n"
+
+#define INTERFACES_LIST \
+ BUS_UNIT_INTERFACES_LIST \
+ "org.freedesktop.systemd1.Timer\0"
+
+const char bus_timer_interface[] _introspect_("Timer") = BUS_TIMER_INTERFACE;
+
+const char bus_timer_invalidating_properties[] =
+ "TimersMonotonic\0"
+ "TimersRealtime\0"
+ "NextElapseUSecRealtime\0"
+ "NextElapseUSecMonotonic\0"
+ "Result\0";
+
+static int bus_timer_append_monotonic_timers(DBusMessageIter *i, const char *property, void *data) {
+ Timer *p = data;
+ DBusMessageIter sub, sub2;
+ TimerValue *k;
+
+ assert(i);
+ assert(property);
+ assert(p);
+
+ if (!dbus_message_iter_open_container(i, DBUS_TYPE_ARRAY, "(stt)", &sub))
+ return -ENOMEM;
+
+ LIST_FOREACH(value, k, p->values) {
+ _cleanup_free_ char *buf = NULL;
+ const char *t;
+ size_t l;
+ bool b;
+
+ if (k->base == TIMER_CALENDAR)
+ continue;
+
+ t = timer_base_to_string(k->base);
+ assert(endswith(t, "Sec"));
+
+ /* s/Sec/USec/ */
+ l = strlen(t);
+ buf = new(char, l+2);
+ if (!buf)
+ return -ENOMEM;
+
+ memcpy(buf, t, l-3);
+ memcpy(buf+l-3, "USec", 5);
+
+ b = dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, NULL, &sub2) &&
+ dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &buf) &&
+ dbus_message_iter_append_basic(&sub2, DBUS_TYPE_UINT64, &k->value) &&
+ dbus_message_iter_append_basic(&sub2, DBUS_TYPE_UINT64, &k->next_elapse) &&
+ dbus_message_iter_close_container(&sub, &sub2);
+
+ if (!b)
+ return -ENOMEM;
+ }
+
+ if (!dbus_message_iter_close_container(i, &sub))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_timer_append_calendar_timers(DBusMessageIter *i, const char *property, void *data) {
+ Timer *p = data;
+ DBusMessageIter sub, sub2;
+ TimerValue *k;
+
+ assert(i);
+ assert(property);
+ assert(p);
+
+ if (!dbus_message_iter_open_container(i, DBUS_TYPE_ARRAY, "(sst)", &sub))
+ return -ENOMEM;
+
+ LIST_FOREACH(value, k, p->values) {
+ _cleanup_free_ char *buf = NULL;
+ const char *t;
+ bool b;
+ int j;
+
+ if (k->base != TIMER_CALENDAR)
+ continue;
+
+ t = timer_base_to_string(k->base);
+ j = calendar_spec_to_string(k->calendar_spec, &buf);
+ if (j < 0)
+ return j;
+
+ b = dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, NULL, &sub2) &&
+ dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &t) &&
+ dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &buf) &&
+ dbus_message_iter_append_basic(&sub2, DBUS_TYPE_UINT64, &k->next_elapse) &&
+ dbus_message_iter_close_container(&sub, &sub2);
+
+ if (!b)
+ return -ENOMEM;
+ }
+
+ if (!dbus_message_iter_close_container(i, &sub))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_timer_append_unit(DBusMessageIter *i, const char *property, void *data) {
+ Unit *u = data, *trigger;
+ const char *t;
+
+ assert(i);
+ assert(property);
+ assert(u);
+
+ trigger = UNIT_TRIGGER(u);
+ t = trigger ? trigger->id : "";
+
+ return dbus_message_iter_append_basic(i, DBUS_TYPE_STRING, &t) ? 0 : -ENOMEM;
+}
+
+static DEFINE_BUS_PROPERTY_APPEND_ENUM(bus_timer_append_timer_result, timer_result, TimerResult);
+
+static const BusProperty bus_timer_properties[] = {
+ { "Unit", bus_timer_append_unit, "s", 0 },
+ { "TimersMonotonic", bus_timer_append_monotonic_timers, "a(stt)", 0 },
+ { "TimersCalendar", bus_timer_append_calendar_timers, "a(sst)", 0 },
+ { "NextElapseUSecMonotonic", bus_property_append_usec, "t", offsetof(Timer, next_elapse_monotonic) },
+ { "NextElapseUSecRealtime", bus_property_append_usec, "t", offsetof(Timer, next_elapse_realtime) },
+ { "Result", bus_timer_append_timer_result, "s", offsetof(Timer, result) },
+ { NULL, }
+};
+
+DBusHandlerResult bus_timer_message_handler(Unit *u, DBusConnection *c, DBusMessage *message) {
+ Timer *t = TIMER(u);
+ const BusBoundProperties bps[] = {
+ { "org.freedesktop.systemd1.Unit", bus_unit_properties, u },
+ { "org.freedesktop.systemd1.Timer", bus_timer_properties, t },
+ { NULL, }
+ };
+
+ SELINUX_UNIT_ACCESS_CHECK(u, c, message, "status");
+
+ return bus_default_message_handler(c, message, INTROSPECTION, INTERFACES_LIST, bps);
+}
diff --git a/src/core/dbus-timer.h b/src/core/dbus-timer.h
new file mode 100644
index 0000000000..9ac30501d1
--- /dev/null
+++ b/src/core/dbus-timer.h
@@ -0,0 +1,31 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <dbus/dbus.h>
+
+#include "unit.h"
+
+DBusHandlerResult bus_timer_message_handler(Unit *u, DBusConnection *c, DBusMessage *message);
+
+extern const char bus_timer_interface[];
+extern const char bus_timer_invalidating_properties[];
diff --git a/src/core/dbus-unit.c b/src/core/dbus-unit.c
new file mode 100644
index 0000000000..575f8eb36a
--- /dev/null
+++ b/src/core/dbus-unit.c
@@ -0,0 +1,1324 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+
+#include "dbus.h"
+#include "log.h"
+#include "dbus-unit.h"
+#include "bus-errors.h"
+#include "dbus-common.h"
+#include "selinux-access.h"
+#include "cgroup-util.h"
+#include "strv.h"
+#include "path-util.h"
+#include "fileio.h"
+
+const char bus_unit_interface[] _introspect_("Unit") = BUS_UNIT_INTERFACE;
+
+#define INVALIDATING_PROPERTIES \
+ "LoadState\0" \
+ "ActiveState\0" \
+ "SubState\0" \
+ "InactiveExitTimestamp\0" \
+ "ActiveEnterTimestamp\0" \
+ "ActiveExitTimestamp\0" \
+ "InactiveEnterTimestamp\0" \
+ "Job\0" \
+ "NeedDaemonReload\0"
+
+static int bus_unit_append_names(DBusMessageIter *i, const char *property, void *data) {
+ char *t;
+ Iterator j;
+ DBusMessageIter sub;
+ Unit *u = data;
+
+ if (!dbus_message_iter_open_container(i, DBUS_TYPE_ARRAY, "s", &sub))
+ return -ENOMEM;
+
+ SET_FOREACH(t, u->names, j)
+ if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &t))
+ return -ENOMEM;
+
+ if (!dbus_message_iter_close_container(i, &sub))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_unit_append_following(DBusMessageIter *i, const char *property, void *data) {
+ Unit *u = data, *f;
+ const char *d;
+
+ assert(i);
+ assert(property);
+ assert(u);
+
+ f = unit_following(u);
+ d = f ? f->id : "";
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_STRING, &d))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_unit_append_dependencies(DBusMessageIter *i, const char *property, void *data) {
+ Unit *u;
+ Iterator j;
+ DBusMessageIter sub;
+ Set *s = data;
+
+ if (!dbus_message_iter_open_container(i, DBUS_TYPE_ARRAY, "s", &sub))
+ return -ENOMEM;
+
+ SET_FOREACH(u, s, j)
+ if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &u->id))
+ return -ENOMEM;
+
+ if (!dbus_message_iter_close_container(i, &sub))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_unit_append_description(DBusMessageIter *i, const char *property, void *data) {
+ Unit *u = data;
+ const char *d;
+
+ assert(i);
+ assert(property);
+ assert(u);
+
+ d = unit_description(u);
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_STRING, &d))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static DEFINE_BUS_PROPERTY_APPEND_ENUM(bus_unit_append_load_state, unit_load_state, UnitLoadState);
+
+static int bus_unit_append_active_state(DBusMessageIter *i, const char *property, void *data) {
+ Unit *u = data;
+ const char *state;
+
+ assert(i);
+ assert(property);
+ assert(u);
+
+ state = unit_active_state_to_string(unit_active_state(u));
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_STRING, &state))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_unit_append_sub_state(DBusMessageIter *i, const char *property, void *data) {
+ Unit *u = data;
+ const char *state;
+
+ assert(i);
+ assert(property);
+ assert(u);
+
+ state = unit_sub_state_to_string(u);
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_STRING, &state))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_unit_append_file_state(DBusMessageIter *i, const char *property, void *data) {
+ Unit *u = data;
+ const char *state;
+
+ assert(i);
+ assert(property);
+ assert(u);
+
+ state = strempty(unit_file_state_to_string(unit_get_unit_file_state(u)));
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_STRING, &state))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_unit_append_can_start(DBusMessageIter *i, const char *property, void *data) {
+ Unit *u = data;
+ dbus_bool_t b;
+
+ assert(i);
+ assert(property);
+ assert(u);
+
+ b = unit_can_start(u) &&
+ !u->refuse_manual_start;
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_BOOLEAN, &b))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_unit_append_can_stop(DBusMessageIter *i, const char *property, void *data) {
+ Unit *u = data;
+ dbus_bool_t b;
+
+ assert(i);
+ assert(property);
+ assert(u);
+
+ /* On the lower levels we assume that every unit we can start
+ * we can also stop */
+
+ b = unit_can_start(u) &&
+ !u->refuse_manual_stop;
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_BOOLEAN, &b))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_unit_append_can_reload(DBusMessageIter *i, const char *property, void *data) {
+ Unit *u = data;
+ dbus_bool_t b;
+
+ assert(i);
+ assert(property);
+ assert(u);
+
+ b = unit_can_reload(u);
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_BOOLEAN, &b))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_unit_append_can_isolate(DBusMessageIter *i, const char *property, void *data) {
+ Unit *u = data;
+ dbus_bool_t b;
+
+ assert(i);
+ assert(property);
+ assert(u);
+
+ b = unit_can_isolate(u) &&
+ !u->refuse_manual_start;
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_BOOLEAN, &b))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_unit_append_job(DBusMessageIter *i, const char *property, void *data) {
+ Unit *u = data;
+ DBusMessageIter sub;
+ _cleanup_free_ char *p = NULL;
+
+ assert(i);
+ assert(property);
+ assert(u);
+
+ if (!dbus_message_iter_open_container(i, DBUS_TYPE_STRUCT, NULL, &sub))
+ return -ENOMEM;
+
+ if (u->job) {
+
+ p = job_dbus_path(u->job);
+ if (!p)
+ return -ENOMEM;
+
+ if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_UINT32, &u->job->id) ||
+ !dbus_message_iter_append_basic(&sub, DBUS_TYPE_OBJECT_PATH, &p))
+ return -ENOMEM;
+ } else {
+ uint32_t id = 0;
+
+ /* No job, so let's fill in some placeholder
+ * data. Since we need to fill in a valid path we
+ * simple point to ourselves. */
+
+ p = unit_dbus_path(u);
+ if (!p)
+ return -ENOMEM;
+
+ if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_UINT32, &id) ||
+ !dbus_message_iter_append_basic(&sub, DBUS_TYPE_OBJECT_PATH, &p))
+ return -ENOMEM;
+ }
+
+ if (!dbus_message_iter_close_container(i, &sub))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_unit_append_default_cgroup(DBusMessageIter *i, const char *property, void *data) {
+ Unit *u = data;
+ char *t;
+ CGroupBonding *cgb;
+ bool success;
+
+ assert(i);
+ assert(property);
+ assert(u);
+
+ cgb = unit_get_default_cgroup(u);
+ if (cgb) {
+ t = cgroup_bonding_to_string(cgb);
+ if (!t)
+ return -ENOMEM;
+ } else
+ t = (char*) "";
+
+ success = dbus_message_iter_append_basic(i, DBUS_TYPE_STRING, &t);
+
+ if (cgb)
+ free(t);
+
+ return success ? 0 : -ENOMEM;
+}
+
+static int bus_unit_append_cgroups(DBusMessageIter *i, const char *property, void *data) {
+ Unit *u = data;
+ CGroupBonding *cgb;
+ DBusMessageIter sub;
+
+ if (!dbus_message_iter_open_container(i, DBUS_TYPE_ARRAY, "s", &sub))
+ return -ENOMEM;
+
+ LIST_FOREACH(by_unit, cgb, u->cgroup_bondings) {
+ _cleanup_free_ char *t = NULL;
+ bool success;
+
+ t = cgroup_bonding_to_string(cgb);
+ if (!t)
+ return -ENOMEM;
+
+ success = dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &t);
+ if (!success)
+ return -ENOMEM;
+ }
+
+ if (!dbus_message_iter_close_container(i, &sub))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_unit_append_cgroup_attrs(DBusMessageIter *i, const char *property, void *data) {
+ Unit *u = data;
+ CGroupAttribute *a;
+ DBusMessageIter sub, sub2;
+
+ if (!dbus_message_iter_open_container(i, DBUS_TYPE_ARRAY, "(sss)", &sub))
+ return -ENOMEM;
+
+ LIST_FOREACH(by_unit, a, u->cgroup_attributes) {
+ _cleanup_free_ char *v = NULL;
+ bool success;
+
+ if (a->semantics && a->semantics->map_write)
+ a->semantics->map_write(a->semantics, a->value, &v);
+
+ success =
+ dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, NULL, &sub2) &&
+ dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &a->controller) &&
+ dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &a->name) &&
+ dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, v ? &v : &a->value) &&
+ dbus_message_iter_close_container(&sub, &sub2);
+ if (!success)
+ return -ENOMEM;
+ }
+
+ if (!dbus_message_iter_close_container(i, &sub))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_unit_append_need_daemon_reload(DBusMessageIter *i, const char *property, void *data) {
+ Unit *u = data;
+ dbus_bool_t b;
+
+ assert(i);
+ assert(property);
+ assert(u);
+
+ b = unit_need_daemon_reload(u);
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_BOOLEAN, &b))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_unit_append_load_error(DBusMessageIter *i, const char *property, void *data) {
+ Unit *u = data;
+ const char *name, *message;
+ DBusMessageIter sub;
+
+ assert(i);
+ assert(property);
+ assert(u);
+
+ if (u->load_error != 0) {
+ name = bus_errno_to_dbus(u->load_error);
+ message = strempty(strerror(-u->load_error));
+ } else
+ name = message = "";
+
+ if (!dbus_message_iter_open_container(i, DBUS_TYPE_STRUCT, NULL, &sub) ||
+ !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &name) ||
+ !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &message) ||
+ !dbus_message_iter_close_container(i, &sub))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static DBusHandlerResult bus_unit_message_dispatch(Unit *u, DBusConnection *connection, DBusMessage *message) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ DBusError error;
+ JobType job_type = _JOB_TYPE_INVALID;
+ bool reload_if_possible = false;
+ int r;
+
+ dbus_error_init(&error);
+
+ if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Unit", "Start"))
+ job_type = JOB_START;
+ else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Unit", "Stop"))
+ job_type = JOB_STOP;
+ else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Unit", "Reload"))
+ job_type = JOB_RELOAD;
+ else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Unit", "Restart"))
+ job_type = JOB_RESTART;
+ else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Unit", "TryRestart"))
+ job_type = JOB_TRY_RESTART;
+ else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Unit", "ReloadOrRestart")) {
+ reload_if_possible = true;
+ job_type = JOB_RESTART;
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Unit", "ReloadOrTryRestart")) {
+ reload_if_possible = true;
+ job_type = JOB_TRY_RESTART;
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Unit", "Kill")) {
+ const char *swho;
+ int32_t signo;
+ KillWho who;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &swho,
+ DBUS_TYPE_INT32, &signo,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ if (isempty(swho))
+ who = KILL_ALL;
+ else {
+ who = kill_who_from_string(swho);
+ if (who < 0)
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+ }
+
+ if (signo <= 0 || signo >= _NSIG)
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ SELINUX_UNIT_ACCESS_CHECK(u, connection, message, "stop");
+
+ r = unit_kill(u, who, signo, &error);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.systemd1.Unit", "ResetFailed")) {
+
+ SELINUX_UNIT_ACCESS_CHECK(u, connection, message, "reload");
+
+ unit_reset_failed(u);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (streq_ptr(dbus_message_get_member(message), "SetControlGroup")) {
+ DBusMessageIter iter;
+
+ SELINUX_UNIT_ACCESS_CHECK(u, connection, message, "start");
+
+ if (!dbus_message_iter_init(message, &iter))
+ goto oom;
+
+ r = bus_unit_cgroup_set(u, &iter);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (streq_ptr(dbus_message_get_member(message), "UnsetControlGroup")) {
+ DBusMessageIter iter;
+
+ SELINUX_UNIT_ACCESS_CHECK(u, connection, message, "stop");
+
+ if (!dbus_message_iter_init(message, &iter))
+ goto oom;
+
+ r = bus_unit_cgroup_unset(u, &iter);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+ } else if (streq_ptr(dbus_message_get_member(message), "GetControlGroupAttribute")) {
+ DBusMessageIter iter;
+ _cleanup_strv_free_ char **list = NULL;
+
+ SELINUX_UNIT_ACCESS_CHECK(u, connection, message, "status");
+
+ if (!dbus_message_iter_init(message, &iter))
+ goto oom;
+
+ r = bus_unit_cgroup_attribute_get(u, &iter, &list);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ dbus_message_iter_init_append(reply, &iter);
+ if (bus_append_strv_iter(&iter, list) < 0)
+ goto oom;
+
+ } else if (streq_ptr(dbus_message_get_member(message), "SetControlGroupAttribute")) {
+ DBusMessageIter iter;
+
+ SELINUX_UNIT_ACCESS_CHECK(u, connection, message, "start");
+
+ if (!dbus_message_iter_init(message, &iter))
+ goto oom;
+
+ r = bus_unit_cgroup_attribute_set(u, &iter);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (streq_ptr(dbus_message_get_member(message), "UnsetControlGroupAttribute")) {
+ DBusMessageIter iter;
+
+ SELINUX_UNIT_ACCESS_CHECK(u, connection, message, "stop");
+
+ if (!dbus_message_iter_init(message, &iter))
+ goto oom;
+
+ r = bus_unit_cgroup_attribute_unset(u, &iter);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (UNIT_VTABLE(u)->bus_message_handler)
+ return UNIT_VTABLE(u)->bus_message_handler(u, connection, message);
+ else
+ return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
+
+ if (job_type != _JOB_TYPE_INVALID) {
+ const char *smode;
+ JobMode mode;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &smode,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ mode = job_mode_from_string(smode);
+ if (mode < 0) {
+ dbus_set_error(&error, BUS_ERROR_INVALID_JOB_MODE, "Job mode %s is invalid.", smode);
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+ }
+
+ return bus_unit_queue_job(connection, message, u, job_type, mode, reload_if_possible);
+ }
+
+ if (reply)
+ if (!bus_maybe_send_reply(connection, message, reply))
+ goto oom;
+
+ return DBUS_HANDLER_RESULT_HANDLED;
+
+oom:
+ dbus_error_free(&error);
+ return DBUS_HANDLER_RESULT_NEED_MEMORY;
+}
+
+static DBusHandlerResult bus_unit_message_handler(DBusConnection *connection, DBusMessage *message, void *data) {
+ Manager *m = data;
+ Unit *u;
+ int r;
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ DBusError error;
+
+ assert(connection);
+ assert(message);
+ assert(m);
+
+ dbus_error_init(&error);
+
+ if (streq(dbus_message_get_path(message), "/org/freedesktop/systemd1/unit")) {
+ /* Be nice to gdbus and return introspection data for our mid-level paths */
+
+ SELINUX_ACCESS_CHECK(connection, message, "status");
+
+ if (dbus_message_is_method_call(message, "org.freedesktop.DBus.Introspectable", "Introspect")) {
+ char *introspection = NULL;
+ FILE *f;
+ Iterator i;
+ const char *k;
+ size_t size;
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ /* We roll our own introspection code here, instead of
+ * relying on bus_default_message_handler() because we
+ * need to generate our introspection string
+ * dynamically. */
+
+ f = open_memstream(&introspection, &size);
+ if (!f)
+ goto oom;
+
+ fputs(DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE
+ "<node>\n", f);
+
+ fputs(BUS_INTROSPECTABLE_INTERFACE, f);
+ fputs(BUS_PEER_INTERFACE, f);
+
+ HASHMAP_FOREACH_KEY(u, k, m->units, i) {
+ char *p;
+
+ if (k != u->id)
+ continue;
+
+ p = bus_path_escape(k);
+ if (!p) {
+ fclose(f);
+ free(introspection);
+ goto oom;
+ }
+
+ fprintf(f, "<node name=\"%s\"/>", p);
+ free(p);
+ }
+
+ fputs("</node>\n", f);
+
+ if (ferror(f)) {
+ fclose(f);
+ free(introspection);
+ goto oom;
+ }
+
+ fclose(f);
+
+ if (!introspection)
+ goto oom;
+
+ if (!dbus_message_append_args(reply, DBUS_TYPE_STRING, &introspection, DBUS_TYPE_INVALID)) {
+ free(introspection);
+ goto oom;
+ }
+
+ free(introspection);
+
+ if (!bus_maybe_send_reply(connection, message, reply))
+ goto oom;
+
+ return DBUS_HANDLER_RESULT_HANDLED;
+ }
+
+ return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
+ }
+
+ r = manager_load_unit_from_dbus_path(m, dbus_message_get_path(message), &error, &u);
+ if (r == -ENOMEM)
+ goto oom;
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ return bus_unit_message_dispatch(u, connection, message);
+
+oom:
+ dbus_error_free(&error);
+
+ return DBUS_HANDLER_RESULT_NEED_MEMORY;
+}
+
+const DBusObjectPathVTable bus_unit_vtable = {
+ .message_function = bus_unit_message_handler
+};
+
+void bus_unit_send_change_signal(Unit *u) {
+ _cleanup_free_ char *p = NULL;
+ _cleanup_dbus_message_unref_ DBusMessage *m = NULL;
+
+ assert(u);
+
+ if (u->in_dbus_queue) {
+ LIST_REMOVE(Unit, dbus_queue, u->manager->dbus_unit_queue, u);
+ u->in_dbus_queue = false;
+ }
+
+ if (!u->id)
+ return;
+
+ if (!bus_has_subscriber(u->manager)) {
+ u->sent_dbus_new_signal = true;
+ return;
+ }
+
+ p = unit_dbus_path(u);
+ if (!p)
+ goto oom;
+
+ if (u->sent_dbus_new_signal) {
+ /* Send a properties changed signal. First for the
+ * specific type, then for the generic unit. The
+ * clients may rely on this order to get atomic
+ * behavior if needed. */
+
+ if (UNIT_VTABLE(u)->bus_invalidating_properties) {
+
+ m = bus_properties_changed_new(p,
+ UNIT_VTABLE(u)->bus_interface,
+ UNIT_VTABLE(u)->bus_invalidating_properties);
+ if (!m)
+ goto oom;
+
+ if (bus_broadcast(u->manager, m) < 0)
+ goto oom;
+
+ dbus_message_unref(m);
+ }
+
+ m = bus_properties_changed_new(p, "org.freedesktop.systemd1.Unit",
+ INVALIDATING_PROPERTIES);
+ if (!m)
+ goto oom;
+
+ } else {
+ /* Send a new signal */
+
+ m = dbus_message_new_signal("/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "UnitNew");
+ if (!m)
+ goto oom;
+
+ if (!dbus_message_append_args(m,
+ DBUS_TYPE_STRING, &u->id,
+ DBUS_TYPE_OBJECT_PATH, &p,
+ DBUS_TYPE_INVALID))
+ goto oom;
+ }
+
+ if (bus_broadcast(u->manager, m) < 0)
+ goto oom;
+
+ u->sent_dbus_new_signal = true;
+
+ return;
+
+oom:
+ log_oom();
+}
+
+void bus_unit_send_removed_signal(Unit *u) {
+ _cleanup_free_ char *p = NULL;
+ _cleanup_dbus_message_unref_ DBusMessage *m = NULL;
+
+ assert(u);
+
+ if (!bus_has_subscriber(u->manager))
+ return;
+
+ if (!u->sent_dbus_new_signal)
+ bus_unit_send_change_signal(u);
+
+ if (!u->id)
+ return;
+
+ p = unit_dbus_path(u);
+ if (!p)
+ goto oom;
+
+ m = dbus_message_new_signal("/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "UnitRemoved");
+ if (!m)
+ goto oom;
+
+ if (!dbus_message_append_args(m,
+ DBUS_TYPE_STRING, &u->id,
+ DBUS_TYPE_OBJECT_PATH, &p,
+ DBUS_TYPE_INVALID))
+ goto oom;
+
+ if (bus_broadcast(u->manager, m) < 0)
+ goto oom;
+
+ return;
+
+oom:
+ log_oom();
+}
+
+DBusHandlerResult bus_unit_queue_job(
+ DBusConnection *connection,
+ DBusMessage *message,
+ Unit *u,
+ JobType type,
+ JobMode mode,
+ bool reload_if_possible) {
+
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ _cleanup_free_ char *path = NULL;
+ Job *j;
+ JobBusClient *cl;
+ DBusError error;
+ int r;
+
+ assert(connection);
+ assert(message);
+ assert(u);
+ assert(type >= 0 && type < _JOB_TYPE_MAX);
+ assert(mode >= 0 && mode < _JOB_MODE_MAX);
+
+ dbus_error_init(&error);
+
+ if (reload_if_possible && unit_can_reload(u)) {
+ if (type == JOB_RESTART)
+ type = JOB_RELOAD_OR_START;
+ else if (type == JOB_TRY_RESTART)
+ type = JOB_RELOAD;
+ }
+
+ SELINUX_UNIT_ACCESS_CHECK(u, connection, message,
+ (type == JOB_START || type == JOB_RESTART || type == JOB_TRY_RESTART) ? "start" :
+ type == JOB_STOP ? "stop" : "reload");
+
+ if (type == JOB_STOP && u->load_state == UNIT_ERROR && unit_active_state(u) == UNIT_INACTIVE) {
+ dbus_set_error(&error, BUS_ERROR_NO_SUCH_UNIT, "Unit %s not loaded.", u->id);
+ return bus_send_error_reply(connection, message, &error, -EPERM);
+ }
+
+ if ((type == JOB_START && u->refuse_manual_start) ||
+ (type == JOB_STOP && u->refuse_manual_stop) ||
+ ((type == JOB_RESTART || type == JOB_TRY_RESTART) && (u->refuse_manual_start || u->refuse_manual_stop))) {
+ dbus_set_error(&error, BUS_ERROR_ONLY_BY_DEPENDENCY,
+ "Operation refused, unit %s may be requested by dependency only.", u->id);
+ return bus_send_error_reply(connection, message, &error, -EPERM);
+ }
+
+ r = manager_add_job(u->manager, type, u, mode, true, &error, &j);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ cl = job_bus_client_new(connection, bus_message_get_sender_with_fallback(message));
+ if (!cl)
+ goto oom;
+
+ LIST_PREPEND(JobBusClient, client, j->bus_client_list, cl);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ path = job_dbus_path(j);
+ if (!path)
+ goto oom;
+
+ if (!dbus_message_append_args(
+ reply,
+ DBUS_TYPE_OBJECT_PATH, &path,
+ DBUS_TYPE_INVALID))
+ goto oom;
+
+ if (!bus_maybe_send_reply(connection, message, reply))
+ goto oom;
+
+ return DBUS_HANDLER_RESULT_HANDLED;
+
+oom:
+ dbus_error_free(&error);
+
+ return DBUS_HANDLER_RESULT_NEED_MEMORY;
+}
+
+static int parse_mode(DBusMessageIter *iter, bool *runtime, bool next) {
+ const char *mode;
+ int r;
+
+ assert(iter);
+ assert(runtime);
+
+ r = bus_iter_get_basic_and_next(iter, DBUS_TYPE_STRING, &mode, next);
+ if (r < 0)
+ return r;
+
+ if (streq(mode, "runtime"))
+ *runtime = true;
+ else if (streq(mode, "persistent"))
+ *runtime = false;
+ else
+ return -EINVAL;
+
+ return 0;
+}
+
+int bus_unit_cgroup_set(Unit *u, DBusMessageIter *iter) {
+ _cleanup_free_ char *controller = NULL, *old_path = NULL, *new_path = NULL, *contents = NULL;
+ const char *name;
+ CGroupBonding *b;
+ bool runtime;
+ int r;
+
+ assert(u);
+ assert(iter);
+
+ if (!unit_get_exec_context(u))
+ return -EINVAL;
+
+ r = bus_iter_get_basic_and_next(iter, DBUS_TYPE_STRING, &name, true);
+ if (r < 0)
+ return r;
+
+ r = parse_mode(iter, &runtime, false);
+ if (r < 0)
+ return r;
+
+ r = cg_split_spec(name, &controller, &new_path);
+ if (r < 0)
+ return r;
+
+ if (!new_path) {
+ new_path = unit_default_cgroup_path(u);
+ if (!new_path)
+ return -ENOMEM;
+ }
+
+ if (!controller || streq(controller, SYSTEMD_CGROUP_CONTROLLER))
+ return -EINVAL;
+
+ b = cgroup_bonding_find_list(u->cgroup_bondings, controller);
+ if (b) {
+ if (streq(b->path, new_path))
+ return 0;
+
+ if (b->essential)
+ return -EINVAL;
+
+ old_path = strdup(b->path);
+ if (!old_path)
+ return -ENOMEM;
+ }
+
+ r = unit_add_cgroup_from_text(u, name, true, &b);
+ if (r < 0)
+ return r;
+ if (r > 0) {
+ CGroupAttribute *a;
+
+ /* Try to move things to the new place, and clean up the old place */
+ cgroup_bonding_realize(b);
+ cgroup_bonding_migrate(b, u->cgroup_bondings);
+
+ if (old_path)
+ cg_trim(controller, old_path, true);
+
+ /* Apply the attributes to the new group */
+ LIST_FOREACH(by_unit, a, u->cgroup_attributes)
+ if (streq(a->controller, controller))
+ cgroup_attribute_apply(a, b);
+ }
+
+ contents = strjoin("[", UNIT_VTABLE(u)->exec_section, "]\n"
+ "ControlGroup=", name, "\n", NULL);
+ if (!contents)
+ return -ENOMEM;
+
+ return unit_write_drop_in(u, runtime, controller, contents);
+}
+
+int bus_unit_cgroup_unset(Unit *u, DBusMessageIter *iter) {
+ _cleanup_free_ char *controller = NULL, *path = NULL, *target = NULL;
+ const char *name;
+ CGroupAttribute *a, *n;
+ CGroupBonding *b;
+ bool runtime;
+ int r;
+
+ assert(u);
+ assert(iter);
+
+ if (!unit_get_exec_context(u))
+ return -EINVAL;
+
+ r = bus_iter_get_basic_and_next(iter, DBUS_TYPE_STRING, &name, true);
+ if (r < 0)
+ return r;
+
+ r = parse_mode(iter, &runtime, false);
+ if (r < 0)
+ return r;
+
+ r = cg_split_spec(name, &controller, &path);
+ if (r < 0)
+ return r;
+
+ if (!controller || streq(controller, SYSTEMD_CGROUP_CONTROLLER))
+ return -EINVAL;
+
+ b = cgroup_bonding_find_list(u->cgroup_bondings, controller);
+ if (!b)
+ return -ENOENT;
+
+ if (path && !path_equal(path, b->path))
+ return -ENOENT;
+
+ if (b->essential)
+ return -EINVAL;
+
+ unit_remove_drop_in(u, runtime, controller);
+
+ /* Try to migrate the old group away */
+ if (cg_pid_get_path(controller, 0, &target) >= 0)
+ cgroup_bonding_migrate_to(u->cgroup_bondings, target, false);
+
+ cgroup_bonding_free(b, true);
+
+ /* Drop all attributes of this controller */
+ LIST_FOREACH_SAFE(by_unit, a, n, u->cgroup_attributes) {
+ if (!streq(a->controller, controller))
+ continue;
+
+ unit_remove_drop_in(u, runtime, a->name);
+ cgroup_attribute_free(a);
+ }
+
+ return 0;
+}
+
+int bus_unit_cgroup_attribute_get(Unit *u, DBusMessageIter *iter, char ***_result) {
+ _cleanup_free_ char *controller = NULL;
+ CGroupAttribute *a;
+ CGroupBonding *b;
+ const char *name;
+ char **l = NULL;
+ int r;
+
+ assert(u);
+ assert(iter);
+ assert(_result);
+
+ if (!unit_get_exec_context(u))
+ return -EINVAL;
+
+ r = bus_iter_get_basic_and_next(iter, DBUS_TYPE_STRING, &name, false);
+ if (r < 0)
+ return r;
+
+ r = cg_controller_from_attr(name, &controller);
+ if (r < 0)
+ return r;
+
+ /* First attempt, read the value from the kernel */
+ b = cgroup_bonding_find_list(u->cgroup_bondings, controller);
+ if (b) {
+ _cleanup_free_ char *p = NULL, *v = NULL;
+
+ r = cg_get_path(b->controller, b->path, name, &p);
+ if (r < 0)
+ return r;
+
+ r = read_full_file(p, &v, NULL);
+ if (r >= 0) {
+ /* Split on new lines */
+ l = strv_split_newlines(v);
+ if (!l)
+ return -ENOMEM;
+
+ *_result = l;
+ return 0;
+
+ }
+ }
+
+ /* If that didn't work, read our cached value */
+ LIST_FOREACH(by_unit, a, u->cgroup_attributes) {
+
+ if (!cgroup_attribute_matches(a, controller, name))
+ continue;
+
+ r = strv_extend(&l, a->value);
+ if (r < 0) {
+ strv_free(l);
+ return r;
+ }
+ }
+
+ if (!l)
+ return -ENOENT;
+
+ *_result = l;
+ return 0;
+}
+
+static int update_attribute_drop_in(Unit *u, bool runtime, const char *name) {
+ _cleanup_free_ char *buf = NULL;
+ CGroupAttribute *a;
+
+ assert(u);
+ assert(name);
+
+ LIST_FOREACH(by_unit, a, u->cgroup_attributes) {
+ if (!cgroup_attribute_matches(a, NULL, name))
+ continue;
+
+ if (!buf) {
+ buf = strjoin("[", UNIT_VTABLE(u)->exec_section, "]\n"
+ "ControlGroupAttribute=", a->name, " ", a->value, "\n", NULL);
+
+ if (!buf)
+ return -ENOMEM;
+ } else {
+ char *b;
+
+ b = strjoin(buf,
+ "ControlGroupAttribute=", a->name, " ", a->value, "\n", NULL);
+
+ if (!b)
+ return -ENOMEM;
+
+ free(buf);
+ buf = b;
+ }
+ }
+
+ if (buf)
+ return unit_write_drop_in(u, runtime, name, buf);
+ else
+ return unit_remove_drop_in(u, runtime, name);
+}
+
+int bus_unit_cgroup_attribute_set(Unit *u, DBusMessageIter *iter) {
+ _cleanup_strv_free_ char **l = NULL;
+ int r;
+ bool runtime = false;
+ char **value;
+ const char *name;
+
+ assert(u);
+ assert(iter);
+
+ if (!unit_get_exec_context(u))
+ return -EINVAL;
+
+ r = bus_iter_get_basic_and_next(iter, DBUS_TYPE_STRING, &name, true);
+ if (r < 0)
+ return r;
+
+ r = bus_parse_strv_iter(iter, &l);
+ if (r < 0)
+ return r;
+
+ if (!dbus_message_iter_next(iter))
+ return -EINVAL;
+
+ r = parse_mode(iter, &runtime, false);
+ if (r < 0)
+ return r;
+
+ STRV_FOREACH(value, l) {
+ _cleanup_free_ char *v = NULL;
+ CGroupAttribute *a;
+ const CGroupSemantics *s;
+
+ r = cgroup_semantics_find(NULL, name, *value, &v, &s);
+ if (r < 0)
+ return r;
+
+ if (s && !s->multiple && l[1])
+ return -EINVAL;
+
+ r = unit_add_cgroup_attribute(u, s, NULL, name, v ? v : *value, &a);
+ if (r < 0)
+ return r;
+
+ if (r > 0) {
+ CGroupBonding *b;
+
+ b = cgroup_bonding_find_list(u->cgroup_bondings, a->controller);
+ if (!b) {
+ /* Doesn't exist yet? Then let's add it */
+ r = unit_add_cgroup_from_text(u, a->controller, false, &b);
+ if (r < 0)
+ return r;
+
+ if (r > 0) {
+ cgroup_bonding_realize(b);
+ cgroup_bonding_migrate(b, u->cgroup_bondings);
+ }
+ }
+
+ /* Make it count */
+ cgroup_attribute_apply(a, u->cgroup_bondings);
+ }
+
+ }
+
+ r = update_attribute_drop_in(u, runtime, name);
+ if (r < 0)
+ return r;
+
+ return 0;
+}
+
+int bus_unit_cgroup_attribute_unset(Unit *u, DBusMessageIter *iter) {
+ const char *name;
+ bool runtime;
+ int r;
+
+ assert(u);
+ assert(iter);
+
+ if (!unit_get_exec_context(u))
+ return -EINVAL;
+
+ r = bus_iter_get_basic_and_next(iter, DBUS_TYPE_STRING, &name, true);
+ if (r < 0)
+ return r;
+
+ r = parse_mode(iter, &runtime, false);
+ if (r < 0)
+ return r;
+
+ cgroup_attribute_free_some(u->cgroup_attributes, NULL, name);
+ update_attribute_drop_in(u, runtime, name);
+
+ return 0;
+}
+
+const BusProperty bus_unit_properties[] = {
+ { "Id", bus_property_append_string, "s", offsetof(Unit, id), true },
+ { "Names", bus_unit_append_names, "as", 0 },
+ { "Following", bus_unit_append_following, "s", 0 },
+ { "Requires", bus_unit_append_dependencies, "as", offsetof(Unit, dependencies[UNIT_REQUIRES]), true },
+ { "RequiresOverridable", bus_unit_append_dependencies, "as", offsetof(Unit, dependencies[UNIT_REQUIRES_OVERRIDABLE]), true },
+ { "Requisite", bus_unit_append_dependencies, "as", offsetof(Unit, dependencies[UNIT_REQUISITE]), true },
+ { "RequisiteOverridable", bus_unit_append_dependencies, "as", offsetof(Unit, dependencies[UNIT_REQUISITE_OVERRIDABLE]), true },
+ { "Wants", bus_unit_append_dependencies, "as", offsetof(Unit, dependencies[UNIT_WANTS]), true },
+ { "BindsTo", bus_unit_append_dependencies, "as", offsetof(Unit, dependencies[UNIT_BINDS_TO]), true },
+ { "PartOf", bus_unit_append_dependencies, "as", offsetof(Unit, dependencies[UNIT_PART_OF]), true },
+ { "RequiredBy", bus_unit_append_dependencies, "as", offsetof(Unit, dependencies[UNIT_REQUIRED_BY]), true },
+ { "RequiredByOverridable",bus_unit_append_dependencies, "as", offsetof(Unit, dependencies[UNIT_REQUIRED_BY_OVERRIDABLE]), true },
+ { "WantedBy", bus_unit_append_dependencies, "as", offsetof(Unit, dependencies[UNIT_WANTED_BY]), true },
+ { "BoundBy", bus_unit_append_dependencies, "as", offsetof(Unit, dependencies[UNIT_BOUND_BY]), true },
+ { "ConsistsOf", bus_unit_append_dependencies, "as", offsetof(Unit, dependencies[UNIT_CONSISTS_OF]), true },
+ { "Conflicts", bus_unit_append_dependencies, "as", offsetof(Unit, dependencies[UNIT_CONFLICTS]), true },
+ { "ConflictedBy", bus_unit_append_dependencies, "as", offsetof(Unit, dependencies[UNIT_CONFLICTED_BY]), true },
+ { "Before", bus_unit_append_dependencies, "as", offsetof(Unit, dependencies[UNIT_BEFORE]), true },
+ { "After", bus_unit_append_dependencies, "as", offsetof(Unit, dependencies[UNIT_AFTER]), true },
+ { "OnFailure", bus_unit_append_dependencies, "as", offsetof(Unit, dependencies[UNIT_ON_FAILURE]), true },
+ { "Triggers", bus_unit_append_dependencies, "as", offsetof(Unit, dependencies[UNIT_TRIGGERS]), true },
+ { "TriggeredBy", bus_unit_append_dependencies, "as", offsetof(Unit, dependencies[UNIT_TRIGGERED_BY]), true },
+ { "PropagatesReloadTo", bus_unit_append_dependencies, "as", offsetof(Unit, dependencies[UNIT_PROPAGATES_RELOAD_TO]), true },
+ { "ReloadPropagatedFrom", bus_unit_append_dependencies, "as", offsetof(Unit, dependencies[UNIT_RELOAD_PROPAGATED_FROM]), true },
+ { "RequiresMountsFor", bus_property_append_strv, "as", offsetof(Unit, requires_mounts_for), true },
+ { "Documentation", bus_property_append_strv, "as", offsetof(Unit, documentation), true },
+ { "Description", bus_unit_append_description, "s", 0 },
+ { "LoadState", bus_unit_append_load_state, "s", offsetof(Unit, load_state) },
+ { "ActiveState", bus_unit_append_active_state, "s", 0 },
+ { "SubState", bus_unit_append_sub_state, "s", 0 },
+ { "FragmentPath", bus_property_append_string, "s", offsetof(Unit, fragment_path), true },
+ { "SourcePath", bus_property_append_string, "s", offsetof(Unit, source_path), true },
+ { "DropInPaths", bus_property_append_strv, "as", offsetof(Unit, dropin_paths), true },
+ { "UnitFileState", bus_unit_append_file_state, "s", 0 },
+ { "InactiveExitTimestamp",bus_property_append_usec, "t", offsetof(Unit, inactive_exit_timestamp.realtime) },
+ { "InactiveExitTimestampMonotonic", bus_property_append_usec, "t", offsetof(Unit, inactive_exit_timestamp.monotonic) },
+ { "ActiveEnterTimestamp", bus_property_append_usec, "t", offsetof(Unit, active_enter_timestamp.realtime) },
+ { "ActiveEnterTimestampMonotonic", bus_property_append_usec, "t", offsetof(Unit, active_enter_timestamp.monotonic) },
+ { "ActiveExitTimestamp", bus_property_append_usec, "t", offsetof(Unit, active_exit_timestamp.realtime) },
+ { "ActiveExitTimestampMonotonic", bus_property_append_usec, "t", offsetof(Unit, active_exit_timestamp.monotonic) },
+ { "InactiveEnterTimestamp", bus_property_append_usec, "t", offsetof(Unit, inactive_enter_timestamp.realtime) },
+ { "InactiveEnterTimestampMonotonic",bus_property_append_usec, "t", offsetof(Unit, inactive_enter_timestamp.monotonic) },
+ { "CanStart", bus_unit_append_can_start, "b", 0 },
+ { "CanStop", bus_unit_append_can_stop, "b", 0 },
+ { "CanReload", bus_unit_append_can_reload, "b", 0 },
+ { "CanIsolate", bus_unit_append_can_isolate, "b", 0 },
+ { "Job", bus_unit_append_job, "(uo)", 0 },
+ { "StopWhenUnneeded", bus_property_append_bool, "b", offsetof(Unit, stop_when_unneeded) },
+ { "RefuseManualStart", bus_property_append_bool, "b", offsetof(Unit, refuse_manual_start) },
+ { "RefuseManualStop", bus_property_append_bool, "b", offsetof(Unit, refuse_manual_stop) },
+ { "AllowIsolate", bus_property_append_bool, "b", offsetof(Unit, allow_isolate) },
+ { "DefaultDependencies", bus_property_append_bool, "b", offsetof(Unit, default_dependencies) },
+ { "OnFailureIsolate", bus_property_append_bool, "b", offsetof(Unit, on_failure_isolate) },
+ { "IgnoreOnIsolate", bus_property_append_bool, "b", offsetof(Unit, ignore_on_isolate) },
+ { "IgnoreOnSnapshot", bus_property_append_bool, "b", offsetof(Unit, ignore_on_snapshot) },
+ { "NeedDaemonReload", bus_unit_append_need_daemon_reload, "b", 0 },
+ { "JobTimeoutUSec", bus_property_append_usec, "t", offsetof(Unit, job_timeout) },
+ { "ConditionTimestamp", bus_property_append_usec, "t", offsetof(Unit, condition_timestamp.realtime) },
+ { "ConditionTimestampMonotonic", bus_property_append_usec, "t", offsetof(Unit, condition_timestamp.monotonic) },
+ { "ConditionResult", bus_property_append_bool, "b", offsetof(Unit, condition_result) },
+ { "LoadError", bus_unit_append_load_error, "(ss)", 0 },
+ { NULL, }
+};
+
+const BusProperty bus_unit_cgroup_properties[] = {
+ { "DefaultControlGroup", bus_unit_append_default_cgroup, "s", 0 },
+ { "ControlGroups", bus_unit_append_cgroups, "as", 0 },
+ { "ControlGroupAttributes", bus_unit_append_cgroup_attrs, "a(sss)", 0 },
+ { NULL, }
+};
diff --git a/src/core/dbus-unit.h b/src/core/dbus-unit.h
new file mode 100644
index 0000000000..acd1ddbe78
--- /dev/null
+++ b/src/core/dbus-unit.h
@@ -0,0 +1,179 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <dbus/dbus.h>
+
+#include "manager.h"
+#include "dbus-common.h"
+
+#define BUS_UNIT_INTERFACE \
+ " <interface name=\"org.freedesktop.systemd1.Unit\">\n" \
+ " <method name=\"Start\">\n" \
+ " <arg name=\"mode\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"job\" type=\"o\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"Stop\">\n" \
+ " <arg name=\"mode\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"job\" type=\"o\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"Reload\">\n" \
+ " <arg name=\"mode\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"job\" type=\"o\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"Restart\">\n" \
+ " <arg name=\"mode\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"job\" type=\"o\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"TryRestart\">\n" \
+ " <arg name=\"mode\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"job\" type=\"o\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"ReloadOrRestart\">\n" \
+ " <arg name=\"mode\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"job\" type=\"o\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"ReloadOrTryRestart\">\n" \
+ " <arg name=\"mode\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"job\" type=\"o\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"Kill\">\n" \
+ " <arg name=\"who\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"signal\" type=\"i\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"ResetFailed\"/>\n" \
+ " <property name=\"Id\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"Names\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"Following\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"Requires\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"RequiresOverridable\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"Requisite\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"RequisiteOverridable\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"Wants\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"BindsTo\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"PartOf\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"RequiredBy\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"RequiredByOverridable\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"WantedBy\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"BoundBy\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"ConsistsOf\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"Conflicts\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"ConflictedBy\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"Before\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"After\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"OnFailure\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"Triggers\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"TriggeredBy\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"PropagatesReloadTo\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"ReloadPropagatedFrom\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"RequiresMountsFor\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"Description\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"SourcePath\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"DropInPaths\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"Documentation\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"LoadState\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"ActiveState\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"SubState\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"FragmentPath\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"UnitFileState\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"InactiveExitTimestamp\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"InactiveExitTimestampMonotonic\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"ActiveEnterTimestamp\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"ActiveEnterTimestampMonotonic\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"ActiveExitTimestamp\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"ActiveExitTimestampMonotonic\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"InactiveEnterTimestamp\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"InactiveEnterTimestampMonotonic\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"CanStart\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"CanStop\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"CanReload\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"CanIsolate\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"Job\" type=\"(uo)\" access=\"read\"/>\n" \
+ " <property name=\"StopWhenUnneeded\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"RefuseManualStart\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"RefuseManualStop\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"AllowIsolate\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"DefaultDependencies\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"OnFailureIsolate\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"IgnoreOnIsolate\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"IgnoreOnSnapshot\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"NeedDaemonReload\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"JobTimeoutUSec\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"ConditionTimestamp\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"ConditionTimestampMonotonic\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"ConditionResult\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"LoadError\" type=\"(ss)\" access=\"read\"/>\n" \
+ " </interface>\n"
+
+#define BUS_UNIT_CGROUP_INTERFACE \
+ " <property name=\"DefaultControlGroup\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"ControlGroups\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"ControlGroupAttributes\" type=\"a(sss)\" access=\"read\"/>\n" \
+ " <method name=\"SetControlGroup\">\n" \
+ " <arg name=\"group\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"mode\" type=\"s\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"UnsetControlGroup\">\n" \
+ " <arg name=\"group\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"mode\" type=\"s\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"GetControlGroupAttribute\">\n" \
+ " <arg name=\"attribute\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"values\" type=\"as\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"SetControlGroupAttribute\">\n" \
+ " <arg name=\"attribute\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"values\" type=\"as\" direction=\"in\"/>\n" \
+ " <arg name=\"mode\" type=\"s\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"UnsetControlGroupAttribute\">\n" \
+ " <arg name=\"attribute\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"mode\" type=\"s\" direction=\"in\"/>\n" \
+ " </method>\n"
+
+#define BUS_UNIT_INTERFACES_LIST \
+ BUS_GENERIC_INTERFACES_LIST \
+ "org.freedesktop.systemd1.Unit\0"
+
+extern const BusProperty bus_unit_properties[];
+extern const BusProperty bus_unit_cgroup_properties[];
+
+void bus_unit_send_change_signal(Unit *u);
+void bus_unit_send_removed_signal(Unit *u);
+
+DBusHandlerResult bus_unit_queue_job(
+ DBusConnection *connection,
+ DBusMessage *message,
+ Unit *u,
+ JobType type,
+ JobMode mode,
+ bool reload_if_possible);
+
+int bus_unit_cgroup_set(Unit *u, DBusMessageIter *iter);
+int bus_unit_cgroup_unset(Unit *u, DBusMessageIter *iter);
+int bus_unit_cgroup_attribute_get(Unit *u, DBusMessageIter *iter, char ***_result);
+int bus_unit_cgroup_attribute_set(Unit *u, DBusMessageIter *iter);
+int bus_unit_cgroup_attribute_unset(Unit *u, DBusMessageIter *iter);
+
+extern const DBusObjectPathVTable bus_unit_vtable;
+
+extern const char bus_unit_interface[];
diff --git a/src/core/dbus.c b/src/core/dbus.c
new file mode 100644
index 0000000000..1272c938cf
--- /dev/null
+++ b/src/core/dbus.c
@@ -0,0 +1,1491 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/epoll.h>
+#include <sys/timerfd.h>
+#include <errno.h>
+#include <unistd.h>
+#include <dbus/dbus.h>
+
+#include "dbus.h"
+#include "log.h"
+#include "strv.h"
+#include "cgroup.h"
+#include "mkdir.h"
+#include "missing.h"
+#include "dbus-unit.h"
+#include "dbus-job.h"
+#include "dbus-manager.h"
+#include "dbus-service.h"
+#include "dbus-socket.h"
+#include "dbus-target.h"
+#include "dbus-device.h"
+#include "dbus-mount.h"
+#include "dbus-automount.h"
+#include "dbus-snapshot.h"
+#include "dbus-swap.h"
+#include "dbus-timer.h"
+#include "dbus-path.h"
+#include "bus-errors.h"
+#include "special.h"
+#include "dbus-common.h"
+
+#define CONNECTIONS_MAX 512
+
+/* Well-known address (http://dbus.freedesktop.org/doc/dbus-specification.html#message-bus-types) */
+#define DBUS_SYSTEM_BUS_DEFAULT_ADDRESS "unix:path=/var/run/dbus/system_bus_socket"
+/* Only used as a fallback */
+#define DBUS_SESSION_BUS_DEFAULT_ADDRESS "autolaunch:"
+
+static const char bus_properties_interface[] = BUS_PROPERTIES_INTERFACE;
+static const char bus_introspectable_interface[] = BUS_INTROSPECTABLE_INTERFACE;
+
+const char *const bus_interface_table[] = {
+ "org.freedesktop.DBus.Properties", bus_properties_interface,
+ "org.freedesktop.DBus.Introspectable", bus_introspectable_interface,
+ "org.freedesktop.systemd1.Manager", bus_manager_interface,
+ "org.freedesktop.systemd1.Job", bus_job_interface,
+ "org.freedesktop.systemd1.Unit", bus_unit_interface,
+ "org.freedesktop.systemd1.Service", bus_service_interface,
+ "org.freedesktop.systemd1.Socket", bus_socket_interface,
+ "org.freedesktop.systemd1.Target", bus_target_interface,
+ "org.freedesktop.systemd1.Device", bus_device_interface,
+ "org.freedesktop.systemd1.Mount", bus_mount_interface,
+ "org.freedesktop.systemd1.Automount", bus_automount_interface,
+ "org.freedesktop.systemd1.Snapshot", bus_snapshot_interface,
+ "org.freedesktop.systemd1.Swap", bus_swap_interface,
+ "org.freedesktop.systemd1.Timer", bus_timer_interface,
+ "org.freedesktop.systemd1.Path", bus_path_interface,
+ NULL
+};
+
+static void bus_done_api(Manager *m);
+static void bus_done_system(Manager *m);
+static void bus_done_private(Manager *m);
+static void shutdown_connection(Manager *m, DBusConnection *c);
+
+static void bus_dispatch_status(DBusConnection *bus, DBusDispatchStatus status, void *data) {
+ Manager *m = data;
+
+ assert(bus);
+ assert(m);
+
+ /* We maintain two sets, one for those connections where we
+ * requested a dispatch, and another where we didn't. And then,
+ * we move the connections between the two sets. */
+
+ if (status == DBUS_DISPATCH_COMPLETE)
+ set_move_one(m->bus_connections, m->bus_connections_for_dispatch, bus);
+ else
+ set_move_one(m->bus_connections_for_dispatch, m->bus_connections, bus);
+}
+
+void bus_watch_event(Manager *m, Watch *w, int events) {
+ assert(m);
+ assert(w);
+
+ /* This is called by the event loop whenever there is
+ * something happening on D-Bus' file handles. */
+
+ if (!dbus_watch_get_enabled(w->data.bus_watch))
+ return;
+
+ dbus_watch_handle(w->data.bus_watch, bus_events_to_flags(events));
+}
+
+static dbus_bool_t bus_add_watch(DBusWatch *bus_watch, void *data) {
+ Manager *m = data;
+ Watch *w;
+ struct epoll_event ev;
+
+ assert(bus_watch);
+ assert(m);
+
+ if (!(w = new0(Watch, 1)))
+ return FALSE;
+
+ w->fd = dbus_watch_get_unix_fd(bus_watch);
+ w->type = WATCH_DBUS_WATCH;
+ w->data.bus_watch = bus_watch;
+
+ zero(ev);
+ ev.events = bus_flags_to_events(bus_watch);
+ ev.data.ptr = w;
+
+ if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, w->fd, &ev) < 0) {
+
+ if (errno != EEXIST) {
+ free(w);
+ return FALSE;
+ }
+
+ /* Hmm, bloody D-Bus creates multiple watches on the
+ * same fd. epoll() does not like that. As a dirty
+ * hack we simply dup() the fd and hence get a second
+ * one we can safely add to the epoll(). */
+
+ if ((w->fd = dup(w->fd)) < 0) {
+ free(w);
+ return FALSE;
+ }
+
+ if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, w->fd, &ev) < 0) {
+ close_nointr_nofail(w->fd);
+ free(w);
+ return FALSE;
+ }
+
+ w->fd_is_dupped = true;
+ }
+
+ dbus_watch_set_data(bus_watch, w, NULL);
+
+ return TRUE;
+}
+
+static void bus_remove_watch(DBusWatch *bus_watch, void *data) {
+ Manager *m = data;
+ Watch *w;
+
+ assert(bus_watch);
+ assert(m);
+
+ w = dbus_watch_get_data(bus_watch);
+ if (!w)
+ return;
+
+ assert(w->type == WATCH_DBUS_WATCH);
+ assert_se(epoll_ctl(m->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
+
+ if (w->fd_is_dupped)
+ close_nointr_nofail(w->fd);
+
+ free(w);
+}
+
+static void bus_toggle_watch(DBusWatch *bus_watch, void *data) {
+ Manager *m = data;
+ Watch *w;
+ struct epoll_event ev;
+
+ assert(bus_watch);
+ assert(m);
+
+ w = dbus_watch_get_data(bus_watch);
+ if (!w)
+ return;
+
+ assert(w->type == WATCH_DBUS_WATCH);
+
+ zero(ev);
+ ev.events = bus_flags_to_events(bus_watch);
+ ev.data.ptr = w;
+
+ assert_se(epoll_ctl(m->epoll_fd, EPOLL_CTL_MOD, w->fd, &ev) == 0);
+}
+
+static int bus_timeout_arm(Manager *m, Watch *w) {
+ struct itimerspec its = {};
+
+ assert(m);
+ assert(w);
+
+ if (dbus_timeout_get_enabled(w->data.bus_timeout)) {
+ timespec_store(&its.it_value, dbus_timeout_get_interval(w->data.bus_timeout) * USEC_PER_MSEC);
+ its.it_interval = its.it_value;
+ }
+
+ if (timerfd_settime(w->fd, 0, &its, NULL) < 0)
+ return -errno;
+
+ return 0;
+}
+
+void bus_timeout_event(Manager *m, Watch *w, int events) {
+ assert(m);
+ assert(w);
+
+ /* This is called by the event loop whenever there is
+ * something happening on D-Bus' file handles. */
+
+ if (!(dbus_timeout_get_enabled(w->data.bus_timeout)))
+ return;
+
+ dbus_timeout_handle(w->data.bus_timeout);
+}
+
+static dbus_bool_t bus_add_timeout(DBusTimeout *timeout, void *data) {
+ Manager *m = data;
+ Watch *w;
+ struct epoll_event ev;
+
+ assert(timeout);
+ assert(m);
+
+ if (!(w = new0(Watch, 1)))
+ return FALSE;
+
+ if ((w->fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC)) < 0)
+ goto fail;
+
+ w->type = WATCH_DBUS_TIMEOUT;
+ w->data.bus_timeout = timeout;
+
+ if (bus_timeout_arm(m, w) < 0)
+ goto fail;
+
+ zero(ev);
+ ev.events = EPOLLIN;
+ ev.data.ptr = w;
+
+ if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, w->fd, &ev) < 0)
+ goto fail;
+
+ dbus_timeout_set_data(timeout, w, NULL);
+
+ return TRUE;
+
+fail:
+ if (w->fd >= 0)
+ close_nointr_nofail(w->fd);
+
+ free(w);
+ return FALSE;
+}
+
+static void bus_remove_timeout(DBusTimeout *timeout, void *data) {
+ Manager *m = data;
+ Watch *w;
+
+ assert(timeout);
+ assert(m);
+
+ w = dbus_timeout_get_data(timeout);
+ if (!w)
+ return;
+
+ assert(w->type == WATCH_DBUS_TIMEOUT);
+
+ assert_se(epoll_ctl(m->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
+ close_nointr_nofail(w->fd);
+ free(w);
+}
+
+static void bus_toggle_timeout(DBusTimeout *timeout, void *data) {
+ Manager *m = data;
+ Watch *w;
+ int r;
+
+ assert(timeout);
+ assert(m);
+
+ w = dbus_timeout_get_data(timeout);
+ if (!w)
+ return;
+
+ assert(w->type == WATCH_DBUS_TIMEOUT);
+
+ if ((r = bus_timeout_arm(m, w)) < 0)
+ log_error("Failed to rearm timer: %s", strerror(-r));
+}
+
+static DBusHandlerResult api_bus_message_filter(DBusConnection *connection, DBusMessage *message, void *data) {
+ Manager *m = data;
+ DBusError error;
+ DBusMessage *reply = NULL;
+
+ assert(connection);
+ assert(message);
+ assert(m);
+
+ dbus_error_init(&error);
+
+ if (dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_METHOD_CALL ||
+ dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_SIGNAL)
+ log_debug("Got D-Bus request: %s.%s() on %s",
+ dbus_message_get_interface(message),
+ dbus_message_get_member(message),
+ dbus_message_get_path(message));
+
+ if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
+ log_debug("API D-Bus connection terminated.");
+ bus_done_api(m);
+
+ } else if (dbus_message_is_signal(message, DBUS_INTERFACE_DBUS, "NameOwnerChanged")) {
+ const char *name, *old_owner, *new_owner;
+
+ if (!dbus_message_get_args(message, &error,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_STRING, &old_owner,
+ DBUS_TYPE_STRING, &new_owner,
+ DBUS_TYPE_INVALID))
+ log_error("Failed to parse NameOwnerChanged message: %s", bus_error_message(&error));
+ else {
+ if (set_remove(BUS_CONNECTION_SUBSCRIBED(m, connection), (char*) name))
+ log_debug("Subscription client vanished: %s (left: %u)", name, set_size(BUS_CONNECTION_SUBSCRIBED(m, connection)));
+
+ if (old_owner[0] == 0)
+ old_owner = NULL;
+
+ if (new_owner[0] == 0)
+ new_owner = NULL;
+
+ manager_dispatch_bus_name_owner_changed(m, name, old_owner, new_owner);
+ }
+ } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Activator", "ActivationRequest")) {
+ const char *name;
+
+ if (!dbus_message_get_args(message, &error,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_INVALID))
+ log_error("Failed to parse ActivationRequest message: %s", bus_error_message(&error));
+ else {
+ int r;
+ Unit *u;
+
+ log_debug("Got D-Bus activation request for %s", name);
+
+ if (manager_unit_inactive_or_pending(m, SPECIAL_DBUS_SERVICE) ||
+ manager_unit_inactive_or_pending(m, SPECIAL_DBUS_SOCKET)) {
+ r = -EADDRNOTAVAIL;
+ dbus_set_error(&error, BUS_ERROR_SHUTTING_DOWN, "Refusing activation, D-Bus is shutting down.");
+ } else {
+ r = manager_load_unit(m, name, NULL, &error, &u);
+
+ if (r >= 0 && u->refuse_manual_start)
+ r = -EPERM;
+
+ if (r >= 0)
+ r = manager_add_job(m, JOB_START, u, JOB_REPLACE, true, &error, NULL);
+ }
+
+ if (r < 0) {
+ const char *id, *text;
+
+ log_debug("D-Bus activation failed for %s: %s", name, strerror(-r));
+
+ if (!(reply = dbus_message_new_signal("/org/freedesktop/systemd1", "org.freedesktop.systemd1.Activator", "ActivationFailure")))
+ goto oom;
+
+ id = error.name ? error.name : bus_errno_to_dbus(r);
+ text = bus_error(&error, r);
+
+ if (!dbus_message_set_destination(reply, DBUS_SERVICE_DBUS) ||
+ !dbus_message_append_args(reply,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_STRING, &id,
+ DBUS_TYPE_STRING, &text,
+ DBUS_TYPE_INVALID))
+ goto oom;
+ }
+
+ /* On success we don't do anything, the service will be spawned now */
+ }
+ }
+
+ dbus_error_free(&error);
+
+ if (reply) {
+ if (!bus_maybe_send_reply(connection, message, reply))
+ goto oom;
+
+ dbus_message_unref(reply);
+ }
+
+ return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
+
+oom:
+ if (reply)
+ dbus_message_unref(reply);
+
+ dbus_error_free(&error);
+
+ return DBUS_HANDLER_RESULT_NEED_MEMORY;
+}
+
+static DBusHandlerResult system_bus_message_filter(DBusConnection *connection, DBusMessage *message, void *data) {
+ Manager *m = data;
+ DBusError error;
+
+ assert(connection);
+ assert(message);
+ assert(m);
+
+ dbus_error_init(&error);
+
+ if (m->api_bus != m->system_bus &&
+ (dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_METHOD_CALL ||
+ dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_SIGNAL))
+ log_debug("Got D-Bus request on system bus: %s.%s() on %s",
+ dbus_message_get_interface(message),
+ dbus_message_get_member(message),
+ dbus_message_get_path(message));
+
+ if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
+ log_debug("System D-Bus connection terminated.");
+ bus_done_system(m);
+
+ } else if (m->running_as != SYSTEMD_SYSTEM &&
+ dbus_message_is_signal(message, "org.freedesktop.systemd1.Agent", "Released")) {
+
+ const char *cgroup;
+
+ if (!dbus_message_get_args(message, &error,
+ DBUS_TYPE_STRING, &cgroup,
+ DBUS_TYPE_INVALID))
+ log_error("Failed to parse Released message: %s", bus_error_message(&error));
+ else
+ cgroup_notify_empty(m, cgroup);
+ }
+
+ dbus_error_free(&error);
+ return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
+}
+
+static DBusHandlerResult private_bus_message_filter(DBusConnection *connection, DBusMessage *message, void *data) {
+ Manager *m = data;
+ DBusError error;
+
+ assert(connection);
+ assert(message);
+ assert(m);
+
+ dbus_error_init(&error);
+
+ if (dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_METHOD_CALL ||
+ dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_SIGNAL)
+ log_debug("Got D-Bus request: %s.%s() on %s",
+ dbus_message_get_interface(message),
+ dbus_message_get_member(message),
+ dbus_message_get_path(message));
+
+ if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected"))
+ shutdown_connection(m, connection);
+ else if (m->running_as == SYSTEMD_SYSTEM &&
+ dbus_message_is_signal(message, "org.freedesktop.systemd1.Agent", "Released")) {
+
+ const char *cgroup;
+
+ if (!dbus_message_get_args(message, &error,
+ DBUS_TYPE_STRING, &cgroup,
+ DBUS_TYPE_INVALID))
+ log_error("Failed to parse Released message: %s", bus_error_message(&error));
+ else
+ cgroup_notify_empty(m, cgroup);
+
+ /* Forward the message to the system bus, so that user
+ * instances are notified as well */
+
+ if (m->system_bus)
+ dbus_connection_send(m->system_bus, message, NULL);
+ }
+
+ dbus_error_free(&error);
+
+ return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
+}
+
+unsigned bus_dispatch(Manager *m) {
+ DBusConnection *c;
+
+ assert(m);
+
+ if (m->queued_message) {
+ /* If we cannot get rid of this message we won't
+ * dispatch any D-Bus messages, so that we won't end
+ * up wanting to queue another message. */
+
+ if (m->queued_message_connection)
+ if (!dbus_connection_send(m->queued_message_connection, m->queued_message, NULL))
+ return 0;
+
+ dbus_message_unref(m->queued_message);
+ m->queued_message = NULL;
+ m->queued_message_connection = NULL;
+ }
+
+ if ((c = set_first(m->bus_connections_for_dispatch))) {
+ if (dbus_connection_dispatch(c) == DBUS_DISPATCH_COMPLETE)
+ set_move_one(m->bus_connections, m->bus_connections_for_dispatch, c);
+
+ return 1;
+ }
+
+ return 0;
+}
+
+static void request_name_pending_cb(DBusPendingCall *pending, void *userdata) {
+ DBusMessage *reply;
+ DBusError error;
+
+ dbus_error_init(&error);
+
+ assert_se(reply = dbus_pending_call_steal_reply(pending));
+
+ switch (dbus_message_get_type(reply)) {
+
+ case DBUS_MESSAGE_TYPE_ERROR:
+
+ assert_se(dbus_set_error_from_message(&error, reply));
+ log_warning("RequestName() failed: %s", bus_error_message(&error));
+ break;
+
+ case DBUS_MESSAGE_TYPE_METHOD_RETURN: {
+ uint32_t r;
+
+ if (!dbus_message_get_args(reply,
+ &error,
+ DBUS_TYPE_UINT32, &r,
+ DBUS_TYPE_INVALID)) {
+ log_error("Failed to parse RequestName() reply: %s", bus_error_message(&error));
+ break;
+ }
+
+ if (r == 1)
+ log_debug("Successfully acquired name.");
+ else
+ log_error("Name already owned.");
+
+ break;
+ }
+
+ default:
+ assert_not_reached("Invalid reply message");
+ }
+
+ dbus_message_unref(reply);
+ dbus_error_free(&error);
+}
+
+static int request_name(Manager *m) {
+ const char *name = "org.freedesktop.systemd1";
+ /* Allow replacing of our name, to ease implementation of
+ * reexecution, where we keep the old connection open until
+ * after the new connection is set up and the name installed
+ * to allow clients to synchronously wait for reexecution to
+ * finish */
+ uint32_t flags = DBUS_NAME_FLAG_ALLOW_REPLACEMENT|DBUS_NAME_FLAG_REPLACE_EXISTING;
+ DBusMessage *message = NULL;
+ DBusPendingCall *pending = NULL;
+
+ if (!(message = dbus_message_new_method_call(
+ DBUS_SERVICE_DBUS,
+ DBUS_PATH_DBUS,
+ DBUS_INTERFACE_DBUS,
+ "RequestName")))
+ goto oom;
+
+ if (!dbus_message_append_args(
+ message,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_UINT32, &flags,
+ DBUS_TYPE_INVALID))
+ goto oom;
+
+ if (!dbus_connection_send_with_reply(m->api_bus, message, &pending, -1))
+ goto oom;
+
+ if (!dbus_pending_call_set_notify(pending, request_name_pending_cb, m, NULL))
+ goto oom;
+
+ dbus_message_unref(message);
+ dbus_pending_call_unref(pending);
+
+ /* We simple ask for the name and don't wait for it. Sooner or
+ * later we'll have it. */
+
+ return 0;
+
+oom:
+ if (pending) {
+ dbus_pending_call_cancel(pending);
+ dbus_pending_call_unref(pending);
+ }
+
+ if (message)
+ dbus_message_unref(message);
+
+ return -ENOMEM;
+}
+
+static void query_name_list_pending_cb(DBusPendingCall *pending, void *userdata) {
+ DBusMessage *reply;
+ DBusError error;
+ Manager *m = userdata;
+
+ assert(m);
+
+ dbus_error_init(&error);
+
+ assert_se(reply = dbus_pending_call_steal_reply(pending));
+
+ switch (dbus_message_get_type(reply)) {
+
+ case DBUS_MESSAGE_TYPE_ERROR:
+
+ assert_se(dbus_set_error_from_message(&error, reply));
+ log_warning("ListNames() failed: %s", bus_error_message(&error));
+ break;
+
+ case DBUS_MESSAGE_TYPE_METHOD_RETURN: {
+ int r;
+ char **l;
+
+ if ((r = bus_parse_strv(reply, &l)) < 0)
+ log_warning("Failed to parse ListNames() reply: %s", strerror(-r));
+ else {
+ char **t;
+
+ STRV_FOREACH(t, l)
+ /* This is a bit hacky, we say the
+ * owner of the name is the name
+ * itself, because we don't want the
+ * extra traffic to figure out the
+ * real owner. */
+ manager_dispatch_bus_name_owner_changed(m, *t, NULL, *t);
+
+ strv_free(l);
+ }
+
+ break;
+ }
+
+ default:
+ assert_not_reached("Invalid reply message");
+ }
+
+ dbus_message_unref(reply);
+ dbus_error_free(&error);
+}
+
+static int query_name_list(Manager *m) {
+ DBusMessage *message = NULL;
+ DBusPendingCall *pending = NULL;
+
+ /* Asks for the currently installed bus names */
+
+ if (!(message = dbus_message_new_method_call(
+ DBUS_SERVICE_DBUS,
+ DBUS_PATH_DBUS,
+ DBUS_INTERFACE_DBUS,
+ "ListNames")))
+ goto oom;
+
+ if (!dbus_connection_send_with_reply(m->api_bus, message, &pending, -1))
+ goto oom;
+
+ if (!dbus_pending_call_set_notify(pending, query_name_list_pending_cb, m, NULL))
+ goto oom;
+
+ dbus_message_unref(message);
+ dbus_pending_call_unref(pending);
+
+ /* We simple ask for the list and don't wait for it. Sooner or
+ * later we'll get it. */
+
+ return 0;
+
+oom:
+ if (pending) {
+ dbus_pending_call_cancel(pending);
+ dbus_pending_call_unref(pending);
+ }
+
+ if (message)
+ dbus_message_unref(message);
+
+ return -ENOMEM;
+}
+
+static int bus_setup_loop(Manager *m, DBusConnection *bus) {
+ assert(m);
+ assert(bus);
+
+ dbus_connection_set_exit_on_disconnect(bus, FALSE);
+
+ if (!dbus_connection_set_watch_functions(bus, bus_add_watch, bus_remove_watch, bus_toggle_watch, m, NULL) ||
+ !dbus_connection_set_timeout_functions(bus, bus_add_timeout, bus_remove_timeout, bus_toggle_timeout, m, NULL))
+ return log_oom();
+
+ if (set_put(m->bus_connections_for_dispatch, bus) < 0)
+ return log_oom();
+
+ dbus_connection_set_dispatch_status_function(bus, bus_dispatch_status, m, NULL);
+ return 0;
+}
+
+static dbus_bool_t allow_only_same_user(DBusConnection *connection, unsigned long uid, void *data) {
+ return uid == 0 || uid == geteuid();
+}
+
+static void bus_new_connection(
+ DBusServer *server,
+ DBusConnection *new_connection,
+ void *data) {
+
+ Manager *m = data;
+
+ assert(m);
+
+ if (set_size(m->bus_connections) >= CONNECTIONS_MAX) {
+ log_error("Too many concurrent connections.");
+ return;
+ }
+
+ dbus_connection_set_unix_user_function(new_connection, allow_only_same_user, NULL, NULL);
+
+ if (bus_setup_loop(m, new_connection) < 0)
+ return;
+
+ if (!dbus_connection_register_object_path(new_connection, "/org/freedesktop/systemd1", &bus_manager_vtable, m) ||
+ !dbus_connection_register_fallback(new_connection, "/org/freedesktop/systemd1/unit", &bus_unit_vtable, m) ||
+ !dbus_connection_register_fallback(new_connection, "/org/freedesktop/systemd1/job", &bus_job_vtable, m) ||
+ !dbus_connection_add_filter(new_connection, private_bus_message_filter, m, NULL)) {
+ log_oom();
+ return;
+ }
+
+ log_debug("Accepted connection on private bus.");
+
+ dbus_connection_ref(new_connection);
+}
+
+static int init_registered_system_bus(Manager *m) {
+ char *id;
+
+ if (!dbus_connection_add_filter(m->system_bus, system_bus_message_filter, m, NULL))
+ return log_oom();
+
+ if (m->running_as != SYSTEMD_SYSTEM) {
+ DBusError error;
+
+ dbus_error_init(&error);
+
+ dbus_bus_add_match(m->system_bus,
+ "type='signal',"
+ "interface='org.freedesktop.systemd1.Agent',"
+ "member='Released',"
+ "path='/org/freedesktop/systemd1/agent'",
+ &error);
+
+ if (dbus_error_is_set(&error)) {
+ log_error("Failed to register match: %s", bus_error_message(&error));
+ dbus_error_free(&error);
+ return -1;
+ }
+ }
+
+ log_debug("Successfully connected to system D-Bus bus %s as %s",
+ strnull((id = dbus_connection_get_server_id(m->system_bus))),
+ strnull(dbus_bus_get_unique_name(m->system_bus)));
+ dbus_free(id);
+
+ return 0;
+}
+
+static int init_registered_api_bus(Manager *m) {
+ int r;
+
+ if (!dbus_connection_register_object_path(m->api_bus, "/org/freedesktop/systemd1", &bus_manager_vtable, m) ||
+ !dbus_connection_register_fallback(m->api_bus, "/org/freedesktop/systemd1/unit", &bus_unit_vtable, m) ||
+ !dbus_connection_register_fallback(m->api_bus, "/org/freedesktop/systemd1/job", &bus_job_vtable, m) ||
+ !dbus_connection_add_filter(m->api_bus, api_bus_message_filter, m, NULL))
+ return log_oom();
+
+ /* Get NameOwnerChange messages */
+ dbus_bus_add_match(m->api_bus,
+ "type='signal',"
+ "sender='"DBUS_SERVICE_DBUS"',"
+ "interface='"DBUS_INTERFACE_DBUS"',"
+ "member='NameOwnerChanged',"
+ "path='"DBUS_PATH_DBUS"'",
+ NULL);
+
+ /* Get activation requests */
+ dbus_bus_add_match(m->api_bus,
+ "type='signal',"
+ "sender='"DBUS_SERVICE_DBUS"',"
+ "interface='org.freedesktop.systemd1.Activator',"
+ "member='ActivationRequest',"
+ "path='"DBUS_PATH_DBUS"'",
+ NULL);
+
+ r = request_name(m);
+ if (r < 0)
+ return r;
+
+ r = query_name_list(m);
+ if (r < 0)
+ return r;
+
+ if (m->running_as == SYSTEMD_USER) {
+ char *id;
+ log_debug("Successfully connected to API D-Bus bus %s as %s",
+ strnull((id = dbus_connection_get_server_id(m->api_bus))),
+ strnull(dbus_bus_get_unique_name(m->api_bus)));
+ dbus_free(id);
+ } else
+ log_debug("Successfully initialized API on the system bus");
+
+ return 0;
+}
+
+static void bus_register_cb(DBusPendingCall *pending, void *userdata) {
+ Manager *m = userdata;
+ DBusConnection **conn;
+ DBusMessage *reply;
+ DBusError error;
+ const char *name;
+ int r = 0;
+
+ dbus_error_init(&error);
+
+ conn = dbus_pending_call_get_data(pending, m->conn_data_slot);
+ assert(conn == &m->system_bus || conn == &m->api_bus);
+
+ reply = dbus_pending_call_steal_reply(pending);
+
+ switch (dbus_message_get_type(reply)) {
+ case DBUS_MESSAGE_TYPE_ERROR:
+ assert_se(dbus_set_error_from_message(&error, reply));
+ log_warning("Failed to register to bus: %s", bus_error_message(&error));
+ r = -1;
+ break;
+ case DBUS_MESSAGE_TYPE_METHOD_RETURN:
+ if (!dbus_message_get_args(reply, &error,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_INVALID)) {
+ log_error("Failed to parse Hello reply: %s", bus_error_message(&error));
+ r = -1;
+ break;
+ }
+
+ log_debug("Received name %s in reply to Hello", name);
+ if (!dbus_bus_set_unique_name(*conn, name)) {
+ log_error("Failed to set unique name");
+ r = -1;
+ break;
+ }
+
+ if (conn == &m->system_bus) {
+ r = init_registered_system_bus(m);
+ if (r == 0 && m->running_as == SYSTEMD_SYSTEM)
+ r = init_registered_api_bus(m);
+ } else
+ r = init_registered_api_bus(m);
+
+ break;
+ default:
+ assert_not_reached("Invalid reply message");
+ }
+
+ dbus_message_unref(reply);
+ dbus_error_free(&error);
+
+ if (r < 0) {
+ if (conn == &m->system_bus) {
+ log_debug("Failed setting up the system bus");
+ bus_done_system(m);
+ } else {
+ log_debug("Failed setting up the API bus");
+ bus_done_api(m);
+ }
+ }
+}
+
+static int manager_bus_async_register(Manager *m, DBusConnection **conn) {
+ DBusMessage *message = NULL;
+ DBusPendingCall *pending = NULL;
+
+ message = dbus_message_new_method_call(DBUS_SERVICE_DBUS,
+ DBUS_PATH_DBUS,
+ DBUS_INTERFACE_DBUS,
+ "Hello");
+ if (!message)
+ goto oom;
+
+ if (!dbus_connection_send_with_reply(*conn, message, &pending, -1))
+ goto oom;
+
+ if (!dbus_pending_call_set_data(pending, m->conn_data_slot, conn, NULL))
+ goto oom;
+
+ if (!dbus_pending_call_set_notify(pending, bus_register_cb, m, NULL))
+ goto oom;
+
+ dbus_message_unref(message);
+ dbus_pending_call_unref(pending);
+
+ return 0;
+oom:
+ if (pending) {
+ dbus_pending_call_cancel(pending);
+ dbus_pending_call_unref(pending);
+ }
+
+ if (message)
+ dbus_message_unref(message);
+
+ return -ENOMEM;
+}
+
+static DBusConnection* manager_bus_connect_private(Manager *m, DBusBusType type) {
+ const char *address;
+ DBusConnection *connection;
+ DBusError error;
+
+ switch (type) {
+ case DBUS_BUS_SYSTEM:
+ address = secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
+ if (!address || !address[0])
+ address = DBUS_SYSTEM_BUS_DEFAULT_ADDRESS;
+ break;
+ case DBUS_BUS_SESSION:
+ address = secure_getenv("DBUS_SESSION_BUS_ADDRESS");
+ if (!address || !address[0])
+ address = DBUS_SESSION_BUS_DEFAULT_ADDRESS;
+ break;
+ default:
+ assert_not_reached("Invalid bus type");
+ }
+
+ dbus_error_init(&error);
+
+ connection = dbus_connection_open_private(address, &error);
+ if (!connection) {
+ log_warning("Failed to open private bus connection: %s", bus_error_message(&error));
+ goto fail;
+ }
+
+ return connection;
+
+fail:
+ dbus_error_free(&error);
+ return NULL;
+}
+
+static int bus_init_system(Manager *m) {
+ int r;
+
+ if (m->system_bus)
+ return 0;
+
+ m->system_bus = manager_bus_connect_private(m, DBUS_BUS_SYSTEM);
+ if (!m->system_bus) {
+ log_debug("Failed to connect to system D-Bus, retrying later");
+ r = 0;
+ goto fail;
+ }
+
+ r = bus_setup_loop(m, m->system_bus);
+ if (r < 0)
+ goto fail;
+
+ r = manager_bus_async_register(m, &m->system_bus);
+ if (r < 0)
+ goto fail;
+
+ return 0;
+fail:
+ bus_done_system(m);
+
+ return r;
+}
+
+static int bus_init_api(Manager *m) {
+ int r;
+
+ if (m->api_bus)
+ return 0;
+
+ if (m->running_as == SYSTEMD_SYSTEM) {
+ m->api_bus = m->system_bus;
+ /* In this mode there is no distinct connection to the API bus,
+ * the API is published on the system bus.
+ * bus_register_cb() is aware of that and will init the API
+ * when the system bus gets registered.
+ * No need to setup anything here. */
+ return 0;
+ }
+
+ m->api_bus = manager_bus_connect_private(m, DBUS_BUS_SESSION);
+ if (!m->api_bus) {
+ log_debug("Failed to connect to API D-Bus, retrying later");
+ r = 0;
+ goto fail;
+ }
+
+ r = bus_setup_loop(m, m->api_bus);
+ if (r < 0)
+ goto fail;
+
+ r = manager_bus_async_register(m, &m->api_bus);
+ if (r < 0)
+ goto fail;
+
+ return 0;
+fail:
+ bus_done_api(m);
+
+ return r;
+}
+
+static int bus_init_private(Manager *m) {
+ DBusError error;
+ int r;
+ static const char *const external_only[] = {
+ "EXTERNAL",
+ NULL
+ };
+
+ assert(m);
+
+ dbus_error_init(&error);
+
+ if (m->private_bus)
+ return 0;
+
+ if (m->running_as == SYSTEMD_SYSTEM) {
+
+ /* We want the private bus only when running as init */
+ if (getpid() != 1)
+ return 0;
+
+ unlink("/run/systemd/private");
+ m->private_bus = dbus_server_listen("unix:path=/run/systemd/private", &error);
+ } else {
+ const char *e;
+ char *p;
+ char *escaped;
+
+ e = secure_getenv("XDG_RUNTIME_DIR");
+ if (!e)
+ return 0;
+
+ if (asprintf(&p, "%s/systemd/private", e) < 0) {
+ r = log_oom();
+ goto fail;
+ }
+
+ mkdir_parents_label(p, 0755);
+ unlink(p);
+ free(p);
+
+ escaped = dbus_address_escape_value(e);
+ if (!escaped) {
+ r = log_oom();
+ goto fail;
+ }
+ if (asprintf(&p, "unix:path=%s/systemd/private", escaped) < 0) {
+ dbus_free(escaped);
+ r = log_oom();
+ goto fail;
+ }
+ dbus_free(escaped);
+
+ m->private_bus = dbus_server_listen(p, &error);
+ free(p);
+ }
+
+ if (!m->private_bus) {
+ log_error("Failed to create private D-Bus server: %s", bus_error_message(&error));
+ r = -EIO;
+ goto fail;
+ }
+
+ if (!dbus_server_set_auth_mechanisms(m->private_bus, (const char**) external_only) ||
+ !dbus_server_set_watch_functions(m->private_bus, bus_add_watch, bus_remove_watch, bus_toggle_watch, m, NULL) ||
+ !dbus_server_set_timeout_functions(m->private_bus, bus_add_timeout, bus_remove_timeout, bus_toggle_timeout, m, NULL)) {
+ r = log_oom();
+ goto fail;
+ }
+
+ dbus_server_set_new_connection_function(m->private_bus, bus_new_connection, m, NULL);
+
+ log_debug("Successfully created private D-Bus server.");
+
+ return 0;
+
+fail:
+ bus_done_private(m);
+ dbus_error_free(&error);
+
+ return r;
+}
+
+int bus_init(Manager *m, bool try_bus_connect) {
+ int r;
+
+ if (set_ensure_allocated(&m->bus_connections, trivial_hash_func, trivial_compare_func) < 0 ||
+ set_ensure_allocated(&m->bus_connections_for_dispatch, trivial_hash_func, trivial_compare_func) < 0)
+ goto oom;
+
+ if (m->name_data_slot < 0)
+ if (!dbus_pending_call_allocate_data_slot(&m->name_data_slot))
+ goto oom;
+
+ if (m->conn_data_slot < 0)
+ if (!dbus_pending_call_allocate_data_slot(&m->conn_data_slot))
+ goto oom;
+
+ if (m->subscribed_data_slot < 0)
+ if (!dbus_connection_allocate_data_slot(&m->subscribed_data_slot))
+ goto oom;
+
+ if (try_bus_connect) {
+ if ((r = bus_init_system(m)) < 0 ||
+ (r = bus_init_api(m)) < 0)
+ return r;
+ }
+
+ if ((r = bus_init_private(m)) < 0)
+ return r;
+
+ return 0;
+oom:
+ return log_oom();
+}
+
+static void shutdown_connection(Manager *m, DBusConnection *c) {
+ Set *s;
+ Job *j;
+ Iterator i;
+
+ HASHMAP_FOREACH(j, m->jobs, i) {
+ JobBusClient *cl, *nextcl;
+ LIST_FOREACH_SAFE(client, cl, nextcl, j->bus_client_list) {
+ if (cl->bus == c) {
+ LIST_REMOVE(JobBusClient, client, j->bus_client_list, cl);
+ free(cl);
+ }
+ }
+ }
+
+ set_remove(m->bus_connections, c);
+ set_remove(m->bus_connections_for_dispatch, c);
+
+ if ((s = BUS_CONNECTION_SUBSCRIBED(m, c))) {
+ char *t;
+
+ while ((t = set_steal_first(s)))
+ free(t);
+
+ set_free(s);
+ }
+
+ if (m->queued_message_connection == c) {
+ m->queued_message_connection = NULL;
+
+ if (m->queued_message) {
+ dbus_message_unref(m->queued_message);
+ m->queued_message = NULL;
+ }
+ }
+
+ dbus_connection_set_dispatch_status_function(c, NULL, NULL, NULL);
+ /* system manager cannot afford to block on DBus */
+ if (m->running_as != SYSTEMD_SYSTEM)
+ dbus_connection_flush(c);
+ dbus_connection_close(c);
+ dbus_connection_unref(c);
+}
+
+static void bus_done_api(Manager *m) {
+ if (!m->api_bus)
+ return;
+
+ if (m->running_as == SYSTEMD_USER)
+ shutdown_connection(m, m->api_bus);
+
+ m->api_bus = NULL;
+
+ if (m->queued_message) {
+ dbus_message_unref(m->queued_message);
+ m->queued_message = NULL;
+ }
+}
+
+static void bus_done_system(Manager *m) {
+ if (!m->system_bus)
+ return;
+
+ if (m->running_as == SYSTEMD_SYSTEM)
+ bus_done_api(m);
+
+ shutdown_connection(m, m->system_bus);
+ m->system_bus = NULL;
+}
+
+static void bus_done_private(Manager *m) {
+ if (!m->private_bus)
+ return;
+
+ dbus_server_disconnect(m->private_bus);
+ dbus_server_unref(m->private_bus);
+ m->private_bus = NULL;
+}
+
+void bus_done(Manager *m) {
+ DBusConnection *c;
+
+ bus_done_api(m);
+ bus_done_system(m);
+ bus_done_private(m);
+
+ while ((c = set_steal_first(m->bus_connections)))
+ shutdown_connection(m, c);
+
+ while ((c = set_steal_first(m->bus_connections_for_dispatch)))
+ shutdown_connection(m, c);
+
+ set_free(m->bus_connections);
+ set_free(m->bus_connections_for_dispatch);
+
+ if (m->name_data_slot >= 0)
+ dbus_pending_call_free_data_slot(&m->name_data_slot);
+
+ if (m->conn_data_slot >= 0)
+ dbus_pending_call_free_data_slot(&m->conn_data_slot);
+
+ if (m->subscribed_data_slot >= 0)
+ dbus_connection_free_data_slot(&m->subscribed_data_slot);
+}
+
+static void query_pid_pending_cb(DBusPendingCall *pending, void *userdata) {
+ Manager *m = userdata;
+ DBusMessage *reply;
+ DBusError error;
+ const char *name;
+
+ dbus_error_init(&error);
+
+ assert_se(name = BUS_PENDING_CALL_NAME(m, pending));
+ assert_se(reply = dbus_pending_call_steal_reply(pending));
+
+ switch (dbus_message_get_type(reply)) {
+
+ case DBUS_MESSAGE_TYPE_ERROR:
+
+ assert_se(dbus_set_error_from_message(&error, reply));
+ log_warning("GetConnectionUnixProcessID() failed: %s", bus_error_message(&error));
+ break;
+
+ case DBUS_MESSAGE_TYPE_METHOD_RETURN: {
+ uint32_t r;
+
+ if (!dbus_message_get_args(reply,
+ &error,
+ DBUS_TYPE_UINT32, &r,
+ DBUS_TYPE_INVALID)) {
+ log_error("Failed to parse GetConnectionUnixProcessID() reply: %s", bus_error_message(&error));
+ break;
+ }
+
+ manager_dispatch_bus_query_pid_done(m, name, (pid_t) r);
+ break;
+ }
+
+ default:
+ assert_not_reached("Invalid reply message");
+ }
+
+ dbus_message_unref(reply);
+ dbus_error_free(&error);
+}
+
+int bus_query_pid(Manager *m, const char *name) {
+ DBusMessage *message = NULL;
+ DBusPendingCall *pending = NULL;
+ char *n = NULL;
+
+ assert(m);
+ assert(name);
+
+ if (!(message = dbus_message_new_method_call(
+ DBUS_SERVICE_DBUS,
+ DBUS_PATH_DBUS,
+ DBUS_INTERFACE_DBUS,
+ "GetConnectionUnixProcessID")))
+ goto oom;
+
+ if (!(dbus_message_append_args(
+ message,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_INVALID)))
+ goto oom;
+
+ if (!dbus_connection_send_with_reply(m->api_bus, message, &pending, -1))
+ goto oom;
+
+ if (!(n = strdup(name)))
+ goto oom;
+
+ if (!dbus_pending_call_set_data(pending, m->name_data_slot, n, free))
+ goto oom;
+
+ n = NULL;
+
+ if (!dbus_pending_call_set_notify(pending, query_pid_pending_cb, m, NULL))
+ goto oom;
+
+ dbus_message_unref(message);
+ dbus_pending_call_unref(pending);
+
+ return 0;
+
+oom:
+ free(n);
+
+ if (pending) {
+ dbus_pending_call_cancel(pending);
+ dbus_pending_call_unref(pending);
+ }
+
+ if (message)
+ dbus_message_unref(message);
+
+ return -ENOMEM;
+}
+
+int bus_broadcast(Manager *m, DBusMessage *message) {
+ bool oom = false;
+ Iterator i;
+ DBusConnection *c;
+
+ assert(m);
+ assert(message);
+
+ SET_FOREACH(c, m->bus_connections_for_dispatch, i)
+ if (c != m->system_bus || m->running_as == SYSTEMD_SYSTEM)
+ oom = !dbus_connection_send(c, message, NULL);
+
+ SET_FOREACH(c, m->bus_connections, i)
+ if (c != m->system_bus || m->running_as == SYSTEMD_SYSTEM)
+ oom = !dbus_connection_send(c, message, NULL);
+
+ return oom ? -ENOMEM : 0;
+}
+
+bool bus_has_subscriber(Manager *m) {
+ Iterator i;
+ DBusConnection *c;
+
+ assert(m);
+
+ SET_FOREACH(c, m->bus_connections_for_dispatch, i)
+ if (bus_connection_has_subscriber(m, c))
+ return true;
+
+ SET_FOREACH(c, m->bus_connections, i)
+ if (bus_connection_has_subscriber(m, c))
+ return true;
+
+ return false;
+}
+
+bool bus_connection_has_subscriber(Manager *m, DBusConnection *c) {
+ assert(m);
+ assert(c);
+
+ return !set_isempty(BUS_CONNECTION_SUBSCRIBED(m, c));
+}
+
+int bus_fdset_add_all(Manager *m, FDSet *fds) {
+ Iterator i;
+ DBusConnection *c;
+
+ assert(m);
+ assert(fds);
+
+ /* When we are about to reexecute we add all D-Bus fds to the
+ * set to pass over to the newly executed systemd. They won't
+ * be used there however, except that they are closed at the
+ * very end of deserialization, those making it possible for
+ * clients to synchronously wait for systemd to reexec by
+ * simply waiting for disconnection */
+
+ SET_FOREACH(c, m->bus_connections_for_dispatch, i) {
+ int fd;
+
+ if (dbus_connection_get_unix_fd(c, &fd)) {
+ fd = fdset_put_dup(fds, fd);
+
+ if (fd < 0)
+ return fd;
+ }
+ }
+
+ SET_FOREACH(c, m->bus_connections, i) {
+ int fd;
+
+ if (dbus_connection_get_unix_fd(c, &fd)) {
+ fd = fdset_put_dup(fds, fd);
+
+ if (fd < 0)
+ return fd;
+ }
+ }
+
+ return 0;
+}
+
+void bus_broadcast_finished(
+ Manager *m,
+ usec_t firmware_usec,
+ usec_t loader_usec,
+ usec_t kernel_usec,
+ usec_t initrd_usec,
+ usec_t userspace_usec,
+ usec_t total_usec) {
+
+ DBusMessage *message;
+
+ assert(m);
+
+ message = dbus_message_new_signal("/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager", "StartupFinished");
+ if (!message) {
+ log_oom();
+ return;
+ }
+
+ assert_cc(sizeof(usec_t) == sizeof(uint64_t));
+ if (!dbus_message_append_args(message,
+ DBUS_TYPE_UINT64, &firmware_usec,
+ DBUS_TYPE_UINT64, &loader_usec,
+ DBUS_TYPE_UINT64, &kernel_usec,
+ DBUS_TYPE_UINT64, &initrd_usec,
+ DBUS_TYPE_UINT64, &userspace_usec,
+ DBUS_TYPE_UINT64, &total_usec,
+ DBUS_TYPE_INVALID)) {
+ log_oom();
+ goto finish;
+ }
+
+
+ if (bus_broadcast(m, message) < 0) {
+ log_oom();
+ goto finish;
+ }
+
+finish:
+ if (message)
+ dbus_message_unref(message);
+}
diff --git a/src/core/dbus.h b/src/core/dbus.h
new file mode 100644
index 0000000000..c7a058e198
--- /dev/null
+++ b/src/core/dbus.h
@@ -0,0 +1,50 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <dbus/dbus.h>
+
+#include "manager.h"
+
+int bus_init(Manager *m, bool try_bus_connect);
+void bus_done(Manager *m);
+
+unsigned bus_dispatch(Manager *m);
+
+void bus_watch_event(Manager *m, Watch *w, int events);
+void bus_timeout_event(Manager *m, Watch *w, int events);
+
+int bus_query_pid(Manager *m, const char *name);
+
+int bus_broadcast(Manager *m, DBusMessage *message);
+
+bool bus_has_subscriber(Manager *m);
+bool bus_connection_has_subscriber(Manager *m, DBusConnection *c);
+
+int bus_fdset_add_all(Manager *m, FDSet *fds);
+
+void bus_broadcast_finished(Manager *m, usec_t firmware_usec, usec_t loader_usec, usec_t kernel_usec, usec_t initrd_usec, usec_t userspace_usec, usec_t total_usec);
+
+#define BUS_CONNECTION_SUBSCRIBED(m, c) dbus_connection_get_data((c), (m)->subscribed_data_slot)
+#define BUS_PENDING_CALL_NAME(m, p) dbus_pending_call_get_data((p), (m)->name_data_slot)
+
+extern const char * const bus_interface_table[];
diff --git a/src/core/device.c b/src/core/device.c
new file mode 100644
index 0000000000..9fca82ab16
--- /dev/null
+++ b/src/core/device.c
@@ -0,0 +1,654 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <sys/epoll.h>
+#include <libudev.h>
+
+#include "unit.h"
+#include "device.h"
+#include "strv.h"
+#include "log.h"
+#include "unit-name.h"
+#include "dbus-device.h"
+#include "def.h"
+#include "path-util.h"
+
+static const UnitActiveState state_translation_table[_DEVICE_STATE_MAX] = {
+ [DEVICE_DEAD] = UNIT_INACTIVE,
+ [DEVICE_PLUGGED] = UNIT_ACTIVE
+};
+
+static void device_unset_sysfs(Device *d) {
+ Device *first;
+
+ assert(d);
+
+ if (!d->sysfs)
+ return;
+
+ /* Remove this unit from the chain of devices which share the
+ * same sysfs path. */
+ first = hashmap_get(UNIT(d)->manager->devices_by_sysfs, d->sysfs);
+ LIST_REMOVE(Device, same_sysfs, first, d);
+
+ if (first)
+ hashmap_remove_and_replace(UNIT(d)->manager->devices_by_sysfs, d->sysfs, first->sysfs, first);
+ else
+ hashmap_remove(UNIT(d)->manager->devices_by_sysfs, d->sysfs);
+
+ free(d->sysfs);
+ d->sysfs = NULL;
+}
+
+static void device_init(Unit *u) {
+ Device *d = DEVICE(u);
+
+ assert(d);
+ assert(UNIT(d)->load_state == UNIT_STUB);
+
+ /* In contrast to all other unit types we timeout jobs waiting
+ * for devices by default. This is because they otherwise wait
+ * indefinitely for plugged in devices, something which cannot
+ * happen for the other units since their operations time out
+ * anyway. */
+ UNIT(d)->job_timeout = DEFAULT_TIMEOUT_USEC;
+
+ UNIT(d)->ignore_on_isolate = true;
+ UNIT(d)->ignore_on_snapshot = true;
+}
+
+static void device_done(Unit *u) {
+ Device *d = DEVICE(u);
+
+ assert(d);
+
+ device_unset_sysfs(d);
+}
+
+static void device_set_state(Device *d, DeviceState state) {
+ DeviceState old_state;
+ assert(d);
+
+ old_state = d->state;
+ d->state = state;
+
+ if (state != old_state)
+ log_debug_unit(UNIT(d)->id,
+ "%s changed %s -> %s", UNIT(d)->id,
+ device_state_to_string(old_state),
+ device_state_to_string(state));
+
+ unit_notify(UNIT(d), state_translation_table[old_state], state_translation_table[state], true);
+}
+
+static int device_coldplug(Unit *u) {
+ Device *d = DEVICE(u);
+
+ assert(d);
+ assert(d->state == DEVICE_DEAD);
+
+ if (d->sysfs)
+ device_set_state(d, DEVICE_PLUGGED);
+
+ return 0;
+}
+
+static void device_dump(Unit *u, FILE *f, const char *prefix) {
+ Device *d = DEVICE(u);
+
+ assert(d);
+
+ fprintf(f,
+ "%sDevice State: %s\n"
+ "%sSysfs Path: %s\n",
+ prefix, device_state_to_string(d->state),
+ prefix, strna(d->sysfs));
+}
+
+_pure_ static UnitActiveState device_active_state(Unit *u) {
+ assert(u);
+
+ return state_translation_table[DEVICE(u)->state];
+}
+
+_pure_ static const char *device_sub_state_to_string(Unit *u) {
+ assert(u);
+
+ return device_state_to_string(DEVICE(u)->state);
+}
+
+static int device_add_escaped_name(Unit *u, const char *dn) {
+ char *e;
+ int r;
+
+ assert(u);
+ assert(dn);
+ assert(dn[0] == '/');
+
+ e = unit_name_from_path(dn, ".device");
+ if (!e)
+ return -ENOMEM;
+
+ r = unit_add_name(u, e);
+ free(e);
+
+ if (r < 0 && r != -EEXIST)
+ return r;
+
+ return 0;
+}
+
+static int device_find_escape_name(Manager *m, const char *dn, Unit **_u) {
+ char *e;
+ Unit *u;
+
+ assert(m);
+ assert(dn);
+ assert(dn[0] == '/');
+ assert(_u);
+
+ e = unit_name_from_path(dn, ".device");
+ if (!e)
+ return -ENOMEM;
+
+ u = manager_get_unit(m, e);
+ free(e);
+
+ if (u) {
+ *_u = u;
+ return 1;
+ }
+
+ return 0;
+}
+
+static int device_update_unit(Manager *m, struct udev_device *dev, const char *path, bool main) {
+ const char *sysfs, *model;
+ Unit *u = NULL;
+ int r;
+ bool delete;
+
+ assert(m);
+
+ if (!(sysfs = udev_device_get_syspath(dev)))
+ return -ENOMEM;
+
+ if ((r = device_find_escape_name(m, path, &u)) < 0)
+ return r;
+
+ if (u && DEVICE(u)->sysfs && !path_equal(DEVICE(u)->sysfs, sysfs))
+ return -EEXIST;
+
+ if (!u) {
+ delete = true;
+
+ u = unit_new(m, sizeof(Device));
+ if (!u)
+ return -ENOMEM;
+
+ r = device_add_escaped_name(u, path);
+ if (r < 0)
+ goto fail;
+
+ unit_add_to_load_queue(u);
+ } else
+ delete = false;
+
+ /* If this was created via some dependency and has not
+ * actually been seen yet ->sysfs will not be
+ * initialized. Hence initialize it if necessary. */
+
+ if (!DEVICE(u)->sysfs) {
+ Device *first;
+
+ if (!(DEVICE(u)->sysfs = strdup(sysfs))) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ if (!m->devices_by_sysfs)
+ if (!(m->devices_by_sysfs = hashmap_new(string_hash_func, string_compare_func))) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ first = hashmap_get(m->devices_by_sysfs, sysfs);
+ LIST_PREPEND(Device, same_sysfs, first, DEVICE(u));
+
+ if ((r = hashmap_replace(m->devices_by_sysfs, DEVICE(u)->sysfs, first)) < 0)
+ goto fail;
+ }
+
+ if ((model = udev_device_get_property_value(dev, "ID_MODEL_FROM_DATABASE")) ||
+ (model = udev_device_get_property_value(dev, "ID_MODEL"))) {
+ if ((r = unit_set_description(u, model)) < 0)
+ goto fail;
+ } else
+ if ((r = unit_set_description(u, path)) < 0)
+ goto fail;
+
+ if (main) {
+ /* The additional systemd udev properties we only
+ * interpret for the main object */
+ const char *wants, *alias;
+
+ alias = udev_device_get_property_value(dev, "SYSTEMD_ALIAS");
+ if (alias) {
+ char *state, *w;
+ size_t l;
+
+ FOREACH_WORD_QUOTED(w, l, alias, state) {
+ char *e;
+
+ e = strndup(w, l);
+ if (!e) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ if (!is_path(e)) {
+ log_warning("SYSTEMD_ALIAS for %s is not a path, ignoring: %s", sysfs, e);
+ free(e);
+ } else {
+ device_update_unit(m, dev, e, false);
+ free(e);
+ }
+ }
+ }
+
+ wants = udev_device_get_property_value(dev, "SYSTEMD_WANTS");
+ if (wants) {
+ char *state, *w;
+ size_t l;
+
+ FOREACH_WORD_QUOTED(w, l, wants, state) {
+ char *e, *n;
+
+ e = strndup(w, l);
+ if (!e) {
+ r = -ENOMEM;
+ goto fail;
+ }
+ n = unit_name_mangle(e);
+ if (!n) {
+ r = -ENOMEM;
+ goto fail;
+ }
+ free(e);
+
+ r = unit_add_dependency_by_name(u, UNIT_WANTS, n, NULL, true);
+ free(n);
+ if (r < 0)
+ goto fail;
+ }
+ }
+ }
+
+ unit_add_to_dbus_queue(u);
+ return 0;
+
+fail:
+ log_warning("Failed to load device unit: %s", strerror(-r));
+
+ if (delete && u)
+ unit_free(u);
+
+ return r;
+}
+
+static int device_process_new_device(Manager *m, struct udev_device *dev, bool update_state) {
+ const char *sysfs, *dn;
+ struct udev_list_entry *item = NULL, *first = NULL;
+ int r;
+
+ assert(m);
+
+ if (!(sysfs = udev_device_get_syspath(dev)))
+ return -ENOMEM;
+
+ /* Add the main unit named after the sysfs path */
+ r = device_update_unit(m, dev, sysfs, true);
+ if (r < 0)
+ return r;
+
+ /* Add an additional unit for the device node */
+ if ((dn = udev_device_get_devnode(dev)))
+ device_update_unit(m, dev, dn, false);
+
+ /* Add additional units for all symlinks */
+ first = udev_device_get_devlinks_list_entry(dev);
+ udev_list_entry_foreach(item, first) {
+ const char *p;
+ struct stat st;
+
+ /* Don't bother with the /dev/block links */
+ p = udev_list_entry_get_name(item);
+
+ if (path_startswith(p, "/dev/block/") ||
+ path_startswith(p, "/dev/char/"))
+ continue;
+
+ /* Verify that the symlink in the FS actually belongs
+ * to this device. This is useful to deal with
+ * conflicting devices, e.g. when two disks want the
+ * same /dev/disk/by-label/xxx link because they have
+ * the same label. We want to make sure that the same
+ * device that won the symlink wins in systemd, so we
+ * check the device node major/minor*/
+ if (stat(p, &st) >= 0)
+ if ((!S_ISBLK(st.st_mode) && !S_ISCHR(st.st_mode)) ||
+ st.st_rdev != udev_device_get_devnum(dev))
+ continue;
+
+ device_update_unit(m, dev, p, false);
+ }
+
+ if (update_state) {
+ Device *d, *l;
+
+ manager_dispatch_load_queue(m);
+
+ l = hashmap_get(m->devices_by_sysfs, sysfs);
+ LIST_FOREACH(same_sysfs, d, l)
+ device_set_state(d, DEVICE_PLUGGED);
+ }
+
+ return 0;
+}
+
+static int device_process_path(Manager *m, const char *path, bool update_state) {
+ int r;
+ struct udev_device *dev;
+
+ assert(m);
+ assert(path);
+
+ if (!(dev = udev_device_new_from_syspath(m->udev, path))) {
+ log_warning("Failed to get udev device object from udev for path %s.", path);
+ return -ENOMEM;
+ }
+
+ r = device_process_new_device(m, dev, update_state);
+ udev_device_unref(dev);
+ return r;
+}
+
+static int device_process_removed_device(Manager *m, struct udev_device *dev) {
+ const char *sysfs;
+ Device *d;
+
+ assert(m);
+ assert(dev);
+
+ if (!(sysfs = udev_device_get_syspath(dev)))
+ return -ENOMEM;
+
+ /* Remove all units of this sysfs path */
+ while ((d = hashmap_get(m->devices_by_sysfs, sysfs))) {
+ device_unset_sysfs(d);
+ device_set_state(d, DEVICE_DEAD);
+ }
+
+ return 0;
+}
+
+static Unit *device_following(Unit *u) {
+ Device *d = DEVICE(u);
+ Device *other, *first = NULL;
+
+ assert(d);
+
+ if (startswith(u->id, "sys-"))
+ return NULL;
+
+ /* Make everybody follow the unit that's named after the sysfs path */
+ for (other = d->same_sysfs_next; other; other = other->same_sysfs_next)
+ if (startswith(UNIT(other)->id, "sys-"))
+ return UNIT(other);
+
+ for (other = d->same_sysfs_prev; other; other = other->same_sysfs_prev) {
+ if (startswith(UNIT(other)->id, "sys-"))
+ return UNIT(other);
+
+ first = other;
+ }
+
+ return UNIT(first);
+}
+
+static int device_following_set(Unit *u, Set **_s) {
+ Device *d = DEVICE(u);
+ Device *other;
+ Set *s;
+ int r;
+
+ assert(d);
+ assert(_s);
+
+ if (!d->same_sysfs_prev && !d->same_sysfs_next) {
+ *_s = NULL;
+ return 0;
+ }
+
+ if (!(s = set_new(NULL, NULL)))
+ return -ENOMEM;
+
+ for (other = d->same_sysfs_next; other; other = other->same_sysfs_next)
+ if ((r = set_put(s, other)) < 0)
+ goto fail;
+
+ for (other = d->same_sysfs_prev; other; other = other->same_sysfs_prev)
+ if ((r = set_put(s, other)) < 0)
+ goto fail;
+
+ *_s = s;
+ return 1;
+
+fail:
+ set_free(s);
+ return r;
+}
+
+static void device_shutdown(Manager *m) {
+ assert(m);
+
+ if (m->udev_monitor) {
+ udev_monitor_unref(m->udev_monitor);
+ m->udev_monitor = NULL;
+ }
+
+ if (m->udev) {
+ udev_unref(m->udev);
+ m->udev = NULL;
+ }
+
+ hashmap_free(m->devices_by_sysfs);
+ m->devices_by_sysfs = NULL;
+}
+
+static int device_enumerate(Manager *m) {
+ int r;
+ struct udev_enumerate *e = NULL;
+ struct udev_list_entry *item = NULL, *first = NULL;
+
+ assert(m);
+
+ if (!m->udev) {
+ struct epoll_event ev;
+
+ if (!(m->udev = udev_new()))
+ return -ENOMEM;
+
+ if (!(m->udev_monitor = udev_monitor_new_from_netlink(m->udev, "udev"))) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ /* This will fail if we are unprivileged, but that
+ * should not matter much, as user instances won't run
+ * during boot. */
+ udev_monitor_set_receive_buffer_size(m->udev_monitor, 128*1024*1024);
+
+ if (udev_monitor_filter_add_match_tag(m->udev_monitor, "systemd") < 0) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ if (udev_monitor_enable_receiving(m->udev_monitor) < 0) {
+ r = -EIO;
+ goto fail;
+ }
+
+ m->udev_watch.type = WATCH_UDEV;
+ m->udev_watch.fd = udev_monitor_get_fd(m->udev_monitor);
+
+ zero(ev);
+ ev.events = EPOLLIN;
+ ev.data.ptr = &m->udev_watch;
+
+ if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->udev_watch.fd, &ev) < 0)
+ return -errno;
+ }
+
+ if (!(e = udev_enumerate_new(m->udev))) {
+ r = -ENOMEM;
+ goto fail;
+ }
+ if (udev_enumerate_add_match_tag(e, "systemd") < 0) {
+ r = -EIO;
+ goto fail;
+ }
+
+ if (udev_enumerate_scan_devices(e) < 0) {
+ r = -EIO;
+ goto fail;
+ }
+
+ first = udev_enumerate_get_list_entry(e);
+ udev_list_entry_foreach(item, first)
+ device_process_path(m, udev_list_entry_get_name(item), false);
+
+ udev_enumerate_unref(e);
+ return 0;
+
+fail:
+ if (e)
+ udev_enumerate_unref(e);
+
+ device_shutdown(m);
+ return r;
+}
+
+void device_fd_event(Manager *m, int events) {
+ struct udev_device *dev;
+ int r;
+ const char *action, *ready;
+
+ assert(m);
+
+ if (events != EPOLLIN) {
+ static RATELIMIT_DEFINE(limit, 10*USEC_PER_SEC, 5);
+
+ if (!ratelimit_test(&limit))
+ log_error("Failed to get udev event: %m");
+ if (!(events & EPOLLIN))
+ return;
+ }
+
+ if (!(dev = udev_monitor_receive_device(m->udev_monitor))) {
+ /*
+ * libudev might filter-out devices which pass the bloom filter,
+ * so getting NULL here is not necessarily an error
+ */
+ return;
+ }
+
+ if (!(action = udev_device_get_action(dev))) {
+ log_error("Failed to get udev action string.");
+ goto fail;
+ }
+
+ ready = udev_device_get_property_value(dev, "SYSTEMD_READY");
+
+ if (streq(action, "remove") || (ready && parse_boolean(ready) == 0)) {
+ if ((r = device_process_removed_device(m, dev)) < 0) {
+ log_error("Failed to process udev device event: %s", strerror(-r));
+ goto fail;
+ }
+ } else {
+ if ((r = device_process_new_device(m, dev, true)) < 0) {
+ log_error("Failed to process udev device event: %s", strerror(-r));
+ goto fail;
+ }
+ }
+
+fail:
+ udev_device_unref(dev);
+}
+
+static const char* const device_state_table[_DEVICE_STATE_MAX] = {
+ [DEVICE_DEAD] = "dead",
+ [DEVICE_PLUGGED] = "plugged"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(device_state, DeviceState);
+
+const UnitVTable device_vtable = {
+ .object_size = sizeof(Device),
+ .sections =
+ "Unit\0"
+ "Device\0"
+ "Install\0",
+
+ .no_instances = true,
+
+ .init = device_init,
+
+ .load = unit_load_fragment_and_dropin_optional,
+ .done = device_done,
+ .coldplug = device_coldplug,
+
+ .dump = device_dump,
+
+ .active_state = device_active_state,
+ .sub_state_to_string = device_sub_state_to_string,
+
+ .bus_interface = "org.freedesktop.systemd1.Device",
+ .bus_message_handler = bus_device_message_handler,
+ .bus_invalidating_properties = bus_device_invalidating_properties,
+
+ .following = device_following,
+ .following_set = device_following_set,
+
+ .enumerate = device_enumerate,
+ .shutdown = device_shutdown,
+
+ .status_message_formats = {
+ .starting_stopping = {
+ [0] = "Expecting device %s...",
+ },
+ .finished_start_job = {
+ [JOB_DONE] = "Found device %s.",
+ [JOB_TIMEOUT] = "Timed out waiting for device %s.",
+ },
+ },
+};
diff --git a/src/core/device.h b/src/core/device.h
new file mode 100644
index 0000000000..41e8de9703
--- /dev/null
+++ b/src/core/device.h
@@ -0,0 +1,56 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+typedef struct Device Device;
+
+#include "unit.h"
+
+/* We simply watch devices, we cannot plug/unplug them. That
+ * simplifies the state engine greatly */
+typedef enum DeviceState {
+ DEVICE_DEAD,
+ DEVICE_PLUGGED,
+ _DEVICE_STATE_MAX,
+ _DEVICE_STATE_INVALID = -1
+} DeviceState;
+
+struct Device {
+ Unit meta;
+
+ char *sysfs;
+
+ /* In order to be able to distinguish dependencies on
+ different device nodes we might end up creating multiple
+ devices for the same sysfs path. We chain them up here. */
+
+ LIST_FIELDS(struct Device, same_sysfs);
+
+ DeviceState state;
+};
+
+extern const UnitVTable device_vtable;
+
+void device_fd_event(Manager *m, int events);
+
+const char* device_state_to_string(DeviceState i) _const_;
+DeviceState device_state_from_string(const char *s) _pure_;
diff --git a/src/core/execute.c b/src/core/execute.c
new file mode 100644
index 0000000000..3959ef9623
--- /dev/null
+++ b/src/core/execute.c
@@ -0,0 +1,2254 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <string.h>
+#include <signal.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <sys/prctl.h>
+#include <linux/sched.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <grp.h>
+#include <pwd.h>
+#include <sys/mount.h>
+#include <linux/fs.h>
+#include <linux/oom.h>
+#include <sys/poll.h>
+#include <linux/seccomp-bpf.h>
+#include <glob.h>
+#include <libgen.h>
+
+#ifdef HAVE_PAM
+#include <security/pam_appl.h>
+#endif
+
+#include "execute.h"
+#include "strv.h"
+#include "macro.h"
+#include "capability.h"
+#include "util.h"
+#include "log.h"
+#include "sd-messages.h"
+#include "ioprio.h"
+#include "securebits.h"
+#include "cgroup.h"
+#include "namespace.h"
+#include "tcpwrap.h"
+#include "exit-status.h"
+#include "missing.h"
+#include "utmp-wtmp.h"
+#include "def.h"
+#include "loopback-setup.h"
+#include "path-util.h"
+#include "syscall-list.h"
+#include "env-util.h"
+#include "fileio.h"
+
+#define IDLE_TIMEOUT_USEC (5*USEC_PER_SEC)
+
+/* This assumes there is a 'tty' group */
+#define TTY_MODE 0620
+
+static int shift_fds(int fds[], unsigned n_fds) {
+ int start, restart_from;
+
+ if (n_fds <= 0)
+ return 0;
+
+ /* Modifies the fds array! (sorts it) */
+
+ assert(fds);
+
+ start = 0;
+ for (;;) {
+ int i;
+
+ restart_from = -1;
+
+ for (i = start; i < (int) n_fds; i++) {
+ int nfd;
+
+ /* Already at right index? */
+ if (fds[i] == i+3)
+ continue;
+
+ if ((nfd = fcntl(fds[i], F_DUPFD, i+3)) < 0)
+ return -errno;
+
+ close_nointr_nofail(fds[i]);
+ fds[i] = nfd;
+
+ /* Hmm, the fd we wanted isn't free? Then
+ * let's remember that and try again from here*/
+ if (nfd != i+3 && restart_from < 0)
+ restart_from = i;
+ }
+
+ if (restart_from < 0)
+ break;
+
+ start = restart_from;
+ }
+
+ return 0;
+}
+
+static int flags_fds(const int fds[], unsigned n_fds, bool nonblock) {
+ unsigned i;
+ int r;
+
+ if (n_fds <= 0)
+ return 0;
+
+ assert(fds);
+
+ /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags */
+
+ for (i = 0; i < n_fds; i++) {
+
+ if ((r = fd_nonblock(fds[i], nonblock)) < 0)
+ return r;
+
+ /* We unconditionally drop FD_CLOEXEC from the fds,
+ * since after all we want to pass these fds to our
+ * children */
+
+ if ((r = fd_cloexec(fds[i], false)) < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+_pure_ static const char *tty_path(const ExecContext *context) {
+ assert(context);
+
+ if (context->tty_path)
+ return context->tty_path;
+
+ return "/dev/console";
+}
+
+void exec_context_tty_reset(const ExecContext *context) {
+ assert(context);
+
+ if (context->tty_vhangup)
+ terminal_vhangup(tty_path(context));
+
+ if (context->tty_reset)
+ reset_terminal(tty_path(context));
+
+ if (context->tty_vt_disallocate && context->tty_path)
+ vt_disallocate(context->tty_path);
+}
+
+static bool is_terminal_output(ExecOutput o) {
+ return
+ o == EXEC_OUTPUT_TTY ||
+ o == EXEC_OUTPUT_SYSLOG_AND_CONSOLE ||
+ o == EXEC_OUTPUT_KMSG_AND_CONSOLE ||
+ o == EXEC_OUTPUT_JOURNAL_AND_CONSOLE;
+}
+
+void exec_context_serialize(const ExecContext *context, Unit *u, FILE *f) {
+ assert(context);
+ assert(u);
+ assert(f);
+
+ if (context->tmp_dir)
+ unit_serialize_item(u, f, "tmp-dir", context->tmp_dir);
+
+ if (context->var_tmp_dir)
+ unit_serialize_item(u, f, "var-tmp-dir", context->var_tmp_dir);
+}
+
+static int open_null_as(int flags, int nfd) {
+ int fd, r;
+
+ assert(nfd >= 0);
+
+ if ((fd = open("/dev/null", flags|O_NOCTTY)) < 0)
+ return -errno;
+
+ if (fd != nfd) {
+ r = dup2(fd, nfd) < 0 ? -errno : nfd;
+ close_nointr_nofail(fd);
+ } else
+ r = nfd;
+
+ return r;
+}
+
+static int connect_logger_as(const ExecContext *context, ExecOutput output, const char *ident, const char *unit_id, int nfd) {
+ int fd, r;
+ union sockaddr_union sa = {
+ .un.sun_family = AF_UNIX,
+ .un.sun_path = "/run/systemd/journal/stdout",
+ };
+
+ assert(context);
+ assert(output < _EXEC_OUTPUT_MAX);
+ assert(ident);
+ assert(nfd >= 0);
+
+ fd = socket(AF_UNIX, SOCK_STREAM, 0);
+ if (fd < 0)
+ return -errno;
+
+ r = connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + strlen(sa.un.sun_path));
+ if (r < 0) {
+ close_nointr_nofail(fd);
+ return -errno;
+ }
+
+ if (shutdown(fd, SHUT_RD) < 0) {
+ close_nointr_nofail(fd);
+ return -errno;
+ }
+
+ dprintf(fd,
+ "%s\n"
+ "%s\n"
+ "%i\n"
+ "%i\n"
+ "%i\n"
+ "%i\n"
+ "%i\n",
+ context->syslog_identifier ? context->syslog_identifier : ident,
+ unit_id,
+ context->syslog_priority,
+ !!context->syslog_level_prefix,
+ output == EXEC_OUTPUT_SYSLOG || output == EXEC_OUTPUT_SYSLOG_AND_CONSOLE,
+ output == EXEC_OUTPUT_KMSG || output == EXEC_OUTPUT_KMSG_AND_CONSOLE,
+ is_terminal_output(output));
+
+ if (fd != nfd) {
+ r = dup2(fd, nfd) < 0 ? -errno : nfd;
+ close_nointr_nofail(fd);
+ } else
+ r = nfd;
+
+ return r;
+}
+static int open_terminal_as(const char *path, mode_t mode, int nfd) {
+ int fd, r;
+
+ assert(path);
+ assert(nfd >= 0);
+
+ if ((fd = open_terminal(path, mode | O_NOCTTY)) < 0)
+ return fd;
+
+ if (fd != nfd) {
+ r = dup2(fd, nfd) < 0 ? -errno : nfd;
+ close_nointr_nofail(fd);
+ } else
+ r = nfd;
+
+ return r;
+}
+
+static bool is_terminal_input(ExecInput i) {
+ return
+ i == EXEC_INPUT_TTY ||
+ i == EXEC_INPUT_TTY_FORCE ||
+ i == EXEC_INPUT_TTY_FAIL;
+}
+
+static int fixup_input(ExecInput std_input, int socket_fd, bool apply_tty_stdin) {
+
+ if (is_terminal_input(std_input) && !apply_tty_stdin)
+ return EXEC_INPUT_NULL;
+
+ if (std_input == EXEC_INPUT_SOCKET && socket_fd < 0)
+ return EXEC_INPUT_NULL;
+
+ return std_input;
+}
+
+static int fixup_output(ExecOutput std_output, int socket_fd) {
+
+ if (std_output == EXEC_OUTPUT_SOCKET && socket_fd < 0)
+ return EXEC_OUTPUT_INHERIT;
+
+ return std_output;
+}
+
+static int setup_input(const ExecContext *context, int socket_fd, bool apply_tty_stdin) {
+ ExecInput i;
+
+ assert(context);
+
+ i = fixup_input(context->std_input, socket_fd, apply_tty_stdin);
+
+ switch (i) {
+
+ case EXEC_INPUT_NULL:
+ return open_null_as(O_RDONLY, STDIN_FILENO);
+
+ case EXEC_INPUT_TTY:
+ case EXEC_INPUT_TTY_FORCE:
+ case EXEC_INPUT_TTY_FAIL: {
+ int fd, r;
+
+ if ((fd = acquire_terminal(
+ tty_path(context),
+ i == EXEC_INPUT_TTY_FAIL,
+ i == EXEC_INPUT_TTY_FORCE,
+ false,
+ (usec_t) -1)) < 0)
+ return fd;
+
+ if (fd != STDIN_FILENO) {
+ r = dup2(fd, STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;
+ close_nointr_nofail(fd);
+ } else
+ r = STDIN_FILENO;
+
+ return r;
+ }
+
+ case EXEC_INPUT_SOCKET:
+ return dup2(socket_fd, STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;
+
+ default:
+ assert_not_reached("Unknown input type");
+ }
+}
+
+static int setup_output(const ExecContext *context, int fileno, int socket_fd, const char *ident, const char *unit_id, bool apply_tty_stdin) {
+ ExecOutput o;
+ ExecInput i;
+ int r;
+
+ assert(context);
+ assert(ident);
+
+ i = fixup_input(context->std_input, socket_fd, apply_tty_stdin);
+ o = fixup_output(context->std_output, socket_fd);
+
+ if (fileno == STDERR_FILENO) {
+ ExecOutput e;
+ e = fixup_output(context->std_error, socket_fd);
+
+ /* This expects the input and output are already set up */
+
+ /* Don't change the stderr file descriptor if we inherit all
+ * the way and are not on a tty */
+ if (e == EXEC_OUTPUT_INHERIT &&
+ o == EXEC_OUTPUT_INHERIT &&
+ i == EXEC_INPUT_NULL &&
+ !is_terminal_input(context->std_input) &&
+ getppid () != 1)
+ return fileno;
+
+ /* Duplicate from stdout if possible */
+ if (e == o || e == EXEC_OUTPUT_INHERIT)
+ return dup2(STDOUT_FILENO, fileno) < 0 ? -errno : fileno;
+
+ o = e;
+
+ } else if (o == EXEC_OUTPUT_INHERIT) {
+ /* If input got downgraded, inherit the original value */
+ if (i == EXEC_INPUT_NULL && is_terminal_input(context->std_input))
+ return open_terminal_as(tty_path(context), O_WRONLY, fileno);
+
+ /* If the input is connected to anything that's not a /dev/null, inherit that... */
+ if (i != EXEC_INPUT_NULL)
+ return dup2(STDIN_FILENO, fileno) < 0 ? -errno : fileno;
+
+ /* If we are not started from PID 1 we just inherit STDOUT from our parent process. */
+ if (getppid() != 1)
+ return fileno;
+
+ /* We need to open /dev/null here anew, to get the right access mode. */
+ return open_null_as(O_WRONLY, fileno);
+ }
+
+ switch (o) {
+
+ case EXEC_OUTPUT_NULL:
+ return open_null_as(O_WRONLY, fileno);
+
+ case EXEC_OUTPUT_TTY:
+ if (is_terminal_input(i))
+ return dup2(STDIN_FILENO, fileno) < 0 ? -errno : fileno;
+
+ /* We don't reset the terminal if this is just about output */
+ return open_terminal_as(tty_path(context), O_WRONLY, fileno);
+
+ case EXEC_OUTPUT_SYSLOG:
+ case EXEC_OUTPUT_SYSLOG_AND_CONSOLE:
+ case EXEC_OUTPUT_KMSG:
+ case EXEC_OUTPUT_KMSG_AND_CONSOLE:
+ case EXEC_OUTPUT_JOURNAL:
+ case EXEC_OUTPUT_JOURNAL_AND_CONSOLE:
+ r = connect_logger_as(context, o, ident, unit_id, fileno);
+ if (r < 0) {
+ log_struct_unit(LOG_CRIT, unit_id,
+ "MESSAGE=Failed to connect std%s of %s to the journal socket: %s",
+ fileno == STDOUT_FILENO ? "out" : "err",
+ unit_id, strerror(-r),
+ "ERRNO=%d", -r,
+ NULL);
+ r = open_null_as(O_WRONLY, fileno);
+ }
+ return r;
+
+ case EXEC_OUTPUT_SOCKET:
+ assert(socket_fd >= 0);
+ return dup2(socket_fd, fileno) < 0 ? -errno : fileno;
+
+ default:
+ assert_not_reached("Unknown error type");
+ }
+}
+
+static int chown_terminal(int fd, uid_t uid) {
+ struct stat st;
+
+ assert(fd >= 0);
+
+ /* This might fail. What matters are the results. */
+ (void) fchown(fd, uid, -1);
+ (void) fchmod(fd, TTY_MODE);
+
+ if (fstat(fd, &st) < 0)
+ return -errno;
+
+ if (st.st_uid != uid || (st.st_mode & 0777) != TTY_MODE)
+ return -EPERM;
+
+ return 0;
+}
+
+static int setup_confirm_stdio(int *_saved_stdin,
+ int *_saved_stdout) {
+ int fd = -1, saved_stdin, saved_stdout = -1, r;
+
+ assert(_saved_stdin);
+ assert(_saved_stdout);
+
+ saved_stdin = fcntl(STDIN_FILENO, F_DUPFD, 3);
+ if (saved_stdin < 0)
+ return -errno;
+
+ saved_stdout = fcntl(STDOUT_FILENO, F_DUPFD, 3);
+ if (saved_stdout < 0) {
+ r = errno;
+ goto fail;
+ }
+
+ fd = acquire_terminal(
+ "/dev/console",
+ false,
+ false,
+ false,
+ DEFAULT_CONFIRM_USEC);
+ if (fd < 0) {
+ r = fd;
+ goto fail;
+ }
+
+ r = chown_terminal(fd, getuid());
+ if (r < 0)
+ goto fail;
+
+ if (dup2(fd, STDIN_FILENO) < 0) {
+ r = -errno;
+ goto fail;
+ }
+
+ if (dup2(fd, STDOUT_FILENO) < 0) {
+ r = -errno;
+ goto fail;
+ }
+
+ if (fd >= 2)
+ close_nointr_nofail(fd);
+
+ *_saved_stdin = saved_stdin;
+ *_saved_stdout = saved_stdout;
+
+ return 0;
+
+fail:
+ if (saved_stdout >= 0)
+ close_nointr_nofail(saved_stdout);
+
+ if (saved_stdin >= 0)
+ close_nointr_nofail(saved_stdin);
+
+ if (fd >= 0)
+ close_nointr_nofail(fd);
+
+ return r;
+}
+
+_printf_attr_(1, 2) static int write_confirm_message(const char *format, ...) {
+ int fd;
+ va_list ap;
+
+ assert(format);
+
+ fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
+ if (fd < 0)
+ return fd;
+
+ va_start(ap, format);
+ vdprintf(fd, format, ap);
+ va_end(ap);
+
+ close_nointr_nofail(fd);
+
+ return 0;
+}
+
+static int restore_confirm_stdio(int *saved_stdin,
+ int *saved_stdout) {
+
+ int r = 0;
+
+ assert(saved_stdin);
+ assert(saved_stdout);
+
+ release_terminal();
+
+ if (*saved_stdin >= 0)
+ if (dup2(*saved_stdin, STDIN_FILENO) < 0)
+ r = -errno;
+
+ if (*saved_stdout >= 0)
+ if (dup2(*saved_stdout, STDOUT_FILENO) < 0)
+ r = -errno;
+
+ if (*saved_stdin >= 0)
+ close_nointr_nofail(*saved_stdin);
+
+ if (*saved_stdout >= 0)
+ close_nointr_nofail(*saved_stdout);
+
+ return r;
+}
+
+static int ask_for_confirmation(char *response, char **argv) {
+ int saved_stdout = -1, saved_stdin = -1, r;
+ char *line;
+
+ r = setup_confirm_stdio(&saved_stdin, &saved_stdout);
+ if (r < 0)
+ return r;
+
+ line = exec_command_line(argv);
+ if (!line)
+ return -ENOMEM;
+
+ r = ask(response, "yns", "Execute %s? [Yes, No, Skip] ", line);
+ free(line);
+
+ restore_confirm_stdio(&saved_stdin, &saved_stdout);
+
+ return r;
+}
+
+static int enforce_groups(const ExecContext *context, const char *username, gid_t gid) {
+ bool keep_groups = false;
+ int r;
+
+ assert(context);
+
+ /* Lookup and set GID and supplementary group list. Here too
+ * we avoid NSS lookups for gid=0. */
+
+ if (context->group || username) {
+
+ if (context->group) {
+ const char *g = context->group;
+
+ if ((r = get_group_creds(&g, &gid)) < 0)
+ return r;
+ }
+
+ /* First step, initialize groups from /etc/groups */
+ if (username && gid != 0) {
+ if (initgroups(username, gid) < 0)
+ return -errno;
+
+ keep_groups = true;
+ }
+
+ /* Second step, set our gids */
+ if (setresgid(gid, gid, gid) < 0)
+ return -errno;
+ }
+
+ if (context->supplementary_groups) {
+ int ngroups_max, k;
+ gid_t *gids;
+ char **i;
+
+ /* Final step, initialize any manually set supplementary groups */
+ assert_se((ngroups_max = (int) sysconf(_SC_NGROUPS_MAX)) > 0);
+
+ if (!(gids = new(gid_t, ngroups_max)))
+ return -ENOMEM;
+
+ if (keep_groups) {
+ if ((k = getgroups(ngroups_max, gids)) < 0) {
+ free(gids);
+ return -errno;
+ }
+ } else
+ k = 0;
+
+ STRV_FOREACH(i, context->supplementary_groups) {
+ const char *g;
+
+ if (k >= ngroups_max) {
+ free(gids);
+ return -E2BIG;
+ }
+
+ g = *i;
+ r = get_group_creds(&g, gids+k);
+ if (r < 0) {
+ free(gids);
+ return r;
+ }
+
+ k++;
+ }
+
+ if (setgroups(k, gids) < 0) {
+ free(gids);
+ return -errno;
+ }
+
+ free(gids);
+ }
+
+ return 0;
+}
+
+static int enforce_user(const ExecContext *context, uid_t uid) {
+ int r;
+ assert(context);
+
+ /* Sets (but doesn't lookup) the uid and make sure we keep the
+ * capabilities while doing so. */
+
+ if (context->capabilities) {
+ cap_t d;
+ static const cap_value_t bits[] = {
+ CAP_SETUID, /* Necessary so that we can run setresuid() below */
+ CAP_SETPCAP /* Necessary so that we can set PR_SET_SECUREBITS later on */
+ };
+
+ /* First step: If we need to keep capabilities but
+ * drop privileges we need to make sure we keep our
+ * caps, while we drop privileges. */
+ if (uid != 0) {
+ int sb = context->secure_bits | 1<<SECURE_KEEP_CAPS;
+
+ if (prctl(PR_GET_SECUREBITS) != sb)
+ if (prctl(PR_SET_SECUREBITS, sb) < 0)
+ return -errno;
+ }
+
+ /* Second step: set the capabilities. This will reduce
+ * the capabilities to the minimum we need. */
+
+ if (!(d = cap_dup(context->capabilities)))
+ return -errno;
+
+ if (cap_set_flag(d, CAP_EFFECTIVE, ELEMENTSOF(bits), bits, CAP_SET) < 0 ||
+ cap_set_flag(d, CAP_PERMITTED, ELEMENTSOF(bits), bits, CAP_SET) < 0) {
+ r = -errno;
+ cap_free(d);
+ return r;
+ }
+
+ if (cap_set_proc(d) < 0) {
+ r = -errno;
+ cap_free(d);
+ return r;
+ }
+
+ cap_free(d);
+ }
+
+ /* Third step: actually set the uids */
+ if (setresuid(uid, uid, uid) < 0)
+ return -errno;
+
+ /* At this point we should have all necessary capabilities but
+ are otherwise a normal user. However, the caps might got
+ corrupted due to the setresuid() so we need clean them up
+ later. This is done outside of this call. */
+
+ return 0;
+}
+
+#ifdef HAVE_PAM
+
+static int null_conv(
+ int num_msg,
+ const struct pam_message **msg,
+ struct pam_response **resp,
+ void *appdata_ptr) {
+
+ /* We don't support conversations */
+
+ return PAM_CONV_ERR;
+}
+
+static int setup_pam(
+ const char *name,
+ const char *user,
+ uid_t uid,
+ const char *tty,
+ char ***pam_env,
+ int fds[], unsigned n_fds) {
+
+ static const struct pam_conv conv = {
+ .conv = null_conv,
+ .appdata_ptr = NULL
+ };
+
+ pam_handle_t *handle = NULL;
+ sigset_t ss, old_ss;
+ int pam_code = PAM_SUCCESS;
+ int err;
+ char **e = NULL;
+ bool close_session = false;
+ pid_t pam_pid = 0, parent_pid;
+
+ assert(name);
+ assert(user);
+ assert(pam_env);
+
+ /* We set up PAM in the parent process, then fork. The child
+ * will then stay around until killed via PR_GET_PDEATHSIG or
+ * systemd via the cgroup logic. It will then remove the PAM
+ * session again. The parent process will exec() the actual
+ * daemon. We do things this way to ensure that the main PID
+ * of the daemon is the one we initially fork()ed. */
+
+ if ((pam_code = pam_start(name, user, &conv, &handle)) != PAM_SUCCESS) {
+ handle = NULL;
+ goto fail;
+ }
+
+ if (tty)
+ if ((pam_code = pam_set_item(handle, PAM_TTY, tty)) != PAM_SUCCESS)
+ goto fail;
+
+ if ((pam_code = pam_acct_mgmt(handle, PAM_SILENT)) != PAM_SUCCESS)
+ goto fail;
+
+ if ((pam_code = pam_open_session(handle, PAM_SILENT)) != PAM_SUCCESS)
+ goto fail;
+
+ close_session = true;
+
+ if ((!(e = pam_getenvlist(handle)))) {
+ pam_code = PAM_BUF_ERR;
+ goto fail;
+ }
+
+ /* Block SIGTERM, so that we know that it won't get lost in
+ * the child */
+ if (sigemptyset(&ss) < 0 ||
+ sigaddset(&ss, SIGTERM) < 0 ||
+ sigprocmask(SIG_BLOCK, &ss, &old_ss) < 0)
+ goto fail;
+
+ parent_pid = getpid();
+
+ if ((pam_pid = fork()) < 0)
+ goto fail;
+
+ if (pam_pid == 0) {
+ int sig;
+ int r = EXIT_PAM;
+
+ /* The child's job is to reset the PAM session on
+ * termination */
+
+ /* This string must fit in 10 chars (i.e. the length
+ * of "/sbin/init"), to look pretty in /bin/ps */
+ rename_process("(sd-pam)");
+
+ /* Make sure we don't keep open the passed fds in this
+ child. We assume that otherwise only those fds are
+ open here that have been opened by PAM. */
+ close_many(fds, n_fds);
+
+ /* Drop privileges - we don't need any to pam_close_session
+ * and this will make PR_SET_PDEATHSIG work in most cases.
+ * If this fails, ignore the error - but expect sd-pam threads
+ * to fail to exit normally */
+ if (setresuid(uid, uid, uid) < 0)
+ log_error("Error: Failed to setresuid() in sd-pam: %s", strerror(-r));
+
+ /* Wait until our parent died. This will only work if
+ * the above setresuid() succeeds, otherwise the kernel
+ * will not allow unprivileged parents kill their privileged
+ * children this way. We rely on the control groups kill logic
+ * to do the rest for us. */
+ if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
+ goto child_finish;
+
+ /* Check if our parent process might already have
+ * died? */
+ if (getppid() == parent_pid) {
+ for (;;) {
+ if (sigwait(&ss, &sig) < 0) {
+ if (errno == EINTR)
+ continue;
+
+ goto child_finish;
+ }
+
+ assert(sig == SIGTERM);
+ break;
+ }
+ }
+
+ /* If our parent died we'll end the session */
+ if (getppid() != parent_pid)
+ if ((pam_code = pam_close_session(handle, PAM_DATA_SILENT)) != PAM_SUCCESS)
+ goto child_finish;
+
+ r = 0;
+
+ child_finish:
+ pam_end(handle, pam_code | PAM_DATA_SILENT);
+ _exit(r);
+ }
+
+ /* If the child was forked off successfully it will do all the
+ * cleanups, so forget about the handle here. */
+ handle = NULL;
+
+ /* Unblock SIGTERM again in the parent */
+ if (sigprocmask(SIG_SETMASK, &old_ss, NULL) < 0)
+ goto fail;
+
+ /* We close the log explicitly here, since the PAM modules
+ * might have opened it, but we don't want this fd around. */
+ closelog();
+
+ *pam_env = e;
+ e = NULL;
+
+ return 0;
+
+fail:
+ if (pam_code != PAM_SUCCESS)
+ err = -EPERM; /* PAM errors do not map to errno */
+ else
+ err = -errno;
+
+ if (handle) {
+ if (close_session)
+ pam_code = pam_close_session(handle, PAM_DATA_SILENT);
+
+ pam_end(handle, pam_code | PAM_DATA_SILENT);
+ }
+
+ strv_free(e);
+
+ closelog();
+
+ if (pam_pid > 1) {
+ kill(pam_pid, SIGTERM);
+ kill(pam_pid, SIGCONT);
+ }
+
+ return err;
+}
+#endif
+
+static void rename_process_from_path(const char *path) {
+ char process_name[11];
+ const char *p;
+ size_t l;
+
+ /* This resulting string must fit in 10 chars (i.e. the length
+ * of "/sbin/init") to look pretty in /bin/ps */
+
+ p = path_get_file_name(path);
+ if (isempty(p)) {
+ rename_process("(...)");
+ return;
+ }
+
+ l = strlen(p);
+ if (l > 8) {
+ /* The end of the process name is usually more
+ * interesting, since the first bit might just be
+ * "systemd-" */
+ p = p + l - 8;
+ l = 8;
+ }
+
+ process_name[0] = '(';
+ memcpy(process_name+1, p, l);
+ process_name[1+l] = ')';
+ process_name[1+l+1] = 0;
+
+ rename_process(process_name);
+}
+
+static int apply_seccomp(uint32_t *syscall_filter) {
+ static const struct sock_filter header[] = {
+ VALIDATE_ARCHITECTURE,
+ EXAMINE_SYSCALL
+ };
+ static const struct sock_filter footer[] = {
+ _KILL_PROCESS
+ };
+
+ int i;
+ unsigned n;
+ struct sock_filter *f;
+ struct sock_fprog prog = {};
+
+ assert(syscall_filter);
+
+ /* First: count the syscalls to check for */
+ for (i = 0, n = 0; i < syscall_max(); i++)
+ if (syscall_filter[i >> 4] & (1 << (i & 31)))
+ n++;
+
+ /* Second: build the filter program from a header the syscall
+ * matches and the footer */
+ f = alloca(sizeof(struct sock_filter) * (ELEMENTSOF(header) + 2*n + ELEMENTSOF(footer)));
+ memcpy(f, header, sizeof(header));
+
+ for (i = 0, n = 0; i < syscall_max(); i++)
+ if (syscall_filter[i >> 4] & (1 << (i & 31))) {
+ struct sock_filter item[] = {
+ BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, INDEX_TO_SYSCALL(i), 0, 1),
+ BPF_STMT(BPF_RET+BPF_K, SECCOMP_RET_ALLOW)
+ };
+
+ assert_cc(ELEMENTSOF(item) == 2);
+
+ f[ELEMENTSOF(header) + 2*n] = item[0];
+ f[ELEMENTSOF(header) + 2*n+1] = item[1];
+
+ n++;
+ }
+
+ memcpy(f + (ELEMENTSOF(header) + 2*n), footer, sizeof(footer));
+
+ /* Third: install the filter */
+ prog.len = ELEMENTSOF(header) + ELEMENTSOF(footer) + 2*n;
+ prog.filter = f;
+ if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog) < 0)
+ return -errno;
+
+ return 0;
+}
+
+int exec_spawn(ExecCommand *command,
+ char **argv,
+ ExecContext *context,
+ int fds[], unsigned n_fds,
+ char **environment,
+ bool apply_permissions,
+ bool apply_chroot,
+ bool apply_tty_stdin,
+ bool confirm_spawn,
+ CGroupBonding *cgroup_bondings,
+ CGroupAttribute *cgroup_attributes,
+ const char *cgroup_suffix,
+ const char *unit_id,
+ int idle_pipe[2],
+ pid_t *ret) {
+
+ pid_t pid;
+ int r;
+ char *line;
+ int socket_fd;
+ _cleanup_strv_free_ char **files_env = NULL;
+
+ assert(command);
+ assert(context);
+ assert(ret);
+ assert(fds || n_fds <= 0);
+
+ if (context->std_input == EXEC_INPUT_SOCKET ||
+ context->std_output == EXEC_OUTPUT_SOCKET ||
+ context->std_error == EXEC_OUTPUT_SOCKET) {
+
+ if (n_fds != 1)
+ return -EINVAL;
+
+ socket_fd = fds[0];
+
+ fds = NULL;
+ n_fds = 0;
+ } else
+ socket_fd = -1;
+
+ r = exec_context_load_environment(context, &files_env);
+ if (r < 0) {
+ log_struct_unit(LOG_ERR,
+ unit_id,
+ "MESSAGE=Failed to load environment files: %s", strerror(-r),
+ "ERRNO=%d", -r,
+ NULL);
+ return r;
+ }
+
+ if (!argv)
+ argv = command->argv;
+
+ line = exec_command_line(argv);
+ if (!line)
+ return log_oom();
+
+ log_struct_unit(LOG_DEBUG,
+ unit_id,
+ "EXECUTABLE=%s", command->path,
+ "MESSAGE=About to execute: %s", line,
+ NULL);
+ free(line);
+
+ r = cgroup_bonding_realize_list(cgroup_bondings);
+ if (r < 0)
+ return r;
+
+ /* We must initialize the attributes in the parent, before we
+ fork, because we really need them initialized before making
+ the process a member of the group (which we do in both the
+ child and the parent), and we cannot really apply them twice
+ (due to 'append' style attributes) */
+ cgroup_attribute_apply_list(cgroup_attributes, cgroup_bondings);
+
+ if (context->private_tmp && !context->tmp_dir && !context->var_tmp_dir) {
+ r = setup_tmpdirs(&context->tmp_dir, &context->var_tmp_dir);
+ if (r < 0)
+ return r;
+ }
+
+ pid = fork();
+ if (pid < 0)
+ return -errno;
+
+ if (pid == 0) {
+ int i, err;
+ sigset_t ss;
+ const char *username = NULL, *home = NULL;
+ uid_t uid = (uid_t) -1;
+ gid_t gid = (gid_t) -1;
+ _cleanup_strv_free_ char **our_env = NULL, **pam_env = NULL,
+ **final_env = NULL, **final_argv = NULL;
+ unsigned n_env = 0;
+ bool set_access = false;
+
+ /* child */
+
+ rename_process_from_path(command->path);
+
+ /* We reset exactly these signals, since they are the
+ * only ones we set to SIG_IGN in the main daemon. All
+ * others we leave untouched because we set them to
+ * SIG_DFL or a valid handler initially, both of which
+ * will be demoted to SIG_DFL. */
+ default_signals(SIGNALS_CRASH_HANDLER,
+ SIGNALS_IGNORE, -1);
+
+ if (context->ignore_sigpipe)
+ ignore_signals(SIGPIPE, -1);
+
+ assert_se(sigemptyset(&ss) == 0);
+ if (sigprocmask(SIG_SETMASK, &ss, NULL) < 0) {
+ err = -errno;
+ r = EXIT_SIGNAL_MASK;
+ goto fail_child;
+ }
+
+ if (idle_pipe) {
+ if (idle_pipe[1] >= 0)
+ close_nointr_nofail(idle_pipe[1]);
+ if (idle_pipe[0] >= 0) {
+ fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT_USEC);
+ close_nointr_nofail(idle_pipe[0]);
+ }
+ }
+
+ /* Close sockets very early to make sure we don't
+ * block init reexecution because it cannot bind its
+ * sockets */
+ log_forget_fds();
+ err = close_all_fds(socket_fd >= 0 ? &socket_fd : fds,
+ socket_fd >= 0 ? 1 : n_fds);
+ if (err < 0) {
+ r = EXIT_FDS;
+ goto fail_child;
+ }
+
+ if (!context->same_pgrp)
+ if (setsid() < 0) {
+ err = -errno;
+ r = EXIT_SETSID;
+ goto fail_child;
+ }
+
+ if (context->tcpwrap_name) {
+ if (socket_fd >= 0)
+ if (!socket_tcpwrap(socket_fd, context->tcpwrap_name)) {
+ err = -EACCES;
+ r = EXIT_TCPWRAP;
+ goto fail_child;
+ }
+
+ for (i = 0; i < (int) n_fds; i++) {
+ if (!socket_tcpwrap(fds[i], context->tcpwrap_name)) {
+ err = -EACCES;
+ r = EXIT_TCPWRAP;
+ goto fail_child;
+ }
+ }
+ }
+
+ exec_context_tty_reset(context);
+
+ if (confirm_spawn) {
+ char response;
+
+ err = ask_for_confirmation(&response, argv);
+ if (err == -ETIMEDOUT)
+ write_confirm_message("Confirmation question timed out, assuming positive response.\n");
+ else if (err < 0)
+ write_confirm_message("Couldn't ask confirmation question, assuming positive response: %s\n", strerror(-err));
+ else if (response == 's') {
+ write_confirm_message("Skipping execution.\n");
+ err = -ECANCELED;
+ r = EXIT_CONFIRM;
+ goto fail_child;
+ } else if (response == 'n') {
+ write_confirm_message("Failing execution.\n");
+ err = r = 0;
+ goto fail_child;
+ }
+ }
+
+ /* If a socket is connected to STDIN/STDOUT/STDERR, we
+ * must sure to drop O_NONBLOCK */
+ if (socket_fd >= 0)
+ fd_nonblock(socket_fd, false);
+
+ err = setup_input(context, socket_fd, apply_tty_stdin);
+ if (err < 0) {
+ r = EXIT_STDIN;
+ goto fail_child;
+ }
+
+ err = setup_output(context, STDOUT_FILENO, socket_fd, path_get_file_name(command->path), unit_id, apply_tty_stdin);
+ if (err < 0) {
+ r = EXIT_STDOUT;
+ goto fail_child;
+ }
+
+ err = setup_output(context, STDERR_FILENO, socket_fd, path_get_file_name(command->path), unit_id, apply_tty_stdin);
+ if (err < 0) {
+ r = EXIT_STDERR;
+ goto fail_child;
+ }
+
+ if (cgroup_bondings) {
+ err = cgroup_bonding_install_list(cgroup_bondings, 0, cgroup_suffix);
+ if (err < 0) {
+ r = EXIT_CGROUP;
+ goto fail_child;
+ }
+ }
+
+ if (context->oom_score_adjust_set) {
+ char t[16];
+
+ snprintf(t, sizeof(t), "%i", context->oom_score_adjust);
+ char_array_0(t);
+
+ if (write_string_file("/proc/self/oom_score_adj", t) < 0) {
+ err = -errno;
+ r = EXIT_OOM_ADJUST;
+ goto fail_child;
+ }
+ }
+
+ if (context->nice_set)
+ if (setpriority(PRIO_PROCESS, 0, context->nice) < 0) {
+ err = -errno;
+ r = EXIT_NICE;
+ goto fail_child;
+ }
+
+ if (context->cpu_sched_set) {
+ struct sched_param param = {
+ .sched_priority = context->cpu_sched_priority,
+ };
+
+ r = sched_setscheduler(0,
+ context->cpu_sched_policy |
+ (context->cpu_sched_reset_on_fork ?
+ SCHED_RESET_ON_FORK : 0),
+ &param);
+ if (r < 0) {
+ err = -errno;
+ r = EXIT_SETSCHEDULER;
+ goto fail_child;
+ }
+ }
+
+ if (context->cpuset)
+ if (sched_setaffinity(0, CPU_ALLOC_SIZE(context->cpuset_ncpus), context->cpuset) < 0) {
+ err = -errno;
+ r = EXIT_CPUAFFINITY;
+ goto fail_child;
+ }
+
+ if (context->ioprio_set)
+ if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
+ err = -errno;
+ r = EXIT_IOPRIO;
+ goto fail_child;
+ }
+
+ if (context->timer_slack_nsec != (nsec_t) -1)
+ if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) {
+ err = -errno;
+ r = EXIT_TIMERSLACK;
+ goto fail_child;
+ }
+
+ if (context->utmp_id)
+ utmp_put_init_process(context->utmp_id, getpid(), getsid(0), context->tty_path);
+
+ if (context->user) {
+ username = context->user;
+ err = get_user_creds(&username, &uid, &gid, &home, NULL);
+ if (err < 0) {
+ r = EXIT_USER;
+ goto fail_child;
+ }
+
+ if (is_terminal_input(context->std_input)) {
+ err = chown_terminal(STDIN_FILENO, uid);
+ if (err < 0) {
+ r = EXIT_STDIN;
+ goto fail_child;
+ }
+ }
+
+ if (cgroup_bondings && context->control_group_modify) {
+ err = cgroup_bonding_set_group_access_list(cgroup_bondings, 0755, uid, gid);
+ if (err >= 0)
+ err = cgroup_bonding_set_task_access_list(
+ cgroup_bondings,
+ 0644,
+ uid,
+ gid,
+ context->control_group_persistent);
+ if (err < 0) {
+ r = EXIT_CGROUP;
+ goto fail_child;
+ }
+
+ set_access = true;
+ }
+ }
+
+ if (cgroup_bondings && !set_access && context->control_group_persistent >= 0) {
+ err = cgroup_bonding_set_task_access_list(
+ cgroup_bondings,
+ (mode_t) -1,
+ (uid_t) -1,
+ (uid_t) -1,
+ context->control_group_persistent);
+ if (err < 0) {
+ r = EXIT_CGROUP;
+ goto fail_child;
+ }
+ }
+
+ if (apply_permissions) {
+ err = enforce_groups(context, username, gid);
+ if (err < 0) {
+ r = EXIT_GROUP;
+ goto fail_child;
+ }
+ }
+
+ umask(context->umask);
+
+#ifdef HAVE_PAM
+ if (apply_permissions && context->pam_name && username) {
+ err = setup_pam(context->pam_name, username, uid, context->tty_path, &pam_env, fds, n_fds);
+ if (err < 0) {
+ r = EXIT_PAM;
+ goto fail_child;
+ }
+ }
+#endif
+ if (context->private_network) {
+ if (unshare(CLONE_NEWNET) < 0) {
+ err = -errno;
+ r = EXIT_NETWORK;
+ goto fail_child;
+ }
+
+ loopback_setup();
+ }
+
+ if (strv_length(context->read_write_dirs) > 0 ||
+ strv_length(context->read_only_dirs) > 0 ||
+ strv_length(context->inaccessible_dirs) > 0 ||
+ context->mount_flags != 0 ||
+ context->private_tmp) {
+ err = setup_namespace(context->read_write_dirs,
+ context->read_only_dirs,
+ context->inaccessible_dirs,
+ context->tmp_dir,
+ context->var_tmp_dir,
+ context->private_tmp,
+ context->mount_flags);
+ if (err < 0) {
+ r = EXIT_NAMESPACE;
+ goto fail_child;
+ }
+ }
+
+ if (apply_chroot) {
+ if (context->root_directory)
+ if (chroot(context->root_directory) < 0) {
+ err = -errno;
+ r = EXIT_CHROOT;
+ goto fail_child;
+ }
+
+ if (chdir(context->working_directory ? context->working_directory : "/") < 0) {
+ err = -errno;
+ r = EXIT_CHDIR;
+ goto fail_child;
+ }
+ } else {
+ _cleanup_free_ char *d = NULL;
+
+ if (asprintf(&d, "%s/%s",
+ context->root_directory ? context->root_directory : "",
+ context->working_directory ? context->working_directory : "") < 0) {
+ err = -ENOMEM;
+ r = EXIT_MEMORY;
+ goto fail_child;
+ }
+
+ if (chdir(d) < 0) {
+ err = -errno;
+ r = EXIT_CHDIR;
+ goto fail_child;
+ }
+ }
+
+ /* We repeat the fd closing here, to make sure that
+ * nothing is leaked from the PAM modules */
+ err = close_all_fds(fds, n_fds);
+ if (err >= 0)
+ err = shift_fds(fds, n_fds);
+ if (err >= 0)
+ err = flags_fds(fds, n_fds, context->non_blocking);
+ if (err < 0) {
+ r = EXIT_FDS;
+ goto fail_child;
+ }
+
+ if (apply_permissions) {
+
+ for (i = 0; i < RLIMIT_NLIMITS; i++) {
+ if (!context->rlimit[i])
+ continue;
+
+ if (setrlimit_closest(i, context->rlimit[i]) < 0) {
+ err = -errno;
+ r = EXIT_LIMITS;
+ goto fail_child;
+ }
+ }
+
+ if (context->capability_bounding_set_drop) {
+ err = capability_bounding_set_drop(context->capability_bounding_set_drop, false);
+ if (err < 0) {
+ r = EXIT_CAPABILITIES;
+ goto fail_child;
+ }
+ }
+
+ if (context->user) {
+ err = enforce_user(context, uid);
+ if (err < 0) {
+ r = EXIT_USER;
+ goto fail_child;
+ }
+ }
+
+ /* PR_GET_SECUREBITS is not privileged, while
+ * PR_SET_SECUREBITS is. So to suppress
+ * potential EPERMs we'll try not to call
+ * PR_SET_SECUREBITS unless necessary. */
+ if (prctl(PR_GET_SECUREBITS) != context->secure_bits)
+ if (prctl(PR_SET_SECUREBITS, context->secure_bits) < 0) {
+ err = -errno;
+ r = EXIT_SECUREBITS;
+ goto fail_child;
+ }
+
+ if (context->capabilities)
+ if (cap_set_proc(context->capabilities) < 0) {
+ err = -errno;
+ r = EXIT_CAPABILITIES;
+ goto fail_child;
+ }
+
+ if (context->no_new_privileges)
+ if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
+ err = -errno;
+ r = EXIT_NO_NEW_PRIVILEGES;
+ goto fail_child;
+ }
+
+ if (context->syscall_filter) {
+ err = apply_seccomp(context->syscall_filter);
+ if (err < 0) {
+ r = EXIT_SECCOMP;
+ goto fail_child;
+ }
+ }
+ }
+
+ our_env = new0(char*, 7);
+ if (!our_env) {
+ err = -ENOMEM;
+ r = EXIT_MEMORY;
+ goto fail_child;
+ }
+
+ if (n_fds > 0)
+ if (asprintf(our_env + n_env++, "LISTEN_PID=%lu", (unsigned long) getpid()) < 0 ||
+ asprintf(our_env + n_env++, "LISTEN_FDS=%u", n_fds) < 0) {
+ err = -ENOMEM;
+ r = EXIT_MEMORY;
+ goto fail_child;
+ }
+
+ if (home)
+ if (asprintf(our_env + n_env++, "HOME=%s", home) < 0) {
+ err = -ENOMEM;
+ r = EXIT_MEMORY;
+ goto fail_child;
+ }
+
+ if (username)
+ if (asprintf(our_env + n_env++, "LOGNAME=%s", username) < 0 ||
+ asprintf(our_env + n_env++, "USER=%s", username) < 0) {
+ err = -ENOMEM;
+ r = EXIT_MEMORY;
+ goto fail_child;
+ }
+
+ if (is_terminal_input(context->std_input) ||
+ context->std_output == EXEC_OUTPUT_TTY ||
+ context->std_error == EXEC_OUTPUT_TTY)
+ if (!(our_env[n_env++] = strdup(default_term_for_tty(tty_path(context))))) {
+ err = -ENOMEM;
+ r = EXIT_MEMORY;
+ goto fail_child;
+ }
+
+ assert(n_env <= 7);
+
+ final_env = strv_env_merge(5,
+ environment,
+ our_env,
+ context->environment,
+ files_env,
+ pam_env,
+ NULL);
+ if (!final_env) {
+ err = -ENOMEM;
+ r = EXIT_MEMORY;
+ goto fail_child;
+ }
+
+ final_argv = replace_env_argv(argv, final_env);
+ if (!final_argv) {
+ err = -ENOMEM;
+ r = EXIT_MEMORY;
+ goto fail_child;
+ }
+
+ final_env = strv_env_clean(final_env);
+
+ if (_unlikely_(log_get_max_level() >= LOG_PRI(LOG_DEBUG))) {
+ line = exec_command_line(final_argv);
+ if (line) {
+ log_open();
+ log_struct_unit(LOG_DEBUG,
+ unit_id,
+ "EXECUTABLE=%s", command->path,
+ "MESSAGE=Executing: %s", line,
+ NULL);
+ log_close();
+ free(line);
+ line = NULL;
+ }
+ }
+ execve(command->path, final_argv, final_env);
+ err = -errno;
+ r = EXIT_EXEC;
+
+ fail_child:
+ if (r != 0) {
+ log_open();
+ log_struct(LOG_ERR, MESSAGE_ID(SD_MESSAGE_SPAWN_FAILED),
+ "EXECUTABLE=%s", command->path,
+ "MESSAGE=Failed at step %s spawning %s: %s",
+ exit_status_to_string(r, EXIT_STATUS_SYSTEMD),
+ command->path, strerror(-err),
+ "ERRNO=%d", -err,
+ NULL);
+ log_close();
+ }
+
+ _exit(r);
+ }
+
+ log_struct_unit(LOG_DEBUG,
+ unit_id,
+ "MESSAGE=Forked %s as %lu",
+ command->path, (unsigned long) pid,
+ NULL);
+
+ /* We add the new process to the cgroup both in the child (so
+ * that we can be sure that no user code is ever executed
+ * outside of the cgroup) and in the parent (so that we can be
+ * sure that when we kill the cgroup the process will be
+ * killed too). */
+ cgroup_bonding_install_list(cgroup_bondings, pid, cgroup_suffix);
+
+ exec_status_start(&command->exec_status, pid);
+
+ *ret = pid;
+ return 0;
+}
+
+void exec_context_init(ExecContext *c) {
+ assert(c);
+
+ c->umask = 0022;
+ c->ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 0);
+ c->cpu_sched_policy = SCHED_OTHER;
+ c->syslog_priority = LOG_DAEMON|LOG_INFO;
+ c->syslog_level_prefix = true;
+ c->control_group_persistent = -1;
+ c->ignore_sigpipe = true;
+ c->timer_slack_nsec = (nsec_t) -1;
+}
+
+void exec_context_tmp_dirs_done(ExecContext *c) {
+ char* dirs[] = {c->tmp_dir ? c->tmp_dir : c->var_tmp_dir,
+ c->tmp_dir ? c->var_tmp_dir : NULL,
+ NULL};
+ char **dirp;
+
+ for(dirp = dirs; *dirp; dirp++) {
+ char *dir;
+ int r;
+
+ r = rm_rf_dangerous(*dirp, false, true, false);
+ dir = dirname(*dirp);
+ if (r < 0)
+ log_warning("Failed to remove content of temporary directory %s: %s",
+ dir, strerror(-r));
+ else {
+ r = rmdir(dir);
+ if (r < 0)
+ log_warning("Failed to remove temporary directory %s: %s",
+ dir, strerror(-r));
+ }
+
+ free(*dirp);
+ }
+
+ c->tmp_dir = c->var_tmp_dir = NULL;
+}
+
+void exec_context_done(ExecContext *c, bool reloading_or_reexecuting) {
+ unsigned l;
+
+ assert(c);
+
+ strv_free(c->environment);
+ c->environment = NULL;
+
+ strv_free(c->environment_files);
+ c->environment_files = NULL;
+
+ for (l = 0; l < ELEMENTSOF(c->rlimit); l++) {
+ free(c->rlimit[l]);
+ c->rlimit[l] = NULL;
+ }
+
+ free(c->working_directory);
+ c->working_directory = NULL;
+ free(c->root_directory);
+ c->root_directory = NULL;
+
+ free(c->tty_path);
+ c->tty_path = NULL;
+
+ free(c->tcpwrap_name);
+ c->tcpwrap_name = NULL;
+
+ free(c->syslog_identifier);
+ c->syslog_identifier = NULL;
+
+ free(c->user);
+ c->user = NULL;
+
+ free(c->group);
+ c->group = NULL;
+
+ strv_free(c->supplementary_groups);
+ c->supplementary_groups = NULL;
+
+ free(c->pam_name);
+ c->pam_name = NULL;
+
+ if (c->capabilities) {
+ cap_free(c->capabilities);
+ c->capabilities = NULL;
+ }
+
+ strv_free(c->read_only_dirs);
+ c->read_only_dirs = NULL;
+
+ strv_free(c->read_write_dirs);
+ c->read_write_dirs = NULL;
+
+ strv_free(c->inaccessible_dirs);
+ c->inaccessible_dirs = NULL;
+
+ if (c->cpuset)
+ CPU_FREE(c->cpuset);
+
+ free(c->utmp_id);
+ c->utmp_id = NULL;
+
+ free(c->syscall_filter);
+ c->syscall_filter = NULL;
+
+ if (!reloading_or_reexecuting)
+ exec_context_tmp_dirs_done(c);
+}
+
+void exec_command_done(ExecCommand *c) {
+ assert(c);
+
+ free(c->path);
+ c->path = NULL;
+
+ strv_free(c->argv);
+ c->argv = NULL;
+}
+
+void exec_command_done_array(ExecCommand *c, unsigned n) {
+ unsigned i;
+
+ for (i = 0; i < n; i++)
+ exec_command_done(c+i);
+}
+
+void exec_command_free_list(ExecCommand *c) {
+ ExecCommand *i;
+
+ while ((i = c)) {
+ LIST_REMOVE(ExecCommand, command, c, i);
+ exec_command_done(i);
+ free(i);
+ }
+}
+
+void exec_command_free_array(ExecCommand **c, unsigned n) {
+ unsigned i;
+
+ for (i = 0; i < n; i++) {
+ exec_command_free_list(c[i]);
+ c[i] = NULL;
+ }
+}
+
+int exec_context_load_environment(const ExecContext *c, char ***l) {
+ char **i, **r = NULL;
+
+ assert(c);
+ assert(l);
+
+ STRV_FOREACH(i, c->environment_files) {
+ char *fn;
+ int k;
+ bool ignore = false;
+ char **p;
+ _cleanup_globfree_ glob_t pglob = {};
+ int count, n;
+
+ fn = *i;
+
+ if (fn[0] == '-') {
+ ignore = true;
+ fn ++;
+ }
+
+ if (!path_is_absolute(fn)) {
+ if (ignore)
+ continue;
+
+ strv_free(r);
+ return -EINVAL;
+ }
+
+ /* Filename supports globbing, take all matching files */
+ errno = 0;
+ if (glob(fn, 0, NULL, &pglob) != 0) {
+ if (ignore)
+ continue;
+
+ strv_free(r);
+ return errno ? -errno : -EINVAL;
+ }
+ count = pglob.gl_pathc;
+ if (count == 0) {
+ if (ignore)
+ continue;
+
+ strv_free(r);
+ return -EINVAL;
+ }
+ for (n = 0; n < count; n++) {
+ k = load_env_file(pglob.gl_pathv[n], NULL, &p);
+ if (k < 0) {
+ if (ignore)
+ continue;
+
+ strv_free(r);
+ return k;
+ }
+ /* Log invalid environment variables with filename */
+ if (p)
+ p = strv_env_clean_log(p, pglob.gl_pathv[n]);
+
+ if (r == NULL)
+ r = p;
+ else {
+ char **m;
+
+ m = strv_env_merge(2, r, p);
+ strv_free(r);
+ strv_free(p);
+ if (!m)
+ return -ENOMEM;
+
+ r = m;
+ }
+ }
+ }
+
+ *l = r;
+
+ return 0;
+}
+
+static bool tty_may_match_dev_console(const char *tty) {
+ char *active = NULL, *console;
+ bool b;
+
+ if (startswith(tty, "/dev/"))
+ tty += 5;
+
+ /* trivial identity? */
+ if (streq(tty, "console"))
+ return true;
+
+ console = resolve_dev_console(&active);
+ /* if we could not resolve, assume it may */
+ if (!console)
+ return true;
+
+ /* "tty0" means the active VC, so it may be the same sometimes */
+ b = streq(console, tty) || (streq(console, "tty0") && tty_is_vc(tty));
+ free(active);
+
+ return b;
+}
+
+bool exec_context_may_touch_console(ExecContext *ec) {
+ return (ec->tty_reset || ec->tty_vhangup || ec->tty_vt_disallocate ||
+ is_terminal_input(ec->std_input) ||
+ is_terminal_output(ec->std_output) ||
+ is_terminal_output(ec->std_error)) &&
+ tty_may_match_dev_console(tty_path(ec));
+}
+
+static void strv_fprintf(FILE *f, char **l) {
+ char **g;
+
+ assert(f);
+
+ STRV_FOREACH(g, l)
+ fprintf(f, " %s", *g);
+}
+
+void exec_context_dump(ExecContext *c, FILE* f, const char *prefix) {
+ char ** e;
+ unsigned i;
+
+ assert(c);
+ assert(f);
+
+ if (!prefix)
+ prefix = "";
+
+ fprintf(f,
+ "%sUMask: %04o\n"
+ "%sWorkingDirectory: %s\n"
+ "%sRootDirectory: %s\n"
+ "%sNonBlocking: %s\n"
+ "%sPrivateTmp: %s\n"
+ "%sControlGroupModify: %s\n"
+ "%sControlGroupPersistent: %s\n"
+ "%sPrivateNetwork: %s\n"
+ "%sIgnoreSIGPIPE: %s\n",
+ prefix, c->umask,
+ prefix, c->working_directory ? c->working_directory : "/",
+ prefix, c->root_directory ? c->root_directory : "/",
+ prefix, yes_no(c->non_blocking),
+ prefix, yes_no(c->private_tmp),
+ prefix, yes_no(c->control_group_modify),
+ prefix, yes_no(c->control_group_persistent),
+ prefix, yes_no(c->private_network),
+ prefix, yes_no(c->ignore_sigpipe));
+
+ STRV_FOREACH(e, c->environment)
+ fprintf(f, "%sEnvironment: %s\n", prefix, *e);
+
+ STRV_FOREACH(e, c->environment_files)
+ fprintf(f, "%sEnvironmentFile: %s\n", prefix, *e);
+
+ if (c->tcpwrap_name)
+ fprintf(f,
+ "%sTCPWrapName: %s\n",
+ prefix, c->tcpwrap_name);
+
+ if (c->nice_set)
+ fprintf(f,
+ "%sNice: %i\n",
+ prefix, c->nice);
+
+ if (c->oom_score_adjust_set)
+ fprintf(f,
+ "%sOOMScoreAdjust: %i\n",
+ prefix, c->oom_score_adjust);
+
+ for (i = 0; i < RLIM_NLIMITS; i++)
+ if (c->rlimit[i])
+ fprintf(f, "%s%s: %llu\n", prefix, rlimit_to_string(i), (unsigned long long) c->rlimit[i]->rlim_max);
+
+ if (c->ioprio_set) {
+ char *class_str;
+ int r;
+
+ r = ioprio_class_to_string_alloc(IOPRIO_PRIO_CLASS(c->ioprio), &class_str);
+ if (r < 0)
+ class_str = NULL;
+ fprintf(f,
+ "%sIOSchedulingClass: %s\n"
+ "%sIOPriority: %i\n",
+ prefix, strna(class_str),
+ prefix, (int) IOPRIO_PRIO_DATA(c->ioprio));
+ free(class_str);
+ }
+
+ if (c->cpu_sched_set) {
+ char *policy_str;
+ int r;
+
+ r = sched_policy_to_string_alloc(c->cpu_sched_policy, &policy_str);
+ if (r < 0)
+ policy_str = NULL;
+ fprintf(f,
+ "%sCPUSchedulingPolicy: %s\n"
+ "%sCPUSchedulingPriority: %i\n"
+ "%sCPUSchedulingResetOnFork: %s\n",
+ prefix, strna(policy_str),
+ prefix, c->cpu_sched_priority,
+ prefix, yes_no(c->cpu_sched_reset_on_fork));
+ free(policy_str);
+ }
+
+ if (c->cpuset) {
+ fprintf(f, "%sCPUAffinity:", prefix);
+ for (i = 0; i < c->cpuset_ncpus; i++)
+ if (CPU_ISSET_S(i, CPU_ALLOC_SIZE(c->cpuset_ncpus), c->cpuset))
+ fprintf(f, " %i", i);
+ fputs("\n", f);
+ }
+
+ if (c->timer_slack_nsec != (nsec_t) -1)
+ fprintf(f, "%sTimerSlackNSec: %lu\n", prefix, (unsigned long)c->timer_slack_nsec);
+
+ fprintf(f,
+ "%sStandardInput: %s\n"
+ "%sStandardOutput: %s\n"
+ "%sStandardError: %s\n",
+ prefix, exec_input_to_string(c->std_input),
+ prefix, exec_output_to_string(c->std_output),
+ prefix, exec_output_to_string(c->std_error));
+
+ if (c->tty_path)
+ fprintf(f,
+ "%sTTYPath: %s\n"
+ "%sTTYReset: %s\n"
+ "%sTTYVHangup: %s\n"
+ "%sTTYVTDisallocate: %s\n",
+ prefix, c->tty_path,
+ prefix, yes_no(c->tty_reset),
+ prefix, yes_no(c->tty_vhangup),
+ prefix, yes_no(c->tty_vt_disallocate));
+
+ if (c->std_output == EXEC_OUTPUT_SYSLOG || c->std_output == EXEC_OUTPUT_KMSG || c->std_output == EXEC_OUTPUT_JOURNAL ||
+ c->std_output == EXEC_OUTPUT_SYSLOG_AND_CONSOLE || c->std_output == EXEC_OUTPUT_KMSG_AND_CONSOLE || c->std_output == EXEC_OUTPUT_JOURNAL_AND_CONSOLE ||
+ c->std_error == EXEC_OUTPUT_SYSLOG || c->std_error == EXEC_OUTPUT_KMSG || c->std_error == EXEC_OUTPUT_JOURNAL ||
+ c->std_error == EXEC_OUTPUT_SYSLOG_AND_CONSOLE || c->std_error == EXEC_OUTPUT_KMSG_AND_CONSOLE || c->std_error == EXEC_OUTPUT_JOURNAL_AND_CONSOLE) {
+ char *fac_str, *lvl_str;
+ int r;
+
+ r = log_facility_unshifted_to_string_alloc(c->syslog_priority >> 3, &fac_str);
+ if (r < 0)
+ fac_str = NULL;
+
+ r = log_level_to_string_alloc(LOG_PRI(c->syslog_priority), &lvl_str);
+ if (r < 0)
+ lvl_str = NULL;
+
+ fprintf(f,
+ "%sSyslogFacility: %s\n"
+ "%sSyslogLevel: %s\n",
+ prefix, strna(fac_str),
+ prefix, strna(lvl_str));
+ free(lvl_str);
+ free(fac_str);
+ }
+
+ if (c->capabilities) {
+ char *t;
+ if ((t = cap_to_text(c->capabilities, NULL))) {
+ fprintf(f, "%sCapabilities: %s\n",
+ prefix, t);
+ cap_free(t);
+ }
+ }
+
+ if (c->secure_bits)
+ fprintf(f, "%sSecure Bits:%s%s%s%s%s%s\n",
+ prefix,
+ (c->secure_bits & 1<<SECURE_KEEP_CAPS) ? " keep-caps" : "",
+ (c->secure_bits & 1<<SECURE_KEEP_CAPS_LOCKED) ? " keep-caps-locked" : "",
+ (c->secure_bits & 1<<SECURE_NO_SETUID_FIXUP) ? " no-setuid-fixup" : "",
+ (c->secure_bits & 1<<SECURE_NO_SETUID_FIXUP_LOCKED) ? " no-setuid-fixup-locked" : "",
+ (c->secure_bits & 1<<SECURE_NOROOT) ? " noroot" : "",
+ (c->secure_bits & 1<<SECURE_NOROOT_LOCKED) ? "noroot-locked" : "");
+
+ if (c->capability_bounding_set_drop) {
+ unsigned long l;
+ fprintf(f, "%sCapabilityBoundingSet:", prefix);
+
+ for (l = 0; l <= cap_last_cap(); l++)
+ if (!(c->capability_bounding_set_drop & ((uint64_t) 1ULL << (uint64_t) l))) {
+ char *t;
+
+ if ((t = cap_to_name(l))) {
+ fprintf(f, " %s", t);
+ cap_free(t);
+ }
+ }
+
+ fputs("\n", f);
+ }
+
+ if (c->user)
+ fprintf(f, "%sUser: %s\n", prefix, c->user);
+ if (c->group)
+ fprintf(f, "%sGroup: %s\n", prefix, c->group);
+
+ if (strv_length(c->supplementary_groups) > 0) {
+ fprintf(f, "%sSupplementaryGroups:", prefix);
+ strv_fprintf(f, c->supplementary_groups);
+ fputs("\n", f);
+ }
+
+ if (c->pam_name)
+ fprintf(f, "%sPAMName: %s\n", prefix, c->pam_name);
+
+ if (strv_length(c->read_write_dirs) > 0) {
+ fprintf(f, "%sReadWriteDirs:", prefix);
+ strv_fprintf(f, c->read_write_dirs);
+ fputs("\n", f);
+ }
+
+ if (strv_length(c->read_only_dirs) > 0) {
+ fprintf(f, "%sReadOnlyDirs:", prefix);
+ strv_fprintf(f, c->read_only_dirs);
+ fputs("\n", f);
+ }
+
+ if (strv_length(c->inaccessible_dirs) > 0) {
+ fprintf(f, "%sInaccessibleDirs:", prefix);
+ strv_fprintf(f, c->inaccessible_dirs);
+ fputs("\n", f);
+ }
+
+ if (c->utmp_id)
+ fprintf(f,
+ "%sUtmpIdentifier: %s\n",
+ prefix, c->utmp_id);
+}
+
+void exec_status_start(ExecStatus *s, pid_t pid) {
+ assert(s);
+
+ zero(*s);
+ s->pid = pid;
+ dual_timestamp_get(&s->start_timestamp);
+}
+
+void exec_status_exit(ExecStatus *s, ExecContext *context, pid_t pid, int code, int status) {
+ assert(s);
+
+ if (s->pid && s->pid != pid)
+ zero(*s);
+
+ s->pid = pid;
+ dual_timestamp_get(&s->exit_timestamp);
+
+ s->code = code;
+ s->status = status;
+
+ if (context) {
+ if (context->utmp_id)
+ utmp_put_dead_process(context->utmp_id, pid, code, status);
+
+ exec_context_tty_reset(context);
+ }
+}
+
+void exec_status_dump(ExecStatus *s, FILE *f, const char *prefix) {
+ char buf[FORMAT_TIMESTAMP_MAX];
+
+ assert(s);
+ assert(f);
+
+ if (!prefix)
+ prefix = "";
+
+ if (s->pid <= 0)
+ return;
+
+ fprintf(f,
+ "%sPID: %lu\n",
+ prefix, (unsigned long) s->pid);
+
+ if (s->start_timestamp.realtime > 0)
+ fprintf(f,
+ "%sStart Timestamp: %s\n",
+ prefix, format_timestamp(buf, sizeof(buf), s->start_timestamp.realtime));
+
+ if (s->exit_timestamp.realtime > 0)
+ fprintf(f,
+ "%sExit Timestamp: %s\n"
+ "%sExit Code: %s\n"
+ "%sExit Status: %i\n",
+ prefix, format_timestamp(buf, sizeof(buf), s->exit_timestamp.realtime),
+ prefix, sigchld_code_to_string(s->code),
+ prefix, s->status);
+}
+
+char *exec_command_line(char **argv) {
+ size_t k;
+ char *n, *p, **a;
+ bool first = true;
+
+ assert(argv);
+
+ k = 1;
+ STRV_FOREACH(a, argv)
+ k += strlen(*a)+3;
+
+ if (!(n = new(char, k)))
+ return NULL;
+
+ p = n;
+ STRV_FOREACH(a, argv) {
+
+ if (!first)
+ *(p++) = ' ';
+ else
+ first = false;
+
+ if (strpbrk(*a, WHITESPACE)) {
+ *(p++) = '\'';
+ p = stpcpy(p, *a);
+ *(p++) = '\'';
+ } else
+ p = stpcpy(p, *a);
+
+ }
+
+ *p = 0;
+
+ /* FIXME: this doesn't really handle arguments that have
+ * spaces and ticks in them */
+
+ return n;
+}
+
+void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) {
+ char *p2;
+ const char *prefix2;
+
+ char *cmd;
+
+ assert(c);
+ assert(f);
+
+ if (!prefix)
+ prefix = "";
+ p2 = strappend(prefix, "\t");
+ prefix2 = p2 ? p2 : prefix;
+
+ cmd = exec_command_line(c->argv);
+
+ fprintf(f,
+ "%sCommand Line: %s\n",
+ prefix, cmd ? cmd : strerror(ENOMEM));
+
+ free(cmd);
+
+ exec_status_dump(&c->exec_status, f, prefix2);
+
+ free(p2);
+}
+
+void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) {
+ assert(f);
+
+ if (!prefix)
+ prefix = "";
+
+ LIST_FOREACH(command, c, c)
+ exec_command_dump(c, f, prefix);
+}
+
+void exec_command_append_list(ExecCommand **l, ExecCommand *e) {
+ ExecCommand *end;
+
+ assert(l);
+ assert(e);
+
+ if (*l) {
+ /* It's kind of important, that we keep the order here */
+ LIST_FIND_TAIL(ExecCommand, command, *l, end);
+ LIST_INSERT_AFTER(ExecCommand, command, *l, end, e);
+ } else
+ *l = e;
+}
+
+int exec_command_set(ExecCommand *c, const char *path, ...) {
+ va_list ap;
+ char **l, *p;
+
+ assert(c);
+ assert(path);
+
+ va_start(ap, path);
+ l = strv_new_ap(path, ap);
+ va_end(ap);
+
+ if (!l)
+ return -ENOMEM;
+
+ if (!(p = strdup(path))) {
+ strv_free(l);
+ return -ENOMEM;
+ }
+
+ free(c->path);
+ c->path = p;
+
+ strv_free(c->argv);
+ c->argv = l;
+
+ return 0;
+}
+
+static const char* const exec_input_table[_EXEC_INPUT_MAX] = {
+ [EXEC_INPUT_NULL] = "null",
+ [EXEC_INPUT_TTY] = "tty",
+ [EXEC_INPUT_TTY_FORCE] = "tty-force",
+ [EXEC_INPUT_TTY_FAIL] = "tty-fail",
+ [EXEC_INPUT_SOCKET] = "socket"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(exec_input, ExecInput);
+
+static const char* const exec_output_table[_EXEC_OUTPUT_MAX] = {
+ [EXEC_OUTPUT_INHERIT] = "inherit",
+ [EXEC_OUTPUT_NULL] = "null",
+ [EXEC_OUTPUT_TTY] = "tty",
+ [EXEC_OUTPUT_SYSLOG] = "syslog",
+ [EXEC_OUTPUT_SYSLOG_AND_CONSOLE] = "syslog+console",
+ [EXEC_OUTPUT_KMSG] = "kmsg",
+ [EXEC_OUTPUT_KMSG_AND_CONSOLE] = "kmsg+console",
+ [EXEC_OUTPUT_JOURNAL] = "journal",
+ [EXEC_OUTPUT_JOURNAL_AND_CONSOLE] = "journal+console",
+ [EXEC_OUTPUT_SOCKET] = "socket"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(exec_output, ExecOutput);
diff --git a/src/core/execute.h b/src/core/execute.h
new file mode 100644
index 0000000000..15574dc97e
--- /dev/null
+++ b/src/core/execute.h
@@ -0,0 +1,217 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+typedef struct ExecStatus ExecStatus;
+typedef struct ExecCommand ExecCommand;
+typedef struct ExecContext ExecContext;
+
+#include <linux/types.h>
+#include <sys/time.h>
+#include <sys/resource.h>
+#include <sys/capability.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <sched.h>
+
+struct CGroupBonding;
+struct CGroupAttribute;
+
+typedef struct Unit Unit;
+
+#include "list.h"
+#include "util.h"
+
+typedef enum ExecInput {
+ EXEC_INPUT_NULL,
+ EXEC_INPUT_TTY,
+ EXEC_INPUT_TTY_FORCE,
+ EXEC_INPUT_TTY_FAIL,
+ EXEC_INPUT_SOCKET,
+ _EXEC_INPUT_MAX,
+ _EXEC_INPUT_INVALID = -1
+} ExecInput;
+
+typedef enum ExecOutput {
+ EXEC_OUTPUT_INHERIT,
+ EXEC_OUTPUT_NULL,
+ EXEC_OUTPUT_TTY,
+ EXEC_OUTPUT_SYSLOG,
+ EXEC_OUTPUT_SYSLOG_AND_CONSOLE,
+ EXEC_OUTPUT_KMSG,
+ EXEC_OUTPUT_KMSG_AND_CONSOLE,
+ EXEC_OUTPUT_JOURNAL,
+ EXEC_OUTPUT_JOURNAL_AND_CONSOLE,
+ EXEC_OUTPUT_SOCKET,
+ _EXEC_OUTPUT_MAX,
+ _EXEC_OUTPUT_INVALID = -1
+} ExecOutput;
+
+struct ExecStatus {
+ dual_timestamp start_timestamp;
+ dual_timestamp exit_timestamp;
+ pid_t pid;
+ int code; /* as in siginfo_t::si_code */
+ int status; /* as in sigingo_t::si_status */
+};
+
+struct ExecCommand {
+ char *path;
+ char **argv;
+ ExecStatus exec_status;
+ LIST_FIELDS(ExecCommand, command); /* useful for chaining commands */
+ bool ignore;
+};
+
+struct ExecContext {
+ char **environment;
+ char **environment_files;
+
+ struct rlimit *rlimit[RLIMIT_NLIMITS];
+ char *working_directory, *root_directory;
+
+ mode_t umask;
+ int oom_score_adjust;
+ int nice;
+ int ioprio;
+ int cpu_sched_policy;
+ int cpu_sched_priority;
+
+ cpu_set_t *cpuset;
+ unsigned cpuset_ncpus;
+
+ ExecInput std_input;
+ ExecOutput std_output;
+ ExecOutput std_error;
+
+ nsec_t timer_slack_nsec;
+
+ char *tcpwrap_name;
+
+ char *tty_path;
+
+ bool tty_reset;
+ bool tty_vhangup;
+ bool tty_vt_disallocate;
+
+ bool ignore_sigpipe;
+
+ /* Since resolving these names might might involve socket
+ * connections and we don't want to deadlock ourselves these
+ * names are resolved on execution only and in the child
+ * process. */
+ char *user;
+ char *group;
+ char **supplementary_groups;
+
+ char *pam_name;
+
+ char *utmp_id;
+
+ char **read_write_dirs, **read_only_dirs, **inaccessible_dirs;
+ unsigned long mount_flags;
+
+ uint64_t capability_bounding_set_drop;
+
+ cap_t capabilities;
+ int secure_bits;
+
+ int syslog_priority;
+ char *syslog_identifier;
+ bool syslog_level_prefix;
+
+ bool cpu_sched_reset_on_fork;
+ bool non_blocking;
+ bool private_tmp;
+ bool private_network;
+ char *tmp_dir;
+ char *var_tmp_dir;
+
+ bool no_new_privileges;
+
+ bool control_group_modify;
+ int control_group_persistent;
+
+ /* This is not exposed to the user but available
+ * internally. We need it to make sure that whenever we spawn
+ * /bin/mount it is run in the same process group as us so
+ * that the autofs logic detects that it belongs to us and we
+ * don't enter a trigger loop. */
+ bool same_pgrp;
+
+ uint32_t *syscall_filter;
+
+ bool oom_score_adjust_set:1;
+ bool nice_set:1;
+ bool ioprio_set:1;
+ bool cpu_sched_set:1;
+};
+
+int exec_spawn(ExecCommand *command,
+ char **argv,
+ ExecContext *context,
+ int fds[], unsigned n_fds,
+ char **environment,
+ bool apply_permissions,
+ bool apply_chroot,
+ bool apply_tty_stdin,
+ bool confirm_spawn,
+ struct CGroupBonding *cgroup_bondings,
+ struct CGroupAttribute *cgroup_attributes,
+ const char *cgroup_suffix,
+ const char *unit_id,
+ int pipe_fd[2],
+ pid_t *ret);
+
+void exec_command_done(ExecCommand *c);
+void exec_command_done_array(ExecCommand *c, unsigned n);
+
+void exec_command_free_list(ExecCommand *c);
+void exec_command_free_array(ExecCommand **c, unsigned n);
+
+char *exec_command_line(char **argv);
+
+void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix);
+void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix);
+void exec_command_append_list(ExecCommand **l, ExecCommand *e);
+int exec_command_set(ExecCommand *c, const char *path, ...);
+
+void exec_context_init(ExecContext *c);
+void exec_context_done(ExecContext *c, bool reloading_or_reexecuting);
+void exec_context_tmp_dirs_done(ExecContext *c);
+void exec_context_dump(ExecContext *c, FILE* f, const char *prefix);
+void exec_context_tty_reset(const ExecContext *context);
+
+int exec_context_load_environment(const ExecContext *c, char ***l);
+
+bool exec_context_may_touch_console(ExecContext *c);
+void exec_context_serialize(const ExecContext *c, Unit *u, FILE *f);
+
+void exec_status_start(ExecStatus *s, pid_t pid);
+void exec_status_exit(ExecStatus *s, ExecContext *context, pid_t pid, int code, int status);
+void exec_status_dump(ExecStatus *s, FILE *f, const char *prefix);
+
+const char* exec_output_to_string(ExecOutput i) _const_;
+ExecOutput exec_output_from_string(const char *s) _pure_;
+
+const char* exec_input_to_string(ExecInput i) _const_;
+ExecInput exec_input_from_string(const char *s) _pure_;
diff --git a/src/core/hostname-setup.c b/src/core/hostname-setup.c
new file mode 100644
index 0000000000..8aa1cff1d3
--- /dev/null
+++ b/src/core/hostname-setup.c
@@ -0,0 +1,92 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <unistd.h>
+#include <stdio.h>
+#include <errno.h>
+#include <string.h>
+#include <stdlib.h>
+
+#include "hostname-setup.h"
+#include "macro.h"
+#include "util.h"
+#include "log.h"
+#include "fileio.h"
+
+static int read_and_strip_hostname(const char *path, char **hn) {
+ char *s;
+ int r;
+
+ assert(path);
+ assert(hn);
+
+ r = read_one_line_file(path, &s);
+ if (r < 0)
+ return r;
+
+ hostname_cleanup(s, false);
+
+ if (isempty(s)) {
+ free(s);
+ return -ENOENT;
+ }
+
+ *hn = s;
+ return 0;
+}
+
+int hostname_setup(void) {
+ int r;
+ _cleanup_free_ char *b = NULL;
+ const char *hn;
+ bool enoent = false;
+
+ r = read_and_strip_hostname("/etc/hostname", &b);
+ if (r < 0) {
+ if (r == -ENOENT)
+ enoent = true;
+ else
+ log_warning("Failed to read configured hostname: %s", strerror(-r));
+
+ hn = NULL;
+ } else
+ hn = b;
+
+ if (isempty(hn)) {
+ /* Don't override the hostname if it is already set
+ * and not explicitly configured */
+ if (hostname_is_set())
+ return 0;
+
+ if (enoent)
+ log_info("No hostname configured.");
+
+ hn = "localhost";
+ }
+
+ if (sethostname(hn, strlen(hn)) < 0) {
+ log_warning("Failed to set hostname to <%s>: %m", hn);
+ return -errno;
+ }
+
+ log_info("Set hostname to <%s>.", hn);
+ return 0;
+}
diff --git a/src/core/hostname-setup.h b/src/core/hostname-setup.h
new file mode 100644
index 0000000000..8dc3a9e1d8
--- /dev/null
+++ b/src/core/hostname-setup.h
@@ -0,0 +1,24 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+int hostname_setup(void);
diff --git a/src/core/ima-setup.c b/src/core/ima-setup.c
new file mode 100644
index 0000000000..7f8ec23d58
--- /dev/null
+++ b/src/core/ima-setup.c
@@ -0,0 +1,110 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+ Copyright (C) 2012 Roberto Sassu - Politecnico di Torino, Italy
+ TORSEC group -- http://security.polito.it
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <unistd.h>
+#include <stdio.h>
+#include <errno.h>
+#include <string.h>
+#include <stdlib.h>
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <sys/mman.h>
+
+#include "ima-setup.h"
+#include "mount-setup.h"
+#include "macro.h"
+#include "util.h"
+#include "log.h"
+#include "label.h"
+
+#define IMA_SECFS_DIR "/sys/kernel/security/ima"
+#define IMA_SECFS_POLICY IMA_SECFS_DIR "/policy"
+#define IMA_POLICY_PATH "/etc/ima/ima-policy"
+
+int ima_setup(void) {
+
+#ifdef HAVE_IMA
+ struct stat st;
+ ssize_t policy_size = 0, written = 0;
+ char *policy;
+ int policyfd = -1, imafd = -1;
+ int result = 0;
+
+ if (stat(IMA_POLICY_PATH, &st) < 0)
+ return 0;
+
+ policy_size = st.st_size;
+ if (stat(IMA_SECFS_DIR, &st) < 0) {
+ log_debug("IMA support is disabled in the kernel, ignoring.");
+ return 0;
+ }
+
+ if (stat(IMA_SECFS_POLICY, &st) < 0) {
+ log_error("Another IMA custom policy has already been loaded, "
+ "ignoring.");
+ return 0;
+ }
+
+ policyfd = open(IMA_POLICY_PATH, O_RDONLY|O_CLOEXEC);
+ if (policyfd < 0) {
+ log_error("Failed to open the IMA custom policy file %s (%m), "
+ "ignoring.", IMA_POLICY_PATH);
+ return 0;
+ }
+
+ imafd = open(IMA_SECFS_POLICY, O_WRONLY|O_CLOEXEC);
+ if (imafd < 0) {
+ log_error("Failed to open the IMA kernel interface %s (%m), "
+ "ignoring.", IMA_SECFS_POLICY);
+ goto out;
+ }
+
+ policy = mmap(NULL, policy_size, PROT_READ, MAP_PRIVATE, policyfd, 0);
+ if (policy == MAP_FAILED) {
+ log_error("mmap() failed (%m), freezing");
+ result = -errno;
+ goto out;
+ }
+
+ written = loop_write(imafd, policy, (size_t)policy_size, false);
+ if (written != policy_size) {
+ log_error("Failed to load the IMA custom policy file %s (%m), "
+ "ignoring.", IMA_POLICY_PATH);
+ goto out_mmap;
+ }
+
+ log_info("Successfully loaded the IMA custom policy %s.",
+ IMA_POLICY_PATH);
+out_mmap:
+ munmap(policy, policy_size);
+out:
+ if (policyfd >= 0)
+ close_nointr_nofail(policyfd);
+ if (imafd >= 0)
+ close_nointr_nofail(imafd);
+ if (result)
+ return result;
+#endif /* HAVE_IMA */
+
+ return 0;
+}
diff --git a/src/core/ima-setup.h b/src/core/ima-setup.h
new file mode 100644
index 0000000000..14b56d1fc2
--- /dev/null
+++ b/src/core/ima-setup.h
@@ -0,0 +1,26 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+ Copyright (C) 2012 Roberto Sassu - Politecnico di Torino, Italy
+ TORSEC group -- http://security.polito.it
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+int ima_setup(void);
diff --git a/src/core/initreq.h b/src/core/initreq.h
new file mode 100644
index 0000000000..859042ce42
--- /dev/null
+++ b/src/core/initreq.h
@@ -0,0 +1,77 @@
+/*
+ * initreq.h Interface to talk to init through /dev/initctl.
+ *
+ * Copyright (C) 1995-2004 Miquel van Smoorenburg
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * Version: @(#)initreq.h 1.28 31-Mar-2004 MvS
+ *
+ */
+#ifndef _INITREQ_H
+#define _INITREQ_H
+
+#include <sys/param.h>
+
+#if defined(__FreeBSD_kernel__)
+# define INIT_FIFO "/etc/.initctl"
+#else
+# define INIT_FIFO "/dev/initctl"
+#endif
+
+#define INIT_MAGIC 0x03091969
+#define INIT_CMD_START 0
+#define INIT_CMD_RUNLVL 1
+#define INIT_CMD_POWERFAIL 2
+#define INIT_CMD_POWERFAILNOW 3
+#define INIT_CMD_POWEROK 4
+#define INIT_CMD_BSD 5
+#define INIT_CMD_SETENV 6
+#define INIT_CMD_UNSETENV 7
+
+#define INIT_CMD_CHANGECONS 12345
+
+#ifdef MAXHOSTNAMELEN
+# define INITRQ_HLEN MAXHOSTNAMELEN
+#else
+# define INITRQ_HLEN 64
+#endif
+
+/*
+ * This is what BSD 4.4 uses when talking to init.
+ * Linux doesn't use this right now.
+ */
+struct init_request_bsd {
+ char gen_id[8]; /* Beats me.. telnetd uses "fe" */
+ char tty_id[16]; /* Tty name minus /dev/tty */
+ char host[INITRQ_HLEN]; /* Hostname */
+ char term_type[16]; /* Terminal type */
+ int signal; /* Signal to send */
+ int pid; /* Process to send to */
+ char exec_name[128]; /* Program to execute */
+ char reserved[128]; /* For future expansion. */
+};
+
+
+/*
+ * Because of legacy interfaces, "runlevel" and "sleeptime"
+ * aren't in a separate struct in the union.
+ *
+ * The weird sizes are because init expects the whole
+ * struct to be 384 bytes.
+ */
+struct init_request {
+ int magic; /* Magic number */
+ int cmd; /* What kind of request */
+ int runlevel; /* Runlevel to change to */
+ int sleeptime; /* Time between TERM and KILL */
+ union {
+ struct init_request_bsd bsd;
+ char data[368];
+ } i;
+};
+
+#endif
diff --git a/src/core/job.c b/src/core/job.c
new file mode 100644
index 0000000000..d304a16d06
--- /dev/null
+++ b/src/core/job.c
@@ -0,0 +1,1143 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <errno.h>
+#include <sys/timerfd.h>
+#include <sys/epoll.h>
+
+#include "systemd/sd-id128.h"
+#include "systemd/sd-messages.h"
+#include "set.h"
+#include "unit.h"
+#include "macro.h"
+#include "strv.h"
+#include "load-fragment.h"
+#include "load-dropin.h"
+#include "log.h"
+#include "dbus-job.h"
+#include "special.h"
+#include "sync.h"
+#include "virt.h"
+
+JobBusClient* job_bus_client_new(DBusConnection *connection, const char *name) {
+ JobBusClient *cl;
+ size_t name_len;
+
+ name_len = strlen(name);
+ cl = malloc0(sizeof(JobBusClient) + name_len + 1);
+ if (!cl)
+ return NULL;
+
+ cl->bus = connection;
+ memcpy(cl->name, name, name_len + 1);
+ return cl;
+}
+
+Job* job_new_raw(Unit *unit) {
+ Job *j;
+
+ /* used for deserialization */
+
+ assert(unit);
+
+ j = new0(Job, 1);
+ if (!j)
+ return NULL;
+
+ j->manager = unit->manager;
+ j->unit = unit;
+ j->type = _JOB_TYPE_INVALID;
+ j->timer_watch.type = WATCH_INVALID;
+
+ return j;
+}
+
+Job* job_new(Unit *unit, JobType type) {
+ Job *j;
+
+ assert(type < _JOB_TYPE_MAX);
+
+ j = job_new_raw(unit);
+ if (!j)
+ return NULL;
+
+ j->id = j->manager->current_job_id++;
+ j->type = type;
+
+ /* We don't link it here, that's what job_dependency() is for */
+
+ return j;
+}
+
+void job_free(Job *j) {
+ JobBusClient *cl;
+
+ assert(j);
+ assert(!j->installed);
+ assert(!j->transaction_prev);
+ assert(!j->transaction_next);
+ assert(!j->subject_list);
+ assert(!j->object_list);
+
+ if (j->in_run_queue)
+ LIST_REMOVE(Job, run_queue, j->manager->run_queue, j);
+
+ if (j->in_dbus_queue)
+ LIST_REMOVE(Job, dbus_queue, j->manager->dbus_job_queue, j);
+
+ if (j->timer_watch.type != WATCH_INVALID) {
+ assert(j->timer_watch.type == WATCH_JOB_TIMER);
+ assert(j->timer_watch.data.job == j);
+ assert(j->timer_watch.fd >= 0);
+
+ assert_se(epoll_ctl(j->manager->epoll_fd, EPOLL_CTL_DEL, j->timer_watch.fd, NULL) >= 0);
+ close_nointr_nofail(j->timer_watch.fd);
+ }
+
+ while ((cl = j->bus_client_list)) {
+ LIST_REMOVE(JobBusClient, client, j->bus_client_list, cl);
+ free(cl);
+ }
+ free(j);
+}
+
+void job_uninstall(Job *j) {
+ Job **pj;
+
+ assert(j->installed);
+
+ pj = (j->type == JOB_NOP) ? &j->unit->nop_job : &j->unit->job;
+ assert(*pj == j);
+
+ /* Detach from next 'bigger' objects */
+
+ /* daemon-reload should be transparent to job observers */
+ if (j->manager->n_reloading <= 0)
+ bus_job_send_removed_signal(j);
+
+ *pj = NULL;
+
+ unit_add_to_gc_queue(j->unit);
+
+ hashmap_remove(j->manager->jobs, UINT32_TO_PTR(j->id));
+ j->installed = false;
+}
+
+static bool job_type_allows_late_merge(JobType t) {
+ /* Tells whether it is OK to merge a job of type 't' with an already
+ * running job.
+ * Reloads cannot be merged this way. Think of the sequence:
+ * 1. Reload of a daemon is in progress; the daemon has already loaded
+ * its config file, but hasn't completed the reload operation yet.
+ * 2. Edit foo's config file.
+ * 3. Trigger another reload to have the daemon use the new config.
+ * Should the second reload job be merged into the first one, the daemon
+ * would not know about the new config.
+ * JOB_RESTART jobs on the other hand can be merged, because they get
+ * patched into JOB_START after stopping the unit. So if we see a
+ * JOB_RESTART running, it means the unit hasn't stopped yet and at
+ * this time the merge is still allowed. */
+ return t != JOB_RELOAD;
+}
+
+static void job_merge_into_installed(Job *j, Job *other) {
+ assert(j->installed);
+ assert(j->unit == other->unit);
+
+ if (j->type != JOB_NOP)
+ job_type_merge_and_collapse(&j->type, other->type, j->unit);
+ else
+ assert(other->type == JOB_NOP);
+
+ j->override = j->override || other->override;
+ j->irreversible = j->irreversible || other->irreversible;
+ j->ignore_order = j->ignore_order || other->ignore_order;
+}
+
+Job* job_install(Job *j) {
+ Job **pj;
+ Job *uj;
+
+ assert(!j->installed);
+ assert(j->type < _JOB_TYPE_MAX_IN_TRANSACTION);
+
+ pj = (j->type == JOB_NOP) ? &j->unit->nop_job : &j->unit->job;
+ uj = *pj;
+
+ if (uj) {
+ if (j->type != JOB_NOP && job_type_is_conflicting(uj->type, j->type))
+ job_finish_and_invalidate(uj, JOB_CANCELED, false);
+ else {
+ /* not conflicting, i.e. mergeable */
+
+ if (j->type == JOB_NOP || uj->state == JOB_WAITING ||
+ (job_type_allows_late_merge(j->type) && job_type_is_superset(uj->type, j->type))) {
+ job_merge_into_installed(uj, j);
+ log_debug_unit(uj->unit->id,
+ "Merged into installed job %s/%s as %u",
+ uj->unit->id, job_type_to_string(uj->type), (unsigned) uj->id);
+ return uj;
+ } else {
+ /* already running and not safe to merge into */
+ /* Patch uj to become a merged job and re-run it. */
+ /* XXX It should be safer to queue j to run after uj finishes, but it is
+ * not currently possible to have more than one installed job per unit. */
+ job_merge_into_installed(uj, j);
+ log_debug_unit(uj->unit->id,
+ "Merged into running job, re-running: %s/%s as %u",
+ uj->unit->id, job_type_to_string(uj->type), (unsigned) uj->id);
+ uj->state = JOB_WAITING;
+ uj->manager->n_running_jobs--;
+ return uj;
+ }
+ }
+ }
+
+ /* Install the job */
+ *pj = j;
+ j->installed = true;
+ j->manager->n_installed_jobs ++;
+ log_debug_unit(j->unit->id,
+ "Installed new job %s/%s as %u",
+ j->unit->id, job_type_to_string(j->type), (unsigned) j->id);
+ return j;
+}
+
+int job_install_deserialized(Job *j) {
+ Job **pj;
+
+ assert(!j->installed);
+
+ if (j->type < 0 || j->type >= _JOB_TYPE_MAX_IN_TRANSACTION) {
+ log_debug("Invalid job type %s in deserialization.", strna(job_type_to_string(j->type)));
+ return -EINVAL;
+ }
+
+ pj = (j->type == JOB_NOP) ? &j->unit->nop_job : &j->unit->job;
+
+ if (*pj) {
+ log_debug_unit(j->unit->id,
+ "Unit %s already has a job installed. Not installing deserialized job.",
+ j->unit->id);
+ return -EEXIST;
+ }
+ *pj = j;
+ j->installed = true;
+ log_debug_unit(j->unit->id,
+ "Reinstalled deserialized job %s/%s as %u",
+ j->unit->id, job_type_to_string(j->type), (unsigned) j->id);
+ return 0;
+}
+
+JobDependency* job_dependency_new(Job *subject, Job *object, bool matters, bool conflicts) {
+ JobDependency *l;
+
+ assert(object);
+
+ /* Adds a new job link, which encodes that the 'subject' job
+ * needs the 'object' job in some way. If 'subject' is NULL
+ * this means the 'anchor' job (i.e. the one the user
+ * explicitly asked for) is the requester. */
+
+ if (!(l = new0(JobDependency, 1)))
+ return NULL;
+
+ l->subject = subject;
+ l->object = object;
+ l->matters = matters;
+ l->conflicts = conflicts;
+
+ if (subject)
+ LIST_PREPEND(JobDependency, subject, subject->subject_list, l);
+
+ LIST_PREPEND(JobDependency, object, object->object_list, l);
+
+ return l;
+}
+
+void job_dependency_free(JobDependency *l) {
+ assert(l);
+
+ if (l->subject)
+ LIST_REMOVE(JobDependency, subject, l->subject->subject_list, l);
+
+ LIST_REMOVE(JobDependency, object, l->object->object_list, l);
+
+ free(l);
+}
+
+void job_dump(Job *j, FILE*f, const char *prefix) {
+ assert(j);
+ assert(f);
+
+ if (!prefix)
+ prefix = "";
+
+ fprintf(f,
+ "%s-> Job %u:\n"
+ "%s\tAction: %s -> %s\n"
+ "%s\tState: %s\n"
+ "%s\tForced: %s\n"
+ "%s\tIrreversible: %s\n",
+ prefix, j->id,
+ prefix, j->unit->id, job_type_to_string(j->type),
+ prefix, job_state_to_string(j->state),
+ prefix, yes_no(j->override),
+ prefix, yes_no(j->irreversible));
+}
+
+/*
+ * Merging is commutative, so imagine the matrix as symmetric. We store only
+ * its lower triangle to avoid duplication. We don't store the main diagonal,
+ * because A merged with A is simply A.
+ *
+ * If the resulting type is collapsed immediately afterwards (to get rid of
+ * the JOB_RELOAD_OR_START, which lies outside the lookup function's domain),
+ * the following properties hold:
+ *
+ * Merging is associative! A merged with B merged with C is the same as
+ * A merged with C merged with B.
+ *
+ * Mergeability is transitive! If A can be merged with B and B with C then
+ * A also with C.
+ *
+ * Also, if A merged with B cannot be merged with C, then either A or B cannot
+ * be merged with C either.
+ */
+static const JobType job_merging_table[] = {
+/* What \ With * JOB_START JOB_VERIFY_ACTIVE JOB_STOP JOB_RELOAD */
+/*********************************************************************************/
+/*JOB_START */
+/*JOB_VERIFY_ACTIVE */ JOB_START,
+/*JOB_STOP */ -1, -1,
+/*JOB_RELOAD */ JOB_RELOAD_OR_START, JOB_RELOAD, -1,
+/*JOB_RESTART */ JOB_RESTART, JOB_RESTART, -1, JOB_RESTART,
+};
+
+JobType job_type_lookup_merge(JobType a, JobType b) {
+ assert_cc(ELEMENTSOF(job_merging_table) == _JOB_TYPE_MAX_MERGING * (_JOB_TYPE_MAX_MERGING - 1) / 2);
+ assert(a >= 0 && a < _JOB_TYPE_MAX_MERGING);
+ assert(b >= 0 && b < _JOB_TYPE_MAX_MERGING);
+
+ if (a == b)
+ return a;
+
+ if (a < b) {
+ JobType tmp = a;
+ a = b;
+ b = tmp;
+ }
+
+ return job_merging_table[(a - 1) * a / 2 + b];
+}
+
+bool job_type_is_redundant(JobType a, UnitActiveState b) {
+ switch (a) {
+
+ case JOB_START:
+ return
+ b == UNIT_ACTIVE ||
+ b == UNIT_RELOADING;
+
+ case JOB_STOP:
+ return
+ b == UNIT_INACTIVE ||
+ b == UNIT_FAILED;
+
+ case JOB_VERIFY_ACTIVE:
+ return
+ b == UNIT_ACTIVE ||
+ b == UNIT_RELOADING;
+
+ case JOB_RELOAD:
+ return
+ b == UNIT_RELOADING;
+
+ case JOB_RESTART:
+ return
+ b == UNIT_ACTIVATING;
+
+ default:
+ assert_not_reached("Invalid job type");
+ }
+}
+
+void job_type_collapse(JobType *t, Unit *u) {
+ UnitActiveState s;
+
+ switch (*t) {
+
+ case JOB_TRY_RESTART:
+ s = unit_active_state(u);
+ if (UNIT_IS_INACTIVE_OR_DEACTIVATING(s))
+ *t = JOB_NOP;
+ else
+ *t = JOB_RESTART;
+ break;
+
+ case JOB_RELOAD_OR_START:
+ s = unit_active_state(u);
+ if (UNIT_IS_INACTIVE_OR_DEACTIVATING(s))
+ *t = JOB_START;
+ else
+ *t = JOB_RELOAD;
+ break;
+
+ default:
+ ;
+ }
+}
+
+int job_type_merge_and_collapse(JobType *a, JobType b, Unit *u) {
+ JobType t = job_type_lookup_merge(*a, b);
+ if (t < 0)
+ return -EEXIST;
+ *a = t;
+ job_type_collapse(a, u);
+ return 0;
+}
+
+bool job_is_runnable(Job *j) {
+ Iterator i;
+ Unit *other;
+
+ assert(j);
+ assert(j->installed);
+
+ /* Checks whether there is any job running for the units this
+ * job needs to be running after (in the case of a 'positive'
+ * job type) or before (in the case of a 'negative' job
+ * type. */
+
+ /* First check if there is an override */
+ if (j->ignore_order)
+ return true;
+
+ if (j->type == JOB_NOP)
+ return true;
+
+ if (j->type == JOB_START ||
+ j->type == JOB_VERIFY_ACTIVE ||
+ j->type == JOB_RELOAD) {
+
+ /* Immediate result is that the job is or might be
+ * started. In this case lets wait for the
+ * dependencies, regardless whether they are
+ * starting or stopping something. */
+
+ SET_FOREACH(other, j->unit->dependencies[UNIT_AFTER], i)
+ if (other->job)
+ return false;
+ }
+
+ /* Also, if something else is being stopped and we should
+ * change state after it, then lets wait. */
+
+ SET_FOREACH(other, j->unit->dependencies[UNIT_BEFORE], i)
+ if (other->job &&
+ (other->job->type == JOB_STOP ||
+ other->job->type == JOB_RESTART))
+ return false;
+
+ /* This means that for a service a and a service b where b
+ * shall be started after a:
+ *
+ * start a + start b → 1st step start a, 2nd step start b
+ * start a + stop b → 1st step stop b, 2nd step start a
+ * stop a + start b → 1st step stop a, 2nd step start b
+ * stop a + stop b → 1st step stop b, 2nd step stop a
+ *
+ * This has the side effect that restarts are properly
+ * synchronized too. */
+
+ return true;
+}
+
+static void job_change_type(Job *j, JobType newtype) {
+ log_debug_unit(j->unit->id,
+ "Converting job %s/%s -> %s/%s",
+ j->unit->id, job_type_to_string(j->type),
+ j->unit->id, job_type_to_string(newtype));
+
+ j->type = newtype;
+}
+
+int job_run_and_invalidate(Job *j) {
+ int r;
+ uint32_t id;
+ Manager *m = j->manager;
+
+ assert(j);
+ assert(j->installed);
+ assert(j->type < _JOB_TYPE_MAX_IN_TRANSACTION);
+ assert(j->in_run_queue);
+
+ LIST_REMOVE(Job, run_queue, j->manager->run_queue, j);
+ j->in_run_queue = false;
+
+ if (j->state != JOB_WAITING)
+ return 0;
+
+ if (!job_is_runnable(j))
+ return -EAGAIN;
+
+ j->state = JOB_RUNNING;
+ m->n_running_jobs++;
+ job_add_to_dbus_queue(j);
+
+ /* While we execute this operation the job might go away (for
+ * example: because it is replaced by a new, conflicting
+ * job.) To make sure we don't access a freed job later on we
+ * store the id here, so that we can verify the job is still
+ * valid. */
+ id = j->id;
+
+ switch (j->type) {
+
+ case JOB_START:
+ r = unit_start(j->unit);
+
+ /* If this unit cannot be started, then simply wait */
+ if (r == -EBADR)
+ r = 0;
+ break;
+
+ case JOB_VERIFY_ACTIVE: {
+ UnitActiveState t = unit_active_state(j->unit);
+ if (UNIT_IS_ACTIVE_OR_RELOADING(t))
+ r = -EALREADY;
+ else if (t == UNIT_ACTIVATING)
+ r = -EAGAIN;
+ else
+ r = -ENOEXEC;
+ break;
+ }
+
+ case JOB_STOP:
+ case JOB_RESTART:
+ r = unit_stop(j->unit);
+
+ /* If this unit cannot stopped, then simply wait. */
+ if (r == -EBADR)
+ r = 0;
+ break;
+
+ case JOB_RELOAD:
+ r = unit_reload(j->unit);
+ break;
+
+ case JOB_NOP:
+ r = -EALREADY;
+ break;
+
+ default:
+ assert_not_reached("Unknown job type");
+ }
+
+ j = manager_get_job(m, id);
+ if (j) {
+ if (r == -EALREADY)
+ r = job_finish_and_invalidate(j, JOB_DONE, true);
+ else if (r == -ENOEXEC)
+ r = job_finish_and_invalidate(j, JOB_SKIPPED, true);
+ else if (r == -EAGAIN) {
+ j->state = JOB_WAITING;
+ m->n_running_jobs--;
+ } else if (r < 0)
+ r = job_finish_and_invalidate(j, JOB_FAILED, true);
+ }
+
+ return r;
+}
+
+_pure_ static const char *job_get_status_message_format(Unit *u, JobType t, JobResult result) {
+ const UnitStatusMessageFormats *format_table;
+
+ assert(u);
+ assert(t >= 0);
+ assert(t < _JOB_TYPE_MAX);
+
+ format_table = &UNIT_VTABLE(u)->status_message_formats;
+ if (!format_table)
+ return NULL;
+
+ if (t == JOB_START)
+ return format_table->finished_start_job[result];
+ else if (t == JOB_STOP || t == JOB_RESTART)
+ return format_table->finished_stop_job[result];
+
+ return NULL;
+}
+
+_pure_ static const char *job_get_status_message_format_try_harder(Unit *u, JobType t, JobResult result) {
+ const char *format;
+
+ assert(u);
+ assert(t >= 0);
+ assert(t < _JOB_TYPE_MAX);
+
+ format = job_get_status_message_format(u, t, result);
+ if (format)
+ return format;
+
+ /* Return generic strings */
+ if (t == JOB_START) {
+ if (result == JOB_DONE)
+ return "Started %s.";
+ else if (result == JOB_FAILED)
+ return "Failed to start %s.";
+ else if (result == JOB_DEPENDENCY)
+ return "Dependency failed for %s.";
+ else if (result == JOB_TIMEOUT)
+ return "Timed out starting %s.";
+ } else if (t == JOB_STOP || t == JOB_RESTART) {
+ if (result == JOB_DONE)
+ return "Stopped %s.";
+ else if (result == JOB_FAILED)
+ return "Stopped (with error) %s.";
+ else if (result == JOB_TIMEOUT)
+ return "Timed out stoppping %s.";
+ } else if (t == JOB_RELOAD) {
+ if (result == JOB_DONE)
+ return "Reloaded %s.";
+ else if (result == JOB_FAILED)
+ return "Reload failed for %s.";
+ else if (result == JOB_TIMEOUT)
+ return "Timed out reloading %s.";
+ }
+
+ return NULL;
+}
+
+static void job_print_status_message(Unit *u, JobType t, JobResult result) {
+ const char *format;
+
+ assert(u);
+ assert(t >= 0);
+ assert(t < _JOB_TYPE_MAX);
+
+ if (t == JOB_START) {
+ format = job_get_status_message_format(u, t, result);
+ if (!format)
+ return;
+
+ switch (result) {
+
+ case JOB_DONE:
+ if (u->condition_result)
+ unit_status_printf(u, ANSI_GREEN_ON " OK " ANSI_HIGHLIGHT_OFF, format);
+ break;
+
+ case JOB_FAILED:
+ unit_status_printf(u, ANSI_HIGHLIGHT_RED_ON "FAILED" ANSI_HIGHLIGHT_OFF, format);
+ manager_status_printf(u->manager, false, NULL, "See 'systemctl status %s' for details.", u->id);
+ break;
+
+ case JOB_DEPENDENCY:
+ unit_status_printf(u, ANSI_HIGHLIGHT_YELLOW_ON "DEPEND" ANSI_HIGHLIGHT_OFF, format);
+ break;
+
+ case JOB_TIMEOUT:
+ unit_status_printf(u, ANSI_HIGHLIGHT_RED_ON " TIME " ANSI_HIGHLIGHT_OFF, format);
+ break;
+
+ default:
+ ;
+ }
+
+ } else if (t == JOB_STOP || t == JOB_RESTART) {
+
+ format = job_get_status_message_format(u, t, result);
+ if (!format)
+ return;
+
+ switch (result) {
+
+ case JOB_TIMEOUT:
+ unit_status_printf(u, ANSI_HIGHLIGHT_RED_ON " TIME " ANSI_HIGHLIGHT_OFF, format);
+ break;
+
+ case JOB_DONE:
+ case JOB_FAILED:
+ unit_status_printf(u, ANSI_GREEN_ON " OK " ANSI_HIGHLIGHT_OFF, format);
+ break;
+
+ default:
+ ;
+ }
+
+ } else if (t == JOB_VERIFY_ACTIVE) {
+
+ /* When verify-active detects the unit is inactive, report it.
+ * Most likely a DEPEND warning from a requisiting unit will
+ * occur next and it's nice to see what was requisited. */
+ if (result == JOB_SKIPPED)
+ unit_status_printf(u, ANSI_HIGHLIGHT_ON " INFO " ANSI_HIGHLIGHT_OFF, "%s is not active.");
+ }
+}
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wformat-nonliteral"
+static void job_log_status_message(Unit *u, JobType t, JobResult result) {
+ const char *format;
+ char buf[LINE_MAX];
+
+ assert(u);
+ assert(t >= 0);
+ assert(t < _JOB_TYPE_MAX);
+
+ /* Skip this if it goes to the console. since we already print
+ * to the console anyway... */
+
+ if (log_on_console())
+ return;
+
+ format = job_get_status_message_format_try_harder(u, t, result);
+ if (!format)
+ return;
+
+ snprintf(buf, sizeof(buf), format, unit_description(u));
+ char_array_0(buf);
+
+ if (t == JOB_START) {
+ sd_id128_t mid;
+
+ mid = result == JOB_DONE ? SD_MESSAGE_UNIT_STARTED : SD_MESSAGE_UNIT_FAILED;
+ log_struct_unit(result == JOB_DONE ? LOG_INFO : LOG_ERR,
+ u->id,
+ MESSAGE_ID(mid),
+ "RESULT=%s", job_result_to_string(result),
+ "MESSAGE=%s", buf,
+ NULL);
+
+ } else if (t == JOB_STOP)
+ log_struct_unit(result == JOB_DONE ? LOG_INFO : LOG_ERR,
+ u->id,
+ MESSAGE_ID(SD_MESSAGE_UNIT_STOPPED),
+ "RESULT=%s", job_result_to_string(result),
+ "MESSAGE=%s", buf,
+ NULL);
+
+ else if (t == JOB_RELOAD)
+ log_struct_unit(result == JOB_DONE ? LOG_INFO : LOG_ERR,
+ u->id,
+ MESSAGE_ID(SD_MESSAGE_UNIT_RELOADED),
+ "RESULT=%s", job_result_to_string(result),
+ "MESSAGE=%s", buf,
+ NULL);
+}
+#pragma GCC diagnostic pop
+
+int job_finish_and_invalidate(Job *j, JobResult result, bool recursive) {
+ Unit *u;
+ Unit *other;
+ JobType t;
+ Iterator i;
+
+ assert(j);
+ assert(j->installed);
+ assert(j->type < _JOB_TYPE_MAX_IN_TRANSACTION);
+
+ u = j->unit;
+ t = j->type;
+
+ j->result = result;
+
+ if (j->state == JOB_RUNNING)
+ j->manager->n_running_jobs--;
+
+ log_debug_unit(u->id, "Job %s/%s finished, result=%s",
+ u->id, job_type_to_string(t), job_result_to_string(result));
+
+ job_print_status_message(u, t, result);
+ job_log_status_message(u, t, result);
+
+ job_add_to_dbus_queue(j);
+
+ /* Patch restart jobs so that they become normal start jobs */
+ if (result == JOB_DONE && t == JOB_RESTART) {
+
+ job_change_type(j, JOB_START);
+ j->state = JOB_WAITING;
+
+ job_add_to_run_queue(j);
+
+ goto finish;
+ }
+
+ if (result == JOB_FAILED)
+ j->manager->n_failed_jobs ++;
+
+ job_uninstall(j);
+ job_free(j);
+
+ /* Fail depending jobs on failure */
+ if (result != JOB_DONE && recursive) {
+
+ if (t == JOB_START ||
+ t == JOB_VERIFY_ACTIVE) {
+
+ SET_FOREACH(other, u->dependencies[UNIT_REQUIRED_BY], i)
+ if (other->job &&
+ (other->job->type == JOB_START ||
+ other->job->type == JOB_VERIFY_ACTIVE))
+ job_finish_and_invalidate(other->job, JOB_DEPENDENCY, true);
+
+ SET_FOREACH(other, u->dependencies[UNIT_BOUND_BY], i)
+ if (other->job &&
+ (other->job->type == JOB_START ||
+ other->job->type == JOB_VERIFY_ACTIVE))
+ job_finish_and_invalidate(other->job, JOB_DEPENDENCY, true);
+
+ SET_FOREACH(other, u->dependencies[UNIT_REQUIRED_BY_OVERRIDABLE], i)
+ if (other->job &&
+ !other->job->override &&
+ (other->job->type == JOB_START ||
+ other->job->type == JOB_VERIFY_ACTIVE))
+ job_finish_and_invalidate(other->job, JOB_DEPENDENCY, true);
+
+ } else if (t == JOB_STOP) {
+
+ SET_FOREACH(other, u->dependencies[UNIT_CONFLICTED_BY], i)
+ if (other->job &&
+ (other->job->type == JOB_START ||
+ other->job->type == JOB_VERIFY_ACTIVE))
+ job_finish_and_invalidate(other->job, JOB_DEPENDENCY, true);
+ }
+ }
+
+ /* Trigger OnFailure dependencies that are not generated by
+ * the unit itself. We don't treat JOB_CANCELED as failure in
+ * this context. And JOB_FAILURE is already handled by the
+ * unit itself. */
+ if (result == JOB_TIMEOUT || result == JOB_DEPENDENCY) {
+ log_struct_unit(LOG_NOTICE,
+ u->id,
+ "JOB_TYPE=%s", job_type_to_string(t),
+ "JOB_RESULT=%s", job_result_to_string(result),
+ "Job %s/%s failed with result '%s'.",
+ u->id,
+ job_type_to_string(t),
+ job_result_to_string(result),
+ NULL);
+
+ unit_start_on_failure(u);
+ }
+
+ unit_trigger_notify(u);
+
+finish:
+ /* Try to start the next jobs that can be started */
+ SET_FOREACH(other, u->dependencies[UNIT_AFTER], i)
+ if (other->job)
+ job_add_to_run_queue(other->job);
+ SET_FOREACH(other, u->dependencies[UNIT_BEFORE], i)
+ if (other->job)
+ job_add_to_run_queue(other->job);
+
+ manager_check_finished(u->manager);
+
+ return 0;
+}
+
+int job_start_timer(Job *j) {
+ struct itimerspec its = {};
+ struct epoll_event ev = {
+ .data.ptr = &j->timer_watch,
+ .events = EPOLLIN,
+ };
+ int fd, r;
+
+ if (j->unit->job_timeout <= 0 ||
+ j->timer_watch.type == WATCH_JOB_TIMER)
+ return 0;
+
+ assert(j->timer_watch.type == WATCH_INVALID);
+
+ if ((fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC)) < 0) {
+ r = -errno;
+ goto fail;
+ }
+
+ timespec_store(&its.it_value, j->unit->job_timeout);
+
+ if (timerfd_settime(fd, 0, &its, NULL) < 0) {
+ r = -errno;
+ goto fail;
+ }
+
+ if (epoll_ctl(j->manager->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
+ r = -errno;
+ goto fail;
+ }
+
+ j->timer_watch.type = WATCH_JOB_TIMER;
+ j->timer_watch.fd = fd;
+ j->timer_watch.data.job = j;
+
+ return 0;
+
+fail:
+ if (fd >= 0)
+ close_nointr_nofail(fd);
+
+ return r;
+}
+
+void job_add_to_run_queue(Job *j) {
+ assert(j);
+ assert(j->installed);
+
+ if (j->in_run_queue)
+ return;
+
+ LIST_PREPEND(Job, run_queue, j->manager->run_queue, j);
+ j->in_run_queue = true;
+}
+
+void job_add_to_dbus_queue(Job *j) {
+ assert(j);
+ assert(j->installed);
+
+ if (j->in_dbus_queue)
+ return;
+
+ /* We don't check if anybody is subscribed here, since this
+ * job might just have been created and not yet assigned to a
+ * connection/client. */
+
+ LIST_PREPEND(Job, dbus_queue, j->manager->dbus_job_queue, j);
+ j->in_dbus_queue = true;
+}
+
+char *job_dbus_path(Job *j) {
+ char *p;
+
+ assert(j);
+
+ if (asprintf(&p, "/org/freedesktop/systemd1/job/%lu", (unsigned long) j->id) < 0)
+ return NULL;
+
+ return p;
+}
+
+void job_timer_event(Job *j, uint64_t n_elapsed, Watch *w) {
+ assert(j);
+ assert(w == &j->timer_watch);
+
+ log_warning_unit(j->unit->id, "Job %s/%s timed out.",
+ j->unit->id, job_type_to_string(j->type));
+ job_finish_and_invalidate(j, JOB_TIMEOUT, true);
+}
+
+int job_serialize(Job *j, FILE *f, FDSet *fds) {
+ fprintf(f, "job-id=%u\n", j->id);
+ fprintf(f, "job-type=%s\n", job_type_to_string(j->type));
+ fprintf(f, "job-state=%s\n", job_state_to_string(j->state));
+ fprintf(f, "job-override=%s\n", yes_no(j->override));
+ fprintf(f, "job-irreversible=%s\n", yes_no(j->irreversible));
+ fprintf(f, "job-sent-dbus-new-signal=%s\n", yes_no(j->sent_dbus_new_signal));
+ fprintf(f, "job-ignore-order=%s\n", yes_no(j->ignore_order));
+ /* Cannot save bus clients. Just note the fact that we're losing
+ * them. job_send_message() will fallback to broadcasting. */
+ fprintf(f, "job-forgot-bus-clients=%s\n",
+ yes_no(j->forgot_bus_clients || j->bus_client_list));
+ if (j->timer_watch.type == WATCH_JOB_TIMER) {
+ int copy = fdset_put_dup(fds, j->timer_watch.fd);
+ if (copy < 0)
+ return copy;
+ fprintf(f, "job-timer-watch-fd=%d\n", copy);
+ }
+
+ /* End marker */
+ fputc('\n', f);
+ return 0;
+}
+
+int job_deserialize(Job *j, FILE *f, FDSet *fds) {
+ for (;;) {
+ char line[LINE_MAX], *l, *v;
+ size_t k;
+
+ if (!fgets(line, sizeof(line), f)) {
+ if (feof(f))
+ return 0;
+ return -errno;
+ }
+
+ char_array_0(line);
+ l = strstrip(line);
+
+ /* End marker */
+ if (l[0] == 0)
+ return 0;
+
+ k = strcspn(l, "=");
+
+ if (l[k] == '=') {
+ l[k] = 0;
+ v = l+k+1;
+ } else
+ v = l+k;
+
+ if (streq(l, "job-id")) {
+ if (safe_atou32(v, &j->id) < 0)
+ log_debug("Failed to parse job id value %s", v);
+ } else if (streq(l, "job-type")) {
+ JobType t = job_type_from_string(v);
+ if (t < 0)
+ log_debug("Failed to parse job type %s", v);
+ else if (t >= _JOB_TYPE_MAX_IN_TRANSACTION)
+ log_debug("Cannot deserialize job of type %s", v);
+ else
+ j->type = t;
+ } else if (streq(l, "job-state")) {
+ JobState s = job_state_from_string(v);
+ if (s < 0)
+ log_debug("Failed to parse job state %s", v);
+ else
+ j->state = s;
+ } else if (streq(l, "job-override")) {
+ int b = parse_boolean(v);
+ if (b < 0)
+ log_debug("Failed to parse job override flag %s", v);
+ else
+ j->override = j->override || b;
+ } else if (streq(l, "job-irreversible")) {
+ int b = parse_boolean(v);
+ if (b < 0)
+ log_debug("Failed to parse job irreversible flag %s", v);
+ else
+ j->irreversible = j->irreversible || b;
+ } else if (streq(l, "job-sent-dbus-new-signal")) {
+ int b = parse_boolean(v);
+ if (b < 0)
+ log_debug("Failed to parse job sent_dbus_new_signal flag %s", v);
+ else
+ j->sent_dbus_new_signal = j->sent_dbus_new_signal || b;
+ } else if (streq(l, "job-ignore-order")) {
+ int b = parse_boolean(v);
+ if (b < 0)
+ log_debug("Failed to parse job ignore_order flag %s", v);
+ else
+ j->ignore_order = j->ignore_order || b;
+ } else if (streq(l, "job-forgot-bus-clients")) {
+ int b = parse_boolean(v);
+ if (b < 0)
+ log_debug("Failed to parse job forgot_bus_clients flag %s", v);
+ else
+ j->forgot_bus_clients = j->forgot_bus_clients || b;
+ } else if (streq(l, "job-timer-watch-fd")) {
+ int fd;
+ if (safe_atoi(v, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
+ log_debug("Failed to parse job-timer-watch-fd value %s", v);
+ else {
+ if (j->timer_watch.type == WATCH_JOB_TIMER)
+ close_nointr_nofail(j->timer_watch.fd);
+
+ j->timer_watch.type = WATCH_JOB_TIMER;
+ j->timer_watch.fd = fdset_remove(fds, fd);
+ j->timer_watch.data.job = j;
+ }
+ }
+ }
+}
+
+int job_coldplug(Job *j) {
+ struct epoll_event ev = {
+ .data.ptr = &j->timer_watch,
+ .events = EPOLLIN,
+ };
+
+ if (j->timer_watch.type != WATCH_JOB_TIMER)
+ return 0;
+
+ if (epoll_ctl(j->manager->epoll_fd, EPOLL_CTL_ADD, j->timer_watch.fd, &ev) < 0)
+ return -errno;
+
+ return 0;
+}
+
+void job_shutdown_magic(Job *j) {
+ assert(j);
+
+ /* The shutdown target gets some special treatment here: we
+ * tell the kernel to begin with flushing its disk caches, to
+ * optimize shutdown time a bit. Ideally we wouldn't hardcode
+ * this magic into PID 1. However all other processes aren't
+ * options either since they'd exit much sooner than PID 1 and
+ * asynchronous sync() would cause their exit to be
+ * delayed. */
+
+ if (!unit_has_name(j->unit, SPECIAL_SHUTDOWN_TARGET))
+ return;
+
+ if (j->type != JOB_START)
+ return;
+
+ if (detect_container(NULL) > 0)
+ return;
+
+ asynchronous_sync();
+}
+
+static const char* const job_state_table[_JOB_STATE_MAX] = {
+ [JOB_WAITING] = "waiting",
+ [JOB_RUNNING] = "running"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(job_state, JobState);
+
+static const char* const job_type_table[_JOB_TYPE_MAX] = {
+ [JOB_START] = "start",
+ [JOB_VERIFY_ACTIVE] = "verify-active",
+ [JOB_STOP] = "stop",
+ [JOB_RELOAD] = "reload",
+ [JOB_RELOAD_OR_START] = "reload-or-start",
+ [JOB_RESTART] = "restart",
+ [JOB_TRY_RESTART] = "try-restart",
+ [JOB_NOP] = "nop",
+};
+
+DEFINE_STRING_TABLE_LOOKUP(job_type, JobType);
+
+static const char* const job_mode_table[_JOB_MODE_MAX] = {
+ [JOB_FAIL] = "fail",
+ [JOB_REPLACE] = "replace",
+ [JOB_REPLACE_IRREVERSIBLY] = "replace-irreversibly",
+ [JOB_ISOLATE] = "isolate",
+ [JOB_IGNORE_DEPENDENCIES] = "ignore-dependencies",
+ [JOB_IGNORE_REQUIREMENTS] = "ignore-requirements"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(job_mode, JobMode);
+
+static const char* const job_result_table[_JOB_RESULT_MAX] = {
+ [JOB_DONE] = "done",
+ [JOB_CANCELED] = "canceled",
+ [JOB_TIMEOUT] = "timeout",
+ [JOB_FAILED] = "failed",
+ [JOB_DEPENDENCY] = "dependency",
+ [JOB_SKIPPED] = "skipped"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(job_result, JobResult);
diff --git a/src/core/job.h b/src/core/job.h
new file mode 100644
index 0000000000..d90bc96b76
--- /dev/null
+++ b/src/core/job.h
@@ -0,0 +1,234 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdbool.h>
+#include <inttypes.h>
+#include <errno.h>
+
+typedef struct Job Job;
+typedef struct JobDependency JobDependency;
+typedef struct JobBusClient JobBusClient;
+typedef enum JobType JobType;
+typedef enum JobState JobState;
+typedef enum JobMode JobMode;
+typedef enum JobResult JobResult;
+
+/* Be careful when changing the job types! Adjust job_merging_table[] accordingly! */
+enum JobType {
+ JOB_START, /* if a unit does not support being started, we'll just wait until it becomes active */
+ JOB_VERIFY_ACTIVE,
+
+ JOB_STOP,
+
+ JOB_RELOAD, /* if running, reload */
+
+ /* Note that restarts are first treated like JOB_STOP, but
+ * then instead of finishing are patched to become
+ * JOB_START. */
+ JOB_RESTART, /* If running, stop. Then start unconditionally. */
+
+ _JOB_TYPE_MAX_MERGING,
+
+ /* JOB_NOP can enter into a transaction, but as it won't pull in
+ * any dependencies, it won't have to merge with anything.
+ * job_install() avoids the problem of merging JOB_NOP too (it's
+ * special-cased, only merges with other JOB_NOPs). */
+ JOB_NOP = _JOB_TYPE_MAX_MERGING, /* do nothing */
+
+ _JOB_TYPE_MAX_IN_TRANSACTION,
+
+ /* JOB_TRY_RESTART can never appear in a transaction, because
+ * it always collapses into JOB_RESTART or JOB_NOP before entering.
+ * Thus we never need to merge it with anything. */
+ JOB_TRY_RESTART = _JOB_TYPE_MAX_IN_TRANSACTION, /* if running, stop and then start */
+
+ /* JOB_RELOAD_OR_START won't enter into a transaction and cannot result
+ * from transaction merging (there's no way for JOB_RELOAD and
+ * JOB_START to meet in one transaction). It can result from a merge
+ * during job installation, but then it will immediately collapse into
+ * one of the two simpler types. */
+ JOB_RELOAD_OR_START, /* if running, reload, otherwise start */
+
+ _JOB_TYPE_MAX,
+ _JOB_TYPE_INVALID = -1
+};
+
+enum JobState {
+ JOB_WAITING,
+ JOB_RUNNING,
+ _JOB_STATE_MAX,
+ _JOB_STATE_INVALID = -1
+};
+
+enum JobMode {
+ JOB_FAIL, /* Fail if a conflicting job is already queued */
+ JOB_REPLACE, /* Replace an existing conflicting job */
+ JOB_REPLACE_IRREVERSIBLY, /* Like JOB_REPLACE + produce irreversible jobs */
+ JOB_ISOLATE, /* Start a unit, and stop all others */
+ JOB_IGNORE_DEPENDENCIES, /* Ignore both requirement and ordering dependencies */
+ JOB_IGNORE_REQUIREMENTS, /* Ignore requirement dependencies */
+ _JOB_MODE_MAX,
+ _JOB_MODE_INVALID = -1
+};
+
+enum JobResult {
+ JOB_DONE, /* Job completed successfully */
+ JOB_CANCELED, /* Job canceled by a conflicting job installation or by explicit cancel request */
+ JOB_TIMEOUT, /* JobTimeout elapsed */
+ JOB_FAILED, /* Job failed */
+ JOB_DEPENDENCY, /* A required dependency job did not result in JOB_DONE */
+ JOB_SKIPPED, /* JOB_RELOAD of inactive unit; negative result of JOB_VERIFY_ACTIVE */
+ _JOB_RESULT_MAX,
+ _JOB_RESULT_INVALID = -1
+};
+
+#include "manager.h"
+#include "unit.h"
+#include "hashmap.h"
+#include "list.h"
+
+struct JobDependency {
+ /* Encodes that the 'subject' job needs the 'object' job in
+ * some way. This structure is used only while building a transaction. */
+ Job *subject;
+ Job *object;
+
+ LIST_FIELDS(JobDependency, subject);
+ LIST_FIELDS(JobDependency, object);
+
+ bool matters;
+ bool conflicts;
+};
+
+struct JobBusClient {
+ LIST_FIELDS(JobBusClient, client);
+ /* Note that this bus object is not ref counted here. */
+ DBusConnection *bus;
+ char name[0];
+};
+
+struct Job {
+ Manager *manager;
+ Unit *unit;
+
+ LIST_FIELDS(Job, transaction);
+ LIST_FIELDS(Job, run_queue);
+ LIST_FIELDS(Job, dbus_queue);
+
+ LIST_HEAD(JobDependency, subject_list);
+ LIST_HEAD(JobDependency, object_list);
+
+ /* Used for graph algs as a "I have been here" marker */
+ Job* marker;
+ unsigned generation;
+
+ uint32_t id;
+
+ JobType type;
+ JobState state;
+
+ Watch timer_watch;
+
+ /* There can be more than one client, because of job merging. */
+ LIST_HEAD(JobBusClient, bus_client_list);
+
+ JobResult result;
+
+ bool installed:1;
+ bool in_run_queue:1;
+ bool matters_to_anchor:1;
+ bool override:1;
+ bool in_dbus_queue:1;
+ bool sent_dbus_new_signal:1;
+ bool ignore_order:1;
+ bool forgot_bus_clients:1;
+ bool irreversible:1;
+};
+
+JobBusClient* job_bus_client_new(DBusConnection *connection, const char *name);
+
+Job* job_new(Unit *unit, JobType type);
+Job* job_new_raw(Unit *unit);
+void job_free(Job *job);
+Job* job_install(Job *j);
+int job_install_deserialized(Job *j);
+void job_uninstall(Job *j);
+void job_dump(Job *j, FILE*f, const char *prefix);
+int job_serialize(Job *j, FILE *f, FDSet *fds);
+int job_deserialize(Job *j, FILE *f, FDSet *fds);
+int job_coldplug(Job *j);
+
+JobDependency* job_dependency_new(Job *subject, Job *object, bool matters, bool conflicts);
+void job_dependency_free(JobDependency *l);
+
+int job_merge(Job *j, Job *other);
+
+JobType job_type_lookup_merge(JobType a, JobType b) _pure_;
+
+_pure_ static inline bool job_type_is_mergeable(JobType a, JobType b) {
+ return job_type_lookup_merge(a, b) >= 0;
+}
+
+_pure_ static inline bool job_type_is_conflicting(JobType a, JobType b) {
+ return !job_type_is_mergeable(a, b);
+}
+
+_pure_ static inline bool job_type_is_superset(JobType a, JobType b) {
+ /* Checks whether operation a is a "superset" of b in its actions */
+ return a == job_type_lookup_merge(a, b);
+}
+
+bool job_type_is_redundant(JobType a, UnitActiveState b) _pure_;
+
+/* Collapses a state-dependent job type into a simpler type by observing
+ * the state of the unit which it is going to be applied to. */
+void job_type_collapse(JobType *t, Unit *u);
+
+int job_type_merge_and_collapse(JobType *a, JobType b, Unit *u);
+
+bool job_is_runnable(Job *j);
+
+void job_add_to_run_queue(Job *j);
+void job_add_to_dbus_queue(Job *j);
+
+int job_start_timer(Job *j);
+void job_timer_event(Job *j, uint64_t n_elapsed, Watch *w);
+
+int job_run_and_invalidate(Job *j);
+int job_finish_and_invalidate(Job *j, JobResult result, bool recursive);
+
+char *job_dbus_path(Job *j);
+
+void job_shutdown_magic(Job *j);
+
+const char* job_type_to_string(JobType t) _const_;
+JobType job_type_from_string(const char *s) _pure_;
+
+const char* job_state_to_string(JobState t) _const_;
+JobState job_state_from_string(const char *s) _pure_;
+
+const char* job_mode_to_string(JobMode t) _const_;
+JobMode job_mode_from_string(const char *s) _pure_;
+
+const char* job_result_to_string(JobResult t) _const_;
+JobResult job_result_from_string(const char *s) _pure_;
diff --git a/src/core/kill.c b/src/core/kill.c
new file mode 100644
index 0000000000..0775653f73
--- /dev/null
+++ b/src/core/kill.c
@@ -0,0 +1,63 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <string.h>
+
+#include "kill.h"
+#include "util.h"
+
+void kill_context_init(KillContext *c) {
+ assert(c);
+
+ c->kill_signal = SIGTERM;
+ c->send_sigkill = true;
+}
+
+void kill_context_dump(KillContext *c, FILE *f, const char *prefix) {
+ assert(c);
+
+ if (!prefix)
+ prefix = "";
+
+ fprintf(f,
+ "%sKillMode: %s\n"
+ "%sKillSignal: SIG%s\n"
+ "%sSendSIGKILL: %s\n",
+ prefix, kill_mode_to_string(c->kill_mode),
+ prefix, signal_to_string(c->kill_signal),
+ prefix, yes_no(c->send_sigkill));
+}
+
+static const char* const kill_mode_table[_KILL_MODE_MAX] = {
+ [KILL_CONTROL_GROUP] = "control-group",
+ [KILL_PROCESS] = "process",
+ [KILL_NONE] = "none"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(kill_mode, KillMode);
+
+static const char* const kill_who_table[_KILL_WHO_MAX] = {
+ [KILL_MAIN] = "main",
+ [KILL_CONTROL] = "control",
+ [KILL_ALL] = "all"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(kill_who, KillWho);
diff --git a/src/core/kill.h b/src/core/kill.h
new file mode 100644
index 0000000000..71a0513e84
--- /dev/null
+++ b/src/core/kill.h
@@ -0,0 +1,62 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+typedef struct KillContext KillContext;
+
+#include <stdbool.h>
+#include <stdio.h>
+
+#include "macro.h"
+
+typedef enum KillMode {
+ /* The kill mode is a property of a unit. */
+ KILL_CONTROL_GROUP = 0,
+ KILL_PROCESS,
+ KILL_NONE,
+ _KILL_MODE_MAX,
+ _KILL_MODE_INVALID = -1
+} KillMode;
+
+struct KillContext {
+ KillMode kill_mode;
+ int kill_signal;
+ bool send_sigkill;
+};
+
+typedef enum KillWho {
+ /* Kill who is a property of an operation */
+ KILL_MAIN,
+ KILL_CONTROL,
+ KILL_ALL,
+ _KILL_WHO_MAX,
+ _KILL_WHO_INVALID = -1
+} KillWho;
+
+void kill_context_init(KillContext *c);
+void kill_context_dump(KillContext *c, FILE *f, const char *prefix);
+
+const char *kill_mode_to_string(KillMode k) _const_;
+KillMode kill_mode_from_string(const char *s) _pure_;
+
+const char *kill_who_to_string(KillWho k) _const_;
+KillWho kill_who_from_string(const char *s) _pure_;
diff --git a/src/core/killall.c b/src/core/killall.c
new file mode 100644
index 0000000000..a0f57455fb
--- /dev/null
+++ b/src/core/killall.c
@@ -0,0 +1,210 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 ProFUSION embedded systems
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/wait.h>
+#include <signal.h>
+#include <errno.h>
+#include <unistd.h>
+
+#include "util.h"
+#include "def.h"
+#include "killall.h"
+#include "set.h"
+
+#define TIMEOUT_USEC (10 * USEC_PER_SEC)
+
+static bool ignore_proc(pid_t pid) {
+ _cleanup_fclose_ FILE *f = NULL;
+ char c;
+ size_t count;
+ uid_t uid;
+ int r;
+
+ /* We are PID 1, let's not commit suicide */
+ if (pid == 1)
+ return true;
+
+ r = get_process_uid(pid, &uid);
+ if (r < 0)
+ return true; /* not really, but better safe than sorry */
+
+ /* Non-root processes otherwise are always subject to be killed */
+ if (uid != 0)
+ return false;
+
+ f = fopen(procfs_file_alloca(pid, "cmdline"), "re");
+ if (!f)
+ return true; /* not really, but has the desired effect */
+
+ count = fread(&c, 1, 1, f);
+
+ /* Kernel threads have an empty cmdline */
+ if (count <= 0)
+ return true;
+
+ /* Processes with argv[0][0] = '@' we ignore from the killing
+ * spree.
+ *
+ * http://www.freedesktop.org/wiki/Software/systemd/RootStorageDaemons */
+ if (count == 1 && c == '@')
+ return true;
+
+ return false;
+}
+
+static void wait_for_children(Set *pids, sigset_t *mask) {
+ usec_t until;
+
+ assert(mask);
+
+ if (set_isempty(pids))
+ return;
+
+ until = now(CLOCK_MONOTONIC) + TIMEOUT_USEC;
+ for (;;) {
+ struct timespec ts;
+ int k;
+ usec_t n;
+ void *p;
+ Iterator i;
+
+ /* First, let the kernel inform us about killed
+ * children. Most processes will probably be our
+ * children, but some are not (might be our
+ * grandchildren instead...). */
+ for (;;) {
+ pid_t pid;
+
+ pid = waitpid(-1, NULL, WNOHANG);
+ if (pid == 0)
+ break;
+ if (pid < 0) {
+ if (errno == ECHILD)
+ break;
+
+ log_error("waitpid() failed: %m");
+ return;
+ }
+
+ set_remove(pids, ULONG_TO_PTR(pid));
+ }
+
+ /* Now explicitly check who might be remaining, who
+ * might not be our child. */
+ SET_FOREACH(p, pids, i) {
+
+ /* We misuse getpgid as a check whether a
+ * process still exists. */
+ if (getpgid((pid_t) PTR_TO_ULONG(p)) >= 0)
+ continue;
+
+ if (errno != ESRCH)
+ continue;
+
+ set_remove(pids, p);
+ }
+
+ if (set_isempty(pids))
+ return;
+
+ n = now(CLOCK_MONOTONIC);
+ if (n >= until)
+ return;
+
+ timespec_store(&ts, until - n);
+ k = sigtimedwait(mask, NULL, &ts);
+ if (k != SIGCHLD) {
+
+ if (k < 0 && errno != EAGAIN) {
+ log_error("sigtimedwait() failed: %m");
+ return;
+ }
+
+ if (k >= 0)
+ log_warning("sigtimedwait() returned unexpected signal.");
+ }
+ }
+}
+
+static int killall(int sig, Set *pids) {
+ _cleanup_closedir_ DIR *dir = NULL;
+ struct dirent *d;
+
+ dir = opendir("/proc");
+ if (!dir)
+ return -errno;
+
+ while ((d = readdir(dir))) {
+ pid_t pid;
+
+ if (d->d_type != DT_DIR &&
+ d->d_type != DT_UNKNOWN)
+ continue;
+
+ if (parse_pid(d->d_name, &pid) < 0)
+ continue;
+
+ if (ignore_proc(pid))
+ continue;
+
+ if (sig == SIGKILL) {
+ _cleanup_free_ char *s;
+
+ get_process_comm(pid, &s);
+ log_notice("Sending SIGKILL to PID %lu (%s).", (unsigned long) pid, strna(s));
+ }
+
+ if (kill(pid, sig) >= 0) {
+ if (pids)
+ set_put(pids, ULONG_TO_PTR((unsigned long) pid));
+ } else if (errno != ENOENT)
+ log_warning("Could not kill %d: %m", pid);
+ }
+
+ return set_size(pids);
+}
+
+void broadcast_signal(int sig, bool wait_for_exit) {
+ sigset_t mask, oldmask;
+ Set *pids = NULL;
+
+ if (wait_for_exit)
+ pids = set_new(trivial_hash_func, trivial_compare_func);
+
+ assert_se(sigemptyset(&mask) == 0);
+ assert_se(sigaddset(&mask, SIGCHLD) == 0);
+ assert_se(sigprocmask(SIG_BLOCK, &mask, &oldmask) == 0);
+
+ if (kill(-1, SIGSTOP) < 0 && errno != ESRCH)
+ log_warning("kill(-1, SIGSTOP) failed: %m");
+
+ killall(sig, pids);
+
+ if (kill(-1, SIGCONT) < 0 && errno != ESRCH)
+ log_warning("kill(-1, SIGCONT) failed: %m");
+
+ if (wait_for_exit)
+ wait_for_children(pids, &mask);
+
+ assert_se(sigprocmask(SIG_SETMASK, &oldmask, NULL) == 0);
+
+ set_free(pids);
+}
diff --git a/src/core/killall.h b/src/core/killall.h
new file mode 100644
index 0000000000..d08ac142f0
--- /dev/null
+++ b/src/core/killall.h
@@ -0,0 +1,27 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef fookillallhfoo
+#define fookillallhfoo
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+void broadcast_signal(int sig, bool wait);
+
+#endif
diff --git a/src/core/kmod-setup.c b/src/core/kmod-setup.c
new file mode 100644
index 0000000000..e4885fb212
--- /dev/null
+++ b/src/core/kmod-setup.c
@@ -0,0 +1,110 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/wait.h>
+#include <unistd.h>
+#include <string.h>
+#include <errno.h>
+#include <libkmod.h>
+
+#include "macro.h"
+#include "execute.h"
+
+#include "kmod-setup.h"
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wformat-nonliteral"
+
+static void systemd_kmod_log(
+ void *data,
+ int priority,
+ const char *file, int line,
+ const char *fn,
+ const char *format,
+ va_list args) {
+
+ /* library logging is enabled at debug only */
+ log_metav(LOG_DEBUG, file, line, fn, format, args);
+}
+
+#pragma GCC diagnostic pop
+
+int kmod_setup(void) {
+
+ static const char kmod_table[] =
+ /* This one we need to load explicitly, since
+ * auto-loading on use doesn't work before udev
+ * created the ghost device nodes, and we need it
+ * earlier than that. */
+ "autofs4\0" "/sys/class/misc/autofs\0"
+
+ /* This one we need to load explicitly, since
+ * auto-loading of IPv6 is not done when we try to
+ * configure ::1 on the loopback device. */
+ "ipv6\0" "/sys/module/ipv6\0"
+
+ "unix\0" "/proc/net/unix\0";
+
+ struct kmod_ctx *ctx = NULL;
+ const char *name, *path;
+ int r;
+
+ NULSTR_FOREACH_PAIR(name, path, kmod_table) {
+ struct kmod_module *mod;
+
+ if (access(path, F_OK) >= 0)
+ continue;
+
+ log_debug("Your kernel apparently lacks built-in %s support. Might be a good idea to compile it in. "
+ "We'll now try to work around this by loading the module...",
+ name);
+
+ if (!ctx) {
+ ctx = kmod_new(NULL, NULL);
+ if (!ctx)
+ return log_oom();
+
+ kmod_set_log_fn(ctx, systemd_kmod_log, NULL);
+ kmod_load_resources(ctx);
+ }
+
+ r = kmod_module_new_from_name(ctx, name, &mod);
+ if (r < 0) {
+ log_error("Failed to lookup module '%s'", name);
+ continue;
+ }
+
+ r = kmod_module_probe_insert_module(mod, KMOD_PROBE_APPLY_BLACKLIST, NULL, NULL, NULL, NULL);
+ if (r == 0)
+ log_info("Inserted module '%s'", kmod_module_get_name(mod));
+ else if (r == KMOD_PROBE_APPLY_BLACKLIST)
+ log_info("Module '%s' is blacklisted", kmod_module_get_name(mod));
+ else
+ log_error("Failed to insert module '%s'", kmod_module_get_name(mod));
+
+ kmod_module_unref(mod);
+ }
+
+ if (ctx)
+ kmod_unref(ctx);
+
+ return 0;
+}
diff --git a/src/core/kmod-setup.h b/src/core/kmod-setup.h
new file mode 100644
index 0000000000..24dcdddfa4
--- /dev/null
+++ b/src/core/kmod-setup.h
@@ -0,0 +1,24 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+int kmod_setup(void);
diff --git a/src/core/load-dropin.c b/src/core/load-dropin.c
new file mode 100644
index 0000000000..a877e66098
--- /dev/null
+++ b/src/core/load-dropin.c
@@ -0,0 +1,223 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <dirent.h>
+#include <errno.h>
+
+#include "unit.h"
+#include "load-dropin.h"
+#include "log.h"
+#include "strv.h"
+#include "unit-name.h"
+#include "conf-parser.h"
+#include "load-fragment.h"
+#include "conf-files.h"
+
+static int iterate_dir(
+ Unit *u,
+ const char *path,
+ UnitDependency dependency,
+ char ***strv) {
+
+ _cleanup_closedir_ DIR *d = NULL;
+ int r;
+
+ assert(u);
+ assert(path);
+
+ /* The config directories are special, since the order of the
+ * drop-ins matters */
+ if (dependency < 0) {
+ r = strv_extend(strv, path);
+ if (r < 0)
+ return log_oom();
+
+ return 0;
+ }
+
+ d = opendir(path);
+ if (!d) {
+ if (errno == ENOENT)
+ return 0;
+
+ return -errno;
+ }
+
+ for (;;) {
+ struct dirent *de;
+ union dirent_storage buf;
+ _cleanup_free_ char *f = NULL;
+ int k;
+
+ k = readdir_r(d, &buf.de, &de);
+ if (k != 0) {
+ log_error("Failed to read directory %s: %s", path, strerror(k));
+ return -k;
+ }
+
+ if (!de)
+ break;
+
+ if (ignore_file(de->d_name))
+ continue;
+
+ f = strjoin(path, "/", de->d_name, NULL);
+ if (!f)
+ return log_oom();
+
+ r = unit_add_dependency_by_name(u, dependency, de->d_name, f, true);
+ if (r < 0)
+ log_error("Cannot add dependency %s to %s, ignoring: %s", de->d_name, u->id, strerror(-r));
+ }
+
+ return 0;
+}
+
+static int process_dir(
+ Unit *u,
+ const char *unit_path,
+ const char *name,
+ const char *suffix,
+ UnitDependency dependency,
+ char ***strv) {
+
+ int r;
+ char *path;
+
+ assert(u);
+ assert(unit_path);
+ assert(name);
+ assert(suffix);
+
+ path = strjoin(unit_path, "/", name, suffix, NULL);
+ if (!path)
+ return log_oom();
+
+ if (u->manager->unit_path_cache &&
+ !set_get(u->manager->unit_path_cache, path))
+ r = 0;
+ else
+ r = iterate_dir(u, path, dependency, strv);
+ free(path);
+
+ if (r < 0)
+ return r;
+
+ if (u->instance) {
+ char *template;
+ /* Also try the template dir */
+
+ template = unit_name_template(name);
+ if (!template)
+ return log_oom();
+
+ path = strjoin(unit_path, "/", template, suffix, NULL);
+ free(template);
+
+ if (!path)
+ return log_oom();
+
+ if (u->manager->unit_path_cache &&
+ !set_get(u->manager->unit_path_cache, path))
+ r = 0;
+ else
+ r = iterate_dir(u, path, dependency, strv);
+ free(path);
+
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+char **unit_find_dropin_paths(Unit *u) {
+ _cleanup_strv_free_ char **strv = NULL;
+ char **configs = NULL;
+ Iterator i;
+ char *t;
+ int r;
+
+ assert(u);
+
+ SET_FOREACH(t, u->names, i) {
+ char **p;
+
+ STRV_FOREACH(p, u->manager->lookup_paths.unit_path) {
+ /* This loads the drop-in config snippets */
+ r = process_dir(u, *p, t, ".d", _UNIT_DEPENDENCY_INVALID, &strv);
+ if (r < 0)
+ return NULL;
+ }
+ }
+
+ if (strv_isempty(strv))
+ return NULL;
+
+ r = conf_files_list_strv(&configs, ".conf", NULL, (const char**) strv);
+ if (r < 0) {
+ log_error("Failed to get list of configuration files: %s", strerror(-r));
+ strv_free(configs);
+ return NULL;
+ }
+
+ return configs;
+}
+
+int unit_load_dropin(Unit *u) {
+ Iterator i;
+ char *t, **f;
+ int r;
+
+ assert(u);
+
+ /* Load dependencies from supplementary drop-in directories */
+
+ SET_FOREACH(t, u->names, i) {
+ char **p;
+
+ STRV_FOREACH(p, u->manager->lookup_paths.unit_path) {
+ r = process_dir(u, *p, t, ".wants", UNIT_WANTS, NULL);
+ if (r < 0)
+ return r;
+
+ r = process_dir(u, *p, t, ".requires", UNIT_REQUIRES, NULL);
+ if (r < 0)
+ return r;
+ }
+ }
+
+ u->dropin_paths = unit_find_dropin_paths(u);
+ if (! u->dropin_paths)
+ return 0;
+
+ STRV_FOREACH(f, u->dropin_paths) {
+ r = config_parse(u->id, *f, NULL,
+ UNIT_VTABLE(u)->sections, config_item_perf_lookup,
+ (void*) load_fragment_gperf_lookup, false, false, u);
+ if (r < 0)
+ return r;
+ }
+
+ u->dropin_mtime = now(CLOCK_REALTIME);
+
+ return 0;
+}
diff --git a/src/core/load-dropin.h b/src/core/load-dropin.h
new file mode 100644
index 0000000000..fd551179e2
--- /dev/null
+++ b/src/core/load-dropin.h
@@ -0,0 +1,29 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "unit.h"
+
+/* Read service data supplementary drop-in directories */
+
+char **unit_find_dropin_paths(Unit *u);
+int unit_load_dropin(Unit *u);
diff --git a/src/core/load-fragment-gperf.gperf.m4 b/src/core/load-fragment-gperf.gperf.m4
new file mode 100644
index 0000000000..4e1454ee6c
--- /dev/null
+++ b/src/core/load-fragment-gperf.gperf.m4
@@ -0,0 +1,258 @@
+%{
+#include <stddef.h>
+#include "conf-parser.h"
+#include "load-fragment.h"
+#include "missing.h"
+%}
+struct ConfigPerfItem;
+%null_strings
+%language=ANSI-C
+%define slot-name section_and_lvalue
+%define hash-function-name load_fragment_gperf_hash
+%define lookup-function-name load_fragment_gperf_lookup
+%readonly-tables
+%omit-struct-type
+%struct-type
+%includes
+%%
+m4_dnl Define the context options only once
+m4_define(`EXEC_CONTEXT_CONFIG_ITEMS',
+`$1.WorkingDirectory, config_parse_unit_path_printf, 0, offsetof($1, exec_context.working_directory)
+$1.RootDirectory, config_parse_unit_path_printf, 0, offsetof($1, exec_context.root_directory)
+$1.User, config_parse_unit_string_printf, 0, offsetof($1, exec_context.user)
+$1.Group, config_parse_unit_string_printf, 0, offsetof($1, exec_context.group)
+$1.SupplementaryGroups, config_parse_strv, 0, offsetof($1, exec_context.supplementary_groups)
+$1.Nice, config_parse_exec_nice, 0, offsetof($1, exec_context)
+$1.OOMScoreAdjust, config_parse_exec_oom_score_adjust, 0, offsetof($1, exec_context)
+$1.IOSchedulingClass, config_parse_exec_io_class, 0, offsetof($1, exec_context)
+$1.IOSchedulingPriority, config_parse_exec_io_priority, 0, offsetof($1, exec_context)
+$1.CPUSchedulingPolicy, config_parse_exec_cpu_sched_policy, 0, offsetof($1, exec_context)
+$1.CPUSchedulingPriority, config_parse_exec_cpu_sched_prio, 0, offsetof($1, exec_context)
+$1.CPUSchedulingResetOnFork, config_parse_bool, 0, offsetof($1, exec_context.cpu_sched_reset_on_fork)
+$1.CPUAffinity, config_parse_exec_cpu_affinity, 0, offsetof($1, exec_context)
+$1.UMask, config_parse_mode, 0, offsetof($1, exec_context.umask)
+$1.Environment, config_parse_environ, 0, offsetof($1, exec_context.environment)
+$1.EnvironmentFile, config_parse_unit_env_file, 0, offsetof($1, exec_context.environment_files)
+$1.StandardInput, config_parse_input, 0, offsetof($1, exec_context.std_input)
+$1.StandardOutput, config_parse_output, 0, offsetof($1, exec_context.std_output)
+$1.StandardError, config_parse_output, 0, offsetof($1, exec_context.std_error)
+$1.TTYPath, config_parse_unit_path_printf, 0, offsetof($1, exec_context.tty_path)
+$1.TTYReset, config_parse_bool, 0, offsetof($1, exec_context.tty_reset)
+$1.TTYVHangup, config_parse_bool, 0, offsetof($1, exec_context.tty_vhangup)
+$1.TTYVTDisallocate, config_parse_bool, 0, offsetof($1, exec_context.tty_vt_disallocate)
+$1.SyslogIdentifier, config_parse_unit_string_printf, 0, offsetof($1, exec_context.syslog_identifier)
+$1.SyslogFacility, config_parse_facility, 0, offsetof($1, exec_context.syslog_priority)
+$1.SyslogLevel, config_parse_level, 0, offsetof($1, exec_context.syslog_priority)
+$1.SyslogLevelPrefix, config_parse_bool, 0, offsetof($1, exec_context.syslog_level_prefix)
+$1.Capabilities, config_parse_exec_capabilities, 0, offsetof($1, exec_context)
+$1.SecureBits, config_parse_exec_secure_bits, 0, offsetof($1, exec_context)
+$1.CapabilityBoundingSet, config_parse_bounding_set, 0, offsetof($1, exec_context.capability_bounding_set_drop)
+$1.TimerSlackNSec, config_parse_nsec, 0, offsetof($1, exec_context.timer_slack_nsec)
+$1.NoNewPrivileges, config_parse_bool, 0, offsetof($1, exec_context.no_new_privileges)
+$1.SystemCallFilter, config_parse_syscall_filter, 0, offsetof($1, exec_context)
+$1.LimitCPU, config_parse_limit, RLIMIT_CPU, offsetof($1, exec_context.rlimit)
+$1.LimitFSIZE, config_parse_limit, RLIMIT_FSIZE, offsetof($1, exec_context.rlimit)
+$1.LimitDATA, config_parse_limit, RLIMIT_DATA, offsetof($1, exec_context.rlimit)
+$1.LimitSTACK, config_parse_limit, RLIMIT_STACK, offsetof($1, exec_context.rlimit)
+$1.LimitCORE, config_parse_limit, RLIMIT_CORE, offsetof($1, exec_context.rlimit)
+$1.LimitRSS, config_parse_limit, RLIMIT_RSS, offsetof($1, exec_context.rlimit)
+$1.LimitNOFILE, config_parse_limit, RLIMIT_NOFILE, offsetof($1, exec_context.rlimit)
+$1.LimitAS, config_parse_limit, RLIMIT_AS, offsetof($1, exec_context.rlimit)
+$1.LimitNPROC, config_parse_limit, RLIMIT_NPROC, offsetof($1, exec_context.rlimit)
+$1.LimitMEMLOCK, config_parse_limit, RLIMIT_MEMLOCK, offsetof($1, exec_context.rlimit)
+$1.LimitLOCKS, config_parse_limit, RLIMIT_LOCKS, offsetof($1, exec_context.rlimit)
+$1.LimitSIGPENDING, config_parse_limit, RLIMIT_SIGPENDING, offsetof($1, exec_context.rlimit)
+$1.LimitMSGQUEUE, config_parse_limit, RLIMIT_MSGQUEUE, offsetof($1, exec_context.rlimit)
+$1.LimitNICE, config_parse_limit, RLIMIT_NICE, offsetof($1, exec_context.rlimit)
+$1.LimitRTPRIO, config_parse_limit, RLIMIT_RTPRIO, offsetof($1, exec_context.rlimit)
+$1.LimitRTTIME, config_parse_limit, RLIMIT_RTTIME, offsetof($1, exec_context.rlimit)
+$1.ControlGroup, config_parse_unit_cgroup, 0, 0
+$1.ControlGroupAttribute, config_parse_unit_cgroup_attr, 0, 0
+$1.CPUShares, config_parse_unit_cgroup_attr_pretty, 0, 0
+$1.MemoryLimit, config_parse_unit_cgroup_attr_pretty, 0, 0
+$1.MemorySoftLimit, config_parse_unit_cgroup_attr_pretty, 0, 0
+$1.DeviceAllow, config_parse_unit_cgroup_attr_pretty, 0, 0
+$1.DeviceDeny, config_parse_unit_cgroup_attr_pretty, 0, 0
+$1.BlockIOWeight, config_parse_unit_cgroup_attr_pretty, 0, 0
+$1.BlockIOReadBandwidth, config_parse_unit_cgroup_attr_pretty, 0, 0
+$1.BlockIOWriteBandwidth, config_parse_unit_cgroup_attr_pretty, 0, 0
+$1.ReadWriteDirectories, config_parse_path_strv, 0, offsetof($1, exec_context.read_write_dirs)
+$1.ReadOnlyDirectories, config_parse_path_strv, 0, offsetof($1, exec_context.read_only_dirs)
+$1.InaccessibleDirectories, config_parse_path_strv, 0, offsetof($1, exec_context.inaccessible_dirs)
+$1.PrivateTmp, config_parse_bool, 0, offsetof($1, exec_context.private_tmp)
+$1.PrivateNetwork, config_parse_bool, 0, offsetof($1, exec_context.private_network)
+$1.MountFlags, config_parse_exec_mount_flags, 0, offsetof($1, exec_context)
+$1.TCPWrapName, config_parse_unit_string_printf, 0, offsetof($1, exec_context.tcpwrap_name)
+$1.PAMName, config_parse_unit_string_printf, 0, offsetof($1, exec_context.pam_name)
+$1.IgnoreSIGPIPE, config_parse_bool, 0, offsetof($1, exec_context.ignore_sigpipe)
+$1.UtmpIdentifier, config_parse_unit_string_printf, 0, offsetof($1, exec_context.utmp_id)
+$1.ControlGroupModify, config_parse_bool, 0, offsetof($1, exec_context.control_group_modify)
+$1.ControlGroupPersistent, config_parse_tristate, 0, offsetof($1, exec_context.control_group_persistent)'
+)m4_dnl
+m4_define(`KILL_CONTEXT_CONFIG_ITEMS',
+`$1.SendSIGKILL, config_parse_bool, 0, offsetof($1, kill_context.send_sigkill)
+$1.KillMode, config_parse_kill_mode, 0, offsetof($1, kill_context.kill_mode)
+$1.KillSignal, config_parse_kill_signal, 0, offsetof($1, kill_context.kill_signal)'
+)m4_dnl
+Unit.Description, config_parse_unit_string_printf, 0, offsetof(Unit, description)
+Unit.Documentation, config_parse_documentation, 0, offsetof(Unit, documentation)
+Unit.SourcePath, config_parse_path, 0, offsetof(Unit, source_path)
+Unit.Requires, config_parse_unit_deps, UNIT_REQUIRES, 0
+Unit.RequiresOverridable, config_parse_unit_deps, UNIT_REQUIRES_OVERRIDABLE, 0
+Unit.Requisite, config_parse_unit_deps, UNIT_REQUISITE, 0
+Unit.RequisiteOverridable, config_parse_unit_deps, UNIT_REQUISITE_OVERRIDABLE, 0
+Unit.Wants, config_parse_unit_deps, UNIT_WANTS, 0
+Unit.BindsTo, config_parse_unit_deps, UNIT_BINDS_TO, 0
+Unit.BindTo, config_parse_unit_deps, UNIT_BINDS_TO, 0
+Unit.Conflicts, config_parse_unit_deps, UNIT_CONFLICTS, 0
+Unit.Before, config_parse_unit_deps, UNIT_BEFORE, 0
+Unit.After, config_parse_unit_deps, UNIT_AFTER, 0
+Unit.OnFailure, config_parse_unit_deps, UNIT_ON_FAILURE, 0
+Unit.PropagatesReloadTo, config_parse_unit_deps, UNIT_PROPAGATES_RELOAD_TO, 0
+Unit.PropagateReloadTo, config_parse_unit_deps, UNIT_PROPAGATES_RELOAD_TO, 0
+Unit.ReloadPropagatedFrom, config_parse_unit_deps, UNIT_RELOAD_PROPAGATED_FROM, 0
+Unit.PropagateReloadFrom, config_parse_unit_deps, UNIT_RELOAD_PROPAGATED_FROM, 0
+Unit.PartOf, config_parse_unit_deps, UNIT_PART_OF, 0
+Unit.RequiresMountsFor, config_parse_unit_requires_mounts_for, 0, offsetof(Unit, requires_mounts_for)
+Unit.StopWhenUnneeded, config_parse_bool, 0, offsetof(Unit, stop_when_unneeded)
+Unit.RefuseManualStart, config_parse_bool, 0, offsetof(Unit, refuse_manual_start)
+Unit.RefuseManualStop, config_parse_bool, 0, offsetof(Unit, refuse_manual_stop)
+Unit.AllowIsolate, config_parse_bool, 0, offsetof(Unit, allow_isolate)
+Unit.DefaultDependencies, config_parse_bool, 0, offsetof(Unit, default_dependencies)
+Unit.OnFailureIsolate, config_parse_bool, 0, offsetof(Unit, on_failure_isolate)
+Unit.IgnoreOnIsolate, config_parse_bool, 0, offsetof(Unit, ignore_on_isolate)
+Unit.IgnoreOnSnapshot, config_parse_bool, 0, offsetof(Unit, ignore_on_snapshot)
+Unit.JobTimeoutSec, config_parse_sec, 0, offsetof(Unit, job_timeout)
+Unit.ConditionPathExists, config_parse_unit_condition_path, CONDITION_PATH_EXISTS, 0
+Unit.ConditionPathExistsGlob, config_parse_unit_condition_path, CONDITION_PATH_EXISTS_GLOB, 0
+Unit.ConditionPathIsDirectory, config_parse_unit_condition_path, CONDITION_PATH_IS_DIRECTORY, 0
+Unit.ConditionPathIsSymbolicLink,config_parse_unit_condition_path, CONDITION_PATH_IS_SYMBOLIC_LINK,0
+Unit.ConditionPathIsMountPoint, config_parse_unit_condition_path, CONDITION_PATH_IS_MOUNT_POINT, 0
+Unit.ConditionPathIsReadWrite, config_parse_unit_condition_path, CONDITION_PATH_IS_READ_WRITE, 0
+Unit.ConditionDirectoryNotEmpty, config_parse_unit_condition_path, CONDITION_DIRECTORY_NOT_EMPTY, 0
+Unit.ConditionFileNotEmpty, config_parse_unit_condition_path, CONDITION_FILE_NOT_EMPTY, 0
+Unit.ConditionFileIsExecutable, config_parse_unit_condition_path, CONDITION_FILE_IS_EXECUTABLE, 0
+Unit.ConditionKernelCommandLine, config_parse_unit_condition_string, CONDITION_KERNEL_COMMAND_LINE, 0
+Unit.ConditionVirtualization, config_parse_unit_condition_string, CONDITION_VIRTUALIZATION, 0
+Unit.ConditionSecurity, config_parse_unit_condition_string, CONDITION_SECURITY, 0
+Unit.ConditionCapability, config_parse_unit_condition_string, CONDITION_CAPABILITY, 0
+Unit.ConditionHost, config_parse_unit_condition_string, CONDITION_HOST, 0
+Unit.ConditionACPower, config_parse_unit_condition_string, CONDITION_AC_POWER, 0
+Unit.ConditionNull, config_parse_unit_condition_null, 0, 0
+m4_dnl
+Service.PIDFile, config_parse_unit_path_printf, 0, offsetof(Service, pid_file)
+Service.ExecStartPre, config_parse_exec, SERVICE_EXEC_START_PRE, offsetof(Service, exec_command)
+Service.ExecStart, config_parse_exec, SERVICE_EXEC_START, offsetof(Service, exec_command)
+Service.ExecStartPost, config_parse_exec, SERVICE_EXEC_START_POST, offsetof(Service, exec_command)
+Service.ExecReload, config_parse_exec, SERVICE_EXEC_RELOAD, offsetof(Service, exec_command)
+Service.ExecStop, config_parse_exec, SERVICE_EXEC_STOP, offsetof(Service, exec_command)
+Service.ExecStopPost, config_parse_exec, SERVICE_EXEC_STOP_POST, offsetof(Service, exec_command)
+Service.RestartSec, config_parse_sec, 0, offsetof(Service, restart_usec)
+Service.TimeoutSec, config_parse_service_timeout, 0, offsetof(Service, timeout_start_usec)
+Service.TimeoutStartSec, config_parse_service_timeout, 0, offsetof(Service, timeout_start_usec)
+Service.TimeoutStopSec, config_parse_service_timeout, 0, offsetof(Service, timeout_stop_usec)
+Service.WatchdogSec, config_parse_sec, 0, offsetof(Service, watchdog_usec)
+Service.StartLimitInterval, config_parse_sec, 0, offsetof(Service, start_limit.interval)
+Service.StartLimitBurst, config_parse_unsigned, 0, offsetof(Service, start_limit.burst)
+Service.StartLimitAction, config_parse_start_limit_action, 0, offsetof(Service, start_limit_action)
+Service.Type, config_parse_service_type, 0, offsetof(Service, type)
+Service.Restart, config_parse_service_restart, 0, offsetof(Service, restart)
+Service.PermissionsStartOnly, config_parse_bool, 0, offsetof(Service, permissions_start_only)
+Service.RootDirectoryStartOnly, config_parse_bool, 0, offsetof(Service, root_directory_start_only)
+Service.RemainAfterExit, config_parse_bool, 0, offsetof(Service, remain_after_exit)
+Service.GuessMainPID, config_parse_bool, 0, offsetof(Service, guess_main_pid)
+Service.RestartPreventExitStatus, config_parse_set_status, 0, offsetof(Service, restart_ignore_status)
+Service.SuccessExitStatus, config_parse_set_status, 0, offsetof(Service, success_status)
+m4_ifdef(`HAVE_SYSV_COMPAT',
+`Service.SysVStartPriority, config_parse_sysv_priority, 0, offsetof(Service, sysv_start_priority)',
+`Service.SysVStartPriority, config_parse_warn_compat, 0, 0')
+Service.NonBlocking, config_parse_bool, 0, offsetof(Service, exec_context.non_blocking)
+Service.BusName, config_parse_unit_string_printf, 0, offsetof(Service, bus_name)
+Service.NotifyAccess, config_parse_notify_access, 0, offsetof(Service, notify_access)
+Service.Sockets, config_parse_service_sockets, 0, 0
+Service.FsckPassNo, config_parse_fsck_passno, 0, offsetof(Service, fsck_passno)
+EXEC_CONTEXT_CONFIG_ITEMS(Service)m4_dnl
+KILL_CONTEXT_CONFIG_ITEMS(Service)m4_dnl
+m4_dnl
+Socket.ListenStream, config_parse_socket_listen, SOCKET_SOCKET, 0
+Socket.ListenDatagram, config_parse_socket_listen, SOCKET_SOCKET, 0
+Socket.ListenSequentialPacket, config_parse_socket_listen, SOCKET_SOCKET, 0
+Socket.ListenFIFO, config_parse_socket_listen, SOCKET_FIFO, 0
+Socket.ListenNetlink, config_parse_socket_listen, SOCKET_SOCKET, 0
+Socket.ListenSpecial, config_parse_socket_listen, SOCKET_SPECIAL, 0
+Socket.ListenMessageQueue, config_parse_socket_listen, SOCKET_MQUEUE, 0
+Socket.BindIPv6Only, config_parse_socket_bind, 0, 0,
+Socket.Backlog, config_parse_unsigned, 0, offsetof(Socket, backlog)
+Socket.BindToDevice, config_parse_socket_bindtodevice, 0, 0
+Socket.ExecStartPre, config_parse_exec, SOCKET_EXEC_START_PRE, offsetof(Socket, exec_command)
+Socket.ExecStartPost, config_parse_exec, SOCKET_EXEC_START_POST, offsetof(Socket, exec_command)
+Socket.ExecStopPre, config_parse_exec, SOCKET_EXEC_STOP_PRE, offsetof(Socket, exec_command)
+Socket.ExecStopPost, config_parse_exec, SOCKET_EXEC_STOP_POST, offsetof(Socket, exec_command)
+Socket.TimeoutSec, config_parse_sec, 0, offsetof(Socket, timeout_usec)
+Socket.DirectoryMode, config_parse_mode, 0, offsetof(Socket, directory_mode)
+Socket.SocketMode, config_parse_mode, 0, offsetof(Socket, socket_mode)
+Socket.Accept, config_parse_bool, 0, offsetof(Socket, accept)
+Socket.MaxConnections, config_parse_unsigned, 0, offsetof(Socket, max_connections)
+Socket.KeepAlive, config_parse_bool, 0, offsetof(Socket, keep_alive)
+Socket.Priority, config_parse_int, 0, offsetof(Socket, priority)
+Socket.ReceiveBuffer, config_parse_bytes_size, 0, offsetof(Socket, receive_buffer)
+Socket.SendBuffer, config_parse_bytes_size, 0, offsetof(Socket, send_buffer)
+Socket.IPTOS, config_parse_ip_tos, 0, offsetof(Socket, ip_tos)
+Socket.IPTTL, config_parse_int, 0, offsetof(Socket, ip_ttl)
+Socket.Mark, config_parse_int, 0, offsetof(Socket, mark)
+Socket.PipeSize, config_parse_bytes_size, 0, offsetof(Socket, pipe_size)
+Socket.FreeBind, config_parse_bool, 0, offsetof(Socket, free_bind)
+Socket.Transparent, config_parse_bool, 0, offsetof(Socket, transparent)
+Socket.Broadcast, config_parse_bool, 0, offsetof(Socket, broadcast)
+Socket.PassCredentials, config_parse_bool, 0, offsetof(Socket, pass_cred)
+Socket.PassSecurity, config_parse_bool, 0, offsetof(Socket, pass_sec)
+Socket.TCPCongestion, config_parse_string, 0, offsetof(Socket, tcp_congestion)
+Socket.MessageQueueMaxMessages, config_parse_long, 0, offsetof(Socket, mq_maxmsg)
+Socket.MessageQueueMessageSize, config_parse_long, 0, offsetof(Socket, mq_msgsize)
+Socket.Service, config_parse_socket_service, 0, 0
+Socket.SmackLabel, config_parse_string, 0, offsetof(Socket, smack)
+Socket.SmackLabelIPIn, config_parse_string, 0, offsetof(Socket, smack_ip_in)
+Socket.SmackLabelIPOut, config_parse_string, 0, offsetof(Socket, smack_ip_out)
+EXEC_CONTEXT_CONFIG_ITEMS(Socket)m4_dnl
+KILL_CONTEXT_CONFIG_ITEMS(Socket)m4_dnl
+m4_dnl
+Mount.What, config_parse_string, 0, offsetof(Mount, parameters_fragment.what)
+Mount.Where, config_parse_path, 0, offsetof(Mount, where)
+Mount.Options, config_parse_string, 0, offsetof(Mount, parameters_fragment.options)
+Mount.Type, config_parse_string, 0, offsetof(Mount, parameters_fragment.fstype)
+Mount.FsckPassNo, config_parse_fsck_passno, 0, offsetof(Mount, parameters_fragment.passno)
+Mount.TimeoutSec, config_parse_sec, 0, offsetof(Mount, timeout_usec)
+Mount.DirectoryMode, config_parse_mode, 0, offsetof(Mount, directory_mode)
+EXEC_CONTEXT_CONFIG_ITEMS(Mount)m4_dnl
+KILL_CONTEXT_CONFIG_ITEMS(Mount)m4_dnl
+m4_dnl
+Automount.Where, config_parse_path, 0, offsetof(Automount, where)
+Automount.DirectoryMode, config_parse_mode, 0, offsetof(Automount, directory_mode)
+m4_dnl
+Swap.What, config_parse_path, 0, offsetof(Swap, parameters_fragment.what)
+Swap.Priority, config_parse_int, 0, offsetof(Swap, parameters_fragment.priority)
+Swap.TimeoutSec, config_parse_sec, 0, offsetof(Swap, timeout_usec)
+EXEC_CONTEXT_CONFIG_ITEMS(Swap)m4_dnl
+KILL_CONTEXT_CONFIG_ITEMS(Swap)m4_dnl
+m4_dnl
+Timer.OnCalendar, config_parse_timer, 0, 0
+Timer.OnActiveSec, config_parse_timer, 0, 0
+Timer.OnBootSec, config_parse_timer, 0, 0
+Timer.OnStartupSec, config_parse_timer, 0, 0
+Timer.OnUnitActiveSec, config_parse_timer, 0, 0
+Timer.OnUnitInactiveSec, config_parse_timer, 0, 0
+Timer.Unit, config_parse_trigger_unit, 0, 0
+m4_dnl
+Path.PathExists, config_parse_path_spec, 0, 0
+Path.PathExistsGlob, config_parse_path_spec, 0, 0
+Path.PathChanged, config_parse_path_spec, 0, 0
+Path.PathModified, config_parse_path_spec, 0, 0
+Path.DirectoryNotEmpty, config_parse_path_spec, 0, 0
+Path.Unit, config_parse_trigger_unit, 0, 0
+Path.MakeDirectory, config_parse_bool, 0, offsetof(Path, make_directory)
+Path.DirectoryMode, config_parse_mode, 0, offsetof(Path, directory_mode)
+m4_dnl The [Install] section is ignored here.
+Install.Alias, NULL, 0, 0
+Install.WantedBy, NULL, 0, 0
+Install.RequiredBy, NULL, 0, 0
+Install.Also, NULL, 0, 0
diff --git a/src/core/load-fragment.c b/src/core/load-fragment.c
new file mode 100644
index 0000000000..e2015ed58f
--- /dev/null
+++ b/src/core/load-fragment.c
@@ -0,0 +1,2486 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+ Copyright 2012 Holger Hans Peter Freyther
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <linux/oom.h>
+#include <assert.h>
+#include <errno.h>
+#include <string.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sched.h>
+#include <sys/prctl.h>
+#include <sys/mount.h>
+#include <linux/fs.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/resource.h>
+
+#include <systemd/sd-messages.h>
+
+#include "unit.h"
+#include "strv.h"
+#include "conf-parser.h"
+#include "load-fragment.h"
+#include "log.h"
+#include "ioprio.h"
+#include "securebits.h"
+#include "missing.h"
+#include "unit-name.h"
+#include "unit-printf.h"
+#include "dbus-common.h"
+#include "utf8.h"
+#include "path-util.h"
+#include "syscall-list.h"
+#include "env-util.h"
+
+#ifndef HAVE_SYSV_COMPAT
+int config_parse_warn_compat(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ log_syntax(unit, LOG_DEBUG, filename, line, EINVAL,
+ "Support for option %s= has been disabled at compile time and is ignored",
+ lvalue);
+ return 0;
+}
+#endif
+
+int config_parse_unit_deps(const char* unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ UnitDependency d = ltype;
+ Unit *u = userdata;
+ char *w;
+ size_t l;
+ char *state;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+
+ FOREACH_WORD_QUOTED(w, l, rvalue, state) {
+ _cleanup_free_ char *t = NULL, *k = NULL;
+ int r;
+
+ t = strndup(w, l);
+ if (!t)
+ return log_oom();
+
+ k = unit_name_printf(u, t);
+ if (!k)
+ return log_oom();
+
+ r = unit_add_dependency_by_name(u, d, k, NULL, true);
+ if (r < 0)
+ log_syntax(unit, LOG_ERR, filename, line, -r,
+ "Failed to add dependency on %s, ignoring: %s", k, strerror(-r));
+ }
+
+ return 0;
+}
+
+int config_parse_unit_string_printf(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ Unit *u = userdata;
+ _cleanup_free_ char *k = NULL;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(u);
+
+ k = unit_full_printf(u, rvalue);
+ if (!k)
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Failed to resolve unit specifiers on %s. Ignoring.", rvalue);
+
+ return config_parse_string(unit, filename, line, section, lvalue, ltype,
+ k ? k : rvalue, data, userdata);
+}
+
+int config_parse_unit_strv_printf(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ Unit *u = userdata;
+ _cleanup_free_ char *k = NULL;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(u);
+
+ k = unit_full_printf(u, rvalue);
+ if (!k)
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Failed to resolve unit specifiers on %s. Ignoring.", rvalue);
+
+ return config_parse_strv(unit, filename, line, section, lvalue, ltype,
+ k ? k : rvalue, data, userdata);
+}
+
+int config_parse_unit_path_printf(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ Unit *u = userdata;
+ _cleanup_free_ char *k = NULL;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(u);
+
+ k = unit_full_printf(u, rvalue);
+ if (!k)
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Failed to resolve unit specifiers on %s. Ignoring.", rvalue);
+
+ return config_parse_path(unit, filename, line, section, lvalue, ltype,
+ k ? k : rvalue, data, userdata);
+}
+
+int config_parse_socket_listen(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ SocketPort *p, *tail;
+ Socket *s;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ s = SOCKET(data);
+
+ if (isempty(rvalue)) {
+ /* An empty assignment removes all ports */
+ socket_free_ports(s);
+ return 0;
+ }
+
+ p = new0(SocketPort, 1);
+ if (!p)
+ return log_oom();
+
+ if (ltype != SOCKET_SOCKET) {
+
+ p->type = ltype;
+ p->path = unit_full_printf(UNIT(s), rvalue);
+ if (!p->path) {
+ p->path = strdup(rvalue);
+ if (!p->path) {
+ free(p);
+ return log_oom();
+ } else
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Failed to resolve unit specifiers on %s. Ignoring.", rvalue);
+ }
+
+ path_kill_slashes(p->path);
+
+ } else if (streq(lvalue, "ListenNetlink")) {
+ _cleanup_free_ char *k = NULL;
+ int r;
+
+ p->type = SOCKET_SOCKET;
+ k = unit_full_printf(UNIT(s), rvalue);
+ if (!k)
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Failed to resolve unit specifiers on %s. Ignoring.", rvalue);
+
+ r = socket_address_parse_netlink(&p->address, k ? k : rvalue);
+ if (r < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Failed to parse address value, ignoring: %s", rvalue);
+ free(p);
+ return 0;
+ }
+
+ } else {
+ _cleanup_free_ char *k = NULL;
+ int r;
+
+ p->type = SOCKET_SOCKET;
+ k = unit_full_printf(UNIT(s), rvalue);
+ if (!k)
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Failed to resolve unit specifiers on %s. Ignoring.", rvalue);
+
+ r = socket_address_parse(&p->address, k ? k : rvalue);
+ if (r < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Failed to parse address value, ignoring: %s", rvalue);
+ free(p);
+ return 0;
+ }
+
+ if (streq(lvalue, "ListenStream"))
+ p->address.type = SOCK_STREAM;
+ else if (streq(lvalue, "ListenDatagram"))
+ p->address.type = SOCK_DGRAM;
+ else {
+ assert(streq(lvalue, "ListenSequentialPacket"));
+ p->address.type = SOCK_SEQPACKET;
+ }
+
+ if (socket_address_family(&p->address) != AF_LOCAL && p->address.type == SOCK_SEQPACKET) {
+ log_syntax(unit, LOG_ERR, filename, line, ENOTSUP,
+ "Address family not supported, ignoring: %s", rvalue);
+ free(p);
+ return 0;
+ }
+ }
+
+ p->fd = -1;
+
+ if (s->ports) {
+ LIST_FIND_TAIL(SocketPort, port, s->ports, tail);
+ LIST_INSERT_AFTER(SocketPort, port, s->ports, tail, p);
+ } else
+ LIST_PREPEND(SocketPort, port, s->ports, p);
+
+ return 0;
+}
+
+int config_parse_socket_bind(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ Socket *s;
+ SocketAddressBindIPv6Only b;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ s = SOCKET(data);
+
+ b = socket_address_bind_ipv6_only_from_string(rvalue);
+ if (b < 0) {
+ int r;
+
+ r = parse_boolean(rvalue);
+ if (r < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Failed to parse bind IPv6 only value, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ s->bind_ipv6_only = r ? SOCKET_ADDRESS_IPV6_ONLY : SOCKET_ADDRESS_BOTH;
+ } else
+ s->bind_ipv6_only = b;
+
+ return 0;
+}
+
+int config_parse_exec_nice(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ ExecContext *c = data;
+ int priority, r;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ r = safe_atoi(rvalue, &priority);
+ if (r < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, -r,
+ "Failed to parse nice priority, ignoring: %s. ", rvalue);
+ return 0;
+ }
+
+ if (priority < PRIO_MIN || priority >= PRIO_MAX) {
+ log_syntax(unit, LOG_ERR, filename, line, ERANGE,
+ "Nice priority out of range, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ c->nice = priority;
+ c->nice_set = true;
+
+ return 0;
+}
+
+int config_parse_exec_oom_score_adjust(const char* unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ ExecContext *c = data;
+ int oa, r;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ r = safe_atoi(rvalue, &oa);
+ if (r < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, -r,
+ "Failed to parse the OOM score adjust value, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ if (oa < OOM_SCORE_ADJ_MIN || oa > OOM_SCORE_ADJ_MAX) {
+ log_syntax(unit, LOG_ERR, filename, line, ERANGE,
+ "OOM score adjust value out of range, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ c->oom_score_adjust = oa;
+ c->oom_score_adjust_set = true;
+
+ return 0;
+}
+
+int config_parse_exec(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ ExecCommand **e = data, *nce;
+ char *path, **n;
+ unsigned k;
+ int r;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(e);
+
+ e += ltype;
+
+ if (isempty(rvalue)) {
+ /* An empty assignment resets the list */
+ exec_command_free_list(*e);
+ *e = NULL;
+ return 0;
+ }
+
+ /* We accept an absolute path as first argument, or
+ * alternatively an absolute prefixed with @ to allow
+ * overriding of argv[0]. */
+ for (;;) {
+ int i;
+ char *w;
+ size_t l;
+ char *state;
+ bool honour_argv0 = false, ignore = false;
+
+ path = NULL;
+ nce = NULL;
+ n = NULL;
+
+ rvalue += strspn(rvalue, WHITESPACE);
+
+ if (rvalue[0] == 0)
+ break;
+
+ for (i = 0; i < 2; i++) {
+ if (rvalue[0] == '-' && !ignore) {
+ ignore = true;
+ rvalue ++;
+ }
+
+ if (rvalue[0] == '@' && !honour_argv0) {
+ honour_argv0 = true;
+ rvalue ++;
+ }
+ }
+
+ if (*rvalue != '/') {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Executable path is not absolute, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ k = 0;
+ FOREACH_WORD_QUOTED(w, l, rvalue, state) {
+ if (strneq(w, ";", MAX(l, 1U)))
+ break;
+
+ k++;
+ }
+
+ n = new(char*, k + !honour_argv0);
+ if (!n)
+ return log_oom();
+
+ k = 0;
+ FOREACH_WORD_QUOTED(w, l, rvalue, state) {
+ if (strneq(w, ";", MAX(l, 1U)))
+ break;
+ else if (strneq(w, "\\;", MAX(l, 1U)))
+ w ++;
+
+ if (honour_argv0 && w == rvalue) {
+ assert(!path);
+
+ path = strndup(w, l);
+ if (!path) {
+ r = log_oom();
+ goto fail;
+ }
+
+ if (!utf8_is_valid(path)) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Path is not UTF-8 clean, ignoring assignment: %s",
+ rvalue);
+ r = 0;
+ goto fail;
+ }
+
+ } else {
+ char *c;
+
+ c = n[k++] = cunescape_length(w, l);
+ if (!c) {
+ r = log_oom();
+ goto fail;
+ }
+
+ if (!utf8_is_valid(c)) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Path is not UTF-8 clean, ignoring assignment: %s",
+ rvalue);
+ r = 0;
+ goto fail;
+ }
+ }
+ }
+
+ n[k] = NULL;
+
+ if (!n[0]) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Invalid command line, ignoring: %s", rvalue);
+ r = 0;
+ goto fail;
+ }
+
+ if (!path) {
+ path = strdup(n[0]);
+ if (!path) {
+ r = log_oom();
+ goto fail;
+ }
+ }
+
+ assert(path_is_absolute(path));
+
+ nce = new0(ExecCommand, 1);
+ if (!nce) {
+ r = log_oom();
+ goto fail;
+ }
+
+ nce->argv = n;
+ nce->path = path;
+ nce->ignore = ignore;
+
+ path_kill_slashes(nce->path);
+
+ exec_command_append_list(e, nce);
+
+ rvalue = state;
+ }
+
+ return 0;
+
+fail:
+ n[k] = NULL;
+ strv_free(n);
+ free(path);
+ free(nce);
+
+ return r;
+}
+
+DEFINE_CONFIG_PARSE_ENUM(config_parse_service_type, service_type, ServiceType, "Failed to parse service type");
+DEFINE_CONFIG_PARSE_ENUM(config_parse_service_restart, service_restart, ServiceRestart, "Failed to parse service restart specifier");
+
+int config_parse_socket_bindtodevice(const char* unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ Socket *s = data;
+ char *n;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ if (rvalue[0] && !streq(rvalue, "*")) {
+ n = strdup(rvalue);
+ if (!n)
+ return log_oom();
+ } else
+ n = NULL;
+
+ free(s->bind_to_device);
+ s->bind_to_device = n;
+
+ return 0;
+}
+
+DEFINE_CONFIG_PARSE_ENUM(config_parse_output, exec_output, ExecOutput, "Failed to parse output specifier");
+DEFINE_CONFIG_PARSE_ENUM(config_parse_input, exec_input, ExecInput, "Failed to parse input specifier");
+
+int config_parse_exec_io_class(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ ExecContext *c = data;
+ int x;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ x = ioprio_class_from_string(rvalue);
+ if (x < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Failed to parse IO scheduling class, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ c->ioprio = IOPRIO_PRIO_VALUE(x, IOPRIO_PRIO_DATA(c->ioprio));
+ c->ioprio_set = true;
+
+ return 0;
+}
+
+int config_parse_exec_io_priority(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ ExecContext *c = data;
+ int i, r;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ r = safe_atoi(rvalue, &i);
+ if (r < 0 || i < 0 || i >= IOPRIO_BE_NR) {
+ log_syntax(unit, LOG_ERR, filename, line, -r,
+ "Failed to parse IO priority, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ c->ioprio = IOPRIO_PRIO_VALUE(IOPRIO_PRIO_CLASS(c->ioprio), i);
+ c->ioprio_set = true;
+
+ return 0;
+}
+
+int config_parse_exec_cpu_sched_policy(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+
+ ExecContext *c = data;
+ int x;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ x = sched_policy_from_string(rvalue);
+ if (x < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, -x,
+ "Failed to parse CPU scheduling policy, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ c->cpu_sched_policy = x;
+ /* Moving to or from real-time policy? We need to adjust the priority */
+ c->cpu_sched_priority = CLAMP(c->cpu_sched_priority, sched_get_priority_min(x), sched_get_priority_max(x));
+ c->cpu_sched_set = true;
+
+ return 0;
+}
+
+int config_parse_exec_cpu_sched_prio(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ ExecContext *c = data;
+ int i, min, max, r;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ r = safe_atoi(rvalue, &i);
+ if (r < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, -r,
+ "Failed to parse CPU scheduling policy, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ /* On Linux RR/FIFO range from 1 to 99 and OTHER/BATCH may only be 0 */
+ min = sched_get_priority_min(c->cpu_sched_policy);
+ max = sched_get_priority_max(c->cpu_sched_policy);
+
+ if (i < min || i > max) {
+ log_syntax(unit, LOG_ERR, filename, line, ERANGE,
+ "CPU scheduling priority is out of range, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ c->cpu_sched_priority = i;
+ c->cpu_sched_set = true;
+
+ return 0;
+}
+
+int config_parse_exec_cpu_affinity(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ ExecContext *c = data;
+ char *w;
+ size_t l;
+ char *state;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ if (isempty(rvalue)) {
+ /* An empty assignment resets the CPU list */
+ if (c->cpuset)
+ CPU_FREE(c->cpuset);
+ c->cpuset = NULL;
+ return 0;
+ }
+
+ FOREACH_WORD_QUOTED(w, l, rvalue, state) {
+ _cleanup_free_ char *t = NULL;
+ int r;
+ unsigned cpu;
+
+ t = strndup(w, l);
+ if (!t)
+ return log_oom();
+
+ r = safe_atou(t, &cpu);
+
+ if (!c->cpuset) {
+ c->cpuset = cpu_set_malloc(&c->cpuset_ncpus);
+ if (!c->cpuset)
+ return log_oom();
+ }
+
+ if (r < 0 || cpu >= c->cpuset_ncpus) {
+ log_syntax(unit, LOG_ERR, filename, line, ERANGE,
+ "Failed to parse CPU affinity '%s', ignoring: %s", t, rvalue);
+ return 0;
+ }
+
+ CPU_SET_S(cpu, CPU_ALLOC_SIZE(c->cpuset_ncpus), c->cpuset);
+ }
+
+ return 0;
+}
+
+int config_parse_exec_capabilities(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ ExecContext *c = data;
+ cap_t cap;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ cap = cap_from_text(rvalue);
+ if (!cap) {
+ log_syntax(unit, LOG_ERR, filename, line, errno,
+ "Failed to parse capabilities, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ if (c->capabilities)
+ cap_free(c->capabilities);
+ c->capabilities = cap;
+
+ return 0;
+}
+
+int config_parse_exec_secure_bits(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ ExecContext *c = data;
+ char *w;
+ size_t l;
+ char *state;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ if (isempty(rvalue)) {
+ /* An empty assignment resets the field */
+ c->secure_bits = 0;
+ return 0;
+ }
+
+ FOREACH_WORD_QUOTED(w, l, rvalue, state) {
+ if (first_word(w, "keep-caps"))
+ c->secure_bits |= 1<<SECURE_KEEP_CAPS;
+ else if (first_word(w, "keep-caps-locked"))
+ c->secure_bits |= 1<<SECURE_KEEP_CAPS_LOCKED;
+ else if (first_word(w, "no-setuid-fixup"))
+ c->secure_bits |= 1<<SECURE_NO_SETUID_FIXUP;
+ else if (first_word(w, "no-setuid-fixup-locked"))
+ c->secure_bits |= 1<<SECURE_NO_SETUID_FIXUP_LOCKED;
+ else if (first_word(w, "noroot"))
+ c->secure_bits |= 1<<SECURE_NOROOT;
+ else if (first_word(w, "noroot-locked"))
+ c->secure_bits |= 1<<SECURE_NOROOT_LOCKED;
+ else {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Failed to parse secure bits, ignoring: %s", rvalue);
+ return 0;
+ }
+ }
+
+ return 0;
+}
+
+int config_parse_bounding_set(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ uint64_t *capability_bounding_set_drop = data;
+ char *w;
+ size_t l;
+ char *state;
+ bool invert = false;
+ uint64_t sum = 0;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ if (rvalue[0] == '~') {
+ invert = true;
+ rvalue++;
+ }
+
+ /* Note that we store this inverted internally, since the
+ * kernel wants it like this. But we actually expose it
+ * non-inverted everywhere to have a fully normalized
+ * interface. */
+
+ FOREACH_WORD_QUOTED(w, l, rvalue, state) {
+ _cleanup_free_ char *t = NULL;
+ int r;
+ cap_value_t cap;
+
+ t = strndup(w, l);
+ if (!t)
+ return log_oom();
+
+ r = cap_from_name(t, &cap);
+ if (r < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, errno,
+ "Failed to parse capability in bounding set, ignoring: %s", t);
+ continue;
+ }
+
+ sum |= ((uint64_t) 1ULL) << (uint64_t) cap;
+ }
+
+ if (invert)
+ *capability_bounding_set_drop |= sum;
+ else
+ *capability_bounding_set_drop |= ~sum;
+
+ return 0;
+}
+
+int config_parse_limit(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ struct rlimit **rl = data;
+ unsigned long long u;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ rl += ltype;
+
+ if (streq(rvalue, "infinity"))
+ u = (unsigned long long) RLIM_INFINITY;
+ else {
+ int r;
+
+ r = safe_atollu(rvalue, &u);
+ if (r < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, -r,
+ "Failed to parse resource value, ignoring: %s", rvalue);
+ return 0;
+ }
+ }
+
+ if (!*rl) {
+ *rl = new(struct rlimit, 1);
+ if (!*rl)
+ return log_oom();
+ }
+
+ (*rl)->rlim_cur = (*rl)->rlim_max = (rlim_t) u;
+ return 0;
+}
+
+int config_parse_unit_cgroup(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ Unit *u = userdata;
+ char *w;
+ size_t l;
+ char *state;
+
+ if (isempty(rvalue)) {
+ /* An empty assignment resets the list */
+ cgroup_bonding_free_list(u->cgroup_bondings, false);
+ u->cgroup_bondings = NULL;
+ return 0;
+ }
+
+ FOREACH_WORD_QUOTED(w, l, rvalue, state) {
+ _cleanup_free_ char *t = NULL, *k = NULL, *ku = NULL;
+ int r;
+
+ t = strndup(w, l);
+ if (!t)
+ return log_oom();
+
+ k = unit_full_printf(u, t);
+ if (!k)
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Failed to resolve unit specifiers on %s. Ignoring.",
+ t);
+
+ ku = cunescape(k ? k : t);
+ if (!ku)
+ return log_oom();
+
+ r = unit_add_cgroup_from_text(u, ku, true, NULL);
+ if (r < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, -r,
+ "Failed to parse cgroup value %s, ignoring: %s",
+ k, rvalue);
+ return 0;
+ }
+ }
+
+ return 0;
+}
+
+#ifdef HAVE_SYSV_COMPAT
+int config_parse_sysv_priority(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ int *priority = data;
+ int i, r;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ r = safe_atoi(rvalue, &i);
+ if (r < 0 || i < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, -r,
+ "Failed to parse SysV start priority, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ *priority = (int) i;
+ return 0;
+}
+#endif
+
+int config_parse_fsck_passno(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ int *passno = data;
+ int i, r;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ r = safe_atoi(rvalue, &i);
+ if (r || i < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, -r,
+ "Failed to parse fsck pass number, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ *passno = (int) i;
+ return 0;
+}
+
+DEFINE_CONFIG_PARSE_ENUM(config_parse_kill_mode, kill_mode, KillMode, "Failed to parse kill mode");
+
+int config_parse_kill_signal(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ int *sig = data;
+ int r;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(sig);
+
+ r = signal_from_string_try_harder(rvalue);
+ if (r <= 0) {
+ log_syntax(unit, LOG_ERR, filename, line, -r,
+ "Failed to parse kill signal, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ *sig = r;
+ return 0;
+}
+
+int config_parse_exec_mount_flags(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ ExecContext *c = data;
+ char *w;
+ size_t l;
+ char *state;
+ unsigned long flags = 0;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ FOREACH_WORD_SEPARATOR(w, l, rvalue, ", ", state) {
+ _cleanup_free_ char *t;
+
+ t = strndup(w, l);
+ if (!t)
+ return log_oom();
+
+ if (streq(t, "shared"))
+ flags |= MS_SHARED;
+ else if (streq(t, "slave"))
+ flags |= MS_SLAVE;
+ else if (streq(w, "private"))
+ flags |= MS_PRIVATE;
+ else {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Failed to parse mount flag %s, ignoring: %s",
+ t, rvalue);
+ return 0;
+ }
+ }
+
+ c->mount_flags = flags;
+ return 0;
+}
+
+int config_parse_timer(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ Timer *t = data;
+ usec_t u = 0;
+ TimerValue *v;
+ TimerBase b;
+ CalendarSpec *c = NULL;
+ clockid_t id;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ if (isempty(rvalue)) {
+ /* Empty assignment resets list */
+ timer_free_values(t);
+ return 0;
+ }
+
+ b = timer_base_from_string(lvalue);
+ if (b < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, -b,
+ "Failed to parse timer base, ignoring: %s", lvalue);
+ return 0;
+ }
+
+ if (b == TIMER_CALENDAR) {
+ if (calendar_spec_from_string(rvalue, &c) < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Failed to parse calendar specification, ignoring: %s",
+ rvalue);
+ return 0;
+ }
+
+ id = CLOCK_REALTIME;
+ } else {
+ if (parse_sec(rvalue, &u) < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Failed to parse timer value, ignoring: %s",
+ rvalue);
+ return 0;
+ }
+
+ id = CLOCK_MONOTONIC;
+ }
+
+ v = new0(TimerValue, 1);
+ if (!v)
+ return log_oom();
+
+ v->base = b;
+ v->clock_id = id;
+ v->value = u;
+ v->calendar_spec = c;
+
+ LIST_PREPEND(TimerValue, value, t->values, v);
+
+ return 0;
+}
+
+int config_parse_trigger_unit(
+ const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ _cleanup_free_ char *p = NULL;
+ Unit *u = data;
+ UnitType type;
+ int r;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ if (!set_isempty(u->dependencies[UNIT_TRIGGERS])) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Multiple units to trigger specified, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ p = unit_name_printf(u, rvalue);
+ if (!p)
+ return log_oom();
+
+ type = unit_name_to_type(p);
+ if (type < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Unit type not valid, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ if (type == u->type) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Trigger cannot be of same type, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ r = unit_add_two_dependencies_by_name(u, UNIT_BEFORE, UNIT_TRIGGERS, p, NULL, true);
+ if (r < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, -r,
+ "Failed to add trigger on %s, ignoring: %s", p, strerror(-r));
+ return 0;
+ }
+
+ return 0;
+}
+
+int config_parse_path_spec(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ Path *p = data;
+ PathSpec *s;
+ PathType b;
+ _cleanup_free_ char *k = NULL;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ if (isempty(rvalue)) {
+ /* Empty assignment clears list */
+ path_free_specs(p);
+ return 0;
+ }
+
+ b = path_type_from_string(lvalue);
+ if (b < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Failed to parse path type, ignoring: %s", lvalue);
+ return 0;
+ }
+
+ k = unit_full_printf(UNIT(p), rvalue);
+ if (!k) {
+ k = strdup(rvalue);
+ if (!k)
+ return log_oom();
+ else
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Failed to resolve unit specifiers on %s. Ignoring.",
+ rvalue);
+ }
+
+ if (!path_is_absolute(k)) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Path is not absolute, ignoring: %s", k);
+ return 0;
+ }
+
+ s = new0(PathSpec, 1);
+ if (!s)
+ return log_oom();
+
+ s->path = path_kill_slashes(k);
+ k = NULL;
+ s->type = b;
+ s->inotify_fd = -1;
+
+ LIST_PREPEND(PathSpec, spec, p->specs, s);
+
+ return 0;
+}
+
+int config_parse_socket_service(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ Socket *s = data;
+ int r;
+ DBusError error;
+ Unit *x;
+ _cleanup_free_ char *p = NULL;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ dbus_error_init(&error);
+
+ p = unit_name_printf(UNIT(s), rvalue);
+ if (!p)
+ return log_oom();
+
+ if (!endswith(p, ".service")) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Unit must be of type service, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ r = manager_load_unit(UNIT(s)->manager, p, NULL, &error, &x);
+ if (r < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Failed to load unit %s, ignoring: %s",
+ rvalue, bus_error(&error, r));
+ dbus_error_free(&error);
+ return 0;
+ }
+
+ unit_ref_set(&s->service, x);
+
+ return 0;
+}
+
+int config_parse_service_sockets(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ Service *s = data;
+ int r;
+ char *state, *w;
+ size_t l;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ FOREACH_WORD_QUOTED(w, l, rvalue, state) {
+ _cleanup_free_ char *t = NULL, *k = NULL;
+
+ t = strndup(w, l);
+ if (!t)
+ return log_oom();
+
+ k = unit_name_printf(UNIT(s), t);
+ if (!k)
+ return log_oom();
+
+ if (!endswith(k, ".socket")) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Unit must be of type socket, ignoring: %s", k);
+ continue;
+ }
+
+ r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_WANTS, UNIT_AFTER, k, NULL, true);
+ if (r < 0)
+ log_syntax(unit, LOG_ERR, filename, line, -r,
+ "Failed to add dependency on %s, ignoring: %s",
+ k, strerror(-r));
+
+ r = unit_add_dependency_by_name(UNIT(s), UNIT_TRIGGERED_BY, k, NULL, true);
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+int config_parse_service_timeout(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ Service *s = userdata;
+ int r;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(s);
+
+ r = config_parse_sec(unit, filename, line, section, lvalue, ltype,
+ rvalue, data, userdata);
+ if (r < 0)
+ return r;
+
+ if (streq(lvalue, "TimeoutSec")) {
+ s->start_timeout_defined = true;
+ s->timeout_stop_usec = s->timeout_start_usec;
+ } else if (streq(lvalue, "TimeoutStartSec"))
+ s->start_timeout_defined = true;
+
+ return 0;
+}
+
+int config_parse_unit_env_file(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ char ***env = data;
+ Unit *u = userdata;
+ _cleanup_free_ char *s = NULL;
+ int r;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ if (isempty(rvalue)) {
+ /* Empty assignment frees the list */
+ strv_free(*env);
+ *env = NULL;
+ return 0;
+ }
+
+ s = unit_full_printf(u, rvalue);
+ if (!s)
+ return log_oom();
+
+ if (!path_is_absolute(s[0] == '-' ? s + 1 : s)) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Path '%s' is not absolute, ignoring.", s);
+ return 0;
+ }
+
+ r = strv_extend(env, s);
+ if (r < 0)
+ return log_oom();
+
+ return 0;
+}
+
+int config_parse_environ(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ Unit *u = userdata;
+ char*** env = data, *w, *state;
+ size_t l;
+ _cleanup_free_ char *k = NULL;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(u);
+
+ if (isempty(rvalue)) {
+ /* Empty assignment resets the list */
+ strv_free(*env);
+ *env = NULL;
+ return 0;
+ }
+
+ k = unit_full_printf(u, rvalue);
+ if (!k)
+ return log_oom();
+
+ FOREACH_WORD_QUOTED(w, l, k, state) {
+ _cleanup_free_ char *n;
+ char **x;
+
+ n = cunescape_length(w, l);
+ if (!n)
+ return log_oom();
+
+ if (!env_assignment_is_valid(n)) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Invalid environment assignment, ignoring: %s", rvalue);
+ continue;
+ }
+
+ x = strv_env_set(*env, n);
+ if (!x)
+ return log_oom();
+
+ strv_free(*env);
+ *env = x;
+ }
+
+ return 0;
+}
+
+int config_parse_ip_tos(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ int *ip_tos = data, x;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ x = ip_tos_from_string(rvalue);
+ if (x < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Failed to parse IP TOS value, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ *ip_tos = x;
+ return 0;
+}
+
+int config_parse_unit_condition_path(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ ConditionType cond = ltype;
+ Unit *u = data;
+ bool trigger, negate;
+ Condition *c;
+ _cleanup_free_ char *p = NULL;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ if (isempty(rvalue)) {
+ /* Empty assignment resets the list */
+ condition_free_list(u->conditions);
+ u->conditions = NULL;
+ return 0;
+ }
+
+ trigger = rvalue[0] == '|';
+ if (trigger)
+ rvalue++;
+
+ negate = rvalue[0] == '!';
+ if (negate)
+ rvalue++;
+
+ p = unit_full_printf(u, rvalue);
+ if (!p)
+ return log_oom();
+
+ if (!path_is_absolute(p)) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Path in condition not absolute, ignoring: %s", p);
+ return 0;
+ }
+
+ c = condition_new(cond, p, trigger, negate);
+ if (!c)
+ return log_oom();
+
+ LIST_PREPEND(Condition, conditions, u->conditions, c);
+ return 0;
+}
+
+int config_parse_unit_condition_string(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ ConditionType cond = ltype;
+ Unit *u = data;
+ bool trigger, negate;
+ Condition *c;
+ _cleanup_free_ char *s = NULL;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ if (isempty(rvalue)) {
+ /* Empty assignment resets the list */
+ condition_free_list(u->conditions);
+ u->conditions = NULL;
+ return 0;
+ }
+
+ trigger = rvalue[0] == '|';
+ if (trigger)
+ rvalue++;
+
+ negate = rvalue[0] == '!';
+ if (negate)
+ rvalue++;
+
+ s = unit_full_printf(u, rvalue);
+ if (!s)
+ return log_oom();
+
+ c = condition_new(cond, s, trigger, negate);
+ if (!c)
+ return log_oom();
+
+ LIST_PREPEND(Condition, conditions, u->conditions, c);
+ return 0;
+}
+
+int config_parse_unit_condition_null(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ Unit *u = data;
+ Condition *c;
+ bool trigger, negate;
+ int b;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ if (isempty(rvalue)) {
+ /* Empty assignment resets the list */
+ condition_free_list(u->conditions);
+ u->conditions = NULL;
+ return 0;
+ }
+
+ trigger = rvalue[0] == '|';
+ if (trigger)
+ rvalue++;
+
+ negate = rvalue[0] == '!';
+ if (negate)
+ rvalue++;
+
+ b = parse_boolean(rvalue);
+ if (b < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, -b,
+ "Failed to parse boolean value in condition, ignoring: %s",
+ rvalue);
+ return 0;
+ }
+
+ if (!b)
+ negate = !negate;
+
+ c = condition_new(CONDITION_NULL, NULL, trigger, negate);
+ if (!c)
+ return log_oom();
+
+ LIST_PREPEND(Condition, conditions, u->conditions, c);
+ return 0;
+}
+
+DEFINE_CONFIG_PARSE_ENUM(config_parse_notify_access, notify_access, NotifyAccess, "Failed to parse notify access specifier");
+DEFINE_CONFIG_PARSE_ENUM(config_parse_start_limit_action, start_limit_action, StartLimitAction, "Failed to parse start limit action specifier");
+
+int config_parse_unit_cgroup_attr(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ Unit *u = data;
+ size_t a, b;
+ _cleanup_free_ char *n = NULL, *v = NULL;
+ const CGroupSemantics *s;
+ int r;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ if (isempty(rvalue)) {
+ /* Empty assignment clears the list */
+ cgroup_attribute_free_list(u->cgroup_attributes);
+ u->cgroup_attributes = NULL;
+ return 0;
+ }
+
+ a = strcspn(rvalue, WHITESPACE);
+ b = strspn(rvalue + a, WHITESPACE);
+ if (a <= 0 || b <= 0) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Failed to parse cgroup attribute value, ignoring: %s",
+ rvalue);
+ return 0;
+ }
+
+ n = strndup(rvalue, a);
+ if (!n)
+ return log_oom();
+
+ r = cgroup_semantics_find(NULL, n, rvalue + a + b, &v, &s);
+ if (r < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, -r,
+ "Failed to parse cgroup attribute value, ignoring: %s",
+ rvalue);
+ return 0;
+ }
+
+ r = unit_add_cgroup_attribute(u, s, NULL, n, v ? v : rvalue + a + b, NULL);
+ if (r < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, -r,
+ "Failed to add cgroup attribute value, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ return 0;
+}
+
+int config_parse_unit_cgroup_attr_pretty(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ Unit *u = data;
+ _cleanup_free_ char *v = NULL;
+ const CGroupSemantics *s;
+ int r;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ r = cgroup_semantics_find(NULL, lvalue, rvalue, &v, &s);
+ if (r < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, -r,
+ "Failed to parse cgroup attribute value, ignoring: %s",
+ rvalue);
+ return 0;
+ } else if (r == 0) {
+ log_syntax(unit, LOG_ERR, filename, line, ENOTSUP,
+ "Unknown or unsupported cgroup attribute %s, ignoring: %s",
+ lvalue, rvalue);
+ return 0;
+ }
+
+ r = unit_add_cgroup_attribute(u, s, NULL, NULL, v, NULL);
+ if (r < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, -r,
+ "Failed to add cgroup attribute value, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ return 0;
+}
+
+int config_parse_unit_requires_mounts_for(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ Unit *u = userdata;
+ int r;
+ bool empty_before;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ empty_before = !u->requires_mounts_for;
+
+ r = config_parse_path_strv(unit, filename, line, section, lvalue, ltype,
+ rvalue, data, userdata);
+
+ /* Make it easy to find units with requires_mounts set */
+ if (empty_before && u->requires_mounts_for)
+ LIST_PREPEND(Unit, has_requires_mounts_for, u->manager->has_requires_mounts_for, u);
+
+ return r;
+}
+
+int config_parse_documentation(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ Unit *u = userdata;
+ int r;
+ char **a, **b;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(u);
+
+ if (isempty(rvalue)) {
+ /* Empty assignment resets the list */
+ strv_free(u->documentation);
+ u->documentation = NULL;
+ return 0;
+ }
+
+ r = config_parse_unit_strv_printf(unit, filename, line, section, lvalue, ltype,
+ rvalue, data, userdata);
+ if (r < 0)
+ return r;
+
+ for (a = b = u->documentation; a && *a; a++) {
+
+ if (is_valid_documentation_url(*a))
+ *(b++) = *a;
+ else {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Invalid URL, ignoring: %s", *a);
+ free(*a);
+ }
+ }
+ *b = NULL;
+
+ return r;
+}
+
+static void syscall_set(uint32_t *p, int nr) {
+ nr = SYSCALL_TO_INDEX(nr);
+ p[nr >> 4] |= 1 << (nr & 31);
+}
+
+static void syscall_unset(uint32_t *p, int nr) {
+ nr = SYSCALL_TO_INDEX(nr);
+ p[nr >> 4] &= ~(1 << (nr & 31));
+}
+
+int config_parse_syscall_filter(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ ExecContext *c = data;
+ Unit *u = userdata;
+ bool invert = false;
+ char *w;
+ size_t l;
+ char *state;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(u);
+
+ if (isempty(rvalue)) {
+ /* Empty assignment resets the list */
+ free(c->syscall_filter);
+ c->syscall_filter = NULL;
+ return 0;
+ }
+
+ if (rvalue[0] == '~') {
+ invert = true;
+ rvalue++;
+ }
+
+ if (!c->syscall_filter) {
+ size_t n;
+
+ n = (syscall_max() + 31) >> 4;
+ c->syscall_filter = new(uint32_t, n);
+ if (!c->syscall_filter)
+ return log_oom();
+
+ memset(c->syscall_filter, invert ? 0xFF : 0, n * sizeof(uint32_t));
+
+ /* Add these by default */
+ syscall_set(c->syscall_filter, __NR_execve);
+ syscall_set(c->syscall_filter, __NR_rt_sigreturn);
+#ifdef __NR_sigreturn
+ syscall_set(c->syscall_filter, __NR_sigreturn);
+#endif
+ syscall_set(c->syscall_filter, __NR_exit_group);
+ syscall_set(c->syscall_filter, __NR_exit);
+ }
+
+ FOREACH_WORD_QUOTED(w, l, rvalue, state) {
+ int id;
+ _cleanup_free_ char *t = NULL;
+
+ t = strndup(w, l);
+ if (!t)
+ return log_oom();
+
+ id = syscall_from_name(t);
+ if (id < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Failed to parse syscall, ignoring: %s", t);
+ continue;
+ }
+
+ if (invert)
+ syscall_unset(c->syscall_filter, id);
+ else
+ syscall_set(c->syscall_filter, id);
+ }
+
+ c->no_new_privileges = true;
+
+ return 0;
+}
+
+#define FOLLOW_MAX 8
+
+static int open_follow(char **filename, FILE **_f, Set *names, char **_final) {
+ unsigned c = 0;
+ int fd, r;
+ FILE *f;
+ char *id = NULL;
+
+ assert(filename);
+ assert(*filename);
+ assert(_f);
+ assert(names);
+
+ /* This will update the filename pointer if the loaded file is
+ * reached by a symlink. The old string will be freed. */
+
+ for (;;) {
+ char *target, *name;
+
+ if (c++ >= FOLLOW_MAX)
+ return -ELOOP;
+
+ path_kill_slashes(*filename);
+
+ /* Add the file name we are currently looking at to
+ * the names of this unit, but only if it is a valid
+ * unit name. */
+ name = path_get_file_name(*filename);
+
+ if (unit_name_is_valid(name, true)) {
+
+ id = set_get(names, name);
+ if (!id) {
+ id = strdup(name);
+ if (!id)
+ return -ENOMEM;
+
+ r = set_consume(names, id);
+ if (r < 0)
+ return r;
+ }
+ }
+
+ /* Try to open the file name, but don't if its a symlink */
+ fd = open(*filename, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
+ if (fd >= 0)
+ break;
+
+ if (errno != ELOOP)
+ return -errno;
+
+ /* Hmm, so this is a symlink. Let's read the name, and follow it manually */
+ r = readlink_and_make_absolute(*filename, &target);
+ if (r < 0)
+ return r;
+
+ free(*filename);
+ *filename = target;
+ }
+
+ f = fdopen(fd, "re");
+ if (!f) {
+ r = -errno;
+ close_nointr_nofail(fd);
+ return r;
+ }
+
+ *_f = f;
+ *_final = id;
+ return 0;
+}
+
+static int merge_by_names(Unit **u, Set *names, const char *id) {
+ char *k;
+ int r;
+
+ assert(u);
+ assert(*u);
+ assert(names);
+
+ /* Let's try to add in all symlink names we found */
+ while ((k = set_steal_first(names))) {
+
+ /* First try to merge in the other name into our
+ * unit */
+ r = unit_merge_by_name(*u, k);
+ if (r < 0) {
+ Unit *other;
+
+ /* Hmm, we couldn't merge the other unit into
+ * ours? Then let's try it the other way
+ * round */
+
+ other = manager_get_unit((*u)->manager, k);
+ free(k);
+
+ if (other) {
+ r = unit_merge(other, *u);
+ if (r >= 0) {
+ *u = other;
+ return merge_by_names(u, names, NULL);
+ }
+ }
+
+ return r;
+ }
+
+ if (id == k)
+ unit_choose_id(*u, id);
+
+ free(k);
+ }
+
+ return 0;
+}
+
+static int load_from_path(Unit *u, const char *path) {
+ int r;
+ Set *symlink_names;
+ FILE *f = NULL;
+ char *filename = NULL, *id = NULL;
+ Unit *merged;
+ struct stat st;
+
+ assert(u);
+ assert(path);
+
+ symlink_names = set_new(string_hash_func, string_compare_func);
+ if (!symlink_names)
+ return -ENOMEM;
+
+ if (path_is_absolute(path)) {
+
+ filename = strdup(path);
+ if (!filename) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ r = open_follow(&filename, &f, symlink_names, &id);
+ if (r < 0) {
+ free(filename);
+ filename = NULL;
+
+ if (r != -ENOENT)
+ goto finish;
+ }
+
+ } else {
+ char **p;
+
+ STRV_FOREACH(p, u->manager->lookup_paths.unit_path) {
+
+ /* Instead of opening the path right away, we manually
+ * follow all symlinks and add their name to our unit
+ * name set while doing so */
+ filename = path_make_absolute(path, *p);
+ if (!filename) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ if (u->manager->unit_path_cache &&
+ !set_get(u->manager->unit_path_cache, filename))
+ r = -ENOENT;
+ else
+ r = open_follow(&filename, &f, symlink_names, &id);
+
+ if (r < 0) {
+ free(filename);
+ filename = NULL;
+
+ if (r != -ENOENT)
+ goto finish;
+
+ /* Empty the symlink names for the next run */
+ set_clear_free(symlink_names);
+ continue;
+ }
+
+ break;
+ }
+ }
+
+ if (!filename) {
+ /* Hmm, no suitable file found? */
+ r = 0;
+ goto finish;
+ }
+
+ merged = u;
+ r = merge_by_names(&merged, symlink_names, id);
+ if (r < 0)
+ goto finish;
+
+ if (merged != u) {
+ u->load_state = UNIT_MERGED;
+ r = 0;
+ goto finish;
+ }
+
+ if (fstat(fileno(f), &st) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ if (null_or_empty(&st))
+ u->load_state = UNIT_MASKED;
+ else {
+ /* Now, parse the file contents */
+ r = config_parse(u->id, filename, f, UNIT_VTABLE(u)->sections,
+ config_item_perf_lookup,
+ (void*) load_fragment_gperf_lookup, false, true, u);
+ if (r < 0)
+ goto finish;
+
+ u->load_state = UNIT_LOADED;
+ }
+
+ free(u->fragment_path);
+ u->fragment_path = filename;
+ filename = NULL;
+
+ u->fragment_mtime = timespec_load(&st.st_mtim);
+
+ if (u->source_path) {
+ if (stat(u->source_path, &st) >= 0)
+ u->source_mtime = timespec_load(&st.st_mtim);
+ else
+ u->source_mtime = 0;
+ }
+
+ r = 0;
+
+finish:
+ set_free_free(symlink_names);
+ free(filename);
+
+ if (f)
+ fclose(f);
+
+ return r;
+}
+
+int unit_load_fragment(Unit *u) {
+ int r;
+ Iterator i;
+ const char *t;
+
+ assert(u);
+ assert(u->load_state == UNIT_STUB);
+ assert(u->id);
+
+ /* First, try to find the unit under its id. We always look
+ * for unit files in the default directories, to make it easy
+ * to override things by placing things in /etc/systemd/system */
+ r = load_from_path(u, u->id);
+ if (r < 0)
+ return r;
+
+ /* Try to find an alias we can load this with */
+ if (u->load_state == UNIT_STUB)
+ SET_FOREACH(t, u->names, i) {
+
+ if (t == u->id)
+ continue;
+
+ r = load_from_path(u, t);
+ if (r < 0)
+ return r;
+
+ if (u->load_state != UNIT_STUB)
+ break;
+ }
+
+ /* And now, try looking for it under the suggested (originally linked) path */
+ if (u->load_state == UNIT_STUB && u->fragment_path) {
+
+ r = load_from_path(u, u->fragment_path);
+ if (r < 0)
+ return r;
+
+ if (u->load_state == UNIT_STUB) {
+ /* Hmm, this didn't work? Then let's get rid
+ * of the fragment path stored for us, so that
+ * we don't point to an invalid location. */
+ free(u->fragment_path);
+ u->fragment_path = NULL;
+ }
+ }
+
+ /* Look for a template */
+ if (u->load_state == UNIT_STUB && u->instance) {
+ char *k;
+
+ k = unit_name_template(u->id);
+ if (!k)
+ return -ENOMEM;
+
+ r = load_from_path(u, k);
+ free(k);
+
+ if (r < 0)
+ return r;
+
+ if (u->load_state == UNIT_STUB)
+ SET_FOREACH(t, u->names, i) {
+
+ if (t == u->id)
+ continue;
+
+ k = unit_name_template(t);
+ if (!k)
+ return -ENOMEM;
+
+ r = load_from_path(u, k);
+ free(k);
+
+ if (r < 0)
+ return r;
+
+ if (u->load_state != UNIT_STUB)
+ break;
+ }
+ }
+
+ return 0;
+}
+
+void unit_dump_config_items(FILE *f) {
+ static const struct {
+ const ConfigParserCallback callback;
+ const char *rvalue;
+ } table[] = {
+ { config_parse_int, "INTEGER" },
+ { config_parse_unsigned, "UNSIGNED" },
+ { config_parse_bytes_size, "SIZE" },
+ { config_parse_bool, "BOOLEAN" },
+ { config_parse_string, "STRING" },
+ { config_parse_path, "PATH" },
+ { config_parse_unit_path_printf, "PATH" },
+ { config_parse_strv, "STRING [...]" },
+ { config_parse_exec_nice, "NICE" },
+ { config_parse_exec_oom_score_adjust, "OOMSCOREADJUST" },
+ { config_parse_exec_io_class, "IOCLASS" },
+ { config_parse_exec_io_priority, "IOPRIORITY" },
+ { config_parse_exec_cpu_sched_policy, "CPUSCHEDPOLICY" },
+ { config_parse_exec_cpu_sched_prio, "CPUSCHEDPRIO" },
+ { config_parse_exec_cpu_affinity, "CPUAFFINITY" },
+ { config_parse_mode, "MODE" },
+ { config_parse_unit_env_file, "FILE" },
+ { config_parse_output, "OUTPUT" },
+ { config_parse_input, "INPUT" },
+ { config_parse_facility, "FACILITY" },
+ { config_parse_level, "LEVEL" },
+ { config_parse_exec_capabilities, "CAPABILITIES" },
+ { config_parse_exec_secure_bits, "SECUREBITS" },
+ { config_parse_bounding_set, "BOUNDINGSET" },
+ { config_parse_limit, "LIMIT" },
+ { config_parse_unit_cgroup, "CGROUP [...]" },
+ { config_parse_unit_deps, "UNIT [...]" },
+ { config_parse_exec, "PATH [ARGUMENT [...]]" },
+ { config_parse_service_type, "SERVICETYPE" },
+ { config_parse_service_restart, "SERVICERESTART" },
+#ifdef HAVE_SYSV_COMPAT
+ { config_parse_sysv_priority, "SYSVPRIORITY" },
+#else
+ { config_parse_warn_compat, "NOTSUPPORTED" },
+#endif
+ { config_parse_kill_mode, "KILLMODE" },
+ { config_parse_kill_signal, "SIGNAL" },
+ { config_parse_socket_listen, "SOCKET [...]" },
+ { config_parse_socket_bind, "SOCKETBIND" },
+ { config_parse_socket_bindtodevice, "NETWORKINTERFACE" },
+ { config_parse_sec, "SECONDS" },
+ { config_parse_nsec, "NANOSECONDS" },
+ { config_parse_path_strv, "PATH [...]" },
+ { config_parse_unit_requires_mounts_for, "PATH [...]" },
+ { config_parse_exec_mount_flags, "MOUNTFLAG [...]" },
+ { config_parse_unit_string_printf, "STRING" },
+ { config_parse_trigger_unit, "UNIT" },
+ { config_parse_timer, "TIMER" },
+ { config_parse_path_spec, "PATH" },
+ { config_parse_notify_access, "ACCESS" },
+ { config_parse_ip_tos, "TOS" },
+ { config_parse_unit_condition_path, "CONDITION" },
+ { config_parse_unit_condition_string, "CONDITION" },
+ { config_parse_unit_condition_null, "CONDITION" },
+ };
+
+ const char *prev = NULL;
+ const char *i;
+
+ assert(f);
+
+ NULSTR_FOREACH(i, load_fragment_gperf_nulstr) {
+ const char *rvalue = "OTHER", *lvalue;
+ unsigned j;
+ size_t prefix_len;
+ const char *dot;
+ const ConfigPerfItem *p;
+
+ assert_se(p = load_fragment_gperf_lookup(i, strlen(i)));
+
+ dot = strchr(i, '.');
+ lvalue = dot ? dot + 1 : i;
+ prefix_len = dot-i;
+
+ if (dot)
+ if (!prev || !strneq(prev, i, prefix_len+1)) {
+ if (prev)
+ fputc('\n', f);
+
+ fprintf(f, "[%.*s]\n", (int) prefix_len, i);
+ }
+
+ for (j = 0; j < ELEMENTSOF(table); j++)
+ if (p->parse == table[j].callback) {
+ rvalue = table[j].rvalue;
+ break;
+ }
+
+ fprintf(f, "%s=%s\n", lvalue, rvalue);
+ prev = i;
+ }
+}
diff --git a/src/core/load-fragment.h b/src/core/load-fragment.h
new file mode 100644
index 0000000000..ff7f22a6f0
--- /dev/null
+++ b/src/core/load-fragment.h
@@ -0,0 +1,84 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "unit.h"
+
+/* Read service data from .desktop file style configuration fragments */
+
+int unit_load_fragment(Unit *u);
+
+void unit_dump_config_items(FILE *f);
+
+int config_parse_warn_compat(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_unit_deps(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_unit_string_printf(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_unit_strv_printf(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_unit_path_printf(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_documentation(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_socket_listen(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_socket_bind(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_exec_nice(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_exec_oom_score_adjust(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_exec(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_service_timeout(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_service_type(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_service_restart(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_socket_bindtodevice(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_output(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_input(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_exec_io_class(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_exec_io_priority(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_exec_cpu_sched_policy(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_exec_cpu_sched_prio(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_exec_cpu_affinity(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_exec_capabilities(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_exec_secure_bits(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_bounding_set(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_limit(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_unit_cgroup(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_sysv_priority(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_fsck_passno(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_kill_signal(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_exec_mount_flags(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_timer(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_trigger_unit(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_path_spec(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_socket_service(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_service_sockets(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_unit_env_file(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_ip_tos(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_unit_condition_path(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_unit_condition_string(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_unit_condition_null(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_kill_mode(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_notify_access(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_start_limit_action(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_unit_cgroup_attr(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_unit_cgroup_attr_pretty(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_unit_requires_mounts_for(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_syscall_filter(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_environ(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+
+/* gperf prototypes */
+const struct ConfigPerfItem* load_fragment_gperf_lookup(const char *key, unsigned length);
+extern const char load_fragment_gperf_nulstr[];
diff --git a/src/core/locale-setup.c b/src/core/locale-setup.c
new file mode 100644
index 0000000000..d7113b9795
--- /dev/null
+++ b/src/core/locale-setup.c
@@ -0,0 +1,145 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <string.h>
+#include <stdlib.h>
+#include <errno.h>
+
+#include "locale-setup.h"
+#include "util.h"
+#include "macro.h"
+#include "virt.h"
+#include "fileio.h"
+
+enum {
+ /* We don't list LC_ALL here on purpose. People should be
+ * using LANG instead. */
+
+ VARIABLE_LANG,
+ VARIABLE_LANGUAGE,
+ VARIABLE_LC_CTYPE,
+ VARIABLE_LC_NUMERIC,
+ VARIABLE_LC_TIME,
+ VARIABLE_LC_COLLATE,
+ VARIABLE_LC_MONETARY,
+ VARIABLE_LC_MESSAGES,
+ VARIABLE_LC_PAPER,
+ VARIABLE_LC_NAME,
+ VARIABLE_LC_ADDRESS,
+ VARIABLE_LC_TELEPHONE,
+ VARIABLE_LC_MEASUREMENT,
+ VARIABLE_LC_IDENTIFICATION,
+ _VARIABLE_MAX
+};
+
+static const char * const variable_names[_VARIABLE_MAX] = {
+ [VARIABLE_LANG] = "LANG",
+ [VARIABLE_LANGUAGE] = "LANGUAGE",
+ [VARIABLE_LC_CTYPE] = "LC_CTYPE",
+ [VARIABLE_LC_NUMERIC] = "LC_NUMERIC",
+ [VARIABLE_LC_TIME] = "LC_TIME",
+ [VARIABLE_LC_COLLATE] = "LC_COLLATE",
+ [VARIABLE_LC_MONETARY] = "LC_MONETARY",
+ [VARIABLE_LC_MESSAGES] = "LC_MESSAGES",
+ [VARIABLE_LC_PAPER] = "LC_PAPER",
+ [VARIABLE_LC_NAME] = "LC_NAME",
+ [VARIABLE_LC_ADDRESS] = "LC_ADDRESS",
+ [VARIABLE_LC_TELEPHONE] = "LC_TELEPHONE",
+ [VARIABLE_LC_MEASUREMENT] = "LC_MEASUREMENT",
+ [VARIABLE_LC_IDENTIFICATION] = "LC_IDENTIFICATION"
+};
+
+int locale_setup(void) {
+ char *variables[_VARIABLE_MAX] = {};
+ int r = 0, i;
+
+ if (detect_container(NULL) <= 0) {
+ r = parse_env_file("/proc/cmdline", WHITESPACE,
+ "locale.LANG", &variables[VARIABLE_LANG],
+ "locale.LANGUAGE", &variables[VARIABLE_LANGUAGE],
+ "locale.LC_CTYPE", &variables[VARIABLE_LC_CTYPE],
+ "locale.LC_NUMERIC", &variables[VARIABLE_LC_NUMERIC],
+ "locale.LC_TIME", &variables[VARIABLE_LC_TIME],
+ "locale.LC_COLLATE", &variables[VARIABLE_LC_COLLATE],
+ "locale.LC_MONETARY", &variables[VARIABLE_LC_MONETARY],
+ "locale.LC_MESSAGES", &variables[VARIABLE_LC_MESSAGES],
+ "locale.LC_PAPER", &variables[VARIABLE_LC_PAPER],
+ "locale.LC_NAME", &variables[VARIABLE_LC_NAME],
+ "locale.LC_ADDRESS", &variables[VARIABLE_LC_ADDRESS],
+ "locale.LC_TELEPHONE", &variables[VARIABLE_LC_TELEPHONE],
+ "locale.LC_MEASUREMENT", &variables[VARIABLE_LC_MEASUREMENT],
+ "locale.LC_IDENTIFICATION", &variables[VARIABLE_LC_IDENTIFICATION],
+ NULL);
+
+ if (r < 0 && r != -ENOENT)
+ log_warning("Failed to read /proc/cmdline: %s", strerror(-r));
+ }
+
+ /* Hmm, nothing set on the kernel cmd line? Then let's
+ * try /etc/locale.conf */
+ if (r <= 0) {
+ r = parse_env_file("/etc/locale.conf", NEWLINE,
+ "LANG", &variables[VARIABLE_LANG],
+ "LANGUAGE", &variables[VARIABLE_LANGUAGE],
+ "LC_CTYPE", &variables[VARIABLE_LC_CTYPE],
+ "LC_NUMERIC", &variables[VARIABLE_LC_NUMERIC],
+ "LC_TIME", &variables[VARIABLE_LC_TIME],
+ "LC_COLLATE", &variables[VARIABLE_LC_COLLATE],
+ "LC_MONETARY", &variables[VARIABLE_LC_MONETARY],
+ "LC_MESSAGES", &variables[VARIABLE_LC_MESSAGES],
+ "LC_PAPER", &variables[VARIABLE_LC_PAPER],
+ "LC_NAME", &variables[VARIABLE_LC_NAME],
+ "LC_ADDRESS", &variables[VARIABLE_LC_ADDRESS],
+ "LC_TELEPHONE", &variables[VARIABLE_LC_TELEPHONE],
+ "LC_MEASUREMENT", &variables[VARIABLE_LC_MEASUREMENT],
+ "LC_IDENTIFICATION", &variables[VARIABLE_LC_IDENTIFICATION],
+ NULL);
+
+ if (r < 0 && r != -ENOENT)
+ log_warning("Failed to read /etc/locale.conf: %s", strerror(-r));
+ }
+
+ if (!variables[VARIABLE_LANG]) {
+ variables[VARIABLE_LANG] = strdup("C");
+ if (!variables[VARIABLE_LANG]) {
+ r = -ENOMEM;
+ goto finish;
+ }
+ }
+
+ for (i = 0; i < _VARIABLE_MAX; i++) {
+ if (variables[i]) {
+ if (setenv(variable_names[i], variables[i], 1) < 0) {
+ r = -errno;
+ goto finish;
+ }
+ } else
+ unsetenv(variable_names[i]);
+ }
+
+ r = 0;
+
+finish:
+ for (i = 0; i < _VARIABLE_MAX; i++)
+ free(variables[i]);
+
+ return r;
+}
diff --git a/src/core/locale-setup.h b/src/core/locale-setup.h
new file mode 100644
index 0000000000..5a0f2f7888
--- /dev/null
+++ b/src/core/locale-setup.h
@@ -0,0 +1,24 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+int locale_setup(void);
diff --git a/src/core/loopback-setup.c b/src/core/loopback-setup.c
new file mode 100644
index 0000000000..aff24fa642
--- /dev/null
+++ b/src/core/loopback-setup.c
@@ -0,0 +1,308 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <sys/socket.h>
+#include <net/if.h>
+#include <asm/types.h>
+#include <netinet/in.h>
+#include <string.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <linux/netlink.h>
+#include <linux/rtnetlink.h>
+
+#include "util.h"
+#include "macro.h"
+#include "loopback-setup.h"
+#include "socket-util.h"
+
+#define NLMSG_TAIL(nmsg) \
+ ((struct rtattr *) (((uint8_t*) (nmsg)) + NLMSG_ALIGN((nmsg)->nlmsg_len)))
+
+static int add_rtattr(struct nlmsghdr *n, size_t max_length, int type, const void *data, size_t data_length) {
+ size_t length;
+ struct rtattr *rta;
+
+ length = RTA_LENGTH(data_length);
+
+ if (NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(length) > max_length)
+ return -E2BIG;
+
+ rta = NLMSG_TAIL(n);
+ rta->rta_type = type;
+ rta->rta_len = length;
+ memcpy(RTA_DATA(rta), data, data_length);
+ n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(length);
+
+ return 0;
+}
+
+static ssize_t sendto_loop(int fd, const void *buf, size_t buf_len, int flags, const struct sockaddr *sa, socklen_t sa_len) {
+
+ for (;;) {
+ ssize_t l;
+
+ l = sendto(fd, buf, buf_len, flags, sa, sa_len);
+ if (l >= 0)
+ return l;
+
+ if (errno != EINTR)
+ return -errno;
+ }
+}
+
+static ssize_t recvfrom_loop(int fd, void *buf, size_t buf_len, int flags, struct sockaddr *sa, socklen_t *sa_len) {
+
+ for (;;) {
+ ssize_t l;
+
+ l = recvfrom(fd, buf, buf_len, flags, sa, sa_len);
+ if (l >= 0)
+ return l;
+
+ if (errno != EINTR)
+ return -errno;
+ }
+}
+
+static int add_adresses(int fd, int if_loopback, unsigned *requests) {
+ union {
+ struct sockaddr sa;
+ struct sockaddr_nl nl;
+ } sa = {
+ .nl.nl_family = AF_NETLINK,
+ };
+
+ union {
+ struct nlmsghdr header;
+ uint8_t buf[NLMSG_ALIGN(sizeof(struct nlmsghdr)) +
+ NLMSG_ALIGN(sizeof(struct ifaddrmsg)) +
+ RTA_LENGTH(sizeof(struct in6_addr))];
+ } request = {
+ .header.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifaddrmsg)),
+ .header.nlmsg_type = RTM_NEWADDR,
+ .header.nlmsg_flags = NLM_F_REQUEST|NLM_F_CREATE|NLM_F_ACK,
+ .header.nlmsg_seq = *requests + 1,
+ };
+
+ struct ifaddrmsg *ifaddrmsg;
+ uint32_t ipv4_address = htonl(INADDR_LOOPBACK);
+ int r;
+
+ ifaddrmsg = NLMSG_DATA(&request.header);
+ ifaddrmsg->ifa_family = AF_INET;
+ ifaddrmsg->ifa_prefixlen = 8;
+ ifaddrmsg->ifa_flags = IFA_F_PERMANENT;
+ ifaddrmsg->ifa_scope = RT_SCOPE_HOST;
+ ifaddrmsg->ifa_index = if_loopback;
+
+ r = add_rtattr(&request.header, sizeof(request), IFA_LOCAL,
+ &ipv4_address, sizeof(ipv4_address));
+ if (r < 0)
+ return r;
+
+ if (sendto_loop(fd, &request, request.header.nlmsg_len, 0, &sa.sa, sizeof(sa)) < 0)
+ return -errno;
+ (*requests)++;
+
+ if (!socket_ipv6_is_supported())
+ return 0;
+
+ request.header.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifaddrmsg));
+ request.header.nlmsg_seq = *requests + 1;
+
+ ifaddrmsg->ifa_family = AF_INET6;
+ ifaddrmsg->ifa_prefixlen = 128;
+
+ r = add_rtattr(&request.header, sizeof(request), IFA_LOCAL,
+ &in6addr_loopback, sizeof(in6addr_loopback));
+ if (r < 0)
+ return r;
+
+ if (sendto_loop(fd, &request, request.header.nlmsg_len, 0, &sa.sa, sizeof(sa)) < 0)
+ return -errno;
+ (*requests)++;
+
+ return 0;
+}
+
+static int start_interface(int fd, int if_loopback, unsigned *requests) {
+ union {
+ struct sockaddr sa;
+ struct sockaddr_nl nl;
+ } sa = {
+ .nl.nl_family = AF_NETLINK,
+ };
+
+ union {
+ struct nlmsghdr header;
+ uint8_t buf[NLMSG_ALIGN(sizeof(struct nlmsghdr)) +
+ NLMSG_ALIGN(sizeof(struct ifinfomsg))];
+ } request = {
+ .header.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifinfomsg)),
+ .header.nlmsg_type = RTM_NEWLINK,
+ .header.nlmsg_flags = NLM_F_REQUEST|NLM_F_ACK,
+ .header.nlmsg_seq = *requests + 1,
+ };
+
+ struct ifinfomsg *ifinfomsg;
+
+ ifinfomsg = NLMSG_DATA(&request.header);
+ ifinfomsg->ifi_family = AF_UNSPEC;
+ ifinfomsg->ifi_index = if_loopback;
+ ifinfomsg->ifi_flags = IFF_UP;
+ ifinfomsg->ifi_change = IFF_UP;
+
+ if (sendto_loop(fd, &request, request.header.nlmsg_len, 0, &sa.sa, sizeof(sa)) < 0)
+ return -errno;
+
+ (*requests)++;
+
+ return 0;
+}
+
+static int read_response(int fd, unsigned requests_max) {
+ union {
+ struct sockaddr sa;
+ struct sockaddr_nl nl;
+ } sa;
+ union {
+ struct nlmsghdr header;
+ uint8_t buf[NLMSG_ALIGN(sizeof(struct nlmsghdr)) +
+ NLMSG_ALIGN(sizeof(struct nlmsgerr))];
+ } response;
+
+ ssize_t l;
+ socklen_t sa_len = sizeof(sa);
+ struct nlmsgerr *nlmsgerr;
+
+ l = recvfrom_loop(fd, &response, sizeof(response), 0, &sa.sa, &sa_len);
+ if (l < 0)
+ return -errno;
+
+ if (sa_len != sizeof(sa.nl) ||
+ sa.nl.nl_family != AF_NETLINK)
+ return -EIO;
+
+ if (sa.nl.nl_pid != 0)
+ return 0;
+
+ if ((size_t) l < sizeof(struct nlmsghdr))
+ return -EIO;
+
+ if (response.header.nlmsg_type != NLMSG_ERROR ||
+ (pid_t) response.header.nlmsg_pid != getpid() ||
+ response.header.nlmsg_seq >= requests_max)
+ return 0;
+
+ if ((size_t) l < NLMSG_LENGTH(sizeof(struct nlmsgerr)) ||
+ response.header.nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr)))
+ return -EIO;
+
+ nlmsgerr = NLMSG_DATA(&response.header);
+
+ if (nlmsgerr->error < 0 && nlmsgerr->error != -EEXIST)
+ return nlmsgerr->error;
+
+ return response.header.nlmsg_seq;
+}
+
+static int check_loopback(void) {
+ int r;
+ _cleanup_close_ int fd;
+ union {
+ struct sockaddr sa;
+ struct sockaddr_in in;
+ } sa = {
+ .in.sin_family = AF_INET,
+ .in.sin_addr.s_addr = INADDR_LOOPBACK,
+ };
+
+ /* If we failed to set up the loop back device, check whether
+ * it might already be set up */
+
+ fd = socket(AF_INET, SOCK_DGRAM|SOCK_NONBLOCK|SOCK_CLOEXEC, 0);
+ if (fd < 0)
+ return -errno;
+
+ if (bind(fd, &sa.sa, sizeof(sa.in)) >= 0)
+ r = 1;
+ else
+ r = errno == EADDRNOTAVAIL ? 0 : -errno;
+
+ return r;
+}
+
+int loopback_setup(void) {
+ int r, if_loopback;
+ union {
+ struct sockaddr sa;
+ struct sockaddr_nl nl;
+ } sa = {
+ .nl.nl_family = AF_NETLINK,
+ };
+ unsigned requests = 0, i;
+ _cleanup_close_ int fd = -1;
+ bool eperm = false;
+
+ errno = 0;
+ if_loopback = (int) if_nametoindex("lo");
+ if (if_loopback <= 0)
+ return errno ? -errno : -ENODEV;
+
+ fd = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
+ if (fd < 0)
+ return -errno;
+
+ if (bind(fd, &sa.sa, sizeof(sa)) < 0) {
+ r = -errno;
+ goto error;
+ }
+
+ r = add_adresses(fd, if_loopback, &requests);
+ if (r < 0)
+ goto error;
+
+ r = start_interface(fd, if_loopback, &requests);
+ if (r < 0)
+ goto error;
+
+ for (i = 0; i < requests; i++) {
+ r = read_response(fd, requests);
+
+ if (r == -EPERM)
+ eperm = true;
+ else if (r < 0)
+ goto error;
+ }
+
+ if (eperm && check_loopback() < 0) {
+ r = -EPERM;
+ goto error;
+ }
+
+ return 0;
+
+error:
+ log_warning("Failed to configure loopback device: %s", strerror(-r));
+ return r;
+}
diff --git a/src/core/loopback-setup.h b/src/core/loopback-setup.h
new file mode 100644
index 0000000000..dd83cf13a7
--- /dev/null
+++ b/src/core/loopback-setup.h
@@ -0,0 +1,24 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+int loopback_setup(void);
diff --git a/src/core/machine-id-setup.c b/src/core/machine-id-setup.c
new file mode 100644
index 0000000000..18e015fe7f
--- /dev/null
+++ b/src/core/machine-id-setup.c
@@ -0,0 +1,237 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <unistd.h>
+#include <stdio.h>
+#include <errno.h>
+#include <string.h>
+#include <stdlib.h>
+#include <fcntl.h>
+#include <sys/mount.h>
+
+#include <systemd/sd-id128.h>
+
+#include "machine-id-setup.h"
+#include "macro.h"
+#include "util.h"
+#include "mkdir.h"
+#include "log.h"
+#include "virt.h"
+#include "fileio.h"
+
+static int shorten_uuid(char destination[36], const char *source) {
+ unsigned i, j;
+
+ for (i = 0, j = 0; i < 36 && j < 32; i++) {
+ int t;
+
+ t = unhexchar(source[i]);
+ if (t < 0)
+ continue;
+
+ destination[j++] = hexchar(t);
+ }
+
+ if (i == 36 && j == 32) {
+ destination[32] = '\n';
+ destination[33] = 0;
+ return 0;
+ }
+
+ return -EINVAL;
+}
+
+static int generate(char id[34]) {
+ int fd, r;
+ unsigned char *p;
+ sd_id128_t buf;
+ char *q;
+ ssize_t k;
+ const char *vm_id;
+
+ assert(id);
+
+ /* First, try reading the D-Bus machine id, unless it is a symlink */
+ fd = open("/var/lib/dbus/machine-id", O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
+ if (fd >= 0) {
+ k = loop_read(fd, id, 33, false);
+ close_nointr_nofail(fd);
+
+ if (k == 33 && id[32] == '\n') {
+
+ id[32] = 0;
+ if (id128_is_valid(id)) {
+ id[32] = '\n';
+ id[33] = 0;
+
+ log_info("Initializing machine ID from D-Bus machine ID.");
+ return 0;
+ }
+ }
+ }
+
+ /* If that didn't work, see if we are running in qemu/kvm and a
+ * machine ID was passed in via -uuid on the qemu/kvm command
+ * line */
+
+ r = detect_vm(&vm_id);
+ if (r > 0 && streq(vm_id, "kvm")) {
+ char uuid[37];
+
+ fd = open("/sys/class/dmi/id/product_uuid", O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
+ if (fd >= 0) {
+ k = loop_read(fd, uuid, 36, false);
+ close_nointr_nofail(fd);
+
+ if (k >= 36) {
+ r = shorten_uuid(id, uuid);
+ if (r >= 0) {
+ log_info("Initializing machine ID from KVM UUID.");
+ return 0;
+ }
+ }
+ }
+ }
+
+ /* If that didn't work either, see if we are running in a
+ * container, and a machine ID was passed in via
+ * $container_uuid the way libvirt/LXC does it */
+ r = detect_container(NULL);
+ if (r > 0) {
+ _cleanup_free_ char *e = NULL;
+
+ r = getenv_for_pid(1, "container_uuid", &e);
+ if (r > 0) {
+ if (strlen(e) >= 36) {
+ r = shorten_uuid(id, e);
+ if (r >= 0) {
+ log_info("Initializing machine ID from container UUID.");
+ return 0;
+ }
+ }
+ }
+ }
+
+ /* If that didn't work, generate a random machine id */
+ r = sd_id128_randomize(&buf);
+ if (r < 0) {
+ log_error("Failed to open /dev/urandom: %s", strerror(-r));
+ return r;
+ }
+
+ for (p = buf.bytes, q = id; p < buf.bytes + sizeof(buf); p++, q += 2) {
+ q[0] = hexchar(*p >> 4);
+ q[1] = hexchar(*p & 15);
+ }
+
+ id[32] = '\n';
+ id[33] = 0;
+
+ log_info("Initializing machine ID from random generator.");
+
+ return 0;
+}
+
+int machine_id_setup(void) {
+ _cleanup_close_ int fd = -1;
+ int r;
+ bool writable;
+ struct stat st;
+ char id[34]; /* 32 + \n + \0 */
+
+ RUN_WITH_UMASK(0000) {
+ /* We create this 0444, to indicate that this isn't really
+ * something you should ever modify. Of course, since the file
+ * will be owned by root it doesn't matter much, but maybe
+ * people look. */
+
+ fd = open("/etc/machine-id", O_RDWR|O_CREAT|O_CLOEXEC|O_NOCTTY, 0444);
+ if (fd >= 0)
+ writable = true;
+ else {
+ fd = open("/etc/machine-id", O_RDONLY|O_CLOEXEC|O_NOCTTY);
+ if (fd < 0) {
+ log_error("Cannot open /etc/machine-id: %m");
+ return -errno;
+ }
+
+ writable = false;
+ }
+ }
+
+ if (fstat(fd, &st) < 0) {
+ log_error("fstat() failed: %m");
+ return -errno;
+ }
+
+ if (S_ISREG(st.st_mode))
+ if (loop_read(fd, id, 33, false) == 33 && id[32] == '\n') {
+ id[32] = 0;
+
+ if (id128_is_valid(id))
+ return 0;
+ }
+
+ /* Hmm, so, the id currently stored is not useful, then let's
+ * generate one */
+
+ r = generate(id);
+ if (r < 0)
+ return r;
+
+ if (S_ISREG(st.st_mode) && writable) {
+ lseek(fd, 0, SEEK_SET);
+
+ if (loop_write(fd, id, 33, false) == 33)
+ return 0;
+ }
+
+ close_nointr_nofail(fd);
+ fd = -1;
+
+ /* Hmm, we couldn't write it? So let's write it to
+ * /run/machine-id as a replacement */
+
+ RUN_WITH_UMASK(0022) {
+ r = write_string_file("/run/machine-id", id);
+ }
+ if (r < 0) {
+ log_error("Cannot write /run/machine-id: %s", strerror(-r));
+ unlink("/run/machine-id");
+ return r;
+ }
+
+ /* And now, let's mount it over */
+ r = mount("/run/machine-id", "/etc/machine-id", NULL, MS_BIND, NULL);
+ if (r < 0) {
+ log_error("Failed to mount /etc/machine-id: %m");
+ unlink_noerrno("/run/machine-id");
+ return -errno;
+ }
+
+ log_info("Installed transient /etc/machine-id file.");
+
+ /* Mark the mount read-only */
+ if (mount(NULL, "/etc/machine-id", NULL, MS_BIND|MS_RDONLY|MS_REMOUNT, NULL) < 0)
+ log_warning("Failed to make transient /etc/machine-id read-only: %m");
+
+ return 0;
+}
diff --git a/src/core/machine-id-setup.h b/src/core/machine-id-setup.h
new file mode 100644
index 0000000000..b9e6b4d674
--- /dev/null
+++ b/src/core/machine-id-setup.h
@@ -0,0 +1,24 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+int machine_id_setup(void);
diff --git a/src/core/macros.systemd.in b/src/core/macros.systemd.in
new file mode 100644
index 0000000000..f77082c2db
--- /dev/null
+++ b/src/core/macros.systemd.in
@@ -0,0 +1,73 @@
+# -*- Mode: makefile; indent-tabs-mode: t -*- */
+#
+# This file is part of systemd.
+#
+# Copyright 2012 Lennart Poettering
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 of the License, or
+# (at your option) any later version.
+#
+# systemd is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with systemd; If not, see <http://www.gnu.org/licenses/>.
+
+# RPM macros for packages installing systemd unit files
+
+%_unitdir @systemunitdir@
+%_presetdir @systempresetdir@
+%_udevhwdbdir @udevhwdbdir@
+%_udevrulesdir @udevrulesdir@
+%_journalcatalogdir @catalogdir@
+%_tmpfilesdir @tmpfilesdir@
+%_sysctldir @sysctldir@
+
+%systemd_requires \
+Requires(post): systemd \
+Requires(preun): systemd \
+Requires(postun): systemd \
+%{nil}
+
+%systemd_post() \
+if [ $1 -eq 1 ] ; then \
+ # Initial installation \
+ @rootbindir@/systemctl preset %{?*} >/dev/null 2>&1 || : \
+fi \
+%{nil}
+
+%systemd_preun() \
+if [ $1 -eq 0 ] ; then \
+ # Package removal, not upgrade \
+ @rootbindir@/systemctl --no-reload disable %{?*} > /dev/null 2>&1 || : \
+ @rootbindir@/systemctl stop %{?*} > /dev/null 2>&1 || : \
+fi \
+%{nil}
+
+%systemd_postun() \
+@rootbindir@/systemctl daemon-reload >/dev/null 2>&1 || : \
+%{nil}
+
+%systemd_postun_with_restart() \
+@rootbindir@/systemctl daemon-reload >/dev/null 2>&1 || : \
+if [ $1 -ge 1 ] ; then \
+ # Package upgrade, not uninstall \
+ @rootbindir@/systemctl try-restart %{?*} >/dev/null 2>&1 || : \
+fi \
+%{nil}
+
+%udev_hwdb_update() \
+@rootbindir@/udevadm hwdb --update >/dev/null 2>&1 || : \
+%{nil}
+
+%udev_rules_update() \
+@rootbindir@/udevadm control --reload >/dev/null 2>&1 || : \
+%{nil}
+
+%journal_catalog_update() \
+@rootbindir@/journalctl --update-catalog >/dev/null 2>&1 || : \
+%{nil}
diff --git a/src/core/main.c b/src/core/main.c
new file mode 100644
index 0000000000..7fc06bea05
--- /dev/null
+++ b/src/core/main.c
@@ -0,0 +1,1958 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <dbus/dbus.h>
+
+#include <stdio.h>
+#include <errno.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <getopt.h>
+#include <signal.h>
+#include <sys/wait.h>
+#include <fcntl.h>
+#include <sys/prctl.h>
+#include <sys/mount.h>
+
+#include "manager.h"
+#include "log.h"
+#include "load-fragment.h"
+#include "fdset.h"
+#include "special.h"
+#include "conf-parser.h"
+#include "dbus-common.h"
+#include "missing.h"
+#include "label.h"
+#include "build.h"
+#include "strv.h"
+#include "def.h"
+#include "virt.h"
+#include "watchdog.h"
+#include "path-util.h"
+#include "switch-root.h"
+#include "capability.h"
+#include "killall.h"
+#include "env-util.h"
+#include "hwclock.h"
+#include "sd-daemon.h"
+#include "sd-messages.h"
+
+#include "mount-setup.h"
+#include "loopback-setup.h"
+#ifdef HAVE_KMOD
+#include "kmod-setup.h"
+#endif
+#include "hostname-setup.h"
+#include "machine-id-setup.h"
+#include "locale-setup.h"
+#include "selinux-setup.h"
+#include "ima-setup.h"
+#include "fileio.h"
+#include "smack-setup.h"
+#include "efivars.h"
+
+static enum {
+ ACTION_RUN,
+ ACTION_HELP,
+ ACTION_VERSION,
+ ACTION_TEST,
+ ACTION_DUMP_CONFIGURATION_ITEMS,
+ ACTION_DONE
+} arg_action = ACTION_RUN;
+
+static char *arg_default_unit = NULL;
+static SystemdRunningAs arg_running_as = _SYSTEMD_RUNNING_AS_INVALID;
+
+static bool arg_dump_core = true;
+static bool arg_crash_shell = false;
+static int arg_crash_chvt = -1;
+static bool arg_confirm_spawn = false;
+static bool arg_show_status = true;
+static bool arg_switched_root = false;
+static char **arg_default_controllers = NULL;
+static char ***arg_join_controllers = NULL;
+static ExecOutput arg_default_std_output = EXEC_OUTPUT_JOURNAL;
+static ExecOutput arg_default_std_error = EXEC_OUTPUT_INHERIT;
+static usec_t arg_runtime_watchdog = 0;
+static usec_t arg_shutdown_watchdog = 10 * USEC_PER_MINUTE;
+static struct rlimit *arg_default_rlimit[RLIMIT_NLIMITS] = {};
+static uint64_t arg_capability_bounding_set_drop = 0;
+static nsec_t arg_timer_slack_nsec = (nsec_t) -1;
+
+static FILE* serialization = NULL;
+
+static void nop_handler(int sig) {
+}
+
+_noreturn_ static void crash(int sig) {
+
+ if (!arg_dump_core)
+ log_error("Caught <%s>, not dumping core.", signal_to_string(sig));
+ else {
+ struct sigaction sa = {
+ .sa_handler = nop_handler,
+ .sa_flags = SA_NOCLDSTOP|SA_RESTART,
+ };
+ pid_t pid;
+
+ /* We want to wait for the core process, hence let's enable SIGCHLD */
+ assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
+
+ pid = fork();
+ if (pid < 0)
+ log_error("Caught <%s>, cannot fork for core dump: %s", signal_to_string(sig), strerror(errno));
+
+ else if (pid == 0) {
+ struct rlimit rl = {};
+
+ /* Enable default signal handler for core dump */
+ zero(sa);
+ sa.sa_handler = SIG_DFL;
+ assert_se(sigaction(sig, &sa, NULL) == 0);
+
+ /* Don't limit the core dump size */
+ rl.rlim_cur = RLIM_INFINITY;
+ rl.rlim_max = RLIM_INFINITY;
+ setrlimit(RLIMIT_CORE, &rl);
+
+ /* Just to be sure... */
+ assert_se(chdir("/") == 0);
+
+ /* Raise the signal again */
+ raise(sig);
+
+ assert_not_reached("We shouldn't be here...");
+ _exit(1);
+
+ } else {
+ siginfo_t status;
+ int r;
+
+ /* Order things nicely. */
+ r = wait_for_terminate(pid, &status);
+ if (r < 0)
+ log_error("Caught <%s>, waitpid() failed: %s", signal_to_string(sig), strerror(-r));
+ else if (status.si_code != CLD_DUMPED)
+ log_error("Caught <%s>, core dump failed.", signal_to_string(sig));
+ else
+ log_error("Caught <%s>, dumped core as pid %lu.", signal_to_string(sig), (unsigned long) pid);
+ }
+ }
+
+ if (arg_crash_chvt)
+ chvt(arg_crash_chvt);
+
+ if (arg_crash_shell) {
+ struct sigaction sa = {
+ .sa_handler = SIG_IGN,
+ .sa_flags = SA_NOCLDSTOP|SA_NOCLDWAIT|SA_RESTART,
+ };
+ pid_t pid;
+
+ log_info("Executing crash shell in 10s...");
+ sleep(10);
+
+ /* Let the kernel reap children for us */
+ assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
+
+ pid = fork();
+ if (pid < 0)
+ log_error("Failed to fork off crash shell: %m");
+ else if (pid == 0) {
+ make_console_stdio();
+ execl("/bin/sh", "/bin/sh", NULL);
+
+ log_error("execl() failed: %m");
+ _exit(1);
+ }
+
+ log_info("Successfully spawned crash shell as pid %lu.", (unsigned long) pid);
+ }
+
+ log_info("Freezing execution.");
+ freeze();
+}
+
+static void install_crash_handler(void) {
+ struct sigaction sa = {
+ .sa_handler = crash,
+ .sa_flags = SA_NODEFER,
+ };
+
+ sigaction_many(&sa, SIGNALS_CRASH_HANDLER, -1);
+}
+
+static int console_setup(bool do_reset) {
+ int tty_fd, r;
+
+ /* If we are init, we connect stdin/stdout/stderr to /dev/null
+ * and make sure we don't have a controlling tty. */
+
+ release_terminal();
+
+ if (!do_reset)
+ return 0;
+
+ tty_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
+ if (tty_fd < 0) {
+ log_error("Failed to open /dev/console: %s", strerror(-tty_fd));
+ return -tty_fd;
+ }
+
+ /* We don't want to force text mode.
+ * plymouth may be showing pictures already from initrd. */
+ r = reset_terminal_fd(tty_fd, false);
+ if (r < 0)
+ log_error("Failed to reset /dev/console: %s", strerror(-r));
+
+ close_nointr_nofail(tty_fd);
+ return r;
+}
+
+static int set_default_unit(const char *u) {
+ char *c;
+
+ assert(u);
+
+ c = strdup(u);
+ if (!c)
+ return -ENOMEM;
+
+ free(arg_default_unit);
+ arg_default_unit = c;
+
+ return 0;
+}
+
+static int parse_proc_cmdline_word(const char *word) {
+
+ static const char * const rlmap[] = {
+ "emergency", SPECIAL_EMERGENCY_TARGET,
+ "-b", SPECIAL_EMERGENCY_TARGET,
+ "single", SPECIAL_RESCUE_TARGET,
+ "-s", SPECIAL_RESCUE_TARGET,
+ "s", SPECIAL_RESCUE_TARGET,
+ "S", SPECIAL_RESCUE_TARGET,
+ "1", SPECIAL_RESCUE_TARGET,
+ "2", SPECIAL_RUNLEVEL2_TARGET,
+ "3", SPECIAL_RUNLEVEL3_TARGET,
+ "4", SPECIAL_RUNLEVEL4_TARGET,
+ "5", SPECIAL_RUNLEVEL5_TARGET,
+ };
+
+ assert(word);
+
+ if (startswith(word, "systemd.unit=")) {
+
+ if (!in_initrd())
+ return set_default_unit(word + 13);
+
+ } else if (startswith(word, "rd.systemd.unit=")) {
+
+ if (in_initrd())
+ return set_default_unit(word + 16);
+
+ } else if (startswith(word, "systemd.log_target=")) {
+
+ if (log_set_target_from_string(word + 19) < 0)
+ log_warning("Failed to parse log target %s. Ignoring.", word + 19);
+
+ } else if (startswith(word, "systemd.log_level=")) {
+
+ if (log_set_max_level_from_string(word + 18) < 0)
+ log_warning("Failed to parse log level %s. Ignoring.", word + 18);
+
+ } else if (startswith(word, "systemd.log_color=")) {
+
+ if (log_show_color_from_string(word + 18) < 0)
+ log_warning("Failed to parse log color setting %s. Ignoring.", word + 18);
+
+ } else if (startswith(word, "systemd.log_location=")) {
+
+ if (log_show_location_from_string(word + 21) < 0)
+ log_warning("Failed to parse log location setting %s. Ignoring.", word + 21);
+
+ } else if (startswith(word, "systemd.dump_core=")) {
+ int r;
+
+ if ((r = parse_boolean(word + 18)) < 0)
+ log_warning("Failed to parse dump core switch %s. Ignoring.", word + 18);
+ else
+ arg_dump_core = r;
+
+ } else if (startswith(word, "systemd.crash_shell=")) {
+ int r;
+
+ if ((r = parse_boolean(word + 20)) < 0)
+ log_warning("Failed to parse crash shell switch %s. Ignoring.", word + 20);
+ else
+ arg_crash_shell = r;
+
+ } else if (startswith(word, "systemd.confirm_spawn=")) {
+ int r;
+
+ if ((r = parse_boolean(word + 22)) < 0)
+ log_warning("Failed to parse confirm spawn switch %s. Ignoring.", word + 22);
+ else
+ arg_confirm_spawn = r;
+
+ } else if (startswith(word, "systemd.crash_chvt=")) {
+ int k;
+
+ if (safe_atoi(word + 19, &k) < 0)
+ log_warning("Failed to parse crash chvt switch %s. Ignoring.", word + 19);
+ else
+ arg_crash_chvt = k;
+
+ } else if (startswith(word, "systemd.show_status=")) {
+ int r;
+
+ if ((r = parse_boolean(word + 20)) < 0)
+ log_warning("Failed to parse show status switch %s. Ignoring.", word + 20);
+ else
+ arg_show_status = r;
+ } else if (startswith(word, "systemd.default_standard_output=")) {
+ int r;
+
+ if ((r = exec_output_from_string(word + 32)) < 0)
+ log_warning("Failed to parse default standard output switch %s. Ignoring.", word + 32);
+ else
+ arg_default_std_output = r;
+ } else if (startswith(word, "systemd.default_standard_error=")) {
+ int r;
+
+ if ((r = exec_output_from_string(word + 31)) < 0)
+ log_warning("Failed to parse default standard error switch %s. Ignoring.", word + 31);
+ else
+ arg_default_std_error = r;
+ } else if (startswith(word, "systemd.setenv=")) {
+ _cleanup_free_ char *cenv = NULL;
+ char *eq;
+ int r;
+
+ cenv = strdup(word + 15);
+ if (!cenv)
+ return -ENOMEM;
+
+ eq = strchr(cenv, '=');
+ if (!eq) {
+ if (!env_name_is_valid(cenv))
+ log_warning("Environment variable name '%s' is not valid. Ignoring.", cenv);
+ else {
+ r = unsetenv(cenv);
+ if (r < 0)
+ log_warning("Unsetting environment variable '%s' failed, ignoring: %m", cenv);
+ }
+ } else {
+ if (!env_assignment_is_valid(cenv))
+ log_warning("Environment variable assignment '%s' is not valid. Ignoring.", cenv);
+ else {
+ *eq = 0;
+ r = setenv(cenv, eq + 1, 1);
+ if (r < 0)
+ log_warning("Setting environment variable '%s=%s' failed, ignoring: %m", cenv, eq + 1);
+ }
+ }
+
+ } else if (startswith(word, "systemd.") ||
+ (in_initrd() && startswith(word, "rd.systemd."))) {
+
+ const char *c;
+
+ /* Ignore systemd.journald.xyz and friends */
+ c = word;
+ if (startswith(c, "rd."))
+ c += 3;
+ if (startswith(c, "systemd."))
+ c += 8;
+ if (c[strcspn(c, ".=")] != '.') {
+
+ log_warning("Unknown kernel switch %s. Ignoring.", word);
+
+ log_info("Supported kernel switches:\n"
+ "systemd.unit=UNIT Default unit to start\n"
+ "rd.systemd.unit=UNIT Default unit to start when run in initrd\n"
+ "systemd.dump_core=0|1 Dump core on crash\n"
+ "systemd.crash_shell=0|1 Run shell on crash\n"
+ "systemd.crash_chvt=N Change to VT #N on crash\n"
+ "systemd.confirm_spawn=0|1 Confirm every process spawn\n"
+ "systemd.show_status=0|1 Show status updates on the console during bootup\n"
+ "systemd.log_target=console|kmsg|journal|journal-or-kmsg|syslog|syslog-or-kmsg|null\n"
+ " Log target\n"
+ "systemd.log_level=LEVEL Log level\n"
+ "systemd.log_color=0|1 Highlight important log messages\n"
+ "systemd.log_location=0|1 Include code location in log messages\n"
+ "systemd.default_standard_output=null|tty|syslog|syslog+console|kmsg|kmsg+console|journal|journal+console\n"
+ " Set default log output for services\n"
+ "systemd.default_standard_error=null|tty|syslog|syslog+console|kmsg|kmsg+console|journal|journal+console\n"
+ " Set default log error output for services\n"
+ "systemd.setenv=ASSIGNMENT Set an environment variable for all spawned processes\n");
+ }
+
+ } else if (streq(word, "quiet"))
+ arg_show_status = false;
+ else if (!in_initrd()) {
+ unsigned i;
+
+ /* SysV compatibility */
+ for (i = 0; i < ELEMENTSOF(rlmap); i += 2)
+ if (streq(word, rlmap[i]))
+ return set_default_unit(rlmap[i+1]);
+ }
+
+ return 0;
+}
+
+#define DEFINE_SETTER(name, func, descr) \
+ static int name(const char *unit, \
+ const char *filename, \
+ unsigned line, \
+ const char *section, \
+ const char *lvalue, \
+ int ltype, \
+ const char *rvalue, \
+ void *data, \
+ void *userdata) { \
+ \
+ int r; \
+ \
+ assert(filename); \
+ assert(lvalue); \
+ assert(rvalue); \
+ \
+ r = func(rvalue); \
+ if (r < 0) \
+ log_syntax(unit, LOG_ERR, filename, line, -r, \
+ "Invalid " descr "'%s': %s", \
+ rvalue, strerror(-r)); \
+ \
+ return 0; \
+ }
+
+DEFINE_SETTER(config_parse_level2, log_set_max_level_from_string, "log level")
+DEFINE_SETTER(config_parse_target, log_set_target_from_string, "target")
+DEFINE_SETTER(config_parse_color, log_show_color_from_string, "color" )
+DEFINE_SETTER(config_parse_location, log_show_location_from_string, "location")
+
+
+static int config_parse_cpu_affinity2(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ char *w;
+ size_t l;
+ char *state;
+ cpu_set_t *c = NULL;
+ unsigned ncpus = 0;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+
+ FOREACH_WORD_QUOTED(w, l, rvalue, state) {
+ char *t;
+ int r;
+ unsigned cpu;
+
+ if (!(t = strndup(w, l)))
+ return log_oom();
+
+ r = safe_atou(t, &cpu);
+ free(t);
+
+ if (!c)
+ if (!(c = cpu_set_malloc(&ncpus)))
+ return log_oom();
+
+ if (r < 0 || cpu >= ncpus) {
+ log_syntax(unit, LOG_ERR, filename, line, -r,
+ "Failed to parse CPU affinity '%s'", rvalue);
+ CPU_FREE(c);
+ return -EBADMSG;
+ }
+
+ CPU_SET_S(cpu, CPU_ALLOC_SIZE(ncpus), c);
+ }
+
+ if (c) {
+ if (sched_setaffinity(0, CPU_ALLOC_SIZE(ncpus), c) < 0)
+ log_warning_unit(unit, "Failed to set CPU affinity: %m");
+
+ CPU_FREE(c);
+ }
+
+ return 0;
+}
+
+static void strv_free_free(char ***l) {
+ char ***i;
+
+ if (!l)
+ return;
+
+ for (i = l; *i; i++)
+ strv_free(*i);
+
+ free(l);
+}
+
+static void free_join_controllers(void) {
+ strv_free_free(arg_join_controllers);
+ arg_join_controllers = NULL;
+}
+
+static int config_parse_join_controllers(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ unsigned n = 0;
+ char *state, *w;
+ size_t length;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+
+ free_join_controllers();
+
+ FOREACH_WORD_QUOTED(w, length, rvalue, state) {
+ char *s, **l;
+
+ s = strndup(w, length);
+ if (!s)
+ return log_oom();
+
+ l = strv_split(s, ",");
+ free(s);
+
+ strv_uniq(l);
+
+ if (strv_length(l) <= 1) {
+ strv_free(l);
+ continue;
+ }
+
+ if (!arg_join_controllers) {
+ arg_join_controllers = new(char**, 2);
+ if (!arg_join_controllers) {
+ strv_free(l);
+ return log_oom();
+ }
+
+ arg_join_controllers[0] = l;
+ arg_join_controllers[1] = NULL;
+
+ n = 1;
+ } else {
+ char ***a;
+ char ***t;
+
+ t = new0(char**, n+2);
+ if (!t) {
+ strv_free(l);
+ return log_oom();
+ }
+
+ n = 0;
+
+ for (a = arg_join_controllers; *a; a++) {
+
+ if (strv_overlap(*a, l)) {
+ char **c;
+
+ c = strv_merge(*a, l);
+ if (!c) {
+ strv_free(l);
+ strv_free_free(t);
+ return log_oom();
+ }
+
+ strv_free(l);
+ l = c;
+ } else {
+ char **c;
+
+ c = strv_copy(*a);
+ if (!c) {
+ strv_free(l);
+ strv_free_free(t);
+ return log_oom();
+ }
+
+ t[n++] = c;
+ }
+ }
+
+ t[n++] = strv_uniq(l);
+
+ strv_free_free(arg_join_controllers);
+ arg_join_controllers = t;
+ }
+ }
+
+ return 0;
+}
+
+static int parse_config_file(void) {
+
+ const ConfigTableItem items[] = {
+ { "Manager", "LogLevel", config_parse_level2, 0, NULL },
+ { "Manager", "LogTarget", config_parse_target, 0, NULL },
+ { "Manager", "LogColor", config_parse_color, 0, NULL },
+ { "Manager", "LogLocation", config_parse_location, 0, NULL },
+ { "Manager", "DumpCore", config_parse_bool, 0, &arg_dump_core },
+ { "Manager", "CrashShell", config_parse_bool, 0, &arg_crash_shell },
+ { "Manager", "ShowStatus", config_parse_bool, 0, &arg_show_status },
+ { "Manager", "CrashChVT", config_parse_int, 0, &arg_crash_chvt },
+ { "Manager", "CPUAffinity", config_parse_cpu_affinity2, 0, NULL },
+ { "Manager", "DefaultControllers", config_parse_strv, 0, &arg_default_controllers },
+ { "Manager", "DefaultStandardOutput", config_parse_output, 0, &arg_default_std_output },
+ { "Manager", "DefaultStandardError", config_parse_output, 0, &arg_default_std_error },
+ { "Manager", "JoinControllers", config_parse_join_controllers, 0, &arg_join_controllers },
+ { "Manager", "RuntimeWatchdogSec", config_parse_sec, 0, &arg_runtime_watchdog },
+ { "Manager", "ShutdownWatchdogSec", config_parse_sec, 0, &arg_shutdown_watchdog },
+ { "Manager", "CapabilityBoundingSet", config_parse_bounding_set, 0, &arg_capability_bounding_set_drop },
+ { "Manager", "TimerSlackNSec", config_parse_nsec, 0, &arg_timer_slack_nsec },
+ { "Manager", "DefaultLimitCPU", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_CPU]},
+ { "Manager", "DefaultLimitFSIZE", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_FSIZE]},
+ { "Manager", "DefaultLimitDATA", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_DATA]},
+ { "Manager", "DefaultLimitSTACK", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_STACK]},
+ { "Manager", "DefaultLimitCORE", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_CORE]},
+ { "Manager", "DefaultLimitRSS", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_RSS]},
+ { "Manager", "DefaultLimitNOFILE", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_NOFILE]},
+ { "Manager", "DefaultLimitAS", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_AS]},
+ { "Manager", "DefaultLimitNPROC", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_NPROC]},
+ { "Manager", "DefaultLimitMEMLOCK", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_MEMLOCK]},
+ { "Manager", "DefaultLimitLOCKS", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_LOCKS]},
+ { "Manager", "DefaultLimitSIGPENDING",config_parse_limit, 0, &arg_default_rlimit[RLIMIT_SIGPENDING]},
+ { "Manager", "DefaultLimitMSGQUEUE", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_MSGQUEUE]},
+ { "Manager", "DefaultLimitNICE", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_NICE]},
+ { "Manager", "DefaultLimitRTPRIO", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_RTPRIO]},
+ { "Manager", "DefaultLimitRTTIME", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_RTTIME]},
+ { NULL, NULL, NULL, 0, NULL }
+ };
+
+ _cleanup_fclose_ FILE *f;
+ const char *fn;
+ int r;
+
+ fn = arg_running_as == SYSTEMD_SYSTEM ? PKGSYSCONFDIR "/system.conf" : PKGSYSCONFDIR "/user.conf";
+ f = fopen(fn, "re");
+ if (!f) {
+ if (errno == ENOENT)
+ return 0;
+
+ log_warning("Failed to open configuration file '%s': %m", fn);
+ return 0;
+ }
+
+ r = config_parse(NULL, fn, f, "Manager\0", config_item_table_lookup, (void*) items, false, false, NULL);
+ if (r < 0)
+ log_warning("Failed to parse configuration file: %s", strerror(-r));
+
+ return 0;
+}
+
+static int parse_proc_cmdline(void) {
+ _cleanup_free_ char *line = NULL;
+ char *w, *state;
+ int r;
+ size_t l;
+
+ /* Don't read /proc/cmdline if we are in a container, since
+ * that is only relevant for the host system */
+ if (detect_container(NULL) > 0)
+ return 0;
+
+ r = read_one_line_file("/proc/cmdline", &line);
+ if (r < 0) {
+ log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
+ return 0;
+ }
+
+ FOREACH_WORD_QUOTED(w, l, line, state) {
+ _cleanup_free_ char *word;
+
+ word = strndup(w, l);
+ if (!word)
+ return log_oom();
+
+ r = parse_proc_cmdline_word(word);
+ if (r < 0) {
+ log_error("Failed on cmdline argument %s: %s", word, strerror(-r));
+ return r;
+ }
+ }
+
+ return 0;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+
+ enum {
+ ARG_LOG_LEVEL = 0x100,
+ ARG_LOG_TARGET,
+ ARG_LOG_COLOR,
+ ARG_LOG_LOCATION,
+ ARG_UNIT,
+ ARG_SYSTEM,
+ ARG_USER,
+ ARG_TEST,
+ ARG_VERSION,
+ ARG_DUMP_CONFIGURATION_ITEMS,
+ ARG_DUMP_CORE,
+ ARG_CRASH_SHELL,
+ ARG_CONFIRM_SPAWN,
+ ARG_SHOW_STATUS,
+ ARG_DESERIALIZE,
+ ARG_SWITCHED_ROOT,
+ ARG_INTROSPECT,
+ ARG_DEFAULT_STD_OUTPUT,
+ ARG_DEFAULT_STD_ERROR
+ };
+
+ static const struct option options[] = {
+ { "log-level", required_argument, NULL, ARG_LOG_LEVEL },
+ { "log-target", required_argument, NULL, ARG_LOG_TARGET },
+ { "log-color", optional_argument, NULL, ARG_LOG_COLOR },
+ { "log-location", optional_argument, NULL, ARG_LOG_LOCATION },
+ { "unit", required_argument, NULL, ARG_UNIT },
+ { "system", no_argument, NULL, ARG_SYSTEM },
+ { "user", no_argument, NULL, ARG_USER },
+ { "test", no_argument, NULL, ARG_TEST },
+ { "help", no_argument, NULL, 'h' },
+ { "version", no_argument, NULL, ARG_VERSION },
+ { "dump-configuration-items", no_argument, NULL, ARG_DUMP_CONFIGURATION_ITEMS },
+ { "dump-core", optional_argument, NULL, ARG_DUMP_CORE },
+ { "crash-shell", optional_argument, NULL, ARG_CRASH_SHELL },
+ { "confirm-spawn", optional_argument, NULL, ARG_CONFIRM_SPAWN },
+ { "show-status", optional_argument, NULL, ARG_SHOW_STATUS },
+ { "deserialize", required_argument, NULL, ARG_DESERIALIZE },
+ { "switched-root", no_argument, NULL, ARG_SWITCHED_ROOT },
+ { "introspect", optional_argument, NULL, ARG_INTROSPECT },
+ { "default-standard-output", required_argument, NULL, ARG_DEFAULT_STD_OUTPUT, },
+ { "default-standard-error", required_argument, NULL, ARG_DEFAULT_STD_ERROR, },
+ { NULL, 0, NULL, 0 }
+ };
+
+ int c, r;
+
+ assert(argc >= 1);
+ assert(argv);
+
+ if (getpid() == 1)
+ opterr = 0;
+
+ while ((c = getopt_long(argc, argv, "hDbsz:", options, NULL)) >= 0)
+
+ switch (c) {
+
+ case ARG_LOG_LEVEL:
+ if ((r = log_set_max_level_from_string(optarg)) < 0) {
+ log_error("Failed to parse log level %s.", optarg);
+ return r;
+ }
+
+ break;
+
+ case ARG_LOG_TARGET:
+
+ if ((r = log_set_target_from_string(optarg)) < 0) {
+ log_error("Failed to parse log target %s.", optarg);
+ return r;
+ }
+
+ break;
+
+ case ARG_LOG_COLOR:
+
+ if (optarg) {
+ if ((r = log_show_color_from_string(optarg)) < 0) {
+ log_error("Failed to parse log color setting %s.", optarg);
+ return r;
+ }
+ } else
+ log_show_color(true);
+
+ break;
+
+ case ARG_LOG_LOCATION:
+
+ if (optarg) {
+ if ((r = log_show_location_from_string(optarg)) < 0) {
+ log_error("Failed to parse log location setting %s.", optarg);
+ return r;
+ }
+ } else
+ log_show_location(true);
+
+ break;
+
+ case ARG_DEFAULT_STD_OUTPUT:
+
+ if ((r = exec_output_from_string(optarg)) < 0) {
+ log_error("Failed to parse default standard output setting %s.", optarg);
+ return r;
+ } else
+ arg_default_std_output = r;
+ break;
+
+ case ARG_DEFAULT_STD_ERROR:
+
+ if ((r = exec_output_from_string(optarg)) < 0) {
+ log_error("Failed to parse default standard error output setting %s.", optarg);
+ return r;
+ } else
+ arg_default_std_error = r;
+ break;
+
+ case ARG_UNIT:
+
+ if ((r = set_default_unit(optarg)) < 0) {
+ log_error("Failed to set default unit %s: %s", optarg, strerror(-r));
+ return r;
+ }
+
+ break;
+
+ case ARG_SYSTEM:
+ arg_running_as = SYSTEMD_SYSTEM;
+ break;
+
+ case ARG_USER:
+ arg_running_as = SYSTEMD_USER;
+ break;
+
+ case ARG_TEST:
+ arg_action = ACTION_TEST;
+ break;
+
+ case ARG_VERSION:
+ arg_action = ACTION_VERSION;
+ break;
+
+ case ARG_DUMP_CONFIGURATION_ITEMS:
+ arg_action = ACTION_DUMP_CONFIGURATION_ITEMS;
+ break;
+
+ case ARG_DUMP_CORE:
+ r = optarg ? parse_boolean(optarg) : 1;
+ if (r < 0) {
+ log_error("Failed to parse dump core boolean %s.", optarg);
+ return r;
+ }
+ arg_dump_core = r;
+ break;
+
+ case ARG_CRASH_SHELL:
+ r = optarg ? parse_boolean(optarg) : 1;
+ if (r < 0) {
+ log_error("Failed to parse crash shell boolean %s.", optarg);
+ return r;
+ }
+ arg_crash_shell = r;
+ break;
+
+ case ARG_CONFIRM_SPAWN:
+ r = optarg ? parse_boolean(optarg) : 1;
+ if (r < 0) {
+ log_error("Failed to parse confirm spawn boolean %s.", optarg);
+ return r;
+ }
+ arg_confirm_spawn = r;
+ break;
+
+ case ARG_SHOW_STATUS:
+ r = optarg ? parse_boolean(optarg) : 1;
+ if (r < 0) {
+ log_error("Failed to parse show status boolean %s.", optarg);
+ return r;
+ }
+ arg_show_status = r;
+ break;
+
+ case ARG_DESERIALIZE: {
+ int fd;
+ FILE *f;
+
+ r = safe_atoi(optarg, &fd);
+ if (r < 0 || fd < 0) {
+ log_error("Failed to parse deserialize option %s.", optarg);
+ return r < 0 ? r : -EINVAL;
+ }
+
+ fd_cloexec(fd, true);
+
+ f = fdopen(fd, "r");
+ if (!f) {
+ log_error("Failed to open serialization fd: %m");
+ return -errno;
+ }
+
+ if (serialization)
+ fclose(serialization);
+
+ serialization = f;
+
+ break;
+ }
+
+ case ARG_SWITCHED_ROOT:
+ arg_switched_root = true;
+ break;
+
+ case ARG_INTROSPECT: {
+ const char * const * i = NULL;
+
+ for (i = bus_interface_table; *i; i += 2)
+ if (!optarg || streq(i[0], optarg)) {
+ fputs(DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE
+ "<node>\n", stdout);
+ fputs(i[1], stdout);
+ fputs("</node>\n", stdout);
+
+ if (optarg)
+ break;
+ }
+
+ if (!i[0] && optarg)
+ log_error("Unknown interface %s.", optarg);
+
+ arg_action = ACTION_DONE;
+ break;
+ }
+
+ case 'h':
+ arg_action = ACTION_HELP;
+ break;
+
+ case 'D':
+ log_set_max_level(LOG_DEBUG);
+ break;
+
+ case 'b':
+ case 's':
+ case 'z':
+ /* Just to eat away the sysvinit kernel
+ * cmdline args without getopt() error
+ * messages that we'll parse in
+ * parse_proc_cmdline_word() or ignore. */
+
+ case '?':
+ default:
+ if (getpid() != 1) {
+ log_error("Unknown option code %c", c);
+ return -EINVAL;
+ }
+
+ break;
+ }
+
+ if (optind < argc && getpid() != 1) {
+ /* Hmm, when we aren't run as init system
+ * let's complain about excess arguments */
+
+ log_error("Excess arguments.");
+ return -EINVAL;
+ }
+
+ if (detect_container(NULL) > 0) {
+ char **a;
+
+ /* All /proc/cmdline arguments the kernel didn't
+ * understand it passed to us. We're not really
+ * interested in that usually since /proc/cmdline is
+ * more interesting and complete. With one exception:
+ * if we are run in a container /proc/cmdline is not
+ * relevant for the container, hence we rely on argv[]
+ * instead. */
+
+ for (a = argv; a < argv + argc; a++)
+ if ((r = parse_proc_cmdline_word(*a)) < 0) {
+ log_error("Failed on cmdline argument %s: %s", *a, strerror(-r));
+ return r;
+ }
+ }
+
+ return 0;
+}
+
+static int help(void) {
+
+ printf("%s [OPTIONS...]\n\n"
+ "Starts up and maintains the system or user services.\n\n"
+ " -h --help Show this help\n"
+ " --test Determine startup sequence, dump it and exit\n"
+ " --dump-configuration-items Dump understood unit configuration items\n"
+ " --introspect[=INTERFACE] Extract D-Bus interface data\n"
+ " --unit=UNIT Set default unit\n"
+ " --system Run a system instance, even if PID != 1\n"
+ " --user Run a user instance\n"
+ " --dump-core[=0|1] Dump core on crash\n"
+ " --crash-shell[=0|1] Run shell on crash\n"
+ " --confirm-spawn[=0|1] Ask for confirmation when spawning processes\n"
+ " --show-status[=0|1] Show status updates on the console during bootup\n"
+ " --log-target=TARGET Set log target (console, journal, syslog, kmsg, journal-or-kmsg, syslog-or-kmsg, null)\n"
+ " --log-level=LEVEL Set log level (debug, info, notice, warning, err, crit, alert, emerg)\n"
+ " --log-color[=0|1] Highlight important log messages\n"
+ " --log-location[=0|1] Include code location in log messages\n"
+ " --default-standard-output= Set default standard output for services\n"
+ " --default-standard-error= Set default standard error output for services\n",
+ program_invocation_short_name);
+
+ return 0;
+}
+
+static int version(void) {
+ puts(PACKAGE_STRING);
+ puts(SYSTEMD_FEATURES);
+
+ return 0;
+}
+
+static int prepare_reexecute(Manager *m, FILE **_f, FDSet **_fds, bool switching_root) {
+ FILE *f = NULL;
+ FDSet *fds = NULL;
+ int r;
+
+ assert(m);
+ assert(_f);
+ assert(_fds);
+
+ /* Make sure nothing is really destructed when we shut down */
+ m->n_reloading ++;
+
+ r = manager_open_serialization(m, &f);
+ if (r < 0) {
+ log_error("Failed to create serialization file: %s", strerror(-r));
+ goto fail;
+ }
+
+ fds = fdset_new();
+ if (!fds) {
+ r = -ENOMEM;
+ log_error("Failed to allocate fd set: %s", strerror(-r));
+ goto fail;
+ }
+
+ r = manager_serialize(m, f, fds, switching_root);
+ if (r < 0) {
+ log_error("Failed to serialize state: %s", strerror(-r));
+ goto fail;
+ }
+
+ if (fseeko(f, 0, SEEK_SET) < 0) {
+ log_error("Failed to rewind serialization fd: %m");
+ goto fail;
+ }
+
+ r = fd_cloexec(fileno(f), false);
+ if (r < 0) {
+ log_error("Failed to disable O_CLOEXEC for serialization: %s", strerror(-r));
+ goto fail;
+ }
+
+ r = fdset_cloexec(fds, false);
+ if (r < 0) {
+ log_error("Failed to disable O_CLOEXEC for serialization fds: %s", strerror(-r));
+ goto fail;
+ }
+
+ *_f = f;
+ *_fds = fds;
+
+ return 0;
+
+fail:
+ fdset_free(fds);
+
+ if (f)
+ fclose(f);
+
+ return r;
+}
+
+static int bump_rlimit_nofile(struct rlimit *saved_rlimit) {
+ struct rlimit nl;
+ int r;
+
+ assert(saved_rlimit);
+
+ /* Save the original RLIMIT_NOFILE so that we can reset it
+ * later when transitioning from the initrd to the main
+ * systemd or suchlike. */
+ if (getrlimit(RLIMIT_NOFILE, saved_rlimit) < 0) {
+ log_error("Reading RLIMIT_NOFILE failed: %m");
+ return -errno;
+ }
+
+ /* Make sure forked processes get the default kernel setting */
+ if (!arg_default_rlimit[RLIMIT_NOFILE]) {
+ struct rlimit *rl;
+
+ rl = newdup(struct rlimit, saved_rlimit, 1);
+ if (!rl)
+ return log_oom();
+
+ arg_default_rlimit[RLIMIT_NOFILE] = rl;
+ }
+
+ /* Bump up the resource limit for ourselves substantially */
+ nl.rlim_cur = nl.rlim_max = 64*1024;
+ r = setrlimit_closest(RLIMIT_NOFILE, &nl);
+ if (r < 0) {
+ log_error("Setting RLIMIT_NOFILE failed: %s", strerror(-r));
+ return r;
+ }
+
+ return 0;
+}
+
+static struct dual_timestamp* parse_initrd_timestamp(struct dual_timestamp *t) {
+ const char *e;
+ unsigned long long a, b;
+
+ assert(t);
+
+ e = getenv("RD_TIMESTAMP");
+ if (!e)
+ return NULL;
+
+ if (sscanf(e, "%llu %llu", &a, &b) != 2)
+ return NULL;
+
+ t->realtime = (usec_t) a;
+ t->monotonic = (usec_t) b;
+
+ return t;
+}
+
+static void test_mtab(void) {
+ char *p;
+
+ /* Check that /etc/mtab is a symlink */
+
+ if (readlink_malloc("/etc/mtab", &p) >= 0) {
+ bool b;
+
+ b = streq(p, "/proc/self/mounts") || streq(p, "/proc/mounts");
+ free(p);
+
+ if (b)
+ return;
+ }
+
+ log_warning("/etc/mtab is not a symlink or not pointing to /proc/self/mounts. "
+ "This is not supported anymore. "
+ "Please make sure to replace this file by a symlink to avoid incorrect or misleading mount(8) output.");
+}
+
+static void test_usr(void) {
+
+ /* Check that /usr is not a separate fs */
+
+ if (dir_is_empty("/usr") <= 0)
+ return;
+
+ log_warning("/usr appears to be on its own filesytem and is not already mounted. This is not a supported setup. "
+ "Some things will probably break (sometimes even silently) in mysterious ways. "
+ "Consult http://freedesktop.org/wiki/Software/systemd/separate-usr-is-broken for more information.");
+}
+
+static void test_cgroups(void) {
+
+ if (access("/proc/cgroups", F_OK) >= 0)
+ return;
+
+ log_warning("CONFIG_CGROUPS was not set when your kernel was compiled. "
+ "Systems without control groups are not supported. "
+ "We will now sleep for 10s, and then continue boot-up. "
+ "Expect breakage and please do not file bugs. "
+ "Instead fix your kernel and enable CONFIG_CGROUPS. "
+ "Consult http://0pointer.de/blog/projects/cgroups-vs-cgroups.html for more information.");
+
+ sleep(10);
+}
+
+static int initialize_join_controllers(void) {
+ /* By default, mount "cpu" + "cpuacct" together, and "net_cls"
+ * + "net_prio". We'd like to add "cpuset" to the mix, but
+ * "cpuset" does't really work for groups with no initialized
+ * attributes. */
+
+ arg_join_controllers = new(char**, 3);
+ if (!arg_join_controllers)
+ return -ENOMEM;
+
+ arg_join_controllers[0] = strv_new("cpu", "cpuacct", NULL);
+ arg_join_controllers[1] = strv_new("net_cls", "net_prio", NULL);
+ arg_join_controllers[2] = NULL;
+
+ if (!arg_join_controllers[0] || !arg_join_controllers[1]) {
+ free_join_controllers();
+ return -ENOMEM;
+ }
+
+ return 0;
+}
+
+int main(int argc, char *argv[]) {
+ Manager *m = NULL;
+ int r, retval = EXIT_FAILURE;
+ usec_t before_startup, after_startup;
+ char timespan[FORMAT_TIMESPAN_MAX];
+ FDSet *fds = NULL;
+ bool reexecute = false;
+ const char *shutdown_verb = NULL;
+ dual_timestamp initrd_timestamp = { 0ULL, 0ULL };
+ dual_timestamp userspace_timestamp = { 0ULL, 0ULL };
+ dual_timestamp kernel_timestamp = { 0ULL, 0ULL };
+ dual_timestamp firmware_timestamp = { 0ULL, 0ULL };
+ dual_timestamp loader_timestamp = { 0ULL, 0ULL };
+ static char systemd[] = "systemd";
+ bool skip_setup = false;
+ int j;
+ bool loaded_policy = false;
+ bool arm_reboot_watchdog = false;
+ bool queue_default_job = false;
+ char *switch_root_dir = NULL, *switch_root_init = NULL;
+ static struct rlimit saved_rlimit_nofile = { 0, 0 };
+
+#ifdef HAVE_SYSV_COMPAT
+ if (getpid() != 1 && strstr(program_invocation_short_name, "init")) {
+ /* This is compatibility support for SysV, where
+ * calling init as a user is identical to telinit. */
+
+ errno = -ENOENT;
+ execv(SYSTEMCTL_BINARY_PATH, argv);
+ log_error("Failed to exec " SYSTEMCTL_BINARY_PATH ": %m");
+ return 1;
+ }
+#endif
+
+ dual_timestamp_from_monotonic(&kernel_timestamp, 0);
+ dual_timestamp_get(&userspace_timestamp);
+
+ /* Determine if this is a reexecution or normal bootup. We do
+ * the full command line parsing much later, so let's just
+ * have a quick peek here. */
+ if (strv_find(argv+1, "--deserialize"))
+ skip_setup = true;
+
+ /* If we have switched root, do all the special setup
+ * things */
+ if (strv_find(argv+1, "--switched-root"))
+ skip_setup = false;
+
+ /* If we get started via the /sbin/init symlink then we are
+ called 'init'. After a subsequent reexecution we are then
+ called 'systemd'. That is confusing, hence let's call us
+ systemd right-away. */
+ program_invocation_short_name = systemd;
+ prctl(PR_SET_NAME, systemd);
+
+ saved_argv = argv;
+ saved_argc = argc;
+
+ log_show_color(isatty(STDERR_FILENO) > 0);
+
+ if (getpid() == 1 && detect_container(NULL) <= 0) {
+#ifdef ENABLE_EFI
+ efi_get_boot_timestamps(&userspace_timestamp, &firmware_timestamp, &loader_timestamp);
+#endif
+ /* Running outside of a container as PID 1 */
+ arg_running_as = SYSTEMD_SYSTEM;
+ make_null_stdio();
+ log_set_target(LOG_TARGET_KMSG);
+ log_open();
+
+ if (in_initrd()) {
+ char *rd_timestamp = NULL;
+
+ initrd_timestamp = userspace_timestamp;
+ asprintf(&rd_timestamp, "%llu %llu",
+ (unsigned long long) initrd_timestamp.realtime,
+ (unsigned long long) initrd_timestamp.monotonic);
+ if (rd_timestamp) {
+ setenv("RD_TIMESTAMP", rd_timestamp, 1);
+ free(rd_timestamp);
+ }
+ }
+
+ if (!skip_setup) {
+ mount_setup_early();
+ if (selinux_setup(&loaded_policy) < 0)
+ goto finish;
+ if (ima_setup() < 0)
+ goto finish;
+ if (smack_setup() < 0)
+ goto finish;
+ }
+
+ if (label_init(NULL) < 0)
+ goto finish;
+
+ if (!skip_setup) {
+ if (hwclock_is_localtime() > 0) {
+ int min;
+
+ /* The first-time call to settimeofday() does a time warp in the kernel */
+ r = hwclock_set_timezone(&min);
+ if (r < 0)
+ log_error("Failed to apply local time delta, ignoring: %s", strerror(-r));
+ else
+ log_info("RTC configured in localtime, applying delta of %i minutes to system time.", min);
+ } else if (!in_initrd()) {
+ /*
+ * Do dummy first-time call to seal the kernel's time warp magic
+ *
+ * Do not call this this from inside the initrd. The initrd might not
+ * carry /etc/adjtime with LOCAL, but the real system could be set up
+ * that way. In such case, we need to delay the time-warp or the sealing
+ * until we reach the real system.
+ */
+ hwclock_reset_timezone();
+
+ /* Tell the kernel our time zone */
+ r = hwclock_set_timezone(NULL);
+ if (r < 0)
+ log_error("Failed to set the kernel's time zone, ignoring: %s", strerror(-r));
+ }
+ }
+
+ /* Set the default for later on, but don't actually
+ * open the logs like this for now. Note that if we
+ * are transitioning from the initrd there might still
+ * be journal fd open, and we shouldn't attempt
+ * opening that before we parsed /proc/cmdline which
+ * might redirect output elsewhere. */
+ log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
+
+ } else if (getpid() == 1) {
+ /* Running inside a container, as PID 1 */
+ arg_running_as = SYSTEMD_SYSTEM;
+ log_set_target(LOG_TARGET_CONSOLE);
+ log_open();
+
+ /* For the later on, see above... */
+ log_set_target(LOG_TARGET_JOURNAL);
+
+ /* clear the kernel timestamp,
+ * because we are in a container */
+ kernel_timestamp.monotonic = 0ULL;
+ kernel_timestamp.realtime = 0ULL;
+
+ } else {
+ /* Running as user instance */
+ arg_running_as = SYSTEMD_USER;
+ log_set_target(LOG_TARGET_AUTO);
+ log_open();
+
+ /* clear the kernel timestamp,
+ * because we are not PID 1 */
+ kernel_timestamp.monotonic = 0ULL;
+ kernel_timestamp.realtime = 0ULL;
+ }
+
+ /* Initialize default unit */
+ r = set_default_unit(SPECIAL_DEFAULT_TARGET);
+ if (r < 0) {
+ log_error("Failed to set default unit %s: %s", SPECIAL_DEFAULT_TARGET, strerror(-r));
+ goto finish;
+ }
+
+ r = initialize_join_controllers();
+ if (r < 0)
+ goto finish;
+
+ /* Mount /proc, /sys and friends, so that /proc/cmdline and
+ * /proc/$PID/fd is available. */
+ if (getpid() == 1) {
+ r = mount_setup(loaded_policy);
+ if (r < 0)
+ goto finish;
+ }
+
+ /* Reset all signal handlers. */
+ assert_se(reset_all_signal_handlers() == 0);
+
+ /* If we are init, we can block sigkill. Yay. */
+ ignore_signals(SIGNALS_IGNORE, -1);
+
+ if (parse_config_file() < 0)
+ goto finish;
+
+ if (arg_running_as == SYSTEMD_SYSTEM)
+ if (parse_proc_cmdline() < 0)
+ goto finish;
+
+ log_parse_environment();
+
+ if (parse_argv(argc, argv) < 0)
+ goto finish;
+
+ if (arg_action == ACTION_TEST &&
+ geteuid() == 0) {
+ log_error("Don't run test mode as root.");
+ goto finish;
+ }
+
+ if (arg_running_as == SYSTEMD_USER &&
+ arg_action == ACTION_RUN &&
+ sd_booted() <= 0) {
+ log_error("Trying to run as user instance, but the system has not been booted with systemd.");
+ goto finish;
+ }
+
+ if (arg_running_as == SYSTEMD_SYSTEM &&
+ arg_action == ACTION_RUN &&
+ running_in_chroot() > 0) {
+ log_error("Cannot be run in a chroot() environment.");
+ goto finish;
+ }
+
+ if (arg_action == ACTION_HELP) {
+ retval = help();
+ goto finish;
+ } else if (arg_action == ACTION_VERSION) {
+ retval = version();
+ goto finish;
+ } else if (arg_action == ACTION_DUMP_CONFIGURATION_ITEMS) {
+ unit_dump_config_items(stdout);
+ retval = EXIT_SUCCESS;
+ goto finish;
+ } else if (arg_action == ACTION_DONE) {
+ retval = EXIT_SUCCESS;
+ goto finish;
+ }
+
+ assert_se(arg_action == ACTION_RUN || arg_action == ACTION_TEST);
+
+ /* Close logging fds, in order not to confuse fdset below */
+ log_close();
+
+ /* Remember open file descriptors for later deserialization */
+ r = fdset_new_fill(&fds);
+ if (r < 0) {
+ log_error("Failed to allocate fd set: %s", strerror(-r));
+ goto finish;
+ } else
+ fdset_cloexec(fds, true);
+
+ if (serialization)
+ assert_se(fdset_remove(fds, fileno(serialization)) >= 0);
+
+ /* Set up PATH unless it is already set */
+ setenv("PATH",
+#ifdef HAVE_SPLIT_USR
+ "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
+#else
+ "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin",
+#endif
+ arg_running_as == SYSTEMD_SYSTEM);
+
+ if (arg_running_as == SYSTEMD_SYSTEM) {
+ /* Parse the data passed to us. We leave this
+ * variables set, but the manager later on will not
+ * pass them on to our children. */
+ if (!in_initrd())
+ parse_initrd_timestamp(&initrd_timestamp);
+
+ /* Unset some environment variables passed in from the
+ * kernel that don't really make sense for us. */
+ unsetenv("HOME");
+ unsetenv("TERM");
+
+ /* When we are invoked by a shell, these might be set,
+ * but make little sense to pass on */
+ unsetenv("PWD");
+ unsetenv("SHLVL");
+ unsetenv("_");
+
+ /* When we are invoked by a chroot-like tool such as
+ * nspawn, these might be set, but make little sense
+ * to pass on */
+ unsetenv("USER");
+ unsetenv("LOGNAME");
+
+ /* We suppress the socket activation env vars, as
+ * we'll try to match *any* open fd to units if
+ * possible. */
+ unsetenv("LISTEN_FDS");
+ unsetenv("LISTEN_PID");
+
+ /* All other variables are left as is, so that clients
+ * can still read them via /proc/1/environ */
+ }
+
+ /* Move out of the way, so that we won't block unmounts */
+ assert_se(chdir("/") == 0);
+
+ if (arg_running_as == SYSTEMD_SYSTEM) {
+ /* Become a session leader if we aren't one yet. */
+ setsid();
+
+ /* Disable the umask logic */
+ umask(0);
+ }
+
+ /* Make sure D-Bus doesn't fiddle with the SIGPIPE handlers */
+ dbus_connection_set_change_sigpipe(FALSE);
+
+ /* Reset the console, but only if this is really init and we
+ * are freshly booted */
+ if (arg_running_as == SYSTEMD_SYSTEM && arg_action == ACTION_RUN)
+ console_setup(getpid() == 1 && !skip_setup);
+
+ /* Open the logging devices, if possible and necessary */
+ log_open();
+
+ /* Make sure we leave a core dump without panicing the
+ * kernel. */
+ if (getpid() == 1) {
+ install_crash_handler();
+
+ r = mount_cgroup_controllers(arg_join_controllers);
+ if (r < 0)
+ goto finish;
+ }
+
+ if (arg_running_as == SYSTEMD_SYSTEM) {
+ const char *virtualization = NULL;
+
+ log_info(PACKAGE_STRING " running in system mode. (" SYSTEMD_FEATURES ")");
+
+ detect_virtualization(&virtualization);
+ if (virtualization)
+ log_info("Detected virtualization '%s'.", virtualization);
+
+ if (in_initrd())
+ log_info("Running in initial RAM disk.");
+
+ } else
+ log_debug(PACKAGE_STRING " running in user mode. (" SYSTEMD_FEATURES ")");
+
+ if (arg_running_as == SYSTEMD_SYSTEM && !skip_setup) {
+ locale_setup();
+
+ if (arg_show_status || plymouth_running())
+ status_welcome();
+
+#ifdef HAVE_KMOD
+ kmod_setup();
+#endif
+ hostname_setup();
+ machine_id_setup();
+ loopback_setup();
+
+ test_mtab();
+ test_usr();
+ test_cgroups();
+ }
+
+ if (arg_running_as == SYSTEMD_SYSTEM && arg_runtime_watchdog > 0)
+ watchdog_set_timeout(&arg_runtime_watchdog);
+
+ if (arg_timer_slack_nsec != (nsec_t) -1)
+ if (prctl(PR_SET_TIMERSLACK, arg_timer_slack_nsec) < 0)
+ log_error("Failed to adjust timer slack: %m");
+
+ if (arg_capability_bounding_set_drop) {
+ r = capability_bounding_set_drop(arg_capability_bounding_set_drop, true);
+ if (r < 0) {
+ log_error("Failed to drop capability bounding set: %s", strerror(-r));
+ goto finish;
+ }
+ r = capability_bounding_set_drop_usermode(arg_capability_bounding_set_drop);
+ if (r < 0) {
+ log_error("Failed to drop capability bounding set of usermode helpers: %s", strerror(-r));
+ goto finish;
+ }
+ }
+
+ if (arg_running_as == SYSTEMD_USER) {
+ /* Become reaper of our children */
+ if (prctl(PR_SET_CHILD_SUBREAPER, 1) < 0) {
+ log_warning("Failed to make us a subreaper: %m");
+ if (errno == EINVAL)
+ log_info("Perhaps the kernel version is too old (< 3.4?)");
+ }
+ }
+
+ if (arg_running_as == SYSTEMD_SYSTEM)
+ bump_rlimit_nofile(&saved_rlimit_nofile);
+
+ r = manager_new(arg_running_as, &m);
+ if (r < 0) {
+ log_error("Failed to allocate manager object: %s", strerror(-r));
+ goto finish;
+ }
+
+ m->confirm_spawn = arg_confirm_spawn;
+ m->default_std_output = arg_default_std_output;
+ m->default_std_error = arg_default_std_error;
+ m->runtime_watchdog = arg_runtime_watchdog;
+ m->shutdown_watchdog = arg_shutdown_watchdog;
+ m->userspace_timestamp = userspace_timestamp;
+ m->kernel_timestamp = kernel_timestamp;
+ m->firmware_timestamp = firmware_timestamp;
+ m->loader_timestamp = loader_timestamp;
+ m->initrd_timestamp = initrd_timestamp;
+
+ manager_set_default_rlimits(m, arg_default_rlimit);
+
+ if (arg_default_controllers)
+ manager_set_default_controllers(m, arg_default_controllers);
+
+ manager_set_show_status(m, arg_show_status);
+
+ /* Remember whether we should queue the default job */
+ queue_default_job = !serialization || arg_switched_root;
+
+ before_startup = now(CLOCK_MONOTONIC);
+
+ r = manager_startup(m, serialization, fds);
+ if (r < 0)
+ log_error("Failed to fully start up daemon: %s", strerror(-r));
+
+ /* This will close all file descriptors that were opened, but
+ * not claimed by any unit. */
+ fdset_free(fds);
+
+ if (serialization) {
+ fclose(serialization);
+ serialization = NULL;
+ }
+
+ if (queue_default_job) {
+ DBusError error;
+ Unit *target = NULL;
+ Job *default_unit_job;
+
+ dbus_error_init(&error);
+
+ log_debug("Activating default unit: %s", arg_default_unit);
+
+ r = manager_load_unit(m, arg_default_unit, NULL, &error, &target);
+ if (r < 0) {
+ log_error("Failed to load default target: %s", bus_error(&error, r));
+ dbus_error_free(&error);
+ } else if (target->load_state == UNIT_ERROR)
+ log_error("Failed to load default target: %s", strerror(-target->load_error));
+ else if (target->load_state == UNIT_MASKED)
+ log_error("Default target masked.");
+
+ if (!target || target->load_state != UNIT_LOADED) {
+ log_info("Trying to load rescue target...");
+
+ r = manager_load_unit(m, SPECIAL_RESCUE_TARGET, NULL, &error, &target);
+ if (r < 0) {
+ log_error("Failed to load rescue target: %s", bus_error(&error, r));
+ dbus_error_free(&error);
+ goto finish;
+ } else if (target->load_state == UNIT_ERROR) {
+ log_error("Failed to load rescue target: %s", strerror(-target->load_error));
+ goto finish;
+ } else if (target->load_state == UNIT_MASKED) {
+ log_error("Rescue target masked.");
+ goto finish;
+ }
+ }
+
+ assert(target->load_state == UNIT_LOADED);
+
+ if (arg_action == ACTION_TEST) {
+ printf("-> By units:\n");
+ manager_dump_units(m, stdout, "\t");
+ }
+
+ r = manager_add_job(m, JOB_START, target, JOB_ISOLATE, false, &error, &default_unit_job);
+ if (r == -EPERM) {
+ log_debug("Default target could not be isolated, starting instead: %s", bus_error(&error, r));
+ dbus_error_free(&error);
+
+ r = manager_add_job(m, JOB_START, target, JOB_REPLACE, false, &error, &default_unit_job);
+ if (r < 0) {
+ log_error("Failed to start default target: %s", bus_error(&error, r));
+ dbus_error_free(&error);
+ goto finish;
+ }
+ } else if (r < 0) {
+ log_error("Failed to isolate default target: %s", bus_error(&error, r));
+ dbus_error_free(&error);
+ goto finish;
+ }
+
+ m->default_unit_job_id = default_unit_job->id;
+
+ after_startup = now(CLOCK_MONOTONIC);
+ log_full(arg_action == ACTION_TEST ? LOG_INFO : LOG_DEBUG,
+ "Loaded units and determined initial transaction in %s.",
+ format_timespan(timespan, sizeof(timespan), after_startup - before_startup, 0));
+
+ if (arg_action == ACTION_TEST) {
+ printf("-> By jobs:\n");
+ manager_dump_jobs(m, stdout, "\t");
+ retval = EXIT_SUCCESS;
+ goto finish;
+ }
+ }
+
+ for (;;) {
+ r = manager_loop(m);
+ if (r < 0) {
+ log_error("Failed to run mainloop: %s", strerror(-r));
+ goto finish;
+ }
+
+ switch (m->exit_code) {
+
+ case MANAGER_EXIT:
+ retval = EXIT_SUCCESS;
+ log_debug("Exit.");
+ goto finish;
+
+ case MANAGER_RELOAD:
+ log_info("Reloading.");
+ r = manager_reload(m);
+ if (r < 0)
+ log_error("Failed to reload: %s", strerror(-r));
+ break;
+
+ case MANAGER_REEXECUTE:
+
+ if (prepare_reexecute(m, &serialization, &fds, false) < 0)
+ goto finish;
+
+ reexecute = true;
+ log_notice("Reexecuting.");
+ goto finish;
+
+ case MANAGER_SWITCH_ROOT:
+ /* Steal the switch root parameters */
+ switch_root_dir = m->switch_root;
+ switch_root_init = m->switch_root_init;
+ m->switch_root = m->switch_root_init = NULL;
+
+ if (!switch_root_init)
+ if (prepare_reexecute(m, &serialization, &fds, true) < 0)
+ goto finish;
+
+ reexecute = true;
+ log_notice("Switching root.");
+ goto finish;
+
+ case MANAGER_REBOOT:
+ case MANAGER_POWEROFF:
+ case MANAGER_HALT:
+ case MANAGER_KEXEC: {
+ static const char * const table[_MANAGER_EXIT_CODE_MAX] = {
+ [MANAGER_REBOOT] = "reboot",
+ [MANAGER_POWEROFF] = "poweroff",
+ [MANAGER_HALT] = "halt",
+ [MANAGER_KEXEC] = "kexec"
+ };
+
+ assert_se(shutdown_verb = table[m->exit_code]);
+ arm_reboot_watchdog = m->exit_code == MANAGER_REBOOT;
+
+ log_notice("Shutting down.");
+ goto finish;
+ }
+
+ default:
+ assert_not_reached("Unknown exit code.");
+ }
+ }
+
+finish:
+ if (m)
+ manager_free(m);
+
+ for (j = 0; j < RLIMIT_NLIMITS; j++)
+ free(arg_default_rlimit[j]);
+
+ free(arg_default_unit);
+ strv_free(arg_default_controllers);
+ free_join_controllers();
+
+ dbus_shutdown();
+ label_finish();
+
+ if (reexecute) {
+ const char **args;
+ unsigned i, args_size;
+
+ /* Close and disarm the watchdog, so that the new
+ * instance can reinitialize it, but doesn't get
+ * rebooted while we do that */
+ watchdog_close(true);
+
+ /* Reset the RLIMIT_NOFILE to the kernel default, so
+ * that the new systemd can pass the kernel default to
+ * its child processes */
+ if (saved_rlimit_nofile.rlim_cur > 0)
+ setrlimit(RLIMIT_NOFILE, &saved_rlimit_nofile);
+
+ if (switch_root_dir) {
+ /* Kill all remaining processes from the
+ * initrd, but don't wait for them, so that we
+ * can handle the SIGCHLD for them after
+ * deserializing. */
+ broadcast_signal(SIGTERM, false);
+
+ /* And switch root */
+ r = switch_root(switch_root_dir);
+ if (r < 0)
+ log_error("Failed to switch root, ignoring: %s", strerror(-r));
+ }
+
+ args_size = MAX(6, argc+1);
+ args = newa(const char*, args_size);
+
+ if (!switch_root_init) {
+ char sfd[16];
+
+ /* First try to spawn ourselves with the right
+ * path, and with full serialization. We do
+ * this only if the user didn't specify an
+ * explicit init to spawn. */
+
+ assert(serialization);
+ assert(fds);
+
+ snprintf(sfd, sizeof(sfd), "%i", fileno(serialization));
+ char_array_0(sfd);
+
+ i = 0;
+ args[i++] = SYSTEMD_BINARY_PATH;
+ if (switch_root_dir)
+ args[i++] = "--switched-root";
+ args[i++] = arg_running_as == SYSTEMD_SYSTEM ? "--system" : "--user";
+ args[i++] = "--deserialize";
+ args[i++] = sfd;
+ args[i++] = NULL;
+
+ assert(i <= args_size);
+ execv(args[0], (char* const*) args);
+ }
+
+ /* Try the fallback, if there is any, without any
+ * serialization. We pass the original argv[] and
+ * envp[]. (Well, modulo the ordering changes due to
+ * getopt() in argv[], and some cleanups in envp[],
+ * but let's hope that doesn't matter.) */
+
+ if (serialization) {
+ fclose(serialization);
+ serialization = NULL;
+ }
+
+ if (fds) {
+ fdset_free(fds);
+ fds = NULL;
+ }
+
+ /* Reopen the console */
+ make_console_stdio();
+
+ for (j = 1, i = 1; j < argc; j++)
+ args[i++] = argv[j];
+ args[i++] = NULL;
+ assert(i <= args_size);
+
+ if (switch_root_init) {
+ args[0] = switch_root_init;
+ execv(args[0], (char* const*) args);
+ log_warning("Failed to execute configured init, trying fallback: %m");
+ }
+
+ args[0] = "/sbin/init";
+ execv(args[0], (char* const*) args);
+
+ if (errno == ENOENT) {
+ log_warning("No /sbin/init, trying fallback");
+
+ args[0] = "/bin/sh";
+ args[1] = NULL;
+ execv(args[0], (char* const*) args);
+ log_error("Failed to execute /bin/sh, giving up: %m");
+ } else
+ log_warning("Failed to execute /sbin/init, giving up: %m");
+ }
+
+ if (serialization)
+ fclose(serialization);
+
+ if (fds)
+ fdset_free(fds);
+
+ if (shutdown_verb) {
+ const char * command_line[] = {
+ SYSTEMD_SHUTDOWN_BINARY_PATH,
+ shutdown_verb,
+ NULL
+ };
+ char **env_block;
+
+ if (arm_reboot_watchdog && arg_shutdown_watchdog > 0) {
+ char e[32];
+
+ /* If we reboot let's set the shutdown
+ * watchdog and tell the shutdown binary to
+ * repeatedly ping it */
+ watchdog_set_timeout(&arg_shutdown_watchdog);
+ watchdog_close(false);
+
+ /* Tell the binary how often to ping */
+ snprintf(e, sizeof(e), "WATCHDOG_USEC=%llu", (unsigned long long) arg_shutdown_watchdog);
+ char_array_0(e);
+
+ env_block = strv_append(environ, e);
+ } else {
+ env_block = strv_copy(environ);
+ watchdog_close(true);
+ }
+
+ execve(SYSTEMD_SHUTDOWN_BINARY_PATH, (char **) command_line, env_block);
+ free(env_block);
+ log_error("Failed to execute shutdown binary, freezing: %m");
+ }
+
+ if (getpid() == 1)
+ freeze();
+
+ return retval;
+}
diff --git a/src/core/manager.c b/src/core/manager.c
new file mode 100644
index 0000000000..c7f8f20a70
--- /dev/null
+++ b/src/core/manager.c
@@ -0,0 +1,2674 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <errno.h>
+#include <string.h>
+#include <sys/epoll.h>
+#include <signal.h>
+#include <sys/signalfd.h>
+#include <sys/wait.h>
+#include <unistd.h>
+#include <sys/poll.h>
+#include <sys/reboot.h>
+#include <sys/ioctl.h>
+#include <linux/kd.h>
+#include <termios.h>
+#include <fcntl.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <dirent.h>
+#include <sys/timerfd.h>
+
+#ifdef HAVE_AUDIT
+#include <libaudit.h>
+#endif
+
+#include "systemd/sd-daemon.h"
+#include "systemd/sd-id128.h"
+#include "systemd/sd-messages.h"
+
+#include "manager.h"
+#include "transaction.h"
+#include "hashmap.h"
+#include "macro.h"
+#include "strv.h"
+#include "log.h"
+#include "util.h"
+#include "mkdir.h"
+#include "ratelimit.h"
+#include "cgroup.h"
+#include "mount-setup.h"
+#include "unit-name.h"
+#include "dbus-unit.h"
+#include "dbus-job.h"
+#include "missing.h"
+#include "path-lookup.h"
+#include "special.h"
+#include "bus-errors.h"
+#include "exit-status.h"
+#include "virt.h"
+#include "watchdog.h"
+#include "cgroup-util.h"
+#include "path-util.h"
+#include "audit-fd.h"
+#include "env-util.h"
+
+/* As soon as 16 units are in our GC queue, make sure to run a gc sweep */
+#define GC_QUEUE_ENTRIES_MAX 16
+
+/* As soon as 5s passed since a unit was added to our GC queue, make sure to run a gc sweep */
+#define GC_QUEUE_USEC_MAX (10*USEC_PER_SEC)
+
+/* Initial delay and the interval for printing status messages about running jobs */
+#define JOBS_IN_PROGRESS_WAIT_SEC 5
+#define JOBS_IN_PROGRESS_PERIOD_SEC 1
+#define JOBS_IN_PROGRESS_PERIOD_DIVISOR 3
+
+/* Where clients shall send notification messages to */
+#define NOTIFY_SOCKET "@/org/freedesktop/systemd1/notify"
+
+#define TIME_T_MAX (time_t)((1UL << ((sizeof(time_t) << 3) - 1)) - 1)
+
+static int manager_setup_notify(Manager *m) {
+ union {
+ struct sockaddr sa;
+ struct sockaddr_un un;
+ } sa = {
+ .sa.sa_family = AF_UNIX,
+ };
+ struct epoll_event ev = {
+ .events = EPOLLIN,
+ .data.ptr = &m->notify_watch,
+ };
+ int one = 1, r;
+
+ m->notify_watch.type = WATCH_NOTIFY;
+ m->notify_watch.fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
+ if (m->notify_watch.fd < 0) {
+ log_error("Failed to allocate notification socket: %m");
+ return -errno;
+ }
+
+ if (getpid() != 1 || detect_container(NULL) > 0)
+ snprintf(sa.un.sun_path, sizeof(sa.un.sun_path), NOTIFY_SOCKET "/%llu", random_ull());
+ else
+ strncpy(sa.un.sun_path, NOTIFY_SOCKET, sizeof(sa.un.sun_path));
+
+ sa.un.sun_path[0] = 0;
+
+ r = bind(m->notify_watch.fd, &sa.sa,
+ offsetof(struct sockaddr_un, sun_path) + 1 + strlen(sa.un.sun_path+1));
+ if (r < 0) {
+ log_error("bind() failed: %m");
+ return -errno;
+ }
+
+ r = setsockopt(m->notify_watch.fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
+ if (r < 0) {
+ log_error("SO_PASSCRED failed: %m");
+ return -errno;
+ }
+
+ r = epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->notify_watch.fd, &ev);
+ if (r < 0) {
+ log_error("Failed to add notification socket fd to epoll: %m");
+ return -errno;
+ }
+
+ sa.un.sun_path[0] = '@';
+ m->notify_socket = strdup(sa.un.sun_path);
+ if (!m->notify_socket)
+ return log_oom();
+
+ log_debug("Using notification socket %s", m->notify_socket);
+
+ return 0;
+}
+
+static int manager_jobs_in_progress_mod_timer(Manager *m) {
+ struct itimerspec its = {
+ .it_value.tv_sec = JOBS_IN_PROGRESS_WAIT_SEC,
+ .it_interval.tv_sec = JOBS_IN_PROGRESS_PERIOD_SEC,
+ };
+
+ if (m->jobs_in_progress_watch.type != WATCH_JOBS_IN_PROGRESS)
+ return 0;
+
+ if (timerfd_settime(m->jobs_in_progress_watch.fd, 0, &its, NULL) < 0)
+ return -errno;
+
+ return 0;
+}
+
+static int manager_watch_jobs_in_progress(Manager *m) {
+ struct epoll_event ev = {
+ .events = EPOLLIN,
+ .data.ptr = &m->jobs_in_progress_watch,
+ };
+ int r;
+
+ if (m->jobs_in_progress_watch.type != WATCH_INVALID)
+ return 0;
+
+ m->jobs_in_progress_watch.type = WATCH_JOBS_IN_PROGRESS;
+ m->jobs_in_progress_watch.fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC);
+ if (m->jobs_in_progress_watch.fd < 0) {
+ log_error("Failed to create timerfd: %m");
+ r = -errno;
+ goto err;
+ }
+
+ r = manager_jobs_in_progress_mod_timer(m);
+ if (r < 0) {
+ log_error("Failed to set up timer for jobs progress watch: %s", strerror(-r));
+ goto err;
+ }
+
+ if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->jobs_in_progress_watch.fd, &ev) < 0) {
+ log_error("Failed to add jobs progress timer fd to epoll: %m");
+ r = -errno;
+ goto err;
+ }
+
+ log_debug("Set up jobs progress timerfd.");
+
+ return 0;
+
+err:
+ if (m->jobs_in_progress_watch.fd >= 0)
+ close_nointr_nofail(m->jobs_in_progress_watch.fd);
+ watch_init(&m->jobs_in_progress_watch);
+ return r;
+}
+
+static void manager_unwatch_jobs_in_progress(Manager *m) {
+ if (m->jobs_in_progress_watch.type != WATCH_JOBS_IN_PROGRESS)
+ return;
+
+ assert_se(epoll_ctl(m->epoll_fd, EPOLL_CTL_DEL, m->jobs_in_progress_watch.fd, NULL) >= 0);
+ close_nointr_nofail(m->jobs_in_progress_watch.fd);
+ watch_init(&m->jobs_in_progress_watch);
+ m->jobs_in_progress_iteration = 0;
+
+ log_debug("Closed jobs progress timerfd.");
+}
+
+#define CYLON_BUFFER_EXTRA (2*strlen(ANSI_RED_ON) + strlen(ANSI_HIGHLIGHT_RED_ON) + 2*strlen(ANSI_HIGHLIGHT_OFF))
+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);
+ p = stpcpy(p, ANSI_RED_ON);
+ *p++ = '*';
+ }
+
+ if (pos > 0 && pos <= width) {
+ p = stpcpy(p, ANSI_HIGHLIGHT_RED_ON);
+ *p++ = '*';
+ }
+
+ p = stpcpy(p, ANSI_HIGHLIGHT_OFF);
+
+ if (pos < width) {
+ p = stpcpy(p, ANSI_RED_ON);
+ *p++ = '*';
+ if (pos < width-1)
+ p = mempset(p, ' ', width-1-pos);
+ p = stpcpy(p, ANSI_HIGHLIGHT_OFF);
+ }
+}
+
+static void manager_print_jobs_in_progress(Manager *m) {
+ Iterator i;
+ Job *j;
+ char *job_of_n = NULL;
+ unsigned counter = 0, print_nr;
+ char cylon[6 + CYLON_BUFFER_EXTRA + 1];
+ unsigned cylon_pos;
+
+ 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);
+
+ 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);
+
+ if (m->n_running_jobs > 1)
+ if (asprintf(&job_of_n, "(%u of %u) ", counter, m->n_running_jobs) < 0)
+ job_of_n = NULL;
+
+ manager_status_printf(m, true, cylon, "%sA %s job is running for %s",
+ strempty(job_of_n), job_type_to_string(j->type), unit_description(j->unit));
+ free(job_of_n);
+
+ m->jobs_in_progress_iteration++;
+}
+
+static int manager_setup_time_change(Manager *m) {
+ struct epoll_event ev = {
+ .events = EPOLLIN,
+ .data.ptr = &m->time_change_watch,
+ };
+
+ /* We only care for the cancellation event, hence we set the
+ * timeout to the latest possible value. */
+ struct itimerspec its = {
+ .it_value.tv_sec = TIME_T_MAX,
+ };
+ assert_cc(sizeof(time_t) == sizeof(TIME_T_MAX));
+
+ assert(m->time_change_watch.type == WATCH_INVALID);
+
+ /* Uses TFD_TIMER_CANCEL_ON_SET to get notifications whenever
+ * CLOCK_REALTIME makes a jump relative to CLOCK_MONOTONIC */
+
+ m->time_change_watch.type = WATCH_TIME_CHANGE;
+ m->time_change_watch.fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK|TFD_CLOEXEC);
+ if (m->time_change_watch.fd < 0) {
+ log_error("Failed to create timerfd: %m");
+ return -errno;
+ }
+
+ if (timerfd_settime(m->time_change_watch.fd, TFD_TIMER_ABSTIME|TFD_TIMER_CANCEL_ON_SET, &its, NULL) < 0) {
+ log_debug("Failed to set up TFD_TIMER_CANCEL_ON_SET, ignoring: %m");
+ close_nointr_nofail(m->time_change_watch.fd);
+ watch_init(&m->time_change_watch);
+ return 0;
+ }
+
+ if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->time_change_watch.fd, &ev) < 0) {
+ log_error("Failed to add timer change fd to epoll: %m");
+ return -errno;
+ }
+
+ log_debug("Set up TFD_TIMER_CANCEL_ON_SET timerfd.");
+
+ return 0;
+}
+
+static int enable_special_signals(Manager *m) {
+ int fd;
+
+ assert(m);
+
+ /* 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 && errno != EPERM && errno != EINVAL)
+ log_warning("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("Failed to open /dev/tty0: %m");
+ } else {
+ /* Enable that we get SIGWINCH on kbrequest */
+ if (ioctl(fd, KDSIGACCEPT, SIGWINCH) < 0)
+ log_warning("Failed to enable kbrequest handling: %s", strerror(errno));
+
+ close_nointr_nofail(fd);
+ }
+
+ return 0;
+}
+
+static int manager_setup_signals(Manager *m) {
+ sigset_t mask;
+ struct epoll_event ev = {
+ .events = EPOLLIN,
+ .data.ptr = &m->signal_watch,
+ };
+ struct sigaction sa = {
+ .sa_handler = SIG_DFL,
+ .sa_flags = SA_NOCLDSTOP|SA_RESTART,
+ };
+
+ assert(m);
+
+ /* We are not interested in SIGSTOP and friends. */
+ assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
+
+ 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 */
+ SIGRTMIN+13, /* systemd: Immediate halt */
+ SIGRTMIN+14, /* systemd: Immediate poweroff */
+ SIGRTMIN+15, /* systemd: Immediate reboot */
+ SIGRTMIN+16, /* systemd: Immediate kexec */
+ 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) */
+ SIGRTMIN+26, /* systemd: set log target to journal-or-kmsg */
+ SIGRTMIN+27, /* systemd: set log target to console */
+ SIGRTMIN+28, /* systemd: set log target to kmsg */
+ SIGRTMIN+29, /* systemd: set log target to syslog-or-kmsg */
+ -1);
+ assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
+
+ m->signal_watch.type = WATCH_SIGNAL;
+ m->signal_watch.fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
+ if (m->signal_watch.fd < 0)
+ return -errno;
+
+ if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->signal_watch.fd, &ev) < 0)
+ return -errno;
+
+ if (m->running_as == SYSTEMD_SYSTEM)
+ return enable_special_signals(m);
+
+ return 0;
+}
+
+static void manager_strip_environment(Manager *m) {
+ assert(m);
+
+ /* Remove variables from the inherited set that are part of
+ * the container interface:
+ * http://www.freedesktop.org/wiki/Software/systemd/ContainerInterface */
+ strv_remove_prefix(m->environment, "container=");
+ strv_remove_prefix(m->environment, "container_");
+
+ /* Remove variables from the inherited set that are part of
+ * the initrd interface:
+ * http://www.freedesktop.org/wiki/Software/systemd/InitrdInterface */
+ strv_remove_prefix(m->environment, "RD_");
+
+ /* Drop invalid entries */
+ strv_env_clean(m->environment);
+}
+
+int manager_new(SystemdRunningAs running_as, Manager **_m) {
+ Manager *m;
+ int r = -ENOMEM;
+
+ assert(_m);
+ assert(running_as >= 0);
+ assert(running_as < _SYSTEMD_RUNNING_AS_MAX);
+
+ m = new0(Manager, 1);
+ if (!m)
+ return -ENOMEM;
+
+ m->running_as = running_as;
+ m->name_data_slot = m->conn_data_slot = m->subscribed_data_slot = -1;
+ m->exit_code = _MANAGER_EXIT_CODE_INVALID;
+ m->pin_cgroupfs_fd = -1;
+ m->idle_pipe[0] = m->idle_pipe[1] = -1;
+
+ watch_init(&m->signal_watch);
+ watch_init(&m->mount_watch);
+ watch_init(&m->swap_watch);
+ watch_init(&m->udev_watch);
+ watch_init(&m->time_change_watch);
+ watch_init(&m->jobs_in_progress_watch);
+
+ m->epoll_fd = m->dev_autofs_fd = -1;
+ m->current_job_id = 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
+
+ m->environment = strv_copy(environ);
+ if (!m->environment)
+ goto fail;
+
+ manager_strip_environment(m);
+
+ if (running_as == SYSTEMD_SYSTEM) {
+ m->default_controllers = strv_new("cpu", NULL);
+ if (!m->default_controllers)
+ goto fail;
+ }
+
+ if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
+ goto fail;
+
+ if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
+ goto fail;
+
+ if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
+ goto fail;
+
+ if (!(m->cgroup_bondings = hashmap_new(string_hash_func, string_compare_func)))
+ goto fail;
+
+ if (!(m->watch_bus = hashmap_new(string_hash_func, string_compare_func)))
+ goto fail;
+
+ m->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
+ if (m->epoll_fd < 0)
+ goto fail;
+
+ r = manager_setup_signals(m);
+ if (r < 0)
+ goto fail;
+
+ r = manager_setup_cgroup(m);
+ if (r < 0)
+ goto fail;
+
+ r = manager_setup_notify(m);
+ if (r < 0)
+ goto fail;
+
+ r = manager_setup_time_change(m);
+ if (r < 0)
+ goto fail;
+
+ /* Try to connect to the busses, if possible. */
+ r = bus_init(m, running_as != SYSTEMD_SYSTEM);
+ if (r < 0)
+ goto fail;
+
+ m->taint_usr = dir_is_empty("/usr") > 0;
+
+ *_m = m;
+ return 0;
+
+fail:
+ manager_free(m);
+ return r;
+}
+
+static unsigned manager_dispatch_cleanup_queue(Manager *m) {
+ Unit *u;
+ unsigned n = 0;
+
+ assert(m);
+
+ while ((u = m->cleanup_queue)) {
+ assert(u->in_cleanup_queue);
+
+ unit_free(u);
+ n++;
+ }
+
+ return n;
+}
+
+enum {
+ GC_OFFSET_IN_PATH, /* This one is on the path we were traveling */
+ GC_OFFSET_UNSURE, /* No clue */
+ GC_OFFSET_GOOD, /* We still need this unit */
+ GC_OFFSET_BAD, /* We don't need this unit anymore */
+ _GC_OFFSET_MAX
+};
+
+static void unit_gc_sweep(Unit *u, unsigned gc_marker) {
+ Iterator i;
+ Unit *other;
+ bool is_bad;
+
+ assert(u);
+
+ if (u->gc_marker == gc_marker + GC_OFFSET_GOOD ||
+ u->gc_marker == gc_marker + GC_OFFSET_BAD ||
+ u->gc_marker == gc_marker + GC_OFFSET_IN_PATH)
+ return;
+
+ if (u->in_cleanup_queue)
+ goto bad;
+
+ if (unit_check_gc(u))
+ goto good;
+
+ u->gc_marker = gc_marker + GC_OFFSET_IN_PATH;
+
+ is_bad = true;
+
+ SET_FOREACH(other, u->dependencies[UNIT_REFERENCED_BY], i) {
+ unit_gc_sweep(other, gc_marker);
+
+ if (other->gc_marker == gc_marker + GC_OFFSET_GOOD)
+ goto good;
+
+ if (other->gc_marker != gc_marker + GC_OFFSET_BAD)
+ is_bad = false;
+ }
+
+ if (is_bad)
+ goto bad;
+
+ /* We were unable to find anything out about this entry, so
+ * let's investigate it later */
+ u->gc_marker = gc_marker + GC_OFFSET_UNSURE;
+ unit_add_to_gc_queue(u);
+ return;
+
+bad:
+ /* We definitely know that this one is not useful anymore, so
+ * let's mark it for deletion */
+ u->gc_marker = gc_marker + GC_OFFSET_BAD;
+ unit_add_to_cleanup_queue(u);
+ return;
+
+good:
+ u->gc_marker = gc_marker + GC_OFFSET_GOOD;
+}
+
+static unsigned manager_dispatch_gc_queue(Manager *m) {
+ Unit *u;
+ unsigned n = 0;
+ unsigned gc_marker;
+
+ assert(m);
+
+ if ((m->n_in_gc_queue < GC_QUEUE_ENTRIES_MAX) &&
+ (m->gc_queue_timestamp <= 0 ||
+ (m->gc_queue_timestamp + GC_QUEUE_USEC_MAX) > now(CLOCK_MONOTONIC)))
+ return 0;
+
+ log_debug("Running GC...");
+
+ m->gc_marker += _GC_OFFSET_MAX;
+ if (m->gc_marker + _GC_OFFSET_MAX <= _GC_OFFSET_MAX)
+ m->gc_marker = 1;
+
+ gc_marker = m->gc_marker;
+
+ while ((u = m->gc_queue)) {
+ assert(u->in_gc_queue);
+
+ unit_gc_sweep(u, gc_marker);
+
+ LIST_REMOVE(Unit, gc_queue, m->gc_queue, u);
+ u->in_gc_queue = false;
+
+ n++;
+
+ if (u->gc_marker == gc_marker + GC_OFFSET_BAD ||
+ u->gc_marker == gc_marker + GC_OFFSET_UNSURE) {
+ log_debug_unit(u->id, "Collecting %s", u->id);
+ u->gc_marker = gc_marker + GC_OFFSET_BAD;
+ unit_add_to_cleanup_queue(u);
+ }
+ }
+
+ m->n_in_gc_queue = 0;
+ m->gc_queue_timestamp = 0;
+
+ return n;
+}
+
+static void manager_clear_jobs_and_units(Manager *m) {
+ Unit *u;
+
+ assert(m);
+
+ while ((u = hashmap_first(m->units)))
+ unit_free(u);
+
+ manager_dispatch_cleanup_queue(m);
+
+ assert(!m->load_queue);
+ assert(!m->run_queue);
+ assert(!m->dbus_unit_queue);
+ assert(!m->dbus_job_queue);
+ assert(!m->cleanup_queue);
+ assert(!m->gc_queue);
+
+ assert(hashmap_isempty(m->jobs));
+ assert(hashmap_isempty(m->units));
+
+ m->n_on_console = 0;
+ m->n_running_jobs = 0;
+}
+
+void manager_free(Manager *m) {
+ UnitType c;
+ int i;
+
+ assert(m);
+
+ manager_clear_jobs_and_units(m);
+
+ for (c = 0; c < _UNIT_TYPE_MAX; c++)
+ if (unit_vtable[c]->shutdown)
+ unit_vtable[c]->shutdown(m);
+
+ /* If we reexecute ourselves, we keep the root cgroup
+ * around */
+ manager_shutdown_cgroup(m, m->exit_code != MANAGER_REEXECUTE);
+
+ manager_undo_generators(m);
+
+ bus_done(m);
+
+ hashmap_free(m->units);
+ hashmap_free(m->jobs);
+ hashmap_free(m->watch_pids);
+ hashmap_free(m->watch_bus);
+
+ if (m->epoll_fd >= 0)
+ close_nointr_nofail(m->epoll_fd);
+ if (m->signal_watch.fd >= 0)
+ close_nointr_nofail(m->signal_watch.fd);
+ if (m->notify_watch.fd >= 0)
+ close_nointr_nofail(m->notify_watch.fd);
+ if (m->time_change_watch.fd >= 0)
+ close_nointr_nofail(m->time_change_watch.fd);
+ if (m->jobs_in_progress_watch.fd >= 0)
+ close_nointr_nofail(m->jobs_in_progress_watch.fd);
+
+ free(m->notify_socket);
+
+ lookup_paths_free(&m->lookup_paths);
+ strv_free(m->environment);
+
+ strv_free(m->default_controllers);
+
+ hashmap_free(m->cgroup_bondings);
+ set_free_free(m->unit_path_cache);
+
+ close_pipe(m->idle_pipe);
+
+ free(m->switch_root);
+ free(m->switch_root_init);
+
+ for (i = 0; i < RLIMIT_NLIMITS; i++)
+ free(m->rlimit[i]);
+
+ free(m);
+}
+
+int manager_enumerate(Manager *m) {
+ int r = 0, q;
+ UnitType c;
+
+ assert(m);
+
+ /* Let's ask every type to load all units from disk/kernel
+ * that it might know */
+ for (c = 0; c < _UNIT_TYPE_MAX; c++)
+ if (unit_vtable[c]->enumerate)
+ if ((q = unit_vtable[c]->enumerate(m)) < 0)
+ r = q;
+
+ manager_dispatch_load_queue(m);
+ return r;
+}
+
+int manager_coldplug(Manager *m) {
+ int r = 0, q;
+ Iterator i;
+ Unit *u;
+ char *k;
+
+ assert(m);
+
+ /* Then, let's set up their initial state. */
+ HASHMAP_FOREACH_KEY(u, k, m->units, i) {
+
+ /* ignore aliases */
+ if (u->id != k)
+ continue;
+
+ if ((q = unit_coldplug(u)) < 0)
+ r = q;
+ }
+
+ return r;
+}
+
+static void manager_build_unit_path_cache(Manager *m) {
+ char **i;
+ _cleanup_free_ DIR *d = NULL;
+ int r;
+
+ assert(m);
+
+ set_free_free(m->unit_path_cache);
+
+ m->unit_path_cache = set_new(string_hash_func, string_compare_func);
+ if (!m->unit_path_cache) {
+ log_error("Failed to allocate unit path cache.");
+ return;
+ }
+
+ /* This simply builds a list of files we know exist, so that
+ * we don't always have to go to disk */
+
+ STRV_FOREACH(i, m->lookup_paths.unit_path) {
+ struct dirent *de;
+
+ d = opendir(*i);
+ if (!d) {
+ if (errno != ENOENT)
+ log_error("Failed to open directory %s: %m", *i);
+ continue;
+ }
+
+ while ((de = readdir(d))) {
+ char *p;
+
+ if (ignore_file(de->d_name))
+ continue;
+
+ p = strjoin(streq(*i, "/") ? "" : *i, "/", de->d_name, NULL);
+ if (!p) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ r = set_consume(m->unit_path_cache, p);
+ if (r < 0)
+ goto fail;
+ }
+
+ closedir(d);
+ d = NULL;
+ }
+
+ return;
+
+fail:
+ log_error("Failed to build unit path cache: %s", strerror(-r));
+
+ set_free_free(m->unit_path_cache);
+ m->unit_path_cache = NULL;
+}
+
+int manager_startup(Manager *m, FILE *serialization, FDSet *fds) {
+ int r, q;
+
+ assert(m);
+
+ manager_run_generators(m);
+
+ r = lookup_paths_init(
+ &m->lookup_paths, m->running_as, true,
+ m->generator_unit_path,
+ m->generator_unit_path_early,
+ m->generator_unit_path_late);
+ if (r < 0)
+ return r;
+
+ manager_build_unit_path_cache(m);
+
+ /* If we will deserialize make sure that during enumeration
+ * this is already known, so we increase the counter here
+ * already */
+ if (serialization)
+ m->n_reloading ++;
+
+ /* First, enumerate what we can from all config files */
+ r = manager_enumerate(m);
+
+ /* Second, deserialize if there is something to deserialize */
+ if (serialization) {
+ q = manager_deserialize(m, serialization, fds);
+ if (q < 0)
+ r = q;
+ }
+
+ /* Any fds left? Find some unit which wants them. This is
+ * useful to allow container managers to pass some file
+ * descriptors to us pre-initialized. This enables
+ * socket-based activation of entire containers. */
+ if (fdset_size(fds) > 0) {
+ q = manager_distribute_fds(m, fds);
+ if (q < 0)
+ r = q;
+ }
+
+ /* Third, fire things up! */
+ q = manager_coldplug(m);
+ if (q < 0)
+ r = q;
+
+ if (serialization) {
+ assert(m->n_reloading > 0);
+ m->n_reloading --;
+ }
+
+ return r;
+}
+
+int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool override, DBusError *e, Job **_ret) {
+ int r;
+ Transaction *tr;
+
+ assert(m);
+ assert(type < _JOB_TYPE_MAX);
+ assert(unit);
+ assert(mode < _JOB_MODE_MAX);
+
+ if (mode == JOB_ISOLATE && type != JOB_START) {
+ dbus_set_error(e, BUS_ERROR_INVALID_JOB_MODE, "Isolate is only valid for start.");
+ return -EINVAL;
+ }
+
+ if (mode == JOB_ISOLATE && !unit->allow_isolate) {
+ dbus_set_error(e, BUS_ERROR_NO_ISOLATION, "Operation refused, unit may not be isolated.");
+ return -EPERM;
+ }
+
+ log_debug_unit(unit->id,
+ "Trying to enqueue job %s/%s/%s", unit->id,
+ job_type_to_string(type), job_mode_to_string(mode));
+
+ job_type_collapse(&type, unit);
+
+ tr = transaction_new(mode == JOB_REPLACE_IRREVERSIBLY);
+ if (!tr)
+ return -ENOMEM;
+
+ r = transaction_add_job_and_dependencies(tr, type, unit, NULL, true, override, false,
+ mode == JOB_IGNORE_DEPENDENCIES || mode == JOB_IGNORE_REQUIREMENTS,
+ mode == JOB_IGNORE_DEPENDENCIES, e);
+ if (r < 0)
+ goto tr_abort;
+
+ if (mode == JOB_ISOLATE) {
+ r = transaction_add_isolate_jobs(tr, m);
+ if (r < 0)
+ goto tr_abort;
+ }
+
+ r = transaction_activate(tr, m, mode, e);
+ if (r < 0)
+ goto tr_abort;
+
+ log_debug_unit(unit->id,
+ "Enqueued job %s/%s as %u", unit->id,
+ job_type_to_string(type), (unsigned) tr->anchor_job->id);
+
+ if (_ret)
+ *_ret = tr->anchor_job;
+
+ transaction_free(tr);
+ return 0;
+
+tr_abort:
+ transaction_abort(tr);
+ transaction_free(tr);
+ return r;
+}
+
+int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, bool override, DBusError *e, Job **_ret) {
+ Unit *unit;
+ int r;
+
+ assert(m);
+ assert(type < _JOB_TYPE_MAX);
+ assert(name);
+ assert(mode < _JOB_MODE_MAX);
+
+ r = manager_load_unit(m, name, NULL, NULL, &unit);
+ if (r < 0)
+ return r;
+
+ return manager_add_job(m, type, unit, mode, override, e, _ret);
+}
+
+Job *manager_get_job(Manager *m, uint32_t id) {
+ assert(m);
+
+ return hashmap_get(m->jobs, UINT32_TO_PTR(id));
+}
+
+Unit *manager_get_unit(Manager *m, const char *name) {
+ assert(m);
+ assert(name);
+
+ return hashmap_get(m->units, name);
+}
+
+unsigned manager_dispatch_load_queue(Manager *m) {
+ Unit *u;
+ unsigned n = 0;
+
+ assert(m);
+
+ /* Make sure we are not run recursively */
+ if (m->dispatching_load_queue)
+ return 0;
+
+ m->dispatching_load_queue = true;
+
+ /* Dispatches the load queue. Takes a unit from the queue and
+ * tries to load its data until the queue is empty */
+
+ while ((u = m->load_queue)) {
+ assert(u->in_load_queue);
+
+ unit_load(u);
+ n++;
+ }
+
+ m->dispatching_load_queue = false;
+ return n;
+}
+
+int manager_load_unit_prepare(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
+ Unit *ret;
+ UnitType t;
+ int r;
+
+ assert(m);
+ assert(name || path);
+
+ /* This will prepare the unit for loading, but not actually
+ * load anything from disk. */
+
+ if (path && !is_path(path)) {
+ dbus_set_error(e, BUS_ERROR_INVALID_PATH, "Path %s is not absolute.", path);
+ return -EINVAL;
+ }
+
+ if (!name)
+ name = path_get_file_name(path);
+
+ t = unit_name_to_type(name);
+
+ if (t == _UNIT_TYPE_INVALID || !unit_name_is_valid(name, false)) {
+ dbus_set_error(e, BUS_ERROR_INVALID_NAME, "Unit name %s is not valid.", name);
+ return -EINVAL;
+ }
+
+ ret = manager_get_unit(m, name);
+ if (ret) {
+ *_ret = ret;
+ return 1;
+ }
+
+ ret = unit_new(m, unit_vtable[t]->object_size);
+ if (!ret)
+ return -ENOMEM;
+
+ if (path) {
+ ret->fragment_path = strdup(path);
+ if (!ret->fragment_path) {
+ unit_free(ret);
+ return -ENOMEM;
+ }
+ }
+
+ if ((r = unit_add_name(ret, name)) < 0) {
+ unit_free(ret);
+ return r;
+ }
+
+ unit_add_to_load_queue(ret);
+ unit_add_to_dbus_queue(ret);
+ unit_add_to_gc_queue(ret);
+
+ if (_ret)
+ *_ret = ret;
+
+ return 0;
+}
+
+int manager_load_unit(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
+ int r;
+
+ assert(m);
+
+ /* This will load the service information files, but not actually
+ * start any services or anything. */
+
+ r = manager_load_unit_prepare(m, name, path, e, _ret);
+ if (r != 0)
+ return r;
+
+ manager_dispatch_load_queue(m);
+
+ if (_ret)
+ *_ret = unit_follow_merge(*_ret);
+
+ return 0;
+}
+
+void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
+ Iterator i;
+ Job *j;
+
+ assert(s);
+ assert(f);
+
+ HASHMAP_FOREACH(j, s->jobs, i)
+ job_dump(j, f, prefix);
+}
+
+void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
+ Iterator i;
+ Unit *u;
+ const char *t;
+
+ assert(s);
+ assert(f);
+
+ HASHMAP_FOREACH_KEY(u, t, s->units, i)
+ if (u->id == t)
+ unit_dump(u, f, prefix);
+}
+
+void manager_clear_jobs(Manager *m) {
+ Job *j;
+
+ assert(m);
+
+ while ((j = hashmap_first(m->jobs)))
+ /* No need to recurse. We're cancelling all jobs. */
+ job_finish_and_invalidate(j, JOB_CANCELED, false);
+}
+
+unsigned manager_dispatch_run_queue(Manager *m) {
+ Job *j;
+ unsigned n = 0;
+
+ if (m->dispatching_run_queue)
+ return 0;
+
+ m->dispatching_run_queue = true;
+
+ while ((j = m->run_queue)) {
+ assert(j->installed);
+ assert(j->in_run_queue);
+
+ job_run_and_invalidate(j);
+ n++;
+ }
+
+ m->dispatching_run_queue = false;
+
+ if (m->n_running_jobs > 0)
+ manager_watch_jobs_in_progress(m);
+
+ return n;
+}
+
+unsigned manager_dispatch_dbus_queue(Manager *m) {
+ Job *j;
+ Unit *u;
+ unsigned n = 0;
+
+ assert(m);
+
+ if (m->dispatching_dbus_queue)
+ return 0;
+
+ m->dispatching_dbus_queue = true;
+
+ while ((u = m->dbus_unit_queue)) {
+ assert(u->in_dbus_queue);
+
+ bus_unit_send_change_signal(u);
+ n++;
+ }
+
+ while ((j = m->dbus_job_queue)) {
+ assert(j->in_dbus_queue);
+
+ bus_job_send_change_signal(j);
+ n++;
+ }
+
+ m->dispatching_dbus_queue = false;
+ return n;
+}
+
+static int manager_process_notify_fd(Manager *m) {
+ ssize_t n;
+
+ assert(m);
+
+ for (;;) {
+ char buf[4096];
+ struct iovec iovec = {
+ .iov_base = buf,
+ .iov_len = sizeof(buf)-1,
+ };
+
+ union {
+ struct cmsghdr cmsghdr;
+ uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
+ } control = {};
+
+ struct msghdr msghdr = {
+ .msg_iov = &iovec,
+ .msg_iovlen = 1,
+ .msg_control = &control,
+ .msg_controllen = sizeof(control),
+ };
+ struct ucred *ucred;
+ Unit *u;
+ _cleanup_strv_free_ char **tags = NULL;
+
+ n = recvmsg(m->notify_watch.fd, &msghdr, MSG_DONTWAIT);
+ if (n <= 0) {
+ if (n == 0)
+ return -EIO;
+
+ if (errno == EAGAIN || errno == EINTR)
+ break;
+
+ return -errno;
+ }
+
+ if (msghdr.msg_controllen < CMSG_LEN(sizeof(struct ucred)) ||
+ control.cmsghdr.cmsg_level != SOL_SOCKET ||
+ control.cmsghdr.cmsg_type != SCM_CREDENTIALS ||
+ control.cmsghdr.cmsg_len != CMSG_LEN(sizeof(struct ucred))) {
+ log_warning("Received notify message without credentials. Ignoring.");
+ continue;
+ }
+
+ ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
+
+ u = hashmap_get(m->watch_pids, LONG_TO_PTR(ucred->pid));
+ if (!u) {
+ u = cgroup_unit_by_pid(m, ucred->pid);
+ if (!u) {
+ log_warning("Cannot find unit for notify message of PID %lu.", (unsigned long) ucred->pid);
+ continue;
+ }
+ }
+
+ assert((size_t) n < sizeof(buf));
+ buf[n] = 0;
+ tags = strv_split(buf, "\n\r");
+ if (!tags)
+ return log_oom();
+
+ log_debug_unit(u->id, "Got notification message for unit %s", u->id);
+
+ if (UNIT_VTABLE(u)->notify_message)
+ UNIT_VTABLE(u)->notify_message(u, ucred->pid, tags);
+ }
+
+ return 0;
+}
+
+static int manager_dispatch_sigchld(Manager *m) {
+ assert(m);
+
+ for (;;) {
+ siginfo_t si = {};
+ Unit *u;
+ int r;
+
+ /* First we call waitd() for a PID and do not reap the
+ * zombie. That way we can still access /proc/$PID for
+ * it while it is a zombie. */
+ if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
+
+ if (errno == ECHILD)
+ break;
+
+ if (errno == EINTR)
+ continue;
+
+ return -errno;
+ }
+
+ if (si.si_pid <= 0)
+ break;
+
+ if (si.si_code == CLD_EXITED || si.si_code == CLD_KILLED || si.si_code == CLD_DUMPED) {
+ _cleanup_free_ char *name = NULL;
+
+ get_process_comm(si.si_pid, &name);
+ log_debug("Got SIGCHLD for process %lu (%s)", (unsigned long) si.si_pid, strna(name));
+ }
+
+ /* Let's flush any message the dying child might still
+ * have queued for us. This ensures that the process
+ * still exists in /proc so that we can figure out
+ * which cgroup and hence unit it belongs to. */
+ r = manager_process_notify_fd(m);
+ if (r < 0)
+ return r;
+
+ /* And now figure out the unit this belongs to */
+ u = hashmap_get(m->watch_pids, LONG_TO_PTR(si.si_pid));
+ if (!u)
+ u = cgroup_unit_by_pid(m, si.si_pid);
+
+ /* And now, we actually reap the zombie. */
+ if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
+ if (errno == EINTR)
+ continue;
+
+ return -errno;
+ }
+
+ if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
+ continue;
+
+ log_debug("Child %lu died (code=%s, status=%i/%s)",
+ (long unsigned) si.si_pid,
+ sigchld_code_to_string(si.si_code),
+ si.si_status,
+ strna(si.si_code == CLD_EXITED
+ ? exit_status_to_string(si.si_status, EXIT_STATUS_FULL)
+ : signal_to_string(si.si_status)));
+
+ if (!u)
+ continue;
+
+ log_debug_unit(u->id,
+ "Child %lu belongs to %s", (long unsigned) si.si_pid, u->id);
+
+ hashmap_remove(m->watch_pids, LONG_TO_PTR(si.si_pid));
+ UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
+ }
+
+ return 0;
+}
+
+static int manager_start_target(Manager *m, const char *name, JobMode mode) {
+ int r;
+ DBusError error;
+
+ dbus_error_init(&error);
+
+ log_debug_unit(name, "Activating special unit %s", name);
+
+ r = manager_add_job_by_name(m, JOB_START, name, mode, true, &error, NULL);
+ if (r < 0)
+ log_error_unit(name,
+ "Failed to enqueue %s job: %s", name, bus_error(&error, r));
+
+ dbus_error_free(&error);
+
+ return r;
+}
+
+static int manager_process_signal_fd(Manager *m) {
+ ssize_t n;
+ struct signalfd_siginfo sfsi;
+ bool sigchld = false;
+
+ assert(m);
+
+ for (;;) {
+ n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi));
+ if (n != sizeof(sfsi)) {
+
+ if (n >= 0)
+ return -EIO;
+
+ if (errno == EINTR || errno == EAGAIN)
+ break;
+
+ return -errno;
+ }
+
+ if (sfsi.ssi_pid > 0) {
+ char *p = NULL;
+
+ get_process_comm(sfsi.ssi_pid, &p);
+
+ log_debug("Received SIG%s from PID %lu (%s).",
+ signal_to_string(sfsi.ssi_signo),
+ (unsigned long) sfsi.ssi_pid, strna(p));
+ free(p);
+ } else
+ log_debug("Received SIG%s.", signal_to_string(sfsi.ssi_signo));
+
+ switch (sfsi.ssi_signo) {
+
+ case SIGCHLD:
+ sigchld = true;
+ break;
+
+ case SIGTERM:
+ if (m->running_as == SYSTEMD_SYSTEM) {
+ /* This is for compatibility with the
+ * original sysvinit */
+ m->exit_code = MANAGER_REEXECUTE;
+ break;
+ }
+
+ /* Fall through */
+
+ case SIGINT:
+ if (m->running_as == SYSTEMD_SYSTEM) {
+ manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE);
+ break;
+ }
+
+ /* Run the exit target if there is one, if not, just exit. */
+ if (manager_start_target(m, SPECIAL_EXIT_TARGET, JOB_REPLACE) < 0) {
+ m->exit_code = MANAGER_EXIT;
+ return 0;
+ }
+
+ break;
+
+ case SIGWINCH:
+ if (m->running_as == SYSTEMD_SYSTEM)
+ manager_start_target(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
+
+ /* This is a nop on non-init */
+ break;
+
+ case SIGPWR:
+ if (m->running_as == SYSTEMD_SYSTEM)
+ manager_start_target(m, SPECIAL_SIGPWR_TARGET, JOB_REPLACE);
+
+ /* This is a nop on non-init */
+ break;
+
+ case SIGUSR1: {
+ Unit *u;
+
+ u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
+
+ if (!u || UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u))) {
+ log_info("Trying to reconnect to bus...");
+ bus_init(m, true);
+ }
+
+ if (!u || !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) {
+ log_info("Loading D-Bus service...");
+ manager_start_target(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
+ }
+
+ break;
+ }
+
+ case SIGUSR2: {
+ FILE *f;
+ char *dump = NULL;
+ size_t size;
+
+ if (!(f = open_memstream(&dump, &size))) {
+ log_warning("Failed to allocate memory stream.");
+ break;
+ }
+
+ manager_dump_units(m, f, "\t");
+ manager_dump_jobs(m, f, "\t");
+
+ if (ferror(f)) {
+ fclose(f);
+ free(dump);
+ log_warning("Failed to write status stream");
+ break;
+ }
+
+ fclose(f);
+ log_dump(LOG_INFO, dump);
+ free(dump);
+
+ break;
+ }
+
+ case SIGHUP:
+ m->exit_code = MANAGER_RELOAD;
+ break;
+
+ default: {
+
+ /* Starting SIGRTMIN+0 */
+ static const char * const target_table[] = {
+ [0] = SPECIAL_DEFAULT_TARGET,
+ [1] = SPECIAL_RESCUE_TARGET,
+ [2] = SPECIAL_EMERGENCY_TARGET,
+ [3] = SPECIAL_HALT_TARGET,
+ [4] = SPECIAL_POWEROFF_TARGET,
+ [5] = SPECIAL_REBOOT_TARGET,
+ [6] = SPECIAL_KEXEC_TARGET
+ };
+
+ /* Starting SIGRTMIN+13, so that target halt and system halt are 10 apart */
+ static const ManagerExitCode code_table[] = {
+ [0] = MANAGER_HALT,
+ [1] = MANAGER_POWEROFF,
+ [2] = MANAGER_REBOOT,
+ [3] = MANAGER_KEXEC
+ };
+
+ if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
+ (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(target_table)) {
+ int idx = (int) sfsi.ssi_signo - SIGRTMIN;
+ manager_start_target(m, target_table[idx],
+ (idx == 1 || idx == 2) ? JOB_ISOLATE : JOB_REPLACE);
+ break;
+ }
+
+ if ((int) sfsi.ssi_signo >= SIGRTMIN+13 &&
+ (int) sfsi.ssi_signo < SIGRTMIN+13+(int) ELEMENTSOF(code_table)) {
+ m->exit_code = code_table[sfsi.ssi_signo - SIGRTMIN - 13];
+ break;
+ }
+
+ switch (sfsi.ssi_signo - SIGRTMIN) {
+
+ case 20:
+ log_debug("Enabling showing of status.");
+ manager_set_show_status(m, true);
+ break;
+
+ case 21:
+ log_debug("Disabling showing of status.");
+ manager_set_show_status(m, false);
+ break;
+
+ case 22:
+ log_set_max_level(LOG_DEBUG);
+ log_notice("Setting log level to debug.");
+ break;
+
+ case 23:
+ log_set_max_level(LOG_INFO);
+ log_notice("Setting log level to info.");
+ break;
+
+ case 24:
+ if (m->running_as == SYSTEMD_USER) {
+ m->exit_code = MANAGER_EXIT;
+ return 0;
+ }
+
+ /* This is a nop on init */
+ break;
+
+ case 26:
+ log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
+ log_notice("Setting log target to journal-or-kmsg.");
+ break;
+
+ case 27:
+ log_set_target(LOG_TARGET_CONSOLE);
+ log_notice("Setting log target to console.");
+ break;
+
+ case 28:
+ log_set_target(LOG_TARGET_KMSG);
+ log_notice("Setting log target to kmsg.");
+ break;
+
+ case 29:
+ log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
+ log_notice("Setting log target to syslog-or-kmsg.");
+ break;
+
+ default:
+ log_warning("Got unhandled signal <%s>.", signal_to_string(sfsi.ssi_signo));
+ }
+ }
+ }
+ }
+
+ if (sigchld)
+ return manager_dispatch_sigchld(m);
+
+ return 0;
+}
+
+static int process_event(Manager *m, struct epoll_event *ev) {
+ int r;
+ Watch *w;
+
+ assert(m);
+ assert(ev);
+
+ assert_se(w = ev->data.ptr);
+
+ if (w->type == WATCH_INVALID)
+ return 0;
+
+ switch (w->type) {
+
+ case WATCH_SIGNAL:
+
+ /* An incoming signal? */
+ if (ev->events != EPOLLIN)
+ return -EINVAL;
+
+ if ((r = manager_process_signal_fd(m)) < 0)
+ return r;
+
+ break;
+
+ case WATCH_NOTIFY:
+
+ /* An incoming daemon notification event? */
+ if (ev->events != EPOLLIN)
+ return -EINVAL;
+
+ if ((r = manager_process_notify_fd(m)) < 0)
+ return r;
+
+ break;
+
+ case WATCH_FD:
+
+ /* Some fd event, to be dispatched to the units */
+ UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
+ break;
+
+ case WATCH_UNIT_TIMER:
+ case WATCH_JOB_TIMER: {
+ uint64_t v;
+ ssize_t k;
+
+ /* Some timer event, to be dispatched to the units */
+ k = read(w->fd, &v, sizeof(v));
+ if (k != sizeof(v)) {
+
+ if (k < 0 && (errno == EINTR || errno == EAGAIN))
+ break;
+
+ log_error("Failed to read timer event counter: %s", k < 0 ? strerror(-k) : "Short read");
+ return k < 0 ? -errno : -EIO;
+ }
+
+ if (w->type == WATCH_UNIT_TIMER)
+ UNIT_VTABLE(w->data.unit)->timer_event(w->data.unit, v, w);
+ else
+ job_timer_event(w->data.job, v, w);
+ break;
+ }
+
+ case WATCH_MOUNT:
+ /* Some mount table change, intended for the mount subsystem */
+ mount_fd_event(m, ev->events);
+ break;
+
+ case WATCH_SWAP:
+ /* Some swap table change, intended for the swap subsystem */
+ swap_fd_event(m, ev->events);
+ break;
+
+ case WATCH_UDEV:
+ /* Some notification from udev, intended for the device subsystem */
+ device_fd_event(m, ev->events);
+ break;
+
+ case WATCH_DBUS_WATCH:
+ bus_watch_event(m, w, ev->events);
+ break;
+
+ case WATCH_DBUS_TIMEOUT:
+ bus_timeout_event(m, w, ev->events);
+ break;
+
+ case WATCH_TIME_CHANGE: {
+ Unit *u;
+ Iterator i;
+
+ log_struct(LOG_INFO,
+ MESSAGE_ID(SD_MESSAGE_TIME_CHANGE),
+ "MESSAGE=Time has been changed",
+ NULL);
+
+ /* Restart the watch */
+ epoll_ctl(m->epoll_fd, EPOLL_CTL_DEL, m->time_change_watch.fd,
+ NULL);
+ close_nointr_nofail(m->time_change_watch.fd);
+ watch_init(&m->time_change_watch);
+ manager_setup_time_change(m);
+
+ HASHMAP_FOREACH(u, m->units, i) {
+ if (UNIT_VTABLE(u)->time_change)
+ UNIT_VTABLE(u)->time_change(u);
+ }
+
+ break;
+ }
+
+ case WATCH_JOBS_IN_PROGRESS: {
+ uint64_t v;
+
+ /* not interested in the data */
+ read(w->fd, &v, sizeof(v));
+
+ manager_print_jobs_in_progress(m);
+ break;
+ }
+
+ default:
+ log_error("event type=%i", w->type);
+ assert_not_reached("Unknown epoll event type.");
+ }
+
+ return 0;
+}
+
+int manager_loop(Manager *m) {
+ int r;
+
+ RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 50000);
+
+ assert(m);
+ m->exit_code = MANAGER_RUNNING;
+
+ /* Release the path cache */
+ set_free_free(m->unit_path_cache);
+ m->unit_path_cache = NULL;
+
+ manager_check_finished(m);
+
+ /* There might still be some zombies hanging around from
+ * before we were exec()'ed. Leat's reap them */
+ r = manager_dispatch_sigchld(m);
+ if (r < 0)
+ return r;
+
+ while (m->exit_code == MANAGER_RUNNING) {
+ struct epoll_event event;
+ int n;
+ int wait_msec = -1;
+
+ if (m->runtime_watchdog > 0 && m->running_as == SYSTEMD_SYSTEM)
+ watchdog_ping();
+
+ if (!ratelimit_test(&rl)) {
+ /* Yay, something is going seriously wrong, pause a little */
+ log_warning("Looping too fast. Throttling execution a little.");
+ sleep(1);
+ continue;
+ }
+
+ if (manager_dispatch_load_queue(m) > 0)
+ continue;
+
+ if (manager_dispatch_run_queue(m) > 0)
+ continue;
+
+ if (bus_dispatch(m) > 0)
+ continue;
+
+ if (manager_dispatch_cleanup_queue(m) > 0)
+ continue;
+
+ if (manager_dispatch_gc_queue(m) > 0)
+ continue;
+
+ if (manager_dispatch_dbus_queue(m) > 0)
+ continue;
+
+ if (swap_dispatch_reload(m) > 0)
+ continue;
+
+ /* Sleep for half the watchdog time */
+ if (m->runtime_watchdog > 0 && m->running_as == SYSTEMD_SYSTEM) {
+ wait_msec = (int) (m->runtime_watchdog / 2 / USEC_PER_MSEC);
+ if (wait_msec <= 0)
+ wait_msec = 1;
+ } else
+ wait_msec = -1;
+
+ n = epoll_wait(m->epoll_fd, &event, 1, wait_msec);
+ if (n < 0) {
+
+ if (errno == EINTR)
+ continue;
+
+ return -errno;
+ } else if (n == 0)
+ continue;
+
+ assert(n == 1);
+
+ r = process_event(m, &event);
+ if (r < 0)
+ return r;
+ }
+
+ return m->exit_code;
+}
+
+int manager_load_unit_from_dbus_path(Manager *m, const char *s, DBusError *e, Unit **_u) {
+ char *n;
+ Unit *u;
+ int r;
+
+ assert(m);
+ assert(s);
+ assert(_u);
+
+ if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
+ return -EINVAL;
+
+ n = bus_path_unescape(s+31);
+ if (!n)
+ return -ENOMEM;
+
+ r = manager_load_unit(m, n, NULL, e, &u);
+ free(n);
+
+ if (r < 0)
+ return r;
+
+ *_u = u;
+
+ return 0;
+}
+
+int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
+ Job *j;
+ unsigned id;
+ int r;
+
+ assert(m);
+ assert(s);
+ assert(_j);
+
+ if (!startswith(s, "/org/freedesktop/systemd1/job/"))
+ return -EINVAL;
+
+ r = safe_atou(s + 30, &id);
+ if (r < 0)
+ return r;
+
+ j = manager_get_job(m, id);
+ if (!j)
+ return -ENOENT;
+
+ *_j = j;
+
+ return 0;
+}
+
+void manager_send_unit_audit(Manager *m, Unit *u, int type, bool success) {
+
+#ifdef HAVE_AUDIT
+ char *p;
+ int audit_fd;
+
+ audit_fd = get_audit_fd();
+ if (audit_fd < 0)
+ return;
+
+ /* Don't generate audit events if the service was already
+ * started and we're just deserializing */
+ if (m->n_reloading > 0)
+ return;
+
+ if (m->running_as != SYSTEMD_SYSTEM)
+ return;
+
+ if (u->type != UNIT_SERVICE)
+ return;
+
+ p = unit_name_to_prefix_and_instance(u->id);
+ if (!p) {
+ log_error_unit(u->id,
+ "Failed to allocate unit name for audit message: %s", strerror(ENOMEM));
+ return;
+ }
+
+ if (audit_log_user_comm_message(audit_fd, type, "", p, NULL, NULL, NULL, success) < 0) {
+ if (errno == EPERM) {
+ /* We aren't allowed to send audit messages?
+ * Then let's not retry again. */
+ close_audit_fd();
+ } else
+ log_warning("Failed to send audit message: %m");
+ }
+
+ free(p);
+#endif
+
+}
+
+void manager_send_unit_plymouth(Manager *m, Unit *u) {
+ int fd = -1;
+ union sockaddr_union sa;
+ int n = 0;
+ char *message = NULL;
+
+ /* Don't generate plymouth events if the service was already
+ * started and we're just deserializing */
+ if (m->n_reloading > 0)
+ return;
+
+ if (m->running_as != SYSTEMD_SYSTEM)
+ return;
+
+ if (u->type != UNIT_SERVICE &&
+ u->type != UNIT_MOUNT &&
+ u->type != UNIT_SWAP)
+ return;
+
+ /* We set SOCK_NONBLOCK here so that we rather drop the
+ * message then wait for plymouth */
+ fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
+ if (fd < 0) {
+ log_error("socket() failed: %m");
+ return;
+ }
+
+ zero(sa);
+ sa.sa.sa_family = AF_UNIX;
+ strncpy(sa.un.sun_path+1, "/org/freedesktop/plymouthd", sizeof(sa.un.sun_path)-1);
+ if (connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + 1 + strlen(sa.un.sun_path+1)) < 0) {
+
+ if (errno != EPIPE &&
+ errno != EAGAIN &&
+ errno != ENOENT &&
+ errno != ECONNREFUSED &&
+ errno != ECONNRESET &&
+ errno != ECONNABORTED)
+ log_error("connect() failed: %m");
+
+ goto finish;
+ }
+
+ if (asprintf(&message, "U\002%c%s%n", (int) (strlen(u->id) + 1), u->id, &n) < 0) {
+ log_oom();
+ goto finish;
+ }
+
+ errno = 0;
+ if (write(fd, message, n + 1) != n + 1) {
+
+ if (errno != EPIPE &&
+ errno != EAGAIN &&
+ errno != ENOENT &&
+ errno != ECONNREFUSED &&
+ errno != ECONNRESET &&
+ errno != ECONNABORTED)
+ log_error("Failed to write Plymouth message: %m");
+
+ goto finish;
+ }
+
+finish:
+ if (fd >= 0)
+ close_nointr_nofail(fd);
+
+ free(message);
+}
+
+void manager_dispatch_bus_name_owner_changed(
+ Manager *m,
+ const char *name,
+ const char* old_owner,
+ const char *new_owner) {
+
+ Unit *u;
+
+ assert(m);
+ assert(name);
+
+ if (!(u = hashmap_get(m->watch_bus, name)))
+ return;
+
+ UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
+}
+
+void manager_dispatch_bus_query_pid_done(
+ Manager *m,
+ const char *name,
+ pid_t pid) {
+
+ Unit *u;
+
+ assert(m);
+ assert(name);
+ assert(pid >= 1);
+
+ if (!(u = hashmap_get(m->watch_bus, name)))
+ return;
+
+ UNIT_VTABLE(u)->bus_query_pid_done(u, name, pid);
+}
+
+int manager_open_serialization(Manager *m, FILE **_f) {
+ char *path = NULL;
+ int fd;
+ FILE *f;
+
+ assert(_f);
+
+ if (m->running_as == SYSTEMD_SYSTEM)
+ asprintf(&path, "/run/systemd/dump-%lu-XXXXXX", (unsigned long) getpid());
+ else
+ asprintf(&path, "/tmp/systemd-dump-%lu-XXXXXX", (unsigned long) getpid());
+
+ if (!path)
+ return -ENOMEM;
+
+ RUN_WITH_UMASK(0077) {
+ fd = mkostemp(path, O_RDWR|O_CLOEXEC);
+ }
+
+ if (fd < 0) {
+ free(path);
+ return -errno;
+ }
+
+ unlink(path);
+
+ log_debug("Serializing state to %s", path);
+ free(path);
+
+ f = fdopen(fd, "w+");
+ if (!f)
+ return -errno;
+
+ *_f = f;
+
+ return 0;
+}
+
+int manager_serialize(Manager *m, FILE *f, FDSet *fds, bool switching_root) {
+ Iterator i;
+ Unit *u;
+ const char *t;
+ char **e;
+ int r;
+
+ assert(m);
+ assert(f);
+ assert(fds);
+
+ m->n_reloading ++;
+
+ fprintf(f, "current-job-id=%i\n", m->current_job_id);
+ fprintf(f, "taint-usr=%s\n", yes_no(m->taint_usr));
+ fprintf(f, "n-installed-jobs=%u\n", m->n_installed_jobs);
+ fprintf(f, "n-failed-jobs=%u\n", m->n_failed_jobs);
+
+ dual_timestamp_serialize(f, "firmware-timestamp", &m->firmware_timestamp);
+ dual_timestamp_serialize(f, "kernel-timestamp", &m->kernel_timestamp);
+ dual_timestamp_serialize(f, "loader-timestamp", &m->loader_timestamp);
+ dual_timestamp_serialize(f, "initrd-timestamp", &m->initrd_timestamp);
+
+ if (!in_initrd()) {
+ dual_timestamp_serialize(f, "userspace-timestamp", &m->userspace_timestamp);
+ dual_timestamp_serialize(f, "finish-timestamp", &m->finish_timestamp);
+ }
+
+ if (!switching_root) {
+ STRV_FOREACH(e, m->environment) {
+ _cleanup_free_ char *ce;
+
+ ce = cescape(*e);
+ if (ce)
+ fprintf(f, "env=%s\n", *e);
+ }
+ }
+
+ fputc('\n', f);
+
+ HASHMAP_FOREACH_KEY(u, t, m->units, i) {
+ if (u->id != t)
+ continue;
+
+ if (!unit_can_serialize(u))
+ continue;
+
+ /* Start marker */
+ fputs(u->id, f);
+ fputc('\n', f);
+
+ if ((r = unit_serialize(u, f, fds, !switching_root)) < 0) {
+ m->n_reloading --;
+ return r;
+ }
+ }
+
+ assert(m->n_reloading > 0);
+ m->n_reloading --;
+
+ if (ferror(f))
+ return -EIO;
+
+ r = bus_fdset_add_all(m, fds);
+ if (r < 0)
+ return r;
+
+ return 0;
+}
+
+int manager_deserialize(Manager *m, FILE *f, FDSet *fds) {
+ int r = 0;
+
+ assert(m);
+ assert(f);
+
+ log_debug("Deserializing state...");
+
+ m->n_reloading ++;
+
+ for (;;) {
+ char line[LINE_MAX], *l;
+
+ if (!fgets(line, sizeof(line), f)) {
+ if (feof(f))
+ r = 0;
+ else
+ r = -errno;
+
+ goto finish;
+ }
+
+ char_array_0(line);
+ l = strstrip(line);
+
+ if (l[0] == 0)
+ break;
+
+ if (startswith(l, "current-job-id=")) {
+ uint32_t id;
+
+ if (safe_atou32(l+15, &id) < 0)
+ log_debug("Failed to parse current job id value %s", l+15);
+ else
+ m->current_job_id = MAX(m->current_job_id, id);
+ } else if (startswith(l, "n-installed-jobs=")) {
+ uint32_t n;
+
+ if (safe_atou32(l+17, &n) < 0)
+ log_debug("Failed to parse installed jobs counter %s", l+17);
+ else
+ m->n_installed_jobs += n;
+ } else if (startswith(l, "n-failed-jobs=")) {
+ uint32_t n;
+
+ if (safe_atou32(l+14, &n) < 0)
+ log_debug("Failed to parse failed jobs counter %s", l+14);
+ else
+ m->n_failed_jobs += n;
+ } else if (startswith(l, "taint-usr=")) {
+ int b;
+
+ if ((b = parse_boolean(l+10)) < 0)
+ log_debug("Failed to parse taint /usr flag %s", l+10);
+ else
+ m->taint_usr = m->taint_usr || b;
+ } else if (startswith(l, "firmware-timestamp="))
+ dual_timestamp_deserialize(l+19, &m->firmware_timestamp);
+ else if (startswith(l, "loader-timestamp="))
+ dual_timestamp_deserialize(l+17, &m->loader_timestamp);
+ else if (startswith(l, "kernel-timestamp="))
+ dual_timestamp_deserialize(l+17, &m->kernel_timestamp);
+ else if (startswith(l, "initrd-timestamp="))
+ dual_timestamp_deserialize(l+17, &m->initrd_timestamp);
+ else if (startswith(l, "userspace-timestamp="))
+ dual_timestamp_deserialize(l+20, &m->userspace_timestamp);
+ else if (startswith(l, "finish-timestamp="))
+ dual_timestamp_deserialize(l+17, &m->finish_timestamp);
+ else if (startswith(l, "env=")) {
+ _cleanup_free_ char *uce = NULL;
+ char **e;
+
+ uce = cunescape(l+4);
+ if (!uce) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ e = strv_env_set(m->environment, uce);
+ if (!e) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ strv_free(m->environment);
+ m->environment = e;
+ } else
+ log_debug("Unknown serialization item '%s'", l);
+ }
+
+ for (;;) {
+ Unit *u;
+ char name[UNIT_NAME_MAX+2];
+
+ /* Start marker */
+ if (!fgets(name, sizeof(name), f)) {
+ if (feof(f))
+ r = 0;
+ else
+ r = -errno;
+
+ goto finish;
+ }
+
+ char_array_0(name);
+
+ r = manager_load_unit(m, strstrip(name), NULL, NULL, &u);
+ if (r < 0)
+ goto finish;
+
+ r = unit_deserialize(u, f, fds);
+ if (r < 0)
+ goto finish;
+ }
+
+finish:
+ if (ferror(f)) {
+ r = -EIO;
+ goto finish;
+ }
+
+ assert(m->n_reloading > 0);
+ m->n_reloading --;
+
+ return r;
+}
+
+int manager_distribute_fds(Manager *m, FDSet *fds) {
+ Unit *u;
+ Iterator i;
+ int r;
+
+ assert(m);
+
+ HASHMAP_FOREACH(u, m->units, i) {
+
+ if (fdset_size(fds) <= 0)
+ break;
+
+ if (UNIT_VTABLE(u)->distribute_fds) {
+ r = UNIT_VTABLE(u)->distribute_fds(u, fds);
+ if (r < 0)
+ return r;
+ }
+ }
+
+ return 0;
+}
+
+int manager_reload(Manager *m) {
+ int r, q;
+ FILE *f;
+ FDSet *fds;
+
+ assert(m);
+
+ r = manager_open_serialization(m, &f);
+ if (r < 0)
+ return r;
+
+ m->n_reloading ++;
+
+ fds = fdset_new();
+ if (!fds) {
+ m->n_reloading --;
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ r = manager_serialize(m, f, fds, false);
+ if (r < 0) {
+ m->n_reloading --;
+ goto finish;
+ }
+
+ if (fseeko(f, 0, SEEK_SET) < 0) {
+ m->n_reloading --;
+ r = -errno;
+ goto finish;
+ }
+
+ /* From here on there is no way back. */
+ manager_clear_jobs_and_units(m);
+ manager_undo_generators(m);
+ lookup_paths_free(&m->lookup_paths);
+
+ /* Find new unit paths */
+ manager_run_generators(m);
+
+ q = lookup_paths_init(
+ &m->lookup_paths, m->running_as, true,
+ m->generator_unit_path,
+ m->generator_unit_path_early,
+ m->generator_unit_path_late);
+ if (q < 0)
+ r = q;
+
+ manager_build_unit_path_cache(m);
+
+ /* First, enumerate what we can from all config files */
+ q = manager_enumerate(m);
+ if (q < 0)
+ r = q;
+
+ /* Second, deserialize our stored data */
+ q = manager_deserialize(m, f, fds);
+ if (q < 0)
+ r = q;
+
+ fclose(f);
+ f = NULL;
+
+ /* Third, fire things up! */
+ q = manager_coldplug(m);
+ if (q < 0)
+ r = q;
+
+ assert(m->n_reloading > 0);
+ m->n_reloading--;
+
+finish:
+ if (f)
+ fclose(f);
+
+ if (fds)
+ fdset_free(fds);
+
+ return r;
+}
+
+static bool manager_is_booting_or_shutting_down(Manager *m) {
+ Unit *u;
+
+ assert(m);
+
+ /* Is the initial job still around? */
+ if (manager_get_job(m, m->default_unit_job_id))
+ return true;
+
+ /* Is there a job for the shutdown target? */
+ u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET);
+ if (u)
+ return !!u->job;
+
+ return false;
+}
+
+bool manager_is_reloading_or_reexecuting(Manager *m) {
+ assert(m);
+
+ return m->n_reloading != 0;
+}
+
+void manager_reset_failed(Manager *m) {
+ Unit *u;
+ Iterator i;
+
+ assert(m);
+
+ HASHMAP_FOREACH(u, m->units, i)
+ unit_reset_failed(u);
+}
+
+bool manager_unit_inactive_or_pending(Manager *m, const char *name) {
+ Unit *u;
+
+ assert(m);
+ assert(name);
+
+ /* Returns true if the unit is inactive or going down */
+ u = manager_get_unit(m, name);
+ if (!u)
+ return true;
+
+ return unit_inactive_or_pending(u);
+}
+
+void manager_check_finished(Manager *m) {
+ char userspace[FORMAT_TIMESPAN_MAX], initrd[FORMAT_TIMESPAN_MAX], kernel[FORMAT_TIMESPAN_MAX], sum[FORMAT_TIMESPAN_MAX];
+ usec_t firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec;
+
+ assert(m);
+
+ if (m->n_running_jobs == 0)
+ manager_unwatch_jobs_in_progress(m);
+
+ if (hashmap_size(m->jobs) > 0) {
+ manager_jobs_in_progress_mod_timer(m);
+ return;
+ }
+
+ /* Notify Type=idle units that we are done now */
+ close_pipe(m->idle_pipe);
+
+ /* Turn off confirm spawn now */
+ m->confirm_spawn = false;
+
+ if (dual_timestamp_is_set(&m->finish_timestamp))
+ return;
+
+ dual_timestamp_get(&m->finish_timestamp);
+
+ if (m->running_as == SYSTEMD_SYSTEM && detect_container(NULL) <= 0) {
+
+ /* Note that m->kernel_usec.monotonic is always at 0,
+ * and m->firmware_usec.monotonic and
+ * m->loader_usec.monotonic should be considered
+ * negative values. */
+
+ firmware_usec = m->firmware_timestamp.monotonic - m->loader_timestamp.monotonic;
+ loader_usec = m->loader_timestamp.monotonic - m->kernel_timestamp.monotonic;
+ userspace_usec = m->finish_timestamp.monotonic - m->userspace_timestamp.monotonic;
+ total_usec = m->firmware_timestamp.monotonic + m->finish_timestamp.monotonic;
+
+ if (dual_timestamp_is_set(&m->initrd_timestamp)) {
+
+ kernel_usec = m->initrd_timestamp.monotonic - m->kernel_timestamp.monotonic;
+ initrd_usec = m->userspace_timestamp.monotonic - m->initrd_timestamp.monotonic;
+
+ if (!log_on_console())
+ log_struct(LOG_INFO,
+ MESSAGE_ID(SD_MESSAGE_STARTUP_FINISHED),
+ "KERNEL_USEC=%llu", (unsigned long long) kernel_usec,
+ "INITRD_USEC=%llu", (unsigned long long) initrd_usec,
+ "USERSPACE_USEC=%llu", (unsigned long long) userspace_usec,
+ "MESSAGE=Startup finished in %s (kernel) + %s (initrd) + %s (userspace) = %s.",
+ format_timespan(kernel, sizeof(kernel), kernel_usec, USEC_PER_MSEC),
+ format_timespan(initrd, sizeof(initrd), initrd_usec, USEC_PER_MSEC),
+ format_timespan(userspace, sizeof(userspace), userspace_usec, USEC_PER_MSEC),
+ format_timespan(sum, sizeof(sum), total_usec, USEC_PER_MSEC),
+ NULL);
+ } else {
+ kernel_usec = m->userspace_timestamp.monotonic - m->kernel_timestamp.monotonic;
+ initrd_usec = 0;
+
+ if (!log_on_console())
+ log_struct(LOG_INFO,
+ MESSAGE_ID(SD_MESSAGE_STARTUP_FINISHED),
+ "KERNEL_USEC=%llu", (unsigned long long) kernel_usec,
+ "USERSPACE_USEC=%llu", (unsigned long long) userspace_usec,
+ "MESSAGE=Startup finished in %s (kernel) + %s (userspace) = %s.",
+ format_timespan(kernel, sizeof(kernel), kernel_usec, USEC_PER_MSEC),
+ format_timespan(userspace, sizeof(userspace), userspace_usec, USEC_PER_MSEC),
+ format_timespan(sum, sizeof(sum), total_usec, USEC_PER_MSEC),
+ NULL);
+ }
+ } else {
+ firmware_usec = loader_usec = initrd_usec = kernel_usec = 0;
+ total_usec = userspace_usec = m->finish_timestamp.monotonic - m->userspace_timestamp.monotonic;
+
+ if (!log_on_console())
+ log_struct(LOG_INFO,
+ MESSAGE_ID(SD_MESSAGE_STARTUP_FINISHED),
+ "USERSPACE_USEC=%llu", (unsigned long long) userspace_usec,
+ "MESSAGE=Startup finished in %s.",
+ format_timespan(sum, sizeof(sum), total_usec, USEC_PER_MSEC),
+ NULL);
+ }
+
+ bus_broadcast_finished(m, firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec);
+
+ sd_notifyf(false,
+ "READY=1\nSTATUS=Startup finished in %s.",
+ format_timespan(sum, sizeof(sum), total_usec, USEC_PER_MSEC));
+}
+
+static int create_generator_dir(Manager *m, char **generator, const char *name) {
+ char *p;
+ int r;
+
+ assert(m);
+ assert(generator);
+ assert(name);
+
+ if (*generator)
+ return 0;
+
+ if (m->running_as == SYSTEMD_SYSTEM && getpid() == 1) {
+
+ p = strappend("/run/systemd/", name);
+ if (!p)
+ return log_oom();
+
+ r = mkdir_p_label(p, 0755);
+ if (r < 0) {
+ log_error("Failed to create generator directory %s: %s",
+ p, strerror(-r));
+ free(p);
+ return r;
+ }
+ } else {
+ p = strjoin("/tmp/systemd-", name, ".XXXXXX", NULL);
+ if (!p)
+ return log_oom();
+
+ if (!mkdtemp(p)) {
+ log_error("Failed to create generator directory %s: %m",
+ p);
+ free(p);
+ return -errno;
+ }
+ }
+
+ *generator = p;
+ return 0;
+}
+
+static void trim_generator_dir(Manager *m, char **generator) {
+ assert(m);
+ assert(generator);
+
+ if (!*generator)
+ return;
+
+ if (rmdir(*generator) >= 0) {
+ free(*generator);
+ *generator = NULL;
+ }
+
+ return;
+}
+
+void manager_run_generators(Manager *m) {
+ DIR *d = NULL;
+ const char *generator_path;
+ const char *argv[5];
+ int r;
+
+ assert(m);
+
+ generator_path = m->running_as == SYSTEMD_SYSTEM ? SYSTEM_GENERATOR_PATH : USER_GENERATOR_PATH;
+ d = opendir(generator_path);
+ if (!d) {
+ if (errno == ENOENT)
+ return;
+
+ log_error("Failed to enumerate generator directory %s: %m",
+ generator_path);
+ return;
+ }
+
+ r = create_generator_dir(m, &m->generator_unit_path, "generator");
+ if (r < 0)
+ goto finish;
+
+ r = create_generator_dir(m, &m->generator_unit_path_early, "generator.early");
+ if (r < 0)
+ goto finish;
+
+ r = create_generator_dir(m, &m->generator_unit_path_late, "generator.late");
+ if (r < 0)
+ goto finish;
+
+ argv[0] = NULL; /* Leave this empty, execute_directory() will fill something in */
+ argv[1] = m->generator_unit_path;
+ argv[2] = m->generator_unit_path_early;
+ argv[3] = m->generator_unit_path_late;
+ argv[4] = NULL;
+
+ RUN_WITH_UMASK(0022) {
+ execute_directory(generator_path, d, (char**) argv);
+ }
+
+ trim_generator_dir(m, &m->generator_unit_path);
+ trim_generator_dir(m, &m->generator_unit_path_early);
+ trim_generator_dir(m, &m->generator_unit_path_late);
+
+finish:
+ if (d)
+ closedir(d);
+}
+
+static void remove_generator_dir(Manager *m, char **generator) {
+ assert(m);
+ assert(generator);
+
+ if (!*generator)
+ return;
+
+ strv_remove(m->lookup_paths.unit_path, *generator);
+ rm_rf(*generator, false, true, false);
+
+ free(*generator);
+ *generator = NULL;
+}
+
+void manager_undo_generators(Manager *m) {
+ assert(m);
+
+ remove_generator_dir(m, &m->generator_unit_path);
+ remove_generator_dir(m, &m->generator_unit_path_early);
+ remove_generator_dir(m, &m->generator_unit_path_late);
+}
+
+int manager_set_default_controllers(Manager *m, char **controllers) {
+ char **l;
+
+ assert(m);
+
+ l = strv_copy(controllers);
+ if (!l)
+ return -ENOMEM;
+
+ strv_free(m->default_controllers);
+ m->default_controllers = l;
+
+ cg_shorten_controllers(m->default_controllers);
+
+ return 0;
+}
+
+int manager_set_default_rlimits(Manager *m, struct rlimit **default_rlimit) {
+ int i;
+
+ assert(m);
+
+ for (i = 0; i < RLIMIT_NLIMITS; i++) {
+ if (!default_rlimit[i])
+ continue;
+
+ m->rlimit[i] = newdup(struct rlimit, default_rlimit[i], 1);
+ if (!m->rlimit[i])
+ return -ENOMEM;
+ }
+
+ return 0;
+}
+
+void manager_recheck_journal(Manager *m) {
+ Unit *u;
+
+ assert(m);
+
+ if (m->running_as != SYSTEMD_SYSTEM)
+ return;
+
+ u = manager_get_unit(m, SPECIAL_JOURNALD_SOCKET);
+ if (u && SOCKET(u)->state != SOCKET_RUNNING) {
+ log_close_journal();
+ return;
+ }
+
+ u = manager_get_unit(m, SPECIAL_JOURNALD_SERVICE);
+ if (u && SERVICE(u)->state != SERVICE_RUNNING) {
+ log_close_journal();
+ return;
+ }
+
+ /* Hmm, OK, so the socket is fully up and the service is up
+ * too, then let's make use of the thing. */
+ log_open();
+}
+
+void manager_set_show_status(Manager *m, bool b) {
+ assert(m);
+
+ if (m->running_as != SYSTEMD_SYSTEM)
+ return;
+
+ m->show_status = b;
+
+ if (b)
+ touch("/run/systemd/show-status");
+ else
+ unlink("/run/systemd/show-status");
+}
+
+static bool manager_get_show_status(Manager *m) {
+ assert(m);
+
+ if (m->running_as != SYSTEMD_SYSTEM)
+ return false;
+
+ if (m->show_status)
+ return true;
+
+ /* If Plymouth is running make sure we show the status, so
+ * that there's something nice to see when people press Esc */
+
+ return plymouth_running();
+}
+
+void manager_status_printf(Manager *m, bool ephemeral, const char *status, const char *format, ...) {
+ va_list ap;
+
+ if (!manager_get_show_status(m))
+ return;
+
+ /* XXX We should totally drop the check for ephemeral here
+ * and thus effectively make 'Type=idle' pointless. */
+ if (ephemeral && m->n_on_console > 0)
+ return;
+
+ if (!manager_is_booting_or_shutting_down(m))
+ return;
+
+ va_start(ap, format);
+ status_vprintf(status, true, ephemeral, format, ap);
+ va_end(ap);
+}
+
+void watch_init(Watch *w) {
+ assert(w);
+
+ w->type = WATCH_INVALID;
+ w->fd = -1;
+}
diff --git a/src/core/manager.h b/src/core/manager.h
new file mode 100644
index 0000000000..bf833540ae
--- /dev/null
+++ b/src/core/manager.h
@@ -0,0 +1,306 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdbool.h>
+#include <inttypes.h>
+#include <stdio.h>
+#include <dbus/dbus.h>
+
+#include "fdset.h"
+
+/* Enforce upper limit how many names we allow */
+#define MANAGER_MAX_NAMES 131072 /* 128K */
+
+typedef struct Manager Manager;
+typedef enum WatchType WatchType;
+typedef struct Watch Watch;
+
+typedef enum ManagerExitCode {
+ MANAGER_RUNNING,
+ MANAGER_EXIT,
+ MANAGER_RELOAD,
+ MANAGER_REEXECUTE,
+ MANAGER_REBOOT,
+ MANAGER_POWEROFF,
+ MANAGER_HALT,
+ MANAGER_KEXEC,
+ MANAGER_SWITCH_ROOT,
+ _MANAGER_EXIT_CODE_MAX,
+ _MANAGER_EXIT_CODE_INVALID = -1
+} ManagerExitCode;
+
+enum WatchType {
+ WATCH_INVALID,
+ WATCH_SIGNAL,
+ WATCH_NOTIFY,
+ WATCH_FD,
+ WATCH_UNIT_TIMER,
+ WATCH_JOB_TIMER,
+ WATCH_MOUNT,
+ WATCH_SWAP,
+ WATCH_UDEV,
+ WATCH_DBUS_WATCH,
+ WATCH_DBUS_TIMEOUT,
+ WATCH_TIME_CHANGE,
+ WATCH_JOBS_IN_PROGRESS
+};
+
+struct Watch {
+ int fd;
+ WatchType type;
+ union {
+ struct Unit *unit;
+ struct Job *job;
+ DBusWatch *bus_watch;
+ DBusTimeout *bus_timeout;
+ } data;
+ bool fd_is_dupped:1;
+ bool socket_accept:1;
+};
+
+#include "unit.h"
+#include "job.h"
+#include "hashmap.h"
+#include "list.h"
+#include "set.h"
+#include "dbus.h"
+#include "path-lookup.h"
+#include "execute.h"
+
+struct Manager {
+ /* Note that the set of units we know of is allowed to be
+ * inconsistent. However the subset of it that is loaded may
+ * not, and the list of jobs may neither. */
+
+ /* Active jobs and units */
+ Hashmap *units; /* name string => Unit object n:1 */
+ Hashmap *jobs; /* job id => Job object 1:1 */
+
+ /* To make it easy to iterate through the units of a specific
+ * type we maintain a per type linked list */
+ LIST_HEAD(Unit, units_by_type[_UNIT_TYPE_MAX]);
+
+ /* To optimize iteration of units that have requires_mounts_for set */
+ LIST_HEAD(Unit, has_requires_mounts_for);
+
+ /* Units that need to be loaded */
+ LIST_HEAD(Unit, load_queue); /* this is actually more a stack than a queue, but uh. */
+
+ /* Jobs that need to be run */
+ LIST_HEAD(Job, run_queue); /* more a stack than a queue, too */
+
+ /* Units and jobs that have not yet been announced via
+ * D-Bus. When something about a job changes it is added here
+ * if it is not in there yet. This allows easy coalescing of
+ * D-Bus change signals. */
+ LIST_HEAD(Unit, dbus_unit_queue);
+ LIST_HEAD(Job, dbus_job_queue);
+
+ /* Units to remove */
+ LIST_HEAD(Unit, cleanup_queue);
+
+ /* Units to check when doing GC */
+ LIST_HEAD(Unit, gc_queue);
+
+ Hashmap *watch_pids; /* pid => Unit object n:1 */
+
+ char *notify_socket;
+
+ Watch notify_watch;
+ Watch signal_watch;
+ Watch time_change_watch;
+ Watch jobs_in_progress_watch;
+
+ int epoll_fd;
+
+ unsigned n_snapshots;
+
+ LookupPaths lookup_paths;
+ Set *unit_path_cache;
+
+ char **environment;
+ char **default_controllers;
+
+ usec_t runtime_watchdog;
+ usec_t shutdown_watchdog;
+
+ dual_timestamp firmware_timestamp;
+ dual_timestamp loader_timestamp;
+ dual_timestamp kernel_timestamp;
+ dual_timestamp initrd_timestamp;
+ dual_timestamp userspace_timestamp;
+ dual_timestamp finish_timestamp;
+
+ char *generator_unit_path;
+ char *generator_unit_path_early;
+ char *generator_unit_path_late;
+
+ /* Data specific to the device subsystem */
+ struct udev* udev;
+ struct udev_monitor* udev_monitor;
+ Watch udev_watch;
+ Hashmap *devices_by_sysfs;
+
+ /* Data specific to the mount subsystem */
+ FILE *proc_self_mountinfo;
+ Watch mount_watch;
+
+ /* Data specific to the swap filesystem */
+ FILE *proc_swaps;
+ Hashmap *swaps_by_proc_swaps;
+ bool request_reload;
+ Watch swap_watch;
+
+ /* Data specific to the D-Bus subsystem */
+ DBusConnection *api_bus, *system_bus;
+ DBusServer *private_bus;
+ Set *bus_connections, *bus_connections_for_dispatch;
+
+ DBusMessage *queued_message; /* This is used during reloading:
+ * before the reload we queue the
+ * reply message here, and
+ * afterwards we send it */
+ DBusConnection *queued_message_connection; /* The connection to send the queued message on */
+
+ Hashmap *watch_bus; /* D-Bus names => Unit object n:1 */
+ int32_t name_data_slot;
+ int32_t conn_data_slot;
+ int32_t subscribed_data_slot;
+
+ uint32_t current_job_id;
+ uint32_t default_unit_job_id;
+
+ /* Data specific to the Automount subsystem */
+ int dev_autofs_fd;
+
+ /* Data specific to the cgroup subsystem */
+ Hashmap *cgroup_bondings; /* path string => CGroupBonding object 1:n */
+ char *cgroup_hierarchy;
+
+ usec_t gc_queue_timestamp;
+ int gc_marker;
+ unsigned n_in_gc_queue;
+
+ /* Make sure the user cannot accidentally unmount our cgroup
+ * file system */
+ int pin_cgroupfs_fd;
+
+ /* Flags */
+ SystemdRunningAs running_as;
+ ManagerExitCode exit_code:5;
+
+ bool dispatching_load_queue:1;
+ bool dispatching_run_queue:1;
+ bool dispatching_dbus_queue:1;
+
+ bool taint_usr:1;
+
+ bool show_status;
+ bool confirm_spawn;
+
+ ExecOutput default_std_output, default_std_error;
+
+ struct rlimit *rlimit[RLIMIT_NLIMITS];
+
+ /* non-zero if we are reloading or reexecuting, */
+ int n_reloading;
+
+ unsigned n_installed_jobs;
+ unsigned n_failed_jobs;
+
+ /* Jobs in progress watching */
+ unsigned n_running_jobs;
+ unsigned n_on_console;
+ unsigned jobs_in_progress_iteration;
+
+ /* Type=idle pipes */
+ int idle_pipe[2];
+
+ char *switch_root;
+ char *switch_root_init;
+};
+
+int manager_new(SystemdRunningAs running_as, Manager **m);
+void manager_free(Manager *m);
+
+int manager_enumerate(Manager *m);
+int manager_coldplug(Manager *m);
+int manager_startup(Manager *m, FILE *serialization, FDSet *fds);
+
+Job *manager_get_job(Manager *m, uint32_t id);
+Unit *manager_get_unit(Manager *m, const char *name);
+
+int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j);
+
+int manager_load_unit_prepare(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret);
+int manager_load_unit(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret);
+int manager_load_unit_from_dbus_path(Manager *m, const char *s, DBusError *e, Unit **_u);
+
+int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool force, DBusError *e, Job **_ret);
+int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, bool force, DBusError *e, Job **_ret);
+
+void manager_dump_units(Manager *s, FILE *f, const char *prefix);
+void manager_dump_jobs(Manager *s, FILE *f, const char *prefix);
+
+void manager_clear_jobs(Manager *m);
+
+unsigned manager_dispatch_load_queue(Manager *m);
+unsigned manager_dispatch_run_queue(Manager *m);
+unsigned manager_dispatch_dbus_queue(Manager *m);
+
+int manager_set_default_controllers(Manager *m, char **controllers);
+int manager_set_default_rlimits(Manager *m, struct rlimit **default_rlimit);
+
+int manager_loop(Manager *m);
+
+void manager_dispatch_bus_name_owner_changed(Manager *m, const char *name, const char* old_owner, const char *new_owner);
+void manager_dispatch_bus_query_pid_done(Manager *m, const char *name, pid_t pid);
+
+int manager_open_serialization(Manager *m, FILE **_f);
+
+int manager_serialize(Manager *m, FILE *f, FDSet *fds, bool switching_root);
+int manager_deserialize(Manager *m, FILE *f, FDSet *fds);
+int manager_distribute_fds(Manager *m, FDSet *fds);
+
+int manager_reload(Manager *m);
+
+bool manager_is_reloading_or_reexecuting(Manager *m) _pure_;
+
+void manager_reset_failed(Manager *m);
+
+void manager_send_unit_audit(Manager *m, Unit *u, int type, bool success);
+void manager_send_unit_plymouth(Manager *m, Unit *u);
+
+bool manager_unit_inactive_or_pending(Manager *m, const char *name);
+
+void manager_check_finished(Manager *m);
+
+void manager_run_generators(Manager *m);
+void manager_undo_generators(Manager *m);
+
+void manager_recheck_journal(Manager *m);
+
+void manager_set_show_status(Manager *m, bool b);
+void manager_status_printf(Manager *m, bool ephemeral, const char *status, const char *format, ...) _printf_attr_(4,5);
+
+void watch_init(Watch *w);
diff --git a/src/core/mount-setup.c b/src/core/mount-setup.c
new file mode 100644
index 0000000000..4629808a7a
--- /dev/null
+++ b/src/core/mount-setup.c
@@ -0,0 +1,417 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/mount.h>
+#include <errno.h>
+#include <sys/stat.h>
+#include <stdlib.h>
+#include <string.h>
+#include <libgen.h>
+#include <assert.h>
+#include <unistd.h>
+#include <ftw.h>
+
+#include "mount-setup.h"
+#include "dev-setup.h"
+#include "log.h"
+#include "macro.h"
+#include "util.h"
+#include "label.h"
+#include "set.h"
+#include "strv.h"
+#include "mkdir.h"
+#include "path-util.h"
+#include "missing.h"
+#include "virt.h"
+#include "efivars.h"
+
+#ifndef TTY_GID
+#define TTY_GID 5
+#endif
+
+typedef enum MountMode {
+ MNT_NONE = 0,
+ MNT_FATAL = 1 << 0,
+ MNT_IN_CONTAINER = 1 << 1,
+} MountMode;
+
+typedef struct MountPoint {
+ const char *what;
+ const char *where;
+ const char *type;
+ const char *options;
+ unsigned long flags;
+ bool (*condition_fn)(void);
+ MountMode mode;
+} MountPoint;
+
+/* The first three entries we might need before SELinux is up. The
+ * fourth (securityfs) is needed by IMA to load a custom policy. The
+ * other ones we can delay until SELinux and IMA are loaded. */
+#define N_EARLY_MOUNT 5
+
+static const MountPoint mount_table[] = {
+ { "proc", "/proc", "proc", NULL, MS_NOSUID|MS_NOEXEC|MS_NODEV,
+ NULL, MNT_FATAL|MNT_IN_CONTAINER },
+ { "sysfs", "/sys", "sysfs", NULL, MS_NOSUID|MS_NOEXEC|MS_NODEV,
+ NULL, MNT_FATAL|MNT_IN_CONTAINER },
+ { "devtmpfs", "/dev", "devtmpfs", "mode=755", MS_NOSUID|MS_STRICTATIME,
+ NULL, MNT_FATAL|MNT_IN_CONTAINER },
+ { "securityfs", "/sys/kernel/security", "securityfs", NULL, MS_NOSUID|MS_NOEXEC|MS_NODEV,
+ NULL, MNT_NONE },
+ { "smackfs", "/sys/fs/smackfs", "smackfs", "smackfsdef=*", MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME,
+ NULL, MNT_NONE },
+ { "tmpfs", "/dev/shm", "tmpfs", "mode=1777", MS_NOSUID|MS_NODEV|MS_STRICTATIME,
+ NULL, MNT_FATAL|MNT_IN_CONTAINER },
+ { "devpts", "/dev/pts", "devpts", "mode=620,gid=" STRINGIFY(TTY_GID), MS_NOSUID|MS_NOEXEC,
+ NULL, MNT_IN_CONTAINER },
+ { "tmpfs", "/run", "tmpfs", "mode=755", MS_NOSUID|MS_NODEV|MS_STRICTATIME,
+ NULL, MNT_FATAL|MNT_IN_CONTAINER },
+ { "tmpfs", "/sys/fs/cgroup", "tmpfs", "mode=755", MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME,
+ NULL, MNT_IN_CONTAINER },
+#ifdef HAVE_XATTR
+ { "cgroup", "/sys/fs/cgroup/systemd", "cgroup", "none,name=systemd,xattr", MS_NOSUID|MS_NOEXEC|MS_NODEV,
+ NULL, MNT_IN_CONTAINER },
+#endif
+ { "cgroup", "/sys/fs/cgroup/systemd", "cgroup", "none,name=systemd", MS_NOSUID|MS_NOEXEC|MS_NODEV,
+ NULL, MNT_IN_CONTAINER },
+ { "pstore", "/sys/fs/pstore", "pstore", NULL, MS_NOSUID|MS_NOEXEC|MS_NODEV,
+ NULL, MNT_NONE },
+#ifdef ENABLE_EFI
+ { "efivarfs", "/sys/firmware/efi/efivars", "efivarfs", NULL, MS_NOSUID|MS_NOEXEC|MS_NODEV,
+ is_efi_boot, MNT_NONE },
+#endif
+};
+
+/* These are API file systems that might be mounted by other software,
+ * we just list them here so that we know that we should ignore them */
+
+static const char ignore_paths[] =
+ /* SELinux file systems */
+ "/sys/fs/selinux\0"
+ "/selinux\0"
+ /* Legacy cgroup mount points */
+ "/dev/cgroup\0"
+ "/cgroup\0"
+ /* Legacy kernel file system */
+ "/proc/bus/usb\0"
+ /* Container bind mounts */
+ "/proc/sys\0"
+ "/dev/console\0"
+ "/proc/kmsg\0";
+
+bool mount_point_is_api(const char *path) {
+ unsigned i;
+
+ /* Checks if this mount point is considered "API", and hence
+ * should be ignored */
+
+ for (i = 0; i < ELEMENTSOF(mount_table); i ++)
+ if (path_equal(path, mount_table[i].where))
+ return true;
+
+ return path_startswith(path, "/sys/fs/cgroup/");
+}
+
+bool mount_point_ignore(const char *path) {
+ const char *i;
+
+ NULSTR_FOREACH(i, ignore_paths)
+ if (path_equal(path, i))
+ return true;
+
+ return false;
+}
+
+static int mount_one(const MountPoint *p, bool relabel) {
+ int r;
+
+ assert(p);
+
+ if (p->condition_fn && !p->condition_fn())
+ return 0;
+
+ /* Relabel first, just in case */
+ if (relabel)
+ label_fix(p->where, true, true);
+
+ r = path_is_mount_point(p->where, true);
+ if (r < 0)
+ return r;
+
+ if (r > 0)
+ return 0;
+
+ /* Skip securityfs in a container */
+ if (!(p->mode & MNT_IN_CONTAINER) && detect_container(NULL) > 0)
+ return 0;
+
+ /* The access mode here doesn't really matter too much, since
+ * the mounted file system will take precedence anyway. */
+ mkdir_p_label(p->where, 0755);
+
+ log_debug("Mounting %s to %s of type %s with options %s.",
+ p->what,
+ p->where,
+ p->type,
+ strna(p->options));
+
+ if (mount(p->what,
+ p->where,
+ p->type,
+ p->flags,
+ p->options) < 0) {
+ log_full((p->mode & MNT_FATAL) ? LOG_ERR : LOG_DEBUG, "Failed to mount %s: %s", p->where, strerror(errno));
+ return (p->mode & MNT_FATAL) ? -errno : 0;
+ }
+
+ /* Relabel again, since we now mounted something fresh here */
+ if (relabel)
+ label_fix(p->where, false, false);
+
+ return 1;
+}
+
+int mount_setup_early(void) {
+ unsigned i;
+ int r = 0;
+
+ assert_cc(N_EARLY_MOUNT <= ELEMENTSOF(mount_table));
+
+ /* Do a minimal mount of /proc and friends to enable the most
+ * basic stuff, such as SELinux */
+ for (i = 0; i < N_EARLY_MOUNT; i ++) {
+ int j;
+
+ j = mount_one(mount_table + i, false);
+ if (r == 0)
+ r = j;
+ }
+
+ return r;
+}
+
+int mount_cgroup_controllers(char ***join_controllers) {
+ int r;
+ char buf[LINE_MAX];
+ _cleanup_set_free_free_ Set *controllers = NULL;
+ _cleanup_fclose_ FILE *f;
+
+ /* Mount all available cgroup controllers that are built into the kernel. */
+
+ f = fopen("/proc/cgroups", "re");
+ if (!f) {
+ log_error("Failed to enumerate cgroup controllers: %m");
+ return 0;
+ }
+
+ controllers = set_new(string_hash_func, string_compare_func);
+ if (!controllers)
+ return log_oom();
+
+ /* Ignore the header line */
+ (void) fgets(buf, sizeof(buf), f);
+
+ for (;;) {
+ char *controller;
+ int enabled = 0;
+
+ if (fscanf(f, "%ms %*i %*i %i", &controller, &enabled) != 2) {
+
+ if (feof(f))
+ break;
+
+ log_error("Failed to parse /proc/cgroups.");
+ return -EIO;
+ }
+
+ if (!enabled) {
+ free(controller);
+ continue;
+ }
+
+ r = set_consume(controllers, controller);
+ if (r < 0) {
+ log_error("Failed to add controller to set.");
+ return r;
+ }
+ }
+
+ for (;;) {
+ MountPoint p = {
+ .what = "cgroup",
+ .type = "cgroup",
+ .flags = MS_NOSUID|MS_NOEXEC|MS_NODEV,
+ .mode = MNT_IN_CONTAINER,
+ };
+ char ***k = NULL;
+ _cleanup_free_ char *options = NULL, *controller;
+
+ controller = set_steal_first(controllers);
+ if (!controller)
+ break;
+
+ if (join_controllers)
+ for (k = join_controllers; *k; k++)
+ if (strv_find(*k, controller))
+ break;
+
+ if (k && *k) {
+ char **i, **j;
+
+ for (i = *k, j = *k; *i; i++) {
+
+ if (!streq(*i, controller)) {
+ char _cleanup_free_ *t;
+
+ t = set_remove(controllers, *i);
+ if (!t) {
+ free(*i);
+ continue;
+ }
+ }
+
+ *(j++) = *i;
+ }
+
+ *j = NULL;
+
+ options = strv_join(*k, ",");
+ if (!options)
+ return log_oom();
+ } else {
+ options = controller;
+ controller = NULL;
+ }
+
+ p.where = strappenda("/sys/fs/cgroup/", options);
+ p.options = options;
+
+ r = mount_one(&p, true);
+ if (r < 0)
+ return r;
+
+ if (r > 0 && k && *k) {
+ char **i;
+
+ for (i = *k; *i; i++) {
+ char *t = strappenda("/sys/fs/cgroup/", *i);
+
+ r = symlink(options, t);
+ if (r < 0 && errno != EEXIST) {
+ log_error("Failed to create symlink %s: %m", t);
+ return -errno;
+ }
+ }
+ }
+ }
+
+ return 0;
+}
+
+static int nftw_cb(
+ const char *fpath,
+ const struct stat *sb,
+ int tflag,
+ struct FTW *ftwbuf) {
+
+ /* No need to label /dev twice in a row... */
+ if (_unlikely_(ftwbuf->level == 0))
+ return FTW_CONTINUE;
+
+ label_fix(fpath, false, false);
+
+ /* /run/initramfs is static data and big, no need to
+ * dynamically relabel its contents at boot... */
+ if (_unlikely_(ftwbuf->level == 1 &&
+ tflag == FTW_D &&
+ streq(fpath, "/run/initramfs")))
+ return FTW_SKIP_SUBTREE;
+
+ return FTW_CONTINUE;
+};
+
+int mount_setup(bool loaded_policy) {
+
+ static const char relabel[] =
+ "/run/initramfs/root-fsck\0"
+ "/run/initramfs/shutdown\0";
+
+ int r;
+ unsigned i;
+ const char *j;
+
+ for (i = 0; i < ELEMENTSOF(mount_table); i ++) {
+ r = mount_one(mount_table + i, true);
+
+ if (r < 0)
+ return r;
+ }
+
+ /* Nodes in devtmpfs and /run need to be manually updated for
+ * the appropriate labels, after mounting. The other virtual
+ * API file systems like /sys and /proc do not need that, they
+ * use the same label for all their files. */
+ if (loaded_policy) {
+ usec_t before_relabel, after_relabel;
+ char timespan[FORMAT_TIMESPAN_MAX];
+
+ before_relabel = now(CLOCK_MONOTONIC);
+
+ nftw("/dev", nftw_cb, 64, FTW_MOUNT|FTW_PHYS|FTW_ACTIONRETVAL);
+ nftw("/run", nftw_cb, 64, FTW_MOUNT|FTW_PHYS|FTW_ACTIONRETVAL);
+
+ /* Explicitly relabel these */
+ NULSTR_FOREACH(j, relabel)
+ label_fix(j, true, false);
+
+ after_relabel = now(CLOCK_MONOTONIC);
+
+ log_info("Relabelled /dev and /run in %s.",
+ format_timespan(timespan, sizeof(timespan), after_relabel - before_relabel, 0));
+ }
+
+ /* Create a few default symlinks, which are normally created
+ * by udevd, but some scripts might need them before we start
+ * udevd. */
+ dev_setup(NULL);
+
+ /* Mark the root directory as shared in regards to mount
+ * propagation. The kernel defaults to "private", but we think
+ * it makes more sense to have a default of "shared" so that
+ * nspawn and the container tools work out of the box. If
+ * specific setups need other settings they can reset the
+ * propagation mode to private if needed. */
+ if (detect_container(NULL) <= 0)
+ if (mount(NULL, "/", NULL, MS_REC|MS_SHARED, NULL) < 0)
+ log_warning("Failed to set up the root directory for shared mount propagation: %m");
+
+ /* Create a few directories we always want around, Note that
+ * sd_booted() checks for /run/systemd/system, so this mkdir
+ * really needs to stay for good, otherwise software that
+ * copied sd-daemon.c into their sources will misdetect
+ * systemd. */
+ mkdir_label("/run/systemd", 0755);
+ mkdir_label("/run/systemd/system", 0755);
+ mkdir_label("/run/systemd/inaccessible", 0000);
+
+ return 0;
+}
diff --git a/src/core/mount-setup.h b/src/core/mount-setup.h
new file mode 100644
index 0000000000..4b521ad0e1
--- /dev/null
+++ b/src/core/mount-setup.h
@@ -0,0 +1,33 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdbool.h>
+
+int mount_setup_early(void);
+
+int mount_setup(bool loaded_policy);
+
+int mount_cgroup_controllers(char ***join_controllers);
+
+bool mount_point_is_api(const char *path);
+bool mount_point_ignore(const char *path);
diff --git a/src/core/mount.c b/src/core/mount.c
new file mode 100644
index 0000000000..10073b50be
--- /dev/null
+++ b/src/core/mount.c
@@ -0,0 +1,1932 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <stdio.h>
+#include <mntent.h>
+#include <sys/epoll.h>
+#include <signal.h>
+
+#include "manager.h"
+#include "unit.h"
+#include "mount.h"
+#include "load-fragment.h"
+#include "load-dropin.h"
+#include "log.h"
+#include "sd-messages.h"
+#include "strv.h"
+#include "mkdir.h"
+#include "path-util.h"
+#include "mount-setup.h"
+#include "unit-name.h"
+#include "dbus-mount.h"
+#include "special.h"
+#include "bus-errors.h"
+#include "exit-status.h"
+#include "def.h"
+
+static const UnitActiveState state_translation_table[_MOUNT_STATE_MAX] = {
+ [MOUNT_DEAD] = UNIT_INACTIVE,
+ [MOUNT_MOUNTING] = UNIT_ACTIVATING,
+ [MOUNT_MOUNTING_DONE] = UNIT_ACTIVE,
+ [MOUNT_MOUNTED] = UNIT_ACTIVE,
+ [MOUNT_REMOUNTING] = UNIT_RELOADING,
+ [MOUNT_UNMOUNTING] = UNIT_DEACTIVATING,
+ [MOUNT_MOUNTING_SIGTERM] = UNIT_DEACTIVATING,
+ [MOUNT_MOUNTING_SIGKILL] = UNIT_DEACTIVATING,
+ [MOUNT_REMOUNTING_SIGTERM] = UNIT_RELOADING,
+ [MOUNT_REMOUNTING_SIGKILL] = UNIT_RELOADING,
+ [MOUNT_UNMOUNTING_SIGTERM] = UNIT_DEACTIVATING,
+ [MOUNT_UNMOUNTING_SIGKILL] = UNIT_DEACTIVATING,
+ [MOUNT_FAILED] = UNIT_FAILED
+};
+
+static void mount_init(Unit *u) {
+ Mount *m = MOUNT(u);
+
+ assert(u);
+ assert(u->load_state == UNIT_STUB);
+
+ m->timeout_usec = DEFAULT_TIMEOUT_USEC;
+ m->directory_mode = 0755;
+
+ exec_context_init(&m->exec_context);
+
+ if (unit_has_name(u, "-.mount")) {
+ /* Don't allow start/stop for root directory */
+ UNIT(m)->refuse_manual_start = true;
+ UNIT(m)->refuse_manual_stop = true;
+ } else {
+ /* The stdio/kmsg bridge socket is on /, in order to avoid a
+ * dep loop, don't use kmsg logging for -.mount */
+ m->exec_context.std_output = u->manager->default_std_output;
+ m->exec_context.std_error = u->manager->default_std_error;
+ }
+
+ kill_context_init(&m->kill_context);
+
+ /* We need to make sure that /bin/mount is always called in
+ * the same process group as us, so that the autofs kernel
+ * side doesn't send us another mount request while we are
+ * already trying to comply its last one. */
+ m->exec_context.same_pgrp = true;
+
+ m->timer_watch.type = WATCH_INVALID;
+
+ m->control_command_id = _MOUNT_EXEC_COMMAND_INVALID;
+
+ UNIT(m)->ignore_on_isolate = true;
+}
+
+static void mount_unwatch_control_pid(Mount *m) {
+ assert(m);
+
+ if (m->control_pid <= 0)
+ return;
+
+ unit_unwatch_pid(UNIT(m), m->control_pid);
+ m->control_pid = 0;
+}
+
+static void mount_parameters_done(MountParameters *p) {
+ assert(p);
+
+ free(p->what);
+ free(p->options);
+ free(p->fstype);
+
+ p->what = p->options = p->fstype = NULL;
+}
+
+static void mount_done(Unit *u) {
+ Mount *m = MOUNT(u);
+
+ assert(m);
+
+ free(m->where);
+ m->where = NULL;
+
+ mount_parameters_done(&m->parameters_proc_self_mountinfo);
+ mount_parameters_done(&m->parameters_fragment);
+
+ exec_context_done(&m->exec_context, manager_is_reloading_or_reexecuting(u->manager));
+ exec_command_done_array(m->exec_command, _MOUNT_EXEC_COMMAND_MAX);
+ m->control_command = NULL;
+
+ mount_unwatch_control_pid(m);
+
+ unit_unwatch_timer(u, &m->timer_watch);
+}
+
+_pure_ static MountParameters* get_mount_parameters_fragment(Mount *m) {
+ assert(m);
+
+ if (m->from_fragment)
+ return &m->parameters_fragment;
+
+ return NULL;
+}
+
+_pure_ static MountParameters* get_mount_parameters(Mount *m) {
+ assert(m);
+
+ if (m->from_proc_self_mountinfo)
+ return &m->parameters_proc_self_mountinfo;
+
+ return get_mount_parameters_fragment(m);
+}
+
+static int mount_add_mount_links(Mount *m) {
+ Unit *other;
+ int r;
+ MountParameters *pm;
+
+ assert(m);
+
+ pm = get_mount_parameters_fragment(m);
+
+ /* Adds in links to other mount points that might lie below or
+ * above us in the hierarchy */
+
+ LIST_FOREACH(units_by_type, other, UNIT(m)->manager->units_by_type[UNIT_MOUNT]) {
+ Mount *n = MOUNT(other);
+ MountParameters *pn;
+
+ if (n == m)
+ continue;
+
+ if (UNIT(n)->load_state != UNIT_LOADED)
+ continue;
+
+ pn = get_mount_parameters_fragment(n);
+
+ if (path_startswith(m->where, n->where)) {
+
+ if ((r = unit_add_dependency(UNIT(m), UNIT_AFTER, UNIT(n), true)) < 0)
+ return r;
+
+ if (pn)
+ if ((r = unit_add_dependency(UNIT(m), UNIT_REQUIRES, UNIT(n), true)) < 0)
+ return r;
+
+ } else if (path_startswith(n->where, m->where)) {
+
+ if ((r = unit_add_dependency(UNIT(n), UNIT_AFTER, UNIT(m), true)) < 0)
+ return r;
+
+ if (pm)
+ if ((r = unit_add_dependency(UNIT(n), UNIT_REQUIRES, UNIT(m), true)) < 0)
+ return r;
+
+ } else if (pm && pm->what && path_startswith(pm->what, n->where)) {
+
+ if ((r = unit_add_dependency(UNIT(m), UNIT_AFTER, UNIT(n), true)) < 0)
+ return r;
+
+ if ((r = unit_add_dependency(UNIT(m), UNIT_REQUIRES, UNIT(n), true)) < 0)
+ return r;
+
+ } else if (pn && pn->what && path_startswith(pn->what, m->where)) {
+
+ if ((r = unit_add_dependency(UNIT(n), UNIT_AFTER, UNIT(m), true)) < 0)
+ return r;
+
+ if ((r = unit_add_dependency(UNIT(n), UNIT_REQUIRES, UNIT(m), true)) < 0)
+ return r;
+ }
+ }
+
+ return 0;
+}
+
+static int mount_add_swap_links(Mount *m) {
+ Unit *other;
+ int r;
+
+ assert(m);
+
+ LIST_FOREACH(units_by_type, other, UNIT(m)->manager->units_by_type[UNIT_SWAP]) {
+ r = swap_add_one_mount_link(SWAP(other), m);
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static int mount_add_path_links(Mount *m) {
+ Unit *other;
+ int r;
+
+ assert(m);
+
+ LIST_FOREACH(units_by_type, other, UNIT(m)->manager->units_by_type[UNIT_PATH]) {
+ r = path_add_one_mount_link(PATH(other), m);
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static int mount_add_automount_links(Mount *m) {
+ Unit *other;
+ int r;
+
+ assert(m);
+
+ LIST_FOREACH(units_by_type, other, UNIT(m)->manager->units_by_type[UNIT_AUTOMOUNT]) {
+ r = automount_add_one_mount_link(AUTOMOUNT(other), m);
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static int mount_add_socket_links(Mount *m) {
+ Unit *other;
+ int r;
+
+ assert(m);
+
+ LIST_FOREACH(units_by_type, other, UNIT(m)->manager->units_by_type[UNIT_SOCKET]) {
+ r = socket_add_one_mount_link(SOCKET(other), m);
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static int mount_add_requires_mounts_links(Mount *m) {
+ Unit *other;
+ int r;
+
+ assert(m);
+
+ LIST_FOREACH(has_requires_mounts_for, other, UNIT(m)->manager->has_requires_mounts_for) {
+ r = unit_add_one_mount_link(other, m);
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static char* mount_test_option(const char *haystack, const char *needle) {
+ struct mntent me = { .mnt_opts = (char*) haystack };
+
+ assert(needle);
+
+ /* Like glibc's hasmntopt(), but works on a string, not a
+ * struct mntent */
+
+ if (!haystack)
+ return NULL;
+
+ return hasmntopt(&me, needle);
+}
+
+static bool mount_is_network(MountParameters *p) {
+ assert(p);
+
+ if (mount_test_option(p->options, "_netdev"))
+ return true;
+
+ if (p->fstype && fstype_is_network(p->fstype))
+ return true;
+
+ return false;
+}
+
+static bool mount_is_bind(MountParameters *p) {
+ assert(p);
+
+ if (mount_test_option(p->options, "bind"))
+ return true;
+
+ if (p->fstype && streq(p->fstype, "bind"))
+ return true;
+
+ if (mount_test_option(p->options, "rbind"))
+ return true;
+
+ if (p->fstype && streq(p->fstype, "rbind"))
+ return true;
+
+ return false;
+}
+
+static bool needs_quota(MountParameters *p) {
+ assert(p);
+
+ if (mount_is_network(p))
+ return false;
+
+ if (mount_is_bind(p))
+ return false;
+
+ return mount_test_option(p->options, "usrquota") ||
+ mount_test_option(p->options, "grpquota") ||
+ mount_test_option(p->options, "quota") ||
+ mount_test_option(p->options, "usrjquota") ||
+ mount_test_option(p->options, "grpjquota");
+}
+
+static int mount_add_device_links(Mount *m) {
+ MountParameters *p;
+ int r;
+
+ assert(m);
+
+ p = get_mount_parameters_fragment(m);
+ if (!p)
+ return 0;
+
+ if (!p->what)
+ return 0;
+
+ if (mount_is_bind(p))
+ return 0;
+
+ if (!is_device_path(p->what))
+ return 0;
+
+ if (path_equal(m->where, "/"))
+ return 0;
+
+ r = unit_add_node_link(UNIT(m), p->what, false);
+ if (r < 0)
+ return r;
+
+ if (p->passno > 0 &&
+ UNIT(m)->manager->running_as == SYSTEMD_SYSTEM) {
+ char *name;
+ Unit *fsck;
+ /* Let's add in the fsck service */
+
+ /* aka SPECIAL_FSCK_SERVICE */
+ name = unit_name_from_path_instance("systemd-fsck", p->what, ".service");
+ if (!name)
+ return -ENOMEM;
+
+ r = manager_load_unit_prepare(UNIT(m)->manager, name, NULL, NULL, &fsck);
+ if (r < 0) {
+ log_warning_unit(name,
+ "Failed to prepare unit %s: %s", name, strerror(-r));
+ free(name);
+ return r;
+ }
+ free(name);
+
+ SERVICE(fsck)->fsck_passno = p->passno;
+
+ r = unit_add_two_dependencies(UNIT(m), UNIT_AFTER, UNIT_REQUIRES, fsck, true);
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static int mount_add_quota_links(Mount *m) {
+ int r;
+ MountParameters *p;
+
+ assert(m);
+
+ if (UNIT(m)->manager->running_as != SYSTEMD_SYSTEM)
+ return 0;
+
+ p = get_mount_parameters_fragment(m);
+ if (!p)
+ return 0;
+
+ if (!needs_quota(p))
+ return 0;
+
+ r = unit_add_two_dependencies_by_name(UNIT(m), UNIT_BEFORE, UNIT_WANTS, SPECIAL_QUOTACHECK_SERVICE, NULL, true);
+ if (r < 0)
+ return r;
+
+ r = unit_add_two_dependencies_by_name(UNIT(m), UNIT_BEFORE, UNIT_WANTS, SPECIAL_QUOTAON_SERVICE, NULL, true);
+ if (r < 0)
+ return r;
+
+ return 0;
+}
+
+static int mount_add_default_dependencies(Mount *m) {
+ const char *after, *after2, *online;
+ MountParameters *p;
+ int r;
+
+ assert(m);
+
+ if (UNIT(m)->manager->running_as != SYSTEMD_SYSTEM)
+ return 0;
+
+ p = get_mount_parameters(m);
+
+ if (!p)
+ return 0;
+
+ if (path_equal(m->where, "/"))
+ return 0;
+
+ if (mount_is_network(p)) {
+ after = SPECIAL_REMOTE_FS_PRE_TARGET;
+ after2 = SPECIAL_NETWORK_TARGET;
+ online = SPECIAL_NETWORK_ONLINE_TARGET;
+ } else {
+ after = SPECIAL_LOCAL_FS_PRE_TARGET;
+ after2 = NULL;
+ online = NULL;
+ }
+
+ r = unit_add_dependency_by_name(UNIT(m), UNIT_AFTER, after, NULL, true);
+ if (r < 0)
+ return r;
+
+ if (after2) {
+ r = unit_add_dependency_by_name(UNIT(m), UNIT_AFTER, after2, NULL, true);
+ if (r < 0)
+ return r;
+ }
+
+ if (online) {
+ r = unit_add_two_dependencies_by_name(UNIT(m), UNIT_WANTS, UNIT_AFTER, online, NULL, true);
+ if (r < 0)
+ return r;
+ }
+
+ r = unit_add_two_dependencies_by_name(UNIT(m), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_UMOUNT_TARGET, NULL, true);
+ if (r < 0)
+ return r;
+
+ return 0;
+}
+
+static int mount_fix_timeouts(Mount *m) {
+ MountParameters *p;
+ const char *timeout = NULL;
+ Unit *other;
+ Iterator i;
+ usec_t u;
+ char *t;
+ int r;
+
+ assert(m);
+
+ p = get_mount_parameters_fragment(m);
+ if (!p)
+ return 0;
+
+ /* Allow configuration how long we wait for a device that
+ * backs a mount point to show up. This is useful to support
+ * endless device timeouts for devices that show up only after
+ * user input, like crypto devices. */
+
+ if ((timeout = mount_test_option(p->options, "comment=systemd.device-timeout")))
+ timeout += 31;
+ else if ((timeout = mount_test_option(p->options, "x-systemd.device-timeout")))
+ timeout += 25;
+ else
+ return 0;
+
+ t = strndup(timeout, strcspn(timeout, ",;" WHITESPACE));
+ if (!t)
+ return -ENOMEM;
+
+ r = parse_sec(t, &u);
+ free(t);
+
+ if (r < 0) {
+ log_warning_unit(UNIT(m)->id,
+ "Failed to parse timeout for %s, ignoring: %s",
+ m->where, timeout);
+ return r;
+ }
+
+ SET_FOREACH(other, UNIT(m)->dependencies[UNIT_AFTER], i) {
+ if (other->type != UNIT_DEVICE)
+ continue;
+
+ other->job_timeout = u;
+ }
+
+ return 0;
+}
+
+static int mount_verify(Mount *m) {
+ bool b;
+ char *e;
+ assert(m);
+
+ if (UNIT(m)->load_state != UNIT_LOADED)
+ return 0;
+
+ if (!m->from_fragment && !m->from_proc_self_mountinfo)
+ return -ENOENT;
+
+ if (!(e = unit_name_from_path(m->where, ".mount")))
+ return -ENOMEM;
+
+ b = unit_has_name(UNIT(m), e);
+ free(e);
+
+ if (!b) {
+ log_error_unit(UNIT(m)->id,
+ "%s's Where setting doesn't match unit name. Refusing.",
+ UNIT(m)->id);
+ return -EINVAL;
+ }
+
+ if (mount_point_is_api(m->where) || mount_point_ignore(m->where)) {
+ log_error_unit(UNIT(m)->id,
+ "Cannot create mount unit for API file system %s. Refusing.",
+ m->where);
+ return -EINVAL;
+ }
+
+ if (UNIT(m)->fragment_path && !m->parameters_fragment.what) {
+ log_error_unit(UNIT(m)->id,
+ "%s's What setting is missing. Refusing.", UNIT(m)->id);
+ return -EBADMSG;
+ }
+
+ if (m->exec_context.pam_name && m->kill_context.kill_mode != KILL_CONTROL_GROUP) {
+ log_error_unit(UNIT(m)->id,
+ "%s has PAM enabled. Kill mode must be set to control-group'. Refusing.",
+ UNIT(m)->id);
+ return -EINVAL;
+ }
+
+ return 0;
+}
+
+static int mount_add_extras(Mount *m) {
+ Unit *u = UNIT(m);
+ int r;
+
+ if (UNIT(m)->fragment_path)
+ m->from_fragment = true;
+
+ if (!m->where) {
+ m->where = unit_name_to_path(u->id);
+ if (!m->where)
+ return -ENOMEM;
+ }
+
+ path_kill_slashes(m->where);
+
+ r = unit_add_exec_dependencies(u, &m->exec_context);
+ if (r < 0)
+ return r;
+
+ if (!UNIT(m)->description) {
+ r = unit_set_description(u, m->where);
+ if (r < 0)
+ return r;
+ }
+
+ r = mount_add_device_links(m);
+ if (r < 0)
+ return r;
+
+ r = mount_add_mount_links(m);
+ if (r < 0)
+ return r;
+
+ r = mount_add_socket_links(m);
+ if (r < 0)
+ return r;
+
+ r = mount_add_swap_links(m);
+ if (r < 0)
+ return r;
+
+ r = mount_add_path_links(m);
+ if (r < 0)
+ return r;
+
+ r = mount_add_requires_mounts_links(m);
+ if (r < 0)
+ return r;
+
+ r = mount_add_automount_links(m);
+ if (r < 0)
+ return r;
+
+ r = mount_add_quota_links(m);
+ if (r < 0)
+ return r;
+
+ if (UNIT(m)->default_dependencies) {
+ r = mount_add_default_dependencies(m);
+ if (r < 0)
+ return r;
+ }
+
+ r = unit_add_default_cgroups(u);
+ if (r < 0)
+ return r;
+
+ r = mount_fix_timeouts(m);
+ if (r < 0)
+ return r;
+
+ return 0;
+}
+
+static int mount_load(Unit *u) {
+ Mount *m = MOUNT(u);
+ int r;
+
+ assert(u);
+ assert(u->load_state == UNIT_STUB);
+
+ if (m->from_proc_self_mountinfo)
+ r = unit_load_fragment_and_dropin_optional(u);
+ else
+ r = unit_load_fragment_and_dropin(u);
+
+ if (r < 0)
+ return r;
+
+ /* This is a new unit? Then let's add in some extras */
+ if (u->load_state == UNIT_LOADED) {
+ r = mount_add_extras(m);
+ if (r < 0)
+ return r;
+
+ r = unit_exec_context_defaults(u, &m->exec_context);
+ if (r < 0)
+ return r;
+ }
+
+ return mount_verify(m);
+}
+
+static int mount_notify_automount(Mount *m, int status) {
+ Unit *p;
+ int r;
+ Iterator i;
+
+ assert(m);
+
+ SET_FOREACH(p, UNIT(m)->dependencies[UNIT_TRIGGERED_BY], i)
+ if (p->type == UNIT_AUTOMOUNT) {
+ r = automount_send_ready(AUTOMOUNT(p), status);
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static void mount_set_state(Mount *m, MountState state) {
+ MountState old_state;
+ assert(m);
+
+ old_state = m->state;
+ m->state = state;
+
+ if (state != MOUNT_MOUNTING &&
+ state != MOUNT_MOUNTING_DONE &&
+ state != MOUNT_REMOUNTING &&
+ state != MOUNT_UNMOUNTING &&
+ state != MOUNT_MOUNTING_SIGTERM &&
+ state != MOUNT_MOUNTING_SIGKILL &&
+ state != MOUNT_UNMOUNTING_SIGTERM &&
+ state != MOUNT_UNMOUNTING_SIGKILL &&
+ state != MOUNT_REMOUNTING_SIGTERM &&
+ state != MOUNT_REMOUNTING_SIGKILL) {
+ unit_unwatch_timer(UNIT(m), &m->timer_watch);
+ mount_unwatch_control_pid(m);
+ m->control_command = NULL;
+ m->control_command_id = _MOUNT_EXEC_COMMAND_INVALID;
+ }
+
+ if (state == MOUNT_MOUNTED ||
+ state == MOUNT_REMOUNTING)
+ mount_notify_automount(m, 0);
+ else if (state == MOUNT_DEAD ||
+ state == MOUNT_UNMOUNTING ||
+ state == MOUNT_MOUNTING_SIGTERM ||
+ state == MOUNT_MOUNTING_SIGKILL ||
+ state == MOUNT_REMOUNTING_SIGTERM ||
+ state == MOUNT_REMOUNTING_SIGKILL ||
+ state == MOUNT_UNMOUNTING_SIGTERM ||
+ state == MOUNT_UNMOUNTING_SIGKILL ||
+ state == MOUNT_FAILED) {
+ if (state != old_state)
+ mount_notify_automount(m, -ENODEV);
+ }
+
+ if (state != old_state)
+ log_debug_unit(UNIT(m)->id,
+ "%s changed %s -> %s",
+ UNIT(m)->id,
+ mount_state_to_string(old_state),
+ mount_state_to_string(state));
+
+ unit_notify(UNIT(m), state_translation_table[old_state], state_translation_table[state], m->reload_result == MOUNT_SUCCESS);
+ m->reload_result = MOUNT_SUCCESS;
+}
+
+static int mount_coldplug(Unit *u) {
+ Mount *m = MOUNT(u);
+ MountState new_state = MOUNT_DEAD;
+ int r;
+
+ assert(m);
+ assert(m->state == MOUNT_DEAD);
+
+ if (m->deserialized_state != m->state)
+ new_state = m->deserialized_state;
+ else if (m->from_proc_self_mountinfo)
+ new_state = MOUNT_MOUNTED;
+
+ if (new_state != m->state) {
+
+ if (new_state == MOUNT_MOUNTING ||
+ new_state == MOUNT_MOUNTING_DONE ||
+ new_state == MOUNT_REMOUNTING ||
+ new_state == MOUNT_UNMOUNTING ||
+ new_state == MOUNT_MOUNTING_SIGTERM ||
+ new_state == MOUNT_MOUNTING_SIGKILL ||
+ new_state == MOUNT_UNMOUNTING_SIGTERM ||
+ new_state == MOUNT_UNMOUNTING_SIGKILL ||
+ new_state == MOUNT_REMOUNTING_SIGTERM ||
+ new_state == MOUNT_REMOUNTING_SIGKILL) {
+
+ if (m->control_pid <= 0)
+ return -EBADMSG;
+
+ r = unit_watch_pid(UNIT(m), m->control_pid);
+ if (r < 0)
+ return r;
+
+ r = unit_watch_timer(UNIT(m), CLOCK_MONOTONIC, true, m->timeout_usec, &m->timer_watch);
+ if (r < 0)
+ return r;
+ }
+
+ mount_set_state(m, new_state);
+ }
+
+ return 0;
+}
+
+static void mount_dump(Unit *u, FILE *f, const char *prefix) {
+ Mount *m = MOUNT(u);
+ MountParameters *p;
+
+ assert(m);
+ assert(f);
+
+ p = get_mount_parameters(m);
+
+ fprintf(f,
+ "%sMount State: %s\n"
+ "%sResult: %s\n"
+ "%sWhere: %s\n"
+ "%sWhat: %s\n"
+ "%sFile System Type: %s\n"
+ "%sOptions: %s\n"
+ "%sFrom /proc/self/mountinfo: %s\n"
+ "%sFrom fragment: %s\n"
+ "%sDirectoryMode: %04o\n",
+ prefix, mount_state_to_string(m->state),
+ prefix, mount_result_to_string(m->result),
+ prefix, m->where,
+ prefix, strna(p->what),
+ prefix, strna(p->fstype),
+ prefix, strna(p->options),
+ prefix, yes_no(m->from_proc_self_mountinfo),
+ prefix, yes_no(m->from_fragment),
+ prefix, m->directory_mode);
+
+ if (m->control_pid > 0)
+ fprintf(f,
+ "%sControl PID: %lu\n",
+ prefix, (unsigned long) m->control_pid);
+
+ exec_context_dump(&m->exec_context, f, prefix);
+ kill_context_dump(&m->kill_context, f, prefix);
+}
+
+static int mount_spawn(Mount *m, ExecCommand *c, pid_t *_pid) {
+ pid_t pid;
+ int r;
+
+ assert(m);
+ assert(c);
+ assert(_pid);
+
+ r = unit_watch_timer(UNIT(m), CLOCK_MONOTONIC, true, m->timeout_usec, &m->timer_watch);
+ if (r < 0)
+ goto fail;
+
+ if ((r = exec_spawn(c,
+ NULL,
+ &m->exec_context,
+ NULL, 0,
+ UNIT(m)->manager->environment,
+ true,
+ true,
+ true,
+ UNIT(m)->manager->confirm_spawn,
+ UNIT(m)->cgroup_bondings,
+ UNIT(m)->cgroup_attributes,
+ NULL,
+ UNIT(m)->id,
+ NULL,
+ &pid)) < 0)
+ goto fail;
+
+ if ((r = unit_watch_pid(UNIT(m), pid)) < 0)
+ /* FIXME: we need to do something here */
+ goto fail;
+
+ *_pid = pid;
+
+ return 0;
+
+fail:
+ unit_unwatch_timer(UNIT(m), &m->timer_watch);
+
+ return r;
+}
+
+static void mount_enter_dead(Mount *m, MountResult f) {
+ assert(m);
+
+ if (f != MOUNT_SUCCESS)
+ m->result = f;
+
+ exec_context_tmp_dirs_done(&m->exec_context);
+ mount_set_state(m, m->result != MOUNT_SUCCESS ? MOUNT_FAILED : MOUNT_DEAD);
+}
+
+static void mount_enter_mounted(Mount *m, MountResult f) {
+ assert(m);
+
+ if (f != MOUNT_SUCCESS)
+ m->result = f;
+
+ mount_set_state(m, MOUNT_MOUNTED);
+}
+
+static void mount_enter_signal(Mount *m, MountState state, MountResult f) {
+ int r;
+
+ assert(m);
+
+ if (f != MOUNT_SUCCESS)
+ m->result = f;
+
+ r = unit_kill_context(
+ UNIT(m),
+ &m->kill_context,
+ state != MOUNT_MOUNTING_SIGTERM && state != MOUNT_UNMOUNTING_SIGTERM && state != MOUNT_REMOUNTING_SIGTERM,
+ -1,
+ m->control_pid,
+ false);
+ if (r < 0)
+ goto fail;
+
+ if (r > 0) {
+ r = unit_watch_timer(UNIT(m), CLOCK_MONOTONIC, true, m->timeout_usec, &m->timer_watch);
+ if (r < 0)
+ goto fail;
+
+ mount_set_state(m, state);
+ } else if (state == MOUNT_REMOUNTING_SIGTERM || state == MOUNT_REMOUNTING_SIGKILL)
+ mount_enter_mounted(m, MOUNT_SUCCESS);
+ else
+ mount_enter_dead(m, MOUNT_SUCCESS);
+
+ return;
+
+fail:
+ log_warning_unit(UNIT(m)->id,
+ "%s failed to kill processes: %s", UNIT(m)->id, strerror(-r));
+
+ if (state == MOUNT_REMOUNTING_SIGTERM || state == MOUNT_REMOUNTING_SIGKILL)
+ mount_enter_mounted(m, MOUNT_FAILURE_RESOURCES);
+ else
+ mount_enter_dead(m, MOUNT_FAILURE_RESOURCES);
+}
+
+void warn_if_dir_nonempty(const char *unit, const char* where) {
+ assert(unit);
+ assert(where);
+
+ if (dir_is_empty(where) > 0)
+ return;
+
+ log_struct_unit(LOG_NOTICE,
+ unit,
+ "MESSAGE=%s: Directory %s to mount over is not empty, mounting anyway.",
+ unit, where,
+ "WHERE=%s", where,
+ MESSAGE_ID(SD_MESSAGE_OVERMOUNTING),
+ NULL);
+}
+
+static void mount_enter_unmounting(Mount *m) {
+ int r;
+
+ assert(m);
+
+ m->control_command_id = MOUNT_EXEC_UNMOUNT;
+ m->control_command = m->exec_command + MOUNT_EXEC_UNMOUNT;
+
+ if ((r = exec_command_set(
+ m->control_command,
+ "/bin/umount",
+ m->where,
+ NULL)) < 0)
+ goto fail;
+
+ mount_unwatch_control_pid(m);
+
+ if ((r = mount_spawn(m, m->control_command, &m->control_pid)) < 0)
+ goto fail;
+
+ mount_set_state(m, MOUNT_UNMOUNTING);
+
+ return;
+
+fail:
+ log_warning_unit(UNIT(m)->id,
+ "%s failed to run 'umount' task: %s",
+ UNIT(m)->id, strerror(-r));
+ mount_enter_mounted(m, MOUNT_FAILURE_RESOURCES);
+}
+
+static void mount_enter_mounting(Mount *m) {
+ int r;
+ MountParameters *p;
+
+ assert(m);
+
+ m->control_command_id = MOUNT_EXEC_MOUNT;
+ m->control_command = m->exec_command + MOUNT_EXEC_MOUNT;
+
+ mkdir_p_label(m->where, m->directory_mode);
+
+ warn_if_dir_nonempty(m->meta.id, m->where);
+
+ /* Create the source directory for bind-mounts if needed */
+ p = get_mount_parameters_fragment(m);
+ if (p && mount_is_bind(p))
+ mkdir_p_label(p->what, m->directory_mode);
+
+ if (m->from_fragment)
+ r = exec_command_set(
+ m->control_command,
+ "/bin/mount",
+ m->parameters_fragment.what,
+ m->where,
+ "-t", m->parameters_fragment.fstype ? m->parameters_fragment.fstype : "auto",
+ m->parameters_fragment.options ? "-o" : NULL, m->parameters_fragment.options,
+ NULL);
+ else
+ r = -ENOENT;
+
+ if (r < 0)
+ goto fail;
+
+ mount_unwatch_control_pid(m);
+
+ r = mount_spawn(m, m->control_command, &m->control_pid);
+ if (r < 0)
+ goto fail;
+
+ mount_set_state(m, MOUNT_MOUNTING);
+
+ return;
+
+fail:
+ log_warning_unit(UNIT(m)->id,
+ "%s failed to run 'mount' task: %s",
+ UNIT(m)->id, strerror(-r));
+ mount_enter_dead(m, MOUNT_FAILURE_RESOURCES);
+}
+
+static void mount_enter_mounting_done(Mount *m) {
+ assert(m);
+
+ mount_set_state(m, MOUNT_MOUNTING_DONE);
+}
+
+static void mount_enter_remounting(Mount *m) {
+ int r;
+
+ assert(m);
+
+ m->control_command_id = MOUNT_EXEC_REMOUNT;
+ m->control_command = m->exec_command + MOUNT_EXEC_REMOUNT;
+
+ if (m->from_fragment) {
+ char *buf = NULL;
+ const char *o;
+
+ if (m->parameters_fragment.options) {
+ if (!(buf = strappend("remount,", m->parameters_fragment.options))) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ o = buf;
+ } else
+ o = "remount";
+
+ r = exec_command_set(
+ m->control_command,
+ "/bin/mount",
+ m->parameters_fragment.what,
+ m->where,
+ "-t", m->parameters_fragment.fstype ? m->parameters_fragment.fstype : "auto",
+ "-o", o,
+ NULL);
+
+ free(buf);
+ } else
+ r = -ENOENT;
+
+ if (r < 0)
+ goto fail;
+
+ mount_unwatch_control_pid(m);
+
+ if ((r = mount_spawn(m, m->control_command, &m->control_pid)) < 0)
+ goto fail;
+
+ mount_set_state(m, MOUNT_REMOUNTING);
+
+ return;
+
+fail:
+ log_warning_unit(UNIT(m)->id,
+ "%s failed to run 'remount' task: %s",
+ UNIT(m)->id, strerror(-r));
+ m->reload_result = MOUNT_FAILURE_RESOURCES;
+ mount_enter_mounted(m, MOUNT_SUCCESS);
+}
+
+static int mount_start(Unit *u) {
+ Mount *m = MOUNT(u);
+
+ assert(m);
+
+ /* We cannot fulfill this request right now, try again later
+ * please! */
+ if (m->state == MOUNT_UNMOUNTING ||
+ m->state == MOUNT_UNMOUNTING_SIGTERM ||
+ m->state == MOUNT_UNMOUNTING_SIGKILL ||
+ m->state == MOUNT_MOUNTING_SIGTERM ||
+ m->state == MOUNT_MOUNTING_SIGKILL)
+ return -EAGAIN;
+
+ /* Already on it! */
+ if (m->state == MOUNT_MOUNTING)
+ return 0;
+
+ assert(m->state == MOUNT_DEAD || m->state == MOUNT_FAILED);
+
+ m->result = MOUNT_SUCCESS;
+ m->reload_result = MOUNT_SUCCESS;
+
+ mount_enter_mounting(m);
+ return 0;
+}
+
+static int mount_stop(Unit *u) {
+ Mount *m = MOUNT(u);
+
+ assert(m);
+
+ /* Already on it */
+ if (m->state == MOUNT_UNMOUNTING ||
+ m->state == MOUNT_UNMOUNTING_SIGKILL ||
+ m->state == MOUNT_UNMOUNTING_SIGTERM ||
+ m->state == MOUNT_MOUNTING_SIGTERM ||
+ m->state == MOUNT_MOUNTING_SIGKILL)
+ return 0;
+
+ assert(m->state == MOUNT_MOUNTING ||
+ m->state == MOUNT_MOUNTING_DONE ||
+ m->state == MOUNT_MOUNTED ||
+ m->state == MOUNT_REMOUNTING ||
+ m->state == MOUNT_REMOUNTING_SIGTERM ||
+ m->state == MOUNT_REMOUNTING_SIGKILL);
+
+ mount_enter_unmounting(m);
+ return 0;
+}
+
+static int mount_reload(Unit *u) {
+ Mount *m = MOUNT(u);
+
+ assert(m);
+
+ if (m->state == MOUNT_MOUNTING_DONE)
+ return -EAGAIN;
+
+ assert(m->state == MOUNT_MOUNTED);
+
+ mount_enter_remounting(m);
+ return 0;
+}
+
+static int mount_serialize(Unit *u, FILE *f, FDSet *fds) {
+ Mount *m = MOUNT(u);
+
+ assert(m);
+ assert(f);
+ assert(fds);
+
+ unit_serialize_item(u, f, "state", mount_state_to_string(m->state));
+ unit_serialize_item(u, f, "result", mount_result_to_string(m->result));
+ unit_serialize_item(u, f, "reload-result", mount_result_to_string(m->reload_result));
+
+ if (m->control_pid > 0)
+ unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) m->control_pid);
+
+ if (m->control_command_id >= 0)
+ unit_serialize_item(u, f, "control-command", mount_exec_command_to_string(m->control_command_id));
+
+ exec_context_serialize(&m->exec_context, UNIT(m), f);
+
+ return 0;
+}
+
+static int mount_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
+ Mount *m = MOUNT(u);
+
+ assert(u);
+ assert(key);
+ assert(value);
+ assert(fds);
+
+ if (streq(key, "state")) {
+ MountState state;
+
+ if ((state = mount_state_from_string(value)) < 0)
+ log_debug_unit(u->id, "Failed to parse state value %s", value);
+ else
+ m->deserialized_state = state;
+ } else if (streq(key, "result")) {
+ MountResult f;
+
+ f = mount_result_from_string(value);
+ if (f < 0)
+ log_debug_unit(UNIT(m)->id,
+ "Failed to parse result value %s", value);
+ else if (f != MOUNT_SUCCESS)
+ m->result = f;
+
+ } else if (streq(key, "reload-result")) {
+ MountResult f;
+
+ f = mount_result_from_string(value);
+ if (f < 0)
+ log_debug_unit(UNIT(m)->id,
+ "Failed to parse reload result value %s", value);
+ else if (f != MOUNT_SUCCESS)
+ m->reload_result = f;
+
+ } else if (streq(key, "control-pid")) {
+ pid_t pid;
+
+ if (parse_pid(value, &pid) < 0)
+ log_debug_unit(UNIT(m)->id,
+ "Failed to parse control-pid value %s", value);
+ else
+ m->control_pid = pid;
+ } else if (streq(key, "control-command")) {
+ MountExecCommand id;
+
+ if ((id = mount_exec_command_from_string(value)) < 0)
+ log_debug_unit(UNIT(m)->id,
+ "Failed to parse exec-command value %s", value);
+ else {
+ m->control_command_id = id;
+ m->control_command = m->exec_command + id;
+ }
+ } else if (streq(key, "tmp-dir")) {
+ char *t;
+
+ t = strdup(value);
+ if (!t)
+ return log_oom();
+
+ m->exec_context.tmp_dir = t;
+ } else if (streq(key, "var-tmp-dir")) {
+ char *t;
+
+ t = strdup(value);
+ if (!t)
+ return log_oom();
+
+ m->exec_context.var_tmp_dir = t;
+ } else
+ log_debug_unit(UNIT(m)->id,
+ "Unknown serialization key '%s'", key);
+
+ return 0;
+}
+
+_pure_ static UnitActiveState mount_active_state(Unit *u) {
+ assert(u);
+
+ return state_translation_table[MOUNT(u)->state];
+}
+
+_pure_ static const char *mount_sub_state_to_string(Unit *u) {
+ assert(u);
+
+ return mount_state_to_string(MOUNT(u)->state);
+}
+
+_pure_ static bool mount_check_gc(Unit *u) {
+ Mount *m = MOUNT(u);
+
+ assert(m);
+
+ return m->from_proc_self_mountinfo;
+}
+
+static void mount_sigchld_event(Unit *u, pid_t pid, int code, int status) {
+ Mount *m = MOUNT(u);
+ MountResult f;
+
+ assert(m);
+ assert(pid >= 0);
+
+ if (pid != m->control_pid)
+ return;
+
+ m->control_pid = 0;
+
+ if (is_clean_exit(code, status, NULL))
+ f = MOUNT_SUCCESS;
+ else if (code == CLD_EXITED)
+ f = MOUNT_FAILURE_EXIT_CODE;
+ else if (code == CLD_KILLED)
+ f = MOUNT_FAILURE_SIGNAL;
+ else if (code == CLD_DUMPED)
+ f = MOUNT_FAILURE_CORE_DUMP;
+ else
+ assert_not_reached("Unknown code");
+
+ if (f != MOUNT_SUCCESS)
+ m->result = f;
+
+ if (m->control_command) {
+ exec_status_exit(&m->control_command->exec_status, &m->exec_context, pid, code, status);
+
+ m->control_command = NULL;
+ m->control_command_id = _MOUNT_EXEC_COMMAND_INVALID;
+ }
+
+ log_full_unit(f == MOUNT_SUCCESS ? LOG_DEBUG : LOG_NOTICE, u->id,
+ "%s mount process exited, code=%s status=%i",
+ u->id, sigchld_code_to_string(code), status);
+
+ /* Note that mount(8) returning and the kernel sending us a
+ * mount table change event might happen out-of-order. If an
+ * operation succeed we assume the kernel will follow soon too
+ * and already change into the resulting state. If it fails
+ * we check if the kernel still knows about the mount. and
+ * change state accordingly. */
+
+ switch (m->state) {
+
+ case MOUNT_MOUNTING:
+ case MOUNT_MOUNTING_DONE:
+ case MOUNT_MOUNTING_SIGKILL:
+ case MOUNT_MOUNTING_SIGTERM:
+
+ if (f == MOUNT_SUCCESS)
+ mount_enter_mounted(m, f);
+ else if (m->from_proc_self_mountinfo)
+ mount_enter_mounted(m, f);
+ else
+ mount_enter_dead(m, f);
+ break;
+
+ case MOUNT_REMOUNTING:
+ case MOUNT_REMOUNTING_SIGKILL:
+ case MOUNT_REMOUNTING_SIGTERM:
+
+ m->reload_result = f;
+ if (m->from_proc_self_mountinfo)
+ mount_enter_mounted(m, MOUNT_SUCCESS);
+ else
+ mount_enter_dead(m, MOUNT_SUCCESS);
+
+ break;
+
+ case MOUNT_UNMOUNTING:
+ case MOUNT_UNMOUNTING_SIGKILL:
+ case MOUNT_UNMOUNTING_SIGTERM:
+
+ if (f == MOUNT_SUCCESS)
+ mount_enter_dead(m, f);
+ else if (m->from_proc_self_mountinfo)
+ mount_enter_mounted(m, f);
+ else
+ mount_enter_dead(m, f);
+ break;
+
+ default:
+ assert_not_reached("Uh, control process died at wrong time.");
+ }
+
+ /* Notify clients about changed exit status */
+ unit_add_to_dbus_queue(u);
+}
+
+static void mount_timer_event(Unit *u, uint64_t elapsed, Watch *w) {
+ Mount *m = MOUNT(u);
+
+ assert(m);
+ assert(elapsed == 1);
+ assert(w == &m->timer_watch);
+
+ switch (m->state) {
+
+ case MOUNT_MOUNTING:
+ case MOUNT_MOUNTING_DONE:
+ log_warning_unit(u->id,
+ "%s mounting timed out. Stopping.", u->id);
+ mount_enter_signal(m, MOUNT_MOUNTING_SIGTERM, MOUNT_FAILURE_TIMEOUT);
+ break;
+
+ case MOUNT_REMOUNTING:
+ log_warning_unit(u->id,
+ "%s remounting timed out. Stopping.", u->id);
+ m->reload_result = MOUNT_FAILURE_TIMEOUT;
+ mount_enter_mounted(m, MOUNT_SUCCESS);
+ break;
+
+ case MOUNT_UNMOUNTING:
+ log_warning_unit(u->id,
+ "%s unmounting timed out. Stopping.", u->id);
+ mount_enter_signal(m, MOUNT_UNMOUNTING_SIGTERM, MOUNT_FAILURE_TIMEOUT);
+ break;
+
+ case MOUNT_MOUNTING_SIGTERM:
+ if (m->kill_context.send_sigkill) {
+ log_warning_unit(u->id,
+ "%s mounting timed out. Killing.", u->id);
+ mount_enter_signal(m, MOUNT_MOUNTING_SIGKILL, MOUNT_FAILURE_TIMEOUT);
+ } else {
+ log_warning_unit(u->id,
+ "%s mounting timed out. Skipping SIGKILL. Ignoring.",
+ u->id);
+
+ if (m->from_proc_self_mountinfo)
+ mount_enter_mounted(m, MOUNT_FAILURE_TIMEOUT);
+ else
+ mount_enter_dead(m, MOUNT_FAILURE_TIMEOUT);
+ }
+ break;
+
+ case MOUNT_REMOUNTING_SIGTERM:
+ if (m->kill_context.send_sigkill) {
+ log_warning_unit(u->id,
+ "%s remounting timed out. Killing.", u->id);
+ mount_enter_signal(m, MOUNT_REMOUNTING_SIGKILL, MOUNT_FAILURE_TIMEOUT);
+ } else {
+ log_warning_unit(u->id,
+ "%s remounting timed out. Skipping SIGKILL. Ignoring.",
+ u->id);
+
+ if (m->from_proc_self_mountinfo)
+ mount_enter_mounted(m, MOUNT_FAILURE_TIMEOUT);
+ else
+ mount_enter_dead(m, MOUNT_FAILURE_TIMEOUT);
+ }
+ break;
+
+ case MOUNT_UNMOUNTING_SIGTERM:
+ if (m->kill_context.send_sigkill) {
+ log_warning_unit(u->id,
+ "%s unmounting timed out. Killing.", u->id);
+ mount_enter_signal(m, MOUNT_UNMOUNTING_SIGKILL, MOUNT_FAILURE_TIMEOUT);
+ } else {
+ log_warning_unit(u->id,
+ "%s unmounting timed out. Skipping SIGKILL. Ignoring.",
+ u->id);
+
+ if (m->from_proc_self_mountinfo)
+ mount_enter_mounted(m, MOUNT_FAILURE_TIMEOUT);
+ else
+ mount_enter_dead(m, MOUNT_FAILURE_TIMEOUT);
+ }
+ break;
+
+ case MOUNT_MOUNTING_SIGKILL:
+ case MOUNT_REMOUNTING_SIGKILL:
+ case MOUNT_UNMOUNTING_SIGKILL:
+ log_warning_unit(u->id,
+ "%s mount process still around after SIGKILL. Ignoring.",
+ u->id);
+
+ if (m->from_proc_self_mountinfo)
+ mount_enter_mounted(m, MOUNT_FAILURE_TIMEOUT);
+ else
+ mount_enter_dead(m, MOUNT_FAILURE_TIMEOUT);
+ break;
+
+ default:
+ assert_not_reached("Timeout at wrong time.");
+ }
+}
+
+static int mount_add_one(
+ Manager *m,
+ const char *what,
+ const char *where,
+ const char *options,
+ const char *fstype,
+ int passno,
+ bool set_flags) {
+ int r;
+ Unit *u;
+ bool delete;
+ char *e, *w = NULL, *o = NULL, *f = NULL;
+ MountParameters *p;
+ bool load_extras = false;
+
+ assert(m);
+ assert(what);
+ assert(where);
+ assert(options);
+ assert(fstype);
+
+ /* Ignore API mount points. They should never be referenced in
+ * dependencies ever. */
+ if (mount_point_is_api(where) || mount_point_ignore(where))
+ return 0;
+
+ if (streq(fstype, "autofs"))
+ return 0;
+
+ /* probably some kind of swap, ignore */
+ if (!is_path(where))
+ return 0;
+
+ e = unit_name_from_path(where, ".mount");
+ if (!e)
+ return -ENOMEM;
+
+ u = manager_get_unit(m, e);
+ if (!u) {
+ delete = true;
+
+ u = unit_new(m, sizeof(Mount));
+ if (!u) {
+ free(e);
+ return -ENOMEM;
+ }
+
+ r = unit_add_name(u, e);
+ free(e);
+
+ if (r < 0)
+ goto fail;
+
+ MOUNT(u)->where = strdup(where);
+ if (!MOUNT(u)->where) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ u->source_path = strdup("/proc/self/mountinfo");
+ if (!u->source_path) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ r = unit_add_dependency_by_name(u, UNIT_BEFORE, SPECIAL_LOCAL_FS_TARGET, NULL, true);
+ if (r < 0)
+ goto fail;
+
+ r = unit_add_dependency_by_name(u, UNIT_CONFLICTS, SPECIAL_UMOUNT_TARGET, NULL, true);
+ if (r < 0)
+ goto fail;
+
+ unit_add_to_load_queue(u);
+ } else {
+ delete = false;
+ free(e);
+
+ if (!MOUNT(u)->where) {
+ MOUNT(u)->where = strdup(where);
+ if (!MOUNT(u)->where) {
+ r = -ENOMEM;
+ goto fail;
+ }
+ }
+
+ if (u->load_state == UNIT_ERROR) {
+ u->load_state = UNIT_LOADED;
+ u->load_error = 0;
+
+ /* Load in the extras later on, after we
+ * finished initialization of the unit */
+ load_extras = true;
+ }
+ }
+
+ if (!(w = strdup(what)) ||
+ !(o = strdup(options)) ||
+ !(f = strdup(fstype))) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ p = &MOUNT(u)->parameters_proc_self_mountinfo;
+ if (set_flags) {
+ MOUNT(u)->is_mounted = true;
+ MOUNT(u)->just_mounted = !MOUNT(u)->from_proc_self_mountinfo;
+ MOUNT(u)->just_changed = !streq_ptr(p->options, o);
+ }
+
+ MOUNT(u)->from_proc_self_mountinfo = true;
+
+ free(p->what);
+ p->what = w;
+
+ free(p->options);
+ p->options = o;
+
+ free(p->fstype);
+ p->fstype = f;
+
+ p->passno = passno;
+
+ if (load_extras) {
+ r = mount_add_extras(MOUNT(u));
+ if (r < 0)
+ goto fail;
+ }
+
+ unit_add_to_dbus_queue(u);
+
+ return 0;
+
+fail:
+ free(w);
+ free(o);
+ free(f);
+
+ if (delete && u)
+ unit_free(u);
+
+ return r;
+}
+
+static int mount_load_proc_self_mountinfo(Manager *m, bool set_flags) {
+ int r = 0;
+ unsigned i;
+ char *device, *path, *options, *options2, *fstype, *d, *p, *o;
+
+ assert(m);
+
+ rewind(m->proc_self_mountinfo);
+
+ for (i = 1;; i++) {
+ int k;
+
+ device = path = options = options2 = fstype = d = p = o = NULL;
+
+ if ((k = fscanf(m->proc_self_mountinfo,
+ "%*s " /* (1) mount id */
+ "%*s " /* (2) parent id */
+ "%*s " /* (3) major:minor */
+ "%*s " /* (4) root */
+ "%ms " /* (5) mount point */
+ "%ms" /* (6) mount options */
+ "%*[^-]" /* (7) optional fields */
+ "- " /* (8) separator */
+ "%ms " /* (9) file system type */
+ "%ms" /* (10) mount source */
+ "%ms" /* (11) mount options 2 */
+ "%*[^\n]", /* some rubbish at the end */
+ &path,
+ &options,
+ &fstype,
+ &device,
+ &options2)) != 5) {
+
+ if (k == EOF)
+ break;
+
+ log_warning("Failed to parse /proc/self/mountinfo:%u.", i);
+ goto clean_up;
+ }
+
+ o = strjoin(options, ",", options2, NULL);
+ if (!o) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ if (!(d = cunescape(device)) ||
+ !(p = cunescape(path))) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ if ((k = mount_add_one(m, d, p, o, fstype, 0, set_flags)) < 0)
+ r = k;
+
+clean_up:
+ free(device);
+ free(path);
+ free(options);
+ free(options2);
+ free(fstype);
+ free(d);
+ free(p);
+ free(o);
+ }
+
+finish:
+ free(device);
+ free(path);
+ free(options);
+ free(options2);
+ free(fstype);
+ free(d);
+ free(p);
+ free(o);
+
+ return r;
+}
+
+static void mount_shutdown(Manager *m) {
+ assert(m);
+
+ if (m->proc_self_mountinfo) {
+ fclose(m->proc_self_mountinfo);
+ m->proc_self_mountinfo = NULL;
+ }
+}
+
+static int mount_enumerate(Manager *m) {
+ int r;
+ assert(m);
+
+ if (!m->proc_self_mountinfo) {
+ struct epoll_event ev = {
+ .events = EPOLLPRI,
+ .data.ptr = &m->mount_watch,
+ };
+
+ m->proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
+ if (!m->proc_self_mountinfo)
+ return -errno;
+
+ m->mount_watch.type = WATCH_MOUNT;
+ m->mount_watch.fd = fileno(m->proc_self_mountinfo);
+
+ if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->mount_watch.fd, &ev) < 0)
+ return -errno;
+ }
+
+ r = mount_load_proc_self_mountinfo(m, false);
+ if (r < 0)
+ goto fail;
+
+ return 0;
+
+fail:
+ mount_shutdown(m);
+ return r;
+}
+
+void mount_fd_event(Manager *m, int events) {
+ Unit *u;
+ int r;
+
+ assert(m);
+ assert(events & EPOLLPRI);
+
+ /* The manager calls this for every fd event happening on the
+ * /proc/self/mountinfo file, which informs us about mounting
+ * table changes */
+
+ r = mount_load_proc_self_mountinfo(m, true);
+ if (r < 0) {
+ log_error("Failed to reread /proc/self/mountinfo: %s", strerror(-r));
+
+ /* Reset flags, just in case, for later calls */
+ LIST_FOREACH(units_by_type, u, m->units_by_type[UNIT_MOUNT]) {
+ Mount *mount = MOUNT(u);
+
+ mount->is_mounted = mount->just_mounted = mount->just_changed = false;
+ }
+
+ return;
+ }
+
+ manager_dispatch_load_queue(m);
+
+ LIST_FOREACH(units_by_type, u, m->units_by_type[UNIT_MOUNT]) {
+ Mount *mount = MOUNT(u);
+
+ if (!mount->is_mounted) {
+ /* This has just been unmounted. */
+
+ mount->from_proc_self_mountinfo = false;
+
+ switch (mount->state) {
+
+ case MOUNT_MOUNTED:
+ mount_enter_dead(mount, MOUNT_SUCCESS);
+ break;
+
+ default:
+ mount_set_state(mount, mount->state);
+ break;
+
+ }
+
+ } else if (mount->just_mounted || mount->just_changed) {
+
+ /* New or changed mount entry */
+
+ switch (mount->state) {
+
+ case MOUNT_DEAD:
+ case MOUNT_FAILED:
+ mount_enter_mounted(mount, MOUNT_SUCCESS);
+ break;
+
+ case MOUNT_MOUNTING:
+ mount_enter_mounting_done(mount);
+ break;
+
+ default:
+ /* Nothing really changed, but let's
+ * issue an notification call
+ * nonetheless, in case somebody is
+ * waiting for this. (e.g. file system
+ * ro/rw remounts.) */
+ mount_set_state(mount, mount->state);
+ break;
+ }
+ }
+
+ /* Reset the flags for later calls */
+ mount->is_mounted = mount->just_mounted = mount->just_changed = false;
+ }
+}
+
+static void mount_reset_failed(Unit *u) {
+ Mount *m = MOUNT(u);
+
+ assert(m);
+
+ if (m->state == MOUNT_FAILED)
+ mount_set_state(m, MOUNT_DEAD);
+
+ m->result = MOUNT_SUCCESS;
+ m->reload_result = MOUNT_SUCCESS;
+}
+
+static int mount_kill(Unit *u, KillWho who, int signo, DBusError *error) {
+ return unit_kill_common(u, who, signo, -1, MOUNT(u)->control_pid, error);
+}
+
+static const char* const mount_state_table[_MOUNT_STATE_MAX] = {
+ [MOUNT_DEAD] = "dead",
+ [MOUNT_MOUNTING] = "mounting",
+ [MOUNT_MOUNTING_DONE] = "mounting-done",
+ [MOUNT_MOUNTED] = "mounted",
+ [MOUNT_REMOUNTING] = "remounting",
+ [MOUNT_UNMOUNTING] = "unmounting",
+ [MOUNT_MOUNTING_SIGTERM] = "mounting-sigterm",
+ [MOUNT_MOUNTING_SIGKILL] = "mounting-sigkill",
+ [MOUNT_REMOUNTING_SIGTERM] = "remounting-sigterm",
+ [MOUNT_REMOUNTING_SIGKILL] = "remounting-sigkill",
+ [MOUNT_UNMOUNTING_SIGTERM] = "unmounting-sigterm",
+ [MOUNT_UNMOUNTING_SIGKILL] = "unmounting-sigkill",
+ [MOUNT_FAILED] = "failed"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(mount_state, MountState);
+
+static const char* const mount_exec_command_table[_MOUNT_EXEC_COMMAND_MAX] = {
+ [MOUNT_EXEC_MOUNT] = "ExecMount",
+ [MOUNT_EXEC_UNMOUNT] = "ExecUnmount",
+ [MOUNT_EXEC_REMOUNT] = "ExecRemount",
+};
+
+DEFINE_STRING_TABLE_LOOKUP(mount_exec_command, MountExecCommand);
+
+static const char* const mount_result_table[_MOUNT_RESULT_MAX] = {
+ [MOUNT_SUCCESS] = "success",
+ [MOUNT_FAILURE_RESOURCES] = "resources",
+ [MOUNT_FAILURE_TIMEOUT] = "timeout",
+ [MOUNT_FAILURE_EXIT_CODE] = "exit-code",
+ [MOUNT_FAILURE_SIGNAL] = "signal",
+ [MOUNT_FAILURE_CORE_DUMP] = "core-dump"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(mount_result, MountResult);
+
+const UnitVTable mount_vtable = {
+ .object_size = sizeof(Mount),
+
+ .sections =
+ "Unit\0"
+ "Mount\0"
+ "Install\0",
+
+ .exec_context_offset = offsetof(Mount, exec_context),
+ .exec_section = "Mount",
+
+ .no_alias = true,
+ .no_instances = true,
+
+ .init = mount_init,
+ .load = mount_load,
+ .done = mount_done,
+
+ .coldplug = mount_coldplug,
+
+ .dump = mount_dump,
+
+ .start = mount_start,
+ .stop = mount_stop,
+ .reload = mount_reload,
+
+ .kill = mount_kill,
+
+ .serialize = mount_serialize,
+ .deserialize_item = mount_deserialize_item,
+
+ .active_state = mount_active_state,
+ .sub_state_to_string = mount_sub_state_to_string,
+
+ .check_gc = mount_check_gc,
+
+ .sigchld_event = mount_sigchld_event,
+ .timer_event = mount_timer_event,
+
+ .reset_failed = mount_reset_failed,
+
+ .bus_interface = "org.freedesktop.systemd1.Mount",
+ .bus_message_handler = bus_mount_message_handler,
+ .bus_invalidating_properties = bus_mount_invalidating_properties,
+
+ .enumerate = mount_enumerate,
+ .shutdown = mount_shutdown,
+
+ .status_message_formats = {
+ .starting_stopping = {
+ [0] = "Mounting %s...",
+ [1] = "Unmounting %s...",
+ },
+ .finished_start_job = {
+ [JOB_DONE] = "Mounted %s.",
+ [JOB_FAILED] = "Failed to mount %s.",
+ [JOB_DEPENDENCY] = "Dependency failed for %s.",
+ [JOB_TIMEOUT] = "Timed out mounting %s.",
+ },
+ .finished_stop_job = {
+ [JOB_DONE] = "Unmounted %s.",
+ [JOB_FAILED] = "Failed unmounting %s.",
+ [JOB_TIMEOUT] = "Timed out unmounting %s.",
+ },
+ },
+};
diff --git a/src/core/mount.h b/src/core/mount.h
new file mode 100644
index 0000000000..bcc10ee0d4
--- /dev/null
+++ b/src/core/mount.h
@@ -0,0 +1,123 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+typedef struct Mount Mount;
+
+#include "unit.h"
+#include "kill.h"
+
+typedef enum MountState {
+ MOUNT_DEAD,
+ MOUNT_MOUNTING, /* /bin/mount is running, but the mount is not done yet. */
+ MOUNT_MOUNTING_DONE, /* /bin/mount is running, and the mount is done. */
+ MOUNT_MOUNTED,
+ MOUNT_REMOUNTING,
+ MOUNT_UNMOUNTING,
+ MOUNT_MOUNTING_SIGTERM,
+ MOUNT_MOUNTING_SIGKILL,
+ MOUNT_REMOUNTING_SIGTERM,
+ MOUNT_REMOUNTING_SIGKILL,
+ MOUNT_UNMOUNTING_SIGTERM,
+ MOUNT_UNMOUNTING_SIGKILL,
+ MOUNT_FAILED,
+ _MOUNT_STATE_MAX,
+ _MOUNT_STATE_INVALID = -1
+} MountState;
+
+typedef enum MountExecCommand {
+ MOUNT_EXEC_MOUNT,
+ MOUNT_EXEC_UNMOUNT,
+ MOUNT_EXEC_REMOUNT,
+ _MOUNT_EXEC_COMMAND_MAX,
+ _MOUNT_EXEC_COMMAND_INVALID = -1
+} MountExecCommand;
+
+typedef struct MountParameters {
+ char *what;
+ char *options;
+ char *fstype;
+ int passno;
+} MountParameters;
+
+typedef enum MountResult {
+ MOUNT_SUCCESS,
+ MOUNT_FAILURE_RESOURCES,
+ MOUNT_FAILURE_TIMEOUT,
+ MOUNT_FAILURE_EXIT_CODE,
+ MOUNT_FAILURE_SIGNAL,
+ MOUNT_FAILURE_CORE_DUMP,
+ _MOUNT_RESULT_MAX,
+ _MOUNT_RESULT_INVALID = -1
+} MountResult;
+
+struct Mount {
+ Unit meta;
+
+ char *where;
+
+ MountParameters parameters_proc_self_mountinfo;
+ MountParameters parameters_fragment;
+
+ bool from_proc_self_mountinfo:1;
+ bool from_fragment:1;
+
+ /* Used while looking for mount points that vanished or got
+ * added from/to /proc/self/mountinfo */
+ bool is_mounted:1;
+ bool just_mounted:1;
+ bool just_changed:1;
+
+ MountResult result;
+ MountResult reload_result;
+
+ mode_t directory_mode;
+
+ usec_t timeout_usec;
+
+ ExecCommand exec_command[_MOUNT_EXEC_COMMAND_MAX];
+ ExecContext exec_context;
+ KillContext kill_context;
+
+ MountState state, deserialized_state;
+
+ ExecCommand* control_command;
+ MountExecCommand control_command_id;
+ pid_t control_pid;
+
+ Watch timer_watch;
+};
+
+extern const UnitVTable mount_vtable;
+
+void mount_fd_event(Manager *m, int events);
+
+const char* mount_state_to_string(MountState i) _const_;
+MountState mount_state_from_string(const char *s) _pure_;
+
+const char* mount_exec_command_to_string(MountExecCommand i) _const_;
+MountExecCommand mount_exec_command_from_string(const char *s) _pure_;
+
+const char* mount_result_to_string(MountResult i) _const_;
+MountResult mount_result_from_string(const char *s) _pure_;
+
+void warn_if_dir_nonempty(const char *unit, const char* where);
diff --git a/src/core/namespace.c b/src/core/namespace.c
new file mode 100644
index 0000000000..7e33d84156
--- /dev/null
+++ b/src/core/namespace.c
@@ -0,0 +1,277 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <sys/mount.h>
+#include <string.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <sched.h>
+#include <sys/syscall.h>
+#include <limits.h>
+#include <linux/fs.h>
+
+#include "strv.h"
+#include "util.h"
+#include "path-util.h"
+#include "namespace.h"
+#include "missing.h"
+#include "execute.h"
+
+typedef enum MountMode {
+ /* This is ordered by priority! */
+ INACCESSIBLE,
+ READONLY,
+ PRIVATE_TMP,
+ PRIVATE_VAR_TMP,
+ READWRITE
+} MountMode;
+
+typedef struct BindMount {
+ const char *path;
+ MountMode mode;
+ bool done;
+} BindMount;
+
+static int append_mounts(BindMount **p, char **strv, MountMode mode) {
+ char **i;
+
+ STRV_FOREACH(i, strv) {
+
+ if (!path_is_absolute(*i))
+ return -EINVAL;
+
+ (*p)->path = *i;
+ (*p)->mode = mode;
+ (*p)++;
+ }
+
+ return 0;
+}
+
+static int mount_path_compare(const void *a, const void *b) {
+ const BindMount *p = a, *q = b;
+
+ if (path_equal(p->path, q->path)) {
+
+ /* If the paths are equal, check the mode */
+ if (p->mode < q->mode)
+ return -1;
+
+ if (p->mode > q->mode)
+ return 1;
+
+ return 0;
+ }
+
+ /* If the paths are not equal, then order prefixes first */
+ if (path_startswith(p->path, q->path))
+ return 1;
+
+ if (path_startswith(q->path, p->path))
+ return -1;
+
+ return 0;
+}
+
+static void drop_duplicates(BindMount *m, unsigned *n) {
+ BindMount *f, *t, *previous;
+
+ assert(m);
+ assert(n);
+
+ for (f = m, t = m, previous = NULL; f < m+*n; f++) {
+
+ /* The first one wins */
+ if (previous && path_equal(f->path, previous->path))
+ continue;
+
+ t->path = f->path;
+ t->mode = f->mode;
+
+ previous = t;
+
+ t++;
+ }
+
+ *n = t - m;
+}
+
+static int apply_mount(
+ BindMount *m,
+ const char *tmp_dir,
+ const char *var_tmp_dir) {
+
+ const char *what;
+ int r;
+
+ assert(m);
+
+ switch (m->mode) {
+
+ case INACCESSIBLE:
+ what = "/run/systemd/inaccessible";
+ break;
+
+ case READONLY:
+ case READWRITE:
+ what = m->path;
+ break;
+
+ case PRIVATE_TMP:
+ what = tmp_dir;
+ break;
+
+ case PRIVATE_VAR_TMP:
+ what = var_tmp_dir;
+ break;
+
+ default:
+ assert_not_reached("Unknown mode");
+ }
+
+ assert(what);
+
+ r = mount(what, m->path, NULL, MS_BIND|MS_REC, NULL);
+ if (r >= 0)
+ log_debug("Successfully mounted %s to %s", what, m->path);
+
+ return r;
+}
+
+static int make_read_only(BindMount *m) {
+ int r;
+
+ assert(m);
+
+ if (m->mode != INACCESSIBLE && m->mode != READONLY)
+ return 0;
+
+ r = mount(NULL, m->path, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY|MS_REC, NULL);
+ if (r < 0)
+ return -errno;
+
+ return 0;
+}
+
+int setup_tmpdirs(char **tmp_dir,
+ char **var_tmp_dir) {
+ int r = 0;
+ char tmp_dir_template[] = "/tmp/systemd-private-XXXXXX",
+ var_tmp_dir_template[] = "/var/tmp/systemd-private-XXXXXX";
+
+ assert(tmp_dir);
+ assert(var_tmp_dir);
+
+ r = create_tmp_dir(tmp_dir_template, tmp_dir);
+ if (r < 0)
+ return r;
+
+ r = create_tmp_dir(var_tmp_dir_template, var_tmp_dir);
+ if (r == 0)
+ return 0;
+
+ /* failure */
+ rmdir(*tmp_dir);
+ rmdir(tmp_dir_template);
+ free(*tmp_dir);
+ *tmp_dir = NULL;
+
+ return r;
+}
+
+int setup_namespace(char** read_write_dirs,
+ char** read_only_dirs,
+ char** inaccessible_dirs,
+ char* tmp_dir,
+ char* var_tmp_dir,
+ bool private_tmp,
+ unsigned mount_flags) {
+
+ unsigned n = strv_length(read_write_dirs) +
+ strv_length(read_only_dirs) +
+ strv_length(inaccessible_dirs) +
+ (private_tmp ? 2 : 0);
+ BindMount *m, *mounts;
+ int r = 0;
+
+ if (!mount_flags)
+ mount_flags = MS_SHARED;
+
+ if (unshare(CLONE_NEWNS) < 0)
+ return -errno;
+
+ m = mounts = (BindMount *) alloca(n * sizeof(BindMount));
+ if ((r = append_mounts(&m, read_write_dirs, READWRITE)) < 0 ||
+ (r = append_mounts(&m, read_only_dirs, READONLY)) < 0 ||
+ (r = append_mounts(&m, inaccessible_dirs, INACCESSIBLE)) < 0)
+ return r;
+
+ if (private_tmp) {
+ m->path = "/tmp";
+ m->mode = PRIVATE_TMP;
+ m++;
+
+ m->path = "/var/tmp";
+ m->mode = PRIVATE_VAR_TMP;
+ m++;
+ }
+
+ assert(mounts + n == m);
+
+ qsort(mounts, n, sizeof(BindMount), mount_path_compare);
+ drop_duplicates(mounts, &n);
+
+ /* Remount / as SLAVE so that nothing now mounted in the namespace
+ shows up in the parent */
+ if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL) < 0)
+ return -errno;
+
+ for (m = mounts; m < mounts + n; ++m) {
+ r = apply_mount(m, tmp_dir, var_tmp_dir);
+ if (r < 0)
+ goto undo_mounts;
+ }
+
+ for (m = mounts; m < mounts + n; ++m) {
+ r = make_read_only(m);
+ if (r < 0)
+ goto undo_mounts;
+ }
+
+ /* Remount / as the desired mode */
+ if (mount(NULL, "/", NULL, mount_flags | MS_REC, NULL) < 0) {
+ r = -errno;
+ goto undo_mounts;
+ }
+
+ return 0;
+
+undo_mounts:
+ for (m = mounts; m < mounts + n; ++m) {
+ if (m->done)
+ umount2(m->path, MNT_DETACH);
+ }
+
+ return r;
+}
diff --git a/src/core/namespace.h b/src/core/namespace.h
new file mode 100644
index 0000000000..ddb579468d
--- /dev/null
+++ b/src/core/namespace.h
@@ -0,0 +1,33 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdbool.h>
+
+int setup_tmpdirs(char **tmp_dir, char **var_tmp_dir);
+int setup_namespace(char **read_write_dirs,
+ char **read_only_dirs,
+ char **inaccessible_dirs,
+ char *tmp_dir,
+ char *var_tmp_dir,
+ bool private_tmp,
+ unsigned mount_flags);
diff --git a/src/core/org.freedesktop.systemd1.conf b/src/core/org.freedesktop.systemd1.conf
new file mode 100644
index 0000000000..a07a8e1ce3
--- /dev/null
+++ b/src/core/org.freedesktop.systemd1.conf
@@ -0,0 +1,92 @@
+<?xml version="1.0"?> <!--*-nxml-*-->
+<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
+ "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
+
+<!--
+ This file is part of systemd.
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+-->
+
+<busconfig>
+
+ <policy user="root">
+ <allow own="org.freedesktop.systemd1"/>
+
+ <!-- Root clients can do everything -->
+ <allow send_destination="org.freedesktop.systemd1"/>
+ <allow receive_sender="org.freedesktop.systemd1"/>
+
+ <!-- systemd may receive activator requests -->
+ <allow receive_interface="org.freedesktop.systemd1.Activator"
+ receive_member="ActivationRequest"/>
+ </policy>
+
+ <policy context="default">
+ <deny send_destination="org.freedesktop.systemd1"/>
+
+ <allow send_destination="org.freedesktop.systemd1"
+ send_interface="org.freedesktop.DBus.Introspectable"/>
+
+ <allow send_destination="org.freedesktop.systemd1"
+ send_interface="org.freedesktop.DBus.Peer"/>
+
+ <allow send_destination="org.freedesktop.systemd1"
+ send_interface="org.freedesktop.DBus.Properties"
+ send_member="Get"/>
+
+ <allow send_destination="org.freedesktop.systemd1"
+ send_interface="org.freedesktop.DBus.Properties"
+ send_member="GetAll"/>
+
+ <allow send_destination="org.freedesktop.systemd1"
+ send_interface="org.freedesktop.systemd1.Manager"
+ send_member="GetUnit"/>
+
+ <allow send_destination="org.freedesktop.systemd1"
+ send_interface="org.freedesktop.systemd1.Manager"
+ send_member="GetUnitByPID"/>
+
+ <allow send_destination="org.freedesktop.systemd1"
+ send_interface="org.freedesktop.systemd1.Manager"
+ send_member="LoadUnit"/>
+
+ <allow send_destination="org.freedesktop.systemd1"
+ send_interface="org.freedesktop.systemd1.Manager"
+ send_member="GetJob"/>
+
+ <allow send_destination="org.freedesktop.systemd1"
+ send_interface="org.freedesktop.systemd1.Manager"
+ send_member="ListUnits"/>
+
+ <allow send_destination="org.freedesktop.systemd1"
+ send_interface="org.freedesktop.systemd1.Manager"
+ send_member="ListUnitFiles"/>
+
+ <allow send_destination="org.freedesktop.systemd1"
+ send_interface="org.freedesktop.systemd1.Manager"
+ send_member="GetUnitFileState"/>
+
+ <allow send_destination="org.freedesktop.systemd1"
+ send_interface="org.freedesktop.systemd1.Manager"
+ send_member="ListJobs"/>
+
+ <allow send_destination="org.freedesktop.systemd1"
+ send_interface="org.freedesktop.systemd1.Manager"
+ send_member="Subscribe"/>
+
+ <allow send_destination="org.freedesktop.systemd1"
+ send_interface="org.freedesktop.systemd1.Manager"
+ send_member="Unsubscribe"/>
+
+ <allow send_destination="org.freedesktop.systemd1"
+ send_interface="org.freedesktop.systemd1.Manager"
+ send_member="Dump"/>
+
+ <allow receive_sender="org.freedesktop.systemd1"/>
+ </policy>
+
+</busconfig>
diff --git a/src/core/org.freedesktop.systemd1.policy.in.in b/src/core/org.freedesktop.systemd1.policy.in.in
new file mode 100644
index 0000000000..51bdafac45
--- /dev/null
+++ b/src/core/org.freedesktop.systemd1.policy.in.in
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="UTF-8"?> <!--*-nxml-*-->
+<!DOCTYPE policyconfig PUBLIC "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
+ "http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd">
+
+<!--
+ This file is part of systemd.
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+-->
+
+<policyconfig>
+
+ <vendor>The systemd Project</vendor>
+ <vendor_url>http://www.freedesktop.org/wiki/Software/systemd</vendor_url>
+
+ <action id="org.freedesktop.systemd1.reply-password">
+ <_description>Send passphrase back to system</_description>
+ <_message>Authentication is required to send the entered passphrase back to the system.</_message>
+ <defaults>
+ <allow_any>no</allow_any>
+ <allow_inactive>no</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.exec.path">@rootlibexecdir@/systemd-reply-password</annotate>
+ </action>
+
+ <action id="org.freedesktop.systemd1.bus-access">
+ <_description>Privileged system and service manager access</_description>
+ <_message>Authentication is required to access the system and service manager.</_message>
+ <defaults>
+ <allow_any>no</allow_any>
+ <allow_inactive>no</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.exec.path">@bindir@/systemd-stdio-bridge</annotate>
+ </action>
+
+</policyconfig>
diff --git a/src/core/org.freedesktop.systemd1.service b/src/core/org.freedesktop.systemd1.service
new file mode 100644
index 0000000000..d4df3e93a2
--- /dev/null
+++ b/src/core/org.freedesktop.systemd1.service
@@ -0,0 +1,11 @@
+# This file is part of systemd.
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 of the License, or
+# (at your option) any later version.
+
+[D-BUS Service]
+Name=org.freedesktop.systemd1
+Exec=/bin/false
+User=root
diff --git a/src/core/path.c b/src/core/path.c
new file mode 100644
index 0000000000..8a09deb4ff
--- /dev/null
+++ b/src/core/path.c
@@ -0,0 +1,833 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/inotify.h>
+#include <sys/epoll.h>
+#include <sys/ioctl.h>
+#include <errno.h>
+#include <unistd.h>
+
+#include "unit.h"
+#include "unit-name.h"
+#include "path.h"
+#include "mkdir.h"
+#include "dbus-path.h"
+#include "special.h"
+#include "dbus-common.h"
+#include "path-util.h"
+#include "macro.h"
+
+static const UnitActiveState state_translation_table[_PATH_STATE_MAX] = {
+ [PATH_DEAD] = UNIT_INACTIVE,
+ [PATH_WAITING] = UNIT_ACTIVE,
+ [PATH_RUNNING] = UNIT_ACTIVE,
+ [PATH_FAILED] = UNIT_FAILED
+};
+
+int path_spec_watch(PathSpec *s, Unit *u) {
+
+ static const int flags_table[_PATH_TYPE_MAX] = {
+ [PATH_EXISTS] = IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB,
+ [PATH_EXISTS_GLOB] = IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB,
+ [PATH_CHANGED] = IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB|IN_CLOSE_WRITE|IN_CREATE|IN_DELETE|IN_MOVED_FROM|IN_MOVED_TO,
+ [PATH_MODIFIED] = IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB|IN_CLOSE_WRITE|IN_CREATE|IN_DELETE|IN_MOVED_FROM|IN_MOVED_TO|IN_MODIFY,
+ [PATH_DIRECTORY_NOT_EMPTY] = IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB|IN_CREATE|IN_MOVED_TO
+ };
+
+ bool exists = false;
+ char *slash, *oldslash = NULL;
+ int r;
+
+ assert(u);
+ assert(s);
+
+ path_spec_unwatch(s, u);
+
+ s->inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
+ if (s->inotify_fd < 0) {
+ r = -errno;
+ goto fail;
+ }
+
+ r = unit_watch_fd(u, s->inotify_fd, EPOLLIN, &s->watch);
+ if (r < 0)
+ goto fail;
+
+ /* This assumes the path was passed through path_kill_slashes()! */
+
+ for (slash = strchr(s->path, '/'); ; slash = strchr(slash+1, '/')) {
+ char *cut = NULL;
+ int flags;
+ char tmp;
+
+ if (slash) {
+ cut = slash + (slash == s->path);
+ tmp = *cut;
+ *cut = '\0';
+
+ flags = IN_MOVE_SELF | IN_DELETE_SELF | IN_ATTRIB | IN_CREATE | IN_MOVED_TO;
+ } else
+ flags = flags_table[s->type];
+
+ r = inotify_add_watch(s->inotify_fd, s->path, flags);
+ if (r < 0) {
+ if (errno == EACCES || errno == ENOENT) {
+ if (cut)
+ *cut = tmp;
+ break;
+ }
+
+ log_warning("Failed to add watch on %s: %m", s->path);
+ r = -errno;
+ if (cut)
+ *cut = tmp;
+ goto fail;
+ } else {
+ exists = true;
+
+ /* Path exists, we don't need to watch parent
+ too closely. */
+ if (oldslash) {
+ char *cut2 = oldslash + (oldslash == s->path);
+ char tmp2 = *cut2;
+ *cut2 = '\0';
+
+ inotify_add_watch(s->inotify_fd, s->path, IN_MOVE_SELF);
+ /* Error is ignored, the worst can happen is
+ we get spurious events. */
+
+ *cut2 = tmp2;
+ }
+ }
+
+ if (cut)
+ *cut = tmp;
+
+ if (slash)
+ oldslash = slash;
+ else {
+ /* whole path has been iterated over */
+ s->primary_wd = r;
+ break;
+ }
+ }
+
+ if (!exists) {
+ log_error("Failed to add watch on any of the components of %s: %m",
+ s->path);
+ r = -errno; /* either EACCESS or ENOENT */
+ goto fail;
+ }
+
+ return 0;
+
+fail:
+ path_spec_unwatch(s, u);
+ return r;
+}
+
+void path_spec_unwatch(PathSpec *s, Unit *u) {
+
+ if (s->inotify_fd < 0)
+ return;
+
+ unit_unwatch_fd(u, &s->watch);
+
+ close_nointr_nofail(s->inotify_fd);
+ s->inotify_fd = -1;
+}
+
+int path_spec_fd_event(PathSpec *s, uint32_t events) {
+ _cleanup_free_ uint8_t *buf = NULL;
+ struct inotify_event *e;
+ ssize_t k;
+ int l;
+ int r = 0;
+
+ if (events != EPOLLIN) {
+ log_error("Got invalid poll event on inotify.");
+ return -EINVAL;
+ }
+
+ if (ioctl(s->inotify_fd, FIONREAD, &l) < 0) {
+ log_error("FIONREAD failed: %m");
+ return -errno;
+ }
+
+ assert(l > 0);
+
+ buf = malloc(l);
+ if (!buf)
+ return log_oom();
+
+ k = read(s->inotify_fd, buf, l);
+ if (k < 0) {
+ log_error("Failed to read inotify event: %m");
+ return -errno;
+ }
+
+ e = (struct inotify_event*) buf;
+
+ while (k > 0) {
+ size_t step;
+
+ if ((s->type == PATH_CHANGED || s->type == PATH_MODIFIED) &&
+ s->primary_wd == e->wd)
+ r = 1;
+
+ step = sizeof(struct inotify_event) + e->len;
+ assert(step <= (size_t) k);
+
+ e = (struct inotify_event*) ((uint8_t*) e + step);
+ k -= step;
+ }
+
+ return r;
+}
+
+static bool path_spec_check_good(PathSpec *s, bool initial) {
+ bool good = false;
+
+ switch (s->type) {
+
+ case PATH_EXISTS:
+ good = access(s->path, F_OK) >= 0;
+ break;
+
+ case PATH_EXISTS_GLOB:
+ good = glob_exists(s->path) > 0;
+ break;
+
+ case PATH_DIRECTORY_NOT_EMPTY: {
+ int k;
+
+ k = dir_is_empty(s->path);
+ good = !(k == -ENOENT || k > 0);
+ break;
+ }
+
+ case PATH_CHANGED:
+ case PATH_MODIFIED: {
+ bool b;
+
+ b = access(s->path, F_OK) >= 0;
+ good = !initial && b != s->previous_exists;
+ s->previous_exists = b;
+ break;
+ }
+
+ default:
+ ;
+ }
+
+ return good;
+}
+
+static bool path_spec_startswith(PathSpec *s, const char *what) {
+ return path_startswith(s->path, what);
+}
+
+static void path_spec_mkdir(PathSpec *s, mode_t mode) {
+ int r;
+
+ if (s->type == PATH_EXISTS || s->type == PATH_EXISTS_GLOB)
+ return;
+
+ r = mkdir_p_label(s->path, mode);
+ if (r < 0)
+ log_warning("mkdir(%s) failed: %s", s->path, strerror(-r));
+}
+
+static void path_spec_dump(PathSpec *s, FILE *f, const char *prefix) {
+ fprintf(f,
+ "%s%s: %s\n",
+ prefix,
+ path_type_to_string(s->type),
+ s->path);
+}
+
+void path_spec_done(PathSpec *s) {
+ assert(s);
+ assert(s->inotify_fd == -1);
+
+ free(s->path);
+}
+
+static void path_init(Unit *u) {
+ Path *p = PATH(u);
+
+ assert(u);
+ assert(u->load_state == UNIT_STUB);
+
+ p->directory_mode = 0755;
+}
+
+void path_free_specs(Path *p) {
+ PathSpec *s;
+
+ assert(p);
+
+ while ((s = p->specs)) {
+ path_spec_unwatch(s, UNIT(p));
+ LIST_REMOVE(PathSpec, spec, p->specs, s);
+ path_spec_done(s);
+ free(s);
+ }
+}
+
+static void path_done(Unit *u) {
+ Path *p = PATH(u);
+
+ assert(p);
+
+ path_free_specs(p);
+}
+
+int path_add_one_mount_link(Path *p, Mount *m) {
+ PathSpec *s;
+ int r;
+
+ assert(p);
+ assert(m);
+
+ if (UNIT(p)->load_state != UNIT_LOADED ||
+ UNIT(m)->load_state != UNIT_LOADED)
+ return 0;
+
+ LIST_FOREACH(spec, s, p->specs) {
+ if (!path_spec_startswith(s, m->where))
+ continue;
+
+ r = unit_add_two_dependencies(UNIT(p), UNIT_AFTER, UNIT_REQUIRES,
+ UNIT(m), true);
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static int path_add_mount_links(Path *p) {
+ Unit *other;
+ int r;
+
+ assert(p);
+
+ LIST_FOREACH(units_by_type, other, UNIT(p)->manager->units_by_type[UNIT_MOUNT]) {
+ r = path_add_one_mount_link(p, MOUNT(other));
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static int path_verify(Path *p) {
+ assert(p);
+
+ if (UNIT(p)->load_state != UNIT_LOADED)
+ return 0;
+
+ if (!p->specs) {
+ log_error_unit(UNIT(p)->id,
+ "%s lacks path setting. Refusing.", UNIT(p)->id);
+ return -EINVAL;
+ }
+
+ return 0;
+}
+
+static int path_add_default_dependencies(Path *p) {
+ int r;
+
+ assert(p);
+
+ r = unit_add_dependency_by_name(UNIT(p), UNIT_BEFORE,
+ SPECIAL_PATHS_TARGET, NULL, true);
+ if (r < 0)
+ return r;
+
+ if (UNIT(p)->manager->running_as == SYSTEMD_SYSTEM) {
+ r = unit_add_two_dependencies_by_name(UNIT(p), UNIT_AFTER, UNIT_REQUIRES,
+ SPECIAL_SYSINIT_TARGET, NULL, true);
+ if (r < 0)
+ return r;
+ }
+
+ return unit_add_two_dependencies_by_name(UNIT(p), UNIT_BEFORE, UNIT_CONFLICTS,
+ SPECIAL_SHUTDOWN_TARGET, NULL, true);
+}
+
+static int path_load(Unit *u) {
+ Path *p = PATH(u);
+ int r;
+
+ assert(u);
+ assert(u->load_state == UNIT_STUB);
+
+ r = unit_load_fragment_and_dropin(u);
+ if (r < 0)
+ return r;
+
+ if (u->load_state == UNIT_LOADED) {
+
+ if (set_isempty(u->dependencies[UNIT_TRIGGERS])) {
+ Unit *x;
+
+ r = unit_load_related_unit(u, ".service", &x);
+ if (r < 0)
+ return r;
+
+ r = unit_add_two_dependencies(u, UNIT_BEFORE, UNIT_TRIGGERS, x, true);
+ if (r < 0)
+ return r;
+ }
+
+ r = path_add_mount_links(p);
+ if (r < 0)
+ return r;
+
+ if (UNIT(p)->default_dependencies) {
+ r = path_add_default_dependencies(p);
+ if (r < 0)
+ return r;
+ }
+ }
+
+ return path_verify(p);
+}
+
+static void path_dump(Unit *u, FILE *f, const char *prefix) {
+ Path *p = PATH(u);
+ Unit *trigger;
+ PathSpec *s;
+
+ assert(p);
+ assert(f);
+
+ trigger = UNIT_TRIGGER(u);
+
+ fprintf(f,
+ "%sPath State: %s\n"
+ "%sResult: %s\n"
+ "%sUnit: %s\n"
+ "%sMakeDirectory: %s\n"
+ "%sDirectoryMode: %04o\n",
+ prefix, path_state_to_string(p->state),
+ prefix, path_result_to_string(p->result),
+ prefix, trigger ? trigger->id : "n/a",
+ prefix, yes_no(p->make_directory),
+ prefix, p->directory_mode);
+
+ LIST_FOREACH(spec, s, p->specs)
+ path_spec_dump(s, f, prefix);
+}
+
+static void path_unwatch(Path *p) {
+ PathSpec *s;
+
+ assert(p);
+
+ LIST_FOREACH(spec, s, p->specs)
+ path_spec_unwatch(s, UNIT(p));
+}
+
+static int path_watch(Path *p) {
+ int r;
+ PathSpec *s;
+
+ assert(p);
+
+ LIST_FOREACH(spec, s, p->specs) {
+ r = path_spec_watch(s, UNIT(p));
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static void path_set_state(Path *p, PathState state) {
+ PathState old_state;
+ assert(p);
+
+ old_state = p->state;
+ p->state = state;
+
+ if (state != PATH_WAITING &&
+ (state != PATH_RUNNING || p->inotify_triggered))
+ path_unwatch(p);
+
+ if (state != old_state)
+ log_debug("%s changed %s -> %s",
+ UNIT(p)->id,
+ path_state_to_string(old_state),
+ path_state_to_string(state));
+
+ unit_notify(UNIT(p), state_translation_table[old_state], state_translation_table[state], true);
+}
+
+static void path_enter_waiting(Path *p, bool initial, bool recheck);
+
+static int path_coldplug(Unit *u) {
+ Path *p = PATH(u);
+
+ assert(p);
+ assert(p->state == PATH_DEAD);
+
+ if (p->deserialized_state != p->state) {
+
+ if (p->deserialized_state == PATH_WAITING ||
+ p->deserialized_state == PATH_RUNNING)
+ path_enter_waiting(p, true, true);
+ else
+ path_set_state(p, p->deserialized_state);
+ }
+
+ return 0;
+}
+
+static void path_enter_dead(Path *p, PathResult f) {
+ assert(p);
+
+ if (f != PATH_SUCCESS)
+ p->result = f;
+
+ path_set_state(p, p->result != PATH_SUCCESS ? PATH_FAILED : PATH_DEAD);
+}
+
+static void path_enter_running(Path *p) {
+ _cleanup_dbus_error_free_ DBusError error;
+ int r;
+
+ assert(p);
+
+ dbus_error_init(&error);
+
+ /* Don't start job if we are supposed to go down */
+ if (unit_stop_pending(UNIT(p)))
+ return;
+
+ r = manager_add_job(UNIT(p)->manager, JOB_START, UNIT_TRIGGER(UNIT(p)),
+ JOB_REPLACE, true, &error, NULL);
+ if (r < 0)
+ goto fail;
+
+ p->inotify_triggered = false;
+
+ r = path_watch(p);
+ if (r < 0)
+ goto fail;
+
+ path_set_state(p, PATH_RUNNING);
+ return;
+
+fail:
+ log_warning("%s failed to queue unit startup job: %s",
+ UNIT(p)->id, bus_error(&error, r));
+ path_enter_dead(p, PATH_FAILURE_RESOURCES);
+}
+
+static bool path_check_good(Path *p, bool initial) {
+ PathSpec *s;
+ bool good = false;
+
+ assert(p);
+
+ LIST_FOREACH(spec, s, p->specs) {
+ good = path_spec_check_good(s, initial);
+
+ if (good)
+ break;
+ }
+
+ return good;
+}
+
+static void path_enter_waiting(Path *p, bool initial, bool recheck) {
+ int r;
+
+ if (recheck)
+ if (path_check_good(p, initial)) {
+ log_debug("%s got triggered.", UNIT(p)->id);
+ path_enter_running(p);
+ return;
+ }
+
+ r = path_watch(p);
+ if (r < 0)
+ goto fail;
+
+ /* Hmm, so now we have created inotify watches, but the file
+ * might have appeared/been removed by now, so we must
+ * recheck */
+
+ if (recheck)
+ if (path_check_good(p, false)) {
+ log_debug("%s got triggered.", UNIT(p)->id);
+ path_enter_running(p);
+ return;
+ }
+
+ path_set_state(p, PATH_WAITING);
+ return;
+
+fail:
+ log_warning("%s failed to enter waiting state: %s",
+ UNIT(p)->id, strerror(-r));
+ path_enter_dead(p, PATH_FAILURE_RESOURCES);
+}
+
+static void path_mkdir(Path *p) {
+ PathSpec *s;
+
+ assert(p);
+
+ if (!p->make_directory)
+ return;
+
+ LIST_FOREACH(spec, s, p->specs)
+ path_spec_mkdir(s, p->directory_mode);
+}
+
+static int path_start(Unit *u) {
+ Path *p = PATH(u);
+
+ assert(p);
+ assert(p->state == PATH_DEAD || p->state == PATH_FAILED);
+
+ if (UNIT_TRIGGER(u)->load_state != UNIT_LOADED)
+ return -ENOENT;
+
+ path_mkdir(p);
+
+ p->result = PATH_SUCCESS;
+ path_enter_waiting(p, true, true);
+
+ return 0;
+}
+
+static int path_stop(Unit *u) {
+ Path *p = PATH(u);
+
+ assert(p);
+ assert(p->state == PATH_WAITING || p->state == PATH_RUNNING);
+
+ path_enter_dead(p, PATH_SUCCESS);
+ return 0;
+}
+
+static int path_serialize(Unit *u, FILE *f, FDSet *fds) {
+ Path *p = PATH(u);
+
+ assert(u);
+ assert(f);
+ assert(fds);
+
+ unit_serialize_item(u, f, "state", path_state_to_string(p->state));
+ unit_serialize_item(u, f, "result", path_result_to_string(p->result));
+
+ return 0;
+}
+
+static int path_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
+ Path *p = PATH(u);
+
+ assert(u);
+ assert(key);
+ assert(value);
+ assert(fds);
+
+ if (streq(key, "state")) {
+ PathState state;
+
+ state = path_state_from_string(value);
+ if (state < 0)
+ log_debug("Failed to parse state value %s", value);
+ else
+ p->deserialized_state = state;
+
+ } else if (streq(key, "result")) {
+ PathResult f;
+
+ f = path_result_from_string(value);
+ if (f < 0)
+ log_debug("Failed to parse result value %s", value);
+ else if (f != PATH_SUCCESS)
+ p->result = f;
+
+ } else
+ log_debug("Unknown serialization key '%s'", key);
+
+ return 0;
+}
+
+_pure_ static UnitActiveState path_active_state(Unit *u) {
+ assert(u);
+
+ return state_translation_table[PATH(u)->state];
+}
+
+_pure_ static const char *path_sub_state_to_string(Unit *u) {
+ assert(u);
+
+ return path_state_to_string(PATH(u)->state);
+}
+
+static void path_fd_event(Unit *u, int fd, uint32_t events, Watch *w) {
+ Path *p = PATH(u);
+ PathSpec *s;
+ int changed;
+
+ assert(p);
+ assert(fd >= 0);
+
+ if (p->state != PATH_WAITING &&
+ p->state != PATH_RUNNING)
+ return;
+
+ /* log_debug("inotify wakeup on %s.", u->id); */
+
+ LIST_FOREACH(spec, s, p->specs)
+ if (path_spec_owns_inotify_fd(s, fd))
+ break;
+
+ if (!s) {
+ log_error("Got event on unknown fd.");
+ goto fail;
+ }
+
+ changed = path_spec_fd_event(s, events);
+ if (changed < 0)
+ goto fail;
+
+ /* If we are already running, then remember that one event was
+ * dispatched so that we restart the service only if something
+ * actually changed on disk */
+ p->inotify_triggered = true;
+
+ if (changed)
+ path_enter_running(p);
+ else
+ path_enter_waiting(p, false, true);
+
+ return;
+
+fail:
+ path_enter_dead(p, PATH_FAILURE_RESOURCES);
+}
+
+static void path_trigger_notify(Unit *u, Unit *other) {
+ Path *p = PATH(u);
+
+ assert(u);
+ assert(other);
+
+ /* Invoked whenever the unit we trigger changes state or gains
+ * or loses a job */
+
+ if (other->load_state != UNIT_LOADED)
+ return;
+
+ if (p->state == PATH_RUNNING &&
+ UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other))) {
+ log_debug_unit(UNIT(p)->id,
+ "%s got notified about unit deactivation.",
+ UNIT(p)->id);
+
+ /* Hmm, so inotify was triggered since the
+ * last activation, so I guess we need to
+ * recheck what is going on. */
+ path_enter_waiting(p, false, p->inotify_triggered);
+ }
+}
+
+static void path_reset_failed(Unit *u) {
+ Path *p = PATH(u);
+
+ assert(p);
+
+ if (p->state == PATH_FAILED)
+ path_set_state(p, PATH_DEAD);
+
+ p->result = PATH_SUCCESS;
+}
+
+static const char* const path_state_table[_PATH_STATE_MAX] = {
+ [PATH_DEAD] = "dead",
+ [PATH_WAITING] = "waiting",
+ [PATH_RUNNING] = "running",
+ [PATH_FAILED] = "failed"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(path_state, PathState);
+
+static const char* const path_type_table[_PATH_TYPE_MAX] = {
+ [PATH_EXISTS] = "PathExists",
+ [PATH_EXISTS_GLOB] = "PathExistsGlob",
+ [PATH_CHANGED] = "PathChanged",
+ [PATH_MODIFIED] = "PathModified",
+ [PATH_DIRECTORY_NOT_EMPTY] = "DirectoryNotEmpty"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(path_type, PathType);
+
+static const char* const path_result_table[_PATH_RESULT_MAX] = {
+ [PATH_SUCCESS] = "success",
+ [PATH_FAILURE_RESOURCES] = "resources"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(path_result, PathResult);
+
+const UnitVTable path_vtable = {
+ .object_size = sizeof(Path),
+ .sections =
+ "Unit\0"
+ "Path\0"
+ "Install\0",
+
+ .init = path_init,
+ .done = path_done,
+ .load = path_load,
+
+ .coldplug = path_coldplug,
+
+ .dump = path_dump,
+
+ .start = path_start,
+ .stop = path_stop,
+
+ .serialize = path_serialize,
+ .deserialize_item = path_deserialize_item,
+
+ .active_state = path_active_state,
+ .sub_state_to_string = path_sub_state_to_string,
+
+ .fd_event = path_fd_event,
+
+ .trigger_notify = path_trigger_notify,
+
+ .reset_failed = path_reset_failed,
+
+ .bus_interface = "org.freedesktop.systemd1.Path",
+ .bus_message_handler = bus_path_message_handler,
+ .bus_invalidating_properties = bus_path_invalidating_properties
+};
diff --git a/src/core/path.h b/src/core/path.h
new file mode 100644
index 0000000000..6adab5897d
--- /dev/null
+++ b/src/core/path.h
@@ -0,0 +1,108 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+typedef struct Path Path;
+
+#include "unit.h"
+#include "mount.h"
+
+typedef enum PathState {
+ PATH_DEAD,
+ PATH_WAITING,
+ PATH_RUNNING,
+ PATH_FAILED,
+ _PATH_STATE_MAX,
+ _PATH_STATE_INVALID = -1
+} PathState;
+
+typedef enum PathType {
+ PATH_EXISTS,
+ PATH_EXISTS_GLOB,
+ PATH_DIRECTORY_NOT_EMPTY,
+ PATH_CHANGED,
+ PATH_MODIFIED,
+ _PATH_TYPE_MAX,
+ _PATH_TYPE_INVALID = -1
+} PathType;
+
+typedef struct PathSpec {
+ char *path;
+
+ Watch watch;
+
+ LIST_FIELDS(struct PathSpec, spec);
+
+ PathType type;
+ int inotify_fd;
+ int primary_wd;
+
+ bool previous_exists;
+} PathSpec;
+
+int path_spec_watch(PathSpec *s, Unit *u);
+void path_spec_unwatch(PathSpec *s, Unit *u);
+int path_spec_fd_event(PathSpec *s, uint32_t events);
+void path_spec_done(PathSpec *s);
+
+static inline bool path_spec_owns_inotify_fd(PathSpec *s, int fd) {
+ return s->inotify_fd == fd;
+}
+
+typedef enum PathResult {
+ PATH_SUCCESS,
+ PATH_FAILURE_RESOURCES,
+ _PATH_RESULT_MAX,
+ _PATH_RESULT_INVALID = -1
+} PathResult;
+
+struct Path {
+ Unit meta;
+
+ LIST_HEAD(PathSpec, specs);
+
+ PathState state, deserialized_state;
+
+ bool inotify_triggered;
+
+ bool make_directory;
+ mode_t directory_mode;
+
+ PathResult result;
+};
+
+/* Called from the mount code figure out if a mount is a dependency of
+ * any of the paths of this path object */
+int path_add_one_mount_link(Path *p, Mount *m);
+
+void path_free_specs(Path *p);
+
+extern const UnitVTable path_vtable;
+
+const char* path_state_to_string(PathState i) _const_;
+PathState path_state_from_string(const char *s) _pure_;
+
+const char* path_type_to_string(PathType i) _const_;
+PathType path_type_from_string(const char *s) _pure_;
+
+const char* path_result_to_string(PathResult i) _const_;
+PathResult path_result_from_string(const char *s) _pure_;
diff --git a/src/core/securebits.h b/src/core/securebits.h
new file mode 100644
index 0000000000..ba0bba5353
--- /dev/null
+++ b/src/core/securebits.h
@@ -0,0 +1,45 @@
+#ifndef _LINUX_SECUREBITS_H
+#define _LINUX_SECUREBITS_H 1
+
+/* This is minimal version of Linux' linux/securebits.h header file,
+ * which is licensed GPL2 */
+
+#define SECUREBITS_DEFAULT 0x00000000
+
+/* When set UID 0 has no special privileges. When unset, we support
+ inheritance of root-permissions and suid-root executable under
+ compatibility mode. We raise the effective and inheritable bitmasks
+ *of the executable file* if the effective uid of the new process is
+ 0. If the real uid is 0, we raise the effective (legacy) bit of the
+ executable file. */
+#define SECURE_NOROOT 0
+#define SECURE_NOROOT_LOCKED 1 /* make bit-0 immutable */
+
+/* When set, setuid to/from uid 0 does not trigger capability-"fixup".
+ When unset, to provide compatibility with old programs relying on
+ set*uid to gain/lose privilege, transitions to/from uid 0 cause
+ capabilities to be gained/lost. */
+#define SECURE_NO_SETUID_FIXUP 2
+#define SECURE_NO_SETUID_FIXUP_LOCKED 3 /* make bit-2 immutable */
+
+/* When set, a process can retain its capabilities even after
+ transitioning to a non-root user (the set-uid fixup suppressed by
+ bit 2). Bit-4 is cleared when a process calls exec(); setting both
+ bit 4 and 5 will create a barrier through exec that no exec()'d
+ child can use this feature again. */
+#define SECURE_KEEP_CAPS 4
+#define SECURE_KEEP_CAPS_LOCKED 5 /* make bit-4 immutable */
+
+/* Each securesetting is implemented using two bits. One bit specifies
+ whether the setting is on or off. The other bit specify whether the
+ setting is locked or not. A setting which is locked cannot be
+ changed from user-level. */
+#define issecure_mask(X) (1 << (X))
+#define issecure(X) (issecure_mask(X) & current_cred_xxx(securebits))
+
+#define SECURE_ALL_BITS (issecure_mask(SECURE_NOROOT) | \
+ issecure_mask(SECURE_NO_SETUID_FIXUP) | \
+ issecure_mask(SECURE_KEEP_CAPS))
+#define SECURE_ALL_LOCKS (SECURE_ALL_BITS << 1)
+
+#endif /* !_LINUX_SECUREBITS_H */
diff --git a/src/core/selinux-access.c b/src/core/selinux-access.c
new file mode 100644
index 0000000000..426aed07d2
--- /dev/null
+++ b/src/core/selinux-access.c
@@ -0,0 +1,439 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Dan Walsh
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "selinux-access.h"
+
+#ifdef HAVE_SELINUX
+
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <limits.h>
+#include <selinux/selinux.h>
+#include <selinux/avc.h>
+#ifdef HAVE_AUDIT
+#include <libaudit.h>
+#endif
+#include <dbus.h>
+
+#include "util.h"
+#include "log.h"
+#include "bus-errors.h"
+#include "dbus-common.h"
+#include "audit.h"
+#include "selinux-util.h"
+#include "audit-fd.h"
+
+static bool initialized = false;
+
+struct auditstruct {
+ const char *path;
+ char *cmdline;
+ uid_t loginuid;
+ uid_t uid;
+ gid_t gid;
+};
+
+static int bus_get_selinux_security_context(
+ DBusConnection *connection,
+ const char *name,
+ char **scon,
+ DBusError *error) {
+
+ _cleanup_dbus_message_unref_ DBusMessage *m = NULL, *reply = NULL;
+ DBusMessageIter iter, sub;
+ const char *bytes;
+ char *b;
+ int nbytes;
+
+ m = dbus_message_new_method_call(
+ DBUS_SERVICE_DBUS,
+ DBUS_PATH_DBUS,
+ DBUS_INTERFACE_DBUS,
+ "GetConnectionSELinuxSecurityContext");
+ if (!m) {
+ dbus_set_error_const(error, DBUS_ERROR_NO_MEMORY, NULL);
+ return -ENOMEM;
+ }
+
+ if (!dbus_message_append_args(
+ m,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_INVALID)) {
+ dbus_set_error_const(error, DBUS_ERROR_NO_MEMORY, NULL);
+ return -ENOMEM;
+ }
+
+ reply = dbus_connection_send_with_reply_and_block(connection, m, -1, error);
+ if (!reply)
+ return -EIO;
+
+ if (dbus_set_error_from_message(error, reply))
+ return -EIO;
+
+ if (!dbus_message_iter_init(reply, &iter))
+ return -EIO;
+
+ if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY)
+ return -EIO;
+
+ dbus_message_iter_recurse(&iter, &sub);
+ dbus_message_iter_get_fixed_array(&sub, &bytes, &nbytes);
+
+ b = strndup(bytes, nbytes);
+ if (!b)
+ return -ENOMEM;
+
+ *scon = b;
+
+ return 0;
+}
+
+static int bus_get_audit_data(
+ DBusConnection *connection,
+ const char *name,
+ struct auditstruct *audit,
+ DBusError *error) {
+
+ pid_t pid;
+ int r;
+
+ pid = bus_get_unix_process_id(connection, name, error);
+ if (pid <= 0)
+ return -EIO;
+
+ r = audit_loginuid_from_pid(pid, &audit->loginuid);
+ if (r < 0)
+ return r;
+
+ r = get_process_uid(pid, &audit->uid);
+ if (r < 0)
+ return r;
+
+ r = get_process_gid(pid, &audit->gid);
+ if (r < 0)
+ return r;
+
+ r = get_process_cmdline(pid, 0, true, &audit->cmdline);
+ if (r < 0)
+ return r;
+
+ return 0;
+}
+
+/*
+ Any time an access gets denied this callback will be called
+ with the aduit data. We then need to just copy the audit data into the msgbuf.
+*/
+static int audit_callback(
+ void *auditdata,
+ security_class_t cls,
+ char *msgbuf,
+ size_t msgbufsize) {
+
+ struct auditstruct *audit = (struct auditstruct *) auditdata;
+
+ snprintf(msgbuf, msgbufsize,
+ "auid=%d uid=%d gid=%d%s%s%s%s%s%s",
+ audit->loginuid,
+ audit->uid,
+ audit->gid,
+ (audit->path ? " path=\"" : ""),
+ strempty(audit->path),
+ (audit->path ? "\"" : ""),
+ (audit->cmdline ? " cmdline=\"" : ""),
+ strempty(audit->cmdline),
+ (audit->cmdline ? "\"" : ""));
+
+ msgbuf[msgbufsize-1] = 0;
+
+ return 0;
+}
+
+/*
+ Any time an access gets denied this callback will be called
+ code copied from dbus. If audit is turned on the messages will go as
+ user_avc's into the /var/log/audit/audit.log, otherwise they will be
+ sent to syslog.
+*/
+_printf_attr_(2, 3) static int log_callback(int type, const char *fmt, ...) {
+ va_list ap;
+
+ va_start(ap, fmt);
+
+#ifdef HAVE_AUDIT
+ if (get_audit_fd() >= 0) {
+ _cleanup_free_ char *buf = NULL;
+ int r;
+
+ r = vasprintf(&buf, fmt, ap);
+ va_end(ap);
+
+ if (r >= 0) {
+ audit_log_user_avc_message(get_audit_fd(), AUDIT_USER_AVC, buf, NULL, NULL, NULL, 0);
+ return 0;
+ }
+
+ va_start(ap, fmt);
+ }
+#endif
+ log_metav(LOG_USER | LOG_INFO, __FILE__, __LINE__, __FUNCTION__, fmt, ap);
+ va_end(ap);
+
+ return 0;
+}
+
+/*
+ Function must be called once to initialize the SELinux AVC environment.
+ Sets up callbacks.
+ If you want to cleanup memory you should need to call selinux_access_finish.
+*/
+static int access_init(void) {
+ int r;
+
+ if (avc_open(NULL, 0)) {
+ log_error("avc_open() failed: %m");
+ return -errno;
+ }
+
+ selinux_set_callback(SELINUX_CB_AUDIT, (union selinux_callback) audit_callback);
+ selinux_set_callback(SELINUX_CB_LOG, (union selinux_callback) log_callback);
+
+ if (security_getenforce() >= 0)
+ return 0;
+
+ r = -errno;
+ avc_destroy();
+
+ return r;
+}
+
+static int selinux_access_init(DBusError *error) {
+ int r;
+
+ if (initialized)
+ return 0;
+
+ if (use_selinux()) {
+ r = access_init();
+ if (r < 0) {
+ dbus_set_error(error, DBUS_ERROR_ACCESS_DENIED, "Failed to initialize SELinux.");
+ return r;
+ }
+ }
+
+ initialized = true;
+ return 0;
+}
+
+void selinux_access_free(void) {
+ if (!initialized)
+ return;
+
+ avc_destroy();
+ initialized = false;
+}
+
+static int get_audit_data(
+ DBusConnection *connection,
+ DBusMessage *message,
+ struct auditstruct *audit,
+ DBusError *error) {
+
+ const char *sender;
+ int r, fd;
+ struct ucred ucred;
+ socklen_t len = sizeof(ucred);
+
+ sender = dbus_message_get_sender(message);
+ if (sender)
+ return bus_get_audit_data(connection, sender, audit, error);
+
+ if (!dbus_connection_get_unix_fd(connection, &fd))
+ return -EINVAL;
+
+ r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &ucred, &len);
+ if (r < 0) {
+ log_error("Failed to determine peer credentials: %m");
+ return -errno;
+ }
+
+ audit->uid = ucred.uid;
+ audit->gid = ucred.gid;
+
+ r = audit_loginuid_from_pid(ucred.pid, &audit->loginuid);
+ if (r < 0)
+ return r;
+
+ r = get_process_cmdline(ucred.pid, 0, true, &audit->cmdline);
+ if (r < 0)
+ return r;
+
+ return 0;
+}
+
+/*
+ This function returns the security context of the remote end of the dbus
+ connections. Whether it is on the bus or a local connection.
+*/
+static int get_calling_context(
+ DBusConnection *connection,
+ DBusMessage *message,
+ security_context_t *scon,
+ DBusError *error) {
+
+ const char *sender;
+ int r;
+ int fd;
+
+ /*
+ If sender exists then
+ if sender is NULL this indicates a local connection. Grab the fd
+ from dbus and do an getpeercon to peers process context
+ */
+ sender = dbus_message_get_sender(message);
+ if (sender) {
+ r = bus_get_selinux_security_context(connection, sender, scon, error);
+ if (r >= 0)
+ return r;
+
+ log_error("bus_get_selinux_security_context failed: %m");
+ return r;
+ }
+
+ if (!dbus_connection_get_unix_fd(connection, &fd)) {
+ log_error("bus_connection_get_unix_fd failed %m");
+ return -EINVAL;
+ }
+
+ r = getpeercon(fd, scon);
+ if (r < 0) {
+ log_error("getpeercon failed %m");
+ return -errno;
+ }
+
+ return 0;
+}
+
+/*
+ This function communicates with the kernel to check whether or not it should
+ allow the access.
+ If the machine is in permissive mode it will return ok. Audit messages will
+ still be generated if the access would be denied in enforcing mode.
+*/
+int selinux_access_check(
+ DBusConnection *connection,
+ DBusMessage *message,
+ const char *path,
+ const char *permission,
+ DBusError *error) {
+
+ security_context_t scon = NULL, fcon = NULL;
+ int r = 0;
+ const char *tclass = NULL;
+ struct auditstruct audit;
+
+ assert(connection);
+ assert(message);
+ assert(permission);
+ assert(error);
+
+ if (!use_selinux())
+ return 0;
+
+ r = selinux_access_init(error);
+ if (r < 0)
+ return r;
+
+ audit.uid = audit.loginuid = (uid_t) -1;
+ audit.gid = (gid_t) -1;
+ audit.cmdline = NULL;
+ audit.path = path;
+
+ r = get_calling_context(connection, message, &scon, error);
+ if (r < 0) {
+ log_error("Failed to get caller's security context on: %m");
+ goto finish;
+ }
+
+ if (path) {
+ tclass = "service";
+ /* get the file context of the unit file */
+ r = getfilecon(path, &fcon);
+ if (r < 0) {
+ dbus_set_error(error, DBUS_ERROR_ACCESS_DENIED, "Failed to get file context on %s.", path);
+ r = -errno;
+ log_error("Failed to get security context on %s: %m",path);
+ goto finish;
+ }
+
+ } else {
+ tclass = "system";
+ r = getcon(&fcon);
+ if (r < 0) {
+ dbus_set_error(error, DBUS_ERROR_ACCESS_DENIED, "Failed to get current context.");
+ r = -errno;
+ log_error("Failed to get current process context on: %m");
+ goto finish;
+ }
+ }
+
+ (void) get_audit_data(connection, message, &audit, error);
+
+ errno = 0;
+ r = selinux_check_access(scon, fcon, tclass, permission, &audit);
+ if (r < 0) {
+ dbus_set_error(error, DBUS_ERROR_ACCESS_DENIED, "SELinux policy denies access.");
+ r = -errno;
+ log_error("SELinux policy denies access.");
+ }
+
+ log_debug("SELinux access check scon=%s tcon=%s tclass=%s perm=%s path=%s cmdline=%s: %i", scon, fcon, tclass, permission, path, audit.cmdline, r);
+
+finish:
+ free(audit.cmdline);
+ freecon(scon);
+ freecon(fcon);
+
+ if (r && security_getenforce() != 1) {
+ dbus_error_init(error);
+ r = 0;
+ }
+
+ return r;
+}
+
+#else
+
+int selinux_access_check(
+ DBusConnection *connection,
+ DBusMessage *message,
+ const char *path,
+ const char *permission,
+ DBusError *error) {
+
+ return 0;
+}
+
+void selinux_access_free(void) {
+}
+
+#endif
diff --git a/src/core/selinux-access.h b/src/core/selinux-access.h
new file mode 100644
index 0000000000..9183cbc9a6
--- /dev/null
+++ b/src/core/selinux-access.h
@@ -0,0 +1,62 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Dan Walsh
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <dbus.h>
+
+void selinux_access_free(void);
+
+int selinux_access_check(DBusConnection *connection, DBusMessage *message, const char *path, const char *permission, DBusError *error);
+
+#ifdef HAVE_SELINUX
+
+#define SELINUX_ACCESS_CHECK(connection, message, permission) \
+ do { \
+ DBusError _error; \
+ int _r; \
+ DBusConnection *_c = (connection); \
+ DBusMessage *_m = (message); \
+ dbus_error_init(&_error); \
+ _r = selinux_access_check(_c, _m, NULL, (permission), &_error); \
+ if (_r < 0) \
+ return bus_send_error_reply(_c, _m, &_error, _r); \
+ } while (false)
+
+#define SELINUX_UNIT_ACCESS_CHECK(unit, connection, message, permission) \
+ do { \
+ DBusError _error; \
+ int _r; \
+ DBusConnection *_c = (connection); \
+ DBusMessage *_m = (message); \
+ Unit *_u = (unit); \
+ dbus_error_init(&_error); \
+ _r = selinux_access_check(_c, _m, _u->source_path ?: _u->fragment_path, (permission), &_error); \
+ if (_r < 0) \
+ return bus_send_error_reply(_c, _m, &_error, _r); \
+ } while (false)
+
+#else
+
+#define SELINUX_ACCESS_CHECK(connection, message, permission) do { } while (false)
+#define SELINUX_UNIT_ACCESS_CHECK(unit, connection, message, permission) do { } while (false)
+
+#endif
diff --git a/src/core/selinux-setup.c b/src/core/selinux-setup.c
new file mode 100644
index 0000000000..7a32ed59a0
--- /dev/null
+++ b/src/core/selinux-setup.c
@@ -0,0 +1,120 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <unistd.h>
+#include <stdio.h>
+#include <errno.h>
+#include <string.h>
+#include <stdlib.h>
+
+#ifdef HAVE_SELINUX
+#include <selinux/selinux.h>
+#endif
+
+#include "selinux-setup.h"
+#include "selinux-util.h"
+#include "label.h"
+#include "mount-setup.h"
+#include "macro.h"
+#include "util.h"
+#include "log.h"
+
+#ifdef HAVE_SELINUX
+static int null_log(int type, const char *fmt, ...) {
+ return 0;
+}
+#endif
+
+int selinux_setup(bool *loaded_policy) {
+
+#ifdef HAVE_SELINUX
+ int enforce = 0;
+ usec_t before_load, after_load;
+ security_context_t con;
+ int r;
+ union selinux_callback cb;
+
+ assert(loaded_policy);
+
+ /* Turn off all of SELinux' own logging, we want to do that */
+ cb.func_log = null_log;
+ selinux_set_callback(SELINUX_CB_LOG, cb);
+
+ /* Already initialized by somebody else? */
+ r = getcon_raw(&con);
+ if (r == 0) {
+ bool initialized;
+
+ initialized = !streq(con, "kernel");
+ freecon(con);
+
+ if (initialized)
+ return 0;
+ }
+
+ /* Make sure we have no fds open while loading the policy and
+ * transitioning */
+ log_close();
+
+ /* Now load the policy */
+ before_load = now(CLOCK_MONOTONIC);
+ r = selinux_init_load_policy(&enforce);
+ if (r == 0) {
+ char timespan[FORMAT_TIMESPAN_MAX];
+ char *label;
+
+ retest_selinux();
+
+ /* Transition to the new context */
+ r = label_get_create_label_from_exe(SYSTEMD_BINARY_PATH, &label);
+ if (r < 0 || label == NULL) {
+ log_open();
+ log_error("Failed to compute init label, ignoring.");
+ } else {
+ r = setcon(label);
+
+ log_open();
+ if (r < 0)
+ log_error("Failed to transition into init label '%s', ignoring.", label);
+
+ label_free(label);
+ }
+
+ after_load = now(CLOCK_MONOTONIC);
+
+ log_info("Successfully loaded SELinux policy in %s.",
+ format_timespan(timespan, sizeof(timespan), after_load - before_load, 0));
+
+ *loaded_policy = true;
+
+ } else {
+ log_open();
+
+ if (enforce > 0) {
+ log_error("Failed to load SELinux policy. Freezing.");
+ return -EIO;
+ } else
+ log_debug("Unable to load SELinux policy. Ignoring.");
+ }
+#endif
+
+ return 0;
+}
diff --git a/src/core/selinux-setup.h b/src/core/selinux-setup.h
new file mode 100644
index 0000000000..39e2bc25bb
--- /dev/null
+++ b/src/core/selinux-setup.h
@@ -0,0 +1,26 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdbool.h>
+
+int selinux_setup(bool *loaded_policy);
diff --git a/src/core/service.c b/src/core/service.c
new file mode 100644
index 0000000000..3617c24711
--- /dev/null
+++ b/src/core/service.c
@@ -0,0 +1,3888 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <signal.h>
+#include <dirent.h>
+#include <unistd.h>
+#include <sys/reboot.h>
+
+#include "manager.h"
+#include "unit.h"
+#include "service.h"
+#include "load-fragment.h"
+#include "load-dropin.h"
+#include "log.h"
+#include "strv.h"
+#include "unit-name.h"
+#include "unit-printf.h"
+#include "dbus-service.h"
+#include "special.h"
+#include "dbus-common.h"
+#include "exit-status.h"
+#include "def.h"
+#include "path-util.h"
+#include "util.h"
+#include "utf8.h"
+#include "env-util.h"
+#include "fileio.h"
+
+#ifdef HAVE_SYSV_COMPAT
+
+#define DEFAULT_SYSV_TIMEOUT_USEC (5*USEC_PER_MINUTE)
+
+typedef enum RunlevelType {
+ RUNLEVEL_UP,
+ RUNLEVEL_DOWN
+} RunlevelType;
+
+static const struct {
+ const char *path;
+ const char *target;
+ const RunlevelType type;
+} rcnd_table[] = {
+ /* Standard SysV runlevels for start-up */
+ { "rc1.d", SPECIAL_RESCUE_TARGET, RUNLEVEL_UP },
+ { "rc2.d", SPECIAL_RUNLEVEL2_TARGET, RUNLEVEL_UP },
+ { "rc3.d", SPECIAL_RUNLEVEL3_TARGET, RUNLEVEL_UP },
+ { "rc4.d", SPECIAL_RUNLEVEL4_TARGET, RUNLEVEL_UP },
+ { "rc5.d", SPECIAL_RUNLEVEL5_TARGET, RUNLEVEL_UP },
+
+ /* Standard SysV runlevels for shutdown */
+ { "rc0.d", SPECIAL_POWEROFF_TARGET, RUNLEVEL_DOWN },
+ { "rc6.d", SPECIAL_REBOOT_TARGET, RUNLEVEL_DOWN }
+
+ /* Note that the order here matters, as we read the
+ directories in this order, and we want to make sure that
+ sysv_start_priority is known when we first load the
+ unit. And that value we only know from S links. Hence
+ UP must be read before DOWN */
+};
+
+#define RUNLEVELS_UP "12345"
+#endif
+
+static const UnitActiveState state_translation_table[_SERVICE_STATE_MAX] = {
+ [SERVICE_DEAD] = UNIT_INACTIVE,
+ [SERVICE_START_PRE] = UNIT_ACTIVATING,
+ [SERVICE_START] = UNIT_ACTIVATING,
+ [SERVICE_START_POST] = UNIT_ACTIVATING,
+ [SERVICE_RUNNING] = UNIT_ACTIVE,
+ [SERVICE_EXITED] = UNIT_ACTIVE,
+ [SERVICE_RELOAD] = UNIT_RELOADING,
+ [SERVICE_STOP] = UNIT_DEACTIVATING,
+ [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
+ [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
+ [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
+ [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
+ [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
+ [SERVICE_FAILED] = UNIT_FAILED,
+ [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
+};
+
+/* For Type=idle we never want to delay any other jobs, hence we
+ * consider idle jobs active as soon as we start working on them */
+static const UnitActiveState state_translation_table_idle[_SERVICE_STATE_MAX] = {
+ [SERVICE_DEAD] = UNIT_INACTIVE,
+ [SERVICE_START_PRE] = UNIT_ACTIVE,
+ [SERVICE_START] = UNIT_ACTIVE,
+ [SERVICE_START_POST] = UNIT_ACTIVE,
+ [SERVICE_RUNNING] = UNIT_ACTIVE,
+ [SERVICE_EXITED] = UNIT_ACTIVE,
+ [SERVICE_RELOAD] = UNIT_RELOADING,
+ [SERVICE_STOP] = UNIT_DEACTIVATING,
+ [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
+ [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
+ [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
+ [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
+ [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
+ [SERVICE_FAILED] = UNIT_FAILED,
+ [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
+};
+
+static void service_init(Unit *u) {
+ Service *s = SERVICE(u);
+
+ assert(u);
+ assert(u->load_state == UNIT_STUB);
+
+ s->timeout_start_usec = DEFAULT_TIMEOUT_USEC;
+ s->timeout_stop_usec = DEFAULT_TIMEOUT_USEC;
+ s->restart_usec = DEFAULT_RESTART_USEC;
+ s->type = _SERVICE_TYPE_INVALID;
+
+ watch_init(&s->watchdog_watch);
+ watch_init(&s->timer_watch);
+
+#ifdef HAVE_SYSV_COMPAT
+ s->sysv_start_priority = -1;
+ s->sysv_start_priority_from_rcnd = -1;
+#endif
+ s->socket_fd = -1;
+ s->guess_main_pid = true;
+
+ exec_context_init(&s->exec_context);
+ kill_context_init(&s->kill_context);
+
+ RATELIMIT_INIT(s->start_limit, 10*USEC_PER_SEC, 5);
+
+ s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
+}
+
+static void service_unwatch_control_pid(Service *s) {
+ assert(s);
+
+ if (s->control_pid <= 0)
+ return;
+
+ unit_unwatch_pid(UNIT(s), s->control_pid);
+ s->control_pid = 0;
+}
+
+static void service_unwatch_main_pid(Service *s) {
+ assert(s);
+
+ if (s->main_pid <= 0)
+ return;
+
+ unit_unwatch_pid(UNIT(s), s->main_pid);
+ s->main_pid = 0;
+}
+
+static void service_unwatch_pid_file(Service *s) {
+ if (!s->pid_file_pathspec)
+ return;
+
+ log_debug_unit(UNIT(s)->id, "Stopping watch for %s's PID file %s",
+ UNIT(s)->id, s->pid_file_pathspec->path);
+ path_spec_unwatch(s->pid_file_pathspec, UNIT(s));
+ path_spec_done(s->pid_file_pathspec);
+ free(s->pid_file_pathspec);
+ s->pid_file_pathspec = NULL;
+}
+
+static int service_set_main_pid(Service *s, pid_t pid) {
+ pid_t ppid;
+
+ assert(s);
+
+ if (pid <= 1)
+ return -EINVAL;
+
+ if (pid == getpid())
+ return -EINVAL;
+
+ s->main_pid = pid;
+ s->main_pid_known = true;
+
+ if (get_parent_of_pid(pid, &ppid) >= 0 && ppid != getpid()) {
+ log_warning_unit(UNIT(s)->id,
+ "%s: Supervising process %lu which is not our child. We'll most likely not notice when it exits.",
+ UNIT(s)->id, (unsigned long) pid);
+
+ s->main_pid_alien = true;
+ } else
+ s->main_pid_alien = false;
+
+ exec_status_start(&s->main_exec_status, pid);
+
+ return 0;
+}
+
+static void service_close_socket_fd(Service *s) {
+ assert(s);
+
+ if (s->socket_fd < 0)
+ return;
+
+ close_nointr_nofail(s->socket_fd);
+ s->socket_fd = -1;
+}
+
+static void service_connection_unref(Service *s) {
+ assert(s);
+
+ if (!UNIT_DEREF(s->accept_socket))
+ return;
+
+ socket_connection_unref(SOCKET(UNIT_DEREF(s->accept_socket)));
+ unit_ref_unset(&s->accept_socket);
+}
+
+static void service_stop_watchdog(Service *s) {
+ assert(s);
+
+ unit_unwatch_timer(UNIT(s), &s->watchdog_watch);
+ s->watchdog_timestamp.realtime = 0;
+ s->watchdog_timestamp.monotonic = 0;
+}
+
+static void service_enter_dead(Service *s, ServiceResult f, bool allow_restart);
+
+static void service_handle_watchdog(Service *s) {
+ usec_t offset;
+ int r;
+
+ assert(s);
+
+ if (s->watchdog_usec == 0)
+ return;
+
+ offset = now(CLOCK_MONOTONIC) - s->watchdog_timestamp.monotonic;
+ if (offset >= s->watchdog_usec) {
+ log_error_unit(UNIT(s)->id, "%s watchdog timeout!", UNIT(s)->id);
+ service_enter_dead(s, SERVICE_FAILURE_WATCHDOG, true);
+ return;
+ }
+
+ r = unit_watch_timer(UNIT(s), CLOCK_MONOTONIC, true, s->watchdog_usec - offset, &s->watchdog_watch);
+ if (r < 0)
+ log_warning_unit(UNIT(s)->id,
+ "%s failed to install watchdog timer: %s",
+ UNIT(s)->id, strerror(-r));
+}
+
+static void service_reset_watchdog(Service *s) {
+ assert(s);
+
+ dual_timestamp_get(&s->watchdog_timestamp);
+ service_handle_watchdog(s);
+}
+
+static void service_done(Unit *u) {
+ Service *s = SERVICE(u);
+
+ assert(s);
+
+ free(s->pid_file);
+ s->pid_file = NULL;
+
+#ifdef HAVE_SYSV_COMPAT
+ free(s->sysv_runlevels);
+ s->sysv_runlevels = NULL;
+#endif
+
+ free(s->status_text);
+ s->status_text = NULL;
+
+ exec_context_done(&s->exec_context, manager_is_reloading_or_reexecuting(u->manager));
+ exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
+ s->control_command = NULL;
+ s->main_command = NULL;
+
+ set_free(s->restart_ignore_status.code);
+ s->restart_ignore_status.code = NULL;
+ set_free(s->restart_ignore_status.signal);
+ s->restart_ignore_status.signal = NULL;
+
+ set_free(s->success_status.code);
+ s->success_status.code = NULL;
+ set_free(s->success_status.signal);
+ s->success_status.signal = NULL;
+
+ /* This will leak a process, but at least no memory or any of
+ * our resources */
+ service_unwatch_main_pid(s);
+ service_unwatch_control_pid(s);
+ service_unwatch_pid_file(s);
+
+ if (s->bus_name) {
+ unit_unwatch_bus_name(u, s->bus_name);
+ free(s->bus_name);
+ s->bus_name = NULL;
+ }
+
+ service_close_socket_fd(s);
+ service_connection_unref(s);
+
+ unit_ref_unset(&s->accept_socket);
+
+ service_stop_watchdog(s);
+
+ unit_unwatch_timer(u, &s->timer_watch);
+}
+
+#ifdef HAVE_SYSV_COMPAT
+static char *sysv_translate_name(const char *name) {
+ char *r;
+
+ r = new(char, strlen(name) + sizeof(".service"));
+ if (!r)
+ return NULL;
+
+ if (endswith(name, ".sh"))
+ /* Drop .sh suffix */
+ strcpy(stpcpy(r, name) - 3, ".service");
+ else
+ /* Normal init script name */
+ strcpy(stpcpy(r, name), ".service");
+
+ return r;
+}
+
+static int sysv_translate_facility(const char *name, const char *filename, char **_r) {
+
+ /* We silently ignore the $ prefix here. According to the LSB
+ * spec it simply indicates whether something is a
+ * standardized name or a distribution-specific one. Since we
+ * just follow what already exists and do not introduce new
+ * uses or names we don't care who introduced a new name. */
+
+ static const char * const table[] = {
+ /* LSB defined facilities */
+ "local_fs", NULL,
+ "network", SPECIAL_NETWORK_TARGET,
+ "named", SPECIAL_NSS_LOOKUP_TARGET,
+ "portmap", SPECIAL_RPCBIND_TARGET,
+ "remote_fs", SPECIAL_REMOTE_FS_TARGET,
+ "syslog", NULL,
+ "time", SPECIAL_TIME_SYNC_TARGET,
+ };
+
+ unsigned i;
+ char *r;
+ const char *n;
+
+ assert(name);
+ assert(_r);
+
+ n = *name == '$' ? name + 1 : name;
+
+ for (i = 0; i < ELEMENTSOF(table); i += 2) {
+
+ if (!streq(table[i], n))
+ continue;
+
+ if (!table[i+1])
+ return 0;
+
+ r = strdup(table[i+1]);
+ if (!r)
+ return log_oom();
+
+ goto finish;
+ }
+
+ /* If we don't know this name, fallback heuristics to figure
+ * out whether something is a target or a service alias. */
+
+ if (*name == '$') {
+ if (!unit_prefix_is_valid(n))
+ return -EINVAL;
+
+ /* Facilities starting with $ are most likely targets */
+ r = unit_name_build(n, NULL, ".target");
+ } else if (filename && streq(name, filename))
+ /* Names equaling the file name of the services are redundant */
+ return 0;
+ else
+ /* Everything else we assume to be normal service names */
+ r = sysv_translate_name(n);
+
+ if (!r)
+ return -ENOMEM;
+
+finish:
+ *_r = r;
+
+ return 1;
+}
+
+static int sysv_fix_order(Service *s) {
+ Unit *other;
+ int r;
+
+ assert(s);
+
+ if (s->sysv_start_priority < 0)
+ return 0;
+
+ /* For each pair of services where at least one lacks a LSB
+ * header, we use the start priority value to order things. */
+
+ LIST_FOREACH(units_by_type, other, UNIT(s)->manager->units_by_type[UNIT_SERVICE]) {
+ Service *t;
+ UnitDependency d;
+ bool special_s, special_t;
+
+ t = SERVICE(other);
+
+ if (s == t)
+ continue;
+
+ if (UNIT(t)->load_state != UNIT_LOADED)
+ continue;
+
+ if (t->sysv_start_priority < 0)
+ continue;
+
+ /* If both units have modern headers we don't care
+ * about the priorities */
+ if ((UNIT(s)->fragment_path || s->sysv_has_lsb) &&
+ (UNIT(t)->fragment_path || t->sysv_has_lsb))
+ continue;
+
+ special_s = s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels);
+ special_t = t->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, t->sysv_runlevels);
+
+ if (special_t && !special_s)
+ d = UNIT_AFTER;
+ else if (special_s && !special_t)
+ d = UNIT_BEFORE;
+ else if (t->sysv_start_priority < s->sysv_start_priority)
+ d = UNIT_AFTER;
+ else if (t->sysv_start_priority > s->sysv_start_priority)
+ d = UNIT_BEFORE;
+ else
+ continue;
+
+ /* FIXME: Maybe we should compare the name here lexicographically? */
+
+ if ((r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static ExecCommand *exec_command_new(const char *path, const char *arg1) {
+ ExecCommand *c;
+
+ if (!(c = new0(ExecCommand, 1)))
+ return NULL;
+
+ if (!(c->path = strdup(path))) {
+ free(c);
+ return NULL;
+ }
+
+ if (!(c->argv = strv_new(path, arg1, NULL))) {
+ free(c->path);
+ free(c);
+ return NULL;
+ }
+
+ return c;
+}
+
+static int sysv_exec_commands(Service *s, const bool supports_reload) {
+ ExecCommand *c;
+
+ assert(s);
+ assert(s->is_sysv);
+ assert(UNIT(s)->source_path);
+
+ c = exec_command_new(UNIT(s)->source_path, "start");
+ if (!c)
+ return -ENOMEM;
+ exec_command_append_list(s->exec_command+SERVICE_EXEC_START, c);
+
+ c = exec_command_new(UNIT(s)->source_path, "stop");
+ if (!c)
+ return -ENOMEM;
+ exec_command_append_list(s->exec_command+SERVICE_EXEC_STOP, c);
+
+ if (supports_reload) {
+ c = exec_command_new(UNIT(s)->source_path, "reload");
+ if (!c)
+ return -ENOMEM;
+ exec_command_append_list(s->exec_command+SERVICE_EXEC_RELOAD, c);
+ }
+
+ return 0;
+}
+
+static bool usage_contains_reload(const char *line) {
+ return (strcasestr(line, "{reload|") ||
+ strcasestr(line, "{reload}") ||
+ strcasestr(line, "{reload\"") ||
+ strcasestr(line, "|reload|") ||
+ strcasestr(line, "|reload}") ||
+ strcasestr(line, "|reload\""));
+}
+
+static int service_load_sysv_path(Service *s, const char *path) {
+ FILE *f;
+ Unit *u;
+ unsigned line = 0;
+ int r;
+ enum {
+ NORMAL,
+ DESCRIPTION,
+ LSB,
+ LSB_DESCRIPTION,
+ USAGE_CONTINUATION
+ } state = NORMAL;
+ char *short_description = NULL, *long_description = NULL, *chkconfig_description = NULL, *description;
+ struct stat st;
+ bool supports_reload = false;
+
+ assert(s);
+ assert(path);
+
+ u = UNIT(s);
+
+ f = fopen(path, "re");
+ if (!f) {
+ r = errno == ENOENT ? 0 : -errno;
+ goto finish;
+ }
+
+ if (fstat(fileno(f), &st) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ free(u->source_path);
+ u->source_path = strdup(path);
+ if (!u->source_path) {
+ r = -ENOMEM;
+ goto finish;
+ }
+ u->source_mtime = timespec_load(&st.st_mtim);
+
+ if (null_or_empty(&st)) {
+ u->load_state = UNIT_MASKED;
+ r = 0;
+ goto finish;
+ }
+
+ s->is_sysv = true;
+
+ while (!feof(f)) {
+ char l[LINE_MAX], *t;
+
+ if (!fgets(l, sizeof(l), f)) {
+ if (feof(f))
+ break;
+
+ r = -errno;
+ log_error_unit(u->id,
+ "Failed to read configuration file '%s': %s",
+ path, strerror(-r));
+ goto finish;
+ }
+
+ line++;
+
+ t = strstrip(l);
+ if (*t != '#') {
+ /* Try to figure out whether this init script supports
+ * the reload operation. This heuristic looks for
+ * "Usage" lines which include the reload option. */
+ if ( state == USAGE_CONTINUATION ||
+ (state == NORMAL && strcasestr(t, "usage"))) {
+ if (usage_contains_reload(t)) {
+ supports_reload = true;
+ state = NORMAL;
+ } else if (t[strlen(t)-1] == '\\')
+ state = USAGE_CONTINUATION;
+ else
+ state = NORMAL;
+ }
+
+ continue;
+ }
+
+ if (state == NORMAL && streq(t, "### BEGIN INIT INFO")) {
+ state = LSB;
+ s->sysv_has_lsb = true;
+ continue;
+ }
+
+ if ((state == LSB_DESCRIPTION || state == LSB) && streq(t, "### END INIT INFO")) {
+ state = NORMAL;
+ continue;
+ }
+
+ t++;
+ t += strspn(t, WHITESPACE);
+
+ if (state == NORMAL) {
+
+ /* Try to parse Red Hat style chkconfig headers */
+
+ if (startswith_no_case(t, "chkconfig:")) {
+ int start_priority;
+ char runlevels[16], *k;
+
+ state = NORMAL;
+
+ if (sscanf(t+10, "%15s %i %*i",
+ runlevels,
+ &start_priority) != 2) {
+
+ log_warning_unit(u->id,
+ "[%s:%u] Failed to parse chkconfig line. Ignoring.",
+ path, line);
+ continue;
+ }
+
+ /* A start priority gathered from the
+ * symlink farms is preferred over the
+ * data from the LSB header. */
+ if (start_priority < 0 || start_priority > 99)
+ log_warning_unit(u->id,
+ "[%s:%u] Start priority out of range. Ignoring.",
+ path, line);
+ else
+ s->sysv_start_priority = start_priority;
+
+ char_array_0(runlevels);
+ k = delete_chars(runlevels, WHITESPACE "-");
+
+ if (k[0]) {
+ char *d;
+
+ if (!(d = strdup(k))) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ free(s->sysv_runlevels);
+ s->sysv_runlevels = d;
+ }
+
+ } else if (startswith_no_case(t, "description:")) {
+
+ size_t k = strlen(t);
+ char *d;
+ const char *j;
+
+ if (t[k-1] == '\\') {
+ state = DESCRIPTION;
+ t[k-1] = 0;
+ }
+
+ if ((j = strstrip(t+12)) && *j) {
+ if (!(d = strdup(j))) {
+ r = -ENOMEM;
+ goto finish;
+ }
+ } else
+ d = NULL;
+
+ free(chkconfig_description);
+ chkconfig_description = d;
+
+ } else if (startswith_no_case(t, "pidfile:")) {
+
+ char *fn;
+
+ state = NORMAL;
+
+ fn = strstrip(t+8);
+ if (!path_is_absolute(fn)) {
+ log_warning_unit(u->id,
+ "[%s:%u] PID file not absolute. Ignoring.",
+ path, line);
+ continue;
+ }
+
+ if (!(fn = strdup(fn))) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ free(s->pid_file);
+ s->pid_file = fn;
+ }
+
+ } else if (state == DESCRIPTION) {
+
+ /* Try to parse Red Hat style description
+ * continuation */
+
+ size_t k = strlen(t);
+ char *j;
+
+ if (t[k-1] == '\\')
+ t[k-1] = 0;
+ else
+ state = NORMAL;
+
+ if ((j = strstrip(t)) && *j) {
+ char *d = NULL;
+
+ if (chkconfig_description)
+ d = strjoin(chkconfig_description, " ", j, NULL);
+ else
+ d = strdup(j);
+
+ if (!d) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ free(chkconfig_description);
+ chkconfig_description = d;
+ }
+
+ } else if (state == LSB || state == LSB_DESCRIPTION) {
+
+ if (startswith_no_case(t, "Provides:")) {
+ char *i, *w;
+ size_t z;
+
+ state = LSB;
+
+ FOREACH_WORD_QUOTED(w, z, t+9, i) {
+ char *n, *m;
+
+ if (!(n = strndup(w, z))) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ r = sysv_translate_facility(n, path_get_file_name(path), &m);
+ free(n);
+
+ if (r < 0)
+ goto finish;
+
+ if (r == 0)
+ continue;
+
+ if (unit_name_to_type(m) == UNIT_SERVICE)
+ r = unit_merge_by_name(u, m);
+ else
+ /* NB: SysV targets
+ * which are provided
+ * by a service are
+ * pulled in by the
+ * services, as an
+ * indication that the
+ * generic service is
+ * now available. This
+ * is strictly
+ * one-way. The
+ * targets do NOT pull
+ * in the SysV
+ * services! */
+ r = unit_add_two_dependencies_by_name(u, UNIT_BEFORE, UNIT_WANTS, m, NULL, true);
+
+ if (r < 0)
+ log_error_unit(u->id,
+ "[%s:%u] Failed to add LSB Provides name %s, ignoring: %s",
+ path, line, m, strerror(-r));
+
+ free(m);
+ }
+
+ } else if (startswith_no_case(t, "Required-Start:") ||
+ startswith_no_case(t, "Should-Start:") ||
+ startswith_no_case(t, "X-Start-Before:") ||
+ startswith_no_case(t, "X-Start-After:")) {
+ char *i, *w;
+ size_t z;
+
+ state = LSB;
+
+ FOREACH_WORD_QUOTED(w, z, strchr(t, ':')+1, i) {
+ char *n, *m;
+
+ if (!(n = strndup(w, z))) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ r = sysv_translate_facility(n, path_get_file_name(path), &m);
+ if (r < 0) {
+ log_error_unit(u->id,
+ "[%s:%u] Failed to translate LSB dependency %s, ignoring: %s",
+ path, line, n, strerror(-r));
+ free(n);
+ continue;
+ }
+
+ free(n);
+
+ if (r == 0)
+ continue;
+
+ r = unit_add_dependency_by_name(u, startswith_no_case(t, "X-Start-Before:") ? UNIT_BEFORE : UNIT_AFTER, m, NULL, true);
+
+ if (r < 0)
+ log_error_unit(u->id, "[%s:%u] Failed to add dependency on %s, ignoring: %s",
+ path, line, m, strerror(-r));
+
+ free(m);
+ }
+ } else if (startswith_no_case(t, "Default-Start:")) {
+ char *k, *d;
+
+ state = LSB;
+
+ k = delete_chars(t+14, WHITESPACE "-");
+
+ if (k[0] != 0) {
+ if (!(d = strdup(k))) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ free(s->sysv_runlevels);
+ s->sysv_runlevels = d;
+ }
+
+ } else if (startswith_no_case(t, "Description:")) {
+ char *d, *j;
+
+ state = LSB_DESCRIPTION;
+
+ if ((j = strstrip(t+12)) && *j) {
+ if (!(d = strdup(j))) {
+ r = -ENOMEM;
+ goto finish;
+ }
+ } else
+ d = NULL;
+
+ free(long_description);
+ long_description = d;
+
+ } else if (startswith_no_case(t, "Short-Description:")) {
+ char *d, *j;
+
+ state = LSB;
+
+ if ((j = strstrip(t+18)) && *j) {
+ if (!(d = strdup(j))) {
+ r = -ENOMEM;
+ goto finish;
+ }
+ } else
+ d = NULL;
+
+ free(short_description);
+ short_description = d;
+
+ } else if (state == LSB_DESCRIPTION) {
+
+ if (startswith(l, "#\t") || startswith(l, "# ")) {
+ char *j;
+
+ if ((j = strstrip(t)) && *j) {
+ char *d = NULL;
+
+ if (long_description)
+ d = strjoin(long_description, " ", t, NULL);
+ else
+ d = strdup(j);
+
+ if (!d) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ free(long_description);
+ long_description = d;
+ }
+
+ } else
+ state = LSB;
+ }
+ }
+ }
+
+ if ((r = sysv_exec_commands(s, supports_reload)) < 0)
+ goto finish;
+
+ if (s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
+ /* If there a runlevels configured for this service
+ * but none of the standard ones, then we assume this
+ * is some special kind of service (which might be
+ * needed for early boot) and don't create any links
+ * to it. */
+
+ UNIT(s)->default_dependencies = false;
+
+ /* Don't timeout special services during boot (like fsck) */
+ s->timeout_start_usec = 0;
+ s->timeout_stop_usec = 0;
+ } else {
+ s->timeout_start_usec = DEFAULT_SYSV_TIMEOUT_USEC;
+ s->timeout_stop_usec = DEFAULT_SYSV_TIMEOUT_USEC;
+ }
+
+ /* Special setting for all SysV services */
+ s->type = SERVICE_FORKING;
+ s->remain_after_exit = !s->pid_file;
+ s->guess_main_pid = false;
+ s->restart = SERVICE_RESTART_NO;
+ s->exec_context.ignore_sigpipe = false;
+ s->kill_context.kill_mode = KILL_PROCESS;
+
+ /* We use the long description only if
+ * no short description is set. */
+
+ if (short_description)
+ description = short_description;
+ else if (chkconfig_description)
+ description = chkconfig_description;
+ else if (long_description)
+ description = long_description;
+ else
+ description = NULL;
+
+ if (description) {
+ char *d;
+
+ if (!(d = strappend(s->sysv_has_lsb ? "LSB: " : "SYSV: ", description))) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ u->description = d;
+ }
+
+ /* The priority that has been set in /etc/rcN.d/ hierarchies
+ * takes precedence over what is stored as default in the LSB
+ * header */
+ if (s->sysv_start_priority_from_rcnd >= 0)
+ s->sysv_start_priority = s->sysv_start_priority_from_rcnd;
+
+ u->load_state = UNIT_LOADED;
+ r = 0;
+
+finish:
+
+ if (f)
+ fclose(f);
+
+ free(short_description);
+ free(long_description);
+ free(chkconfig_description);
+
+ return r;
+}
+
+static int service_load_sysv_name(Service *s, const char *name) {
+ char **p;
+
+ assert(s);
+ assert(name);
+
+ /* For SysV services we strip the *.sh suffixes. */
+ if (endswith(name, ".sh.service"))
+ return -ENOENT;
+
+ STRV_FOREACH(p, UNIT(s)->manager->lookup_paths.sysvinit_path) {
+ char *path;
+ int r;
+
+ path = strjoin(*p, "/", name, NULL);
+ if (!path)
+ return -ENOMEM;
+
+ assert(endswith(path, ".service"));
+ path[strlen(path)-8] = 0;
+
+ r = service_load_sysv_path(s, path);
+
+ if (r >= 0 && UNIT(s)->load_state == UNIT_STUB) {
+ /* Try *.sh source'able init scripts */
+ strcat(path, ".sh");
+ r = service_load_sysv_path(s, path);
+ }
+ free(path);
+
+ if (r < 0)
+ return r;
+
+ if (UNIT(s)->load_state != UNIT_STUB)
+ break;
+ }
+
+ return 0;
+}
+
+static int service_load_sysv(Service *s) {
+ const char *t;
+ Iterator i;
+ int r;
+
+ assert(s);
+
+ /* Load service data from SysV init scripts, preferably with
+ * LSB headers ... */
+
+ if (strv_isempty(UNIT(s)->manager->lookup_paths.sysvinit_path))
+ return 0;
+
+ if ((t = UNIT(s)->id))
+ if ((r = service_load_sysv_name(s, t)) < 0)
+ return r;
+
+ if (UNIT(s)->load_state == UNIT_STUB)
+ SET_FOREACH(t, UNIT(s)->names, i) {
+ if (t == UNIT(s)->id)
+ continue;
+
+ if ((r = service_load_sysv_name(s, t)) < 0)
+ return r;
+
+ if (UNIT(s)->load_state != UNIT_STUB)
+ break;
+ }
+
+ return 0;
+}
+#endif
+
+static int fsck_fix_order(Service *s) {
+ Unit *other;
+ int r;
+
+ assert(s);
+
+ if (s->fsck_passno <= 0)
+ return 0;
+
+ /* For each pair of services where both have an fsck priority
+ * we order things based on it. */
+
+ LIST_FOREACH(units_by_type, other, UNIT(s)->manager->units_by_type[UNIT_SERVICE]) {
+ Service *t;
+ UnitDependency d;
+
+ t = SERVICE(other);
+
+ if (s == t)
+ continue;
+
+ if (UNIT(t)->load_state != UNIT_LOADED)
+ continue;
+
+ if (t->fsck_passno <= 0)
+ continue;
+
+ if (t->fsck_passno < s->fsck_passno)
+ d = UNIT_AFTER;
+ else if (t->fsck_passno > s->fsck_passno)
+ d = UNIT_BEFORE;
+ else
+ continue;
+
+ r = unit_add_dependency(UNIT(s), d, UNIT(t), true);
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static int service_verify(Service *s) {
+ assert(s);
+
+ if (UNIT(s)->load_state != UNIT_LOADED)
+ return 0;
+
+ if (!s->exec_command[SERVICE_EXEC_START]) {
+ log_error_unit(UNIT(s)->id,
+ "%s lacks ExecStart setting. Refusing.", UNIT(s)->id);
+ return -EINVAL;
+ }
+
+ if (s->type != SERVICE_ONESHOT &&
+ s->exec_command[SERVICE_EXEC_START]->command_next) {
+ log_error_unit(UNIT(s)->id,
+ "%s has more than one ExecStart setting, which is only allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
+ return -EINVAL;
+ }
+
+ if (s->type == SERVICE_DBUS && !s->bus_name) {
+ log_error_unit(UNIT(s)->id,
+ "%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", UNIT(s)->id);
+ return -EINVAL;
+ }
+
+ if (s->bus_name && s->type != SERVICE_DBUS)
+ log_warning_unit(UNIT(s)->id,
+ "%s has a D-Bus service name specified, but is not of type dbus. Ignoring.", UNIT(s)->id);
+
+ if (s->exec_context.pam_name && s->kill_context.kill_mode != KILL_CONTROL_GROUP) {
+ log_error_unit(UNIT(s)->id,
+ "%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", UNIT(s)->id);
+ return -EINVAL;
+ }
+
+ return 0;
+}
+
+static int service_add_default_dependencies(Service *s) {
+ int r;
+
+ assert(s);
+
+ /* Add a number of automatic dependencies useful for the
+ * majority of services. */
+
+ /* First, pull in base system */
+ if (UNIT(s)->manager->running_as == SYSTEMD_SYSTEM) {
+ r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES,
+ SPECIAL_BASIC_TARGET, NULL, true);
+ if (r < 0)
+ return r;
+
+ } else if (UNIT(s)->manager->running_as == SYSTEMD_USER) {
+ r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES,
+ SPECIAL_SOCKETS_TARGET, NULL, true);
+ if (r < 0)
+ return r;
+
+ r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES,
+ SPECIAL_TIMERS_TARGET, NULL, true);
+ if (r < 0)
+ return r;
+
+ r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES,
+ SPECIAL_PATHS_TARGET, NULL, true);
+ if (r < 0)
+ return r;
+ }
+
+ /* Second, activate normal shutdown */
+ r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS,
+ SPECIAL_SHUTDOWN_TARGET, NULL, true);
+ return r;
+}
+
+static void service_fix_output(Service *s) {
+ assert(s);
+
+ /* If nothing has been explicitly configured, patch default
+ * output in. If input is socket/tty we avoid this however,
+ * since in that case we want output to default to the same
+ * place as we read input from. */
+
+ if (s->exec_context.std_error == EXEC_OUTPUT_INHERIT &&
+ s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
+ s->exec_context.std_input == EXEC_INPUT_NULL)
+ s->exec_context.std_error = UNIT(s)->manager->default_std_error;
+
+ if (s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
+ s->exec_context.std_input == EXEC_INPUT_NULL)
+ s->exec_context.std_output = UNIT(s)->manager->default_std_output;
+}
+
+static int service_load(Unit *u) {
+ int r;
+ Service *s = SERVICE(u);
+
+ assert(s);
+
+ /* Load a .service file */
+ if ((r = unit_load_fragment(u)) < 0)
+ return r;
+
+#ifdef HAVE_SYSV_COMPAT
+ /* Load a classic init script as a fallback, if we couldn't find anything */
+ if (u->load_state == UNIT_STUB)
+ if ((r = service_load_sysv(s)) < 0)
+ return r;
+#endif
+
+ /* Still nothing found? Then let's give up */
+ if (u->load_state == UNIT_STUB)
+ return -ENOENT;
+
+ /* We were able to load something, then let's add in the
+ * dropin directories. */
+ if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
+ return r;
+
+ /* This is a new unit? Then let's add in some extras */
+ if (u->load_state == UNIT_LOADED) {
+ if (s->type == _SERVICE_TYPE_INVALID)
+ s->type = s->bus_name ? SERVICE_DBUS : SERVICE_SIMPLE;
+
+ /* Oneshot services have disabled start timeout by default */
+ if (s->type == SERVICE_ONESHOT && !s->start_timeout_defined)
+ s->timeout_start_usec = 0;
+
+ service_fix_output(s);
+
+ r = unit_add_exec_dependencies(u, &s->exec_context);
+ if (r < 0)
+ return r;
+
+ r = unit_add_default_cgroups(u);
+ if (r < 0)
+ return r;
+
+#ifdef HAVE_SYSV_COMPAT
+ r = sysv_fix_order(s);
+ if (r < 0)
+ return r;
+#endif
+
+ r = fsck_fix_order(s);
+ if (r < 0)
+ return r;
+
+ if (s->bus_name)
+ if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
+ return r;
+
+ if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
+ s->notify_access = NOTIFY_MAIN;
+
+ if (s->watchdog_usec > 0 && s->notify_access == NOTIFY_NONE)
+ s->notify_access = NOTIFY_MAIN;
+
+ if (s->type == SERVICE_DBUS || s->bus_name) {
+ r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES,
+ SPECIAL_DBUS_SOCKET, NULL, true);
+ if (r < 0)
+ return r;
+ }
+
+ if (UNIT(s)->default_dependencies) {
+ r = service_add_default_dependencies(s);
+ if (r < 0)
+ return r;
+ }
+
+ r = unit_exec_context_defaults(u, &s->exec_context);
+ if (r < 0)
+ return r;
+ }
+
+ return service_verify(s);
+}
+
+static void service_dump(Unit *u, FILE *f, const char *prefix) {
+
+ ServiceExecCommand c;
+ Service *s = SERVICE(u);
+ const char *prefix2;
+ _cleanup_free_ char *p2 = NULL;
+
+ assert(s);
+
+ p2 = strappend(prefix, "\t");
+ prefix2 = p2 ? p2 : prefix;
+
+ fprintf(f,
+ "%sService State: %s\n"
+ "%sResult: %s\n"
+ "%sReload Result: %s\n"
+ "%sPermissionsStartOnly: %s\n"
+ "%sRootDirectoryStartOnly: %s\n"
+ "%sRemainAfterExit: %s\n"
+ "%sGuessMainPID: %s\n"
+ "%sType: %s\n"
+ "%sRestart: %s\n"
+ "%sNotifyAccess: %s\n",
+ prefix, service_state_to_string(s->state),
+ prefix, service_result_to_string(s->result),
+ prefix, service_result_to_string(s->reload_result),
+ prefix, yes_no(s->permissions_start_only),
+ prefix, yes_no(s->root_directory_start_only),
+ prefix, yes_no(s->remain_after_exit),
+ prefix, yes_no(s->guess_main_pid),
+ prefix, service_type_to_string(s->type),
+ prefix, service_restart_to_string(s->restart),
+ prefix, notify_access_to_string(s->notify_access));
+
+ if (s->control_pid > 0)
+ fprintf(f,
+ "%sControl PID: %lu\n",
+ prefix, (unsigned long) s->control_pid);
+
+ if (s->main_pid > 0)
+ fprintf(f,
+ "%sMain PID: %lu\n"
+ "%sMain PID Known: %s\n"
+ "%sMain PID Alien: %s\n",
+ prefix, (unsigned long) s->main_pid,
+ prefix, yes_no(s->main_pid_known),
+ prefix, yes_no(s->main_pid_alien));
+
+ if (s->pid_file)
+ fprintf(f,
+ "%sPIDFile: %s\n",
+ prefix, s->pid_file);
+
+ if (s->bus_name)
+ fprintf(f,
+ "%sBusName: %s\n"
+ "%sBus Name Good: %s\n",
+ prefix, s->bus_name,
+ prefix, yes_no(s->bus_name_good));
+
+ kill_context_dump(&s->kill_context, f, prefix);
+ exec_context_dump(&s->exec_context, f, prefix);
+
+ for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
+
+ if (!s->exec_command[c])
+ continue;
+
+ fprintf(f, "%s-> %s:\n",
+ prefix, service_exec_command_to_string(c));
+
+ exec_command_dump_list(s->exec_command[c], f, prefix2);
+ }
+
+#ifdef HAVE_SYSV_COMPAT
+ if (s->is_sysv)
+ fprintf(f,
+ "%sSysV Init Script has LSB Header: %s\n"
+ "%sSysVEnabled: %s\n",
+ prefix, yes_no(s->sysv_has_lsb),
+ prefix, yes_no(s->sysv_enabled));
+
+ if (s->sysv_start_priority >= 0)
+ fprintf(f,
+ "%sSysVStartPriority: %i\n",
+ prefix, s->sysv_start_priority);
+
+ if (s->sysv_runlevels)
+ fprintf(f, "%sSysVRunLevels: %s\n",
+ prefix, s->sysv_runlevels);
+#endif
+
+ if (s->fsck_passno > 0)
+ fprintf(f,
+ "%sFsckPassNo: %i\n",
+ prefix, s->fsck_passno);
+
+ if (s->status_text)
+ fprintf(f, "%sStatus Text: %s\n",
+ prefix, s->status_text);
+}
+
+static int service_load_pid_file(Service *s, bool may_warn) {
+ _cleanup_free_ char *k = NULL;
+ int r;
+ pid_t pid;
+
+ assert(s);
+
+ if (!s->pid_file)
+ return -ENOENT;
+
+ r = read_one_line_file(s->pid_file, &k);
+ if (r < 0) {
+ if (may_warn)
+ log_info_unit(UNIT(s)->id,
+ "PID file %s not readable (yet?) after %s.",
+ s->pid_file, service_state_to_string(s->state));
+ return r;
+ }
+
+ r = parse_pid(k, &pid);
+ if (r < 0) {
+ if (may_warn)
+ log_info_unit(UNIT(s)->id,
+ "Failed to read PID from file %s: %s",
+ s->pid_file, strerror(-r));
+ return r;
+ }
+
+ if (kill(pid, 0) < 0 && errno != EPERM) {
+ if (may_warn)
+ log_info_unit(UNIT(s)->id,
+ "PID %lu read from file %s does not exist.",
+ (unsigned long) pid, s->pid_file);
+ return -ESRCH;
+ }
+
+ if (s->main_pid_known) {
+ if (pid == s->main_pid)
+ return 0;
+
+ log_debug_unit(UNIT(s)->id,
+ "Main PID changing: %lu -> %lu",
+ (unsigned long) s->main_pid, (unsigned long) pid);
+ service_unwatch_main_pid(s);
+ s->main_pid_known = false;
+ } else
+ log_debug_unit(UNIT(s)->id,
+ "Main PID loaded: %lu", (unsigned long) pid);
+
+ r = service_set_main_pid(s, pid);
+ if (r < 0)
+ return r;
+
+ r = unit_watch_pid(UNIT(s), pid);
+ if (r < 0) {
+ /* FIXME: we need to do something here */
+ log_warning_unit(UNIT(s)->id,
+ "Failed to watch PID %lu from service %s",
+ (unsigned long) pid, UNIT(s)->id);
+ return r;
+ }
+
+ return 0;
+}
+
+static int service_search_main_pid(Service *s) {
+ pid_t pid;
+ int r;
+
+ assert(s);
+
+ /* If we know it anyway, don't ever fallback to unreliable
+ * heuristics */
+ if (s->main_pid_known)
+ return 0;
+
+ if (!s->guess_main_pid)
+ return 0;
+
+ assert(s->main_pid <= 0);
+
+ pid = cgroup_bonding_search_main_pid_list(UNIT(s)->cgroup_bondings);
+ if (pid <= 0)
+ return -ENOENT;
+
+ log_debug_unit(UNIT(s)->id,
+ "Main PID guessed: %lu", (unsigned long) pid);
+ r = service_set_main_pid(s, pid);
+ if (r < 0)
+ return r;
+
+ r = unit_watch_pid(UNIT(s), pid);
+ if (r < 0)
+ /* FIXME: we need to do something here */
+ log_warning_unit(UNIT(s)->id,
+ "Failed to watch PID %lu from service %s",
+ (unsigned long) pid, UNIT(s)->id);
+ return r;
+
+ return 0;
+}
+
+static void service_notify_sockets_dead(Service *s, bool failed_permanent) {
+ Iterator i;
+ Unit *u;
+
+ assert(s);
+
+ /* Notifies all our sockets when we die */
+
+ if (s->socket_fd >= 0)
+ return;
+
+ SET_FOREACH(u, UNIT(s)->dependencies[UNIT_TRIGGERED_BY], i)
+ if (u->type == UNIT_SOCKET)
+ socket_notify_service_dead(SOCKET(u), failed_permanent);
+
+ return;
+}
+
+static void service_set_state(Service *s, ServiceState state) {
+ ServiceState old_state;
+ const UnitActiveState *table;
+ assert(s);
+
+ table = s->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
+
+ old_state = s->state;
+ s->state = state;
+
+ service_unwatch_pid_file(s);
+
+ if (state != SERVICE_START_PRE &&
+ state != SERVICE_START &&
+ state != SERVICE_START_POST &&
+ state != SERVICE_RELOAD &&
+ state != SERVICE_STOP &&
+ state != SERVICE_STOP_SIGTERM &&
+ state != SERVICE_STOP_SIGKILL &&
+ state != SERVICE_STOP_POST &&
+ state != SERVICE_FINAL_SIGTERM &&
+ state != SERVICE_FINAL_SIGKILL &&
+ state != SERVICE_AUTO_RESTART)
+ unit_unwatch_timer(UNIT(s), &s->timer_watch);
+
+ if (state != SERVICE_START &&
+ state != SERVICE_START_POST &&
+ state != SERVICE_RUNNING &&
+ state != SERVICE_RELOAD &&
+ state != SERVICE_STOP &&
+ state != SERVICE_STOP_SIGTERM &&
+ state != SERVICE_STOP_SIGKILL) {
+ service_unwatch_main_pid(s);
+ s->main_command = NULL;
+ }
+
+ if (state != SERVICE_START_PRE &&
+ state != SERVICE_START &&
+ state != SERVICE_START_POST &&
+ state != SERVICE_RELOAD &&
+ state != SERVICE_STOP &&
+ state != SERVICE_STOP_SIGTERM &&
+ state != SERVICE_STOP_SIGKILL &&
+ state != SERVICE_STOP_POST &&
+ state != SERVICE_FINAL_SIGTERM &&
+ state != SERVICE_FINAL_SIGKILL) {
+ service_unwatch_control_pid(s);
+ s->control_command = NULL;
+ s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
+ }
+
+ if (state == SERVICE_FAILED)
+ service_notify_sockets_dead(s, s->result == SERVICE_FAILURE_START_LIMIT);
+
+ if (state == SERVICE_DEAD ||
+ state == SERVICE_STOP ||
+ state == SERVICE_STOP_SIGTERM ||
+ state == SERVICE_STOP_SIGKILL ||
+ state == SERVICE_STOP_POST ||
+ state == SERVICE_FINAL_SIGTERM ||
+ state == SERVICE_FINAL_SIGKILL ||
+ state == SERVICE_AUTO_RESTART)
+ service_notify_sockets_dead(s, false);
+
+ if (state != SERVICE_START_PRE &&
+ state != SERVICE_START &&
+ state != SERVICE_START_POST &&
+ state != SERVICE_RUNNING &&
+ state != SERVICE_RELOAD &&
+ state != SERVICE_STOP &&
+ state != SERVICE_STOP_SIGTERM &&
+ state != SERVICE_STOP_SIGKILL &&
+ state != SERVICE_STOP_POST &&
+ state != SERVICE_FINAL_SIGTERM &&
+ state != SERVICE_FINAL_SIGKILL &&
+ !(state == SERVICE_DEAD && UNIT(s)->job)) {
+ service_close_socket_fd(s);
+ service_connection_unref(s);
+ }
+
+ if (state == SERVICE_STOP || state == SERVICE_STOP_SIGTERM)
+ service_stop_watchdog(s);
+
+ /* For the inactive states unit_notify() will trim the cgroup,
+ * but for exit we have to do that ourselves... */
+ if (state == SERVICE_EXITED && UNIT(s)->manager->n_reloading <= 0)
+ cgroup_bonding_trim_list(UNIT(s)->cgroup_bondings, true);
+
+ if (old_state != state)
+ log_debug_unit(UNIT(s)->id,
+ "%s changed %s -> %s", UNIT(s)->id,
+ service_state_to_string(old_state),
+ service_state_to_string(state));
+
+ unit_notify(UNIT(s), table[old_state], table[state], s->reload_result == SERVICE_SUCCESS);
+ s->reload_result = SERVICE_SUCCESS;
+}
+
+static int service_coldplug(Unit *u) {
+ Service *s = SERVICE(u);
+ int r;
+
+ assert(s);
+ assert(s->state == SERVICE_DEAD);
+
+ if (s->deserialized_state != s->state) {
+
+ if (s->deserialized_state == SERVICE_START_PRE ||
+ s->deserialized_state == SERVICE_START ||
+ s->deserialized_state == SERVICE_START_POST ||
+ s->deserialized_state == SERVICE_RELOAD ||
+ s->deserialized_state == SERVICE_STOP ||
+ s->deserialized_state == SERVICE_STOP_SIGTERM ||
+ s->deserialized_state == SERVICE_STOP_SIGKILL ||
+ s->deserialized_state == SERVICE_STOP_POST ||
+ s->deserialized_state == SERVICE_FINAL_SIGTERM ||
+ s->deserialized_state == SERVICE_FINAL_SIGKILL ||
+ s->deserialized_state == SERVICE_AUTO_RESTART) {
+ if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_start_usec > 0) {
+ usec_t k;
+
+ k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_start_usec;
+
+ r = unit_watch_timer(UNIT(s), CLOCK_MONOTONIC, true, k, &s->timer_watch);
+ if (r < 0)
+ return r;
+ }
+ }
+
+ if ((s->deserialized_state == SERVICE_START &&
+ (s->type == SERVICE_FORKING ||
+ s->type == SERVICE_DBUS ||
+ s->type == SERVICE_ONESHOT ||
+ s->type == SERVICE_NOTIFY)) ||
+ s->deserialized_state == SERVICE_START_POST ||
+ s->deserialized_state == SERVICE_RUNNING ||
+ s->deserialized_state == SERVICE_RELOAD ||
+ s->deserialized_state == SERVICE_STOP ||
+ s->deserialized_state == SERVICE_STOP_SIGTERM ||
+ s->deserialized_state == SERVICE_STOP_SIGKILL)
+ if (s->main_pid > 0) {
+ r = unit_watch_pid(UNIT(s), s->main_pid);
+ if (r < 0)
+ return r;
+ }
+
+ if (s->deserialized_state == SERVICE_START_PRE ||
+ s->deserialized_state == SERVICE_START ||
+ s->deserialized_state == SERVICE_START_POST ||
+ s->deserialized_state == SERVICE_RELOAD ||
+ s->deserialized_state == SERVICE_STOP ||
+ s->deserialized_state == SERVICE_STOP_SIGTERM ||
+ s->deserialized_state == SERVICE_STOP_SIGKILL ||
+ s->deserialized_state == SERVICE_STOP_POST ||
+ s->deserialized_state == SERVICE_FINAL_SIGTERM ||
+ s->deserialized_state == SERVICE_FINAL_SIGKILL)
+ if (s->control_pid > 0) {
+ r = unit_watch_pid(UNIT(s), s->control_pid);
+ if (r < 0)
+ return r;
+ }
+
+ if (s->deserialized_state == SERVICE_START_POST ||
+ s->deserialized_state == SERVICE_RUNNING)
+ service_handle_watchdog(s);
+
+ service_set_state(s, s->deserialized_state);
+ }
+ return 0;
+}
+
+static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
+ Iterator i;
+ int r;
+ int *rfds = NULL;
+ unsigned rn_fds = 0;
+ Unit *u;
+
+ assert(s);
+ assert(fds);
+ assert(n_fds);
+
+ if (s->socket_fd >= 0)
+ return 0;
+
+ SET_FOREACH(u, UNIT(s)->dependencies[UNIT_TRIGGERED_BY], i) {
+ int *cfds;
+ unsigned cn_fds;
+ Socket *sock;
+
+ if (u->type != UNIT_SOCKET)
+ continue;
+
+ sock = SOCKET(u);
+
+ r = socket_collect_fds(sock, &cfds, &cn_fds);
+ if (r < 0)
+ goto fail;
+
+ if (!cfds)
+ continue;
+
+ if (!rfds) {
+ rfds = cfds;
+ rn_fds = cn_fds;
+ } else {
+ int *t;
+
+ t = new(int, rn_fds+cn_fds);
+ if (!t) {
+ free(cfds);
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ memcpy(t, rfds, rn_fds * sizeof(int));
+ memcpy(t+rn_fds, cfds, cn_fds * sizeof(int));
+ free(rfds);
+ free(cfds);
+
+ rfds = t;
+ rn_fds = rn_fds+cn_fds;
+ }
+ }
+
+ *fds = rfds;
+ *n_fds = rn_fds;
+
+ return 0;
+
+fail:
+ free(rfds);
+
+ return r;
+}
+
+static int service_spawn(
+ Service *s,
+ ExecCommand *c,
+ bool timeout,
+ bool pass_fds,
+ bool apply_permissions,
+ bool apply_chroot,
+ bool apply_tty_stdin,
+ bool set_notify_socket,
+ bool is_control,
+ pid_t *_pid) {
+
+ pid_t pid;
+ int r;
+ int *fds = NULL;
+ _cleanup_free_ int *fdsbuf = NULL;
+ unsigned n_fds = 0, n_env = 0;
+ _cleanup_strv_free_ char
+ **argv = NULL, **final_env = NULL, **our_env = NULL;
+
+ assert(s);
+ assert(c);
+ assert(_pid);
+
+ if (pass_fds ||
+ s->exec_context.std_input == EXEC_INPUT_SOCKET ||
+ s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
+ s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
+
+ if (s->socket_fd >= 0) {
+ fds = &s->socket_fd;
+ n_fds = 1;
+ } else {
+ r = service_collect_fds(s, &fdsbuf, &n_fds);
+ if (r < 0)
+ goto fail;
+
+ fds = fdsbuf;
+ }
+ }
+
+ if (timeout && s->timeout_start_usec) {
+ r = unit_watch_timer(UNIT(s), CLOCK_MONOTONIC, true,
+ s->timeout_start_usec, &s->timer_watch);
+ if (r < 0)
+ goto fail;
+ } else
+ unit_unwatch_timer(UNIT(s), &s->timer_watch);
+
+ argv = unit_full_printf_strv(UNIT(s), c->argv);
+ if (!argv) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ our_env = new0(char*, 5);
+ if (!our_env) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ if (set_notify_socket)
+ if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=%s", UNIT(s)->manager->notify_socket) < 0) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ if (s->main_pid > 0)
+ if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ if (s->watchdog_usec > 0)
+ if (asprintf(our_env + n_env++, "WATCHDOG_USEC=%llu", (unsigned long long) s->watchdog_usec) < 0) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ if (s->meta.manager->running_as != SYSTEMD_SYSTEM)
+ if (asprintf(our_env + n_env++, "MANAGERPID=%lu", (unsigned long) getpid()) < 0) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ final_env = strv_env_merge(2, UNIT(s)->manager->environment, our_env, NULL);
+ if (!final_env) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ r = exec_spawn(c,
+ argv,
+ &s->exec_context,
+ fds, n_fds,
+ final_env,
+ apply_permissions,
+ apply_chroot,
+ apply_tty_stdin,
+ UNIT(s)->manager->confirm_spawn,
+ UNIT(s)->cgroup_bondings,
+ UNIT(s)->cgroup_attributes,
+ is_control ? "control" : NULL,
+ UNIT(s)->id,
+ s->type == SERVICE_IDLE ? UNIT(s)->manager->idle_pipe : NULL,
+ &pid);
+ if (r < 0)
+ goto fail;
+
+ r = unit_watch_pid(UNIT(s), pid);
+ if (r < 0)
+ /* FIXME: we need to do something here */
+ goto fail;
+
+ *_pid = pid;
+
+ return 0;
+
+fail:
+ if (timeout)
+ unit_unwatch_timer(UNIT(s), &s->timer_watch);
+
+ return r;
+}
+
+static int main_pid_good(Service *s) {
+ assert(s);
+
+ /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
+ * don't know */
+
+ /* If we know the pid file, then lets just check if it is
+ * still valid */
+ if (s->main_pid_known) {
+
+ /* If it's an alien child let's check if it is still
+ * alive ... */
+ if (s->main_pid_alien)
+ return kill(s->main_pid, 0) >= 0 || errno != ESRCH;
+
+ /* .. otherwise assume we'll get a SIGCHLD for it,
+ * which we really should wait for to collect exit
+ * status and code */
+ return s->main_pid > 0;
+ }
+
+ /* We don't know the pid */
+ return -EAGAIN;
+}
+
+_pure_ static int control_pid_good(Service *s) {
+ assert(s);
+
+ return s->control_pid > 0;
+}
+
+static int cgroup_good(Service *s) {
+ int r;
+
+ assert(s);
+
+ r = cgroup_bonding_is_empty_list(UNIT(s)->cgroup_bondings);
+ if (r < 0)
+ return r;
+
+ return !r;
+}
+
+static void service_enter_dead(Service *s, ServiceResult f, bool allow_restart) {
+ int r;
+ assert(s);
+
+ if (f != SERVICE_SUCCESS)
+ s->result = f;
+
+ service_set_state(s, s->result != SERVICE_SUCCESS ? SERVICE_FAILED : SERVICE_DEAD);
+
+ if (allow_restart &&
+ !s->forbid_restart &&
+ (s->restart == SERVICE_RESTART_ALWAYS ||
+ (s->restart == SERVICE_RESTART_ON_SUCCESS && s->result == SERVICE_SUCCESS) ||
+ (s->restart == SERVICE_RESTART_ON_FAILURE && s->result != SERVICE_SUCCESS) ||
+ (s->restart == SERVICE_RESTART_ON_ABORT && (s->result == SERVICE_FAILURE_SIGNAL ||
+ s->result == SERVICE_FAILURE_CORE_DUMP))) &&
+ (s->result != SERVICE_FAILURE_EXIT_CODE ||
+ !set_contains(s->restart_ignore_status.code, INT_TO_PTR(s->main_exec_status.status))) &&
+ (s->result != SERVICE_FAILURE_SIGNAL ||
+ !set_contains(s->restart_ignore_status.signal, INT_TO_PTR(s->main_exec_status.status)))
+ ) {
+
+ r = unit_watch_timer(UNIT(s), CLOCK_MONOTONIC, true, s->restart_usec, &s->timer_watch);
+ if (r < 0)
+ goto fail;
+
+ service_set_state(s, SERVICE_AUTO_RESTART);
+ }
+
+ s->forbid_restart = false;
+
+ /* we want fresh tmpdirs in case service is started again immediately */
+ exec_context_tmp_dirs_done(&s->exec_context);
+
+ return;
+
+fail:
+ log_warning_unit(UNIT(s)->id,
+ "%s failed to run install restart timer: %s",
+ UNIT(s)->id, strerror(-r));
+ service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
+}
+
+static void service_enter_signal(Service *s, ServiceState state, ServiceResult f);
+
+static void service_enter_stop_post(Service *s, ServiceResult f) {
+ int r;
+ assert(s);
+
+ if (f != SERVICE_SUCCESS)
+ s->result = f;
+
+ service_unwatch_control_pid(s);
+
+ s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST];
+ if (s->control_command) {
+ s->control_command_id = SERVICE_EXEC_STOP_POST;
+
+ r = service_spawn(s,
+ s->control_command,
+ true,
+ false,
+ !s->permissions_start_only,
+ !s->root_directory_start_only,
+ true,
+ false,
+ true,
+ &s->control_pid);
+ if (r < 0)
+ goto fail;
+
+
+ service_set_state(s, SERVICE_STOP_POST);
+ } else
+ service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_SUCCESS);
+
+ return;
+
+fail:
+ log_warning_unit(UNIT(s)->id,
+ "%s failed to run 'stop-post' task: %s",
+ UNIT(s)->id, strerror(-r));
+ service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
+}
+
+static void service_enter_signal(Service *s, ServiceState state, ServiceResult f) {
+ int r;
+
+ assert(s);
+
+ if (f != SERVICE_SUCCESS)
+ s->result = f;
+
+ r = unit_kill_context(
+ UNIT(s),
+ &s->kill_context,
+ state != SERVICE_STOP_SIGTERM && state != SERVICE_FINAL_SIGTERM,
+ s->main_pid,
+ s->control_pid,
+ s->main_pid_alien);
+ if (r < 0)
+ goto fail;
+
+ if (r > 0) {
+ if (s->timeout_stop_usec > 0) {
+ r = unit_watch_timer(UNIT(s), CLOCK_MONOTONIC, true,
+ s->timeout_stop_usec, &s->timer_watch);
+ if (r < 0)
+ goto fail;
+ }
+
+ service_set_state(s, state);
+ } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
+ service_enter_stop_post(s, SERVICE_SUCCESS);
+ else
+ service_enter_dead(s, SERVICE_SUCCESS, true);
+
+ return;
+
+fail:
+ log_warning_unit(UNIT(s)->id,
+ "%s failed to kill processes: %s", UNIT(s)->id, strerror(-r));
+
+ if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
+ service_enter_stop_post(s, SERVICE_FAILURE_RESOURCES);
+ else
+ service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
+}
+
+static void service_enter_stop(Service *s, ServiceResult f) {
+ int r;
+
+ assert(s);
+
+ if (f != SERVICE_SUCCESS)
+ s->result = f;
+
+ service_unwatch_control_pid(s);
+
+ s->control_command = s->exec_command[SERVICE_EXEC_STOP];
+ if (s->control_command) {
+ s->control_command_id = SERVICE_EXEC_STOP;
+
+ r = service_spawn(s,
+ s->control_command,
+ true,
+ false,
+ !s->permissions_start_only,
+ !s->root_directory_start_only,
+ false,
+ false,
+ true,
+ &s->control_pid);
+ if (r < 0)
+ goto fail;
+
+ service_set_state(s, SERVICE_STOP);
+ } else
+ service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
+
+ return;
+
+fail:
+ log_warning_unit(UNIT(s)->id,
+ "%s failed to run 'stop' task: %s", UNIT(s)->id, strerror(-r));
+ service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
+}
+
+static void service_enter_running(Service *s, ServiceResult f) {
+ int main_pid_ok, cgroup_ok;
+ assert(s);
+
+ if (f != SERVICE_SUCCESS)
+ s->result = f;
+
+ main_pid_ok = main_pid_good(s);
+ cgroup_ok = cgroup_good(s);
+
+ if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
+ (s->bus_name_good || s->type != SERVICE_DBUS))
+ service_set_state(s, SERVICE_RUNNING);
+ else if (s->remain_after_exit)
+ service_set_state(s, SERVICE_EXITED);
+ else
+ service_enter_stop(s, SERVICE_SUCCESS);
+}
+
+static void service_enter_start_post(Service *s) {
+ int r;
+ assert(s);
+
+ service_unwatch_control_pid(s);
+
+ if (s->watchdog_usec > 0)
+ service_reset_watchdog(s);
+
+ s->control_command = s->exec_command[SERVICE_EXEC_START_POST];
+ if (s->control_command) {
+ s->control_command_id = SERVICE_EXEC_START_POST;
+
+ r = service_spawn(s,
+ s->control_command,
+ true,
+ false,
+ !s->permissions_start_only,
+ !s->root_directory_start_only,
+ false,
+ false,
+ true,
+ &s->control_pid);
+ if (r < 0)
+ goto fail;
+
+ service_set_state(s, SERVICE_START_POST);
+ } else
+ service_enter_running(s, SERVICE_SUCCESS);
+
+ return;
+
+fail:
+ log_warning_unit(UNIT(s)->id,
+ "%s failed to run 'start-post' task: %s", UNIT(s)->id, strerror(-r));
+ service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
+}
+
+static void service_enter_start(Service *s) {
+ pid_t pid;
+ int r;
+ ExecCommand *c;
+
+ assert(s);
+
+ assert(s->exec_command[SERVICE_EXEC_START]);
+ assert(!s->exec_command[SERVICE_EXEC_START]->command_next || s->type == SERVICE_ONESHOT);
+
+ if (s->type == SERVICE_FORKING)
+ service_unwatch_control_pid(s);
+ else
+ service_unwatch_main_pid(s);
+
+ /* We want to ensure that nobody leaks processes from
+ * START_PRE here, so let's go on a killing spree, People
+ * should not spawn long running processes from START_PRE. */
+ cgroup_bonding_kill_list(UNIT(s)->cgroup_bondings, SIGKILL, true, true, NULL, "control");
+
+ if (s->type == SERVICE_FORKING) {
+ s->control_command_id = SERVICE_EXEC_START;
+ c = s->control_command = s->exec_command[SERVICE_EXEC_START];
+
+ s->main_command = NULL;
+ } else {
+ s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
+ s->control_command = NULL;
+
+ c = s->main_command = s->exec_command[SERVICE_EXEC_START];
+ }
+
+ r = service_spawn(s,
+ c,
+ s->type == SERVICE_FORKING || s->type == SERVICE_DBUS ||
+ s->type == SERVICE_NOTIFY || s->type == SERVICE_ONESHOT,
+ true,
+ true,
+ true,
+ true,
+ s->notify_access != NOTIFY_NONE,
+ false,
+ &pid);
+ if (r < 0)
+ goto fail;
+
+ if (s->type == SERVICE_SIMPLE || s->type == SERVICE_IDLE) {
+ /* For simple services we immediately start
+ * the START_POST binaries. */
+
+ service_set_main_pid(s, pid);
+ service_enter_start_post(s);
+
+ } else if (s->type == SERVICE_FORKING) {
+
+ /* For forking services we wait until the start
+ * process exited. */
+
+ s->control_pid = pid;
+ service_set_state(s, SERVICE_START);
+
+ } else if (s->type == SERVICE_ONESHOT ||
+ s->type == SERVICE_DBUS ||
+ s->type == SERVICE_NOTIFY) {
+
+ /* For oneshot services we wait until the start
+ * process exited, too, but it is our main process. */
+
+ /* For D-Bus services we know the main pid right away,
+ * but wait for the bus name to appear on the
+ * bus. Notify services are similar. */
+
+ service_set_main_pid(s, pid);
+ service_set_state(s, SERVICE_START);
+ } else
+ assert_not_reached("Unknown service type");
+
+ return;
+
+fail:
+ log_warning_unit(UNIT(s)->id,
+ "%s failed to run 'start' task: %s", UNIT(s)->id, strerror(-r));
+ service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
+}
+
+static void service_enter_start_pre(Service *s) {
+ int r;
+
+ assert(s);
+
+ service_unwatch_control_pid(s);
+
+ s->control_command = s->exec_command[SERVICE_EXEC_START_PRE];
+ if (s->control_command) {
+
+ /* Before we start anything, let's clear up what might
+ * be left from previous runs. */
+ cgroup_bonding_kill_list(UNIT(s)->cgroup_bondings, SIGKILL,
+ true,true, NULL, "control");
+
+ s->control_command_id = SERVICE_EXEC_START_PRE;
+
+ r = service_spawn(s,
+ s->control_command,
+ true,
+ false,
+ !s->permissions_start_only,
+ !s->root_directory_start_only,
+ true,
+ false,
+ true,
+ &s->control_pid);
+ if (r < 0)
+ goto fail;
+
+ service_set_state(s, SERVICE_START_PRE);
+ } else
+ service_enter_start(s);
+
+ return;
+
+fail:
+ log_warning_unit(UNIT(s)->id,
+ "%s failed to run 'start-pre' task: %s", UNIT(s)->id, strerror(-r));
+ service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
+}
+
+static void service_enter_restart(Service *s) {
+ int r;
+ DBusError error;
+
+ assert(s);
+ dbus_error_init(&error);
+
+ if (UNIT(s)->job && UNIT(s)->job->type == JOB_STOP) {
+ /* Don't restart things if we are going down anyway */
+ log_info_unit(UNIT(s)->id,
+ "Stop job pending for unit, delaying automatic restart.");
+
+ r = unit_watch_timer(UNIT(s), CLOCK_MONOTONIC, true, s->restart_usec, &s->timer_watch);
+ if (r < 0)
+ goto fail;
+
+ return;
+ }
+
+ /* Any units that are bound to this service must also be
+ * restarted. We use JOB_RESTART (instead of the more obvious
+ * JOB_START) here so that those dependency jobs will be added
+ * as well. */
+ r = manager_add_job(UNIT(s)->manager, JOB_RESTART, UNIT(s), JOB_FAIL, false, &error, NULL);
+ if (r < 0)
+ goto fail;
+
+ /* Note that we stay in the SERVICE_AUTO_RESTART state here,
+ * it will be canceled as part of the service_stop() call that
+ * is executed as part of JOB_RESTART. */
+
+ log_debug_unit(UNIT(s)->id,
+ "%s scheduled restart job.", UNIT(s)->id);
+ return;
+
+fail:
+ log_warning_unit(UNIT(s)->id,
+ "%s failed to schedule restart job: %s",
+ UNIT(s)->id, bus_error(&error, -r));
+ service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
+
+ dbus_error_free(&error);
+}
+
+static void service_enter_reload(Service *s) {
+ int r;
+
+ assert(s);
+
+ service_unwatch_control_pid(s);
+
+ s->control_command = s->exec_command[SERVICE_EXEC_RELOAD];
+ if (s->control_command) {
+ s->control_command_id = SERVICE_EXEC_RELOAD;
+
+ r = service_spawn(s,
+ s->control_command,
+ true,
+ false,
+ !s->permissions_start_only,
+ !s->root_directory_start_only,
+ false,
+ false,
+ true,
+ &s->control_pid);
+ if (r < 0)
+ goto fail;
+
+ service_set_state(s, SERVICE_RELOAD);
+ } else
+ service_enter_running(s, SERVICE_SUCCESS);
+
+ return;
+
+fail:
+ log_warning_unit(UNIT(s)->id,
+ "%s failed to run 'reload' task: %s",
+ UNIT(s)->id, strerror(-r));
+ s->reload_result = SERVICE_FAILURE_RESOURCES;
+ service_enter_running(s, SERVICE_SUCCESS);
+}
+
+static void service_run_next_control(Service *s) {
+ int r;
+
+ assert(s);
+ assert(s->control_command);
+ assert(s->control_command->command_next);
+
+ assert(s->control_command_id != SERVICE_EXEC_START);
+
+ s->control_command = s->control_command->command_next;
+ service_unwatch_control_pid(s);
+
+ r = service_spawn(s,
+ s->control_command,
+ true,
+ false,
+ !s->permissions_start_only,
+ !s->root_directory_start_only,
+ s->control_command_id == SERVICE_EXEC_START_PRE ||
+ s->control_command_id == SERVICE_EXEC_STOP_POST,
+ false,
+ true,
+ &s->control_pid);
+ if (r < 0)
+ goto fail;
+
+ return;
+
+fail:
+ log_warning_unit(UNIT(s)->id,
+ "%s failed to run next control task: %s",
+ UNIT(s)->id, strerror(-r));
+
+ if (s->state == SERVICE_START_PRE)
+ service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
+ else if (s->state == SERVICE_STOP)
+ service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
+ else if (s->state == SERVICE_STOP_POST)
+ service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
+ else if (s->state == SERVICE_RELOAD) {
+ s->reload_result = SERVICE_FAILURE_RESOURCES;
+ service_enter_running(s, SERVICE_SUCCESS);
+ } else
+ service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
+}
+
+static void service_run_next_main(Service *s) {
+ pid_t pid;
+ int r;
+
+ assert(s);
+ assert(s->main_command);
+ assert(s->main_command->command_next);
+ assert(s->type == SERVICE_ONESHOT);
+
+ s->main_command = s->main_command->command_next;
+ service_unwatch_main_pid(s);
+
+ r = service_spawn(s,
+ s->main_command,
+ true,
+ true,
+ true,
+ true,
+ true,
+ s->notify_access != NOTIFY_NONE,
+ false,
+ &pid);
+ if (r < 0)
+ goto fail;
+
+ service_set_main_pid(s, pid);
+
+ return;
+
+fail:
+ log_warning_unit(UNIT(s)->id,
+ "%s failed to run next main task: %s", UNIT(s)->id, strerror(-r));
+ service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
+}
+
+static int service_start_limit_test(Service *s) {
+ assert(s);
+
+ if (ratelimit_test(&s->start_limit))
+ return 0;
+
+ switch (s->start_limit_action) {
+
+ case SERVICE_START_LIMIT_NONE:
+ log_warning_unit(UNIT(s)->id,
+ "%s start request repeated too quickly, refusing to start.",
+ UNIT(s)->id);
+ break;
+
+ case SERVICE_START_LIMIT_REBOOT: {
+ DBusError error;
+ int r;
+
+ dbus_error_init(&error);
+
+ log_warning_unit(UNIT(s)->id,
+ "%s start request repeated too quickly, rebooting.", UNIT(s)->id);
+
+ r = manager_add_job_by_name(UNIT(s)->manager, JOB_START,
+ SPECIAL_REBOOT_TARGET, JOB_REPLACE,
+ true, &error, NULL);
+ if (r < 0) {
+ log_error_unit(UNIT(s)->id,
+ "Failed to reboot: %s.", bus_error(&error, r));
+ dbus_error_free(&error);
+ }
+
+ break;
+ }
+
+ case SERVICE_START_LIMIT_REBOOT_FORCE:
+ log_warning_unit(UNIT(s)->id,
+ "%s start request repeated too quickly, forcibly rebooting.", UNIT(s)->id);
+ UNIT(s)->manager->exit_code = MANAGER_REBOOT;
+ break;
+
+ case SERVICE_START_LIMIT_REBOOT_IMMEDIATE:
+ log_warning_unit(UNIT(s)->id,
+ "%s start request repeated too quickly, rebooting immediately.", UNIT(s)->id);
+ sync();
+ reboot(RB_AUTOBOOT);
+ break;
+
+ default:
+ log_error_unit(UNIT(s)->id,
+ "start limit action=%i", s->start_limit_action);
+ assert_not_reached("Unknown StartLimitAction.");
+ }
+
+ return -ECANCELED;
+}
+
+static int service_start(Unit *u) {
+ Service *s = SERVICE(u);
+ int r;
+
+ assert(s);
+
+ /* We cannot fulfill this request right now, try again later
+ * please! */
+ if (s->state == SERVICE_STOP ||
+ s->state == SERVICE_STOP_SIGTERM ||
+ s->state == SERVICE_STOP_SIGKILL ||
+ s->state == SERVICE_STOP_POST ||
+ s->state == SERVICE_FINAL_SIGTERM ||
+ s->state == SERVICE_FINAL_SIGKILL)
+ return -EAGAIN;
+
+ /* Already on it! */
+ if (s->state == SERVICE_START_PRE ||
+ s->state == SERVICE_START ||
+ s->state == SERVICE_START_POST)
+ return 0;
+
+ /* A service that will be restarted must be stopped first to
+ * trigger BindsTo and/or OnFailure dependencies. If a user
+ * does not want to wait for the holdoff time to elapse, the
+ * service should be manually restarted, not started. We
+ * simply return EAGAIN here, so that any start jobs stay
+ * queued, and assume that the auto restart timer will
+ * eventually trigger the restart. */
+ if (s->state == SERVICE_AUTO_RESTART)
+ return -EAGAIN;
+
+ assert(s->state == SERVICE_DEAD || s->state == SERVICE_FAILED);
+
+ /* Make sure we don't enter a busy loop of some kind. */
+ r = service_start_limit_test(s);
+ if (r < 0) {
+ service_enter_dead(s, SERVICE_FAILURE_START_LIMIT, false);
+ return r;
+ }
+
+ s->result = SERVICE_SUCCESS;
+ s->reload_result = SERVICE_SUCCESS;
+ s->main_pid_known = false;
+ s->main_pid_alien = false;
+ s->forbid_restart = false;
+
+ service_enter_start_pre(s);
+ return 0;
+}
+
+static int service_stop(Unit *u) {
+ Service *s = SERVICE(u);
+
+ assert(s);
+
+ /* Don't create restart jobs from here. */
+ s->forbid_restart = true;
+
+ /* Already on it */
+ if (s->state == SERVICE_STOP ||
+ s->state == SERVICE_STOP_SIGTERM ||
+ s->state == SERVICE_STOP_SIGKILL ||
+ s->state == SERVICE_STOP_POST ||
+ s->state == SERVICE_FINAL_SIGTERM ||
+ s->state == SERVICE_FINAL_SIGKILL)
+ return 0;
+
+ /* A restart will be scheduled or is in progress. */
+ if (s->state == SERVICE_AUTO_RESTART) {
+ service_set_state(s, SERVICE_DEAD);
+ return 0;
+ }
+
+ /* If there's already something running we go directly into
+ * kill mode. */
+ if (s->state == SERVICE_START_PRE ||
+ s->state == SERVICE_START ||
+ s->state == SERVICE_START_POST ||
+ s->state == SERVICE_RELOAD) {
+ service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
+ return 0;
+ }
+
+ assert(s->state == SERVICE_RUNNING ||
+ s->state == SERVICE_EXITED);
+
+ service_enter_stop(s, SERVICE_SUCCESS);
+ return 0;
+}
+
+static int service_reload(Unit *u) {
+ Service *s = SERVICE(u);
+
+ assert(s);
+
+ assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
+
+ service_enter_reload(s);
+ return 0;
+}
+
+_pure_ static bool service_can_reload(Unit *u) {
+ Service *s = SERVICE(u);
+
+ assert(s);
+
+ return !!s->exec_command[SERVICE_EXEC_RELOAD];
+}
+
+static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
+ Service *s = SERVICE(u);
+
+ assert(u);
+ assert(f);
+ assert(fds);
+
+ unit_serialize_item(u, f, "state", service_state_to_string(s->state));
+ unit_serialize_item(u, f, "result", service_result_to_string(s->result));
+ unit_serialize_item(u, f, "reload-result", service_result_to_string(s->reload_result));
+
+ if (s->control_pid > 0)
+ unit_serialize_item_format(u, f, "control-pid", "%lu",
+ (unsigned long) s->control_pid);
+
+ if (s->main_pid_known && s->main_pid > 0)
+ unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
+
+ unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
+
+ if (s->status_text)
+ unit_serialize_item(u, f, "status-text", s->status_text);
+
+ /* FIXME: There's a minor uncleanliness here: if there are
+ * multiple commands attached here, we will start from the
+ * first one again */
+ if (s->control_command_id >= 0)
+ unit_serialize_item(u, f, "control-command",
+ service_exec_command_to_string(s->control_command_id));
+
+ if (s->socket_fd >= 0) {
+ int copy;
+
+ if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
+ return copy;
+
+ unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
+ }
+
+ if (s->main_exec_status.pid > 0) {
+ unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu",
+ (unsigned long) s->main_exec_status.pid);
+ dual_timestamp_serialize(f, "main-exec-status-start",
+ &s->main_exec_status.start_timestamp);
+ dual_timestamp_serialize(f, "main-exec-status-exit",
+ &s->main_exec_status.exit_timestamp);
+
+ if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
+ unit_serialize_item_format(u, f, "main-exec-status-code", "%i",
+ s->main_exec_status.code);
+ unit_serialize_item_format(u, f, "main-exec-status-status", "%i",
+ s->main_exec_status.status);
+ }
+ }
+ if (dual_timestamp_is_set(&s->watchdog_timestamp))
+ dual_timestamp_serialize(f, "watchdog-timestamp",
+ &s->watchdog_timestamp);
+
+ if (s->exec_context.tmp_dir)
+ unit_serialize_item(u, f, "tmp-dir", s->exec_context.tmp_dir);
+
+ if (s->exec_context.var_tmp_dir)
+ unit_serialize_item(u, f, "var-tmp-dir", s->exec_context.var_tmp_dir);
+
+ return 0;
+}
+
+static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
+ Service *s = SERVICE(u);
+
+ assert(u);
+ assert(key);
+ assert(value);
+ assert(fds);
+
+ if (streq(key, "state")) {
+ ServiceState state;
+
+ state = service_state_from_string(value);
+ if (state < 0)
+ log_debug_unit(u->id, "Failed to parse state value %s", value);
+ else
+ s->deserialized_state = state;
+ } else if (streq(key, "result")) {
+ ServiceResult f;
+
+ f = service_result_from_string(value);
+ if (f < 0)
+ log_debug_unit(u->id, "Failed to parse result value %s", value);
+ else if (f != SERVICE_SUCCESS)
+ s->result = f;
+
+ } else if (streq(key, "reload-result")) {
+ ServiceResult f;
+
+ f = service_result_from_string(value);
+ if (f < 0)
+ log_debug_unit(u->id, "Failed to parse reload result value %s", value);
+ else if (f != SERVICE_SUCCESS)
+ s->reload_result = f;
+
+ } else if (streq(key, "control-pid")) {
+ pid_t pid;
+
+ if (parse_pid(value, &pid) < 0)
+ log_debug_unit(u->id, "Failed to parse control-pid value %s", value);
+ else
+ s->control_pid = pid;
+ } else if (streq(key, "main-pid")) {
+ pid_t pid;
+
+ if (parse_pid(value, &pid) < 0)
+ log_debug_unit(u->id, "Failed to parse main-pid value %s", value);
+ else
+ service_set_main_pid(s, (pid_t) pid);
+ } else if (streq(key, "main-pid-known")) {
+ int b;
+
+ b = parse_boolean(value);
+ if (b < 0)
+ log_debug_unit(u->id, "Failed to parse main-pid-known value %s", value);
+ else
+ s->main_pid_known = b;
+ } else if (streq(key, "status-text")) {
+ char *t;
+
+ t = strdup(value);
+ if (!t)
+ log_oom();
+ else {
+ free(s->status_text);
+ s->status_text = t;
+ }
+
+ } else if (streq(key, "control-command")) {
+ ServiceExecCommand id;
+
+ id = service_exec_command_from_string(value);
+ if (id < 0)
+ log_debug_unit(u->id, "Failed to parse exec-command value %s", value);
+ else {
+ s->control_command_id = id;
+ s->control_command = s->exec_command[id];
+ }
+ } else if (streq(key, "socket-fd")) {
+ int fd;
+
+ if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
+ log_debug_unit(u->id, "Failed to parse socket-fd value %s", value);
+ else {
+
+ if (s->socket_fd >= 0)
+ close_nointr_nofail(s->socket_fd);
+ s->socket_fd = fdset_remove(fds, fd);
+ }
+ } else if (streq(key, "main-exec-status-pid")) {
+ pid_t pid;
+
+ if (parse_pid(value, &pid) < 0)
+ log_debug_unit(u->id, "Failed to parse main-exec-status-pid value %s", value);
+ else
+ s->main_exec_status.pid = pid;
+ } else if (streq(key, "main-exec-status-code")) {
+ int i;
+
+ if (safe_atoi(value, &i) < 0)
+ log_debug_unit(u->id, "Failed to parse main-exec-status-code value %s", value);
+ else
+ s->main_exec_status.code = i;
+ } else if (streq(key, "main-exec-status-status")) {
+ int i;
+
+ if (safe_atoi(value, &i) < 0)
+ log_debug_unit(u->id, "Failed to parse main-exec-status-status value %s", value);
+ else
+ s->main_exec_status.status = i;
+ } else if (streq(key, "main-exec-status-start"))
+ dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
+ else if (streq(key, "main-exec-status-exit"))
+ dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
+ else if (streq(key, "watchdog-timestamp"))
+ dual_timestamp_deserialize(value, &s->watchdog_timestamp);
+ else if (streq(key, "tmp-dir")) {
+ char *t;
+
+ t = strdup(value);
+ if (!t)
+ return log_oom();
+
+ s->exec_context.tmp_dir = t;
+ } else if (streq(key, "var-tmp-dir")) {
+ char *t;
+
+ t = strdup(value);
+ if (!t)
+ return log_oom();
+
+ s->exec_context.var_tmp_dir = t;
+ } else
+ log_debug_unit(u->id, "Unknown serialization key '%s'", key);
+
+ return 0;
+}
+
+_pure_ static UnitActiveState service_active_state(Unit *u) {
+ const UnitActiveState *table;
+
+ assert(u);
+
+ table = SERVICE(u)->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
+
+ return table[SERVICE(u)->state];
+}
+
+static const char *service_sub_state_to_string(Unit *u) {
+ assert(u);
+
+ return service_state_to_string(SERVICE(u)->state);
+}
+
+static bool service_check_gc(Unit *u) {
+ Service *s = SERVICE(u);
+
+ assert(s);
+
+ /* Never clean up services that still have a process around,
+ * even if the service is formally dead. */
+ if (cgroup_good(s) > 0 ||
+ main_pid_good(s) > 0 ||
+ control_pid_good(s) > 0)
+ return true;
+
+#ifdef HAVE_SYSV_COMPAT
+ if (s->is_sysv)
+ return true;
+#endif
+
+ return false;
+}
+
+_pure_ static bool service_check_snapshot(Unit *u) {
+ Service *s = SERVICE(u);
+
+ assert(s);
+
+ return !s->got_socket_fd;
+}
+
+static int service_retry_pid_file(Service *s) {
+ int r;
+
+ assert(s->pid_file);
+ assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
+
+ r = service_load_pid_file(s, false);
+ if (r < 0)
+ return r;
+
+ service_unwatch_pid_file(s);
+
+ service_enter_running(s, SERVICE_SUCCESS);
+ return 0;
+}
+
+static int service_watch_pid_file(Service *s) {
+ int r;
+
+ log_debug_unit(UNIT(s)->id,
+ "Setting watch for %s's PID file %s",
+ UNIT(s)->id, s->pid_file_pathspec->path);
+ r = path_spec_watch(s->pid_file_pathspec, UNIT(s));
+ if (r < 0)
+ goto fail;
+
+ /* the pidfile might have appeared just before we set the watch */
+ log_debug_unit(UNIT(s)->id,
+ "Trying to read %s's PID file %s in case it changed",
+ UNIT(s)->id, s->pid_file_pathspec->path);
+ service_retry_pid_file(s);
+
+ return 0;
+fail:
+ log_error_unit(UNIT(s)->id,
+ "Failed to set a watch for %s's PID file %s: %s",
+ UNIT(s)->id, s->pid_file_pathspec->path, strerror(-r));
+ service_unwatch_pid_file(s);
+ return r;
+}
+
+static int service_demand_pid_file(Service *s) {
+ PathSpec *ps;
+
+ assert(s->pid_file);
+ assert(!s->pid_file_pathspec);
+
+ ps = new0(PathSpec, 1);
+ if (!ps)
+ return -ENOMEM;
+
+ ps->path = strdup(s->pid_file);
+ if (!ps->path) {
+ free(ps);
+ return -ENOMEM;
+ }
+
+ path_kill_slashes(ps->path);
+
+ /* PATH_CHANGED would not be enough. There are daemons (sendmail) that
+ * keep their PID file open all the time. */
+ ps->type = PATH_MODIFIED;
+ ps->inotify_fd = -1;
+
+ s->pid_file_pathspec = ps;
+
+ return service_watch_pid_file(s);
+}
+
+static void service_fd_event(Unit *u, int fd, uint32_t events, Watch *w) {
+ Service *s = SERVICE(u);
+
+ assert(s);
+ assert(fd >= 0);
+ assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
+ assert(s->pid_file_pathspec);
+ assert(path_spec_owns_inotify_fd(s->pid_file_pathspec, fd));
+
+ log_debug_unit(u->id, "inotify event for %s", u->id);
+
+ if (path_spec_fd_event(s->pid_file_pathspec, events) < 0)
+ goto fail;
+
+ if (service_retry_pid_file(s) == 0)
+ return;
+
+ if (service_watch_pid_file(s) < 0)
+ goto fail;
+
+ return;
+fail:
+ service_unwatch_pid_file(s);
+ service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
+}
+
+static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
+ Service *s = SERVICE(u);
+ ServiceResult f;
+
+ assert(s);
+ assert(pid >= 0);
+
+ if (UNIT(s)->fragment_path ? is_clean_exit(code, status, &s->success_status) :
+ is_clean_exit_lsb(code, status, &s->success_status))
+ f = SERVICE_SUCCESS;
+ else if (code == CLD_EXITED)
+ f = SERVICE_FAILURE_EXIT_CODE;
+ else if (code == CLD_KILLED)
+ f = SERVICE_FAILURE_SIGNAL;
+ else if (code == CLD_DUMPED)
+ f = SERVICE_FAILURE_CORE_DUMP;
+ else
+ assert_not_reached("Unknown code");
+
+ if (s->main_pid == pid) {
+ /* Forking services may occasionally move to a new PID.
+ * As long as they update the PID file before exiting the old
+ * PID, they're fine. */
+ if (service_load_pid_file(s, false) == 0)
+ return;
+
+ s->main_pid = 0;
+ exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
+
+ if (s->main_command) {
+ /* If this is not a forking service than the
+ * main process got started and hence we copy
+ * the exit status so that it is recorded both
+ * as main and as control process exit
+ * status */
+
+ s->main_command->exec_status = s->main_exec_status;
+
+ if (s->main_command->ignore)
+ f = SERVICE_SUCCESS;
+ } else if (s->exec_command[SERVICE_EXEC_START]) {
+
+ /* If this is a forked process, then we should
+ * ignore the return value if this was
+ * configured for the starter process */
+
+ if (s->exec_command[SERVICE_EXEC_START]->ignore)
+ f = SERVICE_SUCCESS;
+ }
+
+ log_struct_unit(f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
+ u->id,
+ "MESSAGE=%s: main process exited, code=%s, status=%i/%s",
+ u->id, sigchld_code_to_string(code), status,
+ strna(code == CLD_EXITED
+ ? exit_status_to_string(status, EXIT_STATUS_FULL)
+ : signal_to_string(status)),
+ "EXIT_CODE=%s", sigchld_code_to_string(code),
+ "EXIT_STATUS=%i", status,
+ NULL);
+
+ if (f != SERVICE_SUCCESS)
+ s->result = f;
+
+ if (s->main_command &&
+ s->main_command->command_next &&
+ f == SERVICE_SUCCESS) {
+
+ /* There is another command to *
+ * execute, so let's do that. */
+
+ log_debug_unit(u->id,
+ "%s running next main command for state %s",
+ u->id, service_state_to_string(s->state));
+ service_run_next_main(s);
+
+ } else {
+
+ /* The service exited, so the service is officially
+ * gone. */
+ s->main_command = NULL;
+
+ switch (s->state) {
+
+ case SERVICE_START_POST:
+ case SERVICE_RELOAD:
+ case SERVICE_STOP:
+ /* Need to wait until the operation is
+ * done */
+ break;
+
+ case SERVICE_START:
+ if (s->type == SERVICE_ONESHOT) {
+ /* This was our main goal, so let's go on */
+ if (f == SERVICE_SUCCESS)
+ service_enter_start_post(s);
+ else
+ service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
+ break;
+ }
+
+ /* Fall through */
+
+ case SERVICE_RUNNING:
+ service_enter_running(s, f);
+ break;
+
+ case SERVICE_STOP_SIGTERM:
+ case SERVICE_STOP_SIGKILL:
+
+ if (!control_pid_good(s))
+ service_enter_stop_post(s, f);
+
+ /* If there is still a control process, wait for that first */
+ break;
+
+ default:
+ assert_not_reached("Uh, main process died at wrong time.");
+ }
+ }
+
+ } else if (s->control_pid == pid) {
+
+ s->control_pid = 0;
+
+ if (s->control_command) {
+ exec_status_exit(&s->control_command->exec_status,
+ &s->exec_context, pid, code, status);
+
+ if (s->control_command->ignore)
+ f = SERVICE_SUCCESS;
+ }
+
+ log_full_unit(f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE, u->id,
+ "%s: control process exited, code=%s status=%i",
+ u->id, sigchld_code_to_string(code), status);
+
+ if (f != SERVICE_SUCCESS)
+ s->result = f;
+
+ /* Immediately get rid of the cgroup, so that the
+ * kernel doesn't delay the cgroup empty messages for
+ * the service cgroup any longer than necessary */
+ cgroup_bonding_kill_list(UNIT(s)->cgroup_bondings, SIGKILL,
+ true, true, NULL, "control");
+
+ if (s->control_command &&
+ s->control_command->command_next &&
+ f == SERVICE_SUCCESS) {
+
+ /* There is another command to *
+ * execute, so let's do that. */
+
+ log_debug_unit(u->id,
+ "%s running next control command for state %s",
+ u->id, service_state_to_string(s->state));
+ service_run_next_control(s);
+
+ } else {
+ /* No further commands for this step, so let's
+ * figure out what to do next */
+
+ s->control_command = NULL;
+ s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
+
+ log_debug_unit(u->id,
+ "%s got final SIGCHLD for state %s",
+ u->id, service_state_to_string(s->state));
+
+ switch (s->state) {
+
+ case SERVICE_START_PRE:
+ if (f == SERVICE_SUCCESS)
+ service_enter_start(s);
+ else
+ service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
+ break;
+
+ case SERVICE_START:
+ if (s->type != SERVICE_FORKING)
+ /* Maybe spurious event due to a reload that changed the type? */
+ break;
+
+ if (f != SERVICE_SUCCESS) {
+ service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
+ break;
+ }
+
+ if (s->pid_file) {
+ bool has_start_post;
+ int r;
+
+ /* Let's try to load the pid file here if we can.
+ * The PID file might actually be created by a START_POST
+ * script. In that case don't worry if the loading fails. */
+
+ has_start_post = !!s->exec_command[SERVICE_EXEC_START_POST];
+ r = service_load_pid_file(s, !has_start_post);
+ if (!has_start_post && r < 0) {
+ r = service_demand_pid_file(s);
+ if (r < 0 || !cgroup_good(s))
+ service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
+ break;
+ }
+ } else
+ service_search_main_pid(s);
+
+ service_enter_start_post(s);
+ break;
+
+ case SERVICE_START_POST:
+ if (f != SERVICE_SUCCESS) {
+ service_enter_stop(s, f);
+ break;
+ }
+
+ if (s->pid_file) {
+ int r;
+
+ r = service_load_pid_file(s, true);
+ if (r < 0) {
+ r = service_demand_pid_file(s);
+ if (r < 0 || !cgroup_good(s))
+ service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
+ break;
+ }
+ } else
+ service_search_main_pid(s);
+
+ service_enter_running(s, SERVICE_SUCCESS);
+ break;
+
+ case SERVICE_RELOAD:
+ if (f == SERVICE_SUCCESS) {
+ service_load_pid_file(s, true);
+ service_search_main_pid(s);
+ }
+
+ s->reload_result = f;
+ service_enter_running(s, SERVICE_SUCCESS);
+ break;
+
+ case SERVICE_STOP:
+ service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
+ break;
+
+ case SERVICE_STOP_SIGTERM:
+ case SERVICE_STOP_SIGKILL:
+ if (main_pid_good(s) <= 0)
+ service_enter_stop_post(s, f);
+
+ /* If there is still a service
+ * process around, wait until
+ * that one quit, too */
+ break;
+
+ case SERVICE_STOP_POST:
+ case SERVICE_FINAL_SIGTERM:
+ case SERVICE_FINAL_SIGKILL:
+ service_enter_dead(s, f, true);
+ break;
+
+ default:
+ assert_not_reached("Uh, control process died at wrong time.");
+ }
+ }
+ }
+
+ /* Notify clients about changed exit status */
+ unit_add_to_dbus_queue(u);
+}
+
+static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
+ Service *s = SERVICE(u);
+
+ assert(s);
+ assert(elapsed == 1);
+
+ if (w == &s->watchdog_watch) {
+ service_handle_watchdog(s);
+ return;
+ }
+
+ assert(w == &s->timer_watch);
+
+ switch (s->state) {
+
+ case SERVICE_START_PRE:
+ case SERVICE_START:
+ log_warning_unit(u->id,
+ "%s operation timed out. Terminating.", u->id);
+ service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
+ break;
+
+ case SERVICE_START_POST:
+ log_warning_unit(u->id,
+ "%s operation timed out. Stopping.", u->id);
+ service_enter_stop(s, SERVICE_FAILURE_TIMEOUT);
+ break;
+
+ case SERVICE_RELOAD:
+ log_warning_unit(u->id,
+ "%s operation timed out. Stopping.", u->id);
+ s->reload_result = SERVICE_FAILURE_TIMEOUT;
+ service_enter_running(s, SERVICE_SUCCESS);
+ break;
+
+ case SERVICE_STOP:
+ log_warning_unit(u->id,
+ "%s stopping timed out. Terminating.", u->id);
+ service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
+ break;
+
+ case SERVICE_STOP_SIGTERM:
+ if (s->kill_context.send_sigkill) {
+ log_warning_unit(u->id,
+ "%s stopping timed out. Killing.", u->id);
+ service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
+ } else {
+ log_warning_unit(u->id,
+ "%s stopping timed out. Skipping SIGKILL.", u->id);
+ service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
+ }
+
+ break;
+
+ case SERVICE_STOP_SIGKILL:
+ /* Uh, we sent a SIGKILL and it is still not gone?
+ * Must be something we cannot kill, so let's just be
+ * weirded out and continue */
+
+ log_warning_unit(u->id,
+ "%s still around after SIGKILL. Ignoring.", u->id);
+ service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
+ break;
+
+ case SERVICE_STOP_POST:
+ log_warning_unit(u->id,
+ "%s stopping timed out (2). Terminating.", u->id);
+ service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
+ break;
+
+ case SERVICE_FINAL_SIGTERM:
+ if (s->kill_context.send_sigkill) {
+ log_warning_unit(u->id,
+ "%s stopping timed out (2). Killing.", u->id);
+ service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
+ } else {
+ log_warning_unit(u->id,
+ "%s stopping timed out (2). Skipping SIGKILL. Entering failed mode.",
+ u->id);
+ service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
+ }
+
+ break;
+
+ case SERVICE_FINAL_SIGKILL:
+ log_warning_unit(u->id,
+ "%s still around after SIGKILL (2). Entering failed mode.", u->id);
+ service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, true);
+ break;
+
+ case SERVICE_AUTO_RESTART:
+ log_info_unit(u->id,
+ "%s holdoff time over, scheduling restart.", u->id);
+ service_enter_restart(s);
+ break;
+
+ default:
+ assert_not_reached("Timeout at wrong time.");
+ }
+}
+
+static void service_cgroup_notify_event(Unit *u) {
+ Service *s = SERVICE(u);
+
+ assert(u);
+
+ log_debug_unit(u->id,
+ "%s: cgroup is empty", u->id);
+
+ switch (s->state) {
+
+ /* Waiting for SIGCHLD is usually more interesting,
+ * because it includes return codes/signals. Which is
+ * why we ignore the cgroup events for most cases,
+ * except when we don't know pid which to expect the
+ * SIGCHLD for. */
+
+ case SERVICE_START:
+ case SERVICE_START_POST:
+ /* If we were hoping for the daemon to write its PID file,
+ * we can give up now. */
+ if (s->pid_file_pathspec) {
+ log_warning_unit(u->id,
+ "%s never wrote its PID file. Failing.", UNIT(s)->id);
+ service_unwatch_pid_file(s);
+ if (s->state == SERVICE_START)
+ service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
+ else
+ service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
+ }
+ break;
+
+ case SERVICE_RUNNING:
+ /* service_enter_running() will figure out what to do */
+ service_enter_running(s, SERVICE_SUCCESS);
+ break;
+
+ case SERVICE_STOP_SIGTERM:
+ case SERVICE_STOP_SIGKILL:
+
+ if (main_pid_good(s) <= 0 && !control_pid_good(s))
+ service_enter_stop_post(s, SERVICE_SUCCESS);
+
+ break;
+
+ case SERVICE_FINAL_SIGTERM:
+ case SERVICE_FINAL_SIGKILL:
+ if (main_pid_good(s) <= 0 && !control_pid_good(s))
+ service_enter_dead(s, SERVICE_SUCCESS, true);
+
+ break;
+
+ default:
+ ;
+ }
+}
+
+static void service_notify_message(Unit *u, pid_t pid, char **tags) {
+ Service *s = SERVICE(u);
+ const char *e;
+
+ assert(u);
+
+ if (s->notify_access == NOTIFY_NONE) {
+ log_warning_unit(u->id,
+ "%s: Got notification message from PID %lu, but reception is disabled.",
+ u->id, (unsigned long) pid);
+ return;
+ }
+
+ if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
+ log_warning_unit(u->id,
+ "%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
+ u->id, (unsigned long) pid, (unsigned long) s->main_pid);
+ return;
+ }
+
+ log_debug_unit(u->id,
+ "%s: Got message", u->id);
+
+ /* Interpret MAINPID= */
+ if ((e = strv_find_prefix(tags, "MAINPID=")) &&
+ (s->state == SERVICE_START ||
+ s->state == SERVICE_START_POST ||
+ s->state == SERVICE_RUNNING ||
+ s->state == SERVICE_RELOAD)) {
+
+ if (parse_pid(e + 8, &pid) < 0)
+ log_warning_unit(u->id,
+ "Failed to parse notification message %s", e);
+ else {
+ log_debug_unit(u->id,
+ "%s: got %s", u->id, e);
+ service_set_main_pid(s, pid);
+ }
+ }
+
+ /* Interpret READY= */
+ if (s->type == SERVICE_NOTIFY &&
+ s->state == SERVICE_START &&
+ strv_find(tags, "READY=1")) {
+ log_debug_unit(u->id,
+ "%s: got READY=1", u->id);
+
+ service_enter_start_post(s);
+ }
+
+ /* Interpret STATUS= */
+ e = strv_find_prefix(tags, "STATUS=");
+ if (e) {
+ char *t;
+
+ if (e[7]) {
+
+ if (!utf8_is_valid(e+7)) {
+ log_warning_unit(u->id,
+ "Status message in notification is not UTF-8 clean.");
+ return;
+ }
+
+ t = strdup(e+7);
+ if (!t) {
+ log_error_unit(u->id,
+ "Failed to allocate string.");
+ return;
+ }
+
+ log_debug_unit(u->id,
+ "%s: got %s", u->id, e);
+
+ free(s->status_text);
+ s->status_text = t;
+ } else {
+ free(s->status_text);
+ s->status_text = NULL;
+ }
+
+ }
+ if (strv_find(tags, "WATCHDOG=1")) {
+ log_debug_unit(u->id,
+ "%s: got WATCHDOG=1", u->id);
+ if (dual_timestamp_is_set(&s->watchdog_timestamp))
+ service_reset_watchdog(s);
+ }
+
+ /* Notify clients about changed status or main pid */
+ unit_add_to_dbus_queue(u);
+}
+
+#ifdef HAVE_SYSV_COMPAT
+
+static int service_enumerate(Manager *m) {
+ char **p;
+ unsigned i;
+ _cleanup_closedir_ DIR *d = NULL;
+ _cleanup_free_ char *path = NULL, *fpath = NULL, *name = NULL;
+ Set *runlevel_services[ELEMENTSOF(rcnd_table)] = {};
+ _cleanup_set_free_ Set *shutdown_services = NULL;
+ Unit *service;
+ Iterator j;
+ int r;
+
+ assert(m);
+
+ if (m->running_as != SYSTEMD_SYSTEM)
+ return 0;
+
+ STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
+ for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
+ struct dirent *de;
+
+ free(path);
+ path = strjoin(*p, "/", rcnd_table[i].path, NULL);
+ if (!path) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ if (d)
+ closedir(d);
+
+ d = opendir(path);
+ if (!d) {
+ if (errno != ENOENT)
+ log_warning("opendir(%s) failed: %s", path, strerror(errno));
+
+ continue;
+ }
+
+ while ((de = readdir(d))) {
+ int a, b;
+
+ if (ignore_file(de->d_name))
+ continue;
+
+ if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
+ continue;
+
+ if (strlen(de->d_name) < 4)
+ continue;
+
+ a = undecchar(de->d_name[1]);
+ b = undecchar(de->d_name[2]);
+
+ if (a < 0 || b < 0)
+ continue;
+
+ free(fpath);
+ fpath = strjoin(path, "/", de->d_name, NULL);
+ if (!fpath) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ if (access(fpath, X_OK) < 0) {
+
+ if (errno != ENOENT)
+ log_warning("access() failed on %s: %s", fpath, strerror(errno));
+
+ continue;
+ }
+
+ free(name);
+ name = sysv_translate_name(de->d_name + 3);
+ if (!name) {
+ r = log_oom();
+ goto finish;
+ }
+
+ r = manager_load_unit_prepare(m, name, NULL, NULL, &service);
+ if (r < 0) {
+ log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
+ continue;
+ }
+
+ if (de->d_name[0] == 'S') {
+
+ if (rcnd_table[i].type == RUNLEVEL_UP) {
+ SERVICE(service)->sysv_start_priority_from_rcnd =
+ MAX(a*10 + b, SERVICE(service)->sysv_start_priority_from_rcnd);
+
+ SERVICE(service)->sysv_enabled = true;
+ }
+
+ r = set_ensure_allocated(&runlevel_services[i],
+ trivial_hash_func, trivial_compare_func);
+ if (r < 0)
+ goto finish;
+
+ r = set_put(runlevel_services[i], service);
+ if (r < 0)
+ goto finish;
+
+ } else if (de->d_name[0] == 'K' &&
+ (rcnd_table[i].type == RUNLEVEL_DOWN)) {
+
+ r = set_ensure_allocated(&shutdown_services,
+ trivial_hash_func, trivial_compare_func);
+ if (r < 0)
+ goto finish;
+
+ r = set_put(shutdown_services, service);
+ if (r < 0)
+ goto finish;
+ }
+ }
+ }
+
+ /* Now we loaded all stubs and are aware of the lowest
+ start-up priority for all services, not let's actually load
+ the services, this will also tell us which services are
+ actually native now */
+ manager_dispatch_load_queue(m);
+
+ /* If this is a native service, rely on native ways to pull in
+ * a service, don't pull it in via sysv rcN.d links. */
+ for (i = 0; i < ELEMENTSOF(rcnd_table); i ++)
+ SET_FOREACH(service, runlevel_services[i], j) {
+ service = unit_follow_merge(service);
+
+ if (service->fragment_path)
+ continue;
+
+ r = unit_add_two_dependencies_by_name_inverse(
+ service, UNIT_AFTER, UNIT_WANTS,
+ rcnd_table[i].target, NULL, true);
+ if (r < 0)
+ goto finish;
+ }
+
+ /* We honour K links only for halt/reboot. For the normal
+ * runlevels we assume the stop jobs will be implicitly added
+ * by the core logic. Also, we don't really distinguish here
+ * between the runlevels 0 and 6 and just add them to the
+ * special shutdown target. */
+ SET_FOREACH(service, shutdown_services, j) {
+ service = unit_follow_merge(service);
+
+ if (service->fragment_path)
+ continue;
+
+ r = unit_add_two_dependencies_by_name(
+ service, UNIT_BEFORE, UNIT_CONFLICTS,
+ SPECIAL_SHUTDOWN_TARGET, NULL, true);
+ if (r < 0)
+ goto finish;
+ }
+
+ r = 0;
+
+finish:
+
+ for (i = 0; i < ELEMENTSOF(rcnd_table); i++)
+ set_free(runlevel_services[i]);
+
+ return r;
+}
+#endif
+
+static void service_bus_name_owner_change(
+ Unit *u,
+ const char *name,
+ const char *old_owner,
+ const char *new_owner) {
+
+ Service *s = SERVICE(u);
+
+ assert(s);
+ assert(name);
+
+ assert(streq(s->bus_name, name));
+ assert(old_owner || new_owner);
+
+ if (old_owner && new_owner)
+ log_debug_unit(u->id,
+ "%s's D-Bus name %s changed owner from %s to %s",
+ u->id, name, old_owner, new_owner);
+ else if (old_owner)
+ log_debug_unit(u->id,
+ "%s's D-Bus name %s no longer registered by %s",
+ u->id, name, old_owner);
+ else
+ log_debug_unit(u->id,
+ "%s's D-Bus name %s now registered by %s",
+ u->id, name, new_owner);
+
+ s->bus_name_good = !!new_owner;
+
+ if (s->type == SERVICE_DBUS) {
+
+ /* service_enter_running() will figure out what to
+ * do */
+ if (s->state == SERVICE_RUNNING)
+ service_enter_running(s, SERVICE_SUCCESS);
+ else if (s->state == SERVICE_START && new_owner)
+ service_enter_start_post(s);
+
+ } else if (new_owner &&
+ s->main_pid <= 0 &&
+ (s->state == SERVICE_START ||
+ s->state == SERVICE_START_POST ||
+ s->state == SERVICE_RUNNING ||
+ s->state == SERVICE_RELOAD)) {
+
+ /* Try to acquire PID from bus service */
+ log_debug_unit(u->id,
+ "Trying to acquire PID from D-Bus name...");
+
+ bus_query_pid(u->manager, name);
+ }
+}
+
+static void service_bus_query_pid_done(
+ Unit *u,
+ const char *name,
+ pid_t pid) {
+
+ Service *s = SERVICE(u);
+
+ assert(s);
+ assert(name);
+
+ log_debug_unit(u->id,
+ "%s's D-Bus name %s is now owned by process %u",
+ u->id, name, (unsigned) pid);
+
+ if (s->main_pid <= 0 &&
+ (s->state == SERVICE_START ||
+ s->state == SERVICE_START_POST ||
+ s->state == SERVICE_RUNNING ||
+ s->state == SERVICE_RELOAD))
+ service_set_main_pid(s, pid);
+}
+
+int service_set_socket_fd(Service *s, int fd, Socket *sock) {
+
+ assert(s);
+ assert(fd >= 0);
+
+ /* This is called by the socket code when instantiating a new
+ * service for a stream socket and the socket needs to be
+ * configured. */
+
+ if (UNIT(s)->load_state != UNIT_LOADED)
+ return -EINVAL;
+
+ if (s->socket_fd >= 0)
+ return -EBUSY;
+
+ if (s->state != SERVICE_DEAD)
+ return -EAGAIN;
+
+ s->socket_fd = fd;
+ s->got_socket_fd = true;
+
+ unit_ref_set(&s->accept_socket, UNIT(sock));
+
+ return unit_add_two_dependencies(UNIT(sock), UNIT_BEFORE, UNIT_TRIGGERS, UNIT(s), false);
+}
+
+static void service_reset_failed(Unit *u) {
+ Service *s = SERVICE(u);
+
+ assert(s);
+
+ if (s->state == SERVICE_FAILED)
+ service_set_state(s, SERVICE_DEAD);
+
+ s->result = SERVICE_SUCCESS;
+ s->reload_result = SERVICE_SUCCESS;
+
+ RATELIMIT_RESET(s->start_limit);
+}
+
+static int service_kill(Unit *u, KillWho who, int signo, DBusError *error) {
+ Service *s = SERVICE(u);
+ return unit_kill_common(u, who, signo, s->main_pid, s->control_pid, error);
+}
+
+static const char* const service_state_table[_SERVICE_STATE_MAX] = {
+ [SERVICE_DEAD] = "dead",
+ [SERVICE_START_PRE] = "start-pre",
+ [SERVICE_START] = "start",
+ [SERVICE_START_POST] = "start-post",
+ [SERVICE_RUNNING] = "running",
+ [SERVICE_EXITED] = "exited",
+ [SERVICE_RELOAD] = "reload",
+ [SERVICE_STOP] = "stop",
+ [SERVICE_STOP_SIGTERM] = "stop-sigterm",
+ [SERVICE_STOP_SIGKILL] = "stop-sigkill",
+ [SERVICE_STOP_POST] = "stop-post",
+ [SERVICE_FINAL_SIGTERM] = "final-sigterm",
+ [SERVICE_FINAL_SIGKILL] = "final-sigkill",
+ [SERVICE_FAILED] = "failed",
+ [SERVICE_AUTO_RESTART] = "auto-restart",
+};
+
+DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
+
+static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
+ [SERVICE_RESTART_NO] = "no",
+ [SERVICE_RESTART_ON_SUCCESS] = "on-success",
+ [SERVICE_RESTART_ON_FAILURE] = "on-failure",
+ [SERVICE_RESTART_ON_ABORT] = "on-abort",
+ [SERVICE_RESTART_ALWAYS] = "always"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
+
+static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
+ [SERVICE_SIMPLE] = "simple",
+ [SERVICE_FORKING] = "forking",
+ [SERVICE_ONESHOT] = "oneshot",
+ [SERVICE_DBUS] = "dbus",
+ [SERVICE_NOTIFY] = "notify",
+ [SERVICE_IDLE] = "idle"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
+
+static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
+ [SERVICE_EXEC_START_PRE] = "ExecStartPre",
+ [SERVICE_EXEC_START] = "ExecStart",
+ [SERVICE_EXEC_START_POST] = "ExecStartPost",
+ [SERVICE_EXEC_RELOAD] = "ExecReload",
+ [SERVICE_EXEC_STOP] = "ExecStop",
+ [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
+};
+
+DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
+
+static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
+ [NOTIFY_NONE] = "none",
+ [NOTIFY_MAIN] = "main",
+ [NOTIFY_ALL] = "all"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
+
+static const char* const service_result_table[_SERVICE_RESULT_MAX] = {
+ [SERVICE_SUCCESS] = "success",
+ [SERVICE_FAILURE_RESOURCES] = "resources",
+ [SERVICE_FAILURE_TIMEOUT] = "timeout",
+ [SERVICE_FAILURE_EXIT_CODE] = "exit-code",
+ [SERVICE_FAILURE_SIGNAL] = "signal",
+ [SERVICE_FAILURE_CORE_DUMP] = "core-dump",
+ [SERVICE_FAILURE_WATCHDOG] = "watchdog",
+ [SERVICE_FAILURE_START_LIMIT] = "start-limit"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(service_result, ServiceResult);
+
+static const char* const start_limit_action_table[_SERVICE_START_LIMIT_MAX] = {
+ [SERVICE_START_LIMIT_NONE] = "none",
+ [SERVICE_START_LIMIT_REBOOT] = "reboot",
+ [SERVICE_START_LIMIT_REBOOT_FORCE] = "reboot-force",
+ [SERVICE_START_LIMIT_REBOOT_IMMEDIATE] = "reboot-immediate"
+};
+DEFINE_STRING_TABLE_LOOKUP(start_limit_action, StartLimitAction);
+
+const UnitVTable service_vtable = {
+ .object_size = sizeof(Service),
+
+ .sections =
+ "Unit\0"
+ "Service\0"
+ "Install\0",
+
+ .exec_context_offset = offsetof(Service, exec_context),
+ .exec_section = "Service",
+
+ .init = service_init,
+ .done = service_done,
+ .load = service_load,
+
+ .coldplug = service_coldplug,
+
+ .dump = service_dump,
+
+ .start = service_start,
+ .stop = service_stop,
+ .reload = service_reload,
+
+ .can_reload = service_can_reload,
+
+ .kill = service_kill,
+
+ .serialize = service_serialize,
+ .deserialize_item = service_deserialize_item,
+
+ .active_state = service_active_state,
+ .sub_state_to_string = service_sub_state_to_string,
+
+ .check_gc = service_check_gc,
+ .check_snapshot = service_check_snapshot,
+
+ .sigchld_event = service_sigchld_event,
+ .timer_event = service_timer_event,
+ .fd_event = service_fd_event,
+
+ .reset_failed = service_reset_failed,
+
+ .cgroup_notify_empty = service_cgroup_notify_event,
+ .notify_message = service_notify_message,
+
+ .bus_name_owner_change = service_bus_name_owner_change,
+ .bus_query_pid_done = service_bus_query_pid_done,
+
+ .bus_interface = "org.freedesktop.systemd1.Service",
+ .bus_message_handler = bus_service_message_handler,
+ .bus_invalidating_properties = bus_service_invalidating_properties,
+
+#ifdef HAVE_SYSV_COMPAT
+ .enumerate = service_enumerate,
+#endif
+ .status_message_formats = {
+ .starting_stopping = {
+ [0] = "Starting %s...",
+ [1] = "Stopping %s...",
+ },
+ .finished_start_job = {
+ [JOB_DONE] = "Started %s.",
+ [JOB_FAILED] = "Failed to start %s.",
+ [JOB_DEPENDENCY] = "Dependency failed for %s.",
+ [JOB_TIMEOUT] = "Timed out starting %s.",
+ },
+ .finished_stop_job = {
+ [JOB_DONE] = "Stopped %s.",
+ [JOB_FAILED] = "Stopped (with error) %s.",
+ [JOB_TIMEOUT] = "Timed out stopping %s.",
+ },
+ },
+};
diff --git a/src/core/service.h b/src/core/service.h
new file mode 100644
index 0000000000..703d3faa45
--- /dev/null
+++ b/src/core/service.h
@@ -0,0 +1,225 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+typedef struct Service Service;
+
+#include "unit.h"
+#include "path.h"
+#include "ratelimit.h"
+#include "service.h"
+#include "kill.h"
+#include "exit-status.h"
+
+typedef enum ServiceState {
+ SERVICE_DEAD,
+ SERVICE_START_PRE,
+ SERVICE_START,
+ SERVICE_START_POST,
+ SERVICE_RUNNING,
+ SERVICE_EXITED, /* Nothing is running anymore, but RemainAfterExit is true hence this is OK */
+ SERVICE_RELOAD,
+ SERVICE_STOP, /* No STOP_PRE state, instead just register multiple STOP executables */
+ SERVICE_STOP_SIGTERM,
+ SERVICE_STOP_SIGKILL,
+ SERVICE_STOP_POST,
+ SERVICE_FINAL_SIGTERM, /* In case the STOP_POST executable hangs, we shoot that down, too */
+ SERVICE_FINAL_SIGKILL,
+ SERVICE_FAILED,
+ SERVICE_AUTO_RESTART,
+ _SERVICE_STATE_MAX,
+ _SERVICE_STATE_INVALID = -1
+} ServiceState;
+
+typedef enum ServiceRestart {
+ SERVICE_RESTART_NO,
+ SERVICE_RESTART_ON_SUCCESS,
+ SERVICE_RESTART_ON_FAILURE,
+ SERVICE_RESTART_ON_ABORT,
+ SERVICE_RESTART_ALWAYS,
+ _SERVICE_RESTART_MAX,
+ _SERVICE_RESTART_INVALID = -1
+} ServiceRestart;
+
+typedef enum ServiceType {
+ SERVICE_SIMPLE, /* we fork and go on right-away (i.e. modern socket activated daemons) */
+ SERVICE_FORKING, /* forks by itself (i.e. traditional daemons) */
+ SERVICE_ONESHOT, /* we fork and wait until the program finishes (i.e. programs like fsck which run and need to finish before we continue) */
+ SERVICE_DBUS, /* we fork and wait until a specific D-Bus name appears on the bus */
+ SERVICE_NOTIFY, /* we fork and wait until a daemon sends us a ready message with sd_notify() */
+ SERVICE_IDLE, /* much like simple, but delay exec() until all jobs are dispatched. */
+ _SERVICE_TYPE_MAX,
+ _SERVICE_TYPE_INVALID = -1
+} ServiceType;
+
+typedef enum ServiceExecCommand {
+ SERVICE_EXEC_START_PRE,
+ SERVICE_EXEC_START,
+ SERVICE_EXEC_START_POST,
+ SERVICE_EXEC_RELOAD,
+ SERVICE_EXEC_STOP,
+ SERVICE_EXEC_STOP_POST,
+ _SERVICE_EXEC_COMMAND_MAX,
+ _SERVICE_EXEC_COMMAND_INVALID = -1
+} ServiceExecCommand;
+
+typedef enum NotifyAccess {
+ NOTIFY_NONE,
+ NOTIFY_ALL,
+ NOTIFY_MAIN,
+ _NOTIFY_ACCESS_MAX,
+ _NOTIFY_ACCESS_INVALID = -1
+} NotifyAccess;
+
+typedef enum ServiceResult {
+ SERVICE_SUCCESS,
+ SERVICE_FAILURE_RESOURCES,
+ SERVICE_FAILURE_TIMEOUT,
+ SERVICE_FAILURE_EXIT_CODE,
+ SERVICE_FAILURE_SIGNAL,
+ SERVICE_FAILURE_CORE_DUMP,
+ SERVICE_FAILURE_WATCHDOG,
+ SERVICE_FAILURE_START_LIMIT,
+ _SERVICE_RESULT_MAX,
+ _SERVICE_RESULT_INVALID = -1
+} ServiceResult;
+
+typedef enum StartLimitAction {
+ SERVICE_START_LIMIT_NONE,
+ SERVICE_START_LIMIT_REBOOT,
+ SERVICE_START_LIMIT_REBOOT_FORCE,
+ SERVICE_START_LIMIT_REBOOT_IMMEDIATE,
+ _SERVICE_START_LIMIT_MAX,
+ _SERVICE_START_LIMIT_INVALID = -1
+} StartLimitAction;
+
+struct Service {
+ Unit meta;
+
+ ServiceType type;
+ ServiceRestart restart;
+ ExitStatusSet restart_ignore_status;
+ ExitStatusSet success_status;
+
+ /* If set we'll read the main daemon PID from this file */
+ char *pid_file;
+
+ usec_t restart_usec;
+ usec_t timeout_start_usec;
+ usec_t timeout_stop_usec;
+
+ dual_timestamp watchdog_timestamp;
+ usec_t watchdog_usec;
+ Watch watchdog_watch;
+
+ ExecCommand* exec_command[_SERVICE_EXEC_COMMAND_MAX];
+
+ ExecContext exec_context;
+ KillContext kill_context;
+
+ ServiceState state, deserialized_state;
+
+ /* The exit status of the real main process */
+ ExecStatus main_exec_status;
+
+ /* The currently executed control process */
+ ExecCommand *control_command;
+
+ /* The currently executed main process, which may be NULL if
+ * the main process got started via forking mode and not by
+ * us */
+ ExecCommand *main_command;
+
+ /* The ID of the control command currently being executed */
+ ServiceExecCommand control_command_id;
+
+ pid_t main_pid, control_pid;
+ int socket_fd;
+
+ int fsck_passno;
+
+ bool permissions_start_only;
+ bool root_directory_start_only;
+ bool remain_after_exit;
+ bool guess_main_pid;
+
+ /* If we shut down, remember why */
+ ServiceResult result;
+ ServiceResult reload_result;
+
+ bool main_pid_known:1;
+ bool main_pid_alien:1;
+ bool bus_name_good:1;
+ bool forbid_restart:1;
+ bool got_socket_fd:1;
+ bool start_timeout_defined:1;
+#ifdef HAVE_SYSV_COMPAT
+ bool is_sysv:1;
+ bool sysv_has_lsb:1;
+ bool sysv_enabled:1;
+ int sysv_start_priority_from_rcnd;
+ int sysv_start_priority;
+
+ char *sysv_runlevels;
+#endif
+
+ char *bus_name;
+
+ char *status_text;
+
+ RateLimit start_limit;
+ StartLimitAction start_limit_action;
+
+ UnitRef accept_socket;
+
+ Watch timer_watch;
+ PathSpec *pid_file_pathspec;
+
+ NotifyAccess notify_access;
+};
+
+extern const UnitVTable service_vtable;
+
+struct Socket;
+
+int service_set_socket_fd(Service *s, int fd, struct Socket *socket);
+
+const char* service_state_to_string(ServiceState i) _const_;
+ServiceState service_state_from_string(const char *s) _pure_;
+
+const char* service_restart_to_string(ServiceRestart i) _const_;
+ServiceRestart service_restart_from_string(const char *s) _pure_;
+
+const char* service_type_to_string(ServiceType i) _const_;
+ServiceType service_type_from_string(const char *s) _pure_;
+
+const char* service_exec_command_to_string(ServiceExecCommand i) _const_;
+ServiceExecCommand service_exec_command_from_string(const char *s) _pure_;
+
+const char* notify_access_to_string(NotifyAccess i) _const_;
+NotifyAccess notify_access_from_string(const char *s) _pure_;
+
+const char* service_result_to_string(ServiceResult i) _const_;
+ServiceResult service_result_from_string(const char *s) _pure_;
+
+const char* start_limit_action_to_string(StartLimitAction i) _const_;
+StartLimitAction start_limit_action_from_string(const char *s) _pure_;
diff --git a/src/core/shutdown.c b/src/core/shutdown.c
new file mode 100644
index 0000000000..2db761de36
--- /dev/null
+++ b/src/core/shutdown.c
@@ -0,0 +1,332 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 ProFUSION embedded systems
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/mman.h>
+#include <sys/types.h>
+#include <sys/reboot.h>
+#include <linux/reboot.h>
+#include <sys/wait.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/mount.h>
+#include <sys/syscall.h>
+#include <fcntl.h>
+#include <dirent.h>
+#include <errno.h>
+#include <unistd.h>
+#include <signal.h>
+#include <stdbool.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "missing.h"
+#include "log.h"
+#include "umount.h"
+#include "util.h"
+#include "mkdir.h"
+#include "virt.h"
+#include "watchdog.h"
+#include "killall.h"
+
+#define FINALIZE_ATTEMPTS 50
+
+static int prepare_new_root(void) {
+ static const char dirs[] =
+ "/run/initramfs/oldroot\0"
+ "/run/initramfs/proc\0"
+ "/run/initramfs/sys\0"
+ "/run/initramfs/dev\0"
+ "/run/initramfs/run\0";
+
+ const char *dir;
+
+ if (mount("/run/initramfs", "/run/initramfs", NULL, MS_BIND, NULL) < 0) {
+ log_error("Failed to mount bind /run/initramfs on /run/initramfs: %m");
+ return -errno;
+ }
+
+ if (mount(NULL, "/run/initramfs", NULL, MS_PRIVATE, NULL) < 0) {
+ log_error("Failed to make /run/initramfs private mount: %m");
+ return -errno;
+ }
+
+ NULSTR_FOREACH(dir, dirs)
+ if (mkdir_p_label(dir, 0755) < 0 && errno != EEXIST) {
+ log_error("Failed to mkdir %s: %m", dir);
+ return -errno;
+ }
+
+ if (mount("/sys", "/run/initramfs/sys", NULL, MS_BIND, NULL) < 0) {
+ log_error("Failed to mount bind /sys on /run/initramfs/sys: %m");
+ return -errno;
+ }
+
+ if (mount("/proc", "/run/initramfs/proc", NULL, MS_BIND, NULL) < 0) {
+ log_error("Failed to mount bind /proc on /run/initramfs/proc: %m");
+ return -errno;
+ }
+
+ if (mount("/dev", "/run/initramfs/dev", NULL, MS_BIND, NULL) < 0) {
+ log_error("Failed to mount bind /dev on /run/initramfs/dev: %m");
+ return -errno;
+ }
+
+ if (mount("/run", "/run/initramfs/run", NULL, MS_BIND, NULL) < 0) {
+ log_error("Failed to mount bind /run on /run/initramfs/run: %m");
+ return -errno;
+ }
+
+ return 0;
+}
+
+static int pivot_to_new_root(void) {
+
+ if (chdir("/run/initramfs") < 0) {
+ log_error("Failed to change directory to /run/initramfs: %m");
+ return -errno;
+ }
+
+ /* Work-around for a kernel bug: for some reason the kernel
+ * refuses switching root if any file systems are mounted
+ * MS_SHARED. Hence remount them MS_PRIVATE here as a
+ * work-around.
+ *
+ * https://bugzilla.redhat.com/show_bug.cgi?id=847418 */
+ if (mount(NULL, "/", NULL, MS_REC|MS_PRIVATE, NULL) < 0)
+ log_warning("Failed to make \"/\" private mount: %m");
+
+ if (pivot_root(".", "oldroot") < 0) {
+ log_error("pivot failed: %m");
+ /* only chroot if pivot root succeeded */
+ return -errno;
+ }
+
+ chroot(".");
+
+ setsid();
+ make_console_stdio();
+
+ log_info("Successfully changed into root pivot.");
+
+ return 0;
+}
+
+int main(int argc, char *argv[]) {
+ int cmd, r;
+ unsigned retries;
+ bool need_umount = true, need_swapoff = true, need_loop_detach = true, need_dm_detach = true;
+ bool in_container, use_watchdog = false;
+ char *arguments[3];
+
+ log_parse_environment();
+ log_set_target(LOG_TARGET_CONSOLE); /* syslog will die if not gone yet */
+ log_open();
+
+ umask(0022);
+
+ if (getpid() != 1) {
+ log_error("Not executed by init (pid 1).");
+ r = -EPERM;
+ goto error;
+ }
+
+ if (argc != 2) {
+ log_error("Invalid number of arguments.");
+ r = -EINVAL;
+ goto error;
+ }
+
+ in_container = detect_container(NULL) > 0;
+
+ if (streq(argv[1], "reboot"))
+ cmd = RB_AUTOBOOT;
+ else if (streq(argv[1], "poweroff"))
+ cmd = RB_POWER_OFF;
+ else if (streq(argv[1], "halt"))
+ cmd = RB_HALT_SYSTEM;
+ else if (streq(argv[1], "kexec"))
+ cmd = LINUX_REBOOT_CMD_KEXEC;
+ else {
+ log_error("Unknown action '%s'.", argv[1]);
+ r = -EINVAL;
+ goto error;
+ }
+
+ use_watchdog = !!getenv("WATCHDOG_USEC");
+
+ /* lock us into memory */
+ mlockall(MCL_CURRENT|MCL_FUTURE);
+
+ log_info("Sending SIGTERM to remaining processes...");
+ broadcast_signal(SIGTERM, true);
+
+ log_info("Sending SIGKILL to remaining processes...");
+ broadcast_signal(SIGKILL, true);
+
+ if (in_container) {
+ need_swapoff = false;
+ need_dm_detach = false;
+ need_loop_detach = false;
+ }
+
+ /* Unmount all mountpoints, swaps, and loopback devices */
+ for (retries = 0; retries < FINALIZE_ATTEMPTS; retries++) {
+ bool changed = false;
+
+ if (use_watchdog)
+ watchdog_ping();
+
+ if (need_umount) {
+ log_info("Unmounting file systems.");
+ r = umount_all(&changed);
+ if (r == 0) {
+ need_umount = false;
+ log_info("All filesystems unmounted.");
+ } else if (r > 0)
+ log_info("Not all file systems unmounted, %d left.", r);
+ else
+ log_error("Failed to unmount file systems: %s", strerror(-r));
+ }
+
+ if (need_swapoff) {
+ log_info("Deactivating swaps.");
+ r = swapoff_all(&changed);
+ if (r == 0) {
+ need_swapoff = false;
+ log_info("All swaps deactivated.");
+ } else if (r > 0)
+ log_info("Not all swaps deactivated, %d left.", r);
+ else
+ log_error("Failed to deactivate swaps: %s", strerror(-r));
+ }
+
+ if (need_loop_detach) {
+ log_info("Detaching loop devices.");
+ r = loopback_detach_all(&changed);
+ if (r == 0) {
+ need_loop_detach = false;
+ log_info("All loop devices detached.");
+ } else if (r > 0)
+ log_info("Not all loop devices detached, %d left.", r);
+ else
+ log_error("Failed to detach loop devices: %s", strerror(-r));
+ }
+
+ if (need_dm_detach) {
+ log_info("Detaching DM devices.");
+ r = dm_detach_all(&changed);
+ if (r == 0) {
+ need_dm_detach = false;
+ log_info("All DM devices detached.");
+ } else if (r > 0)
+ log_info("Not all DM devices detached, %d left.", r);
+ else
+ log_error("Failed to detach DM devices: %s", strerror(-r));
+ }
+
+ if (!need_umount && !need_swapoff && !need_loop_detach && !need_dm_detach) {
+ if (retries > 0)
+ log_info("All filesystems, swaps, loop devices, DM devices detached.");
+ /* Yay, done */
+ break;
+ }
+
+ /* If in this iteration we didn't manage to
+ * unmount/deactivate anything, we simply give up */
+ if (!changed) {
+ log_error("Cannot finalize remaining file systems and devices, giving up.");
+ break;
+ }
+
+ log_debug("Couldn't finalize remaining file systems and devices after %u retries, trying again.", retries+1);
+ }
+
+ if (retries >= FINALIZE_ATTEMPTS)
+ log_error("Too many iterations, giving up.");
+ else
+ log_info("Storage is finalized.");
+
+ arguments[0] = NULL;
+ arguments[1] = argv[1];
+ arguments[2] = NULL;
+ execute_directory(SYSTEM_SHUTDOWN_PATH, NULL, arguments);
+
+ if (!in_container && !in_initrd() &&
+ access("/run/initramfs/shutdown", X_OK) == 0) {
+
+ if (prepare_new_root() >= 0 &&
+ pivot_to_new_root() >= 0) {
+
+ log_info("Returning to initrd...");
+
+ execv("/shutdown", argv);
+ log_error("Failed to execute shutdown binary: %m");
+ }
+ }
+
+ /* The kernel will automaticall flush ATA disks and suchlike
+ * on reboot(), but the file systems need to be synce'd
+ * explicitly in advance. So let's do this here, but not
+ * needlessly slow down containers. */
+ if (!in_container)
+ sync();
+
+ if (cmd == LINUX_REBOOT_CMD_KEXEC) {
+
+ if (!in_container) {
+ /* We cheat and exec kexec to avoid doing all its work */
+ pid_t pid = fork();
+
+ if (pid < 0)
+ log_error("Could not fork: %m. Falling back to normal reboot.");
+ else if (pid > 0) {
+ wait_for_terminate_and_warn("kexec", pid);
+ log_warning("kexec failed. Falling back to normal reboot.");
+ } else {
+ /* Child */
+ const char *args[3] = { "/sbin/kexec", "-e", NULL };
+ execv(args[0], (char * const *) args);
+ return EXIT_FAILURE;
+ }
+ }
+
+ cmd = RB_AUTOBOOT;
+ }
+
+ reboot(cmd);
+
+ if (errno == EPERM && in_container) {
+ /* If we are in a container, and we lacked
+ * CAP_SYS_BOOT just exit, this will kill our
+ * container for good. */
+ log_error("Exiting container.");
+ exit(0);
+ }
+
+ log_error("Failed to invoke reboot(): %m");
+ r = -errno;
+
+ error:
+ log_error("Critical error while doing system shutdown: %s", strerror(-r));
+
+ freeze();
+ return EXIT_FAILURE;
+}
diff --git a/src/core/smack-setup.c b/src/core/smack-setup.c
new file mode 100644
index 0000000000..73eeb04190
--- /dev/null
+++ b/src/core/smack-setup.c
@@ -0,0 +1,151 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright (C) 2013 Intel Corporation
+ Authors:
+ Nathaniel Chen <nathaniel.chen@intel.com>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published
+ by the Free Software Foundation; either version 2.1 of the License,
+ or (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include <errno.h>
+#include <string.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <sys/vfs.h>
+#include <fcntl.h>
+#include <sys/types.h>
+#include <dirent.h>
+#include <sys/mount.h>
+#include <stdint.h>
+
+#include "macro.h"
+#include "smack-setup.h"
+#include "util.h"
+#include "log.h"
+#include "label.h"
+
+#define SMACK_CONFIG "/etc/smack/accesses.d/"
+#define CIPSO_CONFIG "/etc/smack/cipso/"
+
+static int write_rules(const char* dstpath, const char* srcdir) {
+ _cleanup_fclose_ FILE *dst = NULL;
+ _cleanup_closedir_ DIR *dir = NULL;
+ struct dirent *entry;
+ char buf[NAME_MAX];
+ int dfd = -1;
+ int r = 0;
+
+ dst = fopen(dstpath, "we");
+ if (!dst) {
+ if (errno != ENOENT)
+ log_warning("Failed to open %s: %m", dstpath);
+ return -errno; /* negative error */
+ }
+
+ /* write rules to dst from every file in the directory */
+ dir = opendir(srcdir);
+ if (!dir) {
+ if (errno != ENOENT)
+ log_warning("Failed to opendir %s: %m", srcdir);
+ return errno; /* positive on purpose */
+ }
+
+ dfd = dirfd(dir);
+ assert(dfd >= 0);
+
+ FOREACH_DIRENT(entry, dir, return 0) {
+ int fd;
+ _cleanup_fclose_ FILE *policy = NULL;
+
+ fd = openat(dfd, entry->d_name, O_RDONLY|O_CLOEXEC);
+ if (fd < 0) {
+ if (r == 0)
+ r = -errno;
+ log_warning("Failed to open %s: %m", entry->d_name);
+ continue;
+ }
+
+ policy = fdopen(fd, "re");
+ if (!policy) {
+ if (r == 0)
+ r = -errno;
+ close_nointr_nofail(fd);
+ log_error("Failed to open %s: %m", entry->d_name);
+ continue;
+ }
+
+ /* load2 write rules in the kernel require a line buffered stream */
+ FOREACH_LINE(buf, policy,
+ log_error("Failed to read line from %s: %m",
+ entry->d_name)) {
+ if (!fputs(buf, dst)) {
+ if (r == 0)
+ r = -EINVAL;
+ log_error("Failed to write line to %s", dstpath);
+ break;
+ }
+ if (fflush(dst)) {
+ if (r == 0)
+ r = -errno;
+ log_error("Failed to flush writes to %s: %m", dstpath);
+ break;
+ }
+ }
+ }
+
+ return r;
+}
+
+
+int smack_setup(void) {
+ int r;
+
+ r = write_rules("/sys/fs/smackfs/load2", SMACK_CONFIG);
+ switch(r) {
+ case -ENOENT:
+ log_debug("Smack is not enabled in the kernel.");
+ return 0;
+ case ENOENT:
+ log_debug("Smack access rules directory " SMACK_CONFIG " not found");
+ return 0;
+ case 0:
+ log_info("Successfully loaded Smack policies.");
+ break;
+ default:
+ log_warning("Failed to load Smack access rules: %s, ignoring.",
+ strerror(abs(r)));
+ return 0;
+ }
+
+ r = write_rules("/sys/fs/smackfs/cipso2", CIPSO_CONFIG);
+ switch(r) {
+ case -ENOENT:
+ log_debug("Smack/CIPSO is not enabled in the kernel.");
+ return 0;
+ case ENOENT:
+ log_debug("Smack/CIPSO access rules directory " CIPSO_CONFIG " not found");
+ return 0;
+ case 0:
+ log_info("Successfully loaded Smack/CIPSO policies.");
+ return 0;
+ default:
+ log_warning("Failed to load Smack/CIPSO access rules: %s, ignoring.",
+ strerror(abs(r)));
+ return 0;
+ }
+}
diff --git a/src/core/smack-setup.h b/src/core/smack-setup.h
new file mode 100644
index 0000000000..ffe91843c3
--- /dev/null
+++ b/src/core/smack-setup.h
@@ -0,0 +1,26 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright (C) 2013 Intel Corporation
+ Authors:
+ Nathaniel Chen <nathaniel.chen@intel.com>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published
+ by the Free Software Foundation; either version 2.1 of the License,
+ or (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+int smack_setup(void);
diff --git a/src/core/snapshot.c b/src/core/snapshot.c
new file mode 100644
index 0000000000..a63eccd8de
--- /dev/null
+++ b/src/core/snapshot.c
@@ -0,0 +1,309 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+
+#include "unit.h"
+#include "snapshot.h"
+#include "unit-name.h"
+#include "dbus-snapshot.h"
+#include "bus-errors.h"
+
+static const UnitActiveState state_translation_table[_SNAPSHOT_STATE_MAX] = {
+ [SNAPSHOT_DEAD] = UNIT_INACTIVE,
+ [SNAPSHOT_ACTIVE] = UNIT_ACTIVE
+};
+
+static void snapshot_init(Unit *u) {
+ Snapshot *s = SNAPSHOT(u);
+
+ assert(s);
+ assert(UNIT(s)->load_state == UNIT_STUB);
+
+ UNIT(s)->ignore_on_isolate = true;
+ UNIT(s)->ignore_on_snapshot = true;
+}
+
+static void snapshot_set_state(Snapshot *s, SnapshotState state) {
+ SnapshotState old_state;
+ assert(s);
+
+ old_state = s->state;
+ s->state = state;
+
+ if (state != old_state)
+ log_debug("%s changed %s -> %s",
+ UNIT(s)->id,
+ snapshot_state_to_string(old_state),
+ snapshot_state_to_string(state));
+
+ unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], true);
+}
+
+static int snapshot_load(Unit *u) {
+ Snapshot *s = SNAPSHOT(u);
+
+ assert(u);
+ assert(u->load_state == UNIT_STUB);
+
+ /* Make sure that only snapshots created via snapshot_create()
+ * can be loaded */
+ if (!s->by_snapshot_create && UNIT(s)->manager->n_reloading <= 0)
+ return -ENOENT;
+
+ u->load_state = UNIT_LOADED;
+ return 0;
+}
+
+static int snapshot_coldplug(Unit *u) {
+ Snapshot *s = SNAPSHOT(u);
+
+ assert(s);
+ assert(s->state == SNAPSHOT_DEAD);
+
+ if (s->deserialized_state != s->state)
+ snapshot_set_state(s, s->deserialized_state);
+
+ return 0;
+}
+
+static void snapshot_dump(Unit *u, FILE *f, const char *prefix) {
+ Snapshot *s = SNAPSHOT(u);
+
+ assert(s);
+ assert(f);
+
+ fprintf(f,
+ "%sSnapshot State: %s\n"
+ "%sClean Up: %s\n",
+ prefix, snapshot_state_to_string(s->state),
+ prefix, yes_no(s->cleanup));
+}
+
+static int snapshot_start(Unit *u) {
+ Snapshot *s = SNAPSHOT(u);
+
+ assert(s);
+ assert(s->state == SNAPSHOT_DEAD);
+
+ snapshot_set_state(s, SNAPSHOT_ACTIVE);
+
+ if (s->cleanup)
+ unit_add_to_cleanup_queue(u);
+
+ return 0;
+}
+
+static int snapshot_stop(Unit *u) {
+ Snapshot *s = SNAPSHOT(u);
+
+ assert(s);
+ assert(s->state == SNAPSHOT_ACTIVE);
+
+ snapshot_set_state(s, SNAPSHOT_DEAD);
+ return 0;
+}
+
+static int snapshot_serialize(Unit *u, FILE *f, FDSet *fds) {
+ Snapshot *s = SNAPSHOT(u);
+ Unit *other;
+ Iterator i;
+
+ assert(s);
+ assert(f);
+ assert(fds);
+
+ unit_serialize_item(u, f, "state", snapshot_state_to_string(s->state));
+ unit_serialize_item(u, f, "cleanup", yes_no(s->cleanup));
+ SET_FOREACH(other, u->dependencies[UNIT_WANTS], i)
+ unit_serialize_item(u, f, "wants", other->id);
+
+ return 0;
+}
+
+static int snapshot_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
+ Snapshot *s = SNAPSHOT(u);
+ int r;
+
+ assert(u);
+ assert(key);
+ assert(value);
+ assert(fds);
+
+ if (streq(key, "state")) {
+ SnapshotState state;
+
+ if ((state = snapshot_state_from_string(value)) < 0)
+ log_debug("Failed to parse state value %s", value);
+ else
+ s->deserialized_state = state;
+
+ } else if (streq(key, "cleanup")) {
+
+ if ((r = parse_boolean(value)) < 0)
+ log_debug("Failed to parse cleanup value %s", value);
+ else
+ s->cleanup = r;
+
+ } else if (streq(key, "wants")) {
+
+ if ((r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_WANTS, value, NULL, true)) < 0)
+ return r;
+ } else
+ log_debug("Unknown serialization key '%s'", key);
+
+ return 0;
+}
+
+_pure_ static UnitActiveState snapshot_active_state(Unit *u) {
+ assert(u);
+
+ return state_translation_table[SNAPSHOT(u)->state];
+}
+
+_pure_ static const char *snapshot_sub_state_to_string(Unit *u) {
+ assert(u);
+
+ return snapshot_state_to_string(SNAPSHOT(u)->state);
+}
+
+int snapshot_create(Manager *m, const char *name, bool cleanup, DBusError *e, Snapshot **_s) {
+ Iterator i;
+ Unit *other, *u = NULL;
+ char *n = NULL;
+ int r;
+ const char *k;
+
+ assert(m);
+ assert(_s);
+
+ if (name) {
+ if (!unit_name_is_valid(name, false)) {
+ dbus_set_error(e, BUS_ERROR_INVALID_NAME, "Unit name %s is not valid.", name);
+ return -EINVAL;
+ }
+
+ if (unit_name_to_type(name) != UNIT_SNAPSHOT) {
+ dbus_set_error(e, BUS_ERROR_UNIT_TYPE_MISMATCH, "Unit name %s lacks snapshot suffix.", name);
+ return -EINVAL;
+ }
+
+ if (manager_get_unit(m, name)) {
+ dbus_set_error(e, BUS_ERROR_UNIT_EXISTS, "Snapshot %s exists already.", name);
+ return -EEXIST;
+ }
+
+ } else {
+
+ for (;;) {
+ if (asprintf(&n, "snapshot-%u.snapshot", ++ m->n_snapshots) < 0)
+ return -ENOMEM;
+
+ if (!manager_get_unit(m, n))
+ break;
+
+ free(n);
+ }
+
+ name = n;
+ }
+
+ r = manager_load_unit_prepare(m, name, NULL, e, &u);
+ free(n);
+
+ if (r < 0)
+ goto fail;
+
+ SNAPSHOT(u)->by_snapshot_create = true;
+ manager_dispatch_load_queue(m);
+ assert(u->load_state == UNIT_LOADED);
+
+ HASHMAP_FOREACH_KEY(other, k, m->units, i) {
+
+ if (other->ignore_on_snapshot)
+ continue;
+
+ if (k != other->id)
+ continue;
+
+ if (UNIT_VTABLE(other)->check_snapshot)
+ if (!UNIT_VTABLE(other)->check_snapshot(other))
+ continue;
+
+ if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
+ continue;
+
+ if ((r = unit_add_two_dependencies(u, UNIT_AFTER, UNIT_WANTS, other, true)) < 0)
+ goto fail;
+ }
+
+ SNAPSHOT(u)->cleanup = cleanup;
+ u->allow_isolate = true;
+ *_s = SNAPSHOT(u);
+
+ return 0;
+
+fail:
+ if (u)
+ unit_add_to_cleanup_queue(u);
+
+ return r;
+}
+
+void snapshot_remove(Snapshot *s) {
+ assert(s);
+
+ unit_add_to_cleanup_queue(UNIT(s));
+}
+
+static const char* const snapshot_state_table[_SNAPSHOT_STATE_MAX] = {
+ [SNAPSHOT_DEAD] = "dead",
+ [SNAPSHOT_ACTIVE] = "active"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(snapshot_state, SnapshotState);
+
+const UnitVTable snapshot_vtable = {
+ .object_size = sizeof(Snapshot),
+
+ .no_alias = true,
+ .no_instances = true,
+ .no_gc = true,
+
+ .init = snapshot_init,
+
+ .load = snapshot_load,
+ .coldplug = snapshot_coldplug,
+
+ .dump = snapshot_dump,
+
+ .start = snapshot_start,
+ .stop = snapshot_stop,
+
+ .serialize = snapshot_serialize,
+ .deserialize_item = snapshot_deserialize_item,
+
+ .active_state = snapshot_active_state,
+ .sub_state_to_string = snapshot_sub_state_to_string,
+
+ .bus_interface = "org.freedesktop.systemd1.Snapshot",
+ .bus_message_handler = bus_snapshot_message_handler
+};
diff --git a/src/core/snapshot.h b/src/core/snapshot.h
new file mode 100644
index 0000000000..56f87cff4d
--- /dev/null
+++ b/src/core/snapshot.h
@@ -0,0 +1,50 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+typedef struct Snapshot Snapshot;
+
+#include "unit.h"
+
+typedef enum SnapshotState {
+ SNAPSHOT_DEAD,
+ SNAPSHOT_ACTIVE,
+ _SNAPSHOT_STATE_MAX,
+ _SNAPSHOT_STATE_INVALID = -1
+} SnapshotState;
+
+struct Snapshot {
+ Unit meta;
+
+ SnapshotState state, deserialized_state;
+
+ bool cleanup;
+ bool by_snapshot_create:1;
+};
+
+extern const UnitVTable snapshot_vtable;
+
+int snapshot_create(Manager *m, const char *name, bool cleanup, DBusError *e, Snapshot **s);
+void snapshot_remove(Snapshot *s);
+
+const char* snapshot_state_to_string(SnapshotState i) _const_;
+SnapshotState snapshot_state_from_string(const char *s) _pure_;
diff --git a/src/core/socket.c b/src/core/socket.c
new file mode 100644
index 0000000000..1b08f0a5fd
--- /dev/null
+++ b/src/core/socket.c
@@ -0,0 +1,2411 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <sys/epoll.h>
+#include <signal.h>
+#include <arpa/inet.h>
+#include <mqueue.h>
+#ifdef HAVE_XATTR
+#include <attr/xattr.h>
+#endif
+
+#include "unit.h"
+#include "socket.h"
+#include "netinet/tcp.h"
+#include "log.h"
+#include "load-dropin.h"
+#include "load-fragment.h"
+#include "strv.h"
+#include "mkdir.h"
+#include "path-util.h"
+#include "unit-name.h"
+#include "unit-printf.h"
+#include "dbus-socket.h"
+#include "missing.h"
+#include "special.h"
+#include "dbus-common.h"
+#include "label.h"
+#include "exit-status.h"
+#include "def.h"
+
+static const UnitActiveState state_translation_table[_SOCKET_STATE_MAX] = {
+ [SOCKET_DEAD] = UNIT_INACTIVE,
+ [SOCKET_START_PRE] = UNIT_ACTIVATING,
+ [SOCKET_START_POST] = UNIT_ACTIVATING,
+ [SOCKET_LISTENING] = UNIT_ACTIVE,
+ [SOCKET_RUNNING] = UNIT_ACTIVE,
+ [SOCKET_STOP_PRE] = UNIT_DEACTIVATING,
+ [SOCKET_STOP_PRE_SIGTERM] = UNIT_DEACTIVATING,
+ [SOCKET_STOP_PRE_SIGKILL] = UNIT_DEACTIVATING,
+ [SOCKET_STOP_POST] = UNIT_DEACTIVATING,
+ [SOCKET_FINAL_SIGTERM] = UNIT_DEACTIVATING,
+ [SOCKET_FINAL_SIGKILL] = UNIT_DEACTIVATING,
+ [SOCKET_FAILED] = UNIT_FAILED
+};
+
+static void socket_init(Unit *u) {
+ Socket *s = SOCKET(u);
+
+ assert(u);
+ assert(u->load_state == UNIT_STUB);
+
+ s->backlog = SOMAXCONN;
+ s->timeout_usec = DEFAULT_TIMEOUT_USEC;
+ s->directory_mode = 0755;
+ s->socket_mode = 0666;
+
+ s->max_connections = 64;
+
+ s->priority = -1;
+ s->ip_tos = -1;
+ s->ip_ttl = -1;
+ s->mark = -1;
+
+ exec_context_init(&s->exec_context);
+ s->exec_context.std_output = u->manager->default_std_output;
+ s->exec_context.std_error = u->manager->default_std_error;
+ kill_context_init(&s->kill_context);
+
+ s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
+}
+
+static void socket_unwatch_control_pid(Socket *s) {
+ assert(s);
+
+ if (s->control_pid <= 0)
+ return;
+
+ unit_unwatch_pid(UNIT(s), s->control_pid);
+ s->control_pid = 0;
+}
+
+void socket_free_ports(Socket *s) {
+ SocketPort *p;
+
+ assert(s);
+
+ while ((p = s->ports)) {
+ LIST_REMOVE(SocketPort, port, s->ports, p);
+
+ if (p->fd >= 0) {
+ unit_unwatch_fd(UNIT(s), &p->fd_watch);
+ close_nointr_nofail(p->fd);
+ }
+
+ free(p->path);
+ free(p);
+ }
+}
+
+static void socket_done(Unit *u) {
+ Socket *s = SOCKET(u);
+
+ assert(s);
+
+ socket_free_ports(s);
+
+ exec_context_done(&s->exec_context, manager_is_reloading_or_reexecuting(u->manager));
+ exec_command_free_array(s->exec_command, _SOCKET_EXEC_COMMAND_MAX);
+ s->control_command = NULL;
+
+ socket_unwatch_control_pid(s);
+
+ unit_ref_unset(&s->service);
+
+ free(s->tcp_congestion);
+ s->tcp_congestion = NULL;
+
+ free(s->bind_to_device);
+ s->bind_to_device = NULL;
+
+ free(s->smack);
+ free(s->smack_ip_in);
+ free(s->smack_ip_out);
+
+ unit_unwatch_timer(u, &s->timer_watch);
+}
+
+static int socket_instantiate_service(Socket *s) {
+ char *prefix, *name;
+ int r;
+ Unit *u;
+
+ assert(s);
+
+ /* This fills in s->service if it isn't filled in yet. For
+ * Accept=yes sockets we create the next connection service
+ * here. For Accept=no this is mostly a NOP since the service
+ * is figured out at load time anyway. */
+
+ if (UNIT_DEREF(s->service))
+ return 0;
+
+ assert(s->accept);
+
+ if (!(prefix = unit_name_to_prefix(UNIT(s)->id)))
+ return -ENOMEM;
+
+ r = asprintf(&name, "%s@%u.service", prefix, s->n_accepted);
+ free(prefix);
+
+ if (r < 0)
+ return -ENOMEM;
+
+ r = manager_load_unit(UNIT(s)->manager, name, NULL, NULL, &u);
+ free(name);
+
+ if (r < 0)
+ return r;
+
+#ifdef HAVE_SYSV_COMPAT
+ if (SERVICE(u)->is_sysv) {
+ log_error("Using SysV services for socket activation is not supported. Refusing.");
+ return -ENOENT;
+ }
+#endif
+
+ u->no_gc = true;
+ unit_ref_set(&s->service, u);
+
+ return unit_add_two_dependencies(UNIT(s), UNIT_BEFORE, UNIT_TRIGGERS, u, false);
+}
+
+static bool have_non_accept_socket(Socket *s) {
+ SocketPort *p;
+
+ assert(s);
+
+ if (!s->accept)
+ return true;
+
+ LIST_FOREACH(port, p, s->ports) {
+
+ if (p->type != SOCKET_SOCKET)
+ return true;
+
+ if (!socket_address_can_accept(&p->address))
+ return true;
+ }
+
+ return false;
+}
+
+static int socket_verify(Socket *s) {
+ assert(s);
+
+ if (UNIT(s)->load_state != UNIT_LOADED)
+ return 0;
+
+ if (!s->ports) {
+ log_error_unit(UNIT(s)->id,
+ "%s lacks Listen setting. Refusing.", UNIT(s)->id);
+ return -EINVAL;
+ }
+
+ if (s->accept && have_non_accept_socket(s)) {
+ log_error_unit(UNIT(s)->id,
+ "%s configured for accepting sockets, but sockets are non-accepting. Refusing.",
+ UNIT(s)->id);
+ return -EINVAL;
+ }
+
+ if (s->accept && s->max_connections <= 0) {
+ log_error_unit(UNIT(s)->id,
+ "%s's MaxConnection setting too small. Refusing.", UNIT(s)->id);
+ return -EINVAL;
+ }
+
+ if (s->accept && UNIT_DEREF(s->service)) {
+ log_error_unit(UNIT(s)->id,
+ "Explicit service configuration for accepting sockets not supported on %s. Refusing.",
+ UNIT(s)->id);
+ return -EINVAL;
+ }
+
+ if (s->exec_context.pam_name && s->kill_context.kill_mode != KILL_CONTROL_GROUP) {
+ log_error_unit(UNIT(s)->id,
+ "%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.",
+ UNIT(s)->id);
+ return -EINVAL;
+ }
+
+ return 0;
+}
+
+static bool socket_needs_mount(Socket *s, const char *prefix) {
+ SocketPort *p;
+
+ assert(s);
+
+ LIST_FOREACH(port, p, s->ports) {
+
+ if (p->type == SOCKET_SOCKET) {
+ if (socket_address_needs_mount(&p->address, prefix))
+ return true;
+ } else if (p->type == SOCKET_FIFO || p->type == SOCKET_SPECIAL) {
+ if (path_startswith(p->path, prefix))
+ return true;
+ }
+ }
+
+ return false;
+}
+
+int socket_add_one_mount_link(Socket *s, Mount *m) {
+ int r;
+
+ assert(s);
+ assert(m);
+
+ if (UNIT(s)->load_state != UNIT_LOADED ||
+ UNIT(m)->load_state != UNIT_LOADED)
+ return 0;
+
+ if (!socket_needs_mount(s, m->where))
+ return 0;
+
+ r = unit_add_two_dependencies(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, UNIT(m), true);
+ if (r < 0)
+ return r;
+
+ return 0;
+}
+
+static int socket_add_mount_links(Socket *s) {
+ Unit *other;
+ int r;
+
+ assert(s);
+
+ LIST_FOREACH(units_by_type, other, UNIT(s)->manager->units_by_type[UNIT_MOUNT]) {
+ r = socket_add_one_mount_link(s, MOUNT(other));
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static int socket_add_device_link(Socket *s) {
+ char *t;
+ int r;
+
+ assert(s);
+
+ if (!s->bind_to_device || streq(s->bind_to_device, "lo"))
+ return 0;
+
+ if (asprintf(&t, "/sys/subsystem/net/devices/%s", s->bind_to_device) < 0)
+ return -ENOMEM;
+
+ r = unit_add_node_link(UNIT(s), t, false);
+ free(t);
+
+ return r;
+}
+
+static int socket_add_default_dependencies(Socket *s) {
+ int r;
+ assert(s);
+
+ r = unit_add_dependency_by_name(UNIT(s), UNIT_BEFORE, SPECIAL_SOCKETS_TARGET, NULL, true);
+ if (r < 0)
+ return r;
+
+ if (UNIT(s)->manager->running_as == SYSTEMD_SYSTEM) {
+ r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, NULL, true);
+ if (r < 0)
+ return r;
+ }
+
+ return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
+}
+
+_pure_ static bool socket_has_exec(Socket *s) {
+ unsigned i;
+ assert(s);
+
+ for (i = 0; i < _SOCKET_EXEC_COMMAND_MAX; i++)
+ if (s->exec_command[i])
+ return true;
+
+ return false;
+}
+
+static int socket_load(Unit *u) {
+ Socket *s = SOCKET(u);
+ int r;
+
+ assert(u);
+ assert(u->load_state == UNIT_STUB);
+
+ if ((r = unit_load_fragment_and_dropin(u)) < 0)
+ return r;
+
+ /* This is a new unit? Then let's add in some extras */
+ if (u->load_state == UNIT_LOADED) {
+
+ if (have_non_accept_socket(s)) {
+
+ if (!UNIT_DEREF(s->service)) {
+ Unit *x;
+
+ r = unit_load_related_unit(u, ".service", &x);
+ if (r < 0)
+ return r;
+
+ unit_ref_set(&s->service, x);
+ }
+
+ r = unit_add_two_dependencies(u, UNIT_BEFORE, UNIT_TRIGGERS, UNIT_DEREF(s->service), true);
+ if (r < 0)
+ return r;
+ }
+
+ if ((r = socket_add_mount_links(s)) < 0)
+ return r;
+
+ if ((r = socket_add_device_link(s)) < 0)
+ return r;
+
+ if (socket_has_exec(s))
+ if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
+ return r;
+
+ if ((r = unit_add_default_cgroups(u)) < 0)
+ return r;
+
+ if (UNIT(s)->default_dependencies)
+ if ((r = socket_add_default_dependencies(s)) < 0)
+ return r;
+
+ r = unit_exec_context_defaults(u, &s->exec_context);
+ if (r < 0)
+ return r;
+ }
+
+ return socket_verify(s);
+}
+
+_const_ static const char* listen_lookup(int family, int type) {
+
+ if (family == AF_NETLINK)
+ return "ListenNetlink";
+
+ if (type == SOCK_STREAM)
+ return "ListenStream";
+ else if (type == SOCK_DGRAM)
+ return "ListenDatagram";
+ else if (type == SOCK_SEQPACKET)
+ return "ListenSequentialPacket";
+
+ assert_not_reached("Unknown socket type");
+ return NULL;
+}
+
+static void socket_dump(Unit *u, FILE *f, const char *prefix) {
+
+ SocketExecCommand c;
+ Socket *s = SOCKET(u);
+ SocketPort *p;
+ const char *prefix2;
+ char *p2;
+
+ assert(s);
+ assert(f);
+
+ p2 = strappend(prefix, "\t");
+ prefix2 = p2 ? p2 : prefix;
+
+ fprintf(f,
+ "%sSocket State: %s\n"
+ "%sResult: %s\n"
+ "%sBindIPv6Only: %s\n"
+ "%sBacklog: %u\n"
+ "%sSocketMode: %04o\n"
+ "%sDirectoryMode: %04o\n"
+ "%sKeepAlive: %s\n"
+ "%sFreeBind: %s\n"
+ "%sTransparent: %s\n"
+ "%sBroadcast: %s\n"
+ "%sPassCredentials: %s\n"
+ "%sPassSecurity: %s\n"
+ "%sTCPCongestion: %s\n",
+ prefix, socket_state_to_string(s->state),
+ prefix, socket_result_to_string(s->result),
+ prefix, socket_address_bind_ipv6_only_to_string(s->bind_ipv6_only),
+ prefix, s->backlog,
+ prefix, s->socket_mode,
+ prefix, s->directory_mode,
+ prefix, yes_no(s->keep_alive),
+ prefix, yes_no(s->free_bind),
+ prefix, yes_no(s->transparent),
+ prefix, yes_no(s->broadcast),
+ prefix, yes_no(s->pass_cred),
+ prefix, yes_no(s->pass_sec),
+ prefix, strna(s->tcp_congestion));
+
+ if (s->control_pid > 0)
+ fprintf(f,
+ "%sControl PID: %lu\n",
+ prefix, (unsigned long) s->control_pid);
+
+ if (s->bind_to_device)
+ fprintf(f,
+ "%sBindToDevice: %s\n",
+ prefix, s->bind_to_device);
+
+ if (s->accept)
+ fprintf(f,
+ "%sAccepted: %u\n"
+ "%sNConnections: %u\n"
+ "%sMaxConnections: %u\n",
+ prefix, s->n_accepted,
+ prefix, s->n_connections,
+ prefix, s->max_connections);
+
+ if (s->priority >= 0)
+ fprintf(f,
+ "%sPriority: %i\n",
+ prefix, s->priority);
+
+ if (s->receive_buffer > 0)
+ fprintf(f,
+ "%sReceiveBuffer: %zu\n",
+ prefix, s->receive_buffer);
+
+ if (s->send_buffer > 0)
+ fprintf(f,
+ "%sSendBuffer: %zu\n",
+ prefix, s->send_buffer);
+
+ if (s->ip_tos >= 0)
+ fprintf(f,
+ "%sIPTOS: %i\n",
+ prefix, s->ip_tos);
+
+ if (s->ip_ttl >= 0)
+ fprintf(f,
+ "%sIPTTL: %i\n",
+ prefix, s->ip_ttl);
+
+ if (s->pipe_size > 0)
+ fprintf(f,
+ "%sPipeSize: %zu\n",
+ prefix, s->pipe_size);
+
+ if (s->mark >= 0)
+ fprintf(f,
+ "%sMark: %i\n",
+ prefix, s->mark);
+
+ if (s->mq_maxmsg > 0)
+ fprintf(f,
+ "%sMessageQueueMaxMessages: %li\n",
+ prefix, s->mq_maxmsg);
+
+ if (s->mq_msgsize > 0)
+ fprintf(f,
+ "%sMessageQueueMessageSize: %li\n",
+ prefix, s->mq_msgsize);
+
+ if (s->smack)
+ fprintf(f,
+ "%sSmackLabel: %s\n",
+ prefix, s->smack);
+
+ if (s->smack_ip_in)
+ fprintf(f,
+ "%sSmackLabelIPIn: %s\n",
+ prefix, s->smack_ip_in);
+
+ if (s->smack_ip_out)
+ fprintf(f,
+ "%sSmackLabelIPOut: %s\n",
+ prefix, s->smack_ip_out);
+
+ LIST_FOREACH(port, p, s->ports) {
+
+ if (p->type == SOCKET_SOCKET) {
+ const char *t;
+ int r;
+ char *k = NULL;
+
+ if ((r = socket_address_print(&p->address, &k)) < 0)
+ t = strerror(-r);
+ else
+ t = k;
+
+ fprintf(f, "%s%s: %s\n", prefix, listen_lookup(socket_address_family(&p->address), p->address.type), t);
+ free(k);
+ } else if (p->type == SOCKET_SPECIAL)
+ fprintf(f, "%sListenSpecial: %s\n", prefix, p->path);
+ else if (p->type == SOCKET_MQUEUE)
+ fprintf(f, "%sListenMessageQueue: %s\n", prefix, p->path);
+ else
+ fprintf(f, "%sListenFIFO: %s\n", prefix, p->path);
+ }
+
+ exec_context_dump(&s->exec_context, f, prefix);
+ kill_context_dump(&s->kill_context, f, prefix);
+
+ for (c = 0; c < _SOCKET_EXEC_COMMAND_MAX; c++) {
+ if (!s->exec_command[c])
+ continue;
+
+ fprintf(f, "%s-> %s:\n",
+ prefix, socket_exec_command_to_string(c));
+
+ exec_command_dump_list(s->exec_command[c], f, prefix2);
+ }
+
+ free(p2);
+}
+
+static int instance_from_socket(int fd, unsigned nr, char **instance) {
+ socklen_t l;
+ char *r;
+ union {
+ struct sockaddr sa;
+ struct sockaddr_un un;
+ struct sockaddr_in in;
+ struct sockaddr_in6 in6;
+ struct sockaddr_storage storage;
+ } local, remote;
+
+ assert(fd >= 0);
+ assert(instance);
+
+ l = sizeof(local);
+ if (getsockname(fd, &local.sa, &l) < 0)
+ return -errno;
+
+ l = sizeof(remote);
+ if (getpeername(fd, &remote.sa, &l) < 0)
+ return -errno;
+
+ switch (local.sa.sa_family) {
+
+ case AF_INET: {
+ uint32_t
+ a = ntohl(local.in.sin_addr.s_addr),
+ b = ntohl(remote.in.sin_addr.s_addr);
+
+ if (asprintf(&r,
+ "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
+ nr,
+ a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF,
+ ntohs(local.in.sin_port),
+ b >> 24, (b >> 16) & 0xFF, (b >> 8) & 0xFF, b & 0xFF,
+ ntohs(remote.in.sin_port)) < 0)
+ return -ENOMEM;
+
+ break;
+ }
+
+ case AF_INET6: {
+ static const unsigned char ipv4_prefix[] = {
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
+ };
+
+ if (memcmp(&local.in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0 &&
+ memcmp(&remote.in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0) {
+ const uint8_t
+ *a = local.in6.sin6_addr.s6_addr+12,
+ *b = remote.in6.sin6_addr.s6_addr+12;
+
+ if (asprintf(&r,
+ "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
+ nr,
+ a[0], a[1], a[2], a[3],
+ ntohs(local.in6.sin6_port),
+ b[0], b[1], b[2], b[3],
+ ntohs(remote.in6.sin6_port)) < 0)
+ return -ENOMEM;
+ } else {
+ char a[INET6_ADDRSTRLEN], b[INET6_ADDRSTRLEN];
+
+ if (asprintf(&r,
+ "%u-%s:%u-%s:%u",
+ nr,
+ inet_ntop(AF_INET6, &local.in6.sin6_addr, a, sizeof(a)),
+ ntohs(local.in6.sin6_port),
+ inet_ntop(AF_INET6, &remote.in6.sin6_addr, b, sizeof(b)),
+ ntohs(remote.in6.sin6_port)) < 0)
+ return -ENOMEM;
+ }
+
+ break;
+ }
+
+ case AF_UNIX: {
+ struct ucred ucred;
+
+ l = sizeof(ucred);
+ if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &ucred, &l) < 0)
+ return -errno;
+
+ if (asprintf(&r,
+ "%u-%lu-%lu",
+ nr,
+ (unsigned long) ucred.pid,
+ (unsigned long) ucred.uid) < 0)
+ return -ENOMEM;
+
+ break;
+ }
+
+ default:
+ assert_not_reached("Unhandled socket type.");
+ }
+
+ *instance = r;
+ return 0;
+}
+
+static void socket_close_fds(Socket *s) {
+ SocketPort *p;
+
+ assert(s);
+
+ LIST_FOREACH(port, p, s->ports) {
+ if (p->fd < 0)
+ continue;
+
+ unit_unwatch_fd(UNIT(s), &p->fd_watch);
+ close_nointr_nofail(p->fd);
+
+ /* One little note: we should never delete any sockets
+ * in the file system here! After all some other
+ * process we spawned might still have a reference of
+ * this fd and wants to continue to use it. Therefore
+ * we delete sockets in the file system before we
+ * create a new one, not after we stopped using
+ * one! */
+
+ p->fd = -1;
+ }
+}
+
+static void socket_apply_socket_options(Socket *s, int fd) {
+ assert(s);
+ assert(fd >= 0);
+
+ if (s->keep_alive) {
+ int b = s->keep_alive;
+ if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &b, sizeof(b)) < 0)
+ log_warning_unit(UNIT(s)->id, "SO_KEEPALIVE failed: %m");
+ }
+
+ if (s->broadcast) {
+ int one = 1;
+ if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &one, sizeof(one)) < 0)
+ log_warning_unit(UNIT(s)->id, "SO_BROADCAST failed: %m");
+ }
+
+ if (s->pass_cred) {
+ int one = 1;
+ if (setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one)) < 0)
+ log_warning_unit(UNIT(s)->id, "SO_PASSCRED failed: %m");
+ }
+
+ if (s->pass_sec) {
+ int one = 1;
+ if (setsockopt(fd, SOL_SOCKET, SO_PASSSEC, &one, sizeof(one)) < 0)
+ log_warning_unit(UNIT(s)->id, "SO_PASSSEC failed: %m");
+ }
+
+ if (s->priority >= 0)
+ if (setsockopt(fd, SOL_SOCKET, SO_PRIORITY, &s->priority, sizeof(s->priority)) < 0)
+ log_warning_unit(UNIT(s)->id, "SO_PRIORITY failed: %m");
+
+ if (s->receive_buffer > 0) {
+ int value = (int) s->receive_buffer;
+
+ /* We first try with SO_RCVBUFFORCE, in case we have the perms for that */
+
+ if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
+ if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
+ log_warning_unit(UNIT(s)->id, "SO_RCVBUF failed: %m");
+ }
+
+ if (s->send_buffer > 0) {
+ int value = (int) s->send_buffer;
+ if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
+ if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
+ log_warning_unit(UNIT(s)->id, "SO_SNDBUF failed: %m");
+ }
+
+ if (s->mark >= 0)
+ if (setsockopt(fd, SOL_SOCKET, SO_MARK, &s->mark, sizeof(s->mark)) < 0)
+ log_warning_unit(UNIT(s)->id, "SO_MARK failed: %m");
+
+ if (s->ip_tos >= 0)
+ if (setsockopt(fd, IPPROTO_IP, IP_TOS, &s->ip_tos, sizeof(s->ip_tos)) < 0)
+ log_warning_unit(UNIT(s)->id, "IP_TOS failed: %m");
+
+ if (s->ip_ttl >= 0) {
+ int r, x;
+
+ r = setsockopt(fd, IPPROTO_IP, IP_TTL, &s->ip_ttl, sizeof(s->ip_ttl));
+
+ if (socket_ipv6_is_supported())
+ x = setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &s->ip_ttl, sizeof(s->ip_ttl));
+ else {
+ x = -1;
+ errno = EAFNOSUPPORT;
+ }
+
+ if (r < 0 && x < 0)
+ log_warning_unit(UNIT(s)->id,
+ "IP_TTL/IPV6_UNICAST_HOPS failed: %m");
+ }
+
+ if (s->tcp_congestion)
+ if (setsockopt(fd, SOL_TCP, TCP_CONGESTION, s->tcp_congestion, strlen(s->tcp_congestion)+1) < 0)
+ log_warning_unit(UNIT(s)->id, "TCP_CONGESTION failed: %m");
+
+#ifdef HAVE_XATTR
+ if (s->smack_ip_in)
+ if (fsetxattr(fd, "security.SMACK64IPIN", s->smack_ip_in, strlen(s->smack_ip_in), 0) < 0)
+ log_error_unit(UNIT(s)->id,
+ "fsetxattr(\"security.SMACK64IPIN\"): %m");
+
+ if (s->smack_ip_out)
+ if (fsetxattr(fd, "security.SMACK64IPOUT", s->smack_ip_out, strlen(s->smack_ip_out), 0) < 0)
+ log_error_unit(UNIT(s)->id,
+ "fsetxattr(\"security.SMACK64IPOUT\"): %m");
+#endif
+}
+
+static void socket_apply_fifo_options(Socket *s, int fd) {
+ assert(s);
+ assert(fd >= 0);
+
+ if (s->pipe_size > 0)
+ if (fcntl(fd, F_SETPIPE_SZ, s->pipe_size) < 0)
+ log_warning_unit(UNIT(s)->id,
+ "F_SETPIPE_SZ: %m");
+
+#ifdef HAVE_XATTR
+ if (s->smack)
+ if (fsetxattr(fd, "security.SMACK64", s->smack, strlen(s->smack), 0) < 0)
+ log_error_unit(UNIT(s)->id,
+ "fsetxattr(\"security.SMACK64\"): %m");
+#endif
+}
+
+static int fifo_address_create(
+ const char *path,
+ mode_t directory_mode,
+ mode_t socket_mode,
+ int *_fd) {
+
+ int fd = -1, r = 0;
+ struct stat st;
+ mode_t old_mask;
+
+ assert(path);
+ assert(_fd);
+
+ mkdir_parents_label(path, directory_mode);
+
+ r = label_context_set(path, S_IFIFO);
+ if (r < 0)
+ goto fail;
+
+ /* Enforce the right access mode for the fifo */
+ old_mask = umask(~ socket_mode);
+
+ /* Include the original umask in our mask */
+ umask(~socket_mode | old_mask);
+
+ r = mkfifo(path, socket_mode);
+ umask(old_mask);
+
+ if (r < 0 && errno != EEXIST) {
+ r = -errno;
+ goto fail;
+ }
+
+ if ((fd = open(path, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK|O_NOFOLLOW)) < 0) {
+ r = -errno;
+ goto fail;
+ }
+
+ label_context_clear();
+
+ if (fstat(fd, &st) < 0) {
+ r = -errno;
+ goto fail;
+ }
+
+ if (!S_ISFIFO(st.st_mode) ||
+ (st.st_mode & 0777) != (socket_mode & ~old_mask) ||
+ st.st_uid != getuid() ||
+ st.st_gid != getgid()) {
+
+ r = -EEXIST;
+ goto fail;
+ }
+
+ *_fd = fd;
+ return 0;
+
+fail:
+ label_context_clear();
+
+ if (fd >= 0)
+ close_nointr_nofail(fd);
+
+ return r;
+}
+
+static int special_address_create(
+ const char *path,
+ int *_fd) {
+
+ int fd = -1, r = 0;
+ struct stat st;
+
+ assert(path);
+ assert(_fd);
+
+ if ((fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NONBLOCK|O_NOFOLLOW)) < 0) {
+ r = -errno;
+ goto fail;
+ }
+
+ if (fstat(fd, &st) < 0) {
+ r = -errno;
+ goto fail;
+ }
+
+ /* Check whether this is a /proc, /sys or /dev file or char device */
+ if (!S_ISREG(st.st_mode) && !S_ISCHR(st.st_mode)) {
+ r = -EEXIST;
+ goto fail;
+ }
+
+ *_fd = fd;
+ return 0;
+
+fail:
+ if (fd >= 0)
+ close_nointr_nofail(fd);
+
+ return r;
+}
+
+static int mq_address_create(
+ const char *path,
+ mode_t mq_mode,
+ long maxmsg,
+ long msgsize,
+ int *_fd) {
+
+ int fd = -1, r = 0;
+ struct stat st;
+ mode_t old_mask;
+ struct mq_attr _attr, *attr = NULL;
+
+ assert(path);
+ assert(_fd);
+
+ if (maxmsg > 0 && msgsize > 0) {
+ zero(_attr);
+ _attr.mq_flags = O_NONBLOCK;
+ _attr.mq_maxmsg = maxmsg;
+ _attr.mq_msgsize = msgsize;
+ attr = &_attr;
+ }
+
+ /* Enforce the right access mode for the mq */
+ old_mask = umask(~ mq_mode);
+
+ /* Include the original umask in our mask */
+ umask(~mq_mode | old_mask);
+
+ fd = mq_open(path, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_CREAT, mq_mode, attr);
+ umask(old_mask);
+
+ if (fd < 0) {
+ r = -errno;
+ goto fail;
+ }
+
+ if (fstat(fd, &st) < 0) {
+ r = -errno;
+ goto fail;
+ }
+
+ if ((st.st_mode & 0777) != (mq_mode & ~old_mask) ||
+ st.st_uid != getuid() ||
+ st.st_gid != getgid()) {
+
+ r = -EEXIST;
+ goto fail;
+ }
+
+ *_fd = fd;
+ return 0;
+
+fail:
+ if (fd >= 0)
+ close_nointr_nofail(fd);
+
+ return r;
+}
+
+static int socket_open_fds(Socket *s) {
+ SocketPort *p;
+ int r;
+ char *label = NULL;
+ bool know_label = false;
+
+ assert(s);
+
+ LIST_FOREACH(port, p, s->ports) {
+
+ if (p->fd >= 0)
+ continue;
+
+ if (p->type == SOCKET_SOCKET) {
+
+ if (!know_label) {
+
+ if ((r = socket_instantiate_service(s)) < 0)
+ return r;
+
+ if (UNIT_DEREF(s->service) &&
+ SERVICE(UNIT_DEREF(s->service))->exec_command[SERVICE_EXEC_START]) {
+ r = label_get_create_label_from_exe(SERVICE(UNIT_DEREF(s->service))->exec_command[SERVICE_EXEC_START]->path, &label);
+
+ if (r < 0) {
+ if (r != -EPERM)
+ return r;
+ }
+ }
+
+ know_label = true;
+ }
+
+ if ((r = socket_address_listen(
+ &p->address,
+ s->backlog,
+ s->bind_ipv6_only,
+ s->bind_to_device,
+ s->free_bind,
+ s->transparent,
+ s->directory_mode,
+ s->socket_mode,
+ label,
+ &p->fd)) < 0)
+ goto rollback;
+
+ socket_apply_socket_options(s, p->fd);
+
+ } else if (p->type == SOCKET_SPECIAL) {
+
+ if ((r = special_address_create(
+ p->path,
+ &p->fd)) < 0)
+ goto rollback;
+
+ } else if (p->type == SOCKET_FIFO) {
+
+ if ((r = fifo_address_create(
+ p->path,
+ s->directory_mode,
+ s->socket_mode,
+ &p->fd)) < 0)
+ goto rollback;
+
+ socket_apply_fifo_options(s, p->fd);
+ } else if (p->type == SOCKET_MQUEUE) {
+
+ if ((r = mq_address_create(
+ p->path,
+ s->socket_mode,
+ s->mq_maxmsg,
+ s->mq_msgsize,
+ &p->fd)) < 0)
+ goto rollback;
+ } else
+ assert_not_reached("Unknown port type");
+ }
+
+ label_free(label);
+ return 0;
+
+rollback:
+ socket_close_fds(s);
+ label_free(label);
+ return r;
+}
+
+static void socket_unwatch_fds(Socket *s) {
+ SocketPort *p;
+
+ assert(s);
+
+ LIST_FOREACH(port, p, s->ports) {
+ if (p->fd < 0)
+ continue;
+
+ unit_unwatch_fd(UNIT(s), &p->fd_watch);
+ }
+}
+
+static int socket_watch_fds(Socket *s) {
+ SocketPort *p;
+ int r;
+
+ assert(s);
+
+ LIST_FOREACH(port, p, s->ports) {
+ if (p->fd < 0)
+ continue;
+
+ p->fd_watch.socket_accept =
+ s->accept &&
+ p->type == SOCKET_SOCKET &&
+ socket_address_can_accept(&p->address);
+
+ if ((r = unit_watch_fd(UNIT(s), p->fd, EPOLLIN, &p->fd_watch)) < 0)
+ goto fail;
+ }
+
+ return 0;
+
+fail:
+ socket_unwatch_fds(s);
+ return r;
+}
+
+static void socket_set_state(Socket *s, SocketState state) {
+ SocketState old_state;
+ assert(s);
+
+ old_state = s->state;
+ s->state = state;
+
+ if (state != SOCKET_START_PRE &&
+ state != SOCKET_START_POST &&
+ state != SOCKET_STOP_PRE &&
+ state != SOCKET_STOP_PRE_SIGTERM &&
+ state != SOCKET_STOP_PRE_SIGKILL &&
+ state != SOCKET_STOP_POST &&
+ state != SOCKET_FINAL_SIGTERM &&
+ state != SOCKET_FINAL_SIGKILL) {
+ unit_unwatch_timer(UNIT(s), &s->timer_watch);
+ socket_unwatch_control_pid(s);
+ s->control_command = NULL;
+ s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
+ }
+
+ if (state != SOCKET_LISTENING)
+ socket_unwatch_fds(s);
+
+ if (state != SOCKET_START_POST &&
+ state != SOCKET_LISTENING &&
+ state != SOCKET_RUNNING &&
+ state != SOCKET_STOP_PRE &&
+ state != SOCKET_STOP_PRE_SIGTERM &&
+ state != SOCKET_STOP_PRE_SIGKILL)
+ socket_close_fds(s);
+
+ if (state != old_state)
+ log_debug_unit(UNIT(s)->id,
+ "%s changed %s -> %s", UNIT(s)->id,
+ socket_state_to_string(old_state),
+ socket_state_to_string(state));
+
+ unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], true);
+}
+
+static int socket_coldplug(Unit *u) {
+ Socket *s = SOCKET(u);
+ int r;
+
+ assert(s);
+ assert(s->state == SOCKET_DEAD);
+
+ if (s->deserialized_state != s->state) {
+
+ if (s->deserialized_state == SOCKET_START_PRE ||
+ s->deserialized_state == SOCKET_START_POST ||
+ s->deserialized_state == SOCKET_STOP_PRE ||
+ s->deserialized_state == SOCKET_STOP_PRE_SIGTERM ||
+ s->deserialized_state == SOCKET_STOP_PRE_SIGKILL ||
+ s->deserialized_state == SOCKET_STOP_POST ||
+ s->deserialized_state == SOCKET_FINAL_SIGTERM ||
+ s->deserialized_state == SOCKET_FINAL_SIGKILL) {
+
+ if (s->control_pid <= 0)
+ return -EBADMSG;
+
+ r = unit_watch_pid(UNIT(s), s->control_pid);
+ if (r < 0)
+ return r;
+
+ r = unit_watch_timer(UNIT(s), CLOCK_MONOTONIC, true, s->timeout_usec, &s->timer_watch);
+ if (r < 0)
+ return r;
+ }
+
+ if (s->deserialized_state == SOCKET_START_POST ||
+ s->deserialized_state == SOCKET_LISTENING ||
+ s->deserialized_state == SOCKET_RUNNING ||
+ s->deserialized_state == SOCKET_STOP_PRE ||
+ s->deserialized_state == SOCKET_STOP_PRE_SIGTERM ||
+ s->deserialized_state == SOCKET_STOP_PRE_SIGKILL)
+ if ((r = socket_open_fds(s)) < 0)
+ return r;
+
+ if (s->deserialized_state == SOCKET_LISTENING)
+ if ((r = socket_watch_fds(s)) < 0)
+ return r;
+
+ socket_set_state(s, s->deserialized_state);
+ }
+
+ return 0;
+}
+
+static int socket_spawn(Socket *s, ExecCommand *c, pid_t *_pid) {
+ pid_t pid;
+ int r;
+ char **argv;
+
+ assert(s);
+ assert(c);
+ assert(_pid);
+
+ r = unit_watch_timer(UNIT(s), CLOCK_MONOTONIC, true, s->timeout_usec, &s->timer_watch);
+ if (r < 0)
+ goto fail;
+
+ argv = unit_full_printf_strv(UNIT(s), c->argv);
+ if (!argv) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ r = exec_spawn(c,
+ argv,
+ &s->exec_context,
+ NULL, 0,
+ UNIT(s)->manager->environment,
+ true,
+ true,
+ true,
+ UNIT(s)->manager->confirm_spawn,
+ UNIT(s)->cgroup_bondings,
+ UNIT(s)->cgroup_attributes,
+ NULL,
+ UNIT(s)->id,
+ NULL,
+ &pid);
+
+ strv_free(argv);
+ if (r < 0)
+ goto fail;
+
+ if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
+ /* FIXME: we need to do something here */
+ goto fail;
+
+ *_pid = pid;
+
+ return 0;
+
+fail:
+ unit_unwatch_timer(UNIT(s), &s->timer_watch);
+
+ return r;
+}
+
+static void socket_enter_dead(Socket *s, SocketResult f) {
+ assert(s);
+
+ if (f != SOCKET_SUCCESS)
+ s->result = f;
+
+ exec_context_tmp_dirs_done(&s->exec_context);
+ socket_set_state(s, s->result != SOCKET_SUCCESS ? SOCKET_FAILED : SOCKET_DEAD);
+}
+
+static void socket_enter_signal(Socket *s, SocketState state, SocketResult f);
+
+static void socket_enter_stop_post(Socket *s, SocketResult f) {
+ int r;
+ assert(s);
+
+ if (f != SOCKET_SUCCESS)
+ s->result = f;
+
+ socket_unwatch_control_pid(s);
+
+ s->control_command_id = SOCKET_EXEC_STOP_POST;
+
+ if ((s->control_command = s->exec_command[SOCKET_EXEC_STOP_POST])) {
+ if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
+ goto fail;
+
+ socket_set_state(s, SOCKET_STOP_POST);
+ } else
+ socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_SUCCESS);
+
+ return;
+
+fail:
+ log_warning_unit(UNIT(s)->id,
+ "%s failed to run 'stop-post' task: %s",
+ UNIT(s)->id, strerror(-r));
+ socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_RESOURCES);
+}
+
+static void socket_enter_signal(Socket *s, SocketState state, SocketResult f) {
+ int r;
+
+ assert(s);
+
+ if (f != SOCKET_SUCCESS)
+ s->result = f;
+
+ r = unit_kill_context(
+ UNIT(s),
+ &s->kill_context,
+ state != SOCKET_STOP_PRE_SIGTERM && state != SOCKET_FINAL_SIGTERM,
+ -1,
+ s->control_pid,
+ false);
+ if (r < 0)
+ goto fail;
+
+ if (r > 0) {
+ r = unit_watch_timer(UNIT(s), CLOCK_MONOTONIC, true, s->timeout_usec, &s->timer_watch);
+ if (r < 0)
+ goto fail;
+
+ socket_set_state(s, state);
+ } else if (state == SOCKET_STOP_PRE_SIGTERM || state == SOCKET_STOP_PRE_SIGKILL)
+ socket_enter_stop_post(s, SOCKET_SUCCESS);
+ else
+ socket_enter_dead(s, SOCKET_SUCCESS);
+
+ return;
+
+fail:
+ log_warning_unit(UNIT(s)->id,
+ "%s failed to kill processes: %s",
+ UNIT(s)->id, strerror(-r));
+
+ if (state == SOCKET_STOP_PRE_SIGTERM || state == SOCKET_STOP_PRE_SIGKILL)
+ socket_enter_stop_post(s, SOCKET_FAILURE_RESOURCES);
+ else
+ socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
+}
+
+static void socket_enter_stop_pre(Socket *s, SocketResult f) {
+ int r;
+ assert(s);
+
+ if (f != SOCKET_SUCCESS)
+ s->result = f;
+
+ socket_unwatch_control_pid(s);
+
+ s->control_command_id = SOCKET_EXEC_STOP_PRE;
+
+ if ((s->control_command = s->exec_command[SOCKET_EXEC_STOP_PRE])) {
+ if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
+ goto fail;
+
+ socket_set_state(s, SOCKET_STOP_PRE);
+ } else
+ socket_enter_stop_post(s, SOCKET_SUCCESS);
+
+ return;
+
+fail:
+ log_warning_unit(UNIT(s)->id,
+ "%s failed to run 'stop-pre' task: %s",
+ UNIT(s)->id, strerror(-r));
+ socket_enter_stop_post(s, SOCKET_FAILURE_RESOURCES);
+}
+
+static void socket_enter_listening(Socket *s) {
+ int r;
+ assert(s);
+
+ r = socket_watch_fds(s);
+ if (r < 0) {
+ log_warning_unit(UNIT(s)->id,
+ "%s failed to watch sockets: %s",
+ UNIT(s)->id, strerror(-r));
+ goto fail;
+ }
+
+ socket_set_state(s, SOCKET_LISTENING);
+ return;
+
+fail:
+ socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
+}
+
+static void socket_enter_start_post(Socket *s) {
+ int r;
+ assert(s);
+
+ r = socket_open_fds(s);
+ if (r < 0) {
+ log_warning_unit(UNIT(s)->id,
+ "%s failed to listen on sockets: %s",
+ UNIT(s)->id, strerror(-r));
+ goto fail;
+ }
+
+ socket_unwatch_control_pid(s);
+
+ s->control_command_id = SOCKET_EXEC_START_POST;
+
+ if ((s->control_command = s->exec_command[SOCKET_EXEC_START_POST])) {
+ r = socket_spawn(s, s->control_command, &s->control_pid);
+ if (r < 0) {
+ log_warning_unit(UNIT(s)->id,
+ "%s failed to run 'start-post' task: %s",
+ UNIT(s)->id, strerror(-r));
+ goto fail;
+ }
+
+ socket_set_state(s, SOCKET_START_POST);
+ } else
+ socket_enter_listening(s);
+
+ return;
+
+fail:
+ socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
+}
+
+static void socket_enter_start_pre(Socket *s) {
+ int r;
+ assert(s);
+
+ socket_unwatch_control_pid(s);
+
+ s->control_command_id = SOCKET_EXEC_START_PRE;
+
+ if ((s->control_command = s->exec_command[SOCKET_EXEC_START_PRE])) {
+ if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
+ goto fail;
+
+ socket_set_state(s, SOCKET_START_PRE);
+ } else
+ socket_enter_start_post(s);
+
+ return;
+
+fail:
+ log_warning_unit(UNIT(s)->id,
+ "%s failed to run 'start-pre' task: %s",
+ UNIT(s)->id, strerror(-r));
+ socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
+}
+
+static void socket_enter_running(Socket *s, int cfd) {
+ int r;
+ DBusError error;
+
+ assert(s);
+ dbus_error_init(&error);
+
+ /* We don't take connections anymore if we are supposed to
+ * shut down anyway */
+ if (unit_stop_pending(UNIT(s))) {
+ log_debug_unit(UNIT(s)->id,
+ "Suppressing connection request on %s since unit stop is scheduled.",
+ UNIT(s)->id);
+
+ if (cfd >= 0)
+ close_nointr_nofail(cfd);
+ else {
+ /* Flush all sockets by closing and reopening them */
+ socket_close_fds(s);
+
+ r = socket_watch_fds(s);
+ if (r < 0) {
+ log_warning_unit(UNIT(s)->id,
+ "%s failed to watch sockets: %s",
+ UNIT(s)->id, strerror(-r));
+ socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
+ }
+ }
+
+ return;
+ }
+
+ if (cfd < 0) {
+ Iterator i;
+ Unit *u;
+ bool pending = false;
+
+ /* If there's already a start pending don't bother to
+ * do anything */
+ SET_FOREACH(u, UNIT(s)->dependencies[UNIT_TRIGGERS], i)
+ if (unit_active_or_pending(u)) {
+ pending = true;
+ break;
+ }
+
+ if (!pending) {
+ r = manager_add_job(UNIT(s)->manager, JOB_START, UNIT_DEREF(s->service), JOB_REPLACE, true, &error, NULL);
+ if (r < 0)
+ goto fail;
+ }
+
+ socket_set_state(s, SOCKET_RUNNING);
+ } else {
+ char *prefix, *instance = NULL, *name;
+ Service *service;
+
+ if (s->n_connections >= s->max_connections) {
+ log_warning_unit(UNIT(s)->id,
+ "%s: Too many incoming connections (%u)",
+ UNIT(s)->id, s->n_connections);
+ close_nointr_nofail(cfd);
+ return;
+ }
+
+ r = socket_instantiate_service(s);
+ if (r < 0)
+ goto fail;
+
+ r = instance_from_socket(cfd, s->n_accepted, &instance);
+ if (r < 0) {
+ if (r != -ENOTCONN)
+ goto fail;
+
+ /* ENOTCONN is legitimate if TCP RST was received.
+ * This connection is over, but the socket unit lives on. */
+ close_nointr_nofail(cfd);
+ return;
+ }
+
+ prefix = unit_name_to_prefix(UNIT(s)->id);
+ if (!prefix) {
+ free(instance);
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ name = unit_name_build(prefix, instance, ".service");
+ free(prefix);
+ free(instance);
+
+ if (!name) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ r = unit_add_name(UNIT_DEREF(s->service), name);
+ if (r < 0) {
+ free(name);
+ goto fail;
+ }
+
+ service = SERVICE(UNIT_DEREF(s->service));
+ unit_ref_unset(&s->service);
+ s->n_accepted ++;
+
+ UNIT(service)->no_gc = false;
+
+ unit_choose_id(UNIT(service), name);
+ free(name);
+
+ r = service_set_socket_fd(service, cfd, s);
+ if (r < 0)
+ goto fail;
+
+ cfd = -1;
+ s->n_connections ++;
+
+ r = manager_add_job(UNIT(s)->manager, JOB_START, UNIT(service), JOB_REPLACE, true, &error, NULL);
+ if (r < 0)
+ goto fail;
+
+ /* Notify clients about changed counters */
+ unit_add_to_dbus_queue(UNIT(s));
+ }
+
+ return;
+
+fail:
+ log_warning_unit(UNIT(s)->id,
+ "%s failed to queue service startup job (Maybe the service file is missing or not a %s unit?): %s",
+ UNIT(s)->id,
+ cfd >= 0 ? "template" : "non-template",
+ bus_error(&error, r));
+ socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
+
+ if (cfd >= 0)
+ close_nointr_nofail(cfd);
+
+ dbus_error_free(&error);
+}
+
+static void socket_run_next(Socket *s) {
+ int r;
+
+ assert(s);
+ assert(s->control_command);
+ assert(s->control_command->command_next);
+
+ socket_unwatch_control_pid(s);
+
+ s->control_command = s->control_command->command_next;
+
+ if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
+ goto fail;
+
+ return;
+
+fail:
+ log_warning_unit(UNIT(s)->id,
+ "%s failed to run next task: %s",
+ UNIT(s)->id, strerror(-r));
+
+ if (s->state == SOCKET_START_POST)
+ socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
+ else if (s->state == SOCKET_STOP_POST)
+ socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
+ else
+ socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_RESOURCES);
+}
+
+static int socket_start(Unit *u) {
+ Socket *s = SOCKET(u);
+
+ assert(s);
+
+ /* We cannot fulfill this request right now, try again later
+ * please! */
+ if (s->state == SOCKET_STOP_PRE ||
+ s->state == SOCKET_STOP_PRE_SIGKILL ||
+ s->state == SOCKET_STOP_PRE_SIGTERM ||
+ s->state == SOCKET_STOP_POST ||
+ s->state == SOCKET_FINAL_SIGTERM ||
+ s->state == SOCKET_FINAL_SIGKILL)
+ return -EAGAIN;
+
+ if (s->state == SOCKET_START_PRE ||
+ s->state == SOCKET_START_POST)
+ return 0;
+
+ /* Cannot run this without the service being around */
+ if (UNIT_DEREF(s->service)) {
+ Service *service;
+
+ service = SERVICE(UNIT_DEREF(s->service));
+
+ if (UNIT(service)->load_state != UNIT_LOADED) {
+ log_error_unit(u->id,
+ "Socket service %s not loaded, refusing.",
+ UNIT(service)->id);
+ return -ENOENT;
+ }
+
+ /* If the service is already active we cannot start the
+ * socket */
+ if (service->state != SERVICE_DEAD &&
+ service->state != SERVICE_FAILED &&
+ service->state != SERVICE_AUTO_RESTART) {
+ log_error_unit(u->id,
+ "Socket service %s already active, refusing.",
+ UNIT(service)->id);
+ return -EBUSY;
+ }
+
+#ifdef HAVE_SYSV_COMPAT
+ if (service->is_sysv) {
+ log_error_unit(u->id,
+ "Using SysV services for socket activation is not supported. Refusing.");
+ return -ENOENT;
+ }
+#endif
+ }
+
+ assert(s->state == SOCKET_DEAD || s->state == SOCKET_FAILED);
+
+ s->result = SOCKET_SUCCESS;
+ socket_enter_start_pre(s);
+ return 0;
+}
+
+static int socket_stop(Unit *u) {
+ Socket *s = SOCKET(u);
+
+ assert(s);
+
+ /* Already on it */
+ if (s->state == SOCKET_STOP_PRE ||
+ s->state == SOCKET_STOP_PRE_SIGTERM ||
+ s->state == SOCKET_STOP_PRE_SIGKILL ||
+ s->state == SOCKET_STOP_POST ||
+ s->state == SOCKET_FINAL_SIGTERM ||
+ s->state == SOCKET_FINAL_SIGKILL)
+ return 0;
+
+ /* If there's already something running we go directly into
+ * kill mode. */
+ if (s->state == SOCKET_START_PRE ||
+ s->state == SOCKET_START_POST) {
+ socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, SOCKET_SUCCESS);
+ return -EAGAIN;
+ }
+
+ assert(s->state == SOCKET_LISTENING || s->state == SOCKET_RUNNING);
+
+ socket_enter_stop_pre(s, SOCKET_SUCCESS);
+ return 0;
+}
+
+static int socket_serialize(Unit *u, FILE *f, FDSet *fds) {
+ Socket *s = SOCKET(u);
+ SocketPort *p;
+ int r;
+
+ assert(u);
+ assert(f);
+ assert(fds);
+
+ unit_serialize_item(u, f, "state", socket_state_to_string(s->state));
+ unit_serialize_item(u, f, "result", socket_result_to_string(s->result));
+ unit_serialize_item_format(u, f, "n-accepted", "%u", s->n_accepted);
+
+ if (s->control_pid > 0)
+ unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
+
+ if (s->control_command_id >= 0)
+ unit_serialize_item(u, f, "control-command", socket_exec_command_to_string(s->control_command_id));
+
+ LIST_FOREACH(port, p, s->ports) {
+ int copy;
+
+ if (p->fd < 0)
+ continue;
+
+ if ((copy = fdset_put_dup(fds, p->fd)) < 0)
+ return copy;
+
+ if (p->type == SOCKET_SOCKET) {
+ char *t;
+
+ r = socket_address_print(&p->address, &t);
+ if (r < 0)
+ return r;
+
+ if (socket_address_family(&p->address) == AF_NETLINK)
+ unit_serialize_item_format(u, f, "netlink", "%i %s", copy, t);
+ else
+ unit_serialize_item_format(u, f, "socket", "%i %i %s", copy, p->address.type, t);
+ free(t);
+ } else if (p->type == SOCKET_SPECIAL)
+ unit_serialize_item_format(u, f, "special", "%i %s", copy, p->path);
+ else if (p->type == SOCKET_MQUEUE)
+ unit_serialize_item_format(u, f, "mqueue", "%i %s", copy, p->path);
+ else {
+ assert(p->type == SOCKET_FIFO);
+ unit_serialize_item_format(u, f, "fifo", "%i %s", copy, p->path);
+ }
+ }
+
+ exec_context_serialize(&s->exec_context, UNIT(s), f);
+
+ return 0;
+}
+
+static int socket_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
+ Socket *s = SOCKET(u);
+
+ assert(u);
+ assert(key);
+ assert(value);
+ assert(fds);
+
+ if (streq(key, "state")) {
+ SocketState state;
+
+ state = socket_state_from_string(value);
+ if (state < 0)
+ log_debug_unit(u->id,
+ "Failed to parse state value %s", value);
+ else
+ s->deserialized_state = state;
+ } else if (streq(key, "result")) {
+ SocketResult f;
+
+ f = socket_result_from_string(value);
+ if (f < 0)
+ log_debug_unit(u->id,
+ "Failed to parse result value %s", value);
+ else if (f != SOCKET_SUCCESS)
+ s->result = f;
+
+ } else if (streq(key, "n-accepted")) {
+ unsigned k;
+
+ if (safe_atou(value, &k) < 0)
+ log_debug_unit(u->id,
+ "Failed to parse n-accepted value %s", value);
+ else
+ s->n_accepted += k;
+ } else if (streq(key, "control-pid")) {
+ pid_t pid;
+
+ if (parse_pid(value, &pid) < 0)
+ log_debug_unit(u->id,
+ "Failed to parse control-pid value %s", value);
+ else
+ s->control_pid = pid;
+ } else if (streq(key, "control-command")) {
+ SocketExecCommand id;
+
+ id = socket_exec_command_from_string(value);
+ if (id < 0)
+ log_debug_unit(u->id,
+ "Failed to parse exec-command value %s", value);
+ else {
+ s->control_command_id = id;
+ s->control_command = s->exec_command[id];
+ }
+ } else if (streq(key, "fifo")) {
+ int fd, skip = 0;
+ SocketPort *p;
+
+ if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
+ log_debug_unit(u->id,
+ "Failed to parse fifo value %s", value);
+ else {
+
+ LIST_FOREACH(port, p, s->ports)
+ if (p->type == SOCKET_FIFO &&
+ streq_ptr(p->path, value+skip))
+ break;
+
+ if (p) {
+ if (p->fd >= 0)
+ close_nointr_nofail(p->fd);
+ p->fd = fdset_remove(fds, fd);
+ }
+ }
+
+ } else if (streq(key, "special")) {
+ int fd, skip = 0;
+ SocketPort *p;
+
+ if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
+ log_debug_unit(u->id,
+ "Failed to parse special value %s", value);
+ else {
+
+ LIST_FOREACH(port, p, s->ports)
+ if (p->type == SOCKET_SPECIAL &&
+ streq_ptr(p->path, value+skip))
+ break;
+
+ if (p) {
+ if (p->fd >= 0)
+ close_nointr_nofail(p->fd);
+ p->fd = fdset_remove(fds, fd);
+ }
+ }
+
+ } else if (streq(key, "mqueue")) {
+ int fd, skip = 0;
+ SocketPort *p;
+
+ if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
+ log_debug_unit(u->id,
+ "Failed to parse mqueue value %s", value);
+ else {
+
+ LIST_FOREACH(port, p, s->ports)
+ if (p->type == SOCKET_MQUEUE &&
+ streq_ptr(p->path, value+skip))
+ break;
+
+ if (p) {
+ if (p->fd >= 0)
+ close_nointr_nofail(p->fd);
+ p->fd = fdset_remove(fds, fd);
+ }
+ }
+
+ } else if (streq(key, "socket")) {
+ int fd, type, skip = 0;
+ SocketPort *p;
+
+ if (sscanf(value, "%i %i %n", &fd, &type, &skip) < 2 || fd < 0 || type < 0 || !fdset_contains(fds, fd))
+ log_debug_unit(u->id,
+ "Failed to parse socket value %s", value);
+ else {
+
+ LIST_FOREACH(port, p, s->ports)
+ if (socket_address_is(&p->address, value+skip, type))
+ break;
+
+ if (p) {
+ if (p->fd >= 0)
+ close_nointr_nofail(p->fd);
+ p->fd = fdset_remove(fds, fd);
+ }
+ }
+
+ } else if (streq(key, "netlink")) {
+ int fd, skip = 0;
+ SocketPort *p;
+
+ if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
+ log_debug_unit(u->id,
+ "Failed to parse socket value %s", value);
+ else {
+
+ LIST_FOREACH(port, p, s->ports)
+ if (socket_address_is_netlink(&p->address, value+skip))
+ break;
+
+ if (p) {
+ if (p->fd >= 0)
+ close_nointr_nofail(p->fd);
+ p->fd = fdset_remove(fds, fd);
+ }
+ }
+ } else if (streq(key, "tmp-dir")) {
+ char *t;
+
+ t = strdup(value);
+ if (!t)
+ return log_oom();
+
+ s->exec_context.tmp_dir = t;
+ } else if (streq(key, "var-tmp-dir")) {
+ char *t;
+
+ t = strdup(value);
+ if (!t)
+ return log_oom();
+
+ s->exec_context.var_tmp_dir = t;
+ } else
+ log_debug_unit(UNIT(s)->id,
+ "Unknown serialization key '%s'", key);
+
+ return 0;
+}
+
+static int socket_distribute_fds(Unit *u, FDSet *fds) {
+ Socket *s = SOCKET(u);
+ SocketPort *p;
+
+ assert(u);
+
+ LIST_FOREACH(port, p, s->ports) {
+ Iterator i;
+ int fd;
+
+ if (p->type != SOCKET_SOCKET)
+ continue;
+
+ if (p->fd >= 0)
+ continue;
+
+ FDSET_FOREACH(fd, fds, i) {
+ if (socket_address_matches_fd(&p->address, fd)) {
+ p->fd = fdset_remove(fds, fd);
+ s->deserialized_state = SOCKET_LISTENING;
+ break;
+ }
+ }
+ }
+
+ return 0;
+}
+
+_pure_ static UnitActiveState socket_active_state(Unit *u) {
+ assert(u);
+
+ return state_translation_table[SOCKET(u)->state];
+}
+
+_pure_ static const char *socket_sub_state_to_string(Unit *u) {
+ assert(u);
+
+ return socket_state_to_string(SOCKET(u)->state);
+}
+
+const char* socket_port_type_to_string(SocketPort *p) {
+
+ assert(p);
+
+ switch (p->type) {
+ case SOCKET_SOCKET:
+ switch (p->address.type) {
+ case SOCK_STREAM: return "Stream";
+ case SOCK_DGRAM: return "Datagram";
+ case SOCK_SEQPACKET: return "SequentialPacket";
+ case SOCK_RAW:
+ if (socket_address_family(&p->address) == AF_NETLINK)
+ return "Netlink";
+ default: return "Invalid";
+ }
+ case SOCKET_SPECIAL: return "Special";
+ case SOCKET_MQUEUE: return "MessageQueue";
+ case SOCKET_FIFO: return "FIFO";
+ default: return NULL;
+ }
+}
+
+_pure_ static bool socket_check_gc(Unit *u) {
+ Socket *s = SOCKET(u);
+
+ assert(u);
+
+ return s->n_connections > 0;
+}
+
+static void socket_fd_event(Unit *u, int fd, uint32_t events, Watch *w) {
+ Socket *s = SOCKET(u);
+ int cfd = -1;
+
+ assert(s);
+ assert(fd >= 0);
+
+ if (s->state != SOCKET_LISTENING)
+ return;
+
+ log_debug_unit(u->id, "Incoming traffic on %s", u->id);
+
+ if (events != EPOLLIN) {
+
+ if (events & EPOLLHUP)
+ log_error_unit(u->id,
+ "%s: Got POLLHUP on a listening socket. The service probably invoked shutdown() on it, and should better not do that.",
+ u->id);
+ else
+ log_error_unit(u->id,
+ "%s: Got unexpected poll event (0x%x) on socket.",
+ u->id, events);
+
+ goto fail;
+ }
+
+ if (w->socket_accept) {
+ for (;;) {
+
+ cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK);
+ if (cfd < 0) {
+
+ if (errno == EINTR)
+ continue;
+
+ log_error_unit(u->id,
+ "Failed to accept socket: %m");
+ goto fail;
+ }
+
+ break;
+ }
+
+ socket_apply_socket_options(s, cfd);
+ }
+
+ socket_enter_running(s, cfd);
+ return;
+
+fail:
+ socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
+}
+
+static void socket_sigchld_event(Unit *u, pid_t pid, int code, int status) {
+ Socket *s = SOCKET(u);
+ SocketResult f;
+
+ assert(s);
+ assert(pid >= 0);
+
+ if (pid != s->control_pid)
+ return;
+
+ s->control_pid = 0;
+
+ if (is_clean_exit(code, status, NULL))
+ f = SOCKET_SUCCESS;
+ else if (code == CLD_EXITED)
+ f = SOCKET_FAILURE_EXIT_CODE;
+ else if (code == CLD_KILLED)
+ f = SOCKET_FAILURE_SIGNAL;
+ else if (code == CLD_DUMPED)
+ f = SOCKET_FAILURE_CORE_DUMP;
+ else
+ assert_not_reached("Unknown code");
+
+ if (s->control_command) {
+ exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
+
+ if (s->control_command->ignore)
+ f = SOCKET_SUCCESS;
+ }
+
+ log_full_unit(f == SOCKET_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
+ u->id,
+ "%s control process exited, code=%s status=%i",
+ u->id, sigchld_code_to_string(code), status);
+
+ if (f != SOCKET_SUCCESS)
+ s->result = f;
+
+ if (s->control_command &&
+ s->control_command->command_next &&
+ f == SOCKET_SUCCESS) {
+
+ log_debug_unit(u->id,
+ "%s running next command for state %s",
+ u->id, socket_state_to_string(s->state));
+ socket_run_next(s);
+ } else {
+ s->control_command = NULL;
+ s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
+
+ /* No further commands for this step, so let's figure
+ * out what to do next */
+
+ log_debug_unit(u->id,
+ "%s got final SIGCHLD for state %s",
+ u->id, socket_state_to_string(s->state));
+
+ switch (s->state) {
+
+ case SOCKET_START_PRE:
+ if (f == SOCKET_SUCCESS)
+ socket_enter_start_post(s);
+ else
+ socket_enter_signal(s, SOCKET_FINAL_SIGTERM, f);
+ break;
+
+ case SOCKET_START_POST:
+ if (f == SOCKET_SUCCESS)
+ socket_enter_listening(s);
+ else
+ socket_enter_stop_pre(s, f);
+ break;
+
+ case SOCKET_STOP_PRE:
+ case SOCKET_STOP_PRE_SIGTERM:
+ case SOCKET_STOP_PRE_SIGKILL:
+ socket_enter_stop_post(s, f);
+ break;
+
+ case SOCKET_STOP_POST:
+ case SOCKET_FINAL_SIGTERM:
+ case SOCKET_FINAL_SIGKILL:
+ socket_enter_dead(s, f);
+ break;
+
+ default:
+ assert_not_reached("Uh, control process died at wrong time.");
+ }
+ }
+
+ /* Notify clients about changed exit status */
+ unit_add_to_dbus_queue(u);
+}
+
+static void socket_timer_event(Unit *u, uint64_t elapsed, Watch *w) {
+ Socket *s = SOCKET(u);
+
+ assert(s);
+ assert(elapsed == 1);
+ assert(w == &s->timer_watch);
+
+ switch (s->state) {
+
+ case SOCKET_START_PRE:
+ log_warning_unit(u->id,
+ "%s starting timed out. Terminating.", u->id);
+ socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_TIMEOUT);
+ break;
+
+ case SOCKET_START_POST:
+ log_warning_unit(u->id,
+ "%s starting timed out. Stopping.", u->id);
+ socket_enter_stop_pre(s, SOCKET_FAILURE_TIMEOUT);
+ break;
+
+ case SOCKET_STOP_PRE:
+ log_warning_unit(u->id,
+ "%s stopping timed out. Terminating.", u->id);
+ socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, SOCKET_FAILURE_TIMEOUT);
+ break;
+
+ case SOCKET_STOP_PRE_SIGTERM:
+ if (s->kill_context.send_sigkill) {
+ log_warning_unit(u->id,
+ "%s stopping timed out. Killing.", u->id);
+ socket_enter_signal(s, SOCKET_STOP_PRE_SIGKILL, SOCKET_FAILURE_TIMEOUT);
+ } else {
+ log_warning_unit(u->id,
+ "%s stopping timed out. Skipping SIGKILL. Ignoring.",
+ u->id);
+ socket_enter_stop_post(s, SOCKET_FAILURE_TIMEOUT);
+ }
+ break;
+
+ case SOCKET_STOP_PRE_SIGKILL:
+ log_warning_unit(u->id,
+ "%s still around after SIGKILL. Ignoring.", u->id);
+ socket_enter_stop_post(s, SOCKET_FAILURE_TIMEOUT);
+ break;
+
+ case SOCKET_STOP_POST:
+ log_warning_unit(u->id,
+ "%s stopping timed out (2). Terminating.", u->id);
+ socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_TIMEOUT);
+ break;
+
+ case SOCKET_FINAL_SIGTERM:
+ if (s->kill_context.send_sigkill) {
+ log_warning_unit(u->id,
+ "%s stopping timed out (2). Killing.", u->id);
+ socket_enter_signal(s, SOCKET_FINAL_SIGKILL, SOCKET_FAILURE_TIMEOUT);
+ } else {
+ log_warning_unit(u->id,
+ "%s stopping timed out (2). Skipping SIGKILL. Ignoring.",
+ u->id);
+ socket_enter_dead(s, SOCKET_FAILURE_TIMEOUT);
+ }
+ break;
+
+ case SOCKET_FINAL_SIGKILL:
+ log_warning_unit(u->id,
+ "%s still around after SIGKILL (2). Entering failed mode.",
+ u->id);
+ socket_enter_dead(s, SOCKET_FAILURE_TIMEOUT);
+ break;
+
+ default:
+ assert_not_reached("Timeout at wrong time.");
+ }
+}
+
+int socket_collect_fds(Socket *s, int **fds, unsigned *n_fds) {
+ int *rfds;
+ unsigned rn_fds, k;
+ SocketPort *p;
+
+ assert(s);
+ assert(fds);
+ assert(n_fds);
+
+ /* Called from the service code for requesting our fds */
+
+ rn_fds = 0;
+ LIST_FOREACH(port, p, s->ports)
+ if (p->fd >= 0)
+ rn_fds++;
+
+ if (rn_fds <= 0) {
+ *fds = NULL;
+ *n_fds = 0;
+ return 0;
+ }
+
+ if (!(rfds = new(int, rn_fds)))
+ return -ENOMEM;
+
+ k = 0;
+ LIST_FOREACH(port, p, s->ports)
+ if (p->fd >= 0)
+ rfds[k++] = p->fd;
+
+ assert(k == rn_fds);
+
+ *fds = rfds;
+ *n_fds = rn_fds;
+
+ return 0;
+}
+
+void socket_notify_service_dead(Socket *s, bool failed_permanent) {
+ assert(s);
+
+ /* The service is dead. Dang!
+ *
+ * This is strictly for one-instance-for-all-connections
+ * services. */
+
+ if (s->state == SOCKET_RUNNING) {
+ log_debug_unit(UNIT(s)->id,
+ "%s got notified about service death (failed permanently: %s)",
+ UNIT(s)->id, yes_no(failed_permanent));
+ if (failed_permanent)
+ socket_enter_stop_pre(s, SOCKET_FAILURE_SERVICE_FAILED_PERMANENT);
+ else
+ socket_enter_listening(s);
+ }
+}
+
+void socket_connection_unref(Socket *s) {
+ assert(s);
+
+ /* The service is dead. Yay!
+ *
+ * This is strictly for one-instance-per-connection
+ * services. */
+
+ assert(s->n_connections > 0);
+ s->n_connections--;
+
+ log_debug_unit(UNIT(s)->id,
+ "%s: One connection closed, %u left.", UNIT(s)->id, s->n_connections);
+}
+
+static void socket_reset_failed(Unit *u) {
+ Socket *s = SOCKET(u);
+
+ assert(s);
+
+ if (s->state == SOCKET_FAILED)
+ socket_set_state(s, SOCKET_DEAD);
+
+ s->result = SOCKET_SUCCESS;
+}
+
+static int socket_kill(Unit *u, KillWho who, int signo, DBusError *error) {
+ return unit_kill_common(u, who, signo, -1, SOCKET(u)->control_pid, error);
+}
+
+static const char* const socket_state_table[_SOCKET_STATE_MAX] = {
+ [SOCKET_DEAD] = "dead",
+ [SOCKET_START_PRE] = "start-pre",
+ [SOCKET_START_POST] = "start-post",
+ [SOCKET_LISTENING] = "listening",
+ [SOCKET_RUNNING] = "running",
+ [SOCKET_STOP_PRE] = "stop-pre",
+ [SOCKET_STOP_PRE_SIGTERM] = "stop-pre-sigterm",
+ [SOCKET_STOP_PRE_SIGKILL] = "stop-pre-sigkill",
+ [SOCKET_STOP_POST] = "stop-post",
+ [SOCKET_FINAL_SIGTERM] = "final-sigterm",
+ [SOCKET_FINAL_SIGKILL] = "final-sigkill",
+ [SOCKET_FAILED] = "failed"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(socket_state, SocketState);
+
+static const char* const socket_exec_command_table[_SOCKET_EXEC_COMMAND_MAX] = {
+ [SOCKET_EXEC_START_PRE] = "StartPre",
+ [SOCKET_EXEC_START_POST] = "StartPost",
+ [SOCKET_EXEC_STOP_PRE] = "StopPre",
+ [SOCKET_EXEC_STOP_POST] = "StopPost"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(socket_exec_command, SocketExecCommand);
+
+static const char* const socket_result_table[_SOCKET_RESULT_MAX] = {
+ [SOCKET_SUCCESS] = "success",
+ [SOCKET_FAILURE_RESOURCES] = "resources",
+ [SOCKET_FAILURE_TIMEOUT] = "timeout",
+ [SOCKET_FAILURE_EXIT_CODE] = "exit-code",
+ [SOCKET_FAILURE_SIGNAL] = "signal",
+ [SOCKET_FAILURE_CORE_DUMP] = "core-dump",
+ [SOCKET_FAILURE_SERVICE_FAILED_PERMANENT] = "service-failed-permanent"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(socket_result, SocketResult);
+
+const UnitVTable socket_vtable = {
+ .object_size = sizeof(Socket),
+
+ .sections =
+ "Unit\0"
+ "Socket\0"
+ "Install\0",
+
+ .exec_context_offset = offsetof(Socket, exec_context),
+ .exec_section = "Socket",
+
+ .init = socket_init,
+ .done = socket_done,
+ .load = socket_load,
+
+ .kill = socket_kill,
+
+ .coldplug = socket_coldplug,
+
+ .dump = socket_dump,
+
+ .start = socket_start,
+ .stop = socket_stop,
+
+ .serialize = socket_serialize,
+ .deserialize_item = socket_deserialize_item,
+ .distribute_fds = socket_distribute_fds,
+
+ .active_state = socket_active_state,
+ .sub_state_to_string = socket_sub_state_to_string,
+
+ .check_gc = socket_check_gc,
+
+ .fd_event = socket_fd_event,
+ .sigchld_event = socket_sigchld_event,
+ .timer_event = socket_timer_event,
+
+ .reset_failed = socket_reset_failed,
+
+ .bus_interface = "org.freedesktop.systemd1.Socket",
+ .bus_message_handler = bus_socket_message_handler,
+ .bus_invalidating_properties = bus_socket_invalidating_properties,
+
+ .status_message_formats = {
+ /*.starting_stopping = {
+ [0] = "Starting socket %s...",
+ [1] = "Stopping socket %s...",
+ },*/
+ .finished_start_job = {
+ [JOB_DONE] = "Listening on %s.",
+ [JOB_FAILED] = "Failed to listen on %s.",
+ [JOB_DEPENDENCY] = "Dependency failed for %s.",
+ [JOB_TIMEOUT] = "Timed out starting %s.",
+ },
+ .finished_stop_job = {
+ [JOB_DONE] = "Closed %s.",
+ [JOB_FAILED] = "Failed stopping %s.",
+ [JOB_TIMEOUT] = "Timed out stopping %s.",
+ },
+ },
+};
diff --git a/src/core/socket.h b/src/core/socket.h
new file mode 100644
index 0000000000..9d48cde0a6
--- /dev/null
+++ b/src/core/socket.h
@@ -0,0 +1,180 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+typedef struct Socket Socket;
+
+#include "manager.h"
+#include "unit.h"
+#include "socket-util.h"
+#include "mount.h"
+#include "service.h"
+
+typedef enum SocketState {
+ SOCKET_DEAD,
+ SOCKET_START_PRE,
+ SOCKET_START_POST,
+ SOCKET_LISTENING,
+ SOCKET_RUNNING,
+ SOCKET_STOP_PRE,
+ SOCKET_STOP_PRE_SIGTERM,
+ SOCKET_STOP_PRE_SIGKILL,
+ SOCKET_STOP_POST,
+ SOCKET_FINAL_SIGTERM,
+ SOCKET_FINAL_SIGKILL,
+ SOCKET_FAILED,
+ _SOCKET_STATE_MAX,
+ _SOCKET_STATE_INVALID = -1
+} SocketState;
+
+typedef enum SocketExecCommand {
+ SOCKET_EXEC_START_PRE,
+ SOCKET_EXEC_START_POST,
+ SOCKET_EXEC_STOP_PRE,
+ SOCKET_EXEC_STOP_POST,
+ _SOCKET_EXEC_COMMAND_MAX,
+ _SOCKET_EXEC_COMMAND_INVALID = -1
+} SocketExecCommand;
+
+typedef enum SocketType {
+ SOCKET_SOCKET,
+ SOCKET_FIFO,
+ SOCKET_SPECIAL,
+ SOCKET_MQUEUE,
+ _SOCKET_FIFO_MAX,
+ _SOCKET_FIFO_INVALID = -1
+} SocketType;
+
+typedef enum SocketResult {
+ SOCKET_SUCCESS,
+ SOCKET_FAILURE_RESOURCES,
+ SOCKET_FAILURE_TIMEOUT,
+ SOCKET_FAILURE_EXIT_CODE,
+ SOCKET_FAILURE_SIGNAL,
+ SOCKET_FAILURE_CORE_DUMP,
+ SOCKET_FAILURE_SERVICE_FAILED_PERMANENT,
+ _SOCKET_RESULT_MAX,
+ _SOCKET_RESULT_INVALID = -1
+} SocketResult;
+
+typedef struct SocketPort {
+ SocketType type;
+ int fd;
+
+ SocketAddress address;
+ char *path;
+ Watch fd_watch;
+
+ LIST_FIELDS(struct SocketPort, port);
+} SocketPort;
+
+struct Socket {
+ Unit meta;
+
+ LIST_HEAD(SocketPort, ports);
+
+ unsigned n_accepted;
+ unsigned n_connections;
+ unsigned max_connections;
+
+ unsigned backlog;
+ usec_t timeout_usec;
+
+ ExecCommand* exec_command[_SOCKET_EXEC_COMMAND_MAX];
+ ExecContext exec_context;
+ KillContext kill_context;
+
+ /* For Accept=no sockets refers to the one service we'll
+ activate. For Accept=yes sockets is either NULL, or filled
+ when the next service we spawn. */
+ UnitRef service;
+
+ SocketState state, deserialized_state;
+
+ Watch timer_watch;
+
+ ExecCommand* control_command;
+ SocketExecCommand control_command_id;
+ pid_t control_pid;
+
+ mode_t directory_mode;
+ mode_t socket_mode;
+
+ SocketResult result;
+
+ bool accept;
+
+ /* Socket options */
+ bool keep_alive;
+ bool free_bind;
+ bool transparent;
+ bool broadcast;
+ bool pass_cred;
+ bool pass_sec;
+
+ /* Only for INET6 sockets: issue IPV6_V6ONLY sockopt */
+ SocketAddressBindIPv6Only bind_ipv6_only;
+
+ int priority;
+ int mark;
+ size_t receive_buffer;
+ size_t send_buffer;
+ int ip_tos;
+ int ip_ttl;
+ size_t pipe_size;
+ char *bind_to_device;
+ char *tcp_congestion;
+ long mq_maxmsg;
+ long mq_msgsize;
+
+ char *smack;
+ char *smack_ip_in;
+ char *smack_ip_out;
+};
+
+/* Called from the service code when collecting fds */
+int socket_collect_fds(Socket *s, int **fds, unsigned *n_fds);
+
+/* Called from the service when it shut down */
+void socket_notify_service_dead(Socket *s, bool failed_permanent);
+
+/* Called from the mount code figure out if a mount is a dependency of
+ * any of the sockets of this socket */
+int socket_add_one_mount_link(Socket *s, Mount *m);
+
+/* Called from the service code when a per-connection service ended */
+void socket_connection_unref(Socket *s);
+
+void socket_free_ports(Socket *s);
+
+extern const UnitVTable socket_vtable;
+
+const char* socket_state_to_string(SocketState i) _const_;
+SocketState socket_state_from_string(const char *s) _pure_;
+
+const char* socket_exec_command_to_string(SocketExecCommand i) _const_;
+SocketExecCommand socket_exec_command_from_string(const char *s) _pure_;
+
+const char* socket_result_to_string(SocketResult i) _const_;
+SocketResult socket_result_from_string(const char *s) _pure_;
+
+const char* socket_port_type_to_string(SocketPort *p) _pure_;
diff --git a/src/core/special.h b/src/core/special.h
new file mode 100644
index 0000000000..a9b50bce05
--- /dev/null
+++ b/src/core/special.h
@@ -0,0 +1,115 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#define SPECIAL_DEFAULT_TARGET "default.target"
+
+/* Shutdown targets */
+#define SPECIAL_UMOUNT_TARGET "umount.target"
+/* This is not really intended to be started by directly. This is
+ * mostly so that other targets (reboot/halt/poweroff) can depend on
+ * it to bring all services down that want to be brought down on
+ * system shutdown. */
+#define SPECIAL_SHUTDOWN_TARGET "shutdown.target"
+#define SPECIAL_HALT_TARGET "halt.target"
+#define SPECIAL_POWEROFF_TARGET "poweroff.target"
+#define SPECIAL_REBOOT_TARGET "reboot.target"
+#define SPECIAL_KEXEC_TARGET "kexec.target"
+#define SPECIAL_EXIT_TARGET "exit.target"
+#define SPECIAL_SUSPEND_TARGET "suspend.target"
+#define SPECIAL_HIBERNATE_TARGET "hibernate.target"
+#define SPECIAL_HYBRID_SLEEP_TARGET "hybrid-sleep.target"
+
+/* Special boot targets */
+#define SPECIAL_RESCUE_TARGET "rescue.target"
+#define SPECIAL_EMERGENCY_TARGET "emergency.target"
+
+/* Early boot targets */
+#define SPECIAL_SYSINIT_TARGET "sysinit.target"
+#define SPECIAL_SOCKETS_TARGET "sockets.target"
+#define SPECIAL_TIMERS_TARGET "timers.target"
+#define SPECIAL_PATHS_TARGET "paths.target"
+#define SPECIAL_LOCAL_FS_TARGET "local-fs.target"
+#define SPECIAL_LOCAL_FS_PRE_TARGET "local-fs-pre.target"
+#define SPECIAL_INITRD_FS_TARGET "initrd-fs.target"
+#define SPECIAL_INITRD_ROOT_FS_TARGET "initrd-root-fs.target"
+#define SPECIAL_REMOTE_FS_TARGET "remote-fs.target" /* LSB's $remote_fs */
+#define SPECIAL_REMOTE_FS_PRE_TARGET "remote-fs-pre.target"
+#define SPECIAL_SWAP_TARGET "swap.target"
+#define SPECIAL_NETWORK_ONLINE_TARGET "network-online.target"
+#define SPECIAL_BASIC_TARGET "basic.target"
+
+/* LSB compatibility */
+#define SPECIAL_NETWORK_TARGET "network.target" /* LSB's $network */
+#define SPECIAL_NSS_LOOKUP_TARGET "nss-lookup.target" /* LSB's $named */
+#define SPECIAL_RPCBIND_TARGET "rpcbind.target" /* LSB's $portmap */
+#define SPECIAL_TIME_SYNC_TARGET "time-sync.target" /* LSB's $time */
+
+/*
+ * Rules regarding adding further high level targets like the above:
+ *
+ * - Be conservative, only add more of these when we really need
+ * them. We need strong usecases for further additions.
+ *
+ * - When there can be multiple implementations running side-by-side,
+ * it needs to be a .target unit which can pull in all
+ * implementations.
+ *
+ * - If something can be implemented with socket activation, and
+ * without, it needs to be a .target unit, so that it can pull in
+ * the appropriate unit.
+ *
+ * - Otherwise, it should be a .service unit.
+ *
+ * - In some cases it is OK to have both a .service and a .target
+ * unit, i.e. if there can be multiple parallel implementations, but
+ * only one is the "system" one. Example: syslog.
+ *
+ * Or to put this in other words: .service symlinks can be used to
+ * arbitrate between multiple implementations if there can be only one
+ * of a kind. .target units can be used to support multiple
+ * implementations that can run side-by-side.
+ */
+
+/* Magic early boot services */
+#define SPECIAL_FSCK_SERVICE "systemd-fsck@.service"
+#define SPECIAL_QUOTACHECK_SERVICE "systemd-quotacheck.service"
+#define SPECIAL_QUOTAON_SERVICE "quotaon.service"
+#define SPECIAL_REMOUNT_FS_SERVICE "systemd-remount-fs.service"
+
+/* Services systemd relies on */
+#define SPECIAL_DBUS_SERVICE "dbus.service"
+#define SPECIAL_DBUS_SOCKET "dbus.socket"
+#define SPECIAL_JOURNALD_SOCKET "systemd-journald.socket"
+#define SPECIAL_JOURNALD_SERVICE "systemd-journald.service"
+
+/* Magic init signals */
+#define SPECIAL_KBREQUEST_TARGET "kbrequest.target"
+#define SPECIAL_SIGPWR_TARGET "sigpwr.target"
+#define SPECIAL_CTRL_ALT_DEL_TARGET "ctrl-alt-del.target"
+
+/* For SysV compatibility. Usually an alias for a saner target. On
+ * SysV-free systems this doesn't exist. */
+#define SPECIAL_RUNLEVEL2_TARGET "runlevel2.target"
+#define SPECIAL_RUNLEVEL3_TARGET "runlevel3.target"
+#define SPECIAL_RUNLEVEL4_TARGET "runlevel4.target"
+#define SPECIAL_RUNLEVEL5_TARGET "runlevel5.target"
diff --git a/src/core/swap.c b/src/core/swap.c
new file mode 100644
index 0000000000..d503fe20df
--- /dev/null
+++ b/src/core/swap.c
@@ -0,0 +1,1385 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <limits.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/epoll.h>
+#include <sys/stat.h>
+#include <sys/swap.h>
+#include <libudev.h>
+
+#include "unit.h"
+#include "swap.h"
+#include "load-fragment.h"
+#include "load-dropin.h"
+#include "unit-name.h"
+#include "dbus-swap.h"
+#include "special.h"
+#include "bus-errors.h"
+#include "exit-status.h"
+#include "def.h"
+#include "path-util.h"
+#include "virt.h"
+
+static const UnitActiveState state_translation_table[_SWAP_STATE_MAX] = {
+ [SWAP_DEAD] = UNIT_INACTIVE,
+ [SWAP_ACTIVATING] = UNIT_ACTIVATING,
+ [SWAP_ACTIVE] = UNIT_ACTIVE,
+ [SWAP_DEACTIVATING] = UNIT_DEACTIVATING,
+ [SWAP_ACTIVATING_SIGTERM] = UNIT_DEACTIVATING,
+ [SWAP_ACTIVATING_SIGKILL] = UNIT_DEACTIVATING,
+ [SWAP_DEACTIVATING_SIGTERM] = UNIT_DEACTIVATING,
+ [SWAP_DEACTIVATING_SIGKILL] = UNIT_DEACTIVATING,
+ [SWAP_FAILED] = UNIT_FAILED
+};
+
+static void swap_unset_proc_swaps(Swap *s) {
+ Swap *first;
+ Hashmap *swaps;
+
+ assert(s);
+
+ if (!s->parameters_proc_swaps.what)
+ return;
+
+ /* Remove this unit from the chain of swaps which share the
+ * same kernel swap device. */
+ swaps = UNIT(s)->manager->swaps_by_proc_swaps;
+ first = hashmap_get(swaps, s->parameters_proc_swaps.what);
+ LIST_REMOVE(Swap, same_proc_swaps, first, s);
+
+ if (first)
+ hashmap_remove_and_replace(swaps,
+ s->parameters_proc_swaps.what,
+ first->parameters_proc_swaps.what,
+ first);
+ else
+ hashmap_remove(swaps, s->parameters_proc_swaps.what);
+
+ free(s->parameters_proc_swaps.what);
+ s->parameters_proc_swaps.what = NULL;
+}
+
+static void swap_init(Unit *u) {
+ Swap *s = SWAP(u);
+
+ assert(s);
+ assert(UNIT(s)->load_state == UNIT_STUB);
+
+ s->timeout_usec = DEFAULT_TIMEOUT_USEC;
+
+ exec_context_init(&s->exec_context);
+ s->exec_context.std_output = u->manager->default_std_output;
+ s->exec_context.std_error = u->manager->default_std_error;
+ kill_context_init(&s->kill_context);
+
+ s->parameters_proc_swaps.priority = s->parameters_fragment.priority = -1;
+
+ s->timer_watch.type = WATCH_INVALID;
+
+ s->control_command_id = _SWAP_EXEC_COMMAND_INVALID;
+
+ UNIT(s)->ignore_on_isolate = true;
+}
+
+static void swap_unwatch_control_pid(Swap *s) {
+ assert(s);
+
+ if (s->control_pid <= 0)
+ return;
+
+ unit_unwatch_pid(UNIT(s), s->control_pid);
+ s->control_pid = 0;
+}
+
+static void swap_done(Unit *u) {
+ Swap *s = SWAP(u);
+
+ assert(s);
+
+ swap_unset_proc_swaps(s);
+
+ free(s->what);
+ s->what = NULL;
+
+ free(s->parameters_fragment.what);
+ s->parameters_fragment.what = NULL;
+
+ exec_context_done(&s->exec_context, manager_is_reloading_or_reexecuting(u->manager));
+ exec_command_done_array(s->exec_command, _SWAP_EXEC_COMMAND_MAX);
+ s->control_command = NULL;
+
+ swap_unwatch_control_pid(s);
+
+ unit_unwatch_timer(u, &s->timer_watch);
+}
+
+int swap_add_one_mount_link(Swap *s, Mount *m) {
+ int r;
+
+ assert(s);
+ assert(m);
+
+ if (UNIT(s)->load_state != UNIT_LOADED ||
+ UNIT(m)->load_state != UNIT_LOADED)
+ return 0;
+
+ if (is_device_path(s->what))
+ return 0;
+
+ if (!path_startswith(s->what, m->where))
+ return 0;
+
+ r = unit_add_two_dependencies(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, UNIT(m), true);
+ if (r < 0)
+ return r;
+
+ return 0;
+}
+
+static int swap_add_mount_links(Swap *s) {
+ Unit *other;
+ int r;
+
+ assert(s);
+
+ LIST_FOREACH(units_by_type, other, UNIT(s)->manager->units_by_type[UNIT_MOUNT])
+ if ((r = swap_add_one_mount_link(s, MOUNT(other))) < 0)
+ return r;
+
+ return 0;
+}
+
+static int swap_add_device_links(Swap *s) {
+ SwapParameters *p;
+
+ assert(s);
+
+ if (!s->what)
+ return 0;
+
+ if (s->from_fragment)
+ p = &s->parameters_fragment;
+ else
+ return 0;
+
+ if (is_device_path(s->what))
+ return unit_add_node_link(UNIT(s), s->what,
+ !p->noauto && p->nofail &&
+ UNIT(s)->manager->running_as == SYSTEMD_SYSTEM);
+ else
+ /* File based swap devices need to be ordered after
+ * systemd-remount-fs.service, since they might need a
+ * writable file system. */
+ return unit_add_dependency_by_name(UNIT(s), UNIT_AFTER, SPECIAL_REMOUNT_FS_SERVICE, NULL, true);
+}
+
+static int swap_add_default_dependencies(Swap *s) {
+ int r;
+
+ assert(s);
+
+ if (UNIT(s)->manager->running_as != SYSTEMD_SYSTEM)
+ return 0;
+
+ if (detect_container(NULL) > 0)
+ return 0;
+
+ r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_UMOUNT_TARGET, NULL, true);
+ if (r < 0)
+ return r;
+
+ return 0;
+}
+
+static int swap_verify(Swap *s) {
+ bool b;
+ _cleanup_free_ char *e = NULL;
+
+ if (UNIT(s)->load_state != UNIT_LOADED)
+ return 0;
+
+ e = unit_name_from_path(s->what, ".swap");
+ if (e == NULL)
+ return log_oom();
+
+ b = unit_has_name(UNIT(s), e);
+ if (!b) {
+ log_error_unit(UNIT(s)->id,
+ "%s: Value of \"What\" and unit name do not match, not loading.",
+ UNIT(s)->id);
+ return -EINVAL;
+ }
+
+ if (s->exec_context.pam_name && s->kill_context.kill_mode != KILL_CONTROL_GROUP) {
+ log_error_unit(UNIT(s)->id,
+ "%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing to load.",
+ UNIT(s)->id);
+ return -EINVAL;
+ }
+
+ return 0;
+}
+
+static int swap_load(Unit *u) {
+ int r;
+ Swap *s = SWAP(u);
+
+ assert(s);
+ assert(u->load_state == UNIT_STUB);
+
+ /* Load a .swap file */
+ r = unit_load_fragment_and_dropin_optional(u);
+ if (r < 0)
+ return r;
+
+ if (u->load_state == UNIT_LOADED) {
+ r = unit_add_exec_dependencies(u, &s->exec_context);
+ if (r < 0)
+ return r;
+
+ if (UNIT(s)->fragment_path)
+ s->from_fragment = true;
+
+ if (!s->what) {
+ if (s->parameters_fragment.what)
+ s->what = strdup(s->parameters_fragment.what);
+ else if (s->parameters_proc_swaps.what)
+ s->what = strdup(s->parameters_proc_swaps.what);
+ else
+ s->what = unit_name_to_path(u->id);
+
+ if (!s->what)
+ return -ENOMEM;
+ }
+
+ path_kill_slashes(s->what);
+
+ if (!UNIT(s)->description)
+ if ((r = unit_set_description(u, s->what)) < 0)
+ return r;
+
+ r = swap_add_device_links(s);
+ if (r < 0)
+ return r;
+
+ r = swap_add_mount_links(s);
+ if (r < 0)
+ return r;
+
+ r = unit_add_default_cgroups(u);
+ if (r < 0)
+ return r;
+
+ if (UNIT(s)->default_dependencies) {
+ r = swap_add_default_dependencies(s);
+ if (r < 0)
+ return r;
+ }
+
+ r = unit_exec_context_defaults(u, &s->exec_context);
+ if (r < 0)
+ return r;
+ }
+
+ return swap_verify(s);
+}
+
+static int swap_add_one(
+ Manager *m,
+ const char *what,
+ const char *what_proc_swaps,
+ int priority,
+ bool noauto,
+ bool nofail,
+ bool set_flags) {
+
+ Unit *u = NULL;
+ _cleanup_free_ char *e = NULL;
+ char *wp = NULL;
+ bool delete = false;
+ int r;
+ SwapParameters *p;
+ Swap *first;
+
+ assert(m);
+ assert(what);
+ assert(what_proc_swaps);
+
+ e = unit_name_from_path(what, ".swap");
+ if (!e)
+ return log_oom();
+
+ u = manager_get_unit(m, e);
+
+ if (u &&
+ SWAP(u)->from_proc_swaps &&
+ !path_equal(SWAP(u)->parameters_proc_swaps.what, what_proc_swaps))
+ return -EEXIST;
+
+ if (!u) {
+ delete = true;
+
+ u = unit_new(m, sizeof(Swap));
+ if (!u)
+ return log_oom();
+
+ r = unit_add_name(u, e);
+ if (r < 0)
+ goto fail;
+
+ SWAP(u)->what = strdup(what);
+ if (!SWAP(u)->what) {
+ r = log_oom();
+ goto fail;
+ }
+
+ unit_add_to_load_queue(u);
+ } else
+ delete = false;
+
+ p = &SWAP(u)->parameters_proc_swaps;
+
+ if (!p->what) {
+ wp = strdup(what_proc_swaps);
+ if (!wp) {
+ r = log_oom();
+ goto fail;
+ }
+
+ if (!m->swaps_by_proc_swaps) {
+ m->swaps_by_proc_swaps = hashmap_new(string_hash_func, string_compare_func);
+ if (!m->swaps_by_proc_swaps) {
+ r = log_oom();
+ goto fail;
+ }
+ }
+
+ free(p->what);
+ p->what = wp;
+
+ first = hashmap_get(m->swaps_by_proc_swaps, wp);
+ LIST_PREPEND(Swap, same_proc_swaps, first, SWAP(u));
+
+ r = hashmap_replace(m->swaps_by_proc_swaps, wp, first);
+ if (r < 0)
+ goto fail;
+ }
+
+ if (set_flags) {
+ SWAP(u)->is_active = true;
+ SWAP(u)->just_activated = !SWAP(u)->from_proc_swaps;
+ }
+
+ SWAP(u)->from_proc_swaps = true;
+
+ p->priority = priority;
+ p->noauto = noauto;
+ p->nofail = nofail;
+
+ unit_add_to_dbus_queue(u);
+
+ return 0;
+
+fail:
+ log_warning_unit(e, "Failed to load swap unit: %s", strerror(-r));
+
+ free(wp);
+
+ if (delete && u)
+ unit_free(u);
+
+ return r;
+}
+
+static int swap_process_new_swap(Manager *m, const char *device, int prio, bool set_flags) {
+ struct stat st;
+ int r = 0, k;
+
+ assert(m);
+
+ if (stat(device, &st) >= 0 && S_ISBLK(st.st_mode)) {
+ struct udev_device *d;
+ const char *dn;
+ struct udev_list_entry *item = NULL, *first = NULL;
+
+ /* So this is a proper swap device. Create swap units
+ * for all names this swap device is known under */
+
+ d = udev_device_new_from_devnum(m->udev, 'b', st.st_rdev);
+ if (!d)
+ return log_oom();
+
+ dn = udev_device_get_devnode(d);
+ /* Skip dn==device, since that case will be handled below */
+ if (dn && !streq(dn, device))
+ r = swap_add_one(m, dn, device, prio, false, false, set_flags);
+
+ /* Add additional units for all symlinks */
+ first = udev_device_get_devlinks_list_entry(d);
+ udev_list_entry_foreach(item, first) {
+ const char *p;
+
+ /* Don't bother with the /dev/block links */
+ p = udev_list_entry_get_name(item);
+
+ if (path_startswith(p, "/dev/block/"))
+ continue;
+
+ if (stat(p, &st) >= 0)
+ if ((!S_ISBLK(st.st_mode)) ||
+ st.st_rdev != udev_device_get_devnum(d))
+ continue;
+
+ k = swap_add_one(m, p, device, prio, false, false, set_flags);
+ if (k < 0)
+ r = k;
+ }
+
+ udev_device_unref(d);
+ }
+
+ k = swap_add_one(m, device, device, prio, false, false, set_flags);
+ if (k < 0)
+ r = k;
+
+ return r;
+}
+
+static void swap_set_state(Swap *s, SwapState state) {
+ SwapState old_state;
+
+ assert(s);
+
+ old_state = s->state;
+ s->state = state;
+
+ if (state != SWAP_ACTIVATING &&
+ state != SWAP_ACTIVATING_SIGTERM &&
+ state != SWAP_ACTIVATING_SIGKILL &&
+ state != SWAP_DEACTIVATING &&
+ state != SWAP_DEACTIVATING_SIGTERM &&
+ state != SWAP_DEACTIVATING_SIGKILL) {
+ unit_unwatch_timer(UNIT(s), &s->timer_watch);
+ swap_unwatch_control_pid(s);
+ s->control_command = NULL;
+ s->control_command_id = _SWAP_EXEC_COMMAND_INVALID;
+ }
+
+ if (state != old_state)
+ log_debug_unit(UNIT(s)->id,
+ "%s changed %s -> %s",
+ UNIT(s)->id,
+ swap_state_to_string(old_state),
+ swap_state_to_string(state));
+
+ unit_notify(UNIT(s), state_translation_table[old_state],
+ state_translation_table[state], true);
+}
+
+static int swap_coldplug(Unit *u) {
+ Swap *s = SWAP(u);
+ SwapState new_state = SWAP_DEAD;
+ int r;
+
+ assert(s);
+ assert(s->state == SWAP_DEAD);
+
+ if (s->deserialized_state != s->state)
+ new_state = s->deserialized_state;
+ else if (s->from_proc_swaps)
+ new_state = SWAP_ACTIVE;
+
+ if (new_state != s->state) {
+
+ if (new_state == SWAP_ACTIVATING ||
+ new_state == SWAP_ACTIVATING_SIGTERM ||
+ new_state == SWAP_ACTIVATING_SIGKILL ||
+ new_state == SWAP_DEACTIVATING ||
+ new_state == SWAP_DEACTIVATING_SIGTERM ||
+ new_state == SWAP_DEACTIVATING_SIGKILL) {
+
+ if (s->control_pid <= 0)
+ return -EBADMSG;
+
+ r = unit_watch_pid(UNIT(s), s->control_pid);
+ if (r < 0)
+ return r;
+
+ r = unit_watch_timer(UNIT(s), CLOCK_MONOTONIC, true, s->timeout_usec, &s->timer_watch);
+ if (r < 0)
+ return r;
+ }
+
+ swap_set_state(s, new_state);
+ }
+
+ return 0;
+}
+
+static void swap_dump(Unit *u, FILE *f, const char *prefix) {
+ Swap *s = SWAP(u);
+ SwapParameters *p;
+
+ assert(s);
+ assert(f);
+
+ if (s->from_proc_swaps)
+ p = &s->parameters_proc_swaps;
+ else if (s->from_fragment)
+ p = &s->parameters_fragment;
+ else
+ p = NULL;
+
+ fprintf(f,
+ "%sSwap State: %s\n"
+ "%sResult: %s\n"
+ "%sWhat: %s\n"
+ "%sFrom /proc/swaps: %s\n"
+ "%sFrom fragment: %s\n",
+ prefix, swap_state_to_string(s->state),
+ prefix, swap_result_to_string(s->result),
+ prefix, s->what,
+ prefix, yes_no(s->from_proc_swaps),
+ prefix, yes_no(s->from_fragment));
+
+ if (p)
+ fprintf(f,
+ "%sPriority: %i\n"
+ "%sNoAuto: %s\n"
+ "%sNoFail: %s\n",
+ prefix, p->priority,
+ prefix, yes_no(p->noauto),
+ prefix, yes_no(p->nofail));
+
+ if (s->control_pid > 0)
+ fprintf(f,
+ "%sControl PID: %lu\n",
+ prefix, (unsigned long) s->control_pid);
+
+ exec_context_dump(&s->exec_context, f, prefix);
+ kill_context_dump(&s->kill_context, f, prefix);
+}
+
+static int swap_spawn(Swap *s, ExecCommand *c, pid_t *_pid) {
+ pid_t pid;
+ int r;
+
+ assert(s);
+ assert(c);
+ assert(_pid);
+
+ r = unit_watch_timer(UNIT(s), CLOCK_MONOTONIC, true, s->timeout_usec, &s->timer_watch);
+ if (r < 0)
+ goto fail;
+
+ r = exec_spawn(c,
+ NULL,
+ &s->exec_context,
+ NULL, 0,
+ UNIT(s)->manager->environment,
+ true,
+ true,
+ true,
+ UNIT(s)->manager->confirm_spawn,
+ UNIT(s)->cgroup_bondings,
+ UNIT(s)->cgroup_attributes,
+ NULL,
+ UNIT(s)->id,
+ NULL,
+ &pid);
+ if (r < 0)
+ goto fail;
+
+ r = unit_watch_pid(UNIT(s), pid);
+ if (r < 0)
+ /* FIXME: we need to do something here */
+ goto fail;
+
+ *_pid = pid;
+
+ return 0;
+
+fail:
+ unit_unwatch_timer(UNIT(s), &s->timer_watch);
+
+ return r;
+}
+
+static void swap_enter_dead(Swap *s, SwapResult f) {
+ assert(s);
+
+ if (f != SWAP_SUCCESS)
+ s->result = f;
+
+ exec_context_tmp_dirs_done(&s->exec_context);
+ swap_set_state(s, s->result != SWAP_SUCCESS ? SWAP_FAILED : SWAP_DEAD);
+}
+
+static void swap_enter_active(Swap *s, SwapResult f) {
+ assert(s);
+
+ if (f != SWAP_SUCCESS)
+ s->result = f;
+
+ swap_set_state(s, SWAP_ACTIVE);
+}
+
+static void swap_enter_signal(Swap *s, SwapState state, SwapResult f) {
+ int r;
+
+ assert(s);
+
+ if (f != SWAP_SUCCESS)
+ s->result = f;
+
+ r = unit_kill_context(
+ UNIT(s),
+ &s->kill_context,
+ state != SWAP_ACTIVATING_SIGTERM && state != SWAP_DEACTIVATING_SIGTERM,
+ -1,
+ s->control_pid,
+ false);
+ if (r < 0)
+ goto fail;
+
+ if (r > 0) {
+ r = unit_watch_timer(UNIT(s), CLOCK_MONOTONIC, true, s->timeout_usec, &s->timer_watch);
+ if (r < 0)
+ goto fail;
+
+ swap_set_state(s, state);
+ } else
+ swap_enter_dead(s, SWAP_SUCCESS);
+
+ return;
+
+fail:
+ log_warning_unit(UNIT(s)->id,
+ "%s failed to kill processes: %s", UNIT(s)->id, strerror(-r));
+
+ swap_enter_dead(s, SWAP_FAILURE_RESOURCES);
+}
+
+static void swap_enter_activating(Swap *s) {
+ int r, priority;
+
+ assert(s);
+
+ s->control_command_id = SWAP_EXEC_ACTIVATE;
+ s->control_command = s->exec_command + SWAP_EXEC_ACTIVATE;
+
+ if (s->from_fragment)
+ priority = s->parameters_fragment.priority;
+ else
+ priority = -1;
+
+ if (priority >= 0) {
+ char p[LINE_MAX];
+
+ snprintf(p, sizeof(p), "%i", priority);
+ char_array_0(p);
+
+ r = exec_command_set(
+ s->control_command,
+ "/sbin/swapon",
+ "-p",
+ p,
+ s->what,
+ NULL);
+ } else
+ r = exec_command_set(
+ s->control_command,
+ "/sbin/swapon",
+ s->what,
+ NULL);
+
+ if (r < 0)
+ goto fail;
+
+ swap_unwatch_control_pid(s);
+
+ r = swap_spawn(s, s->control_command, &s->control_pid);
+ if (r < 0)
+ goto fail;
+
+ swap_set_state(s, SWAP_ACTIVATING);
+
+ return;
+
+fail:
+ log_warning_unit(UNIT(s)->id,
+ "%s failed to run 'swapon' task: %s",
+ UNIT(s)->id, strerror(-r));
+ swap_enter_dead(s, SWAP_FAILURE_RESOURCES);
+}
+
+static void swap_enter_deactivating(Swap *s) {
+ int r;
+
+ assert(s);
+
+ s->control_command_id = SWAP_EXEC_DEACTIVATE;
+ s->control_command = s->exec_command + SWAP_EXEC_DEACTIVATE;
+
+ r = exec_command_set(s->control_command,
+ "/sbin/swapoff",
+ s->what,
+ NULL);
+ if (r < 0)
+ goto fail;
+
+ swap_unwatch_control_pid(s);
+
+ r = swap_spawn(s, s->control_command, &s->control_pid);
+ if (r < 0)
+ goto fail;
+
+ swap_set_state(s, SWAP_DEACTIVATING);
+
+ return;
+
+fail:
+ log_warning_unit(UNIT(s)->id,
+ "%s failed to run 'swapoff' task: %s",
+ UNIT(s)->id, strerror(-r));
+ swap_enter_active(s, SWAP_FAILURE_RESOURCES);
+}
+
+static int swap_start(Unit *u) {
+ Swap *s = SWAP(u);
+
+ assert(s);
+
+ /* We cannot fulfill this request right now, try again later
+ * please! */
+
+ if (s->state == SWAP_DEACTIVATING ||
+ s->state == SWAP_DEACTIVATING_SIGTERM ||
+ s->state == SWAP_DEACTIVATING_SIGKILL ||
+ s->state == SWAP_ACTIVATING_SIGTERM ||
+ s->state == SWAP_ACTIVATING_SIGKILL)
+ return -EAGAIN;
+
+ if (s->state == SWAP_ACTIVATING)
+ return 0;
+
+ assert(s->state == SWAP_DEAD || s->state == SWAP_FAILED);
+
+ if (detect_container(NULL) > 0)
+ return -EPERM;
+
+ s->result = SWAP_SUCCESS;
+ swap_enter_activating(s);
+ return 0;
+}
+
+static int swap_stop(Unit *u) {
+ Swap *s = SWAP(u);
+
+ assert(s);
+
+ if (s->state == SWAP_DEACTIVATING ||
+ s->state == SWAP_DEACTIVATING_SIGTERM ||
+ s->state == SWAP_DEACTIVATING_SIGKILL ||
+ s->state == SWAP_ACTIVATING_SIGTERM ||
+ s->state == SWAP_ACTIVATING_SIGKILL)
+ return 0;
+
+ assert(s->state == SWAP_ACTIVATING ||
+ s->state == SWAP_ACTIVE);
+
+ if (detect_container(NULL) > 0)
+ return -EPERM;
+
+ swap_enter_deactivating(s);
+ return 0;
+}
+
+static int swap_serialize(Unit *u, FILE *f, FDSet *fds) {
+ Swap *s = SWAP(u);
+
+ assert(s);
+ assert(f);
+ assert(fds);
+
+ unit_serialize_item(u, f, "state", swap_state_to_string(s->state));
+ unit_serialize_item(u, f, "result", swap_result_to_string(s->result));
+
+ if (s->control_pid > 0)
+ unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
+
+ if (s->control_command_id >= 0)
+ unit_serialize_item(u, f, "control-command", swap_exec_command_to_string(s->control_command_id));
+
+ exec_context_serialize(&s->exec_context, UNIT(s), f);
+
+ return 0;
+}
+
+static int swap_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
+ Swap *s = SWAP(u);
+
+ assert(s);
+ assert(fds);
+
+ if (streq(key, "state")) {
+ SwapState state;
+
+ state = swap_state_from_string(value);
+ if (state < 0)
+ log_debug_unit(u->id, "Failed to parse state value %s", value);
+ else
+ s->deserialized_state = state;
+ } else if (streq(key, "result")) {
+ SwapResult f;
+
+ f = swap_result_from_string(value);
+ if (f < 0)
+ log_debug_unit(u->id, "Failed to parse result value %s", value);
+ else if (f != SWAP_SUCCESS)
+ s->result = f;
+ } else if (streq(key, "control-pid")) {
+ pid_t pid;
+
+ if (parse_pid(value, &pid) < 0)
+ log_debug_unit(u->id, "Failed to parse control-pid value %s", value);
+ else
+ s->control_pid = pid;
+
+ } else if (streq(key, "control-command")) {
+ SwapExecCommand id;
+
+ id = swap_exec_command_from_string(value);
+ if (id < 0)
+ log_debug_unit(u->id, "Failed to parse exec-command value %s", value);
+ else {
+ s->control_command_id = id;
+ s->control_command = s->exec_command + id;
+ }
+ } else if (streq(key, "tmp-dir")) {
+ char *t;
+
+ t = strdup(value);
+ if (!t)
+ return log_oom();
+
+ s->exec_context.tmp_dir = t;
+ } else if (streq(key, "var-tmp-dir")) {
+ char *t;
+
+ t = strdup(value);
+ if (!t)
+ return log_oom();
+
+ s->exec_context.var_tmp_dir = t;
+ } else
+ log_debug_unit(u->id, "Unknown serialization key '%s'", key);
+
+ return 0;
+}
+
+_pure_ static UnitActiveState swap_active_state(Unit *u) {
+ assert(u);
+
+ return state_translation_table[SWAP(u)->state];
+}
+
+_pure_ static const char *swap_sub_state_to_string(Unit *u) {
+ assert(u);
+
+ return swap_state_to_string(SWAP(u)->state);
+}
+
+_pure_ static bool swap_check_gc(Unit *u) {
+ Swap *s = SWAP(u);
+
+ assert(s);
+
+ return s->from_proc_swaps;
+}
+
+static void swap_sigchld_event(Unit *u, pid_t pid, int code, int status) {
+ Swap *s = SWAP(u);
+ SwapResult f;
+
+ assert(s);
+ assert(pid >= 0);
+
+ if (pid != s->control_pid)
+ return;
+
+ s->control_pid = 0;
+
+ if (is_clean_exit(code, status, NULL))
+ f = SWAP_SUCCESS;
+ else if (code == CLD_EXITED)
+ f = SWAP_FAILURE_EXIT_CODE;
+ else if (code == CLD_KILLED)
+ f = SWAP_FAILURE_SIGNAL;
+ else if (code == CLD_DUMPED)
+ f = SWAP_FAILURE_CORE_DUMP;
+ else
+ assert_not_reached("Unknown code");
+
+ if (f != SWAP_SUCCESS)
+ s->result = f;
+
+ if (s->control_command) {
+ exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
+
+ s->control_command = NULL;
+ s->control_command_id = _SWAP_EXEC_COMMAND_INVALID;
+ }
+
+ log_full_unit(f == SWAP_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
+ u->id,
+ "%s swap process exited, code=%s status=%i",
+ u->id, sigchld_code_to_string(code), status);
+
+ switch (s->state) {
+
+ case SWAP_ACTIVATING:
+ case SWAP_ACTIVATING_SIGTERM:
+ case SWAP_ACTIVATING_SIGKILL:
+
+ if (f == SWAP_SUCCESS)
+ swap_enter_active(s, f);
+ else
+ swap_enter_dead(s, f);
+ break;
+
+ case SWAP_DEACTIVATING:
+ case SWAP_DEACTIVATING_SIGKILL:
+ case SWAP_DEACTIVATING_SIGTERM:
+
+ if (f == SWAP_SUCCESS)
+ swap_enter_dead(s, f);
+ else
+ swap_enter_dead(s, f);
+ break;
+
+ default:
+ assert_not_reached("Uh, control process died at wrong time.");
+ }
+
+ /* Notify clients about changed exit status */
+ unit_add_to_dbus_queue(u);
+
+ /* Request a reload of /proc/swaps, so that following units
+ * can follow our state change */
+ u->manager->request_reload = true;
+}
+
+static void swap_timer_event(Unit *u, uint64_t elapsed, Watch *w) {
+ Swap *s = SWAP(u);
+
+ assert(s);
+ assert(elapsed == 1);
+ assert(w == &s->timer_watch);
+
+ switch (s->state) {
+
+ case SWAP_ACTIVATING:
+ log_warning_unit(u->id, "%s activation timed out. Stopping.", u->id);
+ swap_enter_signal(s, SWAP_ACTIVATING_SIGTERM, SWAP_FAILURE_TIMEOUT);
+ break;
+
+ case SWAP_DEACTIVATING:
+ log_warning_unit(u->id, "%s deactivation timed out. Stopping.", u->id);
+ swap_enter_signal(s, SWAP_DEACTIVATING_SIGTERM, SWAP_FAILURE_TIMEOUT);
+ break;
+
+ case SWAP_ACTIVATING_SIGTERM:
+ if (s->kill_context.send_sigkill) {
+ log_warning_unit(u->id, "%s activation timed out. Killing.", u->id);
+ swap_enter_signal(s, SWAP_ACTIVATING_SIGKILL, SWAP_FAILURE_TIMEOUT);
+ } else {
+ log_warning_unit(u->id, "%s activation timed out. Skipping SIGKILL. Ignoring.", u->id);
+ swap_enter_dead(s, SWAP_FAILURE_TIMEOUT);
+ }
+ break;
+
+ case SWAP_DEACTIVATING_SIGTERM:
+ if (s->kill_context.send_sigkill) {
+ log_warning_unit(u->id, "%s deactivation timed out. Killing.", u->id);
+ swap_enter_signal(s, SWAP_DEACTIVATING_SIGKILL, SWAP_FAILURE_TIMEOUT);
+ } else {
+ log_warning_unit(u->id, "%s deactivation timed out. Skipping SIGKILL. Ignoring.", u->id);
+ swap_enter_dead(s, SWAP_FAILURE_TIMEOUT);
+ }
+ break;
+
+ case SWAP_ACTIVATING_SIGKILL:
+ case SWAP_DEACTIVATING_SIGKILL:
+ log_warning_unit(u->id, "%s swap process still around after SIGKILL. Ignoring.", u->id);
+ swap_enter_dead(s, SWAP_FAILURE_TIMEOUT);
+ break;
+
+ default:
+ assert_not_reached("Timeout at wrong time.");
+ }
+}
+
+static int swap_load_proc_swaps(Manager *m, bool set_flags) {
+ unsigned i;
+ int r = 0;
+
+ assert(m);
+
+ rewind(m->proc_swaps);
+
+ (void) fscanf(m->proc_swaps, "%*s %*s %*s %*s %*s\n");
+
+ for (i = 1;; i++) {
+ char *dev = NULL, *d;
+ int prio = 0, k;
+
+ k = fscanf(m->proc_swaps,
+ "%ms " /* device/file */
+ "%*s " /* type of swap */
+ "%*s " /* swap size */
+ "%*s " /* used */
+ "%i\n", /* priority */
+ &dev, &prio);
+ if (k != 2) {
+ if (k == EOF)
+ break;
+
+ log_warning("Failed to parse /proc/swaps:%u", i);
+ free(dev);
+ continue;
+ }
+
+ d = cunescape(dev);
+ free(dev);
+
+ if (!d)
+ return -ENOMEM;
+
+ k = swap_process_new_swap(m, d, prio, set_flags);
+ free(d);
+
+ if (k < 0)
+ r = k;
+ }
+
+ return r;
+}
+
+int swap_dispatch_reload(Manager *m) {
+ /* This function should go as soon as the kernel properly notifies us */
+
+ if (_likely_(!m->request_reload))
+ return 0;
+
+ m->request_reload = false;
+
+ return swap_fd_event(m, EPOLLPRI);
+}
+
+int swap_fd_event(Manager *m, int events) {
+ Unit *u;
+ int r;
+
+ assert(m);
+ assert(events & EPOLLPRI);
+
+ r = swap_load_proc_swaps(m, true);
+ if (r < 0) {
+ log_error("Failed to reread /proc/swaps: %s", strerror(-r));
+
+ /* Reset flags, just in case, for late calls */
+ LIST_FOREACH(units_by_type, u, m->units_by_type[UNIT_SWAP]) {
+ Swap *swap = SWAP(u);
+
+ swap->is_active = swap->just_activated = false;
+ }
+
+ return 0;
+ }
+
+ manager_dispatch_load_queue(m);
+
+ LIST_FOREACH(units_by_type, u, m->units_by_type[UNIT_SWAP]) {
+ Swap *swap = SWAP(u);
+
+ if (!swap->is_active) {
+ /* This has just been deactivated */
+
+ swap->from_proc_swaps = false;
+ swap_unset_proc_swaps(swap);
+
+ switch (swap->state) {
+
+ case SWAP_ACTIVE:
+ swap_enter_dead(swap, SWAP_SUCCESS);
+ break;
+
+ default:
+ swap_set_state(swap, swap->state);
+ break;
+ }
+
+ } else if (swap->just_activated) {
+
+ /* New swap entry */
+
+ switch (swap->state) {
+
+ case SWAP_DEAD:
+ case SWAP_FAILED:
+ swap_enter_active(swap, SWAP_SUCCESS);
+ break;
+
+ default:
+ /* Nothing really changed, but let's
+ * issue an notification call
+ * nonetheless, in case somebody is
+ * waiting for this. */
+ swap_set_state(swap, swap->state);
+ break;
+ }
+ }
+
+ /* Reset the flags for later calls */
+ swap->is_active = swap->just_activated = false;
+ }
+
+ return 1;
+}
+
+static Unit *swap_following(Unit *u) {
+ Swap *s = SWAP(u);
+ Swap *other, *first = NULL;
+
+ assert(s);
+
+ if (streq_ptr(s->what, s->parameters_proc_swaps.what))
+ return NULL;
+
+ /* Make everybody follow the unit that's named after the swap
+ * device in the kernel */
+
+ LIST_FOREACH_AFTER(same_proc_swaps, other, s)
+ if (streq_ptr(other->what, other->parameters_proc_swaps.what))
+ return UNIT(other);
+
+ LIST_FOREACH_BEFORE(same_proc_swaps, other, s) {
+ if (streq_ptr(other->what, other->parameters_proc_swaps.what))
+ return UNIT(other);
+
+ first = other;
+ }
+
+ return UNIT(first);
+}
+
+static int swap_following_set(Unit *u, Set **_set) {
+ Swap *s = SWAP(u);
+ Swap *other;
+ Set *set;
+ int r;
+
+ assert(s);
+ assert(_set);
+
+ if (LIST_JUST_US(same_proc_swaps, s)) {
+ *_set = NULL;
+ return 0;
+ }
+
+ if (!(set = set_new(NULL, NULL)))
+ return -ENOMEM;
+
+ LIST_FOREACH_AFTER(same_proc_swaps, other, s)
+ if ((r = set_put(set, other)) < 0)
+ goto fail;
+
+ LIST_FOREACH_BEFORE(same_proc_swaps, other, s)
+ if ((r = set_put(set, other)) < 0)
+ goto fail;
+
+ *_set = set;
+ return 1;
+
+fail:
+ set_free(set);
+ return r;
+}
+
+static void swap_shutdown(Manager *m) {
+ assert(m);
+
+ if (m->proc_swaps) {
+ fclose(m->proc_swaps);
+ m->proc_swaps = NULL;
+ }
+
+ hashmap_free(m->swaps_by_proc_swaps);
+ m->swaps_by_proc_swaps = NULL;
+}
+
+static int swap_enumerate(Manager *m) {
+ int r;
+ assert(m);
+
+ if (!m->proc_swaps) {
+ struct epoll_event ev = {
+ .events = EPOLLPRI,
+ .data.ptr = &m->swap_watch,
+ };
+
+ m->proc_swaps = fopen("/proc/swaps", "re");
+ if (!m->proc_swaps)
+ return (errno == ENOENT) ? 0 : -errno;
+
+ m->swap_watch.type = WATCH_SWAP;
+ m->swap_watch.fd = fileno(m->proc_swaps);
+
+ if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->swap_watch.fd, &ev) < 0)
+ return -errno;
+ }
+
+ r = swap_load_proc_swaps(m, false);
+ if (r < 0)
+ swap_shutdown(m);
+
+ return r;
+}
+
+static void swap_reset_failed(Unit *u) {
+ Swap *s = SWAP(u);
+
+ assert(s);
+
+ if (s->state == SWAP_FAILED)
+ swap_set_state(s, SWAP_DEAD);
+
+ s->result = SWAP_SUCCESS;
+}
+
+static int swap_kill(Unit *u, KillWho who, int signo, DBusError *error) {
+ return unit_kill_common(u, who, signo, -1, SWAP(u)->control_pid, error);
+}
+
+static const char* const swap_state_table[_SWAP_STATE_MAX] = {
+ [SWAP_DEAD] = "dead",
+ [SWAP_ACTIVATING] = "activating",
+ [SWAP_ACTIVE] = "active",
+ [SWAP_DEACTIVATING] = "deactivating",
+ [SWAP_ACTIVATING_SIGTERM] = "activating-sigterm",
+ [SWAP_ACTIVATING_SIGKILL] = "activating-sigkill",
+ [SWAP_DEACTIVATING_SIGTERM] = "deactivating-sigterm",
+ [SWAP_DEACTIVATING_SIGKILL] = "deactivating-sigkill",
+ [SWAP_FAILED] = "failed"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(swap_state, SwapState);
+
+static const char* const swap_exec_command_table[_SWAP_EXEC_COMMAND_MAX] = {
+ [SWAP_EXEC_ACTIVATE] = "ExecActivate",
+ [SWAP_EXEC_DEACTIVATE] = "ExecDeactivate",
+};
+
+DEFINE_STRING_TABLE_LOOKUP(swap_exec_command, SwapExecCommand);
+
+static const char* const swap_result_table[_SWAP_RESULT_MAX] = {
+ [SWAP_SUCCESS] = "success",
+ [SWAP_FAILURE_RESOURCES] = "resources",
+ [SWAP_FAILURE_TIMEOUT] = "timeout",
+ [SWAP_FAILURE_EXIT_CODE] = "exit-code",
+ [SWAP_FAILURE_SIGNAL] = "signal",
+ [SWAP_FAILURE_CORE_DUMP] = "core-dump"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(swap_result, SwapResult);
+
+const UnitVTable swap_vtable = {
+ .object_size = sizeof(Swap),
+
+ .sections =
+ "Unit\0"
+ "Swap\0"
+ "Install\0",
+
+ .exec_context_offset = offsetof(Swap, exec_context),
+ .exec_section = "Swap",
+
+ .no_alias = true,
+ .no_instances = true,
+
+ .init = swap_init,
+ .load = swap_load,
+ .done = swap_done,
+
+ .coldplug = swap_coldplug,
+
+ .dump = swap_dump,
+
+ .start = swap_start,
+ .stop = swap_stop,
+
+ .kill = swap_kill,
+
+ .serialize = swap_serialize,
+ .deserialize_item = swap_deserialize_item,
+
+ .active_state = swap_active_state,
+ .sub_state_to_string = swap_sub_state_to_string,
+
+ .check_gc = swap_check_gc,
+
+ .sigchld_event = swap_sigchld_event,
+ .timer_event = swap_timer_event,
+
+ .reset_failed = swap_reset_failed,
+
+ .bus_interface = "org.freedesktop.systemd1.Swap",
+ .bus_message_handler = bus_swap_message_handler,
+ .bus_invalidating_properties = bus_swap_invalidating_properties,
+
+ .following = swap_following,
+ .following_set = swap_following_set,
+
+ .enumerate = swap_enumerate,
+ .shutdown = swap_shutdown,
+
+ .status_message_formats = {
+ .starting_stopping = {
+ [0] = "Activating swap %s...",
+ [1] = "Deactivating swap %s...",
+ },
+ .finished_start_job = {
+ [JOB_DONE] = "Activated swap %s.",
+ [JOB_FAILED] = "Failed to activate swap %s.",
+ [JOB_DEPENDENCY] = "Dependency failed for %s.",
+ [JOB_TIMEOUT] = "Timed out activating swap %s.",
+ },
+ .finished_stop_job = {
+ [JOB_DONE] = "Deactivated swap %s.",
+ [JOB_FAILED] = "Failed deactivating swap %s.",
+ [JOB_TIMEOUT] = "Timed out deactivating swap %s.",
+ },
+ },
+};
diff --git a/src/core/swap.h b/src/core/swap.h
new file mode 100644
index 0000000000..121889d1d5
--- /dev/null
+++ b/src/core/swap.h
@@ -0,0 +1,121 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+ Copyright 2010 Maarten Lankhorst
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+typedef struct Swap Swap;
+
+#include "unit.h"
+
+typedef enum SwapState {
+ SWAP_DEAD,
+ SWAP_ACTIVATING,
+ SWAP_ACTIVE,
+ SWAP_DEACTIVATING,
+ SWAP_ACTIVATING_SIGTERM,
+ SWAP_ACTIVATING_SIGKILL,
+ SWAP_DEACTIVATING_SIGTERM,
+ SWAP_DEACTIVATING_SIGKILL,
+ SWAP_FAILED,
+ _SWAP_STATE_MAX,
+ _SWAP_STATE_INVALID = -1
+} SwapState;
+
+typedef enum SwapExecCommand {
+ SWAP_EXEC_ACTIVATE,
+ SWAP_EXEC_DEACTIVATE,
+ _SWAP_EXEC_COMMAND_MAX,
+ _SWAP_EXEC_COMMAND_INVALID = -1
+} SwapExecCommand;
+
+typedef struct SwapParameters {
+ char *what;
+ int priority;
+ bool noauto:1;
+ bool nofail:1;
+} SwapParameters;
+
+typedef enum SwapResult {
+ SWAP_SUCCESS,
+ SWAP_FAILURE_RESOURCES,
+ SWAP_FAILURE_TIMEOUT,
+ SWAP_FAILURE_EXIT_CODE,
+ SWAP_FAILURE_SIGNAL,
+ SWAP_FAILURE_CORE_DUMP,
+ _SWAP_RESULT_MAX,
+ _SWAP_RESULT_INVALID = -1
+} SwapResult;
+
+struct Swap {
+ Unit meta;
+
+ char *what;
+
+ SwapParameters parameters_proc_swaps;
+ SwapParameters parameters_fragment;
+
+ bool from_proc_swaps:1;
+ bool from_fragment:1;
+
+ /* Used while looking for swaps that vanished or got added
+ * from/to /proc/swaps */
+ bool is_active:1;
+ bool just_activated:1;
+
+ SwapResult result;
+
+ usec_t timeout_usec;
+
+ ExecCommand exec_command[_SWAP_EXEC_COMMAND_MAX];
+ ExecContext exec_context;
+ KillContext kill_context;
+
+ SwapState state, deserialized_state;
+
+ ExecCommand* control_command;
+ SwapExecCommand control_command_id;
+ pid_t control_pid;
+
+ Watch timer_watch;
+
+ /* In order to be able to distinguish dependencies on
+ different device nodes we might end up creating multiple
+ devices for the same swap. We chain them up here. */
+
+ LIST_FIELDS(struct Swap, same_proc_swaps);
+};
+
+extern const UnitVTable swap_vtable;
+
+int swap_add_one_mount_link(Swap *s, Mount *m);
+
+int swap_dispatch_reload(Manager *m);
+int swap_fd_event(Manager *m, int events);
+
+const char* swap_state_to_string(SwapState i) _const_;
+SwapState swap_state_from_string(const char *s) _pure_;
+
+const char* swap_exec_command_to_string(SwapExecCommand i) _const_;
+SwapExecCommand swap_exec_command_from_string(const char *s) _pure_;
+
+const char* swap_result_to_string(SwapResult i) _const_;
+SwapResult swap_result_from_string(const char *s) _pure_;
diff --git a/src/core/switch-root.c b/src/core/switch-root.c
new file mode 100644
index 0000000000..ce0e41d510
--- /dev/null
+++ b/src/core/switch-root.c
@@ -0,0 +1,167 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Harald Hoyer, Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/stat.h>
+#include <stdbool.h>
+#include <errno.h>
+#include <string.h>
+#include <sys/mount.h>
+#include <unistd.h>
+#include <fcntl.h>
+
+#include "util.h"
+#include "path-util.h"
+#include "switch-root.h"
+#include "missing.h"
+
+int switch_root(const char *new_root) {
+
+ /* Don't try to unmount/move the old "/", there's no way to do it. */
+ static const char move_mounts[] =
+ "/dev\0"
+ "/proc\0"
+ "/sys\0"
+ "/run\0";
+
+ int r, old_root_fd = -1;
+ struct stat new_root_stat;
+ bool old_root_remove;
+ const char *i;
+ _cleanup_free_ char *temporary_old_root = NULL;
+
+ if (path_equal(new_root, "/"))
+ return 0;
+
+ /* When using pivot_root() we assume that /mnt exists as place
+ * we can temporarily move the old root to. As we immediately
+ * unmount it from there it doesn't matter much which
+ * directory we choose for this, but it should be more likely
+ * than not that /mnt exists and is suitable as mount point
+ * and is on the same fs as the old root dir */
+ temporary_old_root = strappend(new_root, "/mnt");
+ if (!temporary_old_root)
+ return -ENOMEM;
+
+ old_root_remove = in_initrd();
+
+ if (stat(new_root, &new_root_stat) < 0) {
+ r = -errno;
+ log_error("Failed to stat directory %s: %m", new_root);
+ goto fail;
+ }
+
+ /* Work-around for a kernel bug: for some reason the kernel
+ * refuses switching root if any file systems are mounted
+ * MS_SHARED. Hence remount them MS_PRIVATE here as a
+ * work-around.
+ *
+ * https://bugzilla.redhat.com/show_bug.cgi?id=847418 */
+ if (mount(NULL, "/", NULL, MS_REC|MS_PRIVATE, NULL) < 0)
+ log_warning("Failed to make \"/\" private mount: %m");
+
+ NULSTR_FOREACH(i, move_mounts) {
+ char new_mount[PATH_MAX];
+ struct stat sb;
+
+ snprintf(new_mount, sizeof(new_mount), "%s%s", new_root, i);
+ char_array_0(new_mount);
+
+ if ((stat(new_mount, &sb) < 0) ||
+ sb.st_dev != new_root_stat.st_dev) {
+
+ /* Mount point seems to be mounted already or
+ * stat failed. Unmount the old mount
+ * point. */
+ if (umount2(i, MNT_DETACH) < 0)
+ log_warning("Failed to unmount %s: %m", i);
+ continue;
+ }
+
+ if (mount(i, new_mount, NULL, MS_MOVE, NULL) < 0) {
+ log_error("Failed to move mount %s to %s, forcing unmount: %m", i, new_mount);
+
+ if (umount2(i, MNT_FORCE) < 0)
+ log_warning("Failed to unmount %s: %m", i);
+ }
+ }
+
+ if (chdir(new_root) < 0) {
+ r = -errno;
+ log_error("Failed to change directory to %s: %m", new_root);
+ goto fail;
+ }
+
+ if (old_root_remove) {
+ old_root_fd = open("/", O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY|O_DIRECTORY);
+ if (old_root_fd < 0)
+ log_warning("Failed to open root directory: %m");
+ }
+
+ /* We first try a pivot_root() so that we can umount the old
+ * root dir. In many cases (i.e. where rootfs is /), that's
+ * not possible however, and hence we simply overmount root */
+ if (pivot_root(new_root, temporary_old_root) >= 0) {
+
+ /* Immediately get rid of the old root. Since we are
+ * running off it we need to do this lazily. */
+ if (umount2(temporary_old_root, MNT_DETACH) < 0) {
+ r = -errno;
+ log_error("Failed to umount old root dir %s: %m", temporary_old_root);
+ goto fail;
+ }
+
+ } else if (mount(new_root, "/", NULL, MS_MOVE, NULL) < 0) {
+ r = -errno;
+ log_error("Failed to mount moving %s to /: %m", new_root);
+ goto fail;
+ }
+
+ if (chroot(".") < 0) {
+ r = -errno;
+ log_error("Failed to change root: %m");
+ goto fail;
+ }
+
+ if (chdir("/") < 0) {
+ r = -errno;
+ log_error("Failed to change directory: %m");
+ goto fail;
+ }
+
+ if (old_root_fd >= 0) {
+ struct stat rb;
+
+ if (fstat(old_root_fd, &rb) < 0)
+ log_warning("Failed to stat old root directory, leaving: %m");
+ else {
+ rm_rf_children(old_root_fd, false, false, &rb);
+ old_root_fd = -1;
+ }
+ }
+
+ r = 0;
+
+fail:
+ if (old_root_fd >= 0)
+ close_nointr_nofail(old_root_fd);
+
+ return r;
+}
diff --git a/src/core/switch-root.h b/src/core/switch-root.h
new file mode 100644
index 0000000000..0c4cd1e403
--- /dev/null
+++ b/src/core/switch-root.h
@@ -0,0 +1,27 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef fooswitchroothfoo
+#define fooswitchroothfoo
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Harald Hoyer, Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+int switch_root(const char *switch_root);
+
+#endif
diff --git a/src/core/sync.c b/src/core/sync.c
new file mode 100644
index 0000000000..7e74b63071
--- /dev/null
+++ b/src/core/sync.c
@@ -0,0 +1,65 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <pthread.h>
+#include <unistd.h>
+
+#include "sync.h"
+
+static void *sync_thread(void *p) {
+ sync();
+ return NULL;
+}
+
+int asynchronous_sync(void) {
+ pthread_attr_t a;
+ pthread_t t;
+ int r;
+
+ /* It kinda sucks that we have to resort to threads to
+ * implement an asynchronous sync(), but well, such is
+ * life.
+ *
+ * Note that issuing this command right before exiting a
+ * process will cause the process to wait for the sync() to
+ * complete. This function hence is nicely asynchronous really
+ * only in long running processes. */
+
+ r = pthread_attr_init(&a);
+ if (r != 0)
+ return -r;
+
+ r = pthread_attr_setdetachstate(&a, PTHREAD_CREATE_DETACHED);
+ if (r != 0) {
+ r = -r;
+ goto finish;
+ }
+
+ r = pthread_create(&t, &a, sync_thread, NULL);
+ if (r != 0) {
+ r = -r;
+ goto finish;
+ }
+
+finish:
+ pthread_attr_destroy(&a);
+ return r;
+}
diff --git a/src/core/sync.h b/src/core/sync.h
new file mode 100644
index 0000000000..eb26c88deb
--- /dev/null
+++ b/src/core/sync.h
@@ -0,0 +1,24 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+int asynchronous_sync(void);
diff --git a/src/core/syscall-list.c b/src/core/syscall-list.c
new file mode 100644
index 0000000000..35216b2a88
--- /dev/null
+++ b/src/core/syscall-list.c
@@ -0,0 +1,57 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/syscall.h>
+#include <string.h>
+
+#include "util.h"
+
+#include "syscall-list.h"
+
+static const struct syscall_name* lookup_syscall(register const char *str,
+ register unsigned int len);
+
+#include "syscall-to-name.h"
+#include "syscall-from-name.h"
+
+const char *syscall_to_name(int id) {
+ id = SYSCALL_TO_INDEX(id);
+ if (id < 0 || id >= (int) ELEMENTSOF(syscall_names))
+ return NULL;
+
+ return syscall_names[id];
+}
+
+int syscall_from_name(const char *name) {
+ const struct syscall_name *sc;
+
+ assert(name);
+
+ sc = lookup_syscall(name, strlen(name));
+ if (!sc)
+ return -1;
+
+ return sc->id;
+}
+
+int syscall_max(void) {
+ return ELEMENTSOF(syscall_names);
+}
diff --git a/src/core/syscall-list.h b/src/core/syscall-list.h
new file mode 100644
index 0000000000..6bb4d91f91
--- /dev/null
+++ b/src/core/syscall-list.h
@@ -0,0 +1,44 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef foosyscalllisthfoo
+#define foosyscalllisthfoo
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#if defined __x86_64__ && defined __ILP32__
+/* The x32 ABI defines all of its syscalls with bit 30 set, which causes
+ issues when attempting to use syscalls as simple indices into an array.
+ Instead, use the syscall id & ~SYSCALL_MASK as the index, and | the
+ internal id with the syscall mask as needed.
+*/
+#include <asm/unistd.h>
+#define SYSCALL_TO_INDEX(x) ((x) & ~__X32_SYSCALL_BIT)
+#define INDEX_TO_SYSCALL(x) ((x) | __X32_SYSCALL_BIT)
+#else
+#define SYSCALL_TO_INDEX(x) (x)
+#define INDEX_TO_SYSCALL(x) (x)
+#endif
+
+const char *syscall_to_name(int id);
+int syscall_from_name(const char *name);
+
+int syscall_max(void);
+
+#endif
diff --git a/src/core/sysfs-show.h b/src/core/sysfs-show.h
new file mode 100644
index 0000000000..9ffd129c48
--- /dev/null
+++ b/src/core/sysfs-show.h
@@ -0,0 +1,24 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+int show_sysfs(const char *seat, const char *prefix, unsigned columns);
diff --git a/src/core/system.conf b/src/core/system.conf
new file mode 100644
index 0000000000..508e0f5fa4
--- /dev/null
+++ b/src/core/system.conf
@@ -0,0 +1,43 @@
+# This file is part of systemd.
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 of the License, or
+# (at your option) any later version.
+#
+# See systemd-system.conf(5) for details
+
+[Manager]
+#LogLevel=info
+#LogTarget=journal-or-kmsg
+#LogColor=yes
+#LogLocation=no
+#DumpCore=yes
+#CrashShell=no
+#ShowStatus=yes
+#CrashChVT=1
+#CPUAffinity=1 2
+#DefaultControllers=cpu
+#DefaultStandardOutput=journal
+#DefaultStandardError=inherit
+#JoinControllers=cpu,cpuacct,cpuset net_cls,net_prio
+#RuntimeWatchdogSec=0
+#ShutdownWatchdogSec=10min
+#CapabilityBoundingSet=
+#TimerSlackNSec=
+#DefaultLimitCPU=
+#DefaultLimitFSIZE=
+#DefaultLimitDATA=
+#DefaultLimitSTACK=
+#DefaultLimitCORE=
+#DefaultLimitRSS=
+#DefaultLimitNOFILE=
+#DefaultLimitAS=
+#DefaultLimitNPROC=
+#DefaultLimitMEMLOCK=
+#DefaultLimitLOCKS=
+#DefaultLimitSIGPENDING=
+#DefaultLimitMSGQUEUE=
+#DefaultLimitNICE=
+#DefaultLimitRTPRIO=
+#DefaultLimitRTTIME=
diff --git a/src/core/systemd.pc.in b/src/core/systemd.pc.in
new file mode 100644
index 0000000000..2f49d5df52
--- /dev/null
+++ b/src/core/systemd.pc.in
@@ -0,0 +1,23 @@
+# This file is part of systemd.
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 of the License, or
+# (at your option) any later version.
+
+prefix=@prefix@
+exec_prefix=@exec_prefix@
+systemdutildir=@rootlibexecdir@
+systemdsystemunitdir=@systemunitdir@
+systemdsystempresetdir=@systempresetdir@
+systemduserunitdir=@userunitdir@
+systemduserpresetdir=@userpresetdir@
+systemdsystemconfdir=@pkgsysconfdir@/system
+systemduserconfdir=@pkgsysconfdir@/user
+systemdsystemunitpath=${systemdsystemconfdir}:/etc/systemd/system:/run/systemd/system:/usr/local/lib/systemd/system:${systemdsystemunitdir}:/usr/lib/systemd/system:/lib/systemd/system
+systemduserunitpath=${systemduserconfdir}:/etc/systemd/user:/run/systemd/user:/usr/local/lib/systemd/user:/usr/local/share/systemd/user:${systemduserunitdir}:/usr/lib/systemd/user:/usr/share/systemd/user
+
+Name: systemd
+Description: systemd System and Service Manager
+URL: @PACKAGE_URL@
+Version: @PACKAGE_VERSION@
diff --git a/src/core/target.c b/src/core/target.c
new file mode 100644
index 0000000000..3fffa0d2f5
--- /dev/null
+++ b/src/core/target.c
@@ -0,0 +1,239 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <signal.h>
+#include <unistd.h>
+
+#include "unit.h"
+#include "target.h"
+#include "load-fragment.h"
+#include "log.h"
+#include "dbus-target.h"
+#include "special.h"
+#include "unit-name.h"
+
+static const UnitActiveState state_translation_table[_TARGET_STATE_MAX] = {
+ [TARGET_DEAD] = UNIT_INACTIVE,
+ [TARGET_ACTIVE] = UNIT_ACTIVE
+};
+
+static void target_set_state(Target *t, TargetState state) {
+ TargetState old_state;
+ assert(t);
+
+ old_state = t->state;
+ t->state = state;
+
+ if (state != old_state)
+ log_debug("%s changed %s -> %s",
+ UNIT(t)->id,
+ target_state_to_string(old_state),
+ target_state_to_string(state));
+
+ unit_notify(UNIT(t), state_translation_table[old_state], state_translation_table[state], true);
+}
+
+static int target_add_default_dependencies(Target *t) {
+
+ static const UnitDependency deps[] = {
+ UNIT_REQUIRES,
+ UNIT_REQUIRES_OVERRIDABLE,
+ UNIT_REQUISITE,
+ UNIT_REQUISITE_OVERRIDABLE,
+ UNIT_WANTS,
+ UNIT_BINDS_TO,
+ UNIT_PART_OF
+ };
+
+ Iterator i;
+ Unit *other;
+ int r;
+ unsigned k;
+
+ assert(t);
+
+ /* Imply ordering for requirement dependencies on target
+ * units. Note that when the user created a contradicting
+ * ordering manually we won't add anything in here to make
+ * sure we don't create a loop. */
+
+ for (k = 0; k < ELEMENTSOF(deps); k++)
+ SET_FOREACH(other, UNIT(t)->dependencies[deps[k]], i) {
+ r = unit_add_default_target_dependency(other, UNIT(t));
+ if (r < 0)
+ return r;
+ }
+
+ /* Make sure targets are unloaded on shutdown */
+ return unit_add_dependency_by_name(UNIT(t), UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
+}
+
+static int target_load(Unit *u) {
+ Target *t = TARGET(u);
+ int r;
+
+ assert(t);
+
+ r = unit_load_fragment_and_dropin(u);
+ if (r < 0)
+ return r;
+
+ /* This is a new unit? Then let's add in some extras */
+ if (u->load_state == UNIT_LOADED && u->default_dependencies) {
+ r = target_add_default_dependencies(t);
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static int target_coldplug(Unit *u) {
+ Target *t = TARGET(u);
+
+ assert(t);
+ assert(t->state == TARGET_DEAD);
+
+ if (t->deserialized_state != t->state)
+ target_set_state(t, t->deserialized_state);
+
+ return 0;
+}
+
+static void target_dump(Unit *u, FILE *f, const char *prefix) {
+ Target *t = TARGET(u);
+
+ assert(t);
+ assert(f);
+
+ fprintf(f,
+ "%sTarget State: %s\n",
+ prefix, target_state_to_string(t->state));
+}
+
+static int target_start(Unit *u) {
+ Target *t = TARGET(u);
+
+ assert(t);
+ assert(t->state == TARGET_DEAD);
+
+ target_set_state(t, TARGET_ACTIVE);
+ return 0;
+}
+
+static int target_stop(Unit *u) {
+ Target *t = TARGET(u);
+
+ assert(t);
+ assert(t->state == TARGET_ACTIVE);
+
+ target_set_state(t, TARGET_DEAD);
+ return 0;
+}
+
+static int target_serialize(Unit *u, FILE *f, FDSet *fds) {
+ Target *s = TARGET(u);
+
+ assert(s);
+ assert(f);
+ assert(fds);
+
+ unit_serialize_item(u, f, "state", target_state_to_string(s->state));
+ return 0;
+}
+
+static int target_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
+ Target *s = TARGET(u);
+
+ assert(u);
+ assert(key);
+ assert(value);
+ assert(fds);
+
+ if (streq(key, "state")) {
+ TargetState state;
+
+ state = target_state_from_string(value);
+ if (state < 0)
+ log_debug("Failed to parse state value %s", value);
+ else
+ s->deserialized_state = state;
+
+ } else
+ log_debug("Unknown serialization key '%s'", key);
+
+ return 0;
+}
+
+_pure_ static UnitActiveState target_active_state(Unit *u) {
+ assert(u);
+
+ return state_translation_table[TARGET(u)->state];
+}
+
+_pure_ static const char *target_sub_state_to_string(Unit *u) {
+ assert(u);
+
+ return target_state_to_string(TARGET(u)->state);
+}
+
+static const char* const target_state_table[_TARGET_STATE_MAX] = {
+ [TARGET_DEAD] = "dead",
+ [TARGET_ACTIVE] = "active"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(target_state, TargetState);
+
+const UnitVTable target_vtable = {
+ .object_size = sizeof(Target),
+ .sections =
+ "Unit\0"
+ "Target\0"
+ "Install\0",
+
+ .load = target_load,
+ .coldplug = target_coldplug,
+
+ .dump = target_dump,
+
+ .start = target_start,
+ .stop = target_stop,
+
+ .serialize = target_serialize,
+ .deserialize_item = target_deserialize_item,
+
+ .active_state = target_active_state,
+ .sub_state_to_string = target_sub_state_to_string,
+
+ .bus_interface = "org.freedesktop.systemd1.Target",
+ .bus_message_handler = bus_target_message_handler,
+
+ .status_message_formats = {
+ .finished_start_job = {
+ [JOB_DONE] = "Reached target %s.",
+ [JOB_DEPENDENCY] = "Dependency failed for %s.",
+ },
+ .finished_stop_job = {
+ [JOB_DONE] = "Stopped target %s.",
+ },
+ },
+};
diff --git a/src/core/target.h b/src/core/target.h
new file mode 100644
index 0000000000..a5398d9e98
--- /dev/null
+++ b/src/core/target.h
@@ -0,0 +1,44 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+typedef struct Target Target;
+
+#include "unit.h"
+
+typedef enum TargetState {
+ TARGET_DEAD,
+ TARGET_ACTIVE,
+ _TARGET_STATE_MAX,
+ _TARGET_STATE_INVALID = -1
+} TargetState;
+
+struct Target {
+ Unit meta;
+
+ TargetState state, deserialized_state;
+};
+
+extern const UnitVTable target_vtable;
+
+const char* target_state_to_string(TargetState i) _const_;
+TargetState target_state_from_string(const char *s) _pure_;
diff --git a/src/core/tcpwrap.c b/src/core/tcpwrap.c
new file mode 100644
index 0000000000..6c630fac60
--- /dev/null
+++ b/src/core/tcpwrap.c
@@ -0,0 +1,68 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <arpa/inet.h>
+#include <netinet/in.h>
+
+#ifdef HAVE_LIBWRAP
+#include <tcpd.h>
+#endif
+
+#include "tcpwrap.h"
+#include "log.h"
+
+bool socket_tcpwrap(int fd, const char *name) {
+#ifdef HAVE_LIBWRAP
+ struct request_info req;
+ union {
+ struct sockaddr sa;
+ struct sockaddr_in in;
+ struct sockaddr_in6 in6;
+ struct sockaddr_un un;
+ struct sockaddr_storage storage;
+ } sa_union;
+ socklen_t l = sizeof(sa_union);
+
+ if (getsockname(fd, &sa_union.sa, &l) < 0)
+ return true;
+
+ if (sa_union.sa.sa_family != AF_INET &&
+ sa_union.sa.sa_family != AF_INET6)
+ return true;
+
+ request_init(&req,
+ RQ_DAEMON, name,
+ RQ_FILE, fd,
+ NULL);
+
+ fromhost(&req);
+
+ if (!hosts_access(&req)) {
+ log_warning("Connection refused by tcpwrap.");
+ return false;
+ }
+
+ log_debug("Connection accepted by tcpwrap.");
+#endif
+ return true;
+}
diff --git a/src/core/tcpwrap.h b/src/core/tcpwrap.h
new file mode 100644
index 0000000000..3353b6596e
--- /dev/null
+++ b/src/core/tcpwrap.h
@@ -0,0 +1,26 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdbool.h>
+
+bool socket_tcpwrap(int fd, const char *name);
diff --git a/src/core/timer.c b/src/core/timer.c
new file mode 100644
index 0000000000..9166c1e2fc
--- /dev/null
+++ b/src/core/timer.c
@@ -0,0 +1,622 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+
+#include "unit.h"
+#include "unit-name.h"
+#include "timer.h"
+#include "dbus-timer.h"
+#include "special.h"
+#include "dbus-common.h"
+
+static const UnitActiveState state_translation_table[_TIMER_STATE_MAX] = {
+ [TIMER_DEAD] = UNIT_INACTIVE,
+ [TIMER_WAITING] = UNIT_ACTIVE,
+ [TIMER_RUNNING] = UNIT_ACTIVE,
+ [TIMER_ELAPSED] = UNIT_ACTIVE,
+ [TIMER_FAILED] = UNIT_FAILED
+};
+
+static void timer_init(Unit *u) {
+ Timer *t = TIMER(u);
+
+ assert(u);
+ assert(u->load_state == UNIT_STUB);
+
+ t->next_elapse_monotonic = (usec_t) -1;
+ t->next_elapse_realtime = (usec_t) -1;
+ watch_init(&t->monotonic_watch);
+ watch_init(&t->realtime_watch);
+}
+
+void timer_free_values(Timer *t) {
+ TimerValue *v;
+
+ assert(t);
+
+ while ((v = t->values)) {
+ LIST_REMOVE(TimerValue, value, t->values, v);
+
+ if (v->calendar_spec)
+ calendar_spec_free(v->calendar_spec);
+
+ free(v);
+ }
+}
+
+static void timer_done(Unit *u) {
+ Timer *t = TIMER(u);
+
+ assert(t);
+
+ timer_free_values(t);
+
+ unit_unwatch_timer(u, &t->monotonic_watch);
+ unit_unwatch_timer(u, &t->realtime_watch);
+}
+
+static int timer_verify(Timer *t) {
+ assert(t);
+
+ if (UNIT(t)->load_state != UNIT_LOADED)
+ return 0;
+
+ if (!t->values) {
+ log_error_unit(UNIT(t)->id,
+ "%s lacks value setting. Refusing.", UNIT(t)->id);
+ return -EINVAL;
+ }
+
+ return 0;
+}
+
+static int timer_add_default_dependencies(Timer *t) {
+ int r;
+
+ assert(t);
+
+ r = unit_add_dependency_by_name(UNIT(t), UNIT_BEFORE, SPECIAL_TIMERS_TARGET, NULL, true);
+ if (r < 0)
+ return r;
+
+ if (UNIT(t)->manager->running_as == SYSTEMD_SYSTEM) {
+ r = unit_add_two_dependencies_by_name(UNIT(t), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, NULL, true);
+ if (r < 0)
+ return r;
+ }
+
+ return unit_add_two_dependencies_by_name(UNIT(t), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
+}
+
+static int timer_load(Unit *u) {
+ Timer *t = TIMER(u);
+ int r;
+
+ assert(u);
+ assert(u->load_state == UNIT_STUB);
+
+ r = unit_load_fragment_and_dropin(u);
+ if (r < 0)
+ return r;
+
+ if (u->load_state == UNIT_LOADED) {
+
+ if (set_isempty(u->dependencies[UNIT_TRIGGERS])) {
+ Unit *x;
+
+ r = unit_load_related_unit(u, ".service", &x);
+ if (r < 0)
+ return r;
+
+ r = unit_add_two_dependencies(u, UNIT_BEFORE, UNIT_TRIGGERS, x, true);
+ if (r < 0)
+ return r;
+ }
+
+ if (UNIT(t)->default_dependencies) {
+ r = timer_add_default_dependencies(t);
+ if (r < 0)
+ return r;
+ }
+ }
+
+ return timer_verify(t);
+}
+
+static void timer_dump(Unit *u, FILE *f, const char *prefix) {
+ Timer *t = TIMER(u);
+ Unit *trigger;
+ TimerValue *v;
+
+ trigger = UNIT_TRIGGER(u);
+
+ fprintf(f,
+ "%sTimer State: %s\n"
+ "%sResult: %s\n"
+ "%sUnit: %s\n",
+ prefix, timer_state_to_string(t->state),
+ prefix, timer_result_to_string(t->result),
+ prefix, trigger ? trigger->id : "n/a");
+
+ LIST_FOREACH(value, v, t->values) {
+
+ if (v->base == TIMER_CALENDAR) {
+ _cleanup_free_ char *p = NULL;
+
+ calendar_spec_to_string(v->calendar_spec, &p);
+
+ fprintf(f,
+ "%s%s: %s\n",
+ prefix,
+ timer_base_to_string(v->base),
+ strna(p));
+ } else {
+ char timespan1[FORMAT_TIMESPAN_MAX];
+
+ fprintf(f,
+ "%s%s: %s\n",
+ prefix,
+ timer_base_to_string(v->base),
+ strna(format_timespan(timespan1, sizeof(timespan1), v->value, 0)));
+ }
+ }
+}
+
+static void timer_set_state(Timer *t, TimerState state) {
+ TimerState old_state;
+ assert(t);
+
+ old_state = t->state;
+ t->state = state;
+
+ if (state != TIMER_WAITING) {
+ unit_unwatch_timer(UNIT(t), &t->monotonic_watch);
+ unit_unwatch_timer(UNIT(t), &t->realtime_watch);
+ }
+
+ if (state != old_state)
+ log_debug_unit(UNIT(t)->id,
+ "%s changed %s -> %s", UNIT(t)->id,
+ timer_state_to_string(old_state),
+ timer_state_to_string(state));
+
+ unit_notify(UNIT(t), state_translation_table[old_state], state_translation_table[state], true);
+}
+
+static void timer_enter_waiting(Timer *t, bool initial);
+
+static int timer_coldplug(Unit *u) {
+ Timer *t = TIMER(u);
+
+ assert(t);
+ assert(t->state == TIMER_DEAD);
+
+ if (t->deserialized_state != t->state) {
+
+ if (t->deserialized_state == TIMER_WAITING)
+ timer_enter_waiting(t, false);
+ else
+ timer_set_state(t, t->deserialized_state);
+ }
+
+ return 0;
+}
+
+static void timer_enter_dead(Timer *t, TimerResult f) {
+ assert(t);
+
+ if (f != TIMER_SUCCESS)
+ t->result = f;
+
+ timer_set_state(t, t->result != TIMER_SUCCESS ? TIMER_FAILED : TIMER_DEAD);
+}
+
+static void timer_enter_waiting(Timer *t, bool initial) {
+ TimerValue *v;
+ usec_t base = 0;
+ dual_timestamp ts;
+ bool found_monotonic = false, found_realtime = false;
+ int r;
+
+ dual_timestamp_get(&ts);
+ t->next_elapse_monotonic = t->next_elapse_realtime = 0;
+
+ LIST_FOREACH(value, v, t->values) {
+
+ if (v->disabled)
+ continue;
+
+ if (v->base == TIMER_CALENDAR) {
+
+ r = calendar_spec_next_usec(v->calendar_spec, ts.realtime, &v->next_elapse);
+ if (r < 0)
+ continue;
+
+ if (!found_realtime)
+ t->next_elapse_realtime = v->next_elapse;
+ else
+ t->next_elapse_realtime = MIN(t->next_elapse_realtime, v->next_elapse);
+
+ found_realtime = true;
+
+ } else {
+ switch (v->base) {
+
+ case TIMER_ACTIVE:
+ if (state_translation_table[t->state] == UNIT_ACTIVE)
+ base = UNIT(t)->inactive_exit_timestamp.monotonic;
+ else
+ base = ts.monotonic;
+ break;
+
+ case TIMER_BOOT:
+ /* CLOCK_MONOTONIC equals the uptime on Linux */
+ base = 0;
+ break;
+
+ case TIMER_STARTUP:
+ base = UNIT(t)->manager->userspace_timestamp.monotonic;
+ break;
+
+ case TIMER_UNIT_ACTIVE:
+
+ base = UNIT_TRIGGER(UNIT(t))->inactive_exit_timestamp.monotonic;
+
+ if (base <= 0)
+ base = t->last_trigger_monotonic;
+
+ if (base <= 0)
+ continue;
+
+ break;
+
+ case TIMER_UNIT_INACTIVE:
+
+ base = UNIT_TRIGGER(UNIT(t))->inactive_enter_timestamp.monotonic;
+
+ if (base <= 0)
+ base = t->last_trigger_monotonic;
+
+ if (base <= 0)
+ continue;
+
+ break;
+
+ default:
+ assert_not_reached("Unknown timer base");
+ }
+
+ v->next_elapse = base + v->value;
+
+ if (!initial &&
+ v->next_elapse < ts.monotonic &&
+ (v->base == TIMER_ACTIVE || v->base == TIMER_BOOT || v->base == TIMER_STARTUP)) {
+ /* This is a one time trigger, disable it now */
+ v->disabled = true;
+ continue;
+ }
+
+ if (!found_monotonic)
+ t->next_elapse_monotonic = v->next_elapse;
+ else
+ t->next_elapse_monotonic = MIN(t->next_elapse_monotonic, v->next_elapse);
+
+ found_monotonic = true;
+ }
+ }
+
+ if (!found_monotonic && !found_realtime) {
+ log_debug_unit(UNIT(t)->id, "%s: Timer is elapsed.", UNIT(t)->id);
+ timer_set_state(t, TIMER_ELAPSED);
+ return;
+ }
+
+ if (found_monotonic) {
+ char buf[FORMAT_TIMESPAN_MAX];
+ log_debug_unit(UNIT(t)->id,
+ "%s: Monotonic timer elapses in %s.",
+ UNIT(t)->id,
+ format_timespan(buf, sizeof(buf), t->next_elapse_monotonic > ts.monotonic ? t->next_elapse_monotonic - ts.monotonic : 0, 0));
+
+ r = unit_watch_timer(UNIT(t), CLOCK_MONOTONIC, false, t->next_elapse_monotonic, &t->monotonic_watch);
+ if (r < 0)
+ goto fail;
+ } else
+ unit_unwatch_timer(UNIT(t), &t->monotonic_watch);
+
+ if (found_realtime) {
+ char buf[FORMAT_TIMESTAMP_MAX];
+ log_debug_unit(UNIT(t)->id,
+ "%s: Realtime timer elapses at %s.",
+ UNIT(t)->id,
+ format_timestamp(buf, sizeof(buf), t->next_elapse_realtime));
+
+ r = unit_watch_timer(UNIT(t), CLOCK_REALTIME, false, t->next_elapse_realtime, &t->realtime_watch);
+ if (r < 0)
+ goto fail;
+ } else
+ unit_unwatch_timer(UNIT(t), &t->realtime_watch);
+
+ timer_set_state(t, TIMER_WAITING);
+ return;
+
+fail:
+ log_warning_unit(UNIT(t)->id,
+ "%s failed to enter waiting state: %s",
+ UNIT(t)->id, strerror(-r));
+ timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
+}
+
+static void timer_enter_running(Timer *t) {
+ DBusError error;
+ int r;
+
+ assert(t);
+ dbus_error_init(&error);
+
+ /* Don't start job if we are supposed to go down */
+ if (unit_stop_pending(UNIT(t)))
+ return;
+
+ r = manager_add_job(UNIT(t)->manager, JOB_START, UNIT_TRIGGER(UNIT(t)),
+ JOB_REPLACE, true, &error, NULL);
+ if (r < 0)
+ goto fail;
+
+ t->last_trigger_monotonic = now(CLOCK_MONOTONIC);
+
+ timer_set_state(t, TIMER_RUNNING);
+ return;
+
+fail:
+ log_warning_unit(UNIT(t)->id,
+ "%s failed to queue unit startup job: %s",
+ UNIT(t)->id, bus_error(&error, r));
+ timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
+
+ dbus_error_free(&error);
+}
+
+static int timer_start(Unit *u) {
+ Timer *t = TIMER(u);
+
+ assert(t);
+ assert(t->state == TIMER_DEAD || t->state == TIMER_FAILED);
+
+ if (UNIT_TRIGGER(u)->load_state != UNIT_LOADED)
+ return -ENOENT;
+
+ t->result = TIMER_SUCCESS;
+ timer_enter_waiting(t, true);
+ return 0;
+}
+
+static int timer_stop(Unit *u) {
+ Timer *t = TIMER(u);
+
+ assert(t);
+ assert(t->state == TIMER_WAITING || t->state == TIMER_RUNNING || t->state == TIMER_ELAPSED);
+
+ timer_enter_dead(t, TIMER_SUCCESS);
+ return 0;
+}
+
+static int timer_serialize(Unit *u, FILE *f, FDSet *fds) {
+ Timer *t = TIMER(u);
+
+ assert(u);
+ assert(f);
+ assert(fds);
+
+ unit_serialize_item(u, f, "state", timer_state_to_string(t->state));
+ unit_serialize_item(u, f, "result", timer_result_to_string(t->result));
+
+ return 0;
+}
+
+static int timer_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
+ Timer *t = TIMER(u);
+
+ assert(u);
+ assert(key);
+ assert(value);
+ assert(fds);
+
+ if (streq(key, "state")) {
+ TimerState state;
+
+ state = timer_state_from_string(value);
+ if (state < 0)
+ log_debug_unit(u->id, "Failed to parse state value %s", value);
+ else
+ t->deserialized_state = state;
+ } else if (streq(key, "result")) {
+ TimerResult f;
+
+ f = timer_result_from_string(value);
+ if (f < 0)
+ log_debug_unit(u->id, "Failed to parse result value %s", value);
+ else if (f != TIMER_SUCCESS)
+ t->result = f;
+
+ } else
+ log_debug_unit(u->id, "Unknown serialization key '%s'", key);
+
+ return 0;
+}
+
+_pure_ static UnitActiveState timer_active_state(Unit *u) {
+ assert(u);
+
+ return state_translation_table[TIMER(u)->state];
+}
+
+_pure_ static const char *timer_sub_state_to_string(Unit *u) {
+ assert(u);
+
+ return timer_state_to_string(TIMER(u)->state);
+}
+
+static void timer_timer_event(Unit *u, uint64_t elapsed, Watch *w) {
+ Timer *t = TIMER(u);
+
+ assert(t);
+ assert(elapsed == 1);
+
+ if (t->state != TIMER_WAITING)
+ return;
+
+ log_debug_unit(u->id, "Timer elapsed on %s", u->id);
+ timer_enter_running(t);
+}
+
+static void timer_trigger_notify(Unit *u, Unit *other) {
+ Timer *t = TIMER(u);
+ TimerValue *v;
+
+ assert(u);
+ assert(other);
+
+ if (other->load_state != UNIT_LOADED)
+ return;
+
+ /* Reenable all timers that depend on unit state */
+ LIST_FOREACH(value, v, t->values)
+ if (v->base == TIMER_UNIT_ACTIVE ||
+ v->base == TIMER_UNIT_INACTIVE)
+ v->disabled = false;
+
+ switch (t->state) {
+
+ case TIMER_WAITING:
+ case TIMER_ELAPSED:
+
+ /* Recalculate sleep time */
+ timer_enter_waiting(t, false);
+ break;
+
+ case TIMER_RUNNING:
+
+ if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other))) {
+ log_debug_unit(UNIT(t)->id,
+ "%s got notified about unit deactivation.",
+ UNIT(t)->id);
+ timer_enter_waiting(t, false);
+ }
+ break;
+
+ case TIMER_DEAD:
+ case TIMER_FAILED:
+ break;
+
+ default:
+ assert_not_reached("Unknown timer state");
+ }
+}
+
+static void timer_reset_failed(Unit *u) {
+ Timer *t = TIMER(u);
+
+ assert(t);
+
+ if (t->state == TIMER_FAILED)
+ timer_set_state(t, TIMER_DEAD);
+
+ t->result = TIMER_SUCCESS;
+}
+
+static void timer_time_change(Unit *u) {
+ Timer *t = TIMER(u);
+
+ assert(u);
+
+ if (t->state != TIMER_WAITING)
+ return;
+
+ log_debug_unit(u->id,
+ "%s: time change, recalculating next elapse.", u->id);
+ timer_enter_waiting(t, false);
+}
+
+static const char* const timer_state_table[_TIMER_STATE_MAX] = {
+ [TIMER_DEAD] = "dead",
+ [TIMER_WAITING] = "waiting",
+ [TIMER_RUNNING] = "running",
+ [TIMER_ELAPSED] = "elapsed",
+ [TIMER_FAILED] = "failed"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(timer_state, TimerState);
+
+static const char* const timer_base_table[_TIMER_BASE_MAX] = {
+ [TIMER_ACTIVE] = "OnActiveSec",
+ [TIMER_BOOT] = "OnBootSec",
+ [TIMER_STARTUP] = "OnStartupSec",
+ [TIMER_UNIT_ACTIVE] = "OnUnitActiveSec",
+ [TIMER_UNIT_INACTIVE] = "OnUnitInactiveSec",
+ [TIMER_CALENDAR] = "OnCalendar"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(timer_base, TimerBase);
+
+static const char* const timer_result_table[_TIMER_RESULT_MAX] = {
+ [TIMER_SUCCESS] = "success",
+ [TIMER_FAILURE_RESOURCES] = "resources"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(timer_result, TimerResult);
+
+const UnitVTable timer_vtable = {
+ .object_size = sizeof(Timer),
+ .sections =
+ "Unit\0"
+ "Timer\0"
+ "Install\0",
+
+ .init = timer_init,
+ .done = timer_done,
+ .load = timer_load,
+
+ .coldplug = timer_coldplug,
+
+ .dump = timer_dump,
+
+ .start = timer_start,
+ .stop = timer_stop,
+
+ .serialize = timer_serialize,
+ .deserialize_item = timer_deserialize_item,
+
+ .active_state = timer_active_state,
+ .sub_state_to_string = timer_sub_state_to_string,
+
+ .timer_event = timer_timer_event,
+
+ .trigger_notify = timer_trigger_notify,
+
+ .reset_failed = timer_reset_failed,
+ .time_change = timer_time_change,
+
+ .bus_interface = "org.freedesktop.systemd1.Timer",
+ .bus_message_handler = bus_timer_message_handler,
+ .bus_invalidating_properties = bus_timer_invalidating_properties
+};
diff --git a/src/core/timer.h b/src/core/timer.h
new file mode 100644
index 0000000000..4168553e9d
--- /dev/null
+++ b/src/core/timer.h
@@ -0,0 +1,97 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+typedef struct Timer Timer;
+
+#include "unit.h"
+#include "calendarspec.h"
+
+typedef enum TimerState {
+ TIMER_DEAD,
+ TIMER_WAITING,
+ TIMER_RUNNING,
+ TIMER_ELAPSED,
+ TIMER_FAILED,
+ _TIMER_STATE_MAX,
+ _TIMER_STATE_INVALID = -1
+} TimerState;
+
+typedef enum TimerBase {
+ TIMER_ACTIVE,
+ TIMER_BOOT,
+ TIMER_STARTUP,
+ TIMER_UNIT_ACTIVE,
+ TIMER_UNIT_INACTIVE,
+ TIMER_CALENDAR,
+ _TIMER_BASE_MAX,
+ _TIMER_BASE_INVALID = -1
+} TimerBase;
+
+typedef struct TimerValue {
+ TimerBase base;
+ bool disabled;
+ clockid_t clock_id;
+
+ usec_t value; /* only for monotonic events */
+ CalendarSpec *calendar_spec; /* only for calendar events */
+ usec_t next_elapse;
+
+ LIST_FIELDS(struct TimerValue, value);
+} TimerValue;
+
+typedef enum TimerResult {
+ TIMER_SUCCESS,
+ TIMER_FAILURE_RESOURCES,
+ _TIMER_RESULT_MAX,
+ _TIMER_RESULT_INVALID = -1
+} TimerResult;
+
+struct Timer {
+ Unit meta;
+
+ LIST_HEAD(TimerValue, values);
+ usec_t next_elapse_monotonic;
+ usec_t next_elapse_realtime;
+
+ TimerState state, deserialized_state;
+
+ Watch monotonic_watch;
+ Watch realtime_watch;
+
+ TimerResult result;
+
+ usec_t last_trigger_monotonic;
+};
+
+void timer_free_values(Timer *t);
+
+extern const UnitVTable timer_vtable;
+
+const char *timer_state_to_string(TimerState i) _const_;
+TimerState timer_state_from_string(const char *s) _pure_;
+
+const char *timer_base_to_string(TimerBase i) _const_;
+TimerBase timer_base_from_string(const char *s) _pure_;
+
+const char* timer_result_to_string(TimerResult i) _const_;
+TimerResult timer_result_from_string(const char *s) _pure_;
diff --git a/src/core/transaction.c b/src/core/transaction.c
new file mode 100644
index 0000000000..fa97b69755
--- /dev/null
+++ b/src/core/transaction.c
@@ -0,0 +1,1132 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <unistd.h>
+#include <fcntl.h>
+
+#include "transaction.h"
+#include "bus-errors.h"
+#include "dbus-common.h"
+
+static void transaction_unlink_job(Transaction *tr, Job *j, bool delete_dependencies);
+
+static void transaction_delete_job(Transaction *tr, Job *j, bool delete_dependencies) {
+ assert(tr);
+ assert(j);
+
+ /* Deletes one job from the transaction */
+
+ transaction_unlink_job(tr, j, delete_dependencies);
+
+ job_free(j);
+}
+
+static void transaction_delete_unit(Transaction *tr, Unit *u) {
+ Job *j;
+
+ /* Deletes all jobs associated with a certain unit from the
+ * transaction */
+
+ while ((j = hashmap_get(tr->jobs, u)))
+ transaction_delete_job(tr, j, true);
+}
+
+void transaction_abort(Transaction *tr) {
+ Job *j;
+
+ assert(tr);
+
+ while ((j = hashmap_first(tr->jobs)))
+ transaction_delete_job(tr, j, false);
+
+ assert(hashmap_isempty(tr->jobs));
+}
+
+static void transaction_find_jobs_that_matter_to_anchor(Job *j, unsigned generation) {
+ JobDependency *l;
+
+ /* A recursive sweep through the graph that marks all units
+ * that matter to the anchor job, i.e. are directly or
+ * indirectly a dependency of the anchor job via paths that
+ * are fully marked as mattering. */
+
+ j->matters_to_anchor = true;
+ j->generation = generation;
+
+ LIST_FOREACH(subject, l, j->subject_list) {
+
+ /* This link does not matter */
+ if (!l->matters)
+ continue;
+
+ /* This unit has already been marked */
+ if (l->object->generation == generation)
+ continue;
+
+ transaction_find_jobs_that_matter_to_anchor(l->object, generation);
+ }
+}
+
+static void transaction_merge_and_delete_job(Transaction *tr, Job *j, Job *other, JobType t) {
+ JobDependency *l, *last;
+
+ assert(j);
+ assert(other);
+ assert(j->unit == other->unit);
+ assert(!j->installed);
+
+ /* Merges 'other' into 'j' and then deletes 'other'. */
+
+ j->type = t;
+ j->state = JOB_WAITING;
+ j->override = j->override || other->override;
+ j->irreversible = j->irreversible || other->irreversible;
+
+ j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
+
+ /* Patch us in as new owner of the JobDependency objects */
+ last = NULL;
+ LIST_FOREACH(subject, l, other->subject_list) {
+ assert(l->subject == other);
+ l->subject = j;
+ last = l;
+ }
+
+ /* Merge both lists */
+ if (last) {
+ last->subject_next = j->subject_list;
+ if (j->subject_list)
+ j->subject_list->subject_prev = last;
+ j->subject_list = other->subject_list;
+ }
+
+ /* Patch us in as new owner of the JobDependency objects */
+ last = NULL;
+ LIST_FOREACH(object, l, other->object_list) {
+ assert(l->object == other);
+ l->object = j;
+ last = l;
+ }
+
+ /* Merge both lists */
+ if (last) {
+ last->object_next = j->object_list;
+ if (j->object_list)
+ j->object_list->object_prev = last;
+ j->object_list = other->object_list;
+ }
+
+ /* Kill the other job */
+ other->subject_list = NULL;
+ other->object_list = NULL;
+ transaction_delete_job(tr, other, true);
+}
+
+_pure_ static bool job_is_conflicted_by(Job *j) {
+ JobDependency *l;
+
+ assert(j);
+
+ /* Returns true if this job is pulled in by a least one
+ * ConflictedBy dependency. */
+
+ LIST_FOREACH(object, l, j->object_list)
+ if (l->conflicts)
+ return true;
+
+ return false;
+}
+
+static int delete_one_unmergeable_job(Transaction *tr, Job *j) {
+ Job *k;
+
+ assert(j);
+
+ /* Tries to delete one item in the linked list
+ * j->transaction_next->transaction_next->... that conflicts
+ * with another one, in an attempt to make an inconsistent
+ * transaction work. */
+
+ /* We rely here on the fact that if a merged with b does not
+ * merge with c, either a or b merge with c neither */
+ LIST_FOREACH(transaction, j, j)
+ LIST_FOREACH(transaction, k, j->transaction_next) {
+ Job *d;
+
+ /* Is this one mergeable? Then skip it */
+ if (job_type_is_mergeable(j->type, k->type))
+ continue;
+
+ /* Ok, we found two that conflict, let's see if we can
+ * drop one of them */
+ if (!j->matters_to_anchor && !k->matters_to_anchor) {
+
+ /* Both jobs don't matter, so let's
+ * find the one that is smarter to
+ * remove. Let's think positive and
+ * rather remove stops then starts --
+ * except if something is being
+ * stopped because it is conflicted by
+ * another unit in which case we
+ * rather remove the start. */
+
+ log_debug_unit(j->unit->id,
+ "Looking at job %s/%s conflicted_by=%s",
+ j->unit->id, job_type_to_string(j->type),
+ yes_no(j->type == JOB_STOP && job_is_conflicted_by(j)));
+ log_debug_unit(k->unit->id,
+ "Looking at job %s/%s conflicted_by=%s",
+ k->unit->id, job_type_to_string(k->type),
+ yes_no(k->type == JOB_STOP && job_is_conflicted_by(k)));
+
+ if (j->type == JOB_STOP) {
+
+ if (job_is_conflicted_by(j))
+ d = k;
+ else
+ d = j;
+
+ } else if (k->type == JOB_STOP) {
+
+ if (job_is_conflicted_by(k))
+ d = j;
+ else
+ d = k;
+ } else
+ d = j;
+
+ } else if (!j->matters_to_anchor)
+ d = j;
+ else if (!k->matters_to_anchor)
+ d = k;
+ else
+ return -ENOEXEC;
+
+ /* Ok, we can drop one, so let's do so. */
+ log_debug_unit(d->unit->id,
+ "Fixing conflicting jobs by deleting job %s/%s",
+ d->unit->id, job_type_to_string(d->type));
+ transaction_delete_job(tr, d, true);
+ return 0;
+ }
+
+ return -EINVAL;
+}
+
+static int transaction_merge_jobs(Transaction *tr, DBusError *e) {
+ Job *j;
+ Iterator i;
+ int r;
+
+ assert(tr);
+
+ /* First step, check whether any of the jobs for one specific
+ * task conflict. If so, try to drop one of them. */
+ HASHMAP_FOREACH(j, tr->jobs, i) {
+ JobType t;
+ Job *k;
+
+ t = j->type;
+ LIST_FOREACH(transaction, k, j->transaction_next) {
+ if (job_type_merge_and_collapse(&t, k->type, j->unit) >= 0)
+ continue;
+
+ /* OK, we could not merge all jobs for this
+ * action. Let's see if we can get rid of one
+ * of them */
+
+ r = delete_one_unmergeable_job(tr, j);
+ if (r >= 0)
+ /* Ok, we managed to drop one, now
+ * let's ask our callers to call us
+ * again after garbage collecting */
+ return -EAGAIN;
+
+ /* We couldn't merge anything. Failure */
+ dbus_set_error(e, BUS_ERROR_TRANSACTION_JOBS_CONFLICTING, "Transaction contains conflicting jobs '%s' and '%s' for %s. Probably contradicting requirement dependencies configured.",
+ job_type_to_string(t), job_type_to_string(k->type), k->unit->id);
+ return r;
+ }
+ }
+
+ /* Second step, merge the jobs. */
+ HASHMAP_FOREACH(j, tr->jobs, i) {
+ JobType t = j->type;
+ Job *k;
+
+ /* Merge all transaction jobs for j->unit */
+ LIST_FOREACH(transaction, k, j->transaction_next)
+ assert_se(job_type_merge_and_collapse(&t, k->type, j->unit) == 0);
+
+ while ((k = j->transaction_next)) {
+ if (tr->anchor_job == k) {
+ transaction_merge_and_delete_job(tr, k, j, t);
+ j = k;
+ } else
+ transaction_merge_and_delete_job(tr, j, k, t);
+ }
+
+ assert(!j->transaction_next);
+ assert(!j->transaction_prev);
+ }
+
+ return 0;
+}
+
+static void transaction_drop_redundant(Transaction *tr) {
+ Job *j;
+ Iterator i;
+
+ /* Goes through the transaction and removes all jobs of the units
+ * whose jobs are all noops. If not all of a unit's jobs are
+ * redundant, they are kept. */
+
+ assert(tr);
+
+rescan:
+ HASHMAP_FOREACH(j, tr->jobs, i) {
+ Job *k;
+
+ LIST_FOREACH(transaction, k, j) {
+
+ if (tr->anchor_job == k ||
+ !job_type_is_redundant(k->type, unit_active_state(k->unit)) ||
+ (k->unit->job && job_type_is_conflicting(k->type, k->unit->job->type)))
+ goto next_unit;
+ }
+
+ /* log_debug("Found redundant job %s/%s, dropping.", j->unit->id, job_type_to_string(j->type)); */
+ transaction_delete_job(tr, j, false);
+ goto rescan;
+ next_unit:;
+ }
+}
+
+_pure_ static bool unit_matters_to_anchor(Unit *u, Job *j) {
+ assert(u);
+ assert(!j->transaction_prev);
+
+ /* Checks whether at least one of the jobs for this unit
+ * matters to the anchor. */
+
+ LIST_FOREACH(transaction, j, j)
+ if (j->matters_to_anchor)
+ return true;
+
+ return false;
+}
+
+static int transaction_verify_order_one(Transaction *tr, Job *j, Job *from, unsigned generation, DBusError *e) {
+ Iterator i;
+ Unit *u;
+ int r;
+
+ assert(tr);
+ assert(j);
+ assert(!j->transaction_prev);
+
+ /* Does a recursive sweep through the ordering graph, looking
+ * for a cycle. If we find cycle we try to break it. */
+
+ /* Have we seen this before? */
+ if (j->generation == generation) {
+ Job *k, *delete;
+
+ /* If the marker is NULL we have been here already and
+ * decided the job was loop-free from here. Hence
+ * shortcut things and return right-away. */
+ if (!j->marker)
+ return 0;
+
+ /* So, the marker is not NULL and we already have been
+ * here. We have a cycle. Let's try to break it. We go
+ * backwards in our path and try to find a suitable
+ * job to remove. We use the marker to find our way
+ * back, since smart how we are we stored our way back
+ * in there. */
+ log_warning_unit(j->unit->id,
+ "Found ordering cycle on %s/%s",
+ j->unit->id, job_type_to_string(j->type));
+
+ delete = NULL;
+ for (k = from; k; k = ((k->generation == generation && k->marker != k) ? k->marker : NULL)) {
+
+ /* logging for j not k here here to provide consistent narrative */
+ log_info_unit(j->unit->id,
+ "Walked on cycle path to %s/%s",
+ k->unit->id, job_type_to_string(k->type));
+
+ if (!delete &&
+ !unit_matters_to_anchor(k->unit, k)) {
+ /* Ok, we can drop this one, so let's
+ * do so. */
+ delete = k;
+ }
+
+ /* Check if this in fact was the beginning of
+ * the cycle */
+ if (k == j)
+ break;
+ }
+
+
+ if (delete) {
+ /* logging for j not k here here to provide consistent narrative */
+ log_warning_unit(j->unit->id,
+ "Breaking ordering cycle by deleting job %s/%s",
+ delete->unit->id, job_type_to_string(delete->type));
+ log_error_unit(delete->unit->id,
+ "Job %s/%s deleted to break ordering cycle starting with %s/%s",
+ delete->unit->id, job_type_to_string(delete->type),
+ j->unit->id, job_type_to_string(j->type));
+ unit_status_printf(delete->unit, ANSI_HIGHLIGHT_RED_ON " SKIP " ANSI_HIGHLIGHT_OFF,
+ "Ordering cycle found, skipping %s");
+ transaction_delete_unit(tr, delete->unit);
+ return -EAGAIN;
+ }
+
+ log_error("Unable to break cycle");
+
+ dbus_set_error(e, BUS_ERROR_TRANSACTION_ORDER_IS_CYCLIC,
+ "Transaction order is cyclic. See system logs for details.");
+ return -ENOEXEC;
+ }
+
+ /* Make the marker point to where we come from, so that we can
+ * find our way backwards if we want to break a cycle. We use
+ * a special marker for the beginning: we point to
+ * ourselves. */
+ j->marker = from ? from : j;
+ j->generation = generation;
+
+ /* We assume that the dependencies are bidirectional, and
+ * hence can ignore UNIT_AFTER */
+ SET_FOREACH(u, j->unit->dependencies[UNIT_BEFORE], i) {
+ Job *o;
+
+ /* Is there a job for this unit? */
+ o = hashmap_get(tr->jobs, u);
+ if (!o) {
+ /* Ok, there is no job for this in the
+ * transaction, but maybe there is already one
+ * running? */
+ o = u->job;
+ if (!o)
+ continue;
+ }
+
+ r = transaction_verify_order_one(tr, o, j, generation, e);
+ if (r < 0)
+ return r;
+ }
+
+ /* Ok, let's backtrack, and remember that this entry is not on
+ * our path anymore. */
+ j->marker = NULL;
+
+ return 0;
+}
+
+static int transaction_verify_order(Transaction *tr, unsigned *generation, DBusError *e) {
+ Job *j;
+ int r;
+ Iterator i;
+ unsigned g;
+
+ assert(tr);
+ assert(generation);
+
+ /* Check if the ordering graph is cyclic. If it is, try to fix
+ * that up by dropping one of the jobs. */
+
+ g = (*generation)++;
+
+ HASHMAP_FOREACH(j, tr->jobs, i)
+ if ((r = transaction_verify_order_one(tr, j, NULL, g, e)) < 0)
+ return r;
+
+ return 0;
+}
+
+static void transaction_collect_garbage(Transaction *tr) {
+ Iterator i;
+ Job *j;
+
+ assert(tr);
+
+ /* Drop jobs that are not required by any other job */
+
+rescan:
+ HASHMAP_FOREACH(j, tr->jobs, i) {
+ if (tr->anchor_job == j || j->object_list) {
+ /* log_debug("Keeping job %s/%s because of %s/%s", */
+ /* j->unit->id, job_type_to_string(j->type), */
+ /* j->object_list->subject ? j->object_list->subject->unit->id : "root", */
+ /* j->object_list->subject ? job_type_to_string(j->object_list->subject->type) : "root"); */
+ continue;
+ }
+
+ /* log_debug("Garbage collecting job %s/%s", j->unit->id, job_type_to_string(j->type)); */
+ transaction_delete_job(tr, j, true);
+ goto rescan;
+ }
+}
+
+static int transaction_is_destructive(Transaction *tr, JobMode mode, DBusError *e) {
+ Iterator i;
+ Job *j;
+
+ assert(tr);
+
+ /* Checks whether applying this transaction means that
+ * existing jobs would be replaced */
+
+ HASHMAP_FOREACH(j, tr->jobs, i) {
+
+ /* Assume merged */
+ assert(!j->transaction_prev);
+ assert(!j->transaction_next);
+
+ if (j->unit->job && (mode == JOB_FAIL || j->unit->job->irreversible) &&
+ !job_type_is_superset(j->type, j->unit->job->type)) {
+
+ dbus_set_error(e, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE, "Transaction is destructive.");
+ return -EEXIST;
+ }
+ }
+
+ return 0;
+}
+
+static void transaction_minimize_impact(Transaction *tr) {
+ Job *j;
+ Iterator i;
+
+ assert(tr);
+
+ /* Drops all unnecessary jobs that reverse already active jobs
+ * or that stop a running service. */
+
+rescan:
+ HASHMAP_FOREACH(j, tr->jobs, i) {
+ LIST_FOREACH(transaction, j, j) {
+ bool stops_running_service, changes_existing_job;
+
+ /* If it matters, we shouldn't drop it */
+ if (j->matters_to_anchor)
+ continue;
+
+ /* Would this stop a running service?
+ * Would this change an existing job?
+ * If so, let's drop this entry */
+
+ stops_running_service =
+ j->type == JOB_STOP && UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j->unit));
+
+ changes_existing_job =
+ j->unit->job &&
+ job_type_is_conflicting(j->type, j->unit->job->type);
+
+ if (!stops_running_service && !changes_existing_job)
+ continue;
+
+ if (stops_running_service)
+ log_debug_unit(j->unit->id,
+ "%s/%s would stop a running service.",
+ j->unit->id, job_type_to_string(j->type));
+
+ if (changes_existing_job)
+ log_debug_unit(j->unit->id,
+ "%s/%s would change existing job.",
+ j->unit->id, job_type_to_string(j->type));
+
+ /* Ok, let's get rid of this */
+ log_debug_unit(j->unit->id,
+ "Deleting %s/%s to minimize impact.",
+ j->unit->id, job_type_to_string(j->type));
+
+ transaction_delete_job(tr, j, true);
+ goto rescan;
+ }
+ }
+}
+
+static int transaction_apply(Transaction *tr, Manager *m, JobMode mode) {
+ Iterator i;
+ Job *j;
+ int r;
+
+ /* Moves the transaction jobs to the set of active jobs */
+
+ if (mode == JOB_ISOLATE) {
+
+ /* When isolating first kill all installed jobs which
+ * aren't part of the new transaction */
+ HASHMAP_FOREACH(j, m->jobs, i) {
+ assert(j->installed);
+
+ if (hashmap_get(tr->jobs, j->unit))
+ continue;
+
+ /* Not invalidating recursively. Avoids triggering
+ * OnFailure= actions of dependent jobs. Also avoids
+ * invalidating our iterator. */
+ job_finish_and_invalidate(j, JOB_CANCELED, false);
+ }
+ }
+
+ HASHMAP_FOREACH(j, tr->jobs, i) {
+ /* Assume merged */
+ assert(!j->transaction_prev);
+ assert(!j->transaction_next);
+
+ r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j);
+ if (r < 0)
+ goto rollback;
+ }
+
+ while ((j = hashmap_steal_first(tr->jobs))) {
+ Job *installed_job;
+
+ /* Clean the job dependencies */
+ transaction_unlink_job(tr, j, false);
+
+ installed_job = job_install(j);
+ if (installed_job != j) {
+ /* j has been merged into a previously installed job */
+ if (tr->anchor_job == j)
+ tr->anchor_job = installed_job;
+ hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
+ job_free(j);
+ j = installed_job;
+ }
+
+ job_add_to_run_queue(j);
+ job_add_to_dbus_queue(j);
+ job_start_timer(j);
+ job_shutdown_magic(j);
+ }
+
+ return 0;
+
+rollback:
+
+ HASHMAP_FOREACH(j, tr->jobs, i)
+ hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
+
+ return r;
+}
+
+int transaction_activate(Transaction *tr, Manager *m, JobMode mode, DBusError *e) {
+ Iterator i;
+ Job *j;
+ int r;
+ unsigned generation = 1;
+
+ assert(tr);
+
+ /* This applies the changes recorded in tr->jobs to
+ * the actual list of jobs, if possible. */
+
+ /* Reset the generation counter of all installed jobs. The detection of cycles
+ * looks at installed jobs. If they had a non-zero generation from some previous
+ * walk of the graph, the algorithm would break. */
+ HASHMAP_FOREACH(j, m->jobs, i)
+ j->generation = 0;
+
+ /* First step: figure out which jobs matter */
+ transaction_find_jobs_that_matter_to_anchor(tr->anchor_job, generation++);
+
+ /* Second step: Try not to stop any running services if
+ * we don't have to. Don't try to reverse running
+ * jobs if we don't have to. */
+ if (mode == JOB_FAIL)
+ transaction_minimize_impact(tr);
+
+ /* Third step: Drop redundant jobs */
+ transaction_drop_redundant(tr);
+
+ for (;;) {
+ /* Fourth step: Let's remove unneeded jobs that might
+ * be lurking. */
+ if (mode != JOB_ISOLATE)
+ transaction_collect_garbage(tr);
+
+ /* Fifth step: verify order makes sense and correct
+ * cycles if necessary and possible */
+ r = transaction_verify_order(tr, &generation, e);
+ if (r >= 0)
+ break;
+
+ if (r != -EAGAIN) {
+ log_warning("Requested transaction contains an unfixable cyclic ordering dependency: %s", bus_error(e, r));
+ return r;
+ }
+
+ /* Let's see if the resulting transaction ordering
+ * graph is still cyclic... */
+ }
+
+ for (;;) {
+ /* Sixth step: let's drop unmergeable entries if
+ * necessary and possible, merge entries we can
+ * merge */
+ r = transaction_merge_jobs(tr, e);
+ if (r >= 0)
+ break;
+
+ if (r != -EAGAIN) {
+ log_warning("Requested transaction contains unmergeable jobs: %s", bus_error(e, r));
+ return r;
+ }
+
+ /* Seventh step: an entry got dropped, let's garbage
+ * collect its dependencies. */
+ if (mode != JOB_ISOLATE)
+ transaction_collect_garbage(tr);
+
+ /* Let's see if the resulting transaction still has
+ * unmergeable entries ... */
+ }
+
+ /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
+ transaction_drop_redundant(tr);
+
+ /* Ninth step: check whether we can actually apply this */
+ r = transaction_is_destructive(tr, mode, e);
+ if (r < 0) {
+ log_notice("Requested transaction contradicts existing jobs: %s", bus_error(e, r));
+ return r;
+ }
+
+ /* Tenth step: apply changes */
+ r = transaction_apply(tr, m, mode);
+ if (r < 0) {
+ log_warning("Failed to apply transaction: %s", strerror(-r));
+ return r;
+ }
+
+ assert(hashmap_isempty(tr->jobs));
+
+ if (!hashmap_isempty(m->jobs)) {
+ /* Are there any jobs now? Then make sure we have the
+ * idle pipe around. We don't really care too much
+ * whether this works or not, as the idle pipe is a
+ * feature for cosmetics, not actually useful for
+ * anything beyond that. */
+
+ if (m->idle_pipe[0] < 0 && m->idle_pipe[1] < 0)
+ pipe2(m->idle_pipe, O_NONBLOCK|O_CLOEXEC);
+ }
+
+ return 0;
+}
+
+static Job* transaction_add_one_job(Transaction *tr, JobType type, Unit *unit, bool override, bool *is_new) {
+ Job *j, *f;
+
+ assert(tr);
+ assert(unit);
+
+ /* Looks for an existing prospective job and returns that. If
+ * it doesn't exist it is created and added to the prospective
+ * jobs list. */
+
+ f = hashmap_get(tr->jobs, unit);
+
+ LIST_FOREACH(transaction, j, f) {
+ assert(j->unit == unit);
+
+ if (j->type == type) {
+ if (is_new)
+ *is_new = false;
+ return j;
+ }
+ }
+
+ j = job_new(unit, type);
+ if (!j)
+ return NULL;
+
+ j->generation = 0;
+ j->marker = NULL;
+ j->matters_to_anchor = false;
+ j->override = override;
+ j->irreversible = tr->irreversible;
+
+ LIST_PREPEND(Job, transaction, f, j);
+
+ if (hashmap_replace(tr->jobs, unit, f) < 0) {
+ LIST_REMOVE(Job, transaction, f, j);
+ job_free(j);
+ return NULL;
+ }
+
+ if (is_new)
+ *is_new = true;
+
+ /* log_debug("Added job %s/%s to transaction.", unit->id, job_type_to_string(type)); */
+
+ return j;
+}
+
+static void transaction_unlink_job(Transaction *tr, Job *j, bool delete_dependencies) {
+ assert(tr);
+ assert(j);
+
+ if (j->transaction_prev)
+ j->transaction_prev->transaction_next = j->transaction_next;
+ else if (j->transaction_next)
+ hashmap_replace(tr->jobs, j->unit, j->transaction_next);
+ else
+ hashmap_remove_value(tr->jobs, j->unit, j);
+
+ if (j->transaction_next)
+ j->transaction_next->transaction_prev = j->transaction_prev;
+
+ j->transaction_prev = j->transaction_next = NULL;
+
+ while (j->subject_list)
+ job_dependency_free(j->subject_list);
+
+ while (j->object_list) {
+ Job *other = j->object_list->matters ? j->object_list->subject : NULL;
+
+ job_dependency_free(j->object_list);
+
+ if (other && delete_dependencies) {
+ log_debug_unit(other->unit->id,
+ "Deleting job %s/%s as dependency of job %s/%s",
+ other->unit->id, job_type_to_string(other->type),
+ j->unit->id, job_type_to_string(j->type));
+ transaction_delete_job(tr, other, delete_dependencies);
+ }
+ }
+}
+
+int transaction_add_job_and_dependencies(
+ Transaction *tr,
+ JobType type,
+ Unit *unit,
+ Job *by,
+ bool matters,
+ bool override,
+ bool conflicts,
+ bool ignore_requirements,
+ bool ignore_order,
+ DBusError *e) {
+ Job *ret;
+ Iterator i;
+ Unit *dep;
+ int r;
+ bool is_new;
+
+ assert(tr);
+ assert(type < _JOB_TYPE_MAX);
+ assert(type < _JOB_TYPE_MAX_IN_TRANSACTION);
+ assert(unit);
+
+ /* log_debug("Pulling in %s/%s from %s/%s", */
+ /* unit->id, job_type_to_string(type), */
+ /* by ? by->unit->id : "NA", */
+ /* by ? job_type_to_string(by->type) : "NA"); */
+
+ if (unit->load_state != UNIT_LOADED &&
+ unit->load_state != UNIT_ERROR &&
+ unit->load_state != UNIT_MASKED) {
+ dbus_set_error(e, BUS_ERROR_LOAD_FAILED, "Unit %s is not loaded properly.", unit->id);
+ return -EINVAL;
+ }
+
+ if (type != JOB_STOP && unit->load_state == UNIT_ERROR) {
+ dbus_set_error(e, BUS_ERROR_LOAD_FAILED,
+ "Unit %s failed to load: %s. "
+ "See system logs and 'systemctl status %s' for details.",
+ unit->id,
+ strerror(-unit->load_error),
+ unit->id);
+ return -EINVAL;
+ }
+
+ if (type != JOB_STOP && unit->load_state == UNIT_MASKED) {
+ dbus_set_error(e, BUS_ERROR_MASKED, "Unit %s is masked.", unit->id);
+ return -EADDRNOTAVAIL;
+ }
+
+ if (!unit_job_is_applicable(unit, type)) {
+ dbus_set_error(e, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE, "Job type %s is not applicable for unit %s.", job_type_to_string(type), unit->id);
+ return -EBADR;
+ }
+
+ /* First add the job. */
+ ret = transaction_add_one_job(tr, type, unit, override, &is_new);
+ if (!ret)
+ return -ENOMEM;
+
+ ret->ignore_order = ret->ignore_order || ignore_order;
+
+ /* Then, add a link to the job. */
+ if (by) {
+ if (!job_dependency_new(by, ret, matters, conflicts))
+ return -ENOMEM;
+ } else {
+ /* If the job has no parent job, it is the anchor job. */
+ assert(!tr->anchor_job);
+ tr->anchor_job = ret;
+ }
+
+ if (is_new && !ignore_requirements && type != JOB_NOP) {
+ Set *following;
+
+ /* If we are following some other unit, make sure we
+ * add all dependencies of everybody following. */
+ if (unit_following_set(ret->unit, &following) > 0) {
+ SET_FOREACH(dep, following, i) {
+ r = transaction_add_job_and_dependencies(tr, type, dep, ret, false, override, false, false, ignore_order, e);
+ if (r < 0) {
+ log_warning_unit(dep->id,
+ "Cannot add dependency job for unit %s, ignoring: %s",
+ dep->id, bus_error(e, r));
+
+ if (e)
+ dbus_error_free(e);
+ }
+ }
+
+ set_free(following);
+ }
+
+ /* Finally, recursively add in all dependencies. */
+ if (type == JOB_START || type == JOB_RESTART) {
+ SET_FOREACH(dep, ret->unit->dependencies[UNIT_REQUIRES], i) {
+ r = transaction_add_job_and_dependencies(tr, JOB_START, dep, ret, true, override, false, false, ignore_order, e);
+ if (r < 0) {
+ if (r != -EBADR)
+ goto fail;
+
+ if (e)
+ dbus_error_free(e);
+ }
+ }
+
+ SET_FOREACH(dep, ret->unit->dependencies[UNIT_BINDS_TO], i) {
+ r = transaction_add_job_and_dependencies(tr, JOB_START, dep, ret, true, override, false, false, ignore_order, e);
+ if (r < 0) {
+ if (r != -EBADR)
+ goto fail;
+
+ if (e)
+ dbus_error_free(e);
+ }
+ }
+
+ SET_FOREACH(dep, ret->unit->dependencies[UNIT_REQUIRES_OVERRIDABLE], i) {
+ r = transaction_add_job_and_dependencies(tr, JOB_START, dep, ret, !override, override, false, false, ignore_order, e);
+ if (r < 0) {
+ log_full_unit(r == -EADDRNOTAVAIL ? LOG_DEBUG : LOG_WARNING, dep->id,
+ "Cannot add dependency job for unit %s, ignoring: %s",
+ dep->id, bus_error(e, r));
+
+ if (e)
+ dbus_error_free(e);
+ }
+ }
+
+ SET_FOREACH(dep, ret->unit->dependencies[UNIT_WANTS], i) {
+ r = transaction_add_job_and_dependencies(tr, JOB_START, dep, ret, false, false, false, false, ignore_order, e);
+ if (r < 0) {
+ log_full_unit(r == -EADDRNOTAVAIL ? LOG_DEBUG : LOG_WARNING, dep->id,
+ "Cannot add dependency job for unit %s, ignoring: %s",
+ dep->id, bus_error(e, r));
+
+ if (e)
+ dbus_error_free(e);
+ }
+ }
+
+ SET_FOREACH(dep, ret->unit->dependencies[UNIT_REQUISITE], i) {
+ r = transaction_add_job_and_dependencies(tr, JOB_VERIFY_ACTIVE, dep, ret, true, override, false, false, ignore_order, e);
+ if (r < 0) {
+ if (r != -EBADR)
+ goto fail;
+
+ if (e)
+ dbus_error_free(e);
+ }
+ }
+
+ SET_FOREACH(dep, ret->unit->dependencies[UNIT_REQUISITE_OVERRIDABLE], i) {
+ r = transaction_add_job_and_dependencies(tr, JOB_VERIFY_ACTIVE, dep, ret, !override, override, false, false, ignore_order, e);
+ if (r < 0) {
+ log_full_unit(r == -EADDRNOTAVAIL ? LOG_DEBUG : LOG_WARNING, dep->id,
+ "Cannot add dependency job for unit %s, ignoring: %s",
+ dep->id, bus_error(e, r));
+
+ if (e)
+ dbus_error_free(e);
+ }
+ }
+
+ SET_FOREACH(dep, ret->unit->dependencies[UNIT_CONFLICTS], i) {
+ r = transaction_add_job_and_dependencies(tr, JOB_STOP, dep, ret, true, override, true, false, ignore_order, e);
+ if (r < 0) {
+ if (r != -EBADR)
+ goto fail;
+
+ if (e)
+ dbus_error_free(e);
+ }
+ }
+
+ SET_FOREACH(dep, ret->unit->dependencies[UNIT_CONFLICTED_BY], i) {
+ r = transaction_add_job_and_dependencies(tr, JOB_STOP, dep, ret, false, override, false, false, ignore_order, e);
+ if (r < 0) {
+ log_warning_unit(dep->id,
+ "Cannot add dependency job for unit %s, ignoring: %s",
+ dep->id, bus_error(e, r));
+
+ if (e)
+ dbus_error_free(e);
+ }
+ }
+
+ }
+
+ if (type == JOB_STOP || type == JOB_RESTART) {
+
+ SET_FOREACH(dep, ret->unit->dependencies[UNIT_REQUIRED_BY], i) {
+ r = transaction_add_job_and_dependencies(tr, type, dep, ret, true, override, false, false, ignore_order, e);
+ if (r < 0) {
+ if (r != -EBADR)
+ goto fail;
+
+ if (e)
+ dbus_error_free(e);
+ }
+ }
+
+ SET_FOREACH(dep, ret->unit->dependencies[UNIT_BOUND_BY], i) {
+ r = transaction_add_job_and_dependencies(tr, type, dep, ret, true, override, false, false, ignore_order, e);
+ if (r < 0) {
+ if (r != -EBADR)
+ goto fail;
+
+ if (e)
+ dbus_error_free(e);
+ }
+ }
+
+ SET_FOREACH(dep, ret->unit->dependencies[UNIT_CONSISTS_OF], i) {
+ r = transaction_add_job_and_dependencies(tr, type, dep, ret, true, override, false, false, ignore_order, e);
+ if (r < 0) {
+ if (r != -EBADR)
+ goto fail;
+
+ if (e)
+ dbus_error_free(e);
+ }
+ }
+
+ }
+
+ if (type == JOB_RELOAD) {
+
+ SET_FOREACH(dep, ret->unit->dependencies[UNIT_PROPAGATES_RELOAD_TO], i) {
+ r = transaction_add_job_and_dependencies(tr, JOB_RELOAD, dep, ret, false, override, false, false, ignore_order, e);
+ if (r < 0) {
+ log_warning_unit(dep->id,
+ "Cannot add dependency reload job for unit %s, ignoring: %s",
+ dep->id, bus_error(e, r));
+
+ if (e)
+ dbus_error_free(e);
+ }
+ }
+ }
+
+ /* JOB_VERIFY_STARTED require no dependency handling */
+ }
+
+ return 0;
+
+fail:
+ return r;
+}
+
+int transaction_add_isolate_jobs(Transaction *tr, Manager *m) {
+ Iterator i;
+ Unit *u;
+ char *k;
+ int r;
+
+ assert(tr);
+ assert(m);
+
+ HASHMAP_FOREACH_KEY(u, k, m->units, i) {
+
+ /* ignore aliases */
+ if (u->id != k)
+ continue;
+
+ if (u->ignore_on_isolate)
+ continue;
+
+ /* No need to stop inactive jobs */
+ if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(u)) && !u->job)
+ continue;
+
+ /* Is there already something listed for this? */
+ if (hashmap_get(tr->jobs, u))
+ continue;
+
+ r = transaction_add_job_and_dependencies(tr, JOB_STOP, u, tr->anchor_job, true, false, false, false, false, NULL);
+ if (r < 0)
+ log_warning_unit(u->id,
+ "Cannot add isolate job for unit %s, ignoring: %s",
+ u->id, strerror(-r));
+ }
+
+ return 0;
+}
+
+Transaction *transaction_new(bool irreversible) {
+ Transaction *tr;
+
+ tr = new0(Transaction, 1);
+ if (!tr)
+ return NULL;
+
+ tr->jobs = hashmap_new(trivial_hash_func, trivial_compare_func);
+ if (!tr->jobs) {
+ free(tr);
+ return NULL;
+ }
+
+ tr->irreversible = irreversible;
+
+ return tr;
+}
+
+void transaction_free(Transaction *tr) {
+ assert(hashmap_isempty(tr->jobs));
+ hashmap_free(tr->jobs);
+ free(tr);
+}
diff --git a/src/core/transaction.h b/src/core/transaction.h
new file mode 100644
index 0000000000..12f9194927
--- /dev/null
+++ b/src/core/transaction.h
@@ -0,0 +1,57 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef footransactionhfoo
+#define footransactionhfoo
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+typedef struct Transaction Transaction;
+
+#include "unit.h"
+#include "manager.h"
+#include "job.h"
+#include "hashmap.h"
+
+struct Transaction {
+ /* Jobs to be added */
+ Hashmap *jobs; /* Unit object => Job object list 1:1 */
+ Job *anchor_job; /* the job the user asked for */
+ bool irreversible;
+};
+
+Transaction *transaction_new(bool irreversible);
+void transaction_free(Transaction *tr);
+
+int transaction_add_job_and_dependencies(
+ Transaction *tr,
+ JobType type,
+ Unit *unit,
+ Job *by,
+ bool matters,
+ bool override,
+ bool conflicts,
+ bool ignore_requirements,
+ bool ignore_order,
+ DBusError *e);
+int transaction_activate(Transaction *tr, Manager *m, JobMode mode, DBusError *e);
+int transaction_add_isolate_jobs(Transaction *tr, Manager *m);
+void transaction_abort(Transaction *tr);
+
+#endif
diff --git a/src/core/umount.c b/src/core/umount.c
new file mode 100644
index 0000000000..1e95ad70dd
--- /dev/null
+++ b/src/core/umount.c
@@ -0,0 +1,639 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 ProFUSION embedded systems
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <fcntl.h>
+#include <string.h>
+#include <sys/mount.h>
+#include <sys/swap.h>
+#include <unistd.h>
+#include <linux/loop.h>
+#include <linux/dm-ioctl.h>
+#include <libudev.h>
+
+#include "list.h"
+#include "mount-setup.h"
+#include "umount.h"
+#include "path-util.h"
+#include "util.h"
+#include "virt.h"
+
+typedef struct MountPoint {
+ char *path;
+ dev_t devnum;
+ LIST_FIELDS (struct MountPoint, mount_point);
+} MountPoint;
+
+static void mount_point_free(MountPoint **head, MountPoint *m) {
+ assert(head);
+ assert(m);
+
+ LIST_REMOVE(MountPoint, mount_point, *head, m);
+
+ free(m->path);
+ free(m);
+}
+
+static void mount_points_list_free(MountPoint **head) {
+ assert(head);
+
+ while (*head)
+ mount_point_free(head, *head);
+}
+
+static int mount_points_list_get(MountPoint **head) {
+ FILE *proc_self_mountinfo;
+ char *path, *p;
+ unsigned int i;
+ int r;
+
+ assert(head);
+
+ if (!(proc_self_mountinfo = fopen("/proc/self/mountinfo", "re")))
+ return -errno;
+
+ for (i = 1;; i++) {
+ int k;
+ MountPoint *m;
+
+ path = p = NULL;
+
+ if ((k = fscanf(proc_self_mountinfo,
+ "%*s " /* (1) mount id */
+ "%*s " /* (2) parent id */
+ "%*s " /* (3) major:minor */
+ "%*s " /* (4) root */
+ "%ms " /* (5) mount point */
+ "%*s" /* (6) mount options */
+ "%*[^-]" /* (7) optional fields */
+ "- " /* (8) separator */
+ "%*s " /* (9) file system type */
+ "%*s" /* (10) mount source */
+ "%*s" /* (11) mount options 2 */
+ "%*[^\n]", /* some rubbish at the end */
+ &path)) != 1) {
+ if (k == EOF)
+ break;
+
+ log_warning("Failed to parse /proc/self/mountinfo:%u.", i);
+
+ free(path);
+ continue;
+ }
+
+ p = cunescape(path);
+ free(path);
+
+ if (!p) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ /* Ignore mount points we can't unmount because they
+ * are API or because we are keeping them open (like
+ * /dev/console) */
+ if (mount_point_is_api(p) ||
+ mount_point_ignore(p) ||
+ path_equal(p, "/dev/console")) {
+ free(p);
+ continue;
+ }
+
+ if (!(m = new0(MountPoint, 1))) {
+ free(p);
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ m->path = p;
+ LIST_PREPEND(MountPoint, mount_point, *head, m);
+ }
+
+ r = 0;
+
+finish:
+ fclose(proc_self_mountinfo);
+
+ return r;
+}
+
+static int swap_list_get(MountPoint **head) {
+ FILE *proc_swaps;
+ unsigned int i;
+ int r;
+
+ assert(head);
+
+ if (!(proc_swaps = fopen("/proc/swaps", "re")))
+ return (errno == ENOENT) ? 0 : -errno;
+
+ (void) fscanf(proc_swaps, "%*s %*s %*s %*s %*s\n");
+
+ for (i = 2;; i++) {
+ MountPoint *swap;
+ char *dev = NULL, *d;
+ int k;
+
+ if ((k = fscanf(proc_swaps,
+ "%ms " /* device/file */
+ "%*s " /* type of swap */
+ "%*s " /* swap size */
+ "%*s " /* used */
+ "%*s\n", /* priority */
+ &dev)) != 1) {
+
+ if (k == EOF)
+ break;
+
+ log_warning("Failed to parse /proc/swaps:%u.", i);
+
+ free(dev);
+ continue;
+ }
+
+ if (endswith(dev, "(deleted)")) {
+ free(dev);
+ continue;
+ }
+
+ d = cunescape(dev);
+ free(dev);
+
+ if (!d) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ if (!(swap = new0(MountPoint, 1))) {
+ free(d);
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ swap->path = d;
+ LIST_PREPEND(MountPoint, mount_point, *head, swap);
+ }
+
+ r = 0;
+
+finish:
+ fclose(proc_swaps);
+
+ return r;
+}
+
+static int loopback_list_get(MountPoint **head) {
+ int r;
+ struct udev *udev;
+ struct udev_enumerate *e = NULL;
+ struct udev_list_entry *item = NULL, *first = NULL;
+
+ assert(head);
+
+ if (!(udev = udev_new())) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ if (!(e = udev_enumerate_new(udev))) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ if (udev_enumerate_add_match_subsystem(e, "block") < 0 ||
+ udev_enumerate_add_match_sysname(e, "loop*") < 0 ||
+ udev_enumerate_add_match_sysattr(e, "loop/backing_file", NULL) < 0) {
+ r = -EIO;
+ goto finish;
+ }
+
+ if (udev_enumerate_scan_devices(e) < 0) {
+ r = -EIO;
+ goto finish;
+ }
+
+ first = udev_enumerate_get_list_entry(e);
+ udev_list_entry_foreach(item, first) {
+ MountPoint *lb;
+ struct udev_device *d;
+ char *loop;
+ const char *dn;
+
+ if (!(d = udev_device_new_from_syspath(udev, udev_list_entry_get_name(item)))) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ if (!(dn = udev_device_get_devnode(d))) {
+ udev_device_unref(d);
+ continue;
+ }
+
+ loop = strdup(dn);
+ udev_device_unref(d);
+
+ if (!loop) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ if (!(lb = new0(MountPoint, 1))) {
+ free(loop);
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ lb->path = loop;
+ LIST_PREPEND(MountPoint, mount_point, *head, lb);
+ }
+
+ r = 0;
+
+finish:
+ if (e)
+ udev_enumerate_unref(e);
+
+ if (udev)
+ udev_unref(udev);
+
+ return r;
+}
+
+static int dm_list_get(MountPoint **head) {
+ int r;
+ struct udev *udev;
+ struct udev_enumerate *e = NULL;
+ struct udev_list_entry *item = NULL, *first = NULL;
+
+ assert(head);
+
+ if (!(udev = udev_new())) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ if (!(e = udev_enumerate_new(udev))) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ if (udev_enumerate_add_match_subsystem(e, "block") < 0 ||
+ udev_enumerate_add_match_sysname(e, "dm-*") < 0) {
+ r = -EIO;
+ goto finish;
+ }
+
+ if (udev_enumerate_scan_devices(e) < 0) {
+ r = -EIO;
+ goto finish;
+ }
+
+ first = udev_enumerate_get_list_entry(e);
+
+ udev_list_entry_foreach(item, first) {
+ MountPoint *m;
+ struct udev_device *d;
+ dev_t devnum;
+ char *node;
+ const char *dn;
+
+ if (!(d = udev_device_new_from_syspath(udev, udev_list_entry_get_name(item)))) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ devnum = udev_device_get_devnum(d);
+ dn = udev_device_get_devnode(d);
+
+ if (major(devnum) == 0 || !dn) {
+ udev_device_unref(d);
+ continue;
+ }
+
+ node = strdup(dn);
+ udev_device_unref(d);
+
+ if (!node) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ if (!(m = new(MountPoint, 1))) {
+ free(node);
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ m->path = node;
+ m->devnum = devnum;
+ LIST_PREPEND(MountPoint, mount_point, *head, m);
+ }
+
+ r = 0;
+
+finish:
+ if (e)
+ udev_enumerate_unref(e);
+
+ if (udev)
+ udev_unref(udev);
+
+ return r;
+}
+
+static int delete_loopback(const char *device) {
+ int fd, r;
+
+ if ((fd = open(device, O_RDONLY|O_CLOEXEC)) < 0)
+ return errno == ENOENT ? 0 : -errno;
+
+ r = ioctl(fd, LOOP_CLR_FD, 0);
+ close_nointr_nofail(fd);
+
+ if (r >= 0)
+ return 1;
+
+ /* ENXIO: not bound, so no error */
+ if (errno == ENXIO)
+ return 0;
+
+ return -errno;
+}
+
+static int delete_dm(dev_t devnum) {
+ _cleanup_close_ int fd = -1;
+ int r;
+ struct dm_ioctl dm = {
+ .version = {DM_VERSION_MAJOR,
+ DM_VERSION_MINOR,
+ DM_VERSION_PATCHLEVEL},
+ .data_size = sizeof(dm),
+ .dev = devnum,
+ };
+
+ assert(major(devnum) != 0);
+
+ fd = open("/dev/mapper/control", O_RDWR|O_CLOEXEC);
+ if (fd < 0)
+ return -errno;
+
+ r = ioctl(fd, DM_DEV_REMOVE, &dm);
+ return r >= 0 ? 0 : -errno;
+}
+
+static int mount_points_list_umount(MountPoint **head, bool *changed, bool log_error) {
+ MountPoint *m, *n;
+ int n_failed = 0;
+
+ assert(head);
+
+ LIST_FOREACH_SAFE(mount_point, m, n, *head) {
+
+ /* If we are in a container, don't attempt to
+ read-only mount anything as that brings no real
+ benefits, but might confuse the host, as we remount
+ the superblock here, not the bind mound. */
+ if (detect_container(NULL) <= 0) {
+ /* We always try to remount directories
+ * read-only first, before we go on and umount
+ * them.
+ *
+ * Mount points can be stacked. If a mount
+ * point is stacked below / or /usr, we
+ * cannot umount or remount it directly,
+ * since there is no way to refer to the
+ * underlying mount. There's nothing we can do
+ * about it for the general case, but we can
+ * do something about it if it is aliased
+ * somehwere else via a bind mount. If we
+ * explicitly remount the super block of that
+ * alias read-only we hence should be
+ * relatively safe regarding keeping the fs we
+ * can otherwise not see dirty. */
+ mount(NULL, m->path, NULL, MS_REMOUNT|MS_RDONLY, NULL);
+ }
+
+ /* Skip / and /usr since we cannot unmount that
+ * anyway, since we are running from it. They have
+ * already been remounted ro. */
+ if (path_equal(m->path, "/")
+#ifndef HAVE_SPLIT_USR
+ || path_equal(m->path, "/usr")
+#endif
+ )
+ continue;
+
+ /* Trying to umount. We don't force here since we rely
+ * on busy NFS and FUSE file systems to return EBUSY
+ * until we closed everything on top of them. */
+ log_info("Unmounting %s.", m->path);
+ if (umount2(m->path, 0) == 0) {
+ if (changed)
+ *changed = true;
+
+ mount_point_free(head, m);
+ } else if (log_error) {
+ log_warning("Could not unmount %s: %m", m->path);
+ n_failed++;
+ }
+ }
+
+ return n_failed;
+}
+
+static int swap_points_list_off(MountPoint **head, bool *changed) {
+ MountPoint *m, *n;
+ int n_failed = 0;
+
+ assert(head);
+
+ LIST_FOREACH_SAFE(mount_point, m, n, *head) {
+ log_info("Deactivating swap %s.", m->path);
+ if (swapoff(m->path) == 0) {
+ if (changed)
+ *changed = true;
+
+ mount_point_free(head, m);
+ } else {
+ log_warning("Could not deactivate swap %s: %m", m->path);
+ n_failed++;
+ }
+ }
+
+ return n_failed;
+}
+
+static int loopback_points_list_detach(MountPoint **head, bool *changed) {
+ MountPoint *m, *n;
+ int n_failed = 0, k;
+ struct stat root_st;
+
+ assert(head);
+
+ k = lstat("/", &root_st);
+
+ LIST_FOREACH_SAFE(mount_point, m, n, *head) {
+ int r;
+ struct stat loopback_st;
+
+ if (k >= 0 &&
+ major(root_st.st_dev) != 0 &&
+ lstat(m->path, &loopback_st) >= 0 &&
+ root_st.st_dev == loopback_st.st_rdev) {
+ n_failed ++;
+ continue;
+ }
+
+ log_info("Detaching loopback %s.", m->path);
+ r = delete_loopback(m->path);
+ if (r >= 0) {
+ if (r > 0 && changed)
+ *changed = true;
+
+ mount_point_free(head, m);
+ } else {
+ log_warning("Could not detach loopback %s: %m", m->path);
+ n_failed++;
+ }
+ }
+
+ return n_failed;
+}
+
+static int dm_points_list_detach(MountPoint **head, bool *changed) {
+ MountPoint *m, *n;
+ int n_failed = 0, k;
+ struct stat root_st;
+
+ assert(head);
+
+ k = lstat("/", &root_st);
+
+ LIST_FOREACH_SAFE(mount_point, m, n, *head) {
+ int r;
+
+ if (k >= 0 &&
+ major(root_st.st_dev) != 0 &&
+ root_st.st_dev == m->devnum) {
+ n_failed ++;
+ continue;
+ }
+
+ log_info("Detaching DM %u:%u.", major(m->devnum), minor(m->devnum));
+ r = delete_dm(m->devnum);
+ if (r >= 0) {
+ if (changed)
+ *changed = true;
+
+ mount_point_free(head, m);
+ } else {
+ log_warning("Could not detach DM %s: %m", m->path);
+ n_failed++;
+ }
+ }
+
+ return n_failed;
+}
+
+int umount_all(bool *changed) {
+ int r;
+ bool umount_changed;
+ LIST_HEAD(MountPoint, mp_list_head);
+
+ LIST_HEAD_INIT(MountPoint, mp_list_head);
+ r = mount_points_list_get(&mp_list_head);
+ if (r < 0)
+ goto end;
+
+ /* retry umount, until nothing can be umounted anymore */
+ do {
+ umount_changed = false;
+
+ mount_points_list_umount(&mp_list_head, &umount_changed, false);
+ if (umount_changed)
+ *changed = true;
+
+ } while (umount_changed);
+
+ /* umount one more time with logging enabled */
+ r = mount_points_list_umount(&mp_list_head, &umount_changed, true);
+ if (r <= 0)
+ goto end;
+
+ end:
+ mount_points_list_free(&mp_list_head);
+
+ return r;
+}
+
+int swapoff_all(bool *changed) {
+ int r;
+ LIST_HEAD(MountPoint, swap_list_head);
+
+ LIST_HEAD_INIT(MountPoint, swap_list_head);
+
+ r = swap_list_get(&swap_list_head);
+ if (r < 0)
+ goto end;
+
+ r = swap_points_list_off(&swap_list_head, changed);
+
+ end:
+ mount_points_list_free(&swap_list_head);
+
+ return r;
+}
+
+int loopback_detach_all(bool *changed) {
+ int r;
+ LIST_HEAD(MountPoint, loopback_list_head);
+
+ LIST_HEAD_INIT(MountPoint, loopback_list_head);
+
+ r = loopback_list_get(&loopback_list_head);
+ if (r < 0)
+ goto end;
+
+ r = loopback_points_list_detach(&loopback_list_head, changed);
+
+ end:
+ mount_points_list_free(&loopback_list_head);
+
+ return r;
+}
+
+int dm_detach_all(bool *changed) {
+ int r;
+ LIST_HEAD(MountPoint, dm_list_head);
+
+ LIST_HEAD_INIT(MountPoint, dm_list_head);
+
+ r = dm_list_get(&dm_list_head);
+ if (r < 0)
+ goto end;
+
+ r = dm_points_list_detach(&dm_list_head, changed);
+
+ end:
+ mount_points_list_free(&dm_list_head);
+
+ return r;
+}
diff --git a/src/core/umount.h b/src/core/umount.h
new file mode 100644
index 0000000000..8439ffe58f
--- /dev/null
+++ b/src/core/umount.h
@@ -0,0 +1,30 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 ProFUSION embedded systems
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+int umount_all(bool *changed);
+
+int swapoff_all(bool *changed);
+
+int loopback_detach_all(bool *changed);
+
+int dm_detach_all(bool *changed);
diff --git a/src/core/unit-printf.c b/src/core/unit-printf.c
new file mode 100644
index 0000000000..85a05b872a
--- /dev/null
+++ b/src/core/unit-printf.c
@@ -0,0 +1,329 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "systemd/sd-id128.h"
+#include "unit.h"
+#include "specifier.h"
+#include "path-util.h"
+#include "strv.h"
+#include "unit-name.h"
+#include "unit-printf.h"
+#include "macro.h"
+
+static char *specifier_prefix_and_instance(char specifier, void *data, void *userdata) {
+ Unit *u = userdata;
+ assert(u);
+
+ return unit_name_to_prefix_and_instance(u->id);
+}
+
+static char *specifier_prefix(char specifier, void *data, void *userdata) {
+ Unit *u = userdata;
+ assert(u);
+
+ return unit_name_to_prefix(u->id);
+}
+
+static char *specifier_prefix_unescaped(char specifier, void *data, void *userdata) {
+ Unit *u = userdata;
+ char *p, *r;
+
+ assert(u);
+
+ p = unit_name_to_prefix(u->id);
+ if (!p)
+ return NULL;
+
+ r = unit_name_unescape(p);
+ free(p);
+
+ return r;
+}
+
+static char *specifier_instance_unescaped(char specifier, void *data, void *userdata) {
+ Unit *u = userdata;
+ assert(u);
+
+ if (u->instance)
+ return unit_name_unescape(u->instance);
+
+ return strdup("");
+}
+
+static char *specifier_filename(char specifier, void *data, void *userdata) {
+ Unit *u = userdata;
+ assert(u);
+
+ if (u->instance)
+ return unit_name_path_unescape(u->instance);
+
+ return unit_name_to_path(u->id);
+}
+
+static char *specifier_cgroup(char specifier, void *data, void *userdata) {
+ Unit *u = userdata;
+ assert(u);
+
+ return unit_default_cgroup_path(u);
+}
+
+static char *specifier_cgroup_root(char specifier, void *data, void *userdata) {
+ Unit *u = userdata;
+ char *p;
+ assert(u);
+
+ if (specifier == 'r')
+ return strdup(u->manager->cgroup_hierarchy);
+
+ if (path_get_parent(u->manager->cgroup_hierarchy, &p) < 0)
+ return strdup("");
+
+ if (streq(p, "/")) {
+ free(p);
+ return strdup("");
+ }
+
+ return p;
+}
+
+static char *specifier_runtime(char specifier, void *data, void *userdata) {
+ Unit *u = userdata;
+ assert(u);
+
+ if (u->manager->running_as == SYSTEMD_USER) {
+ const char *e;
+
+ e = getenv("XDG_RUNTIME_DIR");
+ if (e)
+ return strdup(e);
+ }
+
+ return strdup("/run");
+}
+
+static char *specifier_user_name(char specifier, void *data, void *userdata) {
+ Unit *u = userdata;
+ ExecContext *c;
+ int r;
+ const char *username;
+ _cleanup_free_ char *tmp = NULL;
+ uid_t uid;
+ char *printed = NULL;
+
+ assert(u);
+
+ c = unit_get_exec_context(u);
+
+ if (c && c->user)
+ username = c->user;
+ else
+ /* get USER env from env or our own uid */
+ username = tmp = getusername_malloc();
+
+ /* fish username from passwd */
+ r = get_user_creds(&username, &uid, NULL, NULL, NULL);
+ if (r < 0)
+ return NULL;
+
+ switch (specifier) {
+ case 'U':
+ if (asprintf(&printed, "%d", uid) < 0)
+ return NULL;
+ break;
+ case 'u':
+ printed = strdup(username);
+ break;
+ }
+
+ return printed;
+}
+
+static char *specifier_user_home(char specifier, void *data, void *userdata) {
+ Unit *u = userdata;
+ ExecContext *c;
+ int r;
+ const char *username, *home;
+
+ assert(u);
+
+ c = unit_get_exec_context(u);
+
+ /* return HOME if set, otherwise from passwd */
+ if (!c || !c->user) {
+ char *h;
+
+ r = get_home_dir(&h);
+ if (r < 0)
+ return NULL;
+
+ return h;
+ }
+
+ username = c->user;
+ r = get_user_creds(&username, NULL, NULL, &home, NULL);
+ if (r < 0)
+ return NULL;
+
+ return strdup(home);
+}
+
+static char *specifier_user_shell(char specifier, void *data, void *userdata) {
+ Unit *u = userdata;
+ ExecContext *c;
+ int r;
+ const char *username, *shell;
+ char *ret;
+
+ assert(u);
+
+ c = unit_get_exec_context(u);
+
+ if (c && c->user)
+ username = c->user;
+ else
+ username = "root";
+
+ /* return /bin/sh for root, otherwise the value from passwd */
+ r = get_user_creds(&username, NULL, NULL, NULL, &shell);
+ if (r < 0) {
+ log_warning_unit(u->id,
+ "Failed to determine shell: %s",
+ strerror(-r));
+ return NULL;
+ }
+
+ if (!path_is_absolute(shell)) {
+ log_warning_unit(u->id,
+ "Shell %s is not absolute, ignoring.",
+ shell);
+ }
+
+ ret = strdup(shell);
+ if (!ret)
+ log_oom();
+
+ return ret;
+}
+
+char *unit_name_printf(Unit *u, const char* format) {
+
+ /*
+ * This will use the passed string as format string and
+ * replace the following specifiers:
+ *
+ * %n: the full id of the unit (foo@bar.waldo)
+ * %N: the id of the unit without the suffix (foo@bar)
+ * %p: the prefix (foo)
+ * %i: the instance (bar)
+ */
+
+ const Specifier table[] = {
+ { 'n', specifier_string, u->id },
+ { 'N', specifier_prefix_and_instance, NULL },
+ { 'p', specifier_prefix, NULL },
+ { 'i', specifier_string, u->instance },
+ { 0, NULL, NULL }
+ };
+
+ assert(u);
+ assert(format);
+
+ return specifier_printf(format, table, u);
+}
+
+char *unit_full_printf(Unit *u, const char *format) {
+
+ /* This is similar to unit_name_printf() but also supports
+ * unescaping. Also, adds a couple of additional codes:
+ *
+ * %f the the instance if set, otherwise the id
+ * %c cgroup path of unit
+ * %r root cgroup path of this systemd instance (e.g. "/user/lennart/shared/systemd-4711")
+ * %R parent of root cgroup path (e.g. "/usr/lennart/shared")
+ * %t the runtime directory to place sockets in (e.g. "/run" or $XDG_RUNTIME_DIR)
+ * %U the UID of the configured user or running user
+ * %u the username of the configured user or running user
+ * %h the homedir of the configured user or running user
+ * %s the shell of the configured user or running user
+ * %m the machine ID of the running system
+ * %H the host name of the running system
+ * %b the boot ID of the running system
+ */
+
+ const Specifier table[] = {
+ { 'n', specifier_string, u->id },
+ { 'N', specifier_prefix_and_instance, NULL },
+ { 'p', specifier_prefix, NULL },
+ { 'P', specifier_prefix_unescaped, NULL },
+ { 'i', specifier_string, u->instance },
+ { 'I', specifier_instance_unescaped, NULL },
+
+ { 'f', specifier_filename, NULL },
+ { 'c', specifier_cgroup, NULL },
+ { 'r', specifier_cgroup_root, NULL },
+ { 'R', specifier_cgroup_root, NULL },
+ { 't', specifier_runtime, NULL },
+ { 'U', specifier_user_name, NULL },
+ { 'u', specifier_user_name, NULL },
+ { 'h', specifier_user_home, NULL },
+ { 's', specifier_user_shell, NULL },
+
+ { 'm', specifier_machine_id, NULL },
+ { 'H', specifier_host_name, NULL },
+ { 'b', specifier_boot_id, NULL },
+ { 0, NULL, NULL }
+ };
+
+ assert(format);
+
+ return specifier_printf(format, table, u);
+}
+
+char **unit_full_printf_strv(Unit *u, char **l) {
+ size_t n;
+ char **r, **i, **j;
+
+ /* Applies unit_full_printf to every entry in l */
+
+ assert(u);
+
+ n = strv_length(l);
+ r = new(char*, n+1);
+ if (!r)
+ return NULL;
+
+ for (i = l, j = r; *i; i++, j++) {
+ *j = unit_full_printf(u, *i);
+ if (!*j)
+ goto fail;
+ }
+
+ *j = NULL;
+ return r;
+
+fail:
+ for (j--; j >= r; j--)
+ free(*j);
+
+ free(r);
+
+ return NULL;
+}
diff --git a/src/core/unit-printf.h b/src/core/unit-printf.h
new file mode 100644
index 0000000000..d2f4ccd178
--- /dev/null
+++ b/src/core/unit-printf.h
@@ -0,0 +1,28 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "unit.h"
+
+char *unit_name_printf(Unit *u, const char* text);
+char *unit_full_printf(Unit *u, const char *text);
+char **unit_full_printf_strv(Unit *u, char **l);
diff --git a/src/core/unit.c b/src/core/unit.c
new file mode 100644
index 0000000000..9b36b225fa
--- /dev/null
+++ b/src/core/unit.c
@@ -0,0 +1,3089 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <errno.h>
+#include <string.h>
+#include <sys/epoll.h>
+#include <sys/timerfd.h>
+#include <sys/poll.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <sys/stat.h>
+
+#include "systemd/sd-id128.h"
+#include "systemd/sd-messages.h"
+#include "set.h"
+#include "unit.h"
+#include "macro.h"
+#include "strv.h"
+#include "path-util.h"
+#include "load-fragment.h"
+#include "load-dropin.h"
+#include "log.h"
+#include "unit-name.h"
+#include "dbus-unit.h"
+#include "special.h"
+#include "cgroup-util.h"
+#include "missing.h"
+#include "cgroup-attr.h"
+#include "mkdir.h"
+#include "label.h"
+#include "fileio-label.h"
+#include "bus-errors.h"
+
+const UnitVTable * const unit_vtable[_UNIT_TYPE_MAX] = {
+ [UNIT_SERVICE] = &service_vtable,
+ [UNIT_TIMER] = &timer_vtable,
+ [UNIT_SOCKET] = &socket_vtable,
+ [UNIT_TARGET] = &target_vtable,
+ [UNIT_DEVICE] = &device_vtable,
+ [UNIT_MOUNT] = &mount_vtable,
+ [UNIT_AUTOMOUNT] = &automount_vtable,
+ [UNIT_SNAPSHOT] = &snapshot_vtable,
+ [UNIT_SWAP] = &swap_vtable,
+ [UNIT_PATH] = &path_vtable
+};
+
+Unit *unit_new(Manager *m, size_t size) {
+ Unit *u;
+
+ assert(m);
+ assert(size >= sizeof(Unit));
+
+ u = malloc0(size);
+ if (!u)
+ return NULL;
+
+ u->names = set_new(string_hash_func, string_compare_func);
+ if (!u->names) {
+ free(u);
+ return NULL;
+ }
+
+ u->manager = m;
+ u->type = _UNIT_TYPE_INVALID;
+ u->deserialized_job = _JOB_TYPE_INVALID;
+ u->default_dependencies = true;
+ u->unit_file_state = _UNIT_FILE_STATE_INVALID;
+
+ return u;
+}
+
+bool unit_has_name(Unit *u, const char *name) {
+ assert(u);
+ assert(name);
+
+ return !!set_get(u->names, (char*) name);
+}
+
+int unit_add_name(Unit *u, const char *text) {
+ UnitType t;
+ char *s, *i = NULL;
+ int r;
+
+ assert(u);
+ assert(text);
+
+ if (unit_name_is_template(text)) {
+ if (!u->instance)
+ return -EINVAL;
+
+ s = unit_name_replace_instance(text, u->instance);
+ } else
+ s = strdup(text);
+
+ if (!s)
+ return -ENOMEM;
+
+ if (!unit_name_is_valid(s, false)) {
+ r = -EINVAL;
+ goto fail;
+ }
+
+ assert_se((t = unit_name_to_type(s)) >= 0);
+
+ if (u->type != _UNIT_TYPE_INVALID && t != u->type) {
+ r = -EINVAL;
+ goto fail;
+ }
+
+ if ((r = unit_name_to_instance(s, &i)) < 0)
+ goto fail;
+
+ if (i && unit_vtable[t]->no_instances) {
+ r = -EINVAL;
+ goto fail;
+ }
+
+ /* Ensure that this unit is either instanced or not instanced,
+ * but not both. */
+ if (u->type != _UNIT_TYPE_INVALID && !u->instance != !i) {
+ r = -EINVAL;
+ goto fail;
+ }
+
+ if (unit_vtable[t]->no_alias &&
+ !set_isempty(u->names) &&
+ !set_get(u->names, s)) {
+ r = -EEXIST;
+ goto fail;
+ }
+
+ if (hashmap_size(u->manager->units) >= MANAGER_MAX_NAMES) {
+ r = -E2BIG;
+ goto fail;
+ }
+
+ if ((r = set_put(u->names, s)) < 0) {
+ if (r == -EEXIST)
+ r = 0;
+ goto fail;
+ }
+
+ if ((r = hashmap_put(u->manager->units, s, u)) < 0) {
+ set_remove(u->names, s);
+ goto fail;
+ }
+
+ if (u->type == _UNIT_TYPE_INVALID) {
+
+ u->type = t;
+ u->id = s;
+ u->instance = i;
+
+ LIST_PREPEND(Unit, units_by_type, u->manager->units_by_type[t], u);
+
+ if (UNIT_VTABLE(u)->init)
+ UNIT_VTABLE(u)->init(u);
+ } else
+ free(i);
+
+ unit_add_to_dbus_queue(u);
+ return 0;
+
+fail:
+ free(s);
+ free(i);
+
+ return r;
+}
+
+int unit_choose_id(Unit *u, const char *name) {
+ char *s, *t = NULL, *i;
+ int r;
+
+ assert(u);
+ assert(name);
+
+ if (unit_name_is_template(name)) {
+
+ if (!u->instance)
+ return -EINVAL;
+
+ if (!(t = unit_name_replace_instance(name, u->instance)))
+ return -ENOMEM;
+
+ name = t;
+ }
+
+ /* Selects one of the names of this unit as the id */
+ s = set_get(u->names, (char*) name);
+ free(t);
+
+ if (!s)
+ return -ENOENT;
+
+ if ((r = unit_name_to_instance(s, &i)) < 0)
+ return r;
+
+ u->id = s;
+
+ free(u->instance);
+ u->instance = i;
+
+ unit_add_to_dbus_queue(u);
+
+ return 0;
+}
+
+int unit_set_description(Unit *u, const char *description) {
+ char *s;
+
+ assert(u);
+
+ if (!(s = strdup(description)))
+ return -ENOMEM;
+
+ free(u->description);
+ u->description = s;
+
+ unit_add_to_dbus_queue(u);
+ return 0;
+}
+
+bool unit_check_gc(Unit *u) {
+ assert(u);
+
+ if (u->load_state == UNIT_STUB)
+ return true;
+
+ if (UNIT_VTABLE(u)->no_gc)
+ return true;
+
+ if (u->no_gc)
+ return true;
+
+ if (u->job)
+ return true;
+
+ if (u->nop_job)
+ return true;
+
+ if (unit_active_state(u) != UNIT_INACTIVE)
+ return true;
+
+ if (u->refs)
+ return true;
+
+ if (UNIT_VTABLE(u)->check_gc)
+ if (UNIT_VTABLE(u)->check_gc(u))
+ return true;
+
+ return false;
+}
+
+void unit_add_to_load_queue(Unit *u) {
+ assert(u);
+ assert(u->type != _UNIT_TYPE_INVALID);
+
+ if (u->load_state != UNIT_STUB || u->in_load_queue)
+ return;
+
+ LIST_PREPEND(Unit, load_queue, u->manager->load_queue, u);
+ u->in_load_queue = true;
+}
+
+void unit_add_to_cleanup_queue(Unit *u) {
+ assert(u);
+
+ if (u->in_cleanup_queue)
+ return;
+
+ LIST_PREPEND(Unit, cleanup_queue, u->manager->cleanup_queue, u);
+ u->in_cleanup_queue = true;
+}
+
+void unit_add_to_gc_queue(Unit *u) {
+ assert(u);
+
+ if (u->in_gc_queue || u->in_cleanup_queue)
+ return;
+
+ if (unit_check_gc(u))
+ return;
+
+ LIST_PREPEND(Unit, gc_queue, u->manager->gc_queue, u);
+ u->in_gc_queue = true;
+
+ u->manager->n_in_gc_queue ++;
+
+ if (u->manager->gc_queue_timestamp <= 0)
+ u->manager->gc_queue_timestamp = now(CLOCK_MONOTONIC);
+}
+
+void unit_add_to_dbus_queue(Unit *u) {
+ assert(u);
+ assert(u->type != _UNIT_TYPE_INVALID);
+
+ if (u->load_state == UNIT_STUB || u->in_dbus_queue)
+ return;
+
+ /* Shortcut things if nobody cares */
+ if (!bus_has_subscriber(u->manager)) {
+ u->sent_dbus_new_signal = true;
+ return;
+ }
+
+ LIST_PREPEND(Unit, dbus_queue, u->manager->dbus_unit_queue, u);
+ u->in_dbus_queue = true;
+}
+
+static void bidi_set_free(Unit *u, Set *s) {
+ Iterator i;
+ Unit *other;
+
+ assert(u);
+
+ /* Frees the set and makes sure we are dropped from the
+ * inverse pointers */
+
+ SET_FOREACH(other, s, i) {
+ UnitDependency d;
+
+ for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
+ set_remove(other->dependencies[d], u);
+
+ unit_add_to_gc_queue(other);
+ }
+
+ set_free(s);
+}
+
+void unit_free(Unit *u) {
+ UnitDependency d;
+ Iterator i;
+ char *t;
+
+ assert(u);
+
+ bus_unit_send_removed_signal(u);
+
+ if (u->load_state != UNIT_STUB)
+ if (UNIT_VTABLE(u)->done)
+ UNIT_VTABLE(u)->done(u);
+
+ SET_FOREACH(t, u->names, i)
+ hashmap_remove_value(u->manager->units, t, u);
+
+ if (u->job) {
+ Job *j = u->job;
+ job_uninstall(j);
+ job_free(j);
+ }
+
+ if (u->nop_job) {
+ Job *j = u->nop_job;
+ job_uninstall(j);
+ job_free(j);
+ }
+
+ for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
+ bidi_set_free(u, u->dependencies[d]);
+
+ if (u->requires_mounts_for) {
+ LIST_REMOVE(Unit, has_requires_mounts_for, u->manager->has_requires_mounts_for, u);
+ strv_free(u->requires_mounts_for);
+ }
+
+ if (u->type != _UNIT_TYPE_INVALID)
+ LIST_REMOVE(Unit, units_by_type, u->manager->units_by_type[u->type], u);
+
+ if (u->in_load_queue)
+ LIST_REMOVE(Unit, load_queue, u->manager->load_queue, u);
+
+ if (u->in_dbus_queue)
+ LIST_REMOVE(Unit, dbus_queue, u->manager->dbus_unit_queue, u);
+
+ if (u->in_cleanup_queue)
+ LIST_REMOVE(Unit, cleanup_queue, u->manager->cleanup_queue, u);
+
+ if (u->in_gc_queue) {
+ LIST_REMOVE(Unit, gc_queue, u->manager->gc_queue, u);
+ u->manager->n_in_gc_queue--;
+ }
+
+ cgroup_bonding_free_list(u->cgroup_bondings, u->manager->n_reloading <= 0);
+ cgroup_attribute_free_list(u->cgroup_attributes);
+
+ free(u->description);
+ strv_free(u->documentation);
+ free(u->fragment_path);
+ free(u->source_path);
+ strv_free(u->dropin_paths);
+ free(u->instance);
+
+ set_free_free(u->names);
+
+ condition_free_list(u->conditions);
+
+ while (u->refs)
+ unit_ref_unset(u->refs);
+
+ free(u);
+}
+
+UnitActiveState unit_active_state(Unit *u) {
+ assert(u);
+
+ if (u->load_state == UNIT_MERGED)
+ return unit_active_state(unit_follow_merge(u));
+
+ /* After a reload it might happen that a unit is not correctly
+ * loaded but still has a process around. That's why we won't
+ * shortcut failed loading to UNIT_INACTIVE_FAILED. */
+
+ return UNIT_VTABLE(u)->active_state(u);
+}
+
+const char* unit_sub_state_to_string(Unit *u) {
+ assert(u);
+
+ return UNIT_VTABLE(u)->sub_state_to_string(u);
+}
+
+static void complete_move(Set **s, Set **other) {
+ assert(s);
+ assert(other);
+
+ if (!*other)
+ return;
+
+ if (*s)
+ set_move(*s, *other);
+ else {
+ *s = *other;
+ *other = NULL;
+ }
+}
+
+static void merge_names(Unit *u, Unit *other) {
+ char *t;
+ Iterator i;
+
+ assert(u);
+ assert(other);
+
+ complete_move(&u->names, &other->names);
+
+ set_free_free(other->names);
+ other->names = NULL;
+ other->id = NULL;
+
+ SET_FOREACH(t, u->names, i)
+ assert_se(hashmap_replace(u->manager->units, t, u) == 0);
+}
+
+static void merge_dependencies(Unit *u, Unit *other, UnitDependency d) {
+ Iterator i;
+ Unit *back;
+ int r;
+
+ assert(u);
+ assert(other);
+ assert(d < _UNIT_DEPENDENCY_MAX);
+
+ /* Fix backwards pointers */
+ SET_FOREACH(back, other->dependencies[d], i) {
+ UnitDependency k;
+
+ for (k = 0; k < _UNIT_DEPENDENCY_MAX; k++)
+ if ((r = set_remove_and_put(back->dependencies[k], other, u)) < 0) {
+
+ if (r == -EEXIST)
+ set_remove(back->dependencies[k], other);
+ else
+ assert(r == -ENOENT);
+ }
+ }
+
+ complete_move(&u->dependencies[d], &other->dependencies[d]);
+
+ set_free(other->dependencies[d]);
+ other->dependencies[d] = NULL;
+}
+
+int unit_merge(Unit *u, Unit *other) {
+ UnitDependency d;
+
+ assert(u);
+ assert(other);
+ assert(u->manager == other->manager);
+ assert(u->type != _UNIT_TYPE_INVALID);
+
+ other = unit_follow_merge(other);
+
+ if (other == u)
+ return 0;
+
+ if (u->type != other->type)
+ return -EINVAL;
+
+ if (!u->instance != !other->instance)
+ return -EINVAL;
+
+ if (other->load_state != UNIT_STUB &&
+ other->load_state != UNIT_ERROR)
+ return -EEXIST;
+
+ if (other->job)
+ return -EEXIST;
+
+ if (other->nop_job)
+ return -EEXIST;
+
+ if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
+ return -EEXIST;
+
+ /* Merge names */
+ merge_names(u, other);
+
+ /* Redirect all references */
+ while (other->refs)
+ unit_ref_set(other->refs, u);
+
+ /* Merge dependencies */
+ for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
+ merge_dependencies(u, other, d);
+
+ other->load_state = UNIT_MERGED;
+ other->merged_into = u;
+
+ /* If there is still some data attached to the other node, we
+ * don't need it anymore, and can free it. */
+ if (other->load_state != UNIT_STUB)
+ if (UNIT_VTABLE(other)->done)
+ UNIT_VTABLE(other)->done(other);
+
+ unit_add_to_dbus_queue(u);
+ unit_add_to_cleanup_queue(other);
+
+ return 0;
+}
+
+int unit_merge_by_name(Unit *u, const char *name) {
+ Unit *other;
+ int r;
+ char *s = NULL;
+
+ assert(u);
+ assert(name);
+
+ if (unit_name_is_template(name)) {
+ if (!u->instance)
+ return -EINVAL;
+
+ if (!(s = unit_name_replace_instance(name, u->instance)))
+ return -ENOMEM;
+
+ name = s;
+ }
+
+ if (!(other = manager_get_unit(u->manager, name)))
+ r = unit_add_name(u, name);
+ else
+ r = unit_merge(u, other);
+
+ free(s);
+ return r;
+}
+
+Unit* unit_follow_merge(Unit *u) {
+ assert(u);
+
+ while (u->load_state == UNIT_MERGED)
+ assert_se(u = u->merged_into);
+
+ return u;
+}
+
+int unit_add_exec_dependencies(Unit *u, ExecContext *c) {
+ int r;
+
+ assert(u);
+ assert(c);
+
+ if (c->std_output != EXEC_OUTPUT_KMSG &&
+ c->std_output != EXEC_OUTPUT_SYSLOG &&
+ c->std_output != EXEC_OUTPUT_JOURNAL &&
+ c->std_output != EXEC_OUTPUT_KMSG_AND_CONSOLE &&
+ c->std_output != EXEC_OUTPUT_SYSLOG_AND_CONSOLE &&
+ c->std_output != EXEC_OUTPUT_JOURNAL_AND_CONSOLE &&
+ c->std_error != EXEC_OUTPUT_KMSG &&
+ c->std_error != EXEC_OUTPUT_SYSLOG &&
+ c->std_error != EXEC_OUTPUT_JOURNAL &&
+ c->std_error != EXEC_OUTPUT_KMSG_AND_CONSOLE &&
+ c->std_error != EXEC_OUTPUT_JOURNAL_AND_CONSOLE &&
+ c->std_error != EXEC_OUTPUT_SYSLOG_AND_CONSOLE)
+ return 0;
+
+ /* If syslog or kernel logging is requested, make sure our own
+ * logging daemon is run first. */
+
+ if (u->manager->running_as == SYSTEMD_SYSTEM) {
+ r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_JOURNALD_SOCKET, NULL, true);
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+const char *unit_description(Unit *u) {
+ assert(u);
+
+ if (u->description)
+ return u->description;
+
+ return strna(u->id);
+}
+
+void unit_dump(Unit *u, FILE *f, const char *prefix) {
+ char *t, **j;
+ UnitDependency d;
+ Iterator i;
+ char *p2;
+ const char *prefix2;
+ char
+ timestamp1[FORMAT_TIMESTAMP_MAX],
+ timestamp2[FORMAT_TIMESTAMP_MAX],
+ timestamp3[FORMAT_TIMESTAMP_MAX],
+ timestamp4[FORMAT_TIMESTAMP_MAX],
+ timespan[FORMAT_TIMESPAN_MAX];
+ Unit *following;
+
+ assert(u);
+ assert(u->type >= 0);
+
+ if (!prefix)
+ prefix = "";
+ p2 = strappend(prefix, "\t");
+ prefix2 = p2 ? p2 : prefix;
+
+ fprintf(f,
+ "%s-> Unit %s:\n"
+ "%s\tDescription: %s\n"
+ "%s\tInstance: %s\n"
+ "%s\tUnit Load State: %s\n"
+ "%s\tUnit Active State: %s\n"
+ "%s\tInactive Exit Timestamp: %s\n"
+ "%s\tActive Enter Timestamp: %s\n"
+ "%s\tActive Exit Timestamp: %s\n"
+ "%s\tInactive Enter Timestamp: %s\n"
+ "%s\tGC Check Good: %s\n"
+ "%s\tNeed Daemon Reload: %s\n",
+ prefix, u->id,
+ prefix, unit_description(u),
+ prefix, strna(u->instance),
+ prefix, unit_load_state_to_string(u->load_state),
+ prefix, unit_active_state_to_string(unit_active_state(u)),
+ prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->inactive_exit_timestamp.realtime)),
+ prefix, strna(format_timestamp(timestamp2, sizeof(timestamp2), u->active_enter_timestamp.realtime)),
+ prefix, strna(format_timestamp(timestamp3, sizeof(timestamp3), u->active_exit_timestamp.realtime)),
+ prefix, strna(format_timestamp(timestamp4, sizeof(timestamp4), u->inactive_enter_timestamp.realtime)),
+ prefix, yes_no(unit_check_gc(u)),
+ prefix, yes_no(unit_need_daemon_reload(u)));
+
+ SET_FOREACH(t, u->names, i)
+ fprintf(f, "%s\tName: %s\n", prefix, t);
+
+ STRV_FOREACH(j, u->documentation)
+ fprintf(f, "%s\tDocumentation: %s\n", prefix, *j);
+
+ if ((following = unit_following(u)))
+ fprintf(f, "%s\tFollowing: %s\n", prefix, following->id);
+
+ if (u->fragment_path)
+ fprintf(f, "%s\tFragment Path: %s\n", prefix, u->fragment_path);
+
+ if (u->source_path)
+ fprintf(f, "%s\tSource Path: %s\n", prefix, u->source_path);
+
+ STRV_FOREACH(j, u->dropin_paths)
+ fprintf(f, "%s\tDropIn Path: %s\n", prefix, *j);
+
+ if (u->job_timeout > 0)
+ fprintf(f, "%s\tJob Timeout: %s\n", prefix, format_timespan(timespan, sizeof(timespan), u->job_timeout, 0));
+
+ condition_dump_list(u->conditions, f, prefix);
+
+ if (dual_timestamp_is_set(&u->condition_timestamp))
+ fprintf(f,
+ "%s\tCondition Timestamp: %s\n"
+ "%s\tCondition Result: %s\n",
+ prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->condition_timestamp.realtime)),
+ prefix, yes_no(u->condition_result));
+
+ for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
+ Unit *other;
+
+ SET_FOREACH(other, u->dependencies[d], i)
+ fprintf(f, "%s\t%s: %s\n", prefix, unit_dependency_to_string(d), other->id);
+ }
+
+ if (!strv_isempty(u->requires_mounts_for)) {
+ fprintf(f,
+ "%s\tRequiresMountsFor:", prefix);
+
+ STRV_FOREACH(j, u->requires_mounts_for)
+ fprintf(f, " %s", *j);
+
+ fputs("\n", f);
+ }
+
+ if (u->load_state == UNIT_LOADED) {
+ CGroupBonding *b;
+ CGroupAttribute *a;
+
+ fprintf(f,
+ "%s\tStopWhenUnneeded: %s\n"
+ "%s\tRefuseManualStart: %s\n"
+ "%s\tRefuseManualStop: %s\n"
+ "%s\tDefaultDependencies: %s\n"
+ "%s\tOnFailureIsolate: %s\n"
+ "%s\tIgnoreOnIsolate: %s\n"
+ "%s\tIgnoreOnSnapshot: %s\n",
+ prefix, yes_no(u->stop_when_unneeded),
+ prefix, yes_no(u->refuse_manual_start),
+ prefix, yes_no(u->refuse_manual_stop),
+ prefix, yes_no(u->default_dependencies),
+ prefix, yes_no(u->on_failure_isolate),
+ prefix, yes_no(u->ignore_on_isolate),
+ prefix, yes_no(u->ignore_on_snapshot));
+
+ LIST_FOREACH(by_unit, b, u->cgroup_bondings)
+ fprintf(f, "%s\tControlGroup: %s:%s\n",
+ prefix, b->controller, b->path);
+
+ LIST_FOREACH(by_unit, a, u->cgroup_attributes) {
+ _cleanup_free_ char *v = NULL;
+
+ if (a->semantics && a->semantics->map_write)
+ a->semantics->map_write(a->semantics, a->value, &v);
+
+ fprintf(f, "%s\tControlGroupAttribute: %s %s \"%s\"\n",
+ prefix, a->controller, a->name, v ? v : a->value);
+ }
+
+ if (UNIT_VTABLE(u)->dump)
+ UNIT_VTABLE(u)->dump(u, f, prefix2);
+
+ } else if (u->load_state == UNIT_MERGED)
+ fprintf(f,
+ "%s\tMerged into: %s\n",
+ prefix, u->merged_into->id);
+ else if (u->load_state == UNIT_ERROR)
+ fprintf(f, "%s\tLoad Error Code: %s\n", prefix, strerror(-u->load_error));
+
+
+ if (u->job)
+ job_dump(u->job, f, prefix2);
+
+ if (u->nop_job)
+ job_dump(u->nop_job, f, prefix2);
+
+ free(p2);
+}
+
+/* Common implementation for multiple backends */
+int unit_load_fragment_and_dropin(Unit *u) {
+ int r;
+
+ assert(u);
+
+ /* Load a .service file */
+ if ((r = unit_load_fragment(u)) < 0)
+ return r;
+
+ if (u->load_state == UNIT_STUB)
+ return -ENOENT;
+
+ /* Load drop-in directory data */
+ if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
+ return r;
+
+ return 0;
+}
+
+/* Common implementation for multiple backends */
+int unit_load_fragment_and_dropin_optional(Unit *u) {
+ int r;
+
+ assert(u);
+
+ /* Same as unit_load_fragment_and_dropin(), but whether
+ * something can be loaded or not doesn't matter. */
+
+ /* Load a .service file */
+ if ((r = unit_load_fragment(u)) < 0)
+ return r;
+
+ if (u->load_state == UNIT_STUB)
+ u->load_state = UNIT_LOADED;
+
+ /* Load drop-in directory data */
+ if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
+ return r;
+
+ return 0;
+}
+
+int unit_add_default_target_dependency(Unit *u, Unit *target) {
+ assert(u);
+ assert(target);
+
+ if (target->type != UNIT_TARGET)
+ return 0;
+
+ /* Only add the dependency if both units are loaded, so that
+ * that loop check below is reliable */
+ if (u->load_state != UNIT_LOADED ||
+ target->load_state != UNIT_LOADED)
+ return 0;
+
+ /* If either side wants no automatic dependencies, then let's
+ * skip this */
+ if (!u->default_dependencies ||
+ !target->default_dependencies)
+ return 0;
+
+ /* Don't create loops */
+ if (set_get(target->dependencies[UNIT_BEFORE], u))
+ return 0;
+
+ return unit_add_dependency(target, UNIT_AFTER, u, true);
+}
+
+static int unit_add_default_dependencies(Unit *u) {
+ static const UnitDependency deps[] = {
+ UNIT_REQUIRED_BY,
+ UNIT_REQUIRED_BY_OVERRIDABLE,
+ UNIT_WANTED_BY,
+ UNIT_BOUND_BY
+ };
+
+ Unit *target;
+ Iterator i;
+ int r;
+ unsigned k;
+
+ assert(u);
+
+ for (k = 0; k < ELEMENTSOF(deps); k++)
+ SET_FOREACH(target, u->dependencies[deps[k]], i)
+ if ((r = unit_add_default_target_dependency(u, target)) < 0)
+ return r;
+
+ return 0;
+}
+
+int unit_load(Unit *u) {
+ int r;
+
+ assert(u);
+
+ if (u->in_load_queue) {
+ LIST_REMOVE(Unit, load_queue, u->manager->load_queue, u);
+ u->in_load_queue = false;
+ }
+
+ if (u->type == _UNIT_TYPE_INVALID)
+ return -EINVAL;
+
+ if (u->load_state != UNIT_STUB)
+ return 0;
+
+ if (UNIT_VTABLE(u)->load)
+ if ((r = UNIT_VTABLE(u)->load(u)) < 0)
+ goto fail;
+
+ if (u->load_state == UNIT_STUB) {
+ r = -ENOENT;
+ goto fail;
+ }
+
+ if (u->load_state == UNIT_LOADED &&
+ u->default_dependencies)
+ if ((r = unit_add_default_dependencies(u)) < 0)
+ goto fail;
+
+ if (u->load_state == UNIT_LOADED) {
+ r = unit_add_mount_links(u);
+ if (r < 0)
+ return r;
+ }
+
+ if (u->on_failure_isolate &&
+ set_size(u->dependencies[UNIT_ON_FAILURE]) > 1) {
+
+ log_error_unit(u->id,
+ "More than one OnFailure= dependencies specified for %s but OnFailureIsolate= enabled. Refusing.", u->id);
+
+ r = -EINVAL;
+ goto fail;
+ }
+
+ assert((u->load_state != UNIT_MERGED) == !u->merged_into);
+
+ unit_add_to_dbus_queue(unit_follow_merge(u));
+ unit_add_to_gc_queue(u);
+
+ return 0;
+
+fail:
+ u->load_state = UNIT_ERROR;
+ u->load_error = r;
+ unit_add_to_dbus_queue(u);
+ unit_add_to_gc_queue(u);
+
+ log_debug_unit(u->id, "Failed to load configuration for %s: %s",
+ u->id, strerror(-r));
+
+ return r;
+}
+
+bool unit_condition_test(Unit *u) {
+ assert(u);
+
+ dual_timestamp_get(&u->condition_timestamp);
+ u->condition_result = condition_test_list(u->conditions);
+
+ return u->condition_result;
+}
+
+_pure_ static const char* unit_get_status_message_format(Unit *u, JobType t) {
+ const UnitStatusMessageFormats *format_table;
+
+ assert(u);
+ assert(t >= 0);
+ assert(t < _JOB_TYPE_MAX);
+
+ if (t != JOB_START && t != JOB_STOP)
+ return NULL;
+
+ format_table = &UNIT_VTABLE(u)->status_message_formats;
+ if (!format_table)
+ return NULL;
+
+ return format_table->starting_stopping[t == JOB_STOP];
+}
+
+_pure_ static const char *unit_get_status_message_format_try_harder(Unit *u, JobType t) {
+ const char *format;
+
+ assert(u);
+ assert(t >= 0);
+ assert(t < _JOB_TYPE_MAX);
+
+ format = unit_get_status_message_format(u, t);
+ if (format)
+ return format;
+
+ /* Return generic strings */
+ if (t == JOB_START)
+ return "Starting %s.";
+ else if (t == JOB_STOP)
+ return "Stopping %s.";
+ else if (t == JOB_RELOAD)
+ return "Reloading %s.";
+
+ return NULL;
+}
+
+static void unit_status_print_starting_stopping(Unit *u, JobType t) {
+ const char *format;
+
+ assert(u);
+
+ /* We only print status messages for selected units on
+ * selected operations. */
+
+ format = unit_get_status_message_format(u, t);
+ if (!format)
+ return;
+
+ unit_status_printf(u, "", format);
+}
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wformat-nonliteral"
+static void unit_status_log_starting_stopping_reloading(Unit *u, JobType t) {
+ const char *format;
+ char buf[LINE_MAX];
+ sd_id128_t mid;
+
+ assert(u);
+
+ if (t != JOB_START && t != JOB_STOP && t != JOB_RELOAD)
+ return;
+
+ if (log_on_console())
+ return;
+
+ /* We log status messages for all units and all operations. */
+
+ format = unit_get_status_message_format_try_harder(u, t);
+ if (!format)
+ return;
+
+ snprintf(buf, sizeof(buf), format, unit_description(u));
+ char_array_0(buf);
+
+ mid = t == JOB_START ? SD_MESSAGE_UNIT_STARTING :
+ t == JOB_STOP ? SD_MESSAGE_UNIT_STOPPING :
+ SD_MESSAGE_UNIT_RELOADING;
+
+ log_struct_unit(LOG_INFO,
+ u->id,
+ MESSAGE_ID(mid),
+ "MESSAGE=%s", buf,
+ NULL);
+}
+#pragma GCC diagnostic pop
+
+/* Errors:
+ * -EBADR: This unit type does not support starting.
+ * -EALREADY: Unit is already started.
+ * -EAGAIN: An operation is already in progress. Retry later.
+ * -ECANCELED: Too many requests for now.
+ */
+int unit_start(Unit *u) {
+ UnitActiveState state;
+ Unit *following;
+
+ assert(u);
+
+ if (u->load_state != UNIT_LOADED)
+ return -EINVAL;
+
+ /* If this is already started, then this will succeed. Note
+ * that this will even succeed if this unit is not startable
+ * by the user. This is relied on to detect when we need to
+ * wait for units and when waiting is finished. */
+ state = unit_active_state(u);
+ if (UNIT_IS_ACTIVE_OR_RELOADING(state))
+ return -EALREADY;
+
+ /* If the conditions failed, don't do anything at all. If we
+ * already are activating this call might still be useful to
+ * speed up activation in case there is some hold-off time,
+ * but we don't want to recheck the condition in that case. */
+ if (state != UNIT_ACTIVATING &&
+ !unit_condition_test(u)) {
+ log_debug_unit(u->id, "Starting of %s requested but condition failed. Ignoring.", u->id);
+ return -EALREADY;
+ }
+
+ /* Forward to the main object, if we aren't it. */
+ if ((following = unit_following(u))) {
+ log_debug_unit(u->id, "Redirecting start request from %s to %s.",
+ u->id, following->id);
+ return unit_start(following);
+ }
+
+ unit_status_log_starting_stopping_reloading(u, JOB_START);
+ unit_status_print_starting_stopping(u, JOB_START);
+
+ /* If it is stopped, but we cannot start it, then fail */
+ if (!UNIT_VTABLE(u)->start)
+ return -EBADR;
+
+ /* We don't suppress calls to ->start() here when we are
+ * already starting, to allow this request to be used as a
+ * "hurry up" call, for example when the unit is in some "auto
+ * restart" state where it waits for a holdoff timer to elapse
+ * before it will start again. */
+
+ unit_add_to_dbus_queue(u);
+
+ return UNIT_VTABLE(u)->start(u);
+}
+
+bool unit_can_start(Unit *u) {
+ assert(u);
+
+ return !!UNIT_VTABLE(u)->start;
+}
+
+bool unit_can_isolate(Unit *u) {
+ assert(u);
+
+ return unit_can_start(u) &&
+ u->allow_isolate;
+}
+
+/* Errors:
+ * -EBADR: This unit type does not support stopping.
+ * -EALREADY: Unit is already stopped.
+ * -EAGAIN: An operation is already in progress. Retry later.
+ */
+int unit_stop(Unit *u) {
+ UnitActiveState state;
+ Unit *following;
+
+ assert(u);
+
+ state = unit_active_state(u);
+ if (UNIT_IS_INACTIVE_OR_FAILED(state))
+ return -EALREADY;
+
+ if ((following = unit_following(u))) {
+ log_debug_unit(u->id, "Redirecting stop request from %s to %s.",
+ u->id, following->id);
+ return unit_stop(following);
+ }
+
+ unit_status_log_starting_stopping_reloading(u, JOB_STOP);
+ unit_status_print_starting_stopping(u, JOB_STOP);
+
+ if (!UNIT_VTABLE(u)->stop)
+ return -EBADR;
+
+ unit_add_to_dbus_queue(u);
+
+ return UNIT_VTABLE(u)->stop(u);
+}
+
+/* Errors:
+ * -EBADR: This unit type does not support reloading.
+ * -ENOEXEC: Unit is not started.
+ * -EAGAIN: An operation is already in progress. Retry later.
+ */
+int unit_reload(Unit *u) {
+ UnitActiveState state;
+ Unit *following;
+
+ assert(u);
+
+ if (u->load_state != UNIT_LOADED)
+ return -EINVAL;
+
+ if (!unit_can_reload(u))
+ return -EBADR;
+
+ state = unit_active_state(u);
+ if (state == UNIT_RELOADING)
+ return -EALREADY;
+
+ if (state != UNIT_ACTIVE)
+ return -ENOEXEC;
+
+ if ((following = unit_following(u))) {
+ log_debug_unit(u->id, "Redirecting reload request from %s to %s.",
+ u->id, following->id);
+ return unit_reload(following);
+ }
+
+ unit_status_log_starting_stopping_reloading(u, JOB_RELOAD);
+
+ unit_add_to_dbus_queue(u);
+ return UNIT_VTABLE(u)->reload(u);
+}
+
+bool unit_can_reload(Unit *u) {
+ assert(u);
+
+ if (!UNIT_VTABLE(u)->reload)
+ return false;
+
+ if (!UNIT_VTABLE(u)->can_reload)
+ return true;
+
+ return UNIT_VTABLE(u)->can_reload(u);
+}
+
+static void unit_check_unneeded(Unit *u) {
+ Iterator i;
+ Unit *other;
+
+ assert(u);
+
+ /* If this service shall be shut down when unneeded then do
+ * so. */
+
+ if (!u->stop_when_unneeded)
+ return;
+
+ if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
+ return;
+
+ SET_FOREACH(other, u->dependencies[UNIT_REQUIRED_BY], i)
+ if (unit_active_or_pending(other))
+ return;
+
+ SET_FOREACH(other, u->dependencies[UNIT_REQUIRED_BY_OVERRIDABLE], i)
+ if (unit_active_or_pending(other))
+ return;
+
+ SET_FOREACH(other, u->dependencies[UNIT_WANTED_BY], i)
+ if (unit_active_or_pending(other))
+ return;
+
+ SET_FOREACH(other, u->dependencies[UNIT_BOUND_BY], i)
+ if (unit_active_or_pending(other))
+ return;
+
+ log_info_unit(u->id, "Service %s is not needed anymore. Stopping.", u->id);
+
+ /* Ok, nobody needs us anymore. Sniff. Then let's commit suicide */
+ manager_add_job(u->manager, JOB_STOP, u, JOB_FAIL, true, NULL, NULL);
+}
+
+static void retroactively_start_dependencies(Unit *u) {
+ Iterator i;
+ Unit *other;
+
+ assert(u);
+ assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)));
+
+ SET_FOREACH(other, u->dependencies[UNIT_REQUIRES], i)
+ if (!set_get(u->dependencies[UNIT_AFTER], other) &&
+ !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
+ manager_add_job(u->manager, JOB_START, other, JOB_REPLACE, true, NULL, NULL);
+
+ SET_FOREACH(other, u->dependencies[UNIT_BINDS_TO], i)
+ if (!set_get(u->dependencies[UNIT_AFTER], other) &&
+ !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
+ manager_add_job(u->manager, JOB_START, other, JOB_REPLACE, true, NULL, NULL);
+
+ SET_FOREACH(other, u->dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
+ if (!set_get(u->dependencies[UNIT_AFTER], other) &&
+ !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
+ manager_add_job(u->manager, JOB_START, other, JOB_FAIL, false, NULL, NULL);
+
+ SET_FOREACH(other, u->dependencies[UNIT_WANTS], i)
+ if (!set_get(u->dependencies[UNIT_AFTER], other) &&
+ !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
+ manager_add_job(u->manager, JOB_START, other, JOB_FAIL, false, NULL, NULL);
+
+ SET_FOREACH(other, u->dependencies[UNIT_CONFLICTS], i)
+ if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
+ manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, true, NULL, NULL);
+
+ SET_FOREACH(other, u->dependencies[UNIT_CONFLICTED_BY], i)
+ if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
+ manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, true, NULL, NULL);
+}
+
+static void retroactively_stop_dependencies(Unit *u) {
+ Iterator i;
+ Unit *other;
+
+ assert(u);
+ assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
+
+ /* Pull down units which are bound to us recursively if enabled */
+ SET_FOREACH(other, u->dependencies[UNIT_BOUND_BY], i)
+ if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
+ manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, true, NULL, NULL);
+}
+
+static void check_unneeded_dependencies(Unit *u) {
+ Iterator i;
+ Unit *other;
+
+ assert(u);
+ assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
+
+ /* Garbage collect services that might not be needed anymore, if enabled */
+ SET_FOREACH(other, u->dependencies[UNIT_REQUIRES], i)
+ if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
+ unit_check_unneeded(other);
+ SET_FOREACH(other, u->dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
+ if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
+ unit_check_unneeded(other);
+ SET_FOREACH(other, u->dependencies[UNIT_WANTS], i)
+ if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
+ unit_check_unneeded(other);
+ SET_FOREACH(other, u->dependencies[UNIT_REQUISITE], i)
+ if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
+ unit_check_unneeded(other);
+ SET_FOREACH(other, u->dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
+ if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
+ unit_check_unneeded(other);
+ SET_FOREACH(other, u->dependencies[UNIT_BINDS_TO], i)
+ if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
+ unit_check_unneeded(other);
+}
+
+void unit_start_on_failure(Unit *u) {
+ Unit *other;
+ Iterator i;
+
+ assert(u);
+
+ if (set_size(u->dependencies[UNIT_ON_FAILURE]) <= 0)
+ return;
+
+ log_info_unit(u->id, "Triggering OnFailure= dependencies of %s.", u->id);
+
+ SET_FOREACH(other, u->dependencies[UNIT_ON_FAILURE], i) {
+ int r;
+
+ r = manager_add_job(u->manager, JOB_START, other, u->on_failure_isolate ? JOB_ISOLATE : JOB_REPLACE, true, NULL, NULL);
+ if (r < 0)
+ log_error_unit(u->id, "Failed to enqueue OnFailure= job: %s", strerror(-r));
+ }
+}
+
+void unit_trigger_notify(Unit *u) {
+ Unit *other;
+ Iterator i;
+
+ assert(u);
+
+ SET_FOREACH(other, u->dependencies[UNIT_TRIGGERED_BY], i)
+ if (UNIT_VTABLE(other)->trigger_notify)
+ UNIT_VTABLE(other)->trigger_notify(other, u);
+}
+
+void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns, bool reload_success) {
+ Manager *m;
+ bool unexpected;
+
+ assert(u);
+ assert(os < _UNIT_ACTIVE_STATE_MAX);
+ assert(ns < _UNIT_ACTIVE_STATE_MAX);
+
+ /* Note that this is called for all low-level state changes,
+ * even if they might map to the same high-level
+ * UnitActiveState! That means that ns == os is OK an expected
+ * behavior here. For example: if a mount point is remounted
+ * this function will be called too! */
+
+ m = u->manager;
+
+ if (m->n_reloading <= 0) {
+ dual_timestamp ts;
+
+ dual_timestamp_get(&ts);
+
+ if (UNIT_IS_INACTIVE_OR_FAILED(os) && !UNIT_IS_INACTIVE_OR_FAILED(ns))
+ u->inactive_exit_timestamp = ts;
+ else if (!UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_INACTIVE_OR_FAILED(ns))
+ u->inactive_enter_timestamp = ts;
+
+ if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns))
+ u->active_enter_timestamp = ts;
+ else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns))
+ u->active_exit_timestamp = ts;
+ }
+
+ if (UNIT_IS_INACTIVE_OR_FAILED(ns))
+ cgroup_bonding_trim_list(u->cgroup_bondings, true);
+
+ if (UNIT_IS_INACTIVE_OR_FAILED(os) != UNIT_IS_INACTIVE_OR_FAILED(ns)) {
+ ExecContext *ec = unit_get_exec_context(u);
+ if (ec && exec_context_may_touch_console(ec)) {
+ if (UNIT_IS_INACTIVE_OR_FAILED(ns))
+ m->n_on_console--;
+ else
+ m->n_on_console++;
+ }
+ }
+
+ if (u->job) {
+ unexpected = false;
+
+ if (u->job->state == JOB_WAITING)
+
+ /* So we reached a different state for this
+ * job. Let's see if we can run it now if it
+ * failed previously due to EAGAIN. */
+ job_add_to_run_queue(u->job);
+
+ /* Let's check whether this state change constitutes a
+ * finished job, or maybe contradicts a running job and
+ * hence needs to invalidate jobs. */
+
+ switch (u->job->type) {
+
+ case JOB_START:
+ case JOB_VERIFY_ACTIVE:
+
+ if (UNIT_IS_ACTIVE_OR_RELOADING(ns))
+ job_finish_and_invalidate(u->job, JOB_DONE, true);
+ else if (u->job->state == JOB_RUNNING && ns != UNIT_ACTIVATING) {
+ unexpected = true;
+
+ if (UNIT_IS_INACTIVE_OR_FAILED(ns))
+ job_finish_and_invalidate(u->job, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE, true);
+ }
+
+ break;
+
+ case JOB_RELOAD:
+ case JOB_RELOAD_OR_START:
+
+ if (u->job->state == JOB_RUNNING) {
+ if (ns == UNIT_ACTIVE)
+ job_finish_and_invalidate(u->job, reload_success ? JOB_DONE : JOB_FAILED, true);
+ else if (ns != UNIT_ACTIVATING && ns != UNIT_RELOADING) {
+ unexpected = true;
+
+ if (UNIT_IS_INACTIVE_OR_FAILED(ns))
+ job_finish_and_invalidate(u->job, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE, true);
+ }
+ }
+
+ break;
+
+ case JOB_STOP:
+ case JOB_RESTART:
+ case JOB_TRY_RESTART:
+
+ if (UNIT_IS_INACTIVE_OR_FAILED(ns))
+ job_finish_and_invalidate(u->job, JOB_DONE, true);
+ else if (u->job->state == JOB_RUNNING && ns != UNIT_DEACTIVATING) {
+ unexpected = true;
+ job_finish_and_invalidate(u->job, JOB_FAILED, true);
+ }
+
+ break;
+
+ default:
+ assert_not_reached("Job type unknown");
+ }
+
+ } else
+ unexpected = true;
+
+ if (m->n_reloading <= 0) {
+
+ /* If this state change happened without being
+ * requested by a job, then let's retroactively start
+ * or stop dependencies. We skip that step when
+ * deserializing, since we don't want to create any
+ * additional jobs just because something is already
+ * activated. */
+
+ if (unexpected) {
+ if (UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
+ retroactively_start_dependencies(u);
+ else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
+ retroactively_stop_dependencies(u);
+ }
+
+ /* stop unneeded units regardless if going down was expected or not */
+ if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
+ check_unneeded_dependencies(u);
+
+ if (ns != os && ns == UNIT_FAILED) {
+ log_notice_unit(u->id,
+ "Unit %s entered failed state.", u->id);
+ unit_start_on_failure(u);
+ }
+ }
+
+ /* Some names are special */
+ if (UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
+
+ if (unit_has_name(u, SPECIAL_DBUS_SERVICE))
+ /* The bus just might have become available,
+ * hence try to connect to it, if we aren't
+ * yet connected. */
+ bus_init(m, true);
+
+ if (u->type == UNIT_SERVICE &&
+ !UNIT_IS_ACTIVE_OR_RELOADING(os) &&
+ m->n_reloading <= 0) {
+ /* Write audit record if we have just finished starting up */
+ manager_send_unit_audit(m, u, AUDIT_SERVICE_START, true);
+ u->in_audit = true;
+ }
+
+ if (!UNIT_IS_ACTIVE_OR_RELOADING(os))
+ manager_send_unit_plymouth(m, u);
+
+ } else {
+
+ /* We don't care about D-Bus here, since we'll get an
+ * asynchronous notification for it anyway. */
+
+ if (u->type == UNIT_SERVICE &&
+ UNIT_IS_INACTIVE_OR_FAILED(ns) &&
+ !UNIT_IS_INACTIVE_OR_FAILED(os) &&
+ m->n_reloading <= 0) {
+
+ /* Hmm, if there was no start record written
+ * write it now, so that we always have a nice
+ * pair */
+ if (!u->in_audit) {
+ manager_send_unit_audit(m, u, AUDIT_SERVICE_START, ns == UNIT_INACTIVE);
+
+ if (ns == UNIT_INACTIVE)
+ manager_send_unit_audit(m, u, AUDIT_SERVICE_STOP, true);
+ } else
+ /* Write audit record if we have just finished shutting down */
+ manager_send_unit_audit(m, u, AUDIT_SERVICE_STOP, ns == UNIT_INACTIVE);
+
+ u->in_audit = false;
+ }
+ }
+
+ manager_recheck_journal(m);
+ unit_trigger_notify(u);
+
+ /* Maybe we finished startup and are now ready for being
+ * stopped because unneeded? */
+ if (u->manager->n_reloading <= 0)
+ unit_check_unneeded(u);
+
+ unit_add_to_dbus_queue(u);
+ unit_add_to_gc_queue(u);
+}
+
+int unit_watch_fd(Unit *u, int fd, uint32_t events, Watch *w) {
+ struct epoll_event ev = {
+ .data.ptr = w,
+ .events = events,
+ };
+
+ assert(u);
+ assert(fd >= 0);
+ assert(w);
+ assert(w->type == WATCH_INVALID || (w->type == WATCH_FD && w->fd == fd && w->data.unit == u));
+
+ if (epoll_ctl(u->manager->epoll_fd,
+ w->type == WATCH_INVALID ? EPOLL_CTL_ADD : EPOLL_CTL_MOD,
+ fd,
+ &ev) < 0)
+ return -errno;
+
+ w->fd = fd;
+ w->type = WATCH_FD;
+ w->data.unit = u;
+
+ return 0;
+}
+
+void unit_unwatch_fd(Unit *u, Watch *w) {
+ assert(u);
+ assert(w);
+
+ if (w->type == WATCH_INVALID)
+ return;
+
+ assert(w->type == WATCH_FD);
+ assert(w->data.unit == u);
+ assert_se(epoll_ctl(u->manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
+
+ w->fd = -1;
+ w->type = WATCH_INVALID;
+ w->data.unit = NULL;
+}
+
+int unit_watch_pid(Unit *u, pid_t pid) {
+ assert(u);
+ assert(pid >= 1);
+
+ /* Watch a specific PID. We only support one unit watching
+ * each PID for now. */
+
+ return hashmap_put(u->manager->watch_pids, LONG_TO_PTR(pid), u);
+}
+
+void unit_unwatch_pid(Unit *u, pid_t pid) {
+ assert(u);
+ assert(pid >= 1);
+
+ hashmap_remove_value(u->manager->watch_pids, LONG_TO_PTR(pid), u);
+}
+
+int unit_watch_timer(Unit *u, clockid_t clock_id, bool relative, usec_t usec, Watch *w) {
+ struct itimerspec its = {};
+ int flags, fd;
+ bool ours;
+
+ assert(u);
+ assert(w);
+ assert(w->type == WATCH_INVALID || (w->type == WATCH_UNIT_TIMER && w->data.unit == u));
+
+ /* This will try to reuse the old timer if there is one */
+
+ if (w->type == WATCH_UNIT_TIMER) {
+ assert(w->data.unit == u);
+ assert(w->fd >= 0);
+
+ ours = false;
+ fd = w->fd;
+ } else if (w->type == WATCH_INVALID) {
+
+ ours = true;
+ fd = timerfd_create(clock_id, TFD_NONBLOCK|TFD_CLOEXEC);
+ if (fd < 0)
+ return -errno;
+ } else
+ assert_not_reached("Invalid watch type");
+
+ if (usec <= 0) {
+ /* Set absolute time in the past, but not 0, since we
+ * don't want to disarm the timer */
+ its.it_value.tv_sec = 0;
+ its.it_value.tv_nsec = 1;
+
+ flags = TFD_TIMER_ABSTIME;
+ } else {
+ timespec_store(&its.it_value, usec);
+ flags = relative ? 0 : TFD_TIMER_ABSTIME;
+ }
+
+ /* This will also flush the elapse counter */
+ if (timerfd_settime(fd, flags, &its, NULL) < 0)
+ goto fail;
+
+ if (w->type == WATCH_INVALID) {
+ struct epoll_event ev = {
+ .data.ptr = w,
+ .events = EPOLLIN,
+ };
+
+ if (epoll_ctl(u->manager->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0)
+ goto fail;
+ }
+
+ w->type = WATCH_UNIT_TIMER;
+ w->fd = fd;
+ w->data.unit = u;
+
+ return 0;
+
+fail:
+ if (ours)
+ close_nointr_nofail(fd);
+
+ return -errno;
+}
+
+void unit_unwatch_timer(Unit *u, Watch *w) {
+ assert(u);
+ assert(w);
+
+ if (w->type == WATCH_INVALID)
+ return;
+
+ assert(w->type == WATCH_UNIT_TIMER);
+ assert(w->data.unit == u);
+ assert(w->fd >= 0);
+
+ assert_se(epoll_ctl(u->manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
+ close_nointr_nofail(w->fd);
+
+ w->fd = -1;
+ w->type = WATCH_INVALID;
+ w->data.unit = NULL;
+}
+
+bool unit_job_is_applicable(Unit *u, JobType j) {
+ assert(u);
+ assert(j >= 0 && j < _JOB_TYPE_MAX);
+
+ switch (j) {
+
+ case JOB_VERIFY_ACTIVE:
+ case JOB_START:
+ case JOB_STOP:
+ case JOB_NOP:
+ return true;
+
+ case JOB_RESTART:
+ case JOB_TRY_RESTART:
+ return unit_can_start(u);
+
+ case JOB_RELOAD:
+ return unit_can_reload(u);
+
+ case JOB_RELOAD_OR_START:
+ return unit_can_reload(u) && unit_can_start(u);
+
+ default:
+ assert_not_reached("Invalid job type");
+ }
+}
+
+int unit_add_dependency(Unit *u, UnitDependency d, Unit *other, bool add_reference) {
+
+ static const UnitDependency inverse_table[_UNIT_DEPENDENCY_MAX] = {
+ [UNIT_REQUIRES] = UNIT_REQUIRED_BY,
+ [UNIT_REQUIRES_OVERRIDABLE] = UNIT_REQUIRED_BY_OVERRIDABLE,
+ [UNIT_WANTS] = UNIT_WANTED_BY,
+ [UNIT_REQUISITE] = UNIT_REQUIRED_BY,
+ [UNIT_REQUISITE_OVERRIDABLE] = UNIT_REQUIRED_BY_OVERRIDABLE,
+ [UNIT_BINDS_TO] = UNIT_BOUND_BY,
+ [UNIT_PART_OF] = UNIT_CONSISTS_OF,
+ [UNIT_REQUIRED_BY] = _UNIT_DEPENDENCY_INVALID,
+ [UNIT_REQUIRED_BY_OVERRIDABLE] = _UNIT_DEPENDENCY_INVALID,
+ [UNIT_WANTED_BY] = _UNIT_DEPENDENCY_INVALID,
+ [UNIT_BOUND_BY] = UNIT_BINDS_TO,
+ [UNIT_CONSISTS_OF] = UNIT_PART_OF,
+ [UNIT_CONFLICTS] = UNIT_CONFLICTED_BY,
+ [UNIT_CONFLICTED_BY] = UNIT_CONFLICTS,
+ [UNIT_BEFORE] = UNIT_AFTER,
+ [UNIT_AFTER] = UNIT_BEFORE,
+ [UNIT_ON_FAILURE] = _UNIT_DEPENDENCY_INVALID,
+ [UNIT_REFERENCES] = UNIT_REFERENCED_BY,
+ [UNIT_REFERENCED_BY] = UNIT_REFERENCES,
+ [UNIT_TRIGGERS] = UNIT_TRIGGERED_BY,
+ [UNIT_TRIGGERED_BY] = UNIT_TRIGGERS,
+ [UNIT_PROPAGATES_RELOAD_TO] = UNIT_RELOAD_PROPAGATED_FROM,
+ [UNIT_RELOAD_PROPAGATED_FROM] = UNIT_PROPAGATES_RELOAD_TO,
+ };
+ int r, q = 0, v = 0, w = 0;
+
+ assert(u);
+ assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
+ assert(other);
+
+ u = unit_follow_merge(u);
+ other = unit_follow_merge(other);
+
+ /* We won't allow dependencies on ourselves. We will not
+ * consider them an error however. */
+ if (u == other)
+ return 0;
+
+ if ((r = set_ensure_allocated(&u->dependencies[d], trivial_hash_func, trivial_compare_func)) < 0)
+ return r;
+
+ if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID)
+ if ((r = set_ensure_allocated(&other->dependencies[inverse_table[d]], trivial_hash_func, trivial_compare_func)) < 0)
+ return r;
+
+ if (add_reference)
+ if ((r = set_ensure_allocated(&u->dependencies[UNIT_REFERENCES], trivial_hash_func, trivial_compare_func)) < 0 ||
+ (r = set_ensure_allocated(&other->dependencies[UNIT_REFERENCED_BY], trivial_hash_func, trivial_compare_func)) < 0)
+ return r;
+
+ if ((q = set_put(u->dependencies[d], other)) < 0)
+ return q;
+
+ if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID)
+ if ((v = set_put(other->dependencies[inverse_table[d]], u)) < 0) {
+ r = v;
+ goto fail;
+ }
+
+ if (add_reference) {
+ if ((w = set_put(u->dependencies[UNIT_REFERENCES], other)) < 0) {
+ r = w;
+ goto fail;
+ }
+
+ if ((r = set_put(other->dependencies[UNIT_REFERENCED_BY], u)) < 0)
+ goto fail;
+ }
+
+ unit_add_to_dbus_queue(u);
+ return 0;
+
+fail:
+ if (q > 0)
+ set_remove(u->dependencies[d], other);
+
+ if (v > 0)
+ set_remove(other->dependencies[inverse_table[d]], u);
+
+ if (w > 0)
+ set_remove(u->dependencies[UNIT_REFERENCES], other);
+
+ return r;
+}
+
+int unit_add_two_dependencies(Unit *u, UnitDependency d, UnitDependency e, Unit *other, bool add_reference) {
+ int r;
+
+ assert(u);
+
+ if ((r = unit_add_dependency(u, d, other, add_reference)) < 0)
+ return r;
+
+ if ((r = unit_add_dependency(u, e, other, add_reference)) < 0)
+ return r;
+
+ return 0;
+}
+
+static const char *resolve_template(Unit *u, const char *name, const char*path, char **p) {
+ char *s;
+
+ assert(u);
+ assert(name || path);
+ assert(p);
+
+ if (!name)
+ name = path_get_file_name(path);
+
+ if (!unit_name_is_template(name)) {
+ *p = NULL;
+ return name;
+ }
+
+ if (u->instance)
+ s = unit_name_replace_instance(name, u->instance);
+ else {
+ _cleanup_free_ char *i = NULL;
+
+ i = unit_name_to_prefix(u->id);
+ if (!i)
+ return NULL;
+
+ s = unit_name_replace_instance(name, i);
+ }
+
+ if (!s)
+ return NULL;
+
+ *p = s;
+ return s;
+}
+
+int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) {
+ Unit *other;
+ int r;
+ _cleanup_free_ char *s = NULL;
+
+ assert(u);
+ assert(name || path);
+
+ name = resolve_template(u, name, path, &s);
+ if (!name)
+ return -ENOMEM;
+
+ r = manager_load_unit(u->manager, name, path, NULL, &other);
+ if (r < 0)
+ return r;
+
+ return unit_add_dependency(u, d, other, add_reference);
+}
+
+int unit_add_two_dependencies_by_name(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference) {
+ Unit *other;
+ int r;
+ char *s;
+
+ assert(u);
+ assert(name || path);
+
+ if (!(name = resolve_template(u, name, path, &s)))
+ return -ENOMEM;
+
+ if ((r = manager_load_unit(u->manager, name, path, NULL, &other)) < 0)
+ goto finish;
+
+ r = unit_add_two_dependencies(u, d, e, other, add_reference);
+
+finish:
+ free(s);
+ return r;
+}
+
+int unit_add_dependency_by_name_inverse(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) {
+ Unit *other;
+ int r;
+ char *s;
+
+ assert(u);
+ assert(name || path);
+
+ if (!(name = resolve_template(u, name, path, &s)))
+ return -ENOMEM;
+
+ if ((r = manager_load_unit(u->manager, name, path, NULL, &other)) < 0)
+ goto finish;
+
+ r = unit_add_dependency(other, d, u, add_reference);
+
+finish:
+ free(s);
+ return r;
+}
+
+int unit_add_two_dependencies_by_name_inverse(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference) {
+ Unit *other;
+ int r;
+ char *s;
+
+ assert(u);
+ assert(name || path);
+
+ if (!(name = resolve_template(u, name, path, &s)))
+ return -ENOMEM;
+
+ if ((r = manager_load_unit(u->manager, name, path, NULL, &other)) < 0)
+ goto finish;
+
+ if ((r = unit_add_two_dependencies(other, d, e, u, add_reference)) < 0)
+ goto finish;
+
+finish:
+ free(s);
+ return r;
+}
+
+int set_unit_path(const char *p) {
+ _cleanup_free_ char *c = NULL;
+
+ /* This is mostly for debug purposes */
+ c = path_make_absolute_cwd(p);
+ if (setenv("SYSTEMD_UNIT_PATH", c, 0) < 0)
+ return -errno;
+
+ return 0;
+}
+
+char *unit_dbus_path(Unit *u) {
+ assert(u);
+
+ if (!u->id)
+ return NULL;
+
+ return unit_dbus_path_from_name(u->id);
+}
+
+static int unit_add_cgroup(Unit *u, CGroupBonding *b) {
+ int r;
+
+ assert(u);
+ assert(b);
+
+ assert(b->path);
+
+ if (!b->controller) {
+ b->controller = strdup(SYSTEMD_CGROUP_CONTROLLER);
+ if (!b->controller)
+ return log_oom();
+
+ b->ours = true;
+ }
+
+ /* Ensure this hasn't been added yet */
+ assert(!b->unit);
+
+ if (streq(b->controller, SYSTEMD_CGROUP_CONTROLLER)) {
+ CGroupBonding *l;
+
+ l = hashmap_get(u->manager->cgroup_bondings, b->path);
+ LIST_PREPEND(CGroupBonding, by_path, l, b);
+
+ r = hashmap_replace(u->manager->cgroup_bondings, b->path, l);
+ if (r < 0) {
+ LIST_REMOVE(CGroupBonding, by_path, l, b);
+ return r;
+ }
+ }
+
+ LIST_PREPEND(CGroupBonding, by_unit, u->cgroup_bondings, b);
+ b->unit = u;
+
+ return 0;
+}
+
+char *unit_default_cgroup_path(Unit *u) {
+ _cleanup_free_ char *escaped_instance = NULL;
+
+ assert(u);
+
+ escaped_instance = cg_escape(u->id);
+ if (!escaped_instance)
+ return NULL;
+
+ if (u->instance) {
+ _cleanup_free_ char *t = NULL, *escaped_template = NULL;
+
+ t = unit_name_template(u->id);
+ if (!t)
+ return NULL;
+
+ escaped_template = cg_escape(t);
+ if (!escaped_template)
+ return NULL;
+
+ return strjoin(u->manager->cgroup_hierarchy, "/", escaped_template, "/", escaped_instance, NULL);
+ } else
+ return strjoin(u->manager->cgroup_hierarchy, "/", escaped_instance, NULL);
+}
+
+int unit_add_cgroup_from_text(Unit *u, const char *name, bool overwrite, CGroupBonding **ret) {
+ char *controller = NULL, *path = NULL;
+ CGroupBonding *b = NULL;
+ bool ours = false;
+ int r;
+
+ assert(u);
+ assert(name);
+
+ r = cg_split_spec(name, &controller, &path);
+ if (r < 0)
+ return r;
+
+ if (!path) {
+ path = unit_default_cgroup_path(u);
+ ours = true;
+ }
+
+ if (!controller) {
+ controller = strdup("systemd");
+ ours = true;
+ }
+
+ if (!path || !controller) {
+ free(path);
+ free(controller);
+ return log_oom();
+ }
+
+ if (streq(controller, "systemd")) {
+ /* Within the systemd unit hierarchy we do not allow changes. */
+ if (path_startswith(path, "/system")) {
+ log_warning_unit(u->id, "Manipulating the systemd:/system cgroup hierarchy is not permitted.");
+ free(path);
+ free(controller);
+ return -EPERM;
+ }
+ }
+
+ b = cgroup_bonding_find_list(u->cgroup_bondings, controller);
+ if (b) {
+ if (streq(path, b->path)) {
+ free(path);
+ free(controller);
+
+ if (ret)
+ *ret = b;
+ return 0;
+ }
+
+ if (overwrite && !b->essential) {
+ free(controller);
+
+ free(b->path);
+ b->path = path;
+
+ b->ours = ours;
+ b->realized = false;
+
+ if (ret)
+ *ret = b;
+
+ return 1;
+ }
+
+ r = -EEXIST;
+ b = NULL;
+ goto fail;
+ }
+
+ b = new0(CGroupBonding, 1);
+ if (!b) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ b->controller = controller;
+ b->path = path;
+ b->ours = ours;
+ b->essential = streq(controller, SYSTEMD_CGROUP_CONTROLLER);
+
+ r = unit_add_cgroup(u, b);
+ if (r < 0)
+ goto fail;
+
+ if (ret)
+ *ret = b;
+
+ return 1;
+
+fail:
+ free(path);
+ free(controller);
+ free(b);
+
+ return r;
+}
+
+static int unit_add_one_default_cgroup(Unit *u, const char *controller) {
+ CGroupBonding *b = NULL;
+ int r = -ENOMEM;
+
+ assert(u);
+
+ if (controller && !cg_controller_is_valid(controller, true))
+ return -EINVAL;
+
+ if (!controller)
+ controller = SYSTEMD_CGROUP_CONTROLLER;
+
+ if (cgroup_bonding_find_list(u->cgroup_bondings, controller))
+ return 0;
+
+ b = new0(CGroupBonding, 1);
+ if (!b)
+ return -ENOMEM;
+
+ b->controller = strdup(controller);
+ if (!b->controller)
+ goto fail;
+
+ b->path = unit_default_cgroup_path(u);
+ if (!b->path)
+ goto fail;
+
+ b->ours = true;
+ b->essential = streq(controller, SYSTEMD_CGROUP_CONTROLLER);
+
+ r = unit_add_cgroup(u, b);
+ if (r < 0)
+ goto fail;
+
+ return 1;
+
+fail:
+ free(b->path);
+ free(b->controller);
+ free(b);
+
+ return r;
+}
+
+int unit_add_default_cgroups(Unit *u) {
+ CGroupAttribute *a;
+ char **c;
+ int r;
+
+ assert(u);
+
+ /* Adds in the default cgroups, if they weren't specified
+ * otherwise. */
+
+ if (!u->manager->cgroup_hierarchy)
+ return 0;
+
+ r = unit_add_one_default_cgroup(u, NULL);
+ if (r < 0)
+ return r;
+
+ STRV_FOREACH(c, u->manager->default_controllers)
+ unit_add_one_default_cgroup(u, *c);
+
+ LIST_FOREACH(by_unit, a, u->cgroup_attributes)
+ unit_add_one_default_cgroup(u, a->controller);
+
+ return 0;
+}
+
+CGroupBonding* unit_get_default_cgroup(Unit *u) {
+ assert(u);
+
+ return cgroup_bonding_find_list(u->cgroup_bondings, NULL);
+}
+
+int unit_add_cgroup_attribute(
+ Unit *u,
+ const CGroupSemantics *semantics,
+ const char *controller,
+ const char *name,
+ const char *value,
+ CGroupAttribute **ret) {
+
+ _cleanup_free_ char *c = NULL;
+ CGroupAttribute *a;
+ int r;
+
+ assert(u);
+ assert(value);
+
+ if (semantics) {
+ /* Semantics always take precedence */
+ if (semantics->name)
+ name = semantics->name;
+
+ if (semantics->controller)
+ controller = semantics->controller;
+ }
+
+ if (!name)
+ return -EINVAL;
+
+ if (!controller) {
+ r = cg_controller_from_attr(name, &c);
+ if (r < 0)
+ return -EINVAL;
+
+ controller = c;
+ }
+
+ if (!controller ||
+ streq(controller, SYSTEMD_CGROUP_CONTROLLER) ||
+ streq(controller, "systemd"))
+ return -EINVAL;
+
+ if (!filename_is_safe(name))
+ return -EINVAL;
+
+ if (!cg_controller_is_valid(controller, false))
+ return -EINVAL;
+
+ /* Check if this attribute already exists. Note that we will
+ * explicitly check for the value here too, as there are
+ * attributes which accept multiple values. */
+ a = cgroup_attribute_find_list(u->cgroup_attributes, controller, name);
+ if (a) {
+ if (streq(value, a->value)) {
+ /* Exactly the same value is always OK, let's ignore this */
+ if (ret)
+ *ret = a;
+
+ return 0;
+ }
+
+ if (semantics && !semantics->multiple) {
+ char *v;
+
+ /* If this is a single-item entry, we can
+ * simply patch the existing attribute */
+
+ v = strdup(value);
+ if (!v)
+ return -ENOMEM;
+
+ free(a->value);
+ a->value = v;
+
+ if (ret)
+ *ret = a;
+ return 1;
+ }
+ }
+
+ a = new0(CGroupAttribute, 1);
+ if (!a)
+ return -ENOMEM;
+
+ if (c) {
+ a->controller = c;
+ c = NULL;
+ } else
+ a->controller = strdup(controller);
+
+ a->name = strdup(name);
+ a->value = strdup(value);
+
+ if (!a->controller || !a->name || !a->value) {
+ free(a->controller);
+ free(a->name);
+ free(a->value);
+ free(a);
+ return -ENOMEM;
+ }
+
+ a->semantics = semantics;
+ a->unit = u;
+
+ LIST_PREPEND(CGroupAttribute, by_unit, u->cgroup_attributes, a);
+
+ if (ret)
+ *ret = a;
+
+ return 1;
+}
+
+int unit_load_related_unit(Unit *u, const char *type, Unit **_found) {
+ _cleanup_free_ char *t = NULL;
+ int r;
+
+ assert(u);
+ assert(type);
+ assert(_found);
+
+ t = unit_name_change_suffix(u->id, type);
+ if (!t)
+ return -ENOMEM;
+
+ assert(!unit_has_name(u, t));
+
+ r = manager_load_unit(u->manager, t, NULL, NULL, _found);
+ assert(r < 0 || *_found != u);
+ return r;
+}
+
+int unit_get_related_unit(Unit *u, const char *type, Unit **_found) {
+ _cleanup_free_ char *t = NULL;
+ Unit *found;
+
+ assert(u);
+ assert(type);
+ assert(_found);
+
+ t = unit_name_change_suffix(u->id, type);
+ if (!t)
+ return -ENOMEM;
+
+ assert(!unit_has_name(u, t));
+
+ found = manager_get_unit(u->manager, t);
+ if (!found)
+ return -ENOENT;
+
+ *_found = found;
+ return 0;
+}
+
+int unit_watch_bus_name(Unit *u, const char *name) {
+ assert(u);
+ assert(name);
+
+ /* Watch a specific name on the bus. We only support one unit
+ * watching each name for now. */
+
+ return hashmap_put(u->manager->watch_bus, name, u);
+}
+
+void unit_unwatch_bus_name(Unit *u, const char *name) {
+ assert(u);
+ assert(name);
+
+ hashmap_remove_value(u->manager->watch_bus, name, u);
+}
+
+bool unit_can_serialize(Unit *u) {
+ assert(u);
+
+ return UNIT_VTABLE(u)->serialize && UNIT_VTABLE(u)->deserialize_item;
+}
+
+int unit_serialize(Unit *u, FILE *f, FDSet *fds, bool serialize_jobs) {
+ int r;
+
+ assert(u);
+ assert(f);
+ assert(fds);
+
+ if (!unit_can_serialize(u))
+ return 0;
+
+ if ((r = UNIT_VTABLE(u)->serialize(u, f, fds)) < 0)
+ return r;
+
+
+ if (serialize_jobs) {
+ if (u->job) {
+ fprintf(f, "job\n");
+ job_serialize(u->job, f, fds);
+ }
+
+ if (u->nop_job) {
+ fprintf(f, "job\n");
+ job_serialize(u->nop_job, f, fds);
+ }
+ }
+
+ dual_timestamp_serialize(f, "inactive-exit-timestamp", &u->inactive_exit_timestamp);
+ dual_timestamp_serialize(f, "active-enter-timestamp", &u->active_enter_timestamp);
+ dual_timestamp_serialize(f, "active-exit-timestamp", &u->active_exit_timestamp);
+ dual_timestamp_serialize(f, "inactive-enter-timestamp", &u->inactive_enter_timestamp);
+ dual_timestamp_serialize(f, "condition-timestamp", &u->condition_timestamp);
+
+ if (dual_timestamp_is_set(&u->condition_timestamp))
+ unit_serialize_item(u, f, "condition-result", yes_no(u->condition_result));
+
+ /* End marker */
+ fputc('\n', f);
+ return 0;
+}
+
+void unit_serialize_item_format(Unit *u, FILE *f, const char *key, const char *format, ...) {
+ va_list ap;
+
+ assert(u);
+ assert(f);
+ assert(key);
+ assert(format);
+
+ fputs(key, f);
+ fputc('=', f);
+
+ va_start(ap, format);
+ vfprintf(f, format, ap);
+ va_end(ap);
+
+ fputc('\n', f);
+}
+
+void unit_serialize_item(Unit *u, FILE *f, const char *key, const char *value) {
+ assert(u);
+ assert(f);
+ assert(key);
+ assert(value);
+
+ fprintf(f, "%s=%s\n", key, value);
+}
+
+int unit_deserialize(Unit *u, FILE *f, FDSet *fds) {
+ int r;
+
+ assert(u);
+ assert(f);
+ assert(fds);
+
+ if (!unit_can_serialize(u))
+ return 0;
+
+ for (;;) {
+ char line[LINE_MAX], *l, *v;
+ size_t k;
+
+ if (!fgets(line, sizeof(line), f)) {
+ if (feof(f))
+ return 0;
+ return -errno;
+ }
+
+ char_array_0(line);
+ l = strstrip(line);
+
+ /* End marker */
+ if (l[0] == 0)
+ return 0;
+
+ k = strcspn(l, "=");
+
+ if (l[k] == '=') {
+ l[k] = 0;
+ v = l+k+1;
+ } else
+ v = l+k;
+
+ if (streq(l, "job")) {
+ if (v[0] == '\0') {
+ /* new-style serialized job */
+ Job *j = job_new_raw(u);
+ if (!j)
+ return -ENOMEM;
+
+ r = job_deserialize(j, f, fds);
+ if (r < 0) {
+ job_free(j);
+ return r;
+ }
+
+ r = hashmap_put(u->manager->jobs, UINT32_TO_PTR(j->id), j);
+ if (r < 0) {
+ job_free(j);
+ return r;
+ }
+
+ r = job_install_deserialized(j);
+ if (r < 0) {
+ hashmap_remove(u->manager->jobs, UINT32_TO_PTR(j->id));
+ job_free(j);
+ return r;
+ }
+
+ if (j->state == JOB_RUNNING)
+ u->manager->n_running_jobs++;
+ } else {
+ /* legacy */
+ JobType type = job_type_from_string(v);
+ if (type < 0)
+ log_debug("Failed to parse job type value %s", v);
+ else
+ u->deserialized_job = type;
+ }
+ continue;
+ } else if (streq(l, "inactive-exit-timestamp")) {
+ dual_timestamp_deserialize(v, &u->inactive_exit_timestamp);
+ continue;
+ } else if (streq(l, "active-enter-timestamp")) {
+ dual_timestamp_deserialize(v, &u->active_enter_timestamp);
+ continue;
+ } else if (streq(l, "active-exit-timestamp")) {
+ dual_timestamp_deserialize(v, &u->active_exit_timestamp);
+ continue;
+ } else if (streq(l, "inactive-enter-timestamp")) {
+ dual_timestamp_deserialize(v, &u->inactive_enter_timestamp);
+ continue;
+ } else if (streq(l, "condition-timestamp")) {
+ dual_timestamp_deserialize(v, &u->condition_timestamp);
+ continue;
+ } else if (streq(l, "condition-result")) {
+ int b;
+
+ if ((b = parse_boolean(v)) < 0)
+ log_debug("Failed to parse condition result value %s", v);
+ else
+ u->condition_result = b;
+
+ continue;
+ }
+
+ if ((r = UNIT_VTABLE(u)->deserialize_item(u, l, v, fds)) < 0)
+ return r;
+ }
+}
+
+int unit_add_node_link(Unit *u, const char *what, bool wants) {
+ Unit *device;
+ char *e;
+ int r;
+
+ assert(u);
+
+ if (!what)
+ return 0;
+
+ /* Adds in links to the device node that this unit is based on */
+
+ if (!is_device_path(what))
+ return 0;
+
+ e = unit_name_from_path(what, ".device");
+ if (!e)
+ return -ENOMEM;
+
+ r = manager_load_unit(u->manager, e, NULL, NULL, &device);
+ free(e);
+ if (r < 0)
+ return r;
+
+ r = unit_add_two_dependencies(u, UNIT_AFTER, UNIT_BINDS_TO, device, true);
+ if (r < 0)
+ return r;
+
+ if (wants) {
+ r = unit_add_dependency(device, UNIT_WANTS, u, false);
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+int unit_coldplug(Unit *u) {
+ int r;
+
+ assert(u);
+
+ if (UNIT_VTABLE(u)->coldplug)
+ if ((r = UNIT_VTABLE(u)->coldplug(u)) < 0)
+ return r;
+
+ if (u->job) {
+ r = job_coldplug(u->job);
+ if (r < 0)
+ return r;
+ } else if (u->deserialized_job >= 0) {
+ /* legacy */
+ r = manager_add_job(u->manager, u->deserialized_job, u, JOB_IGNORE_REQUIREMENTS, false, NULL, NULL);
+ if (r < 0)
+ return r;
+
+ u->deserialized_job = _JOB_TYPE_INVALID;
+ }
+
+ return 0;
+}
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wformat-nonliteral"
+void unit_status_printf(Unit *u, const char *status, const char *unit_status_msg_format) {
+ manager_status_printf(u->manager, false, status, unit_status_msg_format, unit_description(u));
+}
+#pragma GCC diagnostic pop
+
+bool unit_need_daemon_reload(Unit *u) {
+ _cleanup_strv_free_ char **t = NULL;
+ char **path;
+ struct stat st;
+ unsigned loaded_cnt, current_cnt;
+
+ assert(u);
+
+ if (u->fragment_path) {
+ zero(st);
+ if (stat(u->fragment_path, &st) < 0)
+ /* What, cannot access this anymore? */
+ return true;
+
+ if (u->fragment_mtime > 0 &&
+ timespec_load(&st.st_mtim) != u->fragment_mtime)
+ return true;
+ }
+
+ if (u->source_path) {
+ zero(st);
+ if (stat(u->source_path, &st) < 0)
+ return true;
+
+ if (u->source_mtime > 0 &&
+ timespec_load(&st.st_mtim) != u->source_mtime)
+ return true;
+ }
+
+ t = unit_find_dropin_paths(u);
+ loaded_cnt = strv_length(t);
+ current_cnt = strv_length(u->dropin_paths);
+
+ if (loaded_cnt == current_cnt) {
+ if (loaded_cnt == 0)
+ return false;
+
+ if (strv_overlap(u->dropin_paths, t)) {
+ STRV_FOREACH(path, u->dropin_paths) {
+ zero(st);
+ if (stat(*path, &st) < 0)
+ return true;
+
+ if (u->dropin_mtime > 0 &&
+ timespec_load(&st.st_mtim) > u->dropin_mtime)
+ return true;
+ }
+
+ return false;
+ } else
+ return true;
+ } else
+ return true;
+}
+
+void unit_reset_failed(Unit *u) {
+ assert(u);
+
+ if (UNIT_VTABLE(u)->reset_failed)
+ UNIT_VTABLE(u)->reset_failed(u);
+}
+
+Unit *unit_following(Unit *u) {
+ assert(u);
+
+ if (UNIT_VTABLE(u)->following)
+ return UNIT_VTABLE(u)->following(u);
+
+ return NULL;
+}
+
+bool unit_stop_pending(Unit *u) {
+ assert(u);
+
+ /* This call does check the current state of the unit. It's
+ * hence useful to be called from state change calls of the
+ * unit itself, where the state isn't updated yet. This is
+ * different from unit_inactive_or_pending() which checks both
+ * the current state and for a queued job. */
+
+ return u->job && u->job->type == JOB_STOP;
+}
+
+bool unit_inactive_or_pending(Unit *u) {
+ assert(u);
+
+ /* Returns true if the unit is inactive or going down */
+
+ if (UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)))
+ return true;
+
+ if (unit_stop_pending(u))
+ return true;
+
+ return false;
+}
+
+bool unit_active_or_pending(Unit *u) {
+ assert(u);
+
+ /* Returns true if the unit is active or going up */
+
+ if (UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
+ return true;
+
+ if (u->job &&
+ (u->job->type == JOB_START ||
+ u->job->type == JOB_RELOAD_OR_START ||
+ u->job->type == JOB_RESTART))
+ return true;
+
+ return false;
+}
+
+int unit_kill(Unit *u, KillWho w, int signo, DBusError *error) {
+ assert(u);
+ assert(w >= 0 && w < _KILL_WHO_MAX);
+ assert(signo > 0);
+ assert(signo < _NSIG);
+
+ if (!UNIT_VTABLE(u)->kill)
+ return -ENOTSUP;
+
+ return UNIT_VTABLE(u)->kill(u, w, signo, error);
+}
+
+int unit_kill_common(
+ Unit *u,
+ KillWho who,
+ int signo,
+ pid_t main_pid,
+ pid_t control_pid,
+ DBusError *error) {
+
+ int r = 0;
+
+ if (who == KILL_MAIN && main_pid <= 0) {
+ if (main_pid < 0)
+ dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "%s units have no main processes", unit_type_to_string(u->type));
+ else
+ dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No main process to kill");
+ return -ESRCH;
+ }
+
+ if (who == KILL_CONTROL && control_pid <= 0) {
+ if (control_pid < 0)
+ dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "%s units have no control processes", unit_type_to_string(u->type));
+ else
+ dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
+ return -ESRCH;
+ }
+
+ if (who == KILL_CONTROL || who == KILL_ALL)
+ if (control_pid > 0)
+ if (kill(control_pid, signo) < 0)
+ r = -errno;
+
+ if (who == KILL_MAIN || who == KILL_ALL)
+ if (main_pid > 0)
+ if (kill(main_pid, signo) < 0)
+ r = -errno;
+
+ if (who == KILL_ALL) {
+ _cleanup_set_free_ Set *pid_set = NULL;
+ int q;
+
+ pid_set = set_new(trivial_hash_func, trivial_compare_func);
+ if (!pid_set)
+ return -ENOMEM;
+
+ /* Exclude the control/main pid from being killed via the cgroup */
+ if (control_pid > 0) {
+ q = set_put(pid_set, LONG_TO_PTR(control_pid));
+ if (q < 0)
+ return q;
+ }
+
+ if (main_pid > 0) {
+ q = set_put(pid_set, LONG_TO_PTR(main_pid));
+ if (q < 0)
+ return q;
+ }
+
+ q = cgroup_bonding_kill_list(u->cgroup_bondings, signo, false, false, pid_set, NULL);
+ if (q < 0 && q != -EAGAIN && q != -ESRCH && q != -ENOENT)
+ r = q;
+ }
+
+ return r;
+}
+
+int unit_following_set(Unit *u, Set **s) {
+ assert(u);
+ assert(s);
+
+ if (UNIT_VTABLE(u)->following_set)
+ return UNIT_VTABLE(u)->following_set(u, s);
+
+ *s = NULL;
+ return 0;
+}
+
+UnitFileState unit_get_unit_file_state(Unit *u) {
+ assert(u);
+
+ if (u->unit_file_state < 0 && u->fragment_path)
+ u->unit_file_state = unit_file_get_state(
+ u->manager->running_as == SYSTEMD_SYSTEM ? UNIT_FILE_SYSTEM : UNIT_FILE_USER,
+ NULL, path_get_file_name(u->fragment_path));
+
+ return u->unit_file_state;
+}
+
+Unit* unit_ref_set(UnitRef *ref, Unit *u) {
+ assert(ref);
+ assert(u);
+
+ if (ref->unit)
+ unit_ref_unset(ref);
+
+ ref->unit = u;
+ LIST_PREPEND(UnitRef, refs, u->refs, ref);
+ return u;
+}
+
+void unit_ref_unset(UnitRef *ref) {
+ assert(ref);
+
+ if (!ref->unit)
+ return;
+
+ LIST_REMOVE(UnitRef, refs, ref->unit->refs, ref);
+ ref->unit = NULL;
+}
+
+int unit_add_one_mount_link(Unit *u, Mount *m) {
+ char **i;
+
+ assert(u);
+ assert(m);
+
+ if (u->load_state != UNIT_LOADED ||
+ UNIT(m)->load_state != UNIT_LOADED)
+ return 0;
+
+ STRV_FOREACH(i, u->requires_mounts_for) {
+
+ if (UNIT(m) == u)
+ continue;
+
+ if (!path_startswith(*i, m->where))
+ continue;
+
+ return unit_add_two_dependencies(u, UNIT_AFTER, UNIT_REQUIRES, UNIT(m), true);
+ }
+
+ return 0;
+}
+
+int unit_add_mount_links(Unit *u) {
+ Unit *other;
+ int r;
+
+ assert(u);
+
+ LIST_FOREACH(units_by_type, other, u->manager->units_by_type[UNIT_MOUNT]) {
+ r = unit_add_one_mount_link(u, MOUNT(other));
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+int unit_exec_context_defaults(Unit *u, ExecContext *c) {
+ unsigned i;
+ int r;
+
+ assert(u);
+ assert(c);
+
+ /* This only copies in the ones that need memory */
+
+ for (i = 0; i < RLIMIT_NLIMITS; i++)
+ if (u->manager->rlimit[i] && !c->rlimit[i]) {
+ c->rlimit[i] = newdup(struct rlimit, u->manager->rlimit[i], 1);
+ if (!c->rlimit[i])
+ return -ENOMEM;
+ }
+
+ if (u->manager->running_as == SYSTEMD_USER &&
+ !c->working_directory) {
+
+ r = get_home_dir(&c->working_directory);
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+ExecContext *unit_get_exec_context(Unit *u) {
+ size_t offset;
+ assert(u);
+
+ offset = UNIT_VTABLE(u)->exec_context_offset;
+ if (offset <= 0)
+ return NULL;
+
+ return (ExecContext*) ((uint8_t*) u + offset);
+}
+
+static int drop_in_file(Unit *u, bool runtime, const char *name, char **_p, char **_q) {
+ char *p, *q;
+ int r;
+
+ assert(u);
+ assert(name);
+ assert(_p);
+ assert(_q);
+
+ if (u->manager->running_as == SYSTEMD_USER && runtime)
+ return -ENOTSUP;
+
+ if (!filename_is_safe(name))
+ return -EINVAL;
+
+ if (u->manager->running_as == SYSTEMD_USER) {
+ _cleanup_free_ char *c = NULL;
+
+ r = user_config_home(&c);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return -ENOENT;
+
+ p = strjoin(c, "/", u->id, ".d", NULL);
+ } else if (runtime)
+ p = strjoin("/run/systemd/system/", u->id, ".d", NULL);
+ else
+ p = strjoin("/etc/systemd/system/", u->id, ".d", NULL);
+ if (!p)
+ return -ENOMEM;
+
+ q = strjoin(p, "/50-", name, ".conf", NULL);
+ if (!q) {
+ free(p);
+ return -ENOMEM;
+ }
+
+ *_p = p;
+ *_q = q;
+ return 0;
+}
+
+int unit_write_drop_in(Unit *u, bool runtime, const char *name, const char *data) {
+ _cleanup_free_ char *p = NULL, *q = NULL;
+ int r;
+
+ assert(u);
+
+ r = drop_in_file(u, runtime, name, &p, &q);
+ if (r < 0)
+ return r;
+
+ mkdir_p(p, 0755);
+ return write_string_file_atomic_label(q, data);
+}
+
+int unit_remove_drop_in(Unit *u, bool runtime, const char *name) {
+ _cleanup_free_ char *p = NULL, *q = NULL;
+ int r;
+
+ assert(u);
+
+ r = drop_in_file(u, runtime, name, &p, &q);
+ if (unlink(q) < 0)
+ r = -errno;
+ else
+ r = 0;
+
+ rmdir(p);
+ return r;
+}
+
+int unit_kill_context(
+ Unit *u,
+ KillContext *c,
+ bool sigkill,
+ pid_t main_pid,
+ pid_t control_pid,
+ bool main_pid_alien) {
+
+ int sig, wait_for_exit = 0, r;
+
+ assert(u);
+ assert(c);
+
+ if (c->kill_mode == KILL_NONE)
+ return 0;
+
+ sig = sigkill ? SIGKILL : c->kill_signal;
+
+ if (main_pid > 0) {
+ r = kill_and_sigcont(main_pid, sig);
+
+ if (r < 0 && r != -ESRCH) {
+ _cleanup_free_ char *comm = NULL;
+ get_process_comm(main_pid, &comm);
+
+ log_warning_unit(u->id, "Failed to kill main process %li (%s): %s",
+ (long) main_pid, strna(comm), strerror(-r));
+ } else
+ wait_for_exit = !main_pid_alien;
+ }
+
+ if (control_pid > 0) {
+ r = kill_and_sigcont(control_pid, sig);
+
+ if (r < 0 && r != -ESRCH) {
+ _cleanup_free_ char *comm = NULL;
+ get_process_comm(control_pid, &comm);
+
+ log_warning_unit(u->id,
+ "Failed to kill control process %li (%s): %s",
+ (long) control_pid, strna(comm), strerror(-r));
+ } else
+ wait_for_exit = true;
+ }
+
+ if (c->kill_mode == KILL_CONTROL_GROUP) {
+ _cleanup_set_free_ Set *pid_set = NULL;
+
+ pid_set = set_new(trivial_hash_func, trivial_compare_func);
+ if (!pid_set)
+ return -ENOMEM;
+
+ /* Exclude the main/control pids from being killed via the cgroup */
+ if (main_pid > 0) {
+ r = set_put(pid_set, LONG_TO_PTR(main_pid));
+ if (r < 0)
+ return r;
+ }
+
+ if (control_pid > 0) {
+ r = set_put(pid_set, LONG_TO_PTR(control_pid));
+ if (r < 0)
+ return r;
+ }
+
+ r = cgroup_bonding_kill_list(u->cgroup_bondings, sig, true, false, pid_set, NULL);
+ if (r < 0) {
+ if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
+ log_warning_unit(u->id, "Failed to kill control group: %s", strerror(-r));
+ } else if (r > 0)
+ wait_for_exit = true;
+ }
+
+ return wait_for_exit;
+}
+
+static const char* const unit_active_state_table[_UNIT_ACTIVE_STATE_MAX] = {
+ [UNIT_ACTIVE] = "active",
+ [UNIT_RELOADING] = "reloading",
+ [UNIT_INACTIVE] = "inactive",
+ [UNIT_FAILED] = "failed",
+ [UNIT_ACTIVATING] = "activating",
+ [UNIT_DEACTIVATING] = "deactivating"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(unit_active_state, UnitActiveState);
+
+static const char* const unit_dependency_table[_UNIT_DEPENDENCY_MAX] = {
+ [UNIT_REQUIRES] = "Requires",
+ [UNIT_REQUIRES_OVERRIDABLE] = "RequiresOverridable",
+ [UNIT_REQUISITE] = "Requisite",
+ [UNIT_REQUISITE_OVERRIDABLE] = "RequisiteOverridable",
+ [UNIT_WANTS] = "Wants",
+ [UNIT_BINDS_TO] = "BindsTo",
+ [UNIT_PART_OF] = "PartOf",
+ [UNIT_REQUIRED_BY] = "RequiredBy",
+ [UNIT_REQUIRED_BY_OVERRIDABLE] = "RequiredByOverridable",
+ [UNIT_WANTED_BY] = "WantedBy",
+ [UNIT_BOUND_BY] = "BoundBy",
+ [UNIT_CONSISTS_OF] = "ConsistsOf",
+ [UNIT_CONFLICTS] = "Conflicts",
+ [UNIT_CONFLICTED_BY] = "ConflictedBy",
+ [UNIT_BEFORE] = "Before",
+ [UNIT_AFTER] = "After",
+ [UNIT_ON_FAILURE] = "OnFailure",
+ [UNIT_TRIGGERS] = "Triggers",
+ [UNIT_TRIGGERED_BY] = "TriggeredBy",
+ [UNIT_PROPAGATES_RELOAD_TO] = "PropagatesReloadTo",
+ [UNIT_RELOAD_PROPAGATED_FROM] = "ReloadPropagatedFrom",
+ [UNIT_REFERENCES] = "References",
+ [UNIT_REFERENCED_BY] = "ReferencedBy",
+};
+
+DEFINE_STRING_TABLE_LOOKUP(unit_dependency, UnitDependency);
diff --git a/src/core/unit.h b/src/core/unit.h
new file mode 100644
index 0000000000..b04475e4fb
--- /dev/null
+++ b/src/core/unit.h
@@ -0,0 +1,588 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdbool.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+typedef struct Unit Unit;
+typedef struct UnitVTable UnitVTable;
+typedef enum UnitActiveState UnitActiveState;
+typedef enum UnitDependency UnitDependency;
+typedef struct UnitRef UnitRef;
+typedef struct UnitStatusMessageFormats UnitStatusMessageFormats;
+
+#include "set.h"
+#include "util.h"
+#include "list.h"
+#include "socket-util.h"
+#include "execute.h"
+#include "condition.h"
+#include "install.h"
+#include "unit-name.h"
+#include "cgroup-semantics.h"
+
+enum UnitActiveState {
+ UNIT_ACTIVE,
+ UNIT_RELOADING,
+ UNIT_INACTIVE,
+ UNIT_FAILED,
+ UNIT_ACTIVATING,
+ UNIT_DEACTIVATING,
+ _UNIT_ACTIVE_STATE_MAX,
+ _UNIT_ACTIVE_STATE_INVALID = -1
+};
+
+static inline bool UNIT_IS_ACTIVE_OR_RELOADING(UnitActiveState t) {
+ return t == UNIT_ACTIVE || t == UNIT_RELOADING;
+}
+
+static inline bool UNIT_IS_ACTIVE_OR_ACTIVATING(UnitActiveState t) {
+ return t == UNIT_ACTIVE || t == UNIT_ACTIVATING || t == UNIT_RELOADING;
+}
+
+static inline bool UNIT_IS_INACTIVE_OR_DEACTIVATING(UnitActiveState t) {
+ return t == UNIT_INACTIVE || t == UNIT_FAILED || t == UNIT_DEACTIVATING;
+}
+
+static inline bool UNIT_IS_INACTIVE_OR_FAILED(UnitActiveState t) {
+ return t == UNIT_INACTIVE || t == UNIT_FAILED;
+}
+
+enum UnitDependency {
+ /* Positive dependencies */
+ UNIT_REQUIRES,
+ UNIT_REQUIRES_OVERRIDABLE,
+ UNIT_REQUISITE,
+ UNIT_REQUISITE_OVERRIDABLE,
+ UNIT_WANTS,
+ UNIT_BINDS_TO,
+ UNIT_PART_OF,
+
+ /* Inverse of the above */
+ UNIT_REQUIRED_BY, /* inverse of 'requires' and 'requisite' is 'required_by' */
+ UNIT_REQUIRED_BY_OVERRIDABLE, /* inverse of 'requires_overridable' and 'requisite_overridable' is 'soft_required_by' */
+ UNIT_WANTED_BY, /* inverse of 'wants' */
+ UNIT_BOUND_BY, /* inverse of 'binds_to' */
+ UNIT_CONSISTS_OF, /* inverse of 'part_of' */
+
+ /* Negative dependencies */
+ UNIT_CONFLICTS, /* inverse of 'conflicts' is 'conflicted_by' */
+ UNIT_CONFLICTED_BY,
+
+ /* Order */
+ UNIT_BEFORE, /* inverse of 'before' is 'after' and vice versa */
+ UNIT_AFTER,
+
+ /* On Failure */
+ UNIT_ON_FAILURE,
+
+ /* Triggers (i.e. a socket triggers a service) */
+ UNIT_TRIGGERS,
+ UNIT_TRIGGERED_BY,
+
+ /* Propagate reloads */
+ UNIT_PROPAGATES_RELOAD_TO,
+ UNIT_RELOAD_PROPAGATED_FROM,
+
+ /* Reference information for GC logic */
+ UNIT_REFERENCES, /* Inverse of 'references' is 'referenced_by' */
+ UNIT_REFERENCED_BY,
+
+ _UNIT_DEPENDENCY_MAX,
+ _UNIT_DEPENDENCY_INVALID = -1
+};
+
+#include "manager.h"
+#include "job.h"
+#include "cgroup.h"
+#include "cgroup-attr.h"
+
+struct Unit {
+ Manager *manager;
+
+ UnitType type;
+ UnitLoadState load_state;
+ Unit *merged_into;
+
+ char *id; /* One name is special because we use it for identification. Points to an entry in the names set */
+ char *instance;
+
+ Set *names;
+ Set *dependencies[_UNIT_DEPENDENCY_MAX];
+
+ char **requires_mounts_for;
+
+ char *description;
+ char **documentation;
+
+ char *fragment_path; /* if loaded from a config file this is the primary path to it */
+ char *source_path; /* if converted, the source file */
+ char **dropin_paths;
+ usec_t fragment_mtime;
+ usec_t source_mtime;
+ usec_t dropin_mtime;
+
+ /* If there is something to do with this unit, then this is the installed job for it */
+ Job *job;
+
+ /* JOB_NOP jobs are special and can be installed without disturbing the real job. */
+ Job *nop_job;
+
+ usec_t job_timeout;
+
+ /* References to this */
+ LIST_HEAD(UnitRef, refs);
+
+ /* Conditions to check */
+ LIST_HEAD(Condition, conditions);
+
+ dual_timestamp condition_timestamp;
+
+ dual_timestamp inactive_exit_timestamp;
+ dual_timestamp active_enter_timestamp;
+ dual_timestamp active_exit_timestamp;
+ dual_timestamp inactive_enter_timestamp;
+
+ /* Counterparts in the cgroup filesystem */
+ CGroupBonding *cgroup_bondings;
+ CGroupAttribute *cgroup_attributes;
+
+ /* Per type list */
+ LIST_FIELDS(Unit, units_by_type);
+
+ /* All units which have requires_mounts_for set */
+ LIST_FIELDS(Unit, has_requires_mounts_for);
+
+ /* Load queue */
+ LIST_FIELDS(Unit, load_queue);
+
+ /* D-Bus queue */
+ LIST_FIELDS(Unit, dbus_queue);
+
+ /* Cleanup queue */
+ LIST_FIELDS(Unit, cleanup_queue);
+
+ /* GC queue */
+ LIST_FIELDS(Unit, gc_queue);
+
+ /* Used during GC sweeps */
+ unsigned gc_marker;
+
+ /* When deserializing, temporarily store the job type for this
+ * unit here, if there was a job scheduled.
+ * Only for deserializing from a legacy version. New style uses full
+ * serialized jobs. */
+ int deserialized_job; /* This is actually of type JobType */
+
+ /* Error code when we didn't manage to load the unit (negative) */
+ int load_error;
+
+ /* Cached unit file state */
+ UnitFileState unit_file_state;
+
+ /* Garbage collect us we nobody wants or requires us anymore */
+ bool stop_when_unneeded;
+
+ /* Create default dependencies */
+ bool default_dependencies;
+
+ /* Refuse manual starting, allow starting only indirectly via dependency. */
+ bool refuse_manual_start;
+
+ /* Don't allow the user to stop this unit manually, allow stopping only indirectly via dependency. */
+ bool refuse_manual_stop;
+
+ /* Allow isolation requests */
+ bool allow_isolate;
+
+ /* Isolate OnFailure unit */
+ bool on_failure_isolate;
+
+ /* Ignore this unit when isolating */
+ bool ignore_on_isolate;
+
+ /* Ignore this unit when snapshotting */
+ bool ignore_on_snapshot;
+
+ /* Did the last condition check succeed? */
+ bool condition_result;
+
+ bool in_load_queue:1;
+ bool in_dbus_queue:1;
+ bool in_cleanup_queue:1;
+ bool in_gc_queue:1;
+
+ bool sent_dbus_new_signal:1;
+
+ bool no_gc:1;
+
+ bool in_audit:1;
+};
+
+struct UnitRef {
+ /* Keeps tracks of references to a unit. This is useful so
+ * that we can merge two units if necessary and correct all
+ * references to them */
+
+ Unit* unit;
+ LIST_FIELDS(UnitRef, refs);
+};
+
+struct UnitStatusMessageFormats {
+ const char *starting_stopping[2];
+ const char *finished_start_job[_JOB_RESULT_MAX];
+ const char *finished_stop_job[_JOB_RESULT_MAX];
+};
+
+#include "service.h"
+#include "timer.h"
+#include "socket.h"
+#include "target.h"
+#include "device.h"
+#include "mount.h"
+#include "automount.h"
+#include "snapshot.h"
+#include "swap.h"
+#include "path.h"
+
+struct UnitVTable {
+ /* How much memory does an object of this unit type need */
+ size_t object_size;
+
+ /* If greater than 0, the offset into the object where
+ * ExecContext is found, if the unit type has that */
+ size_t exec_context_offset;
+
+ /* The name of the section with the exec settings of ExecContext */
+ const char *exec_section;
+
+ /* Config file sections this unit type understands, separated
+ * by NUL chars */
+ const char *sections;
+
+ /* This should reset all type-specific variables. This should
+ * not allocate memory, and is called with zero-initialized
+ * data. It should hence only initialize variables that need
+ * to be set != 0. */
+ void (*init)(Unit *u);
+
+ /* This should free all type-specific variables. It should be
+ * idempotent. */
+ void (*done)(Unit *u);
+
+ /* Actually load data from disk. This may fail, and should set
+ * load_state to UNIT_LOADED, UNIT_MERGED or leave it at
+ * UNIT_STUB if no configuration could be found. */
+ int (*load)(Unit *u);
+
+ /* If a lot of units got created via enumerate(), this is
+ * where to actually set the state and call unit_notify(). */
+ int (*coldplug)(Unit *u);
+
+ void (*dump)(Unit *u, FILE *f, const char *prefix);
+
+ int (*start)(Unit *u);
+ int (*stop)(Unit *u);
+ int (*reload)(Unit *u);
+
+ int (*kill)(Unit *u, KillWho w, int signo, DBusError *error);
+
+ bool (*can_reload)(Unit *u);
+
+ /* Write all data that cannot be restored from other sources
+ * away using unit_serialize_item() */
+ int (*serialize)(Unit *u, FILE *f, FDSet *fds);
+
+ /* Restore one item from the serialization */
+ int (*deserialize_item)(Unit *u, const char *key, const char *data, FDSet *fds);
+
+ /* Try to match up fds with what we need for this unit */
+ int (*distribute_fds)(Unit *u, FDSet *fds);
+
+ /* Boils down the more complex internal state of this unit to
+ * a simpler one that the engine can understand */
+ UnitActiveState (*active_state)(Unit *u);
+
+ /* Returns the substate specific to this unit type as
+ * string. This is purely information so that we can give the
+ * user a more fine grained explanation in which actual state a
+ * unit is in. */
+ const char* (*sub_state_to_string)(Unit *u);
+
+ /* Return true when there is reason to keep this entry around
+ * even nothing references it and it isn't active in any
+ * way */
+ bool (*check_gc)(Unit *u);
+
+ /* Return true when this unit is suitable for snapshotting */
+ bool (*check_snapshot)(Unit *u);
+
+ void (*fd_event)(Unit *u, int fd, uint32_t events, Watch *w);
+ void (*sigchld_event)(Unit *u, pid_t pid, int code, int status);
+ void (*timer_event)(Unit *u, uint64_t n_elapsed, Watch *w);
+
+ /* Reset failed state if we are in failed state */
+ void (*reset_failed)(Unit *u);
+
+ /* Called whenever any of the cgroups this unit watches for
+ * ran empty */
+ void (*cgroup_notify_empty)(Unit *u);
+
+ /* Called whenever a process of this unit sends us a message */
+ void (*notify_message)(Unit *u, pid_t pid, char **tags);
+
+ /* Called whenever a name this Unit registered for comes or
+ * goes away. */
+ void (*bus_name_owner_change)(Unit *u, const char *name, const char *old_owner, const char *new_owner);
+
+ /* Called whenever a bus PID lookup finishes */
+ void (*bus_query_pid_done)(Unit *u, const char *name, pid_t pid);
+
+ /* Called for each message received on the bus */
+ DBusHandlerResult (*bus_message_handler)(Unit *u, DBusConnection *c, DBusMessage *message);
+
+ /* Return the unit this unit is following */
+ Unit *(*following)(Unit *u);
+
+ /* Return the set of units that are following each other */
+ int (*following_set)(Unit *u, Set **s);
+
+ /* Invoked each time a unit this unit is triggering changes
+ * state or gains/loses a job */
+ void (*trigger_notify)(Unit *u, Unit *trigger);
+
+ /* Called whenever CLOCK_REALTIME made a jump */
+ void (*time_change)(Unit *u);
+
+ /* This is called for each unit type and should be used to
+ * enumerate existing devices and load them. However,
+ * everything that is loaded here should still stay in
+ * inactive state. It is the job of the coldplug() call above
+ * to put the units into the initial state. */
+ int (*enumerate)(Manager *m);
+
+ /* Type specific cleanups. */
+ void (*shutdown)(Manager *m);
+
+ /* When sending out PropertiesChanged signal, which properties
+ * shall be invalidated? This is a NUL separated list of
+ * strings, to minimize relocations a little. */
+ const char *bus_invalidating_properties;
+
+ /* The interface name */
+ const char *bus_interface;
+
+ UnitStatusMessageFormats status_message_formats;
+
+ /* Can units of this type have multiple names? */
+ bool no_alias:1;
+
+ /* Instances make no sense for this type */
+ bool no_instances:1;
+
+ /* Exclude from automatic gc */
+ bool no_gc:1;
+};
+
+extern const UnitVTable * const unit_vtable[_UNIT_TYPE_MAX];
+
+#define UNIT_VTABLE(u) unit_vtable[(u)->type]
+
+/* For casting a unit into the various unit types */
+#define DEFINE_CAST(UPPERCASE, MixedCase) \
+ static inline MixedCase* UPPERCASE(Unit *u) { \
+ if (_unlikely_(!u || u->type != UNIT_##UPPERCASE)) \
+ return NULL; \
+ \
+ return (MixedCase*) u; \
+ }
+
+/* For casting the various unit types into a unit */
+#define UNIT(u) (&(u)->meta)
+
+#define UNIT_TRIGGER(u) ((Unit*) set_first((u)->dependencies[UNIT_TRIGGERS]))
+
+DEFINE_CAST(SOCKET, Socket);
+DEFINE_CAST(TIMER, Timer);
+DEFINE_CAST(SERVICE, Service);
+DEFINE_CAST(TARGET, Target);
+DEFINE_CAST(DEVICE, Device);
+DEFINE_CAST(MOUNT, Mount);
+DEFINE_CAST(AUTOMOUNT, Automount);
+DEFINE_CAST(SNAPSHOT, Snapshot);
+DEFINE_CAST(SWAP, Swap);
+DEFINE_CAST(PATH, Path);
+
+Unit *unit_new(Manager *m, size_t size);
+void unit_free(Unit *u);
+
+int unit_add_name(Unit *u, const char *name);
+
+int unit_add_dependency(Unit *u, UnitDependency d, Unit *other, bool add_reference);
+int unit_add_two_dependencies(Unit *u, UnitDependency d, UnitDependency e, Unit *other, bool add_reference);
+
+int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name, const char *filename, bool add_reference);
+int unit_add_two_dependencies_by_name(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference);
+
+int unit_add_dependency_by_name_inverse(Unit *u, UnitDependency d, const char *name, const char *filename, bool add_reference);
+int unit_add_two_dependencies_by_name_inverse(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference);
+
+int unit_add_exec_dependencies(Unit *u, ExecContext *c);
+
+int unit_add_cgroup_from_text(Unit *u, const char *name, bool overwrite, CGroupBonding **ret);
+int unit_add_default_cgroups(Unit *u);
+CGroupBonding* unit_get_default_cgroup(Unit *u);
+int unit_add_cgroup_attribute(Unit *u, const CGroupSemantics *semantics, const char *controller, const char *name, const char *value, CGroupAttribute **ret);
+
+int unit_choose_id(Unit *u, const char *name);
+int unit_set_description(Unit *u, const char *description);
+
+bool unit_check_gc(Unit *u);
+
+void unit_add_to_load_queue(Unit *u);
+void unit_add_to_dbus_queue(Unit *u);
+void unit_add_to_cleanup_queue(Unit *u);
+void unit_add_to_gc_queue(Unit *u);
+
+int unit_merge(Unit *u, Unit *other);
+int unit_merge_by_name(Unit *u, const char *other);
+
+Unit *unit_follow_merge(Unit *u) _pure_;
+
+int unit_load_fragment_and_dropin(Unit *u);
+int unit_load_fragment_and_dropin_optional(Unit *u);
+int unit_load(Unit *unit);
+
+const char *unit_description(Unit *u) _pure_;
+
+bool unit_has_name(Unit *u, const char *name);
+
+UnitActiveState unit_active_state(Unit *u);
+
+const char* unit_sub_state_to_string(Unit *u);
+
+void unit_dump(Unit *u, FILE *f, const char *prefix);
+
+bool unit_can_reload(Unit *u) _pure_;
+bool unit_can_start(Unit *u) _pure_;
+bool unit_can_isolate(Unit *u) _pure_;
+
+int unit_start(Unit *u);
+int unit_stop(Unit *u);
+int unit_reload(Unit *u);
+
+int unit_kill(Unit *u, KillWho w, int signo, DBusError *error);
+int unit_kill_common(Unit *u, KillWho who, int signo, pid_t main_pid, pid_t control_pid, DBusError *error);
+
+void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns, bool reload_success);
+
+int unit_watch_fd(Unit *u, int fd, uint32_t events, Watch *w);
+void unit_unwatch_fd(Unit *u, Watch *w);
+
+int unit_watch_pid(Unit *u, pid_t pid);
+void unit_unwatch_pid(Unit *u, pid_t pid);
+
+int unit_watch_timer(Unit *u, clockid_t, bool relative, usec_t usec, Watch *w);
+void unit_unwatch_timer(Unit *u, Watch *w);
+
+int unit_watch_bus_name(Unit *u, const char *name);
+void unit_unwatch_bus_name(Unit *u, const char *name);
+
+bool unit_job_is_applicable(Unit *u, JobType j);
+
+int set_unit_path(const char *p);
+
+char *unit_dbus_path(Unit *u);
+
+int unit_load_related_unit(Unit *u, const char *type, Unit **_found);
+int unit_get_related_unit(Unit *u, const char *type, Unit **_found);
+
+bool unit_can_serialize(Unit *u) _pure_;
+int unit_serialize(Unit *u, FILE *f, FDSet *fds, bool serialize_jobs);
+void unit_serialize_item_format(Unit *u, FILE *f, const char *key, const char *value, ...) _printf_attr_(4,5);
+void unit_serialize_item(Unit *u, FILE *f, const char *key, const char *value);
+int unit_deserialize(Unit *u, FILE *f, FDSet *fds);
+
+int unit_add_node_link(Unit *u, const char *what, bool wants);
+
+int unit_coldplug(Unit *u);
+
+void unit_status_printf(Unit *u, const char *status, const char *unit_status_msg_format) _printf_attr_(3, 0);
+
+bool unit_need_daemon_reload(Unit *u);
+
+void unit_reset_failed(Unit *u);
+
+Unit *unit_following(Unit *u);
+
+bool unit_stop_pending(Unit *u) _pure_;
+bool unit_inactive_or_pending(Unit *u) _pure_;
+bool unit_active_or_pending(Unit *u);
+
+int unit_add_default_target_dependency(Unit *u, Unit *target);
+
+char *unit_default_cgroup_path(Unit *u);
+
+int unit_following_set(Unit *u, Set **s);
+
+void unit_start_on_failure(Unit *u);
+void unit_trigger_notify(Unit *u);
+
+bool unit_condition_test(Unit *u);
+
+UnitFileState unit_get_unit_file_state(Unit *u);
+
+Unit* unit_ref_set(UnitRef *ref, Unit *u);
+void unit_ref_unset(UnitRef *ref);
+
+#define UNIT_DEREF(ref) ((ref).unit)
+
+int unit_add_one_mount_link(Unit *u, Mount *m);
+int unit_add_mount_links(Unit *u);
+
+int unit_exec_context_defaults(Unit *u, ExecContext *c);
+
+ExecContext *unit_get_exec_context(Unit *u) _pure_;
+
+int unit_write_drop_in(Unit *u, bool runtime, const char *name, const char *data);
+int unit_remove_drop_in(Unit *u, bool runtime, const char *name);
+
+int unit_kill_context(Unit *u, KillContext *c, bool sigkill, pid_t main_pid, pid_t control_pid, bool main_pid_alien);
+
+const char *unit_active_state_to_string(UnitActiveState i) _const_;
+UnitActiveState unit_active_state_from_string(const char *s) _pure_;
+
+const char *unit_dependency_to_string(UnitDependency i) _const_;
+UnitDependency unit_dependency_from_string(const char *s) _pure_;
+
+/* Macros which append UNIT= or USER_UNIT= to the message */
+
+#define log_full_unit(level, unit, ...) log_meta_object(level, __FILE__, __LINE__, __func__, getpid() == 1 ? "UNIT=" : "USER_UNIT=", unit, __VA_ARGS__)
+#define log_debug_unit(unit, ...) log_full_unit(LOG_DEBUG, unit, __VA_ARGS__)
+#define log_info_unit(unit, ...) log_full_unit(LOG_INFO, unit, __VA_ARGS__)
+#define log_notice_unit(unit, ...) log_full_unit(LOG_NOTICE, unit, __VA_ARGS__)
+#define log_warning_unit(unit, ...) log_full_unit(LOG_WARNING, unit, __VA_ARGS__)
+#define log_error_unit(unit, ...) log_full_unit(LOG_ERR, unit, __VA_ARGS__)
+
+#define log_struct_unit(level, unit, ...) log_struct(level, getpid() == 1 ? "UNIT=%s" : "USER_UNIT=%s", unit, __VA_ARGS__)
diff --git a/src/core/user.conf b/src/core/user.conf
new file mode 100644
index 0000000000..4252451eb7
--- /dev/null
+++ b/src/core/user.conf
@@ -0,0 +1,17 @@
+# This file is part of systemd.
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 of the License, or
+# (at your option) any later version.
+#
+# See systemd-user.conf(5) for details
+
+[Manager]
+#LogLevel=info
+#LogTarget=console
+#LogColor=yes
+#LogLocation=no
+#DefaultControllers=cpu
+#DefaultStandardOutput=inherit
+#DefaultStandardError=inherit
diff --git a/src/cryptsetup/cryptsetup-generator.c b/src/cryptsetup/cryptsetup-generator.c
new file mode 100644
index 0000000000..81b770890a
--- /dev/null
+++ b/src/cryptsetup/cryptsetup-generator.c
@@ -0,0 +1,468 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <string.h>
+#include <errno.h>
+#include <unistd.h>
+
+#include "log.h"
+#include "util.h"
+#include "unit-name.h"
+#include "mkdir.h"
+#include "virt.h"
+#include "strv.h"
+#include "fileio.h"
+
+static const char *arg_dest = "/tmp";
+static bool arg_enabled = true;
+static bool arg_read_crypttab = true;
+
+static bool has_option(const char *haystack, const char *needle) {
+ const char *f = haystack;
+ size_t l;
+
+ assert(needle);
+
+ if (!haystack)
+ return false;
+
+ l = strlen(needle);
+
+ while ((f = strstr(f, needle))) {
+
+ if (f > haystack && f[-1] != ',') {
+ f++;
+ continue;
+ }
+
+ if (f[l] != 0 && f[l] != ',') {
+ f++;
+ continue;
+ }
+
+ return true;
+ }
+
+ return false;
+}
+
+static int create_disk(
+ const char *name,
+ const char *device,
+ const char *password,
+ const char *options) {
+
+ _cleanup_free_ char *p = NULL, *n = NULL, *d = NULL, *u = NULL, *from = NULL, *to = NULL, *e = NULL;
+ _cleanup_fclose_ FILE *f = NULL;
+ bool noauto, nofail;
+
+ assert(name);
+ assert(device);
+
+ noauto = has_option(options, "noauto");
+ nofail = has_option(options, "nofail");
+
+ n = unit_name_from_path_instance("systemd-cryptsetup", name, ".service");
+ if (!n)
+ return log_oom();
+
+ p = strjoin(arg_dest, "/", n, NULL);
+ if (!p)
+ return log_oom();
+
+ u = fstab_node_to_udev_node(device);
+ if (!u)
+ return log_oom();
+
+ d = unit_name_from_path(u, ".device");
+ if (!d)
+ return log_oom();
+
+ f = fopen(p, "wxe");
+ if (!f) {
+ log_error("Failed to create unit file %s: %m", p);
+ return -errno;
+ }
+
+ fputs(
+ "# Automatically generated by systemd-cryptsetup-generator\n\n"
+ "[Unit]\n"
+ "Description=Cryptography Setup for %I\n"
+ "Documentation=man:systemd-cryptsetup@.service(8) man:crypttab(5)\n"
+ "SourcePath=/etc/crypttab\n"
+ "Conflicts=umount.target\n"
+ "DefaultDependencies=no\n"
+ "BindsTo=dev-mapper-%i.device\n"
+ "After=systemd-readahead-collect.service systemd-readahead-replay.service\n",
+ f);
+
+ if (!nofail)
+ fprintf(f,
+ "Before=cryptsetup.target\n");
+
+ if (password) {
+ if (streq(password, "/dev/urandom") ||
+ streq(password, "/dev/random") ||
+ streq(password, "/dev/hw_random"))
+ fputs("After=systemd-random-seed-load.service\n", f);
+ else if (!streq(password, "-") &&
+ !streq(password, "none"))
+ fprintf(f,
+ "RequiresMountsFor=%s\n",
+ password);
+ }
+
+ if (is_device_path(u))
+ fprintf(f,
+ "BindsTo=%s\n"
+ "After=%s\n"
+ "Before=umount.target\n",
+ d, d);
+ else
+ fprintf(f,
+ "RequiresMountsFor=%s\n",
+ u);
+
+ fprintf(f,
+ "\n[Service]\n"
+ "Type=oneshot\n"
+ "RemainAfterExit=yes\n"
+ "TimeoutSec=0\n" /* the binary handles timeouts anyway */
+ "ExecStart=" SYSTEMD_CRYPTSETUP_PATH " attach '%s' '%s' '%s' '%s'\n"
+ "ExecStop=" SYSTEMD_CRYPTSETUP_PATH " detach '%s'\n",
+ name, u, strempty(password), strempty(options),
+ name);
+
+ if (has_option(options, "tmp"))
+ fprintf(f,
+ "ExecStartPost=/sbin/mke2fs '/dev/mapper/%s'\n",
+ name);
+
+ if (has_option(options, "swap"))
+ fprintf(f,
+ "ExecStartPost=/sbin/mkswap '/dev/mapper/%s'\n",
+ name);
+
+ fflush(f);
+
+ if (ferror(f)) {
+ log_error("Failed to write file %s: %m", p);
+ return -errno;
+ }
+
+ if (asprintf(&from, "../%s", n) < 0)
+ return log_oom();
+
+ if (!noauto) {
+
+ to = strjoin(arg_dest, "/", d, ".wants/", n, NULL);
+ if (!to)
+ return log_oom();
+
+ mkdir_parents_label(to, 0755);
+ if (symlink(from, to) < 0) {
+ log_error("Failed to create symlink %s: %m", to);
+ return -errno;
+ }
+
+ free(to);
+ if (!nofail)
+ to = strjoin(arg_dest, "/cryptsetup.target.requires/", n, NULL);
+ else
+ to = strjoin(arg_dest, "/cryptsetup.target.wants/", n, NULL);
+ if (!to)
+ return log_oom();
+
+ mkdir_parents_label(to, 0755);
+ if (symlink(from, to) < 0) {
+ log_error("Failed to create symlink %s: %m", to);
+ return -errno;
+ }
+ }
+
+ e = unit_name_escape(name);
+ if (!e)
+ return log_oom();
+
+ free(to);
+ to = strjoin(arg_dest, "/dev-mapper-", e, ".device.requires/", n, NULL);
+ if (!to)
+ return log_oom();
+
+ mkdir_parents_label(to, 0755);
+ if (symlink(from, to) < 0) {
+ log_error("Failed to create symlink %s: %m", to);
+ return -errno;
+ }
+
+ if (!noauto && !nofail) {
+ int r;
+ free(p);
+ p = strjoin(arg_dest, "/dev-mapper-", e, ".device.d/50-job-timeout-sec-0.conf", NULL);
+ if (!p)
+ return log_oom();
+
+ mkdir_parents_label(p, 0755);
+
+ r = write_string_file(p,
+ "# Automatically generated by systemd-cryptsetup-generator\n\n"
+ "[Unit]\n"
+ "JobTimeoutSec=0\n"); /* the binary handles timeouts anyway */
+ if (r)
+ return r;
+ }
+
+ return 0;
+}
+
+static int parse_proc_cmdline(char ***arg_proc_cmdline_disks, char **arg_proc_cmdline_keyfile) {
+ _cleanup_free_ char *line = NULL;
+ char *w = NULL, *state = NULL;
+ int r;
+ size_t l;
+
+ if (detect_container(NULL) > 0)
+ return 0;
+
+ r = read_one_line_file("/proc/cmdline", &line);
+ if (r < 0) {
+ log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
+ return 0;
+ }
+
+ FOREACH_WORD_QUOTED(w, l, line, state) {
+ _cleanup_free_ char *word = NULL;
+
+ word = strndup(w, l);
+ if (!word)
+ return log_oom();
+
+ if (startswith(word, "luks=")) {
+ r = parse_boolean(word + 5);
+ if (r < 0)
+ log_warning("Failed to parse luks switch %s. Ignoring.", word + 5);
+ else
+ arg_enabled = r;
+
+ } else if (startswith(word, "rd.luks=")) {
+
+ if (in_initrd()) {
+ r = parse_boolean(word + 8);
+ if (r < 0)
+ log_warning("Failed to parse luks switch %s. Ignoring.", word + 8);
+ else
+ arg_enabled = r;
+ }
+
+ } else if (startswith(word, "luks.crypttab=")) {
+ r = parse_boolean(word + 14);
+ if (r < 0)
+ log_warning("Failed to parse luks crypttab switch %s. Ignoring.", word + 14);
+ else
+ arg_read_crypttab = r;
+
+ } else if (startswith(word, "rd.luks.crypttab=")) {
+
+ if (in_initrd()) {
+ r = parse_boolean(word + 17);
+ if (r < 0)
+ log_warning("Failed to parse luks crypttab switch %s. Ignoring.", word + 17);
+ else
+ arg_read_crypttab = r;
+ }
+
+ } else if (startswith(word, "luks.uuid=")) {
+ if (strv_extend(arg_proc_cmdline_disks, word + 10) < 0)
+ return log_oom();
+
+ } else if (startswith(word, "rd.luks.uuid=")) {
+
+ if (in_initrd()) {
+ if (strv_extend(arg_proc_cmdline_disks, word + 13) < 0)
+ return log_oom();
+ }
+
+ } else if (startswith(word, "luks.key=")) {
+ *arg_proc_cmdline_keyfile = strdup(word + 9);
+ if (!*arg_proc_cmdline_keyfile)
+ return log_oom();
+
+ } else if (startswith(word, "rd.luks.key=")) {
+
+ if (in_initrd()) {
+ if (*arg_proc_cmdline_keyfile)
+ free(*arg_proc_cmdline_keyfile);
+ *arg_proc_cmdline_keyfile = strdup(word + 12);
+ if (!*arg_proc_cmdline_keyfile)
+ return log_oom();
+ }
+
+ } else if (startswith(word, "luks.") ||
+ (in_initrd() && startswith(word, "rd.luks."))) {
+
+ log_warning("Unknown kernel switch %s. Ignoring.", word);
+ }
+ }
+
+ strv_uniq(*arg_proc_cmdline_disks);
+
+ return 0;
+}
+
+int main(int argc, char *argv[]) {
+ _cleanup_strv_free_ char **arg_proc_cmdline_disks_done = NULL;
+ _cleanup_strv_free_ char **arg_proc_cmdline_disks = NULL;
+ _cleanup_free_ char *arg_proc_cmdline_keyfile = NULL;
+ _cleanup_fclose_ FILE *f = NULL;
+ unsigned n = 0;
+ int r = EXIT_SUCCESS;
+ char **i;
+
+ if (argc > 1 && argc != 4) {
+ log_error("This program takes three or no arguments.");
+ return EXIT_FAILURE;
+ }
+
+ if (argc > 1)
+ arg_dest = argv[1];
+
+ log_set_target(LOG_TARGET_SAFE);
+ log_parse_environment();
+ log_open();
+
+ umask(0022);
+
+ if (parse_proc_cmdline(&arg_proc_cmdline_disks, &arg_proc_cmdline_keyfile) < 0)
+ return EXIT_FAILURE;
+
+ if (!arg_enabled)
+ return EXIT_SUCCESS;
+
+ if (arg_read_crypttab) {
+ struct stat st;
+
+ f = fopen("/etc/crypttab", "re");
+ if (!f) {
+ if (errno == ENOENT)
+ r = EXIT_SUCCESS;
+ else {
+ r = EXIT_FAILURE;
+ log_error("Failed to open /etc/crypttab: %m");
+ }
+
+ goto next;
+ }
+
+ if (fstat(fileno(f), &st) < 0) {
+ log_error("Failed to stat /etc/crypttab: %m");
+ r = EXIT_FAILURE;
+ goto next;
+ }
+
+ /* If we readd support for specifying passphrases
+ * directly in crypttabe we should upgrade the warning
+ * below, though possibly only if a passphrase is
+ * specified directly. */
+ if (st.st_mode & 0005)
+ log_debug("/etc/crypttab is world-readable. This is usually not a good idea.");
+
+ for (;;) {
+ char line[LINE_MAX], *l;
+ _cleanup_free_ char *name = NULL, *device = NULL, *password = NULL, *options = NULL;
+ int k;
+
+ if (!fgets(line, sizeof(line), f))
+ break;
+
+ n++;
+
+ l = strstrip(line);
+ if (*l == '#' || *l == 0)
+ continue;
+
+ k = sscanf(l, "%ms %ms %ms %ms", &name, &device, &password, &options);
+ if (k < 2 || k > 4) {
+ log_error("Failed to parse /etc/crypttab:%u, ignoring.", n);
+ r = EXIT_FAILURE;
+ continue;
+ }
+
+ if (arg_proc_cmdline_disks) {
+ /*
+ If luks UUIDs are specified on the kernel command line, use them as a filter
+ for /etc/crypttab and only generate units for those.
+ */
+ STRV_FOREACH(i, arg_proc_cmdline_disks) {
+ _cleanup_free_ char *proc_device = NULL, *proc_name = NULL;
+ const char *p = *i;
+
+ if (startswith(p, "luks-"))
+ p += 5;
+
+ proc_name = strappend("luks-", p);
+ proc_device = strappend("UUID=", p);
+
+ if (!proc_name || !proc_device)
+ return log_oom();
+
+ if (streq(proc_device, device) || streq(proc_name, name)) {
+ if (create_disk(name, device, password, options) < 0)
+ r = EXIT_FAILURE;
+
+ if (strv_extend(&arg_proc_cmdline_disks_done, p) < 0)
+ return log_oom();
+ }
+ }
+ } else {
+ if (create_disk(name, device, password, options) < 0)
+ r = EXIT_FAILURE;
+ }
+ }
+ }
+
+next:
+ STRV_FOREACH(i, arg_proc_cmdline_disks) {
+ /*
+ Generate units for those UUIDs, which were specified
+ on the kernel command line and not yet written.
+ */
+
+ _cleanup_free_ char *name = NULL, *device = NULL;
+ const char *p = *i;
+
+ if (startswith(p, "luks-"))
+ p += 5;
+
+ if (strv_contains(arg_proc_cmdline_disks_done, p))
+ continue;
+
+ name = strappend("luks-", p);
+ device = strappend("UUID=", p);
+
+ if (!name || !device)
+ return log_oom();
+
+ if (create_disk(name, device, arg_proc_cmdline_keyfile, "timeout=0") < 0)
+ r = EXIT_FAILURE;
+ }
+
+ return r;
+}
diff --git a/src/cryptsetup/cryptsetup.c b/src/cryptsetup/cryptsetup.c
new file mode 100644
index 0000000000..347394db8e
--- /dev/null
+++ b/src/cryptsetup/cryptsetup.c
@@ -0,0 +1,591 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <string.h>
+#include <errno.h>
+#include <sys/mman.h>
+#include <mntent.h>
+
+#include <libcryptsetup.h>
+#include <libudev.h>
+
+#include "log.h"
+#include "util.h"
+#include "path-util.h"
+#include "strv.h"
+#include "ask-password-api.h"
+#include "def.h"
+
+static const char *opt_type = NULL; /* LUKS1 or PLAIN */
+static char *opt_cipher = NULL;
+static unsigned opt_key_size = 0;
+static unsigned opt_keyfile_size = 0;
+static unsigned opt_keyfile_offset = 0;
+static char *opt_hash = NULL;
+static unsigned opt_tries = 0;
+static bool opt_readonly = false;
+static bool opt_verify = false;
+static bool opt_discards = false;
+static usec_t opt_timeout = 0;
+
+/* Options Debian's crypttab knows we don't:
+
+ offset=
+ skip=
+ precheck=
+ check=
+ checkargs=
+ noearly=
+ loud=
+ keyscript=
+*/
+
+static int parse_one_option(const char *option) {
+ assert(option);
+
+ /* Handled outside of this tool */
+ if (streq(option, "noauto") || streq(option, "nofail"))
+ return 0;
+
+ if (startswith(option, "cipher=")) {
+ char *t;
+
+ t = strdup(option+7);
+ if (!t)
+ return -ENOMEM;
+
+ free(opt_cipher);
+ opt_cipher = t;
+
+ } else if (startswith(option, "size=")) {
+
+ if (safe_atou(option+5, &opt_key_size) < 0) {
+ log_error("size= parse failure, ignoring.");
+ return 0;
+ }
+
+ } else if (startswith(option, "keyfile-size=")) {
+
+ if (safe_atou(option+13, &opt_keyfile_size) < 0) {
+ log_error("keyfile-size= parse failure, ignoring.");
+ return 0;
+ }
+
+ } else if (startswith(option, "keyfile-offset=")) {
+
+ if (safe_atou(option+15, &opt_keyfile_offset) < 0) {
+ log_error("keyfile-offset= parse failure, ignoring.");
+ return 0;
+ }
+
+ } else if (startswith(option, "hash=")) {
+ char *t;
+
+ t = strdup(option+5);
+ if (!t)
+ return -ENOMEM;
+
+ free(opt_hash);
+ opt_hash = t;
+
+ } else if (startswith(option, "tries=")) {
+
+ if (safe_atou(option+6, &opt_tries) < 0) {
+ log_error("tries= parse failure, ignoring.");
+ return 0;
+ }
+
+ } else if (streq(option, "readonly") || streq(option, "read-only"))
+ opt_readonly = true;
+ else if (streq(option, "verify"))
+ opt_verify = true;
+ else if (streq(option, "allow-discards"))
+ opt_discards = true;
+ else if (streq(option, "luks"))
+ opt_type = CRYPT_LUKS1;
+ else if (streq(option, "plain") ||
+ streq(option, "swap") ||
+ streq(option, "tmp"))
+ opt_type = CRYPT_PLAIN;
+ else if (startswith(option, "timeout=")) {
+
+ if (parse_sec(option+8, &opt_timeout) < 0) {
+ log_error("timeout= parse failure, ignoring.");
+ return 0;
+ }
+
+ } else if (!streq(option, "none"))
+ log_error("Encountered unknown /etc/crypttab option '%s', ignoring.", option);
+
+ return 0;
+}
+
+static int parse_options(const char *options) {
+ char *state, *w;
+ size_t l;
+ int r;
+
+ assert(options);
+
+ FOREACH_WORD_SEPARATOR(w, l, options, ",", state) {
+ _cleanup_free_ char *o;
+
+ o = strndup(w, l);
+ if (!o)
+ return -ENOMEM;
+ r = parse_one_option(o);
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static void log_glue(int level, const char *msg, void *usrptr) {
+ log_debug("%s", msg);
+}
+
+static char *disk_description(const char *path) {
+
+ static const char name_fields[] = {
+ "ID_PART_ENTRY_NAME\0"
+ "DM_NAME\0"
+ "ID_MODEL_FROM_DATABASE\0"
+ "ID_MODEL\0"
+ };
+
+ struct udev *udev = NULL;
+ struct udev_device *device = NULL;
+ struct stat st;
+ char *description = NULL;
+ const char *i;
+
+ assert(path);
+
+ if (stat(path, &st) < 0)
+ return NULL;
+
+ if (!S_ISBLK(st.st_mode))
+ return NULL;
+
+ udev = udev_new();
+ if (!udev)
+ return NULL;
+
+ device = udev_device_new_from_devnum(udev, 'b', st.st_rdev);
+ if (!device)
+ goto finish;
+
+ NULSTR_FOREACH(i, name_fields) {
+ const char *name;
+
+ name = udev_device_get_property_value(device, i);
+ if (!isempty(name)) {
+ description = strdup(name);
+ break;
+ }
+ }
+
+finish:
+ if (device)
+ udev_device_unref(device);
+
+ if (udev)
+ udev_unref(udev);
+
+ return description;
+}
+
+static char *disk_mount_point(const char *label) {
+ char *mp = NULL, *device = NULL;
+ FILE *f = NULL;
+ struct mntent *m;
+
+ /* Yeah, we don't support native systemd unit files here for now */
+
+ if (asprintf(&device, "/dev/mapper/%s", label) < 0)
+ goto finish;
+
+ f = setmntent("/etc/fstab", "r");
+ if (!f)
+ goto finish;
+
+ while ((m = getmntent(f)))
+ if (path_equal(m->mnt_fsname, device)) {
+ mp = strdup(m->mnt_dir);
+ break;
+ }
+
+finish:
+ if (f)
+ endmntent(f);
+
+ free(device);
+
+ return mp;
+}
+
+static int help(void) {
+
+ printf("%s attach VOLUME SOURCEDEVICE [PASSWORD] [OPTIONS]\n"
+ "%s detach VOLUME\n\n"
+ "Attaches or detaches an encrypted block device.\n",
+ program_invocation_short_name,
+ program_invocation_short_name);
+
+ return 0;
+}
+
+int main(int argc, char *argv[]) {
+ int r = EXIT_FAILURE;
+ struct crypt_device *cd = NULL;
+ char **passwords = NULL, *truncated_cipher = NULL;
+ const char *cipher = NULL, *cipher_mode = NULL, *hash = NULL, *name = NULL;
+ char *description = NULL, *name_buffer = NULL, *mount_point = NULL;
+
+ if (argc <= 1) {
+ help();
+ return EXIT_SUCCESS;
+ }
+
+ if (argc < 3) {
+ log_error("This program requires at least two arguments.");
+ return EXIT_FAILURE;
+ }
+
+ log_set_target(LOG_TARGET_AUTO);
+ log_parse_environment();
+ log_open();
+
+ umask(0022);
+
+ if (streq(argv[1], "attach")) {
+ uint32_t flags = 0;
+ int k;
+ unsigned try;
+ const char *key_file = NULL;
+ usec_t until;
+ crypt_status_info status;
+
+ /* Arguments: systemd-cryptsetup attach VOLUME SOURCE-DEVICE [PASSWORD] [OPTIONS] */
+
+ if (argc < 4) {
+ log_error("attach requires at least two arguments.");
+ goto finish;
+ }
+
+ if (argc >= 5 &&
+ argv[4][0] &&
+ !streq(argv[4], "-") &&
+ !streq(argv[4], "none")) {
+
+ if (!path_is_absolute(argv[4]))
+ log_error("Password file path %s is not absolute. Ignoring.", argv[4]);
+ else
+ key_file = argv[4];
+ }
+
+ if (argc >= 6 && argv[5][0] && !streq(argv[5], "-")) {
+ if (parse_options(argv[5]) < 0)
+ goto finish;
+ }
+
+ /* A delicious drop of snake oil */
+ mlockall(MCL_FUTURE);
+
+ description = disk_description(argv[3]);
+ mount_point = disk_mount_point(argv[2]);
+
+ if (description && streq(argv[2], description)) {
+ /* If the description string is simply the
+ * volume name, then let's not show this
+ * twice */
+ free(description);
+ description = NULL;
+ }
+
+ if (mount_point && description)
+ asprintf(&name_buffer, "%s (%s) on %s", description, argv[2], mount_point);
+ else if (mount_point)
+ asprintf(&name_buffer, "%s on %s", argv[2], mount_point);
+ else if (description)
+ asprintf(&name_buffer, "%s (%s)", description, argv[2]);
+
+ name = name_buffer ? name_buffer : argv[2];
+
+ k = crypt_init(&cd, argv[3]);
+ if (k) {
+ log_error("crypt_init() failed: %s", strerror(-k));
+ goto finish;
+ }
+
+ crypt_set_log_callback(cd, log_glue, NULL);
+
+ status = crypt_status(cd, argv[2]);
+ if (status == CRYPT_ACTIVE || status == CRYPT_BUSY) {
+ log_info("Volume %s already active.", argv[2]);
+ r = EXIT_SUCCESS;
+ goto finish;
+ }
+
+ if (opt_readonly)
+ flags |= CRYPT_ACTIVATE_READONLY;
+
+ if (opt_discards)
+ flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS;
+
+ if (opt_timeout > 0)
+ until = now(CLOCK_MONOTONIC) + opt_timeout;
+ else
+ until = 0;
+
+ opt_tries = opt_tries > 0 ? opt_tries : 3;
+ opt_key_size = (opt_key_size > 0 ? opt_key_size : 256);
+ if (opt_hash) {
+ /* plain isn't a real hash type. it just means "use no hash" */
+ if (!streq(opt_hash, "plain"))
+ hash = opt_hash;
+ } else
+ hash = "ripemd160";
+
+ if (opt_cipher) {
+ size_t l;
+
+ l = strcspn(opt_cipher, "-");
+ truncated_cipher = strndup(opt_cipher, l);
+
+ if (!truncated_cipher) {
+ log_oom();
+ goto finish;
+ }
+
+ cipher = truncated_cipher;
+ cipher_mode = opt_cipher[l] ? opt_cipher+l+1 : "plain";
+ } else {
+ cipher = "aes";
+ cipher_mode = "cbc-essiv:sha256";
+ }
+
+ for (try = 0; try < opt_tries; try++) {
+ bool pass_volume_key = false;
+
+ strv_free(passwords);
+ passwords = NULL;
+
+ if (!key_file) {
+ char *text, **p;
+
+ if (asprintf(&text, "Please enter passphrase for disk %s!", name) < 0) {
+ log_oom();
+ goto finish;
+ }
+
+ k = ask_password_auto(text, "drive-harddisk", until, try == 0 && !opt_verify, &passwords);
+ free(text);
+
+ if (k < 0) {
+ log_error("Failed to query password: %s", strerror(-k));
+ goto finish;
+ }
+
+ if (opt_verify) {
+ char **passwords2 = NULL;
+
+ assert(strv_length(passwords) == 1);
+
+ if (asprintf(&text, "Please enter passphrase for disk %s! (verification)", name) < 0) {
+ log_oom();
+ goto finish;
+ }
+
+ k = ask_password_auto(text, "drive-harddisk", until, false, &passwords2);
+ free(text);
+
+ if (k < 0) {
+ log_error("Failed to query verification password: %s", strerror(-k));
+ goto finish;
+ }
+
+ assert(strv_length(passwords2) == 1);
+
+ if (!streq(passwords[0], passwords2[0])) {
+ log_warning("Passwords did not match, retrying.");
+ strv_free(passwords2);
+ continue;
+ }
+
+ strv_free(passwords2);
+ }
+
+ strv_uniq(passwords);
+
+ STRV_FOREACH(p, passwords) {
+ char *c;
+
+ if (strlen(*p)+1 >= opt_key_size)
+ continue;
+
+ /* Pad password if necessary */
+ if (!(c = new(char, opt_key_size))) {
+ log_oom();
+ goto finish;
+ }
+
+ strncpy(c, *p, opt_key_size);
+ free(*p);
+ *p = c;
+ }
+ }
+
+ k = 0;
+
+ if (!opt_type || streq(opt_type, CRYPT_LUKS1))
+ k = crypt_load(cd, CRYPT_LUKS1, NULL);
+
+ if ((!opt_type && k < 0) || streq_ptr(opt_type, CRYPT_PLAIN)) {
+ struct crypt_params_plain params = { .hash = hash };
+
+ /* for CRYPT_PLAIN limit reads
+ * from keyfile to key length, and
+ * ignore keyfile-size */
+ opt_keyfile_size = opt_key_size / 8;
+
+ /* In contrast to what the name
+ * crypt_setup() might suggest this
+ * doesn't actually format anything,
+ * it just configures encryption
+ * parameters when used for plain
+ * mode. */
+ k = crypt_format(cd, CRYPT_PLAIN,
+ cipher,
+ cipher_mode,
+ NULL,
+ NULL,
+ opt_keyfile_size,
+ &params);
+
+ /* hash == NULL implies the user passed "plain" */
+ pass_volume_key = (hash == NULL);
+ }
+
+ if (k < 0) {
+ log_error("Loading of cryptographic parameters failed: %s", strerror(-k));
+ goto finish;
+ }
+
+ log_info("Set cipher %s, mode %s, key size %i bits for device %s.",
+ crypt_get_cipher(cd),
+ crypt_get_cipher_mode(cd),
+ crypt_get_volume_key_size(cd)*8,
+ argv[3]);
+
+ if (key_file) {
+ struct stat st;
+
+ /* Ideally we'd do this on the open
+ * fd, but since this is just a
+ * warning it's OK to do this in two
+ * steps */
+ if (stat(key_file, &st) >= 0 && (st.st_mode & 0005))
+ log_warning("Key file %s is world-readable. That's certainly not a good idea.", key_file);
+
+ k = crypt_activate_by_keyfile_offset(
+ cd, argv[2], CRYPT_ANY_SLOT, key_file, opt_keyfile_size,
+ opt_keyfile_offset, flags);
+ if (k < 0) {
+ log_error("Failed to activate with key file '%s': %s", key_file, strerror(-k));
+ key_file = NULL;
+ continue;
+ }
+ } else {
+ char **p;
+
+ STRV_FOREACH(p, passwords) {
+
+ if (pass_volume_key)
+ k = crypt_activate_by_volume_key(cd, argv[2], *p, opt_key_size, flags);
+ else
+ k = crypt_activate_by_passphrase(cd, argv[2], CRYPT_ANY_SLOT, *p, strlen(*p), flags);
+
+ if (k >= 0)
+ break;
+ }
+ }
+
+ if (k >= 0)
+ break;
+
+ if (k != -EPERM) {
+ log_error("Failed to activate: %s", strerror(-k));
+ goto finish;
+ }
+
+ log_warning("Invalid passphrase.");
+ }
+
+ if (try >= opt_tries) {
+ log_error("Too many attempts.");
+ r = EXIT_FAILURE;
+ goto finish;
+ }
+
+ } else if (streq(argv[1], "detach")) {
+ int k;
+
+ k = crypt_init_by_name(&cd, argv[2]);
+ if (k) {
+ log_error("crypt_init() failed: %s", strerror(-k));
+ goto finish;
+ }
+
+ crypt_set_log_callback(cd, log_glue, NULL);
+
+ k = crypt_deactivate(cd, argv[2]);
+ if (k < 0) {
+ log_error("Failed to deactivate: %s", strerror(-k));
+ goto finish;
+ }
+
+ } else {
+ log_error("Unknown verb %s.", argv[1]);
+ goto finish;
+ }
+
+ r = EXIT_SUCCESS;
+
+finish:
+
+ if (cd)
+ crypt_free(cd);
+
+ free(opt_cipher);
+ free(opt_hash);
+
+ free(truncated_cipher);
+
+ strv_free(passwords);
+
+ free(description);
+ free(mount_point);
+ free(name_buffer);
+
+ return r;
+}
diff --git a/src/delta/delta.c b/src/delta/delta.c
new file mode 100644
index 0000000000..aec3dc8995
--- /dev/null
+++ b/src/delta/delta.c
@@ -0,0 +1,489 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <assert.h>
+#include <string.h>
+#include <unistd.h>
+#include <getopt.h>
+
+#include "hashmap.h"
+#include "util.h"
+#include "path-util.h"
+#include "log.h"
+#include "pager.h"
+#include "build.h"
+
+static bool arg_no_pager = false;
+static int arg_diff = -1;
+
+static enum {
+ SHOW_MASKED = 1 << 0,
+ SHOW_EQUIVALENT = 1 << 1,
+ SHOW_REDIRECTED = 1 << 2,
+ SHOW_OVERRIDDEN = 1 << 3,
+ SHOW_UNCHANGED = 1 << 4,
+
+ SHOW_DEFAULTS =
+ (SHOW_MASKED | SHOW_EQUIVALENT | SHOW_REDIRECTED | SHOW_OVERRIDDEN)
+} arg_flags = 0;
+
+static int equivalent(const char *a, const char *b) {
+ _cleanup_free_ char *x = NULL, *y = NULL;
+
+ x = canonicalize_file_name(a);
+ if (!x)
+ return -errno;
+
+ y = canonicalize_file_name(b);
+ if (!y)
+ return -errno;
+
+ return path_equal(x, y);
+}
+
+static int notify_override_masked(const char *top, const char *bottom) {
+ if (!(arg_flags & SHOW_MASKED))
+ return 0;
+
+ printf(ANSI_HIGHLIGHT_RED_ON "[MASKED]" ANSI_HIGHLIGHT_OFF " %s → %s\n", top, bottom);
+ return 1;
+}
+
+static int notify_override_equivalent(const char *top, const char *bottom) {
+ if (!(arg_flags & SHOW_EQUIVALENT))
+ return 0;
+
+ printf(ANSI_HIGHLIGHT_GREEN_ON "[EQUIVALENT]" ANSI_HIGHLIGHT_OFF " %s → %s\n", top, bottom);
+ return 1;
+}
+
+static int notify_override_redirected(const char *top, const char *bottom) {
+ if (!(arg_flags & SHOW_REDIRECTED))
+ return 0;
+
+ printf(ANSI_HIGHLIGHT_ON "[REDIRECTED]" ANSI_HIGHLIGHT_OFF " %s → %s\n", top, bottom);
+ return 1;
+}
+
+static int notify_override_overridden(const char *top, const char *bottom) {
+ if (!(arg_flags & SHOW_OVERRIDDEN))
+ return 0;
+
+ printf(ANSI_HIGHLIGHT_ON "[OVERRIDDEN]" ANSI_HIGHLIGHT_OFF " %s → %s\n", top, bottom);
+ return 1;
+}
+
+static int notify_override_unchanged(const char *f) {
+ if (!(arg_flags & SHOW_UNCHANGED))
+ return 0;
+
+ printf("[UNCHANGED] %s\n", f);
+ return 1;
+}
+
+static int found_override(const char *top, const char *bottom) {
+ _cleanup_free_ char *dest = NULL;
+ int k;
+ pid_t pid;
+
+ assert(top);
+ assert(bottom);
+
+ if (null_or_empty_path(top) > 0) {
+ notify_override_masked(top, bottom);
+ return 0;
+ }
+
+ k = readlink_malloc(top, &dest);
+ if (k >= 0) {
+ if (equivalent(dest, bottom) > 0)
+ notify_override_equivalent(top, bottom);
+ else
+ notify_override_redirected(top, bottom);
+
+ return 0;
+ }
+
+ notify_override_overridden(top, bottom);
+ if (!arg_diff)
+ return 0;
+
+ putchar('\n');
+
+ fflush(stdout);
+
+ pid = fork();
+ if (pid < 0) {
+ log_error("Failed to fork off diff: %m");
+ return -errno;
+ } else if (pid == 0) {
+ execlp("diff", "diff", "-us", "--", bottom, top, NULL);
+ log_error("Failed to execute diff: %m");
+ _exit(1);
+ }
+
+ wait_for_terminate(pid, NULL);
+
+ putchar('\n');
+
+ return 0;
+}
+
+static int enumerate_dir(Hashmap *top, Hashmap *bottom, const char *path) {
+ _cleanup_closedir_ DIR *d;
+
+ assert(top);
+ assert(bottom);
+ assert(path);
+
+ d = opendir(path);
+ if (!d) {
+ if (errno == ENOENT)
+ return 0;
+
+ log_error("Failed to enumerate %s: %m", path);
+ return -errno;
+ }
+
+ for (;;) {
+ struct dirent *de;
+ union dirent_storage buf;
+ int k;
+ char *p;
+
+ k = readdir_r(d, &buf.de, &de);
+ if (k != 0)
+ return -k;
+
+ if (!de)
+ break;
+
+ if (!dirent_is_file(de))
+ continue;
+
+ p = strjoin(path, "/", de->d_name, NULL);
+ if (!p)
+ return -ENOMEM;
+
+ path_kill_slashes(p);
+
+ k = hashmap_put(top, path_get_file_name(p), p);
+ if (k >= 0) {
+ p = strdup(p);
+ if (!p)
+ return -ENOMEM;
+ } else if (k != -EEXIST) {
+ free(p);
+ return k;
+ }
+
+ free(hashmap_remove(bottom, path_get_file_name(p)));
+ k = hashmap_put(bottom, path_get_file_name(p), p);
+ if (k < 0) {
+ free(p);
+ return k;
+ }
+ }
+
+ return 0;
+}
+
+static int process_suffix(const char *prefixes, const char *suffix) {
+ const char *p;
+ char *f;
+ Hashmap *top, *bottom=NULL;
+ int r = 0, k;
+ Iterator i;
+ int n_found = 0;
+
+ assert(prefixes);
+ assert(suffix);
+
+ top = hashmap_new(string_hash_func, string_compare_func);
+ if (!top) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ bottom = hashmap_new(string_hash_func, string_compare_func);
+ if (!bottom) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ NULSTR_FOREACH(p, prefixes) {
+ _cleanup_free_ char *t = NULL;
+
+ t = strjoin(p, "/", suffix, NULL);
+ if (!t) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ k = enumerate_dir(top, bottom, t);
+ if (k < 0)
+ r = k;
+
+ log_debug("Looking at %s", t);
+ }
+
+ HASHMAP_FOREACH(f, top, i) {
+ char *o;
+
+ o = hashmap_get(bottom, path_get_file_name(f));
+ assert(o);
+
+ if (path_equal(o, f)) {
+ notify_override_unchanged(f);
+ continue;
+ }
+
+ k = found_override(f, o);
+ if (k < 0)
+ r = k;
+
+ n_found ++;
+ }
+
+finish:
+ if (top)
+ hashmap_free_free(top);
+ if (bottom)
+ hashmap_free_free(bottom);
+
+ return r < 0 ? r : n_found;
+}
+
+static int process_suffix_chop(const char *prefixes, const char *suffix) {
+ const char *p;
+
+ assert(prefixes);
+ assert(suffix);
+
+ if (!path_is_absolute(suffix))
+ return process_suffix(prefixes, suffix);
+
+ /* Strip prefix from the suffix */
+ NULSTR_FOREACH(p, prefixes) {
+ if (startswith(suffix, p)) {
+ suffix += strlen(p);
+ suffix += strspn(suffix, "/");
+ return process_suffix(prefixes, suffix);
+ }
+ }
+
+ log_error("Invalid suffix specification %s.", suffix);
+ return -EINVAL;
+}
+
+static void help(void) {
+
+ printf("%s [OPTIONS...] [SUFFIX...]\n\n"
+ "Find overridden configuration files.\n\n"
+ " -h --help Show this help\n"
+ " --version Show package version\n"
+ " --no-pager Do not pipe output into a pager\n"
+ " --diff[=1|0] Show a diff when overridden files differ\n"
+ " -t --type=LIST... Only display a selected set of override types\n",
+ program_invocation_short_name);
+}
+
+static int parse_flags(const char *flag_str, int flags) {
+ char *w, *state;
+ size_t l;
+
+ FOREACH_WORD(w, l, flag_str, state) {
+ if (strneq("masked", w, l))
+ flags |= SHOW_MASKED;
+ else if (strneq ("equivalent", w, l))
+ flags |= SHOW_EQUIVALENT;
+ else if (strneq("redirected", w, l))
+ flags |= SHOW_REDIRECTED;
+ else if (strneq("overridden", w, l))
+ flags |= SHOW_OVERRIDDEN;
+ else if (strneq("unchanged", w, l))
+ flags |= SHOW_UNCHANGED;
+ else if (strneq("default", w, l))
+ flags |= SHOW_DEFAULTS;
+ else
+ return -EINVAL;
+ }
+ return flags;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+
+ enum {
+ ARG_NO_PAGER = 0x100,
+ ARG_DIFF,
+ ARG_VERSION
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "version", no_argument, NULL, ARG_VERSION },
+ { "no-pager", no_argument, NULL, ARG_NO_PAGER },
+ { "diff", optional_argument, NULL, ARG_DIFF },
+ { "type", required_argument, NULL, 't' },
+ { NULL, 0, NULL, 0 }
+ };
+
+ int c;
+
+ assert(argc >= 1);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "ht:", options, NULL)) >= 0) {
+
+ switch (c) {
+
+ case 'h':
+ help();
+ return 0;
+
+ case ARG_VERSION:
+ puts(PACKAGE_STRING);
+ puts(SYSTEMD_FEATURES);
+ return 0;
+
+ case ARG_NO_PAGER:
+ arg_no_pager = true;
+ break;
+
+ case '?':
+ return -EINVAL;
+
+ case 't': {
+ int f;
+ f = parse_flags(optarg, arg_flags);
+ if (f < 0) {
+ log_error("Failed to parse flags field.");
+ return -EINVAL;
+ }
+ arg_flags = f;
+ break;
+ }
+
+ case ARG_DIFF:
+ if (!optarg)
+ arg_diff = 1;
+ else {
+ int b;
+
+ b = parse_boolean(optarg);
+ if (b < 0) {
+ log_error("Failed to parse diff boolean.");
+ return -EINVAL;
+ } else if (b)
+ arg_diff = 1;
+ else
+ arg_diff = 0;
+ }
+ break;
+
+ default:
+ log_error("Unknown option code %c", c);
+ return -EINVAL;
+ }
+ }
+
+ return 1;
+}
+
+int main(int argc, char *argv[]) {
+
+ const char prefixes[] =
+ "/etc\0"
+ "/run\0"
+ "/usr/local/lib\0"
+ "/usr/local/share\0"
+ "/usr/lib\0"
+ "/usr/share\0"
+#ifdef HAVE_SPLIT_USR
+ "/lib\0"
+#endif
+ ;
+
+ const char suffixes[] =
+ "sysctl.d\0"
+ "tmpfiles.d\0"
+ "modules-load.d\0"
+ "binfmt.d\0"
+ "systemd/system\0"
+ "systemd/user\0"
+ "systemd/system-preset\0"
+ "systemd/user-preset\0"
+ "udev/rules.d\0"
+ "modprobe.d\0";
+
+ int r = 0, k;
+ int n_found = 0;
+
+ log_parse_environment();
+ log_open();
+
+ r = parse_argv(argc, argv);
+ if (r <= 0)
+ goto finish;
+
+ if (arg_flags == 0)
+ arg_flags = SHOW_DEFAULTS;
+
+ if (arg_diff < 0)
+ arg_diff = !!(arg_flags & SHOW_OVERRIDDEN);
+ else if (arg_diff)
+ arg_flags |= SHOW_OVERRIDDEN;
+
+ if (!arg_no_pager)
+ pager_open(false);
+
+ if (optind < argc) {
+ int i;
+
+ for (i = optind; i < argc; i++) {
+ k = process_suffix_chop(prefixes, argv[i]);
+ if (k < 0)
+ r = k;
+ else
+ n_found += k;
+ }
+
+ } else {
+ const char *n;
+
+ NULSTR_FOREACH(n, suffixes) {
+ k = process_suffix(prefixes, n);
+ if (k < 0)
+ r = k;
+ else
+ n_found += k;
+ }
+ }
+
+ if (r >= 0)
+ printf("\n%i overridden configuration files found.\n", n_found);
+
+finish:
+ pager_close();
+
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/src/detect-virt/detect-virt.c b/src/detect-virt/detect-virt.c
new file mode 100644
index 0000000000..bd3ee452c1
--- /dev/null
+++ b/src/detect-virt/detect-virt.c
@@ -0,0 +1,171 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdlib.h>
+#include <stdbool.h>
+#include <errno.h>
+#include <string.h>
+#include <getopt.h>
+
+#include "util.h"
+#include "virt.h"
+#include "build.h"
+
+static bool arg_quiet = false;
+static enum {
+ ANY_VIRTUALIZATION,
+ ONLY_VM,
+ ONLY_CONTAINER
+} arg_mode = ANY_VIRTUALIZATION;
+
+static int help(void) {
+
+ printf("%s [OPTIONS...]\n\n"
+ "Detect execution in a virtualized environment.\n\n"
+ " -h --help Show this help\n"
+ " --version Show package version\n"
+ " -c --container Only detect whether we are run in a container\n"
+ " -v --vm Only detect whether we are run in a VM\n"
+ " -q --quiet Don't output anything, just set return value\n",
+ program_invocation_short_name);
+
+ return 0;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+
+ enum {
+ ARG_VERSION = 0x100
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "version", no_argument, NULL, ARG_VERSION },
+ { "container", no_argument, NULL, 'c' },
+ { "vm", optional_argument, NULL, 'v' },
+ { "quiet", no_argument, NULL, 'q' },
+ { NULL, 0, NULL, 0 }
+ };
+
+ int c;
+
+ assert(argc >= 0);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "hqcv", options, NULL)) >= 0) {
+
+ switch (c) {
+
+ case 'h':
+ help();
+ return 0;
+
+ case ARG_VERSION:
+ puts(PACKAGE_STRING);
+ puts(SYSTEMD_FEATURES);
+ return 0;
+
+ case 'q':
+ arg_quiet = true;
+ break;
+
+ case 'c':
+ arg_mode = ONLY_CONTAINER;
+ break;
+
+ case 'v':
+ arg_mode = ONLY_VM;
+ break;
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ log_error("Unknown option code %c", c);
+ return -EINVAL;
+ }
+ }
+
+ if (optind < argc) {
+ help();
+ return -EINVAL;
+ }
+
+ return 1;
+}
+
+int main(int argc, char *argv[]) {
+ const char *id = NULL;
+ int r;
+ int retval = EXIT_SUCCESS;
+
+ /* This is mostly intended to be used for scripts which want
+ * to detect whether we are being run in a virtualized
+ * environment or not */
+
+ log_parse_environment();
+ log_open();
+
+ r = parse_argv(argc, argv);
+ if (r <= 0)
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+
+ switch (arg_mode) {
+
+ case ANY_VIRTUALIZATION: {
+ Virtualization v;
+
+ v = detect_virtualization(&id);
+ if (v < 0) {
+ log_error("Failed to check for virtualization: %s", strerror(-v));
+ return EXIT_FAILURE;
+ }
+
+ retval = v != VIRTUALIZATION_NONE ? EXIT_SUCCESS : EXIT_FAILURE;
+ break;
+ }
+
+ case ONLY_CONTAINER:
+ r = detect_container(&id);
+ if (r < 0) {
+ log_error("Failed to check for container: %s", strerror(-r));
+ return EXIT_FAILURE;
+ }
+
+ retval = r > 0 ? EXIT_SUCCESS : EXIT_FAILURE;
+ break;
+
+ case ONLY_VM:
+ r = detect_vm(&id);
+ if (r < 0) {
+ log_error("Failed to check for vm: %s", strerror(-r));
+ return EXIT_FAILURE;
+ }
+
+ retval = r > 0 ? EXIT_SUCCESS : EXIT_FAILURE;
+ break;
+ }
+
+ if (!arg_quiet)
+ puts(id ? id : "none");
+
+ return retval;
+}
diff --git a/src/efi-boot-generator/efi-boot-generator.c b/src/efi-boot-generator/efi-boot-generator.c
new file mode 100644
index 0000000000..4367c536b0
--- /dev/null
+++ b/src/efi-boot-generator/efi-boot-generator.c
@@ -0,0 +1,123 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <unistd.h>
+#include <stdlib.h>
+
+#include "efivars.h"
+#include "path-util.h"
+#include "util.h"
+#include "mkdir.h"
+
+static const char *arg_dest = "/tmp";
+
+int main(int argc, char *argv[]) {
+ int r = EXIT_SUCCESS;
+ sd_id128_t id;
+ _cleanup_free_ char *name = NULL;
+ _cleanup_fclose_ FILE *f = NULL;
+
+ if (argc > 1 && argc != 4) {
+ log_error("This program takes three or no arguments.");
+ return EXIT_FAILURE;
+ }
+
+ if (argc > 1)
+ arg_dest = argv[3];
+
+ log_set_target(LOG_TARGET_SAFE);
+ log_parse_environment();
+ log_open();
+
+ umask(0022);
+
+ if (!is_efi_boot())
+ return EXIT_SUCCESS;
+
+ if (dir_is_empty("/boot") <= 0)
+ return EXIT_SUCCESS;
+
+ r = efi_get_loader_device_part_uuid(&id);
+ if (r == -ENOENT)
+ return EXIT_SUCCESS;
+ if (r < 0) {
+ log_error("Failed to read ESP partition UUID: %s", strerror(-r));
+ return EXIT_FAILURE;
+ }
+
+ name = strjoin(arg_dest, "/boot.mount", NULL);
+ if (!name) {
+ log_oom();
+ return EXIT_FAILURE;
+ }
+
+ f = fopen(name, "wxe");
+ if (!f) {
+ log_error("Failed to create mount unit file %s: %m", name);
+ return EXIT_FAILURE;
+ }
+
+ fprintf(f,
+ "# Automatially generated by systemd-efi-boot-generator\n\n"
+ "[Unit]\n"
+ "Description=EFI System Partition\n\n"
+ "[Mount]\n"
+ "Where=/boot\n"
+ "What=/dev/disk/by-partuuid/%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\n"
+ "Options=umask=0077\n",
+ SD_ID128_FORMAT_VAL(id));
+
+ free(name);
+ name = strjoin(arg_dest, "/boot.automount", NULL);
+ if (!name) {
+ log_oom();
+ return EXIT_FAILURE;
+ }
+
+ fclose(f);
+ f = fopen(name, "wxe");
+ if (!f) {
+ log_error("Failed to create automount unit file %s: %m", name);
+ return EXIT_FAILURE;
+ }
+
+ fputs("# Automatially generated by systemd-efi-boot-generator\n\n"
+ "[Unit]\n"
+ "Description=EFI System Partition Automount\n\n"
+ "[Automount]\n"
+ "Where=/boot\n", f);
+
+ free(name);
+ name = strjoin(arg_dest, "/local-fs.target.wants/boot.automount", NULL);
+ if (!name) {
+ log_oom();
+ return EXIT_FAILURE;
+ }
+
+ mkdir_parents(name, 0755);
+
+ if (symlink("../boot.automount", name) < 0) {
+ log_error("Failed to create symlink %s: %m", name);
+ return EXIT_FAILURE;
+ }
+
+ return 0;
+}
diff --git a/src/fsck/fsck.c b/src/fsck/fsck.c
new file mode 100644
index 0000000000..f298cf7b9a
--- /dev/null
+++ b/src/fsck/fsck.c
@@ -0,0 +1,412 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include <stdbool.h>
+#include <string.h>
+#include <errno.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/file.h>
+
+#include <libudev.h>
+#include <dbus/dbus.h>
+
+#include "util.h"
+#include "dbus-common.h"
+#include "special.h"
+#include "bus-errors.h"
+#include "virt.h"
+#include "fileio.h"
+
+static bool arg_skip = false;
+static bool arg_force = false;
+static bool arg_show_progress = false;
+
+static void start_target(const char *target) {
+ DBusMessage *m = NULL, *reply = NULL;
+ DBusError error;
+ const char *mode = "replace", *basic_target = "basic.target";
+ DBusConnection *bus = NULL;
+
+ assert(target);
+
+ dbus_error_init(&error);
+
+ if (bus_connect(DBUS_BUS_SYSTEM, &bus, NULL, &error) < 0) {
+ log_error("Failed to get D-Bus connection: %s", bus_error_message(&error));
+ goto finish;
+ }
+
+ log_info("Running request %s/start/%s", target, mode);
+
+ if (!(m = dbus_message_new_method_call("org.freedesktop.systemd1", "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager", "StartUnitReplace"))) {
+ log_error("Could not allocate message.");
+ goto finish;
+ }
+
+ /* Start these units only if we can replace base.target with it */
+
+ if (!dbus_message_append_args(m,
+ DBUS_TYPE_STRING, &basic_target,
+ DBUS_TYPE_STRING, &target,
+ DBUS_TYPE_STRING, &mode,
+ DBUS_TYPE_INVALID)) {
+ log_error("Could not attach target and flag information to message.");
+ goto finish;
+ }
+
+ if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
+
+ /* Don't print a warning if we aren't called during
+ * startup */
+ if (!dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_JOB))
+ log_error("Failed to start unit: %s", bus_error_message(&error));
+
+ goto finish;
+ }
+
+finish:
+ if (m)
+ dbus_message_unref(m);
+
+ if (reply)
+ dbus_message_unref(reply);
+
+ if (bus) {
+ dbus_connection_flush(bus);
+ dbus_connection_close(bus);
+ dbus_connection_unref(bus);
+ }
+
+ dbus_error_free(&error);
+}
+
+static int parse_proc_cmdline(void) {
+ char *line, *w, *state;
+ int r;
+ size_t l;
+
+ if (detect_container(NULL) > 0)
+ return 0;
+
+ r = read_one_line_file("/proc/cmdline", &line);
+ if (r < 0) {
+ log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
+ return 0;
+ }
+
+ FOREACH_WORD_QUOTED(w, l, line, state) {
+
+ if (strneq(w, "fsck.mode=auto", l))
+ arg_force = arg_skip = false;
+ else if (strneq(w, "fsck.mode=force", l))
+ arg_force = true;
+ else if (strneq(w, "fsck.mode=skip", l))
+ arg_skip = true;
+ else if (startswith(w, "fsck"))
+ log_warning("Invalid fsck parameter. Ignoring.");
+#ifdef HAVE_SYSV_COMPAT
+ else if (strneq(w, "fastboot", l)) {
+ log_error("Please pass 'fsck.mode=skip' rather than 'fastboot' on the kernel command line.");
+ arg_skip = true;
+ } else if (strneq(w, "forcefsck", l)) {
+ log_error("Please pass 'fsck.mode=force' rather than 'forcefsck' on the kernel command line.");
+ arg_force = true;
+ }
+#endif
+ }
+
+ free(line);
+ return 0;
+}
+
+static void test_files(void) {
+#ifdef HAVE_SYSV_COMPAT
+ if (access("/fastboot", F_OK) >= 0) {
+ log_error("Please pass 'fsck.mode=skip' on the kernel command line rather than creating /fastboot on the root file system.");
+ arg_skip = true;
+ }
+
+ if (access("/forcefsck", F_OK) >= 0) {
+ log_error("Please pass 'fsck.mode=force' on the kernel command line rather than creating /forcefsck on the root file system.");
+ arg_force = true;
+ }
+#endif
+
+ if (access("/run/systemd/show-status", F_OK) >= 0 || plymouth_running())
+ arg_show_progress = true;
+}
+
+static double percent(int pass, unsigned long cur, unsigned long max) {
+ /* Values stolen from e2fsck */
+
+ static const int pass_table[] = {
+ 0, 70, 90, 92, 95, 100
+ };
+
+ if (pass <= 0)
+ return 0.0;
+
+ if ((unsigned) pass >= ELEMENTSOF(pass_table) || max == 0)
+ return 100.0;
+
+ return (double) pass_table[pass-1] +
+ ((double) pass_table[pass] - (double) pass_table[pass-1]) *
+ (double) cur / (double) max;
+}
+
+static int process_progress(int fd) {
+ FILE *f, *console;
+ usec_t last = 0;
+ bool locked = false;
+ int clear = 0;
+
+ f = fdopen(fd, "r");
+ if (!f) {
+ close_nointr_nofail(fd);
+ return -errno;
+ }
+
+ console = fopen("/dev/console", "w");
+ if (!console) {
+ fclose(f);
+ return -ENOMEM;
+ }
+
+ while (!feof(f)) {
+ int pass, m;
+ unsigned long cur, max;
+ char *device;
+ double p;
+ usec_t t;
+
+ if (fscanf(f, "%i %lu %lu %ms", &pass, &cur, &max, &device) != 4)
+ break;
+
+ /* Only show one progress counter at max */
+ if (!locked) {
+ if (flock(fileno(console), LOCK_EX|LOCK_NB) < 0) {
+ free(device);
+ continue;
+ }
+
+ locked = true;
+ }
+
+ /* Only update once every 50ms */
+ t = now(CLOCK_MONOTONIC);
+ if (last + 50 * USEC_PER_MSEC > t) {
+ free(device);
+ continue;
+ }
+
+ last = t;
+
+ p = percent(pass, cur, max);
+ fprintf(console, "\r%s: fsck %3.1f%% complete...\r%n", device, p, &m);
+ fflush(console);
+
+ free(device);
+
+ if (m > clear)
+ clear = m;
+ }
+
+ if (clear > 0) {
+ unsigned j;
+
+ fputc('\r', console);
+ for (j = 0; j < (unsigned) clear; j++)
+ fputc(' ', console);
+ fputc('\r', console);
+ fflush(console);
+ }
+
+ fclose(f);
+ fclose(console);
+ return 0;
+}
+
+int main(int argc, char *argv[]) {
+ const char *cmdline[9];
+ int i = 0, r = EXIT_FAILURE, q;
+ pid_t pid;
+ siginfo_t status;
+ struct udev *udev = NULL;
+ struct udev_device *udev_device = NULL;
+ const char *device;
+ bool root_directory;
+ int progress_pipe[2] = { -1, -1 };
+ char dash_c[2+10+1];
+
+ if (argc > 2) {
+ log_error("This program expects one or no arguments.");
+ return EXIT_FAILURE;
+ }
+
+ log_set_target(LOG_TARGET_AUTO);
+ log_parse_environment();
+ log_open();
+
+ umask(0022);
+
+ parse_proc_cmdline();
+ test_files();
+
+ if (!arg_force && arg_skip)
+ return 0;
+
+ if (argc > 1) {
+ device = argv[1];
+ root_directory = false;
+ } else {
+ struct stat st;
+ struct timespec times[2];
+
+ /* Find root device */
+
+ if (stat("/", &st) < 0) {
+ log_error("Failed to stat() the root directory: %m");
+ goto finish;
+ }
+
+ /* Virtual root devices don't need an fsck */
+ if (major(st.st_dev) == 0)
+ return 0;
+
+ /* check if we are already writable */
+ times[0] = st.st_atim;
+ times[1] = st.st_mtim;
+ if (utimensat(AT_FDCWD, "/", times, 0) == 0) {
+ log_info("Root directory is writable, skipping check.");
+ return 0;
+ }
+
+ if (!(udev = udev_new())) {
+ log_oom();
+ goto finish;
+ }
+
+ if (!(udev_device = udev_device_new_from_devnum(udev, 'b', st.st_dev))) {
+ log_error("Failed to detect root device.");
+ goto finish;
+ }
+
+ if (!(device = udev_device_get_devnode(udev_device))) {
+ log_error("Failed to detect device node of root directory.");
+ goto finish;
+ }
+
+ root_directory = true;
+ }
+
+ if (arg_show_progress)
+ if (pipe(progress_pipe) < 0) {
+ log_error("pipe(): %m");
+ goto finish;
+ }
+
+ cmdline[i++] = "/sbin/fsck";
+ cmdline[i++] = "-a";
+ cmdline[i++] = "-T";
+ cmdline[i++] = "-l";
+
+ if (!root_directory)
+ cmdline[i++] = "-M";
+
+ if (arg_force)
+ cmdline[i++] = "-f";
+
+ if (progress_pipe[1] >= 0) {
+ snprintf(dash_c, sizeof(dash_c), "-C%i", progress_pipe[1]);
+ char_array_0(dash_c);
+ cmdline[i++] = dash_c;
+ }
+
+ cmdline[i++] = device;
+ cmdline[i++] = NULL;
+
+ pid = fork();
+ if (pid < 0) {
+ log_error("fork(): %m");
+ goto finish;
+ } else if (pid == 0) {
+ /* Child */
+ if (progress_pipe[0] >= 0)
+ close_nointr_nofail(progress_pipe[0]);
+ execv(cmdline[0], (char**) cmdline);
+ _exit(8); /* Operational error */
+ }
+
+ if (progress_pipe[1] >= 0) {
+ close_nointr_nofail(progress_pipe[1]);
+ progress_pipe[1] = -1;
+ }
+
+ if (progress_pipe[0] >= 0) {
+ process_progress(progress_pipe[0]);
+ progress_pipe[0] = -1;
+ }
+
+ q = wait_for_terminate(pid, &status);
+ if (q < 0) {
+ log_error("waitid(): %s", strerror(-q));
+ goto finish;
+ }
+
+ if (status.si_code != CLD_EXITED || (status.si_status & ~1)) {
+
+ if (status.si_code == CLD_KILLED || status.si_code == CLD_DUMPED)
+ log_error("fsck terminated by signal %s.", signal_to_string(status.si_status));
+ else if (status.si_code == CLD_EXITED)
+ log_error("fsck failed with error code %i.", status.si_status);
+ else
+ log_error("fsck failed due to unknown reason.");
+
+ if (status.si_code == CLD_EXITED && (status.si_status & 2) && root_directory)
+ /* System should be rebooted. */
+ start_target(SPECIAL_REBOOT_TARGET);
+ else if (status.si_code == CLD_EXITED && (status.si_status & 6))
+ /* Some other problem */
+ start_target(SPECIAL_EMERGENCY_TARGET);
+ else {
+ r = EXIT_SUCCESS;
+ log_warning("Ignoring error.");
+ }
+
+ } else
+ r = EXIT_SUCCESS;
+
+ if (status.si_code == CLD_EXITED && (status.si_status & 1))
+ touch("/run/systemd/quotacheck");
+
+finish:
+ if (udev_device)
+ udev_device_unref(udev_device);
+
+ if (udev)
+ udev_unref(udev);
+
+ close_pipe(progress_pipe);
+
+ return r;
+}
diff --git a/src/fstab-generator/fstab-generator.c b/src/fstab-generator/fstab-generator.c
new file mode 100644
index 0000000000..c17299f267
--- /dev/null
+++ b/src/fstab-generator/fstab-generator.c
@@ -0,0 +1,648 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include <mntent.h>
+#include <errno.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "log.h"
+#include "util.h"
+#include "unit-name.h"
+#include "path-util.h"
+#include "mount-setup.h"
+#include "special.h"
+#include "mkdir.h"
+#include "virt.h"
+#include "fileio.h"
+
+static const char *arg_dest = "/tmp";
+static bool arg_enabled = true;
+
+static int device_name(const char *path, char **unit) {
+ char *p;
+
+ assert(path);
+
+ if (!is_device_path(path))
+ return 0;
+
+ p = unit_name_from_path(path, ".device");
+ if (!p)
+ return log_oom();
+
+ *unit = p;
+ return 1;
+}
+
+static int mount_find_pri(struct mntent *me, int *ret) {
+ char *end, *pri;
+ unsigned long r;
+
+ assert(me);
+ assert(ret);
+
+ pri = hasmntopt(me, "pri");
+ if (!pri)
+ return 0;
+
+ pri += 4;
+
+ errno = 0;
+ r = strtoul(pri, &end, 10);
+ if (errno > 0)
+ return -errno;
+
+ if (end == pri || (*end != ',' && *end != 0))
+ return -EINVAL;
+
+ *ret = (int) r;
+ return 1;
+}
+
+static int add_swap(const char *what, struct mntent *me) {
+ _cleanup_free_ char *name = NULL, *unit = NULL, *lnk = NULL, *device = NULL;
+ _cleanup_fclose_ FILE *f = NULL;
+ bool noauto, nofail;
+ int r, pri = -1;
+
+ assert(what);
+ assert(me);
+
+ r = mount_find_pri(me, &pri);
+ if (r < 0) {
+ log_error("Failed to parse priority");
+ return pri;
+ }
+
+ noauto = !!hasmntopt(me, "noauto");
+ nofail = !!hasmntopt(me, "nofail");
+
+ name = unit_name_from_path(what, ".swap");
+ if (!name)
+ return log_oom();
+
+ unit = strjoin(arg_dest, "/", name, NULL);
+ if (!unit)
+ return log_oom();
+
+ f = fopen(unit, "wxe");
+ if (!f) {
+ if (errno == EEXIST)
+ log_error("Failed to create swap unit file %s, as it already exists. Duplicate entry in /etc/fstab?", unit);
+ else
+ log_error("Failed to create unit file %s: %m", unit);
+ return -errno;
+ }
+
+ fputs("# Automatically generated by systemd-fstab-generator\n\n"
+ "[Unit]\n"
+ "SourcePath=/etc/fstab\n"
+ "DefaultDependencies=no\n"
+ "Conflicts=" SPECIAL_UMOUNT_TARGET "\n"
+ "Before=" SPECIAL_UMOUNT_TARGET "\n", f);
+
+ if (!noauto && !nofail)
+ fputs("Before=" SPECIAL_SWAP_TARGET "\n", f);
+
+ fprintf(f,
+ "\n"
+ "[Swap]\n"
+ "What=%s\n",
+ what);
+
+ if (pri >= 0)
+ fprintf(f,
+ "Priority=%i\n",
+ pri);
+
+ fflush(f);
+ if (ferror(f)) {
+ log_error("Failed to write unit file %s: %m", unit);
+ return -errno;
+ }
+
+ if (!noauto) {
+ lnk = strjoin(arg_dest, "/" SPECIAL_SWAP_TARGET ".wants/", name, NULL);
+ if (!lnk)
+ return log_oom();
+
+ mkdir_parents_label(lnk, 0755);
+ if (symlink(unit, lnk) < 0) {
+ log_error("Failed to create symlink %s: %m", lnk);
+ return -errno;
+ }
+
+ r = device_name(what, &device);
+ if (r < 0)
+ return r;
+
+ if (r > 0) {
+ free(lnk);
+ lnk = strjoin(arg_dest, "/", device, ".wants/", name, NULL);
+ if (!lnk)
+ return log_oom();
+
+ mkdir_parents_label(lnk, 0755);
+ if (symlink(unit, lnk) < 0) {
+ log_error("Failed to create symlink %s: %m", lnk);
+ return -errno;
+ }
+ }
+ }
+
+ return 0;
+}
+
+static bool mount_is_bind(struct mntent *me) {
+ assert(me);
+
+ return
+ hasmntopt(me, "bind") ||
+ streq(me->mnt_type, "bind") ||
+ hasmntopt(me, "rbind") ||
+ streq(me->mnt_type, "rbind");
+}
+
+static bool mount_is_network(struct mntent *me) {
+ assert(me);
+
+ return
+ hasmntopt(me, "_netdev") ||
+ fstype_is_network(me->mnt_type);
+}
+
+static bool mount_in_initrd(struct mntent *me) {
+ assert(me);
+
+ return
+ hasmntopt(me, "x-initrd.mount") ||
+ streq(me->mnt_dir, "/usr");
+}
+
+static int add_mount(
+ const char *what,
+ const char *where,
+ const char *type,
+ const char *opts,
+ int passno,
+ bool noauto,
+ bool nofail,
+ bool automount,
+ bool isbind,
+ const char *pre,
+ const char *pre2,
+ const char *online,
+ const char *post,
+ const char *source) {
+ _cleanup_free_ char
+ *name = NULL, *unit = NULL, *lnk = NULL, *device = NULL,
+ *automount_name = NULL, *automount_unit = NULL;
+ _cleanup_fclose_ FILE *f = NULL;
+ int r;
+
+ assert(what);
+ assert(where);
+ assert(type);
+ assert(opts);
+ assert(source);
+
+ if (streq(type, "autofs"))
+ return 0;
+
+ if (!is_path(where)) {
+ log_warning("Mount point %s is not a valid path, ignoring.", where);
+ return 0;
+ }
+
+ if (mount_point_is_api(where) ||
+ mount_point_ignore(where))
+ return 0;
+
+ name = unit_name_from_path(where, ".mount");
+ if (!name)
+ return log_oom();
+
+ unit = strjoin(arg_dest, "/", name, NULL);
+ if (!unit)
+ return log_oom();
+
+ f = fopen(unit, "wxe");
+ if (!f) {
+ if (errno == EEXIST)
+ log_error("Failed to create mount unit file %s, as it already exists. Duplicate entry in /etc/fstab?", unit);
+ else
+ log_error("Failed to create unit file %s: %m", unit);
+ return -errno;
+ }
+
+ fprintf(f,
+ "# Automatically generated by systemd-fstab-generator\n\n"
+ "[Unit]\n"
+ "SourcePath=%s\n"
+ "DefaultDependencies=no\n",
+ source);
+
+ if (!path_equal(where, "/")) {
+ if (pre)
+ fprintf(f,
+ "After=%s\n",
+ pre);
+
+ if (pre2)
+ fprintf(f,
+ "After=%s\n",
+ pre2);
+
+ if (online)
+ fprintf(f,
+ "After=%s\n"
+ "Wants=%s\n",
+ online,
+ online);
+
+ fprintf(f,
+ "Conflicts=" SPECIAL_UMOUNT_TARGET "\n"
+ "Before=" SPECIAL_UMOUNT_TARGET "\n");
+ }
+
+ if (post && !noauto && !nofail && !automount)
+ fprintf(f,
+ "Before=%s\n",
+ post);
+
+ fprintf(f,
+ "\n"
+ "[Mount]\n"
+ "What=%s\n"
+ "Where=%s\n"
+ "Type=%s\n"
+ "FsckPassNo=%i\n",
+ what,
+ where,
+ type,
+ passno);
+
+ if (!isempty(opts) &&
+ !streq(opts, "defaults"))
+ fprintf(f,
+ "Options=%s\n",
+ opts);
+
+ fflush(f);
+ if (ferror(f)) {
+ log_error("Failed to write unit file %s: %m", unit);
+ return -errno;
+ }
+
+ if (!noauto) {
+ if (post) {
+ lnk = strjoin(arg_dest, "/", post, nofail || automount ? ".wants/" : ".requires/", name, NULL);
+ if (!lnk)
+ return log_oom();
+
+ mkdir_parents_label(lnk, 0755);
+ if (symlink(unit, lnk) < 0) {
+ log_error("Failed to create symlink %s: %m", lnk);
+ return -errno;
+ }
+ }
+
+ if (!isbind &&
+ !path_equal(where, "/")) {
+
+ r = device_name(what, &device);
+ if (r < 0)
+ return r;
+
+ if (r > 0) {
+ free(lnk);
+ lnk = strjoin(arg_dest, "/", device, ".wants/", name, NULL);
+ if (!lnk)
+ return log_oom();
+
+ mkdir_parents_label(lnk, 0755);
+ if (symlink(unit, lnk) < 0) {
+ log_error("Failed to create symlink %s: %m", lnk);
+ return -errno;
+ }
+ }
+ }
+ }
+
+ if (automount && !path_equal(where, "/")) {
+ automount_name = unit_name_from_path(where, ".automount");
+ if (!name)
+ return log_oom();
+
+ automount_unit = strjoin(arg_dest, "/", automount_name, NULL);
+ if (!automount_unit)
+ return log_oom();
+
+ fclose(f);
+ f = fopen(automount_unit, "wxe");
+ if (!f) {
+ log_error("Failed to create unit file %s: %m", automount_unit);
+ return -errno;
+ }
+
+ fprintf(f,
+ "# Automatically generated by systemd-fstab-generator\n\n"
+ "[Unit]\n"
+ "SourcePath=%s\n"
+ "DefaultDependencies=no\n"
+ "Conflicts=" SPECIAL_UMOUNT_TARGET "\n"
+ "Before=" SPECIAL_UMOUNT_TARGET "\n",
+ source);
+
+ if (post)
+ fprintf(f,
+ "Before= %s\n",
+ post);
+
+ fprintf(f,
+ "[Automount]\n"
+ "Where=%s\n",
+ where);
+
+ fflush(f);
+ if (ferror(f)) {
+ log_error("Failed to write unit file %s: %m", automount_unit);
+ return -errno;
+ }
+
+ free(lnk);
+ lnk = strjoin(arg_dest, "/", post, nofail ? ".wants/" : ".requires/", automount_name, NULL);
+ if (!lnk)
+ return log_oom();
+
+ mkdir_parents_label(lnk, 0755);
+ if (symlink(automount_unit, lnk) < 0) {
+ log_error("Failed to create symlink %s: %m", lnk);
+ return -errno;
+ }
+ }
+
+ return 0;
+}
+
+static int parse_fstab(const char *prefix, bool initrd) {
+ _cleanup_free_ char *fstab_path = NULL;
+ FILE *f;
+ int r = 0;
+ struct mntent *me;
+
+ fstab_path = strjoin(strempty(prefix), "/etc/fstab", NULL);
+ if (!fstab_path)
+ return log_oom();
+
+ f = setmntent(fstab_path, "r");
+ if (!f) {
+ if (errno == ENOENT)
+ return 0;
+
+ log_error("Failed to open %s/etc/fstab: %m", strempty(prefix));
+ return -errno;
+ }
+
+ while ((me = getmntent(f))) {
+ _cleanup_free_ char *where = NULL, *what = NULL;
+ int k;
+
+ if (initrd && !mount_in_initrd(me))
+ continue;
+
+ what = fstab_node_to_udev_node(me->mnt_fsname);
+ where = strjoin(strempty(prefix), me->mnt_dir, NULL);
+ if (!what || !where) {
+ r = log_oom();
+ goto finish;
+ }
+
+ if (is_path(where))
+ path_kill_slashes(where);
+
+ log_debug("Found entry what=%s where=%s type=%s", what, where, me->mnt_type);
+
+ if (streq(me->mnt_type, "swap"))
+ k = add_swap(what, me);
+ else {
+ bool noauto, nofail, automount, isbind;
+ const char *pre, *pre2, *post, *online;
+
+ noauto = !!hasmntopt(me, "noauto");
+ nofail = !!hasmntopt(me, "nofail");
+ automount =
+ hasmntopt(me, "comment=systemd.automount") ||
+ hasmntopt(me, "x-systemd.automount");
+ isbind = mount_is_bind(me);
+
+ if (initrd) {
+ pre = pre2 = online = NULL;
+ post = SPECIAL_INITRD_FS_TARGET;
+ } else if (mount_in_initrd(me)) {
+ pre = pre2 = online = NULL;
+ post = SPECIAL_INITRD_ROOT_FS_TARGET;
+ } else if (mount_is_network(me)) {
+ pre = SPECIAL_REMOTE_FS_PRE_TARGET;
+ pre2 = SPECIAL_NETWORK_TARGET;
+ online = SPECIAL_NETWORK_ONLINE_TARGET;
+ post = SPECIAL_REMOTE_FS_TARGET;
+ } else {
+ pre = SPECIAL_LOCAL_FS_PRE_TARGET;
+ pre2 = online = NULL;
+ post = SPECIAL_LOCAL_FS_TARGET;
+ }
+
+ k = add_mount(what, where, me->mnt_type, me->mnt_opts,
+ me->mnt_passno, noauto, nofail, automount,
+ isbind, pre, pre2, online, post, fstab_path);
+ }
+
+ if (k < 0)
+ r = k;
+ }
+
+finish:
+ endmntent(f);
+ return r;
+}
+
+static int parse_new_root_from_proc_cmdline(void) {
+ _cleanup_free_ char *what = NULL, *type = NULL, *opts = NULL, *line = NULL;
+ char *w, *state;
+ int r;
+ size_t l;
+
+ r = read_one_line_file("/proc/cmdline", &line);
+ if (r < 0) {
+ log_error("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
+ return 0;
+ }
+
+ opts = strdup("ro");
+ type = strdup("auto");
+ if (!opts || !type)
+ return log_oom();
+
+ /* root= and roofstype= may occur more than once, the last instance should take precedence.
+ * In the case of multiple rootflags= the arguments should be concatenated */
+ FOREACH_WORD_QUOTED(w, l, line, state) {
+ _cleanup_free_ char *word;
+
+ word = strndup(w, l);
+ if (!word)
+ return log_oom();
+
+ else if (startswith(word, "root=")) {
+ free(what);
+ what = fstab_node_to_udev_node(word+5);
+ if (!what)
+ return log_oom();
+
+ } else if (startswith(word, "rootfstype=")) {
+ free(type);
+ type = strdup(word + 11);
+ if (!type)
+ return log_oom();
+
+ } else if (startswith(word, "rootflags=")) {
+ char *o;
+
+ o = strjoin(opts, ",", word + 10, NULL);
+ if (!o)
+ return log_oom();
+
+ free(opts);
+ opts = o;
+
+ } else if (streq(word, "ro") || streq(word, "rw")) {
+ char *o;
+
+ o = strjoin(opts, ",", word, NULL);
+ if (!o)
+ return log_oom();
+
+ free(opts);
+ opts = o;
+ }
+ }
+
+ if (!what) {
+ log_debug("Could not find a root= entry on the kernel commandline.");
+ return 0;
+ }
+
+ if (what[0] != '/') {
+ log_debug("Skipping entry what=%s where=/sysroot type=%s", what, type);
+ return 0;
+ }
+
+ log_debug("Found entry what=%s where=/sysroot type=%s", what, type);
+ r = add_mount(what, "/sysroot", type, opts, 0, false, false, false,
+ false, NULL, NULL, NULL, SPECIAL_INITRD_ROOT_FS_TARGET, "/proc/cmdline");
+
+ return (r < 0) ? r : 0;
+}
+
+static int parse_proc_cmdline(void) {
+ _cleanup_free_ char *line = NULL;
+ char *w, *state;
+ int r;
+ size_t l;
+
+ if (detect_container(NULL) > 0)
+ return 0;
+
+ r = read_one_line_file("/proc/cmdline", &line);
+ if (r < 0) {
+ log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
+ return 0;
+ }
+
+ FOREACH_WORD_QUOTED(w, l, line, state) {
+ _cleanup_free_ char *word = NULL;
+
+ word = strndup(w, l);
+ if (!word)
+ return log_oom();
+
+ if (startswith(word, "fstab=")) {
+ r = parse_boolean(word + 6);
+ if (r < 0)
+ log_warning("Failed to parse fstab switch %s. Ignoring.", word + 6);
+ else
+ arg_enabled = r;
+
+ } else if (startswith(word, "rd.fstab=")) {
+
+ if (in_initrd()) {
+ r = parse_boolean(word + 6);
+ if (r < 0)
+ log_warning("Failed to parse fstab switch %s. Ignoring.", word + 6);
+ else
+ arg_enabled = r;
+ }
+
+ } else if (startswith(word, "fstab.") ||
+ (in_initrd() && startswith(word, "rd.fstab."))) {
+
+ log_warning("Unknown kernel switch %s. Ignoring.", word);
+ }
+ }
+
+ return 0;
+}
+
+int main(int argc, char *argv[]) {
+ int r = 0, k, l = 0;
+
+ if (argc > 1 && argc != 4) {
+ log_error("This program takes three or no arguments.");
+ return EXIT_FAILURE;
+ }
+
+ if (argc > 1)
+ arg_dest = argv[1];
+
+ log_set_target(LOG_TARGET_SAFE);
+ log_parse_environment();
+ log_open();
+
+ umask(0022);
+
+ if (parse_proc_cmdline() < 0)
+ return EXIT_FAILURE;
+
+ if (in_initrd())
+ r = parse_new_root_from_proc_cmdline();
+
+ if (!arg_enabled)
+ return (r < 0) ? EXIT_FAILURE : EXIT_SUCCESS;
+
+ k = parse_fstab(NULL, false);
+
+ if (in_initrd())
+ l = parse_fstab("/sysroot", true);
+
+ return (r < 0) || (k < 0) || (l < 0) ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/src/getty-generator/getty-generator.c b/src/getty-generator/getty-generator.c
new file mode 100644
index 0000000000..4b7a60a4ec
--- /dev/null
+++ b/src/getty-generator/getty-generator.c
@@ -0,0 +1,181 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <string.h>
+#include <errno.h>
+#include <unistd.h>
+
+#include "log.h"
+#include "util.h"
+#include "mkdir.h"
+#include "unit-name.h"
+#include "virt.h"
+#include "fileio.h"
+
+static const char *arg_dest = "/tmp";
+
+static int add_symlink(const char *fservice, const char *tservice) {
+ char *from = NULL, *to = NULL;
+ int r;
+
+ assert(fservice);
+ assert(tservice);
+
+ from = strappend(SYSTEM_DATA_UNIT_PATH "/", fservice);
+ to = strjoin(arg_dest,"/getty.target.wants/", tservice, NULL);
+
+ if (!from || !to) {
+ r = log_oom();
+ goto finish;
+ }
+
+ mkdir_parents_label(to, 0755);
+
+ r = symlink(from, to);
+ if (r < 0) {
+ if (errno == EEXIST)
+ /* In case console=hvc0 is passed this will very likely result in EEXIST */
+ r = 0;
+ else {
+ log_error("Failed to create symlink %s: %m", to);
+ r = -errno;
+ }
+ }
+
+finish:
+
+ free(from);
+ free(to);
+
+ return r;
+}
+
+static int add_serial_getty(const char *tty) {
+ char *n;
+ int r;
+
+ assert(tty);
+
+ log_debug("Automatically adding serial getty for /dev/%s.", tty);
+
+ n = unit_name_replace_instance("serial-getty@.service", tty);
+ if (!n)
+ return log_oom();
+
+ r = add_symlink("serial-getty@.service", n);
+ free(n);
+
+ return r;
+}
+
+int main(int argc, char *argv[]) {
+
+ static const char virtualization_consoles[] =
+ "hvc0\0"
+ "xvc0\0"
+ "hvsi0\0";
+
+ int r = EXIT_SUCCESS;
+ char *active;
+ const char *j;
+
+ if (argc > 1 && argc != 4) {
+ log_error("This program takes three or no arguments.");
+ return EXIT_FAILURE;
+ }
+
+ if (argc > 1)
+ arg_dest = argv[1];
+
+ log_set_target(LOG_TARGET_SAFE);
+ log_parse_environment();
+ log_open();
+
+ umask(0022);
+
+ if (detect_container(NULL) > 0) {
+ log_debug("Automatically adding console shell.");
+
+ if (add_symlink("console-getty.service", "console-getty.service") < 0)
+ r = EXIT_FAILURE;
+
+ /* Don't add any further magic if we are in a container */
+ goto finish;
+ }
+
+ if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
+ const char *tty;
+
+ tty = strrchr(active, ' ');
+ if (tty)
+ tty ++;
+ else
+ tty = active;
+
+ /* Automatically add in a serial getty on the kernel
+ * console */
+ if (isempty(tty) || tty_is_vc(tty))
+ free(active);
+ else {
+ int k;
+
+ /* We assume that gettys on virtual terminals are
+ * started via manual configuration and do this magic
+ * only for non-VC terminals. */
+
+ k = add_serial_getty(tty);
+ free(active);
+
+ if (k < 0) {
+ r = EXIT_FAILURE;
+ goto finish;
+ }
+ }
+ }
+
+ /* Automatically add in a serial getty on the first
+ * virtualizer console */
+ NULSTR_FOREACH(j, virtualization_consoles) {
+ char *p;
+ int k;
+
+ if (asprintf(&p, "/sys/class/tty/%s", j) < 0) {
+ log_oom();
+ r = EXIT_FAILURE;
+ goto finish;
+ }
+
+ k = access(p, F_OK);
+ free(p);
+
+ if (k < 0)
+ continue;
+
+ k = add_serial_getty(j);
+ if (k < 0) {
+ r = EXIT_FAILURE;
+ goto finish;
+ }
+ }
+
+finish:
+ return r;
+}
diff --git a/src/gudev/gjs-example.js b/src/gudev/gjs-example.js
new file mode 100755
index 0000000000..5586fd6a61
--- /dev/null
+++ b/src/gudev/gjs-example.js
@@ -0,0 +1,75 @@
+#!/usr/bin/env gjs-console
+
+// This currently depends on the following patches to gjs
+//
+// http://bugzilla.gnome.org/show_bug.cgi?id=584558
+// http://bugzilla.gnome.org/show_bug.cgi?id=584560
+// http://bugzilla.gnome.org/show_bug.cgi?id=584568
+
+const GUdev = imports.gi.GUdev;
+const Mainloop = imports.mainloop;
+
+function print_device (device) {
+ print (" subsystem: " + device.get_subsystem ());
+ print (" devtype: " + device.get_devtype ());
+ print (" name: " + device.get_name ());
+ print (" number: " + device.get_number ());
+ print (" sysfs_path: " + device.get_sysfs_path ());
+ print (" driver: " + device.get_driver ());
+ print (" action: " + device.get_action ());
+ print (" seqnum: " + device.get_seqnum ());
+ print (" device type: " + device.get_device_type ());
+ print (" device number: " + device.get_device_number ());
+ print (" device file: " + device.get_device_file ());
+ print (" device file symlinks: " + device.get_device_file_symlinks ());
+ print (" foo: " + device.get_sysfs_attr_as_strv ("stat"));
+ var keys = device.get_property_keys ();
+ for (var n = 0; n < keys.length; n++) {
+ print (" " + keys[n] + "=" + device.get_property (keys[n]));
+ }
+}
+
+function on_uevent (client, action, device) {
+ print ("action " + action + " on device " + device.get_sysfs_path());
+ print_device (device);
+ print ("");
+}
+
+var client = new GUdev.Client ({subsystems: ["block", "usb/usb_interface"]});
+client.connect ("uevent", on_uevent);
+
+var block_devices = client.query_by_subsystem ("block");
+for (var n = 0; n < block_devices.length; n++) {
+ print ("block device: " + block_devices[n].get_device_file ());
+}
+
+var d;
+
+d = client.query_by_device_number (GUdev.DeviceType.BLOCK, 0x0810);
+if (d == null) {
+ print ("query_by_device_number 0x810 -> null");
+} else {
+ print ("query_by_device_number 0x810 -> " + d.get_device_file ());
+ var dd = d.get_parent_with_subsystem ("usb", null);
+ print_device (dd);
+ print ("--------------------------------------------------------------------------");
+ while (d != null) {
+ print_device (d);
+ print ("");
+ d = d.get_parent ();
+ }
+}
+
+d = client.query_by_sysfs_path ("/sys/block/sda/sda1");
+print ("query_by_sysfs_path (\"/sys/block/sda1\") -> " + d.get_device_file ());
+
+d = client.query_by_subsystem_and_name ("block", "sda2");
+print ("query_by_subsystem_and_name (\"block\", \"sda2\") -> " + d.get_device_file ());
+
+d = client.query_by_device_file ("/dev/sda");
+print ("query_by_device_file (\"/dev/sda\") -> " + d.get_device_file ());
+
+d = client.query_by_device_file ("/dev/block/8:0");
+print ("query_by_device_file (\"/dev/block/8:0\") -> " + d.get_device_file ());
+
+Mainloop.run('udev-example');
diff --git a/src/gudev/gudev-1.0.pc.in b/src/gudev/gudev-1.0.pc.in
new file mode 100644
index 0000000000..058262d767
--- /dev/null
+++ b/src/gudev/gudev-1.0.pc.in
@@ -0,0 +1,11 @@
+prefix=@prefix@
+exec_prefix=@exec_prefix@
+libdir=@libdir@
+includedir=@includedir@
+
+Name: gudev-1.0
+Description: GObject bindings for libudev
+Version: @VERSION@
+Requires: glib-2.0, gobject-2.0
+Libs: -L${libdir} -lgudev-1.0
+Cflags: -I${includedir}/gudev-1.0
diff --git a/src/gudev/gudev.h b/src/gudev/gudev.h
new file mode 100644
index 0000000000..1dc42b11b7
--- /dev/null
+++ b/src/gudev/gudev.h
@@ -0,0 +1,32 @@
+/* -*- Mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*-
+ *
+ * Copyright (C) 2008 David Zeuthen <davidz@redhat.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef __G_UDEV_H__
+#define __G_UDEV_H__
+
+#define _GUDEV_INSIDE_GUDEV_H
+#include <gudev/gudevenums.h>
+#include <gudev/gudevenumtypes.h>
+#include <gudev/gudevtypes.h>
+#include <gudev/gudevclient.h>
+#include <gudev/gudevdevice.h>
+#include <gudev/gudevenumerator.h>
+#undef _GUDEV_INSIDE_GUDEV_H
+
+#endif /* __G_UDEV_H__ */
diff --git a/src/gudev/gudevclient.c b/src/gudev/gudevclient.c
new file mode 100644
index 0000000000..a151b50ac6
--- /dev/null
+++ b/src/gudev/gudevclient.c
@@ -0,0 +1,525 @@
+/* -*- Mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*-
+ *
+ * Copyright (C) 2008-2010 David Zeuthen <davidz@redhat.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifdef HAVE_CONFIG_H
+# include "config.h"
+#endif
+
+#include <stdlib.h>
+#include <string.h>
+
+#include "gudevclient.h"
+#include "gudevdevice.h"
+#include "gudevmarshal.h"
+#include "gudevprivate.h"
+
+/**
+ * SECTION:gudevclient
+ * @short_description: Query devices and listen to uevents
+ *
+ * #GUdevClient is used to query information about devices on a Linux
+ * system from the Linux kernel and the udev device
+ * manager.
+ *
+ * Device information is retrieved from the kernel (through the
+ * <literal>sysfs</literal> filesystem) and the udev daemon (through a
+ * <literal>tmpfs</literal> filesystem) and presented through
+ * #GUdevDevice objects. This means that no blocking IO ever happens
+ * (in both cases, we are essentially just reading data from kernel
+ * memory) and as such there are no asynchronous versions of the
+ * provided methods.
+ *
+ * To get #GUdevDevice objects, use
+ * g_udev_client_query_by_subsystem(),
+ * g_udev_client_query_by_device_number(),
+ * g_udev_client_query_by_device_file(),
+ * g_udev_client_query_by_sysfs_path(),
+ * g_udev_client_query_by_subsystem_and_name()
+ * or the #GUdevEnumerator type.
+ *
+ * To listen to uevents, connect to the #GUdevClient::uevent signal.
+ */
+
+struct _GUdevClientPrivate
+{
+ GSource *watch_source;
+ struct udev *udev;
+ struct udev_monitor *monitor;
+
+ gchar **subsystems;
+};
+
+enum
+{
+ PROP_0,
+ PROP_SUBSYSTEMS,
+};
+
+enum
+{
+ UEVENT_SIGNAL,
+ LAST_SIGNAL,
+};
+
+static guint signals[LAST_SIGNAL] = { 0 };
+
+G_DEFINE_TYPE (GUdevClient, g_udev_client, G_TYPE_OBJECT)
+
+/* ---------------------------------------------------------------------------------------------------- */
+
+static gboolean
+monitor_event (GIOChannel *source,
+ GIOCondition condition,
+ gpointer data)
+{
+ GUdevClient *client = (GUdevClient *) data;
+ GUdevDevice *device;
+ struct udev_device *udevice;
+
+ if (client->priv->monitor == NULL)
+ goto out;
+ udevice = udev_monitor_receive_device (client->priv->monitor);
+ if (udevice == NULL)
+ goto out;
+
+ device = _g_udev_device_new (udevice);
+ udev_device_unref (udevice);
+ g_signal_emit (client,
+ signals[UEVENT_SIGNAL],
+ 0,
+ g_udev_device_get_action (device),
+ device);
+ g_object_unref (device);
+
+ out:
+ return TRUE;
+}
+
+static void
+g_udev_client_finalize (GObject *object)
+{
+ GUdevClient *client = G_UDEV_CLIENT (object);
+
+ if (client->priv->watch_source != NULL)
+ {
+ g_source_destroy (client->priv->watch_source);
+ client->priv->watch_source = NULL;
+ }
+
+ if (client->priv->monitor != NULL)
+ {
+ udev_monitor_unref (client->priv->monitor);
+ client->priv->monitor = NULL;
+ }
+
+ if (client->priv->udev != NULL)
+ {
+ udev_unref (client->priv->udev);
+ client->priv->udev = NULL;
+ }
+
+ g_strfreev (client->priv->subsystems);
+
+ if (G_OBJECT_CLASS (g_udev_client_parent_class)->finalize != NULL)
+ G_OBJECT_CLASS (g_udev_client_parent_class)->finalize (object);
+}
+
+static void
+g_udev_client_set_property (GObject *object,
+ guint prop_id,
+ const GValue *value,
+ GParamSpec *pspec)
+{
+ GUdevClient *client = G_UDEV_CLIENT (object);
+
+ switch (prop_id)
+ {
+ case PROP_SUBSYSTEMS:
+ if (client->priv->subsystems != NULL)
+ g_strfreev (client->priv->subsystems);
+ client->priv->subsystems = g_strdupv (g_value_get_boxed (value));
+ break;
+
+ default:
+ G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+ break;
+ }
+}
+
+static void
+g_udev_client_get_property (GObject *object,
+ guint prop_id,
+ GValue *value,
+ GParamSpec *pspec)
+{
+ GUdevClient *client = G_UDEV_CLIENT (object);
+
+ switch (prop_id)
+ {
+ case PROP_SUBSYSTEMS:
+ g_value_set_boxed (value, client->priv->subsystems);
+ break;
+
+ default:
+ G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+ break;
+ }
+}
+
+static void
+g_udev_client_constructed (GObject *object)
+{
+ GUdevClient *client = G_UDEV_CLIENT (object);
+ GIOChannel *channel;
+ guint n;
+
+ client->priv->udev = udev_new ();
+
+ /* connect to event source */
+ client->priv->monitor = udev_monitor_new_from_netlink (client->priv->udev, "udev");
+
+ //g_debug ("ss = %p", client->priv->subsystems);
+
+ if (client->priv->subsystems != NULL)
+ {
+ /* install subsystem filters to only wake up for certain events */
+ for (n = 0; client->priv->subsystems[n] != NULL; n++)
+ {
+ gchar *subsystem;
+ gchar *devtype;
+ gchar *s;
+
+ subsystem = g_strdup (client->priv->subsystems[n]);
+ devtype = NULL;
+
+ //g_debug ("s = '%s'", subsystem);
+
+ s = strstr (subsystem, "/");
+ if (s != NULL)
+ {
+ devtype = s + 1;
+ *s = '\0';
+ }
+
+ if (client->priv->monitor != NULL)
+ udev_monitor_filter_add_match_subsystem_devtype (client->priv->monitor, subsystem, devtype);
+
+ g_free (subsystem);
+ }
+
+ /* listen to events, and buffer them */
+ if (client->priv->monitor != NULL)
+ {
+ udev_monitor_enable_receiving (client->priv->monitor);
+ channel = g_io_channel_unix_new (udev_monitor_get_fd (client->priv->monitor));
+ client->priv->watch_source = g_io_create_watch (channel, G_IO_IN);
+ g_io_channel_unref (channel);
+ g_source_set_callback (client->priv->watch_source, (GSourceFunc) monitor_event, client, NULL);
+ g_source_attach (client->priv->watch_source, g_main_context_get_thread_default ());
+ g_source_unref (client->priv->watch_source);
+ }
+ else
+ {
+ client->priv->watch_source = NULL;
+ }
+ }
+
+ if (G_OBJECT_CLASS (g_udev_client_parent_class)->constructed != NULL)
+ G_OBJECT_CLASS (g_udev_client_parent_class)->constructed (object);
+}
+
+
+static void
+g_udev_client_class_init (GUdevClientClass *klass)
+{
+ GObjectClass *gobject_class = (GObjectClass *) klass;
+
+ gobject_class->constructed = g_udev_client_constructed;
+ gobject_class->set_property = g_udev_client_set_property;
+ gobject_class->get_property = g_udev_client_get_property;
+ gobject_class->finalize = g_udev_client_finalize;
+
+ /**
+ * GUdevClient:subsystems:
+ *
+ * The subsystems to listen for uevents on.
+ *
+ * To listen for only a specific DEVTYPE for a given SUBSYSTEM, use
+ * "subsystem/devtype". For example, to only listen for uevents
+ * where SUBSYSTEM is usb and DEVTYPE is usb_interface, use
+ * "usb/usb_interface".
+ *
+ * If this property is %NULL, then no events will be reported. If
+ * it's the empty array, events from all subsystems will be
+ * reported.
+ */
+ g_object_class_install_property (gobject_class,
+ PROP_SUBSYSTEMS,
+ g_param_spec_boxed ("subsystems",
+ "The subsystems to listen for changes on",
+ "The subsystems to listen for changes on",
+ G_TYPE_STRV,
+ G_PARAM_CONSTRUCT_ONLY |
+ G_PARAM_READWRITE));
+
+ /**
+ * GUdevClient::uevent:
+ * @client: The #GUdevClient receiving the event.
+ * @action: The action for the uevent e.g. "add", "remove", "change", "move", etc.
+ * @device: Details about the #GUdevDevice the event is for.
+ *
+ * Emitted when @client receives an uevent.
+ *
+ * This signal is emitted in the
+ * <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
+ * of the thread that @client was created in.
+ */
+ signals[UEVENT_SIGNAL] = g_signal_new ("uevent",
+ G_TYPE_FROM_CLASS (klass),
+ G_SIGNAL_RUN_LAST,
+ G_STRUCT_OFFSET (GUdevClientClass, uevent),
+ NULL,
+ NULL,
+ g_udev_marshal_VOID__STRING_OBJECT,
+ G_TYPE_NONE,
+ 2,
+ G_TYPE_STRING,
+ G_UDEV_TYPE_DEVICE);
+
+ g_type_class_add_private (klass, sizeof (GUdevClientPrivate));
+}
+
+static void
+g_udev_client_init (GUdevClient *client)
+{
+ client->priv = G_TYPE_INSTANCE_GET_PRIVATE (client,
+ G_UDEV_TYPE_CLIENT,
+ GUdevClientPrivate);
+}
+
+/**
+ * g_udev_client_new:
+ * @subsystems: (array zero-terminated=1) (element-type utf8) (transfer none) (allow-none): A %NULL terminated string array of subsystems to listen for uevents on, %NULL to not listen on uevents at all, or an empty array to listen to uevents on all subsystems. See the documentation for the #GUdevClient:subsystems property for details on this parameter.
+ *
+ * Constructs a #GUdevClient object that can be used to query
+ * information about devices. Connect to the #GUdevClient::uevent
+ * signal to listen for uevents. Note that signals are emitted in the
+ * <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
+ * of the thread that you call this constructor from.
+ *
+ * Returns: A new #GUdevClient object. Free with g_object_unref().
+ */
+GUdevClient *
+g_udev_client_new (const gchar * const *subsystems)
+{
+ return G_UDEV_CLIENT (g_object_new (G_UDEV_TYPE_CLIENT, "subsystems", subsystems, NULL));
+}
+
+/**
+ * g_udev_client_query_by_subsystem:
+ * @client: A #GUdevClient.
+ * @subsystem: (allow-none): The subsystem to get devices for or %NULL to get all devices.
+ *
+ * Gets all devices belonging to @subsystem.
+ *
+ * Returns: (element-type GUdevDevice) (transfer full): A list of #GUdevDevice objects. The caller should free the result by using g_object_unref() on each element in the list and then g_list_free() on the list.
+ */
+GList *
+g_udev_client_query_by_subsystem (GUdevClient *client,
+ const gchar *subsystem)
+{
+ struct udev_enumerate *enumerate;
+ struct udev_list_entry *l, *devices;
+ GList *ret;
+
+ g_return_val_if_fail (G_UDEV_IS_CLIENT (client), NULL);
+
+ ret = NULL;
+
+ /* prepare a device scan */
+ enumerate = udev_enumerate_new (client->priv->udev);
+
+ /* filter for subsystem */
+ if (subsystem != NULL)
+ udev_enumerate_add_match_subsystem (enumerate, subsystem);
+ /* retrieve the list */
+ udev_enumerate_scan_devices (enumerate);
+
+ /* add devices to the list */
+ devices = udev_enumerate_get_list_entry (enumerate);
+ for (l = devices; l != NULL; l = udev_list_entry_get_next (l))
+ {
+ struct udev_device *udevice;
+ GUdevDevice *device;
+
+ udevice = udev_device_new_from_syspath (udev_enumerate_get_udev (enumerate),
+ udev_list_entry_get_name (l));
+ if (udevice == NULL)
+ continue;
+ device = _g_udev_device_new (udevice);
+ udev_device_unref (udevice);
+ ret = g_list_prepend (ret, device);
+ }
+ udev_enumerate_unref (enumerate);
+
+ ret = g_list_reverse (ret);
+
+ return ret;
+}
+
+/**
+ * g_udev_client_query_by_device_number:
+ * @client: A #GUdevClient.
+ * @type: A value from the #GUdevDeviceType enumeration.
+ * @number: A device number.
+ *
+ * Looks up a device for a type and device number.
+ *
+ * Returns: (transfer full): A #GUdevDevice object or %NULL if the device was not found. Free with g_object_unref().
+ */
+GUdevDevice *
+g_udev_client_query_by_device_number (GUdevClient *client,
+ GUdevDeviceType type,
+ GUdevDeviceNumber number)
+{
+ struct udev_device *udevice;
+ GUdevDevice *device;
+
+ g_return_val_if_fail (G_UDEV_IS_CLIENT (client), NULL);
+
+ device = NULL;
+ udevice = udev_device_new_from_devnum (client->priv->udev, type, number);
+
+ if (udevice == NULL)
+ goto out;
+
+ device = _g_udev_device_new (udevice);
+ udev_device_unref (udevice);
+
+ out:
+ return device;
+}
+
+/**
+ * g_udev_client_query_by_device_file:
+ * @client: A #GUdevClient.
+ * @device_file: A device file.
+ *
+ * Looks up a device for a device file.
+ *
+ * Returns: (transfer full): A #GUdevDevice object or %NULL if the device was not found. Free with g_object_unref().
+ */
+GUdevDevice *
+g_udev_client_query_by_device_file (GUdevClient *client,
+ const gchar *device_file)
+{
+ struct stat stat_buf;
+ GUdevDevice *device;
+
+ g_return_val_if_fail (G_UDEV_IS_CLIENT (client), NULL);
+ g_return_val_if_fail (device_file != NULL, NULL);
+
+ device = NULL;
+
+ if (stat (device_file, &stat_buf) != 0)
+ goto out;
+
+ if (stat_buf.st_rdev == 0)
+ goto out;
+
+ if (S_ISBLK (stat_buf.st_mode))
+ device = g_udev_client_query_by_device_number (client, G_UDEV_DEVICE_TYPE_BLOCK, stat_buf.st_rdev);
+ else if (S_ISCHR (stat_buf.st_mode))
+ device = g_udev_client_query_by_device_number (client, G_UDEV_DEVICE_TYPE_CHAR, stat_buf.st_rdev);
+
+ out:
+ return device;
+}
+
+/**
+ * g_udev_client_query_by_sysfs_path:
+ * @client: A #GUdevClient.
+ * @sysfs_path: A sysfs path.
+ *
+ * Looks up a device for a sysfs path.
+ *
+ * Returns: (transfer full): A #GUdevDevice object or %NULL if the device was not found. Free with g_object_unref().
+ */
+GUdevDevice *
+g_udev_client_query_by_sysfs_path (GUdevClient *client,
+ const gchar *sysfs_path)
+{
+ struct udev_device *udevice;
+ GUdevDevice *device;
+
+ g_return_val_if_fail (G_UDEV_IS_CLIENT (client), NULL);
+ g_return_val_if_fail (sysfs_path != NULL, NULL);
+
+ device = NULL;
+ udevice = udev_device_new_from_syspath (client->priv->udev, sysfs_path);
+ if (udevice == NULL)
+ goto out;
+
+ device = _g_udev_device_new (udevice);
+ udev_device_unref (udevice);
+
+ out:
+ return device;
+}
+
+/**
+ * g_udev_client_query_by_subsystem_and_name:
+ * @client: A #GUdevClient.
+ * @subsystem: A subsystem name.
+ * @name: The name of the device.
+ *
+ * Looks up a device for a subsystem and name.
+ *
+ * Returns: (transfer full): A #GUdevDevice object or %NULL if the device was not found. Free with g_object_unref().
+ */
+GUdevDevice *
+g_udev_client_query_by_subsystem_and_name (GUdevClient *client,
+ const gchar *subsystem,
+ const gchar *name)
+{
+ struct udev_device *udevice;
+ GUdevDevice *device;
+
+ g_return_val_if_fail (G_UDEV_IS_CLIENT (client), NULL);
+ g_return_val_if_fail (subsystem != NULL, NULL);
+ g_return_val_if_fail (name != NULL, NULL);
+
+ device = NULL;
+ udevice = udev_device_new_from_subsystem_sysname (client->priv->udev, subsystem, name);
+ if (udevice == NULL)
+ goto out;
+
+ device = _g_udev_device_new (udevice);
+ udev_device_unref (udevice);
+
+ out:
+ return device;
+}
+
+struct udev *
+_g_udev_client_get_udev (GUdevClient *client)
+{
+ g_return_val_if_fail (G_UDEV_IS_CLIENT (client), NULL);
+ return client->priv->udev;
+}
diff --git a/src/gudev/gudevclient.h b/src/gudev/gudevclient.h
new file mode 100644
index 0000000000..23bfce615f
--- /dev/null
+++ b/src/gudev/gudevclient.h
@@ -0,0 +1,99 @@
+/* -*- Mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*-
+ *
+ * Copyright (C) 2008 David Zeuthen <davidz@redhat.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#if !defined (_GUDEV_COMPILATION) && !defined(_GUDEV_INSIDE_GUDEV_H)
+#error "Only <gudev/gudev.h> can be included directly, this file may disappear or change contents."
+#endif
+
+#ifndef __G_UDEV_CLIENT_H__
+#define __G_UDEV_CLIENT_H__
+
+#include <gudev/gudevtypes.h>
+
+G_BEGIN_DECLS
+
+#define G_UDEV_TYPE_CLIENT (g_udev_client_get_type ())
+#define G_UDEV_CLIENT(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), G_UDEV_TYPE_CLIENT, GUdevClient))
+#define G_UDEV_CLIENT_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), G_UDEV_TYPE_CLIENT, GUdevClientClass))
+#define G_UDEV_IS_CLIENT(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), G_UDEV_TYPE_CLIENT))
+#define G_UDEV_IS_CLIENT_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), G_UDEV_TYPE_CLIENT))
+#define G_UDEV_CLIENT_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), G_UDEV_TYPE_CLIENT, GUdevClientClass))
+
+typedef struct _GUdevClientClass GUdevClientClass;
+typedef struct _GUdevClientPrivate GUdevClientPrivate;
+
+/**
+ * GUdevClient:
+ *
+ * The #GUdevClient struct is opaque and should not be accessed directly.
+ */
+struct _GUdevClient
+{
+ GObject parent;
+
+ /*< private >*/
+ GUdevClientPrivate *priv;
+};
+
+/**
+ * GUdevClientClass:
+ * @parent_class: Parent class.
+ * @uevent: Signal class handler for the #GUdevClient::uevent signal.
+ *
+ * Class structure for #GUdevClient.
+ */
+struct _GUdevClientClass
+{
+ GObjectClass parent_class;
+
+ /* signals */
+ void (*uevent) (GUdevClient *client,
+ const gchar *action,
+ GUdevDevice *device);
+
+ /*< private >*/
+ /* Padding for future expansion */
+ void (*reserved1) (void);
+ void (*reserved2) (void);
+ void (*reserved3) (void);
+ void (*reserved4) (void);
+ void (*reserved5) (void);
+ void (*reserved6) (void);
+ void (*reserved7) (void);
+ void (*reserved8) (void);
+};
+
+GType g_udev_client_get_type (void) G_GNUC_CONST;
+GUdevClient *g_udev_client_new (const gchar* const *subsystems);
+GList *g_udev_client_query_by_subsystem (GUdevClient *client,
+ const gchar *subsystem);
+GUdevDevice *g_udev_client_query_by_device_number (GUdevClient *client,
+ GUdevDeviceType type,
+ GUdevDeviceNumber number);
+GUdevDevice *g_udev_client_query_by_device_file (GUdevClient *client,
+ const gchar *device_file);
+GUdevDevice *g_udev_client_query_by_sysfs_path (GUdevClient *client,
+ const gchar *sysfs_path);
+GUdevDevice *g_udev_client_query_by_subsystem_and_name (GUdevClient *client,
+ const gchar *subsystem,
+ const gchar *name);
+
+G_END_DECLS
+
+#endif /* __G_UDEV_CLIENT_H__ */
diff --git a/src/gudev/gudevdevice.c b/src/gudev/gudevdevice.c
new file mode 100644
index 0000000000..6c9e0f56cf
--- /dev/null
+++ b/src/gudev/gudevdevice.c
@@ -0,0 +1,961 @@
+/* -*- Mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*-
+ *
+ * Copyright (C) 2008 David Zeuthen <davidz@redhat.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifdef HAVE_CONFIG_H
+# include "config.h"
+#endif
+
+#include <stdlib.h>
+#include <string.h>
+
+#include "gudevdevice.h"
+#include "gudevprivate.h"
+
+/**
+ * SECTION:gudevdevice
+ * @short_description: Get information about a device
+ *
+ * The #GUdevDevice class is used to get information about a specific
+ * device. Note that you cannot instantiate a #GUdevDevice object
+ * yourself. Instead you must use #GUdevClient to obtain #GUdevDevice
+ * objects.
+ *
+ * To get basic information about a device, use
+ * g_udev_device_get_subsystem(), g_udev_device_get_devtype(),
+ * g_udev_device_get_name(), g_udev_device_get_number(),
+ * g_udev_device_get_sysfs_path(), g_udev_device_get_driver(),
+ * g_udev_device_get_action(), g_udev_device_get_seqnum(),
+ * g_udev_device_get_device_type(), g_udev_device_get_device_number(),
+ * g_udev_device_get_device_file(),
+ * g_udev_device_get_device_file_symlinks().
+ *
+ * To navigate the device tree, use g_udev_device_get_parent() and
+ * g_udev_device_get_parent_with_subsystem().
+ *
+ * To access udev properties for the device, use
+ * g_udev_device_get_property_keys(),
+ * g_udev_device_has_property(),
+ * g_udev_device_get_property(),
+ * g_udev_device_get_property_as_int(),
+ * g_udev_device_get_property_as_uint64(),
+ * g_udev_device_get_property_as_double(),
+ * g_udev_device_get_property_as_boolean() and
+ * g_udev_device_get_property_as_strv().
+ *
+ * To access sysfs attributes for the device, use
+ * g_udev_device_get_sysfs_attr(),
+ * g_udev_device_get_sysfs_attr_as_int(),
+ * g_udev_device_get_sysfs_attr_as_uint64(),
+ * g_udev_device_get_sysfs_attr_as_double(),
+ * g_udev_device_get_sysfs_attr_as_boolean() and
+ * g_udev_device_get_sysfs_attr_as_strv().
+ *
+ * Note that all getters on #GUdevDevice are non-reffing – returned
+ * values are owned by the object, should not be freed and are only
+ * valid as long as the object is alive.
+ *
+ * By design, #GUdevDevice will not react to changes for a device – it
+ * only contains a snapshot of information when the #GUdevDevice
+ * object was created. To work with changes, you typically connect to
+ * the #GUdevClient::uevent signal on a #GUdevClient and get a new
+ * #GUdevDevice whenever an event happens.
+ */
+
+struct _GUdevDevicePrivate
+{
+ struct udev_device *udevice;
+
+ /* computed ondemand and cached */
+ gchar **device_file_symlinks;
+ gchar **property_keys;
+ gchar **tags;
+ GHashTable *prop_strvs;
+ GHashTable *sysfs_attr_strvs;
+};
+
+G_DEFINE_TYPE (GUdevDevice, g_udev_device, G_TYPE_OBJECT)
+
+static void
+g_udev_device_finalize (GObject *object)
+{
+ GUdevDevice *device = G_UDEV_DEVICE (object);
+
+ g_strfreev (device->priv->device_file_symlinks);
+ g_strfreev (device->priv->property_keys);
+ g_strfreev (device->priv->tags);
+
+ if (device->priv->udevice != NULL)
+ udev_device_unref (device->priv->udevice);
+
+ if (device->priv->prop_strvs != NULL)
+ g_hash_table_unref (device->priv->prop_strvs);
+
+ if (device->priv->sysfs_attr_strvs != NULL)
+ g_hash_table_unref (device->priv->sysfs_attr_strvs);
+
+ if (G_OBJECT_CLASS (g_udev_device_parent_class)->finalize != NULL)
+ (* G_OBJECT_CLASS (g_udev_device_parent_class)->finalize) (object);
+}
+
+static void
+g_udev_device_class_init (GUdevDeviceClass *klass)
+{
+ GObjectClass *gobject_class = (GObjectClass *) klass;
+
+ gobject_class->finalize = g_udev_device_finalize;
+
+ g_type_class_add_private (klass, sizeof (GUdevDevicePrivate));
+}
+
+static void
+g_udev_device_init (GUdevDevice *device)
+{
+ device->priv = G_TYPE_INSTANCE_GET_PRIVATE (device,
+ G_UDEV_TYPE_DEVICE,
+ GUdevDevicePrivate);
+}
+
+
+GUdevDevice *
+_g_udev_device_new (struct udev_device *udevice)
+{
+ GUdevDevice *device;
+
+ device = G_UDEV_DEVICE (g_object_new (G_UDEV_TYPE_DEVICE, NULL));
+ device->priv->udevice = udev_device_ref (udevice);
+
+ return device;
+}
+
+/**
+ * g_udev_device_get_subsystem:
+ * @device: A #GUdevDevice.
+ *
+ * Gets the subsystem for @device.
+ *
+ * Returns: The subsystem for @device.
+ */
+const gchar *
+g_udev_device_get_subsystem (GUdevDevice *device)
+{
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), NULL);
+ return udev_device_get_subsystem (device->priv->udevice);
+}
+
+/**
+ * g_udev_device_get_devtype:
+ * @device: A #GUdevDevice.
+ *
+ * Gets the device type for @device.
+ *
+ * Returns: The devtype for @device.
+ */
+const gchar *
+g_udev_device_get_devtype (GUdevDevice *device)
+{
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), NULL);
+ return udev_device_get_devtype (device->priv->udevice);
+}
+
+/**
+ * g_udev_device_get_name:
+ * @device: A #GUdevDevice.
+ *
+ * Gets the name of @device, e.g. "sda3".
+ *
+ * Returns: The name of @device.
+ */
+const gchar *
+g_udev_device_get_name (GUdevDevice *device)
+{
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), NULL);
+ return udev_device_get_sysname (device->priv->udevice);
+}
+
+/**
+ * g_udev_device_get_number:
+ * @device: A #GUdevDevice.
+ *
+ * Gets the number of @device, e.g. "3" if g_udev_device_get_name() returns "sda3".
+ *
+ * Returns: The number of @device.
+ */
+const gchar *
+g_udev_device_get_number (GUdevDevice *device)
+{
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), NULL);
+ return udev_device_get_sysnum (device->priv->udevice);
+}
+
+/**
+ * g_udev_device_get_sysfs_path:
+ * @device: A #GUdevDevice.
+ *
+ * Gets the sysfs path for @device.
+ *
+ * Returns: The sysfs path for @device.
+ */
+const gchar *
+g_udev_device_get_sysfs_path (GUdevDevice *device)
+{
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), NULL);
+ return udev_device_get_syspath (device->priv->udevice);
+}
+
+/**
+ * g_udev_device_get_driver:
+ * @device: A #GUdevDevice.
+ *
+ * Gets the name of the driver used for @device.
+ *
+ * Returns: The name of the driver for @device or %NULL if unknown.
+ */
+const gchar *
+g_udev_device_get_driver (GUdevDevice *device)
+{
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), NULL);
+ return udev_device_get_driver (device->priv->udevice);
+}
+
+/**
+ * g_udev_device_get_action:
+ * @device: A #GUdevDevice.
+ *
+ * Gets the most recent action (e.g. "add", "remove", "change", etc.) for @device.
+ *
+ * Returns: An action string.
+ */
+const gchar *
+g_udev_device_get_action (GUdevDevice *device)
+{
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), NULL);
+ return udev_device_get_action (device->priv->udevice);
+}
+
+/**
+ * g_udev_device_get_seqnum:
+ * @device: A #GUdevDevice.
+ *
+ * Gets the most recent sequence number for @device.
+ *
+ * Returns: A sequence number.
+ */
+guint64
+g_udev_device_get_seqnum (GUdevDevice *device)
+{
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), 0);
+ return udev_device_get_seqnum (device->priv->udevice);
+}
+
+/**
+ * g_udev_device_get_device_type:
+ * @device: A #GUdevDevice.
+ *
+ * Gets the type of the device file, if any, for @device.
+ *
+ * Returns: The device number for @device or #G_UDEV_DEVICE_TYPE_NONE if the device does not have a device file.
+ */
+GUdevDeviceType
+g_udev_device_get_device_type (GUdevDevice *device)
+{
+ struct stat stat_buf;
+ const gchar *device_file;
+ GUdevDeviceType type;
+
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), G_UDEV_DEVICE_TYPE_NONE);
+
+ type = G_UDEV_DEVICE_TYPE_NONE;
+
+ /* TODO: would be better to have support for this in libudev... */
+
+ device_file = g_udev_device_get_device_file (device);
+ if (device_file == NULL)
+ goto out;
+
+ if (stat (device_file, &stat_buf) != 0)
+ goto out;
+
+ if (S_ISBLK (stat_buf.st_mode))
+ type = G_UDEV_DEVICE_TYPE_BLOCK;
+ else if (S_ISCHR (stat_buf.st_mode))
+ type = G_UDEV_DEVICE_TYPE_CHAR;
+
+ out:
+ return type;
+}
+
+/**
+ * g_udev_device_get_device_number:
+ * @device: A #GUdevDevice.
+ *
+ * Gets the device number, if any, for @device.
+ *
+ * Returns: The device number for @device or 0 if unknown.
+ */
+GUdevDeviceNumber
+g_udev_device_get_device_number (GUdevDevice *device)
+{
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), 0);
+ return udev_device_get_devnum (device->priv->udevice);
+}
+
+/**
+ * g_udev_device_get_device_file:
+ * @device: A #GUdevDevice.
+ *
+ * Gets the device file for @device.
+ *
+ * Returns: The device file for @device or %NULL if no device file
+ * exists.
+ */
+const gchar *
+g_udev_device_get_device_file (GUdevDevice *device)
+{
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), NULL);
+ return udev_device_get_devnode (device->priv->udevice);
+}
+
+/**
+ * g_udev_device_get_device_file_symlinks:
+ * @device: A #GUdevDevice.
+ *
+ * Gets a list of symlinks (in <literal>/dev</literal>) that points to
+ * the device file for @device.
+ *
+ * Returns: (transfer none) (array zero-terminated=1) (element-type utf8): A %NULL terminated string array of symlinks. This array is owned by @device and should not be freed by the caller.
+ */
+const gchar * const *
+g_udev_device_get_device_file_symlinks (GUdevDevice *device)
+{
+ struct udev_list_entry *l;
+ GPtrArray *p;
+
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), NULL);
+
+ if (device->priv->device_file_symlinks != NULL)
+ goto out;
+
+ p = g_ptr_array_new ();
+ for (l = udev_device_get_devlinks_list_entry (device->priv->udevice); l != NULL; l = udev_list_entry_get_next (l))
+ {
+ g_ptr_array_add (p, g_strdup (udev_list_entry_get_name (l)));
+ }
+ g_ptr_array_add (p, NULL);
+ device->priv->device_file_symlinks = (gchar **) g_ptr_array_free (p, FALSE);
+
+ out:
+ return (const gchar * const *) device->priv->device_file_symlinks;
+}
+
+/* ---------------------------------------------------------------------------------------------------- */
+
+/**
+ * g_udev_device_get_parent:
+ * @device: A #GUdevDevice.
+ *
+ * Gets the immediate parent of @device, if any.
+ *
+ * Returns: (transfer full): A #GUdevDevice or %NULL if @device has no parent. Free with g_object_unref().
+ */
+GUdevDevice *
+g_udev_device_get_parent (GUdevDevice *device)
+{
+ GUdevDevice *ret;
+ struct udev_device *udevice;
+
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), NULL);
+
+ ret = NULL;
+
+ udevice = udev_device_get_parent (device->priv->udevice);
+ if (udevice == NULL)
+ goto out;
+
+ ret = _g_udev_device_new (udevice);
+
+ out:
+ return ret;
+}
+
+/**
+ * g_udev_device_get_parent_with_subsystem:
+ * @device: A #GUdevDevice.
+ * @subsystem: The subsystem of the parent to get.
+ * @devtype: (allow-none): The devtype of the parent to get or %NULL.
+ *
+ * Walks up the chain of parents of @device and returns the first
+ * device encountered where @subsystem and @devtype matches, if any.
+ *
+ * Returns: (transfer full): A #GUdevDevice or %NULL if @device has no parent with @subsystem and @devtype. Free with g_object_unref().
+ */
+GUdevDevice *
+g_udev_device_get_parent_with_subsystem (GUdevDevice *device,
+ const gchar *subsystem,
+ const gchar *devtype)
+{
+ GUdevDevice *ret;
+ struct udev_device *udevice;
+
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), NULL);
+ g_return_val_if_fail (subsystem != NULL, NULL);
+
+ ret = NULL;
+
+ udevice = udev_device_get_parent_with_subsystem_devtype (device->priv->udevice,
+ subsystem,
+ devtype);
+ if (udevice == NULL)
+ goto out;
+
+ ret = _g_udev_device_new (udevice);
+
+ out:
+ return ret;
+}
+
+/* ---------------------------------------------------------------------------------------------------- */
+
+/**
+ * g_udev_device_get_property_keys:
+ * @device: A #GUdevDevice.
+ *
+ * Gets all keys for properties on @device.
+ *
+ * Returns: (transfer none) (array zero-terminated=1) (element-type utf8): A %NULL terminated string array of property keys. This array is owned by @device and should not be freed by the caller.
+ */
+const gchar* const *
+g_udev_device_get_property_keys (GUdevDevice *device)
+{
+ struct udev_list_entry *l;
+ GPtrArray *p;
+
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), NULL);
+
+ if (device->priv->property_keys != NULL)
+ goto out;
+
+ p = g_ptr_array_new ();
+ for (l = udev_device_get_properties_list_entry (device->priv->udevice); l != NULL; l = udev_list_entry_get_next (l))
+ {
+ g_ptr_array_add (p, g_strdup (udev_list_entry_get_name (l)));
+ }
+ g_ptr_array_add (p, NULL);
+ device->priv->property_keys = (gchar **) g_ptr_array_free (p, FALSE);
+
+ out:
+ return (const gchar * const *) device->priv->property_keys;
+}
+
+
+/**
+ * g_udev_device_has_property:
+ * @device: A #GUdevDevice.
+ * @key: Name of property.
+ *
+ * Check if a the property with the given key exists.
+ *
+ * Returns: %TRUE only if the value for @key exist.
+ */
+gboolean
+g_udev_device_has_property (GUdevDevice *device,
+ const gchar *key)
+{
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), FALSE);
+ g_return_val_if_fail (key != NULL, FALSE);
+ return udev_device_get_property_value (device->priv->udevice, key) != NULL;
+}
+
+/**
+ * g_udev_device_get_property:
+ * @device: A #GUdevDevice.
+ * @key: Name of property.
+ *
+ * Look up the value for @key on @device.
+ *
+ * Returns: The value for @key or %NULL if @key doesn't exist on @device. Do not free this string, it is owned by @device.
+ */
+const gchar *
+g_udev_device_get_property (GUdevDevice *device,
+ const gchar *key)
+{
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), NULL);
+ g_return_val_if_fail (key != NULL, NULL);
+ return udev_device_get_property_value (device->priv->udevice, key);
+}
+
+/**
+ * g_udev_device_get_property_as_int:
+ * @device: A #GUdevDevice.
+ * @key: Name of property.
+ *
+ * Look up the value for @key on @device and convert it to an integer
+ * using strtol().
+ *
+ * Returns: The value for @key or 0 if @key doesn't exist or
+ * isn't an integer.
+ */
+gint
+g_udev_device_get_property_as_int (GUdevDevice *device,
+ const gchar *key)
+{
+ gint result;
+ const gchar *s;
+
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), 0);
+ g_return_val_if_fail (key != NULL, 0);
+
+ result = 0;
+ s = g_udev_device_get_property (device, key);
+ if (s == NULL)
+ goto out;
+
+ result = strtol (s, NULL, 0);
+out:
+ return result;
+}
+
+/**
+ * g_udev_device_get_property_as_uint64:
+ * @device: A #GUdevDevice.
+ * @key: Name of property.
+ *
+ * Look up the value for @key on @device and convert it to an unsigned
+ * 64-bit integer using g_ascii_strtoull().
+ *
+ * Returns: The value for @key or 0 if @key doesn't exist or isn't a
+ * #guint64.
+ */
+guint64
+g_udev_device_get_property_as_uint64 (GUdevDevice *device,
+ const gchar *key)
+{
+ guint64 result;
+ const gchar *s;
+
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), 0);
+ g_return_val_if_fail (key != NULL, 0);
+
+ result = 0;
+ s = g_udev_device_get_property (device, key);
+ if (s == NULL)
+ goto out;
+
+ result = g_ascii_strtoull (s, NULL, 0);
+out:
+ return result;
+}
+
+/**
+ * g_udev_device_get_property_as_double:
+ * @device: A #GUdevDevice.
+ * @key: Name of property.
+ *
+ * Look up the value for @key on @device and convert it to a double
+ * precision floating point number using strtod().
+ *
+ * Returns: The value for @key or 0.0 if @key doesn't exist or isn't a
+ * #gdouble.
+ */
+gdouble
+g_udev_device_get_property_as_double (GUdevDevice *device,
+ const gchar *key)
+{
+ gdouble result;
+ const gchar *s;
+
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), 0.0);
+ g_return_val_if_fail (key != NULL, 0.0);
+
+ result = 0.0;
+ s = g_udev_device_get_property (device, key);
+ if (s == NULL)
+ goto out;
+
+ result = strtod (s, NULL);
+out:
+ return result;
+}
+
+/**
+ * g_udev_device_get_property_as_boolean:
+ * @device: A #GUdevDevice.
+ * @key: Name of property.
+ *
+ * Look up the value for @key on @device and convert it to an
+ * boolean. This is done by doing a case-insensitive string comparison
+ * on the string value against "1" and "true".
+ *
+ * Returns: The value for @key or %FALSE if @key doesn't exist or
+ * isn't a #gboolean.
+ */
+gboolean
+g_udev_device_get_property_as_boolean (GUdevDevice *device,
+ const gchar *key)
+{
+ gboolean result;
+ const gchar *s;
+
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), FALSE);
+ g_return_val_if_fail (key != NULL, FALSE);
+
+ result = FALSE;
+ s = g_udev_device_get_property (device, key);
+ if (s == NULL)
+ goto out;
+
+ if (strcmp (s, "1") == 0 || g_ascii_strcasecmp (s, "true") == 0)
+ result = TRUE;
+ out:
+ return result;
+}
+
+static gchar **
+split_at_whitespace (const gchar *s)
+{
+ gchar **result;
+ guint n;
+ guint m;
+
+ result = g_strsplit_set (s, " \v\t\r\n", 0);
+
+ /* remove empty strings, thanks GLib */
+ for (n = 0; result[n] != NULL; n++)
+ {
+ if (strlen (result[n]) == 0)
+ {
+ g_free (result[n]);
+ for (m = n; result[m] != NULL; m++)
+ result[m] = result[m + 1];
+ n--;
+ }
+ }
+
+ return result;
+}
+
+/**
+ * g_udev_device_get_property_as_strv:
+ * @device: A #GUdevDevice.
+ * @key: Name of property.
+ *
+ * Look up the value for @key on @device and return the result of
+ * splitting it into non-empty tokens split at white space (only space
+ * (' '), form-feed ('\f'), newline ('\n'), carriage return ('\r'),
+ * horizontal tab ('\t'), and vertical tab ('\v') are considered; the
+ * locale is not taken into account).
+ *
+ * Returns: (transfer none) (array zero-terminated=1) (element-type utf8): The value of @key on @device split into tokens or %NULL if @key doesn't exist. This array is owned by @device and should not be freed by the caller.
+ */
+const gchar* const *
+g_udev_device_get_property_as_strv (GUdevDevice *device,
+ const gchar *key)
+{
+ gchar **result;
+ const gchar *s;
+
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), NULL);
+ g_return_val_if_fail (key != NULL, NULL);
+
+ if (device->priv->prop_strvs != NULL)
+ {
+ result = g_hash_table_lookup (device->priv->prop_strvs, key);
+ if (result != NULL)
+ goto out;
+ }
+
+ result = NULL;
+ s = g_udev_device_get_property (device, key);
+ if (s == NULL)
+ goto out;
+
+ result = split_at_whitespace (s);
+ if (result == NULL)
+ goto out;
+
+ if (device->priv->prop_strvs == NULL)
+ device->priv->prop_strvs = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_strfreev);
+ g_hash_table_insert (device->priv->prop_strvs, g_strdup (key), result);
+
+out:
+ return (const gchar* const *) result;
+}
+
+/* ---------------------------------------------------------------------------------------------------- */
+
+/**
+ * g_udev_device_get_sysfs_attr:
+ * @device: A #GUdevDevice.
+ * @name: Name of the sysfs attribute.
+ *
+ * Look up the sysfs attribute with @name on @device.
+ *
+ * Returns: The value of the sysfs attribute or %NULL if there is no
+ * such attribute. Do not free this string, it is owned by @device.
+ */
+const gchar *
+g_udev_device_get_sysfs_attr (GUdevDevice *device,
+ const gchar *name)
+{
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), NULL);
+ g_return_val_if_fail (name != NULL, NULL);
+ return udev_device_get_sysattr_value (device->priv->udevice, name);
+}
+
+/**
+ * g_udev_device_get_sysfs_attr_as_int:
+ * @device: A #GUdevDevice.
+ * @name: Name of the sysfs attribute.
+ *
+ * Look up the sysfs attribute with @name on @device and convert it to an integer
+ * using strtol().
+ *
+ * Returns: The value of the sysfs attribute or 0 if there is no such
+ * attribute.
+ */
+gint
+g_udev_device_get_sysfs_attr_as_int (GUdevDevice *device,
+ const gchar *name)
+{
+ gint result;
+ const gchar *s;
+
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), 0);
+ g_return_val_if_fail (name != NULL, 0);
+
+ result = 0;
+ s = g_udev_device_get_sysfs_attr (device, name);
+ if (s == NULL)
+ goto out;
+
+ result = strtol (s, NULL, 0);
+out:
+ return result;
+}
+
+/**
+ * g_udev_device_get_sysfs_attr_as_uint64:
+ * @device: A #GUdevDevice.
+ * @name: Name of the sysfs attribute.
+ *
+ * Look up the sysfs attribute with @name on @device and convert it to an unsigned
+ * 64-bit integer using g_ascii_strtoull().
+ *
+ * Returns: The value of the sysfs attribute or 0 if there is no such
+ * attribute.
+ */
+guint64
+g_udev_device_get_sysfs_attr_as_uint64 (GUdevDevice *device,
+ const gchar *name)
+{
+ guint64 result;
+ const gchar *s;
+
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), 0);
+ g_return_val_if_fail (name != NULL, 0);
+
+ result = 0;
+ s = g_udev_device_get_sysfs_attr (device, name);
+ if (s == NULL)
+ goto out;
+
+ result = g_ascii_strtoull (s, NULL, 0);
+out:
+ return result;
+}
+
+/**
+ * g_udev_device_get_sysfs_attr_as_double:
+ * @device: A #GUdevDevice.
+ * @name: Name of the sysfs attribute.
+ *
+ * Look up the sysfs attribute with @name on @device and convert it to a double
+ * precision floating point number using strtod().
+ *
+ * Returns: The value of the sysfs attribute or 0.0 if there is no such
+ * attribute.
+ */
+gdouble
+g_udev_device_get_sysfs_attr_as_double (GUdevDevice *device,
+ const gchar *name)
+{
+ gdouble result;
+ const gchar *s;
+
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), 0.0);
+ g_return_val_if_fail (name != NULL, 0.0);
+
+ result = 0.0;
+ s = g_udev_device_get_sysfs_attr (device, name);
+ if (s == NULL)
+ goto out;
+
+ result = strtod (s, NULL);
+out:
+ return result;
+}
+
+/**
+ * g_udev_device_get_sysfs_attr_as_boolean:
+ * @device: A #GUdevDevice.
+ * @name: Name of the sysfs attribute.
+ *
+ * Look up the sysfs attribute with @name on @device and convert it to an
+ * boolean. This is done by doing a case-insensitive string comparison
+ * on the string value against "1" and "true".
+ *
+ * Returns: The value of the sysfs attribute or %FALSE if there is no such
+ * attribute.
+ */
+gboolean
+g_udev_device_get_sysfs_attr_as_boolean (GUdevDevice *device,
+ const gchar *name)
+{
+ gboolean result;
+ const gchar *s;
+
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), FALSE);
+ g_return_val_if_fail (name != NULL, FALSE);
+
+ result = FALSE;
+ s = g_udev_device_get_sysfs_attr (device, name);
+ if (s == NULL)
+ goto out;
+
+ if (strcmp (s, "1") == 0 || g_ascii_strcasecmp (s, "true") == 0)
+ result = TRUE;
+ out:
+ return result;
+}
+
+/**
+ * g_udev_device_get_sysfs_attr_as_strv:
+ * @device: A #GUdevDevice.
+ * @name: Name of the sysfs attribute.
+ *
+ * Look up the sysfs attribute with @name on @device and return the result of
+ * splitting it into non-empty tokens split at white space (only space (' '),
+ * form-feed ('\f'), newline ('\n'), carriage return ('\r'), horizontal
+ * tab ('\t'), and vertical tab ('\v') are considered; the locale is
+ * not taken into account).
+ *
+ * Returns: (transfer none) (array zero-terminated=1) (element-type utf8): The value of the sysfs attribute split into tokens or %NULL if there is no such attribute. This array is owned by @device and should not be freed by the caller.
+ */
+const gchar * const *
+g_udev_device_get_sysfs_attr_as_strv (GUdevDevice *device,
+ const gchar *name)
+{
+ gchar **result;
+ const gchar *s;
+
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), NULL);
+ g_return_val_if_fail (name != NULL, NULL);
+
+ if (device->priv->sysfs_attr_strvs != NULL)
+ {
+ result = g_hash_table_lookup (device->priv->sysfs_attr_strvs, name);
+ if (result != NULL)
+ goto out;
+ }
+
+ result = NULL;
+ s = g_udev_device_get_sysfs_attr (device, name);
+ if (s == NULL)
+ goto out;
+
+ result = split_at_whitespace (s);
+ if (result == NULL)
+ goto out;
+
+ if (device->priv->sysfs_attr_strvs == NULL)
+ device->priv->sysfs_attr_strvs = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_strfreev);
+ g_hash_table_insert (device->priv->sysfs_attr_strvs, g_strdup (name), result);
+
+out:
+ return (const gchar* const *) result;
+}
+
+/**
+ * g_udev_device_get_tags:
+ * @device: A #GUdevDevice.
+ *
+ * Gets all tags for @device.
+ *
+ * Returns: (transfer none) (array zero-terminated=1) (element-type utf8): A %NULL terminated string array of tags. This array is owned by @device and should not be freed by the caller.
+ *
+ * Since: 165
+ */
+const gchar* const *
+g_udev_device_get_tags (GUdevDevice *device)
+{
+ struct udev_list_entry *l;
+ GPtrArray *p;
+
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), NULL);
+
+ if (device->priv->tags != NULL)
+ goto out;
+
+ p = g_ptr_array_new ();
+ for (l = udev_device_get_tags_list_entry (device->priv->udevice); l != NULL; l = udev_list_entry_get_next (l))
+ {
+ g_ptr_array_add (p, g_strdup (udev_list_entry_get_name (l)));
+ }
+ g_ptr_array_add (p, NULL);
+ device->priv->tags = (gchar **) g_ptr_array_free (p, FALSE);
+
+ out:
+ return (const gchar * const *) device->priv->tags;
+}
+
+/**
+ * g_udev_device_get_is_initialized:
+ * @device: A #GUdevDevice.
+ *
+ * Gets whether @device has been initalized.
+ *
+ * Returns: Whether @device has been initialized.
+ *
+ * Since: 165
+ */
+gboolean
+g_udev_device_get_is_initialized (GUdevDevice *device)
+{
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), FALSE);
+ return udev_device_get_is_initialized (device->priv->udevice);
+}
+
+/**
+ * g_udev_device_get_usec_since_initialized:
+ * @device: A #GUdevDevice.
+ *
+ * Gets number of micro-seconds since @device was initialized.
+ *
+ * This only works for devices with properties in the udev
+ * database. All other devices return 0.
+ *
+ * Returns: Number of micro-seconds since @device was initialized or 0 if unknown.
+ *
+ * Since: 165
+ */
+guint64
+g_udev_device_get_usec_since_initialized (GUdevDevice *device)
+{
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), 0);
+ return udev_device_get_usec_since_initialized (device->priv->udevice);
+}
diff --git a/src/gudev/gudevdevice.h b/src/gudev/gudevdevice.h
new file mode 100644
index 0000000000..457b961c5e
--- /dev/null
+++ b/src/gudev/gudevdevice.h
@@ -0,0 +1,127 @@
+/* -*- Mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*-
+ *
+ * Copyright (C) 2008 David Zeuthen <davidz@redhat.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#if !defined (_GUDEV_COMPILATION) && !defined(_GUDEV_INSIDE_GUDEV_H)
+#error "Only <gudev/gudev.h> can be included directly, this file may disappear or change contents."
+#endif
+
+#ifndef __G_UDEV_DEVICE_H__
+#define __G_UDEV_DEVICE_H__
+
+#include <gudev/gudevtypes.h>
+
+G_BEGIN_DECLS
+
+#define G_UDEV_TYPE_DEVICE (g_udev_device_get_type ())
+#define G_UDEV_DEVICE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), G_UDEV_TYPE_DEVICE, GUdevDevice))
+#define G_UDEV_DEVICE_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), G_UDEV_TYPE_DEVICE, GUdevDeviceClass))
+#define G_UDEV_IS_DEVICE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), G_UDEV_TYPE_DEVICE))
+#define G_UDEV_IS_DEVICE_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), G_UDEV_TYPE_DEVICE))
+#define G_UDEV_DEVICE_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), G_UDEV_TYPE_DEVICE, GUdevDeviceClass))
+
+typedef struct _GUdevDeviceClass GUdevDeviceClass;
+typedef struct _GUdevDevicePrivate GUdevDevicePrivate;
+
+/**
+ * GUdevDevice:
+ *
+ * The #GUdevDevice struct is opaque and should not be accessed directly.
+ */
+struct _GUdevDevice
+{
+ GObject parent;
+
+ /*< private >*/
+ GUdevDevicePrivate *priv;
+};
+
+/**
+ * GUdevDeviceClass:
+ * @parent_class: Parent class.
+ *
+ * Class structure for #GUdevDevice.
+ */
+struct _GUdevDeviceClass
+{
+ GObjectClass parent_class;
+
+ /*< private >*/
+ /* Padding for future expansion */
+ void (*reserved1) (void);
+ void (*reserved2) (void);
+ void (*reserved3) (void);
+ void (*reserved4) (void);
+ void (*reserved5) (void);
+ void (*reserved6) (void);
+ void (*reserved7) (void);
+ void (*reserved8) (void);
+};
+
+GType g_udev_device_get_type (void) G_GNUC_CONST;
+gboolean g_udev_device_get_is_initialized (GUdevDevice *device);
+guint64 g_udev_device_get_usec_since_initialized (GUdevDevice *device);
+const gchar *g_udev_device_get_subsystem (GUdevDevice *device);
+const gchar *g_udev_device_get_devtype (GUdevDevice *device);
+const gchar *g_udev_device_get_name (GUdevDevice *device);
+const gchar *g_udev_device_get_number (GUdevDevice *device);
+const gchar *g_udev_device_get_sysfs_path (GUdevDevice *device);
+const gchar *g_udev_device_get_driver (GUdevDevice *device);
+const gchar *g_udev_device_get_action (GUdevDevice *device);
+guint64 g_udev_device_get_seqnum (GUdevDevice *device);
+GUdevDeviceType g_udev_device_get_device_type (GUdevDevice *device);
+GUdevDeviceNumber g_udev_device_get_device_number (GUdevDevice *device);
+const gchar *g_udev_device_get_device_file (GUdevDevice *device);
+const gchar* const *g_udev_device_get_device_file_symlinks (GUdevDevice *device);
+GUdevDevice *g_udev_device_get_parent (GUdevDevice *device);
+GUdevDevice *g_udev_device_get_parent_with_subsystem (GUdevDevice *device,
+ const gchar *subsystem,
+ const gchar *devtype);
+const gchar* const *g_udev_device_get_property_keys (GUdevDevice *device);
+gboolean g_udev_device_has_property (GUdevDevice *device,
+ const gchar *key);
+const gchar *g_udev_device_get_property (GUdevDevice *device,
+ const gchar *key);
+gint g_udev_device_get_property_as_int (GUdevDevice *device,
+ const gchar *key);
+guint64 g_udev_device_get_property_as_uint64 (GUdevDevice *device,
+ const gchar *key);
+gdouble g_udev_device_get_property_as_double (GUdevDevice *device,
+ const gchar *key);
+gboolean g_udev_device_get_property_as_boolean (GUdevDevice *device,
+ const gchar *key);
+const gchar* const *g_udev_device_get_property_as_strv (GUdevDevice *device,
+ const gchar *key);
+
+const gchar *g_udev_device_get_sysfs_attr (GUdevDevice *device,
+ const gchar *name);
+gint g_udev_device_get_sysfs_attr_as_int (GUdevDevice *device,
+ const gchar *name);
+guint64 g_udev_device_get_sysfs_attr_as_uint64 (GUdevDevice *device,
+ const gchar *name);
+gdouble g_udev_device_get_sysfs_attr_as_double (GUdevDevice *device,
+ const gchar *name);
+gboolean g_udev_device_get_sysfs_attr_as_boolean (GUdevDevice *device,
+ const gchar *name);
+const gchar* const *g_udev_device_get_sysfs_attr_as_strv (GUdevDevice *device,
+ const gchar *name);
+const gchar* const *g_udev_device_get_tags (GUdevDevice *device);
+
+G_END_DECLS
+
+#endif /* __G_UDEV_DEVICE_H__ */
diff --git a/src/gudev/gudevenumerator.c b/src/gudev/gudevenumerator.c
new file mode 100644
index 0000000000..1fb3098709
--- /dev/null
+++ b/src/gudev/gudevenumerator.c
@@ -0,0 +1,429 @@
+/* -*- Mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*-
+ *
+ * Copyright (C) 2008-2010 David Zeuthen <davidz@redhat.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifdef HAVE_CONFIG_H
+# include "config.h"
+#endif
+
+#include <stdlib.h>
+#include <string.h>
+
+#include "gudevclient.h"
+#include "gudevenumerator.h"
+#include "gudevdevice.h"
+#include "gudevmarshal.h"
+#include "gudevprivate.h"
+
+/**
+ * SECTION:gudevenumerator
+ * @short_description: Lookup and sort devices
+ *
+ * #GUdevEnumerator is used to lookup and sort devices.
+ *
+ * Since: 165
+ */
+
+struct _GUdevEnumeratorPrivate
+{
+ GUdevClient *client;
+ struct udev_enumerate *e;
+};
+
+enum
+{
+ PROP_0,
+ PROP_CLIENT,
+};
+
+G_DEFINE_TYPE (GUdevEnumerator, g_udev_enumerator, G_TYPE_OBJECT)
+
+/* ---------------------------------------------------------------------------------------------------- */
+
+static void
+g_udev_enumerator_finalize (GObject *object)
+{
+ GUdevEnumerator *enumerator = G_UDEV_ENUMERATOR (object);
+
+ if (enumerator->priv->client != NULL)
+ {
+ g_object_unref (enumerator->priv->client);
+ enumerator->priv->client = NULL;
+ }
+
+ if (enumerator->priv->e != NULL)
+ {
+ udev_enumerate_unref (enumerator->priv->e);
+ enumerator->priv->e = NULL;
+ }
+
+ if (G_OBJECT_CLASS (g_udev_enumerator_parent_class)->finalize != NULL)
+ G_OBJECT_CLASS (g_udev_enumerator_parent_class)->finalize (object);
+}
+
+static void
+g_udev_enumerator_set_property (GObject *object,
+ guint prop_id,
+ const GValue *value,
+ GParamSpec *pspec)
+{
+ GUdevEnumerator *enumerator = G_UDEV_ENUMERATOR (object);
+
+ switch (prop_id)
+ {
+ case PROP_CLIENT:
+ if (enumerator->priv->client != NULL)
+ g_object_unref (enumerator->priv->client);
+ enumerator->priv->client = g_value_dup_object (value);
+ break;
+
+ default:
+ G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+ break;
+ }
+}
+
+static void
+g_udev_enumerator_get_property (GObject *object,
+ guint prop_id,
+ GValue *value,
+ GParamSpec *pspec)
+{
+ GUdevEnumerator *enumerator = G_UDEV_ENUMERATOR (object);
+
+ switch (prop_id)
+ {
+ case PROP_CLIENT:
+ g_value_set_object (value, enumerator->priv->client);
+ break;
+
+ default:
+ G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+ break;
+ }
+}
+
+static void
+g_udev_enumerator_constructed (GObject *object)
+{
+ GUdevEnumerator *enumerator = G_UDEV_ENUMERATOR (object);
+
+ g_assert (G_UDEV_IS_CLIENT (enumerator->priv->client));
+
+ enumerator->priv->e = udev_enumerate_new (_g_udev_client_get_udev (enumerator->priv->client));
+
+ if (G_OBJECT_CLASS (g_udev_enumerator_parent_class)->constructed != NULL)
+ G_OBJECT_CLASS (g_udev_enumerator_parent_class)->constructed (object);
+}
+
+static void
+g_udev_enumerator_class_init (GUdevEnumeratorClass *klass)
+{
+ GObjectClass *gobject_class = (GObjectClass *) klass;
+
+ gobject_class->finalize = g_udev_enumerator_finalize;
+ gobject_class->set_property = g_udev_enumerator_set_property;
+ gobject_class->get_property = g_udev_enumerator_get_property;
+ gobject_class->constructed = g_udev_enumerator_constructed;
+
+ /**
+ * GUdevEnumerator:client:
+ *
+ * The #GUdevClient to enumerate devices from.
+ *
+ * Since: 165
+ */
+ g_object_class_install_property (gobject_class,
+ PROP_CLIENT,
+ g_param_spec_object ("client",
+ "The client to enumerate devices from",
+ "The client to enumerate devices from",
+ G_UDEV_TYPE_CLIENT,
+ G_PARAM_CONSTRUCT_ONLY |
+ G_PARAM_READWRITE));
+
+ g_type_class_add_private (klass, sizeof (GUdevEnumeratorPrivate));
+}
+
+static void
+g_udev_enumerator_init (GUdevEnumerator *enumerator)
+{
+ enumerator->priv = G_TYPE_INSTANCE_GET_PRIVATE (enumerator,
+ G_UDEV_TYPE_ENUMERATOR,
+ GUdevEnumeratorPrivate);
+}
+
+/**
+ * g_udev_enumerator_new:
+ * @client: A #GUdevClient to enumerate devices from.
+ *
+ * Constructs a #GUdevEnumerator object that can be used to enumerate
+ * and sort devices. Use the add_match_*() and add_nomatch_*() methods
+ * and execute the query to get a list of devices with
+ * g_udev_enumerator_execute().
+ *
+ * Returns: A new #GUdevEnumerator object. Free with g_object_unref().
+ *
+ * Since: 165
+ */
+GUdevEnumerator *
+g_udev_enumerator_new (GUdevClient *client)
+{
+ g_return_val_if_fail (G_UDEV_IS_CLIENT (client), NULL);
+ return G_UDEV_ENUMERATOR (g_object_new (G_UDEV_TYPE_ENUMERATOR, "client", client, NULL));
+}
+
+
+/**
+ * g_udev_enumerator_add_match_subsystem:
+ * @enumerator: A #GUdevEnumerator.
+ * @subsystem: Wildcard for subsystem name e.g. 'scsi' or 'a*'.
+ *
+ * All returned devices will match the given @subsystem.
+ *
+ * Returns: (transfer none): The passed in @enumerator.
+ *
+ * Since: 165
+ */
+GUdevEnumerator *
+g_udev_enumerator_add_match_subsystem (GUdevEnumerator *enumerator,
+ const gchar *subsystem)
+{
+ g_return_val_if_fail (G_UDEV_IS_ENUMERATOR (enumerator), NULL);
+ g_return_val_if_fail (subsystem != NULL, NULL);
+ udev_enumerate_add_match_subsystem (enumerator->priv->e, subsystem);
+ return enumerator;
+}
+
+/**
+ * g_udev_enumerator_add_nomatch_subsystem:
+ * @enumerator: A #GUdevEnumerator.
+ * @subsystem: Wildcard for subsystem name e.g. 'scsi' or 'a*'.
+ *
+ * All returned devices will not match the given @subsystem.
+ *
+ * Returns: (transfer none): The passed in @enumerator.
+ *
+ * Since: 165
+ */
+GUdevEnumerator *
+g_udev_enumerator_add_nomatch_subsystem (GUdevEnumerator *enumerator,
+ const gchar *subsystem)
+{
+ g_return_val_if_fail (G_UDEV_IS_ENUMERATOR (enumerator), NULL);
+ g_return_val_if_fail (subsystem != NULL, NULL);
+ udev_enumerate_add_nomatch_subsystem (enumerator->priv->e, subsystem);
+ return enumerator;
+}
+
+/**
+ * g_udev_enumerator_add_match_sysfs_attr:
+ * @enumerator: A #GUdevEnumerator.
+ * @name: Wildcard filter for sysfs attribute key.
+ * @value: Wildcard filter for sysfs attribute value.
+ *
+ * All returned devices will have a sysfs attribute matching the given @name and @value.
+ *
+ * Returns: (transfer none): The passed in @enumerator.
+ *
+ * Since: 165
+ */
+GUdevEnumerator *
+g_udev_enumerator_add_match_sysfs_attr (GUdevEnumerator *enumerator,
+ const gchar *name,
+ const gchar *value)
+{
+ g_return_val_if_fail (G_UDEV_IS_ENUMERATOR (enumerator), NULL);
+ g_return_val_if_fail (name != NULL, NULL);
+ g_return_val_if_fail (value != NULL, NULL);
+ udev_enumerate_add_match_sysattr (enumerator->priv->e, name, value);
+ return enumerator;
+}
+
+/**
+ * g_udev_enumerator_add_nomatch_sysfs_attr:
+ * @enumerator: A #GUdevEnumerator.
+ * @name: Wildcard filter for sysfs attribute key.
+ * @value: Wildcard filter for sysfs attribute value.
+ *
+ * All returned devices will not have a sysfs attribute matching the given @name and @value.
+ *
+ * Returns: (transfer none): The passed in @enumerator.
+ *
+ * Since: 165
+ */
+GUdevEnumerator *
+g_udev_enumerator_add_nomatch_sysfs_attr (GUdevEnumerator *enumerator,
+ const gchar *name,
+ const gchar *value)
+{
+ g_return_val_if_fail (G_UDEV_IS_ENUMERATOR (enumerator), NULL);
+ g_return_val_if_fail (name != NULL, NULL);
+ g_return_val_if_fail (value != NULL, NULL);
+ udev_enumerate_add_nomatch_sysattr (enumerator->priv->e, name, value);
+ return enumerator;
+}
+
+/**
+ * g_udev_enumerator_add_match_property:
+ * @enumerator: A #GUdevEnumerator.
+ * @name: Wildcard filter for property name.
+ * @value: Wildcard filter for property value.
+ *
+ * All returned devices will have a property matching the given @name and @value.
+ *
+ * Returns: (transfer none): The passed in @enumerator.
+ *
+ * Since: 165
+ */
+GUdevEnumerator *
+g_udev_enumerator_add_match_property (GUdevEnumerator *enumerator,
+ const gchar *name,
+ const gchar *value)
+{
+ g_return_val_if_fail (G_UDEV_IS_ENUMERATOR (enumerator), NULL);
+ g_return_val_if_fail (name != NULL, NULL);
+ g_return_val_if_fail (value != NULL, NULL);
+ udev_enumerate_add_match_property (enumerator->priv->e, name, value);
+ return enumerator;
+}
+
+/**
+ * g_udev_enumerator_add_match_name:
+ * @enumerator: A #GUdevEnumerator.
+ * @name: Wildcard filter for kernel name e.g. "sda*".
+ *
+ * All returned devices will match the given @name.
+ *
+ * Returns: (transfer none): The passed in @enumerator.
+ *
+ * Since: 165
+ */
+GUdevEnumerator *
+g_udev_enumerator_add_match_name (GUdevEnumerator *enumerator,
+ const gchar *name)
+{
+ g_return_val_if_fail (G_UDEV_IS_ENUMERATOR (enumerator), NULL);
+ g_return_val_if_fail (name != NULL, NULL);
+ udev_enumerate_add_match_sysname (enumerator->priv->e, name);
+ return enumerator;
+}
+
+/**
+ * g_udev_enumerator_add_sysfs_path:
+ * @enumerator: A #GUdevEnumerator.
+ * @sysfs_path: A sysfs path, e.g. "/sys/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda"
+ *
+ * Add a device to the list of devices, to retrieve it back sorted in dependency order.
+ *
+ * Returns: (transfer none): The passed in @enumerator.
+ *
+ * Since: 165
+ */
+GUdevEnumerator *
+g_udev_enumerator_add_sysfs_path (GUdevEnumerator *enumerator,
+ const gchar *sysfs_path)
+{
+ g_return_val_if_fail (G_UDEV_IS_ENUMERATOR (enumerator), NULL);
+ g_return_val_if_fail (sysfs_path != NULL, NULL);
+ udev_enumerate_add_syspath (enumerator->priv->e, sysfs_path);
+ return enumerator;
+}
+
+/**
+ * g_udev_enumerator_add_match_tag:
+ * @enumerator: A #GUdevEnumerator.
+ * @tag: A udev tag e.g. "udev-acl".
+ *
+ * All returned devices will match the given @tag.
+ *
+ * Returns: (transfer none): The passed in @enumerator.
+ *
+ * Since: 165
+ */
+GUdevEnumerator *
+g_udev_enumerator_add_match_tag (GUdevEnumerator *enumerator,
+ const gchar *tag)
+{
+ g_return_val_if_fail (G_UDEV_IS_ENUMERATOR (enumerator), NULL);
+ g_return_val_if_fail (tag != NULL, NULL);
+ udev_enumerate_add_match_tag (enumerator->priv->e, tag);
+ return enumerator;
+}
+
+/**
+ * g_udev_enumerator_add_match_is_initialized:
+ * @enumerator: A #GUdevEnumerator.
+ *
+ * All returned devices will be initialized.
+ *
+ * Returns: (transfer none): The passed in @enumerator.
+ *
+ * Since: 165
+ */
+GUdevEnumerator *
+g_udev_enumerator_add_match_is_initialized (GUdevEnumerator *enumerator)
+{
+ g_return_val_if_fail (G_UDEV_IS_ENUMERATOR (enumerator), NULL);
+ udev_enumerate_add_match_is_initialized (enumerator->priv->e);
+ return enumerator;
+}
+
+/**
+ * g_udev_enumerator_execute:
+ * @enumerator: A #GUdevEnumerator.
+ *
+ * Executes the query in @enumerator.
+ *
+ * Returns: (element-type GUdevDevice) (transfer full): A list of #GUdevDevice objects. The caller should free the result by using g_object_unref() on each element in the list and then g_list_free() on the list.
+ *
+ * Since: 165
+ */
+GList *
+g_udev_enumerator_execute (GUdevEnumerator *enumerator)
+{
+ GList *ret;
+ struct udev_list_entry *l, *devices;
+
+ g_return_val_if_fail (G_UDEV_IS_ENUMERATOR (enumerator), NULL);
+
+ ret = NULL;
+
+ /* retrieve the list */
+ udev_enumerate_scan_devices (enumerator->priv->e);
+
+ devices = udev_enumerate_get_list_entry (enumerator->priv->e);
+ for (l = devices; l != NULL; l = udev_list_entry_get_next (l))
+ {
+ struct udev_device *udevice;
+ GUdevDevice *device;
+
+ udevice = udev_device_new_from_syspath (udev_enumerate_get_udev (enumerator->priv->e),
+ udev_list_entry_get_name (l));
+ if (udevice == NULL)
+ continue;
+
+ device = _g_udev_device_new (udevice);
+ udev_device_unref (udevice);
+ ret = g_list_prepend (ret, device);
+ }
+
+ ret = g_list_reverse (ret);
+
+ return ret;
+}
diff --git a/src/gudev/gudevenumerator.h b/src/gudev/gudevenumerator.h
new file mode 100644
index 0000000000..e1dbcf1441
--- /dev/null
+++ b/src/gudev/gudevenumerator.h
@@ -0,0 +1,106 @@
+/* -*- Mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*-
+ *
+ * Copyright (C) 2008-2010 David Zeuthen <davidz@redhat.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#if !defined (_GUDEV_COMPILATION) && !defined(_GUDEV_INSIDE_GUDEV_H)
+#error "Only <gudev/gudev.h> can be included directly, this file may disappear or change contents."
+#endif
+
+#ifndef __G_UDEV_ENUMERATOR_H__
+#define __G_UDEV_ENUMERATOR_H__
+
+#include <gudev/gudevtypes.h>
+
+G_BEGIN_DECLS
+
+#define G_UDEV_TYPE_ENUMERATOR (g_udev_enumerator_get_type ())
+#define G_UDEV_ENUMERATOR(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), G_UDEV_TYPE_ENUMERATOR, GUdevEnumerator))
+#define G_UDEV_ENUMERATOR_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), G_UDEV_TYPE_ENUMERATOR, GUdevEnumeratorClass))
+#define G_UDEV_IS_ENUMERATOR(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), G_UDEV_TYPE_ENUMERATOR))
+#define G_UDEV_IS_ENUMERATOR_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), G_UDEV_TYPE_ENUMERATOR))
+#define G_UDEV_ENUMERATOR_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), G_UDEV_TYPE_ENUMERATOR, GUdevEnumeratorClass))
+
+typedef struct _GUdevEnumeratorClass GUdevEnumeratorClass;
+typedef struct _GUdevEnumeratorPrivate GUdevEnumeratorPrivate;
+
+/**
+ * GUdevEnumerator:
+ *
+ * The #GUdevEnumerator struct is opaque and should not be accessed directly.
+ *
+ * Since: 165
+ */
+struct _GUdevEnumerator
+{
+ GObject parent;
+
+ /*< private >*/
+ GUdevEnumeratorPrivate *priv;
+};
+
+/**
+ * GUdevEnumeratorClass:
+ * @parent_class: Parent class.
+ *
+ * Class structure for #GUdevEnumerator.
+ *
+ * Since: 165
+ */
+struct _GUdevEnumeratorClass
+{
+ GObjectClass parent_class;
+
+ /*< private >*/
+ /* Padding for future expansion */
+ void (*reserved1) (void);
+ void (*reserved2) (void);
+ void (*reserved3) (void);
+ void (*reserved4) (void);
+ void (*reserved5) (void);
+ void (*reserved6) (void);
+ void (*reserved7) (void);
+ void (*reserved8) (void);
+};
+
+GType g_udev_enumerator_get_type (void) G_GNUC_CONST;
+GUdevEnumerator *g_udev_enumerator_new (GUdevClient *client);
+GUdevEnumerator *g_udev_enumerator_add_match_subsystem (GUdevEnumerator *enumerator,
+ const gchar *subsystem);
+GUdevEnumerator *g_udev_enumerator_add_nomatch_subsystem (GUdevEnumerator *enumerator,
+ const gchar *subsystem);
+GUdevEnumerator *g_udev_enumerator_add_match_sysfs_attr (GUdevEnumerator *enumerator,
+ const gchar *name,
+ const gchar *value);
+GUdevEnumerator *g_udev_enumerator_add_nomatch_sysfs_attr (GUdevEnumerator *enumerator,
+ const gchar *name,
+ const gchar *value);
+GUdevEnumerator *g_udev_enumerator_add_match_property (GUdevEnumerator *enumerator,
+ const gchar *name,
+ const gchar *value);
+GUdevEnumerator *g_udev_enumerator_add_match_name (GUdevEnumerator *enumerator,
+ const gchar *name);
+GUdevEnumerator *g_udev_enumerator_add_match_tag (GUdevEnumerator *enumerator,
+ const gchar *tag);
+GUdevEnumerator *g_udev_enumerator_add_match_is_initialized (GUdevEnumerator *enumerator);
+GUdevEnumerator *g_udev_enumerator_add_sysfs_path (GUdevEnumerator *enumerator,
+ const gchar *sysfs_path);
+GList *g_udev_enumerator_execute (GUdevEnumerator *enumerator);
+
+G_END_DECLS
+
+#endif /* __G_UDEV_ENUMERATOR_H__ */
diff --git a/src/gudev/gudevenums.h b/src/gudev/gudevenums.h
new file mode 100644
index 0000000000..467e93bd60
--- /dev/null
+++ b/src/gudev/gudevenums.h
@@ -0,0 +1,48 @@
+/* -*- Mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*-
+ *
+ * Copyright (C) 2008 David Zeuthen <davidz@redhat.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#if !defined (_GUDEV_COMPILATION) && !defined(_GUDEV_INSIDE_GUDEV_H)
+#error "Only <gudev/gudev.h> can be included directly, this file may disappear or change contents."
+#endif
+
+#ifndef __G_UDEV_ENUMS_H__
+#define __G_UDEV_ENUMS_H__
+
+#include <glib-object.h>
+
+G_BEGIN_DECLS
+
+/**
+ * GUdevDeviceType:
+ * @G_UDEV_DEVICE_TYPE_NONE: Device does not have a device file.
+ * @G_UDEV_DEVICE_TYPE_BLOCK: Device is a block device.
+ * @G_UDEV_DEVICE_TYPE_CHAR: Device is a character device.
+ *
+ * Enumeration used to specify a the type of a device.
+ */
+typedef enum
+{
+ G_UDEV_DEVICE_TYPE_NONE = 0,
+ G_UDEV_DEVICE_TYPE_BLOCK = 'b',
+ G_UDEV_DEVICE_TYPE_CHAR = 'c',
+} GUdevDeviceType;
+
+G_END_DECLS
+
+#endif /* __G_UDEV_ENUMS_H__ */
diff --git a/src/gudev/gudevenumtypes.c.template b/src/gudev/gudevenumtypes.c.template
new file mode 100644
index 0000000000..fc30b39e2e
--- /dev/null
+++ b/src/gudev/gudevenumtypes.c.template
@@ -0,0 +1,39 @@
+/*** BEGIN file-header ***/
+#include <gudev.h>
+
+/*** END file-header ***/
+
+/*** BEGIN file-production ***/
+/* enumerations from "@filename@" */
+/*** END file-production ***/
+
+/*** BEGIN value-header ***/
+GType
+@enum_name@_get_type (void)
+{
+ static volatile gsize g_define_type_id__volatile = 0;
+
+ if (g_once_init_enter (&g_define_type_id__volatile))
+ {
+ static const G@Type@Value values[] = {
+/*** END value-header ***/
+
+/*** BEGIN value-production ***/
+ { @VALUENAME@, "@VALUENAME@", "@valuenick@" },
+/*** END value-production ***/
+
+/*** BEGIN value-tail ***/
+ { 0, NULL, NULL }
+ };
+ GType g_define_type_id =
+ g_@type@_register_static (g_intern_static_string ("@EnumName@"), values);
+ g_once_init_leave (&g_define_type_id__volatile, g_define_type_id);
+ }
+
+ return g_define_type_id__volatile;
+}
+
+/*** END value-tail ***/
+
+/*** BEGIN file-tail ***/
+/*** END file-tail ***/
diff --git a/src/gudev/gudevenumtypes.h b/src/gudev/gudevenumtypes.h
new file mode 100644
index 0000000000..d773999c56
--- /dev/null
+++ b/src/gudev/gudevenumtypes.h
@@ -0,0 +1,19 @@
+
+/* Generated data (by glib-mkenums) */
+
+#ifndef __GUDEV_ENUM_TYPES_H__
+#define __GUDEV_ENUM_TYPES_H__
+
+#include <glib-object.h>
+
+G_BEGIN_DECLS
+
+/* enumerations from "src/gudev/gudevenums.h" */
+GType g_udev_device_type_get_type (void) G_GNUC_CONST;
+#define G_TYPE_UDEV_DEVICE_TYPE (g_udev_device_type_get_type ())
+G_END_DECLS
+
+#endif /* __GUDEV_ENUM_TYPES_H__ */
+
+/* Generated data ends here */
+
diff --git a/src/gudev/gudevenumtypes.h.template b/src/gudev/gudevenumtypes.h.template
new file mode 100644
index 0000000000..d0ab3393e6
--- /dev/null
+++ b/src/gudev/gudevenumtypes.h.template
@@ -0,0 +1,24 @@
+/*** BEGIN file-header ***/
+#ifndef __GUDEV_ENUM_TYPES_H__
+#define __GUDEV_ENUM_TYPES_H__
+
+#include <glib-object.h>
+
+G_BEGIN_DECLS
+/*** END file-header ***/
+
+/*** BEGIN file-production ***/
+
+/* enumerations from "@filename@" */
+/*** END file-production ***/
+
+/*** BEGIN value-header ***/
+GType @enum_name@_get_type (void) G_GNUC_CONST;
+#define @ENUMPREFIX@_TYPE_@ENUMSHORT@ (@enum_name@_get_type ())
+/*** END value-header ***/
+
+/*** BEGIN file-tail ***/
+G_END_DECLS
+
+#endif /* __GUDEV_ENUM_TYPES_H__ */
+/*** END file-tail ***/
diff --git a/src/gudev/gudevmarshal.list b/src/gudev/gudevmarshal.list
new file mode 100644
index 0000000000..7e665999e8
--- /dev/null
+++ b/src/gudev/gudevmarshal.list
@@ -0,0 +1 @@
+VOID:STRING,OBJECT
diff --git a/src/gudev/gudevprivate.h b/src/gudev/gudevprivate.h
new file mode 100644
index 0000000000..52e272be3d
--- /dev/null
+++ b/src/gudev/gudevprivate.h
@@ -0,0 +1,40 @@
+/* -*- Mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*-
+ *
+ * Copyright (C) 2008 David Zeuthen <davidz@redhat.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#if !defined (_GUDEV_COMPILATION) && !defined(_GUDEV_INSIDE_GUDEV_H)
+#error "Only <gudev/gudev.h> can be included directly, this file may disappear or change contents."
+#endif
+
+#ifndef __G_UDEV_PRIVATE_H__
+#define __G_UDEV_PRIVATE_H__
+
+#include <gudev/gudevtypes.h>
+
+#include <libudev.h>
+
+G_BEGIN_DECLS
+
+GUdevDevice *
+_g_udev_device_new (struct udev_device *udevice);
+
+struct udev *_g_udev_client_get_udev (GUdevClient *client);
+
+G_END_DECLS
+
+#endif /* __G_UDEV_PRIVATE_H__ */
diff --git a/src/gudev/gudevtypes.h b/src/gudev/gudevtypes.h
new file mode 100644
index 0000000000..e2f688ff2d
--- /dev/null
+++ b/src/gudev/gudevtypes.h
@@ -0,0 +1,50 @@
+/* -*- Mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*-
+ *
+ * Copyright (C) 2008 David Zeuthen <davidz@redhat.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#if !defined (_GUDEV_COMPILATION) && !defined(_GUDEV_INSIDE_GUDEV_H)
+#error "Only <gudev/gudev.h> can be included directly, this file may disappear or change contents."
+#endif
+
+#ifndef __G_UDEV_TYPES_H__
+#define __G_UDEV_TYPES_H__
+
+#include <gudev/gudevenums.h>
+#include <sys/types.h>
+
+G_BEGIN_DECLS
+
+typedef struct _GUdevClient GUdevClient;
+typedef struct _GUdevDevice GUdevDevice;
+typedef struct _GUdevEnumerator GUdevEnumerator;
+
+/**
+ * GUdevDeviceNumber:
+ *
+ * Corresponds to the standard #dev_t type as defined by POSIX (Until
+ * bug 584517 is resolved this work-around is needed).
+ */
+#ifdef _GUDEV_WORK_AROUND_DEV_T_BUG
+typedef guint64 GUdevDeviceNumber; /* __UQUAD_TYPE */
+#else
+typedef dev_t GUdevDeviceNumber;
+#endif
+
+G_END_DECLS
+
+#endif /* __G_UDEV_TYPES_H__ */
diff --git a/src/gudev/seed-example-enum.js b/src/gudev/seed-example-enum.js
new file mode 100755
index 0000000000..66206ad806
--- /dev/null
+++ b/src/gudev/seed-example-enum.js
@@ -0,0 +1,38 @@
+#!/usr/bin/env seed
+
+const GLib = imports.gi.GLib;
+const GUdev = imports.gi.GUdev;
+
+function print_device(device) {
+ print(" initialized: " + device.get_is_initialized());
+ print(" usec since initialized: " + device.get_usec_since_initialized());
+ print(" subsystem: " + device.get_subsystem());
+ print(" devtype: " + device.get_devtype());
+ print(" name: " + device.get_name());
+ print(" number: " + device.get_number());
+ print(" sysfs_path: " + device.get_sysfs_path());
+ print(" driver: " + device.get_driver());
+ print(" action: " + device.get_action());
+ print(" seqnum: " + device.get_seqnum());
+ print(" device type: " + device.get_device_type());
+ print(" device number: " + device.get_device_number());
+ print(" device file: " + device.get_device_file());
+ print(" device file symlinks: " + device.get_device_file_symlinks());
+ print(" tags: " + device.get_tags());
+ var keys = device.get_property_keys();
+ for (var n = 0; n < keys.length; n++) {
+ print(" " + keys[n] + "=" + device.get_property(keys[n]));
+ }
+}
+
+var client = new GUdev.Client({subsystems: []});
+var enumerator = new GUdev.Enumerator({client: client});
+enumerator.add_match_subsystem('b*')
+
+var devices = enumerator.execute();
+
+for (var n=0; n < devices.length; n++) {
+ var device = devices[n];
+ print_device(device);
+ print("");
+}
diff --git a/src/gudev/seed-example.js b/src/gudev/seed-example.js
new file mode 100755
index 0000000000..e2ac324d23
--- /dev/null
+++ b/src/gudev/seed-example.js
@@ -0,0 +1,72 @@
+#!/usr/bin/env seed
+
+// seed example
+
+const GLib = imports.gi.GLib;
+const GUdev = imports.gi.GUdev;
+
+function print_device (device) {
+ print (" subsystem: " + device.get_subsystem ());
+ print (" devtype: " + device.get_devtype ());
+ print (" name: " + device.get_name ());
+ print (" number: " + device.get_number ());
+ print (" sysfs_path: " + device.get_sysfs_path ());
+ print (" driver: " + device.get_driver ());
+ print (" action: " + device.get_action ());
+ print (" seqnum: " + device.get_seqnum ());
+ print (" device type: " + device.get_device_type ());
+ print (" device number: " + device.get_device_number ());
+ print (" device file: " + device.get_device_file ());
+ print (" device file symlinks: " + device.get_device_file_symlinks ());
+ print (" foo: " + device.get_sysfs_attr_as_strv ("stat"));
+ var keys = device.get_property_keys ();
+ for (var n = 0; n < keys.length; n++) {
+ print (" " + keys[n] + "=" + device.get_property (keys[n]));
+ }
+}
+
+function on_uevent (client, action, device) {
+ print ("action " + action + " on device " + device.get_sysfs_path());
+ print_device (device);
+ print ("");
+}
+
+var client = new GUdev.Client ({subsystems: ["block", "usb/usb_interface"]});
+client.signal.connect ("uevent", on_uevent);
+
+var block_devices = client.query_by_subsystem ("block");
+for (var n = 0; n < block_devices.length; n++) {
+ print ("block device: " + block_devices[n].get_device_file ());
+}
+
+var d;
+
+d = client.query_by_device_number (GUdev.DeviceType.BLOCK, 0x0810);
+if (d == null) {
+ print ("query_by_device_number 0x810 -> null");
+} else {
+ print ("query_by_device_number 0x810 -> " + d.get_device_file ());
+ dd = d.get_parent_with_subsystem ("usb", null);
+ print_device (dd);
+ print ("--------------------------------------------------------------------------");
+ while (d != null) {
+ print_device (d);
+ print ("");
+ d = d.get_parent ();
+ }
+}
+
+d = client.query_by_sysfs_path ("/sys/block/sda/sda1");
+print ("query_by_sysfs_path (\"/sys/block/sda1\") -> " + d.get_device_file ());
+
+d = client.query_by_subsystem_and_name ("block", "sda2");
+print ("query_by_subsystem_and_name (\"block\", \"sda2\") -> " + d.get_device_file ());
+
+d = client.query_by_device_file ("/dev/sda");
+print ("query_by_device_file (\"/dev/sda\") -> " + d.get_device_file ());
+
+d = client.query_by_device_file ("/dev/block/8:0");
+print ("query_by_device_file (\"/dev/block/8:0\") -> " + d.get_device_file ());
+
+var mainloop = GLib.main_loop_new ();
+GLib.main_loop_run (mainloop);
diff --git a/src/hostname/hostnamectl.c b/src/hostname/hostnamectl.c
new file mode 100644
index 0000000000..064581a31c
--- /dev/null
+++ b/src/hostname/hostnamectl.c
@@ -0,0 +1,583 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdlib.h>
+#include <stdbool.h>
+#include <unistd.h>
+#include <getopt.h>
+#include <locale.h>
+#include <string.h>
+#include <sys/timex.h>
+#include <sys/utsname.h>
+
+#include "dbus-common.h"
+#include "util.h"
+#include "spawn-polkit-agent.h"
+#include "build.h"
+#include "hwclock.h"
+#include "strv.h"
+#include "sd-id128.h"
+#include "virt.h"
+#include "fileio.h"
+
+static enum transport {
+ TRANSPORT_NORMAL,
+ TRANSPORT_SSH,
+ TRANSPORT_POLKIT
+} arg_transport = TRANSPORT_NORMAL;
+static bool arg_ask_password = true;
+static const char *arg_host = NULL;
+static bool arg_set_transient = false;
+static bool arg_set_pretty = false;
+static bool arg_set_static = false;
+
+static void polkit_agent_open_if_enabled(void) {
+
+ /* Open the polkit agent as a child process if necessary */
+
+ if (!arg_ask_password)
+ return;
+
+ polkit_agent_open();
+}
+
+typedef struct StatusInfo {
+ const char *hostname;
+ const char *static_hostname;
+ const char *pretty_hostname;
+ const char *icon_name;
+ const char *chassis;
+} StatusInfo;
+
+static void print_status_info(StatusInfo *i) {
+ sd_id128_t mid, bid;
+ int r;
+ const char *id = NULL;
+ _cleanup_free_ char *pretty_name = NULL, *cpe_name = NULL;
+ struct utsname u;
+
+ assert(i);
+
+ printf(" Static hostname: %s\n",
+ strna(i->static_hostname));
+
+ if (!isempty(i->pretty_hostname) &&
+ !streq_ptr(i->pretty_hostname, i->static_hostname))
+ printf(" Pretty hostname: %s\n",
+ strna(i->pretty_hostname));
+
+ if (!isempty(i->hostname) &&
+ !streq_ptr(i->hostname, i->static_hostname))
+ printf("Transient hostname: %s\n",
+ strna(i->hostname));
+
+ printf(" Icon name: %s\n"
+ " Chassis: %s\n",
+ strna(i->icon_name),
+ strna(i->chassis));
+
+ r = sd_id128_get_machine(&mid);
+ if (r >= 0)
+ printf(" Machine ID: " SD_ID128_FORMAT_STR "\n", SD_ID128_FORMAT_VAL(mid));
+
+ r = sd_id128_get_boot(&bid);
+ if (r >= 0)
+ printf(" Boot ID: " SD_ID128_FORMAT_STR "\n", SD_ID128_FORMAT_VAL(bid));
+
+ if (detect_virtualization(&id) > 0)
+ printf(" Virtualization: %s\n", id);
+
+ r = parse_env_file("/etc/os-release", NEWLINE,
+ "PRETTY_NAME", &pretty_name,
+ "CPE_NAME", &cpe_name,
+ NULL);
+
+ if (!isempty(pretty_name))
+ printf(" Operating System: %s\n", pretty_name);
+
+ if (!isempty(cpe_name))
+ printf(" CPE OS Name: %s\n", cpe_name);
+
+ assert_se(uname(&u) >= 0);
+ printf(" Kernel: %s %s\n"
+ " Architecture: %s\n", u.sysname, u.release, u.machine);
+
+}
+
+static int status_property(const char *name, DBusMessageIter *iter, StatusInfo *i) {
+ assert(name);
+ assert(iter);
+
+ switch (dbus_message_iter_get_arg_type(iter)) {
+
+ case DBUS_TYPE_STRING: {
+ const char *s;
+
+ dbus_message_iter_get_basic(iter, &s);
+ if (!isempty(s)) {
+ if (streq(name, "Hostname"))
+ i->hostname = s;
+ if (streq(name, "StaticHostname"))
+ i->static_hostname = s;
+ if (streq(name, "PrettyHostname"))
+ i->pretty_hostname = s;
+ if (streq(name, "IconName"))
+ i->icon_name = s;
+ if (streq(name, "Chassis"))
+ i->chassis = s;
+ }
+ break;
+ }
+ }
+
+ return 0;
+}
+
+static int show_status(DBusConnection *bus, char **args, unsigned n) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ const char *interface = "";
+ int r;
+ DBusMessageIter iter, sub, sub2, sub3;
+ StatusInfo info = {};
+
+ assert(args);
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.hostname1",
+ "/org/freedesktop/hostname1",
+ "org.freedesktop.DBus.Properties",
+ "GetAll",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &interface,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+
+ if (!dbus_message_iter_init(reply, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
+ dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_recurse(&iter, &sub);
+
+ while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ const char *name;
+
+ if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_recurse(&sub, &sub2);
+
+ if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_recurse(&sub2, &sub3);
+
+ r = status_property(name, &sub3, &info);
+ if (r < 0) {
+ log_error("Failed to parse reply.");
+ return r;
+ }
+
+ dbus_message_iter_next(&sub);
+ }
+
+ print_status_info(&info);
+ return 0;
+}
+
+static int set_hostname(DBusConnection *bus, char **args, unsigned n) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ dbus_bool_t interactive = true;
+ _cleanup_free_ char *h = NULL;
+ const char *hostname = args[1];
+ int r;
+
+ assert(args);
+ assert(n == 2);
+
+ polkit_agent_open_if_enabled();
+
+ if (arg_set_pretty) {
+ const char *p;
+
+ /* If the passed hostname is already valid, then
+ * assume the user doesn't know anything about pretty
+ * hostnames, so let's unset the pretty hostname, and
+ * just set the passed hostname as static/dynamic
+ * hostname. */
+
+ h = strdup(hostname);
+ if (!h)
+ return log_oom();
+
+ hostname_cleanup(h, true);
+
+ if (arg_set_static && streq(h, hostname))
+ p = "";
+ else {
+ p = hostname;
+ hostname = h;
+ }
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.hostname1",
+ "/org/freedesktop/hostname1",
+ "org.freedesktop.hostname1",
+ "SetPrettyHostname",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &p,
+ DBUS_TYPE_BOOLEAN, &interactive,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+
+ dbus_message_unref(reply);
+ reply = NULL;
+ }
+
+ if (arg_set_static) {
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.hostname1",
+ "/org/freedesktop/hostname1",
+ "org.freedesktop.hostname1",
+ "SetStaticHostname",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &hostname,
+ DBUS_TYPE_BOOLEAN, &interactive,
+ DBUS_TYPE_INVALID);
+
+ if (r < 0)
+ return r;
+
+ dbus_message_unref(reply);
+ reply = NULL;
+ }
+
+ if (arg_set_transient) {
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.hostname1",
+ "/org/freedesktop/hostname1",
+ "org.freedesktop.hostname1",
+ "SetHostname",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &hostname,
+ DBUS_TYPE_BOOLEAN, &interactive,
+ DBUS_TYPE_INVALID);
+
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static int set_icon_name(DBusConnection *bus, char **args, unsigned n) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ dbus_bool_t interactive = true;
+
+ assert(args);
+ assert(n == 2);
+
+ polkit_agent_open_if_enabled();
+
+ return bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.hostname1",
+ "/org/freedesktop/hostname1",
+ "org.freedesktop.hostname1",
+ "SetIconName",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &args[1],
+ DBUS_TYPE_BOOLEAN, &interactive,
+ DBUS_TYPE_INVALID);
+}
+
+static int set_chassis(DBusConnection *bus, char **args, unsigned n) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ dbus_bool_t interactive = true;
+
+ assert(args);
+ assert(n == 2);
+
+ polkit_agent_open_if_enabled();
+
+ return bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.hostname1",
+ "/org/freedesktop/hostname1",
+ "org.freedesktop.hostname1",
+ "SetChassis",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &args[1],
+ DBUS_TYPE_BOOLEAN, &interactive,
+ DBUS_TYPE_INVALID);
+}
+
+static int help(void) {
+
+ printf("%s [OPTIONS...] COMMAND ...\n\n"
+ "Query or change system hostname.\n\n"
+ " -h --help Show this help\n"
+ " --version Show package version\n"
+ " --transient Only set transient hostname\n"
+ " --static Only set static hostname\n"
+ " --pretty Only set pretty hostname\n"
+ " --no-ask-password Do not prompt for password\n"
+ " -H --host=[USER@]HOST Operate on remote host\n\n"
+ "Commands:\n"
+ " status Show current hostname settings\n"
+ " set-hostname NAME Set system hostname\n"
+ " set-icon-name NAME Set icon name for host\n"
+ " set-chassis NAME Set chassis type for host\n",
+ program_invocation_short_name);
+
+ return 0;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+
+ enum {
+ ARG_VERSION = 0x100,
+ ARG_NO_ASK_PASSWORD,
+ ARG_SET_TRANSIENT,
+ ARG_SET_STATIC,
+ ARG_SET_PRETTY
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "version", no_argument, NULL, ARG_VERSION },
+ { "transient", no_argument, NULL, ARG_SET_TRANSIENT },
+ { "static", no_argument, NULL, ARG_SET_STATIC },
+ { "pretty", no_argument, NULL, ARG_SET_PRETTY },
+ { "host", required_argument, NULL, 'H' },
+ { "privileged", no_argument, NULL, 'P' },
+ { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
+ { NULL, 0, NULL, 0 }
+ };
+
+ int c;
+
+ assert(argc >= 0);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "hH:P", options, NULL)) >= 0) {
+
+ switch (c) {
+
+ case 'h':
+ help();
+ return 0;
+
+ case ARG_VERSION:
+ puts(PACKAGE_STRING);
+ puts(SYSTEMD_FEATURES);
+ return 0;
+
+ case 'P':
+ arg_transport = TRANSPORT_POLKIT;
+ break;
+
+ case 'H':
+ arg_transport = TRANSPORT_SSH;
+ arg_host = optarg;
+ break;
+
+ case ARG_SET_TRANSIENT:
+ arg_set_transient = true;
+ break;
+
+ case ARG_SET_PRETTY:
+ arg_set_pretty = true;
+ break;
+
+ case ARG_SET_STATIC:
+ arg_set_static = true;
+ break;
+
+ case ARG_NO_ASK_PASSWORD:
+ arg_ask_password = false;
+ break;
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ log_error("Unknown option code %c", c);
+ return -EINVAL;
+ }
+ }
+
+ if (!arg_set_transient && !arg_set_pretty && !arg_set_static)
+ arg_set_transient = arg_set_pretty = arg_set_static = true;
+
+ return 1;
+}
+
+static int hostnamectl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
+
+ static const struct {
+ const char* verb;
+ const enum {
+ MORE,
+ LESS,
+ EQUAL
+ } argc_cmp;
+ const int argc;
+ int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
+ } verbs[] = {
+ { "status", LESS, 1, show_status },
+ { "set-hostname", EQUAL, 2, set_hostname },
+ { "set-icon-name", EQUAL, 2, set_icon_name },
+ { "set-chassis", EQUAL, 2, set_chassis },
+ };
+
+ int left;
+ unsigned i;
+
+ assert(argc >= 0);
+ assert(argv);
+ assert(error);
+
+ left = argc - optind;
+
+ if (left <= 0)
+ /* Special rule: no arguments means "status" */
+ i = 0;
+ else {
+ if (streq(argv[optind], "help")) {
+ help();
+ return 0;
+ }
+
+ for (i = 0; i < ELEMENTSOF(verbs); i++)
+ if (streq(argv[optind], verbs[i].verb))
+ break;
+
+ if (i >= ELEMENTSOF(verbs)) {
+ log_error("Unknown operation %s", argv[optind]);
+ return -EINVAL;
+ }
+ }
+
+ switch (verbs[i].argc_cmp) {
+
+ case EQUAL:
+ if (left != verbs[i].argc) {
+ log_error("Invalid number of arguments.");
+ return -EINVAL;
+ }
+
+ break;
+
+ case MORE:
+ if (left < verbs[i].argc) {
+ log_error("Too few arguments.");
+ return -EINVAL;
+ }
+
+ break;
+
+ case LESS:
+ if (left > verbs[i].argc) {
+ log_error("Too many arguments.");
+ return -EINVAL;
+ }
+
+ break;
+
+ default:
+ assert_not_reached("Unknown comparison operator.");
+ }
+
+ if (!bus) {
+ log_error("Failed to get D-Bus connection: %s", error->message);
+ return -EIO;
+ }
+
+ return verbs[i].dispatch(bus, argv + optind, left);
+}
+
+int main(int argc, char *argv[]) {
+ int r, retval = EXIT_FAILURE;
+ DBusConnection *bus = NULL;
+ DBusError error;
+
+ dbus_error_init(&error);
+
+ setlocale(LC_ALL, "");
+ log_parse_environment();
+ log_open();
+
+ r = parse_argv(argc, argv);
+ if (r < 0)
+ goto finish;
+ else if (r == 0) {
+ retval = EXIT_SUCCESS;
+ goto finish;
+ }
+
+ if (arg_transport == TRANSPORT_NORMAL)
+ bus = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error);
+ else if (arg_transport == TRANSPORT_POLKIT)
+ bus_connect_system_polkit(&bus, &error);
+ else if (arg_transport == TRANSPORT_SSH)
+ bus_connect_system_ssh(NULL, arg_host, &bus, &error);
+ else
+ assert_not_reached("Uh, invalid transport...");
+
+ r = hostnamectl_main(bus, argc, argv, &error);
+ retval = r < 0 ? EXIT_FAILURE : r;
+
+finish:
+ if (bus) {
+ dbus_connection_flush(bus);
+ dbus_connection_close(bus);
+ dbus_connection_unref(bus);
+ }
+
+ dbus_error_free(&error);
+ dbus_shutdown();
+
+ return retval;
+}
diff --git a/src/hostname/hostnamed.c b/src/hostname/hostnamed.c
new file mode 100644
index 0000000000..0437e33a66
--- /dev/null
+++ b/src/hostname/hostnamed.c
@@ -0,0 +1,740 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <dbus/dbus.h>
+
+#include <errno.h>
+#include <string.h>
+#include <unistd.h>
+#include <dlfcn.h>
+
+#include "util.h"
+#include "strv.h"
+#include "dbus-common.h"
+#include "polkit.h"
+#include "def.h"
+#include "virt.h"
+#include "env-util.h"
+#include "fileio-label.h"
+#include "label.h"
+
+#define INTERFACE \
+ " <interface name=\"org.freedesktop.hostname1\">\n" \
+ " <property name=\"Hostname\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"StaticHostname\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"PrettyHostname\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"IconName\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"Chassis\" type=\"s\" access=\"read\"/>\n" \
+ " <method name=\"SetHostname\">\n" \
+ " <arg name=\"name\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"user_interaction\" type=\"b\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"SetStaticHostname\">\n" \
+ " <arg name=\"name\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"user_interaction\" type=\"b\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"SetPrettyHostname\">\n" \
+ " <arg name=\"name\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"user_interaction\" type=\"b\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"SetIconName\">\n" \
+ " <arg name=\"name\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"user_interaction\" type=\"b\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"SetChassis\">\n" \
+ " <arg name=\"name\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"user_interaction\" type=\"b\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " </interface>\n"
+
+#define INTROSPECTION \
+ DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE \
+ "<node>\n" \
+ INTERFACE \
+ BUS_PROPERTIES_INTERFACE \
+ BUS_INTROSPECTABLE_INTERFACE \
+ BUS_PEER_INTERFACE \
+ "</node>\n"
+
+#define INTERFACES_LIST \
+ BUS_GENERIC_INTERFACES_LIST \
+ "org.freedesktop.hostname1\0"
+
+const char hostname_interface[] _introspect_("hostname1") = INTERFACE;
+
+enum {
+ PROP_HOSTNAME,
+ PROP_STATIC_HOSTNAME,
+ PROP_PRETTY_HOSTNAME,
+ PROP_ICON_NAME,
+ PROP_CHASSIS,
+ _PROP_MAX
+};
+
+static char *data[_PROP_MAX] = {
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+};
+
+static usec_t remain_until = 0;
+
+static void free_data(void) {
+ int p;
+
+ for (p = 0; p < _PROP_MAX; p++) {
+ free(data[p]);
+ data[p] = NULL;
+ }
+}
+
+static int read_data(void) {
+ int r;
+
+ free_data();
+
+ data[PROP_HOSTNAME] = gethostname_malloc();
+ if (!data[PROP_HOSTNAME])
+ return -ENOMEM;
+
+ r = read_one_line_file("/etc/hostname", &data[PROP_STATIC_HOSTNAME]);
+ if (r < 0 && r != -ENOENT)
+ return r;
+
+ r = parse_env_file("/etc/machine-info", NEWLINE,
+ "PRETTY_HOSTNAME", &data[PROP_PRETTY_HOSTNAME],
+ "ICON_NAME", &data[PROP_ICON_NAME],
+ "CHASSIS", &data[PROP_CHASSIS],
+ NULL);
+ if (r < 0 && r != -ENOENT)
+ return r;
+
+ return 0;
+}
+
+static bool check_nss(void) {
+ void *dl;
+
+ dl = dlopen("libnss_myhostname.so.2", RTLD_LAZY);
+ if (dl) {
+ dlclose(dl);
+ return true;
+ }
+
+ return false;
+}
+
+static bool valid_chassis(const char *chassis) {
+
+ assert(chassis);
+
+ return nulstr_contains(
+ "vm\0"
+ "container\0"
+ "desktop\0"
+ "laptop\0"
+ "server\0"
+ "tablet\0"
+ "handset\0",
+ chassis);
+}
+
+static const char* fallback_chassis(void) {
+ int r;
+ char *type;
+ unsigned t;
+ Virtualization v;
+
+ v = detect_virtualization(NULL);
+
+ if (v == VIRTUALIZATION_VM)
+ return "vm";
+ if (v == VIRTUALIZATION_CONTAINER)
+ return "container";
+
+ r = read_one_line_file("/sys/firmware/acpi/pm_profile", &type);
+ if (r < 0)
+ goto try_dmi;
+
+ r = safe_atou(type, &t);
+ free(type);
+ if (r < 0)
+ goto try_dmi;
+
+ /* We only list the really obvious cases here as the ACPI data
+ * is not really super reliable.
+ *
+ * See the ACPI 5.0 Spec Section 5.2.9.1 for details:
+ *
+ * http://www.acpi.info/DOWNLOADS/ACPIspec50.pdf
+ */
+
+ switch(t) {
+
+ case 1:
+ case 3:
+ case 6:
+ return "desktop";
+
+ case 2:
+ return "laptop";
+
+ case 4:
+ case 5:
+ case 7:
+ return "server";
+
+ case 8:
+ return "tablet";
+ }
+
+try_dmi:
+ r = read_one_line_file("/sys/class/dmi/id/chassis_type", &type);
+ if (r < 0)
+ return NULL;
+
+ r = safe_atou(type, &t);
+ free(type);
+ if (r < 0)
+ return NULL;
+
+ /* We only list the really obvious cases here. The DMI data is
+ unreliable enough, so let's not do any additional guesswork
+ on top of that.
+
+ See the SMBIOS Specification 2.7.1 section 7.4.1 for
+ details about the values listed here:
+
+ http://www.dmtf.org/sites/default/files/standards/documents/DSP0134_2.7.1.pdf
+ */
+
+ switch (t) {
+
+ case 0x3:
+ case 0x4:
+ case 0x6:
+ case 0x7:
+ return "desktop";
+
+ case 0x8:
+ case 0x9:
+ case 0xA:
+ case 0xE:
+ return "laptop";
+
+ case 0xB:
+ return "handset";
+
+ case 0x11:
+ case 0x1C:
+ return "server";
+ }
+
+ return NULL;
+}
+
+static char* fallback_icon_name(void) {
+ const char *chassis;
+
+ if (!isempty(data[PROP_CHASSIS]))
+ return strappend("computer-", data[PROP_CHASSIS]);
+
+ chassis = fallback_chassis();
+ if (chassis)
+ return strappend("computer-", chassis);
+
+ return strdup("computer");
+}
+
+static int write_data_hostname(void) {
+ const char *hn;
+
+ if (isempty(data[PROP_HOSTNAME]))
+ hn = "localhost";
+ else
+ hn = data[PROP_HOSTNAME];
+
+ if (sethostname(hn, strlen(hn)) < 0)
+ return -errno;
+
+ return 0;
+}
+
+static int write_data_static_hostname(void) {
+
+ if (isempty(data[PROP_STATIC_HOSTNAME])) {
+
+ if (unlink("/etc/hostname") < 0)
+ return errno == ENOENT ? 0 : -errno;
+
+ return 0;
+ }
+ return write_string_file_atomic_label("/etc/hostname", data[PROP_STATIC_HOSTNAME]);
+}
+
+static int write_data_other(void) {
+
+ static const char * const name[_PROP_MAX] = {
+ [PROP_PRETTY_HOSTNAME] = "PRETTY_HOSTNAME",
+ [PROP_ICON_NAME] = "ICON_NAME",
+ [PROP_CHASSIS] = "CHASSIS"
+ };
+
+ char **l = NULL;
+ int r, p;
+
+ r = load_env_file("/etc/machine-info", NULL, &l);
+ if (r < 0 && r != -ENOENT)
+ return r;
+
+ for (p = 2; p < _PROP_MAX; p++) {
+ char *t, **u;
+
+ assert(name[p]);
+
+ if (isempty(data[p])) {
+ strv_env_unset(l, name[p]);
+ continue;
+ }
+
+ if (asprintf(&t, "%s=%s", name[p], strempty(data[p])) < 0) {
+ strv_free(l);
+ return -ENOMEM;
+ }
+
+ u = strv_env_set(l, t);
+ free(t);
+ strv_free(l);
+
+ if (!u)
+ return -ENOMEM;
+ l = u;
+ }
+
+ if (strv_isempty(l)) {
+
+ if (unlink("/etc/machine-info") < 0)
+ return errno == ENOENT ? 0 : -errno;
+
+ return 0;
+ }
+
+ r = write_env_file_label("/etc/machine-info", l);
+ strv_free(l);
+
+ return r;
+}
+
+static int bus_hostname_append_icon_name(DBusMessageIter *i, const char *property, void *userdata) {
+ const char *name;
+ _cleanup_free_ char *n = NULL;
+
+ assert(i);
+ assert(property);
+
+ if (isempty(data[PROP_ICON_NAME]))
+ name = n = fallback_icon_name();
+ else
+ name = data[PROP_ICON_NAME];
+
+ return bus_property_append_string(i, property, (void*) name);
+}
+
+static int bus_hostname_append_chassis(DBusMessageIter *i, const char *property, void *userdata) {
+ const char *name;
+
+ assert(i);
+ assert(property);
+
+ if (isempty(data[PROP_CHASSIS]))
+ name = fallback_chassis();
+ else
+ name = data[PROP_CHASSIS];
+
+ return bus_property_append_string(i, property, (void*) name);
+}
+
+static const BusProperty bus_hostname_properties[] = {
+ { "Hostname", bus_property_append_string, "s", sizeof(data[0])*PROP_HOSTNAME, true },
+ { "StaticHostname", bus_property_append_string, "s", sizeof(data[0])*PROP_STATIC_HOSTNAME, true },
+ { "PrettyHostname", bus_property_append_string, "s", sizeof(data[0])*PROP_PRETTY_HOSTNAME, true },
+ { "IconName", bus_hostname_append_icon_name, "s", sizeof(data[0])*PROP_ICON_NAME, true },
+ { "Chassis", bus_hostname_append_chassis, "s", sizeof(data[0])*PROP_CHASSIS, true },
+ { NULL, }
+};
+
+static const BusBoundProperties bps[] = {
+ { "org.freedesktop.hostname1", bus_hostname_properties, data },
+ { NULL, }
+};
+
+static DBusHandlerResult hostname_message_handler(
+ DBusConnection *connection,
+ DBusMessage *message,
+ void *userdata) {
+
+
+ DBusMessage *reply = NULL, *changed = NULL;
+ DBusError error;
+ int r;
+
+ assert(connection);
+ assert(message);
+
+ dbus_error_init(&error);
+
+ if (dbus_message_is_method_call(message, "org.freedesktop.hostname1", "SetHostname")) {
+ const char *name;
+ dbus_bool_t interactive;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_BOOLEAN, &interactive,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ if (isempty(name))
+ name = data[PROP_STATIC_HOSTNAME];
+
+ if (isempty(name))
+ name = "localhost";
+
+ if (!hostname_is_valid(name))
+ return bus_send_error_reply(connection, message, NULL, -EINVAL);
+
+ if (!streq_ptr(name, data[PROP_HOSTNAME])) {
+ char *h;
+
+ r = verify_polkit(connection, message, "org.freedesktop.hostname1.set-hostname", interactive, NULL, &error);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ h = strdup(name);
+ if (!h)
+ goto oom;
+
+ free(data[PROP_HOSTNAME]);
+ data[PROP_HOSTNAME] = h;
+
+ r = write_data_hostname();
+ if (r < 0) {
+ log_error("Failed to set host name: %s", strerror(-r));
+ return bus_send_error_reply(connection, message, NULL, r);
+ }
+
+ log_info("Changed host name to '%s'", strna(data[PROP_HOSTNAME]));
+
+ changed = bus_properties_changed_new(
+ "/org/freedesktop/hostname1",
+ "org.freedesktop.hostname1",
+ "Hostname\0");
+ if (!changed)
+ goto oom;
+ }
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.hostname1", "SetStaticHostname")) {
+ const char *name;
+ dbus_bool_t interactive;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_BOOLEAN, &interactive,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ if (isempty(name))
+ name = NULL;
+
+ if (!streq_ptr(name, data[PROP_STATIC_HOSTNAME])) {
+
+ r = verify_polkit(connection, message, "org.freedesktop.hostname1.set-static-hostname", interactive, NULL, &error);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ if (isempty(name)) {
+ free(data[PROP_STATIC_HOSTNAME]);
+ data[PROP_STATIC_HOSTNAME] = NULL;
+ } else {
+ char *h;
+
+ if (!hostname_is_valid(name))
+ return bus_send_error_reply(connection, message, NULL, -EINVAL);
+
+ h = strdup(name);
+ if (!h)
+ goto oom;
+
+ free(data[PROP_STATIC_HOSTNAME]);
+ data[PROP_STATIC_HOSTNAME] = h;
+ }
+
+ r = write_data_static_hostname();
+ if (r < 0) {
+ log_error("Failed to write static host name: %s", strerror(-r));
+ return bus_send_error_reply(connection, message, NULL, r);
+ }
+
+ log_info("Changed static host name to '%s'", strna(data[PROP_STATIC_HOSTNAME]));
+
+ changed = bus_properties_changed_new(
+ "/org/freedesktop/hostname1",
+ "org.freedesktop.hostname1",
+ "StaticHostname\0");
+ if (!changed)
+ goto oom;
+ }
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.hostname1", "SetPrettyHostname") ||
+ dbus_message_is_method_call(message, "org.freedesktop.hostname1", "SetIconName") ||
+ dbus_message_is_method_call(message, "org.freedesktop.hostname1", "SetChassis")) {
+
+ const char *name;
+ dbus_bool_t interactive;
+ int k;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_BOOLEAN, &interactive,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ if (isempty(name))
+ name = NULL;
+
+ k = streq(dbus_message_get_member(message), "SetPrettyHostname") ? PROP_PRETTY_HOSTNAME :
+ streq(dbus_message_get_member(message), "SetChassis") ? PROP_CHASSIS : PROP_ICON_NAME;
+
+ if (!streq_ptr(name, data[k])) {
+
+ /* Since the pretty hostname should always be
+ * changed at the same time as the static one,
+ * use the same policy action for both... */
+
+ r = verify_polkit(connection, message, k == PROP_PRETTY_HOSTNAME ?
+ "org.freedesktop.hostname1.set-static-hostname" :
+ "org.freedesktop.hostname1.set-machine-info", interactive, NULL, &error);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ if (isempty(name)) {
+ free(data[k]);
+ data[k] = NULL;
+ } else {
+ char *h;
+
+ /* The icon name might ultimately be
+ * used as file name, so better be
+ * safe than sorry */
+ if (k == PROP_ICON_NAME && !filename_is_safe(name))
+ return bus_send_error_reply(connection, message, NULL, -EINVAL);
+ if (k == PROP_PRETTY_HOSTNAME && string_has_cc(name))
+ return bus_send_error_reply(connection, message, NULL, -EINVAL);
+ if (k == PROP_CHASSIS && !valid_chassis(name))
+ return bus_send_error_reply(connection, message, NULL, -EINVAL);
+
+ h = strdup(name);
+ if (!h)
+ goto oom;
+
+ free(data[k]);
+ data[k] = h;
+ }
+
+ r = write_data_other();
+ if (r < 0) {
+ log_error("Failed to write machine info: %s", strerror(-r));
+ return bus_send_error_reply(connection, message, NULL, r);
+ }
+
+ log_info("Changed %s to '%s'",
+ k == PROP_PRETTY_HOSTNAME ? "pretty host name" :
+ k == PROP_CHASSIS ? "chassis" : "icon name", strna(data[k]));
+
+ changed = bus_properties_changed_new(
+ "/org/freedesktop/hostname1",
+ "org.freedesktop.hostname1",
+ k == PROP_PRETTY_HOSTNAME ? "PrettyHostname\0" :
+ k == PROP_CHASSIS ? "Chassis\0" : "IconName\0");
+ if (!changed)
+ goto oom;
+ }
+
+ } else
+ return bus_default_message_handler(connection, message, INTROSPECTION, INTERFACES_LIST, bps);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ if (!bus_maybe_send_reply(connection, message, reply))
+ goto oom;
+
+ dbus_message_unref(reply);
+ reply = NULL;
+
+ if (changed) {
+
+ if (!dbus_connection_send(connection, changed, NULL))
+ goto oom;
+
+ dbus_message_unref(changed);
+ }
+
+ return DBUS_HANDLER_RESULT_HANDLED;
+
+oom:
+ if (reply)
+ dbus_message_unref(reply);
+
+ if (changed)
+ dbus_message_unref(changed);
+
+ dbus_error_free(&error);
+
+ return DBUS_HANDLER_RESULT_NEED_MEMORY;
+}
+
+static int connect_bus(DBusConnection **_bus) {
+ static const DBusObjectPathVTable hostname_vtable = {
+ .message_function = hostname_message_handler
+ };
+ DBusError error;
+ DBusConnection *bus = NULL;
+ int r;
+
+ assert(_bus);
+
+ dbus_error_init(&error);
+
+ bus = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error);
+ if (!bus) {
+ log_error("Failed to get system D-Bus connection: %s", bus_error_message(&error));
+ r = -ECONNREFUSED;
+ goto fail;
+ }
+
+ dbus_connection_set_exit_on_disconnect(bus, FALSE);
+
+ if (!dbus_connection_register_object_path(bus, "/org/freedesktop/hostname1", &hostname_vtable, NULL) ||
+ !dbus_connection_add_filter(bus, bus_exit_idle_filter, &remain_until, NULL)) {
+ r = log_oom();
+ goto fail;
+ }
+
+ r = dbus_bus_request_name(bus, "org.freedesktop.hostname1", DBUS_NAME_FLAG_DO_NOT_QUEUE, &error);
+ if (dbus_error_is_set(&error)) {
+ log_error("Failed to register name on bus: %s", bus_error_message(&error));
+ r = -EEXIST;
+ goto fail;
+ }
+
+ if (r != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) {
+ log_error("Failed to acquire name.");
+ r = -EEXIST;
+ goto fail;
+ }
+
+ if (_bus)
+ *_bus = bus;
+
+ return 0;
+
+fail:
+ dbus_connection_close(bus);
+ dbus_connection_unref(bus);
+
+ dbus_error_free(&error);
+
+ return r;
+}
+
+int main(int argc, char *argv[]) {
+ int r;
+ DBusConnection *bus = NULL;
+ bool exiting = false;
+
+ log_set_target(LOG_TARGET_AUTO);
+ log_parse_environment();
+ log_open();
+
+ umask(0022);
+ label_init("/etc");
+
+ if (argc == 2 && streq(argv[1], "--introspect")) {
+ fputs(DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE
+ "<node>\n", stdout);
+ fputs(hostname_interface, stdout);
+ fputs("</node>\n", stdout);
+ return 0;
+ }
+
+ if (argc != 1) {
+ log_error("This program takes no arguments.");
+ r = -EINVAL;
+ goto finish;
+ }
+
+ if (!check_nss())
+ log_warning("Warning: nss-myhostname is not installed. Changing the local hostname might make it unresolveable. Please install nss-myhostname!");
+
+ r = read_data();
+ if (r < 0) {
+ log_error("Failed to read hostname data: %s", strerror(-r));
+ goto finish;
+ }
+
+ r = connect_bus(&bus);
+ if (r < 0)
+ goto finish;
+
+ remain_until = now(CLOCK_MONOTONIC) + DEFAULT_EXIT_USEC;
+ for (;;) {
+
+ if (!dbus_connection_read_write_dispatch(bus, exiting ? -1 : (int) (DEFAULT_EXIT_USEC/USEC_PER_MSEC)))
+ break;
+
+ if (!exiting && remain_until < now(CLOCK_MONOTONIC)) {
+ exiting = true;
+ bus_async_unregister_and_exit(bus, "org.freedesktop.hostname1");
+ }
+ }
+
+ r = 0;
+
+finish:
+ free_data();
+
+ if (bus) {
+ dbus_connection_flush(bus);
+ dbus_connection_close(bus);
+ dbus_connection_unref(bus);
+ }
+
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/src/hostname/org.freedesktop.hostname1.conf b/src/hostname/org.freedesktop.hostname1.conf
new file mode 100644
index 0000000000..46b4aadc83
--- /dev/null
+++ b/src/hostname/org.freedesktop.hostname1.conf
@@ -0,0 +1,27 @@
+<?xml version="1.0"?> <!--*-nxml-*-->
+<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
+ "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
+
+<!--
+ This file is part of systemd.
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+-->
+
+<busconfig>
+
+ <policy user="root">
+ <allow own="org.freedesktop.hostname1"/>
+ <allow send_destination="org.freedesktop.hostname1"/>
+ <allow receive_sender="org.freedesktop.hostname1"/>
+ </policy>
+
+ <policy context="default">
+ <allow send_destination="org.freedesktop.hostname1"/>
+ <allow receive_sender="org.freedesktop.hostname1"/>
+ </policy>
+
+</busconfig>
diff --git a/src/hostname/org.freedesktop.hostname1.policy.in b/src/hostname/org.freedesktop.hostname1.policy.in
new file mode 100644
index 0000000000..c32c1d4fda
--- /dev/null
+++ b/src/hostname/org.freedesktop.hostname1.policy.in
@@ -0,0 +1,50 @@
+<?xml version="1.0" encoding="UTF-8"?> <!--*-nxml-*-->
+<!DOCTYPE policyconfig PUBLIC "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
+ "http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd">
+
+<!--
+ This file is part of systemd.
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+-->
+
+<policyconfig>
+
+ <vendor>The systemd Project</vendor>
+ <vendor_url>http://www.freedesktop.org/wiki/Software/systemd</vendor_url>
+
+ <action id="org.freedesktop.hostname1.set-hostname">
+ <_description>Set host name</_description>
+ <_message>Authentication is required to set the local host name.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ </action>
+
+ <action id="org.freedesktop.hostname1.set-static-hostname">
+ <_description>Set static host name</_description>
+ <_message>Authentication is required to set the statically configured local host name, as well as the pretty host name.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.hostname1.set-hostname org.freedesktop.hostname1.set-machine-info</annotate>
+ </action>
+
+ <action id="org.freedesktop.hostname1.set-machine-info">
+ <_description>Set machine information</_description>
+ <_message>Authentication is required to set local machine information.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ </action>
+
+</policyconfig>
diff --git a/src/hostname/org.freedesktop.hostname1.service b/src/hostname/org.freedesktop.hostname1.service
new file mode 100644
index 0000000000..6041ed60ca
--- /dev/null
+++ b/src/hostname/org.freedesktop.hostname1.service
@@ -0,0 +1,12 @@
+# This file is part of systemd.
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 of the License, or
+# (at your option) any later version.
+
+[D-BUS Service]
+Name=org.freedesktop.hostname1
+Exec=/bin/false
+User=root
+SystemdService=dbus-org.freedesktop.hostname1.service
diff --git a/src/initctl/initctl.c b/src/initctl/initctl.c
new file mode 100644
index 0000000000..735f1e1450
--- /dev/null
+++ b/src/initctl/initctl.c
@@ -0,0 +1,459 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <assert.h>
+#include <time.h>
+#include <string.h>
+#include <stdio.h>
+#include <errno.h>
+#include <unistd.h>
+#include <sys/poll.h>
+#include <sys/epoll.h>
+#include <sys/un.h>
+#include <fcntl.h>
+#include <ctype.h>
+
+#include <dbus/dbus.h>
+#include <systemd/sd-daemon.h>
+
+#include "util.h"
+#include "log.h"
+#include "list.h"
+#include "initreq.h"
+#include "special.h"
+#include "dbus-common.h"
+#include "def.h"
+
+#define SERVER_FD_MAX 16
+#define TIMEOUT_MSEC ((int) (DEFAULT_EXIT_USEC/USEC_PER_MSEC))
+
+typedef struct Fifo Fifo;
+
+typedef struct Server {
+ int epoll_fd;
+
+ LIST_HEAD(Fifo, fifos);
+ unsigned n_fifos;
+
+ DBusConnection *bus;
+
+ bool quit;
+} Server;
+
+struct Fifo {
+ Server *server;
+
+ int fd;
+
+ struct init_request buffer;
+ size_t bytes_read;
+
+ LIST_FIELDS(Fifo, fifo);
+};
+
+static const char *translate_runlevel(int runlevel, bool *isolate) {
+ static const struct {
+ const int runlevel;
+ const char *special;
+ bool isolate;
+ } table[] = {
+ { '0', SPECIAL_POWEROFF_TARGET, false },
+ { '1', SPECIAL_RESCUE_TARGET, true },
+ { 's', SPECIAL_RESCUE_TARGET, true },
+ { 'S', SPECIAL_RESCUE_TARGET, true },
+ { '2', SPECIAL_RUNLEVEL2_TARGET, true },
+ { '3', SPECIAL_RUNLEVEL3_TARGET, true },
+ { '4', SPECIAL_RUNLEVEL4_TARGET, true },
+ { '5', SPECIAL_RUNLEVEL5_TARGET, true },
+ { '6', SPECIAL_REBOOT_TARGET, false },
+ };
+
+ unsigned i;
+
+ assert(isolate);
+
+ for (i = 0; i < ELEMENTSOF(table); i++)
+ if (table[i].runlevel == runlevel) {
+ *isolate = table[i].isolate;
+ if (runlevel == '6' && kexec_loaded())
+ return SPECIAL_KEXEC_TARGET;
+ return table[i].special;
+ }
+
+ return NULL;
+}
+
+static void change_runlevel(Server *s, int runlevel) {
+ const char *target;
+ DBusMessage *m = NULL, *reply = NULL;
+ DBusError error;
+ const char *mode;
+ bool isolate = false;
+
+ assert(s);
+
+ dbus_error_init(&error);
+
+ if (!(target = translate_runlevel(runlevel, &isolate))) {
+ log_warning("Got request for unknown runlevel %c, ignoring.", runlevel);
+ goto finish;
+ }
+
+ if (isolate)
+ mode = "isolate";
+ else
+ mode = "replace";
+
+ log_debug("Running request %s/start/%s", target, mode);
+
+ if (!(m = dbus_message_new_method_call("org.freedesktop.systemd1", "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager", "StartUnit"))) {
+ log_error("Could not allocate message.");
+ goto finish;
+ }
+
+ if (!dbus_message_append_args(m,
+ DBUS_TYPE_STRING, &target,
+ DBUS_TYPE_STRING, &mode,
+ DBUS_TYPE_INVALID)) {
+ log_error("Could not attach target and flag information to message.");
+ goto finish;
+ }
+
+ if (!(reply = dbus_connection_send_with_reply_and_block(s->bus, m, -1, &error))) {
+ log_error("Failed to start unit: %s", bus_error_message(&error));
+ goto finish;
+ }
+
+finish:
+ if (m)
+ dbus_message_unref(m);
+
+ if (reply)
+ dbus_message_unref(reply);
+
+ dbus_error_free(&error);
+}
+
+static void request_process(Server *s, const struct init_request *req) {
+ assert(s);
+ assert(req);
+
+ if (req->magic != INIT_MAGIC) {
+ log_error("Got initctl request with invalid magic. Ignoring.");
+ return;
+ }
+
+ switch (req->cmd) {
+
+ case INIT_CMD_RUNLVL:
+ if (!isprint(req->runlevel))
+ log_error("Got invalid runlevel. Ignoring.");
+ else
+ switch (req->runlevel) {
+
+ /* we are async anyway, so just use kill for reexec/reload */
+ case 'u':
+ case 'U':
+ if (kill(1, SIGTERM) < 0)
+ log_error("kill() failed: %m");
+
+ /* The bus connection will be
+ * terminated if PID 1 is reexecuted,
+ * hence let's just exit here, and
+ * rely on that we'll be restarted on
+ * the next request */
+ s->quit = true;
+ break;
+
+ case 'q':
+ case 'Q':
+ if (kill(1, SIGHUP) < 0)
+ log_error("kill() failed: %m");
+ break;
+
+ default:
+ change_runlevel(s, req->runlevel);
+ }
+ return;
+
+ case INIT_CMD_POWERFAIL:
+ case INIT_CMD_POWERFAILNOW:
+ case INIT_CMD_POWEROK:
+ log_warning("Received UPS/power initctl request. This is not implemented in systemd. Upgrade your UPS daemon!");
+ return;
+
+ case INIT_CMD_CHANGECONS:
+ log_warning("Received console change initctl request. This is not implemented in systemd.");
+ return;
+
+ case INIT_CMD_SETENV:
+ case INIT_CMD_UNSETENV:
+ log_warning("Received environment initctl request. This is not implemented in systemd.");
+ return;
+
+ default:
+ log_warning("Received unknown initctl request. Ignoring.");
+ return;
+ }
+}
+
+static int fifo_process(Fifo *f) {
+ ssize_t l;
+
+ assert(f);
+
+ errno = EIO;
+ if ((l = read(f->fd, ((uint8_t*) &f->buffer) + f->bytes_read, sizeof(f->buffer) - f->bytes_read)) <= 0) {
+
+ if (errno == EAGAIN)
+ return 0;
+
+ log_warning("Failed to read from fifo: %s", strerror(errno));
+ return -1;
+ }
+
+ f->bytes_read += l;
+ assert(f->bytes_read <= sizeof(f->buffer));
+
+ if (f->bytes_read == sizeof(f->buffer)) {
+ request_process(f->server, &f->buffer);
+ f->bytes_read = 0;
+ }
+
+ return 0;
+}
+
+static void fifo_free(Fifo *f) {
+ assert(f);
+
+ if (f->server) {
+ assert(f->server->n_fifos > 0);
+ f->server->n_fifos--;
+ LIST_REMOVE(Fifo, fifo, f->server->fifos, f);
+ }
+
+ if (f->fd >= 0) {
+ if (f->server)
+ epoll_ctl(f->server->epoll_fd, EPOLL_CTL_DEL, f->fd, NULL);
+
+ close_nointr_nofail(f->fd);
+ }
+
+ free(f);
+}
+
+static void server_done(Server *s) {
+ assert(s);
+
+ while (s->fifos)
+ fifo_free(s->fifos);
+
+ if (s->epoll_fd >= 0)
+ close_nointr_nofail(s->epoll_fd);
+
+ if (s->bus) {
+ dbus_connection_flush(s->bus);
+ dbus_connection_close(s->bus);
+ dbus_connection_unref(s->bus);
+ }
+}
+
+static int server_init(Server *s, unsigned n_sockets) {
+ int r;
+ unsigned i;
+ DBusError error;
+
+ assert(s);
+ assert(n_sockets > 0);
+
+ dbus_error_init(&error);
+
+ zero(*s);
+
+ s->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
+ if (s->epoll_fd < 0) {
+ r = -errno;
+ log_error("Failed to create epoll object: %s", strerror(errno));
+ goto fail;
+ }
+
+ for (i = 0; i < n_sockets; i++) {
+ struct epoll_event ev;
+ Fifo *f;
+ int fd;
+
+ fd = SD_LISTEN_FDS_START+i;
+
+ r = sd_is_fifo(fd, NULL);
+ if (r < 0) {
+ log_error("Failed to determine file descriptor type: %s",
+ strerror(-r));
+ goto fail;
+ }
+
+ if (!r) {
+ log_error("Wrong file descriptor type.");
+ r = -EINVAL;
+ goto fail;
+ }
+
+ f = new0(Fifo, 1);
+ if (!f) {
+ r = -ENOMEM;
+ log_error("Failed to create fifo object: %s",
+ strerror(errno));
+ goto fail;
+ }
+
+ f->fd = -1;
+
+ zero(ev);
+ ev.events = EPOLLIN;
+ ev.data.ptr = f;
+ if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
+ r = -errno;
+ fifo_free(f);
+ log_error("Failed to add fifo fd to epoll object: %s",
+ strerror(errno));
+ goto fail;
+ }
+
+ f->fd = fd;
+ LIST_PREPEND(Fifo, fifo, s->fifos, f);
+ f->server = s;
+ s->n_fifos ++;
+ }
+
+ if (bus_connect(DBUS_BUS_SYSTEM, &s->bus, NULL, &error) < 0) {
+ log_error("Failed to get D-Bus connection: %s",
+ bus_error_message(&error));
+ r = -EIO;
+ goto fail;
+ }
+
+ return 0;
+
+fail:
+ server_done(s);
+
+ dbus_error_free(&error);
+ return r;
+}
+
+static int process_event(Server *s, struct epoll_event *ev) {
+ int r;
+ Fifo *f;
+
+ assert(s);
+
+ if (!(ev->events & EPOLLIN)) {
+ log_info("Got invalid event from epoll. (3)");
+ return -EIO;
+ }
+
+ f = (Fifo*) ev->data.ptr;
+
+ if ((r = fifo_process(f)) < 0) {
+ log_info("Got error on fifo: %s", strerror(-r));
+ fifo_free(f);
+ return r;
+ }
+
+ return 0;
+}
+
+int main(int argc, char *argv[]) {
+ Server server;
+ int r = EXIT_FAILURE, n;
+
+ if (getppid() != 1) {
+ log_error("This program should be invoked by init only.");
+ return EXIT_FAILURE;
+ }
+
+ if (argc > 1) {
+ log_error("This program does not take arguments.");
+ return EXIT_FAILURE;
+ }
+
+ log_set_target(LOG_TARGET_AUTO);
+ log_parse_environment();
+ log_open();
+
+ umask(0022);
+
+ if ((n = sd_listen_fds(true)) < 0) {
+ log_error("Failed to read listening file descriptors from environment: %s", strerror(-r));
+ return EXIT_FAILURE;
+ }
+
+ if (n <= 0 || n > SERVER_FD_MAX) {
+ log_error("No or too many file descriptors passed.");
+ return EXIT_FAILURE;
+ }
+
+ if (server_init(&server, (unsigned) n) < 0)
+ return EXIT_FAILURE;
+
+ log_debug("systemd-initctl running as pid %lu", (unsigned long) getpid());
+
+ sd_notify(false,
+ "READY=1\n"
+ "STATUS=Processing requests...");
+
+ while (!server.quit) {
+ struct epoll_event event;
+ int k;
+
+ if ((k = epoll_wait(server.epoll_fd,
+ &event, 1,
+ TIMEOUT_MSEC)) < 0) {
+
+ if (errno == EINTR)
+ continue;
+
+ log_error("epoll_wait() failed: %s", strerror(errno));
+ goto fail;
+ }
+
+ if (k <= 0)
+ break;
+
+ if (process_event(&server, &event) < 0)
+ goto fail;
+ }
+
+ r = EXIT_SUCCESS;
+
+ log_debug("systemd-initctl stopped as pid %lu", (unsigned long) getpid());
+
+fail:
+ sd_notify(false,
+ "STATUS=Shutting down...");
+
+ server_done(&server);
+
+ dbus_shutdown();
+
+ return r;
+}
diff --git a/src/journal/browse.html b/src/journal/browse.html
new file mode 100644
index 0000000000..3594f70c87
--- /dev/null
+++ b/src/journal/browse.html
@@ -0,0 +1,544 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>Journal</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
+ <style type="text/css">
+ div#divlogs, div#diventry {
+ font-family: monospace;
+ font-size: 7pt;
+ background-color: #ffffff;
+ padding: 1em;
+ margin: 2em 0em;
+ border-radius: 10px 10px 10px 10px;
+ border: 1px solid threedshadow;
+ white-space: nowrap;
+ overflow-x: scroll;
+ }
+ div#diventry {
+ display: none;
+ }
+ div#divlogs {
+ display: block;
+ }
+ body {
+ background-color: #ededed;
+ color: #313739;
+ font: message-box;
+ margin: 3em;
+ }
+ td.timestamp {
+ text-align: right;
+ border-right: 1px dotted lightgrey;
+ padding-right: 5px;
+ }
+ td.process {
+ border-right: 1px dotted lightgrey;
+ padding-left: 5px;
+ padding-right: 5px;
+ }
+ td.message {
+ padding-left: 5px;
+ }
+ td.message > a:link, td.message > a:visited {
+ text-decoration: none;
+ color: #313739;
+ }
+ td.message-error {
+ padding-left: 5px;
+ color: red;
+ font-weight: bold;
+ }
+ td.message-error > a:link, td.message-error > a:visited {
+ text-decoration: none;
+ color: red;
+ }
+ td.message-highlight {
+ padding-left: 5px;
+ font-weight: bold;
+ }
+ td.message-highlight > a:link, td.message-highlight > a:visited {
+ text-decoration: none;
+ color: #313739;
+ }
+ td > a:hover, td > a:active {
+ text-decoration: underline;
+ color: #c13739;
+ }
+ table#tablelogs, table#tableentry {
+ border-collapse: collapse;
+ }
+ td.field {
+ text-align: right;
+ border-right: 1px dotted lightgrey;
+ padding-right: 5px;
+ }
+ td.data {
+ padding-left: 5px;
+ }
+ div#keynav {
+ text-align: center;
+ font-size: 7pt;
+ color: #818789;
+ padding-top: 2em;
+ }
+ span.key {
+ font-weight: bold;
+ color: #313739;
+ }
+ div#buttonnav {
+ text-align: center;
+ }
+ button {
+ font-size: 18pt;
+ font-weight: bold;
+ width: 2em;
+ height: 2em;
+ }
+ div#filternav {
+ text-align: center;
+ }
+ select {
+ width: 50em;
+ }
+ </style>
+</head>
+
+<body>
+ <!-- TODO:
+ - live display
+ - show red lines for reboots -->
+
+ <h1 id="title"></h1>
+
+ <div id="os"></div>
+ <div id="virtualization"></div>
+ <div id="cutoff"></div>
+ <div id="machine"></div>
+ <div id="usage"></div>
+ <div id="showing"></div>
+
+ <div id="filternav">
+ <select id="filter" onchange="onFilterChange(this);" onfocus="onFilterFocus(this);">
+ <option>No filter</option>
+ </select>
+ &nbsp;&nbsp;&nbsp;&nbsp;
+ <input id="boot" type="checkbox" onchange="onBootChange(this);">Only current boot</input>
+ </div>
+
+ <div id="divlogs"><table id="tablelogs"></table></div>
+ <a name="entry"></a>
+ <div id="diventry"><table id="tableentry"></table></div>
+
+ <div id="buttonnav">
+ <button id="head" onclick="entriesLoadHead();" title="First Page">&#8676;</button>
+ <button id="previous" type="button" onclick="entriesLoadPrevious();" title="Previous Page"/>&#8592;</button>
+ <button id="next" type="button" onclick="entriesLoadNext();" title="Next Page"/>&#8594;</button>
+ <button id="tail" type="button" onclick="entriesLoadTail();" title="Last Page"/>&#8677;</button>
+ &nbsp;&nbsp;&nbsp;&nbsp;
+ <button id="more" type="button" onclick="entriesMore();" title="More Entries"/>+</button>
+ <button id="less" type="button" onclick="entriesLess();" title="Fewer Entries"/>-</button>
+ </div>
+
+ <div id="keynav">
+ <span class="key">g</span>: First Page &nbsp;&nbsp;&nbsp;&nbsp;
+ <span class="key">&#8592;, k, BACKSPACE</span>: Previous Page &nbsp;&nbsp;&nbsp;&nbsp;
+ <span class="key">&#8594;, j, SPACE</span>: Next Page &nbsp;&nbsp;&nbsp;&nbsp;
+ <span class="key">G</span>: Last Page &nbsp;&nbsp;&nbsp;&nbsp;
+ <span class="key">+</span>: More entries &nbsp;&nbsp;&nbsp;&nbsp;
+ <span class="key">-</span>: Fewer entries
+ </div>
+
+ <script type="text/javascript">
+ var first_cursor = null;
+ var last_cursor = null;
+
+ function getNEntries() {
+ var n;
+ n = localStorage["n_entries"];
+ if (n == null)
+ return 50;
+ n = parseInt(n);
+ if (n < 10)
+ return 10;
+ if (n > 1000)
+ return 1000;
+ return n;
+ }
+
+ function showNEntries(n) {
+ var showing = document.getElementById("showing");
+ showing.innerHTML = "Showing <b>" + n.toString() + "</b> entries.";
+ }
+
+ function setNEntries(n) {
+ if (n < 10)
+ return 10;
+ if (n > 1000)
+ return 1000;
+ localStorage["n_entries"] = n.toString();
+ showNEntries(n);
+ }
+
+ function machineLoad() {
+ var request = new XMLHttpRequest();
+ request.open("GET", "/machine");
+ request.onreadystatechange = machineOnResult;
+ request.setRequestHeader("Accept", "application/json");
+ request.send(null);
+ }
+
+ function formatBytes(u) {
+ if (u >= 1024*1024*1024*1024)
+ return (u/1024/1024/1024/1024).toFixed(1) + " TiB";
+ else if (u >= 1024*1024*1024)
+ return (u/1024/1024/1024).toFixed(1) + " GiB";
+ else if (u >= 1024*1024)
+ return (u/1024/1024).toFixed(1) + " MiB";
+ else if (u >= 1024)
+ return (u/1024).toFixed(1) + " KiB";
+ else
+ return u.toString() + " B";
+ }
+
+ function escapeHTML(s) {
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
+ }
+
+ function machineOnResult(event) {
+ if ((event.currentTarget.readyState != 4) ||
+ (event.currentTarget.status != 200 && event.currentTarget.status != 0))
+ return;
+
+ var d = JSON.parse(event.currentTarget.responseText);
+
+ var title = document.getElementById("title");
+ title.innerHTML = 'Journal of ' + escapeHTML(d.hostname);
+ document.title = 'Journal of ' + escapeHTML(d.hostname);
+
+ var machine = document.getElementById("machine");
+ machine.innerHTML = 'Machine ID is <b>' + d.machine_id + '</b>, current boot ID is <b>' + d.boot_id + '</b>.';
+
+ var cutoff = document.getElementById("cutoff");
+ var from = new Date(parseInt(d.cutoff_from_realtime) / 1000);
+ var to = new Date(parseInt(d.cutoff_to_realtime) / 1000);
+ cutoff.innerHTML = 'Journal begins at <b>' + from.toLocaleString() + '</b> and ends at <b>' + to.toLocaleString() + '</b>.';
+
+ var usage = document.getElementById("usage");
+ usage.innerHTML = 'Disk usage is <b>' + formatBytes(parseInt(d.usage)) + '</b>.';
+
+ var os = document.getElementById("os");
+ os.innerHTML = 'Operating system is <b>' + escapeHTML(d.os_pretty_name) + '</b>.';
+
+ var virtualization = document.getElementById("virtualization");
+ virtualization.innerHTML = d.virtualization == "bare" ? "Running on <b>bare metal</b>." : "Running on virtualization <b>" + escapeHTML(d.virtualization) + "</b>.";
+ }
+
+ function entriesLoad(range) {
+
+ if (range == null)
+ range = localStorage["cursor"] + ":0";
+ if (range == null)
+ range = "";
+
+ var url = "/entries";
+
+ if (localStorage["filter"] != "" && localStorage["filter"] != null) {
+ url += "?_SYSTEMD_UNIT=" + escape(localStorage["filter"]);
+
+ if (localStorage["boot"] == "1")
+ url += "&boot";
+ } else {
+ if (localStorage["boot"] == "1")
+ url += "?boot";
+ }
+
+ var request = new XMLHttpRequest();
+ request.open("GET", url);
+ request.onreadystatechange = entriesOnResult;
+ request.setRequestHeader("Accept", "application/json");
+ request.setRequestHeader("Range", "entries=" + range + ":" + getNEntries().toString());
+ request.send(null);
+ }
+
+ function entriesLoadNext() {
+ if (last_cursor == null)
+ entriesLoad("");
+ else
+ entriesLoad(last_cursor + ":1");
+ }
+
+ function entriesLoadPrevious() {
+ if (first_cursor == null)
+ entriesLoad("");
+ else
+ entriesLoad(first_cursor + ":-" + getNEntries().toString());
+ }
+
+ function entriesLoadHead() {
+ entriesLoad("");
+ }
+
+ function entriesLoadTail() {
+ entriesLoad(":-" + getNEntries().toString());
+ }
+
+ function entriesOnResult(event) {
+
+ if ((event.currentTarget.readyState != 4) ||
+ (event.currentTarget.status != 200 && event.currentTarget.status != 0))
+ return;
+
+ var logs = document.getElementById("tablelogs");
+
+ var lc = null;
+ var fc = null;
+
+ var i, l = event.currentTarget.responseText.split('\n');
+
+ if (l.length <= 1) {
+ logs.innerHTML = '<tbody><tr><td colspan="3"><i>No further entries...</i></td></tr></tbody>';
+ return;
+ }
+
+ var buf = '';
+
+ for (i in l) {
+
+ if (l[i] == '')
+ continue;
+
+ var d = JSON.parse(l[i]);
+ if (d.MESSAGE == undefined || d.__CURSOR == undefined)
+ continue;
+
+ if (fc == null)
+ fc = d.__CURSOR;
+ lc = d.__CURSOR;
+
+ var priority;
+ if (d.PRIORITY != undefined)
+ priority = parseInt(d.PRIORITY);
+ else
+ priority = 6;
+
+ if (priority <= 3)
+ clazz = "message-error";
+ else if (priority <= 5)
+ clazz = "message-highlight";
+ else
+ clazz = "message";
+
+ buf += '<tr><td class="timestamp">';
+
+ if (d.__REALTIME_TIMESTAMP != undefined) {
+ var timestamp = new Date(parseInt(d.__REALTIME_TIMESTAMP) / 1000);
+ buf += timestamp.toLocaleString();
+ }
+
+ buf += '</td><td class="process">';
+
+ if (d.SYSLOG_IDENTIFIER != undefined)
+ buf += escapeHTML(d.SYSLOG_IDENTIFIER);
+ else if (d._COMM != undefined)
+ buf += escapeHTML(d._COMM);
+
+ if (d._PID != undefined)
+ buf += "[" + escapeHTML(d._PID) + "]";
+ else if (d.SYSLOG_PID != undefined)
+ buf += "[" + escapeHTML(d.SYSLOG_PID) + "]";
+
+ buf += '</td><td class="' + clazz + '"><a href="#entry" onclick="onMessageClick(\'' + d.__CURSOR + '\');">';
+
+ if (d.MESSAGE == null)
+ buf += "[blob data]";
+ else if (d.MESSAGE instanceof Array)
+ buf += "[" + formatBytes(d.MESSAGE.length) + " blob data]";
+ else
+ buf += escapeHTML(d.MESSAGE);
+
+ buf += '</a></td></tr>';
+ }
+
+ logs.innerHTML = '<tbody>' + buf + '</tbody>';
+
+ if (fc != null) {
+ first_cursor = fc;
+ localStorage["cursor"] = fc;
+ }
+ if (lc != null)
+ last_cursor = lc;
+ }
+
+ function entriesMore() {
+ setNEntries(getNEntries() + 10);
+ entriesLoad(first_cursor);
+ }
+
+ function entriesLess() {
+ setNEntries(getNEntries() - 10);
+ entriesLoad(first_cursor);
+ }
+
+ function onResultMessageClick(event) {
+ if ((event.currentTarget.readyState != 4) ||
+ (event.currentTarget.status != 200 && event.currentTarget.status != 0))
+ return;
+
+ var d = JSON.parse(event.currentTarget.responseText);
+
+ document.getElementById("diventry").style.display = "block";
+ entry = document.getElementById("tableentry");
+
+ var buf = "";
+ for (var key in d){
+ var data = d[key];
+
+ if (data == null)
+ data = "[blob data]";
+ else if (data instanceof Array)
+ data = "[" + formatBytes(data.length) + " blob data]";
+ else
+ data = escapeHTML(data);
+
+ buf += '<tr><td class="field">' + key + '</td><td class="data">' + data + '</td></tr>';
+ }
+ entry.innerHTML = '<tbody>' + buf + '</tbody>';
+ }
+
+ function onMessageClick(t) {
+ var request = new XMLHttpRequest();
+ request.open("GET", "/entries?discrete");
+ request.onreadystatechange = onResultMessageClick;
+ request.setRequestHeader("Accept", "application/json");
+ request.setRequestHeader("Range", "entries=" + t + ":0:1");
+ request.send(null);
+ }
+
+ function onKeyUp(event) {
+ switch (event.keyCode) {
+ case 8:
+ case 37:
+ case 75:
+ entriesLoadPrevious();
+ break;
+ case 32:
+ case 39:
+ case 74:
+ entriesLoadNext();
+ break;
+
+ case 71:
+ if (event.shiftKey)
+ entriesLoadTail();
+ else
+ entriesLoadHead();
+ break;
+ case 171:
+ entriesMore();
+ break;
+ case 173:
+ entriesLess();
+ break;
+ }
+ }
+
+ function onMouseWheel(event) {
+ if (event.detail < 0 || event.wheelDelta > 0)
+ entriesLoadPrevious();
+ else
+ entriesLoadNext();
+ }
+
+ function onResultFilterFocus(event) {
+ if ((event.currentTarget.readyState != 4) ||
+ (event.currentTarget.status != 200 && event.currentTarget.status != 0))
+ return;
+
+ f = document.getElementById("filter");
+
+ var l = event.currentTarget.responseText.split('\n');
+ var buf = '<option>No filter</option>';
+ var j = -1;
+
+ for (i in l) {
+
+ if (l[i] == '')
+ continue;
+
+ var d = JSON.parse(l[i]);
+ if (d._SYSTEMD_UNIT == undefined)
+ continue;
+
+ buf += '<option value="' + escape(d._SYSTEMD_UNIT) + '">' + escapeHTML(d._SYSTEMD_UNIT) + '</option>';
+
+ if (d._SYSTEMD_UNIT == localStorage["filter"])
+ j = i;
+ }
+
+ if (j < 0) {
+ if (localStorage["filter"] != null && localStorage["filter"] != "") {
+ buf += '<option value="' + escape(localStorage["filter"]) + '">' + escapeHTML(localStorage["filter"]) + '</option>';
+ j = i + 1;
+ } else
+ j = 0;
+ }
+
+ f.innerHTML = buf;
+ f.selectedIndex = j;
+ }
+
+ function onFilterFocus(w) {
+ var request = new XMLHttpRequest();
+ request.open("GET", "/fields/_SYSTEMD_UNIT");
+ request.onreadystatechange = onResultFilterFocus;
+ request.setRequestHeader("Accept", "application/json");
+ request.send(null);
+ }
+
+ function onFilterChange(w) {
+ if (w.selectedIndex <= 0)
+ localStorage["filter"] = "";
+ else
+ localStorage["filter"] = unescape(w.options[w.selectedIndex].value);
+
+ entriesLoadHead();
+ }
+
+ function onBootChange(w) {
+ localStorage["boot"] = w.checked ? "1" : "0";
+ entriesLoadHead();
+ }
+
+ function initFilter() {
+ f = document.getElementById("filter");
+
+ var buf = '<option>No filter</option>';
+
+ var filter = localStorage["filter"];
+ if (filter != null && filter != "") {
+ buf += '<option value="' + escape(filter) + '">' + escapeHTML(filter) + '</option>';
+ j = 1;
+ } else
+ j = 0;
+
+ f.innerHTML = buf;
+ f.selectedIndex = j;
+ }
+
+ function installHandlers() {
+ document.onkeyup = onKeyUp;
+
+ logs = document.getElementById("divlogs");
+ logs.addEventListener("mousewheel", onMouseWheel, false);
+ logs.addEventListener("DOMMouseScroll", onMouseWheel, false);
+ }
+
+ machineLoad();
+ entriesLoad(null);
+ showNEntries(getNEntries());
+ initFilter();
+ installHandlers();
+ </script>
+</body>
+</html>
diff --git a/src/journal/cat.c b/src/journal/cat.c
new file mode 100644
index 0000000000..ea61578353
--- /dev/null
+++ b/src/journal/cat.c
@@ -0,0 +1,179 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include <getopt.h>
+#include <assert.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <fcntl.h>
+
+#include <systemd/sd-journal.h>
+
+#include "util.h"
+#include "build.h"
+
+static char *arg_identifier = NULL;
+static int arg_priority = LOG_INFO;
+static bool arg_level_prefix = true;
+
+static int help(void) {
+
+ printf("%s [OPTIONS...] {COMMAND} ...\n\n"
+ "Execute process with stdout/stderr connected to the journal.\n\n"
+ " -h --help Show this help\n"
+ " --version Show package version\n"
+ " -t --identifier=STRING Set syslog identifier\n"
+ " -p --priority=PRIORITY Set priority value (0..7)\n"
+ " --level-prefix=BOOL Control whether level prefix shall be parsed\n",
+ program_invocation_short_name);
+
+ return 0;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+
+ enum {
+ ARG_VERSION = 0x100,
+ ARG_LEVEL_PREFIX
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "version", no_argument, NULL, ARG_VERSION },
+ { "identifier", required_argument, NULL, 't' },
+ { "priority", required_argument, NULL, 'p' },
+ { "level-prefix", required_argument, NULL, ARG_LEVEL_PREFIX },
+ { NULL, 0, NULL, 0 }
+ };
+
+ int c;
+
+ assert(argc >= 0);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "+ht:p:", options, NULL)) >= 0) {
+
+ switch (c) {
+
+ case 'h':
+ help();
+ return 0;
+
+ case ARG_VERSION:
+ puts(PACKAGE_STRING);
+ puts(SYSTEMD_FEATURES);
+ return 0;
+
+ case 't':
+ free(arg_identifier);
+ if (isempty(optarg))
+ arg_identifier = NULL;
+ else {
+ arg_identifier = strdup(optarg);
+ if (!arg_identifier)
+ return log_oom();
+ }
+ break;
+
+ case 'p':
+ arg_priority = log_level_from_string(optarg);
+ if (arg_priority < 0) {
+ log_error("Failed to parse priority value.");
+ return arg_priority;
+ }
+ break;
+
+ case ARG_LEVEL_PREFIX: {
+ int k;
+
+ k = parse_boolean(optarg);
+ if (k < 0) {
+ log_error("Failed to parse level prefix value.");
+ return k;
+ }
+ arg_level_prefix = k;
+ break;
+ }
+
+ default:
+ log_error("Unknown option code %c", c);
+ return -EINVAL;
+ }
+ }
+
+ return 1;
+}
+
+int main(int argc, char *argv[]) {
+ int r, fd = -1, saved_stderr = -1;
+
+ log_parse_environment();
+ log_open();
+
+ r = parse_argv(argc, argv);
+ if (r <= 0)
+ goto finish;
+
+ fd = sd_journal_stream_fd(arg_identifier, arg_priority, arg_level_prefix);
+ if (fd < 0) {
+ log_error("Failed to create stream fd: %s", strerror(-fd));
+ r = fd;
+ goto finish;
+ }
+
+ saved_stderr = fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, 3);
+
+ if (dup3(fd, STDOUT_FILENO, 0) < 0 ||
+ dup3(fd, STDERR_FILENO, 0) < 0) {
+ log_error("Failed to duplicate fd: %m");
+ r = -errno;
+ goto finish;
+ }
+
+ if (fd >= 3)
+ close_nointr_nofail(fd);
+
+ fd = -1;
+
+ if (argc <= optind)
+ execl("/bin/cat", "/bin/cat", NULL);
+ else
+ execvp(argv[optind], argv + optind);
+
+ r = -errno;
+
+ /* Let's try to restore a working stderr, so we can print the error message */
+ if (saved_stderr >= 0)
+ dup3(saved_stderr, STDERR_FILENO, 0);
+
+ log_error("Failed to execute process: %s", strerror(-r));
+
+finish:
+ if (fd >= 0)
+ close_nointr_nofail(fd);
+
+ if (saved_stderr >= 0)
+ close_nointr_nofail(saved_stderr);
+
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/src/journal/catalog.c b/src/journal/catalog.c
new file mode 100644
index 0000000000..7738d243a5
--- /dev/null
+++ b/src/journal/catalog.c
@@ -0,0 +1,655 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <fcntl.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <errno.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <locale.h>
+#include <libgen.h>
+
+#include "util.h"
+#include "log.h"
+#include "sparse-endian.h"
+#include "sd-id128.h"
+#include "hashmap.h"
+#include "strv.h"
+#include "strbuf.h"
+#include "strxcpyx.h"
+#include "conf-files.h"
+#include "mkdir.h"
+#include "catalog.h"
+
+const char * const catalog_file_dirs[] = {
+ "/usr/local/lib/systemd/catalog/",
+ "/usr/lib/systemd/catalog/",
+ NULL
+};
+
+#define CATALOG_SIGNATURE (uint8_t[]) { 'R', 'H', 'H', 'H', 'K', 'S', 'L', 'P' }
+
+typedef struct CatalogHeader {
+ uint8_t signature[8]; /* "RHHHKSLP" */
+ le32_t compatible_flags;
+ le32_t incompatible_flags;
+ le64_t header_size;
+ le64_t n_items;
+ le64_t catalog_item_size;
+} CatalogHeader;
+
+typedef struct CatalogItem {
+ sd_id128_t id;
+ char language[32];
+ le64_t offset;
+} CatalogItem;
+
+unsigned catalog_hash_func(const void *p) {
+ const CatalogItem *i = p;
+
+ assert_cc(sizeof(unsigned) == sizeof(uint8_t)*4);
+
+ return (((unsigned) i->id.bytes[0] << 24) |
+ ((unsigned) i->id.bytes[1] << 16) |
+ ((unsigned) i->id.bytes[2] << 8) |
+ ((unsigned) i->id.bytes[3])) ^
+ (((unsigned) i->id.bytes[4] << 24) |
+ ((unsigned) i->id.bytes[5] << 16) |
+ ((unsigned) i->id.bytes[6] << 8) |
+ ((unsigned) i->id.bytes[7])) ^
+ (((unsigned) i->id.bytes[8] << 24) |
+ ((unsigned) i->id.bytes[9] << 16) |
+ ((unsigned) i->id.bytes[10] << 8) |
+ ((unsigned) i->id.bytes[11])) ^
+ (((unsigned) i->id.bytes[12] << 24) |
+ ((unsigned) i->id.bytes[13] << 16) |
+ ((unsigned) i->id.bytes[14] << 8) |
+ ((unsigned) i->id.bytes[15])) ^
+ string_hash_func(i->language);
+}
+
+int catalog_compare_func(const void *a, const void *b) {
+ const CatalogItem *i = a, *j = b;
+ unsigned k;
+
+ for (k = 0; k < ELEMENTSOF(j->id.bytes); k++) {
+ if (i->id.bytes[k] < j->id.bytes[k])
+ return -1;
+ if (i->id.bytes[k] > j->id.bytes[k])
+ return 1;
+ }
+
+ return strcmp(i->language, j->language);
+}
+
+static int finish_item(
+ Hashmap *h,
+ struct strbuf *sb,
+ sd_id128_t id,
+ const char *language,
+ const char *payload) {
+
+ ssize_t offset;
+ CatalogItem *i;
+ int r;
+
+ assert(h);
+ assert(sb);
+ assert(payload);
+
+ offset = strbuf_add_string(sb, payload, strlen(payload));
+ if (offset < 0)
+ return log_oom();
+
+ i = new0(CatalogItem, 1);
+ if (!i)
+ return log_oom();
+
+ i->id = id;
+ strscpy(i->language, sizeof(i->language), language);
+ i->offset = htole64((uint64_t) offset);
+
+ r = hashmap_put(h, i, i);
+ if (r == EEXIST) {
+ log_warning("Duplicate entry for " SD_ID128_FORMAT_STR ".%s, ignoring.",
+ SD_ID128_FORMAT_VAL(id), language ? language : "C");
+ free(i);
+ return 0;
+ }
+
+ return 0;
+}
+
+int catalog_import_file(Hashmap *h, struct strbuf *sb, const char *path) {
+ _cleanup_fclose_ FILE *f = NULL;
+ _cleanup_free_ char *payload = NULL;
+ unsigned n = 0;
+ sd_id128_t id;
+ char language[32];
+ bool got_id = false, empty_line = true;
+ int r;
+
+ assert(h);
+ assert(sb);
+ assert(path);
+
+ f = fopen(path, "re");
+ if (!f) {
+ log_error("Failed to open file %s: %m", path);
+ return -errno;
+ }
+
+ for (;;) {
+ char line[LINE_MAX];
+ size_t a, b, c;
+ char *t;
+
+ if (!fgets(line, sizeof(line), f)) {
+ if (feof(f))
+ break;
+
+ log_error("Failed to read file %s: %m", path);
+ return -errno;
+ }
+
+ n++;
+
+ truncate_nl(line);
+
+ if (line[0] == 0) {
+ empty_line = true;
+ continue;
+ }
+
+ if (strchr(COMMENTS "\n", line[0]))
+ continue;
+
+ if (empty_line &&
+ strlen(line) >= 2+1+32 &&
+ line[0] == '-' &&
+ line[1] == '-' &&
+ line[2] == ' ' &&
+ (line[2+1+32] == ' ' || line[2+1+32] == '\0')) {
+
+ bool with_language;
+ sd_id128_t jd;
+
+ /* New entry */
+
+ with_language = line[2+1+32] != '\0';
+ line[2+1+32] = '\0';
+
+ if (sd_id128_from_string(line + 2 + 1, &jd) >= 0) {
+
+ if (got_id) {
+ r = finish_item(h, sb, id, language, payload);
+ if (r < 0)
+ return r;
+ }
+
+ if (with_language) {
+ t = strstrip(line + 2 + 1 + 32 + 1);
+
+ c = strlen(t);
+ if (c <= 0) {
+ log_error("[%s:%u] Language too short.", path, n);
+ return -EINVAL;
+ }
+ if (c > sizeof(language) - 1) {
+ log_error("[%s:%u] language too long.", path, n);
+ return -EINVAL;
+ }
+
+ strscpy(language, sizeof(language), t);
+ } else
+ language[0] = '\0';
+
+ got_id = true;
+ empty_line = false;
+ id = jd;
+
+ if (payload)
+ payload[0] = '\0';
+
+ continue;
+ }
+ }
+
+ /* Payload */
+ if (!got_id) {
+ log_error("[%s:%u] Got payload before ID.", path, n);
+ return -EINVAL;
+ }
+
+ a = payload ? strlen(payload) : 0;
+ b = strlen(line);
+
+ c = a + (empty_line ? 1 : 0) + b + 1 + 1;
+ t = realloc(payload, c);
+ if (!t)
+ return log_oom();
+
+ if (empty_line) {
+ t[a] = '\n';
+ memcpy(t + a + 1, line, b);
+ t[a+b+1] = '\n';
+ t[a+b+2] = 0;
+ } else {
+ memcpy(t + a, line, b);
+ t[a+b] = '\n';
+ t[a+b+1] = 0;
+ }
+
+ payload = t;
+ empty_line = false;
+ }
+
+ if (got_id) {
+ r = finish_item(h, sb, id, language, payload);
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static long write_catalog(const char *database, Hashmap *h, struct strbuf *sb,
+ CatalogItem *items, size_t n) {
+ CatalogHeader header;
+ _cleanup_fclose_ FILE *w = NULL;
+ int r;
+ _cleanup_free_ char *d, *p = NULL;
+ size_t k;
+
+ d = dirname_malloc(database);
+ if (!d)
+ return log_oom();
+
+ r = mkdir_p(d, 0775);
+ if (r < 0) {
+ log_error("Recursive mkdir %s: %s", d, strerror(-r));
+ return r;
+ }
+
+ r = fopen_temporary(database, &w, &p);
+ if (r < 0) {
+ log_error("Failed to open database for writing: %s: %s",
+ database, strerror(-r));
+ return r;
+ }
+
+ zero(header);
+ memcpy(header.signature, CATALOG_SIGNATURE, sizeof(header.signature));
+ header.header_size = htole64(ALIGN_TO(sizeof(CatalogHeader), 8));
+ header.catalog_item_size = htole64(sizeof(CatalogItem));
+ header.n_items = htole64(hashmap_size(h));
+
+ r = -EIO;
+
+ k = fwrite(&header, 1, sizeof(header), w);
+ if (k != sizeof(header)) {
+ log_error("%s: failed to write header.", p);
+ goto error;
+ }
+
+ k = fwrite(items, 1, n * sizeof(CatalogItem), w);
+ if (k != n * sizeof(CatalogItem)) {
+ log_error("%s: failed to write database.", p);
+ goto error;
+ }
+
+ k = fwrite(sb->buf, 1, sb->len, w);
+ if (k != sb->len) {
+ log_error("%s: failed to write strings.", p);
+ goto error;
+ }
+
+ fflush(w);
+
+ if (ferror(w)) {
+ log_error("%s: failed to write database.", p);
+ goto error;
+ }
+
+ fchmod(fileno(w), 0644);
+
+ if (rename(p, database) < 0) {
+ log_error("rename (%s -> %s) failed: %m", p, database);
+ r = -errno;
+ goto error;
+ }
+
+ return ftell(w);
+
+error:
+ unlink(p);
+ return r;
+}
+
+int catalog_update(const char* database, const char* root, const char* const* dirs) {
+ _cleanup_strv_free_ char **files = NULL;
+ char **f;
+ Hashmap *h;
+ struct strbuf *sb = NULL;
+ _cleanup_free_ CatalogItem *items = NULL;
+ CatalogItem *i;
+ Iterator j;
+ unsigned n;
+ long r;
+
+ h = hashmap_new(catalog_hash_func, catalog_compare_func);
+ sb = strbuf_new();
+
+ if (!h || !sb) {
+ r = log_oom();
+ goto finish;
+ }
+
+ r = conf_files_list_strv(&files, ".catalog", root, dirs);
+ if (r < 0) {
+ log_error("Failed to get catalog files: %s", strerror(-r));
+ goto finish;
+ }
+
+ STRV_FOREACH(f, files) {
+ log_debug("reading file '%s'", *f);
+ catalog_import_file(h, sb, *f);
+ }
+
+ if (hashmap_size(h) <= 0) {
+ log_info("No items in catalog.");
+ r = 0;
+ goto finish;
+ } else
+ log_debug("Found %u items in catalog.", hashmap_size(h));
+
+ strbuf_complete(sb);
+
+ items = new(CatalogItem, hashmap_size(h));
+ if (!items) {
+ r = log_oom();
+ goto finish;
+ }
+
+ n = 0;
+ HASHMAP_FOREACH(i, h, j) {
+ log_debug("Found " SD_ID128_FORMAT_STR ", language %s",
+ SD_ID128_FORMAT_VAL(i->id),
+ isempty(i->language) ? "C" : i->language);
+ items[n++] = *i;
+ }
+
+ assert(n == hashmap_size(h));
+ qsort(items, n, sizeof(CatalogItem), catalog_compare_func);
+
+ r = write_catalog(database, h, sb, items, n);
+ if (r < 0)
+ log_error("Failed to write %s: %s", database, strerror(-r));
+ else
+ log_debug("%s: wrote %u items, with %zu bytes of strings, %ld total size.",
+ database, n, sb->len, r);
+
+ r = 0;
+
+finish:
+ if (h)
+ hashmap_free_free(h);
+ if (sb)
+ strbuf_cleanup(sb);
+
+ return r < 0 ? r : 0;
+}
+
+static int open_mmap(const char *database, int *_fd, struct stat *_st, void **_p) {
+ const CatalogHeader *h;
+ int fd;
+ void *p;
+ struct stat st;
+
+ assert(_fd);
+ assert(_st);
+ assert(_p);
+
+ fd = open(database, O_RDONLY|O_CLOEXEC);
+ if (fd < 0)
+ return -errno;
+
+ if (fstat(fd, &st) < 0) {
+ close_nointr_nofail(fd);
+ return -errno;
+ }
+
+ if (st.st_size < (off_t) sizeof(CatalogHeader)) {
+ close_nointr_nofail(fd);
+ return -EINVAL;
+ }
+
+ p = mmap(NULL, PAGE_ALIGN(st.st_size), PROT_READ, MAP_SHARED, fd, 0);
+ if (p == MAP_FAILED) {
+ close_nointr_nofail(fd);
+ return -errno;
+ }
+
+ h = p;
+ if (memcmp(h->signature, CATALOG_SIGNATURE, sizeof(h->signature)) != 0 ||
+ le64toh(h->header_size) < sizeof(CatalogHeader) ||
+ le64toh(h->catalog_item_size) < sizeof(CatalogItem) ||
+ h->incompatible_flags != 0 ||
+ le64toh(h->n_items) <= 0 ||
+ st.st_size < (off_t) (le64toh(h->header_size) + le64toh(h->catalog_item_size) * le64toh(h->n_items))) {
+ close_nointr_nofail(fd);
+ munmap(p, st.st_size);
+ return -EBADMSG;
+ }
+
+ *_fd = fd;
+ *_st = st;
+ *_p = p;
+
+ return 0;
+}
+
+static const char *find_id(void *p, sd_id128_t id) {
+ CatalogItem key, *f = NULL;
+ const CatalogHeader *h = p;
+ const char *loc;
+
+ zero(key);
+ key.id = id;
+
+ loc = setlocale(LC_MESSAGES, NULL);
+ if (loc && loc[0] && !streq(loc, "C") && !streq(loc, "POSIX")) {
+ strncpy(key.language, loc, sizeof(key.language));
+ key.language[strcspn(key.language, ".@")] = 0;
+
+ f = bsearch(&key, (const uint8_t*) p + le64toh(h->header_size), le64toh(h->n_items), le64toh(h->catalog_item_size), catalog_compare_func);
+ if (!f) {
+ char *e;
+
+ e = strchr(key.language, '_');
+ if (e) {
+ *e = 0;
+ f = bsearch(&key, (const uint8_t*) p + le64toh(h->header_size), le64toh(h->n_items), le64toh(h->catalog_item_size), catalog_compare_func);
+ }
+ }
+ }
+
+ if (!f) {
+ zero(key.language);
+ f = bsearch(&key, (const uint8_t*) p + le64toh(h->header_size), le64toh(h->n_items), le64toh(h->catalog_item_size), catalog_compare_func);
+ }
+
+ if (!f)
+ return NULL;
+
+ return (const char*) p +
+ le64toh(h->header_size) +
+ le64toh(h->n_items) * le64toh(h->catalog_item_size) +
+ le64toh(f->offset);
+}
+
+int catalog_get(const char* database, sd_id128_t id, char **_text) {
+ _cleanup_close_ int fd = -1;
+ void *p = NULL;
+ struct stat st;
+ char *text = NULL;
+ int r;
+ const char *s;
+
+ assert(_text);
+
+ r = open_mmap(database, &fd, &st, &p);
+ if (r < 0)
+ return r;
+
+ s = find_id(p, id);
+ if (!s) {
+ r = -ENOENT;
+ goto finish;
+ }
+
+ text = strdup(s);
+ if (!text) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ *_text = text;
+ r = 0;
+
+finish:
+ if (p)
+ munmap(p, st.st_size);
+
+ return r;
+}
+
+static char *find_header(const char *s, const char *header) {
+
+ for (;;) {
+ const char *v, *e;
+
+ v = startswith(s, header);
+ if (v) {
+ v += strspn(v, WHITESPACE);
+ return strndup(v, strcspn(v, NEWLINE));
+ }
+
+ /* End of text */
+ e = strchr(s, '\n');
+ if (!e)
+ return NULL;
+
+ /* End of header */
+ if (e == s)
+ return NULL;
+
+ s = e + 1;
+ }
+}
+
+static void dump_catalog_entry(FILE *f, sd_id128_t id, const char *s, bool oneline) {
+ if (oneline) {
+ _cleanup_free_ char *subject = NULL, *defined_by = NULL;
+
+ subject = find_header(s, "Subject:");
+ defined_by = find_header(s, "Defined-By:");
+
+ fprintf(f, SD_ID128_FORMAT_STR " %s: %s\n",
+ SD_ID128_FORMAT_VAL(id),
+ strna(defined_by), strna(subject));
+ } else
+ fprintf(f, "-- " SD_ID128_FORMAT_STR "\n%s\n",
+ SD_ID128_FORMAT_VAL(id), s);
+}
+
+
+int catalog_list(FILE *f, const char *database, bool oneline) {
+ _cleanup_close_ int fd = -1;
+ void *p = NULL;
+ struct stat st;
+ const CatalogHeader *h;
+ const CatalogItem *items;
+ int r;
+ unsigned n;
+ sd_id128_t last_id;
+ bool last_id_set = false;
+
+ r = open_mmap(database, &fd, &st, &p);
+ if (r < 0)
+ return r;
+
+ h = p;
+ items = (const CatalogItem*) ((const uint8_t*) p + le64toh(h->header_size));
+
+ for (n = 0; n < le64toh(h->n_items); n++) {
+ const char *s;
+
+ if (last_id_set && sd_id128_equal(last_id, items[n].id))
+ continue;
+
+ assert_se(s = find_id(p, items[n].id));
+
+ dump_catalog_entry(f, items[n].id, s, oneline);
+
+ last_id_set = true;
+ last_id = items[n].id;
+ }
+
+ munmap(p, st.st_size);
+
+ return 0;
+}
+
+int catalog_list_items(FILE *f, const char *database, bool oneline, char **items) {
+ char **item;
+ int r = 0;
+
+ STRV_FOREACH(item, items) {
+ sd_id128_t id;
+ int k;
+ _cleanup_free_ char *msg = NULL;
+
+ k = sd_id128_from_string(*item, &id);
+ if (k < 0) {
+ log_error("Failed to parse id128 '%s': %s",
+ *item, strerror(-k));
+ if (r == 0)
+ r = k;
+ continue;
+ }
+
+ k = catalog_get(database, id, &msg);
+ if (k < 0) {
+ log_full(k == -ENOENT ? LOG_NOTICE : LOG_ERR,
+ "Failed to retrieve catalog entry for '%s': %s",
+ *item, strerror(-k));
+ if (r == 0)
+ r = k;
+ continue;
+ }
+
+ dump_catalog_entry(f, id, msg, oneline);
+ }
+
+ return r;
+}
diff --git a/src/journal/catalog.h b/src/journal/catalog.h
new file mode 100644
index 0000000000..24a2d0b553
--- /dev/null
+++ b/src/journal/catalog.h
@@ -0,0 +1,37 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdbool.h>
+
+#include "sd-id128.h"
+#include "hashmap.h"
+#include "strbuf.h"
+
+int catalog_import_file(Hashmap *h, struct strbuf *sb, const char *path);
+unsigned catalog_hash_func(const void *p);
+int catalog_compare_func(const void *a, const void *b) _pure_;
+int catalog_update(const char* database, const char* root, const char* const* dirs);
+int catalog_get(const char* database, sd_id128_t id, char **data);
+int catalog_list(FILE *f, const char* database, bool oneline);
+int catalog_list_items(FILE *f, const char* database, bool oneline, char **items);
+extern const char * const catalog_file_dirs[];
diff --git a/src/journal/compress.c b/src/journal/compress.c
new file mode 100644
index 0000000000..a4427be75a
--- /dev/null
+++ b/src/journal/compress.c
@@ -0,0 +1,216 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <stdlib.h>
+#include <string.h>
+#include <lzma.h>
+
+#include "macro.h"
+#include "compress.h"
+
+bool compress_blob(const void *src, uint64_t src_size, void *dst, uint64_t *dst_size) {
+ lzma_stream s = LZMA_STREAM_INIT;
+ lzma_ret ret;
+ bool b = false;
+
+ assert(src);
+ assert(src_size > 0);
+ assert(dst);
+ assert(dst_size);
+
+ /* Returns false if we couldn't compress the data or the
+ * compressed result is longer than the original */
+
+ ret = lzma_easy_encoder(&s, LZMA_PRESET_DEFAULT, LZMA_CHECK_NONE);
+ if (ret != LZMA_OK)
+ return false;
+
+ s.next_in = src;
+ s.avail_in = src_size;
+ s.next_out = dst;
+ s.avail_out = src_size;
+
+ /* Does it fit? */
+ if (lzma_code(&s, LZMA_FINISH) != LZMA_STREAM_END)
+ goto fail;
+
+ /* Is it actually shorter? */
+ if (s.avail_out == 0)
+ goto fail;
+
+ *dst_size = src_size - s.avail_out;
+ b = true;
+
+fail:
+ lzma_end(&s);
+
+ return b;
+}
+
+bool uncompress_blob(const void *src, uint64_t src_size,
+ void **dst, uint64_t *dst_alloc_size, uint64_t* dst_size, uint64_t dst_max) {
+
+ lzma_stream s = LZMA_STREAM_INIT;
+ lzma_ret ret;
+ uint64_t space;
+ bool b = false;
+
+ assert(src);
+ assert(src_size > 0);
+ assert(dst);
+ assert(dst_alloc_size);
+ assert(dst_size);
+ assert(*dst_alloc_size == 0 || *dst);
+
+ ret = lzma_stream_decoder(&s, UINT64_MAX, 0);
+ if (ret != LZMA_OK)
+ return false;
+
+ if (*dst_alloc_size <= src_size) {
+ void *p;
+
+ p = realloc(*dst, src_size*2);
+ if (!p)
+ return false;
+
+ *dst = p;
+ *dst_alloc_size = src_size*2;
+ }
+
+ s.next_in = src;
+ s.avail_in = src_size;
+
+ s.next_out = *dst;
+ space = dst_max > 0 ? MIN(*dst_alloc_size, dst_max) : *dst_alloc_size;
+ s.avail_out = space;
+
+ for (;;) {
+ void *p;
+
+ ret = lzma_code(&s, LZMA_FINISH);
+
+ if (ret == LZMA_STREAM_END)
+ break;
+
+ if (ret != LZMA_OK)
+ goto fail;
+
+ if (dst_max > 0 && (space - s.avail_out) >= dst_max)
+ break;
+
+ p = realloc(*dst, space*2);
+ if (!p)
+ goto fail;
+
+ s.next_out = (uint8_t*) p + ((uint8_t*) s.next_out - (uint8_t*) *dst);
+ s.avail_out += space;
+
+ space *= 2;
+
+ *dst = p;
+ *dst_alloc_size = space;
+ }
+
+ *dst_size = space - s.avail_out;
+ b = true;
+
+fail:
+ lzma_end(&s);
+
+ return b;
+}
+
+bool uncompress_startswith(const void *src, uint64_t src_size,
+ void **buffer, uint64_t *buffer_size,
+ const void *prefix, uint64_t prefix_len,
+ uint8_t extra) {
+
+ lzma_stream s = LZMA_STREAM_INIT;
+ lzma_ret ret;
+ bool b = false;
+
+ /* Checks whether the uncompressed blob starts with the
+ * mentioned prefix. The byte extra needs to follow the
+ * prefix */
+
+ assert(src);
+ assert(src_size > 0);
+ assert(buffer);
+ assert(buffer_size);
+ assert(prefix);
+ assert(*buffer_size == 0 || *buffer);
+
+ ret = lzma_stream_decoder(&s, UINT64_MAX, 0);
+ if (ret != LZMA_OK)
+ return false;
+
+ if (*buffer_size <= prefix_len) {
+ void *p;
+
+ p = realloc(*buffer, prefix_len*2);
+ if (!p)
+ return false;
+
+ *buffer = p;
+ *buffer_size = prefix_len*2;
+ }
+
+ s.next_in = src;
+ s.avail_in = src_size;
+
+ s.next_out = *buffer;
+ s.avail_out = *buffer_size;
+
+ for (;;) {
+ void *p;
+
+ ret = lzma_code(&s, LZMA_FINISH);
+
+ if (ret != LZMA_STREAM_END && ret != LZMA_OK)
+ goto fail;
+
+ if ((*buffer_size - s.avail_out > prefix_len) &&
+ memcmp(*buffer, prefix, prefix_len) == 0 &&
+ ((const uint8_t*) *buffer)[prefix_len] == extra)
+ break;
+
+ if (ret == LZMA_STREAM_END)
+ goto fail;
+
+ p = realloc(*buffer, *buffer_size*2);
+ if (!p)
+ goto fail;
+
+ s.next_out = (uint8_t*) p + ((uint8_t*) s.next_out - (uint8_t*) *buffer);
+ s.avail_out += *buffer_size;
+
+ *buffer = p;
+ *buffer_size *= 2;
+ }
+
+ b = true;
+
+fail:
+ lzma_end(&s);
+
+ return b;
+}
diff --git a/src/journal/compress.h b/src/journal/compress.h
new file mode 100644
index 0000000000..2b87e73a26
--- /dev/null
+++ b/src/journal/compress.h
@@ -0,0 +1,35 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <inttypes.h>
+#include <stdbool.h>
+
+bool compress_blob(const void *src, uint64_t src_size, void *dst, uint64_t *dst_size);
+
+bool uncompress_blob(const void *src, uint64_t src_size,
+ void **dst, uint64_t *dst_alloc_size, uint64_t* dst_size, uint64_t dst_max);
+
+bool uncompress_startswith(const void *src, uint64_t src_size,
+ void **buffer, uint64_t *buffer_size,
+ const void *prefix, uint64_t prefix_len,
+ uint8_t extra);
diff --git a/src/journal/coredump.c b/src/journal/coredump.c
new file mode 100644
index 0000000000..fd03e389bb
--- /dev/null
+++ b/src/journal/coredump.c
@@ -0,0 +1,277 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <sys/prctl.h>
+
+#include <systemd/sd-journal.h>
+
+#ifdef HAVE_LOGIND
+#include <systemd/sd-login.h>
+#endif
+
+#include "log.h"
+#include "util.h"
+#include "macro.h"
+#include "mkdir.h"
+#include "special.h"
+#include "cgroup-util.h"
+
+/* Few programs have less than 3MiB resident */
+#define COREDUMP_MIN_START (3*1024*1024)
+/* Make sure to not make this larger than the maximum journal entry
+ * size. See ENTRY_SIZE_MAX in journald-native.c. */
+#define COREDUMP_MAX (768*1024*1024)
+
+enum {
+ ARG_PID = 1,
+ ARG_UID,
+ ARG_GID,
+ ARG_SIGNAL,
+ ARG_TIMESTAMP,
+ ARG_COMM,
+ _ARG_MAX
+};
+
+static int divert_coredump(void) {
+ _cleanup_fclose_ FILE *f = NULL;
+
+ log_info("Detected coredump of the journal daemon itself, diverting coredump to /var/lib/systemd/coredump/.");
+
+ mkdir_p_label("/var/lib/systemd/coredump", 0755);
+
+ f = fopen("/var/lib/systemd/coredump/core.systemd-journald", "we");
+ if (!f) {
+ log_error("Failed to create coredump file: %m");
+ return -errno;
+ }
+
+ for (;;) {
+ uint8_t buffer[4096];
+ size_t l, q;
+
+ l = fread(buffer, 1, sizeof(buffer), stdin);
+ if (l <= 0) {
+ if (ferror(f)) {
+ log_error("Failed to read coredump: %m");
+ return -errno;
+ }
+
+ break;
+ }
+
+ q = fwrite(buffer, 1, l, f);
+ if (q != l) {
+ log_error("Failed to write coredump: %m");
+ return -errno;
+ }
+ }
+
+ fflush(f);
+
+ if (ferror(f)) {
+ log_error("Failed to write coredump: %m");
+ return -errno;
+ }
+
+ return 0;
+}
+
+int main(int argc, char* argv[]) {
+ int r, j = 0;
+ char *t;
+ ssize_t n;
+ pid_t pid;
+ uid_t uid;
+ gid_t gid;
+ struct iovec iovec[14];
+ size_t coredump_bufsize, coredump_size;
+ _cleanup_free_ char *core_pid = NULL, *core_uid = NULL, *core_gid = NULL, *core_signal = NULL,
+ *core_timestamp = NULL, *core_comm = NULL, *core_exe = NULL, *core_unit = NULL,
+ *core_session = NULL, *core_message = NULL, *core_cmdline = NULL, *coredump_data = NULL;
+
+ prctl(PR_SET_DUMPABLE, 0);
+
+ if (argc != _ARG_MAX) {
+ log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
+ log_open();
+
+ log_error("Invalid number of arguments passed from kernel.");
+ r = -EINVAL;
+ goto finish;
+ }
+
+ r = parse_pid(argv[ARG_PID], &pid);
+ if (r < 0) {
+ log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
+ log_open();
+
+ log_error("Failed to parse PID.");
+ goto finish;
+ }
+
+ if (cg_pid_get_unit(pid, &t) >= 0) {
+
+ if (streq(t, SPECIAL_JOURNALD_SERVICE)) {
+ /* Make sure we don't make use of the journal,
+ * if it's the journal which is crashing */
+ log_set_target(LOG_TARGET_KMSG);
+ log_open();
+
+ r = divert_coredump();
+ goto finish;
+ }
+
+ core_unit = strappend("COREDUMP_UNIT=", t);
+ } else if (cg_pid_get_user_unit(pid, &t) >= 0)
+ core_unit = strappend("COREDUMP_USER_UNIT=", t);
+
+ if (core_unit)
+ IOVEC_SET_STRING(iovec[j++], core_unit);
+
+ /* OK, now we know it's not the journal, hence make use of
+ * it */
+ log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
+ log_open();
+
+ r = parse_uid(argv[ARG_UID], &uid);
+ if (r < 0) {
+ log_error("Failed to parse UID.");
+ goto finish;
+ }
+
+ r = parse_gid(argv[ARG_GID], &gid);
+ if (r < 0) {
+ log_error("Failed to parse GID.");
+ goto finish;
+ }
+
+ core_pid = strappend("COREDUMP_PID=", argv[ARG_PID]);
+ if (core_pid)
+ IOVEC_SET_STRING(iovec[j++], core_pid);
+
+ core_uid = strappend("COREDUMP_UID=", argv[ARG_UID]);
+ if (core_uid)
+ IOVEC_SET_STRING(iovec[j++], core_uid);
+
+ core_gid = strappend("COREDUMP_GID=", argv[ARG_GID]);
+ if (core_gid)
+ IOVEC_SET_STRING(iovec[j++], core_gid);
+
+ core_signal = strappend("COREDUMP_SIGNAL=", argv[ARG_SIGNAL]);
+ if (core_signal)
+ IOVEC_SET_STRING(iovec[j++], core_signal);
+
+ core_comm = strappend("COREDUMP_COMM=", argv[ARG_COMM]);
+ if (core_comm)
+ IOVEC_SET_STRING(iovec[j++], core_comm);
+
+#ifdef HAVE_LOGIND
+ if (sd_pid_get_session(pid, &t) >= 0) {
+ core_session = strappend("COREDUMP_SESSION=", t);
+ free(t);
+
+ if (core_session)
+ IOVEC_SET_STRING(iovec[j++], core_session);
+ }
+
+#endif
+
+ if (get_process_exe(pid, &t) >= 0) {
+ core_exe = strappend("COREDUMP_EXE=", t);
+ free(t);
+
+ if (core_exe)
+ IOVEC_SET_STRING(iovec[j++], core_exe);
+ }
+
+ if (get_process_cmdline(pid, 0, false, &t) >= 0) {
+ core_cmdline = strappend("COREDUMP_CMDLINE=", t);
+ free(t);
+
+ if (core_cmdline)
+ IOVEC_SET_STRING(iovec[j++], core_cmdline);
+ }
+
+ core_timestamp = strjoin("COREDUMP_TIMESTAMP=", argv[ARG_TIMESTAMP], "000000", NULL);
+ if (core_timestamp)
+ IOVEC_SET_STRING(iovec[j++], core_timestamp);
+
+ IOVEC_SET_STRING(iovec[j++], "MESSAGE_ID=fc2e22bc6ee647b6b90729ab34a250b1");
+ IOVEC_SET_STRING(iovec[j++], "PRIORITY=2");
+
+ core_message = strjoin("MESSAGE=Process ", argv[ARG_PID], " (", argv[ARG_COMM], ") dumped core.", NULL);
+ if (core_message)
+ IOVEC_SET_STRING(iovec[j++], core_message);
+
+ /* Now, let's drop privileges to become the user who owns the
+ * segfaulted process and allocate the coredump memory under
+ * his uid. This also ensures that the credentials journald
+ * will see are the ones of the coredumping user, thus making
+ * sure the user himself gets access to the core dump. */
+
+ if (setresgid(gid, gid, gid) < 0 ||
+ setresuid(uid, uid, uid) < 0) {
+ log_error("Failed to drop privileges: %m");
+ r = -errno;
+ goto finish;
+ }
+
+ coredump_bufsize = COREDUMP_MIN_START;
+ coredump_data = malloc(coredump_bufsize);
+ if (!coredump_data) {
+ r = log_oom();
+ goto finish;
+ }
+
+ memcpy(coredump_data, "COREDUMP=", 9);
+ coredump_size = 9;
+
+ for (;;) {
+ n = loop_read(STDIN_FILENO, coredump_data + coredump_size,
+ coredump_bufsize - coredump_size, false);
+ if (n < 0) {
+ log_error("Failed to read core dump data: %s", strerror(-n));
+ r = (int) n;
+ goto finish;
+ } else if (n == 0)
+ break;
+
+ coredump_size += n;
+ if (!GREEDY_REALLOC(coredump_data, coredump_bufsize, coredump_size + 1)) {
+ r = log_oom();
+ goto finish;
+ }
+ }
+
+ iovec[j].iov_base = coredump_data;
+ iovec[j].iov_len = coredump_size;
+ j++;
+
+ r = sd_journal_sendv(iovec, j);
+ if (r < 0)
+ log_error("Failed to send coredump: %s", strerror(-r));
+
+finish:
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/src/journal/coredumpctl.c b/src/journal/coredumpctl.c
new file mode 100644
index 0000000000..5652c2f91a
--- /dev/null
+++ b/src/journal/coredumpctl.c
@@ -0,0 +1,587 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Zbigniew Jędrzejewski-Szmek
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <locale.h>
+#include <stdio.h>
+#include <string.h>
+#include <getopt.h>
+#include <fcntl.h>
+#include <unistd.h>
+
+#include <systemd/sd-journal.h>
+
+#include "build.h"
+#include "set.h"
+#include "util.h"
+#include "log.h"
+#include "path-util.h"
+#include "pager.h"
+#include "macro.h"
+#include "journal-internal.h"
+
+static enum {
+ ACTION_NONE,
+ ACTION_LIST,
+ ACTION_DUMP,
+ ACTION_GDB,
+} arg_action = ACTION_LIST;
+
+static FILE* output = NULL;
+static char* field = NULL;
+
+static int arg_no_pager = false;
+static int arg_no_legend = false;
+
+static Set *new_matches(void) {
+ Set *set;
+ char *tmp;
+ int r;
+
+ set = set_new(trivial_hash_func, trivial_compare_func);
+ if (!set) {
+ log_oom();
+ return NULL;
+ }
+
+ tmp = strdup("MESSAGE_ID=fc2e22bc6ee647b6b90729ab34a250b1");
+ if (!tmp) {
+ log_oom();
+ set_free(set);
+ return NULL;
+ }
+
+ r = set_consume(set, tmp);
+ if (r < 0) {
+ log_error("failed to add to set: %s", strerror(-r));
+ set_free(set);
+ return NULL;
+ }
+
+ return set;
+}
+
+static int help(void) {
+ printf("%s [OPTIONS...] [MATCHES...]\n\n"
+ "List or retrieve coredumps from the journal.\n\n"
+ "Flags:\n"
+ " -o --output=FILE Write output to FILE\n"
+ " --no-pager Do not pipe output into a pager\n"
+
+ "Commands:\n"
+ " -h --help Show this help\n"
+ " --version Print version string\n"
+ " -F --field=FIELD List all values a certain field takes\n"
+ " gdb Start gdb for the first matching coredump\n"
+ " list List available coredumps\n"
+ " dump PID Print coredump to stdout\n"
+ " dump PATH Print coredump to stdout\n"
+ , program_invocation_short_name);
+
+ return 0;
+}
+
+static int add_match(Set *set, const char *match) {
+ int r = -ENOMEM;
+ unsigned pid;
+ const char* prefix;
+ char *pattern = NULL;
+ _cleanup_free_ char *p = NULL;
+
+ if (strchr(match, '='))
+ prefix = "";
+ else if (strchr(match, '/')) {
+ p = path_make_absolute_cwd(match);
+ if (!p)
+ goto fail;
+
+ match = p;
+ prefix = "COREDUMP_EXE=";
+ }
+ else if (safe_atou(match, &pid) == 0)
+ prefix = "COREDUMP_PID=";
+ else
+ prefix = "COREDUMP_COMM=";
+
+ pattern = strjoin(prefix, match, NULL);
+ if (!pattern)
+ goto fail;
+
+ log_debug("Adding pattern: %s", pattern);
+ r = set_consume(set, pattern);
+ if (r < 0) {
+ log_error("Failed to add pattern '%s': %s",
+ pattern, strerror(-r));
+ goto fail;
+ }
+
+ return 0;
+fail:
+ log_error("Failed to add match: %s", strerror(-r));
+ return r;
+}
+
+static int parse_argv(int argc, char *argv[], Set *matches) {
+ enum {
+ ARG_VERSION = 0x100,
+ ARG_NO_PAGER,
+ ARG_NO_LEGEND,
+ };
+
+ int r, c;
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "version" , no_argument, NULL, ARG_VERSION },
+ { "no-pager", no_argument, NULL, ARG_NO_PAGER },
+ { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
+ { "output", required_argument, NULL, 'o' },
+ { "field", required_argument, NULL, 'F' },
+ { NULL, 0, NULL, 0 }
+ };
+
+ assert(argc >= 0);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "ho:F:", options, NULL)) >= 0)
+ switch(c) {
+ case 'h':
+ help();
+ arg_action = ACTION_NONE;
+ return 0;
+
+ case ARG_VERSION:
+ puts(PACKAGE_STRING);
+ puts(SYSTEMD_FEATURES);
+ arg_action = ACTION_NONE;
+ return 0;
+
+ case ARG_NO_PAGER:
+ arg_no_pager = true;
+ break;
+
+ case ARG_NO_LEGEND:
+ arg_no_legend = true;
+ break;
+
+ case 'o':
+ if (output) {
+ log_error("cannot set output more than once");
+ return -EINVAL;
+ }
+
+ output = fopen(optarg, "we");
+ if (!output) {
+ log_error("writing to '%s': %m", optarg);
+ return -errno;
+ }
+
+ break;
+
+ case 'F':
+ if (field) {
+ log_error("cannot use --field/-F more than once");
+ return -EINVAL;
+ }
+
+ field = optarg;
+ break;
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ log_error("Unknown option code %c", c);
+ return -EINVAL;
+ }
+
+ if (optind < argc) {
+ const char *cmd = argv[optind++];
+ if(streq(cmd, "list"))
+ arg_action = ACTION_LIST;
+ else if (streq(cmd, "dump"))
+ arg_action = ACTION_DUMP;
+ else if (streq(cmd, "gdb"))
+ arg_action = ACTION_GDB;
+ else {
+ log_error("Unknown action '%s'", cmd);
+ return -EINVAL;
+ }
+ }
+
+ if (field && arg_action != ACTION_LIST) {
+ log_error("Option --field/-F only makes sense with list");
+ return -EINVAL;
+ }
+
+ while (optind < argc) {
+ r = add_match(matches, argv[optind]);
+ if (r != 0)
+ return r;
+ optind++;
+ }
+
+ return 0;
+}
+
+static int retrieve(const void *data,
+ size_t len,
+ const char *name,
+ const char **var) {
+
+ size_t ident;
+
+ ident = strlen(name) + 1; /* name + "=" */
+
+ if (len < ident)
+ return 0;
+
+ if (memcmp(data, name, ident - 1) != 0)
+ return 0;
+
+ if (((const char*) data)[ident - 1] != '=')
+ return 0;
+
+ *var = strndup((const char*)data + ident, len - ident);
+ if (!*var)
+ return log_oom();
+
+ return 0;
+}
+
+static void print_field(FILE* file, sd_journal *j) {
+ _cleanup_free_ const char *value = NULL;
+ const void *d;
+ size_t l;
+
+ assert(field);
+
+ SD_JOURNAL_FOREACH_DATA(j, d, l)
+ retrieve(d, l, field, &value);
+ if (value)
+ fprintf(file, "%s\n", value);
+}
+
+static int print_entry(FILE* file, sd_journal *j, int had_legend) {
+ _cleanup_free_ const char
+ *pid = NULL, *uid = NULL, *gid = NULL,
+ *sgnl = NULL, *exe = NULL;
+ const void *d;
+ size_t l;
+ usec_t t;
+ char buf[FORMAT_TIMESTAMP_MAX];
+ int r;
+
+ SD_JOURNAL_FOREACH_DATA(j, d, l) {
+ retrieve(d, l, "COREDUMP_PID", &pid);
+ retrieve(d, l, "COREDUMP_PID", &pid);
+ retrieve(d, l, "COREDUMP_UID", &uid);
+ retrieve(d, l, "COREDUMP_GID", &gid);
+ retrieve(d, l, "COREDUMP_SIGNAL", &sgnl);
+ retrieve(d, l, "COREDUMP_EXE", &exe);
+ if (!exe)
+ retrieve(d, l, "COREDUMP_COMM", &exe);
+ if (!exe)
+ retrieve(d, l, "COREDUMP_CMDLINE", &exe);
+ }
+
+ if (!pid && !uid && !gid && !sgnl && !exe) {
+ log_warning("Empty coredump log entry");
+ return -EINVAL;
+ }
+
+ r = sd_journal_get_realtime_usec(j, &t);
+ if (r < 0) {
+ log_error("Failed to get realtime timestamp: %s", strerror(-r));
+ return r;
+ }
+
+ format_timestamp(buf, sizeof(buf), t);
+
+ if (!had_legend && !arg_no_legend)
+ fprintf(file, "%-*s %*s %*s %*s %*s %s\n",
+ FORMAT_TIMESTAMP_MAX-1, "TIME",
+ 6, "PID",
+ 5, "UID",
+ 5, "GID",
+ 3, "SIG",
+ "EXE");
+
+ fprintf(file, "%*s %*s %*s %*s %*s %s\n",
+ FORMAT_TIMESTAMP_MAX-1, buf,
+ 6, pid,
+ 5, uid,
+ 5, gid,
+ 3, sgnl,
+ exe);
+
+ return 0;
+}
+
+static int dump_list(sd_journal *j) {
+ int found = 0;
+
+ assert(j);
+
+ /* The coredumps are likely to compressed, and for just
+ * listing them we don#t need to decompress them, so let's
+ * pick a fairly low data threshold here */
+ sd_journal_set_data_threshold(j, 4096);
+
+ SD_JOURNAL_FOREACH(j) {
+ if (field)
+ print_field(stdout, j);
+ else
+ print_entry(stdout, j, found++);
+ }
+
+ if (!field && !found) {
+ log_notice("No coredumps found");
+ return -ESRCH;
+ }
+
+ return 0;
+}
+
+static int focus(sd_journal *j) {
+ int r;
+
+ r = sd_journal_seek_tail(j);
+ if (r == 0)
+ r = sd_journal_previous(j);
+ if (r < 0) {
+ log_error("Failed to search journal: %s", strerror(-r));
+ return r;
+ }
+ if (r == 0) {
+ log_error("No match found");
+ return -ESRCH;
+ }
+ return r;
+}
+
+static int dump_core(sd_journal* j) {
+ const void *data;
+ size_t len, ret;
+ int r;
+
+ assert(j);
+
+ /* We want full data, nothing truncated. */
+ sd_journal_set_data_threshold(j, 0);
+
+ r = focus(j);
+ if (r < 0)
+ return r;
+
+ print_entry(output ? stdout : stderr, j, false);
+
+ if (on_tty() && !output) {
+ log_error("Refusing to dump core to tty");
+ return -ENOTTY;
+ }
+
+ r = sd_journal_get_data(j, "COREDUMP", (const void**) &data, &len);
+ if (r < 0) {
+ log_error("Failed to retrieve COREDUMP field: %s", strerror(-r));
+ return r;
+ }
+
+ assert(len >= 9);
+ data = (const uint8_t*) data + 9;
+ len -= 9;
+
+ ret = fwrite(data, len, 1, output ? output : stdout);
+ if (ret != 1) {
+ log_error("dumping coredump: %m (%zu)", ret);
+ return -errno;
+ }
+
+ r = sd_journal_previous(j);
+ if (r >= 0)
+ log_warning("More than one entry matches, ignoring rest.\n");
+
+ return 0;
+}
+
+static int run_gdb(sd_journal *j) {
+ char path[] = "/var/tmp/coredump-XXXXXX";
+ const void *data;
+ size_t len;
+ ssize_t sz;
+ pid_t pid;
+ _cleanup_free_ char *exe = NULL;
+ int r;
+ _cleanup_close_ int fd = -1;
+ siginfo_t st;
+
+ assert(j);
+
+ sd_journal_set_data_threshold(j, 0);
+
+ r = focus(j);
+ if (r < 0)
+ return r;
+
+ print_entry(stdout, j, false);
+
+ r = sd_journal_get_data(j, "COREDUMP_EXE", (const void**) &data, &len);
+ if (r < 0) {
+ log_error("Failed to retrieve COREDUMP_EXE field: %s", strerror(-r));
+ return r;
+ }
+
+ assert(len >= 13);
+ data = (const uint8_t*) data + 13;
+ len -= 13;
+
+ exe = strndup(data, len);
+ if (!exe)
+ return log_oom();
+
+ if (endswith(exe, " (deleted)")) {
+ log_error("Binary already deleted.");
+ return -ENOENT;
+ }
+
+ r = sd_journal_get_data(j, "COREDUMP", (const void**) &data, &len);
+ if (r < 0) {
+ log_error("Failed to retrieve COREDUMP field: %s", strerror(-r));
+ return r;
+ }
+
+ assert(len >= 9);
+ data = (const uint8_t*) data + 9;
+ len -= 9;
+
+ fd = mkostemp(path, O_WRONLY);
+ if (fd < 0) {
+ log_error("Failed to create temporary file: %m");
+ return -errno;
+ }
+
+ sz = write(fd, data, len);
+ if (sz < 0) {
+ log_error("Failed to write temporary file: %s", strerror(errno));
+ r = -errno;
+ goto finish;
+ }
+ if (sz != (ssize_t) len) {
+ log_error("Short write to temporary file.");
+ r = -EIO;
+ goto finish;
+ }
+
+ close_nointr_nofail(fd);
+ fd = -1;
+
+ pid = fork();
+ if (pid < 0) {
+ log_error("Failed to fork(): %m");
+ r = -errno;
+ goto finish;
+ }
+ if (pid == 0) {
+ execlp("gdb", "gdb", exe, path, NULL);
+ log_error("Failed to invoke gdb: %m");
+ _exit(1);
+ }
+
+ r = wait_for_terminate(pid, &st);
+ if (r < 0) {
+ log_error("Failed to wait for gdb: %m");
+ goto finish;
+ }
+
+ r = st.si_code == CLD_EXITED ? st.si_status : 255;
+
+finish:
+ unlink(path);
+ return r;
+}
+
+int main(int argc, char *argv[]) {
+ _cleanup_journal_close_ sd_journal*j = NULL;
+ const char* match;
+ Iterator it;
+ int r = 0;
+ _cleanup_set_free_free_ Set *matches = NULL;
+
+ setlocale(LC_ALL, "");
+ log_parse_environment();
+ log_open();
+
+ matches = new_matches();
+ if (!matches) {
+ r = -ENOMEM;
+ goto end;
+ }
+
+ r = parse_argv(argc, argv, matches);
+ if (r < 0)
+ goto end;
+
+ if (arg_action == ACTION_NONE)
+ goto end;
+
+ r = sd_journal_open(&j, SD_JOURNAL_LOCAL_ONLY);
+ if (r < 0) {
+ log_error("Failed to open journal: %s", strerror(-r));
+ goto end;
+ }
+
+ SET_FOREACH(match, matches, it) {
+ r = sd_journal_add_match(j, match, strlen(match));
+ if (r != 0) {
+ log_error("Failed to add match '%s': %s",
+ match, strerror(-r));
+ goto end;
+ }
+ }
+
+ switch(arg_action) {
+
+ case ACTION_LIST:
+ if (!arg_no_pager)
+ pager_open(false);
+
+ r = dump_list(j);
+ break;
+
+ case ACTION_DUMP:
+ r = dump_core(j);
+ break;
+
+ case ACTION_GDB:
+ r = run_gdb(j);
+ break;
+
+ default:
+ assert_not_reached("Shouldn't be here");
+ }
+
+end:
+ pager_close();
+
+ if (output)
+ fclose(output);
+
+ return r >= 0 ? r : EXIT_FAILURE;
+}
diff --git a/src/journal/fsprg.c b/src/journal/fsprg.c
new file mode 100644
index 0000000000..6817a629c8
--- /dev/null
+++ b/src/journal/fsprg.c
@@ -0,0 +1,384 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/*
+ * fsprg v0.1 - (seekable) forward-secure pseudorandom generator
+ * Copyright (C) 2012 B. Poettering
+ * Contact: fsprg@point-at-infinity.org
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA
+ *
+ */
+
+#include <gcrypt.h>
+#include <string.h>
+#include <assert.h>
+
+#include "fsprg.h"
+
+#define ISVALID_SECPAR(secpar) (((secpar) % 16 == 0) && ((secpar) >= 16) && ((secpar) <= 16384))
+#define VALIDATE_SECPAR(secpar) assert(ISVALID_SECPAR(secpar));
+
+#define RND_HASH GCRY_MD_SHA256
+#define RND_GEN_P 0x01
+#define RND_GEN_Q 0x02
+#define RND_GEN_X 0x03
+
+/******************************************************************************/
+
+static void mpi_export(void *buf, size_t buflen, const gcry_mpi_t x) {
+ unsigned len;
+ size_t nwritten;
+
+ assert(gcry_mpi_cmp_ui(x, 0) >= 0);
+ len = (gcry_mpi_get_nbits(x) + 7) / 8;
+ assert(len <= buflen);
+ memset(buf, 0, buflen);
+ gcry_mpi_print(GCRYMPI_FMT_USG, buf + (buflen - len), len, &nwritten, x);
+ assert(nwritten == len);
+}
+
+static gcry_mpi_t mpi_import(const void *buf, size_t buflen) {
+ gcry_mpi_t h;
+ unsigned len;
+
+ gcry_mpi_scan(&h, GCRYMPI_FMT_USG, buf, buflen, NULL);
+ len = (gcry_mpi_get_nbits(h) + 7) / 8;
+ assert(len <= buflen);
+ assert(gcry_mpi_cmp_ui(h, 0) >= 0);
+
+ return h;
+}
+
+static void uint64_export(void *buf, size_t buflen, uint64_t x) {
+ assert(buflen == 8);
+ ((uint8_t*) buf)[0] = (x >> 56) & 0xff;
+ ((uint8_t*) buf)[1] = (x >> 48) & 0xff;
+ ((uint8_t*) buf)[2] = (x >> 40) & 0xff;
+ ((uint8_t*) buf)[3] = (x >> 32) & 0xff;
+ ((uint8_t*) buf)[4] = (x >> 24) & 0xff;
+ ((uint8_t*) buf)[5] = (x >> 16) & 0xff;
+ ((uint8_t*) buf)[6] = (x >> 8) & 0xff;
+ ((uint8_t*) buf)[7] = (x >> 0) & 0xff;
+}
+
+_pure_ static uint64_t uint64_import(const void *buf, size_t buflen) {
+ assert(buflen == 8);
+ return
+ (uint64_t)(((uint8_t*) buf)[0]) << 56 |
+ (uint64_t)(((uint8_t*) buf)[1]) << 48 |
+ (uint64_t)(((uint8_t*) buf)[2]) << 40 |
+ (uint64_t)(((uint8_t*) buf)[3]) << 32 |
+ (uint64_t)(((uint8_t*) buf)[4]) << 24 |
+ (uint64_t)(((uint8_t*) buf)[5]) << 16 |
+ (uint64_t)(((uint8_t*) buf)[6]) << 8 |
+ (uint64_t)(((uint8_t*) buf)[7]) << 0;
+}
+
+/* deterministically generate from seed/idx a string of buflen pseudorandom bytes */
+static void det_randomize(void *buf, size_t buflen, const void *seed, size_t seedlen, uint32_t idx) {
+ gcry_md_hd_t hd, hd2;
+ size_t olen, cpylen;
+ uint32_t ctr;
+
+ olen = gcry_md_get_algo_dlen(RND_HASH);
+ gcry_md_open(&hd, RND_HASH, 0);
+ gcry_md_write(hd, seed, seedlen);
+ gcry_md_putc(hd, (idx >> 24) & 0xff);
+ gcry_md_putc(hd, (idx >> 16) & 0xff);
+ gcry_md_putc(hd, (idx >> 8) & 0xff);
+ gcry_md_putc(hd, (idx >> 0) & 0xff);
+
+ for (ctr = 0; buflen; ctr++) {
+ gcry_md_copy(&hd2, hd);
+ gcry_md_putc(hd2, (ctr >> 24) & 0xff);
+ gcry_md_putc(hd2, (ctr >> 16) & 0xff);
+ gcry_md_putc(hd2, (ctr >> 8) & 0xff);
+ gcry_md_putc(hd2, (ctr >> 0) & 0xff);
+ gcry_md_final(hd2);
+ cpylen = (buflen < olen) ? buflen : olen;
+ memcpy(buf, gcry_md_read(hd2, RND_HASH), cpylen);
+ gcry_md_close(hd2);
+ buf += cpylen;
+ buflen -= cpylen;
+ }
+ gcry_md_close(hd);
+}
+
+/* deterministically generate from seed/idx a prime of length `bits' that is 3 (mod 4) */
+static gcry_mpi_t genprime3mod4(int bits, const void *seed, size_t seedlen, uint32_t idx) {
+ size_t buflen = bits / 8;
+ uint8_t buf[buflen];
+ gcry_mpi_t p;
+
+ assert(bits % 8 == 0);
+ assert(buflen > 0);
+
+ det_randomize(buf, buflen, seed, seedlen, idx);
+ buf[0] |= 0xc0; /* set upper two bits, so that n=pq has maximum size */
+ buf[buflen - 1] |= 0x03; /* set lower two bits, to have result 3 (mod 4) */
+
+ p = mpi_import(buf, buflen);
+ while (gcry_prime_check(p, 0))
+ gcry_mpi_add_ui(p, p, 4);
+
+ return p;
+}
+
+/* deterministically generate from seed/idx a quadratic residue (mod n) */
+static gcry_mpi_t gensquare(const gcry_mpi_t n, const void *seed, size_t seedlen, uint32_t idx, unsigned secpar) {
+ size_t buflen = secpar / 8;
+ uint8_t buf[buflen];
+ gcry_mpi_t x;
+
+ det_randomize(buf, buflen, seed, seedlen, idx);
+ buf[0] &= 0x7f; /* clear upper bit, so that we have x < n */
+ x = mpi_import(buf, buflen);
+ assert(gcry_mpi_cmp(x, n) < 0);
+ gcry_mpi_mulm(x, x, x, n);
+ return x;
+}
+
+/* compute 2^m (mod phi(p)), for a prime p */
+static gcry_mpi_t twopowmodphi(uint64_t m, const gcry_mpi_t p) {
+ gcry_mpi_t phi, r;
+ int n;
+
+ phi = gcry_mpi_new(0);
+ gcry_mpi_sub_ui(phi, p, 1);
+
+ /* count number of used bits in m */
+ for (n = 0; (1ULL << n) <= m; n++)
+ ;
+
+ r = gcry_mpi_new(0);
+ gcry_mpi_set_ui(r, 1);
+ while (n) { /* square and multiply algorithm for fast exponentiation */
+ n--;
+ gcry_mpi_mulm(r, r, r, phi);
+ if (m & ((uint64_t)1 << n)) {
+ gcry_mpi_add(r, r, r);
+ if (gcry_mpi_cmp(r, phi) >= 0)
+ gcry_mpi_sub(r, r, phi);
+ }
+ }
+
+ gcry_mpi_release(phi);
+ return r;
+}
+
+/* Decompose $x \in Z_n$ into $(xp,xq) \in Z_p \times Z_q$ using Chinese Remainder Theorem */
+static void CRT_decompose(gcry_mpi_t *xp, gcry_mpi_t *xq, const gcry_mpi_t x, const gcry_mpi_t p, const gcry_mpi_t q) {
+ *xp = gcry_mpi_new(0);
+ *xq = gcry_mpi_new(0);
+ gcry_mpi_mod(*xp, x, p);
+ gcry_mpi_mod(*xq, x, q);
+}
+
+/* Compose $(xp,xq) \in Z_p \times Z_q$ into $x \in Z_n$ using Chinese Remainder Theorem */
+static void CRT_compose(gcry_mpi_t *x, const gcry_mpi_t xp, const gcry_mpi_t xq, const gcry_mpi_t p, const gcry_mpi_t q) {
+ gcry_mpi_t a, u;
+
+ a = gcry_mpi_new(0);
+ u = gcry_mpi_new(0);
+ *x = gcry_mpi_new(0);
+ gcry_mpi_subm(a, xq, xp, q);
+ gcry_mpi_invm(u, p, q);
+ gcry_mpi_mulm(a, a, u, q); /* a = (xq - xp) / p (mod q) */
+ gcry_mpi_mul(*x, p, a);
+ gcry_mpi_add(*x, *x, xp); /* x = p * ((xq - xp) / p mod q) + xp */
+ gcry_mpi_release(a);
+ gcry_mpi_release(u);
+}
+
+static void initialize_libgcrypt(void) {
+ const char *p;
+ if (gcry_control(GCRYCTL_INITIALIZATION_FINISHED_P))
+ return;
+
+ p = gcry_check_version("1.4.5");
+ assert(p);
+
+ /* Turn off "secmem". Clients which whish to make use of this
+ * feature should initialize the library manually */
+ gcry_control(GCRYCTL_DISABLE_SECMEM);
+ gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
+}
+
+/******************************************************************************/
+
+size_t FSPRG_mskinbytes(unsigned _secpar) {
+ VALIDATE_SECPAR(_secpar);
+ return 2 + 2 * (_secpar / 2) / 8; /* to store header,p,q */
+}
+
+size_t FSPRG_mpkinbytes(unsigned _secpar) {
+ VALIDATE_SECPAR(_secpar);
+ return 2 + _secpar / 8; /* to store header,n */
+}
+
+size_t FSPRG_stateinbytes(unsigned _secpar) {
+ VALIDATE_SECPAR(_secpar);
+ return 2 + 2 * _secpar / 8 + 8; /* to store header,n,x,epoch */
+}
+
+static void store_secpar(void *buf, uint16_t secpar) {
+ secpar = secpar / 16 - 1;
+ ((uint8_t*) buf)[0] = (secpar >> 8) & 0xff;
+ ((uint8_t*) buf)[1] = (secpar >> 0) & 0xff;
+}
+
+static uint16_t read_secpar(const void *buf) {
+ uint16_t secpar;
+ secpar =
+ (uint16_t)(((uint8_t*) buf)[0]) << 8 |
+ (uint16_t)(((uint8_t*) buf)[1]) << 0;
+ return 16 * (secpar + 1);
+}
+
+void FSPRG_GenMK(void *msk, void *mpk, const void *seed, size_t seedlen, unsigned _secpar) {
+ uint8_t iseed[FSPRG_RECOMMENDED_SEEDLEN];
+ gcry_mpi_t n, p, q;
+ uint16_t secpar;
+
+ VALIDATE_SECPAR(_secpar);
+ secpar = _secpar;
+
+ initialize_libgcrypt();
+
+ if (!seed) {
+ gcry_randomize(iseed, FSPRG_RECOMMENDED_SEEDLEN, GCRY_STRONG_RANDOM);
+ seed = iseed;
+ seedlen = FSPRG_RECOMMENDED_SEEDLEN;
+ }
+
+ p = genprime3mod4(secpar / 2, seed, seedlen, RND_GEN_P);
+ q = genprime3mod4(secpar / 2, seed, seedlen, RND_GEN_Q);
+
+ if (msk) {
+ store_secpar(msk + 0, secpar);
+ mpi_export(msk + 2 + 0 * (secpar / 2) / 8, (secpar / 2) / 8, p);
+ mpi_export(msk + 2 + 1 * (secpar / 2) / 8, (secpar / 2) / 8, q);
+ }
+
+ if (mpk) {
+ n = gcry_mpi_new(0);
+ gcry_mpi_mul(n, p, q);
+ assert(gcry_mpi_get_nbits(n) == secpar);
+
+ store_secpar(mpk + 0, secpar);
+ mpi_export(mpk + 2, secpar / 8, n);
+
+ gcry_mpi_release(n);
+ }
+
+ gcry_mpi_release(p);
+ gcry_mpi_release(q);
+}
+
+void FSPRG_GenState0(void *state, const void *mpk, const void *seed, size_t seedlen) {
+ gcry_mpi_t n, x;
+ uint16_t secpar;
+
+ initialize_libgcrypt();
+
+ secpar = read_secpar(mpk + 0);
+ n = mpi_import(mpk + 2, secpar / 8);
+ x = gensquare(n, seed, seedlen, RND_GEN_X, secpar);
+
+ memcpy(state, mpk, 2 + secpar / 8);
+ mpi_export(state + 2 + 1 * secpar / 8, secpar / 8, x);
+ memset(state + 2 + 2 * secpar / 8, 0, 8);
+
+ gcry_mpi_release(n);
+ gcry_mpi_release(x);
+}
+
+void FSPRG_Evolve(void *state) {
+ gcry_mpi_t n, x;
+ uint16_t secpar;
+ uint64_t epoch;
+
+ initialize_libgcrypt();
+
+ secpar = read_secpar(state + 0);
+ n = mpi_import(state + 2 + 0 * secpar / 8, secpar / 8);
+ x = mpi_import(state + 2 + 1 * secpar / 8, secpar / 8);
+ epoch = uint64_import(state + 2 + 2 * secpar / 8, 8);
+
+ gcry_mpi_mulm(x, x, x, n);
+ epoch++;
+
+ mpi_export(state + 2 + 1 * secpar / 8, secpar / 8, x);
+ uint64_export(state + 2 + 2 * secpar / 8, 8, epoch);
+
+ gcry_mpi_release(n);
+ gcry_mpi_release(x);
+}
+
+uint64_t FSPRG_GetEpoch(const void *state) {
+ uint16_t secpar;
+ secpar = read_secpar(state + 0);
+ return uint64_import(state + 2 + 2 * secpar / 8, 8);
+}
+
+void FSPRG_Seek(void *state, uint64_t epoch, const void *msk, const void *seed, size_t seedlen) {
+ gcry_mpi_t p, q, n, x, xp, xq, kp, kq, xm;
+ uint16_t secpar;
+
+ initialize_libgcrypt();
+
+ secpar = read_secpar(msk + 0);
+ p = mpi_import(msk + 2 + 0 * (secpar / 2) / 8, (secpar / 2) / 8);
+ q = mpi_import(msk + 2 + 1 * (secpar / 2) / 8, (secpar / 2) / 8);
+
+ n = gcry_mpi_new(0);
+ gcry_mpi_mul(n, p, q);
+
+ x = gensquare(n, seed, seedlen, RND_GEN_X, secpar);
+ CRT_decompose(&xp, &xq, x, p, q); /* split (mod n) into (mod p) and (mod q) using CRT */
+
+ kp = twopowmodphi(epoch, p); /* compute 2^epoch (mod phi(p)) */
+ kq = twopowmodphi(epoch, q); /* compute 2^epoch (mod phi(q)) */
+
+ gcry_mpi_powm(xp, xp, kp, p); /* compute x^(2^epoch) (mod p) */
+ gcry_mpi_powm(xq, xq, kq, q); /* compute x^(2^epoch) (mod q) */
+
+ CRT_compose(&xm, xp, xq, p, q); /* combine (mod p) and (mod q) to (mod n) using CRT */
+
+ store_secpar(state + 0, secpar);
+ mpi_export(state + 2 + 0 * secpar / 8, secpar / 8, n);
+ mpi_export(state + 2 + 1 * secpar / 8, secpar / 8, xm);
+ uint64_export(state + 2 + 2 * secpar / 8, 8, epoch);
+
+ gcry_mpi_release(p);
+ gcry_mpi_release(q);
+ gcry_mpi_release(n);
+ gcry_mpi_release(x);
+ gcry_mpi_release(xp);
+ gcry_mpi_release(xq);
+ gcry_mpi_release(kp);
+ gcry_mpi_release(kq);
+ gcry_mpi_release(xm);
+}
+
+void FSPRG_GetKey(const void *state, void *key, size_t keylen, uint32_t idx) {
+ uint16_t secpar;
+
+ initialize_libgcrypt();
+
+ secpar = read_secpar(state + 0);
+ det_randomize(key, keylen, state + 2, 2 * secpar / 8 + 8, idx);
+}
diff --git a/src/journal/fsprg.h b/src/journal/fsprg.h
new file mode 100644
index 0000000000..150d034828
--- /dev/null
+++ b/src/journal/fsprg.h
@@ -0,0 +1,66 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef __fsprgh__
+#define __fsprgh__
+
+/*
+ * fsprg v0.1 - (seekable) forward-secure pseudorandom generator
+ * Copyright (C) 2012 B. Poettering
+ * Contact: fsprg@point-at-infinity.org
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA
+ *
+ */
+
+#include <sys/types.h>
+#include <inttypes.h>
+
+#include "macro.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define FSPRG_RECOMMENDED_SECPAR 1536
+#define FSPRG_RECOMMENDED_SEEDLEN (96/8)
+
+size_t FSPRG_mskinbytes(unsigned secpar) _const_;
+size_t FSPRG_mpkinbytes(unsigned secpar) _const_;
+size_t FSPRG_stateinbytes(unsigned secpar) _const_;
+
+/* Setup msk and mpk. Providing seed != NULL makes this algorithm deterministic. */
+void FSPRG_GenMK(void *msk, void *mpk, const void *seed, size_t seedlen, unsigned secpar);
+
+/* Initialize state deterministically in dependence on seed. */
+/* Note: in case one wants to run only one GenState0 per GenMK it is safe to use
+ the same seed for both GenMK and GenState0.
+*/
+void FSPRG_GenState0(void *state, const void *mpk, const void *seed, size_t seedlen);
+
+void FSPRG_Evolve(void *state);
+
+uint64_t FSPRG_GetEpoch(const void *state) _pure_;
+
+/* Seek to any arbitrary state (by providing msk together with seed from GenState0). */
+void FSPRG_Seek(void *state, uint64_t epoch, const void *msk, const void *seed, size_t seedlen);
+
+void FSPRG_GetKey(const void *state, void *key, size_t keylen, uint32_t idx);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/src/journal/journal-authenticate.c b/src/journal/journal-authenticate.c
new file mode 100644
index 0000000000..64bf96874e
--- /dev/null
+++ b/src/journal/journal-authenticate.c
@@ -0,0 +1,563 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <fcntl.h>
+#include <sys/mman.h>
+
+#include "journal-def.h"
+#include "journal-file.h"
+#include "journal-authenticate.h"
+#include "fsprg.h"
+
+static uint64_t journal_file_tag_seqnum(JournalFile *f) {
+ uint64_t r;
+
+ assert(f);
+
+ r = le64toh(f->header->n_tags) + 1;
+ f->header->n_tags = htole64(r);
+
+ return r;
+}
+
+int journal_file_append_tag(JournalFile *f) {
+ Object *o;
+ uint64_t p;
+ int r;
+
+ assert(f);
+
+ if (!f->seal)
+ return 0;
+
+ if (!f->hmac_running)
+ return 0;
+
+ assert(f->hmac);
+
+ r = journal_file_append_object(f, OBJECT_TAG, sizeof(struct TagObject), &o, &p);
+ if (r < 0)
+ return r;
+
+ o->tag.seqnum = htole64(journal_file_tag_seqnum(f));
+ o->tag.epoch = htole64(FSPRG_GetEpoch(f->fsprg_state));
+
+ log_debug("Writing tag %llu for epoch %llu\n",
+ (unsigned long long) le64toh(o->tag.seqnum),
+ (unsigned long long) FSPRG_GetEpoch(f->fsprg_state));
+
+ /* Add the tag object itself, so that we can protect its
+ * header. This will exclude the actual hash value in it */
+ r = journal_file_hmac_put_object(f, OBJECT_TAG, o, p);
+ if (r < 0)
+ return r;
+
+ /* Get the HMAC tag and store it in the object */
+ memcpy(o->tag.tag, gcry_md_read(f->hmac, 0), TAG_LENGTH);
+ f->hmac_running = false;
+
+ return 0;
+}
+
+int journal_file_hmac_start(JournalFile *f) {
+ uint8_t key[256 / 8]; /* Let's pass 256 bit from FSPRG to HMAC */
+ assert(f);
+
+ if (!f->seal)
+ return 0;
+
+ if (f->hmac_running)
+ return 0;
+
+ /* Prepare HMAC for next cycle */
+ gcry_md_reset(f->hmac);
+ FSPRG_GetKey(f->fsprg_state, key, sizeof(key), 0);
+ gcry_md_setkey(f->hmac, key, sizeof(key));
+
+ f->hmac_running = true;
+
+ return 0;
+}
+
+static int journal_file_get_epoch(JournalFile *f, uint64_t realtime, uint64_t *epoch) {
+ uint64_t t;
+
+ assert(f);
+ assert(epoch);
+ assert(f->seal);
+
+ if (f->fss_start_usec == 0 ||
+ f->fss_interval_usec == 0)
+ return -ENOTSUP;
+
+ if (realtime < f->fss_start_usec)
+ return -ESTALE;
+
+ t = realtime - f->fss_start_usec;
+ t = t / f->fss_interval_usec;
+
+ *epoch = t;
+ return 0;
+}
+
+static int journal_file_fsprg_need_evolve(JournalFile *f, uint64_t realtime) {
+ uint64_t goal, epoch;
+ int r;
+ assert(f);
+
+ if (!f->seal)
+ return 0;
+
+ r = journal_file_get_epoch(f, realtime, &goal);
+ if (r < 0)
+ return r;
+
+ epoch = FSPRG_GetEpoch(f->fsprg_state);
+ if (epoch > goal)
+ return -ESTALE;
+
+ return epoch != goal;
+}
+
+int journal_file_fsprg_evolve(JournalFile *f, uint64_t realtime) {
+ uint64_t goal, epoch;
+ int r;
+
+ assert(f);
+
+ if (!f->seal)
+ return 0;
+
+ r = journal_file_get_epoch(f, realtime, &goal);
+ if (r < 0)
+ return r;
+
+ epoch = FSPRG_GetEpoch(f->fsprg_state);
+ if (epoch < goal)
+ log_debug("Evolving FSPRG key from epoch %llu to %llu.", (unsigned long long) epoch, (unsigned long long) goal);
+
+ for (;;) {
+ if (epoch > goal)
+ return -ESTALE;
+ if (epoch == goal)
+ return 0;
+
+ FSPRG_Evolve(f->fsprg_state);
+ epoch = FSPRG_GetEpoch(f->fsprg_state);
+ }
+}
+
+int journal_file_fsprg_seek(JournalFile *f, uint64_t goal) {
+ void *msk;
+ uint64_t epoch;
+
+ assert(f);
+
+ if (!f->seal)
+ return 0;
+
+ assert(f->fsprg_seed);
+
+ if (f->fsprg_state) {
+ /* Cheaper... */
+
+ epoch = FSPRG_GetEpoch(f->fsprg_state);
+ if (goal == epoch)
+ return 0;
+
+ if (goal == epoch+1) {
+ FSPRG_Evolve(f->fsprg_state);
+ return 0;
+ }
+ } else {
+ f->fsprg_state_size = FSPRG_stateinbytes(FSPRG_RECOMMENDED_SECPAR);
+ f->fsprg_state = malloc(f->fsprg_state_size);
+
+ if (!f->fsprg_state)
+ return -ENOMEM;
+ }
+
+ log_debug("Seeking FSPRG key to %llu.", (unsigned long long) goal);
+
+ msk = alloca(FSPRG_mskinbytes(FSPRG_RECOMMENDED_SECPAR));
+ FSPRG_GenMK(msk, NULL, f->fsprg_seed, f->fsprg_seed_size, FSPRG_RECOMMENDED_SECPAR);
+ FSPRG_Seek(f->fsprg_state, goal, msk, f->fsprg_seed, f->fsprg_seed_size);
+ return 0;
+}
+
+int journal_file_maybe_append_tag(JournalFile *f, uint64_t realtime) {
+ int r;
+
+ assert(f);
+
+ if (!f->seal)
+ return 0;
+
+ if (realtime <= 0)
+ realtime = now(CLOCK_REALTIME);
+
+ r = journal_file_fsprg_need_evolve(f, realtime);
+ if (r <= 0)
+ return 0;
+
+ r = journal_file_append_tag(f);
+ if (r < 0)
+ return r;
+
+ r = journal_file_fsprg_evolve(f, realtime);
+ if (r < 0)
+ return r;
+
+ return 0;
+}
+
+int journal_file_hmac_put_object(JournalFile *f, int type, Object *o, uint64_t p) {
+ int r;
+
+ assert(f);
+
+ if (!f->seal)
+ return 0;
+
+ r = journal_file_hmac_start(f);
+ if (r < 0)
+ return r;
+
+ if (!o) {
+ r = journal_file_move_to_object(f, type, p, &o);
+ if (r < 0)
+ return r;
+ } else {
+ if (type >= 0 && o->object.type != type)
+ return -EBADMSG;
+ }
+
+ gcry_md_write(f->hmac, o, offsetof(ObjectHeader, payload));
+
+ switch (o->object.type) {
+
+ case OBJECT_DATA:
+ /* All but hash and payload are mutable */
+ gcry_md_write(f->hmac, &o->data.hash, sizeof(o->data.hash));
+ gcry_md_write(f->hmac, o->data.payload, le64toh(o->object.size) - offsetof(DataObject, payload));
+ break;
+
+ case OBJECT_FIELD:
+ /* Same here */
+ gcry_md_write(f->hmac, &o->field.hash, sizeof(o->field.hash));
+ gcry_md_write(f->hmac, o->field.payload, le64toh(o->object.size) - offsetof(FieldObject, payload));
+ break;
+
+ case OBJECT_ENTRY:
+ /* All */
+ gcry_md_write(f->hmac, &o->entry.seqnum, le64toh(o->object.size) - offsetof(EntryObject, seqnum));
+ break;
+
+ case OBJECT_FIELD_HASH_TABLE:
+ case OBJECT_DATA_HASH_TABLE:
+ case OBJECT_ENTRY_ARRAY:
+ /* Nothing: everything is mutable */
+ break;
+
+ case OBJECT_TAG:
+ /* All but the tag itself */
+ gcry_md_write(f->hmac, &o->tag.seqnum, sizeof(o->tag.seqnum));
+ gcry_md_write(f->hmac, &o->tag.epoch, sizeof(o->tag.epoch));
+ break;
+ default:
+ return -EINVAL;
+ }
+
+ return 0;
+}
+
+int journal_file_hmac_put_header(JournalFile *f) {
+ int r;
+
+ assert(f);
+
+ if (!f->seal)
+ return 0;
+
+ r = journal_file_hmac_start(f);
+ if (r < 0)
+ return r;
+
+ /* All but state+reserved, boot_id, arena_size,
+ * tail_object_offset, n_objects, n_entries,
+ * tail_entry_seqnum, head_entry_seqnum, entry_array_offset,
+ * head_entry_realtime, tail_entry_realtime,
+ * tail_entry_monotonic, n_data, n_fields, n_tags,
+ * n_entry_arrays. */
+
+ gcry_md_write(f->hmac, f->header->signature, offsetof(Header, state) - offsetof(Header, signature));
+ gcry_md_write(f->hmac, &f->header->file_id, offsetof(Header, boot_id) - offsetof(Header, file_id));
+ gcry_md_write(f->hmac, &f->header->seqnum_id, offsetof(Header, arena_size) - offsetof(Header, seqnum_id));
+ gcry_md_write(f->hmac, &f->header->data_hash_table_offset, offsetof(Header, tail_object_offset) - offsetof(Header, data_hash_table_offset));
+
+ return 0;
+}
+
+int journal_file_fss_load(JournalFile *f) {
+ int r, fd = -1;
+ char *p = NULL;
+ struct stat st;
+ FSSHeader *m = NULL;
+ sd_id128_t machine;
+
+ assert(f);
+
+ if (!f->seal)
+ return 0;
+
+ r = sd_id128_get_machine(&machine);
+ if (r < 0)
+ return r;
+
+ if (asprintf(&p, "/var/log/journal/" SD_ID128_FORMAT_STR "/fss",
+ SD_ID128_FORMAT_VAL(machine)) < 0)
+ return -ENOMEM;
+
+ fd = open(p, O_RDWR|O_CLOEXEC|O_NOCTTY, 0600);
+ if (fd < 0) {
+ if (errno != ENOENT)
+ log_error("Failed to open %s: %m", p);
+
+ r = -errno;
+ goto finish;
+ }
+
+ if (fstat(fd, &st) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ if (st.st_size < (off_t) sizeof(FSSHeader)) {
+ r = -ENODATA;
+ goto finish;
+ }
+
+ m = mmap(NULL, PAGE_ALIGN(sizeof(FSSHeader)), PROT_READ, MAP_SHARED, fd, 0);
+ if (m == MAP_FAILED) {
+ m = NULL;
+ r = -errno;
+ goto finish;
+ }
+
+ if (memcmp(m->signature, FSS_HEADER_SIGNATURE, 8) != 0) {
+ r = -EBADMSG;
+ goto finish;
+ }
+
+ if (m->incompatible_flags != 0) {
+ r = -EPROTONOSUPPORT;
+ goto finish;
+ }
+
+ if (le64toh(m->header_size) < sizeof(FSSHeader)) {
+ r = -EBADMSG;
+ goto finish;
+ }
+
+ if (le64toh(m->fsprg_state_size) != FSPRG_stateinbytes(le16toh(m->fsprg_secpar))) {
+ r = -EBADMSG;
+ goto finish;
+ }
+
+ f->fss_file_size = le64toh(m->header_size) + le64toh(m->fsprg_state_size);
+ if ((uint64_t) st.st_size < f->fss_file_size) {
+ r = -ENODATA;
+ goto finish;
+ }
+
+ if (!sd_id128_equal(machine, m->machine_id)) {
+ r = -EHOSTDOWN;
+ goto finish;
+ }
+
+ if (le64toh(m->start_usec) <= 0 ||
+ le64toh(m->interval_usec) <= 0) {
+ r = -EBADMSG;
+ goto finish;
+ }
+
+ f->fss_file = mmap(NULL, PAGE_ALIGN(f->fss_file_size), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
+ if (f->fss_file == MAP_FAILED) {
+ f->fss_file = NULL;
+ r = -errno;
+ goto finish;
+ }
+
+ f->fss_start_usec = le64toh(f->fss_file->start_usec);
+ f->fss_interval_usec = le64toh(f->fss_file->interval_usec);
+
+ f->fsprg_state = (uint8_t*) f->fss_file + le64toh(f->fss_file->header_size);
+ f->fsprg_state_size = le64toh(f->fss_file->fsprg_state_size);
+
+ r = 0;
+
+finish:
+ if (m)
+ munmap(m, PAGE_ALIGN(sizeof(FSSHeader)));
+
+ if (fd >= 0)
+ close_nointr_nofail(fd);
+
+ free(p);
+ return r;
+}
+
+static void initialize_libgcrypt(void) {
+ const char *p;
+
+ if (gcry_control(GCRYCTL_INITIALIZATION_FINISHED_P))
+ return;
+
+ p = gcry_check_version("1.4.5");
+ assert(p);
+
+ gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
+}
+
+int journal_file_hmac_setup(JournalFile *f) {
+ gcry_error_t e;
+
+ if (!f->seal)
+ return 0;
+
+ initialize_libgcrypt();
+
+ e = gcry_md_open(&f->hmac, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
+ if (e != 0)
+ return -ENOTSUP;
+
+ return 0;
+}
+
+int journal_file_append_first_tag(JournalFile *f) {
+ int r;
+ uint64_t p;
+
+ if (!f->seal)
+ return 0;
+
+ log_debug("Calculating first tag...");
+
+ r = journal_file_hmac_put_header(f);
+ if (r < 0)
+ return r;
+
+ p = le64toh(f->header->field_hash_table_offset);
+ if (p < offsetof(Object, hash_table.items))
+ return -EINVAL;
+ p -= offsetof(Object, hash_table.items);
+
+ r = journal_file_hmac_put_object(f, OBJECT_FIELD_HASH_TABLE, NULL, p);
+ if (r < 0)
+ return r;
+
+ p = le64toh(f->header->data_hash_table_offset);
+ if (p < offsetof(Object, hash_table.items))
+ return -EINVAL;
+ p -= offsetof(Object, hash_table.items);
+
+ r = journal_file_hmac_put_object(f, OBJECT_DATA_HASH_TABLE, NULL, p);
+ if (r < 0)
+ return r;
+
+ r = journal_file_append_tag(f);
+ if (r < 0)
+ return r;
+
+ return 0;
+}
+
+int journal_file_parse_verification_key(JournalFile *f, const char *key) {
+ uint8_t *seed;
+ size_t seed_size, c;
+ const char *k;
+ int r;
+ unsigned long long start, interval;
+
+ seed_size = FSPRG_RECOMMENDED_SEEDLEN;
+ seed = malloc(seed_size);
+ if (!seed)
+ return -ENOMEM;
+
+ k = key;
+ for (c = 0; c < seed_size; c++) {
+ int x, y;
+
+ while (*k == '-')
+ k++;
+
+ x = unhexchar(*k);
+ if (x < 0) {
+ free(seed);
+ return -EINVAL;
+ }
+ k++;
+ y = unhexchar(*k);
+ if (y < 0) {
+ free(seed);
+ return -EINVAL;
+ }
+ k++;
+
+ seed[c] = (uint8_t) (x * 16 + y);
+ }
+
+ if (*k != '/') {
+ free(seed);
+ return -EINVAL;
+ }
+ k++;
+
+ r = sscanf(k, "%llx-%llx", &start, &interval);
+ if (r != 2) {
+ free(seed);
+ return -EINVAL;
+ }
+
+ f->fsprg_seed = seed;
+ f->fsprg_seed_size = seed_size;
+
+ f->fss_start_usec = start * interval;
+ f->fss_interval_usec = interval;
+
+ return 0;
+}
+
+bool journal_file_next_evolve_usec(JournalFile *f, usec_t *u) {
+ uint64_t epoch;
+
+ assert(f);
+ assert(u);
+
+ if (!f->seal)
+ return false;
+
+ epoch = FSPRG_GetEpoch(f->fsprg_state);
+
+ *u = (usec_t) (f->fss_start_usec + f->fss_interval_usec * epoch + f->fss_interval_usec);
+
+ return true;
+}
diff --git a/src/journal/journal-authenticate.h b/src/journal/journal-authenticate.h
new file mode 100644
index 0000000000..0aaf836721
--- /dev/null
+++ b/src/journal/journal-authenticate.h
@@ -0,0 +1,44 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdbool.h>
+#include <inttypes.h>
+
+#include "journal-file.h"
+
+int journal_file_append_tag(JournalFile *f);
+int journal_file_maybe_append_tag(JournalFile *f, uint64_t realtime);
+int journal_file_append_first_tag(JournalFile *f);
+
+int journal_file_hmac_setup(JournalFile *f);
+int journal_file_hmac_start(JournalFile *f);
+int journal_file_hmac_put_header(JournalFile *f);
+int journal_file_hmac_put_object(JournalFile *f, int type, Object *o, uint64_t p);
+
+int journal_file_fss_load(JournalFile *f);
+int journal_file_parse_verification_key(JournalFile *f, const char *key);
+
+int journal_file_fsprg_evolve(JournalFile *f, uint64_t realtime);
+int journal_file_fsprg_seek(JournalFile *f, uint64_t epoch);
+
+bool journal_file_next_evolve_usec(JournalFile *f, usec_t *u);
diff --git a/src/journal/journal-def.h b/src/journal/journal-def.h
new file mode 100644
index 0000000000..7e407a416c
--- /dev/null
+++ b/src/journal/journal-def.h
@@ -0,0 +1,216 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "sparse-endian.h"
+
+#include <systemd/sd-id128.h>
+
+#include "macro.h"
+
+/*
+ * If you change this file you probably should also change its documentation:
+ *
+ * http://www.freedesktop.org/wiki/Software/systemd/journal-files
+ *
+ */
+
+typedef struct Header Header;
+
+typedef struct ObjectHeader ObjectHeader;
+typedef union Object Object;
+
+typedef struct DataObject DataObject;
+typedef struct FieldObject FieldObject;
+typedef struct EntryObject EntryObject;
+typedef struct HashTableObject HashTableObject;
+typedef struct EntryArrayObject EntryArrayObject;
+typedef struct TagObject TagObject;
+
+typedef struct EntryItem EntryItem;
+typedef struct HashItem HashItem;
+
+typedef struct FSSHeader FSSHeader;
+
+/* Object types */
+enum {
+ OBJECT_UNUSED,
+ OBJECT_DATA,
+ OBJECT_FIELD,
+ OBJECT_ENTRY,
+ OBJECT_DATA_HASH_TABLE,
+ OBJECT_FIELD_HASH_TABLE,
+ OBJECT_ENTRY_ARRAY,
+ OBJECT_TAG,
+ _OBJECT_TYPE_MAX
+};
+
+/* Object flags */
+enum {
+ OBJECT_COMPRESSED = 1
+};
+
+struct ObjectHeader {
+ uint8_t type;
+ uint8_t flags;
+ uint8_t reserved[6];
+ le64_t size;
+ uint8_t payload[];
+} _packed_;
+
+struct DataObject {
+ ObjectHeader object;
+ le64_t hash;
+ le64_t next_hash_offset;
+ le64_t next_field_offset;
+ le64_t entry_offset; /* the first array entry we store inline */
+ le64_t entry_array_offset;
+ le64_t n_entries;
+ uint8_t payload[];
+} _packed_;
+
+struct FieldObject {
+ ObjectHeader object;
+ le64_t hash;
+ le64_t next_hash_offset;
+ le64_t head_data_offset;
+ uint8_t payload[];
+} _packed_;
+
+struct EntryItem {
+ le64_t object_offset;
+ le64_t hash;
+} _packed_;
+
+struct EntryObject {
+ ObjectHeader object;
+ le64_t seqnum;
+ le64_t realtime;
+ le64_t monotonic;
+ sd_id128_t boot_id;
+ le64_t xor_hash;
+ EntryItem items[];
+} _packed_;
+
+struct HashItem {
+ le64_t head_hash_offset;
+ le64_t tail_hash_offset;
+} _packed_;
+
+struct HashTableObject {
+ ObjectHeader object;
+ HashItem items[];
+} _packed_;
+
+struct EntryArrayObject {
+ ObjectHeader object;
+ le64_t next_entry_array_offset;
+ le64_t items[];
+} _packed_;
+
+#define TAG_LENGTH (256/8)
+
+struct TagObject {
+ ObjectHeader object;
+ le64_t seqnum;
+ le64_t epoch;
+ uint8_t tag[TAG_LENGTH]; /* SHA-256 HMAC */
+} _packed_;
+
+union Object {
+ ObjectHeader object;
+ DataObject data;
+ FieldObject field;
+ EntryObject entry;
+ HashTableObject hash_table;
+ EntryArrayObject entry_array;
+ TagObject tag;
+};
+
+enum {
+ STATE_OFFLINE = 0,
+ STATE_ONLINE = 1,
+ STATE_ARCHIVED = 2,
+ _STATE_MAX
+};
+
+/* Header flags */
+enum {
+ HEADER_INCOMPATIBLE_COMPRESSED = 1
+};
+
+enum {
+ HEADER_COMPATIBLE_SEALED = 1
+};
+
+#define HEADER_SIGNATURE ((char[]) { 'L', 'P', 'K', 'S', 'H', 'H', 'R', 'H' })
+
+struct Header {
+ uint8_t signature[8]; /* "LPKSHHRH" */
+ le32_t compatible_flags;
+ le32_t incompatible_flags;
+ uint8_t state;
+ uint8_t reserved[7];
+ sd_id128_t file_id;
+ sd_id128_t machine_id;
+ sd_id128_t boot_id; /* last writer */
+ sd_id128_t seqnum_id;
+ le64_t header_size;
+ le64_t arena_size;
+ le64_t data_hash_table_offset;
+ le64_t data_hash_table_size;
+ le64_t field_hash_table_offset;
+ le64_t field_hash_table_size;
+ le64_t tail_object_offset;
+ le64_t n_objects;
+ le64_t n_entries;
+ le64_t tail_entry_seqnum;
+ le64_t head_entry_seqnum;
+ le64_t entry_array_offset;
+ le64_t head_entry_realtime;
+ le64_t tail_entry_realtime;
+ le64_t tail_entry_monotonic;
+ /* Added in 187 */
+ le64_t n_data;
+ le64_t n_fields;
+ /* Added in 189 */
+ le64_t n_tags;
+ le64_t n_entry_arrays;
+
+ /* Size: 224 */
+} _packed_;
+
+#define FSS_HEADER_SIGNATURE ((char[]) { 'K', 'S', 'H', 'H', 'R', 'H', 'L', 'P' })
+
+struct FSSHeader {
+ uint8_t signature[8]; /* "KSHHRHLP" */
+ le32_t compatible_flags;
+ le32_t incompatible_flags;
+ sd_id128_t machine_id;
+ sd_id128_t boot_id; /* last writer */
+ le64_t header_size;
+ le64_t start_usec;
+ le64_t interval_usec;
+ le16_t fsprg_secpar;
+ le16_t reserved[3];
+ le64_t fsprg_state_size;
+} _packed_;
diff --git a/src/journal/journal-file.c b/src/journal/journal-file.c
new file mode 100644
index 0000000000..38499a6881
--- /dev/null
+++ b/src/journal/journal-file.c
@@ -0,0 +1,2914 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/mman.h>
+#include <errno.h>
+#include <sys/uio.h>
+#include <unistd.h>
+#include <sys/statvfs.h>
+#include <fcntl.h>
+#include <stddef.h>
+
+#ifdef HAVE_XATTR
+#include <attr/xattr.h>
+#endif
+
+#include "journal-def.h"
+#include "journal-file.h"
+#include "journal-authenticate.h"
+#include "lookup3.h"
+#include "compress.h"
+#include "fsprg.h"
+
+#define DEFAULT_DATA_HASH_TABLE_SIZE (2047ULL*sizeof(HashItem))
+#define DEFAULT_FIELD_HASH_TABLE_SIZE (333ULL*sizeof(HashItem))
+
+#define COMPRESSION_SIZE_THRESHOLD (512ULL)
+
+/* This is the minimum journal file size */
+#define JOURNAL_FILE_SIZE_MIN (4ULL*1024ULL*1024ULL) /* 4 MiB */
+
+/* These are the lower and upper bounds if we deduce the max_use value
+ * from the file system size */
+#define DEFAULT_MAX_USE_LOWER (1ULL*1024ULL*1024ULL) /* 1 MiB */
+#define DEFAULT_MAX_USE_UPPER (4ULL*1024ULL*1024ULL*1024ULL) /* 4 GiB */
+
+/* This is the upper bound if we deduce max_size from max_use */
+#define DEFAULT_MAX_SIZE_UPPER (128ULL*1024ULL*1024ULL) /* 128 MiB */
+
+/* This is the upper bound if we deduce the keep_free value from the
+ * file system size */
+#define DEFAULT_KEEP_FREE_UPPER (4ULL*1024ULL*1024ULL*1024ULL) /* 4 GiB */
+
+/* This is the keep_free value when we can't determine the system
+ * size */
+#define DEFAULT_KEEP_FREE (1024ULL*1024ULL) /* 1 MB */
+
+/* n_data was the first entry we added after the initial file format design */
+#define HEADER_SIZE_MIN ALIGN64(offsetof(Header, n_data))
+
+/* How many entries to keep in the entry array chain cache at max */
+#define CHAIN_CACHE_MAX 20
+
+int journal_file_set_online(JournalFile *f) {
+ assert(f);
+
+ if (!f->writable)
+ return -EPERM;
+
+ if (!(f->fd >= 0 && f->header))
+ return -EINVAL;
+
+ switch(f->header->state) {
+ case STATE_ONLINE:
+ return 0;
+
+ case STATE_OFFLINE:
+ f->header->state = STATE_ONLINE;
+ fsync(f->fd);
+ return 0;
+
+ default:
+ return -EINVAL;
+ }
+}
+
+int journal_file_set_offline(JournalFile *f) {
+ assert(f);
+
+ if (!f->writable)
+ return -EPERM;
+
+ if (!(f->fd >= 0 && f->header))
+ return -EINVAL;
+
+ if (f->header->state != STATE_ONLINE)
+ return 0;
+
+ fsync(f->fd);
+
+ f->header->state = STATE_OFFLINE;
+
+ fsync(f->fd);
+
+ return 0;
+}
+
+void journal_file_close(JournalFile *f) {
+ assert(f);
+
+#ifdef HAVE_GCRYPT
+ /* Write the final tag */
+ if (f->seal && f->writable)
+ journal_file_append_tag(f);
+#endif
+
+ /* Sync everything to disk, before we mark the file offline */
+ if (f->mmap && f->fd >= 0)
+ mmap_cache_close_fd(f->mmap, f->fd);
+
+ journal_file_set_offline(f);
+
+ if (f->header)
+ munmap(f->header, PAGE_ALIGN(sizeof(Header)));
+
+ if (f->fd >= 0)
+ close_nointr_nofail(f->fd);
+
+ free(f->path);
+
+ if (f->mmap)
+ mmap_cache_unref(f->mmap);
+
+ hashmap_free_free(f->chain_cache);
+
+#ifdef HAVE_XZ
+ free(f->compress_buffer);
+#endif
+
+#ifdef HAVE_GCRYPT
+ if (f->fss_file)
+ munmap(f->fss_file, PAGE_ALIGN(f->fss_file_size));
+ else if (f->fsprg_state)
+ free(f->fsprg_state);
+
+ free(f->fsprg_seed);
+
+ if (f->hmac)
+ gcry_md_close(f->hmac);
+#endif
+
+ free(f);
+}
+
+static int journal_file_init_header(JournalFile *f, JournalFile *template) {
+ Header h;
+ ssize_t k;
+ int r;
+
+ assert(f);
+
+ zero(h);
+ memcpy(h.signature, HEADER_SIGNATURE, 8);
+ h.header_size = htole64(ALIGN64(sizeof(h)));
+
+ h.incompatible_flags =
+ htole32(f->compress ? HEADER_INCOMPATIBLE_COMPRESSED : 0);
+
+ h.compatible_flags =
+ htole32(f->seal ? HEADER_COMPATIBLE_SEALED : 0);
+
+ r = sd_id128_randomize(&h.file_id);
+ if (r < 0)
+ return r;
+
+ if (template) {
+ h.seqnum_id = template->header->seqnum_id;
+ h.tail_entry_seqnum = template->header->tail_entry_seqnum;
+ } else
+ h.seqnum_id = h.file_id;
+
+ k = pwrite(f->fd, &h, sizeof(h), 0);
+ if (k < 0)
+ return -errno;
+
+ if (k != sizeof(h))
+ return -EIO;
+
+ return 0;
+}
+
+static int journal_file_refresh_header(JournalFile *f) {
+ int r;
+ sd_id128_t boot_id;
+
+ assert(f);
+
+ r = sd_id128_get_machine(&f->header->machine_id);
+ if (r < 0)
+ return r;
+
+ r = sd_id128_get_boot(&boot_id);
+ if (r < 0)
+ return r;
+
+ if (sd_id128_equal(boot_id, f->header->boot_id))
+ f->tail_entry_monotonic_valid = true;
+
+ f->header->boot_id = boot_id;
+
+ journal_file_set_online(f);
+
+ /* Sync the online state to disk */
+ msync(f->header, PAGE_ALIGN(sizeof(Header)), MS_SYNC);
+ fdatasync(f->fd);
+
+ return 0;
+}
+
+static int journal_file_verify_header(JournalFile *f) {
+ assert(f);
+
+ if (memcmp(f->header->signature, HEADER_SIGNATURE, 8))
+ return -EBADMSG;
+
+ /* In both read and write mode we refuse to open files with
+ * incompatible flags we don't know */
+#ifdef HAVE_XZ
+ if ((le32toh(f->header->incompatible_flags) & ~HEADER_INCOMPATIBLE_COMPRESSED) != 0)
+ return -EPROTONOSUPPORT;
+#else
+ if (f->header->incompatible_flags != 0)
+ return -EPROTONOSUPPORT;
+#endif
+
+ /* When open for writing we refuse to open files with
+ * compatible flags, too */
+ if (f->writable) {
+#ifdef HAVE_GCRYPT
+ if ((le32toh(f->header->compatible_flags) & ~HEADER_COMPATIBLE_SEALED) != 0)
+ return -EPROTONOSUPPORT;
+#else
+ if (f->header->compatible_flags != 0)
+ return -EPROTONOSUPPORT;
+#endif
+ }
+
+ if (f->header->state >= _STATE_MAX)
+ return -EBADMSG;
+
+ /* The first addition was n_data, so check that we are at least this large */
+ if (le64toh(f->header->header_size) < HEADER_SIZE_MIN)
+ return -EBADMSG;
+
+ if (JOURNAL_HEADER_SEALED(f->header) && !JOURNAL_HEADER_CONTAINS(f->header, n_entry_arrays))
+ return -EBADMSG;
+
+ if ((le64toh(f->header->header_size) + le64toh(f->header->arena_size)) > (uint64_t) f->last_stat.st_size)
+ return -ENODATA;
+
+ if (le64toh(f->header->tail_object_offset) > (le64toh(f->header->header_size) + le64toh(f->header->arena_size)))
+ return -ENODATA;
+
+ if (!VALID64(le64toh(f->header->data_hash_table_offset)) ||
+ !VALID64(le64toh(f->header->field_hash_table_offset)) ||
+ !VALID64(le64toh(f->header->tail_object_offset)) ||
+ !VALID64(le64toh(f->header->entry_array_offset)))
+ return -ENODATA;
+
+ if (le64toh(f->header->data_hash_table_offset) < le64toh(f->header->header_size) ||
+ le64toh(f->header->field_hash_table_offset) < le64toh(f->header->header_size) ||
+ le64toh(f->header->tail_object_offset) < le64toh(f->header->header_size) ||
+ le64toh(f->header->entry_array_offset) < le64toh(f->header->header_size))
+ return -ENODATA;
+
+ if (f->writable) {
+ uint8_t state;
+ sd_id128_t machine_id;
+ int r;
+
+ r = sd_id128_get_machine(&machine_id);
+ if (r < 0)
+ return r;
+
+ if (!sd_id128_equal(machine_id, f->header->machine_id))
+ return -EHOSTDOWN;
+
+ state = f->header->state;
+
+ if (state == STATE_ONLINE) {
+ log_debug("Journal file %s is already online. Assuming unclean closing.", f->path);
+ return -EBUSY;
+ } else if (state == STATE_ARCHIVED)
+ return -ESHUTDOWN;
+ else if (state != STATE_OFFLINE) {
+ log_debug("Journal file %s has unknown state %u.", f->path, state);
+ return -EBUSY;
+ }
+ }
+
+ f->compress = JOURNAL_HEADER_COMPRESSED(f->header);
+
+ f->seal = JOURNAL_HEADER_SEALED(f->header);
+
+ return 0;
+}
+
+static int journal_file_allocate(JournalFile *f, uint64_t offset, uint64_t size) {
+ uint64_t old_size, new_size;
+ int r;
+
+ assert(f);
+
+ /* We assume that this file is not sparse, and we know that
+ * for sure, since we always call posix_fallocate()
+ * ourselves */
+
+ old_size =
+ le64toh(f->header->header_size) +
+ le64toh(f->header->arena_size);
+
+ new_size = PAGE_ALIGN(offset + size);
+ if (new_size < le64toh(f->header->header_size))
+ new_size = le64toh(f->header->header_size);
+
+ if (new_size <= old_size)
+ return 0;
+
+ if (f->metrics.max_size > 0 &&
+ new_size > f->metrics.max_size)
+ return -E2BIG;
+
+ if (new_size > f->metrics.min_size &&
+ f->metrics.keep_free > 0) {
+ struct statvfs svfs;
+
+ if (fstatvfs(f->fd, &svfs) >= 0) {
+ uint64_t available;
+
+ available = svfs.f_bfree * svfs.f_bsize;
+
+ if (available >= f->metrics.keep_free)
+ available -= f->metrics.keep_free;
+ else
+ available = 0;
+
+ if (new_size - old_size > available)
+ return -E2BIG;
+ }
+ }
+
+ /* Note that the glibc fallocate() fallback is very
+ inefficient, hence we try to minimize the allocation area
+ as we can. */
+ r = posix_fallocate(f->fd, old_size, new_size - old_size);
+ if (r != 0)
+ return -r;
+
+ if (fstat(f->fd, &f->last_stat) < 0)
+ return -errno;
+
+ f->header->arena_size = htole64(new_size - le64toh(f->header->header_size));
+
+ return 0;
+}
+
+static int journal_file_move_to(JournalFile *f, int context, bool keep_always, uint64_t offset, uint64_t size, void **ret) {
+ assert(f);
+ assert(ret);
+
+ if (size <= 0)
+ return -EINVAL;
+
+ /* Avoid SIGBUS on invalid accesses */
+ if (offset + size > (uint64_t) f->last_stat.st_size) {
+ /* Hmm, out of range? Let's refresh the fstat() data
+ * first, before we trust that check. */
+
+ if (fstat(f->fd, &f->last_stat) < 0 ||
+ offset + size > (uint64_t) f->last_stat.st_size)
+ return -EADDRNOTAVAIL;
+ }
+
+ return mmap_cache_get(f->mmap, f->fd, f->prot, context, keep_always, offset, size, &f->last_stat, ret);
+}
+
+static uint64_t minimum_header_size(Object *o) {
+
+ static uint64_t table[] = {
+ [OBJECT_DATA] = sizeof(DataObject),
+ [OBJECT_FIELD] = sizeof(FieldObject),
+ [OBJECT_ENTRY] = sizeof(EntryObject),
+ [OBJECT_DATA_HASH_TABLE] = sizeof(HashTableObject),
+ [OBJECT_FIELD_HASH_TABLE] = sizeof(HashTableObject),
+ [OBJECT_ENTRY_ARRAY] = sizeof(EntryArrayObject),
+ [OBJECT_TAG] = sizeof(TagObject),
+ };
+
+ if (o->object.type >= ELEMENTSOF(table) || table[o->object.type] <= 0)
+ return sizeof(ObjectHeader);
+
+ return table[o->object.type];
+}
+
+int journal_file_move_to_object(JournalFile *f, int type, uint64_t offset, Object **ret) {
+ int r;
+ void *t;
+ Object *o;
+ uint64_t s;
+ unsigned context;
+
+ assert(f);
+ assert(ret);
+
+ /* Objects may only be located at multiple of 64 bit */
+ if (!VALID64(offset))
+ return -EFAULT;
+
+ /* One context for each type, plus one catch-all for the rest */
+ context = type > 0 && type < _OBJECT_TYPE_MAX ? type : 0;
+
+ r = journal_file_move_to(f, context, false, offset, sizeof(ObjectHeader), &t);
+ if (r < 0)
+ return r;
+
+ o = (Object*) t;
+ s = le64toh(o->object.size);
+
+ if (s < sizeof(ObjectHeader))
+ return -EBADMSG;
+
+ if (o->object.type <= OBJECT_UNUSED)
+ return -EBADMSG;
+
+ if (s < minimum_header_size(o))
+ return -EBADMSG;
+
+ if (type > 0 && o->object.type != type)
+ return -EBADMSG;
+
+ if (s > sizeof(ObjectHeader)) {
+ r = journal_file_move_to(f, o->object.type, false, offset, s, &t);
+ if (r < 0)
+ return r;
+
+ o = (Object*) t;
+ }
+
+ *ret = o;
+ return 0;
+}
+
+static uint64_t journal_file_entry_seqnum(JournalFile *f, uint64_t *seqnum) {
+ uint64_t r;
+
+ assert(f);
+
+ r = le64toh(f->header->tail_entry_seqnum) + 1;
+
+ if (seqnum) {
+ /* If an external seqnum counter was passed, we update
+ * both the local and the external one, and set it to
+ * the maximum of both */
+
+ if (*seqnum + 1 > r)
+ r = *seqnum + 1;
+
+ *seqnum = r;
+ }
+
+ f->header->tail_entry_seqnum = htole64(r);
+
+ if (f->header->head_entry_seqnum == 0)
+ f->header->head_entry_seqnum = htole64(r);
+
+ return r;
+}
+
+int journal_file_append_object(JournalFile *f, int type, uint64_t size, Object **ret, uint64_t *offset) {
+ int r;
+ uint64_t p;
+ Object *tail, *o;
+ void *t;
+
+ assert(f);
+ assert(type > 0 && type < _OBJECT_TYPE_MAX);
+ assert(size >= sizeof(ObjectHeader));
+ assert(offset);
+ assert(ret);
+
+ r = journal_file_set_online(f);
+ if (r < 0)
+ return r;
+
+ p = le64toh(f->header->tail_object_offset);
+ if (p == 0)
+ p = le64toh(f->header->header_size);
+ else {
+ r = journal_file_move_to_object(f, -1, p, &tail);
+ if (r < 0)
+ return r;
+
+ p += ALIGN64(le64toh(tail->object.size));
+ }
+
+ r = journal_file_allocate(f, p, size);
+ if (r < 0)
+ return r;
+
+ r = journal_file_move_to(f, type, false, p, size, &t);
+ if (r < 0)
+ return r;
+
+ o = (Object*) t;
+
+ zero(o->object);
+ o->object.type = type;
+ o->object.size = htole64(size);
+
+ f->header->tail_object_offset = htole64(p);
+ f->header->n_objects = htole64(le64toh(f->header->n_objects) + 1);
+
+ *ret = o;
+ *offset = p;
+
+ return 0;
+}
+
+static int journal_file_setup_data_hash_table(JournalFile *f) {
+ uint64_t s, p;
+ Object *o;
+ int r;
+
+ assert(f);
+
+ /* We estimate that we need 1 hash table entry per 768 of
+ journal file and we want to make sure we never get beyond
+ 75% fill level. Calculate the hash table size for the
+ maximum file size based on these metrics. */
+
+ s = (f->metrics.max_size * 4 / 768 / 3) * sizeof(HashItem);
+ if (s < DEFAULT_DATA_HASH_TABLE_SIZE)
+ s = DEFAULT_DATA_HASH_TABLE_SIZE;
+
+ log_debug("Reserving %llu entries in hash table.", (unsigned long long) (s / sizeof(HashItem)));
+
+ r = journal_file_append_object(f,
+ OBJECT_DATA_HASH_TABLE,
+ offsetof(Object, hash_table.items) + s,
+ &o, &p);
+ if (r < 0)
+ return r;
+
+ memset(o->hash_table.items, 0, s);
+
+ f->header->data_hash_table_offset = htole64(p + offsetof(Object, hash_table.items));
+ f->header->data_hash_table_size = htole64(s);
+
+ return 0;
+}
+
+static int journal_file_setup_field_hash_table(JournalFile *f) {
+ uint64_t s, p;
+ Object *o;
+ int r;
+
+ assert(f);
+
+ /* We use a fixed size hash table for the fields as this
+ * number should grow very slowly only */
+
+ s = DEFAULT_FIELD_HASH_TABLE_SIZE;
+ r = journal_file_append_object(f,
+ OBJECT_FIELD_HASH_TABLE,
+ offsetof(Object, hash_table.items) + s,
+ &o, &p);
+ if (r < 0)
+ return r;
+
+ memset(o->hash_table.items, 0, s);
+
+ f->header->field_hash_table_offset = htole64(p + offsetof(Object, hash_table.items));
+ f->header->field_hash_table_size = htole64(s);
+
+ return 0;
+}
+
+static int journal_file_map_data_hash_table(JournalFile *f) {
+ uint64_t s, p;
+ void *t;
+ int r;
+
+ assert(f);
+
+ p = le64toh(f->header->data_hash_table_offset);
+ s = le64toh(f->header->data_hash_table_size);
+
+ r = journal_file_move_to(f,
+ OBJECT_DATA_HASH_TABLE,
+ true,
+ p, s,
+ &t);
+ if (r < 0)
+ return r;
+
+ f->data_hash_table = t;
+ return 0;
+}
+
+static int journal_file_map_field_hash_table(JournalFile *f) {
+ uint64_t s, p;
+ void *t;
+ int r;
+
+ assert(f);
+
+ p = le64toh(f->header->field_hash_table_offset);
+ s = le64toh(f->header->field_hash_table_size);
+
+ r = journal_file_move_to(f,
+ OBJECT_FIELD_HASH_TABLE,
+ true,
+ p, s,
+ &t);
+ if (r < 0)
+ return r;
+
+ f->field_hash_table = t;
+ return 0;
+}
+
+static int journal_file_link_field(
+ JournalFile *f,
+ Object *o,
+ uint64_t offset,
+ uint64_t hash) {
+
+ uint64_t p, h;
+ int r;
+
+ assert(f);
+ assert(o);
+ assert(offset > 0);
+
+ if (o->object.type != OBJECT_FIELD)
+ return -EINVAL;
+
+ /* This might alter the window we are looking at */
+
+ o->field.next_hash_offset = o->field.head_data_offset = 0;
+
+ h = hash % (le64toh(f->header->field_hash_table_size) / sizeof(HashItem));
+ p = le64toh(f->field_hash_table[h].tail_hash_offset);
+ if (p == 0)
+ f->field_hash_table[h].head_hash_offset = htole64(offset);
+ else {
+ r = journal_file_move_to_object(f, OBJECT_FIELD, p, &o);
+ if (r < 0)
+ return r;
+
+ o->field.next_hash_offset = htole64(offset);
+ }
+
+ f->field_hash_table[h].tail_hash_offset = htole64(offset);
+
+ if (JOURNAL_HEADER_CONTAINS(f->header, n_fields))
+ f->header->n_fields = htole64(le64toh(f->header->n_fields) + 1);
+
+ return 0;
+}
+
+static int journal_file_link_data(
+ JournalFile *f,
+ Object *o,
+ uint64_t offset,
+ uint64_t hash) {
+
+ uint64_t p, h;
+ int r;
+
+ assert(f);
+ assert(o);
+ assert(offset > 0);
+
+ if (o->object.type != OBJECT_DATA)
+ return -EINVAL;
+
+ /* This might alter the window we are looking at */
+
+ o->data.next_hash_offset = o->data.next_field_offset = 0;
+ o->data.entry_offset = o->data.entry_array_offset = 0;
+ o->data.n_entries = 0;
+
+ h = hash % (le64toh(f->header->data_hash_table_size) / sizeof(HashItem));
+ p = le64toh(f->data_hash_table[h].tail_hash_offset);
+ if (p == 0)
+ /* Only entry in the hash table is easy */
+ f->data_hash_table[h].head_hash_offset = htole64(offset);
+ else {
+ /* Move back to the previous data object, to patch in
+ * pointer */
+
+ r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
+ if (r < 0)
+ return r;
+
+ o->data.next_hash_offset = htole64(offset);
+ }
+
+ f->data_hash_table[h].tail_hash_offset = htole64(offset);
+
+ if (JOURNAL_HEADER_CONTAINS(f->header, n_data))
+ f->header->n_data = htole64(le64toh(f->header->n_data) + 1);
+
+ return 0;
+}
+
+int journal_file_find_field_object_with_hash(
+ JournalFile *f,
+ const void *field, uint64_t size, uint64_t hash,
+ Object **ret, uint64_t *offset) {
+
+ uint64_t p, osize, h;
+ int r;
+
+ assert(f);
+ assert(field && size > 0);
+
+ osize = offsetof(Object, field.payload) + size;
+
+ if (f->header->field_hash_table_size == 0)
+ return -EBADMSG;
+
+ h = hash % (le64toh(f->header->field_hash_table_size) / sizeof(HashItem));
+ p = le64toh(f->field_hash_table[h].head_hash_offset);
+
+ while (p > 0) {
+ Object *o;
+
+ r = journal_file_move_to_object(f, OBJECT_FIELD, p, &o);
+ if (r < 0)
+ return r;
+
+ if (le64toh(o->field.hash) == hash &&
+ le64toh(o->object.size) == osize &&
+ memcmp(o->field.payload, field, size) == 0) {
+
+ if (ret)
+ *ret = o;
+ if (offset)
+ *offset = p;
+
+ return 1;
+ }
+
+ p = le64toh(o->field.next_hash_offset);
+ }
+
+ return 0;
+}
+
+int journal_file_find_field_object(
+ JournalFile *f,
+ const void *field, uint64_t size,
+ Object **ret, uint64_t *offset) {
+
+ uint64_t hash;
+
+ assert(f);
+ assert(field && size > 0);
+
+ hash = hash64(field, size);
+
+ return journal_file_find_field_object_with_hash(f,
+ field, size, hash,
+ ret, offset);
+}
+
+int journal_file_find_data_object_with_hash(
+ JournalFile *f,
+ const void *data, uint64_t size, uint64_t hash,
+ Object **ret, uint64_t *offset) {
+
+ uint64_t p, osize, h;
+ int r;
+
+ assert(f);
+ assert(data || size == 0);
+
+ osize = offsetof(Object, data.payload) + size;
+
+ if (f->header->data_hash_table_size == 0)
+ return -EBADMSG;
+
+ h = hash % (le64toh(f->header->data_hash_table_size) / sizeof(HashItem));
+ p = le64toh(f->data_hash_table[h].head_hash_offset);
+
+ while (p > 0) {
+ Object *o;
+
+ r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
+ if (r < 0)
+ return r;
+
+ if (le64toh(o->data.hash) != hash)
+ goto next;
+
+ if (o->object.flags & OBJECT_COMPRESSED) {
+#ifdef HAVE_XZ
+ uint64_t l, rsize;
+
+ l = le64toh(o->object.size);
+ if (l <= offsetof(Object, data.payload))
+ return -EBADMSG;
+
+ l -= offsetof(Object, data.payload);
+
+ if (!uncompress_blob(o->data.payload, l, &f->compress_buffer, &f->compress_buffer_size, &rsize, 0))
+ return -EBADMSG;
+
+ if (rsize == size &&
+ memcmp(f->compress_buffer, data, size) == 0) {
+
+ if (ret)
+ *ret = o;
+
+ if (offset)
+ *offset = p;
+
+ return 1;
+ }
+#else
+ return -EPROTONOSUPPORT;
+#endif
+
+ } else if (le64toh(o->object.size) == osize &&
+ memcmp(o->data.payload, data, size) == 0) {
+
+ if (ret)
+ *ret = o;
+
+ if (offset)
+ *offset = p;
+
+ return 1;
+ }
+
+ next:
+ p = le64toh(o->data.next_hash_offset);
+ }
+
+ return 0;
+}
+
+int journal_file_find_data_object(
+ JournalFile *f,
+ const void *data, uint64_t size,
+ Object **ret, uint64_t *offset) {
+
+ uint64_t hash;
+
+ assert(f);
+ assert(data || size == 0);
+
+ hash = hash64(data, size);
+
+ return journal_file_find_data_object_with_hash(f,
+ data, size, hash,
+ ret, offset);
+}
+
+static int journal_file_append_field(
+ JournalFile *f,
+ const void *field, uint64_t size,
+ Object **ret, uint64_t *offset) {
+
+ uint64_t hash, p;
+ uint64_t osize;
+ Object *o;
+ int r;
+
+ assert(f);
+ assert(field && size > 0);
+
+ hash = hash64(field, size);
+
+ r = journal_file_find_field_object_with_hash(f, field, size, hash, &o, &p);
+ if (r < 0)
+ return r;
+ else if (r > 0) {
+
+ if (ret)
+ *ret = o;
+
+ if (offset)
+ *offset = p;
+
+ return 0;
+ }
+
+ osize = offsetof(Object, field.payload) + size;
+ r = journal_file_append_object(f, OBJECT_FIELD, osize, &o, &p);
+
+ o->field.hash = htole64(hash);
+ memcpy(o->field.payload, field, size);
+
+ r = journal_file_link_field(f, o, p, hash);
+ if (r < 0)
+ return r;
+
+ /* The linking might have altered the window, so let's
+ * refresh our pointer */
+ r = journal_file_move_to_object(f, OBJECT_FIELD, p, &o);
+ if (r < 0)
+ return r;
+
+#ifdef HAVE_GCRYPT
+ r = journal_file_hmac_put_object(f, OBJECT_FIELD, o, p);
+ if (r < 0)
+ return r;
+#endif
+
+ if (ret)
+ *ret = o;
+
+ if (offset)
+ *offset = p;
+
+ return 0;
+}
+
+static int journal_file_append_data(
+ JournalFile *f,
+ const void *data, uint64_t size,
+ Object **ret, uint64_t *offset) {
+
+ uint64_t hash, p;
+ uint64_t osize;
+ Object *o;
+ int r;
+ bool compressed = false;
+ const void *eq;
+
+ assert(f);
+ assert(data || size == 0);
+
+ hash = hash64(data, size);
+
+ r = journal_file_find_data_object_with_hash(f, data, size, hash, &o, &p);
+ if (r < 0)
+ return r;
+ else if (r > 0) {
+
+ if (ret)
+ *ret = o;
+
+ if (offset)
+ *offset = p;
+
+ return 0;
+ }
+
+ osize = offsetof(Object, data.payload) + size;
+ r = journal_file_append_object(f, OBJECT_DATA, osize, &o, &p);
+ if (r < 0)
+ return r;
+
+ o->data.hash = htole64(hash);
+
+#ifdef HAVE_XZ
+ if (f->compress &&
+ size >= COMPRESSION_SIZE_THRESHOLD) {
+ uint64_t rsize;
+
+ compressed = compress_blob(data, size, o->data.payload, &rsize);
+
+ if (compressed) {
+ o->object.size = htole64(offsetof(Object, data.payload) + rsize);
+ o->object.flags |= OBJECT_COMPRESSED;
+
+ log_debug("Compressed data object %lu -> %lu", (unsigned long) size, (unsigned long) rsize);
+ }
+ }
+#endif
+
+ if (!compressed && size > 0)
+ memcpy(o->data.payload, data, size);
+
+ r = journal_file_link_data(f, o, p, hash);
+ if (r < 0)
+ return r;
+
+ /* The linking might have altered the window, so let's
+ * refresh our pointer */
+ r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
+ if (r < 0)
+ return r;
+
+ eq = memchr(data, '=', size);
+ if (eq && eq > data) {
+ uint64_t fp;
+ Object *fo;
+
+ /* Create field object ... */
+ r = journal_file_append_field(f, data, (uint8_t*) eq - (uint8_t*) data, &fo, &fp);
+ if (r < 0)
+ return r;
+
+ /* ... and link it in. */
+ o->data.next_field_offset = fo->field.head_data_offset;
+ fo->field.head_data_offset = le64toh(p);
+ }
+
+#ifdef HAVE_GCRYPT
+ r = journal_file_hmac_put_object(f, OBJECT_DATA, o, p);
+ if (r < 0)
+ return r;
+#endif
+
+ if (ret)
+ *ret = o;
+
+ if (offset)
+ *offset = p;
+
+ return 0;
+}
+
+uint64_t journal_file_entry_n_items(Object *o) {
+ assert(o);
+
+ if (o->object.type != OBJECT_ENTRY)
+ return 0;
+
+ return (le64toh(o->object.size) - offsetof(Object, entry.items)) / sizeof(EntryItem);
+}
+
+uint64_t journal_file_entry_array_n_items(Object *o) {
+ assert(o);
+
+ if (o->object.type != OBJECT_ENTRY_ARRAY)
+ return 0;
+
+ return (le64toh(o->object.size) - offsetof(Object, entry_array.items)) / sizeof(uint64_t);
+}
+
+uint64_t journal_file_hash_table_n_items(Object *o) {
+ assert(o);
+
+ if (o->object.type != OBJECT_DATA_HASH_TABLE &&
+ o->object.type != OBJECT_FIELD_HASH_TABLE)
+ return 0;
+
+ return (le64toh(o->object.size) - offsetof(Object, hash_table.items)) / sizeof(HashItem);
+}
+
+static int link_entry_into_array(JournalFile *f,
+ le64_t *first,
+ le64_t *idx,
+ uint64_t p) {
+ int r;
+ uint64_t n = 0, ap = 0, q, i, a, hidx;
+ Object *o;
+
+ assert(f);
+ assert(first);
+ assert(idx);
+ assert(p > 0);
+
+ a = le64toh(*first);
+ i = hidx = le64toh(*idx);
+ while (a > 0) {
+
+ r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o);
+ if (r < 0)
+ return r;
+
+ n = journal_file_entry_array_n_items(o);
+ if (i < n) {
+ o->entry_array.items[i] = htole64(p);
+ *idx = htole64(hidx + 1);
+ return 0;
+ }
+
+ i -= n;
+ ap = a;
+ a = le64toh(o->entry_array.next_entry_array_offset);
+ }
+
+ if (hidx > n)
+ n = (hidx+1) * 2;
+ else
+ n = n * 2;
+
+ if (n < 4)
+ n = 4;
+
+ r = journal_file_append_object(f, OBJECT_ENTRY_ARRAY,
+ offsetof(Object, entry_array.items) + n * sizeof(uint64_t),
+ &o, &q);
+ if (r < 0)
+ return r;
+
+#ifdef HAVE_GCRYPT
+ r = journal_file_hmac_put_object(f, OBJECT_ENTRY_ARRAY, o, q);
+ if (r < 0)
+ return r;
+#endif
+
+ o->entry_array.items[i] = htole64(p);
+
+ if (ap == 0)
+ *first = htole64(q);
+ else {
+ r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, ap, &o);
+ if (r < 0)
+ return r;
+
+ o->entry_array.next_entry_array_offset = htole64(q);
+ }
+
+ if (JOURNAL_HEADER_CONTAINS(f->header, n_entry_arrays))
+ f->header->n_entry_arrays = htole64(le64toh(f->header->n_entry_arrays) + 1);
+
+ *idx = htole64(hidx + 1);
+
+ return 0;
+}
+
+static int link_entry_into_array_plus_one(JournalFile *f,
+ le64_t *extra,
+ le64_t *first,
+ le64_t *idx,
+ uint64_t p) {
+
+ int r;
+
+ assert(f);
+ assert(extra);
+ assert(first);
+ assert(idx);
+ assert(p > 0);
+
+ if (*idx == 0)
+ *extra = htole64(p);
+ else {
+ le64_t i;
+
+ i = htole64(le64toh(*idx) - 1);
+ r = link_entry_into_array(f, first, &i, p);
+ if (r < 0)
+ return r;
+ }
+
+ *idx = htole64(le64toh(*idx) + 1);
+ return 0;
+}
+
+static int journal_file_link_entry_item(JournalFile *f, Object *o, uint64_t offset, uint64_t i) {
+ uint64_t p;
+ int r;
+ assert(f);
+ assert(o);
+ assert(offset > 0);
+
+ p = le64toh(o->entry.items[i].object_offset);
+ if (p == 0)
+ return -EINVAL;
+
+ r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
+ if (r < 0)
+ return r;
+
+ return link_entry_into_array_plus_one(f,
+ &o->data.entry_offset,
+ &o->data.entry_array_offset,
+ &o->data.n_entries,
+ offset);
+}
+
+static int journal_file_link_entry(JournalFile *f, Object *o, uint64_t offset) {
+ uint64_t n, i;
+ int r;
+
+ assert(f);
+ assert(o);
+ assert(offset > 0);
+
+ if (o->object.type != OBJECT_ENTRY)
+ return -EINVAL;
+
+ __sync_synchronize();
+
+ /* Link up the entry itself */
+ r = link_entry_into_array(f,
+ &f->header->entry_array_offset,
+ &f->header->n_entries,
+ offset);
+ if (r < 0)
+ return r;
+
+ /* log_debug("=> %s seqnr=%lu n_entries=%lu", f->path, (unsigned long) o->entry.seqnum, (unsigned long) f->header->n_entries); */
+
+ if (f->header->head_entry_realtime == 0)
+ f->header->head_entry_realtime = o->entry.realtime;
+
+ f->header->tail_entry_realtime = o->entry.realtime;
+ f->header->tail_entry_monotonic = o->entry.monotonic;
+
+ f->tail_entry_monotonic_valid = true;
+
+ /* Link up the items */
+ n = journal_file_entry_n_items(o);
+ for (i = 0; i < n; i++) {
+ r = journal_file_link_entry_item(f, o, offset, i);
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static int journal_file_append_entry_internal(
+ JournalFile *f,
+ const dual_timestamp *ts,
+ uint64_t xor_hash,
+ const EntryItem items[], unsigned n_items,
+ uint64_t *seqnum,
+ Object **ret, uint64_t *offset) {
+ uint64_t np;
+ uint64_t osize;
+ Object *o;
+ int r;
+
+ assert(f);
+ assert(items || n_items == 0);
+ assert(ts);
+
+ osize = offsetof(Object, entry.items) + (n_items * sizeof(EntryItem));
+
+ r = journal_file_append_object(f, OBJECT_ENTRY, osize, &o, &np);
+ if (r < 0)
+ return r;
+
+ o->entry.seqnum = htole64(journal_file_entry_seqnum(f, seqnum));
+ memcpy(o->entry.items, items, n_items * sizeof(EntryItem));
+ o->entry.realtime = htole64(ts->realtime);
+ o->entry.monotonic = htole64(ts->monotonic);
+ o->entry.xor_hash = htole64(xor_hash);
+ o->entry.boot_id = f->header->boot_id;
+
+#ifdef HAVE_GCRYPT
+ r = journal_file_hmac_put_object(f, OBJECT_ENTRY, o, np);
+ if (r < 0)
+ return r;
+#endif
+
+ r = journal_file_link_entry(f, o, np);
+ if (r < 0)
+ return r;
+
+ if (ret)
+ *ret = o;
+
+ if (offset)
+ *offset = np;
+
+ return 0;
+}
+
+void journal_file_post_change(JournalFile *f) {
+ assert(f);
+
+ /* inotify() does not receive IN_MODIFY events from file
+ * accesses done via mmap(). After each access we hence
+ * trigger IN_MODIFY by truncating the journal file to its
+ * current size which triggers IN_MODIFY. */
+
+ __sync_synchronize();
+
+ if (ftruncate(f->fd, f->last_stat.st_size) < 0)
+ log_error("Failed to truncate file to its own size: %m");
+}
+
+static int entry_item_cmp(const void *_a, const void *_b) {
+ const EntryItem *a = _a, *b = _b;
+
+ if (le64toh(a->object_offset) < le64toh(b->object_offset))
+ return -1;
+ if (le64toh(a->object_offset) > le64toh(b->object_offset))
+ return 1;
+ return 0;
+}
+
+int journal_file_append_entry(JournalFile *f, const dual_timestamp *ts, const struct iovec iovec[], unsigned n_iovec, uint64_t *seqnum, Object **ret, uint64_t *offset) {
+ unsigned i;
+ EntryItem *items;
+ int r;
+ uint64_t xor_hash = 0;
+ struct dual_timestamp _ts;
+
+ assert(f);
+ assert(iovec || n_iovec == 0);
+
+ if (!ts) {
+ dual_timestamp_get(&_ts);
+ ts = &_ts;
+ }
+
+ if (f->tail_entry_monotonic_valid &&
+ ts->monotonic < le64toh(f->header->tail_entry_monotonic))
+ return -EINVAL;
+
+#ifdef HAVE_GCRYPT
+ r = journal_file_maybe_append_tag(f, ts->realtime);
+ if (r < 0)
+ return r;
+#endif
+
+ /* alloca() can't take 0, hence let's allocate at least one */
+ items = alloca(sizeof(EntryItem) * MAX(1u, n_iovec));
+
+ for (i = 0; i < n_iovec; i++) {
+ uint64_t p;
+ Object *o;
+
+ r = journal_file_append_data(f, iovec[i].iov_base, iovec[i].iov_len, &o, &p);
+ if (r < 0)
+ return r;
+
+ xor_hash ^= le64toh(o->data.hash);
+ items[i].object_offset = htole64(p);
+ items[i].hash = o->data.hash;
+ }
+
+ /* Order by the position on disk, in order to improve seek
+ * times for rotating media. */
+ qsort(items, n_iovec, sizeof(EntryItem), entry_item_cmp);
+
+ r = journal_file_append_entry_internal(f, ts, xor_hash, items, n_iovec, seqnum, ret, offset);
+
+ journal_file_post_change(f);
+
+ return r;
+}
+
+typedef struct ChainCacheItem {
+ uint64_t first; /* the array at the begin of the chain */
+ uint64_t array; /* the cached array */
+ uint64_t begin; /* the first item in the cached array */
+ uint64_t total; /* the total number of items in all arrays before this one in the chain */
+} ChainCacheItem;
+
+static void chain_cache_put(
+ Hashmap *h,
+ ChainCacheItem *ci,
+ uint64_t first,
+ uint64_t array,
+ uint64_t begin,
+ uint64_t total) {
+
+ if (!ci) {
+ /* If the chain item to cache for this chain is the
+ * first one it's not worth caching anything */
+ if (array == first)
+ return;
+
+ if (hashmap_size(h) >= CHAIN_CACHE_MAX)
+ ci = hashmap_steal_first(h);
+ else {
+ ci = new(ChainCacheItem, 1);
+ if (!ci)
+ return;
+ }
+
+ ci->first = first;
+
+ if (hashmap_put(h, &ci->first, ci) < 0) {
+ free(ci);
+ return;
+ }
+ } else
+ assert(ci->first == first);
+
+ ci->array = array;
+ ci->begin = begin;
+ ci->total = total;
+}
+
+static int generic_array_get(JournalFile *f,
+ uint64_t first,
+ uint64_t i,
+ Object **ret, uint64_t *offset) {
+
+ Object *o;
+ uint64_t p = 0, a, t = 0;
+ int r;
+ ChainCacheItem *ci;
+
+ assert(f);
+
+ a = first;
+
+ /* Try the chain cache first */
+ ci = hashmap_get(f->chain_cache, &first);
+ if (ci && i > ci->total) {
+ a = ci->array;
+ i -= ci->total;
+ t = ci->total;
+ }
+
+ while (a > 0) {
+ uint64_t k;
+
+ r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o);
+ if (r < 0)
+ return r;
+
+ k = journal_file_entry_array_n_items(o);
+ if (i < k) {
+ p = le64toh(o->entry_array.items[i]);
+ goto found;
+ }
+
+ i -= k;
+ t += k;
+ a = le64toh(o->entry_array.next_entry_array_offset);
+ }
+
+ return 0;
+
+found:
+ /* Let's cache this item for the next invocation */
+ chain_cache_put(f->chain_cache, ci, first, a, o->entry_array.items[0], t);
+
+ r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
+ if (r < 0)
+ return r;
+
+ if (ret)
+ *ret = o;
+
+ if (offset)
+ *offset = p;
+
+ return 1;
+}
+
+static int generic_array_get_plus_one(JournalFile *f,
+ uint64_t extra,
+ uint64_t first,
+ uint64_t i,
+ Object **ret, uint64_t *offset) {
+
+ Object *o;
+
+ assert(f);
+
+ if (i == 0) {
+ int r;
+
+ r = journal_file_move_to_object(f, OBJECT_ENTRY, extra, &o);
+ if (r < 0)
+ return r;
+
+ if (ret)
+ *ret = o;
+
+ if (offset)
+ *offset = extra;
+
+ return 1;
+ }
+
+ return generic_array_get(f, first, i-1, ret, offset);
+}
+
+enum {
+ TEST_FOUND,
+ TEST_LEFT,
+ TEST_RIGHT
+};
+
+static int generic_array_bisect(JournalFile *f,
+ uint64_t first,
+ uint64_t n,
+ uint64_t needle,
+ int (*test_object)(JournalFile *f, uint64_t p, uint64_t needle),
+ direction_t direction,
+ Object **ret,
+ uint64_t *offset,
+ uint64_t *idx) {
+
+ uint64_t a, p, t = 0, i = 0, last_p = 0;
+ bool subtract_one = false;
+ Object *o, *array = NULL;
+ int r;
+ ChainCacheItem *ci;
+
+ assert(f);
+ assert(test_object);
+
+ /* Start with the first array in the chain */
+ a = first;
+
+ ci = hashmap_get(f->chain_cache, &first);
+ if (ci && n > ci->total) {
+ /* Ah, we have iterated this bisection array chain
+ * previously! Let's see if we can skip ahead in the
+ * chain, as far as the last time. But we can't jump
+ * backwards in the chain, so let's check that
+ * first. */
+
+ r = test_object(f, ci->begin, needle);
+ if (r < 0)
+ return r;
+
+ if (r == TEST_LEFT) {
+ /* OK, what we are looking for is right of th
+ * begin of this EntryArray, so let's jump
+ * straight to previously cached array in the
+ * chain */
+
+ a = ci->array;
+ n -= ci->total;
+ t = ci->total;
+ }
+ }
+
+ while (a > 0) {
+ uint64_t left, right, k, lp;
+
+ r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &array);
+ if (r < 0)
+ return r;
+
+ k = journal_file_entry_array_n_items(array);
+ right = MIN(k, n);
+ if (right <= 0)
+ return 0;
+
+ i = right - 1;
+ lp = p = le64toh(array->entry_array.items[i]);
+ if (p <= 0)
+ return -EBADMSG;
+
+ r = test_object(f, p, needle);
+ if (r < 0)
+ return r;
+
+ if (r == TEST_FOUND)
+ r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
+
+ if (r == TEST_RIGHT) {
+ left = 0;
+ right -= 1;
+ for (;;) {
+ if (left == right) {
+ if (direction == DIRECTION_UP)
+ subtract_one = true;
+
+ i = left;
+ goto found;
+ }
+
+ assert(left < right);
+
+ i = (left + right) / 2;
+ p = le64toh(array->entry_array.items[i]);
+ if (p <= 0)
+ return -EBADMSG;
+
+ r = test_object(f, p, needle);
+ if (r < 0)
+ return r;
+
+ if (r == TEST_FOUND)
+ r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
+
+ if (r == TEST_RIGHT)
+ right = i;
+ else
+ left = i + 1;
+ }
+ }
+
+ if (k > n) {
+ if (direction == DIRECTION_UP) {
+ i = n;
+ subtract_one = true;
+ goto found;
+ }
+
+ return 0;
+ }
+
+ last_p = lp;
+
+ n -= k;
+ t += k;
+ a = le64toh(array->entry_array.next_entry_array_offset);
+ }
+
+ return 0;
+
+found:
+ if (subtract_one && t == 0 && i == 0)
+ return 0;
+
+ /* Let's cache this item for the next invocation */
+ chain_cache_put(f->chain_cache, ci, first, a, array->entry_array.items[0], t);
+
+ if (subtract_one && i == 0)
+ p = last_p;
+ else if (subtract_one)
+ p = le64toh(array->entry_array.items[i-1]);
+ else
+ p = le64toh(array->entry_array.items[i]);
+
+ r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
+ if (r < 0)
+ return r;
+
+ if (ret)
+ *ret = o;
+
+ if (offset)
+ *offset = p;
+
+ if (idx)
+ *idx = t + i + (subtract_one ? -1 : 0);
+
+ return 1;
+}
+
+static int generic_array_bisect_plus_one(JournalFile *f,
+ uint64_t extra,
+ uint64_t first,
+ uint64_t n,
+ uint64_t needle,
+ int (*test_object)(JournalFile *f, uint64_t p, uint64_t needle),
+ direction_t direction,
+ Object **ret,
+ uint64_t *offset,
+ uint64_t *idx) {
+
+ int r;
+ bool step_back = false;
+ Object *o;
+
+ assert(f);
+ assert(test_object);
+
+ if (n <= 0)
+ return 0;
+
+ /* This bisects the array in object 'first', but first checks
+ * an extra */
+ r = test_object(f, extra, needle);
+ if (r < 0)
+ return r;
+
+ if (r == TEST_FOUND)
+ r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
+
+ /* if we are looking with DIRECTION_UP then we need to first
+ see if in the actual array there is a matching entry, and
+ return the last one of that. But if there isn't any we need
+ to return this one. Hence remember this, and return it
+ below. */
+ if (r == TEST_LEFT)
+ step_back = direction == DIRECTION_UP;
+
+ if (r == TEST_RIGHT) {
+ if (direction == DIRECTION_DOWN)
+ goto found;
+ else
+ return 0;
+ }
+
+ r = generic_array_bisect(f, first, n-1, needle, test_object, direction, ret, offset, idx);
+
+ if (r == 0 && step_back)
+ goto found;
+
+ if (r > 0 && idx)
+ (*idx) ++;
+
+ return r;
+
+found:
+ r = journal_file_move_to_object(f, OBJECT_ENTRY, extra, &o);
+ if (r < 0)
+ return r;
+
+ if (ret)
+ *ret = o;
+
+ if (offset)
+ *offset = extra;
+
+ if (idx)
+ *idx = 0;
+
+ return 1;
+}
+
+_pure_ static int test_object_offset(JournalFile *f, uint64_t p, uint64_t needle) {
+ assert(f);
+ assert(p > 0);
+
+ if (p == needle)
+ return TEST_FOUND;
+ else if (p < needle)
+ return TEST_LEFT;
+ else
+ return TEST_RIGHT;
+}
+
+int journal_file_move_to_entry_by_offset(
+ JournalFile *f,
+ uint64_t p,
+ direction_t direction,
+ Object **ret,
+ uint64_t *offset) {
+
+ return generic_array_bisect(f,
+ le64toh(f->header->entry_array_offset),
+ le64toh(f->header->n_entries),
+ p,
+ test_object_offset,
+ direction,
+ ret, offset, NULL);
+}
+
+
+static int test_object_seqnum(JournalFile *f, uint64_t p, uint64_t needle) {
+ Object *o;
+ int r;
+
+ assert(f);
+ assert(p > 0);
+
+ r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
+ if (r < 0)
+ return r;
+
+ if (le64toh(o->entry.seqnum) == needle)
+ return TEST_FOUND;
+ else if (le64toh(o->entry.seqnum) < needle)
+ return TEST_LEFT;
+ else
+ return TEST_RIGHT;
+}
+
+int journal_file_move_to_entry_by_seqnum(
+ JournalFile *f,
+ uint64_t seqnum,
+ direction_t direction,
+ Object **ret,
+ uint64_t *offset) {
+
+ return generic_array_bisect(f,
+ le64toh(f->header->entry_array_offset),
+ le64toh(f->header->n_entries),
+ seqnum,
+ test_object_seqnum,
+ direction,
+ ret, offset, NULL);
+}
+
+static int test_object_realtime(JournalFile *f, uint64_t p, uint64_t needle) {
+ Object *o;
+ int r;
+
+ assert(f);
+ assert(p > 0);
+
+ r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
+ if (r < 0)
+ return r;
+
+ if (le64toh(o->entry.realtime) == needle)
+ return TEST_FOUND;
+ else if (le64toh(o->entry.realtime) < needle)
+ return TEST_LEFT;
+ else
+ return TEST_RIGHT;
+}
+
+int journal_file_move_to_entry_by_realtime(
+ JournalFile *f,
+ uint64_t realtime,
+ direction_t direction,
+ Object **ret,
+ uint64_t *offset) {
+
+ return generic_array_bisect(f,
+ le64toh(f->header->entry_array_offset),
+ le64toh(f->header->n_entries),
+ realtime,
+ test_object_realtime,
+ direction,
+ ret, offset, NULL);
+}
+
+static int test_object_monotonic(JournalFile *f, uint64_t p, uint64_t needle) {
+ Object *o;
+ int r;
+
+ assert(f);
+ assert(p > 0);
+
+ r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
+ if (r < 0)
+ return r;
+
+ if (le64toh(o->entry.monotonic) == needle)
+ return TEST_FOUND;
+ else if (le64toh(o->entry.monotonic) < needle)
+ return TEST_LEFT;
+ else
+ return TEST_RIGHT;
+}
+
+static inline int find_data_object_by_boot_id(
+ JournalFile *f,
+ sd_id128_t boot_id,
+ Object **o,
+ uint64_t *b) {
+ char t[sizeof("_BOOT_ID=")-1 + 32 + 1] = "_BOOT_ID=";
+
+ sd_id128_to_string(boot_id, t + 9);
+ return journal_file_find_data_object(f, t, sizeof(t) - 1, o, b);
+}
+
+int journal_file_move_to_entry_by_monotonic(
+ JournalFile *f,
+ sd_id128_t boot_id,
+ uint64_t monotonic,
+ direction_t direction,
+ Object **ret,
+ uint64_t *offset) {
+
+ Object *o;
+ int r;
+
+ assert(f);
+
+ r = find_data_object_by_boot_id(f, boot_id, &o, NULL);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return -ENOENT;
+
+ return generic_array_bisect_plus_one(f,
+ le64toh(o->data.entry_offset),
+ le64toh(o->data.entry_array_offset),
+ le64toh(o->data.n_entries),
+ monotonic,
+ test_object_monotonic,
+ direction,
+ ret, offset, NULL);
+}
+
+int journal_file_next_entry(
+ JournalFile *f,
+ Object *o, uint64_t p,
+ direction_t direction,
+ Object **ret, uint64_t *offset) {
+
+ uint64_t i, n;
+ int r;
+
+ assert(f);
+ assert(p > 0 || !o);
+
+ n = le64toh(f->header->n_entries);
+ if (n <= 0)
+ return 0;
+
+ if (!o)
+ i = direction == DIRECTION_DOWN ? 0 : n - 1;
+ else {
+ if (o->object.type != OBJECT_ENTRY)
+ return -EINVAL;
+
+ r = generic_array_bisect(f,
+ le64toh(f->header->entry_array_offset),
+ le64toh(f->header->n_entries),
+ p,
+ test_object_offset,
+ DIRECTION_DOWN,
+ NULL, NULL,
+ &i);
+ if (r <= 0)
+ return r;
+
+ if (direction == DIRECTION_DOWN) {
+ if (i >= n - 1)
+ return 0;
+
+ i++;
+ } else {
+ if (i <= 0)
+ return 0;
+
+ i--;
+ }
+ }
+
+ /* And jump to it */
+ return generic_array_get(f,
+ le64toh(f->header->entry_array_offset),
+ i,
+ ret, offset);
+}
+
+int journal_file_skip_entry(
+ JournalFile *f,
+ Object *o, uint64_t p,
+ int64_t skip,
+ Object **ret, uint64_t *offset) {
+
+ uint64_t i, n;
+ int r;
+
+ assert(f);
+ assert(o);
+ assert(p > 0);
+
+ if (o->object.type != OBJECT_ENTRY)
+ return -EINVAL;
+
+ r = generic_array_bisect(f,
+ le64toh(f->header->entry_array_offset),
+ le64toh(f->header->n_entries),
+ p,
+ test_object_offset,
+ DIRECTION_DOWN,
+ NULL, NULL,
+ &i);
+ if (r <= 0)
+ return r;
+
+ /* Calculate new index */
+ if (skip < 0) {
+ if ((uint64_t) -skip >= i)
+ i = 0;
+ else
+ i = i - (uint64_t) -skip;
+ } else
+ i += (uint64_t) skip;
+
+ n = le64toh(f->header->n_entries);
+ if (n <= 0)
+ return -EBADMSG;
+
+ if (i >= n)
+ i = n-1;
+
+ return generic_array_get(f,
+ le64toh(f->header->entry_array_offset),
+ i,
+ ret, offset);
+}
+
+int journal_file_next_entry_for_data(
+ JournalFile *f,
+ Object *o, uint64_t p,
+ uint64_t data_offset,
+ direction_t direction,
+ Object **ret, uint64_t *offset) {
+
+ uint64_t n, i;
+ int r;
+ Object *d;
+
+ assert(f);
+ assert(p > 0 || !o);
+
+ r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
+ if (r < 0)
+ return r;
+
+ n = le64toh(d->data.n_entries);
+ if (n <= 0)
+ return n;
+
+ if (!o)
+ i = direction == DIRECTION_DOWN ? 0 : n - 1;
+ else {
+ if (o->object.type != OBJECT_ENTRY)
+ return -EINVAL;
+
+ r = generic_array_bisect_plus_one(f,
+ le64toh(d->data.entry_offset),
+ le64toh(d->data.entry_array_offset),
+ le64toh(d->data.n_entries),
+ p,
+ test_object_offset,
+ DIRECTION_DOWN,
+ NULL, NULL,
+ &i);
+
+ if (r <= 0)
+ return r;
+
+ if (direction == DIRECTION_DOWN) {
+ if (i >= n - 1)
+ return 0;
+
+ i++;
+ } else {
+ if (i <= 0)
+ return 0;
+
+ i--;
+ }
+
+ }
+
+ return generic_array_get_plus_one(f,
+ le64toh(d->data.entry_offset),
+ le64toh(d->data.entry_array_offset),
+ i,
+ ret, offset);
+}
+
+int journal_file_move_to_entry_by_offset_for_data(
+ JournalFile *f,
+ uint64_t data_offset,
+ uint64_t p,
+ direction_t direction,
+ Object **ret, uint64_t *offset) {
+
+ int r;
+ Object *d;
+
+ assert(f);
+
+ r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
+ if (r < 0)
+ return r;
+
+ return generic_array_bisect_plus_one(f,
+ le64toh(d->data.entry_offset),
+ le64toh(d->data.entry_array_offset),
+ le64toh(d->data.n_entries),
+ p,
+ test_object_offset,
+ direction,
+ ret, offset, NULL);
+}
+
+int journal_file_move_to_entry_by_monotonic_for_data(
+ JournalFile *f,
+ uint64_t data_offset,
+ sd_id128_t boot_id,
+ uint64_t monotonic,
+ direction_t direction,
+ Object **ret, uint64_t *offset) {
+
+ Object *o, *d;
+ int r;
+ uint64_t b, z;
+
+ assert(f);
+
+ /* First, seek by time */
+ r = find_data_object_by_boot_id(f, boot_id, &o, &b);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return -ENOENT;
+
+ r = generic_array_bisect_plus_one(f,
+ le64toh(o->data.entry_offset),
+ le64toh(o->data.entry_array_offset),
+ le64toh(o->data.n_entries),
+ monotonic,
+ test_object_monotonic,
+ direction,
+ NULL, &z, NULL);
+ if (r <= 0)
+ return r;
+
+ /* And now, continue seeking until we find an entry that
+ * exists in both bisection arrays */
+
+ for (;;) {
+ Object *qo;
+ uint64_t p, q;
+
+ r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
+ if (r < 0)
+ return r;
+
+ r = generic_array_bisect_plus_one(f,
+ le64toh(d->data.entry_offset),
+ le64toh(d->data.entry_array_offset),
+ le64toh(d->data.n_entries),
+ z,
+ test_object_offset,
+ direction,
+ NULL, &p, NULL);
+ if (r <= 0)
+ return r;
+
+ r = journal_file_move_to_object(f, OBJECT_DATA, b, &o);
+ if (r < 0)
+ return r;
+
+ r = generic_array_bisect_plus_one(f,
+ le64toh(o->data.entry_offset),
+ le64toh(o->data.entry_array_offset),
+ le64toh(o->data.n_entries),
+ p,
+ test_object_offset,
+ direction,
+ &qo, &q, NULL);
+
+ if (r <= 0)
+ return r;
+
+ if (p == q) {
+ if (ret)
+ *ret = qo;
+ if (offset)
+ *offset = q;
+
+ return 1;
+ }
+
+ z = q;
+ }
+
+ return 0;
+}
+
+int journal_file_move_to_entry_by_seqnum_for_data(
+ JournalFile *f,
+ uint64_t data_offset,
+ uint64_t seqnum,
+ direction_t direction,
+ Object **ret, uint64_t *offset) {
+
+ Object *d;
+ int r;
+
+ assert(f);
+
+ r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
+ if (r < 0)
+ return r;
+
+ return generic_array_bisect_plus_one(f,
+ le64toh(d->data.entry_offset),
+ le64toh(d->data.entry_array_offset),
+ le64toh(d->data.n_entries),
+ seqnum,
+ test_object_seqnum,
+ direction,
+ ret, offset, NULL);
+}
+
+int journal_file_move_to_entry_by_realtime_for_data(
+ JournalFile *f,
+ uint64_t data_offset,
+ uint64_t realtime,
+ direction_t direction,
+ Object **ret, uint64_t *offset) {
+
+ Object *d;
+ int r;
+
+ assert(f);
+
+ r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
+ if (r < 0)
+ return r;
+
+ return generic_array_bisect_plus_one(f,
+ le64toh(d->data.entry_offset),
+ le64toh(d->data.entry_array_offset),
+ le64toh(d->data.n_entries),
+ realtime,
+ test_object_realtime,
+ direction,
+ ret, offset, NULL);
+}
+
+void journal_file_dump(JournalFile *f) {
+ Object *o;
+ int r;
+ uint64_t p;
+
+ assert(f);
+
+ journal_file_print_header(f);
+
+ p = le64toh(f->header->header_size);
+ while (p != 0) {
+ r = journal_file_move_to_object(f, -1, p, &o);
+ if (r < 0)
+ goto fail;
+
+ switch (o->object.type) {
+
+ case OBJECT_UNUSED:
+ printf("Type: OBJECT_UNUSED\n");
+ break;
+
+ case OBJECT_DATA:
+ printf("Type: OBJECT_DATA\n");
+ break;
+
+ case OBJECT_FIELD:
+ printf("Type: OBJECT_FIELD\n");
+ break;
+
+ case OBJECT_ENTRY:
+ printf("Type: OBJECT_ENTRY seqnum=%llu monotonic=%llu realtime=%llu\n",
+ (unsigned long long) le64toh(o->entry.seqnum),
+ (unsigned long long) le64toh(o->entry.monotonic),
+ (unsigned long long) le64toh(o->entry.realtime));
+ break;
+
+ case OBJECT_FIELD_HASH_TABLE:
+ printf("Type: OBJECT_FIELD_HASH_TABLE\n");
+ break;
+
+ case OBJECT_DATA_HASH_TABLE:
+ printf("Type: OBJECT_DATA_HASH_TABLE\n");
+ break;
+
+ case OBJECT_ENTRY_ARRAY:
+ printf("Type: OBJECT_ENTRY_ARRAY\n");
+ break;
+
+ case OBJECT_TAG:
+ printf("Type: OBJECT_TAG seqnum=%llu epoch=%llu\n",
+ (unsigned long long) le64toh(o->tag.seqnum),
+ (unsigned long long) le64toh(o->tag.epoch));
+ break;
+
+ default:
+ printf("Type: unknown (%u)\n", o->object.type);
+ break;
+ }
+
+ if (o->object.flags & OBJECT_COMPRESSED)
+ printf("Flags: COMPRESSED\n");
+
+ if (p == le64toh(f->header->tail_object_offset))
+ p = 0;
+ else
+ p = p + ALIGN64(le64toh(o->object.size));
+ }
+
+ return;
+fail:
+ log_error("File corrupt");
+}
+
+void journal_file_print_header(JournalFile *f) {
+ char a[33], b[33], c[33];
+ char x[FORMAT_TIMESTAMP_MAX], y[FORMAT_TIMESTAMP_MAX];
+ struct stat st;
+ char bytes[FORMAT_BYTES_MAX];
+
+ assert(f);
+
+ printf("File Path: %s\n"
+ "File ID: %s\n"
+ "Machine ID: %s\n"
+ "Boot ID: %s\n"
+ "Sequential Number ID: %s\n"
+ "State: %s\n"
+ "Compatible Flags:%s%s\n"
+ "Incompatible Flags:%s%s\n"
+ "Header size: %llu\n"
+ "Arena size: %llu\n"
+ "Data Hash Table Size: %llu\n"
+ "Field Hash Table Size: %llu\n"
+ "Rotate Suggested: %s\n"
+ "Head Sequential Number: %llu\n"
+ "Tail Sequential Number: %llu\n"
+ "Head Realtime Timestamp: %s\n"
+ "Tail Realtime Timestamp: %s\n"
+ "Objects: %llu\n"
+ "Entry Objects: %llu\n",
+ f->path,
+ sd_id128_to_string(f->header->file_id, a),
+ sd_id128_to_string(f->header->machine_id, b),
+ sd_id128_to_string(f->header->boot_id, c),
+ sd_id128_to_string(f->header->seqnum_id, c),
+ f->header->state == STATE_OFFLINE ? "OFFLINE" :
+ f->header->state == STATE_ONLINE ? "ONLINE" :
+ f->header->state == STATE_ARCHIVED ? "ARCHIVED" : "UNKNOWN",
+ JOURNAL_HEADER_SEALED(f->header) ? " SEALED" : "",
+ (le32toh(f->header->compatible_flags) & ~HEADER_COMPATIBLE_SEALED) ? " ???" : "",
+ JOURNAL_HEADER_COMPRESSED(f->header) ? " COMPRESSED" : "",
+ (le32toh(f->header->incompatible_flags) & ~HEADER_INCOMPATIBLE_COMPRESSED) ? " ???" : "",
+ (unsigned long long) le64toh(f->header->header_size),
+ (unsigned long long) le64toh(f->header->arena_size),
+ (unsigned long long) le64toh(f->header->data_hash_table_size) / sizeof(HashItem),
+ (unsigned long long) le64toh(f->header->field_hash_table_size) / sizeof(HashItem),
+ yes_no(journal_file_rotate_suggested(f, 0)),
+ (unsigned long long) le64toh(f->header->head_entry_seqnum),
+ (unsigned long long) le64toh(f->header->tail_entry_seqnum),
+ format_timestamp(x, sizeof(x), le64toh(f->header->head_entry_realtime)),
+ format_timestamp(y, sizeof(y), le64toh(f->header->tail_entry_realtime)),
+ (unsigned long long) le64toh(f->header->n_objects),
+ (unsigned long long) le64toh(f->header->n_entries));
+
+ if (JOURNAL_HEADER_CONTAINS(f->header, n_data))
+ printf("Data Objects: %llu\n"
+ "Data Hash Table Fill: %.1f%%\n",
+ (unsigned long long) le64toh(f->header->n_data),
+ 100.0 * (double) le64toh(f->header->n_data) / ((double) (le64toh(f->header->data_hash_table_size) / sizeof(HashItem))));
+
+ if (JOURNAL_HEADER_CONTAINS(f->header, n_fields))
+ printf("Field Objects: %llu\n"
+ "Field Hash Table Fill: %.1f%%\n",
+ (unsigned long long) le64toh(f->header->n_fields),
+ 100.0 * (double) le64toh(f->header->n_fields) / ((double) (le64toh(f->header->field_hash_table_size) / sizeof(HashItem))));
+
+ if (JOURNAL_HEADER_CONTAINS(f->header, n_tags))
+ printf("Tag Objects: %llu\n",
+ (unsigned long long) le64toh(f->header->n_tags));
+ if (JOURNAL_HEADER_CONTAINS(f->header, n_entry_arrays))
+ printf("Entry Array Objects: %llu\n",
+ (unsigned long long) le64toh(f->header->n_entry_arrays));
+
+ if (fstat(f->fd, &st) >= 0)
+ printf("Disk usage: %s\n", format_bytes(bytes, sizeof(bytes), (off_t) st.st_blocks * 512ULL));
+}
+
+int journal_file_open(
+ const char *fname,
+ int flags,
+ mode_t mode,
+ bool compress,
+ bool seal,
+ JournalMetrics *metrics,
+ MMapCache *mmap_cache,
+ JournalFile *template,
+ JournalFile **ret) {
+
+ JournalFile *f;
+ int r;
+ bool newly_created = false;
+
+ assert(fname);
+ assert(ret);
+
+ if ((flags & O_ACCMODE) != O_RDONLY &&
+ (flags & O_ACCMODE) != O_RDWR)
+ return -EINVAL;
+
+ if (!endswith(fname, ".journal") &&
+ !endswith(fname, ".journal~"))
+ return -EINVAL;
+
+ f = new0(JournalFile, 1);
+ if (!f)
+ return -ENOMEM;
+
+ f->fd = -1;
+ f->mode = mode;
+
+ f->flags = flags;
+ f->prot = prot_from_flags(flags);
+ f->writable = (flags & O_ACCMODE) != O_RDONLY;
+#ifdef HAVE_XZ
+ f->compress = compress;
+#endif
+#ifdef HAVE_GCRYPT
+ f->seal = seal;
+#endif
+
+ if (mmap_cache)
+ f->mmap = mmap_cache_ref(mmap_cache);
+ else {
+ f->mmap = mmap_cache_new();
+ if (!f->mmap) {
+ r = -ENOMEM;
+ goto fail;
+ }
+ }
+
+ f->path = strdup(fname);
+ if (!f->path) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ f->chain_cache = hashmap_new(uint64_hash_func, uint64_compare_func);
+ if (!f->chain_cache) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ f->fd = open(f->path, f->flags|O_CLOEXEC, f->mode);
+ if (f->fd < 0) {
+ r = -errno;
+ goto fail;
+ }
+
+ if (fstat(f->fd, &f->last_stat) < 0) {
+ r = -errno;
+ goto fail;
+ }
+
+ if (f->last_stat.st_size == 0 && f->writable) {
+#ifdef HAVE_XATTR
+ uint64_t crtime;
+
+ /* Let's attach the creation time to the journal file,
+ * so that the vacuuming code knows the age of this
+ * file even if the file might end up corrupted one
+ * day... Ideally we'd just use the creation time many
+ * file systems maintain for each file, but there is
+ * currently no usable API to query this, hence let's
+ * emulate this via extended attributes. If extended
+ * attributes are not supported we'll just skip this,
+ * and rely solely on mtime/atime/ctime of the file.*/
+
+ crtime = htole64((uint64_t) now(CLOCK_REALTIME));
+ fsetxattr(f->fd, "user.crtime_usec", &crtime, sizeof(crtime), XATTR_CREATE);
+#endif
+
+#ifdef HAVE_GCRYPT
+ /* Try to load the FSPRG state, and if we can't, then
+ * just don't do sealing */
+ if (f->seal) {
+ r = journal_file_fss_load(f);
+ if (r < 0)
+ f->seal = false;
+ }
+#endif
+
+ r = journal_file_init_header(f, template);
+ if (r < 0)
+ goto fail;
+
+ if (fstat(f->fd, &f->last_stat) < 0) {
+ r = -errno;
+ goto fail;
+ }
+
+ newly_created = true;
+ }
+
+ if (f->last_stat.st_size < (off_t) HEADER_SIZE_MIN) {
+ r = -EIO;
+ goto fail;
+ }
+
+ f->header = mmap(NULL, PAGE_ALIGN(sizeof(Header)), prot_from_flags(flags), MAP_SHARED, f->fd, 0);
+ if (f->header == MAP_FAILED) {
+ f->header = NULL;
+ r = -errno;
+ goto fail;
+ }
+
+ if (!newly_created) {
+ r = journal_file_verify_header(f);
+ if (r < 0)
+ goto fail;
+ }
+
+#ifdef HAVE_GCRYPT
+ if (!newly_created && f->writable) {
+ r = journal_file_fss_load(f);
+ if (r < 0)
+ goto fail;
+ }
+#endif
+
+ if (f->writable) {
+ if (metrics) {
+ journal_default_metrics(metrics, f->fd);
+ f->metrics = *metrics;
+ } else if (template)
+ f->metrics = template->metrics;
+
+ r = journal_file_refresh_header(f);
+ if (r < 0)
+ goto fail;
+ }
+
+#ifdef HAVE_GCRYPT
+ r = journal_file_hmac_setup(f);
+ if (r < 0)
+ goto fail;
+#endif
+
+ if (newly_created) {
+ r = journal_file_setup_field_hash_table(f);
+ if (r < 0)
+ goto fail;
+
+ r = journal_file_setup_data_hash_table(f);
+ if (r < 0)
+ goto fail;
+
+#ifdef HAVE_GCRYPT
+ r = journal_file_append_first_tag(f);
+ if (r < 0)
+ goto fail;
+#endif
+ }
+
+ r = journal_file_map_field_hash_table(f);
+ if (r < 0)
+ goto fail;
+
+ r = journal_file_map_data_hash_table(f);
+ if (r < 0)
+ goto fail;
+
+ *ret = f;
+ return 0;
+
+fail:
+ journal_file_close(f);
+
+ return r;
+}
+
+int journal_file_rotate(JournalFile **f, bool compress, bool seal) {
+ char *p;
+ size_t l;
+ JournalFile *old_file, *new_file = NULL;
+ int r;
+
+ assert(f);
+ assert(*f);
+
+ old_file = *f;
+
+ if (!old_file->writable)
+ return -EINVAL;
+
+ if (!endswith(old_file->path, ".journal"))
+ return -EINVAL;
+
+ l = strlen(old_file->path);
+
+ p = new(char, l + 1 + 32 + 1 + 16 + 1 + 16 + 1);
+ if (!p)
+ return -ENOMEM;
+
+ memcpy(p, old_file->path, l - 8);
+ p[l-8] = '@';
+ sd_id128_to_string(old_file->header->seqnum_id, p + l - 8 + 1);
+ snprintf(p + l - 8 + 1 + 32, 1 + 16 + 1 + 16 + 8 + 1,
+ "-%016llx-%016llx.journal",
+ (unsigned long long) le64toh((*f)->header->head_entry_seqnum),
+ (unsigned long long) le64toh((*f)->header->head_entry_realtime));
+
+ r = rename(old_file->path, p);
+ free(p);
+
+ if (r < 0)
+ return -errno;
+
+ old_file->header->state = STATE_ARCHIVED;
+
+ r = journal_file_open(old_file->path, old_file->flags, old_file->mode, compress, seal, NULL, old_file->mmap, old_file, &new_file);
+ journal_file_close(old_file);
+
+ *f = new_file;
+ return r;
+}
+
+int journal_file_open_reliably(
+ const char *fname,
+ int flags,
+ mode_t mode,
+ bool compress,
+ bool seal,
+ JournalMetrics *metrics,
+ MMapCache *mmap_cache,
+ JournalFile *template,
+ JournalFile **ret) {
+
+ int r;
+ size_t l;
+ char *p;
+
+ r = journal_file_open(fname, flags, mode, compress, seal,
+ metrics, mmap_cache, template, ret);
+ if (r != -EBADMSG && /* corrupted */
+ r != -ENODATA && /* truncated */
+ r != -EHOSTDOWN && /* other machine */
+ r != -EPROTONOSUPPORT && /* incompatible feature */
+ r != -EBUSY && /* unclean shutdown */
+ r != -ESHUTDOWN /* already archived */)
+ return r;
+
+ if ((flags & O_ACCMODE) == O_RDONLY)
+ return r;
+
+ if (!(flags & O_CREAT))
+ return r;
+
+ if (!endswith(fname, ".journal"))
+ return r;
+
+ /* The file is corrupted. Rotate it away and try it again (but only once) */
+
+ l = strlen(fname);
+ if (asprintf(&p, "%.*s@%016llx-%016llx.journal~",
+ (int) (l-8), fname,
+ (unsigned long long) now(CLOCK_REALTIME),
+ random_ull()) < 0)
+ return -ENOMEM;
+
+ r = rename(fname, p);
+ free(p);
+ if (r < 0)
+ return -errno;
+
+ log_warning("File %s corrupted or uncleanly shut down, renaming and replacing.", fname);
+
+ return journal_file_open(fname, flags, mode, compress, seal,
+ metrics, mmap_cache, template, ret);
+}
+
+int journal_file_copy_entry(JournalFile *from, JournalFile *to, Object *o, uint64_t p, uint64_t *seqnum, Object **ret, uint64_t *offset) {
+ uint64_t i, n;
+ uint64_t q, xor_hash = 0;
+ int r;
+ EntryItem *items;
+ dual_timestamp ts;
+
+ assert(from);
+ assert(to);
+ assert(o);
+ assert(p);
+
+ if (!to->writable)
+ return -EPERM;
+
+ ts.monotonic = le64toh(o->entry.monotonic);
+ ts.realtime = le64toh(o->entry.realtime);
+
+ if (to->tail_entry_monotonic_valid &&
+ ts.monotonic < le64toh(to->header->tail_entry_monotonic))
+ return -EINVAL;
+
+ n = journal_file_entry_n_items(o);
+ items = alloca(sizeof(EntryItem) * n);
+
+ for (i = 0; i < n; i++) {
+ uint64_t l, h;
+ le64_t le_hash;
+ size_t t;
+ void *data;
+ Object *u;
+
+ q = le64toh(o->entry.items[i].object_offset);
+ le_hash = o->entry.items[i].hash;
+
+ r = journal_file_move_to_object(from, OBJECT_DATA, q, &o);
+ if (r < 0)
+ return r;
+
+ if (le_hash != o->data.hash)
+ return -EBADMSG;
+
+ l = le64toh(o->object.size) - offsetof(Object, data.payload);
+ t = (size_t) l;
+
+ /* We hit the limit on 32bit machines */
+ if ((uint64_t) t != l)
+ return -E2BIG;
+
+ if (o->object.flags & OBJECT_COMPRESSED) {
+#ifdef HAVE_XZ
+ uint64_t rsize;
+
+ if (!uncompress_blob(o->data.payload, l, &from->compress_buffer, &from->compress_buffer_size, &rsize, 0))
+ return -EBADMSG;
+
+ data = from->compress_buffer;
+ l = rsize;
+#else
+ return -EPROTONOSUPPORT;
+#endif
+ } else
+ data = o->data.payload;
+
+ r = journal_file_append_data(to, data, l, &u, &h);
+ if (r < 0)
+ return r;
+
+ xor_hash ^= le64toh(u->data.hash);
+ items[i].object_offset = htole64(h);
+ items[i].hash = u->data.hash;
+
+ r = journal_file_move_to_object(from, OBJECT_ENTRY, p, &o);
+ if (r < 0)
+ return r;
+ }
+
+ return journal_file_append_entry_internal(to, &ts, xor_hash, items, n, seqnum, ret, offset);
+}
+
+void journal_default_metrics(JournalMetrics *m, int fd) {
+ uint64_t fs_size = 0;
+ struct statvfs ss;
+ char a[FORMAT_BYTES_MAX], b[FORMAT_BYTES_MAX], c[FORMAT_BYTES_MAX], d[FORMAT_BYTES_MAX];
+
+ assert(m);
+ assert(fd >= 0);
+
+ if (fstatvfs(fd, &ss) >= 0)
+ fs_size = ss.f_frsize * ss.f_blocks;
+
+ if (m->max_use == (uint64_t) -1) {
+
+ if (fs_size > 0) {
+ m->max_use = PAGE_ALIGN(fs_size / 10); /* 10% of file system size */
+
+ if (m->max_use > DEFAULT_MAX_USE_UPPER)
+ m->max_use = DEFAULT_MAX_USE_UPPER;
+
+ if (m->max_use < DEFAULT_MAX_USE_LOWER)
+ m->max_use = DEFAULT_MAX_USE_LOWER;
+ } else
+ m->max_use = DEFAULT_MAX_USE_LOWER;
+ } else {
+ m->max_use = PAGE_ALIGN(m->max_use);
+
+ if (m->max_use < JOURNAL_FILE_SIZE_MIN*2)
+ m->max_use = JOURNAL_FILE_SIZE_MIN*2;
+ }
+
+ if (m->max_size == (uint64_t) -1) {
+ m->max_size = PAGE_ALIGN(m->max_use / 8); /* 8 chunks */
+
+ if (m->max_size > DEFAULT_MAX_SIZE_UPPER)
+ m->max_size = DEFAULT_MAX_SIZE_UPPER;
+ } else
+ m->max_size = PAGE_ALIGN(m->max_size);
+
+ if (m->max_size < JOURNAL_FILE_SIZE_MIN)
+ m->max_size = JOURNAL_FILE_SIZE_MIN;
+
+ if (m->max_size*2 > m->max_use)
+ m->max_use = m->max_size*2;
+
+ if (m->min_size == (uint64_t) -1)
+ m->min_size = JOURNAL_FILE_SIZE_MIN;
+ else {
+ m->min_size = PAGE_ALIGN(m->min_size);
+
+ if (m->min_size < JOURNAL_FILE_SIZE_MIN)
+ m->min_size = JOURNAL_FILE_SIZE_MIN;
+
+ if (m->min_size > m->max_size)
+ m->max_size = m->min_size;
+ }
+
+ if (m->keep_free == (uint64_t) -1) {
+
+ if (fs_size > 0) {
+ m->keep_free = PAGE_ALIGN(fs_size * 3 / 20); /* 15% of file system size */
+
+ if (m->keep_free > DEFAULT_KEEP_FREE_UPPER)
+ m->keep_free = DEFAULT_KEEP_FREE_UPPER;
+
+ } else
+ m->keep_free = DEFAULT_KEEP_FREE;
+ }
+
+ log_debug("Fixed max_use=%s max_size=%s min_size=%s keep_free=%s",
+ format_bytes(a, sizeof(a), m->max_use),
+ format_bytes(b, sizeof(b), m->max_size),
+ format_bytes(c, sizeof(c), m->min_size),
+ format_bytes(d, sizeof(d), m->keep_free));
+}
+
+int journal_file_get_cutoff_realtime_usec(JournalFile *f, usec_t *from, usec_t *to) {
+ assert(f);
+ assert(from || to);
+
+ if (from) {
+ if (f->header->head_entry_realtime == 0)
+ return -ENOENT;
+
+ *from = le64toh(f->header->head_entry_realtime);
+ }
+
+ if (to) {
+ if (f->header->tail_entry_realtime == 0)
+ return -ENOENT;
+
+ *to = le64toh(f->header->tail_entry_realtime);
+ }
+
+ return 1;
+}
+
+int journal_file_get_cutoff_monotonic_usec(JournalFile *f, sd_id128_t boot_id, usec_t *from, usec_t *to) {
+ Object *o;
+ uint64_t p;
+ int r;
+
+ assert(f);
+ assert(from || to);
+
+ r = find_data_object_by_boot_id(f, boot_id, &o, &p);
+ if (r <= 0)
+ return r;
+
+ if (le64toh(o->data.n_entries) <= 0)
+ return 0;
+
+ if (from) {
+ r = journal_file_move_to_object(f, OBJECT_ENTRY, le64toh(o->data.entry_offset), &o);
+ if (r < 0)
+ return r;
+
+ *from = le64toh(o->entry.monotonic);
+ }
+
+ if (to) {
+ r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
+ if (r < 0)
+ return r;
+
+ r = generic_array_get_plus_one(f,
+ le64toh(o->data.entry_offset),
+ le64toh(o->data.entry_array_offset),
+ le64toh(o->data.n_entries)-1,
+ &o, NULL);
+ if (r <= 0)
+ return r;
+
+ *to = le64toh(o->entry.monotonic);
+ }
+
+ return 1;
+}
+
+bool journal_file_rotate_suggested(JournalFile *f, usec_t max_file_usec) {
+ assert(f);
+
+ /* If we gained new header fields we gained new features,
+ * hence suggest a rotation */
+ if (le64toh(f->header->header_size) < sizeof(Header)) {
+ log_debug("%s uses an outdated header, suggesting rotation.", f->path);
+ return true;
+ }
+
+ /* Let's check if the hash tables grew over a certain fill
+ * level (75%, borrowing this value from Java's hash table
+ * implementation), and if so suggest a rotation. To calculate
+ * the fill level we need the n_data field, which only exists
+ * in newer versions. */
+
+ if (JOURNAL_HEADER_CONTAINS(f->header, n_data))
+ if (le64toh(f->header->n_data) * 4ULL > (le64toh(f->header->data_hash_table_size) / sizeof(HashItem)) * 3ULL) {
+ log_debug("Data hash table of %s has a fill level at %.1f (%llu of %llu items, %llu file size, %llu bytes per hash table item), suggesting rotation.",
+ f->path,
+ 100.0 * (double) le64toh(f->header->n_data) / ((double) (le64toh(f->header->data_hash_table_size) / sizeof(HashItem))),
+ (unsigned long long) le64toh(f->header->n_data),
+ (unsigned long long) (le64toh(f->header->data_hash_table_size) / sizeof(HashItem)),
+ (unsigned long long) (f->last_stat.st_size),
+ (unsigned long long) (f->last_stat.st_size / le64toh(f->header->n_data)));
+ return true;
+ }
+
+ if (JOURNAL_HEADER_CONTAINS(f->header, n_fields))
+ if (le64toh(f->header->n_fields) * 4ULL > (le64toh(f->header->field_hash_table_size) / sizeof(HashItem)) * 3ULL) {
+ log_debug("Field hash table of %s has a fill level at %.1f (%llu of %llu items), suggesting rotation.",
+ f->path,
+ 100.0 * (double) le64toh(f->header->n_fields) / ((double) (le64toh(f->header->field_hash_table_size) / sizeof(HashItem))),
+ (unsigned long long) le64toh(f->header->n_fields),
+ (unsigned long long) (le64toh(f->header->field_hash_table_size) / sizeof(HashItem)));
+ return true;
+ }
+
+ /* Are the data objects properly indexed by field objects? */
+ if (JOURNAL_HEADER_CONTAINS(f->header, n_data) &&
+ JOURNAL_HEADER_CONTAINS(f->header, n_fields) &&
+ le64toh(f->header->n_data) > 0 &&
+ le64toh(f->header->n_fields) == 0)
+ return true;
+
+ if (max_file_usec > 0) {
+ usec_t t, h;
+
+ h = le64toh(f->header->head_entry_realtime);
+ t = now(CLOCK_REALTIME);
+
+ if (h > 0 && t > h + max_file_usec)
+ return true;
+ }
+
+ return false;
+}
diff --git a/src/journal/journal-file.h b/src/journal/journal-file.h
new file mode 100644
index 0000000000..7b1cd42854
--- /dev/null
+++ b/src/journal/journal-file.h
@@ -0,0 +1,195 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <inttypes.h>
+
+#ifdef HAVE_GCRYPT
+#include <gcrypt.h>
+#endif
+
+#include <systemd/sd-id128.h>
+
+#include "sparse-endian.h"
+#include "journal-def.h"
+#include "util.h"
+#include "mmap-cache.h"
+#include "hashmap.h"
+
+typedef struct JournalMetrics {
+ uint64_t max_use;
+ uint64_t max_size;
+ uint64_t min_size;
+ uint64_t keep_free;
+} JournalMetrics;
+
+typedef struct JournalFile {
+ int fd;
+ char *path;
+ struct stat last_stat;
+ mode_t mode;
+
+ int flags;
+ int prot;
+ bool writable;
+ bool compress;
+ bool seal;
+
+ bool tail_entry_monotonic_valid;
+
+ Header *header;
+ HashItem *data_hash_table;
+ HashItem *field_hash_table;
+
+ uint64_t current_offset;
+
+ JournalMetrics metrics;
+ MMapCache *mmap;
+
+ Hashmap *chain_cache;
+
+#ifdef HAVE_XZ
+ void *compress_buffer;
+ uint64_t compress_buffer_size;
+#endif
+
+#ifdef HAVE_GCRYPT
+ gcry_md_hd_t hmac;
+ bool hmac_running;
+
+ FSSHeader *fss_file;
+ size_t fss_file_size;
+
+ uint64_t fss_start_usec;
+ uint64_t fss_interval_usec;
+
+ void *fsprg_state;
+ size_t fsprg_state_size;
+
+ void *fsprg_seed;
+ size_t fsprg_seed_size;
+#endif
+} JournalFile;
+
+typedef enum direction {
+ DIRECTION_UP,
+ DIRECTION_DOWN
+} direction_t;
+
+int journal_file_open(
+ const char *fname,
+ int flags,
+ mode_t mode,
+ bool compress,
+ bool seal,
+ JournalMetrics *metrics,
+ MMapCache *mmap_cache,
+ JournalFile *template,
+ JournalFile **ret);
+
+int journal_file_set_offline(JournalFile *f);
+int journal_file_set_online(JournalFile *f);
+void journal_file_close(JournalFile *j);
+
+int journal_file_open_reliably(
+ const char *fname,
+ int flags,
+ mode_t mode,
+ bool compress,
+ bool seal,
+ JournalMetrics *metrics,
+ MMapCache *mmap_cache,
+ JournalFile *template,
+ JournalFile **ret);
+
+#define ALIGN64(x) (((x) + 7ULL) & ~7ULL)
+#define VALID64(x) (((x) & 7ULL) == 0ULL)
+
+static inline bool VALID_REALTIME(uint64_t u) {
+ /* This considers timestamps until the year 3112 valid. That should be plenty room... */
+ return u > 0 && u < (1ULL << 55);
+}
+
+static inline bool VALID_MONOTONIC(uint64_t u) {
+ /* This considers timestamps until 1142 years of runtime valid. */
+ return u < (1ULL << 55);
+}
+
+static inline bool VALID_EPOCH(uint64_t u) {
+ /* This allows changing the key for 1142 years, every usec. */
+ return u < (1ULL << 55);
+}
+
+#define JOURNAL_HEADER_CONTAINS(h, field) \
+ (le64toh((h)->header_size) >= offsetof(Header, field) + sizeof((h)->field))
+
+#define JOURNAL_HEADER_SEALED(h) \
+ (!!(le32toh((h)->compatible_flags) & HEADER_COMPATIBLE_SEALED))
+
+#define JOURNAL_HEADER_COMPRESSED(h) \
+ (!!(le32toh((h)->incompatible_flags) & HEADER_INCOMPATIBLE_COMPRESSED))
+
+int journal_file_move_to_object(JournalFile *f, int type, uint64_t offset, Object **ret);
+
+uint64_t journal_file_entry_n_items(Object *o) _pure_;
+uint64_t journal_file_entry_array_n_items(Object *o) _pure_;
+uint64_t journal_file_hash_table_n_items(Object *o) _pure_;
+
+int journal_file_append_object(JournalFile *f, int type, uint64_t size, Object **ret, uint64_t *offset);
+int journal_file_append_entry(JournalFile *f, const dual_timestamp *ts, const struct iovec iovec[], unsigned n_iovec, uint64_t *seqno, Object **ret, uint64_t *offset);
+
+int journal_file_find_data_object(JournalFile *f, const void *data, uint64_t size, Object **ret, uint64_t *offset);
+int journal_file_find_data_object_with_hash(JournalFile *f, const void *data, uint64_t size, uint64_t hash, Object **ret, uint64_t *offset);
+
+int journal_file_find_field_object(JournalFile *f, const void *field, uint64_t size, Object **ret, uint64_t *offset);
+int journal_file_find_field_object_with_hash(JournalFile *f, const void *field, uint64_t size, uint64_t hash, Object **ret, uint64_t *offset);
+
+int journal_file_next_entry(JournalFile *f, Object *o, uint64_t p, direction_t direction, Object **ret, uint64_t *offset);
+int journal_file_skip_entry(JournalFile *f, Object *o, uint64_t p, int64_t skip, Object **ret, uint64_t *offset);
+
+int journal_file_next_entry_for_data(JournalFile *f, Object *o, uint64_t p, uint64_t data_offset, direction_t direction, Object **ret, uint64_t *offset);
+
+int journal_file_move_to_entry_by_offset(JournalFile *f, uint64_t seqnum, direction_t direction, Object **ret, uint64_t *offset);
+int journal_file_move_to_entry_by_seqnum(JournalFile *f, uint64_t seqnum, direction_t direction, Object **ret, uint64_t *offset);
+int journal_file_move_to_entry_by_realtime(JournalFile *f, uint64_t realtime, direction_t direction, Object **ret, uint64_t *offset);
+int journal_file_move_to_entry_by_monotonic(JournalFile *f, sd_id128_t boot_id, uint64_t monotonic, direction_t direction, Object **ret, uint64_t *offset);
+
+int journal_file_move_to_entry_by_offset_for_data(JournalFile *f, uint64_t data_offset, uint64_t p, direction_t direction, Object **ret, uint64_t *offset);
+int journal_file_move_to_entry_by_seqnum_for_data(JournalFile *f, uint64_t data_offset, uint64_t seqnum, direction_t direction, Object **ret, uint64_t *offset);
+int journal_file_move_to_entry_by_realtime_for_data(JournalFile *f, uint64_t data_offset, uint64_t realtime, direction_t direction, Object **ret, uint64_t *offset);
+int journal_file_move_to_entry_by_monotonic_for_data(JournalFile *f, uint64_t data_offset, sd_id128_t boot_id, uint64_t monotonic, direction_t direction, Object **ret, uint64_t *offset);
+
+int journal_file_copy_entry(JournalFile *from, JournalFile *to, Object *o, uint64_t p, uint64_t *seqnum, Object **ret, uint64_t *offset);
+
+void journal_file_dump(JournalFile *f);
+void journal_file_print_header(JournalFile *f);
+
+int journal_file_rotate(JournalFile **f, bool compress, bool seal);
+
+void journal_file_post_change(JournalFile *f);
+
+void journal_default_metrics(JournalMetrics *m, int fd);
+
+int journal_file_get_cutoff_realtime_usec(JournalFile *f, usec_t *from, usec_t *to);
+int journal_file_get_cutoff_monotonic_usec(JournalFile *f, sd_id128_t boot, usec_t *from, usec_t *to);
+
+bool journal_file_rotate_suggested(JournalFile *f, usec_t max_file_usec);
diff --git a/src/journal/journal-gatewayd.c b/src/journal/journal-gatewayd.c
new file mode 100644
index 0000000000..745f45f932
--- /dev/null
+++ b/src/journal/journal-gatewayd.c
@@ -0,0 +1,1069 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <getopt.h>
+
+#include <microhttpd.h>
+
+#include "log.h"
+#include "util.h"
+#include "sd-journal.h"
+#include "sd-daemon.h"
+#include "sd-bus.h"
+#include "bus-message.h"
+#include "bus-internal.h"
+#include "logs-show.h"
+#include "microhttpd-util.h"
+#include "build.h"
+#include "fileio.h"
+
+typedef struct RequestMeta {
+ sd_journal *journal;
+
+ OutputMode mode;
+
+ char *cursor;
+ int64_t n_skip;
+ uint64_t n_entries;
+ bool n_entries_set;
+
+ FILE *tmp;
+ uint64_t delta, size;
+
+ int argument_parse_error;
+
+ bool follow;
+ bool discrete;
+
+ uint64_t n_fields;
+ bool n_fields_set;
+} RequestMeta;
+
+static const char* const mime_types[_OUTPUT_MODE_MAX] = {
+ [OUTPUT_SHORT] = "text/plain",
+ [OUTPUT_JSON] = "application/json",
+ [OUTPUT_JSON_SSE] = "text/event-stream",
+ [OUTPUT_EXPORT] = "application/vnd.fdo.journal",
+};
+
+static RequestMeta *request_meta(void **connection_cls) {
+ RequestMeta *m;
+
+ if (*connection_cls)
+ return *connection_cls;
+
+ m = new0(RequestMeta, 1);
+ if (!m)
+ return NULL;
+
+ *connection_cls = m;
+ return m;
+}
+
+static void request_meta_free(
+ void *cls,
+ struct MHD_Connection *connection,
+ void **connection_cls,
+ enum MHD_RequestTerminationCode toe) {
+
+ RequestMeta *m = *connection_cls;
+
+ if (!m)
+ return;
+
+ if (m->journal)
+ sd_journal_close(m->journal);
+
+ if (m->tmp)
+ fclose(m->tmp);
+
+ free(m->cursor);
+ free(m);
+}
+
+static int open_journal(RequestMeta *m) {
+ assert(m);
+
+ if (m->journal)
+ return 0;
+
+ return sd_journal_open(&m->journal, SD_JOURNAL_LOCAL_ONLY|SD_JOURNAL_SYSTEM_ONLY);
+}
+
+static int respond_oom_internal(struct MHD_Connection *connection) {
+ struct MHD_Response *response;
+ const char m[] = "Out of memory.\n";
+ int ret;
+
+ assert(connection);
+
+ response = MHD_create_response_from_buffer(sizeof(m)-1, (char*) m, MHD_RESPMEM_PERSISTENT);
+ if (!response)
+ return MHD_NO;
+
+ MHD_add_response_header(response, "Content-Type", "text/plain");
+ ret = MHD_queue_response(connection, MHD_HTTP_SERVICE_UNAVAILABLE, response);
+ MHD_destroy_response(response);
+
+ return ret;
+}
+
+#define respond_oom(connection) log_oom(), respond_oom_internal(connection)
+
+static int respond_error(
+ struct MHD_Connection *connection,
+ unsigned code,
+ const char *format, ...) {
+
+ struct MHD_Response *response;
+ char *m;
+ int r;
+ va_list ap;
+
+ assert(connection);
+ assert(format);
+
+ va_start(ap, format);
+ r = vasprintf(&m, format, ap);
+ va_end(ap);
+
+ if (r < 0)
+ return respond_oom(connection);
+
+ response = MHD_create_response_from_buffer(strlen(m), m, MHD_RESPMEM_MUST_FREE);
+ if (!response) {
+ free(m);
+ return respond_oom(connection);
+ }
+
+ MHD_add_response_header(response, "Content-Type", "text/plain");
+ r = MHD_queue_response(connection, code, response);
+ MHD_destroy_response(response);
+
+ return r;
+}
+
+static ssize_t request_reader_entries(
+ void *cls,
+ uint64_t pos,
+ char *buf,
+ size_t max) {
+
+ RequestMeta *m = cls;
+ int r;
+ size_t n, k;
+
+ assert(m);
+ assert(buf);
+ assert(max > 0);
+ assert(pos >= m->delta);
+
+ pos -= m->delta;
+
+ while (pos >= m->size) {
+ off_t sz;
+
+ /* End of this entry, so let's serialize the next
+ * one */
+
+ if (m->n_entries_set &&
+ m->n_entries <= 0)
+ return MHD_CONTENT_READER_END_OF_STREAM;
+
+ if (m->n_skip < 0)
+ r = sd_journal_previous_skip(m->journal, (uint64_t) -m->n_skip + 1);
+ else if (m->n_skip > 0)
+ r = sd_journal_next_skip(m->journal, (uint64_t) m->n_skip + 1);
+ else
+ r = sd_journal_next(m->journal);
+
+ if (r < 0) {
+ log_error("Failed to advance journal pointer: %s", strerror(-r));
+ return MHD_CONTENT_READER_END_WITH_ERROR;
+ } else if (r == 0) {
+
+ if (m->follow) {
+ r = sd_journal_wait(m->journal, (uint64_t) -1);
+ if (r < 0) {
+ log_error("Couldn't wait for journal event: %s", strerror(-r));
+ return MHD_CONTENT_READER_END_WITH_ERROR;
+ }
+
+ continue;
+ }
+
+ return MHD_CONTENT_READER_END_OF_STREAM;
+ }
+
+ if (m->discrete) {
+ assert(m->cursor);
+
+ r = sd_journal_test_cursor(m->journal, m->cursor);
+ if (r < 0) {
+ log_error("Failed to test cursor: %s", strerror(-r));
+ return MHD_CONTENT_READER_END_WITH_ERROR;
+ }
+
+ if (r == 0)
+ return MHD_CONTENT_READER_END_OF_STREAM;
+ }
+
+ pos -= m->size;
+ m->delta += m->size;
+
+ if (m->n_entries_set)
+ m->n_entries -= 1;
+
+ m->n_skip = 0;
+
+ if (m->tmp)
+ rewind(m->tmp);
+ else {
+ m->tmp = tmpfile();
+ if (!m->tmp) {
+ log_error("Failed to create temporary file: %m");
+ return MHD_CONTENT_READER_END_WITH_ERROR;
+ }
+ }
+
+ r = output_journal(m->tmp, m->journal, m->mode, 0, OUTPUT_FULL_WIDTH);
+ if (r < 0) {
+ log_error("Failed to serialize item: %s", strerror(-r));
+ return MHD_CONTENT_READER_END_WITH_ERROR;
+ }
+
+ sz = ftello(m->tmp);
+ if (sz == (off_t) -1) {
+ log_error("Failed to retrieve file position: %m");
+ return MHD_CONTENT_READER_END_WITH_ERROR;
+ }
+
+ m->size = (uint64_t) sz;
+ }
+
+ if (fseeko(m->tmp, pos, SEEK_SET) < 0) {
+ log_error("Failed to seek to position: %m");
+ return MHD_CONTENT_READER_END_WITH_ERROR;
+ }
+
+ n = m->size - pos;
+ if (n > max)
+ n = max;
+
+ errno = 0;
+ k = fread(buf, 1, n, m->tmp);
+ if (k != n) {
+ log_error("Failed to read from file: %s", errno ? strerror(errno) : "Premature EOF");
+ return MHD_CONTENT_READER_END_WITH_ERROR;
+ }
+
+ return (ssize_t) k;
+}
+
+static int request_parse_accept(
+ RequestMeta *m,
+ struct MHD_Connection *connection) {
+
+ const char *header;
+
+ assert(m);
+ assert(connection);
+
+ header = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, "Accept");
+ if (!header)
+ return 0;
+
+ if (streq(header, mime_types[OUTPUT_JSON]))
+ m->mode = OUTPUT_JSON;
+ else if (streq(header, mime_types[OUTPUT_JSON_SSE]))
+ m->mode = OUTPUT_JSON_SSE;
+ else if (streq(header, mime_types[OUTPUT_EXPORT]))
+ m->mode = OUTPUT_EXPORT;
+ else
+ m->mode = OUTPUT_SHORT;
+
+ return 0;
+}
+
+static int request_parse_range(
+ RequestMeta *m,
+ struct MHD_Connection *connection) {
+
+ const char *range, *colon, *colon2;
+ int r;
+
+ assert(m);
+ assert(connection);
+
+ range = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, "Range");
+ if (!range)
+ return 0;
+
+ if (!startswith(range, "entries="))
+ return 0;
+
+ range += 8;
+ range += strspn(range, WHITESPACE);
+
+ colon = strchr(range, ':');
+ if (!colon)
+ m->cursor = strdup(range);
+ else {
+ const char *p;
+
+ colon2 = strchr(colon + 1, ':');
+ if (colon2) {
+ _cleanup_free_ char *t;
+
+ t = strndup(colon + 1, colon2 - colon - 1);
+ if (!t)
+ return -ENOMEM;
+
+ r = safe_atoi64(t, &m->n_skip);
+ if (r < 0)
+ return r;
+ }
+
+ p = (colon2 ? colon2 : colon) + 1;
+ if (*p) {
+ r = safe_atou64(p, &m->n_entries);
+ if (r < 0)
+ return r;
+
+ if (m->n_entries <= 0)
+ return -EINVAL;
+
+ m->n_entries_set = true;
+ }
+
+ m->cursor = strndup(range, colon - range);
+ }
+
+ if (!m->cursor)
+ return -ENOMEM;
+
+ m->cursor[strcspn(m->cursor, WHITESPACE)] = 0;
+ if (isempty(m->cursor)) {
+ free(m->cursor);
+ m->cursor = NULL;
+ }
+
+ return 0;
+}
+
+static int request_parse_arguments_iterator(
+ void *cls,
+ enum MHD_ValueKind kind,
+ const char *key,
+ const char *value) {
+
+ RequestMeta *m = cls;
+ _cleanup_free_ char *p = NULL;
+ int r;
+
+ assert(m);
+
+ if (isempty(key)) {
+ m->argument_parse_error = -EINVAL;
+ return MHD_NO;
+ }
+
+ if (streq(key, "follow")) {
+ if (isempty(value)) {
+ m->follow = true;
+ return MHD_YES;
+ }
+
+ r = parse_boolean(value);
+ if (r < 0) {
+ m->argument_parse_error = r;
+ return MHD_NO;
+ }
+
+ m->follow = r;
+ return MHD_YES;
+ }
+
+ if (streq(key, "discrete")) {
+ if (isempty(value)) {
+ m->discrete = true;
+ return MHD_YES;
+ }
+
+ r = parse_boolean(value);
+ if (r < 0) {
+ m->argument_parse_error = r;
+ return MHD_NO;
+ }
+
+ m->discrete = r;
+ return MHD_YES;
+ }
+
+ if (streq(key, "boot")) {
+ if (isempty(value))
+ r = true;
+ else {
+ r = parse_boolean(value);
+ if (r < 0) {
+ m->argument_parse_error = r;
+ return MHD_NO;
+ }
+ }
+
+ if (r) {
+ char match[9 + 32 + 1] = "_BOOT_ID=";
+ sd_id128_t bid;
+
+ r = sd_id128_get_boot(&bid);
+ if (r < 0) {
+ log_error("Failed to get boot ID: %s", strerror(-r));
+ return MHD_NO;
+ }
+
+ sd_id128_to_string(bid, match + 9);
+ r = sd_journal_add_match(m->journal, match, sizeof(match)-1);
+ if (r < 0) {
+ m->argument_parse_error = r;
+ return MHD_NO;
+ }
+ }
+
+ return MHD_YES;
+ }
+
+ p = strjoin(key, "=", strempty(value), NULL);
+ if (!p) {
+ m->argument_parse_error = log_oom();
+ return MHD_NO;
+ }
+
+ r = sd_journal_add_match(m->journal, p, 0);
+ if (r < 0) {
+ m->argument_parse_error = r;
+ return MHD_NO;
+ }
+
+ return MHD_YES;
+}
+
+static int request_parse_arguments(
+ RequestMeta *m,
+ struct MHD_Connection *connection) {
+
+ assert(m);
+ assert(connection);
+
+ m->argument_parse_error = 0;
+ MHD_get_connection_values(connection, MHD_GET_ARGUMENT_KIND, request_parse_arguments_iterator, m);
+
+ return m->argument_parse_error;
+}
+
+static int request_handler_entries(
+ struct MHD_Connection *connection,
+ void *connection_cls) {
+
+ struct MHD_Response *response;
+ RequestMeta *m = connection_cls;
+ int r;
+
+ assert(connection);
+ assert(m);
+
+ r = open_journal(m);
+ if (r < 0)
+ return respond_error(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to open journal: %s\n", strerror(-r));
+
+ if (request_parse_accept(m, connection) < 0)
+ return respond_error(connection, MHD_HTTP_BAD_REQUEST, "Failed to parse Accept header.\n");
+
+ if (request_parse_range(m, connection) < 0)
+ return respond_error(connection, MHD_HTTP_BAD_REQUEST, "Failed to parse Range header.\n");
+
+ if (request_parse_arguments(m, connection) < 0)
+ return respond_error(connection, MHD_HTTP_BAD_REQUEST, "Failed to parse URL arguments.\n");
+
+ if (m->discrete) {
+ if (!m->cursor)
+ return respond_error(connection, MHD_HTTP_BAD_REQUEST, "Discrete seeks require a cursor specification.\n");
+
+ m->n_entries = 1;
+ m->n_entries_set = true;
+ }
+
+ if (m->cursor)
+ r = sd_journal_seek_cursor(m->journal, m->cursor);
+ else if (m->n_skip >= 0)
+ r = sd_journal_seek_head(m->journal);
+ else if (m->n_skip < 0)
+ r = sd_journal_seek_tail(m->journal);
+ if (r < 0)
+ return respond_error(connection, MHD_HTTP_BAD_REQUEST, "Failed to seek in journal.\n");
+
+ response = MHD_create_response_from_callback(MHD_SIZE_UNKNOWN, 4*1024, request_reader_entries, m, NULL);
+ if (!response)
+ return respond_oom(connection);
+
+ MHD_add_response_header(response, "Content-Type", mime_types[m->mode]);
+
+ r = MHD_queue_response(connection, MHD_HTTP_OK, response);
+ MHD_destroy_response(response);
+
+ return r;
+}
+
+static int output_field(FILE *f, OutputMode m, const char *d, size_t l) {
+ const char *eq;
+ size_t j;
+
+ eq = memchr(d, '=', l);
+ if (!eq)
+ return -EINVAL;
+
+ j = l - (eq - d + 1);
+
+ if (m == OUTPUT_JSON) {
+ fprintf(f, "{ \"%.*s\" : ", (int) (eq - d), d);
+ json_escape(f, eq+1, j, OUTPUT_FULL_WIDTH);
+ fputs(" }\n", f);
+ } else {
+ fwrite(eq+1, 1, j, f);
+ fputc('\n', f);
+ }
+
+ return 0;
+}
+
+static ssize_t request_reader_fields(
+ void *cls,
+ uint64_t pos,
+ char *buf,
+ size_t max) {
+
+ RequestMeta *m = cls;
+ int r;
+ size_t n, k;
+
+ assert(m);
+ assert(buf);
+ assert(max > 0);
+ assert(pos >= m->delta);
+
+ pos -= m->delta;
+
+ while (pos >= m->size) {
+ off_t sz;
+ const void *d;
+ size_t l;
+
+ /* End of this field, so let's serialize the next
+ * one */
+
+ if (m->n_fields_set &&
+ m->n_fields <= 0)
+ return MHD_CONTENT_READER_END_OF_STREAM;
+
+ r = sd_journal_enumerate_unique(m->journal, &d, &l);
+ if (r < 0) {
+ log_error("Failed to advance field index: %s", strerror(-r));
+ return MHD_CONTENT_READER_END_WITH_ERROR;
+ } else if (r == 0)
+ return MHD_CONTENT_READER_END_OF_STREAM;
+
+ pos -= m->size;
+ m->delta += m->size;
+
+ if (m->n_fields_set)
+ m->n_fields -= 1;
+
+ if (m->tmp)
+ rewind(m->tmp);
+ else {
+ m->tmp = tmpfile();
+ if (!m->tmp) {
+ log_error("Failed to create temporary file: %m");
+ return MHD_CONTENT_READER_END_WITH_ERROR;
+ }
+ }
+
+ r = output_field(m->tmp, m->mode, d, l);
+ if (r < 0) {
+ log_error("Failed to serialize item: %s", strerror(-r));
+ return MHD_CONTENT_READER_END_WITH_ERROR;
+ }
+
+ sz = ftello(m->tmp);
+ if (sz == (off_t) -1) {
+ log_error("Failed to retrieve file position: %m");
+ return MHD_CONTENT_READER_END_WITH_ERROR;
+ }
+
+ m->size = (uint64_t) sz;
+ }
+
+ if (fseeko(m->tmp, pos, SEEK_SET) < 0) {
+ log_error("Failed to seek to position: %m");
+ return MHD_CONTENT_READER_END_WITH_ERROR;
+ }
+
+ n = m->size - pos;
+ if (n > max)
+ n = max;
+
+ errno = 0;
+ k = fread(buf, 1, n, m->tmp);
+ if (k != n) {
+ log_error("Failed to read from file: %s", errno ? strerror(errno) : "Premature EOF");
+ return MHD_CONTENT_READER_END_WITH_ERROR;
+ }
+
+ return (ssize_t) k;
+}
+
+static int request_handler_fields(
+ struct MHD_Connection *connection,
+ const char *field,
+ void *connection_cls) {
+
+ struct MHD_Response *response;
+ RequestMeta *m = connection_cls;
+ int r;
+
+ assert(connection);
+ assert(m);
+
+ r = open_journal(m);
+ if (r < 0)
+ return respond_error(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to open journal: %s\n", strerror(-r));
+
+ if (request_parse_accept(m, connection) < 0)
+ return respond_error(connection, MHD_HTTP_BAD_REQUEST, "Failed to parse Accept header.\n");
+
+ r = sd_journal_query_unique(m->journal, field);
+ if (r < 0)
+ return respond_error(connection, MHD_HTTP_BAD_REQUEST, "Failed to query unique fields.\n");
+
+ response = MHD_create_response_from_callback(MHD_SIZE_UNKNOWN, 4*1024, request_reader_fields, m, NULL);
+ if (!response)
+ return respond_oom(connection);
+
+ MHD_add_response_header(response, "Content-Type", mime_types[m->mode == OUTPUT_JSON ? OUTPUT_JSON : OUTPUT_SHORT]);
+
+ r = MHD_queue_response(connection, MHD_HTTP_OK, response);
+ MHD_destroy_response(response);
+
+ return r;
+}
+
+static int request_handler_redirect(
+ struct MHD_Connection *connection,
+ const char *target) {
+
+ char *page;
+ struct MHD_Response *response;
+ int ret;
+
+ assert(connection);
+ assert(target);
+
+ if (asprintf(&page, "<html><body>Please continue to the <a href=\"%s\">journal browser</a>.</body></html>", target) < 0)
+ return respond_oom(connection);
+
+ response = MHD_create_response_from_buffer(strlen(page), page, MHD_RESPMEM_MUST_FREE);
+ if (!response) {
+ free(page);
+ return respond_oom(connection);
+ }
+
+ MHD_add_response_header(response, "Content-Type", "text/html");
+ MHD_add_response_header(response, "Location", target);
+
+ ret = MHD_queue_response(connection, MHD_HTTP_MOVED_PERMANENTLY, response);
+ MHD_destroy_response(response);
+
+ return ret;
+}
+
+static int request_handler_file(
+ struct MHD_Connection *connection,
+ const char *path,
+ const char *mime_type) {
+
+ struct MHD_Response *response;
+ int ret;
+ _cleanup_close_ int fd = -1;
+ struct stat st;
+
+ assert(connection);
+ assert(path);
+ assert(mime_type);
+
+ fd = open(path, O_RDONLY|O_CLOEXEC);
+ if (fd < 0)
+ return respond_error(connection, MHD_HTTP_NOT_FOUND, "Failed to open file %s: %m\n", path);
+
+ if (fstat(fd, &st) < 0)
+ return respond_error(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to stat file: %m\n");
+
+ response = MHD_create_response_from_fd_at_offset(st.st_size, fd, 0);
+ if (!response)
+ return respond_oom(connection);
+
+ fd = -1;
+
+ MHD_add_response_header(response, "Content-Type", mime_type);
+
+ ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
+ MHD_destroy_response(response);
+
+ return ret;
+}
+
+static int get_virtualization(char **v) {
+ _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
+ _cleanup_bus_unref_ sd_bus *bus = NULL;
+ const char *t;
+ char *b;
+ int r;
+
+ r = sd_bus_open_system(&bus);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_call_method(
+ bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.DBus.Properties",
+ "Get",
+ NULL,
+ &reply,
+ "ss",
+ "org.freedesktop.systemd1.Manager",
+ "Virtualization");
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_read(reply, "v", "s", &t);
+ if (r < 0)
+ return r;
+
+ if (isempty(t)) {
+ *v = NULL;
+ return 0;
+ }
+
+ b = strdup(t);
+ if (!b)
+ return -ENOMEM;
+
+ *v = b;
+ return 1;
+}
+
+static int request_handler_machine(
+ struct MHD_Connection *connection,
+ void *connection_cls) {
+
+ struct MHD_Response *response;
+ RequestMeta *m = connection_cls;
+ int r;
+ _cleanup_free_ char* hostname = NULL, *os_name = NULL;
+ uint64_t cutoff_from, cutoff_to, usage;
+ char *json;
+ sd_id128_t mid, bid;
+ _cleanup_free_ char *v = NULL;
+
+ assert(connection);
+ assert(m);
+
+ r = open_journal(m);
+ if (r < 0)
+ return respond_error(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to open journal: %s\n", strerror(-r));
+
+ r = sd_id128_get_machine(&mid);
+ if (r < 0)
+ return respond_error(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to determine machine ID: %s\n", strerror(-r));
+
+ r = sd_id128_get_boot(&bid);
+ if (r < 0)
+ return respond_error(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to determine boot ID: %s\n", strerror(-r));
+
+ hostname = gethostname_malloc();
+ if (!hostname)
+ return respond_oom(connection);
+
+ r = sd_journal_get_usage(m->journal, &usage);
+ if (r < 0)
+ return respond_error(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to determine disk usage: %s\n", strerror(-r));
+
+ r = sd_journal_get_cutoff_realtime_usec(m->journal, &cutoff_from, &cutoff_to);
+ if (r < 0)
+ return respond_error(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to determine disk usage: %s\n", strerror(-r));
+
+ parse_env_file("/etc/os-release", NEWLINE, "PRETTY_NAME", &os_name, NULL);
+
+ get_virtualization(&v);
+
+ r = asprintf(&json,
+ "{ \"machine_id\" : \"" SD_ID128_FORMAT_STR "\","
+ "\"boot_id\" : \"" SD_ID128_FORMAT_STR "\","
+ "\"hostname\" : \"%s\","
+ "\"os_pretty_name\" : \"%s\","
+ "\"virtualization\" : \"%s\","
+ "\"usage\" : \"%llu\","
+ "\"cutoff_from_realtime\" : \"%llu\","
+ "\"cutoff_to_realtime\" : \"%llu\" }\n",
+ SD_ID128_FORMAT_VAL(mid),
+ SD_ID128_FORMAT_VAL(bid),
+ hostname_cleanup(hostname, false),
+ os_name ? os_name : "Linux",
+ v ? v : "bare",
+ (unsigned long long) usage,
+ (unsigned long long) cutoff_from,
+ (unsigned long long) cutoff_to);
+
+ if (r < 0)
+ return respond_oom(connection);
+
+ response = MHD_create_response_from_buffer(strlen(json), json, MHD_RESPMEM_MUST_FREE);
+ if (!response) {
+ free(json);
+ return respond_oom(connection);
+ }
+
+ MHD_add_response_header(response, "Content-Type", "application/json");
+ r = MHD_queue_response(connection, MHD_HTTP_OK, response);
+ MHD_destroy_response(response);
+
+ return r;
+}
+
+static int request_handler(
+ void *cls,
+ struct MHD_Connection *connection,
+ const char *url,
+ const char *method,
+ const char *version,
+ const char *upload_data,
+ size_t *upload_data_size,
+ void **connection_cls) {
+
+ assert(connection);
+ assert(connection_cls);
+ assert(url);
+ assert(method);
+
+ if (!streq(method, "GET"))
+ return respond_error(connection, MHD_HTTP_METHOD_NOT_ACCEPTABLE,
+ "Unsupported method.\n");
+
+
+ if (!*connection_cls) {
+ if (!request_meta(connection_cls))
+ return respond_oom(connection);
+ return MHD_YES;
+ }
+
+ if (streq(url, "/"))
+ return request_handler_redirect(connection, "/browse");
+
+ if (streq(url, "/entries"))
+ return request_handler_entries(connection, *connection_cls);
+
+ if (startswith(url, "/fields/"))
+ return request_handler_fields(connection, url + 8, *connection_cls);
+
+ if (streq(url, "/browse"))
+ return request_handler_file(connection, DOCUMENT_ROOT "/browse.html", "text/html");
+
+ if (streq(url, "/machine"))
+ return request_handler_machine(connection, *connection_cls);
+
+ return respond_error(connection, MHD_HTTP_NOT_FOUND, "Not found.\n");
+}
+
+static int help(void) {
+
+ printf("%s [OPTIONS...] ...\n\n"
+ "HTTP server for journal events.\n\n"
+ " -h --help Show this help\n"
+ " --version Show package version\n"
+ " --cert=CERT.PEM Specify server certificate in PEM format\n"
+ " --key=KEY.PEM Specify server key in PEM format\n",
+ program_invocation_short_name);
+
+ return 0;
+}
+
+static char *key_pem = NULL;
+static char *cert_pem = NULL;
+
+static int parse_argv(int argc, char *argv[]) {
+ enum {
+ ARG_VERSION = 0x100,
+ ARG_KEY,
+ ARG_CERT,
+ };
+
+ int r, c;
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "version", no_argument, NULL, ARG_VERSION },
+ { "key", required_argument, NULL, ARG_KEY },
+ { "cert", required_argument, NULL, ARG_CERT },
+ { NULL, 0, NULL, 0 }
+ };
+
+ assert(argc >= 0);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
+ switch(c) {
+ case ARG_VERSION:
+ puts(PACKAGE_STRING);
+ puts(SYSTEMD_FEATURES);
+ return 0;
+
+ case 'h':
+ return help();
+
+ case ARG_KEY:
+ if (key_pem) {
+ log_error("Key file specified twice");
+ return -EINVAL;
+ }
+ r = read_full_file(optarg, &key_pem, NULL);
+ if (r < 0) {
+ log_error("Failed to read key file: %s", strerror(-r));
+ return r;
+ }
+ assert(key_pem);
+ break;
+
+ case ARG_CERT:
+ if (cert_pem) {
+ log_error("Certificate file specified twice");
+ return -EINVAL;
+ }
+ r = read_full_file(optarg, &cert_pem, NULL);
+ if (r < 0) {
+ log_error("Failed to read certificate file: %s", strerror(-r));
+ return r;
+ }
+ assert(cert_pem);
+ break;
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ log_error("Unknown option code %c", c);
+ return -EINVAL;
+ }
+
+ if (optind < argc) {
+ log_error("This program does not take arguments.");
+ return -EINVAL;
+ }
+
+ if (!!key_pem != !!cert_pem) {
+ log_error("Certificate and key files must be specified together");
+ return -EINVAL;
+ }
+
+ return 1;
+}
+
+int main(int argc, char *argv[]) {
+ struct MHD_Daemon *d = NULL;
+ int r, n;
+
+ log_set_target(LOG_TARGET_AUTO);
+ log_parse_environment();
+ log_open();
+
+ r = parse_argv(argc, argv);
+ if (r < 0)
+ return EXIT_FAILURE;
+ if (r == 0)
+ return EXIT_SUCCESS;
+
+ n = sd_listen_fds(1);
+ if (n < 0) {
+ log_error("Failed to determine passed sockets: %s", strerror(-n));
+ goto finish;
+ } else if (n > 1) {
+ log_error("Can't listen on more than one socket.");
+ goto finish;
+ } else {
+ struct MHD_OptionItem opts[] = {
+ { MHD_OPTION_NOTIFY_COMPLETED,
+ (intptr_t) request_meta_free, NULL },
+ { MHD_OPTION_EXTERNAL_LOGGER,
+ (intptr_t) microhttpd_logger, NULL },
+ { MHD_OPTION_END, 0, NULL },
+ { MHD_OPTION_END, 0, NULL },
+ { MHD_OPTION_END, 0, NULL },
+ { MHD_OPTION_END, 0, NULL }};
+ int opts_pos = 2;
+ int flags = MHD_USE_THREAD_PER_CONNECTION|MHD_USE_POLL|MHD_USE_DEBUG;
+
+ if (n > 0)
+ opts[opts_pos++] = (struct MHD_OptionItem)
+ {MHD_OPTION_LISTEN_SOCKET, SD_LISTEN_FDS_START};
+ if (key_pem) {
+ assert(cert_pem);
+ opts[opts_pos++] = (struct MHD_OptionItem)
+ {MHD_OPTION_HTTPS_MEM_KEY, 0, key_pem};
+ opts[opts_pos++] = (struct MHD_OptionItem)
+ {MHD_OPTION_HTTPS_MEM_CERT, 0, cert_pem};
+ flags |= MHD_USE_SSL;
+ }
+
+ d = MHD_start_daemon(flags, 19531,
+ NULL, NULL,
+ request_handler, NULL,
+ MHD_OPTION_ARRAY, opts,
+ MHD_OPTION_END);
+ }
+
+ if (!d) {
+ log_error("Failed to start daemon!");
+ goto finish;
+ }
+
+ pause();
+
+ r = EXIT_SUCCESS;
+
+finish:
+ if (d)
+ MHD_stop_daemon(d);
+
+ return r;
+}
diff --git a/src/journal/journal-internal.h b/src/journal/journal-internal.h
new file mode 100644
index 0000000000..c7e585d810
--- /dev/null
+++ b/src/journal/journal-internal.h
@@ -0,0 +1,141 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/types.h>
+#include <inttypes.h>
+#include <stdbool.h>
+
+#include <systemd/sd-id128.h>
+
+#include "journal-def.h"
+#include "list.h"
+#include "hashmap.h"
+#include "set.h"
+#include "journal-file.h"
+
+typedef struct Match Match;
+typedef struct Location Location;
+typedef struct Directory Directory;
+
+typedef enum MatchType {
+ MATCH_DISCRETE,
+ MATCH_OR_TERM,
+ MATCH_AND_TERM
+} MatchType;
+
+struct Match {
+ MatchType type;
+ Match *parent;
+ LIST_FIELDS(Match, matches);
+
+ /* For concrete matches */
+ char *data;
+ size_t size;
+ le64_t le_hash;
+
+ /* For terms */
+ LIST_HEAD(Match, matches);
+};
+
+typedef enum LocationType {
+ /* The first and last entries, resp. */
+ LOCATION_HEAD,
+ LOCATION_TAIL,
+
+ /* We already read the entry we currently point to, and the
+ * next one to read should probably not be this one again. */
+ LOCATION_DISCRETE,
+
+ /* We should seek to the precise location specified, and
+ * return it, as we haven't read it yet. */
+ LOCATION_SEEK
+} LocationType;
+
+struct Location {
+ LocationType type;
+
+ bool seqnum_set;
+ bool realtime_set;
+ bool monotonic_set;
+ bool xor_hash_set;
+
+ uint64_t seqnum;
+ sd_id128_t seqnum_id;
+
+ uint64_t realtime;
+
+ uint64_t monotonic;
+ sd_id128_t boot_id;
+
+ uint64_t xor_hash;
+};
+
+struct Directory {
+ char *path;
+ int wd;
+ bool is_root;
+};
+
+struct sd_journal {
+ int flags;
+
+ char *path;
+
+ Hashmap *files;
+ MMapCache *mmap;
+
+ Location current_location;
+
+ JournalFile *current_file;
+ uint64_t current_field;
+
+ Hashmap *directories_by_path;
+ Hashmap *directories_by_wd;
+
+ int inotify_fd;
+
+ Match *level0, *level1, *level2;
+
+ unsigned current_invalidate_counter, last_invalidate_counter;
+
+ char *unique_field;
+ JournalFile *unique_file;
+ uint64_t unique_offset;
+
+ bool on_network;
+
+ size_t data_threshold;
+
+ Set *errors;
+
+ usec_t last_process_usec;
+};
+
+char *journal_make_match_string(sd_journal *j);
+void journal_print_header(sd_journal *j);
+
+static inline void journal_closep(sd_journal **j) {
+ sd_journal_close(*j);
+}
+
+#define _cleanup_journal_close_ _cleanup_(journal_closep)
diff --git a/src/journal/journal-qrcode.c b/src/journal/journal-qrcode.c
new file mode 100644
index 0000000000..10a14e4def
--- /dev/null
+++ b/src/journal/journal-qrcode.c
@@ -0,0 +1,138 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <stdio.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <stdbool.h>
+
+#include <qrencode.h>
+
+#include "journal-qrcode.h"
+
+#define WHITE_ON_BLACK "\033[40;37;1m"
+#define NORMAL "\033[0m"
+
+static void print_border(FILE *output, unsigned width) {
+ unsigned x, y;
+
+ /* Four rows of border */
+ for (y = 0; y < 4; y += 2) {
+ fputs(WHITE_ON_BLACK, output);
+
+ for (x = 0; x < 4 + width + 4; x++)
+ fputs("\342\226\210", output);
+
+ fputs(NORMAL "\n", output);
+ }
+}
+
+int print_qr_code(
+ FILE *output,
+ const void *seed,
+ size_t seed_size,
+ uint64_t start,
+ uint64_t interval,
+ const char *hn,
+ sd_id128_t machine) {
+
+ FILE *f;
+ char *url = NULL;
+ size_t url_size = 0, i;
+ QRcode* qr;
+ unsigned x, y;
+
+ assert(seed);
+ assert(seed_size > 0);
+
+ f = open_memstream(&url, &url_size);
+ if (!f)
+ return -ENOMEM;
+
+ fputs("fss://", f);
+
+ for (i = 0; i < seed_size; i++) {
+ if (i > 0 && i % 3 == 0)
+ fputc('-', f);
+ fprintf(f, "%02x", ((uint8_t*) seed)[i]);
+ }
+
+ fprintf(f, "/%llx-%llx?machine=" SD_ID128_FORMAT_STR,
+ (unsigned long long) start,
+ (unsigned long long) interval,
+ SD_ID128_FORMAT_VAL(machine));
+
+ if (hn)
+ fprintf(f, ";hostname=%s", hn);
+
+ if (ferror(f)) {
+ fclose(f);
+ free(url);
+ return -ENOMEM;
+ }
+
+ fclose(f);
+
+ qr = QRcode_encodeString(url, 0, QR_ECLEVEL_L, QR_MODE_8, 1);
+ free(url);
+
+ if (!qr)
+ return -ENOMEM;
+
+ print_border(output, qr->width);
+
+ for (y = 0; y < (unsigned) qr->width; y += 2) {
+ const uint8_t *row1, *row2;
+
+ row1 = qr->data + qr->width * y;
+ row2 = row1 + qr->width;
+
+ fputs(WHITE_ON_BLACK, output);
+ for (x = 0; x < 4; x++)
+ fputs("\342\226\210", output);
+
+ for (x = 0; x < (unsigned) qr->width; x ++) {
+ bool a, b;
+
+ a = row1[x] & 1;
+ b = (y+1) < (unsigned) qr->width ? (row2[x] & 1) : false;
+
+ if (a && b)
+ fputc(' ', output);
+ else if (a)
+ fputs("\342\226\204", output);
+ else if (b)
+ fputs("\342\226\200", output);
+ else
+ fputs("\342\226\210", output);
+ }
+
+ for (x = 0; x < 4; x++)
+ fputs("\342\226\210", output);
+ fputs(NORMAL "\n", output);
+ }
+
+ print_border(output, qr->width);
+
+ QRcode_free(qr);
+ return 0;
+}
diff --git a/src/journal/journal-qrcode.h b/src/journal/journal-qrcode.h
new file mode 100644
index 0000000000..da6244c160
--- /dev/null
+++ b/src/journal/journal-qrcode.h
@@ -0,0 +1,30 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <inttypes.h>
+#include <sys/types.h>
+#include <stdio.h>
+
+#include <systemd/sd-id128.h>
+
+int print_qr_code(FILE *f, const void *seed, size_t seed_size, uint64_t start, uint64_t interval, const char *hn, sd_id128_t machine);
diff --git a/src/journal/journal-send.c b/src/journal/journal-send.c
new file mode 100644
index 0000000000..14c437da78
--- /dev/null
+++ b/src/journal/journal-send.c
@@ -0,0 +1,586 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <errno.h>
+#include <stddef.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <printf.h>
+
+#define SD_JOURNAL_SUPPRESS_LOCATION
+
+#include "sd-journal.h"
+#include "util.h"
+#include "socket-util.h"
+
+#define SNDBUF_SIZE (8*1024*1024)
+
+#define ALLOCA_CODE_FUNC(f, func) \
+ do { \
+ size_t _fl; \
+ const char *_func = (func); \
+ char **_f = &(f); \
+ _fl = strlen(_func) + 1; \
+ *_f = alloca(_fl + 10); \
+ memcpy(*_f, "CODE_FUNC=", 10); \
+ memcpy(*_f + 10, _func, _fl); \
+ } while(false)
+
+/* We open a single fd, and we'll share it with the current process,
+ * all its threads, and all its subprocesses. This means we need to
+ * initialize it atomically, and need to operate on it atomically
+ * never assuming we are the only user */
+
+static int journal_fd(void) {
+ int fd;
+ static int fd_plus_one = 0;
+
+retry:
+ if (fd_plus_one > 0)
+ return fd_plus_one - 1;
+
+ fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
+ if (fd < 0)
+ return -errno;
+
+ fd_inc_sndbuf(fd, SNDBUF_SIZE);
+
+ if (!__sync_bool_compare_and_swap(&fd_plus_one, 0, fd+1)) {
+ close_nointr_nofail(fd);
+ goto retry;
+ }
+
+ return fd;
+}
+
+_public_ int sd_journal_print(int priority, const char *format, ...) {
+ int r;
+ va_list ap;
+
+ va_start(ap, format);
+ r = sd_journal_printv(priority, format, ap);
+ va_end(ap);
+
+ return r;
+}
+
+_public_ int sd_journal_printv(int priority, const char *format, va_list ap) {
+
+ /* FIXME: Instead of limiting things to LINE_MAX we could do a
+ C99 variable-length array on the stack here in a loop. */
+
+ char buffer[8 + LINE_MAX], p[11]; struct iovec iov[2];
+
+ if (priority < 0 || priority > 7)
+ return -EINVAL;
+
+ if (!format)
+ return -EINVAL;
+
+ snprintf(p, sizeof(p), "PRIORITY=%i", priority & LOG_PRIMASK);
+ char_array_0(p);
+
+ memcpy(buffer, "MESSAGE=", 8);
+ vsnprintf(buffer+8, sizeof(buffer) - 8, format, ap);
+ char_array_0(buffer);
+
+ zero(iov);
+ IOVEC_SET_STRING(iov[0], buffer);
+ IOVEC_SET_STRING(iov[1], p);
+
+ return sd_journal_sendv(iov, 2);
+}
+
+_printf_attr_(1, 0) static int fill_iovec_sprintf(const char *format, va_list ap, int extra, struct iovec **_iov) {
+ PROTECT_ERRNO;
+ int r, n = 0, i = 0, j;
+ struct iovec *iov = NULL;
+
+ assert(_iov);
+
+ if (extra > 0) {
+ n = MAX(extra * 2, extra + 4);
+ iov = malloc0(n * sizeof(struct iovec));
+ if (!iov) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ i = extra;
+ }
+
+ while (format) {
+ struct iovec *c;
+ char *buffer;
+ va_list aq;
+
+ if (i >= n) {
+ n = MAX(i*2, 4);
+ c = realloc(iov, n * sizeof(struct iovec));
+ if (!c) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ iov = c;
+ }
+
+ va_copy(aq, ap);
+ if (vasprintf(&buffer, format, aq) < 0) {
+ va_end(aq);
+ r = -ENOMEM;
+ goto fail;
+ }
+ va_end(aq);
+
+ VA_FORMAT_ADVANCE(format, ap);
+
+ IOVEC_SET_STRING(iov[i++], buffer);
+
+ format = va_arg(ap, char *);
+ }
+
+ *_iov = iov;
+
+ return i;
+
+fail:
+ for (j = 0; j < i; j++)
+ free(iov[j].iov_base);
+
+ free(iov);
+
+ return r;
+}
+
+_public_ int sd_journal_send(const char *format, ...) {
+ int r, i, j;
+ va_list ap;
+ struct iovec *iov = NULL;
+
+ va_start(ap, format);
+ i = fill_iovec_sprintf(format, ap, 0, &iov);
+ va_end(ap);
+
+ if (_unlikely_(i < 0)) {
+ r = i;
+ goto finish;
+ }
+
+ r = sd_journal_sendv(iov, i);
+
+finish:
+ for (j = 0; j < i; j++)
+ free(iov[j].iov_base);
+
+ free(iov);
+
+ return r;
+}
+
+_public_ int sd_journal_sendv(const struct iovec *iov, int n) {
+ PROTECT_ERRNO;
+ int fd, buffer_fd;
+ struct iovec *w;
+ uint64_t *l;
+ int i, j = 0;
+ struct msghdr mh;
+ struct sockaddr_un sa;
+ ssize_t k;
+ union {
+ struct cmsghdr cmsghdr;
+ uint8_t buf[CMSG_SPACE(sizeof(int))];
+ } control;
+ struct cmsghdr *cmsg;
+ /* We use /dev/shm instead of /tmp here, since we want this to
+ * be a tmpfs, and one that is available from early boot on
+ * and where unprivileged users can create files. */
+ char path[] = "/dev/shm/journal.XXXXXX";
+ bool have_syslog_identifier = false;
+
+ if (_unlikely_(!iov))
+ return -EINVAL;
+
+ if (_unlikely_(n <= 0))
+ return -EINVAL;
+
+ w = alloca(sizeof(struct iovec) * n * 5 + 3);
+ l = alloca(sizeof(uint64_t) * n);
+
+ for (i = 0; i < n; i++) {
+ char *c, *nl;
+
+ if (_unlikely_(!iov[i].iov_base || iov[i].iov_len <= 1))
+ return -EINVAL;
+
+ c = memchr(iov[i].iov_base, '=', iov[i].iov_len);
+ if (_unlikely_(!c || c == iov[i].iov_base))
+ return -EINVAL;
+
+ have_syslog_identifier = have_syslog_identifier ||
+ (c == (char *) iov[i].iov_base + 17 &&
+ memcmp(iov[i].iov_base, "SYSLOG_IDENTIFIER", 17) == 0);
+
+ nl = memchr(iov[i].iov_base, '\n', iov[i].iov_len);
+ if (nl) {
+ if (_unlikely_(nl < c))
+ return -EINVAL;
+
+ /* Already includes a newline? Bummer, then
+ * let's write the variable name, then a
+ * newline, then the size (64bit LE), followed
+ * by the data and a final newline */
+
+ w[j].iov_base = iov[i].iov_base;
+ w[j].iov_len = c - (char*) iov[i].iov_base;
+ j++;
+
+ IOVEC_SET_STRING(w[j++], "\n");
+
+ l[i] = htole64(iov[i].iov_len - (c - (char*) iov[i].iov_base) - 1);
+ w[j].iov_base = &l[i];
+ w[j].iov_len = sizeof(uint64_t);
+ j++;
+
+ w[j].iov_base = c + 1;
+ w[j].iov_len = iov[i].iov_len - (c - (char*) iov[i].iov_base) - 1;
+ j++;
+
+ } else
+ /* Nothing special? Then just add the line and
+ * append a newline */
+ w[j++] = iov[i];
+
+ IOVEC_SET_STRING(w[j++], "\n");
+ }
+
+ if (!have_syslog_identifier &&
+ string_is_safe(program_invocation_short_name)) {
+
+ /* Implicitly add program_invocation_short_name, if it
+ * is not set explicitly. We only do this for
+ * program_invocation_short_name, and nothing else
+ * since everything else is much nicer to retrieve
+ * from the outside. */
+
+ IOVEC_SET_STRING(w[j++], "SYSLOG_IDENTIFIER=");
+ IOVEC_SET_STRING(w[j++], program_invocation_short_name);
+ IOVEC_SET_STRING(w[j++], "\n");
+ }
+
+ fd = journal_fd();
+ if (_unlikely_(fd < 0))
+ return fd;
+
+ zero(sa);
+ sa.sun_family = AF_UNIX;
+ strncpy(sa.sun_path, "/run/systemd/journal/socket", sizeof(sa.sun_path));
+
+ zero(mh);
+ mh.msg_name = &sa;
+ mh.msg_namelen = offsetof(struct sockaddr_un, sun_path) + strlen(sa.sun_path);
+ mh.msg_iov = w;
+ mh.msg_iovlen = j;
+
+ k = sendmsg(fd, &mh, MSG_NOSIGNAL);
+ if (k >= 0)
+ return 0;
+
+ if (errno != EMSGSIZE && errno != ENOBUFS)
+ return -errno;
+
+ /* Message doesn't fit... Let's dump the data in a temporary
+ * file and just pass a file descriptor of it to the other
+ * side */
+
+ buffer_fd = mkostemp(path, O_CLOEXEC|O_RDWR);
+ if (buffer_fd < 0)
+ return -errno;
+
+ if (unlink(path) < 0) {
+ close_nointr_nofail(buffer_fd);
+ return -errno;
+ }
+
+ n = writev(buffer_fd, w, j);
+ if (n < 0) {
+ close_nointr_nofail(buffer_fd);
+ return -errno;
+ }
+
+ mh.msg_iov = NULL;
+ mh.msg_iovlen = 0;
+
+ zero(control);
+ mh.msg_control = &control;
+ mh.msg_controllen = sizeof(control);
+
+ cmsg = CMSG_FIRSTHDR(&mh);
+ cmsg->cmsg_level = SOL_SOCKET;
+ cmsg->cmsg_type = SCM_RIGHTS;
+ cmsg->cmsg_len = CMSG_LEN(sizeof(int));
+ memcpy(CMSG_DATA(cmsg), &buffer_fd, sizeof(int));
+
+ mh.msg_controllen = cmsg->cmsg_len;
+
+ k = sendmsg(fd, &mh, MSG_NOSIGNAL);
+ close_nointr_nofail(buffer_fd);
+
+ if (k < 0)
+ return -errno;
+
+ return 0;
+}
+
+static int fill_iovec_perror_and_send(const char *message, int skip, struct iovec iov[]) {
+ PROTECT_ERRNO;
+ size_t n, k;
+
+ k = isempty(message) ? 0 : strlen(message) + 2;
+ n = 8 + k + 256 + 1;
+
+ for (;;) {
+ char buffer[n];
+ char* j;
+
+ errno = 0;
+ j = strerror_r(_saved_errno_, buffer + 8 + k, n - 8 - k);
+ if (errno == 0) {
+ char error[6 + 10 + 1]; /* for a 32bit value */
+
+ if (j != buffer + 8 + k)
+ memmove(buffer + 8 + k, j, strlen(j)+1);
+
+ memcpy(buffer, "MESSAGE=", 8);
+
+ if (k > 0) {
+ memcpy(buffer + 8, message, k - 2);
+ memcpy(buffer + 8 + k - 2, ": ", 2);
+ }
+
+ snprintf(error, sizeof(error), "ERRNO=%u", _saved_errno_);
+ char_array_0(error);
+
+ IOVEC_SET_STRING(iov[skip+0], "PRIORITY=3");
+ IOVEC_SET_STRING(iov[skip+1], buffer);
+ IOVEC_SET_STRING(iov[skip+2], error);
+
+ return sd_journal_sendv(iov, skip + 3);
+ }
+
+ if (errno != ERANGE)
+ return -errno;
+
+ n *= 2;
+ }
+}
+
+_public_ int sd_journal_perror(const char *message) {
+ struct iovec iovec[3];
+
+ return fill_iovec_perror_and_send(message, 0, iovec);
+}
+
+_public_ int sd_journal_stream_fd(const char *identifier, int priority, int level_prefix) {
+ union sockaddr_union sa;
+ int fd;
+ char *header;
+ size_t l;
+ ssize_t r;
+
+ if (priority < 0 || priority > 7)
+ return -EINVAL;
+
+ fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0);
+ if (fd < 0)
+ return -errno;
+
+ zero(sa);
+ sa.un.sun_family = AF_UNIX;
+ strncpy(sa.un.sun_path, "/run/systemd/journal/stdout", sizeof(sa.un.sun_path));
+
+ r = connect(fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
+ if (r < 0) {
+ close_nointr_nofail(fd);
+ return -errno;
+ }
+
+ if (shutdown(fd, SHUT_RD) < 0) {
+ close_nointr_nofail(fd);
+ return -errno;
+ }
+
+ fd_inc_sndbuf(fd, SNDBUF_SIZE);
+
+ if (!identifier)
+ identifier = "";
+
+ l = strlen(identifier);
+ header = alloca(l + 1 + 1 + 2 + 2 + 2 + 2 + 2);
+
+ memcpy(header, identifier, l);
+ header[l++] = '\n';
+ header[l++] = '\n'; /* unit id */
+ header[l++] = '0' + priority;
+ header[l++] = '\n';
+ header[l++] = '0' + !!level_prefix;
+ header[l++] = '\n';
+ header[l++] = '0';
+ header[l++] = '\n';
+ header[l++] = '0';
+ header[l++] = '\n';
+ header[l++] = '0';
+ header[l++] = '\n';
+
+ r = loop_write(fd, header, l, false);
+ if (r < 0) {
+ close_nointr_nofail(fd);
+ return (int) r;
+ }
+
+ if ((size_t) r != l) {
+ close_nointr_nofail(fd);
+ return -errno;
+ }
+
+ return fd;
+}
+
+_public_ int sd_journal_print_with_location(int priority, const char *file, const char *line, const char *func, const char *format, ...) {
+ int r;
+ va_list ap;
+
+ va_start(ap, format);
+ r = sd_journal_printv_with_location(priority, file, line, func, format, ap);
+ va_end(ap);
+
+ return r;
+}
+
+_public_ int sd_journal_printv_with_location(int priority, const char *file, const char *line, const char *func, const char *format, va_list ap) {
+ char buffer[8 + LINE_MAX], p[11];
+ struct iovec iov[5];
+ char *f;
+
+ if (priority < 0 || priority > 7)
+ return -EINVAL;
+
+ if (_unlikely_(!format))
+ return -EINVAL;
+
+ snprintf(p, sizeof(p), "PRIORITY=%i", priority & LOG_PRIMASK);
+ char_array_0(p);
+
+ memcpy(buffer, "MESSAGE=", 8);
+ vsnprintf(buffer+8, sizeof(buffer) - 8, format, ap);
+ char_array_0(buffer);
+
+ /* func is initialized from __func__ which is not a macro, but
+ * a static const char[], hence cannot easily be prefixed with
+ * CODE_FUNC=, hence let's do it manually here. */
+ ALLOCA_CODE_FUNC(f, func);
+
+ zero(iov);
+ IOVEC_SET_STRING(iov[0], buffer);
+ IOVEC_SET_STRING(iov[1], p);
+ IOVEC_SET_STRING(iov[2], file);
+ IOVEC_SET_STRING(iov[3], line);
+ IOVEC_SET_STRING(iov[4], f);
+
+ return sd_journal_sendv(iov, ELEMENTSOF(iov));
+}
+
+_public_ int sd_journal_send_with_location(const char *file, const char *line, const char *func, const char *format, ...) {
+ int r, i, j;
+ va_list ap;
+ struct iovec *iov = NULL;
+ char *f;
+
+ va_start(ap, format);
+ i = fill_iovec_sprintf(format, ap, 3, &iov);
+ va_end(ap);
+
+ if (_unlikely_(i < 0)) {
+ r = i;
+ goto finish;
+ }
+
+ ALLOCA_CODE_FUNC(f, func);
+
+ IOVEC_SET_STRING(iov[0], file);
+ IOVEC_SET_STRING(iov[1], line);
+ IOVEC_SET_STRING(iov[2], f);
+
+ r = sd_journal_sendv(iov, i);
+
+finish:
+ for (j = 3; j < i; j++)
+ free(iov[j].iov_base);
+
+ free(iov);
+
+ return r;
+}
+
+_public_ int sd_journal_sendv_with_location(
+ const char *file, const char *line,
+ const char *func,
+ const struct iovec *iov, int n) {
+
+ struct iovec *niov;
+ char *f;
+
+ if (_unlikely_(!iov))
+ return -EINVAL;
+
+ if (_unlikely_(n <= 0))
+ return -EINVAL;
+
+ niov = alloca(sizeof(struct iovec) * (n + 3));
+ memcpy(niov, iov, sizeof(struct iovec) * n);
+
+ ALLOCA_CODE_FUNC(f, func);
+
+ IOVEC_SET_STRING(niov[n++], file);
+ IOVEC_SET_STRING(niov[n++], line);
+ IOVEC_SET_STRING(niov[n++], f);
+
+ return sd_journal_sendv(niov, n);
+}
+
+_public_ int sd_journal_perror_with_location(
+ const char *file, const char *line,
+ const char *func,
+ const char *message) {
+
+ struct iovec iov[6];
+ char *f;
+
+ ALLOCA_CODE_FUNC(f, func);
+
+ IOVEC_SET_STRING(iov[0], file);
+ IOVEC_SET_STRING(iov[1], line);
+ IOVEC_SET_STRING(iov[2], f);
+
+ return fill_iovec_perror_and_send(message, 3, iov);
+}
diff --git a/src/journal/journal-vacuum.c b/src/journal/journal-vacuum.c
new file mode 100644
index 0000000000..4a3a5a9e63
--- /dev/null
+++ b/src/journal/journal-vacuum.c
@@ -0,0 +1,318 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/types.h>
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <sys/statvfs.h>
+#include <unistd.h>
+
+#ifdef HAVE_XATTR
+#include <attr/xattr.h>
+#endif
+
+#include "journal-def.h"
+#include "journal-file.h"
+#include "journal-vacuum.h"
+#include "sd-id128.h"
+#include "util.h"
+
+struct vacuum_info {
+ uint64_t usage;
+ char *filename;
+
+ uint64_t realtime;
+ sd_id128_t seqnum_id;
+ uint64_t seqnum;
+
+ bool have_seqnum;
+};
+
+static int vacuum_compare(const void *_a, const void *_b) {
+ const struct vacuum_info *a, *b;
+
+ a = _a;
+ b = _b;
+
+ if (a->have_seqnum && b->have_seqnum &&
+ sd_id128_equal(a->seqnum_id, b->seqnum_id)) {
+ if (a->seqnum < b->seqnum)
+ return -1;
+ else if (a->seqnum > b->seqnum)
+ return 1;
+ else
+ return 0;
+ }
+
+ if (a->realtime < b->realtime)
+ return -1;
+ else if (a->realtime > b->realtime)
+ return 1;
+ else if (a->have_seqnum && b->have_seqnum)
+ return memcmp(&a->seqnum_id, &b->seqnum_id, 16);
+ else
+ return strcmp(a->filename, b->filename);
+}
+
+static void patch_realtime(
+ const char *dir,
+ const char *fn,
+ const struct stat *st,
+ unsigned long long *realtime) {
+
+ usec_t x;
+
+#ifdef HAVE_XATTR
+ uint64_t crtime;
+ _cleanup_free_ const char *path = NULL;
+#endif
+
+ /* The timestamp was determined by the file name, but let's
+ * see if the file might actually be older than the file name
+ * suggested... */
+
+ assert(dir);
+ assert(fn);
+ assert(st);
+ assert(realtime);
+
+ x = timespec_load(&st->st_ctim);
+ if (x > 0 && x != (usec_t) -1 && x < *realtime)
+ *realtime = x;
+
+ x = timespec_load(&st->st_atim);
+ if (x > 0 && x != (usec_t) -1 && x < *realtime)
+ *realtime = x;
+
+ x = timespec_load(&st->st_mtim);
+ if (x > 0 && x != (usec_t) -1 && x < *realtime)
+ *realtime = x;
+
+#ifdef HAVE_XATTR
+ /* Let's read the original creation time, if possible. Ideally
+ * we'd just query the creation time the FS might provide, but
+ * unfortunately there's currently no sane API to query
+ * it. Hence let's implement this manually... */
+
+ /* Unfortunately there is is not fgetxattrat(), so we need to
+ * go via path here. :-( */
+
+ path = strjoin(dir, "/", fn, NULL);
+ if (!path)
+ return;
+
+ if (getxattr(path, "user.crtime_usec", &crtime, sizeof(crtime)) == sizeof(crtime)) {
+ crtime = le64toh(crtime);
+
+ if (crtime > 0 && crtime != (uint64_t) -1 && crtime < *realtime)
+ *realtime = crtime;
+ }
+#endif
+}
+
+int journal_directory_vacuum(
+ const char *directory,
+ uint64_t max_use,
+ uint64_t min_free,
+ usec_t max_retention_usec,
+ usec_t *oldest_usec) {
+
+ DIR *d;
+ int r = 0;
+ struct vacuum_info *list = NULL;
+ unsigned n_list = 0, n_allocated = 0, i;
+ uint64_t sum = 0;
+ usec_t retention_limit = 0;
+
+ assert(directory);
+
+ if (max_use <= 0 && min_free <= 0 && max_retention_usec <= 0)
+ return 0;
+
+ if (max_retention_usec > 0) {
+ retention_limit = now(CLOCK_REALTIME);
+ if (retention_limit > max_retention_usec)
+ retention_limit -= max_retention_usec;
+ else
+ max_retention_usec = retention_limit = 0;
+ }
+
+ d = opendir(directory);
+ if (!d)
+ return -errno;
+
+ for (;;) {
+ int k;
+ struct dirent *de;
+ union dirent_storage buf;
+ size_t q;
+ struct stat st;
+ char *p;
+ unsigned long long seqnum = 0, realtime;
+ sd_id128_t seqnum_id;
+ bool have_seqnum;
+
+ k = readdir_r(d, &buf.de, &de);
+ if (k != 0) {
+ r = -k;
+ goto finish;
+ }
+
+ if (!de)
+ break;
+
+ if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
+ continue;
+
+ if (!S_ISREG(st.st_mode))
+ continue;
+
+ q = strlen(de->d_name);
+
+ if (endswith(de->d_name, ".journal")) {
+
+ /* Vacuum archived files */
+
+ if (q < 1 + 32 + 1 + 16 + 1 + 16 + 8)
+ continue;
+
+ if (de->d_name[q-8-16-1] != '-' ||
+ de->d_name[q-8-16-1-16-1] != '-' ||
+ de->d_name[q-8-16-1-16-1-32-1] != '@')
+ continue;
+
+ p = strdup(de->d_name);
+ if (!p) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ de->d_name[q-8-16-1-16-1] = 0;
+ if (sd_id128_from_string(de->d_name + q-8-16-1-16-1-32, &seqnum_id) < 0) {
+ free(p);
+ continue;
+ }
+
+ if (sscanf(de->d_name + q-8-16-1-16, "%16llx-%16llx.journal", &seqnum, &realtime) != 2) {
+ free(p);
+ continue;
+ }
+
+ have_seqnum = true;
+
+ } else if (endswith(de->d_name, ".journal~")) {
+ unsigned long long tmp;
+
+ /* Vacuum corrupted files */
+
+ if (q < 1 + 16 + 1 + 16 + 8 + 1)
+ continue;
+
+ if (de->d_name[q-1-8-16-1] != '-' ||
+ de->d_name[q-1-8-16-1-16-1] != '@')
+ continue;
+
+ p = strdup(de->d_name);
+ if (!p) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ if (sscanf(de->d_name + q-1-8-16-1-16, "%16llx-%16llx.journal~", &realtime, &tmp) != 2) {
+ free(p);
+ continue;
+ }
+
+ have_seqnum = false;
+ } else
+ /* We do not vacuum active files or unknown files! */
+ continue;
+
+ patch_realtime(directory, de->d_name, &st, &realtime);
+
+ if (n_list >= n_allocated) {
+ struct vacuum_info *j;
+
+ n_allocated = MAX(n_allocated * 2U, 8U);
+ j = realloc(list, n_allocated * sizeof(struct vacuum_info));
+ if (!j) {
+ free(p);
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ list = j;
+ }
+
+ list[n_list].filename = p;
+ list[n_list].usage = 512UL * (uint64_t) st.st_blocks;
+ list[n_list].seqnum = seqnum;
+ list[n_list].realtime = realtime;
+ list[n_list].seqnum_id = seqnum_id;
+ list[n_list].have_seqnum = have_seqnum;
+
+ sum += list[n_list].usage;
+
+ n_list ++;
+ }
+
+ if (n_list > 0)
+ qsort(list, n_list, sizeof(struct vacuum_info), vacuum_compare);
+
+ for (i = 0; i < n_list; i++) {
+ struct statvfs ss;
+
+ if (fstatvfs(dirfd(d), &ss) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ if ((max_retention_usec <= 0 || list[i].realtime >= retention_limit) &&
+ (max_use <= 0 || sum <= max_use) &&
+ (min_free <= 0 || (uint64_t) ss.f_bavail * (uint64_t) ss.f_bsize >= min_free))
+ break;
+
+ if (unlinkat(dirfd(d), list[i].filename, 0) >= 0) {
+ log_debug("Deleted archived journal %s/%s.", directory, list[i].filename);
+
+ if (list[i].usage < sum)
+ sum -= list[i].usage;
+ else
+ sum = 0;
+
+ } else if (errno != ENOENT)
+ log_warning("Failed to delete %s/%s: %m", directory, list[i].filename);
+ }
+
+ if (oldest_usec && i < n_list && (*oldest_usec == 0 || list[i].realtime < *oldest_usec))
+ *oldest_usec = list[i].realtime;
+
+finish:
+ for (i = 0; i < n_list; i++)
+ free(list[i].filename);
+
+ free(list);
+
+ if (d)
+ closedir(d);
+
+ return r;
+}
diff --git a/src/journal/journal-vacuum.h b/src/journal/journal-vacuum.h
new file mode 100644
index 0000000000..f5e3e5291f
--- /dev/null
+++ b/src/journal/journal-vacuum.h
@@ -0,0 +1,26 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <inttypes.h>
+
+int journal_directory_vacuum(const char *directory, uint64_t max_use, uint64_t min_free, usec_t max_retention_usec, usec_t *oldest_usec);
diff --git a/src/journal/journal-verify.c b/src/journal/journal-verify.c
new file mode 100644
index 0000000000..ed28b45737
--- /dev/null
+++ b/src/journal/journal-verify.c
@@ -0,0 +1,1163 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <unistd.h>
+#include <sys/mman.h>
+#include <fcntl.h>
+#include <stddef.h>
+
+#include "util.h"
+#include "macro.h"
+#include "journal-def.h"
+#include "journal-file.h"
+#include "journal-authenticate.h"
+#include "journal-verify.h"
+#include "lookup3.h"
+#include "compress.h"
+#include "fsprg.h"
+
+static int journal_file_object_verify(JournalFile *f, Object *o) {
+ uint64_t i;
+
+ assert(f);
+ assert(o);
+
+ /* This does various superficial tests about the length an
+ * possible field values. It does not follow any references to
+ * other objects. */
+
+ if ((o->object.flags & OBJECT_COMPRESSED) &&
+ o->object.type != OBJECT_DATA)
+ return -EBADMSG;
+
+ switch (o->object.type) {
+
+ case OBJECT_DATA: {
+ uint64_t h1, h2;
+
+ if (le64toh(o->data.entry_offset) <= 0 ||
+ le64toh(o->data.n_entries) <= 0)
+ return -EBADMSG;
+
+ if (le64toh(o->object.size) - offsetof(DataObject, payload) <= 0)
+ return -EBADMSG;
+
+ h1 = le64toh(o->data.hash);
+
+ if (o->object.flags & OBJECT_COMPRESSED) {
+#ifdef HAVE_XZ
+ void *b = NULL;
+ uint64_t alloc = 0, b_size;
+
+ if (!uncompress_blob(o->data.payload,
+ le64toh(o->object.size) - offsetof(Object, data.payload),
+ &b, &alloc, &b_size, 0))
+ return -EBADMSG;
+
+ h2 = hash64(b, b_size);
+ free(b);
+#else
+ return -EPROTONOSUPPORT;
+#endif
+ } else
+ h2 = hash64(o->data.payload, le64toh(o->object.size) - offsetof(Object, data.payload));
+
+ if (h1 != h2)
+ return -EBADMSG;
+
+ if (!VALID64(o->data.next_hash_offset) ||
+ !VALID64(o->data.next_field_offset) ||
+ !VALID64(o->data.entry_offset) ||
+ !VALID64(o->data.entry_array_offset))
+ return -EBADMSG;
+
+ break;
+ }
+
+ case OBJECT_FIELD:
+ if (le64toh(o->object.size) - offsetof(FieldObject, payload) <= 0)
+ return -EBADMSG;
+
+ if (!VALID64(o->field.next_hash_offset) ||
+ !VALID64(o->field.head_data_offset))
+ return -EBADMSG;
+ break;
+
+ case OBJECT_ENTRY:
+ if ((le64toh(o->object.size) - offsetof(EntryObject, items)) % sizeof(EntryItem) != 0)
+ return -EBADMSG;
+
+ if ((le64toh(o->object.size) - offsetof(EntryObject, items)) / sizeof(EntryItem) <= 0)
+ return -EBADMSG;
+
+ if (le64toh(o->entry.seqnum) <= 0 ||
+ !VALID_REALTIME(le64toh(o->entry.realtime)) ||
+ !VALID_MONOTONIC(le64toh(o->entry.monotonic)))
+ return -EBADMSG;
+
+ for (i = 0; i < journal_file_entry_n_items(o); i++) {
+ if (o->entry.items[i].object_offset == 0 ||
+ !VALID64(o->entry.items[i].object_offset))
+ return -EBADMSG;
+ }
+
+ break;
+
+ case OBJECT_DATA_HASH_TABLE:
+ case OBJECT_FIELD_HASH_TABLE:
+ if ((le64toh(o->object.size) - offsetof(HashTableObject, items)) % sizeof(HashItem) != 0)
+ return -EBADMSG;
+
+ if ((le64toh(o->object.size) - offsetof(HashTableObject, items)) / sizeof(HashItem) <= 0)
+ return -EBADMSG;
+
+ for (i = 0; i < journal_file_hash_table_n_items(o); i++) {
+ if (o->hash_table.items[i].head_hash_offset != 0 &&
+ !VALID64(le64toh(o->hash_table.items[i].head_hash_offset)))
+ return -EBADMSG;
+ if (o->hash_table.items[i].tail_hash_offset != 0 &&
+ !VALID64(le64toh(o->hash_table.items[i].tail_hash_offset)))
+ return -EBADMSG;
+
+ if ((o->hash_table.items[i].head_hash_offset != 0) !=
+ (o->hash_table.items[i].tail_hash_offset != 0))
+ return -EBADMSG;
+ }
+
+ break;
+
+ case OBJECT_ENTRY_ARRAY:
+ if ((le64toh(o->object.size) - offsetof(EntryArrayObject, items)) % sizeof(le64_t) != 0)
+ return -EBADMSG;
+
+ if ((le64toh(o->object.size) - offsetof(EntryArrayObject, items)) / sizeof(le64_t) <= 0)
+ return -EBADMSG;
+
+ if (!VALID64(o->entry_array.next_entry_array_offset))
+ return -EBADMSG;
+
+ for (i = 0; i < journal_file_entry_array_n_items(o); i++)
+ if (o->entry_array.items[i] != 0 &&
+ !VALID64(o->entry_array.items[i]))
+ return -EBADMSG;
+
+ break;
+
+ case OBJECT_TAG:
+ if (le64toh(o->object.size) != sizeof(TagObject))
+ return -EBADMSG;
+
+ if (!VALID_EPOCH(o->tag.epoch))
+ return -EBADMSG;
+
+ break;
+ }
+
+ return 0;
+}
+
+static void draw_progress(uint64_t p, usec_t *last_usec) {
+ unsigned n, i, j, k;
+ usec_t z, x;
+
+ if (!on_tty())
+ return;
+
+ z = now(CLOCK_MONOTONIC);
+ x = *last_usec;
+
+ if (x != 0 && x + 40 * USEC_PER_MSEC > z)
+ return;
+
+ *last_usec = z;
+
+ n = (3 * columns()) / 4;
+ j = (n * (unsigned) p) / 65535ULL;
+ k = n - j;
+
+ fputs("\r\x1B[?25l" ANSI_HIGHLIGHT_GREEN_ON, stdout);
+
+ for (i = 0; i < j; i++)
+ fputs("\xe2\x96\x88", stdout);
+
+ fputs(ANSI_HIGHLIGHT_OFF, stdout);
+
+ for (i = 0; i < k; i++)
+ fputs("\xe2\x96\x91", stdout);
+
+ printf(" %3lu%%", 100LU * (unsigned long) p / 65535LU);
+
+ fputs("\r\x1B[?25h", stdout);
+ fflush(stdout);
+}
+
+static void flush_progress(void) {
+ unsigned n, i;
+
+ if (!on_tty())
+ return;
+
+ n = (3 * columns()) / 4;
+
+ putchar('\r');
+
+ for (i = 0; i < n + 5; i++)
+ putchar(' ');
+
+ putchar('\r');
+ fflush(stdout);
+}
+
+static int write_uint64(int fd, uint64_t p) {
+ ssize_t k;
+
+ k = write(fd, &p, sizeof(p));
+ if (k < 0)
+ return -errno;
+ if (k != sizeof(p))
+ return -EIO;
+
+ return 0;
+}
+
+static int contains_uint64(MMapCache *m, int fd, uint64_t n, uint64_t p) {
+ uint64_t a, b;
+ int r;
+
+ assert(m);
+ assert(fd >= 0);
+
+ /* Bisection ... */
+
+ a = 0; b = n;
+ while (a < b) {
+ uint64_t c, *z;
+
+ c = (a + b) / 2;
+
+ r = mmap_cache_get(m, fd, PROT_READ|PROT_WRITE, 0, false, c * sizeof(uint64_t), sizeof(uint64_t), NULL, (void **) &z);
+ if (r < 0)
+ return r;
+
+ if (*z == p)
+ return 1;
+
+ if (a + 1 >= b)
+ return 0;
+
+ if (p < *z)
+ b = c;
+ else
+ a = c;
+ }
+
+ return 0;
+}
+
+static int entry_points_to_data(
+ JournalFile *f,
+ int entry_fd,
+ uint64_t n_entries,
+ uint64_t entry_p,
+ uint64_t data_p) {
+
+ int r;
+ uint64_t i, n, a;
+ Object *o;
+ bool found = false;
+
+ assert(f);
+ assert(entry_fd >= 0);
+
+ if (!contains_uint64(f->mmap, entry_fd, n_entries, entry_p)) {
+ log_error("Data object references invalid entry at %llu", (unsigned long long) data_p);
+ return -EBADMSG;
+ }
+
+ r = journal_file_move_to_object(f, OBJECT_ENTRY, entry_p, &o);
+ if (r < 0)
+ return r;
+
+ n = journal_file_entry_n_items(o);
+ for (i = 0; i < n; i++)
+ if (le64toh(o->entry.items[i].object_offset) == data_p) {
+ found = true;
+ break;
+ }
+
+ if (!found) {
+ log_error("Data object not referenced by linked entry at %llu", (unsigned long long) data_p);
+ return -EBADMSG;
+ }
+
+ /* Check if this entry is also in main entry array. Since the
+ * main entry array has already been verified we can rely on
+ * its consistency.*/
+
+ i = 0;
+ n = le64toh(f->header->n_entries);
+ a = le64toh(f->header->entry_array_offset);
+
+ while (i < n) {
+ uint64_t m, u;
+
+ r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o);
+ if (r < 0)
+ return r;
+
+ m = journal_file_entry_array_n_items(o);
+ u = MIN(n - i, m);
+
+ if (entry_p <= le64toh(o->entry_array.items[u-1])) {
+ uint64_t x, y, z;
+
+ x = 0;
+ y = u;
+
+ while (x < y) {
+ z = (x + y) / 2;
+
+ if (le64toh(o->entry_array.items[z]) == entry_p)
+ return 0;
+
+ if (x + 1 >= y)
+ break;
+
+ if (entry_p < le64toh(o->entry_array.items[z]))
+ y = z;
+ else
+ x = z;
+ }
+
+ log_error("Entry object doesn't exist in main entry array at %llu", (unsigned long long) entry_p);
+ return -EBADMSG;
+ }
+
+ i += u;
+ a = le64toh(o->entry_array.next_entry_array_offset);
+ }
+
+ return 0;
+}
+
+static int verify_data(
+ JournalFile *f,
+ Object *o, uint64_t p,
+ int entry_fd, uint64_t n_entries,
+ int entry_array_fd, uint64_t n_entry_arrays) {
+
+ uint64_t i, n, a, last, q;
+ int r;
+
+ assert(f);
+ assert(o);
+ assert(entry_fd >= 0);
+ assert(entry_array_fd >= 0);
+
+ n = le64toh(o->data.n_entries);
+ a = le64toh(o->data.entry_array_offset);
+
+ /* We already checked this earlier */
+ assert(n > 0);
+
+ last = q = le64toh(o->data.entry_offset);
+ r = entry_points_to_data(f, entry_fd, n_entries, q, p);
+ if (r < 0)
+ return r;
+
+ i = 1;
+ while (i < n) {
+ uint64_t next, m, j;
+
+ if (a == 0) {
+ log_error("Array chain too short at %llu", (unsigned long long) p);
+ return -EBADMSG;
+ }
+
+ if (!contains_uint64(f->mmap, entry_array_fd, n_entry_arrays, a)) {
+ log_error("Invalid array at %llu", (unsigned long long) p);
+ return -EBADMSG;
+ }
+
+ r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o);
+ if (r < 0)
+ return r;
+
+ next = le64toh(o->entry_array.next_entry_array_offset);
+ if (next != 0 && next <= a) {
+ log_error("Array chain has cycle at %llu", (unsigned long long) p);
+ return -EBADMSG;
+ }
+
+ m = journal_file_entry_array_n_items(o);
+ for (j = 0; i < n && j < m; i++, j++) {
+
+ q = le64toh(o->entry_array.items[j]);
+ if (q <= last) {
+ log_error("Data object's entry array not sorted at %llu", (unsigned long long) p);
+ return -EBADMSG;
+ }
+ last = q;
+
+ r = entry_points_to_data(f, entry_fd, n_entries, q, p);
+ if (r < 0)
+ return r;
+
+ /* Pointer might have moved, reposition */
+ r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o);
+ if (r < 0)
+ return r;
+ }
+
+ a = next;
+ }
+
+ return 0;
+}
+
+static int verify_hash_table(
+ JournalFile *f,
+ int data_fd, uint64_t n_data,
+ int entry_fd, uint64_t n_entries,
+ int entry_array_fd, uint64_t n_entry_arrays,
+ usec_t *last_usec,
+ bool show_progress) {
+
+ uint64_t i, n;
+ int r;
+
+ assert(f);
+ assert(data_fd >= 0);
+ assert(entry_fd >= 0);
+ assert(entry_array_fd >= 0);
+ assert(last_usec);
+
+ n = le64toh(f->header->data_hash_table_size) / sizeof(HashItem);
+ for (i = 0; i < n; i++) {
+ uint64_t last = 0, p;
+
+ if (show_progress)
+ draw_progress(0xC000 + (0x3FFF * i / n), last_usec);
+
+ p = le64toh(f->data_hash_table[i].head_hash_offset);
+ while (p != 0) {
+ Object *o;
+ uint64_t next;
+
+ if (!contains_uint64(f->mmap, data_fd, n_data, p)) {
+ log_error("Invalid data object at hash entry %llu of %llu",
+ (unsigned long long) i, (unsigned long long) n);
+ return -EBADMSG;
+ }
+
+ r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
+ if (r < 0)
+ return r;
+
+ next = le64toh(o->data.next_hash_offset);
+ if (next != 0 && next <= p) {
+ log_error("Hash chain has a cycle in hash entry %llu of %llu",
+ (unsigned long long) i, (unsigned long long) n);
+ return -EBADMSG;
+ }
+
+ if (le64toh(o->data.hash) % n != i) {
+ log_error("Hash value mismatch in hash entry %llu of %llu",
+ (unsigned long long) i, (unsigned long long) n);
+ return -EBADMSG;
+ }
+
+ r = verify_data(f, o, p, entry_fd, n_entries, entry_array_fd, n_entry_arrays);
+ if (r < 0)
+ return r;
+
+ last = p;
+ p = next;
+ }
+
+ if (last != le64toh(f->data_hash_table[i].tail_hash_offset)) {
+ log_error("Tail hash pointer mismatch in hash table");
+ return -EBADMSG;
+ }
+ }
+
+ return 0;
+}
+
+static int data_object_in_hash_table(JournalFile *f, uint64_t hash, uint64_t p) {
+ uint64_t n, h, q;
+ int r;
+ assert(f);
+
+ n = le64toh(f->header->data_hash_table_size) / sizeof(HashItem);
+ h = hash % n;
+
+ q = le64toh(f->data_hash_table[h].head_hash_offset);
+ while (q != 0) {
+ Object *o;
+
+ if (p == q)
+ return 1;
+
+ r = journal_file_move_to_object(f, OBJECT_DATA, q, &o);
+ if (r < 0)
+ return r;
+
+ q = le64toh(o->data.next_hash_offset);
+ }
+
+ return 0;
+}
+
+static int verify_entry(
+ JournalFile *f,
+ Object *o, uint64_t p,
+ int data_fd, uint64_t n_data) {
+
+ uint64_t i, n;
+ int r;
+
+ assert(f);
+ assert(o);
+ assert(data_fd >= 0);
+
+ n = journal_file_entry_n_items(o);
+ for (i = 0; i < n; i++) {
+ uint64_t q, h;
+ Object *u;
+
+ q = le64toh(o->entry.items[i].object_offset);
+ h = le64toh(o->entry.items[i].hash);
+
+ if (!contains_uint64(f->mmap, data_fd, n_data, q)) {
+ log_error("Invalid data object at entry %llu",
+ (unsigned long long) p);
+ return -EBADMSG;
+ }
+
+ r = journal_file_move_to_object(f, OBJECT_DATA, q, &u);
+ if (r < 0)
+ return r;
+
+ if (le64toh(u->data.hash) != h) {
+ log_error("Hash mismatch for data object at entry %llu",
+ (unsigned long long) p);
+ return -EBADMSG;
+ }
+
+ r = data_object_in_hash_table(f, h, q);
+ if (r < 0)
+ return r;
+ if (r == 0) {
+ log_error("Data object missing from hash at entry %llu",
+ (unsigned long long) p);
+ return -EBADMSG;
+ }
+ }
+
+ return 0;
+}
+
+static int verify_entry_array(
+ JournalFile *f,
+ int data_fd, uint64_t n_data,
+ int entry_fd, uint64_t n_entries,
+ int entry_array_fd, uint64_t n_entry_arrays,
+ usec_t *last_usec,
+ bool show_progress) {
+
+ uint64_t i = 0, a, n, last = 0;
+ int r;
+
+ assert(f);
+ assert(data_fd >= 0);
+ assert(entry_fd >= 0);
+ assert(entry_array_fd >= 0);
+ assert(last_usec);
+
+ n = le64toh(f->header->n_entries);
+ a = le64toh(f->header->entry_array_offset);
+ while (i < n) {
+ uint64_t next, m, j;
+ Object *o;
+
+ if (show_progress)
+ draw_progress(0x8000 + (0x3FFF * i / n), last_usec);
+
+ if (a == 0) {
+ log_error("Array chain too short at %llu of %llu",
+ (unsigned long long) i, (unsigned long long) n);
+ return -EBADMSG;
+ }
+
+ if (!contains_uint64(f->mmap, entry_array_fd, n_entry_arrays, a)) {
+ log_error("Invalid array at %llu of %llu",
+ (unsigned long long) i, (unsigned long long) n);
+ return -EBADMSG;
+ }
+
+ r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o);
+ if (r < 0)
+ return r;
+
+ next = le64toh(o->entry_array.next_entry_array_offset);
+ if (next != 0 && next <= a) {
+ log_error("Array chain has cycle at %llu of %llu",
+ (unsigned long long) i, (unsigned long long) n);
+ return -EBADMSG;
+ }
+
+ m = journal_file_entry_array_n_items(o);
+ for (j = 0; i < n && j < m; i++, j++) {
+ uint64_t p;
+
+ p = le64toh(o->entry_array.items[j]);
+ if (p <= last) {
+ log_error("Entry array not sorted at %llu of %llu",
+ (unsigned long long) i, (unsigned long long) n);
+ return -EBADMSG;
+ }
+ last = p;
+
+ if (!contains_uint64(f->mmap, entry_fd, n_entries, p)) {
+ log_error("Invalid array entry at %llu of %llu",
+ (unsigned long long) i, (unsigned long long) n);
+ return -EBADMSG;
+ }
+
+ r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
+ if (r < 0)
+ return r;
+
+ r = verify_entry(f, o, p, data_fd, n_data);
+ if (r < 0)
+ return r;
+
+ /* Pointer might have moved, reposition */
+ r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o);
+ if (r < 0)
+ return r;
+ }
+
+ a = next;
+ }
+
+ return 0;
+}
+
+int journal_file_verify(
+ JournalFile *f,
+ const char *key,
+ usec_t *first_contained, usec_t *last_validated, usec_t *last_contained,
+ bool show_progress) {
+ int r;
+ Object *o;
+ uint64_t p = 0, last_epoch = 0, last_tag_realtime = 0, last_sealed_realtime = 0;
+
+ uint64_t entry_seqnum = 0, entry_monotonic = 0, entry_realtime = 0;
+ sd_id128_t entry_boot_id;
+ bool entry_seqnum_set = false, entry_monotonic_set = false, entry_realtime_set = false, found_main_entry_array = false;
+ uint64_t n_weird = 0, n_objects = 0, n_entries = 0, n_data = 0, n_fields = 0, n_data_hash_tables = 0, n_field_hash_tables = 0, n_entry_arrays = 0, n_tags = 0;
+ usec_t last_usec = 0;
+ int data_fd = -1, entry_fd = -1, entry_array_fd = -1;
+ char data_path[] = "/var/tmp/journal-data-XXXXXX",
+ entry_path[] = "/var/tmp/journal-entry-XXXXXX",
+ entry_array_path[] = "/var/tmp/journal-entry-array-XXXXXX";
+ unsigned i;
+ bool found_last;
+#ifdef HAVE_GCRYPT
+ uint64_t last_tag = 0;
+#endif
+ assert(f);
+
+ if (key) {
+#ifdef HAVE_GCRYPT
+ r = journal_file_parse_verification_key(f, key);
+ if (r < 0) {
+ log_error("Failed to parse seed.");
+ return r;
+ }
+#else
+ return -ENOTSUP;
+#endif
+ } else if (f->seal)
+ return -ENOKEY;
+
+ data_fd = mkostemp(data_path, O_CLOEXEC);
+ if (data_fd < 0) {
+ log_error("Failed to create data file: %m");
+ r = -errno;
+ goto fail;
+ }
+ unlink(data_path);
+
+ entry_fd = mkostemp(entry_path, O_CLOEXEC);
+ if (entry_fd < 0) {
+ log_error("Failed to create entry file: %m");
+ r = -errno;
+ goto fail;
+ }
+ unlink(entry_path);
+
+ entry_array_fd = mkostemp(entry_array_path, O_CLOEXEC);
+ if (entry_array_fd < 0) {
+ log_error("Failed to create entry array file: %m");
+ r = -errno;
+ goto fail;
+ }
+ unlink(entry_array_path);
+
+#ifdef HAVE_GCRYPT
+ if ((le32toh(f->header->compatible_flags) & ~HEADER_COMPATIBLE_SEALED) != 0)
+#else
+ if (f->header->compatible_flags != 0)
+#endif
+ {
+ log_error("Cannot verify file with unknown extensions.");
+ r = -ENOTSUP;
+ goto fail;
+ }
+
+ for (i = 0; i < sizeof(f->header->reserved); i++)
+ if (f->header->reserved[i] != 0) {
+ log_error("Reserved field in non-zero.");
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ /* First iteration: we go through all objects, verify the
+ * superficial structure, headers, hashes. */
+
+ p = le64toh(f->header->header_size);
+ while (p != 0) {
+ if (show_progress)
+ draw_progress(0x7FFF * p / le64toh(f->header->tail_object_offset), &last_usec);
+
+ r = journal_file_move_to_object(f, -1, p, &o);
+ if (r < 0) {
+ log_error("Invalid object at %llu", (unsigned long long) p);
+ goto fail;
+ }
+
+ if (p > le64toh(f->header->tail_object_offset)) {
+ log_error("Invalid tail object pointer");
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ if (p == le64toh(f->header->tail_object_offset))
+ found_last = true;
+
+ n_objects ++;
+
+ r = journal_file_object_verify(f, o);
+ if (r < 0) {
+ log_error("Invalid object contents at %llu", (unsigned long long) p);
+ goto fail;
+ }
+
+ if ((o->object.flags & OBJECT_COMPRESSED) && !JOURNAL_HEADER_COMPRESSED(f->header)) {
+ log_error("Compressed object in file without compression at %llu", (unsigned long long) p);
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ switch (o->object.type) {
+
+ case OBJECT_DATA:
+ r = write_uint64(data_fd, p);
+ if (r < 0)
+ goto fail;
+
+ n_data++;
+ break;
+
+ case OBJECT_FIELD:
+ n_fields++;
+ break;
+
+ case OBJECT_ENTRY:
+ if (JOURNAL_HEADER_SEALED(f->header) && n_tags <= 0) {
+ log_error("First entry before first tag at %llu", (unsigned long long) p);
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ r = write_uint64(entry_fd, p);
+ if (r < 0)
+ goto fail;
+
+ if (le64toh(o->entry.realtime) < last_tag_realtime) {
+ log_error("Older entry after newer tag at %llu", (unsigned long long) p);
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ if (!entry_seqnum_set &&
+ le64toh(o->entry.seqnum) != le64toh(f->header->head_entry_seqnum)) {
+ log_error("Head entry sequence number incorrect at %llu", (unsigned long long) p);
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ if (entry_seqnum_set &&
+ entry_seqnum >= le64toh(o->entry.seqnum)) {
+ log_error("Entry sequence number out of synchronization at %llu", (unsigned long long) p);
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ entry_seqnum = le64toh(o->entry.seqnum);
+ entry_seqnum_set = true;
+
+ if (entry_monotonic_set &&
+ sd_id128_equal(entry_boot_id, o->entry.boot_id) &&
+ entry_monotonic > le64toh(o->entry.monotonic)) {
+ log_error("Entry timestamp out of synchronization at %llu", (unsigned long long) p);
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ entry_monotonic = le64toh(o->entry.monotonic);
+ entry_boot_id = o->entry.boot_id;
+ entry_monotonic_set = true;
+
+ if (!entry_realtime_set &&
+ le64toh(o->entry.realtime) != le64toh(f->header->head_entry_realtime)) {
+ log_error("Head entry realtime timestamp incorrect");
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ entry_realtime = le64toh(o->entry.realtime);
+ entry_realtime_set = true;
+
+ n_entries ++;
+ break;
+
+ case OBJECT_DATA_HASH_TABLE:
+ if (n_data_hash_tables > 1) {
+ log_error("More than one data hash table at %llu", (unsigned long long) p);
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ if (le64toh(f->header->data_hash_table_offset) != p + offsetof(HashTableObject, items) ||
+ le64toh(f->header->data_hash_table_size) != le64toh(o->object.size) - offsetof(HashTableObject, items)) {
+ log_error("Header fields for data hash table invalid");
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ n_data_hash_tables++;
+ break;
+
+ case OBJECT_FIELD_HASH_TABLE:
+ if (n_field_hash_tables > 1) {
+ log_error("More than one field hash table at %llu", (unsigned long long) p);
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ if (le64toh(f->header->field_hash_table_offset) != p + offsetof(HashTableObject, items) ||
+ le64toh(f->header->field_hash_table_size) != le64toh(o->object.size) - offsetof(HashTableObject, items)) {
+ log_error("Header fields for field hash table invalid");
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ n_field_hash_tables++;
+ break;
+
+ case OBJECT_ENTRY_ARRAY:
+ r = write_uint64(entry_array_fd, p);
+ if (r < 0)
+ goto fail;
+
+ if (p == le64toh(f->header->entry_array_offset)) {
+ if (found_main_entry_array) {
+ log_error("More than one main entry array at %llu", (unsigned long long) p);
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ found_main_entry_array = true;
+ }
+
+ n_entry_arrays++;
+ break;
+
+ case OBJECT_TAG:
+ if (!JOURNAL_HEADER_SEALED(f->header)) {
+ log_error("Tag object in file without sealing at %llu", (unsigned long long) p);
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ if (le64toh(o->tag.seqnum) != n_tags + 1) {
+ log_error("Tag sequence number out of synchronization at %llu", (unsigned long long) p);
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ if (le64toh(o->tag.epoch) < last_epoch) {
+ log_error("Epoch sequence out of synchronization at %llu", (unsigned long long) p);
+ r = -EBADMSG;
+ goto fail;
+ }
+
+#ifdef HAVE_GCRYPT
+ if (f->seal) {
+ uint64_t q, rt;
+
+ log_debug("Checking tag %llu..", (unsigned long long) le64toh(o->tag.seqnum));
+
+ rt = f->fss_start_usec + o->tag.epoch * f->fss_interval_usec;
+ if (entry_realtime_set && entry_realtime >= rt + f->fss_interval_usec) {
+ log_error("Tag/entry realtime timestamp out of synchronization at %llu", (unsigned long long) p);
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ /* OK, now we know the epoch. So let's now set
+ * it, and calculate the HMAC for everything
+ * since the last tag. */
+ r = journal_file_fsprg_seek(f, le64toh(o->tag.epoch));
+ if (r < 0)
+ goto fail;
+
+ r = journal_file_hmac_start(f);
+ if (r < 0)
+ goto fail;
+
+ if (last_tag == 0) {
+ r = journal_file_hmac_put_header(f);
+ if (r < 0)
+ goto fail;
+
+ q = le64toh(f->header->header_size);
+ } else
+ q = last_tag;
+
+ while (q <= p) {
+ r = journal_file_move_to_object(f, -1, q, &o);
+ if (r < 0)
+ goto fail;
+
+ r = journal_file_hmac_put_object(f, -1, o, q);
+ if (r < 0)
+ goto fail;
+
+ q = q + ALIGN64(le64toh(o->object.size));
+ }
+
+ /* Position might have changed, let's reposition things */
+ r = journal_file_move_to_object(f, -1, p, &o);
+ if (r < 0)
+ goto fail;
+
+ if (memcmp(o->tag.tag, gcry_md_read(f->hmac, 0), TAG_LENGTH) != 0) {
+ log_error("Tag failed verification at %llu", (unsigned long long) p);
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ f->hmac_running = false;
+ last_tag_realtime = rt;
+ last_sealed_realtime = entry_realtime;
+ }
+
+ last_tag = p + ALIGN64(le64toh(o->object.size));
+#endif
+
+ last_epoch = le64toh(o->tag.epoch);
+
+ n_tags ++;
+ break;
+
+ default:
+ n_weird ++;
+ }
+
+ if (p == le64toh(f->header->tail_object_offset))
+ p = 0;
+ else
+ p = p + ALIGN64(le64toh(o->object.size));
+ }
+
+ if (!found_last) {
+ log_error("Tail object pointer dead");
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ if (n_objects != le64toh(f->header->n_objects)) {
+ log_error("Object number mismatch");
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ if (n_entries != le64toh(f->header->n_entries)) {
+ log_error("Entry number mismatch");
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ if (JOURNAL_HEADER_CONTAINS(f->header, n_data) &&
+ n_data != le64toh(f->header->n_data)) {
+ log_error("Data number mismatch");
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ if (JOURNAL_HEADER_CONTAINS(f->header, n_fields) &&
+ n_fields != le64toh(f->header->n_fields)) {
+ log_error("Field number mismatch");
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ if (JOURNAL_HEADER_CONTAINS(f->header, n_tags) &&
+ n_tags != le64toh(f->header->n_tags)) {
+ log_error("Tag number mismatch");
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ if (JOURNAL_HEADER_CONTAINS(f->header, n_entry_arrays) &&
+ n_entry_arrays != le64toh(f->header->n_entry_arrays)) {
+ log_error("Entry array number mismatch");
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ if (n_data_hash_tables != 1) {
+ log_error("Missing data hash table");
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ if (n_field_hash_tables != 1) {
+ log_error("Missing field hash table");
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ if (!found_main_entry_array) {
+ log_error("Missing entry array");
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ if (entry_seqnum_set &&
+ entry_seqnum != le64toh(f->header->tail_entry_seqnum)) {
+ log_error("Invalid tail seqnum");
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ if (entry_monotonic_set &&
+ (!sd_id128_equal(entry_boot_id, f->header->boot_id) ||
+ entry_monotonic != le64toh(f->header->tail_entry_monotonic))) {
+ log_error("Invalid tail monotonic timestamp");
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ if (entry_realtime_set && entry_realtime != le64toh(f->header->tail_entry_realtime)) {
+ log_error("Invalid tail realtime timestamp");
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ /* Second iteration: we follow all objects referenced from the
+ * two entry points: the object hash table and the entry
+ * array. We also check that everything referenced (directly
+ * or indirectly) in the data hash table also exists in the
+ * entry array, and vice versa. Note that we do not care for
+ * unreferenced objects. We only care that everything that is
+ * referenced is consistent. */
+
+ r = verify_entry_array(f,
+ data_fd, n_data,
+ entry_fd, n_entries,
+ entry_array_fd, n_entry_arrays,
+ &last_usec,
+ show_progress);
+ if (r < 0)
+ goto fail;
+
+ r = verify_hash_table(f,
+ data_fd, n_data,
+ entry_fd, n_entries,
+ entry_array_fd, n_entry_arrays,
+ &last_usec,
+ show_progress);
+ if (r < 0)
+ goto fail;
+
+ if (show_progress)
+ flush_progress();
+
+ mmap_cache_close_fd(f->mmap, data_fd);
+ mmap_cache_close_fd(f->mmap, entry_fd);
+ mmap_cache_close_fd(f->mmap, entry_array_fd);
+
+ close_nointr_nofail(data_fd);
+ close_nointr_nofail(entry_fd);
+ close_nointr_nofail(entry_array_fd);
+
+ if (first_contained)
+ *first_contained = le64toh(f->header->head_entry_realtime);
+ if (last_validated)
+ *last_validated = last_sealed_realtime;
+ if (last_contained)
+ *last_contained = le64toh(f->header->tail_entry_realtime);
+
+ return 0;
+
+fail:
+ if (show_progress)
+ flush_progress();
+
+ log_error("File corruption detected at %s:%llu (of %llu, %llu%%).",
+ f->path,
+ (unsigned long long) p,
+ (unsigned long long) f->last_stat.st_size,
+ (unsigned long long) (100 * p / f->last_stat.st_size));
+
+ if (data_fd >= 0) {
+ mmap_cache_close_fd(f->mmap, data_fd);
+ close_nointr_nofail(data_fd);
+ }
+
+ if (entry_fd >= 0) {
+ mmap_cache_close_fd(f->mmap, entry_fd);
+ close_nointr_nofail(entry_fd);
+ }
+
+ if (entry_array_fd >= 0) {
+ mmap_cache_close_fd(f->mmap, entry_array_fd);
+ close_nointr_nofail(entry_array_fd);
+ }
+
+ return r;
+}
diff --git a/src/journal/journal-verify.h b/src/journal/journal-verify.h
new file mode 100644
index 0000000000..e392ab61d7
--- /dev/null
+++ b/src/journal/journal-verify.h
@@ -0,0 +1,26 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "journal-file.h"
+
+int journal_file_verify(JournalFile *f, const char *key, usec_t *first_contained, usec_t *last_validated, usec_t *last_contained, bool show_progress);
diff --git a/src/journal/journalctl.c b/src/journal/journalctl.c
new file mode 100644
index 0000000000..409f082276
--- /dev/null
+++ b/src/journal/journalctl.c
@@ -0,0 +1,1356 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <locale.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <stddef.h>
+#include <string.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <time.h>
+#include <getopt.h>
+#include <signal.h>
+#include <sys/stat.h>
+#include <sys/ioctl.h>
+#include <linux/fs.h>
+
+#ifdef HAVE_ACL
+#include <sys/acl.h>
+#include "acl-util.h"
+#endif
+
+#include <systemd/sd-journal.h>
+
+#include "log.h"
+#include "logs-show.h"
+#include "util.h"
+#include "path-util.h"
+#include "build.h"
+#include "pager.h"
+#include "logs-show.h"
+#include "strv.h"
+#include "journal-internal.h"
+#include "journal-def.h"
+#include "journal-verify.h"
+#include "journal-authenticate.h"
+#include "journal-qrcode.h"
+#include "fsprg.h"
+#include "unit-name.h"
+#include "catalog.h"
+
+#define DEFAULT_FSS_INTERVAL_USEC (15*USEC_PER_MINUTE)
+
+static OutputMode arg_output = OUTPUT_SHORT;
+static bool arg_pager_end = false;
+static bool arg_follow = false;
+static bool arg_full = false;
+static bool arg_all = false;
+static bool arg_no_pager = false;
+static int arg_lines = -1;
+static bool arg_no_tail = false;
+static bool arg_quiet = false;
+static bool arg_merge = false;
+static bool arg_this_boot = false;
+static const char *arg_cursor = NULL;
+static const char *arg_directory = NULL;
+static int arg_priorities = 0xFF;
+static const char *arg_verify_key = NULL;
+#ifdef HAVE_GCRYPT
+static usec_t arg_interval = DEFAULT_FSS_INTERVAL_USEC;
+#endif
+static usec_t arg_since, arg_until;
+static bool arg_since_set = false, arg_until_set = false;
+static char **arg_system_units = NULL;
+static char **arg_user_units = NULL;
+static const char *arg_field = NULL;
+static bool arg_catalog = false;
+static bool arg_reverse = false;
+static const char *arg_root = NULL;
+
+static enum {
+ ACTION_SHOW,
+ ACTION_NEW_ID128,
+ ACTION_PRINT_HEADER,
+ ACTION_SETUP_KEYS,
+ ACTION_VERIFY,
+ ACTION_DISK_USAGE,
+ ACTION_LIST_CATALOG,
+ ACTION_DUMP_CATALOG,
+ ACTION_UPDATE_CATALOG
+} arg_action = ACTION_SHOW;
+
+static int help(void) {
+
+ printf("%s [OPTIONS...] [MATCHES...]\n\n"
+ "Query the journal.\n\n"
+ "Flags:\n"
+ " --since=DATE Start showing entries newer or of the specified date\n"
+ " --until=DATE Stop showing entries older or of the specified date\n"
+ " -c --cursor=CURSOR Start showing entries from specified cursor\n"
+ " -b --this-boot Show data only from current boot\n"
+ " -u --unit=UNIT Show data only from the specified unit\n"
+ " --user-unit=UNIT Show data only from the specified user session unit\n"
+ " -p --priority=RANGE Show only messages within the specified priority range\n"
+ " -e --pager-end Immediately jump to end of the journal in the pager\n"
+ " -f --follow Follow journal\n"
+ " -n --lines[=INTEGER] Number of journal entries to show\n"
+ " --no-tail Show all lines, even in follow mode\n"
+ " -r --reverse Show the newest entries first\n"
+ " -o --output=STRING Change journal output mode (short, short-monotonic,\n"
+ " verbose, export, json, json-pretty, json-sse, cat)\n"
+ " -x --catalog Add message explanations where available\n"
+ " --full Do not ellipsize fields\n"
+ " -a --all Show all fields, including long and unprintable\n"
+ " -q --quiet Don't show privilege warning\n"
+ " --no-pager Do not pipe output into a pager\n"
+ " -m --merge Show entries from all available journals\n"
+ " -D --directory=PATH Show journal files from directory\n"
+ " --root=ROOT Operate on catalog files underneath the root ROOT\n"
+#ifdef HAVE_GCRYPT
+ " --interval=TIME Time interval for changing the FSS sealing key\n"
+ " --verify-key=KEY Specify FSS verification key\n"
+#endif
+ "\nCommands:\n"
+ " -h --help Show this help\n"
+ " --version Show package version\n"
+ " --new-id128 Generate a new 128 Bit ID\n"
+ " --header Show journal header information\n"
+ " --disk-usage Show total disk usage\n"
+ " -F --field=FIELD List all values a certain field takes\n"
+ " --list-catalog Show message IDs of all entries in the message catalog\n"
+ " --dump-catalog Show entries in the message catalog\n"
+ " --update-catalog Update the message catalog database\n"
+#ifdef HAVE_GCRYPT
+ " --setup-keys Generate new FSS key pair\n"
+ " --verify Verify journal file consistency\n"
+#endif
+ , program_invocation_short_name);
+
+ return 0;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+
+ enum {
+ ARG_VERSION = 0x100,
+ ARG_NO_PAGER,
+ ARG_NO_TAIL,
+ ARG_NEW_ID128,
+ ARG_ROOT,
+ ARG_HEADER,
+ ARG_FULL,
+ ARG_SETUP_KEYS,
+ ARG_INTERVAL,
+ ARG_VERIFY,
+ ARG_VERIFY_KEY,
+ ARG_DISK_USAGE,
+ ARG_SINCE,
+ ARG_UNTIL,
+ ARG_USER_UNIT,
+ ARG_LIST_CATALOG,
+ ARG_DUMP_CATALOG,
+ ARG_UPDATE_CATALOG
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "version" , no_argument, NULL, ARG_VERSION },
+ { "no-pager", no_argument, NULL, ARG_NO_PAGER },
+ { "pager-end", no_argument, NULL, 'e' },
+ { "follow", no_argument, NULL, 'f' },
+ { "output", required_argument, NULL, 'o' },
+ { "all", no_argument, NULL, 'a' },
+ { "full", no_argument, NULL, ARG_FULL },
+ { "lines", optional_argument, NULL, 'n' },
+ { "no-tail", no_argument, NULL, ARG_NO_TAIL },
+ { "new-id128", no_argument, NULL, ARG_NEW_ID128 },
+ { "quiet", no_argument, NULL, 'q' },
+ { "merge", no_argument, NULL, 'm' },
+ { "this-boot", no_argument, NULL, 'b' },
+ { "directory", required_argument, NULL, 'D' },
+ { "root", required_argument, NULL, ARG_ROOT },
+ { "header", no_argument, NULL, ARG_HEADER },
+ { "priority", required_argument, NULL, 'p' },
+ { "setup-keys", no_argument, NULL, ARG_SETUP_KEYS },
+ { "interval", required_argument, NULL, ARG_INTERVAL },
+ { "verify", no_argument, NULL, ARG_VERIFY },
+ { "verify-key", required_argument, NULL, ARG_VERIFY_KEY },
+ { "disk-usage", no_argument, NULL, ARG_DISK_USAGE },
+ { "cursor", required_argument, NULL, 'c' },
+ { "since", required_argument, NULL, ARG_SINCE },
+ { "until", required_argument, NULL, ARG_UNTIL },
+ { "unit", required_argument, NULL, 'u' },
+ { "user-unit", required_argument, NULL, ARG_USER_UNIT },
+ { "field", required_argument, NULL, 'F' },
+ { "catalog", no_argument, NULL, 'x' },
+ { "list-catalog", no_argument, NULL, ARG_LIST_CATALOG },
+ { "dump-catalog", no_argument, NULL, ARG_DUMP_CATALOG },
+ { "update-catalog",no_argument, NULL, ARG_UPDATE_CATALOG },
+ { "reverse", no_argument, NULL, 'r' },
+ { NULL, 0, NULL, 0 }
+ };
+
+ int c, r;
+
+ assert(argc >= 0);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "hefo:an::qmbD:p:c:u:F:xr", options, NULL)) >= 0) {
+
+ switch (c) {
+
+ case 'h':
+ help();
+ return 0;
+
+ case ARG_VERSION:
+ puts(PACKAGE_STRING);
+ puts(SYSTEMD_FEATURES);
+ return 0;
+
+ case ARG_NO_PAGER:
+ arg_no_pager = true;
+ break;
+
+ case 'e':
+ arg_pager_end = true;
+
+ if (arg_lines < 0)
+ arg_lines = 1000;
+
+ break;
+
+ case 'f':
+ arg_follow = true;
+ break;
+
+ case 'o':
+ arg_output = output_mode_from_string(optarg);
+ if (arg_output < 0) {
+ log_error("Unknown output format '%s'.", optarg);
+ return -EINVAL;
+ }
+
+ if (arg_output == OUTPUT_EXPORT ||
+ arg_output == OUTPUT_JSON ||
+ arg_output == OUTPUT_JSON_PRETTY ||
+ arg_output == OUTPUT_JSON_SSE ||
+ arg_output == OUTPUT_CAT)
+ arg_quiet = true;
+
+ break;
+
+ case ARG_FULL:
+ arg_full = true;
+ break;
+
+ case 'a':
+ arg_all = true;
+ break;
+
+ case 'n':
+ if (optarg) {
+ r = safe_atoi(optarg, &arg_lines);
+ if (r < 0 || arg_lines < 0) {
+ log_error("Failed to parse lines '%s'", optarg);
+ return -EINVAL;
+ }
+ } else {
+ int n;
+
+ /* Hmm, no argument? Maybe the next
+ * word on the command line is
+ * supposed to be the argument? Let's
+ * see if there is one, and is
+ * parsable as a positive
+ * integer... */
+
+ if (optind < argc &&
+ safe_atoi(argv[optind], &n) >= 0 &&
+ n >= 0) {
+
+ arg_lines = n;
+ optind++;
+ } else
+ arg_lines = 10;
+ }
+
+ break;
+
+ case ARG_NO_TAIL:
+ arg_no_tail = true;
+ break;
+
+ case ARG_NEW_ID128:
+ arg_action = ACTION_NEW_ID128;
+ break;
+
+ case 'q':
+ arg_quiet = true;
+ break;
+
+ case 'm':
+ arg_merge = true;
+ break;
+
+ case 'b':
+ arg_this_boot = true;
+ break;
+
+ case 'D':
+ arg_directory = optarg;
+ break;
+
+ case ARG_ROOT:
+ arg_root = optarg;
+ break;
+
+ case 'c':
+ arg_cursor = optarg;
+ break;
+
+ case ARG_HEADER:
+ arg_action = ACTION_PRINT_HEADER;
+ break;
+
+ case ARG_VERIFY:
+ arg_action = ACTION_VERIFY;
+ break;
+
+ case ARG_DISK_USAGE:
+ arg_action = ACTION_DISK_USAGE;
+ break;
+
+#ifdef HAVE_GCRYPT
+ case ARG_SETUP_KEYS:
+ arg_action = ACTION_SETUP_KEYS;
+ break;
+
+
+ case ARG_VERIFY_KEY:
+ arg_action = ACTION_VERIFY;
+ arg_verify_key = optarg;
+ arg_merge = false;
+ break;
+
+ case ARG_INTERVAL:
+ r = parse_sec(optarg, &arg_interval);
+ if (r < 0 || arg_interval <= 0) {
+ log_error("Failed to parse sealing key change interval: %s", optarg);
+ return -EINVAL;
+ }
+ break;
+#else
+ case ARG_SETUP_KEYS:
+ case ARG_VERIFY_KEY:
+ case ARG_INTERVAL:
+ log_error("Forward-secure sealing not available.");
+ return -ENOTSUP;
+#endif
+
+ case 'p': {
+ const char *dots;
+
+ dots = strstr(optarg, "..");
+ if (dots) {
+ char *a;
+ int from, to, i;
+
+ /* a range */
+ a = strndup(optarg, dots - optarg);
+ if (!a)
+ return log_oom();
+
+ from = log_level_from_string(a);
+ to = log_level_from_string(dots + 2);
+ free(a);
+
+ if (from < 0 || to < 0) {
+ log_error("Failed to parse log level range %s", optarg);
+ return -EINVAL;
+ }
+
+ arg_priorities = 0;
+
+ if (from < to) {
+ for (i = from; i <= to; i++)
+ arg_priorities |= 1 << i;
+ } else {
+ for (i = to; i <= from; i++)
+ arg_priorities |= 1 << i;
+ }
+
+ } else {
+ int p, i;
+
+ p = log_level_from_string(optarg);
+ if (p < 0) {
+ log_error("Unknown log level %s", optarg);
+ return -EINVAL;
+ }
+
+ arg_priorities = 0;
+
+ for (i = 0; i <= p; i++)
+ arg_priorities |= 1 << i;
+ }
+
+ break;
+ }
+
+ case ARG_SINCE:
+ r = parse_timestamp(optarg, &arg_since);
+ if (r < 0) {
+ log_error("Failed to parse timestamp: %s", optarg);
+ return -EINVAL;
+ }
+ arg_since_set = true;
+ break;
+
+ case ARG_UNTIL:
+ r = parse_timestamp(optarg, &arg_until);
+ if (r < 0) {
+ log_error("Failed to parse timestamp: %s", optarg);
+ return -EINVAL;
+ }
+ arg_until_set = true;
+ break;
+
+ case 'u':
+ r = strv_extend(&arg_system_units, optarg);
+ if (r < 0)
+ return log_oom();
+ break;
+
+ case ARG_USER_UNIT:
+ r = strv_extend(&arg_user_units, optarg);
+ if (r < 0)
+ return log_oom();
+ break;
+
+ case '?':
+ return -EINVAL;
+
+ case 'F':
+ arg_field = optarg;
+ break;
+
+ case 'x':
+ arg_catalog = true;
+ break;
+
+ case ARG_LIST_CATALOG:
+ arg_action = ACTION_LIST_CATALOG;
+ break;
+
+ case ARG_DUMP_CATALOG:
+ arg_action = ACTION_DUMP_CATALOG;
+ break;
+
+ case ARG_UPDATE_CATALOG:
+ arg_action = ACTION_UPDATE_CATALOG;
+ break;
+
+ case 'r':
+ arg_reverse = true;
+ break;
+
+ default:
+ log_error("Unknown option code %c", c);
+ return -EINVAL;
+ }
+ }
+
+ if (arg_follow && !arg_no_tail && arg_lines < 0)
+ arg_lines = 10;
+
+ if (arg_since_set && arg_until_set && arg_since > arg_until) {
+ log_error("--since= must be before --until=.");
+ return -EINVAL;
+ }
+
+ if (arg_cursor && arg_since_set) {
+ log_error("Please specify either --since= or --cursor=, not both.");
+ return -EINVAL;
+ }
+
+ if (arg_follow && arg_reverse) {
+ log_error("Please specify either --reverse= or --follow=, not both.");
+ return -EINVAL;
+ }
+
+ return 1;
+}
+
+static int generate_new_id128(void) {
+ sd_id128_t id;
+ int r;
+ unsigned i;
+
+ r = sd_id128_randomize(&id);
+ if (r < 0) {
+ log_error("Failed to generate ID: %s", strerror(-r));
+ return r;
+ }
+
+ printf("As string:\n"
+ SD_ID128_FORMAT_STR "\n\n"
+ "As UUID:\n"
+ "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\n\n"
+ "As macro:\n"
+ "#define MESSAGE_XYZ SD_ID128_MAKE(",
+ SD_ID128_FORMAT_VAL(id),
+ SD_ID128_FORMAT_VAL(id));
+ for (i = 0; i < 16; i++)
+ printf("%02x%s", id.bytes[i], i != 15 ? "," : "");
+ fputs(")\n\n", stdout);
+
+ printf("As Python constant:\n"
+ ">>> import uuid\n"
+ ">>> MESSAGE_XYZ = uuid.UUID('" SD_ID128_FORMAT_STR "')\n",
+ SD_ID128_FORMAT_VAL(id));
+
+ return 0;
+}
+
+static int add_matches(sd_journal *j, char **args) {
+ char **i;
+
+ assert(j);
+
+ STRV_FOREACH(i, args) {
+ int r;
+
+ if (streq(*i, "+"))
+ r = sd_journal_add_disjunction(j);
+ else if (path_is_absolute(*i)) {
+ _cleanup_free_ char *p, *t = NULL;
+ const char *path;
+ struct stat st;
+
+ p = canonicalize_file_name(*i);
+ path = p ? p : *i;
+
+ if (stat(path, &st) < 0) {
+ log_error("Couldn't stat file: %m");
+ return -errno;
+ }
+
+ if (S_ISREG(st.st_mode) && (0111 & st.st_mode))
+ t = strappend("_EXE=", path);
+ else if (S_ISCHR(st.st_mode))
+ asprintf(&t, "_KERNEL_DEVICE=c%u:%u", major(st.st_rdev), minor(st.st_rdev));
+ else if (S_ISBLK(st.st_mode))
+ asprintf(&t, "_KERNEL_DEVICE=b%u:%u", major(st.st_rdev), minor(st.st_rdev));
+ else {
+ log_error("File is neither a device node, nor regular file, nor executable: %s", *i);
+ return -EINVAL;
+ }
+
+ if (!t)
+ return log_oom();
+
+ r = sd_journal_add_match(j, t, 0);
+ } else
+ r = sd_journal_add_match(j, *i, 0);
+
+ if (r < 0) {
+ log_error("Failed to add match '%s': %s", *i, strerror(-r));
+ return r;
+ }
+ }
+
+ return 0;
+}
+
+static int add_this_boot(sd_journal *j) {
+ char match[9+32+1] = "_BOOT_ID=";
+ sd_id128_t boot_id;
+ int r;
+
+ assert(j);
+
+ if (!arg_this_boot)
+ return 0;
+
+ r = sd_id128_get_boot(&boot_id);
+ if (r < 0) {
+ log_error("Failed to get boot id: %s", strerror(-r));
+ return r;
+ }
+
+ sd_id128_to_string(boot_id, match + 9);
+ r = sd_journal_add_match(j, match, strlen(match));
+ if (r < 0) {
+ log_error("Failed to add match: %s", strerror(-r));
+ return r;
+ }
+
+ r = sd_journal_add_conjunction(j);
+ if (r < 0)
+ return r;
+
+ return 0;
+}
+
+static int add_units(sd_journal *j) {
+ _cleanup_free_ char *u = NULL;
+ int r;
+ char **i;
+
+ assert(j);
+
+ STRV_FOREACH(i, arg_system_units) {
+ u = unit_name_mangle(*i);
+ if (!u)
+ return log_oom();
+ r = add_matches_for_unit(j, u);
+ if (r < 0)
+ return r;
+ r = sd_journal_add_disjunction(j);
+ if (r < 0)
+ return r;
+ }
+
+ STRV_FOREACH(i, arg_user_units) {
+ u = unit_name_mangle(*i);
+ if (!u)
+ return log_oom();
+
+ r = add_matches_for_user_unit(j, u, getuid());
+ if (r < 0)
+ return r;
+
+ r = sd_journal_add_disjunction(j);
+ if (r < 0)
+ return r;
+
+ }
+
+ r = sd_journal_add_conjunction(j);
+ if (r < 0)
+ return r;
+
+ return 0;
+}
+
+static int add_priorities(sd_journal *j) {
+ char match[] = "PRIORITY=0";
+ int i, r;
+ assert(j);
+
+ if (arg_priorities == 0xFF)
+ return 0;
+
+ for (i = LOG_EMERG; i <= LOG_DEBUG; i++)
+ if (arg_priorities & (1 << i)) {
+ match[sizeof(match)-2] = '0' + i;
+
+ r = sd_journal_add_match(j, match, strlen(match));
+ if (r < 0) {
+ log_error("Failed to add match: %s", strerror(-r));
+ return r;
+ }
+ }
+
+ r = sd_journal_add_conjunction(j);
+ if (r < 0)
+ return r;
+
+ return 0;
+}
+
+static int setup_keys(void) {
+#ifdef HAVE_GCRYPT
+ size_t mpk_size, seed_size, state_size, i;
+ uint8_t *mpk, *seed, *state;
+ ssize_t l;
+ int fd = -1, r, attr = 0;
+ sd_id128_t machine, boot;
+ char *p = NULL, *k = NULL;
+ struct FSSHeader h;
+ uint64_t n;
+
+ r = sd_id128_get_machine(&machine);
+ if (r < 0) {
+ log_error("Failed to get machine ID: %s", strerror(-r));
+ return r;
+ }
+
+ r = sd_id128_get_boot(&boot);
+ if (r < 0) {
+ log_error("Failed to get boot ID: %s", strerror(-r));
+ return r;
+ }
+
+ if (asprintf(&p, "/var/log/journal/" SD_ID128_FORMAT_STR "/fss",
+ SD_ID128_FORMAT_VAL(machine)) < 0)
+ return log_oom();
+
+ if (access(p, F_OK) >= 0) {
+ log_error("Sealing key file %s exists already.", p);
+ r = -EEXIST;
+ goto finish;
+ }
+
+ if (asprintf(&k, "/var/log/journal/" SD_ID128_FORMAT_STR "/fss.tmp.XXXXXX",
+ SD_ID128_FORMAT_VAL(machine)) < 0) {
+ r = log_oom();
+ goto finish;
+ }
+
+ mpk_size = FSPRG_mskinbytes(FSPRG_RECOMMENDED_SECPAR);
+ mpk = alloca(mpk_size);
+
+ seed_size = FSPRG_RECOMMENDED_SEEDLEN;
+ seed = alloca(seed_size);
+
+ state_size = FSPRG_stateinbytes(FSPRG_RECOMMENDED_SECPAR);
+ state = alloca(state_size);
+
+ fd = open("/dev/random", O_RDONLY|O_CLOEXEC|O_NOCTTY);
+ if (fd < 0) {
+ log_error("Failed to open /dev/random: %m");
+ r = -errno;
+ goto finish;
+ }
+
+ log_info("Generating seed...");
+ l = loop_read(fd, seed, seed_size, true);
+ if (l < 0 || (size_t) l != seed_size) {
+ log_error("Failed to read random seed: %s", strerror(EIO));
+ r = -EIO;
+ goto finish;
+ }
+
+ log_info("Generating key pair...");
+ FSPRG_GenMK(NULL, mpk, seed, seed_size, FSPRG_RECOMMENDED_SECPAR);
+
+ log_info("Generating sealing key...");
+ FSPRG_GenState0(state, mpk, seed, seed_size);
+
+ assert(arg_interval > 0);
+
+ n = now(CLOCK_REALTIME);
+ n /= arg_interval;
+
+ close_nointr_nofail(fd);
+ fd = mkostemp(k, O_WRONLY|O_CLOEXEC|O_NOCTTY);
+ if (fd < 0) {
+ log_error("Failed to open %s: %m", k);
+ r = -errno;
+ goto finish;
+ }
+
+ /* Enable secure remove, exclusion from dump, synchronous
+ * writing and in-place updating */
+ if (ioctl(fd, FS_IOC_GETFLAGS, &attr) < 0)
+ log_warning("FS_IOC_GETFLAGS failed: %m");
+
+ attr |= FS_SECRM_FL|FS_NODUMP_FL|FS_SYNC_FL|FS_NOCOW_FL;
+
+ if (ioctl(fd, FS_IOC_SETFLAGS, &attr) < 0)
+ log_warning("FS_IOC_SETFLAGS failed: %m");
+
+ zero(h);
+ memcpy(h.signature, "KSHHRHLP", 8);
+ h.machine_id = machine;
+ h.boot_id = boot;
+ h.header_size = htole64(sizeof(h));
+ h.start_usec = htole64(n * arg_interval);
+ h.interval_usec = htole64(arg_interval);
+ h.fsprg_secpar = htole16(FSPRG_RECOMMENDED_SECPAR);
+ h.fsprg_state_size = htole64(state_size);
+
+ l = loop_write(fd, &h, sizeof(h), false);
+ if (l < 0 || (size_t) l != sizeof(h)) {
+ log_error("Failed to write header: %s", strerror(EIO));
+ r = -EIO;
+ goto finish;
+ }
+
+ l = loop_write(fd, state, state_size, false);
+ if (l < 0 || (size_t) l != state_size) {
+ log_error("Failed to write state: %s", strerror(EIO));
+ r = -EIO;
+ goto finish;
+ }
+
+ if (link(k, p) < 0) {
+ log_error("Failed to link file: %m");
+ r = -errno;
+ goto finish;
+ }
+
+ if (on_tty()) {
+ fprintf(stderr,
+ "\n"
+ "The new key pair has been generated. The " ANSI_HIGHLIGHT_ON "secret sealing key" ANSI_HIGHLIGHT_OFF " has been written to\n"
+ "the following local file. This key file is automatically updated when the\n"
+ "sealing key is advanced. It should not be used on multiple hosts.\n"
+ "\n"
+ "\t%s\n"
+ "\n"
+ "Please write down the following " ANSI_HIGHLIGHT_ON "secret verification key" ANSI_HIGHLIGHT_OFF ". It should be stored\n"
+ "at a safe location and should not be saved locally on disk.\n"
+ "\n\t" ANSI_HIGHLIGHT_RED_ON, p);
+ fflush(stderr);
+ }
+ for (i = 0; i < seed_size; i++) {
+ if (i > 0 && i % 3 == 0)
+ putchar('-');
+ printf("%02x", ((uint8_t*) seed)[i]);
+ }
+
+ printf("/%llx-%llx\n", (unsigned long long) n, (unsigned long long) arg_interval);
+
+ if (on_tty()) {
+ char tsb[FORMAT_TIMESPAN_MAX], *hn;
+
+ fprintf(stderr,
+ ANSI_HIGHLIGHT_OFF "\n"
+ "The sealing key is automatically changed every %s.\n",
+ format_timespan(tsb, sizeof(tsb), arg_interval, 0));
+
+ hn = gethostname_malloc();
+
+ if (hn) {
+ hostname_cleanup(hn, false);
+ fprintf(stderr, "\nThe keys have been generated for host %s/" SD_ID128_FORMAT_STR ".\n", hn, SD_ID128_FORMAT_VAL(machine));
+ } else
+ fprintf(stderr, "\nThe keys have been generated for host " SD_ID128_FORMAT_STR ".\n", SD_ID128_FORMAT_VAL(machine));
+
+#ifdef HAVE_QRENCODE
+ /* If this is not an UTF-8 system don't print any QR codes */
+ if (is_locale_utf8()) {
+ fputs("\nTo transfer the verification key to your phone please scan the QR code below:\n\n", stderr);
+ print_qr_code(stderr, seed, seed_size, n, arg_interval, hn, machine);
+ }
+#endif
+ free(hn);
+ }
+
+ r = 0;
+
+finish:
+ if (fd >= 0)
+ close_nointr_nofail(fd);
+
+ if (k) {
+ unlink(k);
+ free(k);
+ }
+
+ free(p);
+
+ return r;
+#else
+ log_error("Forward-secure sealing not available.");
+ return -ENOTSUP;
+#endif
+}
+
+static int verify(sd_journal *j) {
+ int r = 0;
+ Iterator i;
+ JournalFile *f;
+
+ assert(j);
+
+ log_show_color(true);
+
+ HASHMAP_FOREACH(f, j->files, i) {
+ int k;
+ usec_t first, validated, last;
+
+#ifdef HAVE_GCRYPT
+ if (!arg_verify_key && JOURNAL_HEADER_SEALED(f->header))
+ log_notice("Journal file %s has sealing enabled but verification key has not been passed using --verify-key=.", f->path);
+#endif
+
+ k = journal_file_verify(f, arg_verify_key, &first, &validated, &last, true);
+ if (k == -EINVAL) {
+ /* If the key was invalid give up right-away. */
+ return k;
+ } else if (k < 0) {
+ log_warning("FAIL: %s (%s)", f->path, strerror(-k));
+ r = k;
+ } else {
+ char a[FORMAT_TIMESTAMP_MAX], b[FORMAT_TIMESTAMP_MAX], c[FORMAT_TIMESPAN_MAX];
+ log_info("PASS: %s", f->path);
+
+ if (arg_verify_key && JOURNAL_HEADER_SEALED(f->header)) {
+ if (validated > 0) {
+ log_info("=> Validated from %s to %s, final %s entries not sealed.",
+ format_timestamp(a, sizeof(a), first),
+ format_timestamp(b, sizeof(b), validated),
+ format_timespan(c, sizeof(c), last > validated ? last - validated : 0, 0));
+ } else if (last > 0)
+ log_info("=> No sealing yet, %s of entries not sealed.",
+ format_timespan(c, sizeof(c), last - first, 0));
+ else
+ log_info("=> No sealing yet, no entries in file.");
+ }
+ }
+ }
+
+ return r;
+}
+
+#ifdef HAVE_ACL
+static int access_check_var_log_journal(sd_journal *j) {
+ _cleanup_strv_free_ char **g = NULL;
+ bool have_access;
+ int r;
+
+ assert(j);
+
+ have_access = in_group("systemd-journal") > 0;
+
+ if (!have_access) {
+ /* Let's enumerate all groups from the default ACL of
+ * the directory, which generally should allow access
+ * to most journal files too */
+ r = search_acl_groups(&g, "/var/log/journal/", &have_access);
+ if (r < 0)
+ return r;
+ }
+
+ if (!have_access) {
+
+ if (strv_isempty(g))
+ log_notice("Hint: You are currently not seeing messages from other users and the system.\n"
+ " Users in the 'systemd-journal' group can see all messages. Pass -q to\n"
+ " turn off this notice.");
+ else {
+ _cleanup_free_ char *s = NULL;
+
+ r = strv_extend(&g, "systemd-journal");
+ if (r < 0)
+ return log_oom();
+
+ strv_sort(g);
+ strv_uniq(g);
+
+ s = strv_join(g, "', '");
+ if (!s)
+ return log_oom();
+
+ log_notice("Hint: You are currently not seeing messages from other users and the system.\n"
+ " Users in the groups '%s' can see all messages.\n"
+ " Pass -q to turn off this notice.", s);
+ }
+ }
+
+ return 0;
+}
+#endif
+
+static int access_check(sd_journal *j) {
+ Iterator it;
+ void *code;
+ int r = 0;
+
+ assert(j);
+
+ if (set_isempty(j->errors)) {
+ if (hashmap_isempty(j->files))
+ log_notice("No journal files were found.");
+ return 0;
+ }
+
+ if (set_contains(j->errors, INT_TO_PTR(-EACCES))) {
+#ifdef HAVE_ACL
+ /* If /var/log/journal doesn't even exist,
+ * unprivileged users have no access at all */
+ if (access("/var/log/journal", F_OK) < 0 &&
+ geteuid() != 0 &&
+ in_group("systemd-journal") <= 0) {
+ log_error("Unprivileged users cannot access messages, unless persistent log storage is\n"
+ "enabled. Users in the 'systemd-journal' group may always access messages.");
+ return -EACCES;
+ }
+
+ /* If /var/log/journal exists, try to pring a nice
+ notice if the user lacks access to it */
+ if (!arg_quiet && geteuid() != 0) {
+ r = access_check_var_log_journal(j);
+ if (r < 0)
+ return r;
+ }
+#else
+ if (geteuid() != 0 && in_group("systemd-journal") <= 0) {
+ log_error("Unprivileged users cannot access messages. Users in the 'systemd-journal' group\n"
+ "group may access messages.");
+ return -EACCES;
+ }
+#endif
+
+ if (hashmap_isempty(j->files)) {
+ log_error("No journal files were opened due to insufficient permissions.");
+ r = -EACCES;
+ }
+ }
+
+ SET_FOREACH(code, j->errors, it) {
+ int err;
+
+ err = -PTR_TO_INT(code);
+ assert(err > 0);
+
+ if (err != EACCES)
+ log_warning("Error was encountered while opening journal files: %s",
+ strerror(err));
+ }
+
+ return r;
+}
+
+int main(int argc, char *argv[]) {
+ int r;
+ _cleanup_journal_close_ sd_journal*j = NULL;
+ bool need_seek = false;
+ sd_id128_t previous_boot_id;
+ bool previous_boot_id_valid = false, first_line = true;
+ int n_shown = 0;
+
+ setlocale(LC_ALL, "");
+ log_parse_environment();
+ log_open();
+
+ r = parse_argv(argc, argv);
+ if (r <= 0)
+ goto finish;
+
+ signal(SIGWINCH, columns_lines_cache_reset);
+
+ if (arg_action == ACTION_NEW_ID128) {
+ r = generate_new_id128();
+ goto finish;
+ }
+
+ if (arg_action == ACTION_SETUP_KEYS) {
+ r = setup_keys();
+ goto finish;
+ }
+
+ if (arg_action == ACTION_UPDATE_CATALOG ||
+ arg_action == ACTION_LIST_CATALOG ||
+ arg_action == ACTION_DUMP_CATALOG) {
+
+ const char* database = CATALOG_DATABASE;
+ _cleanup_free_ char *copy = NULL;
+ if (arg_root) {
+ copy = strjoin(arg_root, "/", CATALOG_DATABASE, NULL);
+ if (!copy) {
+ r = log_oom();
+ goto finish;
+ }
+ path_kill_slashes(copy);
+ database = copy;
+ }
+
+ if (arg_action == ACTION_UPDATE_CATALOG) {
+ r = catalog_update(database, arg_root, catalog_file_dirs);
+ if (r < 0)
+ log_error("Failed to list catalog: %s", strerror(-r));
+ } else {
+ bool oneline = arg_action == ACTION_LIST_CATALOG;
+
+ if (optind < argc)
+ r = catalog_list_items(stdout, database,
+ oneline, argv + optind);
+ else
+ r = catalog_list(stdout, database, oneline);
+ if (r < 0)
+ log_error("Failed to list catalog: %s", strerror(-r));
+ }
+
+ goto finish;
+ }
+
+ if (arg_directory)
+ r = sd_journal_open_directory(&j, arg_directory, 0);
+ else
+ r = sd_journal_open(&j, arg_merge ? 0 : SD_JOURNAL_LOCAL_ONLY);
+ if (r < 0) {
+ log_error("Failed to open journal: %s", strerror(-r));
+ return EXIT_FAILURE;
+ }
+
+ r = access_check(j);
+ if (r < 0)
+ return EXIT_FAILURE;
+
+ if (arg_action == ACTION_VERIFY) {
+ r = verify(j);
+ goto finish;
+ }
+
+ if (arg_action == ACTION_PRINT_HEADER) {
+ journal_print_header(j);
+ return EXIT_SUCCESS;
+ }
+
+ if (arg_action == ACTION_DISK_USAGE) {
+ uint64_t bytes;
+ char sbytes[FORMAT_BYTES_MAX];
+
+ r = sd_journal_get_usage(j, &bytes);
+ if (r < 0)
+ return EXIT_FAILURE;
+
+ printf("Journals take up %s on disk.\n",
+ format_bytes(sbytes, sizeof(sbytes), bytes));
+ return EXIT_SUCCESS;
+ }
+
+ r = add_this_boot(j);
+ if (r < 0)
+ return EXIT_FAILURE;
+
+ r = add_units(j);
+ strv_free(arg_system_units);
+ strv_free(arg_user_units);
+
+ if (r < 0)
+ return EXIT_FAILURE;
+
+ r = add_priorities(j);
+ if (r < 0)
+ return EXIT_FAILURE;
+
+ r = add_matches(j, argv + optind);
+ if (r < 0)
+ return EXIT_FAILURE;
+
+ /* Opening the fd now means the first sd_journal_wait() will actually wait */
+ r = sd_journal_get_fd(j);
+ if (r < 0)
+ return EXIT_FAILURE;
+
+ if (arg_field) {
+ const void *data;
+ size_t size;
+
+ r = sd_journal_set_data_threshold(j, 0);
+ if (r < 0) {
+ log_error("Failed to unset data size threshold");
+ return EXIT_FAILURE;
+ }
+
+ r = sd_journal_query_unique(j, arg_field);
+ if (r < 0) {
+ log_error("Failed to query unique data objects: %s", strerror(-r));
+ return EXIT_FAILURE;
+ }
+
+ SD_JOURNAL_FOREACH_UNIQUE(j, data, size) {
+ const void *eq;
+
+ if (arg_lines >= 0 && n_shown >= arg_lines)
+ break;
+
+ eq = memchr(data, '=', size);
+ if (eq)
+ printf("%.*s\n", (int) (size - ((const uint8_t*) eq - (const uint8_t*) data + 1)), (const char*) eq + 1);
+ else
+ printf("%.*s\n", (int) size, (const char*) data);
+
+ n_shown ++;
+ }
+
+ return EXIT_SUCCESS;
+ }
+
+ if (arg_cursor) {
+ r = sd_journal_seek_cursor(j, arg_cursor);
+ if (r < 0) {
+ log_error("Failed to seek to cursor: %s", strerror(-r));
+ return EXIT_FAILURE;
+ }
+ if (!arg_reverse)
+ r = sd_journal_next(j);
+ else
+ r = sd_journal_previous(j);
+
+ } else if (arg_since_set && !arg_reverse) {
+ r = sd_journal_seek_realtime_usec(j, arg_since);
+ if (r < 0) {
+ log_error("Failed to seek to date: %s", strerror(-r));
+ return EXIT_FAILURE;
+ }
+ r = sd_journal_next(j);
+
+ } else if (arg_until_set && arg_reverse) {
+ r = sd_journal_seek_realtime_usec(j, arg_until);
+ if (r < 0) {
+ log_error("Failed to seek to date: %s", strerror(-r));
+ return EXIT_FAILURE;
+ }
+ r = sd_journal_previous(j);
+
+ } else if (arg_lines >= 0) {
+ r = sd_journal_seek_tail(j);
+ if (r < 0) {
+ log_error("Failed to seek to tail: %s", strerror(-r));
+ return EXIT_FAILURE;
+ }
+
+ r = sd_journal_previous_skip(j, arg_lines);
+
+ } else if (arg_reverse) {
+ r = sd_journal_seek_tail(j);
+ if (r < 0) {
+ log_error("Failed to seek to tail: %s", strerror(-r));
+ return EXIT_FAILURE;
+ }
+
+ r = sd_journal_previous(j);
+
+ } else {
+ r = sd_journal_seek_head(j);
+ if (r < 0) {
+ log_error("Failed to seek to head: %s", strerror(-r));
+ return EXIT_FAILURE;
+ }
+
+ r = sd_journal_next(j);
+ }
+
+ if (r < 0) {
+ log_error("Failed to iterate through journal: %s", strerror(-r));
+ return EXIT_FAILURE;
+ }
+
+ if (!arg_no_pager && !arg_follow)
+ pager_open(arg_pager_end);
+
+ if (!arg_quiet) {
+ usec_t start, end;
+ char start_buf[FORMAT_TIMESTAMP_MAX], end_buf[FORMAT_TIMESTAMP_MAX];
+
+ r = sd_journal_get_cutoff_realtime_usec(j, &start, &end);
+ if (r < 0) {
+ log_error("Failed to get cutoff: %s", strerror(-r));
+ goto finish;
+ }
+
+ if (r > 0) {
+ if (arg_follow)
+ printf("-- Logs begin at %s. --\n",
+ format_timestamp(start_buf, sizeof(start_buf), start));
+ else
+ printf("-- Logs begin at %s, end at %s. --\n",
+ format_timestamp(start_buf, sizeof(start_buf), start),
+ format_timestamp(end_buf, sizeof(end_buf), end));
+ }
+ }
+
+ for (;;) {
+ while (arg_lines < 0 || n_shown < arg_lines || (arg_follow && !first_line)) {
+ int flags;
+
+ if (need_seek) {
+ if (!arg_reverse)
+ r = sd_journal_next(j);
+ else
+ r = sd_journal_previous(j);
+ if (r < 0) {
+ log_error("Failed to iterate through journal: %s", strerror(-r));
+ goto finish;
+ }
+ }
+
+ if (r == 0)
+ break;
+
+ if (arg_until_set && !arg_reverse) {
+ usec_t usec;
+
+ r = sd_journal_get_realtime_usec(j, &usec);
+ if (r < 0) {
+ log_error("Failed to determine timestamp: %s", strerror(-r));
+ goto finish;
+ }
+ if (usec > arg_until)
+ goto finish;
+ }
+
+ if (arg_since_set && arg_reverse) {
+ usec_t usec;
+
+ r = sd_journal_get_realtime_usec(j, &usec);
+ if (r < 0) {
+ log_error("Failed to determine timestamp: %s", strerror(-r));
+ goto finish;
+ }
+ if (usec < arg_since)
+ goto finish;
+ }
+
+ if (!arg_merge) {
+ sd_id128_t boot_id;
+
+ r = sd_journal_get_monotonic_usec(j, NULL, &boot_id);
+ if (r >= 0) {
+ if (previous_boot_id_valid &&
+ !sd_id128_equal(boot_id, previous_boot_id))
+ printf(ANSI_HIGHLIGHT_ON "-- Reboot --" ANSI_HIGHLIGHT_OFF "\n");
+
+ previous_boot_id = boot_id;
+ previous_boot_id_valid = true;
+ }
+ }
+
+ flags =
+ arg_all * OUTPUT_SHOW_ALL |
+ (arg_full || !on_tty() || pager_have()) * OUTPUT_FULL_WIDTH |
+ on_tty() * OUTPUT_COLOR |
+ arg_catalog * OUTPUT_CATALOG;
+
+ r = output_journal(stdout, j, arg_output, 0, flags);
+ if (r < 0 || ferror(stdout))
+ goto finish;
+
+ need_seek = true;
+ n_shown++;
+ }
+
+ if (!arg_follow)
+ break;
+
+ r = sd_journal_wait(j, (uint64_t) -1);
+ if (r < 0) {
+ log_error("Couldn't wait for journal event: %s", strerror(-r));
+ goto finish;
+ }
+
+ first_line = false;
+ }
+
+finish:
+ pager_close();
+
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/src/journal/journald-console.c b/src/journal/journald-console.c
new file mode 100644
index 0000000000..be55f94878
--- /dev/null
+++ b/src/journal/journald-console.c
@@ -0,0 +1,86 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <fcntl.h>
+#include <unistd.h>
+#include <sys/socket.h>
+
+#include "journald-server.h"
+#include "journald-console.h"
+
+void server_forward_console(
+ Server *s,
+ int priority,
+ const char *identifier,
+ const char *message,
+ struct ucred *ucred) {
+
+ struct iovec iovec[4];
+ char header_pid[16];
+ int n = 0, fd;
+ char *ident_buf = NULL;
+ const char *tty;
+
+ assert(s);
+ assert(message);
+
+ if (LOG_PRI(priority) > s->max_level_console)
+ return;
+
+ /* First: identifier and PID */
+ if (ucred) {
+ if (!identifier) {
+ get_process_comm(ucred->pid, &ident_buf);
+ identifier = ident_buf;
+ }
+
+ snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
+ char_array_0(header_pid);
+
+ if (identifier)
+ IOVEC_SET_STRING(iovec[n++], identifier);
+
+ IOVEC_SET_STRING(iovec[n++], header_pid);
+ } else if (identifier) {
+ IOVEC_SET_STRING(iovec[n++], identifier);
+ IOVEC_SET_STRING(iovec[n++], ": ");
+ }
+
+ /* Third: message */
+ IOVEC_SET_STRING(iovec[n++], message);
+ IOVEC_SET_STRING(iovec[n++], "\n");
+
+ tty = s->tty_path ? s->tty_path : "/dev/console";
+
+ fd = open_terminal(tty, O_WRONLY|O_NOCTTY|O_CLOEXEC);
+ if (fd < 0) {
+ log_debug("Failed to open %s for logging: %s", tty, strerror(errno));
+ goto finish;
+ }
+
+ if (writev(fd, iovec, n) < 0)
+ log_debug("Failed to write to %s for logging: %s", tty, strerror(errno));
+
+ close_nointr_nofail(fd);
+
+finish:
+ free(ident_buf);
+}
diff --git a/src/journal/journald-console.h b/src/journal/journald-console.h
new file mode 100644
index 0000000000..aa8e6579ba
--- /dev/null
+++ b/src/journal/journald-console.h
@@ -0,0 +1,26 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "journald-server.h"
+
+void server_forward_console(Server *s, int priority, const char *identifier, const char *message, struct ucred *ucred);
diff --git a/src/journal/journald-gperf.gperf b/src/journal/journald-gperf.gperf
new file mode 100644
index 0000000000..2ecba3bd0e
--- /dev/null
+++ b/src/journal/journald-gperf.gperf
@@ -0,0 +1,40 @@
+%{
+#include <stddef.h>
+#include <sys/socket.h>
+#include "conf-parser.h"
+#include "journald-server.h"
+%}
+struct ConfigPerfItem;
+%null_strings
+%language=ANSI-C
+%define slot-name section_and_lvalue
+%define hash-function-name journald_gperf_hash
+%define lookup-function-name journald_gperf_lookup
+%readonly-tables
+%omit-struct-type
+%struct-type
+%includes
+%%
+Journal.Storage, config_parse_storage, 0, offsetof(Server, storage)
+Journal.Compress, config_parse_bool, 0, offsetof(Server, compress)
+Journal.Seal, config_parse_bool, 0, offsetof(Server, seal)
+Journal.SyncIntervalSec, config_parse_sec, 0, offsetof(Server, sync_interval_usec)
+Journal.RateLimitInterval, config_parse_sec, 0, offsetof(Server, rate_limit_interval)
+Journal.RateLimitBurst, config_parse_unsigned, 0, offsetof(Server, rate_limit_burst)
+Journal.SystemMaxUse, config_parse_bytes_off, 0, offsetof(Server, system_metrics.max_use)
+Journal.SystemMaxFileSize, config_parse_bytes_off, 0, offsetof(Server, system_metrics.max_size)
+Journal.SystemKeepFree, config_parse_bytes_off, 0, offsetof(Server, system_metrics.keep_free)
+Journal.RuntimeMaxUse, config_parse_bytes_off, 0, offsetof(Server, runtime_metrics.max_use)
+Journal.RuntimeMaxFileSize, config_parse_bytes_off, 0, offsetof(Server, runtime_metrics.max_size)
+Journal.RuntimeKeepFree, config_parse_bytes_off, 0, offsetof(Server, runtime_metrics.keep_free)
+Journal.MaxRetentionSec, config_parse_sec, 0, offsetof(Server, max_retention_usec)
+Journal.MaxFileSec, config_parse_sec, 0, offsetof(Server, max_file_usec)
+Journal.ForwardToSyslog, config_parse_bool, 0, offsetof(Server, forward_to_syslog)
+Journal.ForwardToKMsg, config_parse_bool, 0, offsetof(Server, forward_to_kmsg)
+Journal.ForwardToConsole, config_parse_bool, 0, offsetof(Server, forward_to_console)
+Journal.TTYPath, config_parse_path, 0, offsetof(Server, tty_path)
+Journal.MaxLevelStore, config_parse_level, 0, offsetof(Server, max_level_store)
+Journal.MaxLevelSyslog, config_parse_level, 0, offsetof(Server, max_level_syslog)
+Journal.MaxLevelKMsg, config_parse_level, 0, offsetof(Server, max_level_kmsg)
+Journal.MaxLevelConsole, config_parse_level, 0, offsetof(Server, max_level_console)
+Journal.SplitMode, config_parse_split_mode,0, offsetof(Server, split_mode)
diff --git a/src/journal/journald-kmsg.c b/src/journal/journald-kmsg.c
new file mode 100644
index 0000000000..2f536320f8
--- /dev/null
+++ b/src/journal/journald-kmsg.c
@@ -0,0 +1,440 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <unistd.h>
+#include <sys/epoll.h>
+#include <fcntl.h>
+#include <sys/mman.h>
+#include <sys/socket.h>
+
+#include <systemd/sd-messages.h>
+#include <libudev.h>
+
+#include "journald-server.h"
+#include "journald-kmsg.h"
+#include "journald-syslog.h"
+
+void server_forward_kmsg(
+ Server *s,
+ int priority,
+ const char *identifier,
+ const char *message,
+ struct ucred *ucred) {
+
+ struct iovec iovec[5];
+ char header_priority[6], header_pid[16];
+ int n = 0;
+ char *ident_buf = NULL;
+
+ assert(s);
+ assert(priority >= 0);
+ assert(priority <= 999);
+ assert(message);
+
+ if (_unlikely_(LOG_PRI(priority) > s->max_level_kmsg))
+ return;
+
+ if (_unlikely_(s->dev_kmsg_fd < 0))
+ return;
+
+ /* Never allow messages with kernel facility to be written to
+ * kmsg, regardless where the data comes from. */
+ priority = syslog_fixup_facility(priority);
+
+ /* First: priority field */
+ snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
+ char_array_0(header_priority);
+ IOVEC_SET_STRING(iovec[n++], header_priority);
+
+ /* Second: identifier and PID */
+ if (ucred) {
+ if (!identifier) {
+ get_process_comm(ucred->pid, &ident_buf);
+ identifier = ident_buf;
+ }
+
+ snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
+ char_array_0(header_pid);
+
+ if (identifier)
+ IOVEC_SET_STRING(iovec[n++], identifier);
+
+ IOVEC_SET_STRING(iovec[n++], header_pid);
+ } else if (identifier) {
+ IOVEC_SET_STRING(iovec[n++], identifier);
+ IOVEC_SET_STRING(iovec[n++], ": ");
+ }
+
+ /* Fourth: message */
+ IOVEC_SET_STRING(iovec[n++], message);
+ IOVEC_SET_STRING(iovec[n++], "\n");
+
+ if (writev(s->dev_kmsg_fd, iovec, n) < 0)
+ log_debug("Failed to write to /dev/kmsg for logging: %s", strerror(errno));
+
+ free(ident_buf);
+}
+
+static bool is_us(const char *pid) {
+ pid_t t;
+
+ assert(pid);
+
+ if (parse_pid(pid, &t) < 0)
+ return false;
+
+ return t == getpid();
+}
+
+static void dev_kmsg_record(Server *s, char *p, size_t l) {
+ struct iovec iovec[N_IOVEC_META_FIELDS + 7 + N_IOVEC_KERNEL_FIELDS + 2 + N_IOVEC_UDEV_FIELDS];
+ char *message = NULL, *syslog_priority = NULL, *syslog_pid = NULL, *syslog_facility = NULL, *syslog_identifier = NULL, *source_time = NULL;
+ int priority, r;
+ unsigned n = 0, z = 0, j;
+ unsigned long long usec;
+ char *identifier = NULL, *pid = NULL, *e, *f, *k;
+ uint64_t serial;
+ size_t pl;
+ char *kernel_device = NULL;
+
+ assert(s);
+ assert(p);
+
+ if (l <= 0)
+ return;
+
+ e = memchr(p, ',', l);
+ if (!e)
+ return;
+ *e = 0;
+
+ r = safe_atoi(p, &priority);
+ if (r < 0 || priority < 0 || priority > 999)
+ return;
+
+ if (s->forward_to_kmsg && (priority & LOG_FACMASK) != LOG_KERN)
+ return;
+
+ l -= (e - p) + 1;
+ p = e + 1;
+ e = memchr(p, ',', l);
+ if (!e)
+ return;
+ *e = 0;
+
+ r = safe_atou64(p, &serial);
+ if (r < 0)
+ return;
+
+ if (s->kernel_seqnum) {
+ /* We already read this one? */
+ if (serial < *s->kernel_seqnum)
+ return;
+
+ /* Did we lose any? */
+ if (serial > *s->kernel_seqnum)
+ server_driver_message(s, SD_MESSAGE_JOURNAL_MISSED, "Missed %llu kernel messages", (unsigned long long) serial - *s->kernel_seqnum - 1);
+
+ /* Make sure we never read this one again. Note that
+ * we always store the next message serial we expect
+ * here, simply because this makes handling the first
+ * message with serial 0 easy. */
+ *s->kernel_seqnum = serial + 1;
+ }
+
+ l -= (e - p) + 1;
+ p = e + 1;
+ f = memchr(p, ';', l);
+ if (!f)
+ return;
+ /* Kernel 3.6 has the flags field, kernel 3.5 lacks that */
+ e = memchr(p, ',', l);
+ if (!e || f < e)
+ e = f;
+ *e = 0;
+
+ r = safe_atollu(p, &usec);
+ if (r < 0)
+ return;
+
+ l -= (f - p) + 1;
+ p = f + 1;
+ e = memchr(p, '\n', l);
+ if (!e)
+ return;
+ *e = 0;
+
+ pl = e - p;
+ l -= (e - p) + 1;
+ k = e + 1;
+
+ for (j = 0; l > 0 && j < N_IOVEC_KERNEL_FIELDS; j++) {
+ char *m;
+ /* Meta data fields attached */
+
+ if (*k != ' ')
+ break;
+
+ k ++, l --;
+
+ e = memchr(k, '\n', l);
+ if (!e)
+ return;
+
+ *e = 0;
+
+ m = cunescape_length_with_prefix(k, e - k, "_KERNEL_");
+ if (!m)
+ break;
+
+ if (startswith(m, "_KERNEL_DEVICE="))
+ kernel_device = m + 15;
+
+ IOVEC_SET_STRING(iovec[n++], m);
+ z++;
+
+ l -= (e - k) + 1;
+ k = e + 1;
+ }
+
+ if (kernel_device) {
+ struct udev_device *ud;
+
+ ud = udev_device_new_from_device_id(s->udev, kernel_device);
+ if (ud) {
+ const char *g;
+ struct udev_list_entry *ll;
+ char *b;
+
+ g = udev_device_get_devnode(ud);
+ if (g) {
+ b = strappend("_UDEV_DEVNODE=", g);
+ if (b) {
+ IOVEC_SET_STRING(iovec[n++], b);
+ z++;
+ }
+ }
+
+ g = udev_device_get_sysname(ud);
+ if (g) {
+ b = strappend("_UDEV_SYSNAME=", g);
+ if (b) {
+ IOVEC_SET_STRING(iovec[n++], b);
+ z++;
+ }
+ }
+
+ j = 0;
+ ll = udev_device_get_devlinks_list_entry(ud);
+ udev_list_entry_foreach(ll, ll) {
+
+ if (j > N_IOVEC_UDEV_FIELDS)
+ break;
+
+ g = udev_list_entry_get_name(ll);
+ if (g) {
+ b = strappend("_UDEV_DEVLINK=", g);
+ if (b) {
+ IOVEC_SET_STRING(iovec[n++], b);
+ z++;
+ }
+ }
+
+ j++;
+ }
+
+ udev_device_unref(ud);
+ }
+ }
+
+ if (asprintf(&source_time, "_SOURCE_MONOTONIC_TIMESTAMP=%llu", usec) >= 0)
+ IOVEC_SET_STRING(iovec[n++], source_time);
+
+ IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=kernel");
+
+ if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
+ IOVEC_SET_STRING(iovec[n++], syslog_priority);
+
+ if ((priority & LOG_FACMASK) == LOG_KERN)
+ IOVEC_SET_STRING(iovec[n++], "SYSLOG_IDENTIFIER=kernel");
+ else {
+ pl -= syslog_parse_identifier((const char**) &p, &identifier, &pid);
+
+ /* Avoid any messages we generated ourselves via
+ * log_info() and friends. */
+ if (pid && is_us(pid))
+ goto finish;
+
+ if (identifier) {
+ syslog_identifier = strappend("SYSLOG_IDENTIFIER=", identifier);
+ if (syslog_identifier)
+ IOVEC_SET_STRING(iovec[n++], syslog_identifier);
+ }
+
+ if (pid) {
+ syslog_pid = strappend("SYSLOG_PID=", pid);
+ if (syslog_pid)
+ IOVEC_SET_STRING(iovec[n++], syslog_pid);
+ }
+
+ if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
+ IOVEC_SET_STRING(iovec[n++], syslog_facility);
+ }
+
+ message = cunescape_length_with_prefix(p, pl, "MESSAGE=");
+ if (message)
+ IOVEC_SET_STRING(iovec[n++], message);
+
+ server_dispatch_message(s, iovec, n, ELEMENTSOF(iovec), NULL, NULL, NULL, 0, NULL, priority);
+
+finish:
+ for (j = 0; j < z; j++)
+ free(iovec[j].iov_base);
+
+ free(message);
+ free(syslog_priority);
+ free(syslog_identifier);
+ free(syslog_pid);
+ free(syslog_facility);
+ free(source_time);
+ free(identifier);
+ free(pid);
+}
+
+int server_read_dev_kmsg(Server *s) {
+ char buffer[8192+1]; /* the kernel-side limit per record is 8K currently */
+ ssize_t l;
+
+ assert(s);
+ assert(s->dev_kmsg_fd >= 0);
+
+ l = read(s->dev_kmsg_fd, buffer, sizeof(buffer) - 1);
+ if (l == 0)
+ return 0;
+ if (l < 0) {
+ /* Old kernels who don't allow reading from /dev/kmsg
+ * return EINVAL when we try. So handle this cleanly,
+ * but don' try to ever read from it again. */
+ if (errno == EINVAL) {
+ epoll_ctl(s->epoll_fd, EPOLL_CTL_DEL, s->dev_kmsg_fd, NULL);
+ return 0;
+ }
+
+ if (errno == EAGAIN || errno == EINTR || errno == EPIPE)
+ return 0;
+
+ log_error("Failed to read from kernel: %m");
+ return -errno;
+ }
+
+ dev_kmsg_record(s, buffer, l);
+ return 1;
+}
+
+int server_flush_dev_kmsg(Server *s) {
+ int r;
+
+ assert(s);
+
+ if (s->dev_kmsg_fd < 0)
+ return 0;
+
+ if (!s->dev_kmsg_readable)
+ return 0;
+
+ log_debug("Flushing /dev/kmsg...");
+
+ for (;;) {
+ r = server_read_dev_kmsg(s);
+ if (r < 0)
+ return r;
+
+ if (r == 0)
+ break;
+ }
+
+ return 0;
+}
+
+int server_open_dev_kmsg(Server *s) {
+ struct epoll_event ev;
+
+ assert(s);
+
+ s->dev_kmsg_fd = open("/dev/kmsg", O_RDWR|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
+ if (s->dev_kmsg_fd < 0) {
+ log_warning("Failed to open /dev/kmsg, ignoring: %m");
+ return 0;
+ }
+
+ zero(ev);
+ ev.events = EPOLLIN;
+ ev.data.fd = s->dev_kmsg_fd;
+ if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->dev_kmsg_fd, &ev) < 0) {
+
+ /* This will fail with EPERM on older kernels where
+ * /dev/kmsg is not readable. */
+ if (errno == EPERM)
+ return 0;
+
+ log_error("Failed to add /dev/kmsg fd to epoll object: %m");
+ return -errno;
+ }
+
+ s->dev_kmsg_readable = true;
+
+ return 0;
+}
+
+int server_open_kernel_seqnum(Server *s) {
+ int fd;
+ uint64_t *p;
+
+ assert(s);
+
+ /* We store the seqnum we last read in an mmaped file. That
+ * way we can just use it like a variable, but it is
+ * persistent and automatically flushed at reboot. */
+
+ fd = open("/run/systemd/journal/kernel-seqnum", O_RDWR|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0644);
+ if (fd < 0) {
+ log_error("Failed to open /run/systemd/journal/kernel-seqnum, ignoring: %m");
+ return 0;
+ }
+
+ if (posix_fallocate(fd, 0, sizeof(uint64_t)) < 0) {
+ log_error("Failed to allocate sequential number file, ignoring: %m");
+ close_nointr_nofail(fd);
+ return 0;
+ }
+
+ p = mmap(NULL, sizeof(uint64_t), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
+ if (p == MAP_FAILED) {
+ log_error("Failed to map sequential number file, ignoring: %m");
+ close_nointr_nofail(fd);
+ return 0;
+ }
+
+ close_nointr_nofail(fd);
+ s->kernel_seqnum = p;
+
+ return 0;
+}
diff --git a/src/journal/journald-kmsg.h b/src/journal/journald-kmsg.h
new file mode 100644
index 0000000000..f287161329
--- /dev/null
+++ b/src/journal/journald-kmsg.h
@@ -0,0 +1,32 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "journald-server.h"
+
+int server_open_dev_kmsg(Server *s);
+int server_read_dev_kmsg(Server *s);
+int server_flush_dev_kmsg(Server *s);
+
+void server_forward_kmsg(Server *s, int priority, const char *identifier, const char *message, struct ucred *ucred);
+
+int server_open_kernel_seqnum(Server *s);
diff --git a/src/journal/journald-native.c b/src/journal/journald-native.c
new file mode 100644
index 0000000000..f878dfc911
--- /dev/null
+++ b/src/journal/journald-native.c
@@ -0,0 +1,423 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <unistd.h>
+#include <stddef.h>
+#include <sys/epoll.h>
+
+#include "socket-util.h"
+#include "path-util.h"
+#include "journald-server.h"
+#include "journald-native.h"
+#include "journald-kmsg.h"
+#include "journald-console.h"
+#include "journald-syslog.h"
+
+/* Make sure not to make this smaller than the maximum coredump
+ * size. See COREDUMP_MAX in coredump.c */
+#define ENTRY_SIZE_MAX (1024*1024*768)
+#define DATA_SIZE_MAX (1024*1024*768)
+
+static bool valid_user_field(const char *p, size_t l) {
+ const char *a;
+
+ /* We kinda enforce POSIX syntax recommendations for
+ environment variables here, but make a couple of additional
+ requirements.
+
+ http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html */
+
+ /* No empty field names */
+ if (l <= 0)
+ return false;
+
+ /* Don't allow names longer than 64 chars */
+ if (l > 64)
+ return false;
+
+ /* Variables starting with an underscore are protected */
+ if (p[0] == '_')
+ return false;
+
+ /* Don't allow digits as first character */
+ if (p[0] >= '0' && p[0] <= '9')
+ return false;
+
+ /* Only allow A-Z0-9 and '_' */
+ for (a = p; a < p + l; a++)
+ if (!((*a >= 'A' && *a <= 'Z') ||
+ (*a >= '0' && *a <= '9') ||
+ *a == '_'))
+ return false;
+
+ return true;
+}
+
+void server_process_native_message(
+ Server *s,
+ const void *buffer, size_t buffer_size,
+ struct ucred *ucred,
+ struct timeval *tv,
+ const char *label, size_t label_len) {
+
+ struct iovec *iovec = NULL;
+ unsigned n = 0, m = 0, j, tn = (unsigned) -1;
+ const char *p;
+ size_t remaining;
+ int priority = LOG_INFO;
+ char *identifier = NULL, *message = NULL;
+
+ assert(s);
+ assert(buffer || buffer_size == 0);
+
+ p = buffer;
+ remaining = buffer_size;
+
+ while (remaining > 0) {
+ const char *e, *q;
+
+ e = memchr(p, '\n', remaining);
+
+ if (!e) {
+ /* Trailing noise, let's ignore it, and flush what we collected */
+ log_debug("Received message with trailing noise, ignoring.");
+ break;
+ }
+
+ if (e == p) {
+ /* Entry separator */
+ server_dispatch_message(s, iovec, n, m, ucred, tv, label, label_len, NULL, priority);
+ n = 0;
+ priority = LOG_INFO;
+
+ p++;
+ remaining--;
+ continue;
+ }
+
+ if (*p == '.' || *p == '#') {
+ /* Ignore control commands for now, and
+ * comments too. */
+ remaining -= (e - p) + 1;
+ p = e + 1;
+ continue;
+ }
+
+ /* A property follows */
+
+ /* n received properties, +1 for _TRANSPORT */
+ if (n + 1 + N_IOVEC_META_FIELDS >= m) {
+ struct iovec *c;
+ unsigned u;
+
+ u = MAX((n + 1 + N_IOVEC_META_FIELDS) * 2U, 4U);
+ c = realloc(iovec, u * sizeof(struct iovec));
+ if (!c) {
+ log_oom();
+ break;
+ }
+
+ iovec = c;
+ m = u;
+ }
+
+ q = memchr(p, '=', e - p);
+ if (q) {
+ if (valid_user_field(p, q - p)) {
+ size_t l;
+
+ l = e - p;
+
+ /* If the field name starts with an
+ * underscore, skip the variable,
+ * since that indidates a trusted
+ * field */
+ iovec[n].iov_base = (char*) p;
+ iovec[n].iov_len = l;
+ n++;
+
+ /* We need to determine the priority
+ * of this entry for the rate limiting
+ * logic */
+ if (l == 10 &&
+ memcmp(p, "PRIORITY=", 9) == 0 &&
+ p[9] >= '0' && p[9] <= '9')
+ priority = (priority & LOG_FACMASK) | (p[9] - '0');
+
+ else if (l == 17 &&
+ memcmp(p, "SYSLOG_FACILITY=", 16) == 0 &&
+ p[16] >= '0' && p[16] <= '9')
+ priority = (priority & LOG_PRIMASK) | ((p[16] - '0') << 3);
+
+ else if (l == 18 &&
+ memcmp(p, "SYSLOG_FACILITY=", 16) == 0 &&
+ p[16] >= '0' && p[16] <= '9' &&
+ p[17] >= '0' && p[17] <= '9')
+ priority = (priority & LOG_PRIMASK) | (((p[16] - '0')*10 + (p[17] - '0')) << 3);
+
+ else if (l >= 19 &&
+ memcmp(p, "SYSLOG_IDENTIFIER=", 18) == 0) {
+ char *t;
+
+ t = strndup(p + 18, l - 18);
+ if (t) {
+ free(identifier);
+ identifier = t;
+ }
+ } else if (l >= 8 &&
+ memcmp(p, "MESSAGE=", 8) == 0) {
+ char *t;
+
+ t = strndup(p + 8, l - 8);
+ if (t) {
+ free(message);
+ message = t;
+ }
+ }
+ }
+
+ remaining -= (e - p) + 1;
+ p = e + 1;
+ continue;
+ } else {
+ le64_t l_le;
+ uint64_t l;
+ char *k;
+
+ if (remaining < e - p + 1 + sizeof(uint64_t) + 1) {
+ log_debug("Failed to parse message, ignoring.");
+ break;
+ }
+
+ memcpy(&l_le, e + 1, sizeof(uint64_t));
+ l = le64toh(l_le);
+
+ if (l > DATA_SIZE_MAX) {
+ log_debug("Received binary data block too large, ignoring.");
+ break;
+ }
+
+ if ((uint64_t) remaining < e - p + 1 + sizeof(uint64_t) + l + 1 ||
+ e[1+sizeof(uint64_t)+l] != '\n') {
+ log_debug("Failed to parse message, ignoring.");
+ break;
+ }
+
+ k = malloc((e - p) + 1 + l);
+ if (!k) {
+ log_oom();
+ break;
+ }
+
+ memcpy(k, p, e - p);
+ k[e - p] = '=';
+ memcpy(k + (e - p) + 1, e + 1 + sizeof(uint64_t), l);
+
+ if (valid_user_field(p, e - p)) {
+ iovec[n].iov_base = k;
+ iovec[n].iov_len = (e - p) + 1 + l;
+ n++;
+ } else
+ free(k);
+
+ remaining -= (e - p) + 1 + sizeof(uint64_t) + l + 1;
+ p = e + 1 + sizeof(uint64_t) + l + 1;
+ }
+ }
+
+ if (n <= 0)
+ goto finish;
+
+ tn = n++;
+ IOVEC_SET_STRING(iovec[tn], "_TRANSPORT=journal");
+
+ if (message) {
+ if (s->forward_to_syslog)
+ server_forward_syslog(s, priority, identifier, message, ucred, tv);
+
+ if (s->forward_to_kmsg)
+ server_forward_kmsg(s, priority, identifier, message, ucred);
+
+ if (s->forward_to_console)
+ server_forward_console(s, priority, identifier, message, ucred);
+ }
+
+ server_dispatch_message(s, iovec, n, m, ucred, tv, label, label_len, NULL, priority);
+
+finish:
+ for (j = 0; j < n; j++) {
+ if (j == tn)
+ continue;
+
+ if (iovec[j].iov_base < buffer ||
+ (const uint8_t*) iovec[j].iov_base >= (const uint8_t*) buffer + buffer_size)
+ free(iovec[j].iov_base);
+ }
+
+ free(iovec);
+ free(identifier);
+ free(message);
+}
+
+void server_process_native_file(
+ Server *s,
+ int fd,
+ struct ucred *ucred,
+ struct timeval *tv,
+ const char *label, size_t label_len) {
+
+ struct stat st;
+ _cleanup_free_ void *p = NULL;
+ ssize_t n;
+ int r;
+
+ assert(s);
+ assert(fd >= 0);
+
+ if (!ucred || ucred->uid != 0) {
+ _cleanup_free_ char *sl = NULL, *k = NULL;
+ const char *e;
+
+ if (asprintf(&sl, "/proc/self/fd/%i", fd) < 0) {
+ log_oom();
+ return;
+ }
+
+ r = readlink_malloc(sl, &k);
+ if (r < 0) {
+ log_error("readlink(%s) failed: %m", sl);
+ return;
+ }
+
+ e = path_startswith(k, "/dev/shm/");
+ if (!e)
+ e = path_startswith(k, "/tmp/");
+ if (!e)
+ e = path_startswith(k, "/var/tmp/");
+ if (!e) {
+ log_error("Received file outside of allowed directories. Refusing.");
+ return;
+ }
+
+ if (!filename_is_safe(e)) {
+ log_error("Received file in subdirectory of allowed directories. Refusing.");
+ return;
+ }
+ }
+
+ /* Data is in the passed file, since it didn't fit in a
+ * datagram. We can't map the file here, since clients might
+ * then truncate it and trigger a SIGBUS for us. So let's
+ * stupidly read it */
+
+ if (fstat(fd, &st) < 0) {
+ log_error("Failed to stat passed file, ignoring: %m");
+ return;
+ }
+
+ if (!S_ISREG(st.st_mode)) {
+ log_error("File passed is not regular. Ignoring.");
+ return;
+ }
+
+ if (st.st_size <= 0)
+ return;
+
+ if (st.st_size > ENTRY_SIZE_MAX) {
+ log_error("File passed too large. Ignoring.");
+ return;
+ }
+
+ p = malloc(st.st_size);
+ if (!p) {
+ log_oom();
+ return;
+ }
+
+ n = pread(fd, p, st.st_size, 0);
+ if (n < 0)
+ log_error("Failed to read file, ignoring: %s", strerror(-n));
+ else if (n > 0)
+ server_process_native_message(s, p, n, ucred, tv, label, label_len);
+}
+
+int server_open_native_socket(Server*s) {
+ union sockaddr_union sa;
+ int one, r;
+ struct epoll_event ev;
+
+ assert(s);
+
+ if (s->native_fd < 0) {
+
+ s->native_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
+ if (s->native_fd < 0) {
+ log_error("socket() failed: %m");
+ return -errno;
+ }
+
+ zero(sa);
+ sa.un.sun_family = AF_UNIX;
+ strncpy(sa.un.sun_path, "/run/systemd/journal/socket", sizeof(sa.un.sun_path));
+
+ unlink(sa.un.sun_path);
+
+ r = bind(s->native_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
+ if (r < 0) {
+ log_error("bind() failed: %m");
+ return -errno;
+ }
+
+ chmod(sa.un.sun_path, 0666);
+ } else
+ fd_nonblock(s->native_fd, 1);
+
+ one = 1;
+ r = setsockopt(s->native_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
+ if (r < 0) {
+ log_error("SO_PASSCRED failed: %m");
+ return -errno;
+ }
+
+#ifdef HAVE_SELINUX
+ one = 1;
+ r = setsockopt(s->native_fd, SOL_SOCKET, SO_PASSSEC, &one, sizeof(one));
+ if (r < 0)
+ log_warning("SO_PASSSEC failed: %m");
+#endif
+
+ one = 1;
+ r = setsockopt(s->native_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
+ if (r < 0) {
+ log_error("SO_TIMESTAMP failed: %m");
+ return -errno;
+ }
+
+ zero(ev);
+ ev.events = EPOLLIN;
+ ev.data.fd = s->native_fd;
+ if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->native_fd, &ev) < 0) {
+ log_error("Failed to add native server fd to epoll object: %m");
+ return -errno;
+ }
+
+ return 0;
+}
diff --git a/src/journal/journald-native.h b/src/journal/journald-native.h
new file mode 100644
index 0000000000..16c09f523e
--- /dev/null
+++ b/src/journal/journald-native.h
@@ -0,0 +1,30 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "journald-server.h"
+
+void server_process_native_message(Server *s, const void *buffer, size_t buffer_size, struct ucred *ucred, struct timeval *tv, const char *label, size_t label_len);
+
+void server_process_native_file(Server *s, int fd, struct ucred *ucred, struct timeval *tv, const char *label, size_t label_len);
+
+int server_open_native_socket(Server*s);
diff --git a/src/journal/journald-rate-limit.c b/src/journal/journald-rate-limit.c
new file mode 100644
index 0000000000..32e35a926d
--- /dev/null
+++ b/src/journal/journald-rate-limit.c
@@ -0,0 +1,260 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <string.h>
+#include <errno.h>
+
+#include "journald-rate-limit.h"
+#include "list.h"
+#include "util.h"
+#include "hashmap.h"
+
+#define POOLS_MAX 5
+#define BUCKETS_MAX 127
+#define GROUPS_MAX 2047
+
+static const int priority_map[] = {
+ [LOG_EMERG] = 0,
+ [LOG_ALERT] = 0,
+ [LOG_CRIT] = 0,
+ [LOG_ERR] = 1,
+ [LOG_WARNING] = 2,
+ [LOG_NOTICE] = 3,
+ [LOG_INFO] = 3,
+ [LOG_DEBUG] = 4
+};
+
+typedef struct JournalRateLimitPool JournalRateLimitPool;
+typedef struct JournalRateLimitGroup JournalRateLimitGroup;
+
+struct JournalRateLimitPool {
+ usec_t begin;
+ unsigned num;
+ unsigned suppressed;
+};
+
+struct JournalRateLimitGroup {
+ JournalRateLimit *parent;
+
+ char *id;
+ JournalRateLimitPool pools[POOLS_MAX];
+ unsigned hash;
+
+ LIST_FIELDS(JournalRateLimitGroup, bucket);
+ LIST_FIELDS(JournalRateLimitGroup, lru);
+};
+
+struct JournalRateLimit {
+ usec_t interval;
+ unsigned burst;
+
+ JournalRateLimitGroup* buckets[BUCKETS_MAX];
+ JournalRateLimitGroup *lru, *lru_tail;
+
+ unsigned n_groups;
+};
+
+JournalRateLimit *journal_rate_limit_new(usec_t interval, unsigned burst) {
+ JournalRateLimit *r;
+
+ assert(interval > 0 || burst == 0);
+
+ r = new0(JournalRateLimit, 1);
+ if (!r)
+ return NULL;
+
+ r->interval = interval;
+ r->burst = burst;
+
+ return r;
+}
+
+static void journal_rate_limit_group_free(JournalRateLimitGroup *g) {
+ assert(g);
+
+ if (g->parent) {
+ assert(g->parent->n_groups > 0);
+
+ if (g->parent->lru_tail == g)
+ g->parent->lru_tail = g->lru_prev;
+
+ LIST_REMOVE(JournalRateLimitGroup, lru, g->parent->lru, g);
+ LIST_REMOVE(JournalRateLimitGroup, bucket, g->parent->buckets[g->hash % BUCKETS_MAX], g);
+
+ g->parent->n_groups --;
+ }
+
+ free(g->id);
+ free(g);
+}
+
+void journal_rate_limit_free(JournalRateLimit *r) {
+ assert(r);
+
+ while (r->lru)
+ journal_rate_limit_group_free(r->lru);
+
+ free(r);
+}
+
+_pure_ static bool journal_rate_limit_group_expired(JournalRateLimitGroup *g, usec_t ts) {
+ unsigned i;
+
+ assert(g);
+
+ for (i = 0; i < POOLS_MAX; i++)
+ if (g->pools[i].begin + g->parent->interval >= ts)
+ return false;
+
+ return true;
+}
+
+static void journal_rate_limit_vacuum(JournalRateLimit *r, usec_t ts) {
+ assert(r);
+
+ /* Makes room for at least one new item, but drop all
+ * expored items too. */
+
+ while (r->n_groups >= GROUPS_MAX ||
+ (r->lru_tail && journal_rate_limit_group_expired(r->lru_tail, ts)))
+ journal_rate_limit_group_free(r->lru_tail);
+}
+
+static JournalRateLimitGroup* journal_rate_limit_group_new(JournalRateLimit *r, const char *id, usec_t ts) {
+ JournalRateLimitGroup *g;
+
+ assert(r);
+ assert(id);
+
+ g = new0(JournalRateLimitGroup, 1);
+ if (!g)
+ return NULL;
+
+ g->id = strdup(id);
+ if (!g->id)
+ goto fail;
+
+ g->hash = string_hash_func(g->id);
+
+ journal_rate_limit_vacuum(r, ts);
+
+ LIST_PREPEND(JournalRateLimitGroup, bucket, r->buckets[g->hash % BUCKETS_MAX], g);
+ LIST_PREPEND(JournalRateLimitGroup, lru, r->lru, g);
+ if (!g->lru_next)
+ r->lru_tail = g;
+ r->n_groups ++;
+
+ g->parent = r;
+ return g;
+
+fail:
+ journal_rate_limit_group_free(g);
+ return NULL;
+}
+
+static unsigned burst_modulate(unsigned burst, uint64_t available) {
+ unsigned k;
+
+ /* Modulates the burst rate a bit with the amount of available
+ * disk space */
+
+ k = u64log2(available);
+
+ /* 1MB */
+ if (k <= 20)
+ return burst;
+
+ burst = (burst * (k-20)) / 4;
+
+ /*
+ * Example:
+ *
+ * <= 1MB = rate * 1
+ * 16MB = rate * 2
+ * 256MB = rate * 3
+ * 4GB = rate * 4
+ * 64GB = rate * 5
+ * 1TB = rate * 6
+ */
+
+ return burst;
+}
+
+int journal_rate_limit_test(JournalRateLimit *r, const char *id, int priority, uint64_t available) {
+ unsigned h;
+ JournalRateLimitGroup *g;
+ JournalRateLimitPool *p;
+ unsigned burst;
+ usec_t ts;
+
+ assert(id);
+
+ if (!r)
+ return 1;
+
+ if (r->interval == 0 || r->burst == 0)
+ return 1;
+
+ burst = burst_modulate(r->burst, available);
+
+ ts = now(CLOCK_MONOTONIC);
+
+ h = string_hash_func(id);
+ g = r->buckets[h % BUCKETS_MAX];
+
+ LIST_FOREACH(bucket, g, g)
+ if (streq(g->id, id))
+ break;
+
+ if (!g) {
+ g = journal_rate_limit_group_new(r, id, ts);
+ if (!g)
+ return -ENOMEM;
+ }
+
+ p = &g->pools[priority_map[priority]];
+
+ if (p->begin <= 0) {
+ p->suppressed = 0;
+ p->num = 1;
+ p->begin = ts;
+ return 1;
+ }
+
+ if (p->begin + r->interval < ts) {
+ unsigned s;
+
+ s = p->suppressed;
+ p->suppressed = 0;
+ p->num = 1;
+ p->begin = ts;
+
+ return 1 + s;
+ }
+
+ if (p->num <= burst) {
+ p->num++;
+ return 1;
+ }
+
+ p->suppressed++;
+ return 0;
+}
diff --git a/src/journal/journald-rate-limit.h b/src/journal/journald-rate-limit.h
new file mode 100644
index 0000000000..648ab22786
--- /dev/null
+++ b/src/journal/journald-rate-limit.h
@@ -0,0 +1,31 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "macro.h"
+#include "util.h"
+
+typedef struct JournalRateLimit JournalRateLimit;
+
+JournalRateLimit *journal_rate_limit_new(usec_t interval, unsigned burst);
+void journal_rate_limit_free(JournalRateLimit *r);
+int journal_rate_limit_test(JournalRateLimit *r, const char *id, int priority, uint64_t available);
diff --git a/src/journal/journald-server.c b/src/journal/journald-server.c
new file mode 100644
index 0000000000..cc52b8a5c9
--- /dev/null
+++ b/src/journal/journald-server.c
@@ -0,0 +1,1556 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/signalfd.h>
+#include <sys/ioctl.h>
+#include <linux/sockios.h>
+#include <sys/statvfs.h>
+#include <sys/mman.h>
+#include <sys/timerfd.h>
+
+#include <libudev.h>
+#include <systemd/sd-journal.h>
+#include <systemd/sd-messages.h>
+#include <systemd/sd-daemon.h>
+
+#include "fileio.h"
+#include "mkdir.h"
+#include "hashmap.h"
+#include "journal-file.h"
+#include "socket-util.h"
+#include "cgroup-util.h"
+#include "list.h"
+#include "virt.h"
+#include "missing.h"
+#include "conf-parser.h"
+#include "journal-internal.h"
+#include "journal-vacuum.h"
+#include "journal-authenticate.h"
+#include "journald-server.h"
+#include "journald-rate-limit.h"
+#include "journald-kmsg.h"
+#include "journald-syslog.h"
+#include "journald-stream.h"
+#include "journald-console.h"
+#include "journald-native.h"
+
+#ifdef HAVE_ACL
+#include <sys/acl.h>
+#include <acl/libacl.h>
+#include "acl-util.h"
+#endif
+
+#ifdef HAVE_SELINUX
+#include <selinux/selinux.h>
+#endif
+
+#define USER_JOURNALS_MAX 1024
+
+#define DEFAULT_SYNC_INTERVAL_USEC (5*USEC_PER_MINUTE)
+#define DEFAULT_RATE_LIMIT_INTERVAL (10*USEC_PER_SEC)
+#define DEFAULT_RATE_LIMIT_BURST 200
+
+#define RECHECK_AVAILABLE_SPACE_USEC (30*USEC_PER_SEC)
+
+static const char* const storage_table[] = {
+ [STORAGE_AUTO] = "auto",
+ [STORAGE_VOLATILE] = "volatile",
+ [STORAGE_PERSISTENT] = "persistent",
+ [STORAGE_NONE] = "none"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(storage, Storage);
+DEFINE_CONFIG_PARSE_ENUM(config_parse_storage, storage, Storage, "Failed to parse storage setting");
+
+static const char* const split_mode_table[] = {
+ [SPLIT_NONE] = "none",
+ [SPLIT_UID] = "uid",
+ [SPLIT_LOGIN] = "login"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(split_mode, SplitMode);
+DEFINE_CONFIG_PARSE_ENUM(config_parse_split_mode, split_mode, SplitMode, "Failed to parse split mode setting");
+
+static uint64_t available_space(Server *s) {
+ char ids[33];
+ _cleanup_free_ char *p = NULL;
+ const char *f;
+ sd_id128_t machine;
+ struct statvfs ss;
+ uint64_t sum = 0, avail = 0, ss_avail = 0;
+ int r;
+ _cleanup_closedir_ DIR *d = NULL;
+ usec_t ts;
+ JournalMetrics *m;
+
+ ts = now(CLOCK_MONOTONIC);
+
+ if (s->cached_available_space_timestamp + RECHECK_AVAILABLE_SPACE_USEC > ts)
+ return s->cached_available_space;
+
+ r = sd_id128_get_machine(&machine);
+ if (r < 0)
+ return 0;
+
+ if (s->system_journal) {
+ f = "/var/log/journal/";
+ m = &s->system_metrics;
+ } else {
+ f = "/run/log/journal/";
+ m = &s->runtime_metrics;
+ }
+
+ assert(m);
+
+ p = strappend(f, sd_id128_to_string(machine, ids));
+ if (!p)
+ return 0;
+
+ d = opendir(p);
+ if (!d)
+ return 0;
+
+ if (fstatvfs(dirfd(d), &ss) < 0)
+ return 0;
+
+ for (;;) {
+ struct stat st;
+ struct dirent *de;
+ union dirent_storage buf;
+
+ r = readdir_r(d, &buf.de, &de);
+ if (r != 0)
+ break;
+
+ if (!de)
+ break;
+
+ if (!endswith(de->d_name, ".journal") &&
+ !endswith(de->d_name, ".journal~"))
+ continue;
+
+ if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
+ continue;
+
+ if (!S_ISREG(st.st_mode))
+ continue;
+
+ sum += (uint64_t) st.st_blocks * 512UL;
+ }
+
+ avail = sum >= m->max_use ? 0 : m->max_use - sum;
+
+ ss_avail = ss.f_bsize * ss.f_bavail;
+
+ ss_avail = ss_avail < m->keep_free ? 0 : ss_avail - m->keep_free;
+
+ if (ss_avail < avail)
+ avail = ss_avail;
+
+ s->cached_available_space = avail;
+ s->cached_available_space_timestamp = ts;
+
+ return avail;
+}
+
+static void server_read_file_gid(Server *s) {
+ const char *g = "systemd-journal";
+ int r;
+
+ assert(s);
+
+ if (s->file_gid_valid)
+ return;
+
+ r = get_group_creds(&g, &s->file_gid);
+ if (r < 0)
+ log_warning("Failed to resolve '%s' group: %s", g, strerror(-r));
+
+ /* if we couldn't read the gid, then it will be 0, but that's
+ * fine and we shouldn't try to resolve the group again, so
+ * let's just pretend it worked right-away. */
+ s->file_gid_valid = true;
+}
+
+void server_fix_perms(Server *s, JournalFile *f, uid_t uid) {
+ int r;
+#ifdef HAVE_ACL
+ acl_t acl;
+ acl_entry_t entry;
+ acl_permset_t permset;
+#endif
+
+ assert(f);
+
+ server_read_file_gid(s);
+
+ r = fchmod_and_fchown(f->fd, 0640, 0, s->file_gid);
+ if (r < 0)
+ log_warning("Failed to fix access mode/rights on %s, ignoring: %s", f->path, strerror(-r));
+
+#ifdef HAVE_ACL
+ if (uid <= 0)
+ return;
+
+ acl = acl_get_fd(f->fd);
+ if (!acl) {
+ log_warning("Failed to read ACL on %s, ignoring: %m", f->path);
+ return;
+ }
+
+ r = acl_find_uid(acl, uid, &entry);
+ if (r <= 0) {
+
+ if (acl_create_entry(&acl, &entry) < 0 ||
+ acl_set_tag_type(entry, ACL_USER) < 0 ||
+ acl_set_qualifier(entry, &uid) < 0) {
+ log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
+ goto finish;
+ }
+ }
+
+ /* We do not recalculate the mask here, so that the fchmod() mask above stays intact. */
+ if (acl_get_permset(entry, &permset) < 0 ||
+ acl_add_perm(permset, ACL_READ) < 0) {
+ log_warning("Failed to patch ACL on %s, ignoring: %m", f->path);
+ goto finish;
+ }
+
+ if (acl_set_fd(f->fd, acl) < 0)
+ log_warning("Failed to set ACL on %s, ignoring: %m", f->path);
+
+finish:
+ acl_free(acl);
+#endif
+}
+
+static JournalFile* find_journal(Server *s, uid_t uid) {
+ char *p;
+ int r;
+ JournalFile *f;
+ sd_id128_t machine;
+
+ assert(s);
+
+ /* We split up user logs only on /var, not on /run. If the
+ * runtime file is open, we write to it exclusively, in order
+ * to guarantee proper order as soon as we flush /run to
+ * /var and close the runtime file. */
+
+ if (s->runtime_journal)
+ return s->runtime_journal;
+
+ if (uid <= 0)
+ return s->system_journal;
+
+ r = sd_id128_get_machine(&machine);
+ if (r < 0)
+ return s->system_journal;
+
+ f = hashmap_get(s->user_journals, UINT32_TO_PTR(uid));
+ if (f)
+ return f;
+
+ if (asprintf(&p, "/var/log/journal/" SD_ID128_FORMAT_STR "/user-%lu.journal",
+ SD_ID128_FORMAT_VAL(machine), (unsigned long) uid) < 0)
+ return s->system_journal;
+
+ while (hashmap_size(s->user_journals) >= USER_JOURNALS_MAX) {
+ /* Too many open? Then let's close one */
+ f = hashmap_steal_first(s->user_journals);
+ assert(f);
+ journal_file_close(f);
+ }
+
+ r = journal_file_open_reliably(p, O_RDWR|O_CREAT, 0640, s->compress, s->seal, &s->system_metrics, s->mmap, s->system_journal, &f);
+ free(p);
+
+ if (r < 0)
+ return s->system_journal;
+
+ server_fix_perms(s, f, uid);
+
+ r = hashmap_put(s->user_journals, UINT32_TO_PTR(uid), f);
+ if (r < 0) {
+ journal_file_close(f);
+ return s->system_journal;
+ }
+
+ return f;
+}
+
+void server_rotate(Server *s) {
+ JournalFile *f;
+ void *k;
+ Iterator i;
+ int r;
+
+ log_debug("Rotating...");
+
+ if (s->runtime_journal) {
+ r = journal_file_rotate(&s->runtime_journal, s->compress, false);
+ if (r < 0)
+ if (s->runtime_journal)
+ log_error("Failed to rotate %s: %s", s->runtime_journal->path, strerror(-r));
+ else
+ log_error("Failed to create new runtime journal: %s", strerror(-r));
+ else
+ server_fix_perms(s, s->runtime_journal, 0);
+ }
+
+ if (s->system_journal) {
+ r = journal_file_rotate(&s->system_journal, s->compress, s->seal);
+ if (r < 0)
+ if (s->system_journal)
+ log_error("Failed to rotate %s: %s", s->system_journal->path, strerror(-r));
+ else
+ log_error("Failed to create new system journal: %s", strerror(-r));
+
+ else
+ server_fix_perms(s, s->system_journal, 0);
+ }
+
+ HASHMAP_FOREACH_KEY(f, k, s->user_journals, i) {
+ r = journal_file_rotate(&f, s->compress, s->seal);
+ if (r < 0)
+ if (f)
+ log_error("Failed to rotate %s: %s", f->path, strerror(-r));
+ else
+ log_error("Failed to create user journal: %s", strerror(-r));
+ else {
+ hashmap_replace(s->user_journals, k, f);
+ server_fix_perms(s, f, PTR_TO_UINT32(k));
+ }
+ }
+}
+
+void server_sync(Server *s) {
+ JournalFile *f;
+ void *k;
+ Iterator i;
+ int r;
+
+ static const struct itimerspec sync_timer_disable = {};
+
+ if (s->system_journal) {
+ r = journal_file_set_offline(s->system_journal);
+ if (r < 0)
+ log_error("Failed to sync system journal: %s", strerror(-r));
+ }
+
+ HASHMAP_FOREACH_KEY(f, k, s->user_journals, i) {
+ r = journal_file_set_offline(f);
+ if (r < 0)
+ log_error("Failed to sync user journal: %s", strerror(-r));
+ }
+
+ r = timerfd_settime(s->sync_timer_fd, 0, &sync_timer_disable, NULL);
+ if (r < 0)
+ log_error("Failed to disable max timer: %m");
+
+ s->sync_scheduled = false;
+}
+
+void server_vacuum(Server *s) {
+ char *p;
+ char ids[33];
+ sd_id128_t machine;
+ int r;
+
+ log_debug("Vacuuming...");
+
+ s->oldest_file_usec = 0;
+
+ r = sd_id128_get_machine(&machine);
+ if (r < 0) {
+ log_error("Failed to get machine ID: %s", strerror(-r));
+ return;
+ }
+
+ sd_id128_to_string(machine, ids);
+
+ if (s->system_journal) {
+ p = strappend("/var/log/journal/", ids);
+ if (!p) {
+ log_oom();
+ return;
+ }
+
+ r = journal_directory_vacuum(p, s->system_metrics.max_use, s->system_metrics.keep_free, s->max_retention_usec, &s->oldest_file_usec);
+ if (r < 0 && r != -ENOENT)
+ log_error("Failed to vacuum %s: %s", p, strerror(-r));
+ free(p);
+ }
+
+ if (s->runtime_journal) {
+ p = strappend("/run/log/journal/", ids);
+ if (!p) {
+ log_oom();
+ return;
+ }
+
+ r = journal_directory_vacuum(p, s->runtime_metrics.max_use, s->runtime_metrics.keep_free, s->max_retention_usec, &s->oldest_file_usec);
+ if (r < 0 && r != -ENOENT)
+ log_error("Failed to vacuum %s: %s", p, strerror(-r));
+ free(p);
+ }
+
+ s->cached_available_space_timestamp = 0;
+}
+
+bool shall_try_append_again(JournalFile *f, int r) {
+
+ /* -E2BIG Hit configured limit
+ -EFBIG Hit fs limit
+ -EDQUOT Quota limit hit
+ -ENOSPC Disk full
+ -EHOSTDOWN Other machine
+ -EBUSY Unclean shutdown
+ -EPROTONOSUPPORT Unsupported feature
+ -EBADMSG Corrupted
+ -ENODATA Truncated
+ -ESHUTDOWN Already archived */
+
+ if (r == -E2BIG || r == -EFBIG || r == -EDQUOT || r == -ENOSPC)
+ log_debug("%s: Allocation limit reached, rotating.", f->path);
+ else if (r == -EHOSTDOWN)
+ log_info("%s: Journal file from other machine, rotating.", f->path);
+ else if (r == -EBUSY)
+ log_info("%s: Unclean shutdown, rotating.", f->path);
+ else if (r == -EPROTONOSUPPORT)
+ log_info("%s: Unsupported feature, rotating.", f->path);
+ else if (r == -EBADMSG || r == -ENODATA || r == ESHUTDOWN)
+ log_warning("%s: Journal file corrupted, rotating.", f->path);
+ else
+ return false;
+
+ return true;
+}
+
+static void write_to_journal(Server *s, uid_t uid, struct iovec *iovec, unsigned n) {
+ JournalFile *f;
+ bool vacuumed = false;
+ int r;
+
+ assert(s);
+ assert(iovec);
+ assert(n > 0);
+
+ f = find_journal(s, uid);
+ if (!f)
+ return;
+
+ if (journal_file_rotate_suggested(f, s->max_file_usec)) {
+ log_debug("%s: Journal header limits reached or header out-of-date, rotating.", f->path);
+ server_rotate(s);
+ server_vacuum(s);
+ vacuumed = true;
+
+ f = find_journal(s, uid);
+ if (!f)
+ return;
+ }
+
+ r = journal_file_append_entry(f, NULL, iovec, n, &s->seqnum, NULL, NULL);
+ if (r >= 0) {
+ server_schedule_sync(s);
+ return;
+ }
+
+ if (vacuumed || !shall_try_append_again(f, r)) {
+ log_error("Failed to write entry, ignoring: %s", strerror(-r));
+ return;
+ }
+
+ server_rotate(s);
+ server_vacuum(s);
+
+ f = find_journal(s, uid);
+ if (!f)
+ return;
+
+ log_debug("Retrying write.");
+ r = journal_file_append_entry(f, NULL, iovec, n, &s->seqnum, NULL, NULL);
+ if (r < 0)
+ log_error("Failed to write entry, ignoring: %s", strerror(-r));
+}
+
+static void dispatch_message_real(
+ Server *s,
+ struct iovec *iovec, unsigned n, unsigned m,
+ struct ucred *ucred,
+ struct timeval *tv,
+ const char *label, size_t label_len,
+ const char *unit_id) {
+
+ char pid[sizeof("_PID=") + DECIMAL_STR_MAX(pid_t)],
+ uid[sizeof("_UID=") + DECIMAL_STR_MAX(uid_t)],
+ gid[sizeof("_GID=") + DECIMAL_STR_MAX(gid_t)],
+ owner_uid[sizeof("_SYSTEMD_OWNER_UID=") + DECIMAL_STR_MAX(uid_t)],
+ source_time[sizeof("_SOURCE_REALTIME_TIMESTAMP=") + DECIMAL_STR_MAX(usec_t)],
+ boot_id[sizeof("_BOOT_ID=") + 32] = "_BOOT_ID=",
+ machine_id[sizeof("_MACHINE_ID=") + 32] = "_MACHINE_ID=";
+ char *comm, *exe, *cmdline, *cgroup, *session, *unit, *hostname;
+ sd_id128_t id;
+ int r;
+ char *t, *c;
+ uid_t realuid = 0, owner = 0, journal_uid;
+ bool owner_valid = false;
+#ifdef HAVE_AUDIT
+ char audit_session[sizeof("_AUDIT_SESSION=") + DECIMAL_STR_MAX(uint32_t)],
+ audit_loginuid[sizeof("_AUDIT_LOGINUID=") + DECIMAL_STR_MAX(uid_t)];
+
+ uint32_t audit;
+ uid_t loginuid;
+#endif
+
+ assert(s);
+ assert(iovec);
+ assert(n > 0);
+ assert(n + N_IOVEC_META_FIELDS <= m);
+
+ if (ucred) {
+ realuid = ucred->uid;
+
+ sprintf(pid, "_PID=%lu", (unsigned long) ucred->pid);
+ IOVEC_SET_STRING(iovec[n++], pid);
+
+ sprintf(uid, "_UID=%lu", (unsigned long) ucred->uid);
+ IOVEC_SET_STRING(iovec[n++], uid);
+
+ sprintf(gid, "_GID=%lu", (unsigned long) ucred->gid);
+ IOVEC_SET_STRING(iovec[n++], gid);
+
+ r = get_process_comm(ucred->pid, &t);
+ if (r >= 0) {
+ comm = strappenda("_COMM=", t);
+ free(t);
+ IOVEC_SET_STRING(iovec[n++], comm);
+ }
+
+ r = get_process_exe(ucred->pid, &t);
+ if (r >= 0) {
+ exe = strappenda("_EXE=", t);
+ free(t);
+ IOVEC_SET_STRING(iovec[n++], exe);
+ }
+
+ r = get_process_cmdline(ucred->pid, 0, false, &t);
+ if (r >= 0) {
+ cmdline = strappenda("_CMDLINE=", t);
+ free(t);
+ IOVEC_SET_STRING(iovec[n++], cmdline);
+ }
+
+#ifdef HAVE_AUDIT
+ r = audit_session_from_pid(ucred->pid, &audit);
+ if (r >= 0) {
+ sprintf(audit_session, "_AUDIT_SESSION=%lu", (unsigned long) audit);
+ IOVEC_SET_STRING(iovec[n++], audit_session);
+ }
+
+ r = audit_loginuid_from_pid(ucred->pid, &loginuid);
+ if (r >= 0) {
+ sprintf(audit_loginuid, "_AUDIT_LOGINUID=%lu", (unsigned long) loginuid);
+ IOVEC_SET_STRING(iovec[n++], audit_loginuid);
+ }
+#endif
+
+ r = cg_pid_get_path_shifted(ucred->pid, NULL, &c);
+ if (r >= 0) {
+ cgroup = strappenda("_SYSTEMD_CGROUP=", c);
+ IOVEC_SET_STRING(iovec[n++], cgroup);
+
+ r = cg_path_get_session(c, &t);
+ if (r >= 0) {
+ session = strappenda("_SYSTEMD_SESSION=", t);
+ free(t);
+ IOVEC_SET_STRING(iovec[n++], session);
+ }
+
+ if (cg_path_get_owner_uid(c, &owner) >= 0) {
+ owner_valid = true;
+
+ sprintf(owner_uid, "_SYSTEMD_OWNER_UID=%lu", (unsigned long) owner);
+ IOVEC_SET_STRING(iovec[n++], owner_uid);
+ }
+
+ if (cg_path_get_unit(c, &t) >= 0) {
+ unit = strappenda("_SYSTEMD_UNIT=", t);
+ free(t);
+ } else if (cg_path_get_user_unit(c, &t) >= 0) {
+ unit = strappenda("_SYSTEMD_USER_UNIT=", t);
+ free(t);
+ } else if (unit_id) {
+ if (session)
+ unit = strappenda("_SYSTEMD_USER_UNIT=", unit_id);
+ else
+ unit = strappenda("_SYSTEMD_UNIT=", unit_id);
+ } else
+ unit = NULL;
+
+ if (unit)
+ IOVEC_SET_STRING(iovec[n++], unit);
+
+ free(c);
+ }
+
+#ifdef HAVE_SELINUX
+ if (label) {
+ char *selinux_context = alloca(sizeof("_SELINUX_CONTEXT=") + label_len);
+
+ *((char*) mempcpy(stpcpy(selinux_context, "_SELINUX_CONTEXT="), label, label_len)) = 0;
+ IOVEC_SET_STRING(iovec[n++], selinux_context);
+ } else {
+ security_context_t con;
+
+ if (getpidcon(ucred->pid, &con) >= 0) {
+ char *selinux_context = strappenda("_SELINUX_CONTEXT=", con);
+
+ freecon(con);
+ IOVEC_SET_STRING(iovec[n++], selinux_context);
+ }
+ }
+#endif
+ }
+
+ if (tv) {
+ sprintf(source_time, "_SOURCE_REALTIME_TIMESTAMP=%llu", (unsigned long long) timeval_load(tv));
+ IOVEC_SET_STRING(iovec[n++], source_time);
+ }
+
+ /* Note that strictly speaking storing the boot id here is
+ * redundant since the entry includes this in-line
+ * anyway. However, we need this indexed, too. */
+ r = sd_id128_get_boot(&id);
+ if (r >= 0) {
+ sd_id128_to_string(id, boot_id + sizeof("_BOOT_ID=") - 1);
+ IOVEC_SET_STRING(iovec[n++], boot_id);
+ }
+
+ r = sd_id128_get_machine(&id);
+ if (r >= 0) {
+ sd_id128_to_string(id, machine_id + sizeof("_MACHINE_ID=") - 1);
+ IOVEC_SET_STRING(iovec[n++], machine_id);
+ }
+
+ t = gethostname_malloc();
+ if (t) {
+ hostname = strappenda("_HOSTNAME=", t);
+ free(t);
+ IOVEC_SET_STRING(iovec[n++], hostname);
+ }
+
+ assert(n <= m);
+
+ if (s->split_mode == SPLIT_UID && realuid > 0)
+ /* Split up strictly by any UID */
+ journal_uid = realuid;
+ else if (s->split_mode == SPLIT_LOGIN && realuid > 0 && owner_valid && owner > 0)
+ /* Split up by login UIDs, this avoids creation of
+ * individual journals for system UIDs. We do this
+ * only if the realuid is not root, in order not to
+ * accidentally leak privileged information to the
+ * user that is logged by a privileged process that is
+ * part of an unprivileged session.*/
+ journal_uid = owner;
+ else
+ journal_uid = 0;
+
+ write_to_journal(s, journal_uid, iovec, n);
+}
+
+void server_driver_message(Server *s, sd_id128_t message_id, const char *format, ...) {
+ char mid[11 + 32 + 1];
+ char buffer[16 + LINE_MAX + 1];
+ struct iovec iovec[N_IOVEC_META_FIELDS + 4];
+ int n = 0;
+ va_list ap;
+ struct ucred ucred = {};
+
+ assert(s);
+ assert(format);
+
+ IOVEC_SET_STRING(iovec[n++], "PRIORITY=6");
+ IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=driver");
+
+ memcpy(buffer, "MESSAGE=", 8);
+ va_start(ap, format);
+ vsnprintf(buffer + 8, sizeof(buffer) - 8, format, ap);
+ va_end(ap);
+ char_array_0(buffer);
+ IOVEC_SET_STRING(iovec[n++], buffer);
+
+ if (!sd_id128_equal(message_id, SD_ID128_NULL)) {
+ snprintf(mid, sizeof(mid), MESSAGE_ID(message_id));
+ char_array_0(mid);
+ IOVEC_SET_STRING(iovec[n++], mid);
+ }
+
+ ucred.pid = getpid();
+ ucred.uid = getuid();
+ ucred.gid = getgid();
+
+ dispatch_message_real(s, iovec, n, ELEMENTSOF(iovec), &ucred, NULL, NULL, 0, NULL);
+}
+
+void server_dispatch_message(
+ Server *s,
+ struct iovec *iovec, unsigned n, unsigned m,
+ struct ucred *ucred,
+ struct timeval *tv,
+ const char *label, size_t label_len,
+ const char *unit_id,
+ int priority) {
+
+ int rl, r;
+ _cleanup_free_ char *path = NULL;
+ char *c;
+
+ assert(s);
+ assert(iovec || n == 0);
+
+ if (n == 0)
+ return;
+
+ if (LOG_PRI(priority) > s->max_level_store)
+ return;
+
+ if (!ucred)
+ goto finish;
+
+ r = cg_pid_get_path_shifted(ucred->pid, NULL, &path);
+ if (r < 0)
+ goto finish;
+
+ /* example: /user/lennart/3/foobar
+ * /system/dbus.service/foobar
+ *
+ * So let's cut of everything past the third /, since that is
+ * where user directories start */
+
+ c = strchr(path, '/');
+ if (c) {
+ c = strchr(c+1, '/');
+ if (c) {
+ c = strchr(c+1, '/');
+ if (c)
+ *c = 0;
+ }
+ }
+
+ rl = journal_rate_limit_test(s->rate_limit, path,
+ priority & LOG_PRIMASK, available_space(s));
+
+ if (rl == 0)
+ return;
+
+ /* Write a suppression message if we suppressed something */
+ if (rl > 1)
+ server_driver_message(s, SD_MESSAGE_JOURNAL_DROPPED,
+ "Suppressed %u messages from %s", rl - 1, path);
+
+finish:
+ dispatch_message_real(s, iovec, n, m, ucred, tv, label, label_len, unit_id);
+}
+
+
+static int system_journal_open(Server *s) {
+ int r;
+ char *fn;
+ sd_id128_t machine;
+ char ids[33];
+
+ r = sd_id128_get_machine(&machine);
+ if (r < 0)
+ return r;
+
+ sd_id128_to_string(machine, ids);
+
+ if (!s->system_journal &&
+ (s->storage == STORAGE_PERSISTENT || s->storage == STORAGE_AUTO) &&
+ access("/run/systemd/journal/flushed", F_OK) >= 0) {
+
+ /* If in auto mode: first try to create the machine
+ * path, but not the prefix.
+ *
+ * If in persistent mode: create /var/log/journal and
+ * the machine path */
+
+ if (s->storage == STORAGE_PERSISTENT)
+ (void) mkdir("/var/log/journal/", 0755);
+
+ fn = strappend("/var/log/journal/", ids);
+ if (!fn)
+ return -ENOMEM;
+
+ (void) mkdir(fn, 0755);
+ free(fn);
+
+ fn = strjoin("/var/log/journal/", ids, "/system.journal", NULL);
+ if (!fn)
+ return -ENOMEM;
+
+ r = journal_file_open_reliably(fn, O_RDWR|O_CREAT, 0640, s->compress, s->seal, &s->system_metrics, s->mmap, NULL, &s->system_journal);
+ free(fn);
+
+ if (r >= 0) {
+ char fb[FORMAT_BYTES_MAX];
+
+ server_fix_perms(s, s->system_journal, 0);
+ server_driver_message(s, SD_ID128_NULL, "Allowing system journal files to grow to %s.",
+ format_bytes(fb, sizeof(fb), s->system_metrics.max_use));
+
+ } else if (r < 0) {
+
+ if (r != -ENOENT && r != -EROFS)
+ log_warning("Failed to open system journal: %s", strerror(-r));
+
+ r = 0;
+ }
+ }
+
+ if (!s->runtime_journal &&
+ (s->storage != STORAGE_NONE)) {
+
+ fn = strjoin("/run/log/journal/", ids, "/system.journal", NULL);
+ if (!fn)
+ return -ENOMEM;
+
+ if (s->system_journal) {
+
+ /* Try to open the runtime journal, but only
+ * if it already exists, so that we can flush
+ * it into the system journal */
+
+ r = journal_file_open(fn, O_RDWR, 0640, s->compress, false, &s->runtime_metrics, s->mmap, NULL, &s->runtime_journal);
+ free(fn);
+
+ if (r < 0) {
+ if (r != -ENOENT)
+ log_warning("Failed to open runtime journal: %s", strerror(-r));
+
+ r = 0;
+ }
+
+ } else {
+
+ /* OK, we really need the runtime journal, so create
+ * it if necessary. */
+
+ (void) mkdir_parents(fn, 0755);
+ r = journal_file_open_reliably(fn, O_RDWR|O_CREAT, 0640, s->compress, false, &s->runtime_metrics, s->mmap, NULL, &s->runtime_journal);
+ free(fn);
+
+ if (r < 0) {
+ log_error("Failed to open runtime journal: %s", strerror(-r));
+ return r;
+ }
+ }
+
+ if (s->runtime_journal) {
+ char fb[FORMAT_BYTES_MAX];
+
+ server_fix_perms(s, s->runtime_journal, 0);
+ server_driver_message(s, SD_ID128_NULL, "Allowing runtime journal files to grow to %s.",
+ format_bytes(fb, sizeof(fb), s->runtime_metrics.max_use));
+ }
+ }
+
+ return r;
+}
+
+int server_flush_to_var(Server *s) {
+ int r;
+ sd_id128_t machine;
+ sd_journal *j = NULL;
+
+ assert(s);
+
+ if (s->storage != STORAGE_AUTO &&
+ s->storage != STORAGE_PERSISTENT)
+ return 0;
+
+ if (!s->runtime_journal)
+ return 0;
+
+ system_journal_open(s);
+
+ if (!s->system_journal)
+ return 0;
+
+ log_debug("Flushing to /var...");
+
+ r = sd_id128_get_machine(&machine);
+ if (r < 0) {
+ log_error("Failed to get machine id: %s", strerror(-r));
+ return r;
+ }
+
+ r = sd_journal_open(&j, SD_JOURNAL_RUNTIME_ONLY);
+ if (r < 0) {
+ log_error("Failed to read runtime journal: %s", strerror(-r));
+ return r;
+ }
+
+ sd_journal_set_data_threshold(j, 0);
+
+ SD_JOURNAL_FOREACH(j) {
+ Object *o = NULL;
+ JournalFile *f;
+
+ f = j->current_file;
+ assert(f && f->current_offset > 0);
+
+ r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
+ if (r < 0) {
+ log_error("Can't read entry: %s", strerror(-r));
+ goto finish;
+ }
+
+ r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
+ if (r >= 0)
+ continue;
+
+ if (!shall_try_append_again(s->system_journal, r)) {
+ log_error("Can't write entry: %s", strerror(-r));
+ goto finish;
+ }
+
+ server_rotate(s);
+ server_vacuum(s);
+
+ if (!s->system_journal) {
+ log_notice("Didn't flush runtime journal since rotation of system journal wasn't successful.");
+ r = -EIO;
+ goto finish;
+ }
+
+ log_debug("Retrying write.");
+ r = journal_file_copy_entry(f, s->system_journal, o, f->current_offset, NULL, NULL, NULL);
+ if (r < 0) {
+ log_error("Can't write entry: %s", strerror(-r));
+ goto finish;
+ }
+ }
+
+finish:
+ journal_file_post_change(s->system_journal);
+
+ journal_file_close(s->runtime_journal);
+ s->runtime_journal = NULL;
+
+ if (r >= 0)
+ rm_rf("/run/log/journal", false, true, false);
+
+ sd_journal_close(j);
+
+ return r;
+}
+
+int process_event(Server *s, struct epoll_event *ev) {
+ assert(s);
+ assert(ev);
+
+ if (ev->data.fd == s->signal_fd) {
+ struct signalfd_siginfo sfsi;
+ ssize_t n;
+
+ if (ev->events != EPOLLIN) {
+ log_error("Got invalid event from epoll.");
+ return -EIO;
+ }
+
+ n = read(s->signal_fd, &sfsi, sizeof(sfsi));
+ if (n != sizeof(sfsi)) {
+
+ if (n >= 0)
+ return -EIO;
+
+ if (errno == EINTR || errno == EAGAIN)
+ return 1;
+
+ return -errno;
+ }
+
+ if (sfsi.ssi_signo == SIGUSR1) {
+ touch("/run/systemd/journal/flushed");
+ server_flush_to_var(s);
+ server_sync(s);
+ return 1;
+ }
+
+ if (sfsi.ssi_signo == SIGUSR2) {
+ server_rotate(s);
+ server_vacuum(s);
+ return 1;
+ }
+
+ log_info("Received SIG%s", signal_to_string(sfsi.ssi_signo));
+
+ return 0;
+
+ } else if (ev->data.fd == s->sync_timer_fd) {
+ int r;
+ uint64_t t;
+
+ log_debug("Got sync request from epoll.");
+
+ r = read(ev->data.fd, (void *)&t, sizeof(t));
+ if (r < 0)
+ return 0;
+
+ server_sync(s);
+ return 1;
+
+ } else if (ev->data.fd == s->dev_kmsg_fd) {
+ int r;
+
+ if (ev->events != EPOLLIN) {
+ log_error("Got invalid event from epoll.");
+ return -EIO;
+ }
+
+ r = server_read_dev_kmsg(s);
+ if (r < 0)
+ return r;
+
+ return 1;
+
+ } else if (ev->data.fd == s->native_fd ||
+ ev->data.fd == s->syslog_fd) {
+
+ if (ev->events != EPOLLIN) {
+ log_error("Got invalid event from epoll.");
+ return -EIO;
+ }
+
+ for (;;) {
+ struct msghdr msghdr;
+ struct iovec iovec;
+ struct ucred *ucred = NULL;
+ struct timeval *tv = NULL;
+ struct cmsghdr *cmsg;
+ char *label = NULL;
+ size_t label_len = 0;
+ union {
+ struct cmsghdr cmsghdr;
+
+ /* We use NAME_MAX space for the
+ * SELinux label here. The kernel
+ * currently enforces no limit, but
+ * according to suggestions from the
+ * SELinux people this will change and
+ * it will probably be identical to
+ * NAME_MAX. For now we use that, but
+ * this should be updated one day when
+ * the final limit is known.*/
+ uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +
+ CMSG_SPACE(sizeof(struct timeval)) +
+ CMSG_SPACE(sizeof(int)) + /* fd */
+ CMSG_SPACE(NAME_MAX)]; /* selinux label */
+ } control;
+ ssize_t n;
+ int v;
+ int *fds = NULL;
+ unsigned n_fds = 0;
+
+ if (ioctl(ev->data.fd, SIOCINQ, &v) < 0) {
+ log_error("SIOCINQ failed: %m");
+ return -errno;
+ }
+
+ if (s->buffer_size < (size_t) v) {
+ void *b;
+ size_t l;
+
+ l = MAX(LINE_MAX + (size_t) v, s->buffer_size * 2);
+ b = realloc(s->buffer, l+1);
+
+ if (!b) {
+ log_error("Couldn't increase buffer.");
+ return -ENOMEM;
+ }
+
+ s->buffer_size = l;
+ s->buffer = b;
+ }
+
+ zero(iovec);
+ iovec.iov_base = s->buffer;
+ iovec.iov_len = s->buffer_size;
+
+ zero(control);
+ zero(msghdr);
+ msghdr.msg_iov = &iovec;
+ msghdr.msg_iovlen = 1;
+ msghdr.msg_control = &control;
+ msghdr.msg_controllen = sizeof(control);
+
+ n = recvmsg(ev->data.fd, &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
+ if (n < 0) {
+
+ if (errno == EINTR || errno == EAGAIN)
+ return 1;
+
+ log_error("recvmsg() failed: %m");
+ return -errno;
+ }
+
+ for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
+
+ if (cmsg->cmsg_level == SOL_SOCKET &&
+ cmsg->cmsg_type == SCM_CREDENTIALS &&
+ cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred)))
+ ucred = (struct ucred*) CMSG_DATA(cmsg);
+ else if (cmsg->cmsg_level == SOL_SOCKET &&
+ cmsg->cmsg_type == SCM_SECURITY) {
+ label = (char*) CMSG_DATA(cmsg);
+ label_len = cmsg->cmsg_len - CMSG_LEN(0);
+ } else if (cmsg->cmsg_level == SOL_SOCKET &&
+ cmsg->cmsg_type == SO_TIMESTAMP &&
+ cmsg->cmsg_len == CMSG_LEN(sizeof(struct timeval)))
+ tv = (struct timeval*) CMSG_DATA(cmsg);
+ else if (cmsg->cmsg_level == SOL_SOCKET &&
+ cmsg->cmsg_type == SCM_RIGHTS) {
+ fds = (int*) CMSG_DATA(cmsg);
+ n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
+ }
+ }
+
+ if (ev->data.fd == s->syslog_fd) {
+ char *e;
+
+ if (n > 0 && n_fds == 0) {
+ e = memchr(s->buffer, '\n', n);
+ if (e)
+ *e = 0;
+ else
+ s->buffer[n] = 0;
+
+ server_process_syslog_message(s, strstrip(s->buffer), ucred, tv, label, label_len);
+ } else if (n_fds > 0)
+ log_warning("Got file descriptors via syslog socket. Ignoring.");
+
+ } else {
+ if (n > 0 && n_fds == 0)
+ server_process_native_message(s, s->buffer, n, ucred, tv, label, label_len);
+ else if (n == 0 && n_fds == 1)
+ server_process_native_file(s, fds[0], ucred, tv, label, label_len);
+ else if (n_fds > 0)
+ log_warning("Got too many file descriptors via native socket. Ignoring.");
+ }
+
+ close_many(fds, n_fds);
+ }
+
+ return 1;
+
+ } else if (ev->data.fd == s->stdout_fd) {
+
+ if (ev->events != EPOLLIN) {
+ log_error("Got invalid event from epoll.");
+ return -EIO;
+ }
+
+ stdout_stream_new(s);
+ return 1;
+
+ } else {
+ StdoutStream *stream;
+
+ if ((ev->events|EPOLLIN|EPOLLHUP) != (EPOLLIN|EPOLLHUP)) {
+ log_error("Got invalid event from epoll.");
+ return -EIO;
+ }
+
+ /* If it is none of the well-known fds, it must be an
+ * stdout stream fd. Note that this is a bit ugly here
+ * (since we rely that none of the well-known fds
+ * could be interpreted as pointer), but nonetheless
+ * safe, since the well-known fds would never get an
+ * fd > 4096, i.e. beyond the first memory page */
+
+ stream = ev->data.ptr;
+
+ if (stdout_stream_process(stream) <= 0)
+ stdout_stream_free(stream);
+
+ return 1;
+ }
+
+ log_error("Unknown event.");
+ return 0;
+}
+
+static int open_signalfd(Server *s) {
+ sigset_t mask;
+ struct epoll_event ev;
+
+ assert(s);
+
+ assert_se(sigemptyset(&mask) == 0);
+ sigset_add_many(&mask, SIGINT, SIGTERM, SIGUSR1, SIGUSR2, -1);
+ assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
+
+ s->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
+ if (s->signal_fd < 0) {
+ log_error("signalfd(): %m");
+ return -errno;
+ }
+
+ zero(ev);
+ ev.events = EPOLLIN;
+ ev.data.fd = s->signal_fd;
+
+ if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->signal_fd, &ev) < 0) {
+ log_error("epoll_ctl(): %m");
+ return -errno;
+ }
+
+ return 0;
+}
+
+static int server_parse_proc_cmdline(Server *s) {
+ _cleanup_free_ char *line = NULL;
+ char *w, *state;
+ int r;
+ size_t l;
+
+ if (detect_container(NULL) > 0)
+ return 0;
+
+ r = read_one_line_file("/proc/cmdline", &line);
+ if (r < 0) {
+ log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
+ return 0;
+ }
+
+ FOREACH_WORD_QUOTED(w, l, line, state) {
+ _cleanup_free_ char *word;
+
+ word = strndup(w, l);
+ if (!word)
+ return -ENOMEM;
+
+ if (startswith(word, "systemd.journald.forward_to_syslog=")) {
+ r = parse_boolean(word + 35);
+ if (r < 0)
+ log_warning("Failed to parse forward to syslog switch %s. Ignoring.", word + 35);
+ else
+ s->forward_to_syslog = r;
+ } else if (startswith(word, "systemd.journald.forward_to_kmsg=")) {
+ r = parse_boolean(word + 33);
+ if (r < 0)
+ log_warning("Failed to parse forward to kmsg switch %s. Ignoring.", word + 33);
+ else
+ s->forward_to_kmsg = r;
+ } else if (startswith(word, "systemd.journald.forward_to_console=")) {
+ r = parse_boolean(word + 36);
+ if (r < 0)
+ log_warning("Failed to parse forward to console switch %s. Ignoring.", word + 36);
+ else
+ s->forward_to_console = r;
+ } else if (startswith(word, "systemd.journald"))
+ log_warning("Invalid systemd.journald parameter. Ignoring.");
+ }
+
+ return 0;
+}
+
+static int server_parse_config_file(Server *s) {
+ static const char fn[] = "/etc/systemd/journald.conf";
+ _cleanup_fclose_ FILE *f = NULL;
+ int r;
+
+ assert(s);
+
+ f = fopen(fn, "re");
+ if (!f) {
+ if (errno == ENOENT)
+ return 0;
+
+ log_warning("Failed to open configuration file %s: %m", fn);
+ return -errno;
+ }
+
+ r = config_parse(NULL, fn, f, "Journal\0", config_item_perf_lookup,
+ (void*) journald_gperf_lookup, false, false, s);
+ if (r < 0)
+ log_warning("Failed to parse configuration file: %s", strerror(-r));
+
+ return r;
+}
+
+static int server_open_sync_timer(Server *s) {
+ int r;
+ struct epoll_event ev;
+
+ assert(s);
+
+ s->sync_timer_fd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC);
+ if (s->sync_timer_fd < 0)
+ return -errno;
+
+ zero(ev);
+ ev.events = EPOLLIN;
+ ev.data.fd = s->sync_timer_fd;
+
+ r = epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->sync_timer_fd, &ev);
+ if (r < 0) {
+ log_error("Failed to add idle timer fd to epoll object: %m");
+ return -errno;
+ }
+
+ return 0;
+}
+
+int server_schedule_sync(Server *s) {
+ int r;
+
+ assert(s);
+
+ if (s->sync_scheduled)
+ return 0;
+
+ if (s->sync_interval_usec) {
+ struct itimerspec sync_timer_enable = {
+ .it_value.tv_sec = s->sync_interval_usec / USEC_PER_SEC,
+ .it_value.tv_nsec = s->sync_interval_usec % MSEC_PER_SEC,
+ };
+
+ r = timerfd_settime(s->sync_timer_fd, 0, &sync_timer_enable, NULL);
+ if (r < 0)
+ return -errno;
+ }
+
+ s->sync_scheduled = true;
+
+ return 0;
+}
+
+int server_init(Server *s) {
+ int n, r, fd;
+
+ assert(s);
+
+ zero(*s);
+ s->sync_timer_fd = s->syslog_fd = s->native_fd = s->stdout_fd =
+ s->signal_fd = s->epoll_fd = s->dev_kmsg_fd = -1;
+ s->compress = true;
+ s->seal = true;
+
+ s->sync_interval_usec = DEFAULT_SYNC_INTERVAL_USEC;
+ s->sync_scheduled = false;
+
+ s->rate_limit_interval = DEFAULT_RATE_LIMIT_INTERVAL;
+ s->rate_limit_burst = DEFAULT_RATE_LIMIT_BURST;
+
+ s->forward_to_syslog = true;
+
+ s->max_level_store = LOG_DEBUG;
+ s->max_level_syslog = LOG_DEBUG;
+ s->max_level_kmsg = LOG_NOTICE;
+ s->max_level_console = LOG_INFO;
+
+ memset(&s->system_metrics, 0xFF, sizeof(s->system_metrics));
+ memset(&s->runtime_metrics, 0xFF, sizeof(s->runtime_metrics));
+
+ server_parse_config_file(s);
+ server_parse_proc_cmdline(s);
+ if (!!s->rate_limit_interval ^ !!s->rate_limit_burst) {
+ log_debug("Setting both rate limit interval and burst from %llu,%u to 0,0",
+ (long long unsigned) s->rate_limit_interval,
+ s->rate_limit_burst);
+ s->rate_limit_interval = s->rate_limit_burst = 0;
+ }
+
+ mkdir_p("/run/systemd/journal", 0755);
+
+ s->user_journals = hashmap_new(trivial_hash_func, trivial_compare_func);
+ if (!s->user_journals)
+ return log_oom();
+
+ s->mmap = mmap_cache_new();
+ if (!s->mmap)
+ return log_oom();
+
+ s->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
+ if (s->epoll_fd < 0) {
+ log_error("Failed to create epoll object: %m");
+ return -errno;
+ }
+
+ n = sd_listen_fds(true);
+ if (n < 0) {
+ log_error("Failed to read listening file descriptors from environment: %s", strerror(-n));
+ return n;
+ }
+
+ for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
+
+ if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/run/systemd/journal/socket", 0) > 0) {
+
+ if (s->native_fd >= 0) {
+ log_error("Too many native sockets passed.");
+ return -EINVAL;
+ }
+
+ s->native_fd = fd;
+
+ } else if (sd_is_socket_unix(fd, SOCK_STREAM, 1, "/run/systemd/journal/stdout", 0) > 0) {
+
+ if (s->stdout_fd >= 0) {
+ log_error("Too many stdout sockets passed.");
+ return -EINVAL;
+ }
+
+ s->stdout_fd = fd;
+
+ } else if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, "/dev/log", 0) > 0) {
+
+ if (s->syslog_fd >= 0) {
+ log_error("Too many /dev/log sockets passed.");
+ return -EINVAL;
+ }
+
+ s->syslog_fd = fd;
+
+ } else {
+ log_error("Unknown socket passed.");
+ return -EINVAL;
+ }
+ }
+
+ r = server_open_syslog_socket(s);
+ if (r < 0)
+ return r;
+
+ r = server_open_native_socket(s);
+ if (r < 0)
+ return r;
+
+ r = server_open_stdout_socket(s);
+ if (r < 0)
+ return r;
+
+ r = server_open_dev_kmsg(s);
+ if (r < 0)
+ return r;
+
+ r = server_open_kernel_seqnum(s);
+ if (r < 0)
+ return r;
+
+ r = server_open_sync_timer(s);
+ if (r < 0)
+ return r;
+
+ r = open_signalfd(s);
+ if (r < 0)
+ return r;
+
+ s->udev = udev_new();
+ if (!s->udev)
+ return -ENOMEM;
+
+ s->rate_limit = journal_rate_limit_new(s->rate_limit_interval,
+ s->rate_limit_burst);
+ if (!s->rate_limit)
+ return -ENOMEM;
+
+ r = system_journal_open(s);
+ if (r < 0)
+ return r;
+
+ return 0;
+}
+
+void server_maybe_append_tags(Server *s) {
+#ifdef HAVE_GCRYPT
+ JournalFile *f;
+ Iterator i;
+ usec_t n;
+
+ n = now(CLOCK_REALTIME);
+
+ if (s->system_journal)
+ journal_file_maybe_append_tag(s->system_journal, n);
+
+ HASHMAP_FOREACH(f, s->user_journals, i)
+ journal_file_maybe_append_tag(f, n);
+#endif
+}
+
+void server_done(Server *s) {
+ JournalFile *f;
+ assert(s);
+
+ while (s->stdout_streams)
+ stdout_stream_free(s->stdout_streams);
+
+ if (s->system_journal)
+ journal_file_close(s->system_journal);
+
+ if (s->runtime_journal)
+ journal_file_close(s->runtime_journal);
+
+ while ((f = hashmap_steal_first(s->user_journals)))
+ journal_file_close(f);
+
+ hashmap_free(s->user_journals);
+
+ if (s->epoll_fd >= 0)
+ close_nointr_nofail(s->epoll_fd);
+
+ if (s->signal_fd >= 0)
+ close_nointr_nofail(s->signal_fd);
+
+ if (s->syslog_fd >= 0)
+ close_nointr_nofail(s->syslog_fd);
+
+ if (s->native_fd >= 0)
+ close_nointr_nofail(s->native_fd);
+
+ if (s->stdout_fd >= 0)
+ close_nointr_nofail(s->stdout_fd);
+
+ if (s->dev_kmsg_fd >= 0)
+ close_nointr_nofail(s->dev_kmsg_fd);
+
+ if (s->sync_timer_fd >= 0)
+ close_nointr_nofail(s->sync_timer_fd);
+
+ if (s->rate_limit)
+ journal_rate_limit_free(s->rate_limit);
+
+ if (s->kernel_seqnum)
+ munmap(s->kernel_seqnum, sizeof(uint64_t));
+
+ free(s->buffer);
+ free(s->tty_path);
+
+ if (s->mmap)
+ mmap_cache_unref(s->mmap);
+
+ if (s->udev)
+ udev_unref(s->udev);
+}
diff --git a/src/journal/journald-server.h b/src/journal/journald-server.h
new file mode 100644
index 0000000000..129f7e8ab4
--- /dev/null
+++ b/src/journal/journald-server.h
@@ -0,0 +1,158 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <inttypes.h>
+#include <stdbool.h>
+#include <sys/epoll.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+
+#include "journal-file.h"
+#include "hashmap.h"
+#include "util.h"
+#include "audit.h"
+#include "journald-rate-limit.h"
+#include "list.h"
+
+typedef enum Storage {
+ STORAGE_AUTO,
+ STORAGE_VOLATILE,
+ STORAGE_PERSISTENT,
+ STORAGE_NONE,
+ _STORAGE_MAX,
+ _STORAGE_INVALID = -1
+} Storage;
+
+typedef enum SplitMode {
+ SPLIT_LOGIN,
+ SPLIT_UID,
+ SPLIT_NONE,
+ _SPLIT_MAX,
+ _SPLIT_INVALID = -1
+} SplitMode;
+
+typedef struct StdoutStream StdoutStream;
+
+typedef struct Server {
+ int epoll_fd;
+ int signal_fd;
+ int syslog_fd;
+ int native_fd;
+ int stdout_fd;
+ int dev_kmsg_fd;
+
+ JournalFile *runtime_journal;
+ JournalFile *system_journal;
+ Hashmap *user_journals;
+
+ uint64_t seqnum;
+
+ char *buffer;
+ size_t buffer_size;
+
+ JournalRateLimit *rate_limit;
+ usec_t sync_interval_usec;
+ usec_t rate_limit_interval;
+ unsigned rate_limit_burst;
+
+ JournalMetrics runtime_metrics;
+ JournalMetrics system_metrics;
+
+ bool compress;
+ bool seal;
+
+ bool forward_to_kmsg;
+ bool forward_to_syslog;
+ bool forward_to_console;
+
+ unsigned n_forward_syslog_missed;
+ usec_t last_warn_forward_syslog_missed;
+
+ uint64_t cached_available_space;
+ usec_t cached_available_space_timestamp;
+
+ uint64_t var_available_timestamp;
+
+ usec_t max_retention_usec;
+ usec_t max_file_usec;
+ usec_t oldest_file_usec;
+
+ gid_t file_gid;
+ bool file_gid_valid;
+
+ LIST_HEAD(StdoutStream, stdout_streams);
+ unsigned n_stdout_streams;
+
+ char *tty_path;
+
+ int max_level_store;
+ int max_level_syslog;
+ int max_level_kmsg;
+ int max_level_console;
+
+ Storage storage;
+ SplitMode split_mode;
+
+ MMapCache *mmap;
+
+ bool dev_kmsg_readable;
+
+ uint64_t *kernel_seqnum;
+
+ struct udev *udev;
+
+ int sync_timer_fd;
+ bool sync_scheduled;
+} Server;
+
+#define N_IOVEC_META_FIELDS 17
+#define N_IOVEC_KERNEL_FIELDS 64
+#define N_IOVEC_UDEV_FIELDS 32
+
+void server_dispatch_message(Server *s, struct iovec *iovec, unsigned n, unsigned m, struct ucred *ucred, struct timeval *tv, const char *label, size_t label_len, const char *unit_id, int priority);
+void server_driver_message(Server *s, sd_id128_t message_id, const char *format, ...) _printf_attr_(3,4);
+
+/* gperf lookup function */
+const struct ConfigPerfItem* journald_gperf_lookup(const char *key, unsigned length);
+
+int config_parse_storage(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+
+const char *storage_to_string(Storage s) _const_;
+Storage storage_from_string(const char *s) _pure_;
+
+int config_parse_split_mode(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+
+const char *split_mode_to_string(SplitMode s) _const_;
+SplitMode split_mode_from_string(const char *s) _pure_;
+
+void server_fix_perms(Server *s, JournalFile *f, uid_t uid);
+bool shall_try_append_again(JournalFile *f, int r);
+int server_init(Server *s);
+void server_done(Server *s);
+void server_sync(Server *s);
+void server_vacuum(Server *s);
+void server_rotate(Server *s);
+int server_schedule_sync(Server *s);
+int server_flush_to_var(Server *s);
+int process_event(Server *s, struct epoll_event *ev);
+void server_maybe_append_tags(Server *s);
diff --git a/src/journal/journald-stream.c b/src/journal/journald-stream.c
new file mode 100644
index 0000000000..6d51c29083
--- /dev/null
+++ b/src/journal/journald-stream.c
@@ -0,0 +1,458 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <fcntl.h>
+#include <unistd.h>
+#include <stddef.h>
+#include <sys/epoll.h>
+
+#ifdef HAVE_SELINUX
+#include <selinux/selinux.h>
+#endif
+
+#include "socket-util.h"
+#include "journald-server.h"
+#include "journald-stream.h"
+#include "journald-syslog.h"
+#include "journald-kmsg.h"
+#include "journald-console.h"
+
+#define STDOUT_STREAMS_MAX 4096
+
+typedef enum StdoutStreamState {
+ STDOUT_STREAM_IDENTIFIER,
+ STDOUT_STREAM_UNIT_ID,
+ STDOUT_STREAM_PRIORITY,
+ STDOUT_STREAM_LEVEL_PREFIX,
+ STDOUT_STREAM_FORWARD_TO_SYSLOG,
+ STDOUT_STREAM_FORWARD_TO_KMSG,
+ STDOUT_STREAM_FORWARD_TO_CONSOLE,
+ STDOUT_STREAM_RUNNING
+} StdoutStreamState;
+
+struct StdoutStream {
+ Server *server;
+ StdoutStreamState state;
+
+ int fd;
+
+ struct ucred ucred;
+#ifdef HAVE_SELINUX
+ security_context_t security_context;
+#endif
+
+ char *identifier;
+ char *unit_id;
+ int priority;
+ bool level_prefix:1;
+ bool forward_to_syslog:1;
+ bool forward_to_kmsg:1;
+ bool forward_to_console:1;
+
+ char buffer[LINE_MAX+1];
+ size_t length;
+
+ LIST_FIELDS(StdoutStream, stdout_stream);
+};
+
+static int stdout_stream_log(StdoutStream *s, const char *p) {
+ struct iovec iovec[N_IOVEC_META_FIELDS + 5];
+ char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL, *syslog_identifier = NULL;
+ unsigned n = 0;
+ int priority;
+ char *label = NULL;
+ size_t label_len = 0;
+
+ assert(s);
+ assert(p);
+
+ if (isempty(p))
+ return 0;
+
+ priority = s->priority;
+
+ if (s->level_prefix)
+ syslog_parse_priority((char**) &p, &priority);
+
+ if (s->forward_to_syslog || s->server->forward_to_syslog)
+ server_forward_syslog(s->server, syslog_fixup_facility(priority), s->identifier, p, &s->ucred, NULL);
+
+ if (s->forward_to_kmsg || s->server->forward_to_kmsg)
+ server_forward_kmsg(s->server, priority, s->identifier, p, &s->ucred);
+
+ if (s->forward_to_console || s->server->forward_to_console)
+ server_forward_console(s->server, priority, s->identifier, p, &s->ucred);
+
+ IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=stdout");
+
+ if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
+ IOVEC_SET_STRING(iovec[n++], syslog_priority);
+
+ if (priority & LOG_FACMASK)
+ if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
+ IOVEC_SET_STRING(iovec[n++], syslog_facility);
+
+ if (s->identifier) {
+ syslog_identifier = strappend("SYSLOG_IDENTIFIER=", s->identifier);
+ if (syslog_identifier)
+ IOVEC_SET_STRING(iovec[n++], syslog_identifier);
+ }
+
+ message = strappend("MESSAGE=", p);
+ if (message)
+ IOVEC_SET_STRING(iovec[n++], message);
+
+#ifdef HAVE_SELINUX
+ if (s->security_context) {
+ label = (char*) s->security_context;
+ label_len = strlen((char*) s->security_context);
+ }
+#endif
+
+ server_dispatch_message(s->server, iovec, n, ELEMENTSOF(iovec), &s->ucred, NULL, label, label_len, s->unit_id, priority);
+
+ free(message);
+ free(syslog_priority);
+ free(syslog_facility);
+ free(syslog_identifier);
+
+ return 0;
+}
+
+static int stdout_stream_line(StdoutStream *s, char *p) {
+ int r;
+
+ assert(s);
+ assert(p);
+
+ p = strstrip(p);
+
+ switch (s->state) {
+
+ case STDOUT_STREAM_IDENTIFIER:
+ if (isempty(p))
+ s->identifier = NULL;
+ else {
+ s->identifier = strdup(p);
+ if (!s->identifier)
+ return log_oom();
+ }
+
+ s->state = STDOUT_STREAM_UNIT_ID;
+ return 0;
+
+ case STDOUT_STREAM_UNIT_ID:
+ if (s->ucred.uid == 0) {
+ if (isempty(p))
+ s->unit_id = NULL;
+ else {
+ s->unit_id = strdup(p);
+ if (!s->unit_id)
+ return log_oom();
+ }
+ }
+
+ s->state = STDOUT_STREAM_PRIORITY;
+ return 0;
+
+ case STDOUT_STREAM_PRIORITY:
+ r = safe_atoi(p, &s->priority);
+ if (r < 0 || s->priority < 0 || s->priority > 999) {
+ log_warning("Failed to parse log priority line.");
+ return -EINVAL;
+ }
+
+ s->state = STDOUT_STREAM_LEVEL_PREFIX;
+ return 0;
+
+ case STDOUT_STREAM_LEVEL_PREFIX:
+ r = parse_boolean(p);
+ if (r < 0) {
+ log_warning("Failed to parse level prefix line.");
+ return -EINVAL;
+ }
+
+ s->level_prefix = !!r;
+ s->state = STDOUT_STREAM_FORWARD_TO_SYSLOG;
+ return 0;
+
+ case STDOUT_STREAM_FORWARD_TO_SYSLOG:
+ r = parse_boolean(p);
+ if (r < 0) {
+ log_warning("Failed to parse forward to syslog line.");
+ return -EINVAL;
+ }
+
+ s->forward_to_syslog = !!r;
+ s->state = STDOUT_STREAM_FORWARD_TO_KMSG;
+ return 0;
+
+ case STDOUT_STREAM_FORWARD_TO_KMSG:
+ r = parse_boolean(p);
+ if (r < 0) {
+ log_warning("Failed to parse copy to kmsg line.");
+ return -EINVAL;
+ }
+
+ s->forward_to_kmsg = !!r;
+ s->state = STDOUT_STREAM_FORWARD_TO_CONSOLE;
+ return 0;
+
+ case STDOUT_STREAM_FORWARD_TO_CONSOLE:
+ r = parse_boolean(p);
+ if (r < 0) {
+ log_warning("Failed to parse copy to console line.");
+ return -EINVAL;
+ }
+
+ s->forward_to_console = !!r;
+ s->state = STDOUT_STREAM_RUNNING;
+ return 0;
+
+ case STDOUT_STREAM_RUNNING:
+ return stdout_stream_log(s, p);
+ }
+
+ assert_not_reached("Unknown stream state");
+}
+
+static int stdout_stream_scan(StdoutStream *s, bool force_flush) {
+ char *p;
+ size_t remaining;
+ int r;
+
+ assert(s);
+
+ p = s->buffer;
+ remaining = s->length;
+ for (;;) {
+ char *end;
+ size_t skip;
+
+ end = memchr(p, '\n', remaining);
+ if (end)
+ skip = end - p + 1;
+ else if (remaining >= sizeof(s->buffer) - 1) {
+ end = p + sizeof(s->buffer) - 1;
+ skip = remaining;
+ } else
+ break;
+
+ *end = 0;
+
+ r = stdout_stream_line(s, p);
+ if (r < 0)
+ return r;
+
+ remaining -= skip;
+ p += skip;
+ }
+
+ if (force_flush && remaining > 0) {
+ p[remaining] = 0;
+ r = stdout_stream_line(s, p);
+ if (r < 0)
+ return r;
+
+ p += remaining;
+ remaining = 0;
+ }
+
+ if (p > s->buffer) {
+ memmove(s->buffer, p, remaining);
+ s->length = remaining;
+ }
+
+ return 0;
+}
+
+int stdout_stream_process(StdoutStream *s) {
+ ssize_t l;
+ int r;
+
+ assert(s);
+
+ l = read(s->fd, s->buffer+s->length, sizeof(s->buffer)-1-s->length);
+ if (l < 0) {
+
+ if (errno == EAGAIN)
+ return 0;
+
+ log_warning("Failed to read from stream: %m");
+ return -errno;
+ }
+
+ if (l == 0) {
+ r = stdout_stream_scan(s, true);
+ if (r < 0)
+ return r;
+
+ return 0;
+ }
+
+ s->length += l;
+ r = stdout_stream_scan(s, false);
+ if (r < 0)
+ return r;
+
+ return 1;
+
+}
+
+void stdout_stream_free(StdoutStream *s) {
+ assert(s);
+
+ if (s->server) {
+ assert(s->server->n_stdout_streams > 0);
+ s->server->n_stdout_streams --;
+ LIST_REMOVE(StdoutStream, stdout_stream, s->server->stdout_streams, s);
+ }
+
+ if (s->fd >= 0) {
+ if (s->server)
+ epoll_ctl(s->server->epoll_fd, EPOLL_CTL_DEL, s->fd, NULL);
+
+ close_nointr_nofail(s->fd);
+ }
+
+#ifdef HAVE_SELINUX
+ if (s->security_context)
+ freecon(s->security_context);
+#endif
+
+ free(s->identifier);
+ free(s);
+}
+
+int stdout_stream_new(Server *s) {
+ StdoutStream *stream;
+ int fd, r;
+ socklen_t len;
+ struct epoll_event ev;
+
+ assert(s);
+
+ fd = accept4(s->stdout_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
+ if (fd < 0) {
+ if (errno == EAGAIN)
+ return 0;
+
+ log_error("Failed to accept stdout connection: %m");
+ return -errno;
+ }
+
+ if (s->n_stdout_streams >= STDOUT_STREAMS_MAX) {
+ log_warning("Too many stdout streams, refusing connection.");
+ close_nointr_nofail(fd);
+ return 0;
+ }
+
+ stream = new0(StdoutStream, 1);
+ if (!stream) {
+ close_nointr_nofail(fd);
+ return log_oom();
+ }
+
+ stream->fd = fd;
+
+ len = sizeof(stream->ucred);
+ if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &stream->ucred, &len) < 0) {
+ log_error("Failed to determine peer credentials: %m");
+ r = -errno;
+ goto fail;
+ }
+
+#ifdef HAVE_SELINUX
+ if (getpeercon(fd, &stream->security_context) < 0 && errno != ENOPROTOOPT)
+ log_error("Failed to determine peer security context: %m");
+#endif
+
+ if (shutdown(fd, SHUT_WR) < 0) {
+ log_error("Failed to shutdown writing side of socket: %m");
+ r = -errno;
+ goto fail;
+ }
+
+ zero(ev);
+ ev.data.ptr = stream;
+ ev.events = EPOLLIN;
+ if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
+ log_error("Failed to add stream to event loop: %m");
+ r = -errno;
+ goto fail;
+ }
+
+ stream->server = s;
+ LIST_PREPEND(StdoutStream, stdout_stream, s->stdout_streams, stream);
+ s->n_stdout_streams ++;
+
+ return 0;
+
+fail:
+ stdout_stream_free(stream);
+ return r;
+}
+
+int server_open_stdout_socket(Server *s) {
+ int r;
+ struct epoll_event ev;
+
+ assert(s);
+
+ if (s->stdout_fd < 0) {
+ union sockaddr_union sa = {
+ .un.sun_family = AF_UNIX,
+ .un.sun_path = "/run/systemd/journal/stdout",
+ };
+
+ s->stdout_fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
+ if (s->stdout_fd < 0) {
+ log_error("socket() failed: %m");
+ return -errno;
+ }
+
+ unlink(sa.un.sun_path);
+
+ r = bind(s->stdout_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
+ if (r < 0) {
+ log_error("bind() failed: %m");
+ return -errno;
+ }
+
+ chmod(sa.un.sun_path, 0666);
+
+ if (listen(s->stdout_fd, SOMAXCONN) < 0) {
+ log_error("liste() failed: %m");
+ return -errno;
+ }
+ } else
+ fd_nonblock(s->stdout_fd, 1);
+
+ zero(ev);
+ ev.events = EPOLLIN;
+ ev.data.fd = s->stdout_fd;
+ if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->stdout_fd, &ev) < 0) {
+ log_error("Failed to add stdout server fd to epoll object: %m");
+ return -errno;
+ }
+
+ return 0;
+}
diff --git a/src/journal/journald-stream.h b/src/journal/journald-stream.h
new file mode 100644
index 0000000000..dfb6267bf6
--- /dev/null
+++ b/src/journal/journald-stream.h
@@ -0,0 +1,30 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "journald-server.h"
+
+int server_open_stdout_socket(Server *s);
+
+int stdout_stream_new(Server *s);
+void stdout_stream_free(StdoutStream *s);
+int stdout_stream_process(StdoutStream *s);
diff --git a/src/journal/journald-syslog.c b/src/journal/journald-syslog.c
new file mode 100644
index 0000000000..000f5acc10
--- /dev/null
+++ b/src/journal/journald-syslog.c
@@ -0,0 +1,491 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <unistd.h>
+#include <stddef.h>
+#include <sys/epoll.h>
+
+#include "systemd/sd-messages.h"
+#include "socket-util.h"
+#include "journald-server.h"
+#include "journald-syslog.h"
+#include "journald-kmsg.h"
+#include "journald-console.h"
+
+/* Warn once every 30s if we missed syslog message */
+#define WARN_FORWARD_SYSLOG_MISSED_USEC (30 * USEC_PER_SEC)
+
+static void forward_syslog_iovec(Server *s, const struct iovec *iovec, unsigned n_iovec, struct ucred *ucred, struct timeval *tv) {
+
+ union sockaddr_union sa = {
+ .un.sun_family = AF_UNIX,
+ .un.sun_path = "/run/systemd/journal/syslog",
+ };
+ struct msghdr msghdr = {
+ .msg_iov = (struct iovec *) iovec,
+ .msg_iovlen = n_iovec,
+ .msg_name = &sa,
+ .msg_namelen = offsetof(union sockaddr_union, un.sun_path)
+ + sizeof("/run/systemd/journal/syslog") - 1,
+ };
+ struct cmsghdr *cmsg;
+ union {
+ struct cmsghdr cmsghdr;
+ uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
+ } control;
+
+ assert(s);
+ assert(iovec);
+ assert(n_iovec > 0);
+
+ if (ucred) {
+ zero(control);
+ msghdr.msg_control = &control;
+ msghdr.msg_controllen = sizeof(control);
+
+ cmsg = CMSG_FIRSTHDR(&msghdr);
+ cmsg->cmsg_level = SOL_SOCKET;
+ cmsg->cmsg_type = SCM_CREDENTIALS;
+ cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
+ memcpy(CMSG_DATA(cmsg), ucred, sizeof(struct ucred));
+ msghdr.msg_controllen = cmsg->cmsg_len;
+ }
+
+ /* Forward the syslog message we received via /dev/log to
+ * /run/systemd/syslog. Unfortunately we currently can't set
+ * the SO_TIMESTAMP auxiliary data, and hence we don't. */
+
+ if (sendmsg(s->syslog_fd, &msghdr, MSG_NOSIGNAL) >= 0)
+ return;
+
+ /* The socket is full? I guess the syslog implementation is
+ * too slow, and we shouldn't wait for that... */
+ if (errno == EAGAIN) {
+ s->n_forward_syslog_missed++;
+ return;
+ }
+
+ if (ucred && errno == ESRCH) {
+ struct ucred u;
+
+ /* Hmm, presumably the sender process vanished
+ * by now, so let's fix it as good as we
+ * can, and retry */
+
+ u = *ucred;
+ u.pid = getpid();
+ memcpy(CMSG_DATA(cmsg), &u, sizeof(struct ucred));
+
+ if (sendmsg(s->syslog_fd, &msghdr, MSG_NOSIGNAL) >= 0)
+ return;
+
+ if (errno == EAGAIN) {
+ s->n_forward_syslog_missed++;
+ return;
+ }
+ }
+
+ if (errno != ENOENT)
+ log_debug("Failed to forward syslog message: %m");
+}
+
+static void forward_syslog_raw(Server *s, int priority, const char *buffer, struct ucred *ucred, struct timeval *tv) {
+ struct iovec iovec;
+
+ assert(s);
+ assert(buffer);
+
+ if (LOG_PRI(priority) > s->max_level_syslog)
+ return;
+
+ IOVEC_SET_STRING(iovec, buffer);
+ forward_syslog_iovec(s, &iovec, 1, ucred, tv);
+}
+
+void server_forward_syslog(Server *s, int priority, const char *identifier, const char *message, struct ucred *ucred, struct timeval *tv) {
+ struct iovec iovec[5];
+ char header_priority[6], header_time[64], header_pid[16];
+ int n = 0;
+ time_t t;
+ struct tm *tm;
+ char *ident_buf = NULL;
+
+ assert(s);
+ assert(priority >= 0);
+ assert(priority <= 999);
+ assert(message);
+
+ if (LOG_PRI(priority) > s->max_level_syslog)
+ return;
+
+ /* First: priority field */
+ snprintf(header_priority, sizeof(header_priority), "<%i>", priority);
+ char_array_0(header_priority);
+ IOVEC_SET_STRING(iovec[n++], header_priority);
+
+ /* Second: timestamp */
+ t = tv ? tv->tv_sec : ((time_t) (now(CLOCK_REALTIME) / USEC_PER_SEC));
+ tm = localtime(&t);
+ if (!tm)
+ return;
+ if (strftime(header_time, sizeof(header_time), "%h %e %T ", tm) <= 0)
+ return;
+ IOVEC_SET_STRING(iovec[n++], header_time);
+
+ /* Third: identifier and PID */
+ if (ucred) {
+ if (!identifier) {
+ get_process_comm(ucred->pid, &ident_buf);
+ identifier = ident_buf;
+ }
+
+ snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) ucred->pid);
+ char_array_0(header_pid);
+
+ if (identifier)
+ IOVEC_SET_STRING(iovec[n++], identifier);
+
+ IOVEC_SET_STRING(iovec[n++], header_pid);
+ } else if (identifier) {
+ IOVEC_SET_STRING(iovec[n++], identifier);
+ IOVEC_SET_STRING(iovec[n++], ": ");
+ }
+
+ /* Fourth: message */
+ IOVEC_SET_STRING(iovec[n++], message);
+
+ forward_syslog_iovec(s, iovec, n, ucred, tv);
+
+ free(ident_buf);
+}
+
+int syslog_fixup_facility(int priority) {
+
+ if ((priority & LOG_FACMASK) == 0)
+ return (priority & LOG_PRIMASK) | LOG_USER;
+
+ return priority;
+}
+
+size_t syslog_parse_identifier(const char **buf, char **identifier, char **pid) {
+ const char *p;
+ char *t;
+ size_t l, e;
+
+ assert(buf);
+ assert(identifier);
+ assert(pid);
+
+ p = *buf;
+
+ p += strspn(p, WHITESPACE);
+ l = strcspn(p, WHITESPACE);
+
+ if (l <= 0 ||
+ p[l-1] != ':')
+ return 0;
+
+ e = l;
+ l--;
+
+ if (p[l-1] == ']') {
+ size_t k = l-1;
+
+ for (;;) {
+
+ if (p[k] == '[') {
+ t = strndup(p+k+1, l-k-2);
+ if (t)
+ *pid = t;
+
+ l = k;
+ break;
+ }
+
+ if (k == 0)
+ break;
+
+ k--;
+ }
+ }
+
+ t = strndup(p, l);
+ if (t)
+ *identifier = t;
+
+ e += strspn(p + e, WHITESPACE);
+ *buf = p + e;
+ return e;
+}
+
+void syslog_parse_priority(char **p, int *priority) {
+ int a = 0, b = 0, c = 0;
+ int k;
+
+ assert(p);
+ assert(*p);
+ assert(priority);
+
+ if ((*p)[0] != '<')
+ return;
+
+ if (!strchr(*p, '>'))
+ return;
+
+ if ((*p)[2] == '>') {
+ c = undecchar((*p)[1]);
+ k = 3;
+ } else if ((*p)[3] == '>') {
+ b = undecchar((*p)[1]);
+ c = undecchar((*p)[2]);
+ k = 4;
+ } else if ((*p)[4] == '>') {
+ a = undecchar((*p)[1]);
+ b = undecchar((*p)[2]);
+ c = undecchar((*p)[3]);
+ k = 5;
+ } else
+ return;
+
+ if (a < 0 || b < 0 || c < 0)
+ return;
+
+ *priority = a*100+b*10+c;
+ *p += k;
+}
+
+static void syslog_skip_date(char **buf) {
+ enum {
+ LETTER,
+ SPACE,
+ NUMBER,
+ SPACE_OR_NUMBER,
+ COLON
+ } sequence[] = {
+ LETTER, LETTER, LETTER,
+ SPACE,
+ SPACE_OR_NUMBER, NUMBER,
+ SPACE,
+ SPACE_OR_NUMBER, NUMBER,
+ COLON,
+ SPACE_OR_NUMBER, NUMBER,
+ COLON,
+ SPACE_OR_NUMBER, NUMBER,
+ SPACE
+ };
+
+ char *p;
+ unsigned i;
+
+ assert(buf);
+ assert(*buf);
+
+ p = *buf;
+
+ for (i = 0; i < ELEMENTSOF(sequence); i++, p++) {
+
+ if (!*p)
+ return;
+
+ switch (sequence[i]) {
+
+ case SPACE:
+ if (*p != ' ')
+ return;
+ break;
+
+ case SPACE_OR_NUMBER:
+ if (*p == ' ')
+ break;
+
+ /* fall through */
+
+ case NUMBER:
+ if (*p < '0' || *p > '9')
+ return;
+
+ break;
+
+ case LETTER:
+ if (!(*p >= 'A' && *p <= 'Z') &&
+ !(*p >= 'a' && *p <= 'z'))
+ return;
+
+ break;
+
+ case COLON:
+ if (*p != ':')
+ return;
+ break;
+
+ }
+ }
+
+ *buf = p;
+}
+
+void server_process_syslog_message(
+ Server *s,
+ const char *buf,
+ struct ucred *ucred,
+ struct timeval *tv,
+ const char *label,
+ size_t label_len) {
+
+ char *message = NULL, *syslog_priority = NULL, *syslog_facility = NULL, *syslog_identifier = NULL, *syslog_pid = NULL;
+ struct iovec iovec[N_IOVEC_META_FIELDS + 6];
+ unsigned n = 0;
+ int priority = LOG_USER | LOG_INFO;
+ char *identifier = NULL, *pid = NULL;
+ const char *orig;
+
+ assert(s);
+ assert(buf);
+
+ orig = buf;
+ syslog_parse_priority((char**) &buf, &priority);
+
+ if (s->forward_to_syslog)
+ forward_syslog_raw(s, priority, orig, ucred, tv);
+
+ syslog_skip_date((char**) &buf);
+ syslog_parse_identifier(&buf, &identifier, &pid);
+
+ if (s->forward_to_kmsg)
+ server_forward_kmsg(s, priority, identifier, buf, ucred);
+
+ if (s->forward_to_console)
+ server_forward_console(s, priority, identifier, buf, ucred);
+
+ IOVEC_SET_STRING(iovec[n++], "_TRANSPORT=syslog");
+
+ if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
+ IOVEC_SET_STRING(iovec[n++], syslog_priority);
+
+ if (priority & LOG_FACMASK)
+ if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
+ IOVEC_SET_STRING(iovec[n++], syslog_facility);
+
+ if (identifier) {
+ syslog_identifier = strappend("SYSLOG_IDENTIFIER=", identifier);
+ if (syslog_identifier)
+ IOVEC_SET_STRING(iovec[n++], syslog_identifier);
+ }
+
+ if (pid) {
+ syslog_pid = strappend("SYSLOG_PID=", pid);
+ if (syslog_pid)
+ IOVEC_SET_STRING(iovec[n++], syslog_pid);
+ }
+
+ message = strappend("MESSAGE=", buf);
+ if (message)
+ IOVEC_SET_STRING(iovec[n++], message);
+
+ server_dispatch_message(s, iovec, n, ELEMENTSOF(iovec), ucred, tv, label, label_len, NULL, priority);
+
+ free(message);
+ free(identifier);
+ free(pid);
+ free(syslog_priority);
+ free(syslog_facility);
+ free(syslog_identifier);
+ free(syslog_pid);
+}
+
+int server_open_syslog_socket(Server *s) {
+ int one, r;
+ struct epoll_event ev;
+
+ assert(s);
+
+ if (s->syslog_fd < 0) {
+ union sockaddr_union sa = {
+ .un.sun_family = AF_UNIX,
+ .un.sun_path = "/dev/log",
+ };
+
+ s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
+ if (s->syslog_fd < 0) {
+ log_error("socket() failed: %m");
+ return -errno;
+ }
+
+ unlink(sa.un.sun_path);
+
+ r = bind(s->syslog_fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
+ if (r < 0) {
+ log_error("bind() failed: %m");
+ return -errno;
+ }
+
+ chmod(sa.un.sun_path, 0666);
+ } else
+ fd_nonblock(s->syslog_fd, 1);
+
+ one = 1;
+ r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
+ if (r < 0) {
+ log_error("SO_PASSCRED failed: %m");
+ return -errno;
+ }
+
+#ifdef HAVE_SELINUX
+ one = 1;
+ r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSSEC, &one, sizeof(one));
+ if (r < 0)
+ log_warning("SO_PASSSEC failed: %m");
+#endif
+
+ one = 1;
+ r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
+ if (r < 0) {
+ log_error("SO_TIMESTAMP failed: %m");
+ return -errno;
+ }
+
+ zero(ev);
+ ev.events = EPOLLIN;
+ ev.data.fd = s->syslog_fd;
+ if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->syslog_fd, &ev) < 0) {
+ log_error("Failed to add syslog server fd to epoll object: %m");
+ return -errno;
+ }
+
+ return 0;
+}
+
+void server_maybe_warn_forward_syslog_missed(Server *s) {
+ usec_t n;
+ assert(s);
+
+ if (s->n_forward_syslog_missed <= 0)
+ return;
+
+ n = now(CLOCK_MONOTONIC);
+ if (s->last_warn_forward_syslog_missed + WARN_FORWARD_SYSLOG_MISSED_USEC > n)
+ return;
+
+ server_driver_message(s, SD_MESSAGE_FORWARD_SYSLOG_MISSED, "Forwarding to syslog missed %u messages.", s->n_forward_syslog_missed);
+
+ s->n_forward_syslog_missed = 0;
+ s->last_warn_forward_syslog_missed = n;
+}
diff --git a/src/journal/journald-syslog.h b/src/journal/journald-syslog.h
new file mode 100644
index 0000000000..324b70eef0
--- /dev/null
+++ b/src/journal/journald-syslog.h
@@ -0,0 +1,36 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "journald-server.h"
+
+int syslog_fixup_facility(int priority) _const_;
+
+void syslog_parse_priority(char **p, int *priority);
+size_t syslog_parse_identifier(const char **buf, char **identifier, char **pid);
+
+void server_forward_syslog(Server *s, int priority, const char *identifier, const char *message, struct ucred *ucred, struct timeval *tv);
+
+void server_process_syslog_message(Server *s, const char *buf, struct ucred *ucred, struct timeval *tv, const char *label, size_t label_len);
+int server_open_syslog_socket(Server *s);
+
+void server_maybe_warn_forward_syslog_missed(Server *s);
diff --git a/src/journal/journald.c b/src/journal/journald.c
new file mode 100644
index 0000000000..5fb10b1d3f
--- /dev/null
+++ b/src/journal/journald.c
@@ -0,0 +1,139 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/epoll.h>
+#include <sys/socket.h>
+#include <errno.h>
+#include <unistd.h>
+
+#include <systemd/sd-journal.h>
+#include <systemd/sd-messages.h>
+#include <systemd/sd-daemon.h>
+
+#include "journal-authenticate.h"
+#include "journald-server.h"
+#include "journald-kmsg.h"
+#include "journald-syslog.h"
+
+int main(int argc, char *argv[]) {
+ Server server;
+ int r;
+
+ /* if (getppid() != 1) { */
+ /* log_error("This program should be invoked by init only."); */
+ /* return EXIT_FAILURE; */
+ /* } */
+
+ if (argc > 1) {
+ log_error("This program does not take arguments.");
+ return EXIT_FAILURE;
+ }
+
+ log_set_target(LOG_TARGET_SAFE);
+ log_set_facility(LOG_SYSLOG);
+ log_parse_environment();
+ log_open();
+
+ umask(0022);
+
+ r = server_init(&server);
+ if (r < 0)
+ goto finish;
+
+ server_vacuum(&server);
+ server_flush_to_var(&server);
+ server_flush_dev_kmsg(&server);
+
+ log_debug("systemd-journald running as pid %lu", (unsigned long) getpid());
+ server_driver_message(&server, SD_MESSAGE_JOURNAL_START, "Journal started");
+
+ sd_notify(false,
+ "READY=1\n"
+ "STATUS=Processing requests...");
+
+ for (;;) {
+ struct epoll_event event;
+ int t = -1;
+ usec_t n;
+
+ n = now(CLOCK_REALTIME);
+
+ if (server.max_retention_usec > 0 && server.oldest_file_usec > 0) {
+
+ /* The retention time is reached, so let's vacuum! */
+ if (server.oldest_file_usec + server.max_retention_usec < n) {
+ log_info("Retention time reached.");
+ server_rotate(&server);
+ server_vacuum(&server);
+ continue;
+ }
+
+ /* Calculate when to rotate the next time */
+ t = (int) ((server.oldest_file_usec + server.max_retention_usec - n + USEC_PER_MSEC - 1) / USEC_PER_MSEC);
+ }
+
+#ifdef HAVE_GCRYPT
+ if (server.system_journal) {
+ usec_t u;
+
+ if (journal_file_next_evolve_usec(server.system_journal, &u)) {
+ if (n >= u)
+ t = 0;
+ else
+ t = MIN(t, (int) ((u - n + USEC_PER_MSEC - 1) / USEC_PER_MSEC));
+ }
+ }
+#endif
+
+ r = epoll_wait(server.epoll_fd, &event, 1, t);
+ if (r < 0) {
+
+ if (errno == EINTR)
+ continue;
+
+ log_error("epoll_wait() failed: %m");
+ r = -errno;
+ goto finish;
+ }
+
+ if (r > 0) {
+ r = process_event(&server, &event);
+ if (r < 0)
+ goto finish;
+ else if (r == 0)
+ break;
+ }
+
+ server_maybe_append_tags(&server);
+ server_maybe_warn_forward_syslog_missed(&server);
+ }
+
+ log_debug("systemd-journald stopped as pid %lu", (unsigned long) getpid());
+ server_driver_message(&server, SD_MESSAGE_JOURNAL_STOP, "Journal stopped");
+
+finish:
+ sd_notify(false,
+ "STATUS=Shutting down...");
+
+ server_done(&server);
+
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/src/journal/journald.conf b/src/journal/journald.conf
new file mode 100644
index 0000000000..5410477201
--- /dev/null
+++ b/src/journal/journald.conf
@@ -0,0 +1,33 @@
+# This file is part of systemd.
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 of the License, or
+# (at your option) any later version.
+#
+# See journald.conf(5) for details
+
+[Journal]
+#Storage=auto
+#Compress=yes
+#Seal=yes
+#SplitMode=login
+#SyncIntervalSec=5m
+#RateLimitInterval=10s
+#RateLimitBurst=200
+#SystemMaxUse=
+#SystemKeepFree=
+#SystemMaxFileSize=
+#RuntimeMaxUse=
+#RuntimeKeepFree=
+#RuntimeMaxFileSize=
+#MaxRetentionSec=
+#MaxFileSec=1month
+#ForwardToSyslog=yes
+#ForwardToKMsg=no
+#ForwardToConsole=no
+#TTYPath=/dev/console
+#MaxLevelStore=debug
+#MaxLevelSyslog=debug
+#MaxLevelKMsg=notice
+#MaxLevelConsole=info
diff --git a/src/journal/libsystemd-journal.pc.in b/src/journal/libsystemd-journal.pc.in
new file mode 100644
index 0000000000..9883595644
--- /dev/null
+++ b/src/journal/libsystemd-journal.pc.in
@@ -0,0 +1,19 @@
+# This file is part of systemd.
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 of the License, or
+# (at your option) any later version.
+
+prefix=@prefix@
+exec_prefix=@exec_prefix@
+libdir=@libdir@
+includedir=@includedir@
+
+Name: systemd
+Description: systemd Journal Utility Library
+URL: @PACKAGE_URL@
+Version: @PACKAGE_VERSION@
+Requires: libsystemd-id128 = @PACKAGE_VERSION@
+Libs: -L${libdir} -lsystemd-journal
+Cflags: -I${includedir}
diff --git a/src/journal/libsystemd-journal.sym b/src/journal/libsystemd-journal.sym
new file mode 100644
index 0000000000..449f37c4da
--- /dev/null
+++ b/src/journal/libsystemd-journal.sym
@@ -0,0 +1,106 @@
+/***
+ This file is part of systemd.
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+***/
+
+/* Original symbols from systemd v38 */
+
+LIBSYSTEMD_JOURNAL_38 {
+global:
+ sd_journal_print;
+ sd_journal_printv;
+ sd_journal_send;
+ sd_journal_sendv;
+ sd_journal_stream_fd;
+ sd_journal_open;
+ sd_journal_close;
+ sd_journal_previous;
+ sd_journal_next;
+ sd_journal_previous_skip;
+ sd_journal_next_skip;
+ sd_journal_get_realtime_usec;
+ sd_journal_get_monotonic_usec;
+ sd_journal_get_data;
+ sd_journal_enumerate_data;
+ sd_journal_restart_data;
+ sd_journal_add_match;
+ sd_journal_flush_matches;
+ sd_journal_seek_head;
+ sd_journal_seek_tail;
+ sd_journal_seek_monotonic_usec;
+ sd_journal_seek_realtime_usec;
+ sd_journal_seek_cursor;
+ sd_journal_get_cursor;
+ sd_journal_get_fd;
+ sd_journal_process;
+local:
+ *;
+};
+
+LIBSYSTEMD_JOURNAL_183 {
+global:
+ sd_journal_print_with_location;
+ sd_journal_printv_with_location;
+ sd_journal_send_with_location;
+ sd_journal_sendv_with_location;
+} LIBSYSTEMD_JOURNAL_38;
+
+LIBSYSTEMD_JOURNAL_184 {
+global:
+ sd_journal_get_cutoff_realtime_usec;
+ sd_journal_get_cutoff_monotonic_usec;
+} LIBSYSTEMD_JOURNAL_183;
+
+LIBSYSTEMD_JOURNAL_187 {
+global:
+ sd_journal_wait;
+ sd_journal_open_directory;
+ sd_journal_add_disjunction;
+} LIBSYSTEMD_JOURNAL_184;
+
+LIBSYSTEMD_JOURNAL_188 {
+global:
+ sd_journal_perror;
+ sd_journal_perror_with_location;
+} LIBSYSTEMD_JOURNAL_187;
+
+LIBSYSTEMD_JOURNAL_190 {
+global:
+ sd_journal_get_usage;
+} LIBSYSTEMD_JOURNAL_188;
+
+LIBSYSTEMD_JOURNAL_195 {
+global:
+ sd_journal_test_cursor;
+ sd_journal_query_unique;
+ sd_journal_enumerate_unique;
+ sd_journal_restart_unique;
+} LIBSYSTEMD_JOURNAL_190;
+
+LIBSYSTEMD_JOURNAL_196 {
+global:
+ sd_journal_get_catalog;
+ sd_journal_get_catalog_for_message_id;
+ sd_journal_set_data_threshold;
+ sd_journal_get_data_threshold;
+} LIBSYSTEMD_JOURNAL_195;
+
+LIBSYSTEMD_JOURNAL_198 {
+global:
+ sd_journal_reliable_fd;
+} LIBSYSTEMD_JOURNAL_196;
+
+LIBSYSTEMD_JOURNAL_201 {
+global:
+ sd_journal_get_events;
+ sd_journal_get_timeout;
+} LIBSYSTEMD_JOURNAL_198;
+
+LIBSYSTEMD_JOURNAL_202 {
+global:
+ sd_journal_add_conjunction;
+} LIBSYSTEMD_JOURNAL_201;
diff --git a/src/journal/lookup3.c b/src/journal/lookup3.c
new file mode 100644
index 0000000000..52ffdf7b1d
--- /dev/null
+++ b/src/journal/lookup3.c
@@ -0,0 +1,1009 @@
+/* Slightly modified by Lennart Poettering, to avoid name clashes, and
+ * unexport a few functions. */
+
+#include "lookup3.h"
+
+/*
+-------------------------------------------------------------------------------
+lookup3.c, by Bob Jenkins, May 2006, Public Domain.
+
+These are functions for producing 32-bit hashes for hash table lookup.
+hashword(), hashlittle(), hashlittle2(), hashbig(), mix(), and final()
+are externally useful functions. Routines to test the hash are included
+if SELF_TEST is defined. You can use this free for any purpose. It's in
+the public domain. It has no warranty.
+
+You probably want to use hashlittle(). hashlittle() and hashbig()
+hash byte arrays. hashlittle() is faster than hashbig() on
+little-endian machines. Intel and AMD are little-endian machines.
+On second thought, you probably want hashlittle2(), which is identical to
+hashlittle() except it returns two 32-bit hashes for the price of one.
+You could implement hashbig2() if you wanted but I haven't bothered here.
+
+If you want to find a hash of, say, exactly 7 integers, do
+ a = i1; b = i2; c = i3;
+ mix(a,b,c);
+ a += i4; b += i5; c += i6;
+ mix(a,b,c);
+ a += i7;
+ final(a,b,c);
+then use c as the hash value. If you have a variable length array of
+4-byte integers to hash, use hashword(). If you have a byte array (like
+a character string), use hashlittle(). If you have several byte arrays, or
+a mix of things, see the comments above hashlittle().
+
+Why is this so big? I read 12 bytes at a time into 3 4-byte integers,
+then mix those integers. This is fast (you can do a lot more thorough
+mixing with 12*3 instructions on 3 integers than you can with 3 instructions
+on 1 byte), but shoehorning those bytes into integers efficiently is messy.
+-------------------------------------------------------------------------------
+*/
+/* #define SELF_TEST 1 */
+
+#include <stdio.h> /* defines printf for tests */
+#include <time.h> /* defines time_t for timings in the test */
+#include <stdint.h> /* defines uint32_t etc */
+#include <sys/param.h> /* attempt to define endianness */
+#ifdef linux
+# include <endian.h> /* attempt to define endianness */
+#endif
+
+/*
+ * My best guess at if you are big-endian or little-endian. This may
+ * need adjustment.
+ */
+#if (defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && \
+ __BYTE_ORDER == __LITTLE_ENDIAN) || \
+ (defined(i386) || defined(__i386__) || defined(__i486__) || \
+ defined(__i586__) || defined(__i686__) || defined(vax) || defined(MIPSEL))
+# define HASH_LITTLE_ENDIAN 1
+# define HASH_BIG_ENDIAN 0
+#elif (defined(__BYTE_ORDER) && defined(__BIG_ENDIAN) && \
+ __BYTE_ORDER == __BIG_ENDIAN) || \
+ (defined(sparc) || defined(POWERPC) || defined(mc68000) || defined(sel))
+# define HASH_LITTLE_ENDIAN 0
+# define HASH_BIG_ENDIAN 1
+#else
+# define HASH_LITTLE_ENDIAN 0
+# define HASH_BIG_ENDIAN 0
+#endif
+
+#define hashsize(n) ((uint32_t)1<<(n))
+#define hashmask(n) (hashsize(n)-1)
+#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
+
+/*
+-------------------------------------------------------------------------------
+mix -- mix 3 32-bit values reversibly.
+
+This is reversible, so any information in (a,b,c) before mix() is
+still in (a,b,c) after mix().
+
+If four pairs of (a,b,c) inputs are run through mix(), or through
+mix() in reverse, there are at least 32 bits of the output that
+are sometimes the same for one pair and different for another pair.
+This was tested for:
+* pairs that differed by one bit, by two bits, in any combination
+ of top bits of (a,b,c), or in any combination of bottom bits of
+ (a,b,c).
+* "differ" is defined as +, -, ^, or ~^. For + and -, I transformed
+ the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
+ is commonly produced by subtraction) look like a single 1-bit
+ difference.
+* the base values were pseudorandom, all zero but one bit set, or
+ all zero plus a counter that starts at zero.
+
+Some k values for my "a-=c; a^=rot(c,k); c+=b;" arrangement that
+satisfy this are
+ 4 6 8 16 19 4
+ 9 15 3 18 27 15
+ 14 9 3 7 17 3
+Well, "9 15 3 18 27 15" didn't quite get 32 bits diffing
+for "differ" defined as + with a one-bit base and a two-bit delta. I
+used http://burtleburtle.net/bob/hash/avalanche.html to choose
+the operations, constants, and arrangements of the variables.
+
+This does not achieve avalanche. There are input bits of (a,b,c)
+that fail to affect some output bits of (a,b,c), especially of a. The
+most thoroughly mixed value is c, but it doesn't really even achieve
+avalanche in c.
+
+This allows some parallelism. Read-after-writes are good at doubling
+the number of bits affected, so the goal of mixing pulls in the opposite
+direction as the goal of parallelism. I did what I could. Rotates
+seem to cost as much as shifts on every machine I could lay my hands
+on, and rotates are much kinder to the top and bottom bits, so I used
+rotates.
+-------------------------------------------------------------------------------
+*/
+#define mix(a,b,c) \
+{ \
+ a -= c; a ^= rot(c, 4); c += b; \
+ b -= a; b ^= rot(a, 6); a += c; \
+ c -= b; c ^= rot(b, 8); b += a; \
+ a -= c; a ^= rot(c,16); c += b; \
+ b -= a; b ^= rot(a,19); a += c; \
+ c -= b; c ^= rot(b, 4); b += a; \
+}
+
+/*
+-------------------------------------------------------------------------------
+final -- final mixing of 3 32-bit values (a,b,c) into c
+
+Pairs of (a,b,c) values differing in only a few bits will usually
+produce values of c that look totally different. This was tested for
+* pairs that differed by one bit, by two bits, in any combination
+ of top bits of (a,b,c), or in any combination of bottom bits of
+ (a,b,c).
+* "differ" is defined as +, -, ^, or ~^. For + and -, I transformed
+ the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
+ is commonly produced by subtraction) look like a single 1-bit
+ difference.
+* the base values were pseudorandom, all zero but one bit set, or
+ all zero plus a counter that starts at zero.
+
+These constants passed:
+ 14 11 25 16 4 14 24
+ 12 14 25 16 4 14 24
+and these came close:
+ 4 8 15 26 3 22 24
+ 10 8 15 26 3 22 24
+ 11 8 15 26 3 22 24
+-------------------------------------------------------------------------------
+*/
+#define final(a,b,c) \
+{ \
+ c ^= b; c -= rot(b,14); \
+ a ^= c; a -= rot(c,11); \
+ b ^= a; b -= rot(a,25); \
+ c ^= b; c -= rot(b,16); \
+ a ^= c; a -= rot(c,4); \
+ b ^= a; b -= rot(a,14); \
+ c ^= b; c -= rot(b,24); \
+}
+
+/*
+--------------------------------------------------------------------
+ This works on all machines. To be useful, it requires
+ -- that the key be an array of uint32_t's, and
+ -- that the length be the number of uint32_t's in the key
+
+ The function hashword() is identical to hashlittle() on little-endian
+ machines, and identical to hashbig() on big-endian machines,
+ except that the length has to be measured in uint32_ts rather than in
+ bytes. hashlittle() is more complicated than hashword() only because
+ hashlittle() has to dance around fitting the key bytes into registers.
+--------------------------------------------------------------------
+*/
+uint32_t jenkins_hashword(
+const uint32_t *k, /* the key, an array of uint32_t values */
+size_t length, /* the length of the key, in uint32_ts */
+uint32_t initval) /* the previous hash, or an arbitrary value */
+{
+ uint32_t a,b,c;
+
+ /* Set up the internal state */
+ a = b = c = 0xdeadbeef + (((uint32_t)length)<<2) + initval;
+
+ /*------------------------------------------------- handle most of the key */
+ while (length > 3)
+ {
+ a += k[0];
+ b += k[1];
+ c += k[2];
+ mix(a,b,c);
+ length -= 3;
+ k += 3;
+ }
+
+ /*------------------------------------------- handle the last 3 uint32_t's */
+ switch(length) /* all the case statements fall through */
+ {
+ case 3 : c+=k[2];
+ case 2 : b+=k[1];
+ case 1 : a+=k[0];
+ final(a,b,c);
+ case 0: /* case 0: nothing left to add */
+ break;
+ }
+ /*------------------------------------------------------ report the result */
+ return c;
+}
+
+
+/*
+--------------------------------------------------------------------
+hashword2() -- same as hashword(), but take two seeds and return two
+32-bit values. pc and pb must both be nonnull, and *pc and *pb must
+both be initialized with seeds. If you pass in (*pb)==0, the output
+(*pc) will be the same as the return value from hashword().
+--------------------------------------------------------------------
+*/
+void jenkins_hashword2 (
+const uint32_t *k, /* the key, an array of uint32_t values */
+size_t length, /* the length of the key, in uint32_ts */
+uint32_t *pc, /* IN: seed OUT: primary hash value */
+uint32_t *pb) /* IN: more seed OUT: secondary hash value */
+{
+ uint32_t a,b,c;
+
+ /* Set up the internal state */
+ a = b = c = 0xdeadbeef + ((uint32_t)(length<<2)) + *pc;
+ c += *pb;
+
+ /*------------------------------------------------- handle most of the key */
+ while (length > 3)
+ {
+ a += k[0];
+ b += k[1];
+ c += k[2];
+ mix(a,b,c);
+ length -= 3;
+ k += 3;
+ }
+
+ /*------------------------------------------- handle the last 3 uint32_t's */
+ switch(length) /* all the case statements fall through */
+ {
+ case 3 : c+=k[2];
+ case 2 : b+=k[1];
+ case 1 : a+=k[0];
+ final(a,b,c);
+ case 0: /* case 0: nothing left to add */
+ break;
+ }
+ /*------------------------------------------------------ report the result */
+ *pc=c; *pb=b;
+}
+
+
+/*
+-------------------------------------------------------------------------------
+hashlittle() -- hash a variable-length key into a 32-bit value
+ k : the key (the unaligned variable-length array of bytes)
+ length : the length of the key, counting by bytes
+ initval : can be any 4-byte value
+Returns a 32-bit value. Every bit of the key affects every bit of
+the return value. Two keys differing by one or two bits will have
+totally different hash values.
+
+The best hash table sizes are powers of 2. There is no need to do
+mod a prime (mod is sooo slow!). If you need less than 32 bits,
+use a bitmask. For example, if you need only 10 bits, do
+ h = (h & hashmask(10));
+In which case, the hash table should have hashsize(10) elements.
+
+If you are hashing n strings (uint8_t **)k, do it like this:
+ for (i=0, h=0; i<n; ++i) h = hashlittle( k[i], len[i], h);
+
+By Bob Jenkins, 2006. bob_jenkins@burtleburtle.net. You may use this
+code any way you wish, private, educational, or commercial. It's free.
+
+Use for hash table lookup, or anything where one collision in 2^^32 is
+acceptable. Do NOT use for cryptographic purposes.
+-------------------------------------------------------------------------------
+*/
+
+uint32_t jenkins_hashlittle( const void *key, size_t length, uint32_t initval)
+{
+ uint32_t a,b,c; /* internal state */
+ union { const void *ptr; size_t i; } u; /* needed for Mac Powerbook G4 */
+
+ /* Set up the internal state */
+ a = b = c = 0xdeadbeef + ((uint32_t)length) + initval;
+
+ u.ptr = key;
+ if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) {
+ const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */
+
+ /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
+ while (length > 12)
+ {
+ a += k[0];
+ b += k[1];
+ c += k[2];
+ mix(a,b,c);
+ length -= 12;
+ k += 3;
+ }
+
+ /*----------------------------- handle the last (probably partial) block */
+ /*
+ * "k[2]&0xffffff" actually reads beyond the end of the string, but
+ * then masks off the part it's not allowed to read. Because the
+ * string is aligned, the masked-off tail is in the same word as the
+ * rest of the string. Every machine with memory protection I've seen
+ * does it on word boundaries, so is OK with this. But VALGRIND will
+ * still catch it and complain. The masking trick does make the hash
+ * noticeably faster for short strings (like English words).
+ */
+#ifndef VALGRIND
+
+ switch(length)
+ {
+ case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
+ case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;
+ case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;
+ case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;
+ case 8 : b+=k[1]; a+=k[0]; break;
+ case 7 : b+=k[1]&0xffffff; a+=k[0]; break;
+ case 6 : b+=k[1]&0xffff; a+=k[0]; break;
+ case 5 : b+=k[1]&0xff; a+=k[0]; break;
+ case 4 : a+=k[0]; break;
+ case 3 : a+=k[0]&0xffffff; break;
+ case 2 : a+=k[0]&0xffff; break;
+ case 1 : a+=k[0]&0xff; break;
+ case 0 : return c; /* zero length strings require no mixing */
+ }
+
+#else /* make valgrind happy */
+ {
+ const uint8_t *k8 = (const uint8_t *) k;
+
+ switch(length)
+ {
+ case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
+ case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
+ case 10: c+=((uint32_t)k8[9])<<8; /* fall through */
+ case 9 : c+=k8[8]; /* fall through */
+ case 8 : b+=k[1]; a+=k[0]; break;
+ case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
+ case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */
+ case 5 : b+=k8[4]; /* fall through */
+ case 4 : a+=k[0]; break;
+ case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
+ case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */
+ case 1 : a+=k8[0]; break;
+ case 0 : return c;
+ }
+ }
+
+#endif /* !valgrind */
+
+ } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) {
+ const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */
+ const uint8_t *k8;
+
+ /*--------------- all but last block: aligned reads and different mixing */
+ while (length > 12)
+ {
+ a += k[0] + (((uint32_t)k[1])<<16);
+ b += k[2] + (((uint32_t)k[3])<<16);
+ c += k[4] + (((uint32_t)k[5])<<16);
+ mix(a,b,c);
+ length -= 12;
+ k += 6;
+ }
+
+ /*----------------------------- handle the last (probably partial) block */
+ k8 = (const uint8_t *)k;
+ switch(length)
+ {
+ case 12: c+=k[4]+(((uint32_t)k[5])<<16);
+ b+=k[2]+(((uint32_t)k[3])<<16);
+ a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
+ case 10: c+=k[4];
+ b+=k[2]+(((uint32_t)k[3])<<16);
+ a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 9 : c+=k8[8]; /* fall through */
+ case 8 : b+=k[2]+(((uint32_t)k[3])<<16);
+ a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
+ case 6 : b+=k[2];
+ a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 5 : b+=k8[4]; /* fall through */
+ case 4 : a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
+ case 2 : a+=k[0];
+ break;
+ case 1 : a+=k8[0];
+ break;
+ case 0 : return c; /* zero length requires no mixing */
+ }
+
+ } else { /* need to read the key one byte at a time */
+ const uint8_t *k = (const uint8_t *)key;
+
+ /*--------------- all but the last block: affect some 32 bits of (a,b,c) */
+ while (length > 12)
+ {
+ a += k[0];
+ a += ((uint32_t)k[1])<<8;
+ a += ((uint32_t)k[2])<<16;
+ a += ((uint32_t)k[3])<<24;
+ b += k[4];
+ b += ((uint32_t)k[5])<<8;
+ b += ((uint32_t)k[6])<<16;
+ b += ((uint32_t)k[7])<<24;
+ c += k[8];
+ c += ((uint32_t)k[9])<<8;
+ c += ((uint32_t)k[10])<<16;
+ c += ((uint32_t)k[11])<<24;
+ mix(a,b,c);
+ length -= 12;
+ k += 12;
+ }
+
+ /*-------------------------------- last block: affect all 32 bits of (c) */
+ switch(length) /* all the case statements fall through */
+ {
+ case 12: c+=((uint32_t)k[11])<<24;
+ case 11: c+=((uint32_t)k[10])<<16;
+ case 10: c+=((uint32_t)k[9])<<8;
+ case 9 : c+=k[8];
+ case 8 : b+=((uint32_t)k[7])<<24;
+ case 7 : b+=((uint32_t)k[6])<<16;
+ case 6 : b+=((uint32_t)k[5])<<8;
+ case 5 : b+=k[4];
+ case 4 : a+=((uint32_t)k[3])<<24;
+ case 3 : a+=((uint32_t)k[2])<<16;
+ case 2 : a+=((uint32_t)k[1])<<8;
+ case 1 : a+=k[0];
+ break;
+ case 0 : return c;
+ }
+ }
+
+ final(a,b,c);
+ return c;
+}
+
+
+/*
+ * hashlittle2: return 2 32-bit hash values
+ *
+ * This is identical to hashlittle(), except it returns two 32-bit hash
+ * values instead of just one. This is good enough for hash table
+ * lookup with 2^^64 buckets, or if you want a second hash if you're not
+ * happy with the first, or if you want a probably-unique 64-bit ID for
+ * the key. *pc is better mixed than *pb, so use *pc first. If you want
+ * a 64-bit value do something like "*pc + (((uint64_t)*pb)<<32)".
+ */
+void jenkins_hashlittle2(
+ const void *key, /* the key to hash */
+ size_t length, /* length of the key */
+ uint32_t *pc, /* IN: primary initval, OUT: primary hash */
+ uint32_t *pb) /* IN: secondary initval, OUT: secondary hash */
+{
+ uint32_t a,b,c; /* internal state */
+ union { const void *ptr; size_t i; } u; /* needed for Mac Powerbook G4 */
+
+ /* Set up the internal state */
+ a = b = c = 0xdeadbeef + ((uint32_t)length) + *pc;
+ c += *pb;
+
+ u.ptr = key;
+ if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) {
+ const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */
+
+ /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
+ while (length > 12)
+ {
+ a += k[0];
+ b += k[1];
+ c += k[2];
+ mix(a,b,c);
+ length -= 12;
+ k += 3;
+ }
+
+ /*----------------------------- handle the last (probably partial) block */
+ /*
+ * "k[2]&0xffffff" actually reads beyond the end of the string, but
+ * then masks off the part it's not allowed to read. Because the
+ * string is aligned, the masked-off tail is in the same word as the
+ * rest of the string. Every machine with memory protection I've seen
+ * does it on word boundaries, so is OK with this. But VALGRIND will
+ * still catch it and complain. The masking trick does make the hash
+ * noticeably faster for short strings (like English words).
+ */
+#ifndef VALGRIND
+
+ switch(length)
+ {
+ case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
+ case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;
+ case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;
+ case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;
+ case 8 : b+=k[1]; a+=k[0]; break;
+ case 7 : b+=k[1]&0xffffff; a+=k[0]; break;
+ case 6 : b+=k[1]&0xffff; a+=k[0]; break;
+ case 5 : b+=k[1]&0xff; a+=k[0]; break;
+ case 4 : a+=k[0]; break;
+ case 3 : a+=k[0]&0xffffff; break;
+ case 2 : a+=k[0]&0xffff; break;
+ case 1 : a+=k[0]&0xff; break;
+ case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */
+ }
+
+#else /* make valgrind happy */
+
+ {
+ const uint8_t *k8 = (const uint8_t *)k;
+ switch(length)
+ {
+ case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
+ case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
+ case 10: c+=((uint32_t)k8[9])<<8; /* fall through */
+ case 9 : c+=k8[8]; /* fall through */
+ case 8 : b+=k[1]; a+=k[0]; break;
+ case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
+ case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */
+ case 5 : b+=k8[4]; /* fall through */
+ case 4 : a+=k[0]; break;
+ case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
+ case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */
+ case 1 : a+=k8[0]; break;
+ case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */
+ }
+ }
+
+#endif /* !valgrind */
+
+ } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) {
+ const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */
+ const uint8_t *k8;
+
+ /*--------------- all but last block: aligned reads and different mixing */
+ while (length > 12)
+ {
+ a += k[0] + (((uint32_t)k[1])<<16);
+ b += k[2] + (((uint32_t)k[3])<<16);
+ c += k[4] + (((uint32_t)k[5])<<16);
+ mix(a,b,c);
+ length -= 12;
+ k += 6;
+ }
+
+ /*----------------------------- handle the last (probably partial) block */
+ k8 = (const uint8_t *)k;
+ switch(length)
+ {
+ case 12: c+=k[4]+(((uint32_t)k[5])<<16);
+ b+=k[2]+(((uint32_t)k[3])<<16);
+ a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
+ case 10: c+=k[4];
+ b+=k[2]+(((uint32_t)k[3])<<16);
+ a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 9 : c+=k8[8]; /* fall through */
+ case 8 : b+=k[2]+(((uint32_t)k[3])<<16);
+ a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
+ case 6 : b+=k[2];
+ a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 5 : b+=k8[4]; /* fall through */
+ case 4 : a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
+ case 2 : a+=k[0];
+ break;
+ case 1 : a+=k8[0];
+ break;
+ case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */
+ }
+
+ } else { /* need to read the key one byte at a time */
+ const uint8_t *k = (const uint8_t *)key;
+
+ /*--------------- all but the last block: affect some 32 bits of (a,b,c) */
+ while (length > 12)
+ {
+ a += k[0];
+ a += ((uint32_t)k[1])<<8;
+ a += ((uint32_t)k[2])<<16;
+ a += ((uint32_t)k[3])<<24;
+ b += k[4];
+ b += ((uint32_t)k[5])<<8;
+ b += ((uint32_t)k[6])<<16;
+ b += ((uint32_t)k[7])<<24;
+ c += k[8];
+ c += ((uint32_t)k[9])<<8;
+ c += ((uint32_t)k[10])<<16;
+ c += ((uint32_t)k[11])<<24;
+ mix(a,b,c);
+ length -= 12;
+ k += 12;
+ }
+
+ /*-------------------------------- last block: affect all 32 bits of (c) */
+ switch(length) /* all the case statements fall through */
+ {
+ case 12: c+=((uint32_t)k[11])<<24;
+ case 11: c+=((uint32_t)k[10])<<16;
+ case 10: c+=((uint32_t)k[9])<<8;
+ case 9 : c+=k[8];
+ case 8 : b+=((uint32_t)k[7])<<24;
+ case 7 : b+=((uint32_t)k[6])<<16;
+ case 6 : b+=((uint32_t)k[5])<<8;
+ case 5 : b+=k[4];
+ case 4 : a+=((uint32_t)k[3])<<24;
+ case 3 : a+=((uint32_t)k[2])<<16;
+ case 2 : a+=((uint32_t)k[1])<<8;
+ case 1 : a+=k[0];
+ break;
+ case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */
+ }
+ }
+
+ final(a,b,c);
+ *pc=c; *pb=b;
+}
+
+
+
+/*
+ * hashbig():
+ * This is the same as hashword() on big-endian machines. It is different
+ * from hashlittle() on all machines. hashbig() takes advantage of
+ * big-endian byte ordering.
+ */
+uint32_t jenkins_hashbig( const void *key, size_t length, uint32_t initval)
+{
+ uint32_t a,b,c;
+ union { const void *ptr; size_t i; } u; /* to cast key to (size_t) happily */
+
+ /* Set up the internal state */
+ a = b = c = 0xdeadbeef + ((uint32_t)length) + initval;
+
+ u.ptr = key;
+ if (HASH_BIG_ENDIAN && ((u.i & 0x3) == 0)) {
+ const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */
+
+ /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
+ while (length > 12)
+ {
+ a += k[0];
+ b += k[1];
+ c += k[2];
+ mix(a,b,c);
+ length -= 12;
+ k += 3;
+ }
+
+ /*----------------------------- handle the last (probably partial) block */
+ /*
+ * "k[2]<<8" actually reads beyond the end of the string, but
+ * then shifts out the part it's not allowed to read. Because the
+ * string is aligned, the illegal read is in the same word as the
+ * rest of the string. Every machine with memory protection I've seen
+ * does it on word boundaries, so is OK with this. But VALGRIND will
+ * still catch it and complain. The masking trick does make the hash
+ * noticeably faster for short strings (like English words).
+ */
+#ifndef VALGRIND
+
+ switch(length)
+ {
+ case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
+ case 11: c+=k[2]&0xffffff00; b+=k[1]; a+=k[0]; break;
+ case 10: c+=k[2]&0xffff0000; b+=k[1]; a+=k[0]; break;
+ case 9 : c+=k[2]&0xff000000; b+=k[1]; a+=k[0]; break;
+ case 8 : b+=k[1]; a+=k[0]; break;
+ case 7 : b+=k[1]&0xffffff00; a+=k[0]; break;
+ case 6 : b+=k[1]&0xffff0000; a+=k[0]; break;
+ case 5 : b+=k[1]&0xff000000; a+=k[0]; break;
+ case 4 : a+=k[0]; break;
+ case 3 : a+=k[0]&0xffffff00; break;
+ case 2 : a+=k[0]&0xffff0000; break;
+ case 1 : a+=k[0]&0xff000000; break;
+ case 0 : return c; /* zero length strings require no mixing */
+ }
+
+#else /* make valgrind happy */
+
+ {
+ const uint8_t *k8 = (const uint8_t *)k;
+ switch(length) /* all the case statements fall through */
+ {
+ case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
+ case 11: c+=((uint32_t)k8[10])<<8; /* fall through */
+ case 10: c+=((uint32_t)k8[9])<<16; /* fall through */
+ case 9 : c+=((uint32_t)k8[8])<<24; /* fall through */
+ case 8 : b+=k[1]; a+=k[0]; break;
+ case 7 : b+=((uint32_t)k8[6])<<8; /* fall through */
+ case 6 : b+=((uint32_t)k8[5])<<16; /* fall through */
+ case 5 : b+=((uint32_t)k8[4])<<24; /* fall through */
+ case 4 : a+=k[0]; break;
+ case 3 : a+=((uint32_t)k8[2])<<8; /* fall through */
+ case 2 : a+=((uint32_t)k8[1])<<16; /* fall through */
+ case 1 : a+=((uint32_t)k8[0])<<24; break;
+ case 0 : return c;
+ }
+ }
+
+#endif /* !VALGRIND */
+
+ } else { /* need to read the key one byte at a time */
+ const uint8_t *k = (const uint8_t *)key;
+
+ /*--------------- all but the last block: affect some 32 bits of (a,b,c) */
+ while (length > 12)
+ {
+ a += ((uint32_t)k[0])<<24;
+ a += ((uint32_t)k[1])<<16;
+ a += ((uint32_t)k[2])<<8;
+ a += ((uint32_t)k[3]);
+ b += ((uint32_t)k[4])<<24;
+ b += ((uint32_t)k[5])<<16;
+ b += ((uint32_t)k[6])<<8;
+ b += ((uint32_t)k[7]);
+ c += ((uint32_t)k[8])<<24;
+ c += ((uint32_t)k[9])<<16;
+ c += ((uint32_t)k[10])<<8;
+ c += ((uint32_t)k[11]);
+ mix(a,b,c);
+ length -= 12;
+ k += 12;
+ }
+
+ /*-------------------------------- last block: affect all 32 bits of (c) */
+ switch(length) /* all the case statements fall through */
+ {
+ case 12: c+=k[11];
+ case 11: c+=((uint32_t)k[10])<<8;
+ case 10: c+=((uint32_t)k[9])<<16;
+ case 9 : c+=((uint32_t)k[8])<<24;
+ case 8 : b+=k[7];
+ case 7 : b+=((uint32_t)k[6])<<8;
+ case 6 : b+=((uint32_t)k[5])<<16;
+ case 5 : b+=((uint32_t)k[4])<<24;
+ case 4 : a+=k[3];
+ case 3 : a+=((uint32_t)k[2])<<8;
+ case 2 : a+=((uint32_t)k[1])<<16;
+ case 1 : a+=((uint32_t)k[0])<<24;
+ break;
+ case 0 : return c;
+ }
+ }
+
+ final(a,b,c);
+ return c;
+}
+
+
+#ifdef SELF_TEST
+
+/* used for timings */
+void driver1()
+{
+ uint8_t buf[256];
+ uint32_t i;
+ uint32_t h=0;
+ time_t a,z;
+
+ time(&a);
+ for (i=0; i<256; ++i) buf[i] = 'x';
+ for (i=0; i<1; ++i)
+ {
+ h = hashlittle(&buf[0],1,h);
+ }
+ time(&z);
+ if (z-a > 0) printf("time %d %.8x\n", z-a, h);
+}
+
+/* check that every input bit changes every output bit half the time */
+#define HASHSTATE 1
+#define HASHLEN 1
+#define MAXPAIR 60
+#define MAXLEN 70
+void driver2()
+{
+ uint8_t qa[MAXLEN+1], qb[MAXLEN+2], *a = &qa[0], *b = &qb[1];
+ uint32_t c[HASHSTATE], d[HASHSTATE], i=0, j=0, k, l, m=0, z;
+ uint32_t e[HASHSTATE],f[HASHSTATE],g[HASHSTATE],h[HASHSTATE];
+ uint32_t x[HASHSTATE],y[HASHSTATE];
+ uint32_t hlen;
+
+ printf("No more than %d trials should ever be needed \n",MAXPAIR/2);
+ for (hlen=0; hlen < MAXLEN; ++hlen)
+ {
+ z=0;
+ for (i=0; i<hlen; ++i) /*----------------------- for each input byte, */
+ {
+ for (j=0; j<8; ++j) /*------------------------ for each input bit, */
+ {
+ for (m=1; m<8; ++m) /*------------ for serveral possible initvals, */
+ {
+ for (l=0; l<HASHSTATE; ++l)
+ e[l]=f[l]=g[l]=h[l]=x[l]=y[l]=~((uint32_t)0);
+
+ /*---- check that every output bit is affected by that input bit */
+ for (k=0; k<MAXPAIR; k+=2)
+ {
+ uint32_t finished=1;
+ /* keys have one bit different */
+ for (l=0; l<hlen+1; ++l) {a[l] = b[l] = (uint8_t)0;}
+ /* have a and b be two keys differing in only one bit */
+ a[i] ^= (k<<j);
+ a[i] ^= (k>>(8-j));
+ c[0] = hashlittle(a, hlen, m);
+ b[i] ^= ((k+1)<<j);
+ b[i] ^= ((k+1)>>(8-j));
+ d[0] = hashlittle(b, hlen, m);
+ /* check every bit is 1, 0, set, and not set at least once */
+ for (l=0; l<HASHSTATE; ++l)
+ {
+ e[l] &= (c[l]^d[l]);
+ f[l] &= ~(c[l]^d[l]);
+ g[l] &= c[l];
+ h[l] &= ~c[l];
+ x[l] &= d[l];
+ y[l] &= ~d[l];
+ if (e[l]|f[l]|g[l]|h[l]|x[l]|y[l]) finished=0;
+ }
+ if (finished) break;
+ }
+ if (k>z) z=k;
+ if (k==MAXPAIR)
+ {
+ printf("Some bit didn't change: ");
+ printf("%.8x %.8x %.8x %.8x %.8x %.8x ",
+ e[0],f[0],g[0],h[0],x[0],y[0]);
+ printf("i %d j %d m %d len %d\n", i, j, m, hlen);
+ }
+ if (z==MAXPAIR) goto done;
+ }
+ }
+ }
+ done:
+ if (z < MAXPAIR)
+ {
+ printf("Mix success %2d bytes %2d initvals ",i,m);
+ printf("required %d trials\n", z/2);
+ }
+ }
+ printf("\n");
+}
+
+/* Check for reading beyond the end of the buffer and alignment problems */
+void driver3()
+{
+ uint8_t buf[MAXLEN+20], *b;
+ uint32_t len;
+ uint8_t q[] = "This is the time for all good men to come to the aid of their country...";
+ uint32_t h;
+ uint8_t qq[] = "xThis is the time for all good men to come to the aid of their country...";
+ uint32_t i;
+ uint8_t qqq[] = "xxThis is the time for all good men to come to the aid of their country...";
+ uint32_t j;
+ uint8_t qqqq[] = "xxxThis is the time for all good men to come to the aid of their country...";
+ uint32_t ref,x,y;
+ uint8_t *p;
+
+ printf("Endianness. These lines should all be the same (for values filled in):\n");
+ printf("%.8x %.8x %.8x\n",
+ hashword((const uint32_t *)q, (sizeof(q)-1)/4, 13),
+ hashword((const uint32_t *)q, (sizeof(q)-5)/4, 13),
+ hashword((const uint32_t *)q, (sizeof(q)-9)/4, 13));
+ p = q;
+ printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n",
+ hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13),
+ hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13),
+ hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13),
+ hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13),
+ hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13),
+ hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13));
+ p = &qq[1];
+ printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n",
+ hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13),
+ hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13),
+ hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13),
+ hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13),
+ hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13),
+ hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13));
+ p = &qqq[2];
+ printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n",
+ hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13),
+ hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13),
+ hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13),
+ hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13),
+ hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13),
+ hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13));
+ p = &qqqq[3];
+ printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n",
+ hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13),
+ hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13),
+ hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13),
+ hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13),
+ hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13),
+ hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13));
+ printf("\n");
+
+ /* check that hashlittle2 and hashlittle produce the same results */
+ i=47; j=0;
+ hashlittle2(q, sizeof(q), &i, &j);
+ if (hashlittle(q, sizeof(q), 47) != i)
+ printf("hashlittle2 and hashlittle mismatch\n");
+
+ /* check that hashword2 and hashword produce the same results */
+ len = 0xdeadbeef;
+ i=47, j=0;
+ hashword2(&len, 1, &i, &j);
+ if (hashword(&len, 1, 47) != i)
+ printf("hashword2 and hashword mismatch %x %x\n",
+ i, hashword(&len, 1, 47));
+
+ /* check hashlittle doesn't read before or after the ends of the string */
+ for (h=0, b=buf+1; h<8; ++h, ++b)
+ {
+ for (i=0; i<MAXLEN; ++i)
+ {
+ len = i;
+ for (j=0; j<i; ++j) *(b+j)=0;
+
+ /* these should all be equal */
+ ref = hashlittle(b, len, (uint32_t)1);
+ *(b+i)=(uint8_t)~0;
+ *(b-1)=(uint8_t)~0;
+ x = hashlittle(b, len, (uint32_t)1);
+ y = hashlittle(b, len, (uint32_t)1);
+ if ((ref != x) || (ref != y))
+ {
+ printf("alignment error: %.8x %.8x %.8x %d %d\n",ref,x,y,
+ h, i);
+ }
+ }
+ }
+}
+
+/* check for problems with nulls */
+ void driver4()
+{
+ uint8_t buf[1];
+ uint32_t h,i,state[HASHSTATE];
+
+
+ buf[0] = ~0;
+ for (i=0; i<HASHSTATE; ++i) state[i] = 1;
+ printf("These should all be different\n");
+ for (i=0, h=0; i<8; ++i)
+ {
+ h = hashlittle(buf, 0, h);
+ printf("%2ld 0-byte strings, hash is %.8x\n", i, h);
+ }
+}
+
+void driver5()
+{
+ uint32_t b,c;
+ b=0, c=0, hashlittle2("", 0, &c, &b);
+ printf("hash is %.8lx %.8lx\n", c, b); /* deadbeef deadbeef */
+ b=0xdeadbeef, c=0, hashlittle2("", 0, &c, &b);
+ printf("hash is %.8lx %.8lx\n", c, b); /* bd5b7dde deadbeef */
+ b=0xdeadbeef, c=0xdeadbeef, hashlittle2("", 0, &c, &b);
+ printf("hash is %.8lx %.8lx\n", c, b); /* 9c093ccd bd5b7dde */
+ b=0, c=0, hashlittle2("Four score and seven years ago", 30, &c, &b);
+ printf("hash is %.8lx %.8lx\n", c, b); /* 17770551 ce7226e6 */
+ b=1, c=0, hashlittle2("Four score and seven years ago", 30, &c, &b);
+ printf("hash is %.8lx %.8lx\n", c, b); /* e3607cae bd371de4 */
+ b=0, c=1, hashlittle2("Four score and seven years ago", 30, &c, &b);
+ printf("hash is %.8lx %.8lx\n", c, b); /* cd628161 6cbea4b3 */
+ c = hashlittle("Four score and seven years ago", 30, 0);
+ printf("hash is %.8lx\n", c); /* 17770551 */
+ c = hashlittle("Four score and seven years ago", 30, 1);
+ printf("hash is %.8lx\n", c); /* cd628161 */
+}
+
+
+int main()
+{
+ driver1(); /* test that the key is hashed: used for timings */
+ driver2(); /* test that whole key is hashed thoroughly */
+ driver3(); /* test that nothing but the key is hashed */
+ driver4(); /* test hashing multiple buffers (all buffers are null) */
+ driver5(); /* test the hash against known vectors */
+ return 1;
+}
+
+#endif /* SELF_TEST */
diff --git a/src/journal/lookup3.h b/src/journal/lookup3.h
new file mode 100644
index 0000000000..3224473a6a
--- /dev/null
+++ b/src/journal/lookup3.h
@@ -0,0 +1,24 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+#include <inttypes.h>
+#include <sys/types.h>
+
+#include "macro.h"
+
+uint32_t jenkins_hashword(const uint32_t *k, size_t length, uint32_t initval) _pure_;
+void jenkins_hashword2(const uint32_t *k, size_t length, uint32_t *pc, uint32_t *pb);
+
+uint32_t jenkins_hashlittle(const void *key, size_t length, uint32_t initval) _pure_;
+void jenkins_hashlittle2(const void *key, size_t length, uint32_t *pc, uint32_t *pb);
+
+uint32_t jenkins_hashbig(const void *key, size_t length, uint32_t initval) _pure_;
+
+static inline uint64_t hash64(const void *data, size_t length) {
+ uint32_t a = 0, b = 0;
+
+ jenkins_hashlittle2(data, length, &a, &b);
+
+ return ((uint64_t) a << 32ULL) | (uint64_t) b;
+}
diff --git a/src/journal/microhttpd-util.c b/src/journal/microhttpd-util.c
new file mode 100644
index 0000000000..382087c790
--- /dev/null
+++ b/src/journal/microhttpd-util.c
@@ -0,0 +1,37 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Zbigniew Jędrzejewski-Szmek
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stddef.h>
+#include <stdio.h>
+
+#include "microhttpd-util.h"
+#include "log.h"
+#include "macro.h"
+#include "util.h"
+
+void microhttpd_logger(void *arg, const char *fmt, va_list ap) {
+ _cleanup_free_ char *f;
+ if (asprintf(&f, "microhttpd: %s", fmt) <= 0) {
+ log_oom();
+ return;
+ }
+ log_metav(LOG_INFO, NULL, 0, NULL, f, ap);
+}
diff --git a/src/journal/microhttpd-util.h b/src/journal/microhttpd-util.h
new file mode 100644
index 0000000000..20ad76990c
--- /dev/null
+++ b/src/journal/microhttpd-util.h
@@ -0,0 +1,28 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Zbigniew Jędrzejewski-Szmek
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#pragma once
+
+#include <stdarg.h>
+
+#include "macro.h"
+
+void microhttpd_logger(void *arg, const char *fmt, va_list ap) _printf_attr_(2, 0);
diff --git a/src/journal/mmap-cache.c b/src/journal/mmap-cache.c
new file mode 100644
index 0000000000..767f555526
--- /dev/null
+++ b/src/journal/mmap-cache.c
@@ -0,0 +1,576 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <stdlib.h>
+#include <sys/mman.h>
+#include <string.h>
+
+#include "hashmap.h"
+#include "list.h"
+#include "log.h"
+#include "util.h"
+#include "macro.h"
+#include "mmap-cache.h"
+
+typedef struct Window Window;
+typedef struct Context Context;
+typedef struct FileDescriptor FileDescriptor;
+
+struct Window {
+ MMapCache *cache;
+
+ bool keep_always;
+ bool in_unused;
+
+ int prot;
+ void *ptr;
+ uint64_t offset;
+ size_t size;
+
+ FileDescriptor *fd;
+
+ LIST_FIELDS(Window, by_fd);
+ LIST_FIELDS(Window, unused);
+
+ LIST_HEAD(Context, contexts);
+};
+
+struct Context {
+ MMapCache *cache;
+ unsigned id;
+ Window *window;
+
+ LIST_FIELDS(Context, by_window);
+};
+
+struct FileDescriptor {
+ MMapCache *cache;
+ int fd;
+ LIST_HEAD(Window, windows);
+};
+
+struct MMapCache {
+ int n_ref;
+ unsigned n_windows;
+
+ Hashmap *fds;
+ Hashmap *contexts;
+
+ LIST_HEAD(Window, unused);
+ Window *last_unused;
+};
+
+#define WINDOWS_MIN 64
+#define WINDOW_SIZE (8ULL*1024ULL*1024ULL)
+
+MMapCache* mmap_cache_new(void) {
+ MMapCache *m;
+
+ m = new0(MMapCache, 1);
+ if (!m)
+ return NULL;
+
+ m->n_ref = 1;
+ return m;
+}
+
+MMapCache* mmap_cache_ref(MMapCache *m) {
+ assert(m);
+ assert(m->n_ref > 0);
+
+ m->n_ref ++;
+ return m;
+}
+
+static void window_unlink(Window *w) {
+ Context *c;
+
+ assert(w);
+
+ if (w->ptr)
+ munmap(w->ptr, w->size);
+
+ if (w->fd)
+ LIST_REMOVE(Window, by_fd, w->fd->windows, w);
+
+ if (w->in_unused) {
+ if (w->cache->last_unused == w)
+ w->cache->last_unused = w->unused_prev;
+
+ LIST_REMOVE(Window, unused, w->cache->unused, w);
+ }
+
+ LIST_FOREACH(by_window, c, w->contexts) {
+ assert(c->window == w);
+ c->window = NULL;
+ }
+}
+
+static void window_free(Window *w) {
+ assert(w);
+
+ window_unlink(w);
+ w->cache->n_windows--;
+ free(w);
+}
+
+_pure_ static bool window_matches(Window *w, int fd, int prot, uint64_t offset, size_t size) {
+ assert(w);
+ assert(fd >= 0);
+ assert(size > 0);
+
+ return
+ w->fd &&
+ fd == w->fd->fd &&
+ prot == w->prot &&
+ offset >= w->offset &&
+ offset + size <= w->offset + w->size;
+}
+
+static Window *window_add(MMapCache *m) {
+ Window *w;
+
+ assert(m);
+
+ if (!m->last_unused || m->n_windows <= WINDOWS_MIN) {
+
+ /* Allocate a new window */
+ w = new0(Window, 1);
+ if (!w)
+ return NULL;
+ m->n_windows++;
+ } else {
+
+ /* Reuse an existing one */
+ w = m->last_unused;
+ window_unlink(w);
+ zero(*w);
+ }
+
+ w->cache = m;
+ return w;
+}
+
+static void context_detach_window(Context *c) {
+ Window *w;
+
+ assert(c);
+
+ if (!c->window)
+ return;
+
+ w = c->window;
+ c->window = NULL;
+ LIST_REMOVE(Context, by_window, w->contexts, c);
+
+ if (!w->contexts && !w->keep_always) {
+ /* Not used anymore? */
+ LIST_PREPEND(Window, unused, c->cache->unused, w);
+ if (!c->cache->last_unused)
+ c->cache->last_unused = w;
+
+ w->in_unused = true;
+ }
+}
+
+static void context_attach_window(Context *c, Window *w) {
+ assert(c);
+ assert(w);
+
+ if (c->window == w)
+ return;
+
+ context_detach_window(c);
+
+ if (w->in_unused) {
+ /* Used again? */
+ LIST_REMOVE(Window, unused, c->cache->unused, w);
+ if (c->cache->last_unused == w)
+ c->cache->last_unused = w->unused_prev;
+
+ w->in_unused = false;
+ }
+
+ c->window = w;
+ LIST_PREPEND(Context, by_window, w->contexts, c);
+}
+
+static Context *context_add(MMapCache *m, unsigned id) {
+ Context *c;
+ int r;
+
+ assert(m);
+
+ c = hashmap_get(m->contexts, UINT_TO_PTR(id + 1));
+ if (c)
+ return c;
+
+ r = hashmap_ensure_allocated(&m->contexts, trivial_hash_func, trivial_compare_func);
+ if (r < 0)
+ return NULL;
+
+ c = new0(Context, 1);
+ if (!c)
+ return NULL;
+
+ c->cache = m;
+ c->id = id;
+
+ r = hashmap_put(m->contexts, UINT_TO_PTR(id + 1), c);
+ if (r < 0) {
+ free(c);
+ return NULL;
+ }
+
+ return c;
+}
+
+static void context_free(Context *c) {
+ assert(c);
+
+ context_detach_window(c);
+
+ if (c->cache)
+ assert_se(hashmap_remove(c->cache->contexts, UINT_TO_PTR(c->id + 1)));
+
+ free(c);
+}
+
+static void fd_free(FileDescriptor *f) {
+ assert(f);
+
+ while (f->windows)
+ window_free(f->windows);
+
+ if (f->cache)
+ assert_se(hashmap_remove(f->cache->fds, INT_TO_PTR(f->fd + 1)));
+
+ free(f);
+}
+
+static FileDescriptor* fd_add(MMapCache *m, int fd) {
+ FileDescriptor *f;
+ int r;
+
+ assert(m);
+ assert(fd >= 0);
+
+ f = hashmap_get(m->fds, INT_TO_PTR(fd + 1));
+ if (f)
+ return f;
+
+ r = hashmap_ensure_allocated(&m->fds, trivial_hash_func, trivial_compare_func);
+ if (r < 0)
+ return NULL;
+
+ f = new0(FileDescriptor, 1);
+ if (!f)
+ return NULL;
+
+ f->cache = m;
+ f->fd = fd;
+
+ r = hashmap_put(m->fds, UINT_TO_PTR(fd + 1), f);
+ if (r < 0) {
+ free(f);
+ return NULL;
+ }
+
+ return f;
+}
+
+static void mmap_cache_free(MMapCache *m) {
+ Context *c;
+ FileDescriptor *f;
+
+ assert(m);
+
+ while ((c = hashmap_first(m->contexts)))
+ context_free(c);
+
+ while ((f = hashmap_first(m->fds)))
+ fd_free(f);
+
+ while (m->unused)
+ window_free(m->unused);
+
+ free(m);
+}
+
+MMapCache* mmap_cache_unref(MMapCache *m) {
+ assert(m);
+ assert(m->n_ref > 0);
+
+ m->n_ref --;
+ if (m->n_ref == 0)
+ mmap_cache_free(m);
+
+ return NULL;
+}
+
+static int make_room(MMapCache *m) {
+ assert(m);
+
+ if (!m->last_unused)
+ return 0;
+
+ window_free(m->last_unused);
+ return 1;
+}
+
+static int try_context(
+ MMapCache *m,
+ int fd,
+ int prot,
+ unsigned context,
+ bool keep_always,
+ uint64_t offset,
+ size_t size,
+ void **ret) {
+
+ Context *c;
+
+ assert(m);
+ assert(m->n_ref > 0);
+ assert(fd >= 0);
+ assert(size > 0);
+ assert(ret);
+
+ c = hashmap_get(m->contexts, UINT_TO_PTR(context+1));
+ if (!c)
+ return 0;
+
+ assert(c->id == context);
+
+ if (!c->window)
+ return 0;
+
+ if (!window_matches(c->window, fd, prot, offset, size)) {
+
+ /* Drop the reference to the window, since it's unnecessary now */
+ context_detach_window(c);
+ return 0;
+ }
+
+ c->window->keep_always = c->window->keep_always || keep_always;
+
+ *ret = (uint8_t*) c->window->ptr + (offset - c->window->offset);
+ return 1;
+}
+
+static int find_mmap(
+ MMapCache *m,
+ int fd,
+ int prot,
+ unsigned context,
+ bool keep_always,
+ uint64_t offset,
+ size_t size,
+ void **ret) {
+
+ FileDescriptor *f;
+ Window *w;
+ Context *c;
+
+ assert(m);
+ assert(m->n_ref > 0);
+ assert(fd >= 0);
+ assert(size > 0);
+ assert(ret);
+
+ f = hashmap_get(m->fds, INT_TO_PTR(fd + 1));
+ if (!f)
+ return 0;
+
+ assert(f->fd == fd);
+
+ LIST_FOREACH(by_fd, w, f->windows)
+ if (window_matches(w, fd, prot, offset, size))
+ break;
+
+ if (!w)
+ return 0;
+
+ c = context_add(m, context);
+ if (!c)
+ return -ENOMEM;
+
+ context_attach_window(c, w);
+ w->keep_always = w->keep_always || keep_always;
+
+ *ret = (uint8_t*) w->ptr + (offset - w->offset);
+ return 1;
+}
+
+static int add_mmap(
+ MMapCache *m,
+ int fd,
+ int prot,
+ unsigned context,
+ bool keep_always,
+ uint64_t offset,
+ size_t size,
+ struct stat *st,
+ void **ret) {
+
+ uint64_t woffset, wsize;
+ Context *c;
+ FileDescriptor *f;
+ Window *w;
+ void *d;
+ int r;
+
+ assert(m);
+ assert(m->n_ref > 0);
+ assert(fd >= 0);
+ assert(size > 0);
+ assert(ret);
+
+ woffset = offset & ~((uint64_t) page_size() - 1ULL);
+ wsize = size + (offset - woffset);
+ wsize = PAGE_ALIGN(wsize);
+
+ if (wsize < WINDOW_SIZE) {
+ uint64_t delta;
+
+ delta = PAGE_ALIGN((WINDOW_SIZE - wsize) / 2);
+
+ if (delta > offset)
+ woffset = 0;
+ else
+ woffset -= delta;
+
+ wsize = WINDOW_SIZE;
+ }
+
+ if (st) {
+ /* Memory maps that are larger then the files
+ underneath have undefined behavior. Hence, clamp
+ things to the file size if we know it */
+
+ if (woffset >= (uint64_t) st->st_size)
+ return -EADDRNOTAVAIL;
+
+ if (woffset + wsize > (uint64_t) st->st_size)
+ wsize = PAGE_ALIGN(st->st_size - woffset);
+ }
+
+ for (;;) {
+ d = mmap(NULL, wsize, prot, MAP_SHARED, fd, woffset);
+ if (d != MAP_FAILED)
+ break;
+ if (errno != ENOMEM)
+ return -errno;
+
+ r = make_room(m);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return -ENOMEM;
+ }
+
+ c = context_add(m, context);
+ if (!c)
+ return -ENOMEM;
+
+ f = fd_add(m, fd);
+ if (!f)
+ return -ENOMEM;
+
+ w = window_add(m);
+ if (!w)
+ return -ENOMEM;
+
+ w->keep_always = keep_always;
+ w->ptr = d;
+ w->offset = woffset;
+ w->prot = prot;
+ w->size = wsize;
+ w->fd = f;
+
+ LIST_PREPEND(Window, by_fd, f->windows, w);
+
+ context_detach_window(c);
+ c->window = w;
+ LIST_PREPEND(Context, by_window, w->contexts, c);
+
+ *ret = (uint8_t*) w->ptr + (offset - w->offset);
+ return 1;
+}
+
+int mmap_cache_get(
+ MMapCache *m,
+ int fd,
+ int prot,
+ unsigned context,
+ bool keep_always,
+ uint64_t offset,
+ size_t size,
+ struct stat *st,
+ void **ret) {
+
+ int r;
+
+ assert(m);
+ assert(m->n_ref > 0);
+ assert(fd >= 0);
+ assert(size > 0);
+ assert(ret);
+
+ /* Check whether the current context is the right one already */
+ r = try_context(m, fd, prot, context, keep_always, offset, size, ret);
+ if (r != 0)
+ return r;
+
+ /* Search for a matching mmap */
+ r = find_mmap(m, fd, prot, context, keep_always, offset, size, ret);
+ if (r != 0)
+ return r;
+
+ /* Create a new mmap */
+ return add_mmap(m, fd, prot, context, keep_always, offset, size, st, ret);
+}
+
+void mmap_cache_close_fd(MMapCache *m, int fd) {
+ FileDescriptor *f;
+
+ assert(m);
+ assert(fd >= 0);
+
+ f = hashmap_get(m->fds, INT_TO_PTR(fd + 1));
+ if (!f)
+ return;
+
+ fd_free(f);
+}
+
+void mmap_cache_close_context(MMapCache *m, unsigned context) {
+ Context *c;
+
+ assert(m);
+
+ c = hashmap_get(m->contexts, UINT_TO_PTR(context + 1));
+ if (!c)
+ return;
+
+ context_free(c);
+}
diff --git a/src/journal/mmap-cache.h b/src/journal/mmap-cache.h
new file mode 100644
index 0000000000..0c42fb88e6
--- /dev/null
+++ b/src/journal/mmap-cache.h
@@ -0,0 +1,36 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <inttypes.h>
+#include <stdbool.h>
+#include <sys/stat.h>
+
+typedef struct MMapCache MMapCache;
+
+MMapCache* mmap_cache_new(void);
+MMapCache* mmap_cache_ref(MMapCache *m);
+MMapCache* mmap_cache_unref(MMapCache *m);
+
+int mmap_cache_get(MMapCache *m, int fd, int prot, unsigned context, bool keep_always, uint64_t offset, size_t size, struct stat *st, void **ret);
+void mmap_cache_close_fd(MMapCache *m, int fd);
+void mmap_cache_close_context(MMapCache *m, unsigned context);
diff --git a/src/journal/sd-journal.c b/src/journal/sd-journal.c
new file mode 100644
index 0000000000..c21712b7c4
--- /dev/null
+++ b/src/journal/sd-journal.c
@@ -0,0 +1,2552 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stddef.h>
+#include <unistd.h>
+#include <sys/inotify.h>
+#include <sys/poll.h>
+#include <sys/vfs.h>
+#include <linux/magic.h>
+
+#include "sd-journal.h"
+#include "journal-def.h"
+#include "journal-file.h"
+#include "hashmap.h"
+#include "list.h"
+#include "path-util.h"
+#include "lookup3.h"
+#include "compress.h"
+#include "journal-internal.h"
+#include "missing.h"
+#include "catalog.h"
+#include "replace-var.h"
+
+#define JOURNAL_FILES_MAX 1024
+
+#define JOURNAL_FILES_RECHECK_USEC (2 * USEC_PER_SEC)
+
+#define REPLACE_VAR_MAX 256
+
+#define DEFAULT_DATA_THRESHOLD (64*1024)
+
+/* We return an error here only if we didn't manage to
+ memorize the real error. */
+static int set_put_error(sd_journal *j, int r) {
+ int k;
+
+ if (r >= 0)
+ return r;
+
+ k = set_ensure_allocated(&j->errors, trivial_hash_func, trivial_compare_func);
+ if (k < 0)
+ return k;
+
+ return set_put(j->errors, INT_TO_PTR(r));
+}
+
+static void detach_location(sd_journal *j) {
+ Iterator i;
+ JournalFile *f;
+
+ assert(j);
+
+ j->current_file = NULL;
+ j->current_field = 0;
+
+ HASHMAP_FOREACH(f, j->files, i)
+ f->current_offset = 0;
+}
+
+static void reset_location(sd_journal *j) {
+ assert(j);
+
+ detach_location(j);
+ zero(j->current_location);
+}
+
+static void init_location(Location *l, LocationType type, JournalFile *f, Object *o) {
+ assert(l);
+ assert(type == LOCATION_DISCRETE || type == LOCATION_SEEK);
+ assert(f);
+ assert(o->object.type == OBJECT_ENTRY);
+
+ l->type = type;
+ l->seqnum = le64toh(o->entry.seqnum);
+ l->seqnum_id = f->header->seqnum_id;
+ l->realtime = le64toh(o->entry.realtime);
+ l->monotonic = le64toh(o->entry.monotonic);
+ l->boot_id = o->entry.boot_id;
+ l->xor_hash = le64toh(o->entry.xor_hash);
+
+ l->seqnum_set = l->realtime_set = l->monotonic_set = l->xor_hash_set = true;
+}
+
+static void set_location(sd_journal *j, LocationType type, JournalFile *f, Object *o, uint64_t offset) {
+ assert(j);
+ assert(type == LOCATION_DISCRETE || type == LOCATION_SEEK);
+ assert(f);
+ assert(o);
+
+ init_location(&j->current_location, type, f, o);
+
+ if (j->current_file)
+ j->current_file->current_offset = 0;
+
+ j->current_file = f;
+ j->current_field = 0;
+
+ f->current_offset = offset;
+}
+
+static int match_is_valid(const void *data, size_t size) {
+ const char *b, *p;
+
+ assert(data);
+
+ if (size < 2)
+ return false;
+
+ if (startswith(data, "__"))
+ return false;
+
+ b = data;
+ for (p = b; p < b + size; p++) {
+
+ if (*p == '=')
+ return p > b;
+
+ if (*p == '_')
+ continue;
+
+ if (*p >= 'A' && *p <= 'Z')
+ continue;
+
+ if (*p >= '0' && *p <= '9')
+ continue;
+
+ return false;
+ }
+
+ return false;
+}
+
+static bool same_field(const void *_a, size_t s, const void *_b, size_t t) {
+ const uint8_t *a = _a, *b = _b;
+ size_t j;
+
+ for (j = 0; j < s && j < t; j++) {
+
+ if (a[j] != b[j])
+ return false;
+
+ if (a[j] == '=')
+ return true;
+ }
+
+ return true;
+}
+
+static Match *match_new(Match *p, MatchType t) {
+ Match *m;
+
+ m = new0(Match, 1);
+ if (!m)
+ return NULL;
+
+ m->type = t;
+
+ if (p) {
+ m->parent = p;
+ LIST_PREPEND(Match, matches, p->matches, m);
+ }
+
+ return m;
+}
+
+static void match_free(Match *m) {
+ assert(m);
+
+ while (m->matches)
+ match_free(m->matches);
+
+ if (m->parent)
+ LIST_REMOVE(Match, matches, m->parent->matches, m);
+
+ free(m->data);
+ free(m);
+}
+
+static void match_free_if_empty(Match *m) {
+ assert(m);
+
+ if (m->matches)
+ return;
+
+ match_free(m);
+}
+
+_public_ int sd_journal_add_match(sd_journal *j, const void *data, size_t size) {
+ Match *l3, *l4, *add_here = NULL, *m;
+ le64_t le_hash;
+
+ if (!j)
+ return -EINVAL;
+
+ if (!data)
+ return -EINVAL;
+
+ if (size == 0)
+ size = strlen(data);
+
+ if (!match_is_valid(data, size))
+ return -EINVAL;
+
+ /* level 0: AND term
+ * level 1: OR terms
+ * level 2: AND terms
+ * level 3: OR terms
+ * level 4: concrete matches */
+
+ if (!j->level0) {
+ j->level0 = match_new(NULL, MATCH_AND_TERM);
+ if (!j->level0)
+ return -ENOMEM;
+ }
+
+ if (!j->level1) {
+ j->level1 = match_new(j->level0, MATCH_OR_TERM);
+ if (!j->level1)
+ return -ENOMEM;
+ }
+
+ if (!j->level2) {
+ j->level2 = match_new(j->level1, MATCH_AND_TERM);
+ if (!j->level2)
+ return -ENOMEM;
+ }
+
+ assert(j->level0->type == MATCH_AND_TERM);
+ assert(j->level1->type == MATCH_OR_TERM);
+ assert(j->level2->type == MATCH_AND_TERM);
+
+ le_hash = htole64(hash64(data, size));
+
+ LIST_FOREACH(matches, l3, j->level2->matches) {
+ assert(l3->type == MATCH_OR_TERM);
+
+ LIST_FOREACH(matches, l4, l3->matches) {
+ assert(l4->type == MATCH_DISCRETE);
+
+ /* Exactly the same match already? Then ignore
+ * this addition */
+ if (l4->le_hash == le_hash &&
+ l4->size == size &&
+ memcmp(l4->data, data, size) == 0)
+ return 0;
+
+ /* Same field? Then let's add this to this OR term */
+ if (same_field(data, size, l4->data, l4->size)) {
+ add_here = l3;
+ break;
+ }
+ }
+
+ if (add_here)
+ break;
+ }
+
+ if (!add_here) {
+ add_here = match_new(j->level2, MATCH_OR_TERM);
+ if (!add_here)
+ goto fail;
+ }
+
+ m = match_new(add_here, MATCH_DISCRETE);
+ if (!m)
+ goto fail;
+
+ m->le_hash = le_hash;
+ m->size = size;
+ m->data = memdup(data, size);
+ if (!m->data)
+ goto fail;
+
+ detach_location(j);
+
+ return 0;
+
+fail:
+ if (add_here)
+ match_free_if_empty(add_here);
+
+ if (j->level2)
+ match_free_if_empty(j->level2);
+
+ if (j->level1)
+ match_free_if_empty(j->level1);
+
+ if (j->level0)
+ match_free_if_empty(j->level0);
+
+ return -ENOMEM;
+}
+
+_public_ int sd_journal_add_conjunction(sd_journal *j) {
+ assert(j);
+
+ if (!j->level0)
+ return 0;
+
+ if (!j->level1)
+ return 0;
+
+ if (!j->level1->matches)
+ return 0;
+
+ j->level1 = NULL;
+ j->level2 = NULL;
+
+ return 0;
+}
+
+_public_ int sd_journal_add_disjunction(sd_journal *j) {
+ assert(j);
+
+ if (!j->level0)
+ return 0;
+
+ if (!j->level1)
+ return 0;
+
+ if (!j->level2)
+ return 0;
+
+ if (!j->level2->matches)
+ return 0;
+
+ j->level2 = NULL;
+ return 0;
+}
+
+static char *match_make_string(Match *m) {
+ char *p, *r;
+ Match *i;
+ bool enclose = false;
+
+ if (!m)
+ return strdup("");
+
+ if (m->type == MATCH_DISCRETE)
+ return strndup(m->data, m->size);
+
+ p = NULL;
+ LIST_FOREACH(matches, i, m->matches) {
+ char *t, *k;
+
+ t = match_make_string(i);
+ if (!t) {
+ free(p);
+ return NULL;
+ }
+
+ if (p) {
+ k = strjoin(p, m->type == MATCH_OR_TERM ? " OR " : " AND ", t, NULL);
+ free(p);
+ free(t);
+
+ if (!k)
+ return NULL;
+
+ p = k;
+
+ enclose = true;
+ } else {
+ free(p);
+ p = t;
+ }
+ }
+
+ if (enclose) {
+ r = strjoin("(", p, ")", NULL);
+ free(p);
+ return r;
+ }
+
+ return p;
+}
+
+char *journal_make_match_string(sd_journal *j) {
+ assert(j);
+
+ return match_make_string(j->level0);
+}
+
+_public_ void sd_journal_flush_matches(sd_journal *j) {
+
+ if (!j)
+ return;
+
+ if (j->level0)
+ match_free(j->level0);
+
+ j->level0 = j->level1 = j->level2 = NULL;
+
+ detach_location(j);
+}
+
+static int compare_entry_order(JournalFile *af, Object *_ao,
+ JournalFile *bf, uint64_t bp) {
+
+ uint64_t a, b;
+ Object *ao, *bo;
+ int r;
+
+ assert(af);
+ assert(bf);
+ assert(_ao);
+
+ /* The mmap cache might invalidate the object from the first
+ * file if we look at the one from the second file. Hence
+ * temporarily copy the header of the first one, and look at
+ * that only. */
+ ao = alloca(offsetof(EntryObject, items));
+ memcpy(ao, _ao, offsetof(EntryObject, items));
+
+ r = journal_file_move_to_object(bf, OBJECT_ENTRY, bp, &bo);
+ if (r < 0)
+ return strcmp(af->path, bf->path);
+
+ /* We operate on two different files here, hence we can access
+ * two objects at the same time, which we normally can't.
+ *
+ * If contents and timestamps match, these entries are
+ * identical, even if the seqnum does not match */
+
+ if (sd_id128_equal(ao->entry.boot_id, bo->entry.boot_id) &&
+ ao->entry.monotonic == bo->entry.monotonic &&
+ ao->entry.realtime == bo->entry.realtime &&
+ ao->entry.xor_hash == bo->entry.xor_hash)
+ return 0;
+
+ if (sd_id128_equal(af->header->seqnum_id, bf->header->seqnum_id)) {
+
+ /* If this is from the same seqnum source, compare
+ * seqnums */
+ a = le64toh(ao->entry.seqnum);
+ b = le64toh(bo->entry.seqnum);
+
+ if (a < b)
+ return -1;
+ if (a > b)
+ return 1;
+
+ /* Wow! This is weird, different data but the same
+ * seqnums? Something is borked, but let's make the
+ * best of it and compare by time. */
+ }
+
+ if (sd_id128_equal(ao->entry.boot_id, bo->entry.boot_id)) {
+
+ /* If the boot id matches compare monotonic time */
+ a = le64toh(ao->entry.monotonic);
+ b = le64toh(bo->entry.monotonic);
+
+ if (a < b)
+ return -1;
+ if (a > b)
+ return 1;
+ }
+
+ /* Otherwise compare UTC time */
+ a = le64toh(ao->entry.realtime);
+ b = le64toh(bo->entry.realtime);
+
+ if (a < b)
+ return -1;
+ if (a > b)
+ return 1;
+
+ /* Finally, compare by contents */
+ a = le64toh(ao->entry.xor_hash);
+ b = le64toh(bo->entry.xor_hash);
+
+ if (a < b)
+ return -1;
+ if (a > b)
+ return 1;
+
+ return 0;
+}
+
+_pure_ static int compare_with_location(JournalFile *af, Object *ao, Location *l) {
+ uint64_t a;
+
+ assert(af);
+ assert(ao);
+ assert(l);
+ assert(l->type == LOCATION_DISCRETE || l->type == LOCATION_SEEK);
+
+ if (l->monotonic_set &&
+ sd_id128_equal(ao->entry.boot_id, l->boot_id) &&
+ l->realtime_set &&
+ le64toh(ao->entry.realtime) == l->realtime &&
+ l->xor_hash_set &&
+ le64toh(ao->entry.xor_hash) == l->xor_hash)
+ return 0;
+
+ if (l->seqnum_set &&
+ sd_id128_equal(af->header->seqnum_id, l->seqnum_id)) {
+
+ a = le64toh(ao->entry.seqnum);
+
+ if (a < l->seqnum)
+ return -1;
+ if (a > l->seqnum)
+ return 1;
+ }
+
+ if (l->monotonic_set &&
+ sd_id128_equal(ao->entry.boot_id, l->boot_id)) {
+
+ a = le64toh(ao->entry.monotonic);
+
+ if (a < l->monotonic)
+ return -1;
+ if (a > l->monotonic)
+ return 1;
+ }
+
+ if (l->realtime_set) {
+
+ a = le64toh(ao->entry.realtime);
+
+ if (a < l->realtime)
+ return -1;
+ if (a > l->realtime)
+ return 1;
+ }
+
+ if (l->xor_hash_set) {
+ a = le64toh(ao->entry.xor_hash);
+
+ if (a < l->xor_hash)
+ return -1;
+ if (a > l->xor_hash)
+ return 1;
+ }
+
+ return 0;
+}
+
+static int next_for_match(
+ sd_journal *j,
+ Match *m,
+ JournalFile *f,
+ uint64_t after_offset,
+ direction_t direction,
+ Object **ret,
+ uint64_t *offset) {
+
+ int r;
+ uint64_t np = 0;
+ Object *n;
+
+ assert(j);
+ assert(m);
+ assert(f);
+
+ if (m->type == MATCH_DISCRETE) {
+ uint64_t dp;
+
+ r = journal_file_find_data_object_with_hash(f, m->data, m->size, le64toh(m->le_hash), NULL, &dp);
+ if (r <= 0)
+ return r;
+
+ return journal_file_move_to_entry_by_offset_for_data(f, dp, after_offset, direction, ret, offset);
+
+ } else if (m->type == MATCH_OR_TERM) {
+ Match *i;
+
+ /* Find the earliest match beyond after_offset */
+
+ LIST_FOREACH(matches, i, m->matches) {
+ uint64_t cp;
+
+ r = next_for_match(j, i, f, after_offset, direction, NULL, &cp);
+ if (r < 0)
+ return r;
+ else if (r > 0) {
+ if (np == 0 || (direction == DIRECTION_DOWN ? np > cp : np < cp))
+ np = cp;
+ }
+ }
+
+ } else if (m->type == MATCH_AND_TERM) {
+ Match *i;
+ bool continue_looking;
+
+ /* Always jump to the next matching entry and repeat
+ * this until we fine and offset that matches for all
+ * matches. */
+
+ if (!m->matches)
+ return 0;
+
+ np = 0;
+ do {
+ continue_looking = false;
+
+ LIST_FOREACH(matches, i, m->matches) {
+ uint64_t cp, limit;
+
+ if (np == 0)
+ limit = after_offset;
+ else if (direction == DIRECTION_DOWN)
+ limit = MAX(np, after_offset);
+ else
+ limit = MIN(np, after_offset);
+
+ r = next_for_match(j, i, f, limit, direction, NULL, &cp);
+ if (r <= 0)
+ return r;
+
+ if ((direction == DIRECTION_DOWN ? cp >= after_offset : cp <= after_offset) &&
+ (np == 0 || (direction == DIRECTION_DOWN ? cp > np : cp < np))) {
+ np = cp;
+ continue_looking = true;
+ }
+ }
+
+ } while (continue_looking);
+ }
+
+ if (np == 0)
+ return 0;
+
+ r = journal_file_move_to_object(f, OBJECT_ENTRY, np, &n);
+ if (r < 0)
+ return r;
+
+ if (ret)
+ *ret = n;
+ if (offset)
+ *offset = np;
+
+ return 1;
+}
+
+static int find_location_for_match(
+ sd_journal *j,
+ Match *m,
+ JournalFile *f,
+ direction_t direction,
+ Object **ret,
+ uint64_t *offset) {
+
+ int r;
+
+ assert(j);
+ assert(m);
+ assert(f);
+
+ if (m->type == MATCH_DISCRETE) {
+ uint64_t dp;
+
+ r = journal_file_find_data_object_with_hash(f, m->data, m->size, le64toh(m->le_hash), NULL, &dp);
+ if (r <= 0)
+ return r;
+
+ /* FIXME: missing: find by monotonic */
+
+ if (j->current_location.type == LOCATION_HEAD)
+ return journal_file_next_entry_for_data(f, NULL, 0, dp, DIRECTION_DOWN, ret, offset);
+ if (j->current_location.type == LOCATION_TAIL)
+ return journal_file_next_entry_for_data(f, NULL, 0, dp, DIRECTION_UP, ret, offset);
+ if (j->current_location.seqnum_set && sd_id128_equal(j->current_location.seqnum_id, f->header->seqnum_id))
+ return journal_file_move_to_entry_by_seqnum_for_data(f, dp, j->current_location.seqnum, direction, ret, offset);
+ if (j->current_location.monotonic_set) {
+ r = journal_file_move_to_entry_by_monotonic_for_data(f, dp, j->current_location.boot_id, j->current_location.monotonic, direction, ret, offset);
+ if (r != -ENOENT)
+ return r;
+ }
+ if (j->current_location.realtime_set)
+ return journal_file_move_to_entry_by_realtime_for_data(f, dp, j->current_location.realtime, direction, ret, offset);
+
+ return journal_file_next_entry_for_data(f, NULL, 0, dp, direction, ret, offset);
+
+ } else if (m->type == MATCH_OR_TERM) {
+ uint64_t np = 0;
+ Object *n;
+ Match *i;
+
+ /* Find the earliest match */
+
+ LIST_FOREACH(matches, i, m->matches) {
+ uint64_t cp;
+
+ r = find_location_for_match(j, i, f, direction, NULL, &cp);
+ if (r < 0)
+ return r;
+ else if (r > 0) {
+ if (np == 0 || (direction == DIRECTION_DOWN ? np > cp : np < cp))
+ np = cp;
+ }
+ }
+
+ if (np == 0)
+ return 0;
+
+ r = journal_file_move_to_object(f, OBJECT_ENTRY, np, &n);
+ if (r < 0)
+ return r;
+
+ if (ret)
+ *ret = n;
+ if (offset)
+ *offset = np;
+
+ return 1;
+
+ } else {
+ Match *i;
+ uint64_t np = 0;
+
+ assert(m->type == MATCH_AND_TERM);
+
+ /* First jump to the last match, and then find the
+ * next one where all matches match */
+
+ if (!m->matches)
+ return 0;
+
+ LIST_FOREACH(matches, i, m->matches) {
+ uint64_t cp;
+
+ r = find_location_for_match(j, i, f, direction, NULL, &cp);
+ if (r <= 0)
+ return r;
+
+ if (np == 0 || (direction == DIRECTION_DOWN ? np < cp : np > cp))
+ np = cp;
+ }
+
+ return next_for_match(j, m, f, np, direction, ret, offset);
+ }
+}
+
+static int find_location_with_matches(
+ sd_journal *j,
+ JournalFile *f,
+ direction_t direction,
+ Object **ret,
+ uint64_t *offset) {
+
+ int r;
+
+ assert(j);
+ assert(f);
+ assert(ret);
+ assert(offset);
+
+ if (!j->level0) {
+ /* No matches is simple */
+
+ if (j->current_location.type == LOCATION_HEAD)
+ return journal_file_next_entry(f, NULL, 0, DIRECTION_DOWN, ret, offset);
+ if (j->current_location.type == LOCATION_TAIL)
+ return journal_file_next_entry(f, NULL, 0, DIRECTION_UP, ret, offset);
+ if (j->current_location.seqnum_set && sd_id128_equal(j->current_location.seqnum_id, f->header->seqnum_id))
+ return journal_file_move_to_entry_by_seqnum(f, j->current_location.seqnum, direction, ret, offset);
+ if (j->current_location.monotonic_set) {
+ r = journal_file_move_to_entry_by_monotonic(f, j->current_location.boot_id, j->current_location.monotonic, direction, ret, offset);
+ if (r != -ENOENT)
+ return r;
+ }
+ if (j->current_location.realtime_set)
+ return journal_file_move_to_entry_by_realtime(f, j->current_location.realtime, direction, ret, offset);
+
+ return journal_file_next_entry(f, NULL, 0, direction, ret, offset);
+ } else
+ return find_location_for_match(j, j->level0, f, direction, ret, offset);
+}
+
+static int next_with_matches(
+ sd_journal *j,
+ JournalFile *f,
+ direction_t direction,
+ Object **ret,
+ uint64_t *offset) {
+
+ Object *c;
+ uint64_t cp;
+
+ assert(j);
+ assert(f);
+ assert(ret);
+ assert(offset);
+
+ c = *ret;
+ cp = *offset;
+
+ /* No matches is easy. We simple advance the file
+ * pointer by one. */
+ if (!j->level0)
+ return journal_file_next_entry(f, c, cp, direction, ret, offset);
+
+ /* If we have a match then we look for the next matching entry
+ * with an offset at least one step larger */
+ return next_for_match(j, j->level0, f, direction == DIRECTION_DOWN ? cp+1 : cp-1, direction, ret, offset);
+}
+
+static int next_beyond_location(sd_journal *j, JournalFile *f, direction_t direction, Object **ret, uint64_t *offset) {
+ Object *c;
+ uint64_t cp;
+ int r;
+
+ assert(j);
+ assert(f);
+
+ if (f->current_offset > 0) {
+ cp = f->current_offset;
+
+ r = journal_file_move_to_object(f, OBJECT_ENTRY, cp, &c);
+ if (r < 0)
+ return r;
+
+ r = next_with_matches(j, f, direction, &c, &cp);
+ if (r <= 0)
+ return r;
+ } else {
+ r = find_location_with_matches(j, f, direction, &c, &cp);
+ if (r <= 0)
+ return r;
+ }
+
+ /* OK, we found the spot, now let's advance until to an entry
+ * that is actually different from what we were previously
+ * looking at. This is necessary to handle entries which exist
+ * in two (or more) journal files, and which shall all be
+ * suppressed but one. */
+
+ for (;;) {
+ bool found;
+
+ if (j->current_location.type == LOCATION_DISCRETE) {
+ int k;
+
+ k = compare_with_location(f, c, &j->current_location);
+ if (direction == DIRECTION_DOWN)
+ found = k > 0;
+ else
+ found = k < 0;
+ } else
+ found = true;
+
+ if (found) {
+ if (ret)
+ *ret = c;
+ if (offset)
+ *offset = cp;
+ return 1;
+ }
+
+ r = next_with_matches(j, f, direction, &c, &cp);
+ if (r <= 0)
+ return r;
+ }
+}
+
+static int real_journal_next(sd_journal *j, direction_t direction) {
+ JournalFile *f, *new_file = NULL;
+ uint64_t new_offset = 0;
+ Object *o;
+ uint64_t p;
+ Iterator i;
+ int r;
+
+ if (!j)
+ return -EINVAL;
+
+ HASHMAP_FOREACH(f, j->files, i) {
+ bool found;
+
+ r = next_beyond_location(j, f, direction, &o, &p);
+ if (r < 0) {
+ log_debug("Can't iterate through %s, ignoring: %s", f->path, strerror(-r));
+ continue;
+ } else if (r == 0)
+ continue;
+
+ if (!new_file)
+ found = true;
+ else {
+ int k;
+
+ k = compare_entry_order(f, o, new_file, new_offset);
+
+ if (direction == DIRECTION_DOWN)
+ found = k < 0;
+ else
+ found = k > 0;
+ }
+
+ if (found) {
+ new_file = f;
+ new_offset = p;
+ }
+ }
+
+ if (!new_file)
+ return 0;
+
+ r = journal_file_move_to_object(new_file, OBJECT_ENTRY, new_offset, &o);
+ if (r < 0)
+ return r;
+
+ set_location(j, LOCATION_DISCRETE, new_file, o, new_offset);
+
+ return 1;
+}
+
+_public_ int sd_journal_next(sd_journal *j) {
+ return real_journal_next(j, DIRECTION_DOWN);
+}
+
+_public_ int sd_journal_previous(sd_journal *j) {
+ return real_journal_next(j, DIRECTION_UP);
+}
+
+static int real_journal_next_skip(sd_journal *j, direction_t direction, uint64_t skip) {
+ int c = 0, r;
+
+ if (!j)
+ return -EINVAL;
+
+ if (skip == 0) {
+ /* If this is not a discrete skip, then at least
+ * resolve the current location */
+ if (j->current_location.type != LOCATION_DISCRETE)
+ return real_journal_next(j, direction);
+
+ return 0;
+ }
+
+ do {
+ r = real_journal_next(j, direction);
+ if (r < 0)
+ return r;
+
+ if (r == 0)
+ return c;
+
+ skip--;
+ c++;
+ } while (skip > 0);
+
+ return c;
+}
+
+_public_ int sd_journal_next_skip(sd_journal *j, uint64_t skip) {
+ return real_journal_next_skip(j, DIRECTION_DOWN, skip);
+}
+
+_public_ int sd_journal_previous_skip(sd_journal *j, uint64_t skip) {
+ return real_journal_next_skip(j, DIRECTION_UP, skip);
+}
+
+_public_ int sd_journal_get_cursor(sd_journal *j, char **cursor) {
+ Object *o;
+ int r;
+ char bid[33], sid[33];
+
+ if (!j)
+ return -EINVAL;
+ if (!cursor)
+ return -EINVAL;
+
+ if (!j->current_file || j->current_file->current_offset <= 0)
+ return -EADDRNOTAVAIL;
+
+ r = journal_file_move_to_object(j->current_file, OBJECT_ENTRY, j->current_file->current_offset, &o);
+ if (r < 0)
+ return r;
+
+ sd_id128_to_string(j->current_file->header->seqnum_id, sid);
+ sd_id128_to_string(o->entry.boot_id, bid);
+
+ if (asprintf(cursor,
+ "s=%s;i=%llx;b=%s;m=%llx;t=%llx;x=%llx",
+ sid, (unsigned long long) le64toh(o->entry.seqnum),
+ bid, (unsigned long long) le64toh(o->entry.monotonic),
+ (unsigned long long) le64toh(o->entry.realtime),
+ (unsigned long long) le64toh(o->entry.xor_hash)) < 0)
+ return -ENOMEM;
+
+ return 0;
+}
+
+_public_ int sd_journal_seek_cursor(sd_journal *j, const char *cursor) {
+ char *w, *state;
+ size_t l;
+ unsigned long long seqnum, monotonic, realtime, xor_hash;
+ bool
+ seqnum_id_set = false,
+ seqnum_set = false,
+ boot_id_set = false,
+ monotonic_set = false,
+ realtime_set = false,
+ xor_hash_set = false;
+ sd_id128_t seqnum_id, boot_id;
+
+ if (!j)
+ return -EINVAL;
+ if (isempty(cursor))
+ return -EINVAL;
+
+ FOREACH_WORD_SEPARATOR(w, l, cursor, ";", state) {
+ char *item;
+ int k = 0;
+
+ if (l < 2 || w[1] != '=')
+ return -EINVAL;
+
+ item = strndup(w, l);
+ if (!item)
+ return -ENOMEM;
+
+ switch (w[0]) {
+
+ case 's':
+ seqnum_id_set = true;
+ k = sd_id128_from_string(item+2, &seqnum_id);
+ break;
+
+ case 'i':
+ seqnum_set = true;
+ if (sscanf(item+2, "%llx", &seqnum) != 1)
+ k = -EINVAL;
+ break;
+
+ case 'b':
+ boot_id_set = true;
+ k = sd_id128_from_string(item+2, &boot_id);
+ break;
+
+ case 'm':
+ monotonic_set = true;
+ if (sscanf(item+2, "%llx", &monotonic) != 1)
+ k = -EINVAL;
+ break;
+
+ case 't':
+ realtime_set = true;
+ if (sscanf(item+2, "%llx", &realtime) != 1)
+ k = -EINVAL;
+ break;
+
+ case 'x':
+ xor_hash_set = true;
+ if (sscanf(item+2, "%llx", &xor_hash) != 1)
+ k = -EINVAL;
+ break;
+ }
+
+ free(item);
+
+ if (k < 0)
+ return k;
+ }
+
+ if ((!seqnum_set || !seqnum_id_set) &&
+ (!monotonic_set || !boot_id_set) &&
+ !realtime_set)
+ return -EINVAL;
+
+ reset_location(j);
+
+ j->current_location.type = LOCATION_SEEK;
+
+ if (realtime_set) {
+ j->current_location.realtime = (uint64_t) realtime;
+ j->current_location.realtime_set = true;
+ }
+
+ if (seqnum_set && seqnum_id_set) {
+ j->current_location.seqnum = (uint64_t) seqnum;
+ j->current_location.seqnum_id = seqnum_id;
+ j->current_location.seqnum_set = true;
+ }
+
+ if (monotonic_set && boot_id_set) {
+ j->current_location.monotonic = (uint64_t) monotonic;
+ j->current_location.boot_id = boot_id;
+ j->current_location.monotonic_set = true;
+ }
+
+ if (xor_hash_set) {
+ j->current_location.xor_hash = (uint64_t) xor_hash;
+ j->current_location.xor_hash_set = true;
+ }
+
+ return 0;
+}
+
+_public_ int sd_journal_test_cursor(sd_journal *j, const char *cursor) {
+ int r;
+ char *w, *state;
+ size_t l;
+ Object *o;
+
+ if (!j)
+ return -EINVAL;
+ if (isempty(cursor))
+ return -EINVAL;
+
+ if (!j->current_file || j->current_file->current_offset <= 0)
+ return -EADDRNOTAVAIL;
+
+ r = journal_file_move_to_object(j->current_file, OBJECT_ENTRY, j->current_file->current_offset, &o);
+ if (r < 0)
+ return r;
+
+ FOREACH_WORD_SEPARATOR(w, l, cursor, ";", state) {
+ _cleanup_free_ char *item = NULL;
+ sd_id128_t id;
+ unsigned long long ll;
+ int k = 0;
+
+ if (l < 2 || w[1] != '=')
+ return -EINVAL;
+
+ item = strndup(w, l);
+ if (!item)
+ return -ENOMEM;
+
+ switch (w[0]) {
+
+ case 's':
+ k = sd_id128_from_string(item+2, &id);
+ if (k < 0)
+ return k;
+ if (!sd_id128_equal(id, j->current_file->header->seqnum_id))
+ return 0;
+ break;
+
+ case 'i':
+ if (sscanf(item+2, "%llx", &ll) != 1)
+ return -EINVAL;
+ if (ll != le64toh(o->entry.seqnum))
+ return 0;
+ break;
+
+ case 'b':
+ k = sd_id128_from_string(item+2, &id);
+ if (k < 0)
+ return k;
+ if (!sd_id128_equal(id, o->entry.boot_id))
+ return 0;
+ break;
+
+ case 'm':
+ if (sscanf(item+2, "%llx", &ll) != 1)
+ return -EINVAL;
+ if (ll != le64toh(o->entry.monotonic))
+ return 0;
+ break;
+
+ case 't':
+ if (sscanf(item+2, "%llx", &ll) != 1)
+ return -EINVAL;
+ if (ll != le64toh(o->entry.realtime))
+ return 0;
+ break;
+
+ case 'x':
+ if (sscanf(item+2, "%llx", &ll) != 1)
+ return -EINVAL;
+ if (ll != le64toh(o->entry.xor_hash))
+ return 0;
+ break;
+ }
+ }
+
+ return 1;
+}
+
+
+_public_ int sd_journal_seek_monotonic_usec(sd_journal *j, sd_id128_t boot_id, uint64_t usec) {
+ if (!j)
+ return -EINVAL;
+
+ reset_location(j);
+ j->current_location.type = LOCATION_SEEK;
+ j->current_location.boot_id = boot_id;
+ j->current_location.monotonic = usec;
+ j->current_location.monotonic_set = true;
+
+ return 0;
+}
+
+_public_ int sd_journal_seek_realtime_usec(sd_journal *j, uint64_t usec) {
+ if (!j)
+ return -EINVAL;
+
+ reset_location(j);
+ j->current_location.type = LOCATION_SEEK;
+ j->current_location.realtime = usec;
+ j->current_location.realtime_set = true;
+
+ return 0;
+}
+
+_public_ int sd_journal_seek_head(sd_journal *j) {
+ if (!j)
+ return -EINVAL;
+
+ reset_location(j);
+ j->current_location.type = LOCATION_HEAD;
+
+ return 0;
+}
+
+_public_ int sd_journal_seek_tail(sd_journal *j) {
+ if (!j)
+ return -EINVAL;
+
+ reset_location(j);
+ j->current_location.type = LOCATION_TAIL;
+
+ return 0;
+}
+
+static void check_network(sd_journal *j, int fd) {
+ struct statfs sfs;
+
+ assert(j);
+
+ if (j->on_network)
+ return;
+
+ if (fstatfs(fd, &sfs) < 0)
+ return;
+
+ j->on_network =
+ F_TYPE_CMP(sfs.f_type, CIFS_MAGIC_NUMBER) ||
+ F_TYPE_CMP(sfs.f_type, CODA_SUPER_MAGIC) ||
+ F_TYPE_CMP(sfs.f_type, NCP_SUPER_MAGIC) ||
+ F_TYPE_CMP(sfs.f_type, NFS_SUPER_MAGIC) ||
+ F_TYPE_CMP(sfs.f_type, SMB_SUPER_MAGIC);
+}
+
+static int add_file(sd_journal *j, const char *prefix, const char *filename) {
+ _cleanup_free_ char *path = NULL;
+ int r;
+ JournalFile *f;
+
+ assert(j);
+ assert(prefix);
+ assert(filename);
+
+ if ((j->flags & SD_JOURNAL_SYSTEM_ONLY) &&
+ !(streq(filename, "system.journal") ||
+ streq(filename, "system.journal~") ||
+ (startswith(filename, "system@") &&
+ (endswith(filename, ".journal") || endswith(filename, ".journal~")))))
+ return 0;
+
+ path = strjoin(prefix, "/", filename, NULL);
+ if (!path)
+ return -ENOMEM;
+
+ if (hashmap_get(j->files, path))
+ return 0;
+
+ if (hashmap_size(j->files) >= JOURNAL_FILES_MAX) {
+ log_debug("Too many open journal files, not adding %s, ignoring.", path);
+ return set_put_error(j, -ETOOMANYREFS);
+ }
+
+ r = journal_file_open(path, O_RDONLY, 0, false, false, NULL, j->mmap, NULL, &f);
+ if (r < 0) {
+ if (errno == ENOENT)
+ return 0;
+
+ return r;
+ }
+
+ /* journal_file_dump(f); */
+
+ r = hashmap_put(j->files, f->path, f);
+ if (r < 0) {
+ journal_file_close(f);
+ return r;
+ }
+
+ log_debug("File %s got added.", f->path);
+
+ check_network(j, f->fd);
+
+ j->current_invalidate_counter ++;
+
+ return 0;
+}
+
+static int remove_file(sd_journal *j, const char *prefix, const char *filename) {
+ char *path;
+ JournalFile *f;
+
+ assert(j);
+ assert(prefix);
+ assert(filename);
+
+ path = strjoin(prefix, "/", filename, NULL);
+ if (!path)
+ return -ENOMEM;
+
+ f = hashmap_get(j->files, path);
+ free(path);
+ if (!f)
+ return 0;
+
+ hashmap_remove(j->files, f->path);
+
+ log_debug("File %s got removed.", f->path);
+
+ if (j->current_file == f) {
+ j->current_file = NULL;
+ j->current_field = 0;
+ }
+
+ if (j->unique_file == f) {
+ j->unique_file = NULL;
+ j->unique_offset = 0;
+ }
+
+ journal_file_close(f);
+
+ j->current_invalidate_counter ++;
+
+ return 0;
+}
+
+static int add_directory(sd_journal *j, const char *prefix, const char *dirname) {
+ _cleanup_free_ char *path = NULL;
+ int r;
+ _cleanup_closedir_ DIR *d = NULL;
+ sd_id128_t id, mid;
+ Directory *m;
+
+ assert(j);
+ assert(prefix);
+ assert(dirname);
+
+ log_debug("Considering %s/%s.", prefix, dirname);
+
+ if ((j->flags & SD_JOURNAL_LOCAL_ONLY) &&
+ (sd_id128_from_string(dirname, &id) < 0 ||
+ sd_id128_get_machine(&mid) < 0 ||
+ !(sd_id128_equal(id, mid) || path_startswith(prefix, "/run"))))
+ return 0;
+
+ path = strjoin(prefix, "/", dirname, NULL);
+ if (!path)
+ return -ENOMEM;
+
+ d = opendir(path);
+ if (!d) {
+ log_debug("Failed to open %s: %m", path);
+ if (errno == ENOENT)
+ return 0;
+ return -errno;
+ }
+
+ m = hashmap_get(j->directories_by_path, path);
+ if (!m) {
+ m = new0(Directory, 1);
+ if (!m)
+ return -ENOMEM;
+
+ m->is_root = false;
+ m->path = path;
+
+ if (hashmap_put(j->directories_by_path, m->path, m) < 0) {
+ free(m);
+ return -ENOMEM;
+ }
+
+ path = NULL; /* avoid freeing in cleanup */
+ j->current_invalidate_counter ++;
+
+ log_debug("Directory %s got added.", m->path);
+
+ } else if (m->is_root)
+ return 0;
+
+ if (m->wd <= 0 && j->inotify_fd >= 0) {
+
+ m->wd = inotify_add_watch(j->inotify_fd, m->path,
+ IN_CREATE|IN_MOVED_TO|IN_MODIFY|IN_ATTRIB|IN_DELETE|
+ IN_DELETE_SELF|IN_MOVE_SELF|IN_UNMOUNT|IN_MOVED_FROM|
+ IN_ONLYDIR);
+
+ if (m->wd > 0 && hashmap_put(j->directories_by_wd, INT_TO_PTR(m->wd), m) < 0)
+ inotify_rm_watch(j->inotify_fd, m->wd);
+ }
+
+ for (;;) {
+ struct dirent *de;
+ union dirent_storage buf;
+
+ r = readdir_r(d, &buf.de, &de);
+ if (r != 0 || !de)
+ break;
+
+ if (dirent_is_file_with_suffix(de, ".journal") ||
+ dirent_is_file_with_suffix(de, ".journal~")) {
+ r = add_file(j, m->path, de->d_name);
+ if (r < 0) {
+ log_debug("Failed to add file %s/%s: %s",
+ m->path, de->d_name, strerror(-r));
+ r = set_put_error(j, r);
+ if (r < 0)
+ return r;
+ }
+ }
+ }
+
+ check_network(j, dirfd(d));
+
+ return 0;
+}
+
+static int add_root_directory(sd_journal *j, const char *p) {
+ _cleanup_closedir_ DIR *d = NULL;
+ Directory *m;
+ int r;
+
+ assert(j);
+ assert(p);
+
+ if ((j->flags & SD_JOURNAL_RUNTIME_ONLY) &&
+ !path_startswith(p, "/run"))
+ return -EINVAL;
+
+ d = opendir(p);
+ if (!d)
+ return -errno;
+
+ m = hashmap_get(j->directories_by_path, p);
+ if (!m) {
+ m = new0(Directory, 1);
+ if (!m)
+ return -ENOMEM;
+
+ m->is_root = true;
+ m->path = strdup(p);
+ if (!m->path) {
+ free(m);
+ return -ENOMEM;
+ }
+
+ if (hashmap_put(j->directories_by_path, m->path, m) < 0) {
+ free(m->path);
+ free(m);
+ return -ENOMEM;
+ }
+
+ j->current_invalidate_counter ++;
+
+ log_debug("Root directory %s got added.", m->path);
+
+ } else if (!m->is_root)
+ return 0;
+
+ if (m->wd <= 0 && j->inotify_fd >= 0) {
+
+ m->wd = inotify_add_watch(j->inotify_fd, m->path,
+ IN_CREATE|IN_MOVED_TO|IN_MODIFY|IN_ATTRIB|IN_DELETE|
+ IN_ONLYDIR);
+
+ if (m->wd > 0 && hashmap_put(j->directories_by_wd, INT_TO_PTR(m->wd), m) < 0)
+ inotify_rm_watch(j->inotify_fd, m->wd);
+ }
+
+ for (;;) {
+ struct dirent *de;
+ union dirent_storage buf;
+ sd_id128_t id;
+
+ r = readdir_r(d, &buf.de, &de);
+ if (r != 0 || !de)
+ break;
+
+ if (dirent_is_file_with_suffix(de, ".journal") ||
+ dirent_is_file_with_suffix(de, ".journal~")) {
+ r = add_file(j, m->path, de->d_name);
+ if (r < 0) {
+ log_debug("Failed to add file %s/%s: %s",
+ m->path, de->d_name, strerror(-r));
+ r = set_put_error(j, r);
+ if (r < 0)
+ return r;
+ }
+ } else if ((de->d_type == DT_DIR || de->d_type == DT_LNK || de->d_type == DT_UNKNOWN) &&
+ sd_id128_from_string(de->d_name, &id) >= 0) {
+
+ r = add_directory(j, m->path, de->d_name);
+ if (r < 0)
+ log_debug("Failed to add directory %s/%s: %s", m->path, de->d_name, strerror(-r));
+ }
+ }
+
+ check_network(j, dirfd(d));
+
+ return 0;
+}
+
+static int remove_directory(sd_journal *j, Directory *d) {
+ assert(j);
+
+ if (d->wd > 0) {
+ hashmap_remove(j->directories_by_wd, INT_TO_PTR(d->wd));
+
+ if (j->inotify_fd >= 0)
+ inotify_rm_watch(j->inotify_fd, d->wd);
+ }
+
+ hashmap_remove(j->directories_by_path, d->path);
+
+ if (d->is_root)
+ log_debug("Root directory %s got removed.", d->path);
+ else
+ log_debug("Directory %s got removed.", d->path);
+
+ free(d->path);
+ free(d);
+
+ return 0;
+}
+
+static int add_search_paths(sd_journal *j) {
+ int r;
+ const char search_paths[] =
+ "/run/log/journal\0"
+ "/var/log/journal\0";
+ const char *p;
+
+ assert(j);
+
+ /* We ignore most errors here, since the idea is to only open
+ * what's actually accessible, and ignore the rest. */
+
+ NULSTR_FOREACH(p, search_paths) {
+ r = add_root_directory(j, p);
+ if (r < 0 && r != -ENOENT) {
+ r = set_put_error(j, r);
+ if (r < 0)
+ return r;
+ }
+ }
+
+ return 0;
+}
+
+static int allocate_inotify(sd_journal *j) {
+ assert(j);
+
+ if (j->inotify_fd < 0) {
+ j->inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
+ if (j->inotify_fd < 0)
+ return -errno;
+ }
+
+ if (!j->directories_by_wd) {
+ j->directories_by_wd = hashmap_new(trivial_hash_func, trivial_compare_func);
+ if (!j->directories_by_wd)
+ return -ENOMEM;
+ }
+
+ return 0;
+}
+
+static sd_journal *journal_new(int flags, const char *path) {
+ sd_journal *j;
+
+ j = new0(sd_journal, 1);
+ if (!j)
+ return NULL;
+
+ j->inotify_fd = -1;
+ j->flags = flags;
+ j->data_threshold = DEFAULT_DATA_THRESHOLD;
+
+ if (path) {
+ j->path = strdup(path);
+ if (!j->path)
+ goto fail;
+ }
+
+ j->files = hashmap_new(string_hash_func, string_compare_func);
+ j->directories_by_path = hashmap_new(string_hash_func, string_compare_func);
+ j->mmap = mmap_cache_new();
+ if (!j->files || !j->directories_by_path || !j->mmap)
+ goto fail;
+
+ return j;
+
+fail:
+ sd_journal_close(j);
+ return NULL;
+}
+
+_public_ int sd_journal_open(sd_journal **ret, int flags) {
+ sd_journal *j;
+ int r;
+
+ if (!ret)
+ return -EINVAL;
+
+ if (flags & ~(SD_JOURNAL_LOCAL_ONLY|
+ SD_JOURNAL_RUNTIME_ONLY|
+ SD_JOURNAL_SYSTEM_ONLY))
+ return -EINVAL;
+
+ j = journal_new(flags, NULL);
+ if (!j)
+ return -ENOMEM;
+
+ r = add_search_paths(j);
+ if (r < 0)
+ goto fail;
+
+ *ret = j;
+ return 0;
+
+fail:
+ sd_journal_close(j);
+
+ return r;
+}
+
+_public_ int sd_journal_open_directory(sd_journal **ret, const char *path, int flags) {
+ sd_journal *j;
+ int r;
+
+ if (!ret)
+ return -EINVAL;
+
+ if (!path)
+ return -EINVAL;
+
+ if (flags != 0)
+ return -EINVAL;
+
+ j = journal_new(flags, path);
+ if (!j)
+ return -ENOMEM;
+
+ r = add_root_directory(j, path);
+ if (r < 0) {
+ set_put_error(j, r);
+ goto fail;
+ }
+
+ *ret = j;
+ return 0;
+
+fail:
+ sd_journal_close(j);
+
+ return r;
+}
+
+_public_ void sd_journal_close(sd_journal *j) {
+ Directory *d;
+ JournalFile *f;
+
+ if (!j)
+ return;
+
+ sd_journal_flush_matches(j);
+
+ while ((f = hashmap_steal_first(j->files)))
+ journal_file_close(f);
+
+ hashmap_free(j->files);
+
+ while ((d = hashmap_first(j->directories_by_path)))
+ remove_directory(j, d);
+
+ while ((d = hashmap_first(j->directories_by_wd)))
+ remove_directory(j, d);
+
+ hashmap_free(j->directories_by_path);
+ hashmap_free(j->directories_by_wd);
+
+ if (j->inotify_fd >= 0)
+ close_nointr_nofail(j->inotify_fd);
+
+ if (j->mmap)
+ mmap_cache_unref(j->mmap);
+
+ free(j->path);
+ free(j->unique_field);
+ set_free(j->errors);
+ free(j);
+}
+
+_public_ int sd_journal_get_realtime_usec(sd_journal *j, uint64_t *ret) {
+ Object *o;
+ JournalFile *f;
+ int r;
+
+ if (!j)
+ return -EINVAL;
+ if (!ret)
+ return -EINVAL;
+
+ f = j->current_file;
+ if (!f)
+ return -EADDRNOTAVAIL;
+
+ if (f->current_offset <= 0)
+ return -EADDRNOTAVAIL;
+
+ r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
+ if (r < 0)
+ return r;
+
+ *ret = le64toh(o->entry.realtime);
+ return 0;
+}
+
+_public_ int sd_journal_get_monotonic_usec(sd_journal *j, uint64_t *ret, sd_id128_t *ret_boot_id) {
+ Object *o;
+ JournalFile *f;
+ int r;
+ sd_id128_t id;
+
+ if (!j)
+ return -EINVAL;
+
+ f = j->current_file;
+ if (!f)
+ return -EADDRNOTAVAIL;
+
+ if (f->current_offset <= 0)
+ return -EADDRNOTAVAIL;
+
+ r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
+ if (r < 0)
+ return r;
+
+ if (ret_boot_id)
+ *ret_boot_id = o->entry.boot_id;
+ else {
+ r = sd_id128_get_boot(&id);
+ if (r < 0)
+ return r;
+
+ if (!sd_id128_equal(id, o->entry.boot_id))
+ return -ESTALE;
+ }
+
+ if (ret)
+ *ret = le64toh(o->entry.monotonic);
+
+ return 0;
+}
+
+static bool field_is_valid(const char *field) {
+ const char *p;
+
+ assert(field);
+
+ if (isempty(field))
+ return false;
+
+ if (startswith(field, "__"))
+ return false;
+
+ for (p = field; *p; p++) {
+
+ if (*p == '_')
+ continue;
+
+ if (*p >= 'A' && *p <= 'Z')
+ continue;
+
+ if (*p >= '0' && *p <= '9')
+ continue;
+
+ return false;
+ }
+
+ return true;
+}
+
+_public_ int sd_journal_get_data(sd_journal *j, const char *field, const void **data, size_t *size) {
+ JournalFile *f;
+ uint64_t i, n;
+ size_t field_length;
+ int r;
+ Object *o;
+
+ if (!j)
+ return -EINVAL;
+ if (!field)
+ return -EINVAL;
+ if (!data)
+ return -EINVAL;
+ if (!size)
+ return -EINVAL;
+
+ if (!field_is_valid(field))
+ return -EINVAL;
+
+ f = j->current_file;
+ if (!f)
+ return -EADDRNOTAVAIL;
+
+ if (f->current_offset <= 0)
+ return -EADDRNOTAVAIL;
+
+ r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
+ if (r < 0)
+ return r;
+
+ field_length = strlen(field);
+
+ n = journal_file_entry_n_items(o);
+ for (i = 0; i < n; i++) {
+ uint64_t p, l;
+ le64_t le_hash;
+ size_t t;
+
+ p = le64toh(o->entry.items[i].object_offset);
+ le_hash = o->entry.items[i].hash;
+ r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
+ if (r < 0)
+ return r;
+
+ if (le_hash != o->data.hash)
+ return -EBADMSG;
+
+ l = le64toh(o->object.size) - offsetof(Object, data.payload);
+
+ if (o->object.flags & OBJECT_COMPRESSED) {
+
+#ifdef HAVE_XZ
+ if (uncompress_startswith(o->data.payload, l,
+ &f->compress_buffer, &f->compress_buffer_size,
+ field, field_length, '=')) {
+
+ uint64_t rsize;
+
+ if (!uncompress_blob(o->data.payload, l,
+ &f->compress_buffer, &f->compress_buffer_size, &rsize,
+ j->data_threshold))
+ return -EBADMSG;
+
+ *data = f->compress_buffer;
+ *size = (size_t) rsize;
+
+ return 0;
+ }
+#else
+ return -EPROTONOSUPPORT;
+#endif
+
+ } else if (l >= field_length+1 &&
+ memcmp(o->data.payload, field, field_length) == 0 &&
+ o->data.payload[field_length] == '=') {
+
+ t = (size_t) l;
+
+ if ((uint64_t) t != l)
+ return -E2BIG;
+
+ *data = o->data.payload;
+ *size = t;
+
+ return 0;
+ }
+
+ r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
+ if (r < 0)
+ return r;
+ }
+
+ return -ENOENT;
+}
+
+static int return_data(sd_journal *j, JournalFile *f, Object *o, const void **data, size_t *size) {
+ size_t t;
+ uint64_t l;
+
+ l = le64toh(o->object.size) - offsetof(Object, data.payload);
+ t = (size_t) l;
+
+ /* We can't read objects larger than 4G on a 32bit machine */
+ if ((uint64_t) t != l)
+ return -E2BIG;
+
+ if (o->object.flags & OBJECT_COMPRESSED) {
+#ifdef HAVE_XZ
+ uint64_t rsize;
+
+ if (!uncompress_blob(o->data.payload, l, &f->compress_buffer, &f->compress_buffer_size, &rsize, j->data_threshold))
+ return -EBADMSG;
+
+ *data = f->compress_buffer;
+ *size = (size_t) rsize;
+#else
+ return -EPROTONOSUPPORT;
+#endif
+ } else {
+ *data = o->data.payload;
+ *size = t;
+ }
+
+ return 0;
+}
+
+_public_ int sd_journal_enumerate_data(sd_journal *j, const void **data, size_t *size) {
+ JournalFile *f;
+ uint64_t p, n;
+ le64_t le_hash;
+ int r;
+ Object *o;
+
+ if (!j)
+ return -EINVAL;
+ if (!data)
+ return -EINVAL;
+ if (!size)
+ return -EINVAL;
+
+ f = j->current_file;
+ if (!f)
+ return -EADDRNOTAVAIL;
+
+ if (f->current_offset <= 0)
+ return -EADDRNOTAVAIL;
+
+ r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
+ if (r < 0)
+ return r;
+
+ n = journal_file_entry_n_items(o);
+ if (j->current_field >= n)
+ return 0;
+
+ p = le64toh(o->entry.items[j->current_field].object_offset);
+ le_hash = o->entry.items[j->current_field].hash;
+ r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
+ if (r < 0)
+ return r;
+
+ if (le_hash != o->data.hash)
+ return -EBADMSG;
+
+ r = return_data(j, f, o, data, size);
+ if (r < 0)
+ return r;
+
+ j->current_field ++;
+
+ return 1;
+}
+
+_public_ void sd_journal_restart_data(sd_journal *j) {
+ if (!j)
+ return;
+
+ j->current_field = 0;
+}
+
+_public_ int sd_journal_get_fd(sd_journal *j) {
+ int r;
+
+ if (!j)
+ return -EINVAL;
+
+ if (j->inotify_fd >= 0)
+ return j->inotify_fd;
+
+ r = allocate_inotify(j);
+ if (r < 0)
+ return r;
+
+ /* Iterate through all dirs again, to add them to the
+ * inotify */
+ if (j->path)
+ r = add_root_directory(j, j->path);
+ else
+ r = add_search_paths(j);
+ if (r < 0)
+ return r;
+
+ return j->inotify_fd;
+}
+
+_public_ int sd_journal_get_events(sd_journal *j) {
+ int fd;
+
+ if (!j)
+ return -EINVAL;
+
+ fd = sd_journal_get_fd(j);
+ if (fd < 0)
+ return fd;
+
+ return POLLIN;
+}
+
+_public_ int sd_journal_get_timeout(sd_journal *j, uint64_t *timeout_usec) {
+ int fd;
+
+ if (!j)
+ return -EINVAL;
+ if (!timeout_usec)
+ return -EINVAL;
+
+ fd = sd_journal_get_fd(j);
+ if (fd < 0)
+ return fd;
+
+ if (!j->on_network) {
+ *timeout_usec = (uint64_t) -1;
+ return 0;
+ }
+
+ /* If we are on the network we need to regularly check for
+ * changes manually */
+
+ *timeout_usec = j->last_process_usec + JOURNAL_FILES_RECHECK_USEC;
+ return 1;
+}
+
+static void process_inotify_event(sd_journal *j, struct inotify_event *e) {
+ Directory *d;
+ int r;
+
+ assert(j);
+ assert(e);
+
+ /* Is this a subdirectory we watch? */
+ d = hashmap_get(j->directories_by_wd, INT_TO_PTR(e->wd));
+ if (d) {
+ sd_id128_t id;
+
+ if (!(e->mask & IN_ISDIR) && e->len > 0 &&
+ (endswith(e->name, ".journal") ||
+ endswith(e->name, ".journal~"))) {
+
+ /* Event for a journal file */
+
+ if (e->mask & (IN_CREATE|IN_MOVED_TO|IN_MODIFY|IN_ATTRIB)) {
+ r = add_file(j, d->path, e->name);
+ if (r < 0) {
+ log_debug("Failed to add file %s/%s: %s",
+ d->path, e->name, strerror(-r));
+ set_put_error(j, r);
+ }
+
+ } else if (e->mask & (IN_DELETE|IN_MOVED_FROM|IN_UNMOUNT)) {
+
+ r = remove_file(j, d->path, e->name);
+ if (r < 0)
+ log_debug("Failed to remove file %s/%s: %s", d->path, e->name, strerror(-r));
+ }
+
+ } else if (!d->is_root && e->len == 0) {
+
+ /* Event for a subdirectory */
+
+ if (e->mask & (IN_DELETE_SELF|IN_MOVE_SELF|IN_UNMOUNT)) {
+ r = remove_directory(j, d);
+ if (r < 0)
+ log_debug("Failed to remove directory %s: %s", d->path, strerror(-r));
+ }
+
+
+ } else if (d->is_root && (e->mask & IN_ISDIR) && e->len > 0 && sd_id128_from_string(e->name, &id) >= 0) {
+
+ /* Event for root directory */
+
+ if (e->mask & (IN_CREATE|IN_MOVED_TO|IN_MODIFY|IN_ATTRIB)) {
+ r = add_directory(j, d->path, e->name);
+ if (r < 0)
+ log_debug("Failed to add directory %s/%s: %s", d->path, e->name, strerror(-r));
+ }
+ }
+
+ return;
+ }
+
+ if (e->mask & IN_IGNORED)
+ return;
+
+ log_warning("Unknown inotify event.");
+}
+
+static int determine_change(sd_journal *j) {
+ bool b;
+
+ assert(j);
+
+ b = j->current_invalidate_counter != j->last_invalidate_counter;
+ j->last_invalidate_counter = j->current_invalidate_counter;
+
+ return b ? SD_JOURNAL_INVALIDATE : SD_JOURNAL_APPEND;
+}
+
+_public_ int sd_journal_process(sd_journal *j) {
+ uint8_t buffer[sizeof(struct inotify_event) + FILENAME_MAX] _alignas_(struct inotify_event);
+ bool got_something = false;
+
+ if (!j)
+ return -EINVAL;
+
+ j->last_process_usec = now(CLOCK_MONOTONIC);
+
+ for (;;) {
+ struct inotify_event *e;
+ ssize_t l;
+
+ l = read(j->inotify_fd, buffer, sizeof(buffer));
+ if (l < 0) {
+ if (errno == EAGAIN || errno == EINTR)
+ return got_something ? determine_change(j) : SD_JOURNAL_NOP;
+
+ return -errno;
+ }
+
+ got_something = true;
+
+ e = (struct inotify_event*) buffer;
+ while (l > 0) {
+ size_t step;
+
+ process_inotify_event(j, e);
+
+ step = sizeof(struct inotify_event) + e->len;
+ assert(step <= (size_t) l);
+
+ e = (struct inotify_event*) ((uint8_t*) e + step);
+ l -= step;
+ }
+ }
+
+ return determine_change(j);
+}
+
+_public_ int sd_journal_wait(sd_journal *j, uint64_t timeout_usec) {
+ int r;
+ uint64_t t;
+
+ assert(j);
+
+ if (j->inotify_fd < 0) {
+
+ /* This is the first invocation, hence create the
+ * inotify watch */
+ r = sd_journal_get_fd(j);
+ if (r < 0)
+ return r;
+
+ /* The journal might have changed since the context
+ * object was created and we weren't watching before,
+ * hence don't wait for anything, and return
+ * immediately. */
+ return determine_change(j);
+ }
+
+ r = sd_journal_get_timeout(j, &t);
+ if (r < 0)
+ return r;
+
+ if (t != (uint64_t) -1) {
+ usec_t n;
+
+ n = now(CLOCK_MONOTONIC);
+ t = t > n ? t - n : 0;
+
+ if (timeout_usec == (uint64_t) -1 || timeout_usec > t)
+ timeout_usec = t;
+ }
+
+ do {
+ r = fd_wait_for_event(j->inotify_fd, POLLIN, timeout_usec);
+ } while (r == -EINTR);
+
+ if (r < 0)
+ return r;
+
+ return sd_journal_process(j);
+}
+
+_public_ int sd_journal_get_cutoff_realtime_usec(sd_journal *j, uint64_t *from, uint64_t *to) {
+ Iterator i;
+ JournalFile *f;
+ bool first = true;
+ int r;
+
+ if (!j)
+ return -EINVAL;
+ if (!from && !to)
+ return -EINVAL;
+
+ HASHMAP_FOREACH(f, j->files, i) {
+ usec_t fr, t;
+
+ r = journal_file_get_cutoff_realtime_usec(f, &fr, &t);
+ if (r == -ENOENT)
+ continue;
+ if (r < 0)
+ return r;
+ if (r == 0)
+ continue;
+
+ if (first) {
+ if (from)
+ *from = fr;
+ if (to)
+ *to = t;
+ first = false;
+ } else {
+ if (from)
+ *from = MIN(fr, *from);
+ if (to)
+ *to = MAX(t, *to);
+ }
+ }
+
+ return first ? 0 : 1;
+}
+
+_public_ int sd_journal_get_cutoff_monotonic_usec(sd_journal *j, sd_id128_t boot_id, uint64_t *from, uint64_t *to) {
+ Iterator i;
+ JournalFile *f;
+ bool first = true;
+ int r;
+
+ if (!j)
+ return -EINVAL;
+ if (!from && !to)
+ return -EINVAL;
+
+ HASHMAP_FOREACH(f, j->files, i) {
+ usec_t fr, t;
+
+ r = journal_file_get_cutoff_monotonic_usec(f, boot_id, &fr, &t);
+ if (r == -ENOENT)
+ continue;
+ if (r < 0)
+ return r;
+ if (r == 0)
+ continue;
+
+ if (first) {
+ if (from)
+ *from = fr;
+ if (to)
+ *to = t;
+ first = false;
+ } else {
+ if (from)
+ *from = MIN(fr, *from);
+ if (to)
+ *to = MAX(t, *to);
+ }
+ }
+
+ return first ? 0 : 1;
+}
+
+void journal_print_header(sd_journal *j) {
+ Iterator i;
+ JournalFile *f;
+ bool newline = false;
+
+ assert(j);
+
+ HASHMAP_FOREACH(f, j->files, i) {
+ if (newline)
+ putchar('\n');
+ else
+ newline = true;
+
+ journal_file_print_header(f);
+ }
+}
+
+_public_ int sd_journal_get_usage(sd_journal *j, uint64_t *bytes) {
+ Iterator i;
+ JournalFile *f;
+ uint64_t sum = 0;
+
+ if (!j)
+ return -EINVAL;
+ if (!bytes)
+ return -EINVAL;
+
+ HASHMAP_FOREACH(f, j->files, i) {
+ struct stat st;
+
+ if (fstat(f->fd, &st) < 0)
+ return -errno;
+
+ sum += (uint64_t) st.st_blocks * 512ULL;
+ }
+
+ *bytes = sum;
+ return 0;
+}
+
+_public_ int sd_journal_query_unique(sd_journal *j, const char *field) {
+ char *f;
+
+ if (!j)
+ return -EINVAL;
+ if (isempty(field))
+ return -EINVAL;
+ if (!field_is_valid(field))
+ return -EINVAL;
+
+ f = strdup(field);
+ if (!f)
+ return -ENOMEM;
+
+ free(j->unique_field);
+ j->unique_field = f;
+ j->unique_file = NULL;
+ j->unique_offset = 0;
+
+ return 0;
+}
+
+_public_ int sd_journal_enumerate_unique(sd_journal *j, const void **data, size_t *l) {
+ Object *o;
+ size_t k;
+ int r;
+
+ if (!j)
+ return -EINVAL;
+ if (!data)
+ return -EINVAL;
+ if (!l)
+ return -EINVAL;
+ if (!j->unique_field)
+ return -EINVAL;
+
+ k = strlen(j->unique_field);
+
+ if (!j->unique_file) {
+ j->unique_file = hashmap_first(j->files);
+ if (!j->unique_file)
+ return 0;
+ j->unique_offset = 0;
+ }
+
+ for (;;) {
+ JournalFile *of;
+ Iterator i;
+ const void *odata;
+ size_t ol;
+ bool found;
+
+ /* Proceed to next data object in the field's linked list */
+ if (j->unique_offset == 0) {
+ r = journal_file_find_field_object(j->unique_file, j->unique_field, k, &o, NULL);
+ if (r < 0)
+ return r;
+
+ j->unique_offset = r > 0 ? le64toh(o->field.head_data_offset) : 0;
+ } else {
+ r = journal_file_move_to_object(j->unique_file, OBJECT_DATA, j->unique_offset, &o);
+ if (r < 0)
+ return r;
+
+ j->unique_offset = le64toh(o->data.next_field_offset);
+ }
+
+ /* We reached the end of the list? Then start again, with the next file */
+ if (j->unique_offset == 0) {
+ JournalFile *n;
+
+ n = hashmap_next(j->files, j->unique_file->path);
+ if (!n)
+ return 0;
+
+ j->unique_file = n;
+ continue;
+ }
+
+ /* We do not use the type context here, but 0 instead,
+ * so that we can look at this data object at the same
+ * time as one on another file */
+ r = journal_file_move_to_object(j->unique_file, 0, j->unique_offset, &o);
+ if (r < 0)
+ return r;
+
+ /* Let's do the type check by hand, since we used 0 context above. */
+ if (o->object.type != OBJECT_DATA)
+ return -EBADMSG;
+
+ r = return_data(j, j->unique_file, o, &odata, &ol);
+ if (r < 0)
+ return r;
+
+ /* OK, now let's see if we already returned this data
+ * object by checking if it exists in the earlier
+ * traversed files. */
+ found = false;
+ HASHMAP_FOREACH(of, j->files, i) {
+ Object *oo;
+ uint64_t op;
+
+ if (of == j->unique_file)
+ break;
+
+ /* Skip this file it didn't have any fields
+ * indexed */
+ if (JOURNAL_HEADER_CONTAINS(of->header, n_fields) &&
+ le64toh(of->header->n_fields) <= 0)
+ continue;
+
+ r = journal_file_find_data_object_with_hash(of, odata, ol, le64toh(o->data.hash), &oo, &op);
+ if (r < 0)
+ return r;
+
+ if (r > 0)
+ found = true;
+ }
+
+ if (found)
+ continue;
+
+ r = return_data(j, j->unique_file, o, data, l);
+ if (r < 0)
+ return r;
+
+ return 1;
+ }
+}
+
+_public_ void sd_journal_restart_unique(sd_journal *j) {
+ if (!j)
+ return;
+
+ j->unique_file = NULL;
+ j->unique_offset = 0;
+}
+
+_public_ int sd_journal_reliable_fd(sd_journal *j) {
+ if (!j)
+ return -EINVAL;
+
+ return !j->on_network;
+}
+
+static char *lookup_field(const char *field, void *userdata) {
+ sd_journal *j = userdata;
+ const void *data;
+ size_t size, d;
+ int r;
+
+ assert(field);
+ assert(j);
+
+ r = sd_journal_get_data(j, field, &data, &size);
+ if (r < 0 ||
+ size > REPLACE_VAR_MAX)
+ return strdup(field);
+
+ d = strlen(field) + 1;
+
+ return strndup((const char*) data + d, size - d);
+}
+
+_public_ int sd_journal_get_catalog(sd_journal *j, char **ret) {
+ const void *data;
+ size_t size;
+ sd_id128_t id;
+ _cleanup_free_ char *text = NULL, *cid = NULL;
+ char *t;
+ int r;
+
+ if (!j)
+ return -EINVAL;
+ if (!ret)
+ return -EINVAL;
+
+ r = sd_journal_get_data(j, "MESSAGE_ID", &data, &size);
+ if (r < 0)
+ return r;
+
+ cid = strndup((const char*) data + 11, size - 11);
+ if (!cid)
+ return -ENOMEM;
+
+ r = sd_id128_from_string(cid, &id);
+ if (r < 0)
+ return r;
+
+ r = catalog_get(CATALOG_DATABASE, id, &text);
+ if (r < 0)
+ return r;
+
+ t = replace_var(text, lookup_field, j);
+ if (!t)
+ return -ENOMEM;
+
+ *ret = t;
+ return 0;
+}
+
+_public_ int sd_journal_get_catalog_for_message_id(sd_id128_t id, char **ret) {
+ if (!ret)
+ return -EINVAL;
+
+ return catalog_get(CATALOG_DATABASE, id, ret);
+}
+
+_public_ int sd_journal_set_data_threshold(sd_journal *j, size_t sz) {
+ if (!j)
+ return -EINVAL;
+
+ j->data_threshold = sz;
+ return 0;
+}
+
+_public_ int sd_journal_get_data_threshold(sd_journal *j, size_t *sz) {
+ if (!j)
+ return -EINVAL;
+ if (!sz)
+ return -EINVAL;
+
+ *sz = j->data_threshold;
+ return 0;
+}
diff --git a/src/journal/test-catalog.c b/src/journal/test-catalog.c
new file mode 100644
index 0000000000..987867f0c8
--- /dev/null
+++ b/src/journal/test-catalog.c
@@ -0,0 +1,134 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+ Copyright 2013 Zbigniew Jędrzejewski-Szmek
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <locale.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <errno.h>
+
+#include "util.h"
+#include "log.h"
+#include "macro.h"
+#include "sd-messages.h"
+#include "catalog.h"
+
+static void test_import(Hashmap *h, struct strbuf *sb,
+ const char* contents, ssize_t size, int code) {
+ int r;
+ char name[] = "/tmp/test-catalog.XXXXXX";
+ _cleanup_close_ int fd = mkstemp(name);
+ assert(fd >= 0);
+ assert_se(write(fd, contents, size) == size);
+
+ r = catalog_import_file(h, sb, name);
+ assert(r == code);
+
+ unlink(name);
+}
+
+static void test_catalog_importing(void) {
+ Hashmap *h;
+ struct strbuf *sb;
+
+ assert_se(h = hashmap_new(catalog_hash_func, catalog_compare_func));
+ assert_se(sb = strbuf_new());
+
+#define BUF "xxx"
+ test_import(h, sb, BUF, sizeof(BUF), -EINVAL);
+#undef BUF
+ assert(hashmap_isempty(h));
+ log_debug("----------------------------------------");
+
+#define BUF \
+"-- 0027229ca0644181a76c4e92458afaff dededededededededededededededede\n" \
+"Subject: message\n" \
+"\n" \
+"payload\n"
+ test_import(h, sb, BUF, sizeof(BUF), -EINVAL);
+#undef BUF
+
+ log_debug("----------------------------------------");
+
+#define BUF \
+"-- 0027229ca0644181a76c4e92458afaff dededededededededededededededed\n" \
+"Subject: message\n" \
+"\n" \
+"payload\n"
+ test_import(h, sb, BUF, sizeof(BUF), 0);
+#undef BUF
+
+ assert(hashmap_size(h) == 1);
+
+ log_debug("----------------------------------------");
+
+ hashmap_free_free(h);
+ strbuf_cleanup(sb);
+}
+
+
+static const char* database = NULL;
+
+static void test_catalog_update(void) {
+ int r;
+
+ static char name[] = "/tmp/test-catalog.XXXXXX";
+ r = mkstemp(name);
+ assert(r >= 0);
+
+ database = name;
+
+ /* Test what happens if there are no files. */
+ r = catalog_update(database, NULL, NULL);
+ assert(r >= 0);
+
+ /* Note: this might actually not find anything, if systemd was
+ * not installed before. That should be fine too. */
+ r = catalog_update(database, NULL, catalog_file_dirs);
+ assert(r >= 0);
+}
+
+int main(int argc, char *argv[]) {
+ _cleanup_free_ char *text = NULL;
+ int r;
+
+ setlocale(LC_ALL, "de_DE.UTF-8");
+
+ log_set_max_level(LOG_DEBUG);
+
+ test_catalog_importing();
+
+ test_catalog_update();
+
+ r = catalog_list(stdout, database, true);
+ assert_se(r >= 0);
+
+ r = catalog_list(stdout, database, false);
+ assert_se(r >= 0);
+
+ assert_se(catalog_get(database, SD_MESSAGE_COREDUMP, &text) >= 0);
+ printf(">>>%s<<<\n", text);
+
+ if (database)
+ unlink(database);
+
+ return 0;
+}
diff --git a/src/journal/test-journal-enum.c b/src/journal/test-journal-enum.c
new file mode 100644
index 0000000000..980244e016
--- /dev/null
+++ b/src/journal/test-journal-enum.c
@@ -0,0 +1,55 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+
+#include "log.h"
+#include "sd-journal.h"
+#include "macro.h"
+#include "util.h"
+#include "journal-internal.h"
+
+int main(int argc, char *argv[]) {
+ unsigned n = 0;
+ _cleanup_journal_close_ sd_journal*j = NULL;
+
+ log_set_max_level(LOG_DEBUG);
+
+ assert_se(sd_journal_open(&j, SD_JOURNAL_LOCAL_ONLY) >= 0);
+
+ assert_se(sd_journal_add_match(j, "_TRANSPORT=syslog", 0) >= 0);
+ assert_se(sd_journal_add_match(j, "_UID=0", 0) >= 0);
+
+ SD_JOURNAL_FOREACH_BACKWARDS(j) {
+ const void *d;
+ size_t l;
+
+ assert_se(sd_journal_get_data(j, "MESSAGE", &d, &l) >= 0);
+
+ printf("%.*s\n", (int) l, (char*) d);
+
+ n ++;
+ if (n >= 10)
+ break;
+ }
+
+ return 0;
+}
diff --git a/src/journal/test-journal-match.c b/src/journal/test-journal-match.c
new file mode 100644
index 0000000000..37bffc1883
--- /dev/null
+++ b/src/journal/test-journal-match.c
@@ -0,0 +1,76 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+
+#include <systemd/sd-journal.h>
+
+#include "journal-internal.h"
+#include "util.h"
+#include "log.h"
+
+int main(int argc, char *argv[]) {
+ _cleanup_journal_close_ sd_journal*j;
+ _cleanup_free_ char *t;
+
+ log_set_max_level(LOG_DEBUG);
+
+ assert_se(sd_journal_open(&j, 0) >= 0);
+
+ assert_se(sd_journal_add_match(j, "foobar", 0) < 0);
+ assert_se(sd_journal_add_match(j, "foobar=waldo", 0) < 0);
+ assert_se(sd_journal_add_match(j, "", 0) < 0);
+ assert_se(sd_journal_add_match(j, "=", 0) < 0);
+ assert_se(sd_journal_add_match(j, "=xxxxx", 0) < 0);
+ assert_se(sd_journal_add_match(j, "HALLO=WALDO", 0) >= 0);
+ assert_se(sd_journal_add_match(j, "QUUX=mmmm", 0) >= 0);
+ assert_se(sd_journal_add_match(j, "QUUX=xxxxx", 0) >= 0);
+ assert_se(sd_journal_add_match(j, "HALLO=", 0) >= 0);
+ assert_se(sd_journal_add_match(j, "QUUX=xxxxx", 0) >= 0);
+ assert_se(sd_journal_add_match(j, "QUUX=yyyyy", 0) >= 0);
+ assert_se(sd_journal_add_match(j, "PIFF=paff", 0) >= 0);
+
+ assert_se(sd_journal_add_disjunction(j) >= 0);
+
+ assert_se(sd_journal_add_match(j, "ONE=one", 0) >= 0);
+ assert_se(sd_journal_add_match(j, "ONE=two", 0) >= 0);
+ assert_se(sd_journal_add_match(j, "TWO=two", 0) >= 0);
+
+ assert_se(sd_journal_add_conjunction(j) >= 0);
+
+ assert_se(sd_journal_add_match(j, "L4_1=yes", 0) >= 0);
+ assert_se(sd_journal_add_match(j, "L4_1=ok", 0) >= 0);
+ assert_se(sd_journal_add_match(j, "L4_2=yes", 0) >= 0);
+ assert_se(sd_journal_add_match(j, "L4_2=ok", 0) >= 0);
+
+ assert_se(sd_journal_add_disjunction(j) >= 0);
+
+ assert_se(sd_journal_add_match(j, "L3=yes", 0) >= 0);
+ assert_se(sd_journal_add_match(j, "L3=ok", 0) >= 0);
+
+ assert_se(t = journal_make_match_string(j));
+
+ printf("resulting match expression is: %s\n", t);
+
+ assert_se(streq(t, "(((L3=ok OR L3=yes) OR ((L4_2=ok OR L4_2=yes) AND (L4_1=ok OR L4_1=yes))) AND ((TWO=two AND (ONE=two OR ONE=one)) OR (PIFF=paff AND (QUUX=yyyyy OR QUUX=xxxxx OR QUUX=mmmm) AND (HALLO= OR HALLO=WALDO))))"));
+
+ return 0;
+}
diff --git a/src/journal/test-journal-send.c b/src/journal/test-journal-send.c
new file mode 100644
index 0000000000..3e986ed99a
--- /dev/null
+++ b/src/journal/test-journal-send.c
@@ -0,0 +1,78 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <systemd/sd-journal.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#include "log.h"
+
+int main(int argc, char *argv[]) {
+ char huge[4096*1024];
+
+ log_set_max_level(LOG_DEBUG);
+
+ sd_journal_print(LOG_INFO, "piepapo");
+
+ sd_journal_send("MESSAGE=foobar",
+ "VALUE=%i", 7,
+ NULL);
+
+ errno = ENOENT;
+ sd_journal_perror("Foobar");
+
+ sd_journal_perror("");
+
+ memset(huge, 'x', sizeof(huge));
+ memcpy(huge, "HUGE=", 5);
+ char_array_0(huge);
+
+ sd_journal_send("MESSAGE=Huge field attached",
+ huge,
+ NULL);
+
+ sd_journal_send("MESSAGE=uiui",
+ "VALUE=A",
+ "VALUE=B",
+ "VALUE=C",
+ "SINGLETON=1",
+ "OTHERVALUE=X",
+ "OTHERVALUE=Y",
+ "WITH_BINARY=this is a binary value \a",
+ NULL);
+
+ syslog(LOG_NOTICE, "Hello World!");
+
+ sd_journal_print(LOG_NOTICE, "Hello World");
+
+ sd_journal_send("MESSAGE=Hello World!",
+ "MESSAGE_ID=52fb62f99e2c49d89cfbf9d6de5e3555",
+ "PRIORITY=5",
+ "HOME=%s", getenv("HOME"),
+ "TERM=%s", getenv("TERM"),
+ "PAGE_SIZE=%li", sysconf(_SC_PAGESIZE),
+ "N_CPUS=%li", sysconf(_SC_NPROCESSORS_ONLN),
+ NULL);
+
+ sleep(10);
+
+ return 0;
+}
diff --git a/src/journal/test-journal-stream.c b/src/journal/test-journal-stream.c
new file mode 100644
index 0000000000..4aba7febc7
--- /dev/null
+++ b/src/journal/test-journal-stream.c
@@ -0,0 +1,181 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <unistd.h>
+#include <fcntl.h>
+
+#include <systemd/sd-journal.h>
+
+#include "journal-file.h"
+#include "journal-internal.h"
+#include "util.h"
+#include "log.h"
+
+#define N_ENTRIES 200
+
+static void verify_contents(sd_journal *j, unsigned skip) {
+ unsigned i;
+
+ assert(j);
+
+ i = 0;
+ SD_JOURNAL_FOREACH(j) {
+ const void *d;
+ char *k, *c;
+ size_t l;
+ unsigned u;
+
+ assert_se(sd_journal_get_cursor(j, &k) >= 0);
+ printf("cursor: %s\n", k);
+ free(k);
+
+ assert_se(sd_journal_get_data(j, "MAGIC", &d, &l) >= 0);
+ printf("\t%.*s\n", (int) l, (const char*) d);
+
+ assert_se(sd_journal_get_data(j, "NUMBER", &d, &l) >= 0);
+ assert_se(k = strndup(d, l));
+ printf("\t%s\n", k);
+
+ if (skip > 0) {
+ assert_se(safe_atou(k + 7, &u) >= 0);
+ assert_se(i == u);
+ i += skip;
+ }
+
+ free(k);
+
+ assert_se(sd_journal_get_cursor(j, &c) >= 0);
+ assert_se(sd_journal_test_cursor(j, c) > 0);
+ free(c);
+ }
+
+ if (skip > 0)
+ assert_se(i == N_ENTRIES);
+}
+
+int main(int argc, char *argv[]) {
+ JournalFile *one, *two, *three;
+ char t[] = "/tmp/journal-stream-XXXXXX";
+ unsigned i;
+ _cleanup_journal_close_ sd_journal*j = NULL;
+ char *z;
+ const void *data;
+ size_t l;
+
+ log_set_max_level(LOG_DEBUG);
+
+ assert_se(mkdtemp(t));
+ assert_se(chdir(t) >= 0);
+
+ assert_se(journal_file_open("one.journal", O_RDWR|O_CREAT, 0666, true, false, NULL, NULL, NULL, &one) == 0);
+ assert_se(journal_file_open("two.journal", O_RDWR|O_CREAT, 0666, true, false, NULL, NULL, NULL, &two) == 0);
+ assert_se(journal_file_open("three.journal", O_RDWR|O_CREAT, 0666, true, false, NULL, NULL, NULL, &three) == 0);
+
+ for (i = 0; i < N_ENTRIES; i++) {
+ char *p, *q;
+ dual_timestamp ts;
+ struct iovec iovec[2];
+
+ dual_timestamp_get(&ts);
+
+ assert_se(asprintf(&p, "NUMBER=%u", i) >= 0);
+ iovec[0].iov_base = p;
+ iovec[0].iov_len = strlen(p);
+
+ assert_se(asprintf(&q, "MAGIC=%s", i % 5 == 0 ? "quux" : "waldo") >= 0);
+
+ iovec[1].iov_base = q;
+ iovec[1].iov_len = strlen(q);
+
+ if (i % 10 == 0)
+ assert_se(journal_file_append_entry(three, &ts, iovec, 2, NULL, NULL, NULL) == 0);
+ else {
+ if (i % 3 == 0)
+ assert_se(journal_file_append_entry(two, &ts, iovec, 2, NULL, NULL, NULL) == 0);
+
+ assert_se(journal_file_append_entry(one, &ts, iovec, 2, NULL, NULL, NULL) == 0);
+ }
+
+ free(p);
+ free(q);
+ }
+
+ journal_file_close(one);
+ journal_file_close(two);
+ journal_file_close(three);
+
+ assert_se(sd_journal_open_directory(&j, t, 0) >= 0);
+
+ assert_se(sd_journal_add_match(j, "MAGIC=quux", 0) >= 0);
+ SD_JOURNAL_FOREACH_BACKWARDS(j) {
+ _cleanup_free_ char *c;
+
+ assert_se(sd_journal_get_data(j, "NUMBER", &data, &l) >= 0);
+ printf("\t%.*s\n", (int) l, (const char*) data);
+
+ assert_se(sd_journal_get_cursor(j, &c) >= 0);
+ assert_se(sd_journal_test_cursor(j, c) > 0);
+ }
+
+ SD_JOURNAL_FOREACH(j) {
+ _cleanup_free_ char *c;
+
+ assert_se(sd_journal_get_data(j, "NUMBER", &data, &l) >= 0);
+ printf("\t%.*s\n", (int) l, (const char*) data);
+
+ assert_se(sd_journal_get_cursor(j, &c) >= 0);
+ assert_se(sd_journal_test_cursor(j, c) > 0);
+ }
+
+ sd_journal_flush_matches(j);
+
+ verify_contents(j, 1);
+
+ printf("NEXT TEST\n");
+ assert_se(sd_journal_add_match(j, "MAGIC=quux", 0) >= 0);
+
+ assert_se(z = journal_make_match_string(j));
+ printf("resulting match expression is: %s\n", z);
+ free(z);
+
+ verify_contents(j, 5);
+
+ printf("NEXT TEST\n");
+ sd_journal_flush_matches(j);
+ assert_se(sd_journal_add_match(j, "MAGIC=waldo", 0) >= 0);
+ assert_se(sd_journal_add_match(j, "NUMBER=10", 0) >= 0);
+ assert_se(sd_journal_add_match(j, "NUMBER=11", 0) >= 0);
+ assert_se(sd_journal_add_match(j, "NUMBER=12", 0) >= 0);
+
+ assert_se(z = journal_make_match_string(j));
+ printf("resulting match expression is: %s\n", z);
+ free(z);
+
+ verify_contents(j, 0);
+
+ assert_se(sd_journal_query_unique(j, "NUMBER") >= 0);
+ SD_JOURNAL_FOREACH_UNIQUE(j, data, l)
+ printf("%.*s\n", (int) l, (const char*) data);
+
+ assert_se(rm_rf_dangerous(t, false, true, false) >= 0);
+
+ return 0;
+}
diff --git a/src/journal/test-journal-syslog.c b/src/journal/test-journal-syslog.c
new file mode 100644
index 0000000000..b9419372ad
--- /dev/null
+++ b/src/journal/test-journal-syslog.c
@@ -0,0 +1,44 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "journald-syslog.h"
+#include "macro.h"
+
+static void test_syslog_parse_identifier(const char* str,
+ const char *ident, const char*pid, int ret) {
+ const char *buf = str;
+ _cleanup_free_ char *ident2 = NULL, *pid2 = NULL;
+ int ret2;
+
+ ret2 = syslog_parse_identifier(&buf, &ident2, &pid2);
+
+ assert(ret == ret2);
+ assert(ident==ident2 || streq(ident, ident2));
+ assert(pid==pid2 || streq(pid, pid2));
+}
+
+int main(void) {
+ test_syslog_parse_identifier("pidu[111]: xxx", "pidu", "111", 11);
+ test_syslog_parse_identifier("pidu: xxx", "pidu", NULL, 6);
+ test_syslog_parse_identifier("pidu xxx", NULL, NULL, 0);
+
+ return 0;
+}
diff --git a/src/journal/test-journal-verify.c b/src/journal/test-journal-verify.c
new file mode 100644
index 0000000000..ad2e2d4c3b
--- /dev/null
+++ b/src/journal/test-journal-verify.c
@@ -0,0 +1,147 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include <unistd.h>
+#include <fcntl.h>
+
+#include "util.h"
+#include "log.h"
+#include "journal-file.h"
+#include "journal-verify.h"
+#include "journal-authenticate.h"
+
+#define N_ENTRIES 6000
+#define RANDOM_RANGE 77
+
+static void bit_toggle(const char *fn, uint64_t p) {
+ uint8_t b;
+ ssize_t r;
+ int fd;
+
+ fd = open(fn, O_RDWR|O_CLOEXEC);
+ assert(fd >= 0);
+
+ r = pread(fd, &b, 1, p/8);
+ assert(r == 1);
+
+ b ^= 1 << (p % 8);
+
+ r = pwrite(fd, &b, 1, p/8);
+ assert(r == 1);
+
+ close_nointr_nofail(fd);
+}
+
+static int raw_verify(const char *fn, const char *verification_key) {
+ JournalFile *f;
+ int r;
+
+ r = journal_file_open(fn, O_RDONLY, 0666, true, !!verification_key, NULL, NULL, NULL, &f);
+ if (r < 0)
+ return r;
+
+ r = journal_file_verify(f, verification_key, NULL, NULL, NULL, false);
+ journal_file_close(f);
+
+ return r;
+}
+
+int main(int argc, char *argv[]) {
+ char t[] = "/tmp/journal-XXXXXX";
+ unsigned n;
+ JournalFile *f;
+ const char *verification_key = argv[1];
+ usec_t from = 0, to = 0, total = 0;
+ char a[FORMAT_TIMESTAMP_MAX];
+ char b[FORMAT_TIMESTAMP_MAX];
+ char c[FORMAT_TIMESPAN_MAX];
+ struct stat st;
+ uint64_t p;
+
+ log_set_max_level(LOG_DEBUG);
+
+ assert_se(mkdtemp(t));
+ assert_se(chdir(t) >= 0);
+
+ log_info("Generating...");
+
+ assert_se(journal_file_open("test.journal", O_RDWR|O_CREAT, 0666, true, !!verification_key, NULL, NULL, NULL, &f) == 0);
+
+ for (n = 0; n < N_ENTRIES; n++) {
+ struct iovec iovec;
+ struct dual_timestamp ts;
+ char *test;
+
+ dual_timestamp_get(&ts);
+
+ assert_se(asprintf(&test, "RANDOM=%lu", random() % RANDOM_RANGE));
+
+ iovec.iov_base = (void*) test;
+ iovec.iov_len = strlen(test);
+
+ assert_se(journal_file_append_entry(f, &ts, &iovec, 1, NULL, NULL, NULL) == 0);
+
+ free(test);
+ }
+
+ journal_file_close(f);
+
+ log_info("Verifying...");
+
+ assert_se(journal_file_open("test.journal", O_RDONLY, 0666, true, !!verification_key, NULL, NULL, NULL, &f) == 0);
+ /* journal_file_print_header(f); */
+ journal_file_dump(f);
+
+ assert_se(journal_file_verify(f, verification_key, &from, &to, &total, true) >= 0);
+
+ if (verification_key && JOURNAL_HEADER_SEALED(f->header)) {
+ log_info("=> Validated from %s to %s, %s missing",
+ format_timestamp(a, sizeof(a), from),
+ format_timestamp(b, sizeof(b), to),
+ format_timespan(c, sizeof(c), total > to ? total - to : 0, 0));
+ }
+
+ journal_file_close(f);
+
+ if (verification_key) {
+ log_info("Toggling bits...");
+
+ assert_se(stat("test.journal", &st) >= 0);
+
+ for (p = 38448*8+0; p < ((uint64_t) st.st_size * 8); p ++) {
+ bit_toggle("test.journal", p);
+
+ log_info("[ %llu+%llu]", (unsigned long long) p / 8, (unsigned long long) p % 8);
+
+ if (raw_verify("test.journal", verification_key) >= 0)
+ log_notice(ANSI_HIGHLIGHT_RED_ON ">>>> %llu (bit %llu) can be toggled without detection." ANSI_HIGHLIGHT_OFF, (unsigned long long) p / 8, (unsigned long long) p % 8);
+
+ bit_toggle("test.journal", p);
+ }
+ }
+
+ log_info("Exiting...");
+
+ assert_se(rm_rf_dangerous(t, false, true, false) >= 0);
+
+ return 0;
+}
diff --git a/src/journal/test-journal.c b/src/journal/test-journal.c
new file mode 100644
index 0000000000..f4dc52cd81
--- /dev/null
+++ b/src/journal/test-journal.c
@@ -0,0 +1,129 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <fcntl.h>
+#include <unistd.h>
+
+#include <systemd/sd-journal.h>
+
+#include "log.h"
+#include "journal-file.h"
+#include "journal-authenticate.h"
+#include "journal-vacuum.h"
+
+int main(int argc, char *argv[]) {
+ dual_timestamp ts;
+ JournalFile *f;
+ struct iovec iovec;
+ static const char test[] = "TEST1=1", test2[] = "TEST2=2";
+ Object *o;
+ uint64_t p;
+ char t[] = "/tmp/journal-XXXXXX";
+
+ log_set_max_level(LOG_DEBUG);
+
+ assert_se(mkdtemp(t));
+ assert_se(chdir(t) >= 0);
+
+ assert_se(journal_file_open("test.journal", O_RDWR|O_CREAT, 0666, true, true, NULL, NULL, NULL, &f) == 0);
+
+ dual_timestamp_get(&ts);
+
+ iovec.iov_base = (void*) test;
+ iovec.iov_len = strlen(test);
+ assert_se(journal_file_append_entry(f, &ts, &iovec, 1, NULL, NULL, NULL) == 0);
+
+ iovec.iov_base = (void*) test2;
+ iovec.iov_len = strlen(test2);
+ assert_se(journal_file_append_entry(f, &ts, &iovec, 1, NULL, NULL, NULL) == 0);
+
+ iovec.iov_base = (void*) test;
+ iovec.iov_len = strlen(test);
+ assert_se(journal_file_append_entry(f, &ts, &iovec, 1, NULL, NULL, NULL) == 0);
+
+#ifdef HAVE_GCRYPT
+ journal_file_append_tag(f);
+#endif
+ journal_file_dump(f);
+
+ assert(journal_file_next_entry(f, NULL, 0, DIRECTION_DOWN, &o, &p) == 1);
+ assert(le64toh(o->entry.seqnum) == 1);
+
+ assert(journal_file_next_entry(f, o, p, DIRECTION_DOWN, &o, &p) == 1);
+ assert(le64toh(o->entry.seqnum) == 2);
+
+ assert(journal_file_next_entry(f, o, p, DIRECTION_DOWN, &o, &p) == 1);
+ assert(le64toh(o->entry.seqnum) == 3);
+
+ assert(journal_file_next_entry(f, o, p, DIRECTION_DOWN, &o, &p) == 0);
+
+ assert(journal_file_next_entry(f, NULL, 0, DIRECTION_DOWN, &o, &p) == 1);
+ assert(le64toh(o->entry.seqnum) == 1);
+
+ assert(journal_file_skip_entry(f, o, p, 2, &o, &p) == 1);
+ assert(le64toh(o->entry.seqnum) == 3);
+
+ assert(journal_file_skip_entry(f, o, p, -2, &o, &p) == 1);
+ assert(le64toh(o->entry.seqnum) == 1);
+
+ assert(journal_file_skip_entry(f, o, p, -2, &o, &p) == 1);
+ assert(le64toh(o->entry.seqnum) == 1);
+
+ assert(journal_file_find_data_object(f, test, strlen(test), NULL, &p) == 1);
+ assert(journal_file_next_entry_for_data(f, NULL, 0, p, DIRECTION_DOWN, &o, NULL) == 1);
+ assert(le64toh(o->entry.seqnum) == 1);
+
+ assert(journal_file_next_entry_for_data(f, NULL, 0, p, DIRECTION_UP, &o, NULL) == 1);
+ assert(le64toh(o->entry.seqnum) == 3);
+
+ assert(journal_file_find_data_object(f, test2, strlen(test2), NULL, &p) == 1);
+ assert(journal_file_next_entry_for_data(f, NULL, 0, p, DIRECTION_UP, &o, NULL) == 1);
+ assert(le64toh(o->entry.seqnum) == 2);
+
+ assert(journal_file_next_entry_for_data(f, NULL, 0, p, DIRECTION_DOWN, &o, NULL) == 1);
+ assert(le64toh(o->entry.seqnum) == 2);
+
+ assert(journal_file_find_data_object(f, "quux", 4, NULL, &p) == 0);
+
+ assert(journal_file_move_to_entry_by_seqnum(f, 1, DIRECTION_DOWN, &o, NULL) == 1);
+ assert(le64toh(o->entry.seqnum) == 1);
+
+ assert(journal_file_move_to_entry_by_seqnum(f, 3, DIRECTION_DOWN, &o, NULL) == 1);
+ assert(le64toh(o->entry.seqnum) == 3);
+
+ assert(journal_file_move_to_entry_by_seqnum(f, 2, DIRECTION_DOWN, &o, NULL) == 1);
+ assert(le64toh(o->entry.seqnum) == 2);
+
+ assert(journal_file_move_to_entry_by_seqnum(f, 10, DIRECTION_DOWN, &o, NULL) == 0);
+
+ journal_file_rotate(&f, true, true);
+ journal_file_rotate(&f, true, true);
+
+ journal_file_close(f);
+
+ journal_directory_vacuum(".", 3000000, 0, 0, NULL);
+
+ log_error("Exiting...");
+
+ assert_se(rm_rf_dangerous(t, false, true, false) >= 0);
+
+ return 0;
+}
diff --git a/src/journal/test-mmap-cache.c b/src/journal/test-mmap-cache.c
new file mode 100644
index 0000000000..e2ffaf4723
--- /dev/null
+++ b/src/journal/test-mmap-cache.c
@@ -0,0 +1,79 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdlib.h>
+#include <sys/mman.h>
+#include <unistd.h>
+
+#include "log.h"
+#include "macro.h"
+#include "util.h"
+#include "mmap-cache.h"
+
+int main(int argc, char *argv[]) {
+ int x, y, z, r;
+ char px[] = "/tmp/testmmapXXXXXXX", py[] = "/tmp/testmmapYXXXXXX", pz[] = "/tmp/testmmapZXXXXXX";
+ MMapCache *m;
+ void *p, *q;
+
+ assert_se(m = mmap_cache_new());
+
+ x = mkstemp(px);
+ assert(x >= 0);
+ unlink(px);
+
+ y = mkstemp(py);
+ assert(y >= 0);
+ unlink(py);
+
+ z = mkstemp(pz);
+ assert(z >= 0);
+ unlink(pz);
+
+ r = mmap_cache_get(m, x, PROT_READ, 0, false, 1, 2, NULL, &p);
+ assert(r >= 0);
+
+ r = mmap_cache_get(m, x, PROT_READ, 0, false, 2, 2, NULL, &q);
+ assert(r >= 0);
+
+ assert((uint8_t*) p + 1 == (uint8_t*) q);
+
+ r = mmap_cache_get(m, x, PROT_READ, 1, false, 3, 2, NULL, &q);
+ assert(r >= 0);
+
+ assert((uint8_t*) p + 2 == (uint8_t*) q);
+
+ r = mmap_cache_get(m, x, PROT_READ, 0, false, 16ULL*1024ULL*1024ULL, 2, NULL, &p);
+ assert(r >= 0);
+
+ r = mmap_cache_get(m, x, PROT_READ, 1, false, 16ULL*1024ULL*1024ULL+1, 2, NULL, &q);
+ assert(r >= 0);
+
+ assert((uint8_t*) p + 1 == (uint8_t*) q);
+
+ mmap_cache_unref(m);
+
+ close_nointr_nofail(x);
+ close_nointr_nofail(y);
+ close_nointr_nofail(z);
+
+ return 0;
+}
diff --git a/src/kernel-install/50-depmod.install b/src/kernel-install/50-depmod.install
new file mode 100644
index 0000000000..68c24bed7a
--- /dev/null
+++ b/src/kernel-install/50-depmod.install
@@ -0,0 +1,8 @@
+#!/bin/bash
+# -*- mode: shell-script; indent-tabs-mode: nil; sh-basic-offset: 4; -*-
+# ex: ts=8 sw=4 sts=4 et filetype=sh
+
+[[ $1 == "add" ]] || exit 0
+[[ $2 ]] || exit 1
+
+exec depmod -a "$2"
diff --git a/src/kernel-install/90-loaderentry.install b/src/kernel-install/90-loaderentry.install
new file mode 100644
index 0000000000..55b4d24672
--- /dev/null
+++ b/src/kernel-install/90-loaderentry.install
@@ -0,0 +1,77 @@
+#!/bin/bash
+# -*- mode: shell-script; indent-tabs-mode: nil; sh-basic-offset: 4; -*-
+# ex: ts=8 sw=4 sts=4 et filetype=sh
+
+COMMAND="$1"
+KERNEL_VERSION="$2"
+BOOT_DIR_ABS="$3"
+KERNEL_IMAGE="$4"
+
+if [[ -f /etc/machine-id ]]; then
+ read MACHINE_ID < /etc/machine-id
+fi
+
+if ! [[ $MACHINE_ID ]]; then
+ exit 1
+fi
+
+BOOT_DIR="/$MACHINE_ID/$KERNEL_VERSION"
+LOADER_ENTRY="/boot/loader/entries/$MACHINE_ID-$KERNEL_VERSION.conf"
+
+if [[ $COMMAND == remove ]]; then
+ exec rm -f "$LOADER_ENTRY"
+fi
+
+if ! [[ $COMMAND == add ]]; then
+ exit 1
+fi
+
+if ! [[ $KERNEL_IMAGE ]]; then
+ exit 1
+fi
+
+if [[ -f /etc/os-release ]]; then
+ . /etc/os-release
+fi
+
+if ! [[ $PRETTY_NAME ]]; then
+ PRETTY_NAME="Linux $KERNEL_VERSION"
+fi
+
+if [[ -f /etc/kernel/cmdline ]]; then
+ readarray -t BOOT_OPTIONS < /etc/kernel/cmdline
+fi
+
+if ! [[ ${BOOT_OPTIONS[*]} ]]; then
+ readarray -t BOOT_OPTIONS < /proc/cmdline
+fi
+
+if ! [[ $BOOT_OPTIONS ]]; then
+ echo "Could not determine the kernel command line parameters." >&2
+ echo "Please specify the kernel command line in /etc/kernel/cmdline!" >&2
+ exit 1
+fi
+
+cp --preserve "$KERNEL_IMAGE" "$BOOT_DIR_ABS/linux" || {
+ echo "Could not copy '$KERNEL_IMAGE to '$BOOT_DIR_ABS/linux'." >&2
+ exit 1
+}
+
+mkdir -p "${LOADER_ENTRY%/*}" || {
+ echo "Could not create loader entry directory '${LOADER_ENTRY%/*}'." >&2
+ exit 1
+}
+
+{
+ echo "title $PRETTY_NAME"
+ echo "version $KERNEL_VERSION"
+ echo "machine-id $MACHINE_ID"
+ echo "options ${BOOT_OPTIONS[*]}"
+ echo "linux $BOOT_DIR/linux"
+ [[ -f $BOOT_DIR_ABS/initrd ]] && \
+ echo "initrd $BOOT_DIR/initrd"
+} > "$LOADER_ENTRY" || {
+ echo "Could not create loader entry '$LOADER_ENTRY'." >&2
+ exit 1
+}
+exit 0
diff --git a/src/kernel-install/kernel-install b/src/kernel-install/kernel-install
new file mode 100644
index 0000000000..fb2ee57b5b
--- /dev/null
+++ b/src/kernel-install/kernel-install
@@ -0,0 +1,123 @@
+#!/bin/bash
+# -*- mode: shell-script; indent-tabs-mode: nil; sh-basic-offset: 4; -*-
+# ex: ts=8 sw=4 sts=4 et filetype=sh
+#
+# This file is part of systemd.
+#
+# Copyright 2013 Harald Hoyer
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 of the License, or
+# (at your option) any later version.
+#
+# systemd is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with systemd; If not, see <http://www.gnu.org/licenses/>.
+
+usage()
+{
+ echo "Usage:" >&2
+ echo " $0 add <kernel-version> <kernel-image>" >&2
+ echo " $0 remove <kernel-version> <kernel-image>" >&2
+}
+
+dropindirs_sort()
+{
+ local suffix=$1; shift
+ local -a files
+ local f d i
+
+ readarray -t files < <(
+ for d in "$@"; do
+ for i in "$d/"*"$suffix"; do
+ if [[ -e "$i" ]]; then
+ echo "${i##*/}"
+ fi
+ done
+ done | sort -Vu
+ )
+
+ for f in "${files[@]}"; do
+ for d in "$@"; do
+ if [[ -e "$d/$f" ]]; then
+ echo "$d/$f"
+ continue 2
+ fi
+ done
+ done
+}
+
+export LC_COLLATE=C
+
+COMMAND="$1"
+KERNEL_VERSION="$2"
+KERNEL_IMAGE="$3"
+
+if [[ -f /etc/machine-id ]]; then
+ read MACHINE_ID < /etc/machine-id
+fi
+
+if ! [[ $MACHINE_ID ]]; then
+ echo "Could not determine your machine ID from /etc/machine-id." >&2
+ echo "Please run 'systemd-machine-id-setup' as root. See man:machine-id(5)" >&2
+ exit 1
+fi
+
+if [[ ! $COMMAND ]] || [[ ! $KERNEL_VERSION ]]; then
+ usage
+ exit 1
+fi
+
+BOOT_DIR_ABS="/boot/$MACHINE_ID/$KERNEL_VERSION"
+ret=0
+
+readarray -t PLUGINS < <(
+ dropindirs_sort ".install" \
+ "/etc/kernel/install.d" \
+ "/usr/lib/kernel/install.d"
+)
+
+case $COMMAND in
+ add)
+ if [[ ! $KERNEL_IMAGE ]]; then
+ usage
+ exit 1
+ fi
+
+ mkdir -p "$BOOT_DIR_ABS" || {
+ echo "Could not create boot directory '$BOOT_DIR_ABS'." >&2
+ exit 1
+ }
+
+ for f in "${PLUGINS[@]}"; do
+ if [[ -x $f ]]; then
+ "$f" add "$KERNEL_VERSION" "$BOOT_DIR_ABS" "$KERNEL_IMAGE"
+ ((ret+=$?))
+ fi
+ done
+ ;;
+
+ remove)
+ for f in "${PLUGINS[@]}"; do
+ if [[ -x $f ]]; then
+ "$f" remove "$KERNEL_VERSION" "$BOOT_DIR_ABS"
+ ((ret+=$?))
+ fi
+ done
+
+ rm -rf "$BOOT_DIR_ABS"
+ ((ret+=$?))
+ ;;
+
+ *)
+ usage
+ exit 1
+ ;;
+esac
+
+exit $ret
diff --git a/src/libsystemd-bus/bus-bloom.c b/src/libsystemd-bus/bus-bloom.c
new file mode 100644
index 0000000000..cb65e47b4c
--- /dev/null
+++ b/src/libsystemd-bus/bus-bloom.c
@@ -0,0 +1,93 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "util.h"
+#include "MurmurHash3.h"
+
+#include "bus-bloom.h"
+
+static inline void set_bit(uint64_t filter[], unsigned b) {
+ filter[b >> 6] |= 1ULL << (b & 63);
+}
+
+void bloom_add_data(uint64_t filter[BLOOM_SIZE/8], const void *data, size_t n) {
+ uint16_t hash[8];
+ unsigned k = 0;
+
+ /*
+ * Our bloom filter has the following parameters:
+ *
+ * m=512 (bits in the filter)
+ * k=8 (hash functions)
+ *
+ * We calculate a single 128bit MurmurHash value of which we
+ * use 8 parts of 9 bits as individual hash functions.
+ *
+ */
+
+ MurmurHash3_x64_128(data, n, 0, hash);
+
+ assert_cc(BLOOM_SIZE*8 == 512);
+
+ for (k = 0; k < ELEMENTSOF(hash); k++)
+ set_bit(filter, hash[k] & 511);
+}
+
+void bloom_add_pair(uint64_t filter[BLOOM_SIZE/8], const char *a, const char *b) {
+ size_t n;
+ char *c;
+
+ assert(filter);
+ assert(a);
+ assert(b);
+
+ n = strlen(a) + 1 + strlen(b);
+ c = alloca(n + 1);
+ strcpy(stpcpy(stpcpy(c, a), ":"), b);
+
+ bloom_add_data(filter, c, n);
+}
+
+void bloom_add_prefixes(uint64_t filter[BLOOM_SIZE/8], const char *a, const char *b, char sep) {
+ size_t n;
+ char *c, *p;
+
+ assert(filter);
+ assert(a);
+ assert(b);
+
+ n = strlen(a) + 1 + strlen(b);
+ c = alloca(n + 1);
+
+ p = stpcpy(stpcpy(c, a), ":");
+ strcpy(p, b);
+
+ for (;;) {
+ char *e;
+
+ e = strrchr(p, sep);
+ if (!e || e == p)
+ break;
+
+ *e = 0;
+ bloom_add_data(filter, c, e - c);
+ }
+}
diff --git a/src/libsystemd-bus/bus-bloom.h b/src/libsystemd-bus/bus-bloom.h
new file mode 100644
index 0000000000..1bf14a3331
--- /dev/null
+++ b/src/libsystemd-bus/bus-bloom.h
@@ -0,0 +1,30 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/types.h>
+
+#define BLOOM_SIZE 64
+
+void bloom_add_data(uint64_t filter[BLOOM_SIZE/8], const void *data, size_t n);
+void bloom_add_pair(uint64_t filter[BLOOM_SIZE/8], const char *a, const char *b);
+void bloom_add_prefixes(uint64_t filter[BLOOM_SIZE/8], const char *a, const char *b, char sep);
diff --git a/src/libsystemd-bus/bus-control.c b/src/libsystemd-bus/bus-control.c
new file mode 100644
index 0000000000..a4dc9bf511
--- /dev/null
+++ b/src/libsystemd-bus/bus-control.c
@@ -0,0 +1,378 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#ifdef HAVE_VALGRIND_MEMCHECK_H
+#include <valgrind/memcheck.h>
+#endif
+
+#include <stddef.h>
+#include <errno.h>
+
+#include "strv.h"
+
+#include "sd-bus.h"
+#include "bus-internal.h"
+#include "bus-message.h"
+#include "bus-control.h"
+
+int sd_bus_get_unique_name(sd_bus *bus, const char **unique) {
+ int r;
+
+ if (!bus)
+ return -EINVAL;
+ if (!unique)
+ return -EINVAL;
+
+ r = bus_ensure_running(bus);
+ if (r < 0)
+ return r;
+
+ *unique = bus->unique_name;
+ return 0;
+}
+
+int sd_bus_request_name(sd_bus *bus, const char *name, int flags) {
+ _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
+ uint32_t ret;
+ int r;
+
+ if (!bus)
+ return -EINVAL;
+ if (!name)
+ return -EINVAL;
+ if (!bus->bus_client)
+ return -EINVAL;
+
+ if (bus->is_kernel) {
+ struct kdbus_cmd_name *n;
+ size_t l;
+
+ l = strlen(name);
+ n = alloca0(offsetof(struct kdbus_cmd_name, name) + l + 1);
+ n->size = offsetof(struct kdbus_cmd_name, name) + l + 1;
+ n->name_flags = flags;
+ memcpy(n->name, name, l+1);
+
+#ifdef HAVE_VALGRIND_MEMCHECK_H
+ VALGRIND_MAKE_MEM_DEFINED(n, n->size);
+#endif
+
+ r = ioctl(bus->input_fd, KDBUS_CMD_NAME_ACQUIRE, n);
+ if (r < 0)
+ return -errno;
+
+ return n->name_flags;
+ } else {
+ r = sd_bus_call_method(
+ bus,
+ "org.freedesktop.DBus",
+ "/",
+ "org.freedesktop.DBus",
+ "RequestName",
+ NULL,
+ &reply,
+ "su",
+ name,
+ flags);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_read(reply, "u", &ret);
+ if (r < 0)
+ return r;
+
+ return ret;
+ }
+}
+
+int sd_bus_release_name(sd_bus *bus, const char *name) {
+ _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
+ uint32_t ret;
+ int r;
+
+ if (!bus)
+ return -EINVAL;
+ if (!name)
+ return -EINVAL;
+ if (!bus->bus_client)
+ return -EINVAL;
+
+ if (bus->is_kernel) {
+ struct kdbus_cmd_name *n;
+ size_t l;
+
+ l = strlen(name);
+ n = alloca0(offsetof(struct kdbus_cmd_name, name) + l + 1);
+ n->size = offsetof(struct kdbus_cmd_name, name) + l + 1;
+ memcpy(n->name, name, l+1);
+
+#ifdef HAVE_VALGRIND_MEMCHECK_H
+ VALGRIND_MAKE_MEM_DEFINED(n, n->size);
+#endif
+ r = ioctl(bus->input_fd, KDBUS_CMD_NAME_RELEASE, n);
+ if (r < 0)
+ return -errno;
+
+ return n->name_flags;
+ } else {
+ r = sd_bus_call_method(
+ bus,
+ "org.freedesktop.DBus",
+ "/",
+ "org.freedesktop.DBus",
+ "ReleaseName",
+ NULL,
+ &reply,
+ "s",
+ name);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_read(reply, "u", &ret);
+ if (r < 0)
+ return r;
+ }
+
+ return ret;
+}
+
+int sd_bus_list_names(sd_bus *bus, char ***l) {
+ _cleanup_bus_message_unref_ sd_bus_message *reply1 = NULL, *reply2 = NULL;
+ char **x = NULL;
+ int r;
+
+ if (!bus)
+ return -EINVAL;
+ if (!l)
+ return -EINVAL;
+
+ r = sd_bus_call_method(
+ bus,
+ "org.freedesktop.DBus",
+ "/",
+ "org.freedesktop.DBus",
+ "ListNames",
+ NULL,
+ &reply1,
+ NULL);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_call_method(
+ bus,
+ "org.freedesktop.DBus",
+ "/",
+ "org.freedesktop.DBus",
+ "ListActivatableNames",
+ NULL,
+ &reply2,
+ NULL);
+ if (r < 0)
+ return r;
+
+ r = bus_message_read_strv_extend(reply1, &x);
+ if (r < 0) {
+ strv_free(x);
+ return r;
+ }
+
+ r = bus_message_read_strv_extend(reply2, &x);
+ if (r < 0) {
+ strv_free(x);
+ return r;
+ }
+
+ *l = strv_uniq(x);
+ return 0;
+}
+
+int sd_bus_get_owner(sd_bus *bus, const char *name, char **owner) {
+ _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
+ const char *found;
+ int r;
+
+ if (!bus)
+ return -EINVAL;
+ if (!name)
+ return -EINVAL;
+
+ r = sd_bus_call_method(
+ bus,
+ "org.freedesktop.DBus",
+ "/",
+ "org.freedesktop.DBus",
+ "GetNameOwner",
+ NULL,
+ &reply,
+ "s",
+ name);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_read(reply, "s", &found);
+ if (r < 0)
+ return r;
+
+ if (owner) {
+ char *t;
+
+ t = strdup(found);
+ if (!t)
+ return -ENOMEM;
+
+ *owner = t;
+ }
+
+ return 0;
+}
+
+int sd_bus_get_owner_uid(sd_bus *bus, const char *name, uid_t *uid) {
+ _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
+ uint32_t u;
+ int r;
+
+ if (!bus)
+ return -EINVAL;
+ if (!name)
+ return -EINVAL;
+ if (!uid)
+ return -EINVAL;
+
+ r = sd_bus_call_method(
+ bus,
+ "org.freedesktop.DBus",
+ "/",
+ "org.freedesktop.DBus",
+ "GetConnectionUnixUser",
+ NULL,
+ &reply,
+ "s",
+ name);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_read(reply, "u", &u);
+ if (r < 0)
+ return r;
+
+ *uid = (uid_t) u;
+ return 0;
+}
+
+int sd_bus_get_owner_pid(sd_bus *bus, const char *name, pid_t *pid) {
+ _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
+ uint32_t u;
+ int r;
+
+ if (!bus)
+ return -EINVAL;
+ if (!name)
+ return -EINVAL;
+ if (!pid)
+ return -EINVAL;
+
+ r = sd_bus_call_method(
+ bus,
+ "org.freedesktop.DBus",
+ "/",
+ "org.freedesktop.DBus",
+ "GetConnectionUnixProcessID",
+ NULL,
+ &reply,
+ "s",
+ name);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_read(reply, "u", &u);
+ if (r < 0)
+ return r;
+
+ if (u == 0)
+ return -EIO;
+
+ *pid = (uid_t) u;
+ return 0;
+}
+
+int bus_add_match_internal(sd_bus *bus, const char *match) {
+ assert(bus);
+ assert(match);
+
+ return sd_bus_call_method(
+ bus,
+ "org.freedesktop.DBus",
+ "/",
+ "org.freedesktop.DBus",
+ "AddMatch",
+ NULL,
+ NULL,
+ "s",
+ match);
+}
+
+int bus_remove_match_internal(sd_bus *bus, const char *match) {
+ assert(bus);
+ assert(match);
+
+ return sd_bus_call_method(
+ bus,
+ "org.freedesktop.DBus",
+ "/",
+ "org.freedesktop.DBus",
+ "RemoveMatch",
+ NULL,
+ NULL,
+ "s",
+ match);
+}
+
+int sd_bus_get_owner_machine_id(sd_bus *bus, const char *name, sd_id128_t *machine) {
+ _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
+ const char *mid;
+ int r;
+
+ if (!bus)
+ return -EINVAL;
+ if (!name)
+ return -EINVAL;
+
+ if (streq_ptr(name, bus->unique_name))
+ return sd_id128_get_machine(machine);
+
+ r = sd_bus_call_method(bus,
+ name,
+ "/",
+ "org.freedesktop.DBus.Peer",
+ "GetMachineId",
+ NULL,
+ &reply,
+ NULL);
+
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_read(reply, "s", &mid);
+ if (r < 0)
+ return r;
+
+ return sd_id128_from_string(mid, machine);
+}
diff --git a/src/libsystemd-bus/bus-control.h b/src/libsystemd-bus/bus-control.h
new file mode 100644
index 0000000000..34ecb260c3
--- /dev/null
+++ b/src/libsystemd-bus/bus-control.h
@@ -0,0 +1,27 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "sd-bus.h"
+
+int bus_add_match_internal(sd_bus *bus, const char *match);
+int bus_remove_match_internal(sd_bus *bus, const char *match);
diff --git a/src/libsystemd-bus/bus-error.c b/src/libsystemd-bus/bus-error.c
new file mode 100644
index 0000000000..5faa17384e
--- /dev/null
+++ b/src/libsystemd-bus/bus-error.c
@@ -0,0 +1,177 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <stdbool.h>
+#include <string.h>
+#include <stdio.h>
+
+#include "util.h"
+
+#include "sd-bus.h"
+#include "bus-error.h"
+
+bool bus_error_is_dirty(sd_bus_error *e) {
+ if (!e)
+ return 0;
+
+ return e->name || e->message || e->need_free;
+}
+
+void sd_bus_error_free(sd_bus_error *e) {
+ if (!e)
+ return;
+
+ if (e->need_free) {
+ free((void*) e->name);
+ free((void*) e->message);
+ }
+
+ e->name = e->message = NULL;
+ e->need_free = false;
+}
+
+int sd_bus_error_set(sd_bus_error *e, const char *name, const char *format, ...) {
+ char *n, *m = NULL;
+ va_list ap;
+ int r;
+
+ if (!e)
+ return 0;
+ if (bus_error_is_dirty(e))
+ return -EINVAL;
+ if (!name)
+ return -EINVAL;
+
+ n = strdup(name);
+ if (!n)
+ return -ENOMEM;
+
+ if (format) {
+ va_start(ap, format);
+ r = vasprintf(&m, format, ap);
+ va_end(ap);
+
+ if (r < 0) {
+ free(n);
+ return -ENOMEM;
+ }
+ }
+
+ e->name = n;
+ e->message = m;
+ e->need_free = true;
+
+ return 0;
+}
+
+int sd_bus_error_copy(sd_bus_error *dest, const sd_bus_error *e) {
+ char *x, *y = NULL;
+
+ if (!dest)
+ return 0;
+ if (bus_error_is_dirty(dest))
+ return -EINVAL;
+ if (!sd_bus_error_is_set(e))
+ return 0;
+
+ x = strdup(e->name);
+ if (!x)
+ return -ENOMEM;
+
+ if (e->message) {
+ y = strdup(e->message);
+ if (!y) {
+ free(x);
+ return -ENOMEM;
+ }
+ }
+
+ dest->name = x;
+ dest->message = y;
+ dest->need_free = true;
+ return 0;
+}
+
+void sd_bus_error_set_const(sd_bus_error *e, const char *name, const char *message) {
+ if (!e)
+ return;
+ if (bus_error_is_dirty(e))
+ return;
+
+ e->name = name;
+ e->message = message;
+ e->need_free = false;
+}
+
+int sd_bus_error_is_set(const sd_bus_error *e) {
+ if (!e)
+ return 0;
+
+ return !!e->name;
+}
+
+int sd_bus_error_has_name(const sd_bus_error *e, const char *name) {
+ if (!e)
+ return 0;
+
+ return streq_ptr(e->name, name);
+}
+
+int bus_error_to_errno(const sd_bus_error* e) {
+
+ /* Better replce this with a gperf table */
+
+ if (!e->name)
+ return -EIO;
+
+ if (streq(e->name, "org.freedesktop.DBus.Error.NoMemory"))
+ return -ENOMEM;
+
+ if (streq(e->name, "org.freedesktop.DBus.Error.AuthFailed") ||
+ streq(e->name, "org.freedesktop.DBus.Error.AccessDenied"))
+ return -EPERM;
+
+ return -EIO;
+}
+
+int bus_error_from_errno(sd_bus_error *e, int error) {
+ if (!e)
+ return error;
+
+ if (error == -ENOMEM)
+ sd_bus_error_set_const(e, "org.freedesktop.DBus.Error.NoMemory", strerror(-error));
+ else if (error == -EPERM || error == -EACCES)
+ sd_bus_error_set_const(e, "org.freedesktop.DBus.Error.AccessDenied", strerror(-error));
+ else
+ sd_bus_error_set_const(e, "org.freedesktop.DBus.Error.Failed", "Operation failed");
+
+ return error;
+}
+
+const char *bus_error_message(const sd_bus_error *e, int error) {
+ if (e && e->message)
+ return e->message;
+
+ return strerror(error);
+}
diff --git a/src/libsystemd-bus/bus-error.h b/src/libsystemd-bus/bus-error.h
new file mode 100644
index 0000000000..ceca7d678f
--- /dev/null
+++ b/src/libsystemd-bus/bus-error.h
@@ -0,0 +1,31 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "sd-bus.h"
+
+int bus_error_to_errno(const sd_bus_error *e);
+int bus_error_from_errno(sd_bus_error *e, int error);
+
+bool bus_error_is_dirty(sd_bus_error *e);
+
+const char *bus_error_message(const sd_bus_error *e, int error);
diff --git a/src/libsystemd-bus/bus-internal.c b/src/libsystemd-bus/bus-internal.c
new file mode 100644
index 0000000000..0e66f3d355
--- /dev/null
+++ b/src/libsystemd-bus/bus-internal.c
@@ -0,0 +1,256 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "bus-internal.h"
+
+bool object_path_is_valid(const char *p) {
+ const char *q;
+ bool slash;
+
+ if (!p)
+ return false;
+
+ if (p[0] != '/')
+ return false;
+
+ if (p[1] == 0)
+ return true;
+
+ for (slash = true, q = p+1; *q; q++)
+ if (*q == '/') {
+ if (slash)
+ return false;
+
+ slash = true;
+ } else {
+ bool good;
+
+ good =
+ (*q >= 'a' && *q <= 'z') ||
+ (*q >= 'A' && *q <= 'Z') ||
+ (*q >= '0' && *q <= '9') ||
+ *q == '_';
+
+ if (!good)
+ return false;
+
+ slash = false;
+ }
+
+ if (slash)
+ return false;
+
+ return true;
+}
+
+bool interface_name_is_valid(const char *p) {
+ const char *q;
+ bool dot, found_dot;
+
+ if (isempty(p))
+ return false;
+
+ for (dot = true, q = p; *q; q++)
+ if (*q == '.') {
+ if (dot)
+ return false;
+
+ found_dot = dot = true;
+ } else {
+ bool good;
+
+ good =
+ (*q >= 'a' && *q <= 'z') ||
+ (*q >= 'A' && *q <= 'Z') ||
+ (!dot && *q >= '0' && *q <= '9') ||
+ *q == '_';
+
+ if (!good)
+ return false;
+
+ dot = false;
+ }
+
+ if (q - p > 255)
+ return false;
+
+ if (dot)
+ return false;
+
+ if (!found_dot)
+ return false;
+
+ return true;
+}
+
+bool service_name_is_valid(const char *p) {
+ const char *q;
+ bool dot, found_dot, unique;
+
+ if (isempty(p))
+ return false;
+
+ unique = p[0] == ':';
+
+ for (dot = true, q = unique ? p+1 : p; *q; q++)
+ if (*q == '.') {
+ if (dot)
+ return false;
+
+ found_dot = dot = true;
+ } else {
+ bool good;
+
+ good =
+ (*q >= 'a' && *q <= 'z') ||
+ (*q >= 'A' && *q <= 'Z') ||
+ ((!dot || unique) && *q >= '0' && *q <= '9') ||
+ *q == '_' || *q == '-';
+
+ if (!good)
+ return false;
+
+ dot = false;
+ }
+
+ if (q - p > 255)
+ return false;
+
+ if (dot)
+ return false;
+
+ if (!found_dot)
+ return false;
+
+ return true;
+}
+
+bool member_name_is_valid(const char *p) {
+ const char *q;
+
+ if (isempty(p))
+ return false;
+
+ for (q = p; *q; q++) {
+ bool good;
+
+ good =
+ (*q >= 'a' && *q <= 'z') ||
+ (*q >= 'A' && *q <= 'Z') ||
+ (*q >= '0' && *q <= '9') ||
+ *q == '_';
+
+ if (!good)
+ return false;
+ }
+
+ if (q - p > 255)
+ return false;
+
+ return true;
+}
+
+static bool complex_pattern_check(char c, const char *a, const char *b) {
+ bool separator = false;
+
+ if (!a && !b)
+ return true;
+
+ if (!a || !b)
+ return false;
+
+ for (;;) {
+ if (*a != *b)
+ return (separator && (*a == 0 || *b == 0)) ||
+ (*a == 0 && *b == c && b[1] == 0) ||
+ (*b == 0 && *a == c && a[1] == 0);
+
+ if (*a == 0)
+ return true;
+
+ separator = *a == c;
+
+ a++, b++;
+ }
+}
+
+bool namespace_complex_pattern(const char *pattern, const char *value) {
+ return complex_pattern_check('.', pattern, value);
+}
+
+bool path_complex_pattern(const char *pattern, const char *value) {
+ return complex_pattern_check('/', pattern, value);
+}
+
+static bool simple_pattern_check(char c, const char *a, const char *b) {
+
+ if (!a && !b)
+ return true;
+
+ if (!a || !b)
+ return false;
+
+ for (;;) {
+ if (*a != *b)
+ return *a == 0 && *b == c;
+
+ if (*a == 0)
+ return true;
+
+ a++, b++;
+ }
+}
+
+bool namespace_simple_pattern(const char *pattern, const char *value) {
+ return simple_pattern_check('.', pattern, value);
+}
+
+bool path_simple_pattern(const char *pattern, const char *value) {
+ return simple_pattern_check('/', pattern, value);
+}
+
+int bus_message_type_from_string(const char *s, uint8_t *u) {
+ if (streq(s, "signal"))
+ *u = SD_BUS_MESSAGE_TYPE_SIGNAL;
+ else if (streq(s, "method_call"))
+ *u = SD_BUS_MESSAGE_TYPE_METHOD_CALL;
+ else if (streq(s, "error"))
+ *u = SD_BUS_MESSAGE_TYPE_METHOD_ERROR;
+ else if (streq(s, "method_return"))
+ *u = SD_BUS_MESSAGE_TYPE_METHOD_RETURN;
+ else
+ return -EINVAL;
+
+ return 0;
+}
+
+const char *bus_message_type_to_string(uint8_t u) {
+ if (u == SD_BUS_MESSAGE_TYPE_SIGNAL)
+ return "signal";
+ else if (u == SD_BUS_MESSAGE_TYPE_METHOD_CALL)
+ return "method_call";
+ else if (u == SD_BUS_MESSAGE_TYPE_METHOD_ERROR)
+ return "error";
+ else if (u == SD_BUS_MESSAGE_TYPE_METHOD_RETURN)
+ return "method_return";
+ else
+ return NULL;
+}
diff --git a/src/libsystemd-bus/bus-internal.h b/src/libsystemd-bus/bus-internal.h
new file mode 100644
index 0000000000..4babfac86d
--- /dev/null
+++ b/src/libsystemd-bus/bus-internal.h
@@ -0,0 +1,198 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <netinet/in.h>
+
+#include "hashmap.h"
+#include "prioq.h"
+#include "list.h"
+#include "util.h"
+
+#include "sd-bus.h"
+#include "bus-error.h"
+#include "bus-match.h"
+
+struct reply_callback {
+ sd_bus_message_handler_t callback;
+ void *userdata;
+ usec_t timeout;
+ uint64_t serial;
+ unsigned prioq_idx;
+};
+
+struct filter_callback {
+ sd_bus_message_handler_t callback;
+ void *userdata;
+
+ unsigned last_iteration;
+
+ LIST_FIELDS(struct filter_callback, callbacks);
+};
+
+struct object_callback {
+ sd_bus_message_handler_t callback;
+ void *userdata;
+
+ char *path;
+ bool is_fallback;
+
+ unsigned last_iteration;
+};
+
+enum bus_state {
+ BUS_UNSET,
+ BUS_OPENING,
+ BUS_AUTHENTICATING,
+ BUS_HELLO,
+ BUS_RUNNING
+};
+
+enum bus_auth {
+ _BUS_AUTH_INVALID,
+ BUS_AUTH_EXTERNAL,
+ BUS_AUTH_ANONYMOUS
+};
+
+struct sd_bus {
+ unsigned n_ref;
+ enum bus_state state;
+ int input_fd, output_fd;
+ int message_version;
+
+ bool is_kernel:1;
+ bool negotiate_fds:1;
+ bool can_fds:1;
+ bool bus_client:1;
+ bool ucred_valid:1;
+ bool is_server:1;
+ bool anonymous_auth:1;
+ bool prefer_readv:1;
+ bool prefer_writev:1;
+ bool processing:1;
+ bool match_callbacks_modified:1;
+ bool filter_callbacks_modified:1;
+ bool object_callbacks_modified:1;
+
+ void *rbuffer;
+ size_t rbuffer_size;
+
+ sd_bus_message **rqueue;
+ unsigned rqueue_size;
+
+ sd_bus_message **wqueue;
+ unsigned wqueue_size;
+ size_t windex;
+
+ uint64_t serial;
+
+ char *unique_name;
+
+ struct bus_match_node match_callbacks;
+ Prioq *reply_callbacks_prioq;
+ Hashmap *reply_callbacks;
+ LIST_HEAD(struct filter_callback, filter_callbacks);
+ Hashmap *object_callbacks;
+
+ union {
+ struct sockaddr sa;
+ struct sockaddr_un un;
+ struct sockaddr_in in;
+ struct sockaddr_in6 in6;
+ } sockaddr;
+ socklen_t sockaddr_size;
+
+ char *kernel;
+
+ sd_id128_t server_id;
+
+ char *address;
+ unsigned address_index;
+
+ int last_connect_error;
+
+ enum bus_auth auth;
+ size_t auth_rbegin;
+ struct iovec auth_iovec[3];
+ unsigned auth_index;
+ char *auth_buffer;
+ usec_t auth_timeout;
+
+ struct ucred ucred;
+ char label[NAME_MAX];
+
+ int *fds;
+ unsigned n_fds;
+
+ char *exec_path;
+ char **exec_argv;
+
+ uint64_t hello_serial;
+ unsigned iteration_counter;
+};
+
+static inline void bus_unrefp(sd_bus **b) {
+ sd_bus_unref(*b);
+}
+
+#define _cleanup_bus_unref_ __attribute__((cleanup(bus_unrefp)))
+#define _cleanup_bus_error_free_ __attribute__((cleanup(sd_bus_error_free)))
+
+#define BUS_DEFAULT_TIMEOUT ((usec_t) (25 * USEC_PER_SEC))
+
+#define BUS_WQUEUE_MAX 128
+#define BUS_RQUEUE_MAX 128
+
+#define BUS_MESSAGE_SIZE_MAX (64*1024*1024)
+#define BUS_AUTH_SIZE_MAX (64*1024)
+
+#define BUS_CONTAINER_DEPTH 128
+
+/* Defined by the specification as maximum size of an array in
+ * bytes */
+#define BUS_ARRAY_MAX_SIZE 67108864
+
+#define BUS_FDS_MAX 1024
+
+#define BUS_EXEC_ARGV_MAX 256
+
+bool object_path_is_valid(const char *p);
+bool interface_name_is_valid(const char *p);
+bool service_name_is_valid(const char *p);
+bool member_name_is_valid(const char *p);
+
+bool namespace_complex_pattern(const char *pattern, const char *value);
+bool path_complex_pattern(const char *pattern, const char *value);
+
+bool namespace_simple_pattern(const char *pattern, const char *value);
+bool path_simple_pattern(const char *pattern, const char *value);
+
+int bus_message_type_from_string(const char *s, uint8_t *u);
+const char *bus_message_type_to_string(uint8_t u);
+
+#define error_name_is_valid interface_name_is_valid
+
+int bus_ensure_running(sd_bus *bus);
+int bus_start_running(sd_bus *bus);
+int bus_next_address(sd_bus *bus);
diff --git a/src/libsystemd-bus/bus-kernel.c b/src/libsystemd-bus/bus-kernel.c
new file mode 100644
index 0000000000..0762b7836f
--- /dev/null
+++ b/src/libsystemd-bus/bus-kernel.c
@@ -0,0 +1,618 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#ifdef HAVE_VALGRIND_MEMCHECK_H
+#include <valgrind/memcheck.h>
+#endif
+
+#include <fcntl.h>
+#include <malloc.h>
+
+#include "util.h"
+
+#include "bus-internal.h"
+#include "bus-message.h"
+#include "bus-kernel.h"
+#include "bus-bloom.h"
+
+#define KDBUS_ITEM_NEXT(item) \
+ (typeof(item))(((uint8_t *)item) + ALIGN8((item)->size))
+
+#define KDBUS_ITEM_FOREACH(item, head) \
+ for (item = (head)->items; \
+ (uint8_t *)(item) < (uint8_t *)(head) + (head)->size; \
+ item = KDBUS_ITEM_NEXT(item))
+
+#define KDBUS_ITEM_HEADER_SIZE offsetof(struct kdbus_item, data)
+#define KDBUS_ITEM_SIZE(s) ALIGN8((s) + KDBUS_ITEM_HEADER_SIZE)
+
+static int parse_unique_name(const char *s, uint64_t *id) {
+ int r;
+
+ assert(s);
+ assert(id);
+
+ if (!startswith(s, ":1."))
+ return 0;
+
+ r = safe_atou64(s + 3, id);
+ if (r < 0)
+ return r;
+
+ return 1;
+}
+
+static void append_payload_vec(struct kdbus_item **d, const void *p, size_t sz) {
+ assert(d);
+ assert(p);
+ assert(sz > 0);
+
+ *d = ALIGN8_PTR(*d);
+
+ (*d)->size = offsetof(struct kdbus_item, vec) + sizeof(struct kdbus_vec);
+ (*d)->type = KDBUS_MSG_PAYLOAD_VEC;
+ (*d)->vec.address = (intptr_t) p;
+ (*d)->vec.size = sz;
+
+ *d = (struct kdbus_item *) ((uint8_t*) *d + (*d)->size);
+}
+
+static void append_destination(struct kdbus_item **d, const char *s, size_t length) {
+ assert(d);
+ assert(s);
+
+ *d = ALIGN8_PTR(*d);
+
+ (*d)->size = offsetof(struct kdbus_item, str) + length + 1;
+ (*d)->type = KDBUS_MSG_DST_NAME;
+ memcpy((*d)->str, s, length + 1);
+
+ *d = (struct kdbus_item *) ((uint8_t*) *d + (*d)->size);
+}
+
+static void* append_bloom(struct kdbus_item **d, size_t length) {
+ void *r;
+
+ assert(d);
+
+ *d = ALIGN8_PTR(*d);
+
+ (*d)->size = offsetof(struct kdbus_item, data) + length;
+ (*d)->type = KDBUS_MSG_BLOOM;
+ r = (*d)->data;
+
+ *d = (struct kdbus_item *) ((uint8_t*) *d + (*d)->size);
+
+ return r;
+}
+
+static void append_fds(struct kdbus_item **d, const int fds[], unsigned n_fds) {
+ assert(d);
+ assert(fds);
+ assert(n_fds > 0);
+
+ *d = ALIGN8_PTR(*d);
+ (*d)->size = offsetof(struct kdbus_item, fds) + sizeof(int) * n_fds;
+ (*d)->type = KDBUS_MSG_UNIX_FDS;
+ memcpy((*d)->fds, fds, sizeof(int) * n_fds);
+
+ *d = (struct kdbus_item *) ((uint8_t*) *d + (*d)->size);
+}
+
+static int bus_message_setup_bloom(sd_bus_message *m, void *bloom) {
+ unsigned i;
+ int r;
+
+ assert(m);
+ assert(bloom);
+
+ memset(bloom, 0, BLOOM_SIZE);
+
+ bloom_add_pair(bloom, "message-type", bus_message_type_to_string(m->header->type));
+
+ if (m->interface)
+ bloom_add_pair(bloom, "interface", m->interface);
+ if (m->member)
+ bloom_add_pair(bloom, "member", m->member);
+ if (m->path) {
+ bloom_add_pair(bloom, "path", m->path);
+ bloom_add_prefixes(bloom, "path-slash-prefix", m->path, '/');
+ }
+
+ r = sd_bus_message_rewind(m, true);
+ if (r < 0)
+ return r;
+
+ for (i = 0; i < 64; i++) {
+ char type;
+ const char *t;
+ char buf[sizeof("arg")-1 + 2 + sizeof("-slash-prefix")];
+ char *e;
+
+ r = sd_bus_message_peek_type(m, &type, NULL);
+ if (r < 0)
+ return r;
+
+ if (type != SD_BUS_TYPE_STRING &&
+ type != SD_BUS_TYPE_OBJECT_PATH &&
+ type != SD_BUS_TYPE_SIGNATURE)
+ break;
+
+ r = sd_bus_message_read_basic(m, type, &t);
+ if (r < 0)
+ return r;
+
+ e = stpcpy(buf, "arg");
+ if (i < 10)
+ *(e++) = '0' + i;
+ else {
+ *(e++) = '0' + (i / 10);
+ *(e++) = '0' + (i % 10);
+ }
+
+ *e = 0;
+ bloom_add_pair(bloom, buf, t);
+
+ strcpy(e, "-dot-prefix");
+ bloom_add_prefixes(bloom, buf, t, '.');
+ strcpy(e, "-slash-prefix");
+ bloom_add_prefixes(bloom, buf, t, '/');
+ }
+
+ return 0;
+}
+
+static int bus_message_setup_kmsg(sd_bus *b, sd_bus_message *m) {
+ struct kdbus_item *d;
+ bool well_known;
+ uint64_t unique;
+ size_t sz, dl;
+ int r;
+
+ assert(b);
+ assert(m);
+ assert(m->sealed);
+
+ if (m->kdbus)
+ return 0;
+
+ if (m->destination) {
+ r = parse_unique_name(m->destination, &unique);
+ if (r < 0)
+ return r;
+
+ well_known = r == 0;
+ } else
+ well_known = false;
+
+ sz = offsetof(struct kdbus_msg, items);
+
+ /* Add in fixed header, fields header and payload */
+ sz += 3 * ALIGN8(offsetof(struct kdbus_item, vec) + sizeof(struct kdbus_vec));
+
+ /* Add space for bloom filter */
+ sz += ALIGN8(offsetof(struct kdbus_item, data) + BLOOM_SIZE);
+
+ /* Add in well-known destination header */
+ if (well_known) {
+ dl = strlen(m->destination);
+ sz += ALIGN8(offsetof(struct kdbus_item, str) + dl + 1);
+ }
+
+ /* Add space for unix fds */
+ if (m->n_fds > 0)
+ sz += ALIGN8(offsetof(struct kdbus_item, fds) + sizeof(int)*m->n_fds);
+
+ m->kdbus = memalign(8, sz);
+ if (!m->kdbus)
+ return -ENOMEM;
+
+ memset(m->kdbus, 0, sz);
+
+ m->kdbus->flags =
+ ((m->header->flags & SD_BUS_MESSAGE_NO_REPLY_EXPECTED) ? 0 : KDBUS_MSG_FLAGS_EXPECT_REPLY) |
+ ((m->header->flags & SD_BUS_MESSAGE_NO_AUTO_START) ? KDBUS_MSG_FLAGS_NO_AUTO_START : 0);
+ m->kdbus->dst_id =
+ well_known ? 0 :
+ m->destination ? unique : KDBUS_DST_ID_BROADCAST;
+ m->kdbus->payload_type = KDBUS_PAYLOAD_DBUS1;
+ m->kdbus->cookie = m->header->serial;
+
+ m->kdbus->timeout_ns = m->timeout * NSEC_PER_USEC;
+
+ d = m->kdbus->items;
+
+ if (well_known)
+ append_destination(&d, m->destination, dl);
+
+ append_payload_vec(&d, m->header, sizeof(*m->header));
+
+ if (m->fields)
+ append_payload_vec(&d, m->fields, ALIGN8(m->header->fields_size));
+
+ if (m->body)
+ append_payload_vec(&d, m->body, m->header->body_size);
+
+ if (m->kdbus->dst_id == KDBUS_DST_ID_BROADCAST) {
+ void *p;
+
+ p = append_bloom(&d, BLOOM_SIZE);
+ r = bus_message_setup_bloom(m, p);
+ if (r < 0) {
+ free(m->kdbus);
+ m->kdbus = NULL;
+ return -r;
+ }
+ }
+
+ if (m->n_fds > 0)
+ append_fds(&d, m->fds, m->n_fds);
+
+ m->kdbus->size = (uint8_t*) d - (uint8_t*) m->kdbus;
+ assert(m->kdbus->size <= sz);
+
+ m->free_kdbus = true;
+
+ return 0;
+}
+
+int bus_kernel_take_fd(sd_bus *b) {
+ struct kdbus_cmd_hello hello = {
+ .conn_flags =
+ KDBUS_HELLO_ACCEPT_FD|
+ KDBUS_HELLO_ATTACH_COMM|
+ KDBUS_HELLO_ATTACH_EXE|
+ KDBUS_HELLO_ATTACH_CMDLINE|
+ KDBUS_HELLO_ATTACH_CGROUP|
+ KDBUS_HELLO_ATTACH_CAPS|
+ KDBUS_HELLO_ATTACH_SECLABEL|
+ KDBUS_HELLO_ATTACH_AUDIT
+ };
+ int r;
+
+ assert(b);
+
+ if (b->is_server)
+ return -EINVAL;
+
+ r = ioctl(b->input_fd, KDBUS_CMD_HELLO, &hello);
+ if (r < 0)
+ return -errno;
+
+ /* The higher 32bit of both flags fields are considered
+ * 'incompatible flags'. Refuse them all for now. */
+ if (hello.bus_flags > 0xFFFFFFFFULL ||
+ hello.conn_flags > 0xFFFFFFFFULL)
+ return -ENOTSUP;
+
+ if (hello.bloom_size != BLOOM_SIZE)
+ return -ENOTSUP;
+
+ if (asprintf(&b->unique_name, ":1.%llu", (unsigned long long) hello.id) < 0)
+ return -ENOMEM;
+
+ b->is_kernel = true;
+ b->bus_client = true;
+ b->can_fds = true;
+
+ r = bus_start_running(b);
+ if (r < 0)
+ return r;
+
+ return 1;
+}
+
+int bus_kernel_connect(sd_bus *b) {
+ assert(b);
+ assert(b->input_fd < 0);
+ assert(b->output_fd < 0);
+ assert(b->kernel);
+
+ if (b->is_server)
+ return -EINVAL;
+
+ b->input_fd = open(b->kernel, O_RDWR|O_NOCTTY|O_CLOEXEC);
+ if (b->input_fd < 0)
+ return -errno;
+
+ b->output_fd = b->input_fd;
+
+ return bus_kernel_take_fd(b);
+}
+
+int bus_kernel_write_message(sd_bus *bus, sd_bus_message *m) {
+ int r;
+
+ assert(bus);
+ assert(m);
+ assert(bus->state == BUS_RUNNING);
+
+ r = bus_message_setup_kmsg(bus, m);
+ if (r < 0)
+ return r;
+
+ r = ioctl(bus->output_fd, KDBUS_CMD_MSG_SEND, m->kdbus);
+ if (r < 0)
+ return errno == EAGAIN ? 0 : -errno;
+
+ return 1;
+}
+
+static void close_kdbus_msg(struct kdbus_msg *k) {
+ struct kdbus_item *d;
+
+ KDBUS_ITEM_FOREACH(d, k) {
+
+ if (d->type != KDBUS_MSG_UNIX_FDS)
+ continue;
+
+ close_many(d->fds, (d->size - offsetof(struct kdbus_item, fds)) / sizeof(int));
+ }
+}
+
+static int bus_kernel_make_message(sd_bus *bus, struct kdbus_msg *k, sd_bus_message **ret) {
+ sd_bus_message *m = NULL;
+ struct kdbus_item *d;
+ unsigned n_payload = 0, n_fds = 0;
+ _cleanup_free_ int *fds = NULL;
+ struct bus_header *h = NULL;
+ size_t total, n_bytes = 0, idx = 0;
+ const char *destination = NULL, *seclabel = NULL;
+ int r;
+
+ assert(bus);
+ assert(k);
+ assert(ret);
+
+ if (k->payload_type != KDBUS_PAYLOAD_DBUS1)
+ return 0;
+
+ KDBUS_ITEM_FOREACH(d, k) {
+ size_t l;
+
+ l = d->size - offsetof(struct kdbus_item, data);
+
+ if (d->type == KDBUS_MSG_PAYLOAD) {
+
+ if (!h) {
+ if (l < sizeof(struct bus_header))
+ return -EBADMSG;
+
+ h = (struct bus_header*) d->data;
+ }
+
+ n_payload++;
+ n_bytes += l;
+
+ } else if (d->type == KDBUS_MSG_UNIX_FDS) {
+ int *f;
+ unsigned j;
+
+ j = l / sizeof(int);
+ f = realloc(fds, sizeof(int) * (n_fds + j));
+ if (!f)
+ return -ENOMEM;
+
+ fds = f;
+ memcpy(fds + n_fds, d->fds, sizeof(int) * j);
+ n_fds += j;
+
+ } else if (d->type == KDBUS_MSG_DST_NAME)
+ destination = d->str;
+ else if (d->type == KDBUS_MSG_SRC_SECLABEL)
+ seclabel = d->str;
+ }
+
+ if (!h)
+ return -EBADMSG;
+
+ r = bus_header_size(h, &total);
+ if (r < 0)
+ return r;
+
+ if (n_bytes != total)
+ return -EBADMSG;
+
+ r = bus_message_from_header(h, sizeof(struct bus_header), fds, n_fds, NULL, seclabel, 0, &m);
+ if (r < 0)
+ return r;
+
+ KDBUS_ITEM_FOREACH(d, k) {
+ size_t l;
+
+ l = d->size - offsetof(struct kdbus_item, data);
+
+ if (d->type == KDBUS_MSG_PAYLOAD) {
+
+ if (idx == sizeof(struct bus_header) &&
+ l == ALIGN8(BUS_MESSAGE_FIELDS_SIZE(m)))
+ m->fields = d->data;
+ else if (idx == sizeof(struct bus_header) + ALIGN8(BUS_MESSAGE_FIELDS_SIZE(m)) &&
+ l == BUS_MESSAGE_BODY_SIZE(m))
+ m->body = d->data;
+ else if (!(idx == 0 && l == sizeof(struct bus_header))) {
+ sd_bus_message_unref(m);
+ return -EBADMSG;
+ }
+
+ idx += l;
+ } else if (d->type == KDBUS_MSG_SRC_CREDS) {
+ m->pid_starttime = d->creds.starttime / NSEC_PER_USEC;
+ m->uid = d->creds.uid;
+ m->gid = d->creds.gid;
+ m->pid = d->creds.pid;
+ m->tid = d->creds.tid;
+ m->uid_valid = m->gid_valid = true;
+ } else if (d->type == KDBUS_MSG_TIMESTAMP) {
+ m->realtime = d->timestamp.realtime_ns / NSEC_PER_USEC;
+ m->monotonic = d->timestamp.monotonic_ns / NSEC_PER_USEC;
+ } else if (d->type == KDBUS_MSG_SRC_PID_COMM)
+ m->comm = d->str;
+ else if (d->type == KDBUS_MSG_SRC_TID_COMM)
+ m->tid_comm = d->str;
+ else if (d->type == KDBUS_MSG_SRC_EXE)
+ m->exe = d->str;
+ else if (d->type == KDBUS_MSG_SRC_CMDLINE) {
+ m->cmdline = d->str;
+ m->cmdline_length = l;
+ } else if (d->type == KDBUS_MSG_SRC_CGROUP)
+ m->cgroup = d->str;
+ else if (d->type == KDBUS_MSG_SRC_AUDIT)
+ m->audit = &d->audit;
+ else if (d->type == KDBUS_MSG_SRC_CAPS) {
+ m->capability = d->data;
+ m->capability_size = l;
+ } else
+ log_debug("Got unknown field from kernel %llu", d->type);
+ }
+
+ r = bus_message_parse_fields(m);
+ if (r < 0) {
+ sd_bus_message_unref(m);
+ return r;
+ }
+
+ if (k->src_id == KDBUS_SRC_ID_KERNEL)
+ m->sender = "org.freedesktop.DBus";
+ else {
+ snprintf(m->sender_buffer, sizeof(m->sender_buffer), ":1.%llu", (unsigned long long) k->src_id);
+ m->sender = m->sender_buffer;
+ }
+
+ if (!m->destination) {
+ if (destination)
+ m->destination = destination;
+ else if (k->dst_id != KDBUS_DST_ID_WELL_KNOWN_NAME &&
+ k->dst_id != KDBUS_DST_ID_BROADCAST) {
+ snprintf(m->destination_buffer, sizeof(m->destination_buffer), ":1.%llu", (unsigned long long) k->dst_id);
+ m->destination = m->destination_buffer;
+ }
+ }
+
+ /* We take possession of the kmsg struct now */
+ m->kdbus = k;
+ m->free_kdbus = true;
+ m->free_fds = true;
+
+ fds = NULL;
+
+ *ret = m;
+ return 1;
+}
+
+int bus_kernel_read_message(sd_bus *bus, sd_bus_message **m) {
+ struct kdbus_msg *k;
+ size_t sz = 1024;
+ int r;
+
+ assert(bus);
+ assert(m);
+
+ for (;;) {
+ void *q;
+
+ q = memalign(8, sz);
+ if (!q)
+ return -errno;
+
+ free(bus->rbuffer);
+ k = bus->rbuffer = q;
+ k->size = sz;
+
+ /* Let's tell valgrind that there's really no need to
+ * initialize this fully. This should be removed again
+ * when valgrind learned the kdbus ioctls natively. */
+#ifdef HAVE_VALGRIND_MEMCHECK_H
+ VALGRIND_MAKE_MEM_DEFINED(k, sz);
+#endif
+
+ r = ioctl(bus->input_fd, KDBUS_CMD_MSG_RECV, bus->rbuffer);
+ if (r >= 0)
+ break;
+
+ if (errno == EAGAIN)
+ return 0;
+
+ if (errno != ENOBUFS)
+ return -errno;
+
+ sz *= 2;
+ }
+
+ r = bus_kernel_make_message(bus, k, m);
+ if (r > 0)
+ bus->rbuffer = NULL;
+ else
+ close_kdbus_msg(k);
+
+ return r < 0 ? r : 1;
+}
+
+int bus_kernel_create(const char *name, char **s) {
+ struct kdbus_cmd_bus_make *make;
+ struct kdbus_item *n, *cg;
+ size_t l;
+ int fd;
+ char *p;
+
+ assert(name);
+ assert(s);
+
+ fd = open("/dev/kdbus/control", O_RDWR|O_NOCTTY|O_CLOEXEC);
+ if (fd < 0)
+ return -errno;
+
+ l = strlen(name);
+ make = alloca0(offsetof(struct kdbus_cmd_bus_make, items) +
+ KDBUS_ITEM_HEADER_SIZE + sizeof(uint64_t) +
+ KDBUS_ITEM_HEADER_SIZE + DECIMAL_STR_MAX(uid_t) + 1 + l + 1);
+
+ cg = make->items;
+ cg->type = KDBUS_MAKE_CGROUP;
+ cg->data64[0] = 1;
+ cg->size = KDBUS_ITEM_HEADER_SIZE + sizeof(uint64_t);
+
+ n = KDBUS_ITEM_NEXT(cg);
+ n->type = KDBUS_MAKE_NAME;
+ sprintf(n->str, "%lu-%s", (unsigned long) getuid(), name);
+ n->size = KDBUS_ITEM_HEADER_SIZE + strlen(n->str) + 1;
+
+ make->size = offsetof(struct kdbus_cmd_bus_make, items) + cg->size + n->size;
+ make->flags = KDBUS_MAKE_ACCESS_WORLD | KDBUS_MAKE_POLICY_OPEN;
+ make->bus_flags = 0;
+ make->bloom_size = BLOOM_SIZE;
+ assert_cc(BLOOM_SIZE % 8 == 0);
+
+ p = strjoin("/dev/kdbus/", n->str, "/bus", NULL);
+ if (!p)
+ return -ENOMEM;
+
+ if (ioctl(fd, KDBUS_CMD_BUS_MAKE, make) < 0) {
+ close_nointr_nofail(fd);
+ free(p);
+ return -errno;
+ }
+
+ if (s)
+ *s = p;
+
+ return fd;
+}
diff --git a/src/libsystemd-bus/bus-kernel.h b/src/libsystemd-bus/bus-kernel.h
new file mode 100644
index 0000000000..ac746afe03
--- /dev/null
+++ b/src/libsystemd-bus/bus-kernel.h
@@ -0,0 +1,32 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "sd-bus.h"
+
+int bus_kernel_connect(sd_bus *b);
+int bus_kernel_take_fd(sd_bus *b);
+
+int bus_kernel_write_message(sd_bus *bus, sd_bus_message *m);
+int bus_kernel_read_message(sd_bus *bus, sd_bus_message **m);
+
+int bus_kernel_create(const char *name, char **s);
diff --git a/src/libsystemd-bus/bus-match.c b/src/libsystemd-bus/bus-match.c
new file mode 100644
index 0000000000..501a38df70
--- /dev/null
+++ b/src/libsystemd-bus/bus-match.c
@@ -0,0 +1,994 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "bus-internal.h"
+#include "bus-message.h"
+#include "bus-match.h"
+
+/* Example:
+ *
+ * A: type=signal,sender=foo,interface=bar
+ * B: type=signal,sender=quux,interface=fips
+ * C: type=signal,sender=quux,interface=waldo
+ * D: type=signal,member=test
+ * E: sender=miau
+ * F: type=signal
+ * G: type=signal
+ *
+ * results in this tree:
+ *
+ * BUS_MATCH_ROOT
+ * + BUS_MATCH_MESSAGE_TYPE
+ * | ` BUS_MATCH_VALUE: value == signal
+ * | + DBUS_MATCH_SENDER
+ * | | + BUS_MATCH_VALUE: value == foo
+ * | | | ` DBUS_MATCH_INTERFACE
+ * | | | ` BUS_MATCH_VALUE: value == bar
+ * | | | ` BUS_MATCH_LEAF: A
+ * | | ` BUS_MATCH_VALUE: value == quux
+ * | | ` DBUS_MATCH_INTERFACE
+ * | | | BUS_MATCH_VALUE: value == fips
+ * | | | ` BUS_MATCH_LEAF: B
+ * | | ` BUS_MATCH_VALUE: value == waldo
+ * | | ` BUS_MATCH_LEAF: C
+ * | + DBUS_MATCH_MEMBER
+ * | | ` BUS_MATCH_VALUE: value == test
+ * | | ` BUS_MATCH_LEAF: D
+ * | + BUS_MATCH_LEAF: F
+ * | ` BUS_MATCH_LEAF: G
+ * ` BUS_MATCH_SENDER
+ * ` BUS_MATCH_VALUE: value == miau
+ * ` BUS_MATCH_LEAF: E
+ */
+
+static inline bool BUS_MATCH_IS_COMPARE(enum bus_match_node_type t) {
+ return t >= BUS_MATCH_MESSAGE_TYPE && t <= BUS_MATCH_ARG_NAMESPACE_LAST;
+}
+
+static inline bool BUS_MATCH_CAN_HASH(enum bus_match_node_type t) {
+ return (t >= BUS_MATCH_MESSAGE_TYPE && t <= BUS_MATCH_PATH) ||
+ (t >= BUS_MATCH_ARG && t <= BUS_MATCH_ARG_LAST);
+}
+
+static void bus_match_node_free(struct bus_match_node *node) {
+ assert(node);
+ assert(node->parent);
+ assert(!node->child);
+ assert(node->type != BUS_MATCH_ROOT);
+ assert(node->type < _BUS_MATCH_NODE_TYPE_MAX);
+
+ if (node->parent->child) {
+ /* We are apparently linked into the parent's child
+ * list. Let's remove us from there. */
+ if (node->prev) {
+ assert(node->prev->next == node);
+ node->prev->next = node->next;
+ } else {
+ assert(node->parent->child == node);
+ node->parent->child = node->next;
+ }
+
+ if (node->next)
+ node->next->prev = node->prev;
+ }
+
+ if (node->type == BUS_MATCH_VALUE) {
+ /* We might be in the parent's hash table, so clean
+ * this up */
+
+ if (node->parent->type == BUS_MATCH_MESSAGE_TYPE)
+ hashmap_remove(node->parent->compare.children, UINT_TO_PTR(node->value.u8));
+ else if (BUS_MATCH_CAN_HASH(node->parent->type) && node->value.str)
+ hashmap_remove(node->parent->compare.children, node->value.str);
+
+ free(node->value.str);
+ }
+
+ if (BUS_MATCH_IS_COMPARE(node->type)) {
+ assert(hashmap_isempty(node->compare.children));
+ hashmap_free(node->compare.children);
+ }
+
+ free(node);
+}
+
+static bool bus_match_node_maybe_free(struct bus_match_node *node) {
+ assert(node);
+
+ if (node->child)
+ return false;
+
+ if (BUS_MATCH_IS_COMPARE(node->type) && !hashmap_isempty(node->compare.children))
+ return true;
+
+ bus_match_node_free(node);
+ return true;
+}
+
+static bool value_node_test(
+ struct bus_match_node *node,
+ enum bus_match_node_type parent_type,
+ uint8_t value_u8,
+ const char *value_str) {
+
+ assert(node);
+ assert(node->type == BUS_MATCH_VALUE);
+
+ /* Tests parameters against this value node, doing prefix
+ * magic and stuff. */
+
+ switch (parent_type) {
+
+ case BUS_MATCH_MESSAGE_TYPE:
+ return node->value.u8 == value_u8;
+
+ case BUS_MATCH_SENDER:
+ case BUS_MATCH_DESTINATION:
+ case BUS_MATCH_INTERFACE:
+ case BUS_MATCH_MEMBER:
+ case BUS_MATCH_PATH:
+ case BUS_MATCH_ARG ... BUS_MATCH_ARG_LAST:
+ return streq_ptr(node->value.str, value_str);
+
+ case BUS_MATCH_ARG_NAMESPACE ... BUS_MATCH_ARG_NAMESPACE_LAST:
+ return namespace_simple_pattern(node->value.str, value_str);
+
+ case BUS_MATCH_PATH_NAMESPACE:
+ return path_simple_pattern(node->value.str, value_str);
+
+ case BUS_MATCH_ARG_PATH ... BUS_MATCH_ARG_PATH_LAST:
+ return path_complex_pattern(node->value.str, value_str);
+
+ default:
+ assert_not_reached("Invalid node type");
+ }
+}
+
+static bool value_node_same(
+ struct bus_match_node *node,
+ enum bus_match_node_type parent_type,
+ uint8_t value_u8,
+ const char *value_str) {
+
+ /* Tests parameters against this value node, not doing prefix
+ * magic and stuff, i.e. this one actually compares the match
+ * itself.*/
+
+ assert(node);
+ assert(node->type == BUS_MATCH_VALUE);
+
+ switch (parent_type) {
+
+ case BUS_MATCH_MESSAGE_TYPE:
+ return node->value.u8 == value_u8;
+
+ case BUS_MATCH_SENDER:
+ case BUS_MATCH_DESTINATION:
+ case BUS_MATCH_INTERFACE:
+ case BUS_MATCH_MEMBER:
+ case BUS_MATCH_PATH:
+ case BUS_MATCH_ARG ... BUS_MATCH_ARG_LAST:
+ case BUS_MATCH_ARG_NAMESPACE ... BUS_MATCH_ARG_NAMESPACE_LAST:
+ case BUS_MATCH_PATH_NAMESPACE:
+ case BUS_MATCH_ARG_PATH ... BUS_MATCH_ARG_PATH_LAST:
+ return streq(node->value.str, value_str);
+
+ default:
+ assert_not_reached("Invalid node type");
+ }
+}
+
+int bus_match_run(
+ sd_bus *bus,
+ struct bus_match_node *node,
+ int ret,
+ sd_bus_message *m) {
+
+
+ const char *test_str = NULL;
+ uint8_t test_u8 = 0;
+ int r;
+
+ assert(m);
+
+ if (!node)
+ return 0;
+
+ if (bus && bus->match_callbacks_modified)
+ return 0;
+
+ /* Not these special semantics: when traversing the tree we
+ * usually let bus_match_run() when called for a node
+ * recursively invoke bus_match_run(). There's are two
+ * exceptions here though, which are BUS_NODE_ROOT (which
+ * cannot have a sibling), and BUS_NODE_VALUE (whose siblings
+ * are invoked anyway by its parent. */
+
+ switch (node->type) {
+
+ case BUS_MATCH_ROOT:
+
+ /* Run all children. Since we cannot have any siblings
+ * we won't call any. The children of the root node
+ * are compares or leaves, they will automatically
+ * call their siblings. */
+ return bus_match_run(bus, node->child, ret, m);
+
+ case BUS_MATCH_VALUE:
+
+ /* Run all children. We don't execute any siblings, we
+ * assume our caller does that. The children of value
+ * nodes are compares or leaves, they will
+ * automatically call their siblings */
+
+ assert(node->child);
+ return bus_match_run(bus, node->child, ret, m);
+
+ case BUS_MATCH_LEAF:
+
+ if (bus) {
+ if (node->leaf.last_iteration == bus->iteration_counter)
+ return 0;
+
+ node->leaf.last_iteration = bus->iteration_counter;
+ }
+
+ r = sd_bus_message_rewind(m, true);
+ if (r < 0)
+ return r;
+
+ /* Run the callback. And then invoke siblings. */
+ assert(node->leaf.callback);
+ r = node->leaf.callback(bus, ret, m, node->leaf.userdata);
+ if (r != 0)
+ return r;
+
+ return bus_match_run(bus, node->next, ret, m);
+
+ case BUS_MATCH_MESSAGE_TYPE:
+ test_u8 = m->header->type;
+ break;
+
+ case BUS_MATCH_SENDER:
+ test_str = m->sender;
+ /* FIXME: resolve test_str from a well-known to a unique name first */
+ break;
+
+ case BUS_MATCH_DESTINATION:
+ test_str = m->destination;
+ break;
+
+ case BUS_MATCH_INTERFACE:
+ test_str = m->interface;
+ break;
+
+ case BUS_MATCH_MEMBER:
+ test_str = m->member;
+ break;
+
+ case BUS_MATCH_PATH:
+ case BUS_MATCH_PATH_NAMESPACE:
+ test_str = m->path;
+ break;
+
+ case BUS_MATCH_ARG ... BUS_MATCH_ARG_LAST:
+ test_str = bus_message_get_arg(m, node->type - BUS_MATCH_ARG);
+ break;
+
+ case BUS_MATCH_ARG_PATH ... BUS_MATCH_ARG_PATH_LAST:
+ test_str = bus_message_get_arg(m, node->type - BUS_MATCH_ARG_PATH);
+ break;
+
+ case BUS_MATCH_ARG_NAMESPACE ... BUS_MATCH_ARG_NAMESPACE_LAST:
+ test_str = bus_message_get_arg(m, node->type - BUS_MATCH_ARG_NAMESPACE);
+ break;
+
+ default:
+ assert_not_reached("Unknown match type.");
+ }
+
+ if (BUS_MATCH_CAN_HASH(node->type)) {
+ struct bus_match_node *found;
+
+ /* Lookup via hash table, nice! So let's jump directly. */
+
+ if (test_str)
+ found = hashmap_get(node->compare.children, test_str);
+ else if (node->type == BUS_MATCH_MESSAGE_TYPE)
+ found = hashmap_get(node->compare.children, UINT_TO_PTR(test_u8));
+ else
+ found = NULL;
+
+ if (found) {
+ r = bus_match_run(bus, found, ret, m);
+ if (r != 0)
+ return r;
+ }
+ } else {
+ struct bus_match_node *c;
+
+ /* No hash table, so let's iterate manually... */
+
+ for (c = node->child; c; c = c->next) {
+ if (!value_node_test(c, node->type, test_u8, test_str))
+ continue;
+
+ r = bus_match_run(bus, c, ret, m);
+ if (r != 0)
+ return r;
+ }
+ }
+
+ if (bus && bus->match_callbacks_modified)
+ return 0;
+
+ /* And now, let's invoke our siblings */
+ return bus_match_run(bus, node->next, ret, m);
+}
+
+static int bus_match_add_compare_value(
+ struct bus_match_node *where,
+ enum bus_match_node_type t,
+ uint8_t value_u8,
+ const char *value_str,
+ struct bus_match_node **ret) {
+
+ struct bus_match_node *c = NULL, *n = NULL;
+ int r;
+
+ assert(where);
+ assert(where->type == BUS_MATCH_ROOT || where->type == BUS_MATCH_VALUE);
+ assert(BUS_MATCH_IS_COMPARE(t));
+ assert(ret);
+
+ for (c = where->child; c && c->type != t; c = c->next)
+ ;
+
+ if (c) {
+ /* Comparison node already exists? Then let's see if
+ * the value node exists too. */
+
+ if (t == BUS_MATCH_MESSAGE_TYPE)
+ n = hashmap_get(c->compare.children, UINT_TO_PTR(value_u8));
+ else if (BUS_MATCH_CAN_HASH(t))
+ n = hashmap_get(c->compare.children, value_str);
+ else {
+ for (n = c->child; n && !value_node_same(n, t, value_u8, value_str); n = n->next)
+ ;
+ }
+
+ if (n) {
+ *ret = n;
+ return 0;
+ }
+ } else {
+ /* Comparison node, doesn't exist yet? Then let's
+ * create it. */
+
+ c = new0(struct bus_match_node, 1);
+ if (!c) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ c->type = t;
+ c->parent = where;
+ c->next = where->child;
+ if (c->next)
+ c->next->prev = c;
+ where->child = c;
+
+ if (t == BUS_MATCH_MESSAGE_TYPE) {
+ c->compare.children = hashmap_new(trivial_hash_func, trivial_compare_func);
+ if (!c->compare.children) {
+ r = -ENOMEM;
+ goto fail;
+ }
+ } else if (BUS_MATCH_CAN_HASH(t)) {
+ c->compare.children = hashmap_new(string_hash_func, string_compare_func);
+ if (!c->compare.children) {
+ r = -ENOMEM;
+ goto fail;
+ }
+ }
+ }
+
+ n = new0(struct bus_match_node, 1);
+ if (!n) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ n->type = BUS_MATCH_VALUE;
+ n->value.u8 = value_u8;
+ if (value_str) {
+ n->value.str = strdup(value_str);
+ if (!n->value.str) {
+ r = -ENOMEM;
+ goto fail;
+ }
+ }
+
+ n->parent = c;
+ if (c->compare.children) {
+
+ if (t == BUS_MATCH_MESSAGE_TYPE)
+ r = hashmap_put(c->compare.children, UINT_TO_PTR(value_u8), n);
+ else
+ r = hashmap_put(c->compare.children, n->value.str, n);
+
+ if (r < 0)
+ goto fail;
+ } else {
+ n->next = c->child;
+ if (n->next)
+ n->next->prev = n;
+ c->child = n;
+ }
+
+ *ret = n;
+ return 1;
+
+fail:
+ if (c)
+ bus_match_node_maybe_free(c);
+
+ if (n) {
+ free(n->value.str);
+ free(n);
+ }
+
+ return r;
+}
+
+static int bus_match_find_compare_value(
+ struct bus_match_node *where,
+ enum bus_match_node_type t,
+ uint8_t value_u8,
+ const char *value_str,
+ struct bus_match_node **ret) {
+
+ struct bus_match_node *c, *n;
+
+ assert(where);
+ assert(where->type == BUS_MATCH_ROOT || where->type == BUS_MATCH_VALUE);
+ assert(BUS_MATCH_IS_COMPARE(t));
+ assert(ret);
+
+ for (c = where->child; c && c->type != t; c = c->next)
+ ;
+
+ if (!c)
+ return 0;
+
+ if (t == BUS_MATCH_MESSAGE_TYPE)
+ n = hashmap_get(c->compare.children, UINT_TO_PTR(value_u8));
+ else if (BUS_MATCH_CAN_HASH(t))
+ n = hashmap_get(c->compare.children, value_str);
+ else {
+ for (n = c->child; !value_node_same(n, t, value_u8, value_str); n = n->next)
+ ;
+ }
+
+ if (n) {
+ *ret = n;
+ return 1;
+ }
+
+ return 0;
+}
+
+static int bus_match_add_leaf(
+ struct bus_match_node *where,
+ sd_bus_message_handler_t callback,
+ void *userdata,
+ struct bus_match_node **ret) {
+
+ struct bus_match_node *n;
+
+ assert(where);
+ assert(where->type == BUS_MATCH_ROOT || where->type == BUS_MATCH_VALUE);
+ assert(ret);
+
+ n = new0(struct bus_match_node, 1);
+ if (!n)
+ return -ENOMEM;
+
+ n->type = BUS_MATCH_LEAF;
+ n->parent = where;
+ n->next = where->child;
+ if (n->next)
+ n->next->prev = n;
+ n->leaf.callback = callback;
+ n->leaf.userdata = userdata;
+
+ where->child = n;
+
+ *ret = n;
+ return 1;
+}
+
+static int bus_match_find_leaf(
+ struct bus_match_node *where,
+ sd_bus_message_handler_t callback,
+ void *userdata,
+ struct bus_match_node **ret) {
+
+ struct bus_match_node *c;
+
+ assert(where);
+ assert(where->type == BUS_MATCH_ROOT || where->type == BUS_MATCH_VALUE);
+ assert(ret);
+
+ for (c = where->child; c; c = c->next) {
+ if (c->type == BUS_MATCH_LEAF &&
+ c->leaf.callback == callback &&
+ c->leaf.userdata == userdata) {
+ *ret = c;
+ return 1;
+ }
+ }
+
+ return 0;
+}
+
+enum bus_match_node_type bus_match_node_type_from_string(const char *k, size_t n) {
+ assert(k);
+
+ if (n == 4 && memcmp(k, "type", 4) == 0)
+ return BUS_MATCH_MESSAGE_TYPE;
+ if (n == 6 && memcmp(k, "sender", 6) == 0)
+ return BUS_MATCH_SENDER;
+ if (n == 11 && memcmp(k, "destination", 11) == 0)
+ return BUS_MATCH_DESTINATION;
+ if (n == 9 && memcmp(k, "interface", 9) == 0)
+ return BUS_MATCH_INTERFACE;
+ if (n == 6 && memcmp(k, "member", 6) == 0)
+ return BUS_MATCH_MEMBER;
+ if (n == 4 && memcmp(k, "path", 4) == 0)
+ return BUS_MATCH_PATH;
+ if (n == 14 && memcmp(k, "path_namespace", 14) == 0)
+ return BUS_MATCH_PATH_NAMESPACE;
+
+ if (n == 4 && memcmp(k, "arg", 3) == 0) {
+ int j;
+
+ j = undecchar(k[3]);
+ if (j < 0)
+ return -EINVAL;
+
+ return BUS_MATCH_ARG + j;
+ }
+
+ if (n == 5 && memcmp(k, "arg", 3) == 0) {
+ int a, b;
+ enum bus_match_node_type t;
+
+ a = undecchar(k[3]);
+ b = undecchar(k[4]);
+ if (a <= 0 || b < 0)
+ return -EINVAL;
+
+ t = BUS_MATCH_ARG + a * 10 + b;
+ if (t > BUS_MATCH_ARG_LAST)
+ return -EINVAL;
+
+ return t;
+ }
+
+ if (n == 8 && memcmp(k, "arg", 3) == 0 && memcmp(k + 4, "path", 4) == 0) {
+ int j;
+
+ j = undecchar(k[3]);
+ if (j < 0)
+ return -EINVAL;
+
+ return BUS_MATCH_ARG_PATH + j;
+ }
+
+ if (n == 9 && memcmp(k, "arg", 3) == 0 && memcmp(k + 5, "path", 4) == 0) {
+ enum bus_match_node_type t;
+ int a, b;
+
+ a = undecchar(k[3]);
+ b = undecchar(k[4]);
+ if (a <= 0 || b < 0)
+ return -EINVAL;
+
+ t = BUS_MATCH_ARG_PATH + a * 10 + b;
+ if (t > BUS_MATCH_ARG_PATH_LAST)
+ return -EINVAL;
+
+ return t;
+ }
+
+ if (n == 13 && memcmp(k, "arg", 3) == 0 && memcmp(k + 4, "namespace", 9) == 0) {
+ int j;
+
+ j = undecchar(k[3]);
+ if (j < 0)
+ return -EINVAL;
+
+ return BUS_MATCH_ARG_NAMESPACE + j;
+ }
+
+ if (n == 14 && memcmp(k, "arg", 3) == 0 && memcmp(k + 5, "namespace", 9) == 0) {
+ enum bus_match_node_type t;
+ int a, b;
+
+ a = undecchar(k[3]);
+ b = undecchar(k[4]);
+ if (a <= 0 || b < 0)
+ return -EINVAL;
+
+ t = BUS_MATCH_ARG_NAMESPACE + a * 10 + b;
+ if (t > BUS_MATCH_ARG_NAMESPACE_LAST)
+ return -EINVAL;
+
+ return t;
+ }
+
+ return -EINVAL;
+}
+
+struct match_component {
+ enum bus_match_node_type type;
+ uint8_t value_u8;
+ char *value_str;
+};
+
+static int match_component_compare(const void *a, const void *b) {
+ const struct match_component *x = a, *y = b;
+
+ if (x->type < y->type)
+ return -1;
+ if (x->type > y->type)
+ return 1;
+
+ return 0;
+}
+
+static void free_components(struct match_component *components, unsigned n_components) {
+ unsigned i;
+
+ for (i = 0; i < n_components; i++)
+ free(components[i].value_str);
+
+ free(components);
+}
+
+static int parse_match(
+ const char *match,
+ struct match_component **_components,
+ unsigned *_n_components) {
+
+ const char *p = match;
+ struct match_component *components = NULL;
+ size_t components_allocated = 0;
+ unsigned n_components = 0, i;
+ _cleanup_free_ char *value = NULL;
+ int r;
+
+ assert(match);
+ assert(_components);
+ assert(_n_components);
+
+ while (*p != 0) {
+ const char *eq, *q;
+ enum bus_match_node_type t;
+ unsigned j = 0;
+ size_t value_allocated = 0;
+ bool escaped = false;
+ uint8_t u;
+
+ eq = strchr(p, '=');
+ if (!eq)
+ return -EINVAL;
+
+ if (eq[1] != '\'')
+ return -EINVAL;
+
+ t = bus_match_node_type_from_string(p, eq - p);
+ if (t < 0)
+ return -EINVAL;
+
+ for (q = eq + 2;; q++) {
+
+ if (*q == 0) {
+ r = -EINVAL;
+ goto fail;
+ }
+
+ if (!escaped) {
+ if (*q == '\\') {
+ escaped = true;
+ continue;
+ }
+ if (*q == '\'') {
+ if (value)
+ value[j] = 0;
+ break;
+ }
+ }
+
+ if (!GREEDY_REALLOC(value, value_allocated, j + 2)) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ value[j++] = *q;
+ escaped = false;
+ }
+
+ if (t == BUS_MATCH_MESSAGE_TYPE) {
+ r = bus_message_type_from_string(value, &u);
+ if (r < 0)
+ goto fail;
+
+ free(value);
+ value = NULL;
+ } else
+ u = 0;
+
+ if (!GREEDY_REALLOC(components, components_allocated, n_components + 1)) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ components[n_components].type = t;
+ components[n_components].value_str = value;
+ components[n_components].value_u8 = u;
+ n_components++;
+
+ value = NULL;
+
+ if (q[1] == 0)
+ break;
+
+ if (q[1] != ',') {
+ r = -EINVAL;
+ goto fail;
+ }
+
+ p = q + 2;
+ }
+
+ /* Order the whole thing, so that we always generate the same tree */
+ qsort(components, n_components, sizeof(struct match_component), match_component_compare);
+
+ /* Check for duplicates */
+ for (i = 0; i+1 < n_components; i++)
+ if (components[i].type == components[i+1].type) {
+ r = -EINVAL;
+ goto fail;
+ }
+
+ *_components = components;
+ *_n_components = n_components;
+
+ return 0;
+
+fail:
+ free_components(components, n_components);
+ return r;
+}
+
+int bus_match_add(
+ struct bus_match_node *root,
+ const char *match,
+ sd_bus_message_handler_t callback,
+ void *userdata,
+ struct bus_match_node **ret) {
+
+ struct match_component *components = NULL;
+ unsigned n_components = 0, i;
+ struct bus_match_node *n;
+ int r;
+
+ assert(root);
+ assert(match);
+ assert(callback);
+
+ r = parse_match(match, &components, &n_components);
+ if (r < 0)
+ return r;
+
+ n = root;
+ for (i = 0; i < n_components; i++) {
+ r = bus_match_add_compare_value(
+ n, components[i].type,
+ components[i].value_u8, components[i].value_str, &n);
+ if (r < 0)
+ goto finish;
+ }
+
+ r = bus_match_add_leaf(n, callback, userdata, &n);
+ if (r < 0)
+ goto finish;
+
+ if (ret)
+ *ret = n;
+
+finish:
+ free_components(components, n_components);
+ return r;
+}
+
+int bus_match_remove(
+ struct bus_match_node *root,
+ const char *match,
+ sd_bus_message_handler_t callback,
+ void *userdata) {
+
+ struct match_component *components = NULL;
+ unsigned n_components = 0, i;
+ struct bus_match_node *n, **gc;
+ int r;
+
+ assert(root);
+ assert(match);
+
+ r = parse_match(match, &components, &n_components);
+ if (r < 0)
+ return r;
+
+ gc = newa(struct bus_match_node*, n_components);
+
+ n = root;
+ for (i = 0; i < n_components; i++) {
+ r = bus_match_find_compare_value(
+ n, components[i].type,
+ components[i].value_u8, components[i].value_str,
+ &n);
+ if (r <= 0)
+ goto finish;
+
+ gc[i] = n;
+ }
+
+ r = bus_match_find_leaf(n, callback, userdata, &n);
+ if (r <= 0)
+ goto finish;
+
+ /* Free the leaf */
+ bus_match_node_free(n);
+
+ /* Prune the tree above */
+ for (i = n_components; i > 0; i --) {
+ struct bus_match_node *p = gc[i-1]->parent;
+
+ if (!bus_match_node_maybe_free(gc[i-1]))
+ break;
+
+ if (!bus_match_node_maybe_free(p))
+ break;
+ }
+
+finish:
+ free_components(components, n_components);
+ return r;
+}
+
+void bus_match_free(struct bus_match_node *node) {
+ struct bus_match_node *c;
+
+ if (!node)
+ return;
+
+ if (BUS_MATCH_CAN_HASH(node->type)) {
+ Iterator i;
+
+ HASHMAP_FOREACH(c, node->compare.children, i)
+ bus_match_free(c);
+
+ assert(hashmap_isempty(node->compare.children));
+ }
+
+ while ((c = node->child))
+ bus_match_free(c);
+
+ if (node->type != BUS_MATCH_ROOT)
+ bus_match_node_free(node);
+}
+
+const char* bus_match_node_type_to_string(enum bus_match_node_type t, char buf[], size_t l) {
+ switch (t) {
+
+ case BUS_MATCH_ROOT:
+ return "root";
+
+ case BUS_MATCH_VALUE:
+ return "value";
+
+ case BUS_MATCH_LEAF:
+ return "leaf";
+
+ case BUS_MATCH_MESSAGE_TYPE:
+ return "type";
+
+ case BUS_MATCH_SENDER:
+ return "sender";
+
+ case BUS_MATCH_DESTINATION:
+ return "destination";
+
+ case BUS_MATCH_INTERFACE:
+ return "interface";
+
+ case BUS_MATCH_MEMBER:
+ return "member";
+
+ case BUS_MATCH_PATH:
+ return "path";
+
+ case BUS_MATCH_PATH_NAMESPACE:
+ return "path_namespace";
+
+ case BUS_MATCH_ARG ... BUS_MATCH_ARG_LAST:
+ snprintf(buf, l, "arg%i", t - BUS_MATCH_ARG);
+ return buf;
+
+ case BUS_MATCH_ARG_PATH ... BUS_MATCH_ARG_PATH_LAST:
+ snprintf(buf, l, "arg%ipath", t - BUS_MATCH_ARG_PATH);
+ return buf;
+
+ case BUS_MATCH_ARG_NAMESPACE ... BUS_MATCH_ARG_NAMESPACE_LAST:
+ snprintf(buf, l, "arg%inamespace", t - BUS_MATCH_ARG_NAMESPACE);
+ return buf;
+
+ default:
+ return NULL;
+ }
+}
+
+void bus_match_dump(struct bus_match_node *node, unsigned level) {
+ struct bus_match_node *c;
+ _cleanup_free_ char *pfx = NULL;
+ char buf[32];
+
+ if (!node)
+ return;
+
+ pfx = strrep(" ", level);
+ printf("%s[%s]", strempty(pfx), bus_match_node_type_to_string(node->type, buf, sizeof(buf)));
+
+ if (node->type == BUS_MATCH_VALUE) {
+ if (node->parent->type == BUS_MATCH_MESSAGE_TYPE)
+ printf(" <%u>\n", node->value.u8);
+ else
+ printf(" <%s>\n", node->value.str);
+ } else if (node->type == BUS_MATCH_ROOT)
+ puts(" root");
+ else if (node->type == BUS_MATCH_LEAF)
+ printf(" %p/%p\n", node->leaf.callback, node->leaf.userdata);
+ else
+ putchar('\n');
+
+ if (BUS_MATCH_CAN_HASH(node->type)) {
+ Iterator i;
+
+ HASHMAP_FOREACH(c, node->compare.children, i)
+ bus_match_dump(c, level + 1);
+ }
+
+ for (c = node->child; c; c = c->next)
+ bus_match_dump(c, level + 1);
+}
diff --git a/src/libsystemd-bus/bus-match.h b/src/libsystemd-bus/bus-match.h
new file mode 100644
index 0000000000..075f1a9e3a
--- /dev/null
+++ b/src/libsystemd-bus/bus-match.h
@@ -0,0 +1,82 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "hashmap.h"
+
+#include "sd-bus.h"
+
+enum bus_match_node_type {
+ BUS_MATCH_ROOT,
+ BUS_MATCH_VALUE,
+ BUS_MATCH_LEAF,
+
+ /* The following are all different kinds of compare nodes */
+ BUS_MATCH_MESSAGE_TYPE,
+ BUS_MATCH_SENDER,
+ BUS_MATCH_DESTINATION,
+ BUS_MATCH_INTERFACE,
+ BUS_MATCH_MEMBER,
+ BUS_MATCH_PATH,
+ BUS_MATCH_PATH_NAMESPACE,
+ BUS_MATCH_ARG,
+ BUS_MATCH_ARG_LAST = BUS_MATCH_ARG + 63,
+ BUS_MATCH_ARG_PATH,
+ BUS_MATCH_ARG_PATH_LAST = BUS_MATCH_ARG_PATH + 63,
+ BUS_MATCH_ARG_NAMESPACE,
+ BUS_MATCH_ARG_NAMESPACE_LAST = BUS_MATCH_ARG_NAMESPACE + 63,
+ _BUS_MATCH_NODE_TYPE_MAX,
+ _BUS_MATCH_NODE_TYPE_INVALID = -1
+};
+
+struct bus_match_node {
+ enum bus_match_node_type type;
+ struct bus_match_node *parent, *next, *prev, *child;
+
+ union {
+ struct {
+ char *str;
+ uint8_t u8;
+ } value;
+ struct {
+ sd_bus_message_handler_t callback;
+ void *userdata;
+ unsigned last_iteration;
+ } leaf;
+ struct {
+ /* If this is set, then the child is NULL */
+ Hashmap *children;
+ } compare;
+ };
+};
+
+int bus_match_run(sd_bus *bus, struct bus_match_node *root, int ret, sd_bus_message *m);
+
+int bus_match_add(struct bus_match_node *root, const char *match, sd_bus_message_handler_t callback, void *userdata, struct bus_match_node **ret);
+int bus_match_remove(struct bus_match_node *root, const char *match, sd_bus_message_handler_t callback, void *userdata);
+
+void bus_match_free(struct bus_match_node *node);
+
+void bus_match_dump(struct bus_match_node *node, unsigned level);
+
+const char* bus_match_node_type_to_string(enum bus_match_node_type t, char buf[], size_t l);
+enum bus_match_node_type bus_match_node_type_from_string(const char *k, size_t n);
diff --git a/src/libsystemd-bus/bus-message.c b/src/libsystemd-bus/bus-message.c
new file mode 100644
index 0000000000..835a9f9a44
--- /dev/null
+++ b/src/libsystemd-bus/bus-message.c
@@ -0,0 +1,3494 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <fcntl.h>
+
+#include "util.h"
+#include "utf8.h"
+#include "strv.h"
+#include "time-util.h"
+#include "cgroup-util.h"
+
+#include "sd-bus.h"
+#include "bus-message.h"
+#include "bus-internal.h"
+#include "bus-type.h"
+#include "bus-signature.h"
+
+static int message_append_basic(sd_bus_message *m, char type, const void *p, const void **stored);
+
+static void reset_containers(sd_bus_message *m) {
+ unsigned i;
+
+ assert(m);
+
+ for (i = 0; i < m->n_containers; i++)
+ free(m->containers[i].signature);
+
+ free(m->containers);
+ m->containers = NULL;
+
+ m->n_containers = 0;
+ m->root_container.index = 0;
+}
+
+static void message_free(sd_bus_message *m) {
+ assert(m);
+
+ if (m->free_header)
+ free(m->header);
+
+ if (m->free_fields)
+ free(m->fields);
+
+ if (m->free_body)
+ free(m->body);
+
+ if (m->free_kdbus)
+ free(m->kdbus);
+
+ if (m->free_fds) {
+ close_many(m->fds, m->n_fds);
+ free(m->fds);
+ }
+
+ free(m->cmdline_array);
+
+ reset_containers(m);
+ free(m->root_container.signature);
+
+ free(m->peeked_signature);
+
+ free(m->unit);
+ free(m->user_unit);
+ free(m->session);
+ free(m);
+}
+
+static void* buffer_extend(void **p, uint32_t *sz, size_t align, size_t extend) {
+ size_t start, n;
+ void *k;
+
+ assert(p);
+ assert(sz);
+ assert(align > 0);
+
+ start = ALIGN_TO((size_t) *sz, align);
+ n = start + extend;
+
+ if (n == *sz)
+ return (uint8_t*) *p + start;
+
+ if (n > (size_t) ((uint32_t) -1))
+ return NULL;
+
+ k = realloc(*p, n);
+ if (!k)
+ return NULL;
+
+ /* Zero out padding */
+ if (start > *sz)
+ memset((uint8_t*) k + *sz, 0, start - *sz);
+
+ *p = k;
+ *sz = n;
+
+ return (uint8_t*) k + start;
+}
+
+static void *message_extend_fields(sd_bus_message *m, size_t align, size_t sz) {
+ void *p, *o;
+
+ assert(m);
+
+ o = m->fields;
+ p = buffer_extend(&m->fields, &m->header->fields_size, align, sz);
+ if (!p)
+ return NULL;
+
+ if (o != m->fields) {
+ /* Adjust quick access pointers */
+
+ if (m->path)
+ m->path = (const char*) m->fields + (m->path - (const char*) o);
+ if (m->interface)
+ m->interface = (const char*) m->fields + (m->interface - (const char*) o);
+ if (m->member)
+ m->member = (const char*) m->fields + (m->member - (const char*) o);
+ if (m->destination)
+ m->destination = (const char*) m->fields + (m->destination - (const char*) o);
+ if (m->sender)
+ m->sender = (const char*) m->fields + (m->sender - (const char*) o);
+ if (m->error.name)
+ m->error.name = (const char*) m->fields + (m->error.name - (const char*) o);
+ }
+
+ m->free_fields = true;
+
+ return p;
+}
+
+static int message_append_field_string(
+ sd_bus_message *m,
+ uint8_t h,
+ char type,
+ const char *s,
+ const char **ret) {
+
+ size_t l;
+ uint8_t *p;
+
+ assert(m);
+
+ l = strlen(s);
+ if (l > (size_t) (uint32_t) -1)
+ return -EINVAL;
+
+ /* field id byte + signature length + signature 's' + NUL + string length + string + NUL */
+ p = message_extend_fields(m, 8, 4 + 4 + l + 1);
+ if (!p)
+ return -ENOMEM;
+
+ p[0] = h;
+ p[1] = 1;
+ p[2] = type;
+ p[3] = 0;
+
+ ((uint32_t*) p)[1] = l;
+ memcpy(p + 8, s, l + 1);
+
+ if (ret)
+ *ret = (const char*) p + 8;
+
+ return 0;
+}
+
+static int message_append_field_signature(
+ sd_bus_message *m,
+ uint8_t h,
+ const char *s,
+ const char **ret) {
+
+ size_t l;
+ uint8_t *p;
+
+ assert(m);
+
+ l = strlen(s);
+ if (l > 255)
+ return -EINVAL;
+
+ /* field id byte + signature length + signature 'g' + NUL + string length + string + NUL */
+ p = message_extend_fields(m, 8, 4 + 1 + l + 1);
+ if (!p)
+ return -ENOMEM;
+
+ p[0] = h;
+ p[1] = 1;
+ p[2] = SD_BUS_TYPE_SIGNATURE;
+ p[3] = 0;
+ p[4] = l;
+ memcpy(p + 5, s, l + 1);
+
+ if (ret)
+ *ret = (const char*) p + 5;
+
+ return 0;
+}
+
+static int message_append_field_uint32(sd_bus_message *m, uint8_t h, uint32_t x) {
+ uint8_t *p;
+
+ assert(m);
+
+ /* field id byte + signature length + signature 'u' + NUL + value */
+ p = message_extend_fields(m, 8, 4 + 4);
+ if (!p)
+ return -ENOMEM;
+
+ p[0] = h;
+ p[1] = 1;
+ p[2] = SD_BUS_TYPE_UINT32;
+ p[3] = 0;
+
+ ((uint32_t*) p)[1] = x;
+
+ return 0;
+}
+
+int bus_message_from_header(
+ void *buffer,
+ size_t length,
+ int *fds,
+ unsigned n_fds,
+ const struct ucred *ucred,
+ const char *label,
+ size_t extra,
+ sd_bus_message **ret) {
+
+ sd_bus_message *m;
+ struct bus_header *h;
+ size_t a, label_sz;
+
+ assert(buffer || length <= 0);
+ assert(fds || n_fds <= 0);
+ assert(ret);
+
+ if (length < sizeof(struct bus_header))
+ return -EBADMSG;
+
+ h = buffer;
+ if (h->version != 1)
+ return -EBADMSG;
+
+ if (h->serial == 0)
+ return -EBADMSG;
+
+ if (h->type == _SD_BUS_MESSAGE_TYPE_INVALID)
+ return -EBADMSG;
+
+ if (h->endian != SD_BUS_LITTLE_ENDIAN &&
+ h->endian != SD_BUS_BIG_ENDIAN)
+ return -EBADMSG;
+
+ a = ALIGN(sizeof(sd_bus_message)) + ALIGN(extra);
+
+ if (label) {
+ label_sz = strlen(label);
+ a += label_sz + 1;
+ }
+
+ m = malloc0(a);
+ if (!m)
+ return -ENOMEM;
+
+ m->n_ref = 1;
+ m->sealed = true;
+ m->header = h;
+ m->fds = fds;
+ m->n_fds = n_fds;
+
+ if (ucred) {
+ m->uid = ucred->uid;
+ m->pid = ucred->pid;
+ m->gid = ucred->gid;
+ m->uid_valid = m->gid_valid = true;
+ }
+
+ if (label) {
+ m->label = (char*) m + ALIGN(sizeof(sd_bus_message)) + ALIGN(extra);
+ memcpy(m->label, label, label_sz + 1);
+ }
+
+ *ret = m;
+ return 0;
+}
+
+int bus_message_from_malloc(
+ void *buffer,
+ size_t length,
+ int *fds,
+ unsigned n_fds,
+ const struct ucred *ucred,
+ const char *label,
+ sd_bus_message **ret) {
+
+ sd_bus_message *m;
+ int r;
+
+ r = bus_message_from_header(buffer, length, fds, n_fds, ucred, label, 0, &m);
+ if (r < 0)
+ return r;
+
+ if (length != BUS_MESSAGE_SIZE(m)) {
+ r = -EBADMSG;
+ goto fail;
+ }
+
+ m->fields = (uint8_t*) buffer + sizeof(struct bus_header);
+ m->body = (uint8_t*) buffer + sizeof(struct bus_header) + ALIGN8(BUS_MESSAGE_FIELDS_SIZE(m));
+
+ m->n_iovec = 1;
+ m->iovec[0].iov_base = buffer;
+ m->iovec[0].iov_len = length;
+
+ r = bus_message_parse_fields(m);
+ if (r < 0)
+ goto fail;
+
+ /* We take possession of the memory and fds now */
+ m->free_header = true;
+ m->free_fds = true;
+
+ *ret = m;
+ return 0;
+
+fail:
+ message_free(m);
+ return r;
+}
+
+static sd_bus_message *message_new(sd_bus *bus, uint8_t type) {
+ sd_bus_message *m;
+
+ m = malloc0(ALIGN(sizeof(sd_bus_message)) + sizeof(struct bus_header));
+ if (!m)
+ return NULL;
+
+ m->n_ref = 1;
+ m->header = (struct bus_header*) ((uint8_t*) m + ALIGN(sizeof(struct sd_bus_message)));
+ m->header->endian = SD_BUS_NATIVE_ENDIAN;
+ m->header->type = type;
+ m->header->version = bus ? bus->message_version : 1;
+ m->allow_fds = !bus || bus->can_fds || (bus->state != BUS_HELLO && bus->state != BUS_RUNNING);
+
+ return m;
+}
+
+int sd_bus_message_new_signal(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *member,
+ sd_bus_message **m) {
+
+ sd_bus_message *t;
+ int r;
+
+ if (!path)
+ return -EINVAL;
+ if (!interface)
+ return -EINVAL;
+ if (!member)
+ return -EINVAL;
+ if (!m)
+ return -EINVAL;
+ if (bus && bus->state == BUS_UNSET)
+ return -ENOTCONN;
+
+ t = message_new(bus, SD_BUS_MESSAGE_TYPE_SIGNAL);
+ if (!t)
+ return -ENOMEM;
+
+ t->header->flags |= SD_BUS_MESSAGE_NO_REPLY_EXPECTED;
+
+ r = message_append_field_string(t, SD_BUS_MESSAGE_HEADER_PATH, SD_BUS_TYPE_OBJECT_PATH, path, &t->path);
+ if (r < 0)
+ goto fail;
+ r = message_append_field_string(t, SD_BUS_MESSAGE_HEADER_INTERFACE, SD_BUS_TYPE_STRING, interface, &t->interface);
+ if (r < 0)
+ goto fail;
+ r = message_append_field_string(t, SD_BUS_MESSAGE_HEADER_MEMBER, SD_BUS_TYPE_STRING, member, &t->member);
+ if (r < 0)
+ goto fail;
+
+ *m = t;
+ return 0;
+
+fail:
+ sd_bus_message_unref(t);
+ return r;
+}
+
+int sd_bus_message_new_method_call(
+ sd_bus *bus,
+ const char *destination,
+ const char *path,
+ const char *interface,
+ const char *member,
+ sd_bus_message **m) {
+
+ sd_bus_message *t;
+ int r;
+
+ if (!path)
+ return -EINVAL;
+ if (!member)
+ return -EINVAL;
+ if (!m)
+ return -EINVAL;
+ if (bus && bus->state == BUS_UNSET)
+ return -ENOTCONN;
+
+ t = message_new(bus, SD_BUS_MESSAGE_TYPE_METHOD_CALL);
+ if (!t)
+ return -ENOMEM;
+
+ r = message_append_field_string(t, SD_BUS_MESSAGE_HEADER_PATH, SD_BUS_TYPE_OBJECT_PATH, path, &t->path);
+ if (r < 0)
+ goto fail;
+ r = message_append_field_string(t, SD_BUS_MESSAGE_HEADER_MEMBER, SD_BUS_TYPE_STRING, member, &t->member);
+ if (r < 0)
+ goto fail;
+
+ if (interface) {
+ r = message_append_field_string(t, SD_BUS_MESSAGE_HEADER_INTERFACE, SD_BUS_TYPE_STRING, interface, &t->interface);
+ if (r < 0)
+ goto fail;
+ }
+
+ if (destination) {
+ r = message_append_field_string(t, SD_BUS_MESSAGE_HEADER_DESTINATION, SD_BUS_TYPE_STRING, destination, &t->destination);
+ if (r < 0)
+ goto fail;
+ }
+
+ *m = t;
+ return 0;
+
+fail:
+ message_free(t);
+ return r;
+}
+
+static int message_new_reply(
+ sd_bus *bus,
+ sd_bus_message *call,
+ uint8_t type,
+ sd_bus_message **m) {
+
+ sd_bus_message *t;
+ int r;
+
+ if (!call)
+ return -EINVAL;
+ if (!call->sealed)
+ return -EPERM;
+ if (call->header->type != SD_BUS_MESSAGE_TYPE_METHOD_CALL)
+ return -EINVAL;
+ if (!m)
+ return -EINVAL;
+ if (bus && bus->state == BUS_UNSET)
+ return -ENOTCONN;
+
+ t = message_new(bus, type);
+ if (!t)
+ return -ENOMEM;
+
+ t->header->flags |= SD_BUS_MESSAGE_NO_REPLY_EXPECTED;
+ t->reply_serial = BUS_MESSAGE_SERIAL(call);
+
+ r = message_append_field_uint32(t, SD_BUS_MESSAGE_HEADER_REPLY_SERIAL, t->reply_serial);
+ if (r < 0)
+ goto fail;
+
+ if (call->sender) {
+ r = message_append_field_string(t, SD_BUS_MESSAGE_HEADER_DESTINATION, SD_BUS_TYPE_STRING, call->sender, &t->sender);
+ if (r < 0)
+ goto fail;
+ }
+
+ t->dont_send = !!(call->header->flags & SD_BUS_MESSAGE_NO_REPLY_EXPECTED);
+
+ *m = t;
+ return 0;
+
+fail:
+ message_free(t);
+ return r;
+}
+
+int sd_bus_message_new_method_return(
+ sd_bus *bus,
+ sd_bus_message *call,
+ sd_bus_message **m) {
+
+ return message_new_reply(bus, call, SD_BUS_MESSAGE_TYPE_METHOD_RETURN, m);
+}
+
+int sd_bus_message_new_method_error(
+ sd_bus *bus,
+ sd_bus_message *call,
+ const sd_bus_error *e,
+ sd_bus_message **m) {
+
+ sd_bus_message *t;
+ int r;
+
+ if (!sd_bus_error_is_set(e))
+ return -EINVAL;
+ if (!m)
+ return -EINVAL;
+
+ r = message_new_reply(bus, call, SD_BUS_MESSAGE_TYPE_METHOD_ERROR, &t);
+ if (r < 0)
+ return r;
+
+ r = message_append_field_string(t, SD_BUS_MESSAGE_HEADER_ERROR_NAME, SD_BUS_TYPE_STRING, e->name, &t->error.name);
+ if (r < 0)
+ goto fail;
+
+ if (e->message) {
+ r = message_append_basic(t, SD_BUS_TYPE_STRING, e->message, (const void**) &t->error.message);
+ if (r < 0)
+ goto fail;
+ }
+
+ *m = t;
+ return 0;
+
+fail:
+ message_free(t);
+ return r;
+}
+
+sd_bus_message* sd_bus_message_ref(sd_bus_message *m) {
+ if (!m)
+ return NULL;
+
+ assert(m->n_ref > 0);
+ m->n_ref++;
+
+ return m;
+}
+
+sd_bus_message* sd_bus_message_unref(sd_bus_message *m) {
+ if (!m)
+ return NULL;
+
+ assert(m->n_ref > 0);
+ m->n_ref--;
+
+ if (m->n_ref <= 0)
+ message_free(m);
+
+ return NULL;
+}
+
+int sd_bus_message_get_type(sd_bus_message *m, uint8_t *type) {
+ if (!m)
+ return -EINVAL;
+ if (!type)
+ return -EINVAL;
+
+ *type = m->header->type;
+ return 0;
+}
+
+int sd_bus_message_get_serial(sd_bus_message *m, uint64_t *serial) {
+ if (!m)
+ return -EINVAL;
+ if (!serial)
+ return -EINVAL;
+ if (m->header->serial == 0)
+ return -ENOENT;
+
+ *serial = BUS_MESSAGE_SERIAL(m);
+ return 0;
+}
+
+int sd_bus_message_get_reply_serial(sd_bus_message *m, uint64_t *serial) {
+ if (!m)
+ return -EINVAL;
+ if (!serial)
+ return -EINVAL;
+ if (m->reply_serial == 0)
+ return -ENOENT;
+
+ *serial = m->reply_serial;
+ return 0;
+}
+
+int sd_bus_message_get_no_reply(sd_bus_message *m) {
+ if (!m)
+ return -EINVAL;
+
+ return m->header->type == SD_BUS_MESSAGE_TYPE_METHOD_CALL ? !!(m->header->flags & SD_BUS_MESSAGE_NO_REPLY_EXPECTED) : 0;
+}
+
+const char *sd_bus_message_get_path(sd_bus_message *m) {
+ if (!m)
+ return NULL;
+
+ return m->path;
+}
+
+const char *sd_bus_message_get_interface(sd_bus_message *m) {
+ if (!m)
+ return NULL;
+
+ return m->interface;
+}
+
+const char *sd_bus_message_get_member(sd_bus_message *m) {
+ if (!m)
+ return NULL;
+
+ return m->member;
+}
+const char *sd_bus_message_get_destination(sd_bus_message *m) {
+ if (!m)
+ return NULL;
+
+ return m->destination;
+}
+
+const char *sd_bus_message_get_sender(sd_bus_message *m) {
+ if (!m)
+ return NULL;
+
+ return m->sender;
+}
+
+const sd_bus_error *sd_bus_message_get_error(sd_bus_message *m) {
+ if (!m)
+ return NULL;
+
+ if (!sd_bus_error_is_set(&m->error))
+ return NULL;
+
+ return &m->error;
+}
+
+int sd_bus_message_get_uid(sd_bus_message *m, uid_t *uid) {
+ if (!m)
+ return -EINVAL;
+ if (!uid)
+ return -EINVAL;
+ if (!m->uid_valid)
+ return -ESRCH;
+
+ *uid = m->uid;
+ return 0;
+}
+
+int sd_bus_message_get_gid(sd_bus_message *m, gid_t *gid) {
+ if (!m)
+ return -EINVAL;
+ if (!gid)
+ return -EINVAL;
+ if (!m->gid_valid)
+ return -ESRCH;
+
+ *gid = m->gid;
+ return 0;
+}
+
+int sd_bus_message_get_pid(sd_bus_message *m, pid_t *pid) {
+ if (!m)
+ return -EINVAL;
+ if (!pid)
+ return -EINVAL;
+ if (m->pid <= 0)
+ return -ESRCH;
+
+ *pid = m->pid;
+ return 0;
+}
+
+int sd_bus_message_get_tid(sd_bus_message *m, pid_t *tid) {
+ if (!m)
+ return -EINVAL;
+ if (!tid)
+ return -EINVAL;
+ if (m->tid <= 0)
+ return -ESRCH;
+
+ *tid = m->tid;
+ return 0;
+}
+
+int sd_bus_message_get_pid_starttime(sd_bus_message *m, uint64_t *usec) {
+ if (!m)
+ return -EINVAL;
+ if (!usec)
+ return -EINVAL;
+ if (m->pid_starttime <= 0)
+ return -ESRCH;
+
+ *usec = m->pid_starttime;
+ return 0;
+}
+
+int sd_bus_message_get_selinux_context(sd_bus_message *m, const char **ret) {
+ if (!m)
+ return -EINVAL;
+ if (!m->label)
+ return -ESRCH;
+
+ *ret = m->label;
+ return 0;
+}
+
+int sd_bus_message_get_monotonic_timestamp(sd_bus_message *m, uint64_t *usec) {
+ if (!m)
+ return -EINVAL;
+ if (!usec)
+ return -EINVAL;
+ if (m->monotonic <= 0)
+ return -ESRCH;
+
+ *usec = m->monotonic;
+ return 0;
+}
+
+int sd_bus_message_get_realtime_timestamp(sd_bus_message *m, uint64_t *usec) {
+ if (!m)
+ return -EINVAL;
+ if (!usec)
+ return -EINVAL;
+ if (m->realtime <= 0)
+ return -ESRCH;
+
+ *usec = m->realtime;
+ return 0;
+}
+
+int sd_bus_message_get_comm(sd_bus_message *m, const char **ret) {
+ if (!m)
+ return -EINVAL;
+ if (!ret)
+ return -EINVAL;
+ if (!m->comm)
+ return -ESRCH;
+
+ *ret = m->comm;
+ return 0;
+}
+
+int sd_bus_message_get_tid_comm(sd_bus_message *m, const char **ret) {
+ if (!m)
+ return -EINVAL;
+ if (!ret)
+ return -EINVAL;
+ if (!m->tid_comm)
+ return -ESRCH;
+
+ *ret = m->tid_comm;
+ return 0;
+}
+
+int sd_bus_message_get_exe(sd_bus_message *m, const char **ret) {
+ if (!m)
+ return -EINVAL;
+ if (!ret)
+ return -EINVAL;
+ if (!m->exe)
+ return -ESRCH;
+
+ *ret = m->exe;
+ return 0;
+}
+
+int sd_bus_message_get_cgroup(sd_bus_message *m, const char **ret) {
+ if (!m)
+ return -EINVAL;
+ if (!ret)
+ return -EINVAL;
+ if (!m->cgroup)
+ return -ESRCH;
+
+ *ret = m->cgroup;
+ return 0;
+}
+
+int sd_bus_message_get_unit(sd_bus_message *m, const char **ret) {
+ int r;
+
+ if (!m)
+ return -EINVAL;
+ if (!ret)
+ return -EINVAL;
+ if (!m->cgroup)
+ return -ESRCH;
+
+ if (!m->unit) {
+ r = cg_path_get_unit(m->cgroup, &m->unit);
+ if (r < 0)
+ return r;
+ }
+
+ *ret = m->unit;
+ return 0;
+}
+
+int sd_bus_message_get_user_unit(sd_bus_message *m, const char **ret) {
+ int r;
+
+ if (!m)
+ return -EINVAL;
+ if (!ret)
+ return -EINVAL;
+ if (!m->cgroup)
+ return -ESRCH;
+
+ if (!m->user_unit) {
+ r = cg_path_get_user_unit(m->cgroup, &m->user_unit);
+ if (r < 0)
+ return r;
+ }
+
+ *ret = m->user_unit;
+ return 0;
+}
+
+int sd_bus_message_get_session(sd_bus_message *m, const char **ret) {
+ int r;
+
+ if (!m)
+ return -EINVAL;
+ if (!ret)
+ return -EINVAL;
+ if (!m->cgroup)
+ return -ESRCH;
+
+ if (!m->session) {
+ r = cg_path_get_session(m->cgroup, &m->session);
+ if (r < 0)
+ return r;
+ }
+
+ *ret = m->session;
+ return 0;
+}
+
+int sd_bus_message_get_owner_uid(sd_bus_message *m, uid_t *uid) {
+ if (!m)
+ return -EINVAL;
+ if (!uid)
+ return -EINVAL;
+ if (!m->cgroup)
+ return -ESRCH;
+
+ return cg_path_get_owner_uid(m->cgroup, uid);
+}
+
+int sd_bus_message_get_cmdline(sd_bus_message *m, char ***cmdline) {
+ size_t n, i;
+ const char *p;
+ bool first;
+
+ if (!m)
+ return -EINVAL;
+
+ if (!m->cmdline)
+ return -ENOENT;
+
+ for (p = m->cmdline, n = 0; p < m->cmdline + m->cmdline_length; p++)
+ if (*p == 0)
+ n++;
+
+ m->cmdline_array = new(char*, n + 1);
+ if (!m->cmdline_array)
+ return -ENOMEM;
+
+ for (p = m->cmdline, i = 0, first = true; p < m->cmdline + m->cmdline_length; p++) {
+ if (first)
+ m->cmdline_array[i++] = (char*) p;
+
+ first = *p == 0;
+ }
+
+ m->cmdline_array[i] = NULL;
+ *cmdline = m->cmdline_array;
+
+ return 0;
+}
+
+int sd_bus_message_get_audit_sessionid(sd_bus_message *m, uint32_t *sessionid) {
+ if (!m)
+ return -EINVAL;
+ if (!sessionid)
+ return -EINVAL;
+ if (!m->audit)
+ return -ESRCH;
+
+ *sessionid = m->audit->sessionid;
+ return 0;
+}
+
+int sd_bus_message_get_audit_loginuid(sd_bus_message *m, uid_t *uid) {
+ if (!m)
+ return -EINVAL;
+ if (!uid)
+ return -EINVAL;
+ if (!m->audit)
+ return -ESRCH;
+
+ *uid = m->audit->loginuid;
+ return 0;
+}
+
+int sd_bus_message_has_effective_cap(sd_bus_message *m, int capability) {
+ unsigned sz;
+
+ if (!m)
+ return -EINVAL;
+ if (capability < 0)
+ return -EINVAL;
+ if (!m->capability)
+ return -ESRCH;
+
+ sz = m->capability_size / 4;
+ if ((unsigned) capability >= sz*8)
+ return 0;
+
+ return !!(m->capability[2 * sz + (capability / 8)] & (1 << (capability % 8)));
+}
+
+int sd_bus_message_is_signal(sd_bus_message *m, const char *interface, const char *member) {
+ if (!m)
+ return -EINVAL;
+
+ if (m->header->type != SD_BUS_MESSAGE_TYPE_SIGNAL)
+ return 0;
+
+ if (interface && (!m->interface || !streq(m->interface, interface)))
+ return 0;
+
+ if (member && (!m->member || !streq(m->member, member)))
+ return 0;
+
+ return 1;
+}
+
+int sd_bus_message_is_method_call(sd_bus_message *m, const char *interface, const char *member) {
+ if (!m)
+ return -EINVAL;
+
+ if (m->header->type != SD_BUS_MESSAGE_TYPE_METHOD_CALL)
+ return 0;
+
+ if (interface && (!m->interface || !streq(m->interface, interface)))
+ return 0;
+
+ if (member && (!m->member || !streq(m->member, member)))
+ return 0;
+
+ return 1;
+}
+
+int sd_bus_message_is_method_error(sd_bus_message *m, const char *name) {
+ if (!m)
+ return -EINVAL;
+
+ if (m->header->type != SD_BUS_MESSAGE_TYPE_METHOD_ERROR)
+ return 0;
+
+ if (name && (!m->error.name || !streq(m->error.name, name)))
+ return 0;
+
+ return 1;
+}
+
+int sd_bus_message_set_no_reply(sd_bus_message *m, int b) {
+ if (!m)
+ return -EINVAL;
+ if (m->sealed)
+ return -EPERM;
+ if (m->header->type != SD_BUS_MESSAGE_TYPE_METHOD_CALL)
+ return -EPERM;
+
+ if (b)
+ m->header->flags |= SD_BUS_MESSAGE_NO_REPLY_EXPECTED;
+ else
+ m->header->flags &= ~SD_BUS_MESSAGE_NO_REPLY_EXPECTED;
+
+ return 0;
+}
+
+static struct bus_container *message_get_container(sd_bus_message *m) {
+ assert(m);
+
+ if (m->n_containers == 0)
+ return &m->root_container;
+
+ assert(m->containers);
+ return m->containers + m->n_containers - 1;
+}
+
+static void *message_extend_body(sd_bus_message *m, size_t align, size_t sz) {
+ void *p, *o;
+ size_t added;
+ struct bus_container *c;
+
+ assert(m);
+ assert(align > 0);
+
+ o = m->body;
+ added = m->header->body_size;
+
+ p = buffer_extend(&m->body, &m->header->body_size, align, sz);
+ if (!p)
+ return NULL;
+
+ added = m->header->body_size - added;
+
+ for (c = m->containers; c < m->containers + m->n_containers; c++)
+ if (c->array_size) {
+ c->array_size = (uint32_t*) ((uint8_t*) m->body + ((uint8_t*) c->array_size - (uint8_t*) o));
+ *c->array_size += added;
+ }
+
+ if (o != m->body) {
+ if (m->error.message)
+ m->error.message = (const char*) m->body + (m->error.message - (const char*) o);
+ }
+
+ m->free_body = true;
+
+ return p;
+}
+
+int message_append_basic(sd_bus_message *m, char type, const void *p, const void **stored) {
+ struct bus_container *c;
+ ssize_t align, sz;
+ uint32_t k;
+ void *a;
+ char *e = NULL;
+ int fd = -1;
+ uint32_t fdi = 0;
+ int r;
+
+ if (!m)
+ return -EINVAL;
+ if (!p)
+ return -EINVAL;
+ if (m->sealed)
+ return -EPERM;
+ if (!bus_type_is_basic(type))
+ return -EINVAL;
+
+ c = message_get_container(m);
+
+ if (c->signature && c->signature[c->index]) {
+ /* Container signature is already set */
+
+ if (c->signature[c->index] != type)
+ return -ENXIO;
+ } else {
+ /* Maybe we can append to the signature? But only if this is the top-level container*/
+ if (c->enclosing != 0)
+ return -ENXIO;
+
+ e = strextend(&c->signature, CHAR_TO_STR(type), NULL);
+ if (!e)
+ return -ENOMEM;
+ }
+
+ switch (type) {
+
+ case SD_BUS_TYPE_STRING:
+ case SD_BUS_TYPE_OBJECT_PATH:
+
+ align = 4;
+ sz = 4 + strlen(p) + 1;
+ break;
+
+ case SD_BUS_TYPE_SIGNATURE:
+
+ align = 1;
+ sz = 1 + strlen(p) + 1;
+ break;
+
+ case SD_BUS_TYPE_BOOLEAN:
+ align = sz = 4;
+
+ assert_cc(sizeof(int) == sizeof(uint32_t));
+ memcpy(&k, p, 4);
+ k = !!k;
+ p = &k;
+ break;
+
+ case SD_BUS_TYPE_UNIX_FD: {
+ int z, *f;
+
+ if (!m->allow_fds) {
+ r = -ENOTSUP;
+ goto fail;
+ }
+
+ align = sz = 4;
+
+ z = *(int*) p;
+ if (z < 0) {
+ r = -EINVAL;
+ goto fail;
+ }
+
+ fd = fcntl(z, F_DUPFD_CLOEXEC, 3);
+ if (fd < 0) {
+ r = -errno;
+ goto fail;
+ }
+
+ f = realloc(m->fds, sizeof(int) * (m->n_fds + 1));
+ if (!f) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ fdi = m->n_fds;
+ f[fdi] = fd;
+ m->fds = f;
+ m->free_fds = true;
+ break;
+ }
+
+ default:
+ align = bus_type_get_alignment(type);
+ sz = bus_type_get_size(type);
+ break;
+ }
+
+ assert(align > 0);
+ assert(sz > 0);
+
+ a = message_extend_body(m, align, sz);
+ if (!a) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ if (type == SD_BUS_TYPE_STRING || type == SD_BUS_TYPE_OBJECT_PATH) {
+ *(uint32_t*) a = sz - 5;
+ memcpy((uint8_t*) a + 4, p, sz - 4);
+
+ if (stored)
+ *stored = (const uint8_t*) a + 4;
+
+ } else if (type == SD_BUS_TYPE_SIGNATURE) {
+ *(uint8_t*) a = sz - 1;
+ memcpy((uint8_t*) a + 1, p, sz - 1);
+
+ if (stored)
+ *stored = (const uint8_t*) a + 1;
+ } else if (type == SD_BUS_TYPE_UNIX_FD) {
+ *(uint32_t*) a = fdi;
+
+ if (stored)
+ *stored = a;
+
+ m->n_fds ++;
+
+ } else {
+ memcpy(a, p, sz);
+
+ if (stored)
+ *stored = a;
+ }
+
+ if (c->enclosing != SD_BUS_TYPE_ARRAY)
+ c->index++;
+
+ return 0;
+
+fail:
+ /* Truncate extended signature again */
+ if (e)
+ c->signature[c->index] = 0;
+
+ if (fd >= 0)
+ close_nointr_nofail(fd);
+
+ return r;
+}
+
+int sd_bus_message_append_basic(sd_bus_message *m, char type, const void *p) {
+ return message_append_basic(m, type, p, NULL);
+}
+
+static int bus_message_open_array(
+ sd_bus_message *m,
+ struct bus_container *c,
+ const char *contents,
+ uint32_t **array_size) {
+
+ unsigned nindex;
+ char *e = NULL;
+ void *a, *b;
+ int alignment;
+ size_t saved;
+
+ assert(m);
+ assert(c);
+ assert(contents);
+ assert(array_size);
+
+ if (!signature_is_single(contents))
+ return -EINVAL;
+
+ alignment = bus_type_get_alignment(contents[0]);
+ if (alignment < 0)
+ return alignment;
+
+ if (c->signature && c->signature[c->index]) {
+
+ /* Verify the existing signature */
+
+ if (c->signature[c->index] != SD_BUS_TYPE_ARRAY)
+ return -ENXIO;
+
+ if (!startswith(c->signature + c->index + 1, contents))
+ return -ENXIO;
+
+ nindex = c->index + 1 + strlen(contents);
+ } else {
+ if (c->enclosing != 0)
+ return -ENXIO;
+
+ /* Extend the existing signature */
+
+ e = strextend(&c->signature, CHAR_TO_STR(SD_BUS_TYPE_ARRAY), contents, NULL);
+ if (!e)
+ return -ENOMEM;
+
+ nindex = e - c->signature;
+ }
+
+ saved = m->header->body_size;
+ a = message_extend_body(m, 4, 4);
+ if (!a) {
+ /* Truncate extended signature again */
+ if (e)
+ c->signature[c->index] = 0;
+
+ return -ENOMEM;
+ }
+ b = m->body;
+
+ if (!message_extend_body(m, alignment, 0)) {
+ /* Add alignment between size and first element */
+ if (e)
+ c->signature[c->index] = 0;
+
+ m->header->body_size = saved;
+ return -ENOMEM;
+ }
+
+ if (c->enclosing != SD_BUS_TYPE_ARRAY)
+ c->index = nindex;
+
+ /* m->body might have changed so let's readjust a */
+ a = (uint8_t*) m->body + ((uint8_t*) a - (uint8_t*) b);
+ *(uint32_t*) a = 0;
+
+ *array_size = a;
+ return 0;
+}
+
+static int bus_message_open_variant(
+ sd_bus_message *m,
+ struct bus_container *c,
+ const char *contents) {
+
+ char *e = NULL;
+ size_t l;
+ void *a;
+
+ assert(m);
+ assert(c);
+ assert(contents);
+
+ if (!signature_is_single(contents))
+ return -EINVAL;
+
+ if (*contents == SD_BUS_TYPE_DICT_ENTRY_BEGIN)
+ return -EINVAL;
+
+ if (c->signature && c->signature[c->index]) {
+
+ if (c->signature[c->index] != SD_BUS_TYPE_VARIANT)
+ return -ENXIO;
+
+ } else {
+ if (c->enclosing != 0)
+ return -ENXIO;
+
+ e = strextend(&c->signature, CHAR_TO_STR(SD_BUS_TYPE_VARIANT), NULL);
+ if (!e)
+ return -ENOMEM;
+ }
+
+ l = strlen(contents);
+ a = message_extend_body(m, 1, 1 + l + 1);
+ if (!a) {
+ /* Truncate extended signature again */
+ if (e)
+ c->signature[c->index] = 0;
+
+ return -ENOMEM;
+ }
+
+ *(uint8_t*) a = l;
+ memcpy((uint8_t*) a + 1, contents, l + 1);
+
+ if (c->enclosing != SD_BUS_TYPE_ARRAY)
+ c->index++;
+
+ return 0;
+}
+
+static int bus_message_open_struct(
+ sd_bus_message *m,
+ struct bus_container *c,
+ const char *contents) {
+
+ size_t nindex;
+ char *e = NULL;
+
+ assert(m);
+ assert(c);
+ assert(contents);
+
+ if (!signature_is_valid(contents, false))
+ return -EINVAL;
+
+ if (c->signature && c->signature[c->index]) {
+ size_t l;
+
+ l = strlen(contents);
+
+ if (c->signature[c->index] != SD_BUS_TYPE_STRUCT_BEGIN ||
+ !startswith(c->signature + c->index + 1, contents) ||
+ c->signature[c->index + 1 + l] != SD_BUS_TYPE_STRUCT_END)
+ return -ENXIO;
+
+ nindex = c->index + 1 + l + 1;
+ } else {
+ if (c->enclosing != 0)
+ return -ENXIO;
+
+ e = strextend(&c->signature, CHAR_TO_STR(SD_BUS_TYPE_STRUCT_BEGIN), contents, CHAR_TO_STR(SD_BUS_TYPE_STRUCT_END), NULL);
+ if (!e)
+ return -ENOMEM;
+
+ nindex = e - c->signature;
+ }
+
+ /* Align contents to 8 byte boundary */
+ if (!message_extend_body(m, 8, 0)) {
+ if (e)
+ c->signature[c->index] = 0;
+
+ return -ENOMEM;
+ }
+
+ if (c->enclosing != SD_BUS_TYPE_ARRAY)
+ c->index = nindex;
+
+ return 0;
+}
+
+static int bus_message_open_dict_entry(
+ sd_bus_message *m,
+ struct bus_container *c,
+ const char *contents) {
+
+ size_t nindex;
+
+ assert(m);
+ assert(c);
+ assert(contents);
+
+ if (!signature_is_pair(contents))
+ return -EINVAL;
+
+ if (c->enclosing != SD_BUS_TYPE_ARRAY)
+ return -ENXIO;
+
+ if (c->signature && c->signature[c->index]) {
+ size_t l;
+
+ l = strlen(contents);
+
+ if (c->signature[c->index] != SD_BUS_TYPE_DICT_ENTRY_BEGIN ||
+ !startswith(c->signature + c->index + 1, contents) ||
+ c->signature[c->index + 1 + l] != SD_BUS_TYPE_DICT_ENTRY_END)
+ return -ENXIO;
+
+ nindex = c->index + 1 + l + 1;
+ } else
+ return -ENXIO;
+
+ /* Align contents to 8 byte boundary */
+ if (!message_extend_body(m, 8, 0))
+ return -ENOMEM;
+
+ if (c->enclosing != SD_BUS_TYPE_ARRAY)
+ c->index = nindex;
+
+ return 0;
+}
+
+int sd_bus_message_open_container(
+ sd_bus_message *m,
+ char type,
+ const char *contents) {
+
+ struct bus_container *c, *w;
+ uint32_t *array_size = NULL;
+ char *signature;
+ int r;
+
+ if (!m)
+ return -EINVAL;
+ if (m->sealed)
+ return -EPERM;
+ if (!contents)
+ return -EINVAL;
+
+ /* Make sure we have space for one more container */
+ w = realloc(m->containers, sizeof(struct bus_container) * (m->n_containers + 1));
+ if (!w)
+ return -ENOMEM;
+ m->containers = w;
+
+ c = message_get_container(m);
+
+ signature = strdup(contents);
+ if (!signature)
+ return -ENOMEM;
+
+ if (type == SD_BUS_TYPE_ARRAY)
+ r = bus_message_open_array(m, c, contents, &array_size);
+ else if (type == SD_BUS_TYPE_VARIANT)
+ r = bus_message_open_variant(m, c, contents);
+ else if (type == SD_BUS_TYPE_STRUCT)
+ r = bus_message_open_struct(m, c, contents);
+ else if (type == SD_BUS_TYPE_DICT_ENTRY)
+ r = bus_message_open_dict_entry(m, c, contents);
+ else
+ r = -EINVAL;
+
+ if (r < 0) {
+ free(signature);
+ return r;
+ }
+
+ /* OK, let's fill it in */
+ w += m->n_containers++;
+ w->enclosing = type;
+ w->signature = signature;
+ w->index = 0;
+ w->array_size = array_size;
+ w->begin = 0;
+
+ return 0;
+}
+
+int sd_bus_message_close_container(sd_bus_message *m) {
+ struct bus_container *c;
+
+ if (!m)
+ return -EINVAL;
+ if (m->sealed)
+ return -EPERM;
+ if (m->n_containers <= 0)
+ return -EINVAL;
+
+ c = message_get_container(m);
+ if (c->enclosing != SD_BUS_TYPE_ARRAY)
+ if (c->signature && c->signature[c->index] != 0)
+ return -EINVAL;
+
+ free(c->signature);
+ m->n_containers--;
+
+ return 0;
+}
+
+
+typedef struct {
+ const char *types;
+ unsigned n_struct;
+ unsigned n_array;
+} TypeStack;
+
+static int type_stack_push(TypeStack *stack, unsigned max, unsigned *i, const char *types, unsigned n_struct, unsigned n_array) {
+ assert(stack);
+ assert(max > 0);
+
+ if (*i >= max)
+ return -EINVAL;
+
+ stack[*i].types = types;
+ stack[*i].n_struct = n_struct;
+ stack[*i].n_array = n_array;
+ (*i)++;
+
+ return 0;
+}
+
+static int type_stack_pop(TypeStack *stack, unsigned max, unsigned *i, const char **types, unsigned *n_struct, unsigned *n_array) {
+ assert(stack);
+ assert(max > 0);
+ assert(types);
+ assert(n_struct);
+ assert(n_array);
+
+ if (*i <= 0)
+ return 0;
+
+ (*i)--;
+ *types = stack[*i].types;
+ *n_struct = stack[*i].n_struct;
+ *n_array = stack[*i].n_array;
+
+ return 1;
+}
+
+int bus_message_append_ap(
+ sd_bus_message *m,
+ const char *types,
+ va_list ap) {
+
+ unsigned n_array, n_struct;
+ TypeStack stack[BUS_CONTAINER_DEPTH];
+ unsigned stack_ptr = 0;
+ int r;
+
+ assert(m);
+
+ if (!types)
+ return 0;
+
+ n_array = (unsigned) -1;
+ n_struct = strlen(types);
+
+ for (;;) {
+ const char *t;
+
+ if (n_array == 0 || (n_array == (unsigned) -1 && n_struct == 0)) {
+ r = type_stack_pop(stack, ELEMENTSOF(stack), &stack_ptr, &types, &n_struct, &n_array);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ break;
+
+ r = sd_bus_message_close_container(m);
+ if (r < 0)
+ return r;
+
+ continue;
+ }
+
+ t = types;
+ if (n_array != (unsigned) -1)
+ n_array --;
+ else {
+ types ++;
+ n_struct--;
+ }
+
+ switch (*t) {
+
+ case SD_BUS_TYPE_BYTE: {
+ uint8_t x;
+
+ x = (uint8_t) va_arg(ap, int);
+ r = sd_bus_message_append_basic(m, *t, &x);
+ break;
+ }
+
+ case SD_BUS_TYPE_BOOLEAN:
+ case SD_BUS_TYPE_INT32:
+ case SD_BUS_TYPE_UINT32:
+ case SD_BUS_TYPE_UNIX_FD: {
+ uint32_t x;
+
+ /* We assume a boolean is the same as int32_t */
+ assert_cc(sizeof(int32_t) == sizeof(int));
+
+ x = va_arg(ap, uint32_t);
+ r = sd_bus_message_append_basic(m, *t, &x);
+ break;
+ }
+
+ case SD_BUS_TYPE_INT16:
+ case SD_BUS_TYPE_UINT16: {
+ uint16_t x;
+
+ x = (uint16_t) va_arg(ap, int);
+ r = sd_bus_message_append_basic(m, *t, &x);
+ break;
+ }
+
+ case SD_BUS_TYPE_INT64:
+ case SD_BUS_TYPE_UINT64:
+ case SD_BUS_TYPE_DOUBLE: {
+ uint64_t x;
+
+ x = va_arg(ap, uint64_t);
+ r = sd_bus_message_append_basic(m, *t, &x);
+ break;
+ }
+
+ case SD_BUS_TYPE_STRING:
+ case SD_BUS_TYPE_OBJECT_PATH:
+ case SD_BUS_TYPE_SIGNATURE: {
+ const char *x;
+
+ x = va_arg(ap, const char*);
+ r = sd_bus_message_append_basic(m, *t, x);
+ break;
+ }
+
+ case SD_BUS_TYPE_ARRAY: {
+ size_t k;
+
+ r = signature_element_length(t + 1, &k);
+ if (r < 0)
+ return r;
+
+ {
+ char s[k + 1];
+ memcpy(s, t + 1, k);
+ s[k] = 0;
+
+ r = sd_bus_message_open_container(m, SD_BUS_TYPE_ARRAY, s);
+ if (r < 0)
+ return r;
+ }
+
+ if (n_array == (unsigned) -1) {
+ types += k;
+ n_struct -= k;
+ }
+
+ r = type_stack_push(stack, ELEMENTSOF(stack), &stack_ptr, types, n_struct, n_array);
+ if (r < 0)
+ return r;
+
+ types = t + 1;
+ n_struct = k;
+ n_array = va_arg(ap, unsigned);
+
+ break;
+ }
+
+ case SD_BUS_TYPE_VARIANT: {
+ const char *s;
+
+ s = va_arg(ap, const char*);
+ if (!s)
+ return -EINVAL;
+
+ r = sd_bus_message_open_container(m, SD_BUS_TYPE_VARIANT, s);
+ if (r < 0)
+ return r;
+
+ r = type_stack_push(stack, ELEMENTSOF(stack), &stack_ptr, types, n_struct, n_array);
+ if (r < 0)
+ return r;
+
+ types = s;
+ n_struct = strlen(s);
+ n_array = (unsigned) -1;
+
+ break;
+ }
+
+ case SD_BUS_TYPE_STRUCT_BEGIN:
+ case SD_BUS_TYPE_DICT_ENTRY_BEGIN: {
+ size_t k;
+
+ r = signature_element_length(t, &k);
+ if (r < 0)
+ return r;
+
+ {
+ char s[k - 1];
+
+ memcpy(s, t + 1, k - 2);
+ s[k - 2] = 0;
+
+ r = sd_bus_message_open_container(m, *t == SD_BUS_TYPE_STRUCT_BEGIN ? SD_BUS_TYPE_STRUCT : SD_BUS_TYPE_DICT_ENTRY, s);
+ if (r < 0)
+ return r;
+ }
+
+ if (n_array == (unsigned) -1) {
+ types += k - 1;
+ n_struct -= k - 1;
+ }
+
+ r = type_stack_push(stack, ELEMENTSOF(stack), &stack_ptr, types, n_struct, n_array);
+ if (r < 0)
+ return r;
+
+ types = t + 1;
+ n_struct = k - 2;
+ n_array = (unsigned) -1;
+
+ break;
+ }
+
+ default:
+ r = -EINVAL;
+ }
+
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+int sd_bus_message_append(sd_bus_message *m, const char *types, ...) {
+ va_list ap;
+ int r;
+
+ if (!m)
+ return -EINVAL;
+ if (m->sealed)
+ return -EPERM;
+ if (!types)
+ return 0;
+
+ va_start(ap, types);
+ r = bus_message_append_ap(m, types, ap);
+ va_end(ap);
+
+ return r;
+}
+
+static int buffer_peek(const void *p, uint32_t sz, size_t *rindex, size_t align, size_t nbytes, void **r) {
+ size_t k, start, n;
+
+ assert(rindex);
+ assert(align > 0);
+
+ start = ALIGN_TO((size_t) *rindex, align);
+ n = start + nbytes;
+
+ if (n > sz)
+ return -EBADMSG;
+
+ /* Verify that padding is 0 */
+ for (k = *rindex; k < start; k++)
+ if (((const uint8_t*) p)[k] != 0)
+ return -EBADMSG;
+
+ if (r)
+ *r = (uint8_t*) p + start;
+
+ *rindex = n;
+
+ return 1;
+}
+
+static bool message_end_of_array(sd_bus_message *m, size_t index) {
+ struct bus_container *c;
+
+ assert(m);
+
+ c = message_get_container(m);
+ if (!c->array_size)
+ return false;
+
+ return index >= c->begin + BUS_MESSAGE_BSWAP32(m, *c->array_size);
+}
+
+static int message_peek_body(sd_bus_message *m, size_t *rindex, size_t align, size_t nbytes, void **ret) {
+ assert(m);
+ assert(rindex);
+ assert(align > 0);
+
+ if (message_end_of_array(m, *rindex))
+ return 0;
+
+ return buffer_peek(m->body, BUS_MESSAGE_BODY_SIZE(m), rindex, align, nbytes, ret);
+}
+
+static bool validate_nul(const char *s, size_t l) {
+
+ /* Check for NUL chars in the string */
+ if (memchr(s, 0, l))
+ return false;
+
+ /* Check for NUL termination */
+ if (s[l] != 0)
+ return false;
+
+ return true;
+}
+
+static bool validate_string(const char *s, size_t l) {
+
+ if (!validate_nul(s, l))
+ return false;
+
+ /* Check if valid UTF8 */
+ if (!utf8_is_valid(s))
+ return false;
+
+ return true;
+}
+
+static bool validate_signature(const char *s, size_t l) {
+
+ if (!validate_nul(s, l))
+ return false;
+
+ /* Check if valid signature */
+ if (!signature_is_valid(s, true))
+ return false;
+
+ return true;
+}
+
+static bool validate_object_path(const char *s, size_t l) {
+
+ if (!validate_nul(s, l))
+ return false;
+
+ if (!object_path_is_valid(s))
+ return false;
+
+ return true;
+}
+
+int sd_bus_message_read_basic(sd_bus_message *m, char type, void *p) {
+ struct bus_container *c;
+ int r;
+ void *q;
+
+ if (!m)
+ return -EINVAL;
+ if (!m->sealed)
+ return -EPERM;
+ if (!bus_type_is_basic(type))
+ return -EINVAL;
+ if (!p)
+ return -EINVAL;
+
+ c = message_get_container(m);
+
+ if (!c->signature || c->signature[c->index] == 0)
+ return 0;
+
+ if (c->signature[c->index] != type)
+ return -ENXIO;
+
+ switch (type) {
+
+ case SD_BUS_TYPE_STRING:
+ case SD_BUS_TYPE_OBJECT_PATH: {
+ uint32_t l;
+ size_t rindex;
+
+ rindex = m->rindex;
+ r = message_peek_body(m, &rindex, 4, 4, &q);
+ if (r <= 0)
+ return r;
+
+ l = BUS_MESSAGE_BSWAP32(m, *(uint32_t*) q);
+ r = message_peek_body(m, &rindex, 1, l+1, &q);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return -EBADMSG;
+
+ if (type == SD_BUS_TYPE_OBJECT_PATH) {
+ if (!validate_object_path(q, l))
+ return -EBADMSG;
+ } else {
+ if (!validate_string(q, l))
+ return -EBADMSG;
+ }
+
+ m->rindex = rindex;
+ *(const char**) p = q;
+ break;
+ }
+
+ case SD_BUS_TYPE_SIGNATURE: {
+ uint8_t l;
+ size_t rindex;
+
+ rindex = m->rindex;
+ r = message_peek_body(m, &rindex, 1, 1, &q);
+ if (r <= 0)
+ return r;
+
+ l = *(uint8_t*) q;
+ r = message_peek_body(m, &rindex, 1, l+1, &q);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return -EBADMSG;
+
+ if (!validate_signature(q, l))
+ return -EBADMSG;
+
+ m->rindex = rindex;
+ *(const char**) p = q;
+ break;
+ }
+
+ default: {
+ ssize_t sz, align;
+ size_t rindex;
+
+ align = bus_type_get_alignment(type);
+ sz = bus_type_get_size(type);
+ assert(align > 0 && sz > 0);
+
+ rindex = m->rindex;
+ r = message_peek_body(m, &rindex, align, sz, &q);
+ if (r <= 0)
+ return r;
+
+ switch (type) {
+
+ case SD_BUS_TYPE_BYTE:
+ *(uint8_t*) p = *(uint8_t*) q;
+ break;
+
+ case SD_BUS_TYPE_BOOLEAN:
+ *(int*) p = !!*(uint32_t*) q;
+ break;
+
+ case SD_BUS_TYPE_INT16:
+ case SD_BUS_TYPE_UINT16:
+ *(uint16_t*) p = BUS_MESSAGE_BSWAP16(m, *(uint16_t*) q);
+ break;
+
+ case SD_BUS_TYPE_INT32:
+ case SD_BUS_TYPE_UINT32:
+ *(uint32_t*) p = BUS_MESSAGE_BSWAP32(m, *(uint32_t*) q);
+ break;
+
+ case SD_BUS_TYPE_INT64:
+ case SD_BUS_TYPE_UINT64:
+ case SD_BUS_TYPE_DOUBLE:
+ *(uint64_t*) p = BUS_MESSAGE_BSWAP64(m, *(uint64_t*) q);
+ break;
+
+ case SD_BUS_TYPE_UNIX_FD: {
+ uint32_t j;
+
+ j = BUS_MESSAGE_BSWAP32(m, *(uint32_t*) q);
+ if (j >= m->n_fds)
+ return -EBADMSG;
+
+ *(int*) p = m->fds[j];
+ break;
+ }
+
+ default:
+ assert_not_reached("Unknown basic type...");
+ }
+
+ m->rindex = rindex;
+
+ break;
+ }
+ }
+
+ if (c->enclosing != SD_BUS_TYPE_ARRAY)
+ c->index++;
+
+ return 1;
+}
+
+static int bus_message_enter_array(
+ sd_bus_message *m,
+ struct bus_container *c,
+ const char *contents,
+ uint32_t **array_size) {
+
+ size_t rindex;
+ void *q;
+ int r, alignment;
+
+ assert(m);
+ assert(c);
+ assert(contents);
+ assert(array_size);
+
+ if (!signature_is_single(contents))
+ return -EINVAL;
+
+ alignment = bus_type_get_alignment(contents[0]);
+ if (alignment < 0)
+ return alignment;
+
+ if (!c->signature || c->signature[c->index] == 0)
+ return 0;
+
+ if (c->signature[c->index] != SD_BUS_TYPE_ARRAY)
+ return -ENXIO;
+
+ if (!startswith(c->signature + c->index + 1, contents))
+ return -ENXIO;
+
+ rindex = m->rindex;
+ r = message_peek_body(m, &rindex, 4, 4, &q);
+ if (r <= 0)
+ return r;
+
+ if (BUS_MESSAGE_BSWAP32(m, *(uint32_t*) q) > BUS_ARRAY_MAX_SIZE)
+ return -EBADMSG;
+
+ r = message_peek_body(m, &rindex, alignment, 0, NULL);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return -EBADMSG;
+
+ if (c->enclosing != SD_BUS_TYPE_ARRAY)
+ c->index += 1 + strlen(contents);
+
+ m->rindex = rindex;
+
+ *array_size = (uint32_t*) q;
+
+ return 1;
+}
+
+static int bus_message_enter_variant(
+ sd_bus_message *m,
+ struct bus_container *c,
+ const char *contents) {
+
+ size_t rindex;
+ uint8_t l;
+ void *q;
+ int r;
+
+ assert(m);
+ assert(c);
+ assert(contents);
+
+ if (!signature_is_single(contents))
+ return -EINVAL;
+
+ if (*contents == SD_BUS_TYPE_DICT_ENTRY_BEGIN)
+ return -EINVAL;
+
+ if (!c->signature || c->signature[c->index] == 0)
+ return 0;
+
+ if (c->signature[c->index] != SD_BUS_TYPE_VARIANT)
+ return -ENXIO;
+
+ rindex = m->rindex;
+ r = message_peek_body(m, &rindex, 1, 1, &q);
+ if (r <= 0)
+ return r;
+
+ l = *(uint8_t*) q;
+ r = message_peek_body(m, &rindex, 1, l+1, &q);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return -EBADMSG;
+
+ if (!validate_signature(q, l))
+ return -EBADMSG;
+
+ if (!streq(q, contents))
+ return -ENXIO;
+
+ if (c->enclosing != SD_BUS_TYPE_ARRAY)
+ c->index++;
+
+ m->rindex = rindex;
+
+ return 1;
+}
+
+static int bus_message_enter_struct(
+ sd_bus_message *m,
+ struct bus_container *c,
+ const char *contents) {
+
+ size_t l;
+ int r;
+
+ assert(m);
+ assert(c);
+ assert(contents);
+
+ if (!signature_is_valid(contents, false))
+ return -EINVAL;
+
+ if (!c->signature || c->signature[c->index] == 0)
+ return 0;
+
+ l = strlen(contents);
+
+ if (c->signature[c->index] != SD_BUS_TYPE_STRUCT_BEGIN ||
+ !startswith(c->signature + c->index + 1, contents) ||
+ c->signature[c->index + 1 + l] != SD_BUS_TYPE_STRUCT_END)
+ return -ENXIO;
+
+ r = message_peek_body(m, &m->rindex, 8, 0, NULL);
+ if (r <= 0)
+ return r;
+
+ if (c->enclosing != SD_BUS_TYPE_ARRAY)
+ c->index += 1 + l + 1;
+
+ return 1;
+}
+
+static int bus_message_enter_dict_entry(
+ sd_bus_message *m,
+ struct bus_container *c,
+ const char *contents) {
+
+ size_t l;
+ int r;
+
+ assert(m);
+ assert(c);
+ assert(contents);
+
+ if (!signature_is_pair(contents))
+ return -EINVAL;
+
+ if (c->enclosing != SD_BUS_TYPE_ARRAY)
+ return -ENXIO;
+
+ if (!c->signature || c->signature[c->index] == 0)
+ return 0;
+
+ l = strlen(contents);
+
+ if (c->signature[c->index] != SD_BUS_TYPE_DICT_ENTRY_BEGIN ||
+ !startswith(c->signature + c->index + 1, contents) ||
+ c->signature[c->index + 1 + l] != SD_BUS_TYPE_DICT_ENTRY_END)
+ return -ENXIO;
+
+ r = message_peek_body(m, &m->rindex, 8, 0, NULL);
+ if (r <= 0)
+ return r;
+
+ if (c->enclosing != SD_BUS_TYPE_ARRAY)
+ c->index += 1 + l + 1;
+
+ return 1;
+}
+
+int sd_bus_message_enter_container(sd_bus_message *m, char type, const char *contents) {
+ struct bus_container *c, *w;
+ uint32_t *array_size = NULL;
+ char *signature;
+ int r;
+
+ if (!m)
+ return -EINVAL;
+ if (!m->sealed)
+ return -EPERM;
+ if (!contents)
+ return -EINVAL;
+
+ /*
+ * We enforce a global limit on container depth, that is much
+ * higher than the 32 structs and 32 arrays the specification
+ * mandates. This is simpler to implement for us, and we need
+ * this only to ensure our container array doesn't grow
+ * without bounds. We are happy to return any data from a
+ * message as long as the data itself is valid, even if the
+ * overall message might be not.
+ *
+ * Note that the message signature is validated when
+ * parsing the headers, and that validation does check the
+ * 32/32 limit.
+ *
+ * Note that the specification defines no limits on the depth
+ * of stacked variants, but we do.
+ */
+ if (m->n_containers >= BUS_CONTAINER_DEPTH)
+ return -EBADMSG;
+
+ w = realloc(m->containers, sizeof(struct bus_container) * (m->n_containers + 1));
+ if (!w)
+ return -ENOMEM;
+ m->containers = w;
+
+ c = message_get_container(m);
+
+ if (!c->signature || c->signature[c->index] == 0)
+ return 0;
+
+ signature = strdup(contents);
+ if (!signature)
+ return -ENOMEM;
+
+ if (type == SD_BUS_TYPE_ARRAY)
+ r = bus_message_enter_array(m, c, contents, &array_size);
+ else if (type == SD_BUS_TYPE_VARIANT)
+ r = bus_message_enter_variant(m, c, contents);
+ else if (type == SD_BUS_TYPE_STRUCT)
+ r = bus_message_enter_struct(m, c, contents);
+ else if (type == SD_BUS_TYPE_DICT_ENTRY)
+ r = bus_message_enter_dict_entry(m, c, contents);
+ else
+ r = -EINVAL;
+
+ if (r <= 0) {
+ free(signature);
+ return r;
+ }
+
+ /* OK, let's fill it in */
+ w += m->n_containers++;
+ w->enclosing = type;
+ w->signature = signature;
+ w->index = 0;
+ w->array_size = array_size;
+ w->begin = m->rindex;
+
+ return 1;
+}
+
+int sd_bus_message_exit_container(sd_bus_message *m) {
+ struct bus_container *c;
+
+ if (!m)
+ return -EINVAL;
+ if (!m->sealed)
+ return -EPERM;
+ if (m->n_containers <= 0)
+ return -EINVAL;
+
+ c = message_get_container(m);
+ if (c->enclosing == SD_BUS_TYPE_ARRAY) {
+ uint32_t l;
+
+ l = BUS_MESSAGE_BSWAP32(m, *c->array_size);
+ if (c->begin + l != m->rindex)
+ return -EBUSY;
+
+ } else {
+ if (c->signature && c->signature[c->index] != 0)
+ return -EINVAL;
+ }
+
+ free(c->signature);
+ m->n_containers--;
+
+ return 1;
+}
+
+int sd_bus_message_peek_type(sd_bus_message *m, char *type, const char **contents) {
+ struct bus_container *c;
+ int r;
+
+ if (!m)
+ return -EINVAL;
+ if (!m->sealed)
+ return -EPERM;
+
+ c = message_get_container(m);
+
+ if (!c->signature || c->signature[c->index] == 0)
+ goto eof;
+
+ if (message_end_of_array(m, m->rindex))
+ goto eof;
+
+ if (bus_type_is_basic(c->signature[c->index])) {
+ if (contents)
+ *contents = NULL;
+ if (type)
+ *type = c->signature[c->index];
+ return 1;
+ }
+
+ if (c->signature[c->index] == SD_BUS_TYPE_ARRAY) {
+
+ if (contents) {
+ size_t l;
+ char *sig;
+
+ r = signature_element_length(c->signature+c->index+1, &l);
+ if (r < 0)
+ return r;
+
+ assert(l >= 1);
+
+ sig = strndup(c->signature + c->index + 1, l);
+ if (!sig)
+ return -ENOMEM;
+
+ free(m->peeked_signature);
+ m->peeked_signature = sig;
+
+ *contents = sig;
+ }
+
+ if (type)
+ *type = SD_BUS_TYPE_ARRAY;
+
+ return 1;
+ }
+
+ if (c->signature[c->index] == SD_BUS_TYPE_STRUCT_BEGIN ||
+ c->signature[c->index] == SD_BUS_TYPE_DICT_ENTRY_BEGIN) {
+
+ if (contents) {
+ size_t l;
+ char *sig;
+
+ r = signature_element_length(c->signature+c->index, &l);
+ if (r < 0)
+ return r;
+
+ assert(l >= 2);
+ sig = strndup(c->signature + c->index + 1, l - 2);
+ if (!sig)
+ return -ENOMEM;
+
+ free(m->peeked_signature);
+ m->peeked_signature = sig;
+
+ *contents = sig;
+ }
+
+ if (type)
+ *type = c->signature[c->index] == SD_BUS_TYPE_STRUCT_BEGIN ? SD_BUS_TYPE_STRUCT : SD_BUS_TYPE_DICT_ENTRY;
+
+ return 1;
+ }
+
+ if (c->signature[c->index] == SD_BUS_TYPE_VARIANT) {
+ if (contents) {
+ size_t rindex, l;
+ void *q;
+
+ rindex = m->rindex;
+ r = message_peek_body(m, &rindex, 1, 1, &q);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ goto eof;
+
+ l = *(uint8_t*) q;
+ r = message_peek_body(m, &rindex, 1, l+1, &q);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return -EBADMSG;
+
+ if (!validate_signature(q, l))
+ return -EBADMSG;
+
+ *contents = q;
+ }
+
+ if (type)
+ *type = SD_BUS_TYPE_VARIANT;
+
+ return 1;
+ }
+
+ return -EINVAL;
+
+eof:
+ if (type)
+ *type = c->enclosing;
+ if (contents)
+ *contents = NULL;
+ return 0;
+}
+
+int sd_bus_message_rewind(sd_bus_message *m, int complete) {
+ struct bus_container *c;
+
+ if (!m)
+ return -EINVAL;
+ if (!m->sealed)
+ return -EPERM;
+
+ if (complete) {
+ reset_containers(m);
+ m->rindex = 0;
+ m->root_container.index = 0;
+
+ c = message_get_container(m);
+ } else {
+ c = message_get_container(m);
+
+ c->index = 0;
+ m->rindex = c->begin;
+ }
+
+ return !isempty(c->signature);
+}
+static int message_read_ap(
+ sd_bus_message *m,
+ const char *types,
+ va_list ap) {
+
+ unsigned n_array, n_struct;
+ TypeStack stack[BUS_CONTAINER_DEPTH];
+ unsigned stack_ptr = 0;
+ int r;
+
+ assert(m);
+
+ if (!types)
+ return 0;
+
+ /* Ideally, we'd just call ourselves recursively on every
+ * complex type. However, the state of a va_list that is
+ * passed to a function is undefined after that function
+ * returns. This means we need to docode the va_list linearly
+ * in a single stackframe. We hence implement our own
+ * home-grown stack in an array. */
+
+ n_array = (unsigned) -1;
+ n_struct = strlen(types);
+
+ for (;;) {
+ const char *t;
+
+ if (n_array == 0 || (n_array == (unsigned) -1 && n_struct == 0)) {
+ r = type_stack_pop(stack, ELEMENTSOF(stack), &stack_ptr, &types, &n_struct, &n_array);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ break;
+
+ r = sd_bus_message_exit_container(m);
+ if (r < 0)
+ return r;
+
+ continue;
+ }
+
+ t = types;
+ if (n_array != (unsigned) -1)
+ n_array --;
+ else {
+ types ++;
+ n_struct--;
+ }
+
+ switch (*t) {
+
+ case SD_BUS_TYPE_BYTE:
+ case SD_BUS_TYPE_BOOLEAN:
+ case SD_BUS_TYPE_INT16:
+ case SD_BUS_TYPE_UINT16:
+ case SD_BUS_TYPE_INT32:
+ case SD_BUS_TYPE_UINT32:
+ case SD_BUS_TYPE_INT64:
+ case SD_BUS_TYPE_UINT64:
+ case SD_BUS_TYPE_DOUBLE:
+ case SD_BUS_TYPE_STRING:
+ case SD_BUS_TYPE_OBJECT_PATH:
+ case SD_BUS_TYPE_SIGNATURE:
+ case SD_BUS_TYPE_UNIX_FD: {
+ void *p;
+
+ p = va_arg(ap, void*);
+ r = sd_bus_message_read_basic(m, *t, p);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return -ENXIO;
+
+ break;
+ }
+
+ case SD_BUS_TYPE_ARRAY: {
+ size_t k;
+
+ r = signature_element_length(t + 1, &k);
+ if (r < 0)
+ return r;
+
+ {
+ char s[k + 1];
+ memcpy(s, t + 1, k);
+ s[k] = 0;
+
+ r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, s);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return -ENXIO;
+ }
+
+ if (n_array == (unsigned) -1) {
+ types += k;
+ n_struct -= k;
+ }
+
+ r = type_stack_push(stack, ELEMENTSOF(stack), &stack_ptr, types, n_struct, n_array);
+ if (r < 0)
+ return r;
+
+ types = t + 1;
+ n_struct = k;
+ n_array = va_arg(ap, unsigned);
+
+ break;
+ }
+
+ case SD_BUS_TYPE_VARIANT: {
+ const char *s;
+
+ s = va_arg(ap, const char *);
+ if (!s)
+ return -EINVAL;
+
+ r = sd_bus_message_enter_container(m, SD_BUS_TYPE_VARIANT, s);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return -ENXIO;
+
+ r = type_stack_push(stack, ELEMENTSOF(stack), &stack_ptr, types, n_struct, n_array);
+ if (r < 0)
+ return r;
+
+ types = s;
+ n_struct = strlen(s);
+ n_array = (unsigned) -1;
+
+ break;
+ }
+
+ case SD_BUS_TYPE_STRUCT_BEGIN:
+ case SD_BUS_TYPE_DICT_ENTRY_BEGIN: {
+ size_t k;
+
+ r = signature_element_length(t, &k);
+ if (r < 0)
+ return r;
+
+ {
+ char s[k - 1];
+ memcpy(s, t + 1, k - 2);
+ s[k - 2] = 0;
+
+ r = sd_bus_message_enter_container(m, *t == SD_BUS_TYPE_STRUCT_BEGIN ? SD_BUS_TYPE_STRUCT : SD_BUS_TYPE_DICT_ENTRY, s);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return -ENXIO;
+ }
+
+ if (n_array == (unsigned) -1) {
+ types += k - 1;
+ n_struct -= k - 1;
+ }
+
+ r = type_stack_push(stack, ELEMENTSOF(stack), &stack_ptr, types, n_struct, n_array);
+ if (r < 0)
+ return r;
+
+ types = t + 1;
+ n_struct = k - 2;
+ n_array = (unsigned) -1;
+
+ break;
+ }
+
+ default:
+ return -EINVAL;
+ }
+ }
+
+ return 1;
+}
+
+int sd_bus_message_read(sd_bus_message *m, const char *types, ...) {
+ va_list ap;
+ int r;
+
+ if (!m)
+ return -EINVAL;
+ if (!m->sealed)
+ return -EPERM;
+ if (!types)
+ return -EINVAL;
+
+ va_start(ap, types);
+ r = message_read_ap(m, types, ap);
+ va_end(ap);
+
+ return r;
+}
+
+static int message_peek_fields(
+ sd_bus_message *m,
+ size_t *rindex,
+ size_t align,
+ size_t nbytes,
+ void **ret) {
+
+ assert(m);
+ assert(rindex);
+ assert(align > 0);
+
+ return buffer_peek(m->fields, BUS_MESSAGE_FIELDS_SIZE(m), rindex, align, nbytes, ret);
+}
+
+static int message_peek_field_uint32(
+ sd_bus_message *m,
+ size_t *ri,
+ uint32_t *ret) {
+
+ int r;
+ void *q;
+
+ assert(m);
+ assert(ri);
+
+ r = message_peek_fields(m, ri, 4, 4, &q);
+ if (r < 0)
+ return r;
+
+ if (ret)
+ *ret = BUS_MESSAGE_BSWAP32(m, *(uint32_t*) q);
+
+ return 0;
+}
+
+static int message_peek_field_string(
+ sd_bus_message *m,
+ bool (*validate)(const char *p),
+ size_t *ri,
+ const char **ret) {
+
+ uint32_t l;
+ int r;
+ void *q;
+
+ assert(m);
+ assert(ri);
+
+ r = message_peek_field_uint32(m, ri, &l);
+ if (r < 0)
+ return r;
+
+ r = message_peek_fields(m, ri, 1, l+1, &q);
+ if (r < 0)
+ return r;
+
+ if (validate) {
+ if (!validate_nul(q, l))
+ return -EBADMSG;
+
+ if (!validate(q))
+ return -EBADMSG;
+ } else {
+ if (!validate_string(q, l))
+ return -EBADMSG;
+ }
+
+ if (ret)
+ *ret = q;
+
+ return 0;
+}
+
+static int message_peek_field_signature(
+ sd_bus_message *m,
+ size_t *ri,
+ const char **ret) {
+
+ size_t l;
+ int r;
+ void *q;
+
+ assert(m);
+ assert(ri);
+
+ r = message_peek_fields(m, ri, 1, 1, &q);
+ if (r < 0)
+ return r;
+
+ l = *(uint8_t*) q;
+ r = message_peek_fields(m, ri, 1, l+1, &q);
+ if (r < 0)
+ return r;
+
+ if (!validate_signature(q, l))
+ return -EBADMSG;
+
+ if (ret)
+ *ret = q;
+
+ return 0;
+}
+
+static int message_skip_fields(
+ sd_bus_message *m,
+ size_t *ri,
+ uint32_t array_size,
+ const char **signature) {
+
+ size_t original_index;
+ int r;
+
+ assert(m);
+ assert(ri);
+ assert(signature);
+
+ original_index = *ri;
+
+ for (;;) {
+ char t;
+ size_t l;
+
+ if (array_size != (uint32_t) -1 &&
+ array_size <= *ri - original_index)
+ return 0;
+
+ t = **signature;
+ if (!t)
+ return 0;
+
+ if (t == SD_BUS_TYPE_STRING) {
+
+ r = message_peek_field_string(m, NULL, ri, NULL);
+ if (r < 0)
+ return r;
+
+ (*signature)++;
+
+ } else if (t == SD_BUS_TYPE_OBJECT_PATH) {
+
+ r = message_peek_field_string(m, object_path_is_valid, ri, NULL);
+ if (r < 0)
+ return r;
+
+ (*signature)++;
+
+ } else if (t == SD_BUS_TYPE_SIGNATURE) {
+
+ r = message_peek_field_signature(m, ri, NULL);
+ if (r < 0)
+ return r;
+
+ (*signature)++;
+
+ } else if (bus_type_is_basic(t)) {
+ ssize_t align, k;
+
+ align = bus_type_get_alignment(t);
+ k = bus_type_get_size(t);
+ assert(align > 0 && k > 0);
+
+ r = message_peek_fields(m, ri, align, k, NULL);
+ if (r < 0)
+ return r;
+
+ (*signature)++;
+
+ } else if (t == SD_BUS_TYPE_ARRAY) {
+
+ r = signature_element_length(*signature+1, &l);
+ if (r < 0)
+ return r;
+
+ assert(l >= 1);
+ {
+ char sig[l-1], *s;
+ uint32_t nas;
+ int alignment;
+
+ strncpy(sig, *signature + 1, l-1);
+ s = sig;
+
+ alignment = bus_type_get_alignment(sig[0]);
+ if (alignment < 0)
+ return alignment;
+
+ r = message_peek_field_uint32(m, ri, &nas);
+ if (r < 0)
+ return r;
+ if (nas > BUS_ARRAY_MAX_SIZE)
+ return -EBADMSG;
+
+ r = message_peek_fields(m, ri, alignment, 0, NULL);
+ if (r < 0)
+ return r;
+
+ r = message_skip_fields(m, ri, nas, (const char**) &s);
+ if (r < 0)
+ return r;
+ }
+
+ (*signature) += 1 + l;
+
+ } else if (t == SD_BUS_TYPE_VARIANT) {
+ const char *s;
+
+ r = message_peek_field_signature(m, ri, &s);
+ if (r < 0)
+ return r;
+
+ r = message_skip_fields(m, ri, (uint32_t) -1, (const char**) &s);
+ if (r < 0)
+ return r;
+
+ (*signature)++;
+
+ } else if (t == SD_BUS_TYPE_STRUCT ||
+ t == SD_BUS_TYPE_DICT_ENTRY) {
+
+ r = signature_element_length(*signature, &l);
+ if (r < 0)
+ return r;
+
+ assert(l >= 2);
+ {
+ char sig[l-1], *s;
+ strncpy(sig, *signature + 1, l-1);
+ s = sig;
+
+ r = message_skip_fields(m, ri, (uint32_t) -1, (const char**) &s);
+ if (r < 0)
+ return r;
+ }
+
+ *signature += l;
+ } else
+ return -EINVAL;
+ }
+}
+
+int bus_message_parse_fields(sd_bus_message *m) {
+ size_t ri;
+ int r;
+ uint32_t unix_fds = 0;
+
+ assert(m);
+
+ for (ri = 0; ri < BUS_MESSAGE_FIELDS_SIZE(m); ) {
+ const char *signature;
+ uint8_t *header;
+
+ r = message_peek_fields(m, &ri, 8, 1, (void**) &header);
+ if (r < 0)
+ return r;
+
+ r = message_peek_field_signature(m, &ri, &signature);
+ if (r < 0)
+ return r;
+
+ switch (*header) {
+ case _SD_BUS_MESSAGE_HEADER_INVALID:
+ return -EBADMSG;
+
+ case SD_BUS_MESSAGE_HEADER_PATH:
+
+ if (m->path)
+ return -EBADMSG;
+
+ if (!streq(signature, "o"))
+ return -EBADMSG;
+
+ r = message_peek_field_string(m, object_path_is_valid, &ri, &m->path);
+ break;
+
+ case SD_BUS_MESSAGE_HEADER_INTERFACE:
+
+ if (m->interface)
+ return -EBADMSG;
+
+ if (!streq(signature, "s"))
+ return -EBADMSG;
+
+ r = message_peek_field_string(m, interface_name_is_valid, &ri, &m->interface);
+ break;
+
+ case SD_BUS_MESSAGE_HEADER_MEMBER:
+
+ if (m->member)
+ return -EBADMSG;
+
+ if (!streq(signature, "s"))
+ return -EBADMSG;
+
+ r = message_peek_field_string(m, member_name_is_valid, &ri, &m->member);
+ break;
+
+ case SD_BUS_MESSAGE_HEADER_ERROR_NAME:
+
+ if (m->error.name)
+ return -EBADMSG;
+
+ if (!streq(signature, "s"))
+ return -EBADMSG;
+
+ r = message_peek_field_string(m, error_name_is_valid, &ri, &m->error.name);
+ break;
+
+ case SD_BUS_MESSAGE_HEADER_DESTINATION:
+
+ if (m->destination)
+ return -EBADMSG;
+
+ if (!streq(signature, "s"))
+ return -EBADMSG;
+
+ r = message_peek_field_string(m, service_name_is_valid, &ri, &m->destination);
+ break;
+
+ case SD_BUS_MESSAGE_HEADER_SENDER:
+
+ if (m->sender)
+ return -EBADMSG;
+
+ if (!streq(signature, "s"))
+ return -EBADMSG;
+
+ r = message_peek_field_string(m, service_name_is_valid, &ri, &m->sender);
+ break;
+
+
+ case SD_BUS_MESSAGE_HEADER_SIGNATURE: {
+ const char *s;
+ char *c;
+
+ if (m->root_container.signature)
+ return -EBADMSG;
+
+ if (!streq(signature, "g"))
+ return -EBADMSG;
+
+ r = message_peek_field_signature(m, &ri, &s);
+ if (r < 0)
+ return r;
+
+ c = strdup(s);
+ if (!c)
+ return -ENOMEM;
+
+ free(m->root_container.signature);
+ m->root_container.signature = c;
+ break;
+ }
+
+ case SD_BUS_MESSAGE_HEADER_REPLY_SERIAL:
+ if (m->reply_serial != 0)
+ return -EBADMSG;
+
+ if (!streq(signature, "u"))
+ return -EBADMSG;
+
+ r = message_peek_field_uint32(m, &ri, &m->reply_serial);
+ if (r < 0)
+ return r;
+
+ if (m->reply_serial == 0)
+ return -EBADMSG;
+
+ break;
+
+ case SD_BUS_MESSAGE_HEADER_UNIX_FDS:
+ if (unix_fds != 0)
+ return -EBADMSG;
+
+ if (!streq(signature, "u"))
+ return -EBADMSG;
+
+ r = message_peek_field_uint32(m, &ri, &unix_fds);
+ if (r < 0)
+ return -EBADMSG;
+
+ if (unix_fds == 0)
+ return -EBADMSG;
+
+ break;
+
+ default:
+ r = message_skip_fields(m, &ri, (uint32_t) -1, (const char **) &signature);
+ }
+
+ if (r < 0)
+ return r;
+ }
+
+ if (m->n_fds != unix_fds)
+ return -EBADMSG;
+
+ if (isempty(m->root_container.signature) != (BUS_MESSAGE_BODY_SIZE(m) == 0))
+ return -EBADMSG;
+
+ switch (m->header->type) {
+
+ case SD_BUS_MESSAGE_TYPE_SIGNAL:
+ if (!m->path || !m->interface || !m->member)
+ return -EBADMSG;
+ break;
+
+ case SD_BUS_MESSAGE_TYPE_METHOD_CALL:
+
+ if (!m->path || !m->member)
+ return -EBADMSG;
+
+ break;
+
+ case SD_BUS_MESSAGE_TYPE_METHOD_RETURN:
+
+ if (m->reply_serial == 0)
+ return -EBADMSG;
+ break;
+
+ case SD_BUS_MESSAGE_TYPE_METHOD_ERROR:
+
+ if (m->reply_serial == 0 || !m->error.name)
+ return -EBADMSG;
+ break;
+ }
+
+ /* Try to read the error message, but if we can't it's a non-issue */
+ if (m->header->type == SD_BUS_MESSAGE_TYPE_METHOD_ERROR)
+ sd_bus_message_read(m, "s", &m->error.message);
+
+ return 0;
+}
+
+int bus_message_seal(sd_bus_message *m, uint64_t serial) {
+ int r;
+ size_t l, a;
+
+ assert(m);
+
+ if (m->sealed)
+ return -EPERM;
+
+ if (m->n_containers > 0)
+ return -EBADMSG;
+
+ /* If there's a non-trivial signature set, then add it in here */
+ if (!isempty(m->root_container.signature)) {
+ r = message_append_field_signature(m, SD_BUS_MESSAGE_HEADER_SIGNATURE, m->root_container.signature, NULL);
+ if (r < 0)
+ return r;
+ }
+
+ if (m->n_fds > 0) {
+ r = message_append_field_uint32(m, SD_BUS_MESSAGE_HEADER_UNIX_FDS, m->n_fds);
+ if (r < 0)
+ return r;
+ }
+
+ l = BUS_MESSAGE_FIELDS_SIZE(m);
+ a = ALIGN8(l) - l;
+
+ if (a > 0) {
+ /* Add padding at the end, since we know the body
+ * needs to start at an 8 byte alignment. */
+ void *p;
+
+ p = message_extend_fields(m, 1, a);
+ if (!p)
+ return -ENOMEM;
+
+ memset(p, 0, a);
+ m->header->fields_size -= a;
+ }
+
+ m->header->serial = serial;
+ m->sealed = true;
+
+ return 0;
+}
+
+int sd_bus_message_set_destination(sd_bus_message *m, const char *destination) {
+ if (!m)
+ return -EINVAL;
+ if (!destination)
+ return -EINVAL;
+ if (m->sealed)
+ return -EPERM;
+ if (m->destination)
+ return -EEXIST;
+
+ return message_append_field_string(m, SD_BUS_MESSAGE_HEADER_DESTINATION, SD_BUS_TYPE_STRING, destination, &m->destination);
+}
+
+int bus_message_dump(sd_bus_message *m) {
+ const char *u = NULL, *uu = NULL, *s = NULL;
+ char **cmdline = NULL;
+ unsigned level = 1;
+ int r;
+ uid_t owner, audit_loginuid;
+ uint32_t audit_sessionid;
+
+ assert(m);
+
+ printf("Message %p\n"
+ "\tn_ref=%u\n"
+ "\tendian=%c\n"
+ "\ttype=%i\n"
+ "\tflags=%u\n"
+ "\tversion=%u\n"
+ "\tserial=%u\n"
+ "\tfields_size=%u\n"
+ "\tbody_size=%u\n"
+ "\tpath=%s\n"
+ "\tinterface=%s\n"
+ "\tmember=%s\n"
+ "\tdestination=%s\n"
+ "\tsender=%s\n"
+ "\tsignature=%s\n"
+ "\treply_serial=%u\n"
+ "\terror.name=%s\n"
+ "\terror.message=%s\n"
+ "\tsealed=%s\n",
+ m,
+ m->n_ref,
+ m->header->endian,
+ m->header->type,
+ m->header->flags,
+ m->header->version,
+ BUS_MESSAGE_SERIAL(m),
+ BUS_MESSAGE_FIELDS_SIZE(m),
+ BUS_MESSAGE_BODY_SIZE(m),
+ strna(m->path),
+ strna(m->interface),
+ strna(m->member),
+ strna(m->destination),
+ strna(m->sender),
+ strna(m->root_container.signature),
+ m->reply_serial,
+ strna(m->error.name),
+ strna(m->error.message),
+ yes_no(m->sealed));
+
+ if (m->pid != 0)
+ printf("\tpid=%lu\n", (unsigned long) m->pid);
+ if (m->tid != 0)
+ printf("\ttid=%lu\n", (unsigned long) m->tid);
+ if (m->uid_valid)
+ printf("\tuid=%lu\n", (unsigned long) m->uid);
+ if (m->gid_valid)
+ printf("\tgid=%lu\n", (unsigned long) m->gid);
+ if (m->pid_starttime != 0)
+ printf("\tpid_starttime=%llu\n", (unsigned long long) m->pid_starttime);
+ if (m->monotonic != 0)
+ printf("\tmonotonic=%llu\n", (unsigned long long) m->monotonic);
+ if (m->realtime != 0)
+ printf("\trealtime=%llu\n", (unsigned long long) m->realtime);
+ if (m->exe)
+ printf("\texe=[%s]\n", m->exe);
+ if (m->comm)
+ printf("\tcomm=[%s]\n", m->comm);
+ if (m->tid_comm)
+ printf("\ttid_comm=[%s]\n", m->tid_comm);
+ if (m->label)
+ printf("\tlabel=[%s]\n", m->label);
+ if (m->cgroup)
+ printf("\tcgroup=[%s]\n", m->cgroup);
+
+ sd_bus_message_get_unit(m, &u);
+ if (u)
+ printf("\tunit=[%s]\n", u);
+ sd_bus_message_get_user_unit(m, &uu);
+ if (uu)
+ printf("\tuser_unit=[%s]\n", uu);
+ sd_bus_message_get_session(m, &s);
+ if (s)
+ printf("\tsession=[%s]\n", s);
+ if (sd_bus_message_get_owner_uid(m, &owner) >= 0)
+ printf("\towner_uid=%lu\n", (unsigned long) owner);
+ if (sd_bus_message_get_audit_loginuid(m, &audit_loginuid) >= 0)
+ printf("\taudit_loginuid=%lu\n", (unsigned long) audit_loginuid);
+ if (sd_bus_message_get_audit_sessionid(m, &audit_sessionid) >= 0)
+ printf("\taudit_sessionid=%lu\n", (unsigned long) audit_sessionid);
+
+ printf("\tCAP_KILL=%i\n", sd_bus_message_has_effective_cap(m, 5));
+
+ if (sd_bus_message_get_cmdline(m, &cmdline) >= 0) {
+ char **c;
+
+ fputs("\tcmdline=[", stdout);
+ STRV_FOREACH(c, cmdline) {
+ if (c != cmdline)
+ putchar(' ');
+
+ fputs(*c, stdout);
+ }
+
+ fputs("]\n", stdout);
+ }
+
+ r = sd_bus_message_rewind(m, true);
+ if (r < 0) {
+ log_error("Failed to rewind: %s", strerror(-r));
+ return r;
+ }
+
+ printf("BEGIN_MESSAGE \"%s\" {\n", strempty(m->root_container.signature));
+
+ for(;;) {
+ _cleanup_free_ char *prefix = NULL;
+ const char *contents = NULL;
+ char type;
+ union {
+ uint8_t u8;
+ uint16_t u16;
+ int16_t s16;
+ uint32_t u32;
+ int32_t s32;
+ uint64_t u64;
+ int64_t s64;
+ double d64;
+ const char *string;
+ int i;
+ } basic;
+
+ r = sd_bus_message_peek_type(m, &type, &contents);
+ if (r < 0) {
+ log_error("Failed to peek type: %s", strerror(-r));
+ return r;
+ }
+ if (r == 0) {
+ if (level <= 1)
+ break;
+
+ r = sd_bus_message_exit_container(m);
+ if (r < 0) {
+ log_error("Failed to exit container: %s", strerror(-r));
+ return r;
+ }
+
+ level--;
+
+ prefix = strrep("\t", level);
+ if (!prefix)
+ return log_oom();
+
+ if (type == SD_BUS_TYPE_ARRAY)
+ printf("%s} END_ARRAY \n", prefix);
+ else if (type == SD_BUS_TYPE_VARIANT)
+ printf("%s} END_VARIANT\n", prefix);
+ else if (type == SD_BUS_TYPE_STRUCT)
+ printf("%s} END_STRUCT\n", prefix);
+ else if (type == SD_BUS_TYPE_DICT_ENTRY)
+ printf("%s} END_DICT_ENTRY\n", prefix);
+
+ continue;
+ }
+
+ prefix = strrep("\t", level);
+ if (!prefix)
+ return log_oom();
+
+ if (bus_type_is_container(type) > 0) {
+ r = sd_bus_message_enter_container(m, type, contents);
+ if (r < 0) {
+ log_error("Failed to enter container: %s", strerror(-r));
+ return r;
+ }
+
+ if (type == SD_BUS_TYPE_ARRAY)
+ printf("%sBEGIN_ARRAY \"%s\" {\n", prefix, contents);
+ else if (type == SD_BUS_TYPE_VARIANT)
+ printf("%sBEGIN_VARIANT \"%s\" {\n", prefix, contents);
+ else if (type == SD_BUS_TYPE_STRUCT)
+ printf("%sBEGIN_STRUCT \"%s\" {\n", prefix, contents);
+ else if (type == SD_BUS_TYPE_DICT_ENTRY)
+ printf("%sBEGIN_DICT_ENTRY \"%s\" {\n", prefix, contents);
+
+ level ++;
+
+ continue;
+ }
+
+ r = sd_bus_message_read_basic(m, type, &basic);
+ if (r < 0) {
+ log_error("Failed to get basic: %s", strerror(-r));
+ return r;
+ }
+
+ switch (type) {
+
+ case SD_BUS_TYPE_BYTE:
+ printf("%sBYTE: %u\n", prefix, basic.u8);
+ break;
+
+ case SD_BUS_TYPE_BOOLEAN:
+ printf("%sBOOLEAN: %s\n", prefix, yes_no(basic.i));
+ break;
+
+ case SD_BUS_TYPE_INT16:
+ printf("%sINT16: %i\n", prefix, basic.s16);
+ break;
+
+ case SD_BUS_TYPE_UINT16:
+ printf("%sUINT16: %u\n", prefix, basic.u16);
+ break;
+
+ case SD_BUS_TYPE_INT32:
+ printf("%sINT32: %i\n", prefix, basic.s32);
+ break;
+
+ case SD_BUS_TYPE_UINT32:
+ printf("%sUINT32: %u\n", prefix, basic.u32);
+ break;
+
+ case SD_BUS_TYPE_INT64:
+ printf("%sINT64: %lli\n", prefix, (long long) basic.s64);
+ break;
+
+ case SD_BUS_TYPE_UINT64:
+ printf("%sUINT64: %llu\n", prefix, (unsigned long long) basic.u64);
+ break;
+
+ case SD_BUS_TYPE_DOUBLE:
+ printf("%sDOUBLE: %g\n", prefix, basic.d64);
+ break;
+
+ case SD_BUS_TYPE_STRING:
+ printf("%sSTRING: \"%s\"\n", prefix, basic.string);
+ break;
+
+ case SD_BUS_TYPE_OBJECT_PATH:
+ printf("%sOBJECT_PATH: \"%s\"\n", prefix, basic.string);
+ break;
+
+ case SD_BUS_TYPE_SIGNATURE:
+ printf("%sSIGNATURE: \"%s\"\n", prefix, basic.string);
+ break;
+
+ case SD_BUS_TYPE_UNIX_FD:
+ printf("%sUNIX_FD: %i\n", prefix, basic.i);
+ break;
+
+ default:
+ assert_not_reached("Unknown basic type.");
+ }
+ }
+
+ printf("} END_MESSAGE\n");
+ return 0;
+}
+
+int bus_message_get_blob(sd_bus_message *m, void **buffer, size_t *sz) {
+ size_t total;
+ void *p, *e;
+
+ assert(m);
+ assert(buffer);
+ assert(sz);
+
+ total = BUS_MESSAGE_SIZE(m);
+
+ p = malloc(total);
+ if (!p)
+ return -ENOMEM;
+
+ e = mempcpy(p, m->header, sizeof(*m->header));
+
+ if (m->fields) {
+ e = mempcpy(e, m->fields, m->header->fields_size);
+
+ if (m->header->fields_size % 8 != 0)
+ e = mempset(e, 0, 8 - (m->header->fields_size % 8));
+ }
+
+ if (m->body)
+ e = mempcpy(e, m->body, m->header->body_size);
+
+ assert(total == (size_t) ((uint8_t*) e - (uint8_t*) p));
+
+ *buffer = p;
+ *sz = total;
+
+ return 0;
+}
+
+int bus_message_read_strv_extend(sd_bus_message *m, char ***l) {
+ int r;
+
+ assert(m);
+ assert(l);
+
+ r = sd_bus_message_enter_container(m, 'a', "s");
+ if (r < 0)
+ return r;
+
+ for (;;) {
+ const char *s;
+
+ r = sd_bus_message_read_basic(m, 's', &s);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ break;
+
+ r = strv_extend(l, s);
+ if (r < 0)
+ return r;
+ }
+
+ r = sd_bus_message_exit_container(m);
+ if (r < 0)
+ return r;
+
+ return 0;
+}
+
+const char* bus_message_get_arg(sd_bus_message *m, unsigned i) {
+ int r;
+ const char *t = NULL;
+ unsigned j;
+
+ assert(m);
+
+ r = sd_bus_message_rewind(m, true);
+ if (r < 0)
+ return NULL;
+
+ for (j = 0; j <= i; j++) {
+ char type;
+
+ r = sd_bus_message_peek_type(m, &type, NULL);
+ if (r < 0)
+ return NULL;
+
+ if (type != SD_BUS_TYPE_STRING &&
+ type != SD_BUS_TYPE_OBJECT_PATH &&
+ type != SD_BUS_TYPE_SIGNATURE)
+ return NULL;
+
+ r = sd_bus_message_read_basic(m, type, &t);
+ if (r < 0)
+ return NULL;
+ }
+
+ return t;
+}
+
+int bus_header_size(struct bus_header *h, size_t *sum) {
+ size_t fs, bs;
+
+ assert(h);
+ assert(sum);
+
+ if (h->endian == SD_BUS_NATIVE_ENDIAN) {
+ fs = h->fields_size;
+ bs = h->body_size;
+ } else if (h->endian == SD_BUS_REVERSE_ENDIAN) {
+ fs = bswap_32(h->fields_size);
+ bs = bswap_32(h->body_size);
+ } else
+ return -EBADMSG;
+
+ *sum = sizeof(struct bus_header) + ALIGN8(fs) + bs;
+ return 0;
+}
diff --git a/src/libsystemd-bus/bus-message.h b/src/libsystemd-bus/bus-message.h
new file mode 100644
index 0000000000..9c0829c7fa
--- /dev/null
+++ b/src/libsystemd-bus/bus-message.h
@@ -0,0 +1,198 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdbool.h>
+#include <byteswap.h>
+#include <sys/socket.h>
+
+#include "macro.h"
+#include "sd-bus.h"
+#include "kdbus.h"
+#include "time-util.h"
+
+struct bus_container {
+ char enclosing;
+
+ char *signature;
+ unsigned index;
+
+ uint32_t *array_size;
+ size_t begin;
+};
+
+struct bus_header {
+ uint8_t endian;
+ uint8_t type;
+ uint8_t flags;
+ uint8_t version;
+ uint32_t body_size;
+ uint32_t serial;
+ uint32_t fields_size;
+} _packed_;
+
+struct sd_bus_message {
+ unsigned n_ref;
+
+ uint32_t reply_serial;
+
+ const char *path;
+ const char *interface;
+ const char *member;
+ const char *destination;
+ const char *sender;
+
+ sd_bus_error error;
+
+ uid_t uid;
+ gid_t gid;
+ pid_t pid;
+ pid_t tid;
+ usec_t pid_starttime;
+ usec_t monotonic;
+ usec_t realtime;
+
+ bool sealed:1;
+ bool dont_send:1;
+ bool allow_fds:1;
+ bool uid_valid:1;
+ bool gid_valid:1;
+ bool free_header:1;
+ bool free_fields:1;
+ bool free_body:1;
+ bool free_kdbus:1;
+ bool free_fds:1;
+
+ struct bus_header *header;
+ void *fields;
+ void *body;
+ struct kdbus_msg *kdbus;
+
+ char *label;
+
+ size_t rindex;
+
+ uint32_t n_fds;
+ int *fds;
+
+ struct bus_container root_container, *containers;
+ unsigned n_containers;
+
+ struct iovec iovec[3];
+ unsigned n_iovec;
+
+ char *peeked_signature;
+
+ usec_t timeout;
+
+ char sender_buffer[3 + DECIMAL_STR_MAX(uint64_t) + 1];
+ char destination_buffer[3 + DECIMAL_STR_MAX(uint64_t) + 1];
+
+ const char *exe;
+ const char *comm;
+ const char *tid_comm;
+ const char *cgroup;
+
+ const char *cmdline;
+ size_t cmdline_length;
+ char **cmdline_array;
+
+ char *session;
+ char *unit;
+ char *user_unit;
+
+ struct kdbus_audit *audit;
+
+ uint8_t *capability;
+ size_t capability_size;
+};
+
+#define BUS_MESSAGE_NEED_BSWAP(m) ((m)->header->endian != SD_BUS_NATIVE_ENDIAN)
+
+static inline uint16_t BUS_MESSAGE_BSWAP16(sd_bus_message *m, uint16_t u) {
+ return BUS_MESSAGE_NEED_BSWAP(m) ? bswap_16(u) : u;
+}
+
+static inline uint32_t BUS_MESSAGE_BSWAP32(sd_bus_message *m, uint32_t u) {
+ return BUS_MESSAGE_NEED_BSWAP(m) ? bswap_32(u) : u;
+}
+
+static inline uint64_t BUS_MESSAGE_BSWAP64(sd_bus_message *m, uint64_t u) {
+ return BUS_MESSAGE_NEED_BSWAP(m) ? bswap_64(u) : u;
+}
+
+static inline uint32_t BUS_MESSAGE_SERIAL(sd_bus_message *m) {
+ return BUS_MESSAGE_BSWAP32(m, m->header->serial);
+}
+
+static inline uint32_t BUS_MESSAGE_BODY_SIZE(sd_bus_message *m) {
+ return BUS_MESSAGE_BSWAP32(m, m->header->body_size);
+}
+
+static inline uint32_t BUS_MESSAGE_FIELDS_SIZE(sd_bus_message *m) {
+ return BUS_MESSAGE_BSWAP32(m, m->header->fields_size);
+}
+
+static inline uint32_t BUS_MESSAGE_SIZE(sd_bus_message *m) {
+ return
+ sizeof(struct bus_header) +
+ ALIGN8(BUS_MESSAGE_FIELDS_SIZE(m)) +
+ BUS_MESSAGE_BODY_SIZE(m);
+}
+
+static inline void bus_message_unrefp(sd_bus_message **m) {
+ sd_bus_message_unref(*m);
+}
+
+#define _cleanup_bus_message_unref_ __attribute__((cleanup(bus_message_unrefp)))
+
+int bus_message_seal(sd_bus_message *m, uint64_t serial);
+int bus_message_dump(sd_bus_message *m);
+int bus_message_get_blob(sd_bus_message *m, void **buffer, size_t *sz);
+int bus_message_read_strv_extend(sd_bus_message *m, char ***l);
+
+int bus_message_from_header(
+ void *header,
+ size_t length,
+ int *fds,
+ unsigned n_fds,
+ const struct ucred *ucred,
+ const char *label,
+ size_t extra,
+ sd_bus_message **ret);
+
+int bus_message_from_malloc(
+ void *buffer,
+ size_t length,
+ int *fds,
+ unsigned n_fds,
+ const struct ucred *ucred,
+ const char *label,
+ sd_bus_message **ret);
+
+const char* bus_message_get_arg(sd_bus_message *m, unsigned i);
+
+int bus_message_append_ap(sd_bus_message *m, const char *types, va_list ap);
+
+int bus_message_parse_fields(sd_bus_message *m);
+
+int bus_header_size(struct bus_header *h, size_t *sum);
diff --git a/src/libsystemd-bus/bus-signature.c b/src/libsystemd-bus/bus-signature.c
new file mode 100644
index 0000000000..a92b7124c3
--- /dev/null
+++ b/src/libsystemd-bus/bus-signature.c
@@ -0,0 +1,153 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <util.h>
+
+#include "bus-signature.h"
+#include "bus-type.h"
+
+static int signature_element_length_internal(
+ const char *s,
+ bool allow_dict_entry,
+ unsigned array_depth,
+ unsigned struct_depth,
+ size_t *l) {
+
+ int r;
+
+ assert(s);
+
+ if (bus_type_is_basic(*s) || *s == SD_BUS_TYPE_VARIANT) {
+ *l = 1;
+ return 0;
+ }
+
+ if (*s == SD_BUS_TYPE_ARRAY) {
+ size_t t;
+
+ if (array_depth >= 32)
+ return -EINVAL;
+
+ r = signature_element_length_internal(s + 1, true, array_depth+1, struct_depth, &t);
+ if (r < 0)
+ return r;
+
+ *l = t + 1;
+ return 0;
+ }
+
+ if (*s == SD_BUS_TYPE_STRUCT_BEGIN) {
+ const char *p = s + 1;
+
+ if (struct_depth >= 32)
+ return -EINVAL;
+
+ while (*p != SD_BUS_TYPE_STRUCT_END) {
+ size_t t;
+
+ r = signature_element_length_internal(p, false, array_depth, struct_depth+1, &t);
+ if (r < 0)
+ return r;
+
+ p += t;
+ }
+
+ *l = p - s + 1;
+ return 0;
+ }
+
+ if (*s == SD_BUS_TYPE_DICT_ENTRY_BEGIN && allow_dict_entry) {
+ const char *p = s + 1;
+ unsigned n = 0;
+
+ if (struct_depth >= 32)
+ return -EINVAL;
+
+ while (*p != SD_BUS_TYPE_DICT_ENTRY_END) {
+ size_t t;
+
+ if (n == 0 && !bus_type_is_basic(*p))
+ return -EINVAL;
+
+ r = signature_element_length_internal(p, false, array_depth, struct_depth+1, &t);
+ if (r < 0)
+ return r;
+
+ p += t;
+ n++;
+ }
+
+ if (n != 2)
+ return -EINVAL;
+
+ *l = p - s + 1;
+ return 0;
+ }
+
+ return -EINVAL;
+}
+
+
+int signature_element_length(const char *s, size_t *l) {
+ return signature_element_length_internal(s, true, 0, 0, l);
+}
+
+bool signature_is_single(const char *s) {
+ int r;
+ size_t t;
+
+ assert(s);
+
+ r = signature_element_length(s, &t);
+ if (r < 0)
+ return false;
+
+ return s[t] == 0;
+}
+
+bool signature_is_pair(const char *s) {
+ assert(s);
+
+ if (!bus_type_is_basic(*s))
+ return false;
+
+ return signature_is_single(s + 1);
+}
+
+bool signature_is_valid(const char *s, bool allow_dict_entry) {
+ const char *p;
+ int r;
+
+ assert(s);
+
+ p = s;
+ while (*p) {
+ size_t t;
+
+ r = signature_element_length_internal(p, allow_dict_entry, 0, 0, &t);
+ if (r < 0)
+ return false;
+
+ p += t;
+ }
+
+ return p - s <= 255;
+}
diff --git a/src/libsystemd-bus/bus-signature.h b/src/libsystemd-bus/bus-signature.h
new file mode 100644
index 0000000000..4000e0612a
--- /dev/null
+++ b/src/libsystemd-bus/bus-signature.h
@@ -0,0 +1,31 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdbool.h>
+#include <sys/types.h>
+
+bool signature_is_single(const char *s);
+bool signature_is_pair(const char *s);
+bool signature_is_valid(const char *s, bool allow_dict_entry);
+
+int signature_element_length(const char *s, size_t *l);
diff --git a/src/libsystemd-bus/bus-socket.c b/src/libsystemd-bus/bus-socket.c
new file mode 100644
index 0000000000..8a86b02c68
--- /dev/null
+++ b/src/libsystemd-bus/bus-socket.c
@@ -0,0 +1,1059 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <endian.h>
+#include <assert.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <sys/poll.h>
+#include <byteswap.h>
+
+#include "util.h"
+#include "macro.h"
+#include "missing.h"
+#include "strv.h"
+#include "utf8.h"
+#include "sd-daemon.h"
+
+#include "sd-bus.h"
+#include "bus-socket.h"
+#include "bus-internal.h"
+#include "bus-message.h"
+
+static void iovec_advance(struct iovec iov[], unsigned *idx, size_t size) {
+
+ while (size > 0) {
+ struct iovec *i = iov + *idx;
+
+ if (i->iov_len > size) {
+ i->iov_base = (uint8_t*) i->iov_base + size;
+ i->iov_len -= size;
+ return;
+ }
+
+ size -= i->iov_len;
+
+ i->iov_base = NULL;
+ i->iov_len = 0;
+
+ (*idx) ++;
+ }
+}
+
+static void append_iovec(sd_bus_message *m, const void *p, size_t sz) {
+ assert(m);
+ assert(p);
+ assert(sz > 0);
+
+ m->iovec[m->n_iovec].iov_base = (void*) p;
+ m->iovec[m->n_iovec].iov_len = sz;
+ m->n_iovec++;
+}
+
+static void bus_message_setup_iovec(sd_bus_message *m) {
+ assert(m);
+ assert(m->sealed);
+
+ if (m->n_iovec > 0)
+ return;
+
+ append_iovec(m, m->header, sizeof(*m->header));
+
+ if (m->fields)
+ append_iovec(m, m->fields, ALIGN8(m->header->fields_size));
+
+ if (m->body)
+ append_iovec(m, m->body, m->header->body_size);
+}
+
+bool bus_socket_auth_needs_write(sd_bus *b) {
+
+ unsigned i;
+
+ if (b->auth_index >= ELEMENTSOF(b->auth_iovec))
+ return false;
+
+ for (i = b->auth_index; i < ELEMENTSOF(b->auth_iovec); i++) {
+ struct iovec *j = b->auth_iovec + i;
+
+ if (j->iov_len > 0)
+ return true;
+ }
+
+ return false;
+}
+
+static int bus_socket_write_auth(sd_bus *b) {
+ ssize_t k;
+
+ assert(b);
+ assert(b->state == BUS_AUTHENTICATING);
+
+ if (!bus_socket_auth_needs_write(b))
+ return 0;
+
+ if (b->prefer_writev)
+ k = writev(b->output_fd, b->auth_iovec + b->auth_index, ELEMENTSOF(b->auth_iovec) - b->auth_index);
+ else {
+ struct msghdr mh;
+ zero(mh);
+
+ mh.msg_iov = b->auth_iovec + b->auth_index;
+ mh.msg_iovlen = ELEMENTSOF(b->auth_iovec) - b->auth_index;
+
+ k = sendmsg(b->output_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL);
+ if (k < 0 && errno == ENOTSOCK) {
+ b->prefer_writev = true;
+ k = writev(b->output_fd, b->auth_iovec + b->auth_index, ELEMENTSOF(b->auth_iovec) - b->auth_index);
+ }
+ }
+
+ if (k < 0)
+ return errno == EAGAIN ? 0 : -errno;
+
+ iovec_advance(b->auth_iovec, &b->auth_index, (size_t) k);
+ return 1;
+}
+
+static int bus_socket_auth_verify_client(sd_bus *b) {
+ char *e, *f, *start;
+ sd_id128_t peer;
+ unsigned i;
+ int r;
+
+ assert(b);
+
+ /* We expect two response lines: "OK" and possibly
+ * "AGREE_UNIX_FD" */
+
+ e = memmem(b->rbuffer, b->rbuffer_size, "\r\n", 2);
+ if (!e)
+ return 0;
+
+ if (b->negotiate_fds) {
+ f = memmem(e + 2, b->rbuffer_size - (e - (char*) b->rbuffer) - 2, "\r\n", 2);
+ if (!f)
+ return 0;
+
+ start = f + 2;
+ } else {
+ f = NULL;
+ start = e + 2;
+ }
+
+ /* Nice! We got all the lines we need. First check the OK
+ * line */
+
+ if (e - (char*) b->rbuffer != 3 + 32)
+ return -EPERM;
+
+ if (memcmp(b->rbuffer, "OK ", 3))
+ return -EPERM;
+
+ b->auth = b->anonymous_auth ? BUS_AUTH_ANONYMOUS : BUS_AUTH_EXTERNAL;
+
+ for (i = 0; i < 32; i += 2) {
+ int x, y;
+
+ x = unhexchar(((char*) b->rbuffer)[3 + i]);
+ y = unhexchar(((char*) b->rbuffer)[3 + i + 1]);
+
+ if (x < 0 || y < 0)
+ return -EINVAL;
+
+ peer.bytes[i/2] = ((uint8_t) x << 4 | (uint8_t) y);
+ }
+
+ if (!sd_id128_equal(b->server_id, SD_ID128_NULL) &&
+ !sd_id128_equal(b->server_id, peer))
+ return -EPERM;
+
+ b->server_id = peer;
+
+ /* And possibly check the second line, too */
+
+ if (f)
+ b->can_fds =
+ (f - e == sizeof("\r\nAGREE_UNIX_FD") - 1) &&
+ memcmp(e + 2, "AGREE_UNIX_FD", sizeof("AGREE_UNIX_FD") - 1) == 0;
+
+ b->rbuffer_size -= (start - (char*) b->rbuffer);
+ memmove(b->rbuffer, start, b->rbuffer_size);
+
+ r = bus_start_running(b);
+ if (r < 0)
+ return r;
+
+ return 1;
+}
+
+static bool line_equals(const char *s, size_t m, const char *line) {
+ size_t l;
+
+ l = strlen(line);
+ if (l != m)
+ return false;
+
+ return memcmp(s, line, l) == 0;
+}
+
+static bool line_begins(const char *s, size_t m, const char *word) {
+ size_t l;
+
+ l = strlen(word);
+ if (m < l)
+ return false;
+
+ if (memcmp(s, word, l) != 0)
+ return false;
+
+ return m == l || (m > l && s[l] == ' ');
+}
+
+static int verify_anonymous_token(sd_bus *b, const char *p, size_t l) {
+ _cleanup_free_ char *token = NULL;
+
+ if (!b->anonymous_auth)
+ return 0;
+
+ if (l <= 0)
+ return 1;
+
+ assert(p[0] == ' ');
+ p++; l--;
+
+ if (l % 2 != 0)
+ return 0;
+ token = unhexmem(p, l);
+ if (!token)
+ return -ENOMEM;
+
+ if (memchr(token, 0, l/2))
+ return 0;
+
+ return !!utf8_is_valid(token);
+}
+
+static int verify_external_token(sd_bus *b, const char *p, size_t l) {
+ _cleanup_free_ char *token = NULL;
+ uid_t u;
+ int r;
+
+ /* We don't do any real authentication here. Instead, we if
+ * the owner of this bus wanted authentication he should have
+ * checked SO_PEERCRED before even creating the bus object. */
+
+ if (!b->anonymous_auth && !b->ucred_valid)
+ return 0;
+
+ if (l <= 0)
+ return 1;
+
+ assert(p[0] == ' ');
+ p++; l--;
+
+ if (l % 2 != 0)
+ return 0;
+
+ token = unhexmem(p, l);
+ if (!token)
+ return -ENOMEM;
+
+ if (memchr(token, 0, l/2))
+ return 0;
+
+ r = parse_uid(token, &u);
+ if (r < 0)
+ return 0;
+
+ /* We ignore the passed value if anonymous authentication is
+ * on anyway. */
+ if (!b->anonymous_auth && u != b->ucred.uid)
+ return 0;
+
+ return 1;
+}
+
+static int bus_socket_auth_write(sd_bus *b, const char *t) {
+ char *p;
+ size_t l;
+
+ assert(b);
+ assert(t);
+
+ /* We only make use of the first iovec */
+ assert(b->auth_index == 0 || b->auth_index == 1);
+
+ l = strlen(t);
+ p = malloc(b->auth_iovec[0].iov_len + l);
+ if (!p)
+ return -ENOMEM;
+
+ memcpy(p, b->auth_iovec[0].iov_base, b->auth_iovec[0].iov_len);
+ memcpy(p + b->auth_iovec[0].iov_len, t, l);
+
+ b->auth_iovec[0].iov_base = p;
+ b->auth_iovec[0].iov_len += l;
+
+ free(b->auth_buffer);
+ b->auth_buffer = p;
+ b->auth_index = 0;
+ return 0;
+}
+
+static int bus_socket_auth_write_ok(sd_bus *b) {
+ char t[3 + 32 + 2 + 1];
+
+ assert(b);
+
+ snprintf(t, sizeof(t), "OK " SD_ID128_FORMAT_STR "\r\n", SD_ID128_FORMAT_VAL(b->server_id));
+ char_array_0(t);
+
+ return bus_socket_auth_write(b, t);
+}
+
+static int bus_socket_auth_verify_server(sd_bus *b) {
+ char *e;
+ const char *line;
+ size_t l;
+ bool processed = false;
+ int r;
+
+ assert(b);
+
+ if (b->rbuffer_size < 1)
+ return 0;
+
+ /* First char must be a NUL byte */
+ if (*(char*) b->rbuffer != 0)
+ return -EIO;
+
+ if (b->rbuffer_size < 3)
+ return 0;
+
+ /* Begin with the first line */
+ if (b->auth_rbegin <= 0)
+ b->auth_rbegin = 1;
+
+ for (;;) {
+ /* Check if line is complete */
+ line = (char*) b->rbuffer + b->auth_rbegin;
+ e = memmem(line, b->rbuffer_size - b->auth_rbegin, "\r\n", 2);
+ if (!e)
+ return processed;
+
+ l = e - line;
+
+ if (line_begins(line, l, "AUTH ANONYMOUS")) {
+
+ r = verify_anonymous_token(b, line + 14, l - 14);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ r = bus_socket_auth_write(b, "REJECTED\r\n");
+ else {
+ b->auth = BUS_AUTH_ANONYMOUS;
+ r = bus_socket_auth_write_ok(b);
+ }
+
+ } else if (line_begins(line, l, "AUTH EXTERNAL")) {
+
+ r = verify_external_token(b, line + 13, l - 13);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ r = bus_socket_auth_write(b, "REJECTED\r\n");
+ else {
+ b->auth = BUS_AUTH_EXTERNAL;
+ r = bus_socket_auth_write_ok(b);
+ }
+
+ } else if (line_begins(line, l, "AUTH"))
+ r = bus_socket_auth_write(b, "REJECTED EXTERNAL ANONYMOUS\r\n");
+ else if (line_equals(line, l, "CANCEL") ||
+ line_begins(line, l, "ERROR")) {
+
+ b->auth = _BUS_AUTH_INVALID;
+ r = bus_socket_auth_write(b, "REJECTED\r\n");
+
+ } else if (line_equals(line, l, "BEGIN")) {
+
+ if (b->auth == _BUS_AUTH_INVALID)
+ r = bus_socket_auth_write(b, "ERROR\r\n");
+ else {
+ /* We can't leave from the auth phase
+ * before we haven't written
+ * everything queued, so let's check
+ * that */
+
+ if (bus_socket_auth_needs_write(b))
+ return 1;
+
+ b->rbuffer_size -= (e + 2 - (char*) b->rbuffer);
+ memmove(b->rbuffer, e + 2, b->rbuffer_size);
+ return bus_start_running(b);
+ }
+
+ } else if (line_begins(line, l, "DATA")) {
+
+ if (b->auth == _BUS_AUTH_INVALID)
+ r = bus_socket_auth_write(b, "ERROR\r\n");
+ else {
+ if (b->auth == BUS_AUTH_ANONYMOUS)
+ r = verify_anonymous_token(b, line + 4, l - 4);
+ else
+ r = verify_external_token(b, line + 4, l - 4);
+
+ if (r < 0)
+ return r;
+ if (r == 0) {
+ b->auth = _BUS_AUTH_INVALID;
+ r = bus_socket_auth_write(b, "REJECTED\r\n");
+ } else
+ r = bus_socket_auth_write_ok(b);
+ }
+ } else if (line_equals(line, l, "NEGOTIATE_UNIX_FD")) {
+ if (b->auth == _BUS_AUTH_INVALID || !b->negotiate_fds)
+ r = bus_socket_auth_write(b, "ERROR\r\n");
+ else {
+ b->can_fds = true;
+ r = bus_socket_auth_write(b, "AGREE_UNIX_FD\r\n");
+ }
+ } else
+ r = bus_socket_auth_write(b, "ERROR\r\n");
+
+ if (r < 0)
+ return r;
+
+ b->auth_rbegin = e + 2 - (char*) b->rbuffer;
+
+ processed = true;
+ }
+}
+
+static int bus_socket_auth_verify(sd_bus *b) {
+ assert(b);
+
+ if (b->is_server)
+ return bus_socket_auth_verify_server(b);
+ else
+ return bus_socket_auth_verify_client(b);
+}
+
+static int bus_socket_read_auth(sd_bus *b) {
+ struct msghdr mh;
+ struct iovec iov;
+ size_t n;
+ ssize_t k;
+ int r;
+ void *p;
+ union {
+ struct cmsghdr cmsghdr;
+ uint8_t buf[CMSG_SPACE(sizeof(int) * BUS_FDS_MAX) +
+ CMSG_SPACE(sizeof(struct ucred)) +
+ CMSG_SPACE(NAME_MAX)]; /*selinux label */
+ } control;
+ struct cmsghdr *cmsg;
+ bool handle_cmsg = false;
+
+ assert(b);
+ assert(b->state == BUS_AUTHENTICATING);
+
+ r = bus_socket_auth_verify(b);
+ if (r != 0)
+ return r;
+
+ n = MAX(256u, b->rbuffer_size * 2);
+
+ if (n > BUS_AUTH_SIZE_MAX)
+ n = BUS_AUTH_SIZE_MAX;
+
+ if (b->rbuffer_size >= n)
+ return -ENOBUFS;
+
+ p = realloc(b->rbuffer, n);
+ if (!p)
+ return -ENOMEM;
+
+ b->rbuffer = p;
+
+ zero(iov);
+ iov.iov_base = (uint8_t*) b->rbuffer + b->rbuffer_size;
+ iov.iov_len = n - b->rbuffer_size;
+
+ if (b->prefer_readv)
+ k = readv(b->input_fd, &iov, 1);
+ else {
+ zero(mh);
+ mh.msg_iov = &iov;
+ mh.msg_iovlen = 1;
+ mh.msg_control = &control;
+ mh.msg_controllen = sizeof(control);
+
+ k = recvmsg(b->input_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL|MSG_CMSG_CLOEXEC);
+ if (k < 0 && errno == ENOTSOCK) {
+ b->prefer_readv = true;
+ k = readv(b->input_fd, &iov, 1);
+ } else
+ handle_cmsg = true;
+ }
+ if (k < 0)
+ return errno == EAGAIN ? 0 : -errno;
+ if (k == 0)
+ return -ECONNRESET;
+
+ b->rbuffer_size += k;
+
+ if (handle_cmsg) {
+ for (cmsg = CMSG_FIRSTHDR(&mh); cmsg; cmsg = CMSG_NXTHDR(&mh, cmsg)) {
+ if (cmsg->cmsg_level == SOL_SOCKET &&
+ cmsg->cmsg_type == SCM_RIGHTS) {
+ int j;
+
+ /* Whut? We received fds during the auth
+ * protocol? Somebody is playing games with
+ * us. Close them all, and fail */
+ j = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
+ close_many((int*) CMSG_DATA(cmsg), j);
+ return -EIO;
+
+ } else if (cmsg->cmsg_level == SOL_SOCKET &&
+ cmsg->cmsg_type == SCM_CREDENTIALS &&
+ cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred))) {
+
+ /* Ignore bogus data, which we might
+ * get on socketpair() sockets */
+ if (((struct ucred*) CMSG_DATA(cmsg))->pid != 0) {
+ memcpy(&b->ucred, CMSG_DATA(cmsg), sizeof(struct ucred));
+ b->ucred_valid = true;
+ }
+
+ } else if (cmsg->cmsg_level == SOL_SOCKET &&
+ cmsg->cmsg_type == SCM_SECURITY) {
+
+ size_t l;
+
+ l = cmsg->cmsg_len - CMSG_LEN(0);
+ if (l > 0) {
+ memcpy(&b->label, CMSG_DATA(cmsg), l);
+ b->label[l] = 0;
+ }
+ }
+ }
+ }
+
+ r = bus_socket_auth_verify(b);
+ if (r != 0)
+ return r;
+
+ return 1;
+}
+
+static int bus_socket_setup(sd_bus *b) {
+ int enable;
+ socklen_t l;
+
+ assert(b);
+
+ /* Enable SO_PASSCRED + SO_PASSEC. We try this on any
+ * socket, just in case. */
+ enable = !b->bus_client;
+ setsockopt(b->input_fd, SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable));
+ setsockopt(b->input_fd, SOL_SOCKET, SO_PASSSEC, &enable, sizeof(enable));
+
+ /* Increase the buffers to a MB */
+ fd_inc_rcvbuf(b->input_fd, 1024*1024);
+ fd_inc_sndbuf(b->output_fd, 1024*1024);
+
+ /* Get the peer for socketpair() sockets */
+ l = sizeof(b->ucred);
+ if (getsockopt(b->input_fd, SOL_SOCKET, SO_PEERCRED, &b->ucred, &l) >= 0 && l >= sizeof(b->ucred))
+ b->ucred_valid = b->ucred.pid > 0;
+
+ return 0;
+}
+
+static int bus_socket_start_auth_client(sd_bus *b) {
+ size_t l;
+ const char *auth_suffix, *auth_prefix;
+
+ assert(b);
+
+ if (b->anonymous_auth) {
+ auth_prefix = "\0AUTH ANONYMOUS ";
+
+ /* For ANONYMOUS auth we send some arbitrary "trace" string */
+ l = 9;
+ b->auth_buffer = hexmem("anonymous", l);
+ } else {
+ char text[20 + 1]; /* enough space for a 64bit integer plus NUL */
+
+ auth_prefix = "\0AUTH EXTERNAL ";
+
+ snprintf(text, sizeof(text), "%lu", (unsigned long) geteuid());
+ char_array_0(text);
+
+ l = strlen(text);
+ b->auth_buffer = hexmem(text, l);
+ }
+
+ if (!b->auth_buffer)
+ return -ENOMEM;
+
+ if (b->negotiate_fds)
+ auth_suffix = "\r\nNEGOTIATE_UNIX_FD\r\nBEGIN\r\n";
+ else
+ auth_suffix = "\r\nBEGIN\r\n";
+
+ b->auth_iovec[0].iov_base = (void*) auth_prefix;
+ b->auth_iovec[0].iov_len = 1 + strlen(auth_prefix + 1);
+ b->auth_iovec[1].iov_base = (void*) b->auth_buffer;
+ b->auth_iovec[1].iov_len = l * 2;
+ b->auth_iovec[2].iov_base = (void*) auth_suffix;
+ b->auth_iovec[2].iov_len = strlen(auth_suffix);
+
+ return bus_socket_write_auth(b);
+}
+
+static int bus_socket_start_auth(sd_bus *b) {
+ assert(b);
+
+ b->state = BUS_AUTHENTICATING;
+ b->auth_timeout = now(CLOCK_MONOTONIC) + BUS_DEFAULT_TIMEOUT;
+
+ if (sd_is_socket(b->input_fd, AF_UNIX, 0, 0) <= 0)
+ b->negotiate_fds = false;
+
+ if (b->output_fd != b->input_fd)
+ if (sd_is_socket(b->output_fd, AF_UNIX, 0, 0) <= 0)
+ b->negotiate_fds = false;
+
+ if (b->is_server)
+ return bus_socket_read_auth(b);
+ else
+ return bus_socket_start_auth_client(b);
+}
+
+int bus_socket_connect(sd_bus *b) {
+ int r;
+
+ assert(b);
+ assert(b->input_fd < 0);
+ assert(b->output_fd < 0);
+ assert(b->sockaddr.sa.sa_family != AF_UNSPEC);
+
+ b->input_fd = socket(b->sockaddr.sa.sa_family, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
+ if (b->input_fd < 0)
+ return -errno;
+
+ b->output_fd = b->input_fd;
+
+ r = bus_socket_setup(b);
+ if (r < 0)
+ return r;
+
+ r = connect(b->input_fd, &b->sockaddr.sa, b->sockaddr_size);
+ if (r < 0) {
+ if (errno == EINPROGRESS)
+ return 1;
+
+ return -errno;
+ }
+
+ return bus_socket_start_auth(b);
+}
+
+int bus_socket_exec(sd_bus *b) {
+ int s[2], r;
+ pid_t pid;
+
+ assert(b);
+ assert(b->input_fd < 0);
+ assert(b->output_fd < 0);
+ assert(b->exec_path);
+
+ r = socketpair(AF_UNIX, SOCK_STREAM|SOCK_NONBLOCK|SOCK_CLOEXEC, 0, s);
+ if (r < 0)
+ return -errno;
+
+ pid = fork();
+ if (pid < 0) {
+ close_pipe(s);
+ return -errno;
+ }
+ if (pid == 0) {
+ /* Child */
+
+ reset_all_signal_handlers();
+
+ close_all_fds(s+1, 1);
+
+ assert_se(dup3(s[1], STDIN_FILENO, 0) == STDIN_FILENO);
+ assert_se(dup3(s[1], STDOUT_FILENO, 0) == STDOUT_FILENO);
+
+ if (s[1] != STDIN_FILENO && s[1] != STDOUT_FILENO)
+ close_nointr_nofail(s[1]);
+
+ fd_cloexec(STDIN_FILENO, false);
+ fd_cloexec(STDOUT_FILENO, false);
+ fd_nonblock(STDIN_FILENO, false);
+ fd_nonblock(STDOUT_FILENO, false);
+
+ if (b->exec_argv)
+ execvp(b->exec_path, b->exec_argv);
+ else {
+ const char *argv[] = { b->exec_path, NULL };
+ execvp(b->exec_path, (char**) argv);
+ }
+
+ _exit(EXIT_FAILURE);
+ }
+
+ close_nointr_nofail(s[1]);
+ b->output_fd = b->input_fd = s[0];
+
+ return bus_socket_start_auth(b);
+}
+
+int bus_socket_take_fd(sd_bus *b) {
+ int r;
+ assert(b);
+
+ r = bus_socket_setup(b);
+ if (r < 0)
+ return r;
+
+ return bus_socket_start_auth(b);
+}
+
+int bus_socket_write_message(sd_bus *bus, sd_bus_message *m, size_t *idx) {
+ struct iovec *iov;
+ ssize_t k;
+ size_t n;
+ unsigned j;
+
+ assert(bus);
+ assert(m);
+ assert(idx);
+ assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
+
+ if (*idx >= BUS_MESSAGE_SIZE(m))
+ return 0;
+
+ bus_message_setup_iovec(m);
+
+ n = m->n_iovec * sizeof(struct iovec);
+ iov = alloca(n);
+ memcpy(iov, m->iovec, n);
+
+ j = 0;
+ iovec_advance(iov, &j, *idx);
+
+ if (bus->prefer_writev)
+ k = writev(bus->output_fd, iov, m->n_iovec);
+ else {
+ struct msghdr mh;
+ zero(mh);
+
+ if (m->n_fds > 0) {
+ struct cmsghdr *control;
+ control = alloca(CMSG_SPACE(sizeof(int) * m->n_fds));
+
+ mh.msg_control = control;
+ control->cmsg_level = SOL_SOCKET;
+ control->cmsg_type = SCM_RIGHTS;
+ mh.msg_controllen = control->cmsg_len = CMSG_LEN(sizeof(int) * m->n_fds);
+ memcpy(CMSG_DATA(control), m->fds, sizeof(int) * m->n_fds);
+ }
+
+ mh.msg_iov = iov;
+ mh.msg_iovlen = m->n_iovec;
+
+ k = sendmsg(bus->output_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL);
+ if (k < 0 && errno == ENOTSOCK) {
+ bus->prefer_writev = true;
+ k = writev(bus->output_fd, iov, m->n_iovec);
+ }
+ }
+
+ if (k < 0)
+ return errno == EAGAIN ? 0 : -errno;
+
+ *idx += (size_t) k;
+ return 1;
+}
+
+static int bus_socket_read_message_need(sd_bus *bus, size_t *need) {
+ uint32_t a, b;
+ uint8_t e;
+ uint64_t sum;
+
+ assert(bus);
+ assert(need);
+ assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
+
+ if (bus->rbuffer_size < sizeof(struct bus_header)) {
+ *need = sizeof(struct bus_header) + 8;
+
+ /* Minimum message size:
+ *
+ * Header +
+ *
+ * Method Call: +2 string headers
+ * Signal: +3 string headers
+ * Method Error: +1 string headers
+ * +1 uint32 headers
+ * Method Reply: +1 uint32 headers
+ *
+ * A string header is at least 9 bytes
+ * A uint32 header is at least 8 bytes
+ *
+ * Hence the minimum message size of a valid message
+ * is header + 8 bytes */
+
+ return 0;
+ }
+
+ a = ((const uint32_t*) bus->rbuffer)[1];
+ b = ((const uint32_t*) bus->rbuffer)[3];
+
+ e = ((const uint8_t*) bus->rbuffer)[0];
+ if (e == SD_BUS_LITTLE_ENDIAN) {
+ a = le32toh(a);
+ b = le32toh(b);
+ } else if (e == SD_BUS_BIG_ENDIAN) {
+ a = be32toh(a);
+ b = be32toh(b);
+ } else
+ return -EBADMSG;
+
+ sum = (uint64_t) sizeof(struct bus_header) + (uint64_t) ALIGN_TO(b, 8) + (uint64_t) a;
+ if (sum >= BUS_MESSAGE_SIZE_MAX)
+ return -ENOBUFS;
+
+ *need = (size_t) sum;
+ return 0;
+}
+
+static int bus_socket_make_message(sd_bus *bus, size_t size, sd_bus_message **m) {
+ sd_bus_message *t;
+ void *b;
+ int r;
+
+ assert(bus);
+ assert(m);
+ assert(bus->rbuffer_size >= size);
+ assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
+
+ if (bus->rbuffer_size > size) {
+ b = memdup((const uint8_t*) bus->rbuffer + size,
+ bus->rbuffer_size - size);
+ if (!b)
+ return -ENOMEM;
+ } else
+ b = NULL;
+
+ r = bus_message_from_malloc(bus->rbuffer, size,
+ bus->fds, bus->n_fds,
+ bus->ucred_valid ? &bus->ucred : NULL,
+ bus->label[0] ? bus->label : NULL,
+ &t);
+ if (r < 0) {
+ free(b);
+ return r;
+ }
+
+ bus->rbuffer = b;
+ bus->rbuffer_size -= size;
+
+ bus->fds = NULL;
+ bus->n_fds = 0;
+
+ *m = t;
+ return 1;
+}
+
+int bus_socket_read_message(sd_bus *bus, sd_bus_message **m) {
+ struct msghdr mh;
+ struct iovec iov;
+ ssize_t k;
+ size_t need;
+ int r;
+ void *b;
+ union {
+ struct cmsghdr cmsghdr;
+ uint8_t buf[CMSG_SPACE(sizeof(int) * BUS_FDS_MAX) +
+ CMSG_SPACE(sizeof(struct ucred)) +
+ CMSG_SPACE(NAME_MAX)]; /*selinux label */
+ } control;
+ struct cmsghdr *cmsg;
+ bool handle_cmsg = false;
+
+ assert(bus);
+ assert(m);
+ assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
+
+ r = bus_socket_read_message_need(bus, &need);
+ if (r < 0)
+ return r;
+
+ if (bus->rbuffer_size >= need)
+ return bus_socket_make_message(bus, need, m);
+
+ b = realloc(bus->rbuffer, need);
+ if (!b)
+ return -ENOMEM;
+
+ bus->rbuffer = b;
+
+ zero(iov);
+ iov.iov_base = (uint8_t*) bus->rbuffer + bus->rbuffer_size;
+ iov.iov_len = need - bus->rbuffer_size;
+
+ if (bus->prefer_readv)
+ k = readv(bus->input_fd, &iov, 1);
+ else {
+ zero(mh);
+ mh.msg_iov = &iov;
+ mh.msg_iovlen = 1;
+ mh.msg_control = &control;
+ mh.msg_controllen = sizeof(control);
+
+ k = recvmsg(bus->input_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL|MSG_CMSG_CLOEXEC);
+ if (k < 0 && errno == ENOTSOCK) {
+ bus->prefer_readv = true;
+ k = readv(bus->input_fd, &iov, 1);
+ } else
+ handle_cmsg = true;
+ }
+ if (k < 0)
+ return errno == EAGAIN ? 0 : -errno;
+ if (k == 0)
+ return -ECONNRESET;
+
+ bus->rbuffer_size += k;
+
+ if (handle_cmsg) {
+ for (cmsg = CMSG_FIRSTHDR(&mh); cmsg; cmsg = CMSG_NXTHDR(&mh, cmsg)) {
+ if (cmsg->cmsg_level == SOL_SOCKET &&
+ cmsg->cmsg_type == SCM_RIGHTS) {
+ int n, *f;
+
+ n = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
+
+ if (!bus->can_fds) {
+ /* Whut? We received fds but this
+ * isn't actually enabled? Close them,
+ * and fail */
+
+ close_many((int*) CMSG_DATA(cmsg), n);
+ return -EIO;
+ }
+
+ f = realloc(bus->fds, sizeof(int) + (bus->n_fds + n));
+ if (!f) {
+ close_many((int*) CMSG_DATA(cmsg), n);
+ return -ENOMEM;
+ }
+
+ memcpy(f + bus->n_fds, CMSG_DATA(cmsg), n * sizeof(int));
+ bus->fds = f;
+ bus->n_fds += n;
+ } else if (cmsg->cmsg_level == SOL_SOCKET &&
+ cmsg->cmsg_type == SCM_CREDENTIALS &&
+ cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred))) {
+
+ /* Ignore bogus data, which we might
+ * get on socketpair() sockets */
+ if (((struct ucred*) CMSG_DATA(cmsg))->pid != 0) {
+ memcpy(&bus->ucred, CMSG_DATA(cmsg), sizeof(struct ucred));
+ bus->ucred_valid = true;
+ }
+
+ } else if (cmsg->cmsg_level == SOL_SOCKET &&
+ cmsg->cmsg_type == SCM_SECURITY) {
+
+ size_t l;
+ l = cmsg->cmsg_len - CMSG_LEN(0);
+ if (l > 0) {
+ memcpy(&bus->label, CMSG_DATA(cmsg), l);
+ bus->label[l] = 0;
+ }
+ }
+ }
+ }
+
+ r = bus_socket_read_message_need(bus, &need);
+ if (r < 0)
+ return r;
+
+ if (bus->rbuffer_size >= need)
+ return bus_socket_make_message(bus, need, m);
+
+ return 1;
+}
+
+int bus_socket_process_opening(sd_bus *b) {
+ int error = 0;
+ socklen_t slen = sizeof(error);
+ struct pollfd p = {
+ .fd = b->output_fd,
+ .events = POLLOUT,
+ };
+ int r;
+
+ assert(b->state == BUS_OPENING);
+
+ r = poll(&p, 1, 0);
+ if (r < 0)
+ return -errno;
+
+ if (!(p.revents & (POLLOUT|POLLERR|POLLHUP)))
+ return 0;
+
+ r = getsockopt(b->output_fd, SOL_SOCKET, SO_ERROR, &error, &slen);
+ if (r < 0)
+ b->last_connect_error = errno;
+ else if (error != 0)
+ b->last_connect_error = error;
+ else if (p.revents & (POLLERR|POLLHUP))
+ b->last_connect_error = ECONNREFUSED;
+ else
+ return bus_socket_start_auth(b);
+
+ return bus_next_address(b);
+}
+
+int bus_socket_process_authenticating(sd_bus *b) {
+ int r;
+
+ assert(b);
+ assert(b->state == BUS_AUTHENTICATING);
+
+ if (now(CLOCK_MONOTONIC) >= b->auth_timeout)
+ return -ETIMEDOUT;
+
+ r = bus_socket_write_auth(b);
+ if (r != 0)
+ return r;
+
+ return bus_socket_read_auth(b);
+}
diff --git a/src/libsystemd-bus/bus-socket.h b/src/libsystemd-bus/bus-socket.h
new file mode 100644
index 0000000000..a9c43f82df
--- /dev/null
+++ b/src/libsystemd-bus/bus-socket.h
@@ -0,0 +1,36 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "sd-bus.h"
+
+int bus_socket_connect(sd_bus *b);
+int bus_socket_exec(sd_bus *b);
+int bus_socket_take_fd(sd_bus *b);
+
+int bus_socket_write_message(sd_bus *bus, sd_bus_message *m, size_t *idx);
+int bus_socket_read_message(sd_bus *bus, sd_bus_message **m);
+
+int bus_socket_process_opening(sd_bus *b);
+int bus_socket_process_authenticating(sd_bus *b);
+
+bool bus_socket_auth_needs_write(sd_bus *b);
diff --git a/src/libsystemd-bus/bus-type.c b/src/libsystemd-bus/bus-type.c
new file mode 100644
index 0000000000..0557328085
--- /dev/null
+++ b/src/libsystemd-bus/bus-type.c
@@ -0,0 +1,163 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "util.h"
+#include "bus-type.h"
+
+bool bus_type_is_valid(char c) {
+ static const char valid[] = {
+ SD_BUS_TYPE_BYTE,
+ SD_BUS_TYPE_BOOLEAN,
+ SD_BUS_TYPE_INT16,
+ SD_BUS_TYPE_UINT16,
+ SD_BUS_TYPE_INT32,
+ SD_BUS_TYPE_UINT32,
+ SD_BUS_TYPE_INT64,
+ SD_BUS_TYPE_UINT64,
+ SD_BUS_TYPE_DOUBLE,
+ SD_BUS_TYPE_STRING,
+ SD_BUS_TYPE_OBJECT_PATH,
+ SD_BUS_TYPE_SIGNATURE,
+ SD_BUS_TYPE_ARRAY,
+ SD_BUS_TYPE_VARIANT,
+ SD_BUS_TYPE_STRUCT,
+ SD_BUS_TYPE_DICT_ENTRY,
+ SD_BUS_TYPE_UNIX_FD
+ };
+
+ return !!memchr(valid, c, sizeof(valid));
+}
+
+bool bus_type_is_valid_in_signature(char c) {
+ static const char valid[] = {
+ SD_BUS_TYPE_BYTE,
+ SD_BUS_TYPE_BOOLEAN,
+ SD_BUS_TYPE_INT16,
+ SD_BUS_TYPE_UINT16,
+ SD_BUS_TYPE_INT32,
+ SD_BUS_TYPE_UINT32,
+ SD_BUS_TYPE_INT64,
+ SD_BUS_TYPE_UINT64,
+ SD_BUS_TYPE_DOUBLE,
+ SD_BUS_TYPE_STRING,
+ SD_BUS_TYPE_OBJECT_PATH,
+ SD_BUS_TYPE_SIGNATURE,
+ SD_BUS_TYPE_ARRAY,
+ SD_BUS_TYPE_VARIANT,
+ SD_BUS_TYPE_STRUCT_BEGIN,
+ SD_BUS_TYPE_STRUCT_END,
+ SD_BUS_TYPE_DICT_ENTRY_BEGIN,
+ SD_BUS_TYPE_DICT_ENTRY_END,
+ SD_BUS_TYPE_UNIX_FD
+ };
+
+ return !!memchr(valid, c, sizeof(valid));
+}
+
+bool bus_type_is_basic(char c) {
+ static const char valid[] = {
+ SD_BUS_TYPE_BYTE,
+ SD_BUS_TYPE_BOOLEAN,
+ SD_BUS_TYPE_INT16,
+ SD_BUS_TYPE_UINT16,
+ SD_BUS_TYPE_INT32,
+ SD_BUS_TYPE_UINT32,
+ SD_BUS_TYPE_INT64,
+ SD_BUS_TYPE_UINT64,
+ SD_BUS_TYPE_DOUBLE,
+ SD_BUS_TYPE_STRING,
+ SD_BUS_TYPE_OBJECT_PATH,
+ SD_BUS_TYPE_SIGNATURE,
+ SD_BUS_TYPE_UNIX_FD
+ };
+
+ return !!memchr(valid, c, sizeof(valid));
+}
+
+bool bus_type_is_container(char c) {
+ static const char valid[] = {
+ SD_BUS_TYPE_ARRAY,
+ SD_BUS_TYPE_VARIANT,
+ SD_BUS_TYPE_STRUCT,
+ SD_BUS_TYPE_DICT_ENTRY
+ };
+
+ return !!memchr(valid, c, sizeof(valid));
+}
+
+int bus_type_get_alignment(char c) {
+
+ switch (c) {
+ case SD_BUS_TYPE_BYTE:
+ case SD_BUS_TYPE_SIGNATURE:
+ case SD_BUS_TYPE_VARIANT:
+ return 1;
+
+ case SD_BUS_TYPE_INT16:
+ case SD_BUS_TYPE_UINT16:
+ return 2;
+
+ case SD_BUS_TYPE_BOOLEAN:
+ case SD_BUS_TYPE_INT32:
+ case SD_BUS_TYPE_UINT32:
+ case SD_BUS_TYPE_STRING:
+ case SD_BUS_TYPE_OBJECT_PATH:
+ case SD_BUS_TYPE_ARRAY:
+ case SD_BUS_TYPE_UNIX_FD:
+ return 4;
+
+ case SD_BUS_TYPE_INT64:
+ case SD_BUS_TYPE_UINT64:
+ case SD_BUS_TYPE_DOUBLE:
+ case SD_BUS_TYPE_STRUCT:
+ case SD_BUS_TYPE_STRUCT_BEGIN:
+ case SD_BUS_TYPE_DICT_ENTRY:
+ case SD_BUS_TYPE_DICT_ENTRY_BEGIN:
+ return 8;
+ }
+
+ return -EINVAL;
+}
+
+int bus_type_get_size(char c) {
+
+ switch (c) {
+ case SD_BUS_TYPE_BYTE:
+ return 1;
+
+ case SD_BUS_TYPE_INT16:
+ case SD_BUS_TYPE_UINT16:
+ return 2;
+
+ case SD_BUS_TYPE_BOOLEAN:
+ case SD_BUS_TYPE_INT32:
+ case SD_BUS_TYPE_UINT32:
+ case SD_BUS_TYPE_UNIX_FD:
+ return 4;
+
+ case SD_BUS_TYPE_INT64:
+ case SD_BUS_TYPE_UINT64:
+ case SD_BUS_TYPE_DOUBLE:
+ return 8;
+ }
+
+ return -EINVAL;
+}
diff --git a/src/libsystemd-bus/bus-type.h b/src/libsystemd-bus/bus-type.h
new file mode 100644
index 0000000000..e261136084
--- /dev/null
+++ b/src/libsystemd-bus/bus-type.h
@@ -0,0 +1,34 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdbool.h>
+
+#include "sd-bus.h"
+#include "sd-bus-protocol.h"
+
+bool bus_type_is_valid(char c);
+bool bus_type_is_valid_in_signature(char c);
+bool bus_type_is_basic(char c);
+bool bus_type_is_container(char c);
+int bus_type_get_alignment(char c);
+int bus_type_get_size(char c);
diff --git a/src/libsystemd-bus/busctl.c b/src/libsystemd-bus/busctl.c
new file mode 100644
index 0000000000..220c1eb34e
--- /dev/null
+++ b/src/libsystemd-bus/busctl.c
@@ -0,0 +1,340 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <getopt.h>
+
+#include "strv.h"
+#include "util.h"
+#include "log.h"
+#include "build.h"
+#include "pager.h"
+
+#include "sd-bus.h"
+#include "bus-message.h"
+#include "bus-internal.h"
+
+static bool arg_no_pager = false;
+static char *arg_address = NULL;
+static bool arg_user = false;
+static bool arg_no_unique = false;
+static char **arg_matches = NULL;
+
+static void pager_open_if_enabled(void) {
+
+ /* Cache result before we open the pager */
+ if (arg_no_pager)
+ return;
+
+ pager_open(false);
+}
+
+static int list_bus_names(sd_bus *bus, char **argv) {
+ _cleanup_strv_free_ char **l = NULL;
+ char **i;
+ int r;
+ size_t max_i = 0;
+
+ assert(bus);
+
+ r = sd_bus_list_names(bus, &l);
+ if (r < 0) {
+ log_error("Failed to list names: %s", strerror(-r));
+ return r;
+ }
+
+ pager_open_if_enabled();
+
+ strv_sort(l);
+
+ STRV_FOREACH(i, l)
+ max_i = MAX(max_i, strlen(*i));
+
+ printf("%-*s %*s %-*s %-*s CONNECTION\n",
+ (int) max_i, "NAME", 10, "PID", 15, "PROCESS", 16, "USER");
+
+ STRV_FOREACH(i, l) {
+ _cleanup_free_ char *owner = NULL;
+ pid_t pid;
+ uid_t uid;
+
+ if (arg_no_unique && (*i)[0] == ':')
+ continue;
+
+ printf("%-*s", (int) max_i, *i);
+
+ r = sd_bus_get_owner_pid(bus, *i, &pid);
+ if (r >= 0) {
+ _cleanup_free_ char *comm = NULL;
+
+ printf(" %10lu", (unsigned long) pid);
+
+ get_process_comm(pid, &comm);
+ printf(" %-15s", strna(comm));
+ } else
+ printf(" - - ");
+
+ r = sd_bus_get_owner_uid(bus, *i, &uid);
+ if (r >= 0) {
+ _cleanup_free_ char *u = NULL;
+
+ u = uid_to_name(uid);
+ if (!u)
+ return log_oom();
+
+ if (strlen(u) > 16)
+ u[16] = 0;
+
+ printf(" %-16s", u);
+ } else
+ printf(" - ");
+
+ r = sd_bus_get_owner(bus, *i, &owner);
+ if (r >= 0)
+ printf(" %s\n", owner);
+ else
+ printf(" -\n");
+ }
+
+ return 0;
+}
+
+static int monitor(sd_bus *bus, char *argv[]) {
+ char **i;
+ int r;
+
+ STRV_FOREACH(i, argv+1) {
+ _cleanup_free_ char *m = NULL;
+
+ if (!service_name_is_valid(*i)) {
+ log_error("Invalid service name '%s'", *i);
+ return -EINVAL;
+ }
+
+ m = strjoin("sender='", *i, "'", NULL);
+ if (!m)
+ return log_oom();
+
+ r = sd_bus_add_match(bus, m, NULL, NULL);
+ if (r < 0) {
+ log_error("Failed to add match: %s", strerror(-r));
+ return r;
+ }
+ }
+
+ STRV_FOREACH(i, arg_matches) {
+ r = sd_bus_add_match(bus, *i, NULL, NULL);
+ if (r < 0) {
+ log_error("Failed to add match: %s", strerror(-r));
+ return r;
+ }
+ }
+
+ for (;;) {
+ _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
+
+ r = sd_bus_process(bus, &m);
+ if (r < 0) {
+ log_error("Failed to process bus: %s", strerror(-r));
+ return r;
+ }
+
+ if (m) {
+ bus_message_dump(m);
+ continue;
+ }
+
+ if (r > 0)
+ continue;
+
+ r = sd_bus_wait(bus, (uint64_t) -1);
+ if (r < 0) {
+ log_error("Failed to wait for bus: %s", strerror(-r));
+ return r;
+ }
+ }
+
+ return -EINVAL;
+}
+
+static int help(void) {
+
+ printf("%s [OPTIONS...] {COMMAND} ...\n\n"
+ "Introspect the bus.\n\n"
+ " -h --help Show this help\n"
+ " --version Show package version\n"
+ " --system Connect to system bus\n"
+ " --user Connect to user bus\n"
+ " --address=ADDRESS Connect to bus specified by address\n"
+ " --no-unique Only show well-known names\n"
+ " --match=MATCH Only show matching messages\n"
+ " --no-pager Do not pipe output into a pager\n\n"
+ "Commands:\n"
+ " list List bus names\n"
+ " monitor [SERVICE...] Show bus traffic\n",
+ program_invocation_short_name);
+
+ return 0;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+
+ enum {
+ ARG_VERSION = 0x100,
+ ARG_NO_PAGER,
+ ARG_SYSTEM,
+ ARG_USER,
+ ARG_ADDRESS,
+ ARG_MATCH,
+ ARG_NO_UNIQUE
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "version", no_argument, NULL, ARG_VERSION },
+ { "no-pager", no_argument, NULL, ARG_NO_PAGER },
+ { "system", no_argument, NULL, ARG_SYSTEM },
+ { "user", no_argument, NULL, ARG_USER },
+ { "address", required_argument, NULL, ARG_ADDRESS },
+ { "no-unique", no_argument, NULL, ARG_NO_UNIQUE },
+ { "match", required_argument, NULL, ARG_MATCH },
+ { NULL, 0, NULL, 0 },
+ };
+
+ int c;
+
+ assert(argc >= 0);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
+
+ switch (c) {
+
+ case 'h':
+ return help();
+
+ case ARG_VERSION:
+ puts(PACKAGE_STRING);
+ puts(SYSTEMD_FEATURES);
+ return 0;
+
+ case ARG_NO_PAGER:
+ arg_no_pager = true;
+ break;
+
+ case ARG_USER:
+ arg_user = true;
+ break;
+
+ case ARG_SYSTEM:
+ arg_user = false;
+ break;
+
+ case ARG_ADDRESS:
+ arg_address = optarg;
+ break;
+
+ case ARG_NO_UNIQUE:
+ arg_no_unique = true;
+ break;
+
+ case ARG_MATCH:
+ if (strv_extend(&arg_matches, optarg) < 0)
+ return log_oom();
+ break;
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ log_error("Unknown option code %c", c);
+ return -EINVAL;
+ }
+ }
+
+ return 1;
+}
+
+static int busctl_main(sd_bus *bus, int argc, char *argv[]) {
+ assert(bus);
+
+ if (optind >= argc ||
+ streq(argv[optind], "list"))
+ return list_bus_names(bus, argv + optind);
+
+ if (streq(argv[optind], "monitor"))
+ return monitor(bus, argv + optind);
+
+ if (streq(argv[optind], "help"))
+ return help();
+
+ log_error("Unknown command '%s'", argv[optind]);
+ return -EINVAL;
+}
+
+int main(int argc, char *argv[]) {
+ _cleanup_bus_unref_ sd_bus *bus = NULL;
+ int r;
+
+ log_parse_environment();
+ log_open();
+
+ r = parse_argv(argc, argv);
+ if (r <= 0)
+ goto finish;
+
+ if (arg_address) {
+ r = sd_bus_new(&bus);
+ if (r < 0) {
+ log_error("Failed to allocate bus: %s", strerror(-r));
+ goto finish;
+ }
+
+ r = sd_bus_set_address(bus, arg_address);
+ if (r < 0) {
+ log_error("Failed to set address: %s", strerror(-r));
+ goto finish;
+ }
+
+ r = sd_bus_set_bus_client(bus, true);
+ if (r < 0) {
+ log_error("Failed to set bus client: %s", strerror(-r));
+ goto finish;
+ }
+
+ r = sd_bus_start(bus);
+ } else if (arg_user)
+ r = sd_bus_open_user(&bus);
+ else
+ r = sd_bus_open_system(&bus);
+
+ if (r < 0) {
+ log_error("Failed to connect to bus: %s", strerror(-r));
+ goto finish;
+ }
+
+ r = busctl_main(bus, argc, argv);
+
+finish:
+ pager_close();
+ strv_free(arg_matches);
+
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/src/libsystemd-bus/kdbus.h b/src/libsystemd-bus/kdbus.h
new file mode 100644
index 0000000000..db5e243c17
--- /dev/null
+++ b/src/libsystemd-bus/kdbus.h
@@ -0,0 +1,418 @@
+/*
+ * Copyright (C) 2013 Kay Sievers
+ * Copyright (C) 2013 Greg Kroah-Hartman <gregkh@linuxfoundation.org>
+ * Copyright (C) 2013 Linux Foundation
+ * Copyright (C) 2013 Lennart Poettering
+ * Copyright (C) 2013 Daniel Mack <daniel@zonque.org>
+ *
+ * kdbus is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU Lesser General Public License as published by the
+ * Free Software Foundation; either version 2.1 of the License, or (at
+ * your option) any later version.
+ */
+
+#ifndef _KDBUS_H_
+#define _KDBUS_H_
+
+#ifndef __KERNEL__
+#include <sys/ioctl.h>
+#include <sys/types.h>
+#include <linux/types.h>
+#endif
+
+#define KDBUS_IOC_MAGIC 0x95
+
+/* Message sent from kernel to userspace, when the owner or starter of
+ * a well-known name changes */
+struct kdbus_manager_msg_name_change {
+ __u64 old_id;
+ __u64 new_id;
+ __u64 flags; /* 0 or (possibly?) KDBUS_NAME_IN_QUEUE */
+ char name[0];
+};
+
+struct kdbus_manager_msg_id_change {
+ __u64 id;
+ __u64 flags; /* The kernel flags field from KDBUS_HELLO */
+};
+
+struct kdbus_creds {
+ __u64 uid;
+ __u64 gid;
+ __u64 pid;
+ __u64 tid;
+
+ /* The starttime of the process PID. This is useful to detect
+ PID overruns from the client side. i.e. if you use the PID to
+ look something up in /proc/$PID/ you can afterwards check the
+ starttime field of it to ensure you didn't run into a PID
+ ovretun. */
+ __u64 starttime;
+};
+
+struct kdbus_audit {
+ __u64 sessionid;
+ __u64 loginuid;
+};
+
+struct kdbus_timestamp {
+ __u64 monotonic_ns;
+ __u64 realtime_ns;
+};
+
+#define KDBUS_SRC_ID_KERNEL (0)
+#define KDBUS_DST_ID_WELL_KNOWN_NAME (0)
+#define KDBUS_MATCH_SRC_ID_ANY (~0ULL)
+#define KDBUS_DST_ID_BROADCAST (~0ULL)
+
+/* Message Item Types */
+enum {
+ KDBUS_MSG_NULL,
+
+ /* Filled in by userspace */
+ KDBUS_MSG_PAYLOAD, /* .data, inline memory */
+ KDBUS_MSG_PAYLOAD_VEC, /* .data_vec, reference to memory area */
+ KDBUS_MSG_UNIX_FDS, /* .data_fds of file descriptors */
+ KDBUS_MSG_BLOOM, /* for broadcasts, carries bloom filter blob in .data */
+ KDBUS_MSG_DST_NAME, /* destination's well-known name, in .str */
+
+ /* Filled in by kernelspace */
+ KDBUS_MSG_SRC_NAMES = 0x200,/* NUL separated string list with well-known names of source */
+ KDBUS_MSG_TIMESTAMP, /* .timestamp */
+ KDBUS_MSG_SRC_CREDS, /* .creds */
+ KDBUS_MSG_SRC_PID_COMM, /* optional, in .str */
+ KDBUS_MSG_SRC_TID_COMM, /* optional, in .str */
+ KDBUS_MSG_SRC_EXE, /* optional, in .str */
+ KDBUS_MSG_SRC_CMDLINE, /* optional, in .str (a chain of NUL str) */
+ KDBUS_MSG_SRC_CGROUP, /* optional, in .str */
+ KDBUS_MSG_SRC_CAPS, /* caps data blob, in .data */
+ KDBUS_MSG_SRC_SECLABEL, /* NUL terminated string, in .str */
+ KDBUS_MSG_SRC_AUDIT, /* .audit */
+
+ /* Special messages from kernel, consisting of one and only one of these data blocks */
+ KDBUS_MSG_NAME_ADD = 0x400,/* .name_change */
+ KDBUS_MSG_NAME_REMOVE, /* .name_change */
+ KDBUS_MSG_NAME_CHANGE, /* .name_change */
+ KDBUS_MSG_ID_ADD, /* .id_change */
+ KDBUS_MSG_ID_REMOVE, /* .id_change */
+ KDBUS_MSG_REPLY_TIMEOUT, /* empty, but .reply_cookie in .kdbus_msg is filled in */
+ KDBUS_MSG_REPLY_DEAD, /* dito */
+};
+
+enum {
+ KDBUS_VEC_ALIGNED = 1 << 0,
+};
+
+struct kdbus_vec {
+ __u64 address;
+ __u64 size;
+ __u64 flags;
+};
+
+/**
+ * struct kdbus_item - chain of data blocks
+ *
+ * size: overall data record size
+ * type: kdbus_item type of data
+ */
+struct kdbus_item {
+ __u64 size;
+ __u64 type;
+ union {
+ /* inline data */
+ __u8 data[0];
+ __u32 data32[0];
+ __u64 data64[0];
+ char str[0];
+
+ /* connection */
+ __u64 id;
+
+ /* data vector */
+ struct kdbus_vec vec;
+
+ /* process credentials and properties*/
+ struct kdbus_creds creds;
+ struct kdbus_audit audit;
+ struct kdbus_timestamp timestamp;
+
+ /* specific fields */
+ int fds[0];
+ struct kdbus_manager_msg_name_change name_change;
+ struct kdbus_manager_msg_id_change id_change;
+ };
+};
+
+enum {
+ KDBUS_MSG_FLAGS_EXPECT_REPLY = 1 << 0,
+ KDBUS_MSG_FLAGS_NO_AUTO_START = 1 << 1,
+};
+
+enum {
+ KDBUS_PAYLOAD_NULL,
+ KDBUS_PAYLOAD_DBUS1 = 0x4442757356657231ULL, /* 'DBusVer1' */
+ KDBUS_PAYLOAD_GVARIANT = 0x4756617269616e74ULL, /* 'GVariant' */
+};
+
+/**
+ * struct kdbus_msg
+ *
+ * set by userspace:
+ * dst_id: destination id
+ * flags: KDBUS_MSG_FLAGS_*
+ * items: data records
+ *
+ * set by kernel:
+ * src_id: who sent the message
+ */
+struct kdbus_msg {
+ __u64 size;
+ __u64 flags;
+ __u64 dst_id; /* connection, 0 == name in data, ~0 broadcast */
+ __u64 src_id; /* connection, 0 == kernel */
+ __u64 payload_type; /* 'DBusVer1', 'GVariant', ... */
+ __u64 cookie; /* userspace-supplied cookie */
+ union {
+ __u64 cookie_reply; /* cookie we reply to */
+ __u64 timeout_ns; /* timespan to wait for reply */
+ };
+ struct kdbus_item items[0];
+};
+
+enum {
+ KDBUS_POLICY_NULL,
+ KDBUS_POLICY_NAME,
+ KDBUS_POLICY_ACCESS,
+};
+
+enum {
+ KDBUS_POLICY_ACCESS_NULL,
+ KDBUS_POLICY_ACCESS_USER,
+ KDBUS_POLICY_ACCESS_GROUP,
+ KDBUS_POLICY_ACCESS_WORLD,
+};
+
+enum {
+ KDBUS_POLICY_RECV = 1 << 2,
+ KDBUS_POLICY_SEND = 1 << 1,
+ KDBUS_POLICY_OWN = 1 << 0,
+};
+
+struct kdbus_policy {
+ __u64 size;
+ __u64 type; /* NAME or ACCESS */
+ union {
+ char name[0];
+ struct {
+ __u32 type; /* USER, GROUP, WORLD */
+ __u32 bits; /* RECV, SEND, OWN */
+ __u64 id; /* uid, gid, 0 */
+ } access;
+ };
+};
+
+struct kdbus_cmd_policy {
+ __u64 size;
+ __u8 buffer[0]; /* a series of KDBUS_POLICY_NAME plus one or
+ * more KDBUS_POLICY_ACCESS each. */
+};
+
+/* Flags for struct kdbus_cmd_hello */
+enum {
+ KDBUS_HELLO_STARTER = 1 << 0,
+ KDBUS_HELLO_ACCEPT_FD = 1 << 1,
+
+ /* The following have an effect on directed messages only --
+ * not for broadcasts */
+ KDBUS_HELLO_ATTACH_COMM = 1 << 10,
+ KDBUS_HELLO_ATTACH_EXE = 1 << 11,
+ KDBUS_HELLO_ATTACH_CMDLINE = 1 << 12,
+ KDBUS_HELLO_ATTACH_CGROUP = 1 << 13,
+ KDBUS_HELLO_ATTACH_CAPS = 1 << 14,
+ KDBUS_HELLO_ATTACH_SECLABEL = 1 << 15,
+ KDBUS_HELLO_ATTACH_AUDIT = 1 << 16,
+};
+
+/* Items to append to struct kdbus_cmd_hello */
+enum {
+ KDBUS_HELLO_NULL,
+};
+
+struct kdbus_cmd_hello {
+ __u64 size;
+
+ /* userspace → kernel, kernel → userspace */
+ __u64 conn_flags; /* userspace specifies its
+ * capabilities and more, kernel
+ * returns its capabilites and
+ * more. Kernel might refuse client's
+ * capabilities by returning an error
+ * from KDBUS_HELLO */
+
+ /* kernel → userspace */
+ __u64 bus_flags; /* this is .flags copied verbatim from
+ * from original KDBUS_CMD_BUS_MAKE
+ * ioctl. It's intended to be useful
+ * to do negotiation of features of
+ * the payload that is transfreted. */
+ __u64 id; /* id assigned to this connection */
+ __u64 bloom_size; /* The bloom filter size chosen by the
+ * bus owner */
+ struct kdbus_item items[0];
+};
+
+/* Flags for kdbus_cmd_{bus,ep,ns}_make */
+enum {
+ KDBUS_MAKE_ACCESS_GROUP = 1 << 0,
+ KDBUS_MAKE_ACCESS_WORLD = 1 << 1,
+ KDBUS_MAKE_POLICY_OPEN = 1 << 2,
+};
+
+/* Items to append to kdbus_cmd_{bus,ep,ns}_make */
+enum {
+ KDBUS_MAKE_NULL,
+ KDBUS_MAKE_NAME,
+ KDBUS_MAKE_CGROUP, /* the cgroup hierarchy ID for which to attach
+ * cgroup membership paths * to messages. */
+ KDBUS_MAKE_CRED, /* allow translator services which connect
+ * to the bus on behalf of somebody else,
+ * allow specifying the credentials of the
+ * client to connect on behalf on. Needs
+ * privileges */
+};
+
+struct kdbus_cmd_bus_make {
+ __u64 size;
+ __u64 flags; /* userspace → kernel, kernel → userspace
+ * When creating a bus feature
+ * kernel negotiation. */
+ __u64 bus_flags; /* userspace → kernel
+ * When a bus is created this value is
+ * copied verbatim into the bus
+ * structure and returned from
+ * KDBUS_CMD_HELLO, later */
+ __u64 bloom_size; /* size of the bloom filter for this bus */
+ struct kdbus_item items[0];
+
+};
+
+struct kdbus_cmd_ep_make {
+ __u64 size;
+ __u64 flags; /* userspace → kernel, kernel → userspace
+ * When creating an entry point
+ * feature kernel negotiation done the
+ * same way as for
+ * KDBUS_CMD_BUS_MAKE. Unused for
+ * now. */
+ struct kdbus_item items[0];
+};
+
+struct kdbus_cmd_ns_make {
+ __u64 size;
+ __u64 flags; /* userspace → kernel, kernel → userspace
+ * When creating an entry point
+ * feature kernel negotiation done the
+ * same way as for
+ * KDBUS_CMD_BUS_MAKE. Unused for
+ * now. */
+ struct kdbus_item items[0];
+};
+
+enum {
+ /* userspace → kernel */
+ KDBUS_NAME_REPLACE_EXISTING = 1 << 0,
+ KDBUS_NAME_QUEUE = 1 << 1,
+ KDBUS_NAME_ALLOW_REPLACEMENT = 1 << 2,
+
+ /* kernel → userspace */
+ KDBUS_NAME_IN_QUEUE = 1 << 16,
+};
+
+struct kdbus_cmd_name {
+ __u64 size;
+ __u64 name_flags;
+ __u64 id; /* We allow registration/deregestration of names of other peers */
+ __u64 conn_flags;
+ char name[0];
+};
+
+struct kdbus_cmd_names {
+ __u64 size;
+ struct kdbus_cmd_name names[0];
+};
+
+enum {
+ KDBUS_NAME_INFO_ITEM_NULL,
+ KDBUS_NAME_INFO_ITEM_NAME, /* userspace → kernel */
+ KDBUS_NAME_INFO_ITEM_SECLABEL, /* kernel → userspace */
+ KDBUS_NAME_INFO_ITEM_AUDIT, /* kernel → userspace */
+};
+
+struct kdbus_cmd_name_info {
+ __u64 size; /* overall size of info */
+ __u64 flags;
+ __u64 id; /* either ID, or 0 and _ITEM_NAME follows */
+ struct kdbus_creds creds;
+ struct kdbus_item items[0]; /* list of item records */
+};
+
+enum {
+ KDBUS_MATCH_NULL,
+ KDBUS_MATCH_BLOOM, /* Matches a mask blob against KDBUS_MSG_BLOOM */
+ KDBUS_MATCH_SRC_NAME, /* Matches a name string against KDBUS_MSG_SRC_NAMES */
+ KDBUS_MATCH_NAME_ADD, /* Matches a name string against KDBUS_MSG_NAME_ADD */
+ KDBUS_MATCH_NAME_REMOVE, /* Matches a name string against KDBUS_MSG_NAME_REMOVE */
+ KDBUS_MATCH_NAME_CHANGE, /* Matches a name string against KDBUS_MSG_NAME_CHANGE */
+ KDBUS_MATCH_ID_ADD, /* Matches an ID against KDBUS_MSG_ID_ADD */
+ KDBUS_MATCH_ID_REMOVE, /* Matches an ID against KDBUS_MSG_ID_REMOVE */
+};
+
+struct kdbus_cmd_match {
+ __u64 size;
+ __u64 id; /* We allow registration/deregestration of matches for other peers */
+ __u64 cookie; /* userspace supplied cookie; when removing; kernel deletes everything with same cookie */
+ __u64 src_id; /* ~0: any. other: exact unique match */
+ struct kdbus_item items[0];
+};
+
+struct kdbus_cmd_monitor {
+ __u64 id; /* We allow setting the monitor flag of other peers */
+ unsigned int enabled; /* A boolean to enable/disable monitoring */
+};
+
+/* FD states:
+ * control nodes: unset
+ * bus owner (via KDBUS_CMD_BUS_MAKE)
+ * ns owner (via KDBUS_CMD_NS_MAKE)
+ *
+ * ep nodes: unset
+ * connected (via KDBUS_CMD_HELLO)
+ * starter (via KDBUS_CMD_HELLO with KDBUS_CMD_HELLO_STARTER)
+ * ep owner (via KDBUS_CMD_EP_MAKE)
+ */
+enum kdbus_cmd {
+ /* kdbus control node commands: require unset state */
+ KDBUS_CMD_BUS_MAKE = _IOWR(KDBUS_IOC_MAGIC, 0x00, struct kdbus_cmd_bus_make),
+ KDBUS_CMD_NS_MAKE = _IOWR(KDBUS_IOC_MAGIC, 0x10, struct kdbus_cmd_ns_make),
+
+ /* kdbus ep node commands: require unset state */
+ KDBUS_CMD_EP_MAKE = _IOWR(KDBUS_IOC_MAGIC, 0x20, struct kdbus_cmd_ep_make),
+ KDBUS_CMD_HELLO = _IOWR(KDBUS_IOC_MAGIC, 0x30, struct kdbus_cmd_hello),
+
+ /* kdbus ep node commands: require connected state */
+ KDBUS_CMD_MSG_SEND = _IOWR(KDBUS_IOC_MAGIC, 0x40, struct kdbus_msg),
+ KDBUS_CMD_MSG_RECV = _IOWR(KDBUS_IOC_MAGIC, 0x41, struct kdbus_msg),
+
+ KDBUS_CMD_NAME_ACQUIRE = _IOWR(KDBUS_IOC_MAGIC, 0x50, struct kdbus_cmd_name),
+ KDBUS_CMD_NAME_RELEASE = _IOWR(KDBUS_IOC_MAGIC, 0x51, struct kdbus_cmd_name),
+ KDBUS_CMD_NAME_LIST = _IOWR(KDBUS_IOC_MAGIC, 0x52, struct kdbus_cmd_names),
+ KDBUS_CMD_NAME_QUERY = _IOWR(KDBUS_IOC_MAGIC, 0x53, struct kdbus_cmd_name_info),
+
+ KDBUS_CMD_MATCH_ADD = _IOWR(KDBUS_IOC_MAGIC, 0x60, struct kdbus_cmd_match),
+ KDBUS_CMD_MATCH_REMOVE = _IOWR(KDBUS_IOC_MAGIC, 0x61, struct kdbus_cmd_match),
+ KDBUS_CMD_MONITOR = _IOWR(KDBUS_IOC_MAGIC, 0x62, struct kdbus_cmd_monitor),
+
+ /* kdbus ep node commands: require ep owner state */
+ KDBUS_CMD_EP_POLICY_SET = _IOWR(KDBUS_IOC_MAGIC, 0x70, struct kdbus_cmd_policy),
+};
+#endif
diff --git a/src/libsystemd-bus/sd-bus.c b/src/libsystemd-bus/sd-bus.c
new file mode 100644
index 0000000000..7d6d848ec5
--- /dev/null
+++ b/src/libsystemd-bus/sd-bus.c
@@ -0,0 +1,2425 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <endian.h>
+#include <assert.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <netdb.h>
+#include <sys/poll.h>
+#include <byteswap.h>
+
+#include "util.h"
+#include "macro.h"
+#include "strv.h"
+#include "set.h"
+#include "missing.h"
+
+#include "sd-bus.h"
+#include "bus-internal.h"
+#include "bus-message.h"
+#include "bus-type.h"
+#include "bus-socket.h"
+#include "bus-kernel.h"
+#include "bus-control.h"
+
+static int bus_poll(sd_bus *bus, bool need_more, uint64_t timeout_usec);
+
+static void bus_free(sd_bus *b) {
+ struct filter_callback *f;
+ struct object_callback *c;
+ unsigned i;
+
+ assert(b);
+
+ sd_bus_close(b);
+
+ free(b->rbuffer);
+ free(b->unique_name);
+ free(b->auth_buffer);
+ free(b->address);
+ free(b->kernel);
+
+ free(b->exec_path);
+ strv_free(b->exec_argv);
+
+ close_many(b->fds, b->n_fds);
+ free(b->fds);
+
+ for (i = 0; i < b->rqueue_size; i++)
+ sd_bus_message_unref(b->rqueue[i]);
+ free(b->rqueue);
+
+ for (i = 0; i < b->wqueue_size; i++)
+ sd_bus_message_unref(b->wqueue[i]);
+ free(b->wqueue);
+
+ hashmap_free_free(b->reply_callbacks);
+ prioq_free(b->reply_callbacks_prioq);
+
+ while ((f = b->filter_callbacks)) {
+ LIST_REMOVE(struct filter_callback, callbacks, b->filter_callbacks, f);
+ free(f);
+ }
+
+ while ((c = hashmap_steal_first(b->object_callbacks))) {
+ free(c->path);
+ free(c);
+ }
+
+ hashmap_free(b->object_callbacks);
+
+ bus_match_free(&b->match_callbacks);
+
+ free(b);
+}
+
+int sd_bus_new(sd_bus **ret) {
+ sd_bus *r;
+
+ if (!ret)
+ return -EINVAL;
+
+ r = new0(sd_bus, 1);
+ if (!r)
+ return -ENOMEM;
+
+ r->n_ref = 1;
+ r->input_fd = r->output_fd = -1;
+ r->message_version = 1;
+ r->negotiate_fds = true;
+
+ /* We guarantee that wqueue always has space for at least one
+ * entry */
+ r->wqueue = new(sd_bus_message*, 1);
+ if (!r->wqueue) {
+ free(r);
+ return -ENOMEM;
+ }
+
+ *ret = r;
+ return 0;
+}
+
+int sd_bus_set_address(sd_bus *bus, const char *address) {
+ char *a;
+
+ if (!bus)
+ return -EINVAL;
+ if (bus->state != BUS_UNSET)
+ return -EPERM;
+ if (!address)
+ return -EINVAL;
+
+ a = strdup(address);
+ if (!a)
+ return -ENOMEM;
+
+ free(bus->address);
+ bus->address = a;
+
+ return 0;
+}
+
+int sd_bus_set_fd(sd_bus *bus, int input_fd, int output_fd) {
+ if (!bus)
+ return -EINVAL;
+ if (bus->state != BUS_UNSET)
+ return -EPERM;
+ if (input_fd < 0)
+ return -EINVAL;
+ if (output_fd < 0)
+ return -EINVAL;
+
+ bus->input_fd = input_fd;
+ bus->output_fd = output_fd;
+ return 0;
+}
+
+int sd_bus_set_exec(sd_bus *bus, const char *path, char *const argv[]) {
+ char *p, **a;
+
+ if (!bus)
+ return -EINVAL;
+ if (bus->state != BUS_UNSET)
+ return -EPERM;
+ if (!path)
+ return -EINVAL;
+ if (strv_isempty(argv))
+ return -EINVAL;
+
+ p = strdup(path);
+ if (!p)
+ return -ENOMEM;
+
+ a = strv_copy(argv);
+ if (!a) {
+ free(p);
+ return -ENOMEM;
+ }
+
+ free(bus->exec_path);
+ strv_free(bus->exec_argv);
+
+ bus->exec_path = p;
+ bus->exec_argv = a;
+
+ return 0;
+}
+
+int sd_bus_set_bus_client(sd_bus *bus, int b) {
+ if (!bus)
+ return -EINVAL;
+ if (bus->state != BUS_UNSET)
+ return -EPERM;
+
+ bus->bus_client = !!b;
+ return 0;
+}
+
+int sd_bus_set_negotiate_fds(sd_bus *bus, int b) {
+ if (!bus)
+ return -EINVAL;
+ if (bus->state != BUS_UNSET)
+ return -EPERM;
+
+ bus->negotiate_fds = !!b;
+ return 0;
+}
+
+int sd_bus_set_server(sd_bus *bus, int b, sd_id128_t server_id) {
+ if (!bus)
+ return -EINVAL;
+ if (!b && !sd_id128_equal(server_id, SD_ID128_NULL))
+ return -EINVAL;
+ if (bus->state != BUS_UNSET)
+ return -EPERM;
+
+ bus->is_server = !!b;
+ bus->server_id = server_id;
+ return 0;
+}
+
+int sd_bus_set_anonymous(sd_bus *bus, int b) {
+ if (!bus)
+ return -EINVAL;
+ if (bus->state != BUS_UNSET)
+ return -EPERM;
+
+ bus->anonymous_auth = !!b;
+ return 0;
+}
+
+static int hello_callback(sd_bus *bus, int error, sd_bus_message *reply, void *userdata) {
+ const char *s;
+ int r;
+
+ assert(bus);
+ assert(bus->state == BUS_HELLO);
+
+ if (error != 0)
+ return -error;
+
+ assert(reply);
+
+ r = sd_bus_message_read(reply, "s", &s);
+ if (r < 0)
+ return r;
+
+ if (!service_name_is_valid(s) || s[0] != ':')
+ return -EBADMSG;
+
+ bus->unique_name = strdup(s);
+ if (!bus->unique_name)
+ return -ENOMEM;
+
+ bus->state = BUS_RUNNING;
+
+ return 1;
+}
+
+static int bus_send_hello(sd_bus *bus) {
+ _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
+ int r;
+
+ assert(bus);
+
+ if (!bus->bus_client || bus->is_kernel)
+ return 0;
+
+ r = sd_bus_message_new_method_call(
+ bus,
+ "org.freedesktop.DBus",
+ "/",
+ "org.freedesktop.DBus",
+ "Hello",
+ &m);
+ if (r < 0)
+ return r;
+
+ return sd_bus_send_with_reply(bus, m, hello_callback, NULL, 0, &bus->hello_serial);
+}
+
+int bus_start_running(sd_bus *bus) {
+ assert(bus);
+
+ if (bus->bus_client && !bus->is_kernel) {
+ bus->state = BUS_HELLO;
+ return 1;
+ }
+
+ bus->state = BUS_RUNNING;
+ return 1;
+}
+
+static int parse_address_key(const char **p, const char *key, char **value) {
+ size_t l, n = 0;
+ const char *a;
+ char *r = NULL;
+
+ assert(p);
+ assert(*p);
+ assert(value);
+
+ if (key) {
+ l = strlen(key);
+ if (strncmp(*p, key, l) != 0)
+ return 0;
+
+ if ((*p)[l] != '=')
+ return 0;
+
+ if (*value)
+ return -EINVAL;
+
+ a = *p + l + 1;
+ } else
+ a = *p;
+
+ while (*a != ';' && *a != ',' && *a != 0) {
+ char c, *t;
+
+ if (*a == '%') {
+ int x, y;
+
+ x = unhexchar(a[1]);
+ if (x < 0) {
+ free(r);
+ return x;
+ }
+
+ y = unhexchar(a[2]);
+ if (y < 0) {
+ free(r);
+ return y;
+ }
+
+ c = (char) ((x << 4) | y);
+ a += 3;
+ } else {
+ c = *a;
+ a++;
+ }
+
+ t = realloc(r, n + 2);
+ if (!t) {
+ free(r);
+ return -ENOMEM;
+ }
+
+ r = t;
+ r[n++] = c;
+ }
+
+ if (!r) {
+ r = strdup("");
+ if (!r)
+ return -ENOMEM;
+ } else
+ r[n] = 0;
+
+ if (*a == ',')
+ a++;
+
+ *p = a;
+
+ free(*value);
+ *value = r;
+
+ return 1;
+}
+
+static void skip_address_key(const char **p) {
+ assert(p);
+ assert(*p);
+
+ *p += strcspn(*p, ",");
+
+ if (**p == ',')
+ (*p) ++;
+}
+
+static int parse_unix_address(sd_bus *b, const char **p, char **guid) {
+ _cleanup_free_ char *path = NULL, *abstract = NULL;
+ size_t l;
+ int r;
+
+ assert(b);
+ assert(p);
+ assert(*p);
+ assert(guid);
+
+ while (**p != 0 && **p != ';') {
+ r = parse_address_key(p, "guid", guid);
+ if (r < 0)
+ return r;
+ else if (r > 0)
+ continue;
+
+ r = parse_address_key(p, "path", &path);
+ if (r < 0)
+ return r;
+ else if (r > 0)
+ continue;
+
+ r = parse_address_key(p, "abstract", &abstract);
+ if (r < 0)
+ return r;
+ else if (r > 0)
+ continue;
+
+ skip_address_key(p);
+ }
+
+ if (!path && !abstract)
+ return -EINVAL;
+
+ if (path && abstract)
+ return -EINVAL;
+
+ if (path) {
+ l = strlen(path);
+ if (l > sizeof(b->sockaddr.un.sun_path))
+ return -E2BIG;
+
+ b->sockaddr.un.sun_family = AF_UNIX;
+ strncpy(b->sockaddr.un.sun_path, path, sizeof(b->sockaddr.un.sun_path));
+ b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + l;
+ } else if (abstract) {
+ l = strlen(abstract);
+ if (l > sizeof(b->sockaddr.un.sun_path) - 1)
+ return -E2BIG;
+
+ b->sockaddr.un.sun_family = AF_UNIX;
+ b->sockaddr.un.sun_path[0] = 0;
+ strncpy(b->sockaddr.un.sun_path+1, abstract, sizeof(b->sockaddr.un.sun_path)-1);
+ b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + 1 + l;
+ }
+
+ return 0;
+}
+
+static int parse_tcp_address(sd_bus *b, const char **p, char **guid) {
+ _cleanup_free_ char *host = NULL, *port = NULL, *family = NULL;
+ int r;
+ struct addrinfo *result, hints = {
+ .ai_socktype = SOCK_STREAM,
+ .ai_flags = AI_ADDRCONFIG,
+ };
+
+ assert(b);
+ assert(p);
+ assert(*p);
+ assert(guid);
+
+ while (**p != 0 && **p != ';') {
+ r = parse_address_key(p, "guid", guid);
+ if (r < 0)
+ return r;
+ else if (r > 0)
+ continue;
+
+ r = parse_address_key(p, "host", &host);
+ if (r < 0)
+ return r;
+ else if (r > 0)
+ continue;
+
+ r = parse_address_key(p, "port", &port);
+ if (r < 0)
+ return r;
+ else if (r > 0)
+ continue;
+
+ r = parse_address_key(p, "family", &family);
+ if (r < 0)
+ return r;
+ else if (r > 0)
+ continue;
+
+ skip_address_key(p);
+ }
+
+ if (!host || !port)
+ return -EINVAL;
+
+ if (family) {
+ if (streq(family, "ipv4"))
+ hints.ai_family = AF_INET;
+ else if (streq(family, "ipv6"))
+ hints.ai_family = AF_INET6;
+ else
+ return -EINVAL;
+ }
+
+ r = getaddrinfo(host, port, &hints, &result);
+ if (r == EAI_SYSTEM)
+ return -errno;
+ else if (r != 0)
+ return -EADDRNOTAVAIL;
+
+ memcpy(&b->sockaddr, result->ai_addr, result->ai_addrlen);
+ b->sockaddr_size = result->ai_addrlen;
+
+ freeaddrinfo(result);
+
+ return 0;
+}
+
+static int parse_exec_address(sd_bus *b, const char **p, char **guid) {
+ char *path = NULL;
+ unsigned n_argv = 0, j;
+ char **argv = NULL;
+ int r;
+
+ assert(b);
+ assert(p);
+ assert(*p);
+ assert(guid);
+
+ while (**p != 0 && **p != ';') {
+ r = parse_address_key(p, "guid", guid);
+ if (r < 0)
+ goto fail;
+ else if (r > 0)
+ continue;
+
+ r = parse_address_key(p, "path", &path);
+ if (r < 0)
+ goto fail;
+ else if (r > 0)
+ continue;
+
+ if (startswith(*p, "argv")) {
+ unsigned ul;
+
+ errno = 0;
+ ul = strtoul(*p + 4, (char**) p, 10);
+ if (errno > 0 || **p != '=' || ul > 256) {
+ r = -EINVAL;
+ goto fail;
+ }
+
+ (*p) ++;
+
+ if (ul >= n_argv) {
+ char **x;
+
+ x = realloc(argv, sizeof(char*) * (ul + 2));
+ if (!x) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ memset(x + n_argv, 0, sizeof(char*) * (ul - n_argv + 2));
+
+ argv = x;
+ n_argv = ul + 1;
+ }
+
+ r = parse_address_key(p, NULL, argv + ul);
+ if (r < 0)
+ goto fail;
+
+ continue;
+ }
+
+ skip_address_key(p);
+ }
+
+ if (!path) {
+ r = -EINVAL;
+ goto fail;
+ }
+
+ /* Make sure there are no holes in the array, with the
+ * exception of argv[0] */
+ for (j = 1; j < n_argv; j++)
+ if (!argv[j]) {
+ r = -EINVAL;
+ goto fail;
+ }
+
+ if (argv && argv[0] == NULL) {
+ argv[0] = strdup(path);
+ if (!argv[0]) {
+ r = -ENOMEM;
+ goto fail;
+ }
+ }
+
+ b->exec_path = path;
+ b->exec_argv = argv;
+ return 0;
+
+fail:
+ for (j = 0; j < n_argv; j++)
+ free(argv[j]);
+
+ free(argv);
+ free(path);
+ return r;
+}
+
+static int parse_kernel_address(sd_bus *b, const char **p, char **guid) {
+ _cleanup_free_ char *path = NULL;
+ int r;
+
+ assert(b);
+ assert(p);
+ assert(*p);
+ assert(guid);
+
+ while (**p != 0 && **p != ';') {
+ r = parse_address_key(p, "guid", guid);
+ if (r < 0)
+ return r;
+ else if (r > 0)
+ continue;
+
+ r = parse_address_key(p, "path", &path);
+ if (r < 0)
+ return r;
+ else if (r > 0)
+ continue;
+
+ skip_address_key(p);
+ }
+
+ if (!path)
+ return -EINVAL;
+
+ free(b->kernel);
+ b->kernel = path;
+ path = NULL;
+
+ return 0;
+}
+
+static void bus_reset_parsed_address(sd_bus *b) {
+ assert(b);
+
+ zero(b->sockaddr);
+ b->sockaddr_size = 0;
+ strv_free(b->exec_argv);
+ free(b->exec_path);
+ b->exec_path = NULL;
+ b->exec_argv = NULL;
+ b->server_id = SD_ID128_NULL;
+ free(b->kernel);
+ b->kernel = NULL;
+}
+
+static int bus_parse_next_address(sd_bus *b) {
+ _cleanup_free_ char *guid = NULL;
+ const char *a;
+ int r;
+
+ assert(b);
+
+ if (!b->address)
+ return 0;
+ if (b->address[b->address_index] == 0)
+ return 0;
+
+ bus_reset_parsed_address(b);
+
+ a = b->address + b->address_index;
+
+ while (*a != 0) {
+
+ if (*a == ';') {
+ a++;
+ continue;
+ }
+
+ if (startswith(a, "unix:")) {
+ a += 5;
+
+ r = parse_unix_address(b, &a, &guid);
+ if (r < 0)
+ return r;
+ break;
+
+ } else if (startswith(a, "tcp:")) {
+
+ a += 4;
+ r = parse_tcp_address(b, &a, &guid);
+ if (r < 0)
+ return r;
+
+ break;
+
+ } else if (startswith(a, "unixexec:")) {
+
+ a += 9;
+ r = parse_exec_address(b, &a, &guid);
+ if (r < 0)
+ return r;
+
+ break;
+
+ } else if (startswith(a, "kernel:")) {
+
+ a += 7;
+ r = parse_kernel_address(b, &a, &guid);
+ if (r < 0)
+ return r;
+
+ break;
+ }
+
+ a = strchr(a, ';');
+ if (!a)
+ return 0;
+ }
+
+ if (guid) {
+ r = sd_id128_from_string(guid, &b->server_id);
+ if (r < 0)
+ return r;
+ }
+
+ b->address_index = a - b->address;
+ return 1;
+}
+
+static int bus_start_address(sd_bus *b) {
+ int r;
+
+ assert(b);
+
+ for (;;) {
+ sd_bus_close(b);
+
+ if (b->sockaddr.sa.sa_family != AF_UNSPEC) {
+
+ r = bus_socket_connect(b);
+ if (r >= 0)
+ return r;
+
+ b->last_connect_error = -r;
+
+ } else if (b->exec_path) {
+
+ r = bus_socket_exec(b);
+ if (r >= 0)
+ return r;
+
+ b->last_connect_error = -r;
+ } else if (b->kernel) {
+
+ r = bus_kernel_connect(b);
+ if (r >= 0)
+ return r;
+
+ b->last_connect_error = -r;
+ }
+
+ r = bus_parse_next_address(b);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return b->last_connect_error ? -b->last_connect_error : -ECONNREFUSED;
+ }
+}
+
+int bus_next_address(sd_bus *b) {
+ assert(b);
+
+ bus_reset_parsed_address(b);
+ return bus_start_address(b);
+}
+
+static int bus_start_fd(sd_bus *b) {
+ struct stat st;
+ int r;
+
+ assert(b);
+ assert(b->input_fd >= 0);
+ assert(b->output_fd >= 0);
+
+ r = fd_nonblock(b->input_fd, true);
+ if (r < 0)
+ return r;
+
+ r = fd_cloexec(b->input_fd, true);
+ if (r < 0)
+ return r;
+
+ if (b->input_fd != b->output_fd) {
+ r = fd_nonblock(b->output_fd, true);
+ if (r < 0)
+ return r;
+
+ r = fd_cloexec(b->output_fd, true);
+ if (r < 0)
+ return r;
+ }
+
+ if (fstat(b->input_fd, &st) < 0)
+ return -errno;
+
+ if (S_ISCHR(b->input_fd))
+ return bus_kernel_take_fd(b);
+ else
+ return bus_socket_take_fd(b);
+}
+
+int sd_bus_start(sd_bus *bus) {
+ int r;
+
+ if (!bus)
+ return -EINVAL;
+ if (bus->state != BUS_UNSET)
+ return -EPERM;
+
+ bus->state = BUS_OPENING;
+
+ if (bus->is_server && bus->bus_client)
+ return -EINVAL;
+
+ if (bus->input_fd >= 0)
+ r = bus_start_fd(bus);
+ else if (bus->address || bus->sockaddr.sa.sa_family != AF_UNSPEC || bus->exec_path || bus->kernel)
+ r = bus_start_address(bus);
+ else
+ return -EINVAL;
+
+ if (r < 0)
+ return r;
+
+ return bus_send_hello(bus);
+}
+
+int sd_bus_open_system(sd_bus **ret) {
+ const char *e;
+ sd_bus *b;
+ int r;
+
+ if (!ret)
+ return -EINVAL;
+
+ r = sd_bus_new(&b);
+ if (r < 0)
+ return r;
+
+ e = secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
+ if (e) {
+ r = sd_bus_set_address(b, e);
+ if (r < 0)
+ goto fail;
+ } else {
+ b->sockaddr.un.sun_family = AF_UNIX;
+ strncpy(b->sockaddr.un.sun_path, "/run/dbus/system_bus_socket", sizeof(b->sockaddr.un.sun_path));
+ b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + sizeof("/run/dbus/system_bus_socket") - 1;
+ }
+
+ b->bus_client = true;
+
+ r = sd_bus_start(b);
+ if (r < 0)
+ goto fail;
+
+ *ret = b;
+ return 0;
+
+fail:
+ bus_free(b);
+ return r;
+}
+
+int sd_bus_open_user(sd_bus **ret) {
+ const char *e;
+ sd_bus *b;
+ size_t l;
+ int r;
+
+ if (!ret)
+ return -EINVAL;
+
+ r = sd_bus_new(&b);
+ if (r < 0)
+ return r;
+
+ e = secure_getenv("DBUS_SESSION_BUS_ADDRESS");
+ if (e) {
+ r = sd_bus_set_address(b, e);
+ if (r < 0)
+ goto fail;
+ } else {
+ e = secure_getenv("XDG_RUNTIME_DIR");
+ if (!e) {
+ r = -ENOENT;
+ goto fail;
+ }
+
+ l = strlen(e);
+ if (l + 4 > sizeof(b->sockaddr.un.sun_path)) {
+ r = -E2BIG;
+ goto fail;
+ }
+
+ b->sockaddr.un.sun_family = AF_UNIX;
+ memcpy(mempcpy(b->sockaddr.un.sun_path, e, l), "/bus", 4);
+ b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + l + 4;
+ }
+
+ b->bus_client = true;
+
+ r = sd_bus_start(b);
+ if (r < 0)
+ goto fail;
+
+ *ret = b;
+ return 0;
+
+fail:
+ bus_free(b);
+ return r;
+}
+
+void sd_bus_close(sd_bus *bus) {
+ if (!bus)
+ return;
+
+ if (bus->input_fd >= 0)
+ close_nointr_nofail(bus->input_fd);
+ if (bus->output_fd >= 0 && bus->output_fd != bus->input_fd)
+ close_nointr_nofail(bus->output_fd);
+
+ bus->input_fd = bus->output_fd = -1;
+}
+
+sd_bus *sd_bus_ref(sd_bus *bus) {
+ if (!bus)
+ return NULL;
+
+ assert(bus->n_ref > 0);
+
+ bus->n_ref++;
+ return bus;
+}
+
+sd_bus *sd_bus_unref(sd_bus *bus) {
+ if (!bus)
+ return NULL;
+
+ assert(bus->n_ref > 0);
+ bus->n_ref--;
+
+ if (bus->n_ref <= 0)
+ bus_free(bus);
+
+ return NULL;
+}
+
+int sd_bus_is_open(sd_bus *bus) {
+ if (!bus)
+ return -EINVAL;
+
+ return bus->state != BUS_UNSET && bus->input_fd >= 0;
+}
+
+int sd_bus_can_send(sd_bus *bus, char type) {
+ int r;
+
+ if (!bus)
+ return -EINVAL;
+ if (bus->output_fd < 0)
+ return -ENOTCONN;
+
+ if (type == SD_BUS_TYPE_UNIX_FD) {
+ if (!bus->negotiate_fds)
+ return 0;
+
+ r = bus_ensure_running(bus);
+ if (r < 0)
+ return r;
+
+ return bus->can_fds;
+ }
+
+ return bus_type_is_valid(type);
+}
+
+int sd_bus_get_server_id(sd_bus *bus, sd_id128_t *server_id) {
+ int r;
+
+ if (!bus)
+ return -EINVAL;
+ if (!server_id)
+ return -EINVAL;
+
+ r = bus_ensure_running(bus);
+ if (r < 0)
+ return r;
+
+ *server_id = bus->server_id;
+ return 0;
+}
+
+static int bus_seal_message(sd_bus *b, sd_bus_message *m) {
+ assert(m);
+
+ if (m->header->version > b->message_version)
+ return -EPERM;
+
+ if (m->sealed)
+ return 0;
+
+ return bus_message_seal(m, ++b->serial);
+}
+
+static int dispatch_wqueue(sd_bus *bus) {
+ int r, ret = 0;
+
+ assert(bus);
+ assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
+
+ if (bus->output_fd < 0)
+ return -ENOTCONN;
+
+ while (bus->wqueue_size > 0) {
+
+ if (bus->is_kernel)
+ r = bus_kernel_write_message(bus, bus->wqueue[0]);
+ else
+ r = bus_socket_write_message(bus, bus->wqueue[0], &bus->windex);
+
+ if (r < 0) {
+ sd_bus_close(bus);
+ return r;
+ } else if (r == 0)
+ /* Didn't do anything this time */
+ return ret;
+ else if (bus->is_kernel || bus->windex >= BUS_MESSAGE_SIZE(bus->wqueue[0])) {
+ /* Fully written. Let's drop the entry from
+ * the queue.
+ *
+ * This isn't particularly optimized, but
+ * well, this is supposed to be our worst-case
+ * buffer only, and the socket buffer is
+ * supposed to be our primary buffer, and if
+ * it got full, then all bets are off
+ * anyway. */
+
+ sd_bus_message_unref(bus->wqueue[0]);
+ bus->wqueue_size --;
+ memmove(bus->wqueue, bus->wqueue + 1, sizeof(sd_bus_message*) * bus->wqueue_size);
+ bus->windex = 0;
+
+ ret = 1;
+ }
+ }
+
+ return ret;
+}
+
+static int dispatch_rqueue(sd_bus *bus, sd_bus_message **m) {
+ sd_bus_message *z = NULL;
+ int r, ret = 0;
+
+ assert(bus);
+ assert(m);
+ assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
+
+ if (bus->input_fd < 0)
+ return -ENOTCONN;
+
+ if (bus->rqueue_size > 0) {
+ /* Dispatch a queued message */
+
+ *m = bus->rqueue[0];
+ bus->rqueue_size --;
+ memmove(bus->rqueue, bus->rqueue + 1, sizeof(sd_bus_message*) * bus->rqueue_size);
+ return 1;
+ }
+
+ /* Try to read a new message */
+ do {
+ if (bus->is_kernel)
+ r = bus_kernel_read_message(bus, &z);
+ else
+ r = bus_socket_read_message(bus, &z);
+
+ if (r < 0) {
+ sd_bus_close(bus);
+ return r;
+ }
+ if (r == 0)
+ return ret;
+
+ r = 1;
+ } while (!z);
+
+ *m = z;
+ return 1;
+}
+
+int sd_bus_send(sd_bus *bus, sd_bus_message *m, uint64_t *serial) {
+ int r;
+
+ if (!bus)
+ return -EINVAL;
+ if (bus->state == BUS_UNSET)
+ return -ENOTCONN;
+ if (bus->output_fd < 0)
+ return -ENOTCONN;
+ if (!m)
+ return -EINVAL;
+
+ if (m->n_fds > 0) {
+ r = sd_bus_can_send(bus, SD_BUS_TYPE_UNIX_FD);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return -ENOTSUP;
+ }
+
+ /* If the serial number isn't kept, then we know that no reply
+ * is expected */
+ if (!serial && !m->sealed)
+ m->header->flags |= SD_BUS_MESSAGE_NO_REPLY_EXPECTED;
+
+ r = bus_seal_message(bus, m);
+ if (r < 0)
+ return r;
+
+ /* If this is a reply and no reply was requested, then let's
+ * suppress this, if we can */
+ if (m->dont_send && !serial)
+ return 0;
+
+ if ((bus->state == BUS_RUNNING || bus->state == BUS_HELLO) && bus->wqueue_size <= 0) {
+ size_t idx = 0;
+
+ if (bus->is_kernel)
+ r = bus_kernel_write_message(bus, m);
+ else
+ r = bus_socket_write_message(bus, m, &idx);
+
+ if (r < 0) {
+ sd_bus_close(bus);
+ return r;
+ } else if (!bus->is_kernel && idx < BUS_MESSAGE_SIZE(m)) {
+ /* Wasn't fully written. So let's remember how
+ * much was written. Note that the first entry
+ * of the wqueue array is always allocated so
+ * that we always can remember how much was
+ * written. */
+ bus->wqueue[0] = sd_bus_message_ref(m);
+ bus->wqueue_size = 1;
+ bus->windex = idx;
+ }
+ } else {
+ sd_bus_message **q;
+
+ /* Just append it to the queue. */
+
+ if (bus->wqueue_size >= BUS_WQUEUE_MAX)
+ return -ENOBUFS;
+
+ q = realloc(bus->wqueue, sizeof(sd_bus_message*) * (bus->wqueue_size + 1));
+ if (!q)
+ return -ENOMEM;
+
+ bus->wqueue = q;
+ q[bus->wqueue_size ++] = sd_bus_message_ref(m);
+ }
+
+ if (serial)
+ *serial = BUS_MESSAGE_SERIAL(m);
+
+ return 0;
+}
+
+static usec_t calc_elapse(uint64_t usec) {
+ if (usec == (uint64_t) -1)
+ return 0;
+
+ if (usec == 0)
+ usec = BUS_DEFAULT_TIMEOUT;
+
+ return now(CLOCK_MONOTONIC) + usec;
+}
+
+static int timeout_compare(const void *a, const void *b) {
+ const struct reply_callback *x = a, *y = b;
+
+ if (x->timeout != 0 && y->timeout == 0)
+ return -1;
+
+ if (x->timeout == 0 && y->timeout != 0)
+ return 1;
+
+ if (x->timeout < y->timeout)
+ return -1;
+
+ if (x->timeout > y->timeout)
+ return 1;
+
+ return 0;
+}
+
+int sd_bus_send_with_reply(
+ sd_bus *bus,
+ sd_bus_message *m,
+ sd_bus_message_handler_t callback,
+ void *userdata,
+ uint64_t usec,
+ uint64_t *serial) {
+
+ struct reply_callback *c;
+ int r;
+
+ if (!bus)
+ return -EINVAL;
+ if (bus->state == BUS_UNSET)
+ return -ENOTCONN;
+ if (bus->output_fd < 0)
+ return -ENOTCONN;
+ if (!m)
+ return -EINVAL;
+ if (!callback)
+ return -EINVAL;
+ if (m->header->type != SD_BUS_MESSAGE_TYPE_METHOD_CALL)
+ return -EINVAL;
+ if (m->header->flags & SD_BUS_MESSAGE_NO_REPLY_EXPECTED)
+ return -EINVAL;
+
+ r = hashmap_ensure_allocated(&bus->reply_callbacks, uint64_hash_func, uint64_compare_func);
+ if (r < 0)
+ return r;
+
+ if (usec != (uint64_t) -1) {
+ r = prioq_ensure_allocated(&bus->reply_callbacks_prioq, timeout_compare);
+ if (r < 0)
+ return r;
+ }
+
+ r = bus_seal_message(bus, m);
+ if (r < 0)
+ return r;
+
+ c = new0(struct reply_callback, 1);
+ if (!c)
+ return -ENOMEM;
+
+ c->callback = callback;
+ c->userdata = userdata;
+ c->serial = BUS_MESSAGE_SERIAL(m);
+ c->timeout = calc_elapse(usec);
+
+ r = hashmap_put(bus->reply_callbacks, &c->serial, c);
+ if (r < 0) {
+ free(c);
+ return r;
+ }
+
+ if (c->timeout != 0) {
+ r = prioq_put(bus->reply_callbacks_prioq, c, &c->prioq_idx);
+ if (r < 0) {
+ c->timeout = 0;
+ sd_bus_send_with_reply_cancel(bus, c->serial);
+ return r;
+ }
+ }
+
+ r = sd_bus_send(bus, m, serial);
+ if (r < 0) {
+ sd_bus_send_with_reply_cancel(bus, c->serial);
+ return r;
+ }
+
+ return r;
+}
+
+int sd_bus_send_with_reply_cancel(sd_bus *bus, uint64_t serial) {
+ struct reply_callback *c;
+
+ if (!bus)
+ return -EINVAL;
+ if (serial == 0)
+ return -EINVAL;
+
+ c = hashmap_remove(bus->reply_callbacks, &serial);
+ if (!c)
+ return 0;
+
+ if (c->timeout != 0)
+ prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
+
+ free(c);
+ return 1;
+}
+
+int bus_ensure_running(sd_bus *bus) {
+ int r;
+
+ assert(bus);
+
+ if (bus->input_fd < 0)
+ return -ENOTCONN;
+ if (bus->state == BUS_UNSET)
+ return -ENOTCONN;
+
+ if (bus->state == BUS_RUNNING)
+ return 1;
+
+ for (;;) {
+ r = sd_bus_process(bus, NULL);
+ if (r < 0)
+ return r;
+ if (bus->state == BUS_RUNNING)
+ return 1;
+ if (r > 0)
+ continue;
+
+ r = sd_bus_wait(bus, (uint64_t) -1);
+ if (r < 0)
+ return r;
+ }
+}
+
+int sd_bus_send_with_reply_and_block(
+ sd_bus *bus,
+ sd_bus_message *m,
+ uint64_t usec,
+ sd_bus_error *error,
+ sd_bus_message **reply) {
+
+ int r;
+ usec_t timeout;
+ uint64_t serial;
+ bool room = false;
+
+ if (!bus)
+ return -EINVAL;
+ if (bus->output_fd < 0)
+ return -ENOTCONN;
+ if (bus->state == BUS_UNSET)
+ return -ENOTCONN;
+ if (!m)
+ return -EINVAL;
+ if (m->header->type != SD_BUS_MESSAGE_TYPE_METHOD_CALL)
+ return -EINVAL;
+ if (m->header->flags & SD_BUS_MESSAGE_NO_REPLY_EXPECTED)
+ return -EINVAL;
+ if (bus_error_is_dirty(error))
+ return -EINVAL;
+
+ r = bus_ensure_running(bus);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_send(bus, m, &serial);
+ if (r < 0)
+ return r;
+
+ timeout = calc_elapse(usec);
+
+ for (;;) {
+ usec_t left;
+ sd_bus_message *incoming = NULL;
+
+ if (!room) {
+ sd_bus_message **q;
+
+ if (bus->rqueue_size >= BUS_RQUEUE_MAX)
+ return -ENOBUFS;
+
+ /* Make sure there's room for queuing this
+ * locally, before we read the message */
+
+ q = realloc(bus->rqueue, (bus->rqueue_size + 1) * sizeof(sd_bus_message*));
+ if (!q)
+ return -ENOMEM;
+
+ bus->rqueue = q;
+ room = true;
+ }
+
+ if (bus->is_kernel)
+ r = bus_kernel_read_message(bus, &incoming);
+ else
+ r = bus_socket_read_message(bus, &incoming);
+ if (r < 0)
+ return r;
+ if (incoming) {
+
+ if (incoming->reply_serial == serial) {
+ /* Found a match! */
+
+ if (incoming->header->type == SD_BUS_MESSAGE_TYPE_METHOD_RETURN) {
+
+ if (reply)
+ *reply = incoming;
+ else
+ sd_bus_message_unref(incoming);
+
+ return 0;
+ }
+
+ if (incoming->header->type == SD_BUS_MESSAGE_TYPE_METHOD_ERROR) {
+ int k;
+
+ r = sd_bus_error_copy(error, &incoming->error);
+ if (r < 0) {
+ sd_bus_message_unref(incoming);
+ return r;
+ }
+
+ k = bus_error_to_errno(&incoming->error);
+ sd_bus_message_unref(incoming);
+ return k;
+ }
+
+ sd_bus_message_unref(incoming);
+ return -EIO;
+ }
+
+ /* There's already guaranteed to be room for
+ * this, so need to resize things here */
+ bus->rqueue[bus->rqueue_size ++] = incoming;
+ room = false;
+
+ /* Try to read more, right-away */
+ continue;
+ }
+ if (r != 0)
+ continue;
+
+ if (timeout > 0) {
+ usec_t n;
+
+ n = now(CLOCK_MONOTONIC);
+ if (n >= timeout)
+ return -ETIMEDOUT;
+
+ left = timeout - n;
+ } else
+ left = (uint64_t) -1;
+
+ r = bus_poll(bus, true, left);
+ if (r < 0)
+ return r;
+
+ r = dispatch_wqueue(bus);
+ if (r < 0)
+ return r;
+ }
+}
+
+int sd_bus_get_fd(sd_bus *bus) {
+ if (!bus)
+ return -EINVAL;
+ if (bus->input_fd < 0)
+ return -ENOTCONN;
+ if (bus->input_fd != bus->output_fd)
+ return -EPERM;
+
+ return bus->input_fd;
+}
+
+int sd_bus_get_events(sd_bus *bus) {
+ int flags = 0;
+
+ if (!bus)
+ return -EINVAL;
+ if (bus->state == BUS_UNSET)
+ return -ENOTCONN;
+ if (bus->input_fd < 0)
+ return -ENOTCONN;
+
+ if (bus->state == BUS_OPENING)
+ flags |= POLLOUT;
+ else if (bus->state == BUS_AUTHENTICATING) {
+
+ if (bus_socket_auth_needs_write(bus))
+ flags |= POLLOUT;
+
+ flags |= POLLIN;
+
+ } else if (bus->state == BUS_RUNNING || bus->state == BUS_HELLO) {
+ if (bus->rqueue_size <= 0)
+ flags |= POLLIN;
+ if (bus->wqueue_size > 0)
+ flags |= POLLOUT;
+ }
+
+ return flags;
+}
+
+int sd_bus_get_timeout(sd_bus *bus, uint64_t *timeout_usec) {
+ struct reply_callback *c;
+
+ if (!bus)
+ return -EINVAL;
+ if (!timeout_usec)
+ return -EINVAL;
+ if (bus->state == BUS_UNSET)
+ return -ENOTCONN;
+ if (bus->input_fd < 0)
+ return -ENOTCONN;
+
+ if (bus->state == BUS_AUTHENTICATING) {
+ *timeout_usec = bus->auth_timeout;
+ return 1;
+ }
+
+ if (bus->state != BUS_RUNNING && bus->state != BUS_HELLO) {
+ *timeout_usec = (uint64_t) -1;
+ return 0;
+ }
+
+ c = prioq_peek(bus->reply_callbacks_prioq);
+ if (!c) {
+ *timeout_usec = (uint64_t) -1;
+ return 0;
+ }
+
+ *timeout_usec = c->timeout;
+ return 1;
+}
+
+static int process_timeout(sd_bus *bus) {
+ struct reply_callback *c;
+ usec_t n;
+ int r;
+
+ assert(bus);
+
+ c = prioq_peek(bus->reply_callbacks_prioq);
+ if (!c)
+ return 0;
+
+ n = now(CLOCK_MONOTONIC);
+ if (c->timeout > n)
+ return 0;
+
+ assert_se(prioq_pop(bus->reply_callbacks_prioq) == c);
+ hashmap_remove(bus->reply_callbacks, &c->serial);
+
+ r = c->callback(bus, ETIMEDOUT, NULL, c->userdata);
+ free(c);
+
+ return r < 0 ? r : 1;
+}
+
+static int process_hello(sd_bus *bus, sd_bus_message *m) {
+ assert(bus);
+ assert(m);
+
+ if (bus->state != BUS_HELLO)
+ return 0;
+
+ /* Let's make sure the first message on the bus is the HELLO
+ * reply. But note that we don't actually parse the message
+ * here (we leave that to the usual handling), we just verify
+ * we don't let any earlier msg through. */
+
+ if (m->header->type != SD_BUS_MESSAGE_TYPE_METHOD_RETURN &&
+ m->header->type != SD_BUS_MESSAGE_TYPE_METHOD_ERROR)
+ return -EIO;
+
+ if (m->reply_serial != bus->hello_serial)
+ return -EIO;
+
+ return 0;
+}
+
+static int process_reply(sd_bus *bus, sd_bus_message *m) {
+ struct reply_callback *c;
+ int r;
+
+ assert(bus);
+ assert(m);
+
+ if (m->header->type != SD_BUS_MESSAGE_TYPE_METHOD_RETURN &&
+ m->header->type != SD_BUS_MESSAGE_TYPE_METHOD_ERROR)
+ return 0;
+
+ c = hashmap_remove(bus->reply_callbacks, &m->reply_serial);
+ if (!c)
+ return 0;
+
+ if (c->timeout != 0)
+ prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
+
+ r = sd_bus_message_rewind(m, true);
+ if (r < 0)
+ return r;
+
+ r = c->callback(bus, 0, m, c->userdata);
+ free(c);
+
+ return r;
+}
+
+static int process_filter(sd_bus *bus, sd_bus_message *m) {
+ struct filter_callback *l;
+ int r;
+
+ assert(bus);
+ assert(m);
+
+ do {
+ bus->filter_callbacks_modified = false;
+
+ LIST_FOREACH(callbacks, l, bus->filter_callbacks) {
+
+ if (bus->filter_callbacks_modified)
+ break;
+
+ /* Don't run this more than once per iteration */
+ if (l->last_iteration == bus->iteration_counter)
+ continue;
+
+ l->last_iteration = bus->iteration_counter;
+
+ r = sd_bus_message_rewind(m, true);
+ if (r < 0)
+ return r;
+
+ r = l->callback(bus, 0, m, l->userdata);
+ if (r != 0)
+ return r;
+
+ }
+
+ } while (bus->filter_callbacks_modified);
+
+ return 0;
+}
+
+static int process_match(sd_bus *bus, sd_bus_message *m) {
+ int r;
+
+ assert(bus);
+ assert(m);
+
+ do {
+ bus->match_callbacks_modified = false;
+
+ r = bus_match_run(bus, &bus->match_callbacks, 0, m);
+ if (r != 0)
+ return r;
+
+ } while (bus->match_callbacks_modified);
+
+ return 0;
+}
+
+static int process_builtin(sd_bus *bus, sd_bus_message *m) {
+ _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
+ int r;
+
+ assert(bus);
+ assert(m);
+
+ if (m->header->type != SD_BUS_MESSAGE_TYPE_METHOD_CALL)
+ return 0;
+
+ if (!streq_ptr(m->interface, "org.freedesktop.DBus.Peer"))
+ return 0;
+
+ if (m->header->flags & SD_BUS_MESSAGE_NO_REPLY_EXPECTED)
+ return 1;
+
+ if (streq_ptr(m->member, "Ping"))
+ r = sd_bus_message_new_method_return(bus, m, &reply);
+ else if (streq_ptr(m->member, "GetMachineId")) {
+ sd_id128_t id;
+ char sid[33];
+
+ r = sd_id128_get_machine(&id);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_new_method_return(bus, m, &reply);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_append(reply, "s", sd_id128_to_string(id, sid));
+ } else {
+ _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
+
+ sd_bus_error_set(&error,
+ "org.freedesktop.DBus.Error.UnknownMethod",
+ "Unknown method '%s' on interface '%s'.", m->member, m->interface);
+
+ r = sd_bus_message_new_method_error(bus, m, &error, &reply);
+ }
+
+ if (r < 0)
+ return r;
+
+ r = sd_bus_send(bus, reply, NULL);
+ if (r < 0)
+ return r;
+
+ return 1;
+}
+
+static int process_object(sd_bus *bus, sd_bus_message *m) {
+ _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
+ _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
+ struct object_callback *c;
+ int r;
+ bool found = false;
+ size_t pl;
+
+ assert(bus);
+ assert(m);
+
+ if (m->header->type != SD_BUS_MESSAGE_TYPE_METHOD_CALL)
+ return 0;
+
+ if (hashmap_isempty(bus->object_callbacks))
+ return 0;
+
+ pl = strlen(m->path);
+
+ do {
+ char p[pl+1];
+
+ bus->object_callbacks_modified = false;
+
+ c = hashmap_get(bus->object_callbacks, m->path);
+ if (c && c->last_iteration != bus->iteration_counter) {
+
+ c->last_iteration = bus->iteration_counter;
+
+ r = sd_bus_message_rewind(m, true);
+ if (r < 0)
+ return r;
+
+ r = c->callback(bus, 0, m, c->userdata);
+ if (r != 0)
+ return r;
+
+ found = true;
+ }
+
+ /* Look for fallback prefixes */
+ strcpy(p, m->path);
+ for (;;) {
+ char *e;
+
+ if (bus->object_callbacks_modified)
+ break;
+
+ e = strrchr(p, '/');
+ if (e == p || !e)
+ break;
+
+ *e = 0;
+
+ c = hashmap_get(bus->object_callbacks, p);
+ if (c && c->last_iteration != bus->iteration_counter && c->is_fallback) {
+
+ c->last_iteration = bus->iteration_counter;
+
+ r = sd_bus_message_rewind(m, true);
+ if (r < 0)
+ return r;
+
+ r = c->callback(bus, 0, m, c->userdata);
+ if (r != 0)
+ return r;
+
+ found = true;
+ }
+ }
+
+ } while (bus->object_callbacks_modified);
+
+ /* We found some handlers but none wanted to take this, then
+ * return this -- with one exception, we can handle
+ * introspection minimally ourselves */
+ if (!found || sd_bus_message_is_method_call(m, "org.freedesktop.DBus.Introspectable", "Introspect"))
+ return 0;
+
+ sd_bus_error_set(&error,
+ "org.freedesktop.DBus.Error.UnknownMethod",
+ "Unknown method '%s' or interface '%s'.", m->member, m->interface);
+
+ r = sd_bus_message_new_method_error(bus, m, &error, &reply);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_send(bus, reply, NULL);
+ if (r < 0)
+ return r;
+
+ return 1;
+}
+
+static int process_introspect(sd_bus *bus, sd_bus_message *m) {
+ _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
+ _cleanup_free_ char *introspection = NULL;
+ _cleanup_set_free_free_ Set *s = NULL;
+ _cleanup_fclose_ FILE *f = NULL;
+ struct object_callback *c;
+ Iterator i;
+ size_t size = 0;
+ char *node;
+ int r;
+
+ assert(bus);
+ assert(m);
+
+ if (!sd_bus_message_is_method_call(m, "org.freedesktop.DBus.Introspectable", "Introspect"))
+ return 0;
+
+ if (!m->path)
+ return 0;
+
+ s = set_new(string_hash_func, string_compare_func);
+ if (!s)
+ return -ENOMEM;
+
+ HASHMAP_FOREACH(c, bus->object_callbacks, i) {
+ const char *e;
+ char *a, *p;
+
+ if (streq(c->path, "/"))
+ continue;
+
+ if (streq(m->path, "/"))
+ e = c->path;
+ else {
+ e = startswith(c->path, m->path);
+ if (!e || *e != '/')
+ continue;
+ }
+
+ a = strdup(e+1);
+ if (!a)
+ return -ENOMEM;
+
+ p = strchr(a, '/');
+ if (p)
+ *p = 0;
+
+ r = set_consume(s, a);
+ if (r < 0 && r != -EEXIST)
+ return r;
+ }
+
+ f = open_memstream(&introspection, &size);
+ if (!f)
+ return -ENOMEM;
+
+ fputs(SD_BUS_INTROSPECT_DOCTYPE, f);
+ fputs("<node>\n", f);
+ fputs(SD_BUS_INTROSPECT_INTERFACE_PEER, f);
+ fputs(SD_BUS_INTROSPECT_INTERFACE_INTROSPECTABLE, f);
+
+ while ((node = set_steal_first(s))) {
+ fprintf(f, " <node name=\"%s\"/>\n", node);
+ free(node);
+ }
+
+ fputs("</node>\n", f);
+
+ fflush(f);
+
+ if (ferror(f))
+ return -ENOMEM;
+
+ r = sd_bus_message_new_method_return(bus, m, &reply);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_append(reply, "s", introspection);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_send(bus, reply, NULL);
+ if (r < 0)
+ return r;
+
+ return 1;
+}
+
+static int process_message(sd_bus *bus, sd_bus_message *m) {
+ int r;
+
+ assert(bus);
+ assert(m);
+
+ bus->iteration_counter++;
+
+ r = process_hello(bus, m);
+ if (r != 0)
+ return r;
+
+ r = process_reply(bus, m);
+ if (r != 0)
+ return r;
+
+ r = process_filter(bus, m);
+ if (r != 0)
+ return r;
+
+ r = process_match(bus, m);
+ if (r != 0)
+ return r;
+
+ r = process_builtin(bus, m);
+ if (r != 0)
+ return r;
+
+ r = process_object(bus, m);
+ if (r != 0)
+ return r;
+
+ return process_introspect(bus, m);
+}
+
+static int process_running(sd_bus *bus, sd_bus_message **ret) {
+ _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
+ int r;
+
+ assert(bus);
+ assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
+
+ r = process_timeout(bus);
+ if (r != 0)
+ goto null_message;
+
+ r = dispatch_wqueue(bus);
+ if (r != 0)
+ goto null_message;
+
+ r = dispatch_rqueue(bus, &m);
+ if (r < 0)
+ return r;
+ if (!m)
+ goto null_message;
+
+ r = process_message(bus, m);
+ if (r != 0)
+ goto null_message;
+
+ if (ret) {
+ r = sd_bus_message_rewind(m, true);
+ if (r < 0)
+ return r;
+
+ *ret = m;
+ m = NULL;
+ return 1;
+ }
+
+ if (m->header->type == SD_BUS_MESSAGE_TYPE_METHOD_CALL) {
+ _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
+ _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
+
+ sd_bus_error_set(&error, "org.freedesktop.DBus.Error.UnknownObject", "Unknown object '%s'.", m->path);
+
+ r = sd_bus_message_new_method_error(bus, m, &error, &reply);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_send(bus, reply, NULL);
+ if (r < 0)
+ return r;
+ }
+
+ return 1;
+
+null_message:
+ if (r >= 0 && ret)
+ *ret = NULL;
+
+ return r;
+}
+
+int sd_bus_process(sd_bus *bus, sd_bus_message **ret) {
+ int r;
+
+ /* Returns 0 when we didn't do anything. This should cause the
+ * caller to invoke sd_bus_wait() before returning the next
+ * time. Returns > 0 when we did something, which possibly
+ * means *ret is filled in with an unprocessed message. */
+
+ if (!bus)
+ return -EINVAL;
+ if (bus->input_fd < 0)
+ return -ENOTCONN;
+
+ /* We don't allow recursively invoking sd_bus_process(). */
+ if (bus->processing)
+ return -EBUSY;
+
+ switch (bus->state) {
+
+ case BUS_UNSET:
+ return -ENOTCONN;
+
+ case BUS_OPENING:
+ r = bus_socket_process_opening(bus);
+ if (r < 0)
+ return r;
+ if (ret)
+ *ret = NULL;
+ return r;
+
+ case BUS_AUTHENTICATING:
+
+ r = bus_socket_process_authenticating(bus);
+ if (r < 0)
+ return r;
+ if (ret)
+ *ret = NULL;
+ return r;
+
+ case BUS_RUNNING:
+ case BUS_HELLO:
+
+ bus->processing = true;
+ r = process_running(bus, ret);
+ bus->processing = false;
+
+ return r;
+ }
+
+ assert_not_reached("Unknown state");
+}
+
+static int bus_poll(sd_bus *bus, bool need_more, uint64_t timeout_usec) {
+ struct pollfd p[2] = {};
+ int r, e, n;
+ struct timespec ts;
+ usec_t until, m;
+
+ assert(bus);
+
+ if (bus->input_fd < 0)
+ return -ENOTCONN;
+
+ e = sd_bus_get_events(bus);
+ if (e < 0)
+ return e;
+
+ if (need_more)
+ e |= POLLIN;
+
+ r = sd_bus_get_timeout(bus, &until);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ m = (uint64_t) -1;
+ else {
+ usec_t nw;
+ nw = now(CLOCK_MONOTONIC);
+ m = until > nw ? until - nw : 0;
+ }
+
+ if (timeout_usec != (uint64_t) -1 && (m == (uint64_t) -1 || timeout_usec < m))
+ m = timeout_usec;
+
+ p[0].fd = bus->input_fd;
+ if (bus->output_fd == bus->input_fd) {
+ p[0].events = e;
+ n = 1;
+ } else {
+ p[0].events = e & POLLIN;
+ p[1].fd = bus->output_fd;
+ p[1].events = e & POLLOUT;
+ n = 2;
+ }
+
+ r = ppoll(p, n, m == (uint64_t) -1 ? NULL : timespec_store(&ts, m), NULL);
+ if (r < 0)
+ return -errno;
+
+ return r > 0 ? 1 : 0;
+}
+
+int sd_bus_wait(sd_bus *bus, uint64_t timeout_usec) {
+
+ if (!bus)
+ return -EINVAL;
+ if (bus->state == BUS_UNSET)
+ return -ENOTCONN;
+ if (bus->input_fd < 0)
+ return -ENOTCONN;
+ if (bus->rqueue_size > 0)
+ return 0;
+
+ return bus_poll(bus, false, timeout_usec);
+}
+
+int sd_bus_flush(sd_bus *bus) {
+ int r;
+
+ if (!bus)
+ return -EINVAL;
+ if (bus->state == BUS_UNSET)
+ return -ENOTCONN;
+ if (bus->output_fd < 0)
+ return -ENOTCONN;
+
+ r = bus_ensure_running(bus);
+ if (r < 0)
+ return r;
+
+ if (bus->wqueue_size <= 0)
+ return 0;
+
+ for (;;) {
+ r = dispatch_wqueue(bus);
+ if (r < 0)
+ return r;
+
+ if (bus->wqueue_size <= 0)
+ return 0;
+
+ r = bus_poll(bus, false, (uint64_t) -1);
+ if (r < 0)
+ return r;
+ }
+}
+
+int sd_bus_add_filter(sd_bus *bus, sd_bus_message_handler_t callback, void *userdata) {
+ struct filter_callback *f;
+
+ if (!bus)
+ return -EINVAL;
+ if (!callback)
+ return -EINVAL;
+
+ f = new0(struct filter_callback, 1);
+ if (!f)
+ return -ENOMEM;
+ f->callback = callback;
+ f->userdata = userdata;
+
+ bus->filter_callbacks_modified = true;
+ LIST_PREPEND(struct filter_callback, callbacks, bus->filter_callbacks, f);
+ return 0;
+}
+
+int sd_bus_remove_filter(sd_bus *bus, sd_bus_message_handler_t callback, void *userdata) {
+ struct filter_callback *f;
+
+ if (!bus)
+ return -EINVAL;
+ if (!callback)
+ return -EINVAL;
+
+ LIST_FOREACH(callbacks, f, bus->filter_callbacks) {
+ if (f->callback == callback && f->userdata == userdata) {
+ bus->filter_callbacks_modified = true;
+ LIST_REMOVE(struct filter_callback, callbacks, bus->filter_callbacks, f);
+ free(f);
+ return 1;
+ }
+ }
+
+ return 0;
+}
+
+static int bus_add_object(
+ sd_bus *bus,
+ bool fallback,
+ const char *path,
+ sd_bus_message_handler_t callback,
+ void *userdata) {
+
+ struct object_callback *c;
+ int r;
+
+ if (!bus)
+ return -EINVAL;
+ if (!path)
+ return -EINVAL;
+ if (!callback)
+ return -EINVAL;
+
+ r = hashmap_ensure_allocated(&bus->object_callbacks, string_hash_func, string_compare_func);
+ if (r < 0)
+ return r;
+
+ c = new0(struct object_callback, 1);
+ if (!c)
+ return -ENOMEM;
+
+ c->path = strdup(path);
+ if (!c->path) {
+ free(c);
+ return -ENOMEM;
+ }
+
+ c->callback = callback;
+ c->userdata = userdata;
+ c->is_fallback = fallback;
+
+ bus->object_callbacks_modified = true;
+ r = hashmap_put(bus->object_callbacks, c->path, c);
+ if (r < 0) {
+ free(c->path);
+ free(c);
+ return r;
+ }
+
+ return 0;
+}
+
+static int bus_remove_object(
+ sd_bus *bus,
+ bool fallback,
+ const char *path,
+ sd_bus_message_handler_t callback,
+ void *userdata) {
+
+ struct object_callback *c;
+
+ if (!bus)
+ return -EINVAL;
+ if (!path)
+ return -EINVAL;
+ if (!callback)
+ return -EINVAL;
+
+ c = hashmap_get(bus->object_callbacks, path);
+ if (!c)
+ return 0;
+
+ if (c->callback != callback || c->userdata != userdata || c->is_fallback != fallback)
+ return 0;
+
+ bus->object_callbacks_modified = true;
+ assert_se(c == hashmap_remove(bus->object_callbacks, c->path));
+
+ free(c->path);
+ free(c);
+
+ return 1;
+}
+
+int sd_bus_add_object(sd_bus *bus, const char *path, sd_bus_message_handler_t callback, void *userdata) {
+ return bus_add_object(bus, false, path, callback, userdata);
+}
+
+int sd_bus_remove_object(sd_bus *bus, const char *path, sd_bus_message_handler_t callback, void *userdata) {
+ return bus_remove_object(bus, false, path, callback, userdata);
+}
+
+int sd_bus_add_fallback(sd_bus *bus, const char *prefix, sd_bus_message_handler_t callback, void *userdata) {
+ return bus_add_object(bus, true, prefix, callback, userdata);
+}
+
+int sd_bus_remove_fallback(sd_bus *bus, const char *prefix, sd_bus_message_handler_t callback, void *userdata) {
+ return bus_remove_object(bus, true, prefix, callback, userdata);
+}
+
+int sd_bus_add_match(sd_bus *bus, const char *match, sd_bus_message_handler_t callback, void *userdata) {
+ int r = 0;
+
+ if (!bus)
+ return -EINVAL;
+ if (!match)
+ return -EINVAL;
+
+ if (bus->bus_client) {
+ r = bus_add_match_internal(bus, match);
+ if (r < 0)
+ return r;
+ }
+
+ if (callback) {
+ bus->match_callbacks_modified = true;
+ r = bus_match_add(&bus->match_callbacks, match, callback, userdata, NULL);
+ if (r < 0) {
+
+ if (bus->bus_client)
+ bus_remove_match_internal(bus, match);
+ }
+ }
+
+ return r;
+}
+
+int sd_bus_remove_match(sd_bus *bus, const char *match, sd_bus_message_handler_t callback, void *userdata) {
+ int r = 0, q = 0;
+
+ if (!bus)
+ return -EINVAL;
+ if (!match)
+ return -EINVAL;
+
+ if (bus->bus_client)
+ r = bus_remove_match_internal(bus, match);
+
+ if (callback) {
+ bus->match_callbacks_modified = true;
+ q = bus_match_remove(&bus->match_callbacks, match, callback, userdata);
+ }
+
+ if (r < 0)
+ return r;
+ return q;
+}
+
+int sd_bus_emit_signal(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *member,
+ const char *types, ...) {
+
+ _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
+ va_list ap;
+ int r;
+
+ if (!bus)
+ return -EINVAL;
+
+ r = sd_bus_message_new_signal(bus, path, interface, member, &m);
+ if (r < 0)
+ return r;
+
+ va_start(ap, types);
+ r = bus_message_append_ap(m, types, ap);
+ va_end(ap);
+ if (r < 0)
+ return r;
+
+ return sd_bus_send(bus, m, NULL);
+}
+
+int sd_bus_call_method(
+ sd_bus *bus,
+ const char *destination,
+ const char *path,
+ const char *interface,
+ const char *member,
+ sd_bus_error *error,
+ sd_bus_message **reply,
+ const char *types, ...) {
+
+ _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
+ va_list ap;
+ int r;
+
+ if (!bus)
+ return -EINVAL;
+
+ r = sd_bus_message_new_method_call(bus, destination, path, interface, member, &m);
+ if (r < 0)
+ return r;
+
+ va_start(ap, types);
+ r = bus_message_append_ap(m, types, ap);
+ va_end(ap);
+ if (r < 0)
+ return r;
+
+ return sd_bus_send_with_reply_and_block(bus, m, 0, error, reply);
+}
+
+int sd_bus_reply_method_return(
+ sd_bus *bus,
+ sd_bus_message *call,
+ const char *types, ...) {
+
+ _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
+ va_list ap;
+ int r;
+
+ if (!bus)
+ return -EINVAL;
+ if (!call)
+ return -EINVAL;
+ if (!call->sealed)
+ return -EPERM;
+ if (call->header->type != SD_BUS_MESSAGE_TYPE_METHOD_CALL)
+ return -EINVAL;
+
+ if (call->header->flags & SD_BUS_MESSAGE_NO_REPLY_EXPECTED)
+ return 0;
+
+ r = sd_bus_message_new_method_return(bus, call, &m);
+ if (r < 0)
+ return r;
+
+ va_start(ap, types);
+ r = bus_message_append_ap(m, types, ap);
+ va_end(ap);
+ if (r < 0)
+ return r;
+
+ return sd_bus_send(bus, m, NULL);
+}
+
+int sd_bus_reply_method_error(
+ sd_bus *bus,
+ sd_bus_message *call,
+ const sd_bus_error *e) {
+
+ _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
+ int r;
+
+ if (!bus)
+ return -EINVAL;
+ if (!call)
+ return -EINVAL;
+ if (!call->sealed)
+ return -EPERM;
+ if (call->header->type != SD_BUS_MESSAGE_TYPE_METHOD_CALL)
+ return -EINVAL;
+ if (!sd_bus_error_is_set(e))
+ return -EINVAL;
+
+ if (call->header->flags & SD_BUS_MESSAGE_NO_REPLY_EXPECTED)
+ return 0;
+
+ r = sd_bus_message_new_method_error(bus, call, e, &m);
+ if (r < 0)
+ return r;
+
+ return sd_bus_send(bus, m, NULL);
+}
diff --git a/src/libsystemd-bus/test-bus-chat.c b/src/libsystemd-bus/test-bus-chat.c
new file mode 100644
index 0000000000..f457c8f88a
--- /dev/null
+++ b/src/libsystemd-bus/test-bus-chat.c
@@ -0,0 +1,576 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <stdlib.h>
+#include <pthread.h>
+#include <unistd.h>
+#include <fcntl.h>
+
+#include "log.h"
+#include "util.h"
+#include "macro.h"
+
+#include "sd-bus.h"
+#include "bus-message.h"
+#include "bus-error.h"
+#include "bus-match.h"
+#include "bus-internal.h"
+
+static int match_callback(sd_bus *bus, int error, sd_bus_message *m, void *userdata) {
+ log_info("Match triggered! interface=%s member=%s", strna(sd_bus_message_get_interface(m)), strna(sd_bus_message_get_member(m)));
+ return 0;
+}
+
+static int object_callback(sd_bus *bus, int error, sd_bus_message *m, void *userdata) {
+ int r;
+
+ assert(bus);
+
+ if (error != 0)
+ return 0;
+
+ if (sd_bus_message_is_method_call(m, "org.object.test", "Foobar")) {
+ log_info("Invoked Foobar() on %s", sd_bus_message_get_path(m));
+
+ r = sd_bus_reply_method_return(bus, m, NULL);
+ if (r < 0) {
+ log_error("Failed to send reply: %s", strerror(-r));
+ return r;
+ }
+
+ return 1;
+ }
+
+ return 0;
+}
+
+static int server_init(sd_bus **_bus) {
+ sd_bus *bus = NULL;
+ sd_id128_t id;
+ int r;
+ const char *unique;
+
+ assert(_bus);
+
+ r = sd_bus_open_user(&bus);
+ if (r < 0) {
+ log_error("Failed to connect to user bus: %s", strerror(-r));
+ goto fail;
+ }
+
+ r = sd_bus_get_server_id(bus, &id);
+ if (r < 0) {
+ log_error("Failed to get server ID: %s", strerror(-r));
+ goto fail;
+ }
+
+ r = sd_bus_get_unique_name(bus, &unique);
+ if (r < 0) {
+ log_error("Failed to get unique name: %s", strerror(-r));
+ goto fail;
+ }
+
+ log_info("Peer ID is " SD_ID128_FORMAT_STR ".", SD_ID128_FORMAT_VAL(id));
+ log_info("Unique ID: %s", unique);
+ log_info("Can send file handles: %i", sd_bus_can_send(bus, 'h'));
+
+ r = sd_bus_request_name(bus, "org.freedesktop.systemd.test", 0);
+ if (r < 0) {
+ log_error("Failed to acquire name: %s", strerror(-r));
+ goto fail;
+ }
+
+ r = sd_bus_add_fallback(bus, "/foo/bar", object_callback, NULL);
+ if (r < 0) {
+ log_error("Failed to add object: %s", strerror(-r));
+ goto fail;
+ }
+
+ r = sd_bus_add_match(bus, "type='signal',interface='foo.bar',member='Notify'", match_callback, NULL);
+ if (r < 0) {
+ log_error("Failed to add match: %s", strerror(-r));
+ goto fail;
+ }
+
+ r = sd_bus_add_match(bus, "type='signal',interface='org.freedesktop.DBus',member='NameOwnerChanged'", match_callback, NULL);
+ if (r < 0) {
+ log_error("Failed to add match: %s", strerror(-r));
+ goto fail;
+ }
+
+ bus_match_dump(&bus->match_callbacks, 0);
+
+ *_bus = bus;
+ return 0;
+
+fail:
+ if (bus)
+ sd_bus_unref(bus);
+
+ return r;
+}
+
+static int server(sd_bus *bus) {
+ int r;
+ bool client1_gone = false, client2_gone = false;
+
+ while (!client1_gone || !client2_gone) {
+ _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
+ pid_t pid = 0;
+ const char *label = NULL;
+
+ r = sd_bus_process(bus, &m);
+ if (r < 0) {
+ log_error("Failed to process requests: %s", strerror(-r));
+ goto fail;
+ }
+
+ if (r == 0) {
+ r = sd_bus_wait(bus, (uint64_t) -1);
+ if (r < 0) {
+ log_error("Failed to wait: %s", strerror(-r));
+ goto fail;
+ }
+
+ continue;
+ }
+
+ if (!m)
+ continue;
+
+ sd_bus_message_get_pid(m, &pid);
+ sd_bus_message_get_selinux_context(m, &label);
+ log_info("Got message! member=%s pid=%lu label=%s",
+ strna(sd_bus_message_get_member(m)),
+ (unsigned long) pid,
+ strna(label));
+ /* bus_message_dump(m); */
+ /* sd_bus_message_rewind(m, true); */
+
+ if (sd_bus_message_is_method_call(m, "org.freedesktop.systemd.test", "LowerCase")) {
+ const char *hello;
+ _cleanup_free_ char *lowercase = NULL;
+
+ r = sd_bus_message_read(m, "s", &hello);
+ if (r < 0) {
+ log_error("Failed to get parameter: %s", strerror(-r));
+ goto fail;
+ }
+
+ lowercase = strdup(hello);
+ if (!lowercase) {
+ r = log_oom();
+ goto fail;
+ }
+
+ ascii_strlower(lowercase);
+
+ r = sd_bus_reply_method_return(bus, m, "s", lowercase);
+ if (r < 0) {
+ log_error("Failed to send reply: %s", strerror(-r));
+ goto fail;
+ }
+ } else if (sd_bus_message_is_method_call(m, "org.freedesktop.systemd.test", "ExitClient1")) {
+
+ r = sd_bus_reply_method_return(bus, m, NULL);
+ if (r < 0) {
+ log_error("Failed to send reply: %s", strerror(-r));
+ goto fail;
+ }
+
+ client1_gone = true;
+ } else if (sd_bus_message_is_method_call(m, "org.freedesktop.systemd.test", "ExitClient2")) {
+
+ r = sd_bus_reply_method_return(bus, m, NULL);
+ if (r < 0) {
+ log_error("Failed to send reply: %s", strerror(-r));
+ goto fail;
+ }
+
+ client2_gone = true;
+ } else if (sd_bus_message_is_method_call(m, "org.freedesktop.systemd.test", "Slow")) {
+
+ sleep(1);
+
+ r = sd_bus_reply_method_return(bus, m, NULL);
+ if (r < 0) {
+ log_error("Failed to send reply: %s", strerror(-r));
+ goto fail;
+ }
+
+ } else if (sd_bus_message_is_method_call(m, "org.freedesktop.systemd.test", "FileDescriptor")) {
+ int fd;
+ static const char x = 'X';
+
+ r = sd_bus_message_read(m, "h", &fd);
+ if (r < 0) {
+ log_error("Failed to get parameter: %s", strerror(-r));
+ goto fail;
+ }
+
+ if (write(fd, &x, 1) < 0) {
+ log_error("Failed to write to fd: %m");
+ close_nointr_nofail(fd);
+ goto fail;
+ }
+
+ r = sd_bus_reply_method_return(bus, m, NULL);
+ if (r < 0) {
+ log_error("Failed to send reply: %s", strerror(-r));
+ goto fail;
+ }
+
+ } else if (sd_bus_message_is_method_call(m, NULL, NULL)) {
+
+ r = sd_bus_reply_method_error(
+ bus, m,
+ &SD_BUS_ERROR_MAKE("org.freedesktop.DBus.Error.UnknownMethod", "Unknown method."));
+ if (r < 0) {
+ log_error("Failed to send reply: %s", strerror(-r));
+ goto fail;
+ }
+ }
+ }
+
+ r = 0;
+
+fail:
+ if (bus) {
+ sd_bus_flush(bus);
+ sd_bus_unref(bus);
+ }
+
+ return r;
+}
+
+static void* client1(void*p) {
+ _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
+ sd_bus *bus = NULL;
+ sd_bus_error error = SD_BUS_ERROR_NULL;
+ const char *hello;
+ int r;
+ int pp[2] = { -1, -1 };
+ char x;
+
+ r = sd_bus_open_user(&bus);
+ if (r < 0) {
+ log_error("Failed to connect to user bus: %s", strerror(-r));
+ goto finish;
+ }
+
+ r = sd_bus_call_method(
+ bus,
+ "org.freedesktop.systemd.test",
+ "/",
+ "org.freedesktop.systemd.test",
+ "LowerCase",
+ &error,
+ &reply,
+ "s",
+ "HELLO");
+ if (r < 0) {
+ log_error("Failed to issue method call: %s", strerror(-r));
+ goto finish;
+ }
+
+ r = sd_bus_message_read(reply, "s", &hello);
+ if (r < 0) {
+ log_error("Failed to get string: %s", strerror(-r));
+ goto finish;
+ }
+
+ assert(streq(hello, "hello"));
+
+ if (pipe2(pp, O_CLOEXEC|O_NONBLOCK) < 0) {
+ log_error("Failed to allocate pipe: %m");
+ r = -errno;
+ goto finish;
+ }
+
+ r = sd_bus_call_method(
+ bus,
+ "org.freedesktop.systemd.test",
+ "/",
+ "org.freedesktop.systemd.test",
+ "FileDescriptor",
+ &error,
+ NULL,
+ "h",
+ pp[1]);
+ if (r < 0) {
+ log_error("Failed to issue method call: %s", strerror(-r));
+ goto finish;
+ }
+
+ errno = 0;
+ if (read(pp[0], &x, 1) <= 0) {
+ log_error("Failed to read from pipe: %s", errno ? strerror(errno) : "early read");
+ goto finish;
+ }
+
+ r = 0;
+
+finish:
+ if (bus) {
+ _cleanup_bus_message_unref_ sd_bus_message *q;
+
+ r = sd_bus_message_new_method_call(
+ bus,
+ "org.freedesktop.systemd.test",
+ "/",
+ "org.freedesktop.systemd.test",
+ "ExitClient1",
+ &q);
+ if (r < 0)
+ log_error("Failed to allocate method call: %s", strerror(-r));
+ else
+ sd_bus_send(bus, q, NULL);
+
+ sd_bus_flush(bus);
+ sd_bus_unref(bus);
+ }
+
+ sd_bus_error_free(&error);
+
+ close_pipe(pp);
+
+ return INT_TO_PTR(r);
+}
+
+static int quit_callback(sd_bus *b, int ret, sd_bus_message *m, void *userdata) {
+ bool *x = userdata;
+
+ log_error("Quit callback: %s", strerror(ret));
+
+ *x = 1;
+ return 1;
+}
+
+static void* client2(void*p) {
+ _cleanup_bus_message_unref_ sd_bus_message *m = NULL, *reply = NULL;
+ sd_bus *bus = NULL;
+ sd_bus_error error = SD_BUS_ERROR_NULL;
+ bool quit = false;
+ const char *mid;
+ int r;
+
+ r = sd_bus_open_user(&bus);
+ if (r < 0) {
+ log_error("Failed to connect to user bus: %s", strerror(-r));
+ goto finish;
+ }
+
+ r = sd_bus_message_new_method_call(
+ bus,
+ "org.freedesktop.systemd.test",
+ "/foo/bar/waldo/piep",
+ "org.object.test",
+ "Foobar",
+ &m);
+ if (r < 0) {
+ log_error("Failed to allocate method call: %s", strerror(-r));
+ goto finish;
+ }
+
+ r = sd_bus_send(bus, m, NULL);
+ if (r < 0) {
+ log_error("Failed to issue method call: %s", bus_error_message(&error, -r));
+ goto finish;
+ }
+
+ sd_bus_message_unref(m);
+ m = NULL;
+
+ r = sd_bus_message_new_signal(
+ bus,
+ "/foobar",
+ "foo.bar",
+ "Notify",
+ &m);
+ if (r < 0) {
+ log_error("Failed to allocate signal: %s", strerror(-r));
+ goto finish;
+ }
+
+ r = sd_bus_send(bus, m, NULL);
+ if (r < 0) {
+ log_error("Failed to issue signal: %s", bus_error_message(&error, -r));
+ goto finish;
+ }
+
+ sd_bus_message_unref(m);
+ m = NULL;
+
+ r = sd_bus_message_new_method_call(
+ bus,
+ "org.freedesktop.systemd.test",
+ "/",
+ "org.freedesktop.DBus.Peer",
+ "GetMachineId",
+ &m);
+ if (r < 0) {
+ log_error("Failed to allocate method call: %s", strerror(-r));
+ goto finish;
+ }
+
+ r = sd_bus_send_with_reply_and_block(bus, m, 0, &error, &reply);
+ if (r < 0) {
+ log_error("Failed to issue method call: %s", bus_error_message(&error, -r));
+ goto finish;
+ }
+
+ r = sd_bus_message_read(reply, "s", &mid);
+ if (r < 0) {
+ log_error("Failed to parse machine ID: %s", strerror(-r));
+ goto finish;
+ }
+
+ log_info("Machine ID is %s.", mid);
+
+ sd_bus_message_unref(m);
+ m = NULL;
+
+ r = sd_bus_message_new_method_call(
+ bus,
+ "org.freedesktop.systemd.test",
+ "/",
+ "org.freedesktop.systemd.test",
+ "Slow",
+ &m);
+ if (r < 0) {
+ log_error("Failed to allocate method call: %s", strerror(-r));
+ goto finish;
+ }
+
+ sd_bus_message_unref(reply);
+ reply = NULL;
+
+ r = sd_bus_send_with_reply_and_block(bus, m, 200 * USEC_PER_MSEC, &error, &reply);
+ if (r < 0)
+ log_info("Failed to issue method call: %s", bus_error_message(&error, -r));
+ else
+ log_info("Slow call succeed.");
+
+ sd_bus_message_unref(m);
+ m = NULL;
+
+ r = sd_bus_message_new_method_call(
+ bus,
+ "org.freedesktop.systemd.test",
+ "/",
+ "org.freedesktop.systemd.test",
+ "Slow",
+ &m);
+ if (r < 0) {
+ log_error("Failed to allocate method call: %s", strerror(-r));
+ goto finish;
+ }
+
+ r = sd_bus_send_with_reply(bus, m, quit_callback, &quit, 200 * USEC_PER_MSEC, NULL);
+ if (r < 0) {
+ log_info("Failed to issue method call: %s", bus_error_message(&error, -r));
+ goto finish;
+ }
+
+ while (!quit) {
+ r = sd_bus_process(bus, NULL);
+ if (r < 0) {
+ log_error("Failed to process requests: %s", strerror(-r));
+ goto finish;
+ }
+ if (r == 0) {
+ r = sd_bus_wait(bus, (uint64_t) -1);
+ if (r < 0) {
+ log_error("Failed to wait: %s", strerror(-r));
+ goto finish;
+ }
+ }
+ }
+
+ r = 0;
+
+finish:
+ if (bus) {
+ _cleanup_bus_message_unref_ sd_bus_message *q;
+
+ r = sd_bus_message_new_method_call(
+ bus,
+ "org.freedesktop.systemd.test",
+ "/",
+ "org.freedesktop.systemd.test",
+ "ExitClient2",
+ &q);
+ if (r < 0) {
+ log_error("Failed to allocate method call: %s", strerror(-r));
+ goto finish;
+ }
+
+ sd_bus_send(bus, q, NULL);
+ sd_bus_flush(bus);
+ sd_bus_unref(bus);
+ }
+
+ sd_bus_error_free(&error);
+ return INT_TO_PTR(r);
+}
+
+int main(int argc, char *argv[]) {
+ pthread_t c1, c2;
+ sd_bus *bus;
+ void *p;
+ int q, r;
+
+ r = server_init(&bus);
+ if (r < 0) {
+ log_info("Failed to connect to bus, skipping tests.");
+ return EXIT_TEST_SKIP;
+ }
+
+ log_info("Initialized...");
+
+ r = pthread_create(&c1, NULL, client1, bus);
+ if (r != 0)
+ return EXIT_FAILURE;
+
+ r = pthread_create(&c2, NULL, client2, bus);
+ if (r != 0)
+ return EXIT_FAILURE;
+
+ r = server(bus);
+
+ q = pthread_join(c1, &p);
+ if (q != 0)
+ return EXIT_FAILURE;
+ if (PTR_TO_INT(p) < 0)
+ return EXIT_FAILURE;
+
+ q = pthread_join(c2, &p);
+ if (q != 0)
+ return EXIT_FAILURE;
+ if (PTR_TO_INT(p) < 0)
+ return EXIT_FAILURE;
+
+ if (r < 0)
+ return EXIT_FAILURE;
+
+ return EXIT_SUCCESS;
+}
diff --git a/src/libsystemd-bus/test-bus-kernel.c b/src/libsystemd-bus/test-bus-kernel.c
new file mode 100644
index 0000000000..1095e57e42
--- /dev/null
+++ b/src/libsystemd-bus/test-bus-kernel.c
@@ -0,0 +1,162 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <fcntl.h>
+
+#include "util.h"
+
+#include "sd-bus.h"
+#include "bus-message.h"
+#include "bus-error.h"
+#include "bus-kernel.h"
+
+int main(int argc, char *argv[]) {
+ _cleanup_close_ int bus_ref = -1;
+ _cleanup_free_ char *bus_name = NULL, *address = NULL;
+ _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
+ const char *ua = NULL, *ub = NULL, *the_string = NULL;
+ sd_bus *a, *b;
+ int r, pipe_fds[2];
+
+ bus_ref = bus_kernel_create("deine-mutter", &bus_name);
+ if (bus_ref == -ENOENT)
+ return EXIT_TEST_SKIP;
+
+ assert_se(bus_ref >= 0);
+
+ address = strappend("kernel:path=", bus_name);
+ assert_se(address);
+
+ r = sd_bus_new(&a);
+ assert_se(r >= 0);
+
+ r = sd_bus_new(&b);
+ assert_se(r >= 0);
+
+ r = sd_bus_set_address(a, address);
+ assert_se(r >= 0);
+
+ r = sd_bus_set_address(b, address);
+ assert_se(r >= 0);
+
+ r = sd_bus_start(a);
+ assert_se(r >= 0);
+
+ r = sd_bus_start(b);
+ assert_se(r >= 0);
+
+ r = sd_bus_get_unique_name(a, &ua);
+ assert_se(r >= 0);
+
+ printf("unique a: %s\n", ua);
+
+ r = sd_bus_get_unique_name(b, &ub);
+ assert_se(r >= 0);
+
+ printf("unique b: %s\n", ub);
+
+ {
+ //FIXME:
+ struct kdbus_cmd_match cmd_match;
+
+ cmd_match.size = sizeof(cmd_match);
+ cmd_match.src_id = KDBUS_MATCH_SRC_ID_ANY;
+
+ r = ioctl(sd_bus_get_fd(a), KDBUS_CMD_MATCH_ADD, &cmd_match);
+ assert_se(r >= 0);
+
+ r = ioctl(sd_bus_get_fd(b), KDBUS_CMD_MATCH_ADD, &cmd_match);
+ assert_se(r >= 0);
+ }
+
+ r = sd_bus_emit_signal(a, "/foo/bar/waldo", "waldo.com", "Piep", "sss", "I am a string", "/this/is/a/path", "and.this.a.domain.name");
+ assert_se(r >= 0);
+
+ r = sd_bus_process(b, &m);
+ assert_se(r > 0);
+ assert_se(m);
+
+ bus_message_dump(m);
+ assert_se(sd_bus_message_rewind(m, true) >= 0);
+
+ r = sd_bus_message_read(m, "s", &the_string);
+ assert_se(r >= 0);
+ assert_se(streq(the_string, "I am a string"));
+
+ sd_bus_message_unref(m);
+ m = NULL;
+
+ r = sd_bus_request_name(a, "net.x0pointer.foobar", 0);
+ assert_se(r >= 0);
+
+ r = sd_bus_message_new_method_call(b, "net.x0pointer.foobar", "/a/path", "an.inter.face", "AMethod", &m);
+ assert_se(r >= 0);
+
+ assert_se(pipe2(pipe_fds, O_CLOEXEC) >= 0);
+
+ assert_se(write(pipe_fds[1], "x", 1) == 1);
+
+ close_nointr_nofail(pipe_fds[1]);
+ pipe_fds[1] = -1;
+
+ r = sd_bus_message_append(m, "h", pipe_fds[0]);
+ assert_se(r >= 0);
+
+ close_nointr_nofail(pipe_fds[0]);
+ pipe_fds[0] = -1;
+
+ r = sd_bus_send(b, m, NULL);
+ assert_se(r >= 0);
+
+ for (;;) {
+ sd_bus_message_unref(m);
+ m = NULL;
+ r = sd_bus_process(a, &m);
+ assert_se(r > 0);
+ assert_se(m);
+
+ bus_message_dump(m);
+ assert_se(sd_bus_message_rewind(m, true) >= 0);
+
+ if (sd_bus_message_is_method_call(m, "an.inter.face", "AMethod")) {
+ int fd;
+ char x;
+
+ r = sd_bus_message_read(m, "h", &fd);
+ assert_se(r >= 0);
+
+ assert_se(read(fd, &x, 1) == 1);
+ assert_se(x == 'x');
+ break;
+ }
+ }
+
+ r = sd_bus_release_name(a, "net.x0pointer.foobar");
+ assert_se(r >= 0);
+
+ r = sd_bus_release_name(a, "net.x0pointer.foobar");
+ assert_se(r == -ESRCH);
+
+ sd_bus_unref(a);
+ sd_bus_unref(b);
+
+ return 0;
+}
diff --git a/src/libsystemd-bus/test-bus-marshal.c b/src/libsystemd-bus/test-bus-marshal.c
new file mode 100644
index 0000000000..20ae723fbe
--- /dev/null
+++ b/src/libsystemd-bus/test-bus-marshal.c
@@ -0,0 +1,175 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <stdlib.h>
+#include <byteswap.h>
+
+#ifdef HAVE_GLIB
+#include <gio/gio.h>
+#endif
+
+#include <dbus.h>
+
+#include "log.h"
+#include "util.h"
+
+#include "sd-bus.h"
+#include "bus-message.h"
+
+int main(int argc, char *argv[]) {
+ _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
+ int r, boolean;
+ const char *x, *y, *z, *a, *b, *c, *d;
+ uint8_t u, v;
+ void *buffer = NULL;
+ size_t sz;
+ char *h;
+
+ r = sd_bus_message_new_method_call(NULL, "foobar.waldo", "/", "foobar.waldo", "Piep", &m);
+ assert_se(r >= 0);
+
+ r = sd_bus_message_append(m, "s", "a string");
+ assert_se(r >= 0);
+
+ r = sd_bus_message_append(m, "s", NULL);
+ assert_se(r < 0);
+
+ r = sd_bus_message_append(m, "as", 2, "string #1", "string #2");
+ assert_se(r >= 0);
+
+ r = sd_bus_message_append(m, "sass", "foobar", 5, "foo", "bar", "waldo", "piep", "pap", "after");
+ assert_se(r >= 0);
+
+ r = sd_bus_message_append(m, "a{yv}", 2, 3, "s", "foo", 5, "s", "waldo");
+ assert_se(r >= 0);
+
+ r = sd_bus_message_append(m, "ba(ss)", 255, 3, "aaa", "1", "bbb", "2", "ccc", "3");
+ assert_se(r >= 0);
+
+ r = sd_bus_message_open_container(m, 'a', "s");
+ assert_se(r >= 0);
+
+ r = sd_bus_message_append_basic(m, 's', "foobar");
+ assert_se(r >= 0);
+
+ r = sd_bus_message_append_basic(m, 's', "waldo");
+ assert_se(r >= 0);
+
+ r = sd_bus_message_close_container(m);
+ assert_se(r >= 0);
+
+ r = bus_message_seal(m, 4711);
+ assert_se(r >= 0);
+
+ bus_message_dump(m);
+
+ r = bus_message_get_blob(m, &buffer, &sz);
+ assert_se(r >= 0);
+
+ h = hexmem(buffer, sz);
+ assert_se(h);
+
+ log_info("message size = %lu, contents =\n%s", (unsigned long) sz, h);
+ free(h);
+
+#ifdef HAVE_GLIB
+ {
+ GDBusMessage *g;
+ char *p;
+
+#if !defined(GLIB_VERSION_2_36)
+ g_type_init();
+#endif
+
+ g = g_dbus_message_new_from_blob(buffer, sz, 0, NULL);
+ p = g_dbus_message_print(g, 0);
+ log_info("%s", p);
+ g_free(p);
+ g_object_unref(g);
+ }
+#endif
+
+ {
+ DBusMessage *w;
+ DBusError error;
+
+ dbus_error_init(&error);
+
+ w = dbus_message_demarshal(buffer, sz, &error);
+ if (!w) {
+ log_error("%s", error.message);
+ } else
+ dbus_message_unref(w);
+ }
+
+ m = sd_bus_message_unref(m);
+
+ r = bus_message_from_malloc(buffer, sz, NULL, 0, NULL, NULL, &m);
+ assert_se(r >= 0);
+
+ bus_message_dump(m);
+
+ assert_se(sd_bus_message_rewind(m, true) >= 0);
+
+ r = sd_bus_message_read(m, "sas", &x, 2, &y, &z);
+ assert_se(r > 0);
+ assert_se(streq(x, "a string"));
+ assert_se(streq(y, "string #1"));
+ assert_se(streq(z, "string #2"));
+
+ r = sd_bus_message_read(m, "sass", &x, 5, &y, &z, &a, &b, &c, &d);
+ assert_se(r > 0);
+ assert_se(streq(x, "foobar"));
+ assert_se(streq(y, "foo"));
+ assert_se(streq(z, "bar"));
+ assert_se(streq(a, "waldo"));
+ assert_se(streq(b, "piep"));
+ assert_se(streq(c, "pap"));
+ assert_se(streq(d, "after"));
+
+ r = sd_bus_message_read(m, "a{yv}", 2, &u, "s", &x, &v, "s", &y);
+ assert_se(r > 0);
+ assert_se(u == 3);
+ assert_se(streq(x, "foo"));
+ assert_se(v == 5);
+ assert_se(streq(y, "waldo"));
+
+ r = sd_bus_message_read(m, "ba(ss)", &boolean, 3, &x, &y, &a, &b, &c, &d);
+ assert_se(r > 0);
+ assert_se(boolean);
+ assert_se(streq(x, "aaa"));
+ assert_se(streq(y, "1"));
+ assert_se(streq(a, "bbb"));
+ assert_se(streq(b, "2"));
+ assert_se(streq(c, "ccc"));
+ assert_se(streq(d, "3"));
+
+ r = sd_bus_message_read(m, "as", 2, &x, &y);
+ assert_se(r > 0);
+ assert_se(streq(x, "foobar"));
+ assert_se(streq(y, "waldo"));
+
+ r = sd_bus_message_peek_type(m, NULL, NULL);
+ assert_se(r == 0);
+
+ return 0;
+}
diff --git a/src/libsystemd-bus/test-bus-match.c b/src/libsystemd-bus/test-bus-match.c
new file mode 100644
index 0000000000..9cf994009d
--- /dev/null
+++ b/src/libsystemd-bus/test-bus-match.c
@@ -0,0 +1,114 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+
+#include "log.h"
+#include "util.h"
+#include "macro.h"
+
+#include "bus-match.h"
+#include "bus-message.h"
+
+static bool mask[32];
+
+static int filter(sd_bus *b, int ret, sd_bus_message *m, void *userdata) {
+ log_info("Ran %i", PTR_TO_INT(userdata));
+ mask[PTR_TO_INT(userdata)] = true;
+ return 0;
+}
+
+static bool mask_contains(unsigned a[], unsigned n) {
+ unsigned i, j;
+
+ for (i = 0; i < ELEMENTSOF(mask); i++) {
+ bool found = false;
+
+ for (j = 0; j < n; j++)
+ if (a[j] == i) {
+ found = true;
+ break;
+ }
+
+ if (found != mask[i])
+ return false;
+ }
+
+ return true;
+}
+
+int main(int argc, char *argv[]) {
+ struct bus_match_node root;
+ _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
+ enum bus_match_node_type i;
+
+ zero(root);
+ root.type = BUS_MATCH_ROOT;
+
+ assert_se(bus_match_add(&root, "arg2='wal\\'do',sender='foo',type='signal',interface='bar',", filter, INT_TO_PTR(1), NULL) >= 0);
+ assert_se(bus_match_add(&root, "arg2='wal\\'do2',sender='foo',type='signal',interface='bar',", filter, INT_TO_PTR(2), NULL) >= 0);
+ assert_se(bus_match_add(&root, "arg3='test',sender='foo',type='signal',interface='bar',", filter, INT_TO_PTR(3), NULL) >= 0);
+ assert_se(bus_match_add(&root, "arg3='test',sender='foo',type='method_call',interface='bar',", filter, INT_TO_PTR(4), NULL) >= 0);
+ assert_se(bus_match_add(&root, "", filter, INT_TO_PTR(5), NULL) >= 0);
+ assert_se(bus_match_add(&root, "interface='quux'", filter, INT_TO_PTR(6), NULL) >= 0);
+ assert_se(bus_match_add(&root, "interface='bar'", filter, INT_TO_PTR(7), NULL) >= 0);
+ assert_se(bus_match_add(&root, "member='waldo',path='/foo/bar'", filter, INT_TO_PTR(8), NULL) >= 0);
+ assert_se(bus_match_add(&root, "path='/foo/bar'", filter, INT_TO_PTR(9), NULL) >= 0);
+ assert_se(bus_match_add(&root, "path_namespace='/foo'", filter, INT_TO_PTR(10), NULL) >= 0);
+ assert_se(bus_match_add(&root, "path_namespace='/foo/quux'", filter, INT_TO_PTR(11), NULL) >= 0);
+ assert_se(bus_match_add(&root, "arg1='two'", filter, INT_TO_PTR(12), NULL) >= 0);
+ assert_se(bus_match_add(&root, "member='waldo',arg2path='/prefix/'", filter, INT_TO_PTR(13), NULL) >= 0);
+ assert_se(bus_match_add(&root, "member='waldo',path='/foo/bar',arg3namespace='prefix'", filter, INT_TO_PTR(14), NULL) >= 0);
+
+ bus_match_dump(&root, 0);
+
+ assert_se(sd_bus_message_new_signal(NULL, "/foo/bar", "bar", "waldo", &m) >= 0);
+ assert_se(sd_bus_message_append(m, "ssss", "one", "two", "/prefix/three", "prefix.four") >= 0);
+ assert_se(bus_message_seal(m, 1) >= 0);
+
+ zero(mask);
+ assert_se(bus_match_run(NULL, &root, 0, m) == 0);
+ assert_se(mask_contains((unsigned[]) { 9, 8, 7, 5, 10, 12, 13, 14 }, 8));
+
+ assert_se(bus_match_remove(&root, "member='waldo',path='/foo/bar'", filter, INT_TO_PTR(8)) > 0);
+ assert_se(bus_match_remove(&root, "arg2path='/prefix/',member='waldo'", filter, INT_TO_PTR(13)) > 0);
+ assert_se(bus_match_remove(&root, "interface='barxx'", filter, INT_TO_PTR(7)) == 0);
+
+ bus_match_dump(&root, 0);
+
+ zero(mask);
+ assert_se(bus_match_run(NULL, &root, 0, m) == 0);
+ assert_se(mask_contains((unsigned[]) { 9, 5, 10, 12, 14, 7 }, 6));
+
+ for (i = 0; i < _BUS_MATCH_NODE_TYPE_MAX; i++) {
+ char buf[32];
+ const char *x;
+
+ assert_se(x = bus_match_node_type_to_string(i, buf, sizeof(buf)));
+
+ if (i >= BUS_MATCH_MESSAGE_TYPE)
+ assert_se(bus_match_node_type_from_string(x, strlen(x)) == i);
+ }
+
+ bus_match_free(&root);
+
+ return 0;
+}
diff --git a/src/libsystemd-bus/test-bus-server.c b/src/libsystemd-bus/test-bus-server.c
new file mode 100644
index 0000000000..a9772624f2
--- /dev/null
+++ b/src/libsystemd-bus/test-bus-server.c
@@ -0,0 +1,223 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <stdlib.h>
+#include <pthread.h>
+#include <unistd.h>
+#include <fcntl.h>
+
+#include "log.h"
+#include "util.h"
+#include "macro.h"
+
+#include "sd-bus.h"
+#include "bus-internal.h"
+#include "bus-message.h"
+
+struct context {
+ int fds[2];
+
+ bool client_negotiate_unix_fds;
+ bool server_negotiate_unix_fds;
+
+ bool client_anonymous_auth;
+ bool server_anonymous_auth;
+};
+
+static void *server(void *p) {
+ struct context *c = p;
+ sd_bus *bus = NULL;
+ sd_id128_t id;
+ bool quit = false;
+ int r;
+
+ assert_se(sd_id128_randomize(&id) >= 0);
+
+ assert_se(sd_bus_new(&bus) >= 0);
+ assert_se(sd_bus_set_fd(bus, c->fds[0], c->fds[0]) >= 0);
+ assert_se(sd_bus_set_server(bus, 1, id) >= 0);
+ assert_se(sd_bus_set_negotiate_fds(bus, c->server_negotiate_unix_fds) >= 0);
+ assert_se(sd_bus_set_anonymous(bus, c->server_anonymous_auth) >= 0);
+ assert_se(sd_bus_start(bus) >= 0);
+
+ while (!quit) {
+ _cleanup_bus_message_unref_ sd_bus_message *m = NULL, *reply = NULL;
+
+ r = sd_bus_process(bus, &m);
+ if (r < 0) {
+ log_error("Failed to process requests: %s", strerror(-r));
+ goto fail;
+ }
+
+ if (r == 0) {
+ r = sd_bus_wait(bus, (uint64_t) -1);
+ if (r < 0) {
+ log_error("Failed to wait: %s", strerror(-r));
+ goto fail;
+ }
+
+ continue;
+ }
+
+ if (!m)
+ continue;
+
+ log_info("Got message! member=%s", strna(sd_bus_message_get_member(m)));
+
+ if (sd_bus_message_is_method_call(m, "org.freedesktop.systemd.test", "Exit")) {
+
+ assert_se((sd_bus_can_send(bus, 'h') >= 1) == (c->server_negotiate_unix_fds && c->client_negotiate_unix_fds));
+
+ r = sd_bus_message_new_method_return(bus, m, &reply);
+ if (r < 0) {
+ log_error("Failed to allocate return: %s", strerror(-r));
+ goto fail;
+ }
+
+ quit = true;
+
+ } else if (sd_bus_message_is_method_call(m, NULL, NULL)) {
+ r = sd_bus_message_new_method_error(
+ bus, m,
+ &SD_BUS_ERROR_MAKE("org.freedesktop.DBus.Error.UnknownMethod", "Unknown method."),
+ &reply);
+ if (r < 0) {
+ log_error("Failed to allocate return: %s", strerror(-r));
+ goto fail;
+ }
+ }
+
+ if (reply) {
+ r = sd_bus_send(bus, reply, NULL);
+ if (r < 0) {
+ log_error("Failed to send reply: %s", strerror(-r));
+ goto fail;
+ }
+ }
+ }
+
+ r = 0;
+
+fail:
+ if (bus) {
+ sd_bus_flush(bus);
+ sd_bus_unref(bus);
+ }
+
+ return INT_TO_PTR(r);
+}
+
+static int client(struct context *c) {
+ _cleanup_bus_message_unref_ sd_bus_message *m = NULL, *reply = NULL;
+ _cleanup_bus_unref_ sd_bus *bus = NULL;
+ sd_bus_error error = SD_BUS_ERROR_NULL;
+ int r;
+
+ assert_se(sd_bus_new(&bus) >= 0);
+ assert_se(sd_bus_set_fd(bus, c->fds[1], c->fds[1]) >= 0);
+ assert_se(sd_bus_set_negotiate_fds(bus, c->client_negotiate_unix_fds) >= 0);
+ assert_se(sd_bus_set_anonymous(bus, c->client_anonymous_auth) >= 0);
+ assert_se(sd_bus_start(bus) >= 0);
+
+ r = sd_bus_message_new_method_call(
+ bus,
+ "org.freedesktop.systemd.test",
+ "/",
+ "org.freedesktop.systemd.test",
+ "Exit",
+ &m);
+ if (r < 0) {
+ log_error("Failed to allocate method call: %s", strerror(-r));
+ return r;
+ }
+
+ r = sd_bus_send_with_reply_and_block(bus, m, 0, &error, &reply);
+ if (r < 0) {
+ log_error("Failed to issue method call: %s", bus_error_message(&error, -r));
+ return r;
+ }
+
+ return 0;
+}
+
+static int test_one(bool client_negotiate_unix_fds, bool server_negotiate_unix_fds,
+ bool client_anonymous_auth, bool server_anonymous_auth) {
+
+ struct context c;
+ pthread_t s;
+ void *p;
+ int r, q;
+
+ zero(c);
+
+ assert_se(socketpair(AF_UNIX, SOCK_STREAM, 0, c.fds) >= 0);
+
+ c.client_negotiate_unix_fds = client_negotiate_unix_fds;
+ c.server_negotiate_unix_fds = server_negotiate_unix_fds;
+ c.client_anonymous_auth = client_anonymous_auth;
+ c.server_anonymous_auth = server_anonymous_auth;
+
+ r = pthread_create(&s, NULL, server, &c);
+ if (r != 0)
+ return -r;
+
+ r = client(&c);
+
+ q = pthread_join(s, &p);
+ if (q != 0)
+ return -q;
+
+ if (r < 0)
+ return r;
+
+ if (PTR_TO_INT(p) < 0)
+ return PTR_TO_INT(p);
+
+ return 0;
+}
+
+int main(int argc, char *argv[]) {
+ int r;
+
+ r = test_one(true, true, false, false);
+ assert_se(r >= 0);
+
+ r = test_one(true, false, false, false);
+ assert_se(r >= 0);
+
+ r = test_one(false, true, false, false);
+ assert_se(r >= 0);
+
+ r = test_one(false, false, false, false);
+ assert_se(r >= 0);
+
+ r = test_one(true, true, true, true);
+ assert_se(r >= 0);
+
+ r = test_one(true, true, false, true);
+ assert_se(r >= 0);
+
+ r = test_one(true, true, true, false);
+ assert_se(r == -EPERM);
+
+ return EXIT_SUCCESS;
+}
diff --git a/src/libsystemd-bus/test-bus-signature.c b/src/libsystemd-bus/test-bus-signature.c
new file mode 100644
index 0000000000..cab0daa77e
--- /dev/null
+++ b/src/libsystemd-bus/test-bus-signature.c
@@ -0,0 +1,116 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <stdlib.h>
+
+#include "log.h"
+#include "bus-signature.h"
+#include "bus-internal.h"
+
+int main(int argc, char *argv[]) {
+
+ assert_se(signature_is_single("y"));
+ assert_se(signature_is_single("u"));
+ assert_se(signature_is_single("v"));
+ assert_se(signature_is_single("as"));
+ assert_se(signature_is_single("(ss)"));
+ assert_se(signature_is_single("()"));
+ assert_se(signature_is_single("(()()()()())"));
+ assert_se(signature_is_single("(((())))"));
+ assert_se(signature_is_single("((((s))))"));
+ assert_se(signature_is_single("{ss}"));
+ assert_se(signature_is_single("a{ss}"));
+ assert_se(!signature_is_single("uu"));
+ assert_se(!signature_is_single(""));
+ assert_se(!signature_is_single("("));
+ assert_se(!signature_is_single(")"));
+ assert_se(!signature_is_single("())"));
+ assert_se(!signature_is_single("((())"));
+ assert_se(!signature_is_single("{)"));
+ assert_se(!signature_is_single("{}"));
+ assert_se(!signature_is_single("{sss}"));
+ assert_se(!signature_is_single("{s}"));
+ assert_se(!signature_is_single("{ass}"));
+ assert_se(!signature_is_single("a}"));
+
+ assert_se(signature_is_pair("yy"));
+ assert_se(signature_is_pair("ss"));
+ assert_se(signature_is_pair("sas"));
+ assert_se(signature_is_pair("sv"));
+ assert_se(signature_is_pair("sa(vs)"));
+ assert_se(!signature_is_pair(""));
+ assert_se(!signature_is_pair("va"));
+ assert_se(!signature_is_pair("sss"));
+ assert_se(!signature_is_pair("{s}ss"));
+
+ assert_se(signature_is_valid("ssa{ss}sssub", true));
+ assert_se(signature_is_valid("ssa{ss}sssub", false));
+ assert_se(signature_is_valid("{ss}", true));
+ assert_se(!signature_is_valid("{ss}", false));
+ assert_se(signature_is_valid("", true));
+ assert_se(signature_is_valid("", false));
+
+ assert_se(signature_is_valid("sssusa(uuubbba(uu)uuuu)a{u(uuuvas)}", false));
+
+ assert_se(!signature_is_valid("a", false));
+ assert_se(signature_is_valid("as", false));
+ assert_se(signature_is_valid("aas", false));
+ assert_se(signature_is_valid("aaas", false));
+ assert_se(signature_is_valid("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaad", false));
+ assert_se(signature_is_valid("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaas", false));
+ assert_se(!signature_is_valid("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaau", false));
+
+ assert_se(signature_is_valid("(((((((((((((((((((((((((((((((())))))))))))))))))))))))))))))))", false));
+ assert_se(!signature_is_valid("((((((((((((((((((((((((((((((((()))))))))))))))))))))))))))))))))", false));
+
+ assert_se(namespace_complex_pattern("", ""));
+ assert_se(namespace_complex_pattern("foobar", "foobar"));
+ assert_se(namespace_complex_pattern("foobar.waldo", "foobar.waldo"));
+ assert_se(namespace_complex_pattern("foobar.", "foobar.waldo"));
+ assert_se(namespace_complex_pattern("foobar.waldo", "foobar."));
+ assert_se(!namespace_complex_pattern("foobar.waldo", "foobar"));
+ assert_se(!namespace_complex_pattern("foobar", "foobar.waldo"));
+ assert_se(!namespace_complex_pattern("", "foo"));
+ assert_se(!namespace_complex_pattern("foo", ""));
+ assert_se(!namespace_complex_pattern("foo.", ""));
+
+ assert_se(path_complex_pattern("", ""));
+ assert_se(path_complex_pattern("", "/"));
+ assert_se(path_complex_pattern("/", ""));
+ assert_se(path_complex_pattern("/", "/"));
+ assert_se(path_complex_pattern("/foobar/", "/"));
+ assert_se(path_complex_pattern("/foobar/", "/foobar"));
+ assert_se(path_complex_pattern("/foobar", "/foobar"));
+ assert_se(path_complex_pattern("/foobar", "/foobar/"));
+ assert_se(!path_complex_pattern("/foobar", "/foobar/waldo"));
+ assert_se(path_complex_pattern("/foobar/", "/foobar/waldo"));
+
+ assert_se(namespace_simple_pattern("", ""));
+ assert_se(namespace_simple_pattern("foobar", "foobar"));
+ assert_se(namespace_simple_pattern("foobar.waldo", "foobar.waldo"));
+ assert_se(namespace_simple_pattern("foobar", "foobar.waldo"));
+ assert_se(!namespace_simple_pattern("foobar.waldo", "foobar"));
+ assert_se(!namespace_simple_pattern("", "foo"));
+ assert_se(!namespace_simple_pattern("foo", ""));
+
+ return 0;
+}
diff --git a/src/libsystemd-daemon/libsystemd-daemon.pc.in b/src/libsystemd-daemon/libsystemd-daemon.pc.in
new file mode 100644
index 0000000000..8bb3a74c87
--- /dev/null
+++ b/src/libsystemd-daemon/libsystemd-daemon.pc.in
@@ -0,0 +1,19 @@
+# Permission is hereby granted, free of charge, to any person
+# obtaining a copy of this software and associated documentation files
+# (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, sublicense, and/or sell copies of the Software,
+# and to permit persons to whom the Software is furnished to do so,
+# subject to the following conditions:
+
+prefix=@prefix@
+exec_prefix=@exec_prefix@
+libdir=@libdir@
+includedir=@includedir@
+
+Name: systemd
+Description: systemd Daemon Utility Library
+URL: @PACKAGE_URL@
+Version: @PACKAGE_VERSION@
+Libs: -L${libdir} -lsystemd-daemon
+Cflags: -I${includedir}
diff --git a/src/libsystemd-daemon/libsystemd-daemon.sym b/src/libsystemd-daemon/libsystemd-daemon.sym
new file mode 100644
index 0000000000..f440238931
--- /dev/null
+++ b/src/libsystemd-daemon/libsystemd-daemon.sym
@@ -0,0 +1,27 @@
+/***
+ Permission is hereby granted, free of charge, to any person
+ obtaining a copy of this software and associated documentation files
+ (the "Software"), to deal in the Software without restriction,
+ including without limitation the rights to use, copy, modify, merge,
+ publish, distribute, sublicense, and/or sell copies of the Software,
+ and to permit persons to whom the Software is furnished to do so,
+ subject to the following conditions:
+***/
+
+/* Original symbols from systemd v31 */
+
+LIBSYSTEMD_DAEMON_31 {
+global:
+ sd_booted;
+ sd_is_fifo;
+ sd_is_mq;
+ sd_is_socket;
+ sd_is_socket_inet;
+ sd_is_socket_unix;
+ sd_is_special;
+ sd_listen_fds;
+ sd_notify;
+ sd_notifyf;
+local:
+ *;
+};
diff --git a/src/libsystemd-daemon/sd-daemon.c b/src/libsystemd-daemon/sd-daemon.c
new file mode 100644
index 0000000000..485b301023
--- /dev/null
+++ b/src/libsystemd-daemon/sd-daemon.c
@@ -0,0 +1,520 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ Copyright 2010 Lennart Poettering
+
+ Permission is hereby granted, free of charge, to any person
+ obtaining a copy of this software and associated documentation files
+ (the "Software"), to deal in the Software without restriction,
+ including without limitation the rights to use, copy, modify, merge,
+ publish, distribute, sublicense, and/or sell copies of the Software,
+ and to permit persons to whom the Software is furnished to do so,
+ subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+***/
+
+#ifndef _GNU_SOURCE
+# define _GNU_SOURCE
+#endif
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <fcntl.h>
+#include <netinet/in.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <unistd.h>
+#include <string.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stddef.h>
+#include <limits.h>
+
+#if defined(__linux__) && !defined(SD_DAEMON_DISABLE_MQ)
+# include <mqueue.h>
+#endif
+
+#include "sd-daemon.h"
+
+#if (__GNUC__ >= 4)
+# ifdef SD_EXPORT_SYMBOLS
+/* Export symbols */
+# define _sd_export_ __attribute__ ((visibility("default")))
+# else
+/* Don't export the symbols */
+# define _sd_export_ __attribute__ ((visibility("hidden")))
+# endif
+#else
+# define _sd_export_
+#endif
+
+_sd_export_ int sd_listen_fds(int unset_environment) {
+
+#if defined(DISABLE_SYSTEMD) || !defined(__linux__)
+ return 0;
+#else
+ int r, fd;
+ const char *e;
+ char *p = NULL;
+ unsigned long l;
+
+ e = getenv("LISTEN_PID");
+ if (!e) {
+ r = 0;
+ goto finish;
+ }
+
+ errno = 0;
+ l = strtoul(e, &p, 10);
+
+ if (errno > 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ if (!p || p == e || *p || l <= 0) {
+ r = -EINVAL;
+ goto finish;
+ }
+
+ /* Is this for us? */
+ if (getpid() != (pid_t) l) {
+ r = 0;
+ goto finish;
+ }
+
+ e = getenv("LISTEN_FDS");
+ if (!e) {
+ r = 0;
+ goto finish;
+ }
+
+ errno = 0;
+ l = strtoul(e, &p, 10);
+
+ if (errno > 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ if (!p || p == e || *p) {
+ r = -EINVAL;
+ goto finish;
+ }
+
+ for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + (int) l; fd ++) {
+ int flags;
+
+ flags = fcntl(fd, F_GETFD);
+ if (flags < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ if (flags & FD_CLOEXEC)
+ continue;
+
+ if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0) {
+ r = -errno;
+ goto finish;
+ }
+ }
+
+ r = (int) l;
+
+finish:
+ if (unset_environment) {
+ unsetenv("LISTEN_PID");
+ unsetenv("LISTEN_FDS");
+ }
+
+ return r;
+#endif
+}
+
+_sd_export_ int sd_is_fifo(int fd, const char *path) {
+ struct stat st_fd;
+
+ if (fd < 0)
+ return -EINVAL;
+
+ if (fstat(fd, &st_fd) < 0)
+ return -errno;
+
+ if (!S_ISFIFO(st_fd.st_mode))
+ return 0;
+
+ if (path) {
+ struct stat st_path;
+
+ if (stat(path, &st_path) < 0) {
+
+ if (errno == ENOENT || errno == ENOTDIR)
+ return 0;
+
+ return -errno;
+ }
+
+ return
+ st_path.st_dev == st_fd.st_dev &&
+ st_path.st_ino == st_fd.st_ino;
+ }
+
+ return 1;
+}
+
+_sd_export_ int sd_is_special(int fd, const char *path) {
+ struct stat st_fd;
+
+ if (fd < 0)
+ return -EINVAL;
+
+ if (fstat(fd, &st_fd) < 0)
+ return -errno;
+
+ if (!S_ISREG(st_fd.st_mode) && !S_ISCHR(st_fd.st_mode))
+ return 0;
+
+ if (path) {
+ struct stat st_path;
+
+ if (stat(path, &st_path) < 0) {
+
+ if (errno == ENOENT || errno == ENOTDIR)
+ return 0;
+
+ return -errno;
+ }
+
+ if (S_ISREG(st_fd.st_mode) && S_ISREG(st_path.st_mode))
+ return
+ st_path.st_dev == st_fd.st_dev &&
+ st_path.st_ino == st_fd.st_ino;
+ else if (S_ISCHR(st_fd.st_mode) && S_ISCHR(st_path.st_mode))
+ return st_path.st_rdev == st_fd.st_rdev;
+ else
+ return 0;
+ }
+
+ return 1;
+}
+
+static int sd_is_socket_internal(int fd, int type, int listening) {
+ struct stat st_fd;
+
+ if (fd < 0 || type < 0)
+ return -EINVAL;
+
+ if (fstat(fd, &st_fd) < 0)
+ return -errno;
+
+ if (!S_ISSOCK(st_fd.st_mode))
+ return 0;
+
+ if (type != 0) {
+ int other_type = 0;
+ socklen_t l = sizeof(other_type);
+
+ if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &other_type, &l) < 0)
+ return -errno;
+
+ if (l != sizeof(other_type))
+ return -EINVAL;
+
+ if (other_type != type)
+ return 0;
+ }
+
+ if (listening >= 0) {
+ int accepting = 0;
+ socklen_t l = sizeof(accepting);
+
+ if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &accepting, &l) < 0)
+ return -errno;
+
+ if (l != sizeof(accepting))
+ return -EINVAL;
+
+ if (!accepting != !listening)
+ return 0;
+ }
+
+ return 1;
+}
+
+union sockaddr_union {
+ struct sockaddr sa;
+ struct sockaddr_in in4;
+ struct sockaddr_in6 in6;
+ struct sockaddr_un un;
+ struct sockaddr_storage storage;
+};
+
+_sd_export_ int sd_is_socket(int fd, int family, int type, int listening) {
+ int r;
+
+ if (family < 0)
+ return -EINVAL;
+
+ r = sd_is_socket_internal(fd, type, listening);
+ if (r <= 0)
+ return r;
+
+ if (family > 0) {
+ union sockaddr_union sockaddr = {};
+ socklen_t l = sizeof(sockaddr);
+
+ if (getsockname(fd, &sockaddr.sa, &l) < 0)
+ return -errno;
+
+ if (l < sizeof(sa_family_t))
+ return -EINVAL;
+
+ return sockaddr.sa.sa_family == family;
+ }
+
+ return 1;
+}
+
+_sd_export_ int sd_is_socket_inet(int fd, int family, int type, int listening, uint16_t port) {
+ union sockaddr_union sockaddr = {};
+ socklen_t l = sizeof(sockaddr);
+ int r;
+
+ if (family != 0 && family != AF_INET && family != AF_INET6)
+ return -EINVAL;
+
+ r = sd_is_socket_internal(fd, type, listening);
+ if (r <= 0)
+ return r;
+
+ if (getsockname(fd, &sockaddr.sa, &l) < 0)
+ return -errno;
+
+ if (l < sizeof(sa_family_t))
+ return -EINVAL;
+
+ if (sockaddr.sa.sa_family != AF_INET &&
+ sockaddr.sa.sa_family != AF_INET6)
+ return 0;
+
+ if (family > 0)
+ if (sockaddr.sa.sa_family != family)
+ return 0;
+
+ if (port > 0) {
+ if (sockaddr.sa.sa_family == AF_INET) {
+ if (l < sizeof(struct sockaddr_in))
+ return -EINVAL;
+
+ return htons(port) == sockaddr.in4.sin_port;
+ } else {
+ if (l < sizeof(struct sockaddr_in6))
+ return -EINVAL;
+
+ return htons(port) == sockaddr.in6.sin6_port;
+ }
+ }
+
+ return 1;
+}
+
+_sd_export_ int sd_is_socket_unix(int fd, int type, int listening, const char *path, size_t length) {
+ union sockaddr_union sockaddr = {};
+ socklen_t l = sizeof(sockaddr);
+ int r;
+
+ r = sd_is_socket_internal(fd, type, listening);
+ if (r <= 0)
+ return r;
+
+ if (getsockname(fd, &sockaddr.sa, &l) < 0)
+ return -errno;
+
+ if (l < sizeof(sa_family_t))
+ return -EINVAL;
+
+ if (sockaddr.sa.sa_family != AF_UNIX)
+ return 0;
+
+ if (path) {
+ if (length == 0)
+ length = strlen(path);
+
+ if (length == 0)
+ /* Unnamed socket */
+ return l == offsetof(struct sockaddr_un, sun_path);
+
+ if (path[0])
+ /* Normal path socket */
+ return
+ (l >= offsetof(struct sockaddr_un, sun_path) + length + 1) &&
+ memcmp(path, sockaddr.un.sun_path, length+1) == 0;
+ else
+ /* Abstract namespace socket */
+ return
+ (l == offsetof(struct sockaddr_un, sun_path) + length) &&
+ memcmp(path, sockaddr.un.sun_path, length) == 0;
+ }
+
+ return 1;
+}
+
+_sd_export_ int sd_is_mq(int fd, const char *path) {
+#if !defined(__linux__) || defined(SD_DAEMON_DISABLE_MQ)
+ return 0;
+#else
+ struct mq_attr attr;
+
+ if (fd < 0)
+ return -EINVAL;
+
+ if (mq_getattr(fd, &attr) < 0)
+ return -errno;
+
+ if (path) {
+ char fpath[PATH_MAX];
+ struct stat a, b;
+
+ if (path[0] != '/')
+ return -EINVAL;
+
+ if (fstat(fd, &a) < 0)
+ return -errno;
+
+ strncpy(stpcpy(fpath, "/dev/mqueue"), path, sizeof(fpath) - 12);
+ fpath[sizeof(fpath)-1] = 0;
+
+ if (stat(fpath, &b) < 0)
+ return -errno;
+
+ if (a.st_dev != b.st_dev ||
+ a.st_ino != b.st_ino)
+ return 0;
+ }
+
+ return 1;
+#endif
+}
+
+_sd_export_ int sd_notify(int unset_environment, const char *state) {
+#if defined(DISABLE_SYSTEMD) || !defined(__linux__) || !defined(SOCK_CLOEXEC)
+ return 0;
+#else
+ int fd = -1, r;
+ struct msghdr msghdr;
+ struct iovec iovec;
+ union sockaddr_union sockaddr;
+ const char *e;
+
+ if (!state) {
+ r = -EINVAL;
+ goto finish;
+ }
+
+ e = getenv("NOTIFY_SOCKET");
+ if (!e)
+ return 0;
+
+ /* Must be an abstract socket, or an absolute path */
+ if ((e[0] != '@' && e[0] != '/') || e[1] == 0) {
+ r = -EINVAL;
+ goto finish;
+ }
+
+ fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
+ if (fd < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ memset(&sockaddr, 0, sizeof(sockaddr));
+ sockaddr.sa.sa_family = AF_UNIX;
+ strncpy(sockaddr.un.sun_path, e, sizeof(sockaddr.un.sun_path));
+
+ if (sockaddr.un.sun_path[0] == '@')
+ sockaddr.un.sun_path[0] = 0;
+
+ memset(&iovec, 0, sizeof(iovec));
+ iovec.iov_base = (char*) state;
+ iovec.iov_len = strlen(state);
+
+ memset(&msghdr, 0, sizeof(msghdr));
+ msghdr.msg_name = &sockaddr;
+ msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + strlen(e);
+
+ if (msghdr.msg_namelen > sizeof(struct sockaddr_un))
+ msghdr.msg_namelen = sizeof(struct sockaddr_un);
+
+ msghdr.msg_iov = &iovec;
+ msghdr.msg_iovlen = 1;
+
+ if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ r = 1;
+
+finish:
+ if (unset_environment)
+ unsetenv("NOTIFY_SOCKET");
+
+ if (fd >= 0)
+ close(fd);
+
+ return r;
+#endif
+}
+
+_sd_export_ int sd_notifyf(int unset_environment, const char *format, ...) {
+#if defined(DISABLE_SYSTEMD) || !defined(__linux__)
+ return 0;
+#else
+ va_list ap;
+ char *p = NULL;
+ int r;
+
+ va_start(ap, format);
+ r = vasprintf(&p, format, ap);
+ va_end(ap);
+
+ if (r < 0 || !p)
+ return -ENOMEM;
+
+ r = sd_notify(unset_environment, p);
+ free(p);
+
+ return r;
+#endif
+}
+
+_sd_export_ int sd_booted(void) {
+#if defined(DISABLE_SYSTEMD) || !defined(__linux__)
+ return 0;
+#else
+ struct stat st;
+
+ /* We test whether the runtime unit file directory has been
+ * created. This takes place in mount-setup.c, so is
+ * guaranteed to happen very early during boot. */
+
+ if (lstat("/run/systemd/system/", &st) < 0)
+ return 0;
+
+ return !!S_ISDIR(st.st_mode);
+#endif
+}
diff --git a/src/libsystemd-id128/libsystemd-id128.pc.in b/src/libsystemd-id128/libsystemd-id128.pc.in
new file mode 100644
index 0000000000..bb65ffde33
--- /dev/null
+++ b/src/libsystemd-id128/libsystemd-id128.pc.in
@@ -0,0 +1,18 @@
+# This file is part of systemd.
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 of the License, or
+# (at your option) any later version.
+
+prefix=@prefix@
+exec_prefix=@exec_prefix@
+libdir=@libdir@
+includedir=@includedir@
+
+Name: systemd
+Description: systemd 128 Bit ID Utility Library
+URL: @PACKAGE_URL@
+Version: @PACKAGE_VERSION@
+Libs: -L${libdir} -lsystemd-id128
+Cflags: -I${includedir}
diff --git a/src/libsystemd-id128/libsystemd-id128.sym b/src/libsystemd-id128/libsystemd-id128.sym
new file mode 100644
index 0000000000..604c0026c6
--- /dev/null
+++ b/src/libsystemd-id128/libsystemd-id128.sym
@@ -0,0 +1,21 @@
+/***
+ This file is part of systemd.
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+***/
+
+/* Original symbols from systemd v38 */
+
+LIBSYSTEMD_ID128_38 {
+global:
+ sd_id128_to_string;
+ sd_id128_from_string;
+ sd_id128_randomize;
+ sd_id128_get_machine;
+ sd_id128_get_boot;
+local:
+ *;
+};
diff --git a/src/libsystemd-id128/sd-id128.c b/src/libsystemd-id128/sd-id128.c
new file mode 100644
index 0000000000..64ddd09236
--- /dev/null
+++ b/src/libsystemd-id128/sd-id128.c
@@ -0,0 +1,241 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <fcntl.h>
+#include <unistd.h>
+
+#include "sd-id128.h"
+
+#include "util.h"
+#include "macro.h"
+
+_public_ char *sd_id128_to_string(sd_id128_t id, char s[33]) {
+ unsigned n;
+
+ if (!s)
+ return NULL;
+
+ for (n = 0; n < 16; n++) {
+ s[n*2] = hexchar(id.bytes[n] >> 4);
+ s[n*2+1] = hexchar(id.bytes[n] & 0xF);
+ }
+
+ s[32] = 0;
+
+ return s;
+}
+
+_public_ int sd_id128_from_string(const char s[], sd_id128_t *ret) {
+ unsigned n, i;
+ sd_id128_t t;
+ bool is_guid = false;
+
+ if (!s)
+ return -EINVAL;
+ if (!ret)
+ return -EINVAL;
+
+ for (n = 0, i = 0; n < 16;) {
+ int a, b;
+
+ if (s[i] == '-') {
+ /* Is this a GUID? Then be nice, and skip over
+ * the dashes */
+
+ if (i == 8)
+ is_guid = true;
+ else if (i == 13 || i == 18 || i == 23) {
+ if (!is_guid)
+ return -EINVAL;
+ } else
+ return -EINVAL;
+
+ i++;
+ continue;
+ }
+
+ a = unhexchar(s[i++]);
+ if (a < 0)
+ return -EINVAL;
+
+ b = unhexchar(s[i++]);
+ if (b < 0)
+ return -EINVAL;
+
+ t.bytes[n++] = (a << 4) | b;
+ }
+
+ if (i != (is_guid ? 36 : 32))
+ return -EINVAL;
+
+ if (s[i] != 0)
+ return -EINVAL;
+
+ *ret = t;
+ return 0;
+}
+
+static sd_id128_t make_v4_uuid(sd_id128_t id) {
+ /* Stolen from generate_random_uuid() of drivers/char/random.c
+ * in the kernel sources */
+
+ /* Set UUID version to 4 --- truly random generation */
+ id.bytes[6] = (id.bytes[6] & 0x0F) | 0x40;
+
+ /* Set the UUID variant to DCE */
+ id.bytes[8] = (id.bytes[8] & 0x3F) | 0x80;
+
+ return id;
+}
+
+_public_ int sd_id128_get_machine(sd_id128_t *ret) {
+ static __thread sd_id128_t saved_machine_id;
+ static __thread bool saved_machine_id_valid = false;
+ _cleanup_close_ int fd = -1;
+ char buf[33];
+ ssize_t k;
+ unsigned j;
+ sd_id128_t t;
+
+ if (!ret)
+ return -EINVAL;
+
+ if (saved_machine_id_valid) {
+ *ret = saved_machine_id;
+ return 0;
+ }
+
+ fd = open("/etc/machine-id", O_RDONLY|O_CLOEXEC|O_NOCTTY);
+ if (fd < 0)
+ return -errno;
+
+ k = loop_read(fd, buf, 33, false);
+ if (k < 0)
+ return (int) k;
+
+ if (k != 33)
+ return -EIO;
+
+ if (buf[32] !='\n')
+ return -EIO;
+
+ for (j = 0; j < 16; j++) {
+ int a, b;
+
+ a = unhexchar(buf[j*2]);
+ b = unhexchar(buf[j*2+1]);
+
+ if (a < 0 || b < 0)
+ return -EIO;
+
+ t.bytes[j] = a << 4 | b;
+ }
+
+ saved_machine_id = t;
+ saved_machine_id_valid = true;
+
+ *ret = t;
+ return 0;
+}
+
+_public_ int sd_id128_get_boot(sd_id128_t *ret) {
+ static __thread sd_id128_t saved_boot_id;
+ static __thread bool saved_boot_id_valid = false;
+ _cleanup_close_ int fd = -1;
+ char buf[36];
+ ssize_t k;
+ unsigned j;
+ sd_id128_t t;
+ char *p;
+
+ if (!ret)
+ return -EINVAL;
+
+ if (saved_boot_id_valid) {
+ *ret = saved_boot_id;
+ return 0;
+ }
+
+ fd = open("/proc/sys/kernel/random/boot_id", O_RDONLY|O_CLOEXEC|O_NOCTTY);
+ if (fd < 0)
+ return -errno;
+
+ k = loop_read(fd, buf, 36, false);
+ if (k < 0)
+ return (int) k;
+
+ if (k != 36)
+ return -EIO;
+
+ for (j = 0, p = buf; j < 16; j++) {
+ int a, b;
+
+ if (p >= buf + k)
+ return -EIO;
+
+ if (*p == '-')
+ p++;
+
+ a = unhexchar(p[0]);
+ b = unhexchar(p[1]);
+
+ if (a < 0 || b < 0)
+ return -EIO;
+
+ t.bytes[j] = a << 4 | b;
+
+ p += 2;
+ }
+
+ saved_boot_id = t;
+ saved_boot_id_valid = true;
+
+ *ret = t;
+ return 0;
+}
+
+_public_ int sd_id128_randomize(sd_id128_t *ret) {
+ _cleanup_close_ int fd = -1;
+ sd_id128_t t;
+ ssize_t k;
+
+ if (!ret)
+ return -EINVAL;
+
+ fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
+ if (fd < 0)
+ return -errno;
+
+ k = loop_read(fd, &t, 16, false);
+ if (k < 0)
+ return (int) k;
+
+ if (k != 16)
+ return -EIO;
+
+ /* Turn this into a valid v4 UUID, to be nice. Note that we
+ * only guarantee this for newly generated UUIDs, not for
+ * pre-existing ones.*/
+
+ *ret = make_v4_uuid(t);
+ return 0;
+}
diff --git a/src/libudev/libudev-device-private.c b/src/libudev/libudev-device-private.c
new file mode 100644
index 0000000000..cba08d2f65
--- /dev/null
+++ b/src/libudev/libudev-device-private.c
@@ -0,0 +1,192 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2008-2012 Kay Sievers <kay@vrfy.org>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <stddef.h>
+#include <stdbool.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <string.h>
+#include <sys/stat.h>
+
+#include "libudev.h"
+#include "libudev-private.h"
+
+static void udev_device_tag(struct udev_device *dev, const char *tag, bool add)
+{
+ const char *id;
+ char filename[UTIL_PATH_SIZE];
+
+ id = udev_device_get_id_filename(dev);
+ if (id == NULL)
+ return;
+ strscpyl(filename, sizeof(filename), "/run/udev/tags/", tag, "/", id, NULL);
+
+ if (add) {
+ int fd;
+
+ mkdir_parents(filename, 0755);
+ fd = open(filename, O_WRONLY|O_CREAT|O_CLOEXEC|O_TRUNC|O_NOFOLLOW, 0444);
+ if (fd >= 0)
+ close(fd);
+ } else {
+ unlink(filename);
+ }
+}
+
+int udev_device_tag_index(struct udev_device *dev, struct udev_device *dev_old, bool add)
+{
+ struct udev_list_entry *list_entry;
+ bool found;
+
+ if (add && dev_old != NULL) {
+ /* delete possible left-over tags */
+ udev_list_entry_foreach(list_entry, udev_device_get_tags_list_entry(dev_old)) {
+ const char *tag_old = udev_list_entry_get_name(list_entry);
+ struct udev_list_entry *list_entry_current;
+
+ found = false;
+ udev_list_entry_foreach(list_entry_current, udev_device_get_tags_list_entry(dev)) {
+ const char *tag = udev_list_entry_get_name(list_entry_current);
+
+ if (streq(tag, tag_old)) {
+ found = true;
+ break;
+ }
+ }
+ if (!found)
+ udev_device_tag(dev_old, tag_old, false);
+ }
+ }
+
+ udev_list_entry_foreach(list_entry, udev_device_get_tags_list_entry(dev))
+ udev_device_tag(dev, udev_list_entry_get_name(list_entry), add);
+
+ return 0;
+}
+
+static bool device_has_info(struct udev_device *udev_device)
+{
+ struct udev_list_entry *list_entry;
+
+ if (udev_device_get_devlinks_list_entry(udev_device) != NULL)
+ return true;
+ if (udev_device_get_devlink_priority(udev_device) != 0)
+ return true;
+ udev_list_entry_foreach(list_entry, udev_device_get_properties_list_entry(udev_device))
+ if (udev_list_entry_get_num(list_entry))
+ return true;
+ if (udev_device_get_tags_list_entry(udev_device) != NULL)
+ return true;
+ if (udev_device_get_watch_handle(udev_device) >= 0)
+ return true;
+ return false;
+}
+
+int udev_device_update_db(struct udev_device *udev_device)
+{
+ struct udev *udev = udev_device_get_udev(udev_device);
+ bool has_info;
+ const char *id;
+ char filename[UTIL_PATH_SIZE];
+ char filename_tmp[UTIL_PATH_SIZE];
+ FILE *f;
+ int r;
+
+ id = udev_device_get_id_filename(udev_device);
+ if (id == NULL)
+ return -1;
+
+ has_info = device_has_info(udev_device);
+ strscpyl(filename, sizeof(filename), "/run/udev/data/", id, NULL);
+
+ /* do not store anything for otherwise empty devices */
+ if (!has_info &&
+ major(udev_device_get_devnum(udev_device)) == 0 &&
+ udev_device_get_ifindex(udev_device) == 0) {
+ unlink(filename);
+ return 0;
+ }
+
+ /* write a database file */
+ strscpyl(filename_tmp, sizeof(filename_tmp), filename, ".tmp", NULL);
+ mkdir_parents(filename_tmp, 0755);
+ f = fopen(filename_tmp, "we");
+ if (f == NULL) {
+ udev_err(udev, "unable to create temporary db file '%s': %m\n", filename_tmp);
+ return -1;
+ }
+
+ /*
+ * set 'sticky' bit to indicate that we should not clean the
+ * database when we transition from initramfs to the real root
+ */
+ if (udev_device_get_db_persist(udev_device))
+ fchmod(fileno(f), 01644);
+
+ if (has_info) {
+ struct udev_list_entry *list_entry;
+
+ if (major(udev_device_get_devnum(udev_device)) > 0) {
+ udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(udev_device))
+ fprintf(f, "S:%s\n", udev_list_entry_get_name(list_entry) + strlen("/dev/"));
+ if (udev_device_get_devlink_priority(udev_device) != 0)
+ fprintf(f, "L:%i\n", udev_device_get_devlink_priority(udev_device));
+ if (udev_device_get_watch_handle(udev_device) >= 0)
+ fprintf(f, "W:%i\n", udev_device_get_watch_handle(udev_device));
+ }
+
+ if (udev_device_get_usec_initialized(udev_device) > 0)
+ fprintf(f, "I:%llu\n", (unsigned long long)udev_device_get_usec_initialized(udev_device));
+
+ udev_list_entry_foreach(list_entry, udev_device_get_properties_list_entry(udev_device)) {
+ if (!udev_list_entry_get_num(list_entry))
+ continue;
+ fprintf(f, "E:%s=%s\n",
+ udev_list_entry_get_name(list_entry),
+ udev_list_entry_get_value(list_entry));
+ }
+
+ udev_list_entry_foreach(list_entry, udev_device_get_tags_list_entry(udev_device))
+ fprintf(f, "G:%s\n", udev_list_entry_get_name(list_entry));
+ }
+
+ fclose(f);
+ r = rename(filename_tmp, filename);
+ if (r < 0)
+ return -1;
+ udev_dbg(udev, "created %s file '%s' for '%s'\n", has_info ? "db" : "empty",
+ filename, udev_device_get_devpath(udev_device));
+ return 0;
+}
+
+int udev_device_delete_db(struct udev_device *udev_device)
+{
+ const char *id;
+ char filename[UTIL_PATH_SIZE];
+
+ id = udev_device_get_id_filename(udev_device);
+ if (id == NULL)
+ return -1;
+ strscpyl(filename, sizeof(filename), "/run/udev/data/", id, NULL);
+ unlink(filename);
+ return 0;
+}
diff --git a/src/libudev/libudev-device.c b/src/libudev/libudev-device.c
new file mode 100644
index 0000000000..6bb2e41510
--- /dev/null
+++ b/src/libudev/libudev-device.c
@@ -0,0 +1,1871 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2008-2012 Kay Sievers <kay@vrfy.org>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <unistd.h>
+#include <stdbool.h>
+#include <errno.h>
+#include <string.h>
+#include <dirent.h>
+#include <fcntl.h>
+#include <ctype.h>
+#include <net/if.h>
+#include <sys/stat.h>
+#include <sys/ioctl.h>
+#include <sys/socket.h>
+#include <linux/sockios.h>
+
+#include "libudev.h"
+#include "libudev-private.h"
+
+/**
+ * SECTION:libudev-device
+ * @short_description: kernel sys devices
+ *
+ * Representation of kernel sys devices. Devices are uniquely identified
+ * by their syspath, every device has exactly one path in the kernel sys
+ * filesystem. Devices usually belong to a kernel subsystem, and and have
+ * a unique name inside that subsystem.
+ */
+
+/**
+ * udev_device:
+ *
+ * Opaque object representing one kernel sys device.
+ */
+struct udev_device {
+ struct udev *udev;
+ struct udev_device *parent_device;
+ char *syspath;
+ const char *devpath;
+ char *sysname;
+ const char *sysnum;
+ char *devnode;
+ mode_t devnode_mode;
+ uid_t devnode_uid;
+ gid_t devnode_gid;
+ char *subsystem;
+ char *devtype;
+ char *driver;
+ char *action;
+ char *devpath_old;
+ char *id_filename;
+ char **envp;
+ char *monitor_buf;
+ size_t monitor_buf_len;
+ struct udev_list devlinks_list;
+ struct udev_list properties_list;
+ struct udev_list sysattr_value_list;
+ struct udev_list sysattr_list;
+ struct udev_list tags_list;
+ unsigned long long int seqnum;
+ usec_t usec_initialized;
+ int devlink_priority;
+ int refcount;
+ dev_t devnum;
+ int ifindex;
+ int watch_handle;
+ int maj, min;
+ bool parent_set;
+ bool subsystem_set;
+ bool devtype_set;
+ bool devlinks_uptodate;
+ bool envp_uptodate;
+ bool tags_uptodate;
+ bool driver_set;
+ bool info_loaded;
+ bool db_loaded;
+ bool uevent_loaded;
+ bool is_initialized;
+ bool sysattr_list_read;
+ bool db_persist;
+};
+
+/**
+ * udev_device_get_seqnum:
+ * @udev_device: udev device
+ *
+ * This is only valid if the device was received through a monitor. Devices read from
+ * sys do not have a sequence number.
+ *
+ * Returns: the kernel event sequence number, or 0 if there is no sequence number available.
+ **/
+_public_ unsigned long long int udev_device_get_seqnum(struct udev_device *udev_device)
+{
+ if (udev_device == NULL)
+ return 0;
+ return udev_device->seqnum;
+}
+
+static int udev_device_set_seqnum(struct udev_device *udev_device, unsigned long long int seqnum)
+{
+ char num[32];
+
+ udev_device->seqnum = seqnum;
+ snprintf(num, sizeof(num), "%llu", seqnum);
+ udev_device_add_property(udev_device, "SEQNUM", num);
+ return 0;
+}
+
+int udev_device_get_ifindex(struct udev_device *udev_device)
+{
+ if (!udev_device->info_loaded)
+ udev_device_read_uevent_file(udev_device);
+ return udev_device->ifindex;
+}
+
+static int udev_device_set_ifindex(struct udev_device *udev_device, int ifindex)
+{
+ char num[32];
+
+ udev_device->ifindex = ifindex;
+ snprintf(num, sizeof(num), "%u", ifindex);
+ udev_device_add_property(udev_device, "IFINDEX", num);
+ return 0;
+}
+
+/**
+ * udev_device_get_devnum:
+ * @udev_device: udev device
+ *
+ * Get the device major/minor number.
+ *
+ * Returns: the dev_t number.
+ **/
+_public_ dev_t udev_device_get_devnum(struct udev_device *udev_device)
+{
+ if (udev_device == NULL)
+ return makedev(0, 0);
+ if (!udev_device->info_loaded)
+ udev_device_read_uevent_file(udev_device);
+ return udev_device->devnum;
+}
+
+static int udev_device_set_devnum(struct udev_device *udev_device, dev_t devnum)
+{
+ char num[32];
+
+ udev_device->devnum = devnum;
+
+ snprintf(num, sizeof(num), "%u", major(devnum));
+ udev_device_add_property(udev_device, "MAJOR", num);
+ snprintf(num, sizeof(num), "%u", minor(devnum));
+ udev_device_add_property(udev_device, "MINOR", num);
+ return 0;
+}
+
+const char *udev_device_get_devpath_old(struct udev_device *udev_device)
+{
+ return udev_device->devpath_old;
+}
+
+static int udev_device_set_devpath_old(struct udev_device *udev_device, const char *devpath_old)
+{
+ const char *pos;
+
+ free(udev_device->devpath_old);
+ udev_device->devpath_old = strdup(devpath_old);
+ if (udev_device->devpath_old == NULL)
+ return -ENOMEM;
+ udev_device_add_property(udev_device, "DEVPATH_OLD", udev_device->devpath_old);
+
+ pos = strrchr(udev_device->devpath_old, '/');
+ if (pos == NULL)
+ return -EINVAL;
+ return 0;
+}
+
+/**
+ * udev_device_get_driver:
+ * @udev_device: udev device
+ *
+ * Get the kernel driver name.
+ *
+ * Returns: the driver name string, or #NULL if there is no driver attached.
+ **/
+_public_ const char *udev_device_get_driver(struct udev_device *udev_device)
+{
+ char driver[UTIL_NAME_SIZE];
+
+ if (udev_device == NULL)
+ return NULL;
+ if (!udev_device->driver_set) {
+ udev_device->driver_set = true;
+ if (util_get_sys_core_link_value(udev_device->udev, "driver", udev_device->syspath, driver, sizeof(driver)) > 0)
+ udev_device->driver = strdup(driver);
+ }
+ return udev_device->driver;
+}
+
+static int udev_device_set_driver(struct udev_device *udev_device, const char *driver)
+{
+ free(udev_device->driver);
+ udev_device->driver = strdup(driver);
+ if (udev_device->driver == NULL)
+ return -ENOMEM;
+ udev_device->driver_set = true;
+ udev_device_add_property(udev_device, "DRIVER", udev_device->driver);
+ return 0;
+}
+
+/**
+ * udev_device_get_devtype:
+ * @udev_device: udev device
+ *
+ * Retrieve the devtype string of the udev device.
+ *
+ * Returns: the devtype name of the udev device, or #NULL if it can not be determined
+ **/
+_public_ const char *udev_device_get_devtype(struct udev_device *udev_device)
+{
+ if (udev_device == NULL)
+ return NULL;
+ if (!udev_device->devtype_set) {
+ udev_device->devtype_set = true;
+ udev_device_read_uevent_file(udev_device);
+ }
+ return udev_device->devtype;
+}
+
+static int udev_device_set_devtype(struct udev_device *udev_device, const char *devtype)
+{
+ free(udev_device->devtype);
+ udev_device->devtype = strdup(devtype);
+ if (udev_device->devtype == NULL)
+ return -ENOMEM;
+ udev_device->devtype_set = true;
+ udev_device_add_property(udev_device, "DEVTYPE", udev_device->devtype);
+ return 0;
+}
+
+int udev_device_set_subsystem(struct udev_device *udev_device, const char *subsystem)
+{
+ free(udev_device->subsystem);
+ udev_device->subsystem = strdup(subsystem);
+ if (udev_device->subsystem == NULL)
+ return -ENOMEM;
+ udev_device->subsystem_set = true;
+ udev_device_add_property(udev_device, "SUBSYSTEM", udev_device->subsystem);
+ return 0;
+}
+
+/**
+ * udev_device_get_subsystem:
+ * @udev_device: udev device
+ *
+ * Retrieve the subsystem string of the udev device. The string does not
+ * contain any "/".
+ *
+ * Returns: the subsystem name of the udev device, or #NULL if it can not be determined
+ **/
+_public_ const char *udev_device_get_subsystem(struct udev_device *udev_device)
+{
+ char subsystem[UTIL_NAME_SIZE];
+
+ if (udev_device == NULL)
+ return NULL;
+ if (!udev_device->subsystem_set) {
+ udev_device->subsystem_set = true;
+ /* read "subsystem" link */
+ if (util_get_sys_core_link_value(udev_device->udev, "subsystem", udev_device->syspath, subsystem, sizeof(subsystem)) > 0) {
+ udev_device_set_subsystem(udev_device, subsystem);
+ return udev_device->subsystem;
+ }
+ /* implicit names */
+ if (startswith(udev_device->devpath, "/module/")) {
+ udev_device_set_subsystem(udev_device, "module");
+ return udev_device->subsystem;
+ }
+ if (strstr(udev_device->devpath, "/drivers/") != NULL) {
+ udev_device_set_subsystem(udev_device, "drivers");
+ return udev_device->subsystem;
+ }
+ if (startswith(udev_device->devpath, "/subsystem/") ||
+ startswith(udev_device->devpath, "/class/") ||
+ startswith(udev_device->devpath, "/bus/")) {
+ udev_device_set_subsystem(udev_device, "subsystem");
+ return udev_device->subsystem;
+ }
+ }
+ return udev_device->subsystem;
+}
+
+mode_t udev_device_get_devnode_mode(struct udev_device *udev_device)
+{
+ if (!udev_device->info_loaded)
+ udev_device_read_uevent_file(udev_device);
+ return udev_device->devnode_mode;
+}
+
+static int udev_device_set_devnode_mode(struct udev_device *udev_device, mode_t mode)
+{
+ char num[32];
+
+ udev_device->devnode_mode = mode;
+ snprintf(num, sizeof(num), "%#o", mode);
+ udev_device_add_property(udev_device, "DEVMODE", num);
+ return 0;
+}
+
+uid_t udev_device_get_devnode_uid(struct udev_device *udev_device)
+{
+ if (!udev_device->info_loaded)
+ udev_device_read_uevent_file(udev_device);
+ return udev_device->devnode_uid;
+}
+
+static int udev_device_set_devnode_uid(struct udev_device *udev_device, uid_t uid)
+{
+ char num[32];
+
+ udev_device->devnode_uid = uid;
+ snprintf(num, sizeof(num), "%u", uid);
+ udev_device_add_property(udev_device, "DEVUID", num);
+ return 0;
+}
+
+gid_t udev_device_get_devnode_gid(struct udev_device *udev_device)
+{
+ if (!udev_device->info_loaded)
+ udev_device_read_uevent_file(udev_device);
+ return udev_device->devnode_gid;
+}
+
+static int udev_device_set_devnode_gid(struct udev_device *udev_device, gid_t gid)
+{
+ char num[32];
+
+ udev_device->devnode_gid = gid;
+ snprintf(num, sizeof(num), "%u", gid);
+ udev_device_add_property(udev_device, "DEVGID", num);
+ return 0;
+}
+
+struct udev_list_entry *udev_device_add_property(struct udev_device *udev_device, const char *key, const char *value)
+{
+ udev_device->envp_uptodate = false;
+ if (value == NULL) {
+ struct udev_list_entry *list_entry;
+
+ list_entry = udev_device_get_properties_list_entry(udev_device);
+ list_entry = udev_list_entry_get_by_name(list_entry, key);
+ if (list_entry != NULL)
+ udev_list_entry_delete(list_entry);
+ return NULL;
+ }
+ return udev_list_entry_add(&udev_device->properties_list, key, value);
+}
+
+static struct udev_list_entry *udev_device_add_property_from_string(struct udev_device *udev_device, const char *property)
+{
+ char name[UTIL_LINE_SIZE];
+ char *val;
+
+ strscpy(name, sizeof(name), property);
+ val = strchr(name, '=');
+ if (val == NULL)
+ return NULL;
+ val[0] = '\0';
+ val = &val[1];
+ if (val[0] == '\0')
+ val = NULL;
+ return udev_device_add_property(udev_device, name, val);
+}
+
+/*
+ * parse property string, and if needed, update internal values accordingly
+ *
+ * udev_device_add_property_from_string_parse_finish() needs to be
+ * called after adding properties, and its return value checked
+ *
+ * udev_device_set_info_loaded() needs to be set, to avoid trying
+ * to use a device without a DEVPATH set
+ */
+void udev_device_add_property_from_string_parse(struct udev_device *udev_device, const char *property)
+{
+ if (startswith(property, "DEVPATH=")) {
+ char path[UTIL_PATH_SIZE];
+
+ strscpyl(path, sizeof(path), "/sys", &property[8], NULL);
+ udev_device_set_syspath(udev_device, path);
+ } else if (startswith(property, "SUBSYSTEM=")) {
+ udev_device_set_subsystem(udev_device, &property[10]);
+ } else if (startswith(property, "DEVTYPE=")) {
+ udev_device_set_devtype(udev_device, &property[8]);
+ } else if (startswith(property, "DEVNAME=")) {
+ udev_device_set_devnode(udev_device, &property[8]);
+ } else if (startswith(property, "DEVLINKS=")) {
+ char devlinks[UTIL_PATH_SIZE];
+ char *slink;
+ char *next;
+
+ strscpy(devlinks, sizeof(devlinks), &property[9]);
+ slink = devlinks;
+ next = strchr(slink, ' ');
+ while (next != NULL) {
+ next[0] = '\0';
+ udev_device_add_devlink(udev_device, slink);
+ slink = &next[1];
+ next = strchr(slink, ' ');
+ }
+ if (slink[0] != '\0')
+ udev_device_add_devlink(udev_device, slink);
+ } else if (startswith(property, "TAGS=")) {
+ char tags[UTIL_PATH_SIZE];
+ char *next;
+
+ strscpy(tags, sizeof(tags), &property[5]);
+ next = strchr(tags, ':');
+ if (next != NULL) {
+ next++;
+ while (next[0] != '\0') {
+ char *tag;
+
+ tag = next;
+ next = strchr(tag, ':');
+ if (next == NULL)
+ break;
+ next[0] = '\0';
+ next++;
+ udev_device_add_tag(udev_device, tag);
+ }
+ }
+ } else if (startswith(property, "USEC_INITIALIZED=")) {
+ udev_device_set_usec_initialized(udev_device, strtoull(&property[19], NULL, 10));
+ } else if (startswith(property, "DRIVER=")) {
+ udev_device_set_driver(udev_device, &property[7]);
+ } else if (startswith(property, "ACTION=")) {
+ udev_device_set_action(udev_device, &property[7]);
+ } else if (startswith(property, "MAJOR=")) {
+ udev_device->maj = strtoull(&property[6], NULL, 10);
+ } else if (startswith(property, "MINOR=")) {
+ udev_device->min = strtoull(&property[6], NULL, 10);
+ } else if (startswith(property, "DEVPATH_OLD=")) {
+ udev_device_set_devpath_old(udev_device, &property[12]);
+ } else if (startswith(property, "SEQNUM=")) {
+ udev_device_set_seqnum(udev_device, strtoull(&property[7], NULL, 10));
+ } else if (startswith(property, "IFINDEX=")) {
+ udev_device_set_ifindex(udev_device, strtoull(&property[8], NULL, 10));
+ } else if (startswith(property, "DEVMODE=")) {
+ udev_device_set_devnode_mode(udev_device, strtoul(&property[8], NULL, 8));
+ } else if (startswith(property, "DEVUID=")) {
+ udev_device_set_devnode_uid(udev_device, strtoul(&property[7], NULL, 10));
+ } else if (startswith(property, "DEVGID=")) {
+ udev_device_set_devnode_gid(udev_device, strtoul(&property[7], NULL, 10));
+ } else {
+ udev_device_add_property_from_string(udev_device, property);
+ }
+}
+
+int udev_device_add_property_from_string_parse_finish(struct udev_device *udev_device)
+{
+ if (udev_device->maj > 0)
+ udev_device_set_devnum(udev_device, makedev(udev_device->maj, udev_device->min));
+ udev_device->maj = 0;
+ udev_device->min = 0;
+
+ if (udev_device->devpath == NULL || udev_device->subsystem == NULL)
+ return -EINVAL;
+ return 0;
+}
+
+/**
+ * udev_device_get_property_value:
+ * @udev_device: udev device
+ * @key: property name
+ *
+ * Get the value of a given property.
+ *
+ * Returns: the property string, or #NULL if there is no such property.
+ **/
+_public_ const char *udev_device_get_property_value(struct udev_device *udev_device, const char *key)
+{
+ struct udev_list_entry *list_entry;
+
+ if (udev_device == NULL)
+ return NULL;
+ if (key == NULL)
+ return NULL;
+
+ list_entry = udev_device_get_properties_list_entry(udev_device);
+ list_entry = udev_list_entry_get_by_name(list_entry, key);
+ return udev_list_entry_get_value(list_entry);
+}
+
+int udev_device_read_db(struct udev_device *udev_device, const char *dbfile)
+{
+ char filename[UTIL_PATH_SIZE];
+ char line[UTIL_LINE_SIZE];
+ FILE *f;
+
+ /* providing a database file will always force-load it */
+ if (dbfile == NULL) {
+ const char *id;
+
+ if (udev_device->db_loaded)
+ return 0;
+ udev_device->db_loaded = true;
+
+ id = udev_device_get_id_filename(udev_device);
+ if (id == NULL)
+ return -1;
+ strscpyl(filename, sizeof(filename), "/run/udev/data/", id, NULL);
+ dbfile = filename;
+ }
+
+ f = fopen(dbfile, "re");
+ if (f == NULL) {
+ udev_dbg(udev_device->udev, "no db file to read %s: %m\n", dbfile);
+ return -1;
+ }
+ udev_device->is_initialized = true;
+
+ while (fgets(line, sizeof(line), f)) {
+ ssize_t len;
+ const char *val;
+ struct udev_list_entry *entry;
+
+ len = strlen(line);
+ if (len < 4)
+ break;
+ line[len-1] = '\0';
+ val = &line[2];
+ switch(line[0]) {
+ case 'S':
+ strscpyl(filename, sizeof(filename), "/dev/", val, NULL);
+ udev_device_add_devlink(udev_device, filename);
+ break;
+ case 'L':
+ udev_device_set_devlink_priority(udev_device, atoi(val));
+ break;
+ case 'E':
+ entry = udev_device_add_property_from_string(udev_device, val);
+ udev_list_entry_set_num(entry, true);
+ break;
+ case 'G':
+ udev_device_add_tag(udev_device, val);
+ break;
+ case 'W':
+ udev_device_set_watch_handle(udev_device, atoi(val));
+ break;
+ case 'I':
+ udev_device_set_usec_initialized(udev_device, strtoull(val, NULL, 10));
+ break;
+ }
+ }
+ fclose(f);
+
+ udev_dbg(udev_device->udev, "device %p filled with db file data\n", udev_device);
+ return 0;
+}
+
+int udev_device_read_uevent_file(struct udev_device *udev_device)
+{
+ char filename[UTIL_PATH_SIZE];
+ FILE *f;
+ char line[UTIL_LINE_SIZE];
+ int maj = 0;
+ int min = 0;
+
+ if (udev_device->uevent_loaded)
+ return 0;
+
+ strscpyl(filename, sizeof(filename), udev_device->syspath, "/uevent", NULL);
+ f = fopen(filename, "re");
+ if (f == NULL)
+ return -1;
+ udev_device->uevent_loaded = true;
+
+ while (fgets(line, sizeof(line), f)) {
+ char *pos;
+
+ pos = strchr(line, '\n');
+ if (pos == NULL)
+ continue;
+ pos[0] = '\0';
+
+ if (startswith(line, "DEVTYPE=")) {
+ udev_device_set_devtype(udev_device, &line[8]);
+ continue;
+ }
+ if (startswith(line, "IFINDEX=")) {
+ udev_device_set_ifindex(udev_device, strtoull(&line[8], NULL, 10));
+ continue;
+ }
+ if (startswith(line, "DEVNAME=")) {
+ udev_device_set_devnode(udev_device, &line[8]);
+ continue;
+ }
+
+ if (startswith(line, "MAJOR="))
+ maj = strtoull(&line[6], NULL, 10);
+ else if (startswith(line, "MINOR="))
+ min = strtoull(&line[6], NULL, 10);
+ else if (startswith(line, "DEVMODE="))
+ udev_device->devnode_mode = strtoul(&line[8], NULL, 8);
+
+ udev_device_add_property_from_string(udev_device, line);
+ }
+
+ udev_device->devnum = makedev(maj, min);
+ fclose(f);
+ return 0;
+}
+
+void udev_device_set_info_loaded(struct udev_device *device)
+{
+ device->info_loaded = true;
+}
+
+struct udev_device *udev_device_new(struct udev *udev)
+{
+ struct udev_device *udev_device;
+ struct udev_list_entry *list_entry;
+
+ if (udev == NULL)
+ return NULL;
+
+ udev_device = calloc(1, sizeof(struct udev_device));
+ if (udev_device == NULL)
+ return NULL;
+ udev_device->refcount = 1;
+ udev_device->udev = udev;
+ udev_list_init(udev, &udev_device->devlinks_list, true);
+ udev_list_init(udev, &udev_device->properties_list, true);
+ udev_list_init(udev, &udev_device->sysattr_value_list, true);
+ udev_list_init(udev, &udev_device->sysattr_list, false);
+ udev_list_init(udev, &udev_device->tags_list, true);
+ udev_device->watch_handle = -1;
+ /* copy global properties */
+ udev_list_entry_foreach(list_entry, udev_get_properties_list_entry(udev))
+ udev_device_add_property(udev_device,
+ udev_list_entry_get_name(list_entry),
+ udev_list_entry_get_value(list_entry));
+ return udev_device;
+}
+
+/**
+ * udev_device_new_from_syspath:
+ * @udev: udev library context
+ * @syspath: sys device path including sys directory
+ *
+ * Create new udev device, and fill in information from the sys
+ * device and the udev database entry. The syspath is the absolute
+ * path to the device, including the sys mount point.
+ *
+ * The initial refcount is 1, and needs to be decremented to
+ * release the resources of the udev device.
+ *
+ * Returns: a new udev device, or #NULL, if it does not exist
+ **/
+_public_ struct udev_device *udev_device_new_from_syspath(struct udev *udev, const char *syspath)
+{
+ const char *subdir;
+ char path[UTIL_PATH_SIZE];
+ char *pos;
+ struct stat statbuf;
+ struct udev_device *udev_device;
+
+ if (udev == NULL)
+ return NULL;
+ if (syspath == NULL)
+ return NULL;
+
+ /* path starts in sys */
+ if (!startswith(syspath, "/sys")) {
+ udev_dbg(udev, "not in sys :%s\n", syspath);
+ return NULL;
+ }
+
+ /* path is not a root directory */
+ subdir = syspath + strlen("/sys");
+ pos = strrchr(subdir, '/');
+ if (pos == NULL || pos[1] == '\0' || pos < &subdir[2])
+ return NULL;
+
+ /* resolve possible symlink to real path */
+ strscpy(path, sizeof(path), syspath);
+ util_resolve_sys_link(udev, path, sizeof(path));
+
+ if (startswith(path + strlen("/sys"), "/devices/")) {
+ char file[UTIL_PATH_SIZE];
+
+ /* all "devices" require a "uevent" file */
+ strscpyl(file, sizeof(file), path, "/uevent", NULL);
+ if (stat(file, &statbuf) != 0)
+ return NULL;
+ } else {
+ /* everything else just needs to be a directory */
+ if (stat(path, &statbuf) != 0 || !S_ISDIR(statbuf.st_mode))
+ return NULL;
+ }
+
+ udev_device = udev_device_new(udev);
+ if (udev_device == NULL)
+ return NULL;
+
+ udev_device_set_syspath(udev_device, path);
+ udev_dbg(udev, "device %p has devpath '%s'\n", udev_device, udev_device_get_devpath(udev_device));
+
+ return udev_device;
+}
+
+/**
+ * udev_device_new_from_devnum:
+ * @udev: udev library context
+ * @type: char or block device
+ * @devnum: device major/minor number
+ *
+ * Create new udev device, and fill in information from the sys
+ * device and the udev database entry. The device is looked-up
+ * by its major/minor number and type. Character and block device
+ * numbers are not unique across the two types.
+ *
+ * The initial refcount is 1, and needs to be decremented to
+ * release the resources of the udev device.
+ *
+ * Returns: a new udev device, or #NULL, if it does not exist
+ **/
+_public_ struct udev_device *udev_device_new_from_devnum(struct udev *udev, char type, dev_t devnum)
+{
+ char path[UTIL_PATH_SIZE];
+ const char *type_str;
+
+ if (type == 'b')
+ type_str = "block";
+ else if (type == 'c')
+ type_str = "char";
+ else
+ return NULL;
+
+ /* use /sys/dev/{block,char}/<maj>:<min> link */
+ snprintf(path, sizeof(path), "/sys/dev/%s/%u:%u",
+ type_str, major(devnum), minor(devnum));
+ return udev_device_new_from_syspath(udev, path);
+}
+
+/**
+ * udev_device_new_from_device_id:
+ * @udev: udev library context
+ * @id: text string identifying a kernel device
+ *
+ * Create new udev device, and fill in information from the sys
+ * device and the udev database entry. The device is looked-up
+ * by a special string:
+ * b8:2 - block device major:minor
+ * c128:1 - char device major:minor
+ * n3 - network device ifindex
+ * +sound:card29 - kernel driver core subsystem:device name
+ *
+ * The initial refcount is 1, and needs to be decremented to
+ * release the resources of the udev device.
+ *
+ * Returns: a new udev device, or #NULL, if it does not exist
+ **/
+_public_ struct udev_device *udev_device_new_from_device_id(struct udev *udev, char *id)
+{
+ char type;
+ int maj, min;
+ char subsys[UTIL_PATH_SIZE];
+ char *sysname;
+
+ switch(id[0]) {
+ case 'b':
+ case 'c':
+ if (sscanf(id, "%c%i:%i", &type, &maj, &min) != 3)
+ return NULL;
+ return udev_device_new_from_devnum(udev, type, makedev(maj, min));
+ case 'n': {
+ int sk;
+ struct ifreq ifr;
+ struct udev_device *dev;
+ int ifindex;
+
+ ifindex = strtoul(&id[1], NULL, 10);
+ if (ifindex <= 0)
+ return NULL;
+
+ sk = socket(PF_INET, SOCK_DGRAM, 0);
+ if (sk < 0)
+ return NULL;
+ memset(&ifr, 0x00, sizeof(struct ifreq));
+ ifr.ifr_ifindex = ifindex;
+ if (ioctl(sk, SIOCGIFNAME, &ifr) != 0) {
+ close(sk);
+ return NULL;
+ }
+ close(sk);
+
+ dev = udev_device_new_from_subsystem_sysname(udev, "net", ifr.ifr_name);
+ if (dev == NULL)
+ return NULL;
+ if (udev_device_get_ifindex(dev) == ifindex)
+ return dev;
+ udev_device_unref(dev);
+ return NULL;
+ }
+ case '+':
+ strscpy(subsys, sizeof(subsys), &id[1]);
+ sysname = strchr(subsys, ':');
+ if (sysname == NULL)
+ return NULL;
+ sysname[0] = '\0';
+ sysname = &sysname[1];
+ return udev_device_new_from_subsystem_sysname(udev, subsys, sysname);
+ default:
+ return NULL;
+ }
+}
+
+/**
+ * udev_device_new_from_subsystem_sysname:
+ * @udev: udev library context
+ * @subsystem: the subsystem of the device
+ * @sysname: the name of the device
+ *
+ * Create new udev device, and fill in information from the sys device
+ * and the udev database entry. The device is looked up by the subsystem
+ * and name string of the device, like "mem" / "zero", or "block" / "sda".
+ *
+ * The initial refcount is 1, and needs to be decremented to
+ * release the resources of the udev device.
+ *
+ * Returns: a new udev device, or #NULL, if it does not exist
+ **/
+_public_ struct udev_device *udev_device_new_from_subsystem_sysname(struct udev *udev, const char *subsystem, const char *sysname)
+{
+ char path[UTIL_PATH_SIZE];
+ struct stat statbuf;
+
+ if (streq(subsystem, "subsystem")) {
+ strscpyl(path, sizeof(path), "/sys/subsystem/", sysname, NULL);
+ if (stat(path, &statbuf) == 0)
+ goto found;
+
+ strscpyl(path, sizeof(path), "/sys/bus/", sysname, NULL);
+ if (stat(path, &statbuf) == 0)
+ goto found;
+
+ strscpyl(path, sizeof(path), "/sys/class/", sysname, NULL);
+ if (stat(path, &statbuf) == 0)
+ goto found;
+ goto out;
+ }
+
+ if (streq(subsystem, "module")) {
+ strscpyl(path, sizeof(path), "/sys/module/", sysname, NULL);
+ if (stat(path, &statbuf) == 0)
+ goto found;
+ goto out;
+ }
+
+ if (streq(subsystem, "drivers")) {
+ char subsys[UTIL_NAME_SIZE];
+ char *driver;
+
+ strscpy(subsys, sizeof(subsys), sysname);
+ driver = strchr(subsys, ':');
+ if (driver != NULL) {
+ driver[0] = '\0';
+ driver = &driver[1];
+
+ strscpyl(path, sizeof(path), "/sys/subsystem/", subsys, "/drivers/", driver, NULL);
+ if (stat(path, &statbuf) == 0)
+ goto found;
+
+ strscpyl(path, sizeof(path), "/sys/bus/", subsys, "/drivers/", driver, NULL);
+ if (stat(path, &statbuf) == 0)
+ goto found;
+ }
+ goto out;
+ }
+
+ strscpyl(path, sizeof(path), "/sys/subsystem/", subsystem, "/devices/", sysname, NULL);
+ if (stat(path, &statbuf) == 0)
+ goto found;
+
+ strscpyl(path, sizeof(path), "/sys/bus/", subsystem, "/devices/", sysname, NULL);
+ if (stat(path, &statbuf) == 0)
+ goto found;
+
+ strscpyl(path, sizeof(path), "/sys/class/", subsystem, "/", sysname, NULL);
+ if (stat(path, &statbuf) == 0)
+ goto found;
+out:
+ return NULL;
+found:
+ return udev_device_new_from_syspath(udev, path);
+}
+
+/**
+ * udev_device_new_from_environment
+ * @udev: udev library context
+ *
+ * Create new udev device, and fill in information from the
+ * current process environment. This only works reliable if
+ * the process is called from a udev rule. It is usually used
+ * for tools executed from IMPORT= rules.
+ *
+ * The initial refcount is 1, and needs to be decremented to
+ * release the resources of the udev device.
+ *
+ * Returns: a new udev device, or #NULL, if it does not exist
+ **/
+_public_ struct udev_device *udev_device_new_from_environment(struct udev *udev)
+{
+ int i;
+ struct udev_device *udev_device;
+
+ udev_device = udev_device_new(udev);
+ if (udev_device == NULL)
+ return NULL;
+ udev_device_set_info_loaded(udev_device);
+
+ for (i = 0; environ[i] != NULL; i++)
+ udev_device_add_property_from_string_parse(udev_device, environ[i]);
+
+ if (udev_device_add_property_from_string_parse_finish(udev_device) < 0) {
+ udev_dbg(udev, "missing values, invalid device\n");
+ udev_device_unref(udev_device);
+ udev_device = NULL;
+ }
+
+ return udev_device;
+}
+
+static struct udev_device *device_new_from_parent(struct udev_device *udev_device)
+{
+ struct udev_device *udev_device_parent = NULL;
+ char path[UTIL_PATH_SIZE];
+ const char *subdir;
+
+ strscpy(path, sizeof(path), udev_device->syspath);
+ subdir = path + strlen("/sys/");
+ for (;;) {
+ char *pos;
+
+ pos = strrchr(subdir, '/');
+ if (pos == NULL || pos < &subdir[2])
+ break;
+ pos[0] = '\0';
+ udev_device_parent = udev_device_new_from_syspath(udev_device->udev, path);
+ if (udev_device_parent != NULL)
+ return udev_device_parent;
+ }
+ return NULL;
+}
+
+/**
+ * udev_device_get_parent:
+ * @udev_device: the device to start searching from
+ *
+ * Find the next parent device, and fill in information from the sys
+ * device and the udev database entry.
+ *
+ * The returned the device is not referenced. It is attached to the
+ * child device, and will be cleaned up when the child device
+ * is cleaned up.
+ *
+ * It is not necessarily just the upper level directory, empty or not
+ * recognized sys directories are ignored.
+ *
+ * It can be called as many times as needed, without caring about
+ * references.
+ *
+ * Returns: a new udev device, or #NULL, if it no parent exist.
+ **/
+_public_ struct udev_device *udev_device_get_parent(struct udev_device *udev_device)
+{
+ if (udev_device == NULL)
+ return NULL;
+ if (!udev_device->parent_set) {
+ udev_device->parent_set = true;
+ udev_device->parent_device = device_new_from_parent(udev_device);
+ }
+ return udev_device->parent_device;
+}
+
+/**
+ * udev_device_get_parent_with_subsystem_devtype:
+ * @udev_device: udev device to start searching from
+ * @subsystem: the subsystem of the device
+ * @devtype: the type (DEVTYPE) of the device
+ *
+ * Find the next parent device, with a matching subsystem and devtype
+ * value, and fill in information from the sys device and the udev
+ * database entry.
+ *
+ * If devtype is #NULL, only subsystem is checked, and any devtype will
+ * match.
+ *
+ * The returned the device is not referenced. It is attached to the
+ * child device, and will be cleaned up when the child device
+ * is cleaned up.
+ *
+ * It can be called as many times as needed, without caring about
+ * references.
+ *
+ * Returns: a new udev device, or #NULL if no matching parent exists.
+ **/
+_public_ struct udev_device *udev_device_get_parent_with_subsystem_devtype(struct udev_device *udev_device, const char *subsystem, const char *devtype)
+{
+ struct udev_device *parent;
+
+ if (subsystem == NULL)
+ return NULL;
+
+ parent = udev_device_get_parent(udev_device);
+ while (parent != NULL) {
+ const char *parent_subsystem;
+ const char *parent_devtype;
+
+ parent_subsystem = udev_device_get_subsystem(parent);
+ if (parent_subsystem != NULL && streq(parent_subsystem, subsystem)) {
+ if (devtype == NULL)
+ break;
+ parent_devtype = udev_device_get_devtype(parent);
+ if (parent_devtype != NULL && streq(parent_devtype, devtype))
+ break;
+ }
+ parent = udev_device_get_parent(parent);
+ }
+ return parent;
+}
+
+/**
+ * udev_device_get_udev:
+ * @udev_device: udev device
+ *
+ * Retrieve the udev library context the device was created with.
+ *
+ * Returns: the udev library context
+ **/
+_public_ struct udev *udev_device_get_udev(struct udev_device *udev_device)
+{
+ if (udev_device == NULL)
+ return NULL;
+ return udev_device->udev;
+}
+
+/**
+ * udev_device_ref:
+ * @udev_device: udev device
+ *
+ * Take a reference of a udev device.
+ *
+ * Returns: the passed udev device
+ **/
+_public_ struct udev_device *udev_device_ref(struct udev_device *udev_device)
+{
+ if (udev_device == NULL)
+ return NULL;
+ udev_device->refcount++;
+ return udev_device;
+}
+
+/**
+ * udev_device_unref:
+ * @udev_device: udev device
+ *
+ * Drop a reference of a udev device. If the refcount reaches zero,
+ * the resources of the device will be released.
+ *
+ * Returns: the passed udev device if it has still an active reference, or #NULL otherwise.
+ **/
+_public_ struct udev_device *udev_device_unref(struct udev_device *udev_device)
+{
+ if (udev_device == NULL)
+ return NULL;
+ udev_device->refcount--;
+ if (udev_device->refcount > 0)
+ return udev_device;
+ if (udev_device->parent_device != NULL)
+ udev_device_unref(udev_device->parent_device);
+ free(udev_device->syspath);
+ free(udev_device->sysname);
+ free(udev_device->devnode);
+ free(udev_device->subsystem);
+ free(udev_device->devtype);
+ udev_list_cleanup(&udev_device->devlinks_list);
+ udev_list_cleanup(&udev_device->properties_list);
+ udev_list_cleanup(&udev_device->sysattr_value_list);
+ udev_list_cleanup(&udev_device->sysattr_list);
+ udev_list_cleanup(&udev_device->tags_list);
+ free(udev_device->action);
+ free(udev_device->driver);
+ free(udev_device->devpath_old);
+ free(udev_device->id_filename);
+ free(udev_device->envp);
+ free(udev_device->monitor_buf);
+ free(udev_device);
+ return NULL;
+}
+
+/**
+ * udev_device_get_devpath:
+ * @udev_device: udev device
+ *
+ * Retrieve the kernel devpath value of the udev device. The path
+ * does not contain the sys mount point, and starts with a '/'.
+ *
+ * Returns: the devpath of the udev device
+ **/
+_public_ const char *udev_device_get_devpath(struct udev_device *udev_device)
+{
+ if (udev_device == NULL)
+ return NULL;
+ return udev_device->devpath;
+}
+
+/**
+ * udev_device_get_syspath:
+ * @udev_device: udev device
+ *
+ * Retrieve the sys path of the udev device. The path is an
+ * absolute path and starts with the sys mount point.
+ *
+ * Returns: the sys path of the udev device
+ **/
+_public_ const char *udev_device_get_syspath(struct udev_device *udev_device)
+{
+ if (udev_device == NULL)
+ return NULL;
+ return udev_device->syspath;
+}
+
+/**
+ * udev_device_get_sysname:
+ * @udev_device: udev device
+ *
+ * Get the kernel device name in /sys.
+ *
+ * Returns: the name string of the device device
+ **/
+_public_ const char *udev_device_get_sysname(struct udev_device *udev_device)
+{
+ if (udev_device == NULL)
+ return NULL;
+ return udev_device->sysname;
+}
+
+/**
+ * udev_device_get_sysnum:
+ * @udev_device: udev device
+ *
+ * Get the instance number of the device.
+ *
+ * Returns: the trailing number string of the device name
+ **/
+_public_ const char *udev_device_get_sysnum(struct udev_device *udev_device)
+{
+ if (udev_device == NULL)
+ return NULL;
+ return udev_device->sysnum;
+}
+
+/**
+ * udev_device_get_devnode:
+ * @udev_device: udev device
+ *
+ * Retrieve the device node file name belonging to the udev device.
+ * The path is an absolute path, and starts with the device directory.
+ *
+ * Returns: the device node file name of the udev device, or #NULL if no device node exists
+ **/
+_public_ const char *udev_device_get_devnode(struct udev_device *udev_device)
+{
+ if (udev_device == NULL)
+ return NULL;
+ if (udev_device->devnode != NULL)
+ return udev_device->devnode;
+ if (!udev_device->info_loaded)
+ udev_device_read_uevent_file(udev_device);
+ return udev_device->devnode;
+}
+
+/**
+ * udev_device_get_devlinks_list_entry:
+ * @udev_device: udev device
+ *
+ * Retrieve the list of device links pointing to the device file of
+ * the udev device. The next list entry can be retrieved with
+ * udev_list_entry_get_next(), which returns #NULL if no more entries exist.
+ * The devlink path can be retrieved from the list entry by
+ * udev_list_entry_get_name(). The path is an absolute path, and starts with
+ * the device directory.
+ *
+ * Returns: the first entry of the device node link list
+ **/
+_public_ struct udev_list_entry *udev_device_get_devlinks_list_entry(struct udev_device *udev_device)
+{
+ if (udev_device == NULL)
+ return NULL;
+ if (!udev_device->info_loaded)
+ udev_device_read_db(udev_device, NULL);
+ return udev_list_get_entry(&udev_device->devlinks_list);
+}
+
+void udev_device_cleanup_devlinks_list(struct udev_device *udev_device)
+{
+ udev_device->devlinks_uptodate = false;
+ udev_list_cleanup(&udev_device->devlinks_list);
+}
+
+/**
+ * udev_device_get_properties_list_entry:
+ * @udev_device: udev device
+ *
+ * Retrieve the list of key/value device properties of the udev
+ * device. The next list entry can be retrieved with udev_list_entry_get_next(),
+ * which returns #NULL if no more entries exist. The property name
+ * can be retrieved from the list entry by udev_list_entry_get_name(),
+ * the property value by udev_list_entry_get_value().
+ *
+ * Returns: the first entry of the property list
+ **/
+_public_ struct udev_list_entry *udev_device_get_properties_list_entry(struct udev_device *udev_device)
+{
+ if (udev_device == NULL)
+ return NULL;
+ if (!udev_device->info_loaded) {
+ udev_device_read_uevent_file(udev_device);
+ udev_device_read_db(udev_device, NULL);
+ }
+ if (!udev_device->devlinks_uptodate) {
+ char symlinks[UTIL_PATH_SIZE];
+ struct udev_list_entry *list_entry;
+
+ udev_device->devlinks_uptodate = true;
+ list_entry = udev_device_get_devlinks_list_entry(udev_device);
+ if (list_entry != NULL) {
+ char *s;
+ size_t l;
+
+ s = symlinks;
+ l = strpcpyl(&s, sizeof(symlinks), udev_list_entry_get_name(list_entry), NULL);
+ udev_list_entry_foreach(list_entry, udev_list_entry_get_next(list_entry))
+ l = strpcpyl(&s, l, " ", udev_list_entry_get_name(list_entry), NULL);
+ udev_device_add_property(udev_device, "DEVLINKS", symlinks);
+ }
+ }
+ if (!udev_device->tags_uptodate) {
+ udev_device->tags_uptodate = true;
+ if (udev_device_get_tags_list_entry(udev_device) != NULL) {
+ char tags[UTIL_PATH_SIZE];
+ struct udev_list_entry *list_entry;
+ char *s;
+ size_t l;
+
+ s = tags;
+ l = strpcpyl(&s, sizeof(tags), ":", NULL);
+ udev_list_entry_foreach(list_entry, udev_device_get_tags_list_entry(udev_device))
+ l = strpcpyl(&s, l, udev_list_entry_get_name(list_entry), ":", NULL);
+ udev_device_add_property(udev_device, "TAGS", tags);
+ }
+ }
+ return udev_list_get_entry(&udev_device->properties_list);
+}
+
+/**
+ * udev_device_get_action:
+ * @udev_device: udev device
+ *
+ * This is only valid if the device was received through a monitor. Devices read from
+ * sys do not have an action string. Usual actions are: add, remove, change, online,
+ * offline.
+ *
+ * Returns: the kernel action value, or #NULL if there is no action value available.
+ **/
+_public_ const char *udev_device_get_action(struct udev_device *udev_device)
+{
+ if (udev_device == NULL)
+ return NULL;
+ return udev_device->action;
+}
+
+/**
+ * udev_device_get_usec_since_initialized:
+ * @udev_device: udev device
+ *
+ * Return the number of microseconds passed since udev set up the
+ * device for the first time.
+ *
+ * This is only implemented for devices with need to store properties
+ * in the udev database. All other devices return 0 here.
+ *
+ * Returns: the number of microseconds since the device was first seen.
+ **/
+_public_ unsigned long long int udev_device_get_usec_since_initialized(struct udev_device *udev_device)
+{
+ usec_t now_ts;
+
+ if (udev_device == NULL)
+ return 0;
+ if (!udev_device->info_loaded)
+ udev_device_read_db(udev_device, NULL);
+ if (udev_device->usec_initialized == 0)
+ return 0;
+ now_ts = now(CLOCK_MONOTONIC);
+ if (now_ts == 0)
+ return 0;
+ return now_ts - udev_device->usec_initialized;
+}
+
+usec_t udev_device_get_usec_initialized(struct udev_device *udev_device)
+{
+ return udev_device->usec_initialized;
+}
+
+void udev_device_set_usec_initialized(struct udev_device *udev_device, usec_t usec_initialized)
+{
+ char num[32];
+
+ udev_device->usec_initialized = usec_initialized;
+ snprintf(num, sizeof(num), "%llu", (unsigned long long)usec_initialized);
+ udev_device_add_property(udev_device, "USEC_INITIALIZED", num);
+}
+
+/**
+ * udev_device_get_sysattr_value:
+ * @udev_device: udev device
+ * @sysattr: attribute name
+ *
+ * The retrieved value is cached in the device. Repeated calls will return the same
+ * value and not open the attribute again.
+ *
+ * Returns: the content of a sys attribute file, or #NULL if there is no sys attribute value.
+ **/
+_public_ const char *udev_device_get_sysattr_value(struct udev_device *udev_device, const char *sysattr)
+{
+ struct udev_list_entry *list_entry;
+ char path[UTIL_PATH_SIZE];
+ char value[4096];
+ struct stat statbuf;
+ int fd;
+ ssize_t size;
+ const char *val = NULL;
+
+ if (udev_device == NULL)
+ return NULL;
+ if (sysattr == NULL)
+ return NULL;
+
+ /* look for possibly already cached result */
+ list_entry = udev_list_get_entry(&udev_device->sysattr_value_list);
+ list_entry = udev_list_entry_get_by_name(list_entry, sysattr);
+ if (list_entry != NULL)
+ return udev_list_entry_get_value(list_entry);
+
+ strscpyl(path, sizeof(path), udev_device_get_syspath(udev_device), "/", sysattr, NULL);
+ if (lstat(path, &statbuf) != 0) {
+ udev_list_entry_add(&udev_device->sysattr_value_list, sysattr, NULL);
+ goto out;
+ }
+
+ if (S_ISLNK(statbuf.st_mode)) {
+ /*
+ * Some core links return only the last element of the target path,
+ * these are just values, the paths should not be exposed.
+ */
+ if (streq(sysattr, "driver") ||
+ streq(sysattr, "subsystem") ||
+ streq(sysattr, "module")) {
+ if (util_get_sys_core_link_value(udev_device->udev, sysattr,
+ udev_device->syspath, value, sizeof(value)) < 0)
+ return NULL;
+ list_entry = udev_list_entry_add(&udev_device->sysattr_value_list, sysattr, value);
+ val = udev_list_entry_get_value(list_entry);
+ goto out;
+ }
+
+ goto out;
+ }
+
+ /* skip directories */
+ if (S_ISDIR(statbuf.st_mode))
+ goto out;
+
+ /* skip non-readable files */
+ if ((statbuf.st_mode & S_IRUSR) == 0)
+ goto out;
+
+ /* read attribute value */
+ fd = open(path, O_RDONLY|O_CLOEXEC);
+ if (fd < 0)
+ goto out;
+ size = read(fd, value, sizeof(value));
+ close(fd);
+ if (size < 0)
+ goto out;
+ if (size == sizeof(value))
+ goto out;
+
+ /* got a valid value, store it in cache and return it */
+ value[size] = '\0';
+ util_remove_trailing_chars(value, '\n');
+ list_entry = udev_list_entry_add(&udev_device->sysattr_value_list, sysattr, value);
+ val = udev_list_entry_get_value(list_entry);
+out:
+ return val;
+}
+
+/**
+ * udev_device_set_sysattr_value:
+ * @udev_device: udev device
+ * @sysattr: attribute name
+ * @value: new value to be set
+ *
+ * Update the contents of the sys attribute and the cached value of the device.
+ *
+ * Returns: Negative error code on failure or 0 on success.
+ **/
+_public_ int udev_device_set_sysattr_value(struct udev_device *udev_device, const char *sysattr, char *value)
+{
+ struct udev_device *dev;
+ char path[UTIL_PATH_SIZE];
+ struct stat statbuf;
+ int fd;
+ ssize_t size, value_len;
+ int ret = 0;
+
+ if (udev_device == NULL)
+ return -EINVAL;
+ dev = udev_device;
+ if (sysattr == NULL)
+ return -EINVAL;
+ if (value == NULL)
+ value_len = 0;
+ else
+ value_len = strlen(value);
+
+ strscpyl(path, sizeof(path), udev_device_get_syspath(dev), "/", sysattr, NULL);
+ if (lstat(path, &statbuf) != 0) {
+ udev_list_entry_add(&dev->sysattr_value_list, sysattr, NULL);
+ ret = -ENXIO;
+ goto out;
+ }
+
+ if (S_ISLNK(statbuf.st_mode)) {
+ ret = -EINVAL;
+ goto out;
+ }
+
+ /* skip directories */
+ if (S_ISDIR(statbuf.st_mode)) {
+ ret = -EISDIR;
+ goto out;
+ }
+
+ /* skip non-readable files */
+ if ((statbuf.st_mode & S_IRUSR) == 0) {
+ ret = -EACCES;
+ goto out;
+ }
+
+ /* Value is limited to 4k */
+ if (value_len > 4096) {
+ ret = -EINVAL;
+ goto out;
+ }
+ util_remove_trailing_chars(value, '\n');
+
+ /* write attribute value */
+ fd = open(path, O_WRONLY|O_CLOEXEC);
+ if (fd < 0) {
+ ret = -errno;
+ goto out;
+ }
+ size = write(fd, value, value_len);
+ close(fd);
+ if (size < 0) {
+ ret = -errno;
+ goto out;
+ }
+ if (size < value_len) {
+ ret = -EIO;
+ goto out;
+ }
+
+ /* wrote a valid value, store it in cache and return it */
+ udev_list_entry_add(&dev->sysattr_value_list, sysattr, value);
+out:
+ if (dev != udev_device)
+ udev_device_unref(dev);
+ return ret;
+}
+
+static int udev_device_sysattr_list_read(struct udev_device *udev_device)
+{
+ struct dirent *dent;
+ DIR *dir;
+ int num = 0;
+
+ if (udev_device == NULL)
+ return -1;
+ if (udev_device->sysattr_list_read)
+ return 0;
+
+ dir = opendir(udev_device_get_syspath(udev_device));
+ if (!dir)
+ return -1;
+
+ for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
+ char path[UTIL_PATH_SIZE];
+ struct stat statbuf;
+
+ /* only handle symlinks and regular files */
+ if (dent->d_type != DT_LNK && dent->d_type != DT_REG)
+ continue;
+
+ strscpyl(path, sizeof(path), udev_device_get_syspath(udev_device), "/", dent->d_name, NULL);
+ if (lstat(path, &statbuf) != 0)
+ continue;
+ if ((statbuf.st_mode & S_IRUSR) == 0)
+ continue;
+
+ udev_list_entry_add(&udev_device->sysattr_list, dent->d_name, NULL);
+ num++;
+ }
+
+ closedir(dir);
+ udev_device->sysattr_list_read = true;
+
+ return num;
+}
+
+/**
+ * udev_device_get_sysattr_list_entry:
+ * @udev_device: udev device
+ *
+ * Retrieve the list of available sysattrs, with value being empty;
+ * This just return all available sysfs attributes for a particular
+ * device without reading their values.
+ *
+ * Returns: the first entry of the property list
+ **/
+_public_ struct udev_list_entry *udev_device_get_sysattr_list_entry(struct udev_device *udev_device)
+{
+ if (!udev_device->sysattr_list_read) {
+ int ret;
+ ret = udev_device_sysattr_list_read(udev_device);
+ if (0 > ret)
+ return NULL;
+ }
+
+ return udev_list_get_entry(&udev_device->sysattr_list);
+}
+
+int udev_device_set_syspath(struct udev_device *udev_device, const char *syspath)
+{
+ const char *pos;
+ size_t len;
+
+ free(udev_device->syspath);
+ udev_device->syspath = strdup(syspath);
+ if (udev_device->syspath == NULL)
+ return -ENOMEM;
+ udev_device->devpath = udev_device->syspath + strlen("/sys");
+ udev_device_add_property(udev_device, "DEVPATH", udev_device->devpath);
+
+ pos = strrchr(udev_device->syspath, '/');
+ if (pos == NULL)
+ return -EINVAL;
+ udev_device->sysname = strdup(&pos[1]);
+ if (udev_device->sysname == NULL)
+ return -ENOMEM;
+
+ /* some devices have '!' in their name, change that to '/' */
+ len = 0;
+ while (udev_device->sysname[len] != '\0') {
+ if (udev_device->sysname[len] == '!')
+ udev_device->sysname[len] = '/';
+ len++;
+ }
+
+ /* trailing number */
+ while (len > 0 && isdigit(udev_device->sysname[--len]))
+ udev_device->sysnum = &udev_device->sysname[len];
+
+ /* sysname is completely numeric */
+ if (len == 0)
+ udev_device->sysnum = NULL;
+
+ return 0;
+}
+
+int udev_device_set_devnode(struct udev_device *udev_device, const char *devnode)
+{
+ free(udev_device->devnode);
+ if (devnode[0] != '/') {
+ if (asprintf(&udev_device->devnode, "/dev/%s", devnode) < 0)
+ udev_device->devnode = NULL;
+ } else {
+ udev_device->devnode = strdup(devnode);
+ }
+ if (udev_device->devnode == NULL)
+ return -ENOMEM;
+ udev_device_add_property(udev_device, "DEVNAME", udev_device->devnode);
+ return 0;
+}
+
+int udev_device_add_devlink(struct udev_device *udev_device, const char *devlink)
+{
+ struct udev_list_entry *list_entry;
+
+ udev_device->devlinks_uptodate = false;
+ list_entry = udev_list_entry_add(&udev_device->devlinks_list, devlink, NULL);
+ if (list_entry == NULL)
+ return -ENOMEM;
+ return 0;
+}
+
+const char *udev_device_get_id_filename(struct udev_device *udev_device)
+{
+ if (udev_device->id_filename == NULL) {
+ if (udev_device_get_subsystem(udev_device) == NULL)
+ return NULL;
+
+ if (major(udev_device_get_devnum(udev_device)) > 0) {
+ /* use dev_t -- b259:131072, c254:0 */
+ if (asprintf(&udev_device->id_filename, "%c%u:%u",
+ streq(udev_device_get_subsystem(udev_device), "block") ? 'b' : 'c',
+ major(udev_device_get_devnum(udev_device)),
+ minor(udev_device_get_devnum(udev_device))) < 0)
+ udev_device->id_filename = NULL;
+ } else if (udev_device_get_ifindex(udev_device) > 0) {
+ /* use netdev ifindex -- n3 */
+ if (asprintf(&udev_device->id_filename, "n%u", udev_device_get_ifindex(udev_device)) < 0)
+ udev_device->id_filename = NULL;
+ } else {
+ /*
+ * use $subsys:$syname -- pci:0000:00:1f.2
+ * sysname() has '!' translated, get it from devpath
+ */
+ const char *sysname;
+ sysname = strrchr(udev_device->devpath, '/');
+ if (sysname == NULL)
+ return NULL;
+ sysname = &sysname[1];
+ if (asprintf(&udev_device->id_filename, "+%s:%s", udev_device_get_subsystem(udev_device), sysname) < 0)
+ udev_device->id_filename = NULL;
+ }
+ }
+ return udev_device->id_filename;
+}
+
+/**
+ * udev_device_get_is_initialized:
+ * @udev_device: udev device
+ *
+ * Check if udev has already handled the device and has set up
+ * device node permissions and context, or has renamed a network
+ * device.
+ *
+ * This is only implemented for devices with a device node
+ * or network interfaces. All other devices return 1 here.
+ *
+ * Returns: 1 if the device is set up. 0 otherwise.
+ **/
+_public_ int udev_device_get_is_initialized(struct udev_device *udev_device)
+{
+ if (!udev_device->info_loaded)
+ udev_device_read_db(udev_device, NULL);
+ return udev_device->is_initialized;
+}
+
+void udev_device_set_is_initialized(struct udev_device *udev_device)
+{
+ udev_device->is_initialized = true;
+}
+
+int udev_device_add_tag(struct udev_device *udev_device, const char *tag)
+{
+ if (strchr(tag, ':') != NULL || strchr(tag, ' ') != NULL)
+ return -EINVAL;
+ udev_device->tags_uptodate = false;
+ if (udev_list_entry_add(&udev_device->tags_list, tag, NULL) != NULL)
+ return 0;
+ return -ENOMEM;
+}
+
+void udev_device_cleanup_tags_list(struct udev_device *udev_device)
+{
+ udev_device->tags_uptodate = false;
+ udev_list_cleanup(&udev_device->tags_list);
+}
+
+/**
+ * udev_device_get_tags_list_entry:
+ * @udev_device: udev device
+ *
+ * Retrieve the list of tags attached to the udev device. The next
+ * list entry can be retrieved with udev_list_entry_get_next(),
+ * which returns #NULL if no more entries exist. The tag string
+ * can be retrieved from the list entry by udev_list_entry_get_name().
+ *
+ * Returns: the first entry of the tag list
+ **/
+_public_ struct udev_list_entry *udev_device_get_tags_list_entry(struct udev_device *udev_device)
+{
+ if (udev_device == NULL)
+ return NULL;
+ if (!udev_device->info_loaded)
+ udev_device_read_db(udev_device, NULL);
+ return udev_list_get_entry(&udev_device->tags_list);
+}
+
+/**
+ * udev_device_has_tag:
+ * @udev_device: udev device
+ * @tag: tag name
+ *
+ * Check if a given device has a certain tag associated.
+ *
+ * Returns: 1 if the tag is found. 0 otherwise.
+ **/
+_public_ int udev_device_has_tag(struct udev_device *udev_device, const char *tag)
+{
+ struct udev_list_entry *list_entry;
+
+ if (udev_device == NULL)
+ return false;
+ if (!udev_device->info_loaded)
+ udev_device_read_db(udev_device, NULL);
+ list_entry = udev_device_get_tags_list_entry(udev_device);
+ if (udev_list_entry_get_by_name(list_entry, tag) != NULL)
+ return true;
+ return false;
+}
+
+#define ENVP_SIZE 128
+#define MONITOR_BUF_SIZE 4096
+static int update_envp_monitor_buf(struct udev_device *udev_device)
+{
+ struct udev_list_entry *list_entry;
+ char *s;
+ size_t l;
+ unsigned int i;
+
+ /* monitor buffer of property strings */
+ free(udev_device->monitor_buf);
+ udev_device->monitor_buf_len = 0;
+ udev_device->monitor_buf = malloc(MONITOR_BUF_SIZE);
+ if (udev_device->monitor_buf == NULL)
+ return -ENOMEM;
+
+ /* envp array, strings will point into monitor buffer */
+ if (udev_device->envp == NULL)
+ udev_device->envp = malloc(sizeof(char *) * ENVP_SIZE);
+ if (udev_device->envp == NULL)
+ return -ENOMEM;
+
+ i = 0;
+ s = udev_device->monitor_buf;
+ l = MONITOR_BUF_SIZE;
+ udev_list_entry_foreach(list_entry, udev_device_get_properties_list_entry(udev_device)) {
+ const char *key;
+
+ key = udev_list_entry_get_name(list_entry);
+ /* skip private variables */
+ if (key[0] == '.')
+ continue;
+
+ /* add string to envp array */
+ udev_device->envp[i++] = s;
+ if (i+1 >= ENVP_SIZE)
+ return -EINVAL;
+
+ /* add property string to monitor buffer */
+ l = strpcpyl(&s, l, key, "=", udev_list_entry_get_value(list_entry), NULL);
+ if (l == 0)
+ return -EINVAL;
+ /* advance past the trailing '\0' that strpcpyl() guarantees */
+ s++;
+ l--;
+ }
+ udev_device->envp[i] = NULL;
+ udev_device->monitor_buf_len = s - udev_device->monitor_buf;
+ udev_device->envp_uptodate = true;
+ return 0;
+}
+
+char **udev_device_get_properties_envp(struct udev_device *udev_device)
+{
+ if (!udev_device->envp_uptodate)
+ if (update_envp_monitor_buf(udev_device) != 0)
+ return NULL;
+ return udev_device->envp;
+}
+
+ssize_t udev_device_get_properties_monitor_buf(struct udev_device *udev_device, const char **buf)
+{
+ if (!udev_device->envp_uptodate)
+ if (update_envp_monitor_buf(udev_device) != 0)
+ return -EINVAL;
+ *buf = udev_device->monitor_buf;
+ return udev_device->monitor_buf_len;
+}
+
+int udev_device_set_action(struct udev_device *udev_device, const char *action)
+{
+ free(udev_device->action);
+ udev_device->action = strdup(action);
+ if (udev_device->action == NULL)
+ return -ENOMEM;
+ udev_device_add_property(udev_device, "ACTION", udev_device->action);
+ return 0;
+}
+
+int udev_device_get_devlink_priority(struct udev_device *udev_device)
+{
+ if (!udev_device->info_loaded)
+ udev_device_read_db(udev_device, NULL);
+ return udev_device->devlink_priority;
+}
+
+int udev_device_set_devlink_priority(struct udev_device *udev_device, int prio)
+{
+ udev_device->devlink_priority = prio;
+ return 0;
+}
+
+int udev_device_get_watch_handle(struct udev_device *udev_device)
+{
+ if (!udev_device->info_loaded)
+ udev_device_read_db(udev_device, NULL);
+ return udev_device->watch_handle;
+}
+
+int udev_device_set_watch_handle(struct udev_device *udev_device, int handle)
+{
+ udev_device->watch_handle = handle;
+ return 0;
+}
+
+bool udev_device_get_db_persist(struct udev_device *udev_device)
+{
+ return udev_device->db_persist;
+}
+
+void udev_device_set_db_persist(struct udev_device *udev_device)
+{
+ udev_device->db_persist = true;
+}
diff --git a/src/libudev/libudev-enumerate.c b/src/libudev/libudev-enumerate.c
new file mode 100644
index 0000000000..5ccaabdc6c
--- /dev/null
+++ b/src/libudev/libudev-enumerate.c
@@ -0,0 +1,958 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2008-2012 Kay Sievers <kay@vrfy.org>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <unistd.h>
+#include <errno.h>
+#include <string.h>
+#include <dirent.h>
+#include <fnmatch.h>
+#include <stdbool.h>
+#include <sys/stat.h>
+#include <sys/param.h>
+
+#include "libudev.h"
+#include "libudev-private.h"
+
+/**
+ * SECTION:libudev-enumerate
+ * @short_description: lookup and sort sys devices
+ *
+ * Lookup devices in the sys filesystem, filter devices by properties,
+ * and return a sorted list of devices.
+ */
+
+struct syspath {
+ char *syspath;
+ size_t len;
+};
+
+/**
+ * udev_enumerate:
+ *
+ * Opaque object representing one device lookup/sort context.
+ */
+struct udev_enumerate {
+ struct udev *udev;
+ int refcount;
+ struct udev_list sysattr_match_list;
+ struct udev_list sysattr_nomatch_list;
+ struct udev_list subsystem_match_list;
+ struct udev_list subsystem_nomatch_list;
+ struct udev_list sysname_match_list;
+ struct udev_list properties_match_list;
+ struct udev_list tags_match_list;
+ struct udev_device *parent_match;
+ struct udev_list devices_list;
+ struct syspath *devices;
+ unsigned int devices_cur;
+ unsigned int devices_max;
+ bool devices_uptodate:1;
+ bool match_is_initialized;
+};
+
+/**
+ * udev_enumerate_new:
+ * @udev: udev library context
+ *
+ * Create an enumeration context to scan /sys.
+ *
+ * Returns: an enumeration context.
+ **/
+_public_ struct udev_enumerate *udev_enumerate_new(struct udev *udev)
+{
+ struct udev_enumerate *udev_enumerate;
+
+ if (udev == NULL)
+ return NULL;
+ udev_enumerate = calloc(1, sizeof(struct udev_enumerate));
+ if (udev_enumerate == NULL)
+ return NULL;
+ udev_enumerate->refcount = 1;
+ udev_enumerate->udev = udev;
+ udev_list_init(udev, &udev_enumerate->sysattr_match_list, false);
+ udev_list_init(udev, &udev_enumerate->sysattr_nomatch_list, false);
+ udev_list_init(udev, &udev_enumerate->subsystem_match_list, true);
+ udev_list_init(udev, &udev_enumerate->subsystem_nomatch_list, true);
+ udev_list_init(udev, &udev_enumerate->sysname_match_list, true);
+ udev_list_init(udev, &udev_enumerate->properties_match_list, false);
+ udev_list_init(udev, &udev_enumerate->tags_match_list, true);
+ udev_list_init(udev, &udev_enumerate->devices_list, false);
+ return udev_enumerate;
+}
+
+/**
+ * udev_enumerate_ref:
+ * @udev_enumerate: context
+ *
+ * Take a reference of a enumeration context.
+ *
+ * Returns: the passed enumeration context
+ **/
+_public_ struct udev_enumerate *udev_enumerate_ref(struct udev_enumerate *udev_enumerate)
+{
+ if (udev_enumerate == NULL)
+ return NULL;
+ udev_enumerate->refcount++;
+ return udev_enumerate;
+}
+
+/**
+ * udev_enumerate_unref:
+ * @udev_enumerate: context
+ *
+ * Drop a reference of an enumeration context. If the refcount reaches zero,
+ * all resources of the enumeration context will be released.
+ *
+ * Returns: the passed enumeration context if it has still an active reference, or #NULL otherwise.
+ **/
+_public_ struct udev_enumerate *udev_enumerate_unref(struct udev_enumerate *udev_enumerate)
+{
+ unsigned int i;
+
+ if (udev_enumerate == NULL)
+ return NULL;
+ udev_enumerate->refcount--;
+ if (udev_enumerate->refcount > 0)
+ return udev_enumerate;
+ udev_list_cleanup(&udev_enumerate->sysattr_match_list);
+ udev_list_cleanup(&udev_enumerate->sysattr_nomatch_list);
+ udev_list_cleanup(&udev_enumerate->subsystem_match_list);
+ udev_list_cleanup(&udev_enumerate->subsystem_nomatch_list);
+ udev_list_cleanup(&udev_enumerate->sysname_match_list);
+ udev_list_cleanup(&udev_enumerate->properties_match_list);
+ udev_list_cleanup(&udev_enumerate->tags_match_list);
+ udev_device_unref(udev_enumerate->parent_match);
+ udev_list_cleanup(&udev_enumerate->devices_list);
+ for (i = 0; i < udev_enumerate->devices_cur; i++)
+ free(udev_enumerate->devices[i].syspath);
+ free(udev_enumerate->devices);
+ free(udev_enumerate);
+ return NULL;
+}
+
+/**
+ * udev_enumerate_get_udev:
+ * @udev_enumerate: context
+ *
+ * Get the udev library context.
+ *
+ * Returns: a pointer to the context.
+ */
+_public_ struct udev *udev_enumerate_get_udev(struct udev_enumerate *udev_enumerate)
+{
+ if (udev_enumerate == NULL)
+ return NULL;
+ return udev_enumerate->udev;
+}
+
+static int syspath_add(struct udev_enumerate *udev_enumerate, const char *syspath)
+{
+ char *path;
+ struct syspath *entry;
+
+ /* double array size if needed */
+ if (udev_enumerate->devices_cur >= udev_enumerate->devices_max) {
+ struct syspath *buf;
+ unsigned int add;
+
+ add = udev_enumerate->devices_max;
+ if (add < 1024)
+ add = 1024;
+ buf = realloc(udev_enumerate->devices, (udev_enumerate->devices_max + add) * sizeof(struct syspath));
+ if (buf == NULL)
+ return -ENOMEM;
+ udev_enumerate->devices = buf;
+ udev_enumerate->devices_max += add;
+ }
+
+ path = strdup(syspath);
+ if (path == NULL)
+ return -ENOMEM;
+ entry = &udev_enumerate->devices[udev_enumerate->devices_cur];
+ entry->syspath = path;
+ entry->len = strlen(path);
+ udev_enumerate->devices_cur++;
+ udev_enumerate->devices_uptodate = false;
+ return 0;
+}
+
+static int syspath_cmp(const void *p1, const void *p2)
+{
+ const struct syspath *path1 = p1;
+ const struct syspath *path2 = p2;
+ size_t len;
+ int ret;
+
+ len = MIN(path1->len, path2->len);
+ ret = memcmp(path1->syspath, path2->syspath, len);
+ if (ret == 0) {
+ if (path1->len < path2->len)
+ ret = -1;
+ else if (path1->len > path2->len)
+ ret = 1;
+ }
+ return ret;
+}
+
+/* For devices that should be moved to the absolute end of the list */
+static bool devices_delay_end(struct udev *udev, const char *syspath)
+{
+ static const char *delay_device_list[] = {
+ "/block/md",
+ "/block/dm-",
+ NULL
+ };
+ int i;
+
+ for (i = 0; delay_device_list[i] != NULL; i++) {
+ if (strstr(syspath + strlen("/sys"), delay_device_list[i]) != NULL)
+ return true;
+ }
+ return false;
+}
+
+/* For devices that should just be moved a little bit later, just
+ * before the point where some common path prefix changes. Returns the
+ * number of characters that make up that common prefix */
+static size_t devices_delay_later(struct udev *udev, const char *syspath)
+{
+ const char *c;
+
+ /* For sound cards the control device must be enumerated last
+ * to make sure it's the final device node that gets ACLs
+ * applied. Applications rely on this fact and use ACL changes
+ * on the control node as an indicator that the ACL change of
+ * the entire sound card completed. The kernel makes this
+ * guarantee when creating those devices, and hence we should
+ * too when enumerating them. */
+
+ if ((c = strstr(syspath, "/sound/card"))) {
+ c += 11;
+ c += strcspn(c, "/");
+
+ if (startswith(c, "/controlC"))
+ return c - syspath + 1;
+ }
+
+ return 0;
+}
+
+/**
+ * udev_enumerate_get_list_entry:
+ * @udev_enumerate: context
+ *
+ * Get the first entry of the sorted list of device paths.
+ *
+ * Returns: a udev_list_entry.
+ */
+_public_ struct udev_list_entry *udev_enumerate_get_list_entry(struct udev_enumerate *udev_enumerate)
+{
+ if (udev_enumerate == NULL)
+ return NULL;
+ if (!udev_enumerate->devices_uptodate) {
+ unsigned int i;
+ unsigned int max;
+ struct syspath *prev = NULL, *move_later = NULL;
+ size_t move_later_prefix = 0;
+
+ udev_list_cleanup(&udev_enumerate->devices_list);
+ qsort(udev_enumerate->devices, udev_enumerate->devices_cur, sizeof(struct syspath), syspath_cmp);
+
+ max = udev_enumerate->devices_cur;
+ for (i = 0; i < max; i++) {
+ struct syspath *entry = &udev_enumerate->devices[i];
+
+ /* skip duplicated entries */
+ if (prev != NULL &&
+ entry->len == prev->len &&
+ memcmp(entry->syspath, prev->syspath, entry->len) == 0)
+ continue;
+ prev = entry;
+
+ /* skip to be delayed devices, and add them to the end of the list */
+ if (devices_delay_end(udev_enumerate->udev, entry->syspath)) {
+ syspath_add(udev_enumerate, entry->syspath);
+ /* need to update prev here for the case realloc() gives a different address */
+ prev = &udev_enumerate->devices[i];
+ continue;
+ }
+
+ /* skip to be delayed devices, and move the to
+ * the point where the prefix changes. We can
+ * only move one item at a time. */
+ if (!move_later) {
+ move_later_prefix = devices_delay_later(udev_enumerate->udev, entry->syspath);
+
+ if (move_later_prefix > 0) {
+ move_later = entry;
+ continue;
+ }
+ }
+
+ if (move_later &&
+ !strneq(entry->syspath, move_later->syspath, move_later_prefix)) {
+
+ udev_list_entry_add(&udev_enumerate->devices_list, move_later->syspath, NULL);
+ move_later = NULL;
+ }
+
+ udev_list_entry_add(&udev_enumerate->devices_list, entry->syspath, NULL);
+ }
+
+ if (move_later)
+ udev_list_entry_add(&udev_enumerate->devices_list, move_later->syspath, NULL);
+
+ /* add and cleanup delayed devices from end of list */
+ for (i = max; i < udev_enumerate->devices_cur; i++) {
+ struct syspath *entry = &udev_enumerate->devices[i];
+
+ udev_list_entry_add(&udev_enumerate->devices_list, entry->syspath, NULL);
+ free(entry->syspath);
+ }
+ udev_enumerate->devices_cur = max;
+
+ udev_enumerate->devices_uptodate = true;
+ }
+ return udev_list_get_entry(&udev_enumerate->devices_list);
+}
+
+/**
+ * udev_enumerate_add_match_subsystem:
+ * @udev_enumerate: context
+ * @subsystem: filter for a subsystem of the device to include in the list
+ *
+ * Match only devices belonging to a certain kernel subsystem.
+ *
+ * Returns: 0 on success, otherwise a negative error value.
+ */
+_public_ int udev_enumerate_add_match_subsystem(struct udev_enumerate *udev_enumerate, const char *subsystem)
+{
+ if (udev_enumerate == NULL)
+ return -EINVAL;
+ if (subsystem == NULL)
+ return 0;
+ if (udev_list_entry_add(&udev_enumerate->subsystem_match_list, subsystem, NULL) == NULL)
+ return -ENOMEM;
+ return 0;
+}
+
+/**
+ * udev_enumerate_add_nomatch_subsystem:
+ * @udev_enumerate: context
+ * @subsystem: filter for a subsystem of the device to exclude from the list
+ *
+ * Match only devices not belonging to a certain kernel subsystem.
+ *
+ * Returns: 0 on success, otherwise a negative error value.
+ */
+_public_ int udev_enumerate_add_nomatch_subsystem(struct udev_enumerate *udev_enumerate, const char *subsystem)
+{
+ if (udev_enumerate == NULL)
+ return -EINVAL;
+ if (subsystem == NULL)
+ return 0;
+ if (udev_list_entry_add(&udev_enumerate->subsystem_nomatch_list, subsystem, NULL) == NULL)
+ return -ENOMEM;
+ return 0;
+}
+
+/**
+ * udev_enumerate_add_match_sysattr:
+ * @udev_enumerate: context
+ * @sysattr: filter for a sys attribute at the device to include in the list
+ * @value: optional value of the sys attribute
+ *
+ * Match only devices with a certain /sys device attribute.
+ *
+ * Returns: 0 on success, otherwise a negative error value.
+ */
+_public_ int udev_enumerate_add_match_sysattr(struct udev_enumerate *udev_enumerate, const char *sysattr, const char *value)
+{
+ if (udev_enumerate == NULL)
+ return -EINVAL;
+ if (sysattr == NULL)
+ return 0;
+ if (udev_list_entry_add(&udev_enumerate->sysattr_match_list, sysattr, value) == NULL)
+ return -ENOMEM;
+ return 0;
+}
+
+/**
+ * udev_enumerate_add_nomatch_sysattr:
+ * @udev_enumerate: context
+ * @sysattr: filter for a sys attribute at the device to exclude from the list
+ * @value: optional value of the sys attribute
+ *
+ * Match only devices not having a certain /sys device attribute.
+ *
+ * Returns: 0 on success, otherwise a negative error value.
+ */
+_public_ int udev_enumerate_add_nomatch_sysattr(struct udev_enumerate *udev_enumerate, const char *sysattr, const char *value)
+{
+ if (udev_enumerate == NULL)
+ return -EINVAL;
+ if (sysattr == NULL)
+ return 0;
+ if (udev_list_entry_add(&udev_enumerate->sysattr_nomatch_list, sysattr, value) == NULL)
+ return -ENOMEM;
+ return 0;
+}
+
+static int match_sysattr_value(struct udev_device *dev, const char *sysattr, const char *match_val)
+{
+ const char *val = NULL;
+ bool match = false;
+
+ val = udev_device_get_sysattr_value(dev, sysattr);
+ if (val == NULL)
+ goto exit;
+ if (match_val == NULL) {
+ match = true;
+ goto exit;
+ }
+ if (fnmatch(match_val, val, 0) == 0) {
+ match = true;
+ goto exit;
+ }
+exit:
+ return match;
+}
+
+/**
+ * udev_enumerate_add_match_property:
+ * @udev_enumerate: context
+ * @property: filter for a property of the device to include in the list
+ * @value: value of the property
+ *
+ * Match only devices with a certain property.
+ *
+ * Returns: 0 on success, otherwise a negative error value.
+ */
+_public_ int udev_enumerate_add_match_property(struct udev_enumerate *udev_enumerate, const char *property, const char *value)
+{
+ if (udev_enumerate == NULL)
+ return -EINVAL;
+ if (property == NULL)
+ return 0;
+ if (udev_list_entry_add(&udev_enumerate->properties_match_list, property, value) == NULL)
+ return -ENOMEM;
+ return 0;
+}
+
+/**
+ * udev_enumerate_add_match_tag:
+ * @udev_enumerate: context
+ * @tag: filter for a tag of the device to include in the list
+ *
+ * Match only devices with a certain tag.
+ *
+ * Returns: 0 on success, otherwise a negative error value.
+ */
+_public_ int udev_enumerate_add_match_tag(struct udev_enumerate *udev_enumerate, const char *tag)
+{
+ if (udev_enumerate == NULL)
+ return -EINVAL;
+ if (tag == NULL)
+ return 0;
+ if (udev_list_entry_add(&udev_enumerate->tags_match_list, tag, NULL) == NULL)
+ return -ENOMEM;
+ return 0;
+}
+
+/**
+ * udev_enumerate_add_match_parent:
+ * @udev_enumerate: context
+ * @parent: parent device where to start searching
+ *
+ * Return the devices on the subtree of one given device. The parent
+ * itself is included in the list.
+ *
+ * A reference for the device is held until the udev_enumerate context
+ * is cleaned up.
+ *
+ * Returns: 0 on success, otherwise a negative error value.
+ */
+_public_ int udev_enumerate_add_match_parent(struct udev_enumerate *udev_enumerate, struct udev_device *parent)
+{
+ if (udev_enumerate == NULL)
+ return -EINVAL;
+ if (parent == NULL)
+ return 0;
+ if (udev_enumerate->parent_match != NULL)
+ udev_device_unref(udev_enumerate->parent_match);
+ udev_enumerate->parent_match = udev_device_ref(parent);
+ return 0;
+}
+
+/**
+ * udev_enumerate_add_match_is_initialized:
+ * @udev_enumerate: context
+ *
+ * Match only devices which udev has set up already. This makes
+ * sure, that the device node permissions and context are properly set
+ * and that network devices are fully renamed.
+ *
+ * Usually, devices which are found in the kernel but not already
+ * handled by udev, have still pending events. Services should subscribe
+ * to monitor events and wait for these devices to become ready, instead
+ * of using uninitialized devices.
+ *
+ * For now, this will not affect devices which do not have a device node
+ * and are not network interfaces.
+ *
+ * Returns: 0 on success, otherwise a negative error value.
+ */
+_public_ int udev_enumerate_add_match_is_initialized(struct udev_enumerate *udev_enumerate)
+{
+ if (udev_enumerate == NULL)
+ return -EINVAL;
+ udev_enumerate->match_is_initialized = true;
+ return 0;
+}
+
+/**
+ * udev_enumerate_add_match_sysname:
+ * @udev_enumerate: context
+ * @sysname: filter for the name of the device to include in the list
+ *
+ * Match only devices with a given /sys device name.
+ *
+ * Returns: 0 on success, otherwise a negative error value.
+ */
+_public_ int udev_enumerate_add_match_sysname(struct udev_enumerate *udev_enumerate, const char *sysname)
+{
+ if (udev_enumerate == NULL)
+ return -EINVAL;
+ if (sysname == NULL)
+ return 0;
+ if (udev_list_entry_add(&udev_enumerate->sysname_match_list, sysname, NULL) == NULL)
+ return -ENOMEM;
+ return 0;
+}
+
+static bool match_sysattr(struct udev_enumerate *udev_enumerate, struct udev_device *dev)
+{
+ struct udev_list_entry *list_entry;
+
+ /* skip list */
+ udev_list_entry_foreach(list_entry, udev_list_get_entry(&udev_enumerate->sysattr_nomatch_list)) {
+ if (match_sysattr_value(dev, udev_list_entry_get_name(list_entry),
+ udev_list_entry_get_value(list_entry)))
+ return false;
+ }
+ /* include list */
+ if (udev_list_get_entry(&udev_enumerate->sysattr_match_list) != NULL) {
+ udev_list_entry_foreach(list_entry, udev_list_get_entry(&udev_enumerate->sysattr_match_list)) {
+ /* anything that does not match, will make it FALSE */
+ if (!match_sysattr_value(dev, udev_list_entry_get_name(list_entry),
+ udev_list_entry_get_value(list_entry)))
+ return false;
+ }
+ return true;
+ }
+ return true;
+}
+
+static bool match_property(struct udev_enumerate *udev_enumerate, struct udev_device *dev)
+{
+ struct udev_list_entry *list_entry;
+ bool match = false;
+
+ /* no match always matches */
+ if (udev_list_get_entry(&udev_enumerate->properties_match_list) == NULL)
+ return true;
+
+ /* loop over matches */
+ udev_list_entry_foreach(list_entry, udev_list_get_entry(&udev_enumerate->properties_match_list)) {
+ const char *match_key = udev_list_entry_get_name(list_entry);
+ const char *match_value = udev_list_entry_get_value(list_entry);
+ struct udev_list_entry *property_entry;
+
+ /* loop over device properties */
+ udev_list_entry_foreach(property_entry, udev_device_get_properties_list_entry(dev)) {
+ const char *dev_key = udev_list_entry_get_name(property_entry);
+ const char *dev_value = udev_list_entry_get_value(property_entry);
+
+ if (fnmatch(match_key, dev_key, 0) != 0)
+ continue;
+ if (match_value == NULL && dev_value == NULL) {
+ match = true;
+ goto out;
+ }
+ if (match_value == NULL || dev_value == NULL)
+ continue;
+ if (fnmatch(match_value, dev_value, 0) == 0) {
+ match = true;
+ goto out;
+ }
+ }
+ }
+out:
+ return match;
+}
+
+static bool match_tag(struct udev_enumerate *udev_enumerate, struct udev_device *dev)
+{
+ struct udev_list_entry *list_entry;
+
+ /* no match always matches */
+ if (udev_list_get_entry(&udev_enumerate->tags_match_list) == NULL)
+ return true;
+
+ /* loop over matches */
+ udev_list_entry_foreach(list_entry, udev_list_get_entry(&udev_enumerate->tags_match_list))
+ if (!udev_device_has_tag(dev, udev_list_entry_get_name(list_entry)))
+ return false;
+
+ return true;
+}
+
+static bool match_parent(struct udev_enumerate *udev_enumerate, struct udev_device *dev)
+{
+ if (udev_enumerate->parent_match == NULL)
+ return true;
+
+ return startswith(udev_device_get_devpath(dev), udev_device_get_devpath(udev_enumerate->parent_match));
+}
+
+static bool match_sysname(struct udev_enumerate *udev_enumerate, const char *sysname)
+{
+ struct udev_list_entry *list_entry;
+
+ if (udev_list_get_entry(&udev_enumerate->sysname_match_list) == NULL)
+ return true;
+
+ udev_list_entry_foreach(list_entry, udev_list_get_entry(&udev_enumerate->sysname_match_list)) {
+ if (fnmatch(udev_list_entry_get_name(list_entry), sysname, 0) != 0)
+ continue;
+ return true;
+ }
+ return false;
+}
+
+static int scan_dir_and_add_devices(struct udev_enumerate *udev_enumerate,
+ const char *basedir, const char *subdir1, const char *subdir2)
+{
+ char path[UTIL_PATH_SIZE];
+ size_t l;
+ char *s;
+ DIR *dir;
+ struct dirent *dent;
+
+ s = path;
+ l = strpcpyl(&s, sizeof(path), "/sys/", basedir, NULL);
+ if (subdir1 != NULL)
+ l = strpcpyl(&s, l, "/", subdir1, NULL);
+ if (subdir2 != NULL)
+ strpcpyl(&s, l, "/", subdir2, NULL);
+ dir = opendir(path);
+ if (dir == NULL)
+ return -ENOENT;
+ for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
+ char syspath[UTIL_PATH_SIZE];
+ struct udev_device *dev;
+
+ if (dent->d_name[0] == '.')
+ continue;
+
+ if (!match_sysname(udev_enumerate, dent->d_name))
+ continue;
+
+ strscpyl(syspath, sizeof(syspath), path, "/", dent->d_name, NULL);
+ dev = udev_device_new_from_syspath(udev_enumerate->udev, syspath);
+ if (dev == NULL)
+ continue;
+
+ if (udev_enumerate->match_is_initialized) {
+ /*
+ * All devices with a device node or network interfaces
+ * possibly need udev to adjust the device node permission
+ * or context, or rename the interface before it can be
+ * reliably used from other processes.
+ *
+ * For now, we can only check these types of devices, we
+ * might not store a database, and have no way to find out
+ * for all other types of devices.
+ */
+ if (!udev_device_get_is_initialized(dev) &&
+ (major(udev_device_get_devnum(dev)) > 0 || udev_device_get_ifindex(dev) > 0))
+ goto nomatch;
+ }
+ if (!match_parent(udev_enumerate, dev))
+ goto nomatch;
+ if (!match_tag(udev_enumerate, dev))
+ goto nomatch;
+ if (!match_property(udev_enumerate, dev))
+ goto nomatch;
+ if (!match_sysattr(udev_enumerate, dev))
+ goto nomatch;
+
+ syspath_add(udev_enumerate, udev_device_get_syspath(dev));
+nomatch:
+ udev_device_unref(dev);
+ }
+ closedir(dir);
+ return 0;
+}
+
+static bool match_subsystem(struct udev_enumerate *udev_enumerate, const char *subsystem)
+{
+ struct udev_list_entry *list_entry;
+
+ udev_list_entry_foreach(list_entry, udev_list_get_entry(&udev_enumerate->subsystem_nomatch_list)) {
+ if (fnmatch(udev_list_entry_get_name(list_entry), subsystem, 0) == 0)
+ return false;
+ }
+ if (udev_list_get_entry(&udev_enumerate->subsystem_match_list) != NULL) {
+ udev_list_entry_foreach(list_entry, udev_list_get_entry(&udev_enumerate->subsystem_match_list)) {
+ if (fnmatch(udev_list_entry_get_name(list_entry), subsystem, 0) == 0)
+ return true;
+ }
+ return false;
+ }
+ return true;
+}
+
+static int scan_dir(struct udev_enumerate *udev_enumerate, const char *basedir, const char *subdir, const char *subsystem)
+{
+ char path[UTIL_PATH_SIZE];
+ DIR *dir;
+ struct dirent *dent;
+
+ strscpyl(path, sizeof(path), "/sys/", basedir, NULL);
+ dir = opendir(path);
+ if (dir == NULL)
+ return -1;
+ for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
+ if (dent->d_name[0] == '.')
+ continue;
+ if (!match_subsystem(udev_enumerate, subsystem != NULL ? subsystem : dent->d_name))
+ continue;
+ scan_dir_and_add_devices(udev_enumerate, basedir, dent->d_name, subdir);
+ }
+ closedir(dir);
+ return 0;
+}
+
+/**
+ * udev_enumerate_add_syspath:
+ * @udev_enumerate: context
+ * @syspath: path of a device
+ *
+ * Add a device to the list of devices, to retrieve it back sorted in dependency order.
+ *
+ * Returns: 0 on success, otherwise a negative error value.
+ */
+_public_ int udev_enumerate_add_syspath(struct udev_enumerate *udev_enumerate, const char *syspath)
+{
+ struct udev_device *udev_device;
+
+ if (udev_enumerate == NULL)
+ return -EINVAL;
+ if (syspath == NULL)
+ return 0;
+ /* resolve to real syspath */
+ udev_device = udev_device_new_from_syspath(udev_enumerate->udev, syspath);
+ if (udev_device == NULL)
+ return -EINVAL;
+ syspath_add(udev_enumerate, udev_device_get_syspath(udev_device));
+ udev_device_unref(udev_device);
+ return 0;
+}
+
+static int scan_devices_tags(struct udev_enumerate *udev_enumerate)
+{
+ struct udev_list_entry *list_entry;
+
+ /* scan only tagged devices, use tags reverse-index, instead of searching all devices in /sys */
+ udev_list_entry_foreach(list_entry, udev_list_get_entry(&udev_enumerate->tags_match_list)) {
+ DIR *dir;
+ struct dirent *dent;
+ char path[UTIL_PATH_SIZE];
+
+ strscpyl(path, sizeof(path), "/run/udev/tags/", udev_list_entry_get_name(list_entry), NULL);
+ dir = opendir(path);
+ if (dir == NULL)
+ continue;
+ for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
+ struct udev_device *dev;
+
+ if (dent->d_name[0] == '.')
+ continue;
+
+ dev = udev_device_new_from_device_id(udev_enumerate->udev, dent->d_name);
+ if (dev == NULL)
+ continue;
+
+ if (!match_subsystem(udev_enumerate, udev_device_get_subsystem(dev)))
+ goto nomatch;
+ if (!match_sysname(udev_enumerate, udev_device_get_sysname(dev)))
+ goto nomatch;
+ if (!match_parent(udev_enumerate, dev))
+ goto nomatch;
+ if (!match_property(udev_enumerate, dev))
+ goto nomatch;
+ if (!match_sysattr(udev_enumerate, dev))
+ goto nomatch;
+
+ syspath_add(udev_enumerate, udev_device_get_syspath(dev));
+nomatch:
+ udev_device_unref(dev);
+ }
+ closedir(dir);
+ }
+ return 0;
+}
+
+static int parent_add_child(struct udev_enumerate *enumerate, const char *path)
+{
+ struct udev_device *dev;
+
+ dev = udev_device_new_from_syspath(enumerate->udev, path);
+ if (dev == NULL)
+ return -ENODEV;
+
+ if (!match_subsystem(enumerate, udev_device_get_subsystem(dev)))
+ return 0;
+ if (!match_sysname(enumerate, udev_device_get_sysname(dev)))
+ return 0;
+ if (!match_property(enumerate, dev))
+ return 0;
+ if (!match_sysattr(enumerate, dev))
+ return 0;
+
+ syspath_add(enumerate, udev_device_get_syspath(dev));
+ udev_device_unref(dev);
+ return 1;
+}
+
+static int parent_crawl_children(struct udev_enumerate *enumerate, const char *path, int maxdepth)
+{
+ DIR *d;
+ struct dirent *dent;
+
+ d = opendir(path);
+ if (d == NULL)
+ return -errno;
+
+ for (dent = readdir(d); dent != NULL; dent = readdir(d)) {
+ char *child;
+
+ if (dent->d_name[0] == '.')
+ continue;
+ if (dent->d_type != DT_DIR)
+ continue;
+ if (asprintf(&child, "%s/%s", path, dent->d_name) < 0)
+ continue;
+ parent_add_child(enumerate, child);
+ if (maxdepth > 0)
+ parent_crawl_children(enumerate, child, maxdepth-1);
+ free(child);
+ }
+
+ closedir(d);
+ return 0;
+}
+
+static int scan_devices_children(struct udev_enumerate *enumerate)
+{
+ const char *path;
+
+ path = udev_device_get_syspath(enumerate->parent_match);
+ parent_add_child(enumerate, path);
+ return parent_crawl_children(enumerate, path, 256);
+}
+
+static int scan_devices_all(struct udev_enumerate *udev_enumerate)
+{
+ struct stat statbuf;
+
+ if (stat("/sys/subsystem", &statbuf) == 0) {
+ /* we have /subsystem/, forget all the old stuff */
+ scan_dir(udev_enumerate, "subsystem", "devices", NULL);
+ } else {
+ scan_dir(udev_enumerate, "bus", "devices", NULL);
+ scan_dir(udev_enumerate, "class", NULL, NULL);
+ }
+ return 0;
+}
+
+/**
+ * udev_enumerate_scan_devices:
+ * @udev_enumerate: udev enumeration context
+ *
+ * Scan /sys for all devices which match the given filters. No matches
+ * will return all currently available devices.
+ *
+ * Returns: 0 on success, otherwise a negative error value.
+ **/
+_public_ int udev_enumerate_scan_devices(struct udev_enumerate *udev_enumerate)
+{
+ if (udev_enumerate == NULL)
+ return -EINVAL;
+
+ /* efficiently lookup tags only, we maintain a reverse-index */
+ if (udev_list_get_entry(&udev_enumerate->tags_match_list) != NULL)
+ return scan_devices_tags(udev_enumerate);
+
+ /* walk the subtree of one parent device only */
+ if (udev_enumerate->parent_match != NULL)
+ return scan_devices_children(udev_enumerate);
+
+ /* scan devices of all subsystems */
+ return scan_devices_all(udev_enumerate);
+}
+
+/**
+ * udev_enumerate_scan_subsystems:
+ * @udev_enumerate: udev enumeration context
+ *
+ * Scan /sys for all kernel subsystems, including buses, classes, drivers.
+ *
+ * Returns: 0 on success, otherwise a negative error value.
+ **/
+_public_ int udev_enumerate_scan_subsystems(struct udev_enumerate *udev_enumerate)
+{
+ struct stat statbuf;
+ const char *subsysdir;
+
+ if (udev_enumerate == NULL)
+ return -EINVAL;
+
+ /* all kernel modules */
+ if (match_subsystem(udev_enumerate, "module"))
+ scan_dir_and_add_devices(udev_enumerate, "module", NULL, NULL);
+
+ if (stat("/sys/subsystem", &statbuf) == 0)
+ subsysdir = "subsystem";
+ else
+ subsysdir = "bus";
+
+ /* all subsystems (only buses support coldplug) */
+ if (match_subsystem(udev_enumerate, "subsystem"))
+ scan_dir_and_add_devices(udev_enumerate, subsysdir, NULL, NULL);
+
+ /* all subsystem drivers */
+ if (match_subsystem(udev_enumerate, "drivers"))
+ scan_dir(udev_enumerate, subsysdir, "drivers", "drivers");
+ return 0;
+}
diff --git a/src/libudev/libudev-hwdb-def.h b/src/libudev/libudev-hwdb-def.h
new file mode 100644
index 0000000000..b76a13f3e4
--- /dev/null
+++ b/src/libudev/libudev-hwdb-def.h
@@ -0,0 +1,74 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Kay Sievers <kay@vrfy.org>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#ifndef _LIBUDEV_HWDB_DEF_H_
+#define _LIBUDEV_HWDB_DEF_H_
+
+#include "sparse-endian.h"
+
+#define HWDB_SIG { 'K', 'S', 'L', 'P', 'H', 'H', 'R', 'H' }
+
+/* on-disk trie objects */
+struct trie_header_f {
+ uint8_t signature[8];
+
+ /* version of tool which created the file */
+ le64_t tool_version;
+ le64_t file_size;
+
+ /* size of structures to allow them to grow */
+ le64_t header_size;
+ le64_t node_size;
+ le64_t child_entry_size;
+ le64_t value_entry_size;
+
+ /* offset of the root trie node */
+ le64_t nodes_root_off;
+
+ /* size of the nodes and string section */
+ le64_t nodes_len;
+ le64_t strings_len;
+} _packed_;
+
+struct trie_node_f {
+ /* prefix of lookup string, shared by all children */
+ le64_t prefix_off;
+ /* size of children entry array appended to the node */
+ uint8_t children_count;
+ uint8_t padding[7];
+ /* size of value entry array appended to the node */
+ le64_t values_count;
+} _packed_;
+
+/* array of child entries, follows directly the node record */
+struct trie_child_entry_f {
+ /* index of the child node */
+ uint8_t c;
+ uint8_t padding[7];
+ /* offset of the child node */
+ le64_t child_off;
+} _packed_;
+
+/* array of value entries, follows directly the node record/child array */
+struct trie_value_entry_f {
+ le64_t key_off;
+ le64_t value_off;
+} _packed_;
+
+#endif
diff --git a/src/libudev/libudev-hwdb.c b/src/libudev/libudev-hwdb.c
new file mode 100644
index 0000000000..42ab6d9a6b
--- /dev/null
+++ b/src/libudev/libudev-hwdb.c
@@ -0,0 +1,392 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Kay Sievers <kay@vrfy.org>
+ Copyright 2008 Alan Jenkins <alan.christopher.jenkins@googlemail.com>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include <errno.h>
+#include <string.h>
+#include <inttypes.h>
+#include <ctype.h>
+#include <stdlib.h>
+#include <fnmatch.h>
+#include <getopt.h>
+#include <sys/mman.h>
+
+#include "libudev-private.h"
+#include "libudev-hwdb-def.h"
+
+/**
+ * SECTION:libudev-hwdb
+ * @short_description: retrieve properties from the hardware database
+ *
+ * Libudev hardware database interface.
+ */
+
+/**
+ * udev_hwdb:
+ *
+ * Opaque object representing the hardware database.
+ */
+struct udev_hwdb {
+ struct udev *udev;
+ int refcount;
+
+ FILE *f;
+ struct stat st;
+ union {
+ struct trie_header_f *head;
+ const char *map;
+ };
+
+ struct udev_list properties_list;
+};
+
+struct linebuf {
+ char bytes[LINE_MAX];
+ size_t size;
+ size_t len;
+};
+
+static void linebuf_init(struct linebuf *buf) {
+ buf->size = 0;
+ buf->len = 0;
+}
+
+static const char *linebuf_get(struct linebuf *buf) {
+ if (buf->len + 1 >= sizeof(buf->bytes))
+ return NULL;
+ buf->bytes[buf->len] = '\0';
+ return buf->bytes;
+}
+
+static bool linebuf_add(struct linebuf *buf, const char *s, size_t len) {
+ if (buf->len + len >= sizeof(buf->bytes))
+ return false;
+ memcpy(buf->bytes + buf->len, s, len);
+ buf->len += len;
+ return true;
+}
+
+static bool linebuf_add_char(struct linebuf *buf, char c)
+{
+ if (buf->len + 1 >= sizeof(buf->bytes))
+ return false;
+ buf->bytes[buf->len++] = c;
+ return true;
+}
+
+static void linebuf_rem(struct linebuf *buf, size_t count) {
+ assert(buf->len >= count);
+ buf->len -= count;
+}
+
+static void linebuf_rem_char(struct linebuf *buf) {
+ linebuf_rem(buf, 1);
+}
+
+static const struct trie_child_entry_f *trie_node_children(struct udev_hwdb *hwdb, const struct trie_node_f *node) {
+ return (const struct trie_child_entry_f *)((const char *)node + le64toh(hwdb->head->node_size));
+}
+
+static const struct trie_value_entry_f *trie_node_values(struct udev_hwdb *hwdb, const struct trie_node_f *node) {
+ const char *base = (const char *)node;
+
+ base += le64toh(hwdb->head->node_size);
+ base += node->children_count * le64toh(hwdb->head->child_entry_size);
+ return (const struct trie_value_entry_f *)base;
+}
+
+static const struct trie_node_f *trie_node_from_off(struct udev_hwdb *hwdb, le64_t off) {
+ return (const struct trie_node_f *)(hwdb->map + le64toh(off));
+}
+
+static const char *trie_string(struct udev_hwdb *hwdb, le64_t off) {
+ return hwdb->map + le64toh(off);
+}
+
+static int trie_children_cmp_f(const void *v1, const void *v2) {
+ const struct trie_child_entry_f *n1 = v1;
+ const struct trie_child_entry_f *n2 = v2;
+
+ return n1->c - n2->c;
+}
+
+static const struct trie_node_f *node_lookup_f(struct udev_hwdb *hwdb, const struct trie_node_f *node, uint8_t c) {
+ struct trie_child_entry_f *child;
+ struct trie_child_entry_f search;
+
+ search.c = c;
+ child = bsearch(&search, trie_node_children(hwdb, node), node->children_count,
+ le64toh(hwdb->head->child_entry_size), trie_children_cmp_f);
+ if (child)
+ return trie_node_from_off(hwdb, child->child_off);
+ return NULL;
+}
+
+static int hwdb_add_property(struct udev_hwdb *hwdb, const char *key, const char *value) {
+ /* TODO: add sub-matches (+) against DMI data */
+ if (key[0] != ' ')
+ return 0;
+ if (udev_list_entry_add(&hwdb->properties_list, key+1, value) == NULL)
+ return -ENOMEM;
+ return 0;
+}
+
+static int trie_fnmatch_f(struct udev_hwdb *hwdb, const struct trie_node_f *node, size_t p,
+ struct linebuf *buf, const char *search) {
+ size_t len;
+ size_t i;
+ const char *prefix;
+ int err;
+
+ prefix = trie_string(hwdb, node->prefix_off);
+ len = strlen(prefix + p);
+ linebuf_add(buf, prefix + p, len);
+
+ for (i = 0; i < node->children_count; i++) {
+ const struct trie_child_entry_f *child = &trie_node_children(hwdb, node)[i];
+
+ linebuf_add_char(buf, child->c);
+ err = trie_fnmatch_f(hwdb, trie_node_from_off(hwdb, child->child_off), 0, buf, search);
+ if (err < 0)
+ return err;
+ linebuf_rem_char(buf);
+ }
+
+ if (le64toh(node->values_count) && fnmatch(linebuf_get(buf), search, 0) == 0)
+ for (i = 0; i < le64toh(node->values_count); i++) {
+ err = hwdb_add_property(hwdb, trie_string(hwdb, trie_node_values(hwdb, node)[i].key_off),
+ trie_string(hwdb, trie_node_values(hwdb, node)[i].value_off));
+ if (err < 0)
+ return err;
+ }
+
+ linebuf_rem(buf, len);
+ return 0;
+}
+
+static int trie_search_f(struct udev_hwdb *hwdb, const char *search) {
+ struct linebuf buf;
+ const struct trie_node_f *node;
+ size_t i = 0;
+ int err;
+
+ linebuf_init(&buf);
+
+ node = trie_node_from_off(hwdb, hwdb->head->nodes_root_off);
+ while (node) {
+ const struct trie_node_f *child;
+ size_t p = 0;
+
+ if (node->prefix_off) {
+ uint8_t c;
+
+ for (; (c = trie_string(hwdb, node->prefix_off)[p]); p++) {
+ if (c == '*' || c == '?' || c == '[')
+ return trie_fnmatch_f(hwdb, node, p, &buf, search + i + p);
+ if (c != search[i + p])
+ return 0;
+ }
+ i += p;
+ }
+
+ child = node_lookup_f(hwdb, node, '*');
+ if (child) {
+ linebuf_add_char(&buf, '*');
+ err = trie_fnmatch_f(hwdb, child, 0, &buf, search + i);
+ if (err < 0)
+ return err;
+ linebuf_rem_char(&buf);
+ }
+
+ child = node_lookup_f(hwdb, node, '?');
+ if (child) {
+ linebuf_add_char(&buf, '?');
+ err = trie_fnmatch_f(hwdb, child, 0, &buf, search + i);
+ if (err < 0)
+ return err;
+ linebuf_rem_char(&buf);
+ }
+
+ child = node_lookup_f(hwdb, node, '[');
+ if (child) {
+ linebuf_add_char(&buf, '[');
+ err = trie_fnmatch_f(hwdb, child, 0, &buf, search + i);
+ if (err < 0)
+ return err;
+ linebuf_rem_char(&buf);
+ }
+
+ if (search[i] == '\0') {
+ size_t n;
+
+ for (n = 0; n < le64toh(node->values_count); n++) {
+ err = hwdb_add_property(hwdb, trie_string(hwdb, trie_node_values(hwdb, node)[n].key_off),
+ trie_string(hwdb, trie_node_values(hwdb, node)[n].value_off));
+ if (err < 0)
+ return err;
+ }
+ return 0;
+ }
+
+ child = node_lookup_f(hwdb, node, search[i]);
+ node = child;
+ i++;
+ }
+ return 0;
+}
+
+/**
+ * udev_hwdb_new:
+ * @udev: udev library context
+ *
+ * Create a hardware database context to query properties for devices.
+ *
+ * Returns: a hwdb context.
+ **/
+_public_ struct udev_hwdb *udev_hwdb_new(struct udev *udev) {
+ struct udev_hwdb *hwdb;
+ const char sig[] = HWDB_SIG;
+
+ hwdb = new0(struct udev_hwdb, 1);
+ if (!hwdb)
+ return NULL;
+
+ hwdb->refcount = 1;
+ udev_list_init(udev, &hwdb->properties_list, true);
+
+ hwdb->f = fopen("/etc/udev/hwdb.bin", "re");
+ if (!hwdb->f) {
+ log_debug("error reading /etc/udev/hwdb.bin: %m");
+ udev_hwdb_unref(hwdb);
+ return NULL;
+ }
+
+ if (fstat(fileno(hwdb->f), &hwdb->st) < 0 ||
+ (size_t)hwdb->st.st_size < offsetof(struct trie_header_f, strings_len) + 8) {
+ log_debug("error reading /etc/udev/hwdb.bin: %m");
+ udev_hwdb_unref(hwdb);
+ return NULL;
+ }
+
+ hwdb->map = mmap(0, hwdb->st.st_size, PROT_READ, MAP_SHARED, fileno(hwdb->f), 0);
+ if (hwdb->map == MAP_FAILED) {
+ log_debug("error mapping /etc/udev/hwdb.bin: %m");
+ udev_hwdb_unref(hwdb);
+ return NULL;
+ }
+
+ if (memcmp(hwdb->map, sig, sizeof(hwdb->head->signature)) != 0 ||
+ (size_t)hwdb->st.st_size != le64toh(hwdb->head->file_size)) {
+ log_debug("error recognizing the format of /etc/udev/hwdb.bin");
+ udev_hwdb_unref(hwdb);
+ return NULL;
+ }
+
+ log_debug("=== trie on-disk ===\n");
+ log_debug("tool version: %llu", (unsigned long long)le64toh(hwdb->head->tool_version));
+ log_debug("file size: %8llu bytes\n", (unsigned long long)hwdb->st.st_size);
+ log_debug("header size %8llu bytes\n", (unsigned long long)le64toh(hwdb->head->header_size));
+ log_debug("strings %8llu bytes\n", (unsigned long long)le64toh(hwdb->head->strings_len));
+ log_debug("nodes %8llu bytes\n", (unsigned long long)le64toh(hwdb->head->nodes_len));
+ return hwdb;
+}
+
+/**
+ * udev_hwdb_ref:
+ * @hwdb: context
+ *
+ * Take a reference of a hwdb context.
+ *
+ * Returns: the passed enumeration context
+ **/
+_public_ struct udev_hwdb *udev_hwdb_ref(struct udev_hwdb *hwdb) {
+ if (!hwdb)
+ return NULL;
+ hwdb->refcount++;
+ return hwdb;
+}
+
+/**
+ * udev_hwdb_unref:
+ * @hwdb: context
+ *
+ * Drop a reference of a hwdb context. If the refcount reaches zero,
+ * all resources of the hwdb context will be released.
+ *
+ * Returns: the passed hwdb context if it has still an active reference, or #NULL otherwise.
+ **/
+_public_ struct udev_hwdb *udev_hwdb_unref(struct udev_hwdb *hwdb) {
+ if (!hwdb)
+ return NULL;
+ hwdb->refcount--;
+ if (hwdb->refcount > 0)
+ return hwdb;
+ if (hwdb->map)
+ munmap((void *)hwdb->map, hwdb->st.st_size);
+ if (hwdb->f)
+ fclose(hwdb->f);
+ udev_list_cleanup(&hwdb->properties_list);
+ free(hwdb);
+ return NULL;
+}
+
+bool udev_hwdb_validate(struct udev_hwdb *hwdb) {
+ struct stat st;
+
+ if (!hwdb)
+ return false;
+ if (!hwdb->f)
+ return false;
+ if (fstat(fileno(hwdb->f), &st) < 0)
+ return true;
+ if (timespec_load(&hwdb->st.st_mtim) != timespec_load(&st.st_mtim))
+ return true;
+ return false;
+}
+
+/**
+ * udev_hwdb_get_properties_list_entry:
+ * @hwdb: context
+ * @modalias: modalias string
+ * @flags: (unused)
+ *
+ * Lookup a matching device in the hardware database. The lookup key is a
+ * modalias string, whose formats are defined for the Linux kernel modules.
+ * Examples are: pci:v00008086d00001C2D*, usb:v04F2pB221*. The first entry
+ * of a list of retrieved properties is returned.
+ *
+ * Returns: a udev_list_entry.
+ */
+_public_ struct udev_list_entry *udev_hwdb_get_properties_list_entry(struct udev_hwdb *hwdb, const char *modalias, unsigned int flags) {
+ int err;
+
+ if (!hwdb || !hwdb->f) {
+ errno = EINVAL;
+ return NULL;
+ }
+
+ udev_list_cleanup(&hwdb->properties_list);
+ err = trie_search_f(hwdb, modalias);
+ if (err < 0) {
+ errno = -err;
+ return NULL;
+ }
+ return udev_list_get_entry(&hwdb->properties_list);
+}
diff --git a/src/libudev/libudev-list.c b/src/libudev/libudev-list.c
new file mode 100644
index 0000000000..59ba69e279
--- /dev/null
+++ b/src/libudev/libudev-list.c
@@ -0,0 +1,355 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2008-2012 Kay Sievers <kay@vrfy.org>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <unistd.h>
+#include <errno.h>
+#include <string.h>
+
+#include "libudev.h"
+#include "libudev-private.h"
+
+/**
+ * SECTION:libudev-list
+ * @short_description: list operation
+ *
+ * Libudev list operations.
+ */
+
+/**
+ * udev_list_entry:
+ *
+ * Opaque object representing one entry in a list. An entry contains
+ * contains a name, and optionally a value.
+ */
+struct udev_list_entry {
+ struct udev_list_node node;
+ struct udev_list *list;
+ char *name;
+ char *value;
+ int num;
+};
+
+/* the list's head points to itself if empty */
+void udev_list_node_init(struct udev_list_node *list)
+{
+ list->next = list;
+ list->prev = list;
+}
+
+int udev_list_node_is_empty(struct udev_list_node *list)
+{
+ return list->next == list;
+}
+
+static void udev_list_node_insert_between(struct udev_list_node *new,
+ struct udev_list_node *prev,
+ struct udev_list_node *next)
+{
+ next->prev = new;
+ new->next = next;
+ new->prev = prev;
+ prev->next = new;
+}
+
+void udev_list_node_append(struct udev_list_node *new, struct udev_list_node *list)
+{
+ udev_list_node_insert_between(new, list->prev, list);
+}
+
+void udev_list_node_remove(struct udev_list_node *entry)
+{
+ struct udev_list_node *prev = entry->prev;
+ struct udev_list_node *next = entry->next;
+
+ next->prev = prev;
+ prev->next = next;
+
+ entry->prev = NULL;
+ entry->next = NULL;
+}
+
+/* return list entry which embeds this node */
+static inline struct udev_list_entry *list_node_to_entry(struct udev_list_node *node)
+{
+ return container_of(node, struct udev_list_entry, node);
+}
+
+void udev_list_init(struct udev *udev, struct udev_list *list, bool unique)
+{
+ memset(list, 0x00, sizeof(struct udev_list));
+ list->udev = udev;
+ list->unique = unique;
+ udev_list_node_init(&list->node);
+}
+
+/* insert entry into a list as the last element */
+void udev_list_entry_append(struct udev_list_entry *new, struct udev_list *list)
+{
+ /* inserting before the list head make the node the last node in the list */
+ udev_list_node_insert_between(&new->node, list->node.prev, &list->node);
+ new->list = list;
+}
+
+/* insert entry into a list, before a given existing entry */
+void udev_list_entry_insert_before(struct udev_list_entry *new, struct udev_list_entry *entry)
+{
+ udev_list_node_insert_between(&new->node, entry->node.prev, &entry->node);
+ new->list = entry->list;
+}
+
+/* binary search in sorted array */
+static int list_search(struct udev_list *list, const char *name)
+{
+ unsigned int first, last;
+
+ first = 0;
+ last = list->entries_cur;
+ while (first < last) {
+ unsigned int i;
+ int cmp;
+
+ i = (first + last)/2;
+ cmp = strcmp(name, list->entries[i]->name);
+ if (cmp < 0)
+ last = i;
+ else if (cmp > 0)
+ first = i+1;
+ else
+ return i;
+ }
+
+ /* not found, return negative insertion-index+1 */
+ return -(first+1);
+}
+
+struct udev_list_entry *udev_list_entry_add(struct udev_list *list, const char *name, const char *value)
+{
+ struct udev_list_entry *entry;
+ int i = 0;
+
+ if (list->unique) {
+ /* lookup existing name or insertion-index */
+ i = list_search(list, name);
+ if (i >= 0) {
+ entry = list->entries[i];
+
+ free(entry->value);
+ if (value == NULL) {
+ entry->value = NULL;
+ return entry;
+ }
+ entry->value = strdup(value);
+ if (entry->value == NULL)
+ return NULL;
+ return entry;
+ }
+ }
+
+ /* add new name */
+ entry = calloc(1, sizeof(struct udev_list_entry));
+ if (entry == NULL)
+ return NULL;
+ entry->name = strdup(name);
+ if (entry->name == NULL) {
+ free(entry);
+ return NULL;
+ }
+ if (value != NULL) {
+ entry->value = strdup(value);
+ if (entry->value == NULL) {
+ free(entry->name);
+ free(entry);
+ return NULL;
+ }
+ }
+
+ if (list->unique) {
+ /* allocate or enlarge sorted array if needed */
+ if (list->entries_cur >= list->entries_max) {
+ struct udev_list_entry **entries;
+ unsigned int add;
+
+ add = list->entries_max;
+ if (add < 1)
+ add = 64;
+ entries = realloc(list->entries, (list->entries_max + add) * sizeof(struct udev_list_entry *));
+ if (entries == NULL) {
+ free(entry->name);
+ free(entry->value);
+ free(entry);
+ return NULL;
+ }
+ list->entries = entries;
+ list->entries_max += add;
+ }
+
+ /* the negative i returned the insertion index */
+ i = (-i)-1;
+
+ /* insert into sorted list */
+ if ((unsigned int)i < list->entries_cur)
+ udev_list_entry_insert_before(entry, list->entries[i]);
+ else
+ udev_list_entry_append(entry, list);
+
+ /* insert into sorted array */
+ memmove(&list->entries[i+1], &list->entries[i],
+ (list->entries_cur - i) * sizeof(struct udev_list_entry *));
+ list->entries[i] = entry;
+ list->entries_cur++;
+ } else {
+ udev_list_entry_append(entry, list);
+ }
+
+ return entry;
+}
+
+void udev_list_entry_delete(struct udev_list_entry *entry)
+{
+ if (entry->list->entries != NULL) {
+ int i;
+ struct udev_list *list = entry->list;
+
+ /* remove entry from sorted array */
+ i = list_search(list, entry->name);
+ if (i >= 0) {
+ memmove(&list->entries[i], &list->entries[i+1],
+ ((list->entries_cur-1) - i) * sizeof(struct udev_list_entry *));
+ list->entries_cur--;
+ }
+ }
+
+ udev_list_node_remove(&entry->node);
+ free(entry->name);
+ free(entry->value);
+ free(entry);
+}
+
+void udev_list_cleanup(struct udev_list *list)
+{
+ struct udev_list_entry *entry_loop;
+ struct udev_list_entry *entry_tmp;
+
+ free(list->entries);
+ list->entries = NULL;
+ list->entries_cur = 0;
+ list->entries_max = 0;
+ udev_list_entry_foreach_safe(entry_loop, entry_tmp, udev_list_get_entry(list))
+ udev_list_entry_delete(entry_loop);
+}
+
+struct udev_list_entry *udev_list_get_entry(struct udev_list *list)
+{
+ if (udev_list_node_is_empty(&list->node))
+ return NULL;
+ return list_node_to_entry(list->node.next);
+}
+
+/**
+ * udev_list_entry_get_next:
+ * @list_entry: current entry
+ *
+ * Get the next entry from the list.
+ *
+ * Returns: udev_list_entry, #NULL if no more entries are available.
+ */
+_public_ struct udev_list_entry *udev_list_entry_get_next(struct udev_list_entry *list_entry)
+{
+ struct udev_list_node *next;
+
+ if (list_entry == NULL)
+ return NULL;
+ next = list_entry->node.next;
+ /* empty list or no more entries */
+ if (next == &list_entry->list->node)
+ return NULL;
+ return list_node_to_entry(next);
+}
+
+/**
+ * udev_list_entry_get_by_name:
+ * @list_entry: current entry
+ * @name: name string to match
+ *
+ * Lookup an entry in the list with a certain name.
+ *
+ * Returns: udev_list_entry, #NULL if no matching entry is found.
+ */
+_public_ struct udev_list_entry *udev_list_entry_get_by_name(struct udev_list_entry *list_entry, const char *name)
+{
+ int i;
+
+ if (list_entry == NULL)
+ return NULL;
+
+ if (!list_entry->list->unique)
+ return NULL;
+
+ i = list_search(list_entry->list, name);
+ if (i < 0)
+ return NULL;
+ return list_entry->list->entries[i];
+}
+
+/**
+ * udev_list_entry_get_name:
+ * @list_entry: current entry
+ *
+ * Get the name of a list entry.
+ *
+ * Returns: the name string of this entry.
+ */
+_public_ const char *udev_list_entry_get_name(struct udev_list_entry *list_entry)
+{
+ if (list_entry == NULL)
+ return NULL;
+ return list_entry->name;
+}
+
+/**
+ * udev_list_entry_get_value:
+ * @list_entry: current entry
+ *
+ * Get the value of list entry.
+ *
+ * Returns: the value string of this entry.
+ */
+_public_ const char *udev_list_entry_get_value(struct udev_list_entry *list_entry)
+{
+ if (list_entry == NULL)
+ return NULL;
+ return list_entry->value;
+}
+
+int udev_list_entry_get_num(struct udev_list_entry *list_entry)
+{
+ if (list_entry == NULL)
+ return -EINVAL;
+ return list_entry->num;
+}
+
+void udev_list_entry_set_num(struct udev_list_entry *list_entry, int num)
+{
+ if (list_entry == NULL)
+ return;
+ list_entry->num = num;
+}
diff --git a/src/libudev/libudev-monitor.c b/src/libudev/libudev-monitor.c
new file mode 100644
index 0000000000..0212792552
--- /dev/null
+++ b/src/libudev/libudev-monitor.c
@@ -0,0 +1,782 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2008-2012 Kay Sievers <kay@vrfy.org>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <unistd.h>
+#include <errno.h>
+#include <string.h>
+#include <dirent.h>
+#include <sys/poll.h>
+#include <sys/stat.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <arpa/inet.h>
+#include <linux/netlink.h>
+#include <linux/filter.h>
+
+#include "libudev.h"
+#include "libudev-private.h"
+#include "socket-util.h"
+
+/**
+ * SECTION:libudev-monitor
+ * @short_description: device event source
+ *
+ * Connects to a device event source.
+ */
+
+/**
+ * udev_monitor:
+ *
+ * Opaque object handling an event source.
+ */
+struct udev_monitor {
+ struct udev *udev;
+ int refcount;
+ int sock;
+ union sockaddr_union snl;
+ union sockaddr_union snl_trusted_sender;
+ union sockaddr_union snl_destination;
+ socklen_t addrlen;
+ struct udev_list filter_subsystem_list;
+ struct udev_list filter_tag_list;
+ bool bound;
+};
+
+enum udev_monitor_netlink_group {
+ UDEV_MONITOR_NONE,
+ UDEV_MONITOR_KERNEL,
+ UDEV_MONITOR_UDEV,
+};
+
+#define UDEV_MONITOR_MAGIC 0xfeedcafe
+struct udev_monitor_netlink_header {
+ /* "libudev" prefix to distinguish libudev and kernel messages */
+ char prefix[8];
+ /*
+ * magic to protect against daemon <-> library message format mismatch
+ * used in the kernel from socket filter rules; needs to be stored in network order
+ */
+ unsigned int magic;
+ /* total length of header structure known to the sender */
+ unsigned int header_size;
+ /* properties string buffer */
+ unsigned int properties_off;
+ unsigned int properties_len;
+ /*
+ * hashes of primary device properties strings, to let libudev subscribers
+ * use in-kernel socket filters; values need to be stored in network order
+ */
+ unsigned int filter_subsystem_hash;
+ unsigned int filter_devtype_hash;
+ unsigned int filter_tag_bloom_hi;
+ unsigned int filter_tag_bloom_lo;
+};
+
+static struct udev_monitor *udev_monitor_new(struct udev *udev)
+{
+ struct udev_monitor *udev_monitor;
+
+ udev_monitor = calloc(1, sizeof(struct udev_monitor));
+ if (udev_monitor == NULL)
+ return NULL;
+ udev_monitor->refcount = 1;
+ udev_monitor->udev = udev;
+ udev_list_init(udev, &udev_monitor->filter_subsystem_list, false);
+ udev_list_init(udev, &udev_monitor->filter_tag_list, true);
+ return udev_monitor;
+}
+
+struct udev_monitor *udev_monitor_new_from_netlink_fd(struct udev *udev, const char *name, int fd)
+{
+ struct udev_monitor *udev_monitor;
+ unsigned int group;
+
+ if (udev == NULL)
+ return NULL;
+
+ if (name == NULL)
+ group = UDEV_MONITOR_NONE;
+ else if (streq(name, "udev"))
+ group = UDEV_MONITOR_UDEV;
+ else if (streq(name, "kernel"))
+ group = UDEV_MONITOR_KERNEL;
+ else
+ return NULL;
+
+ udev_monitor = udev_monitor_new(udev);
+ if (udev_monitor == NULL)
+ return NULL;
+
+ if (fd < 0) {
+ udev_monitor->sock = socket(PF_NETLINK, SOCK_RAW|SOCK_CLOEXEC|SOCK_NONBLOCK, NETLINK_KOBJECT_UEVENT);
+ if (udev_monitor->sock == -1) {
+ udev_err(udev, "error getting socket: %m\n");
+ free(udev_monitor);
+ return NULL;
+ }
+ } else {
+ udev_monitor->bound = true;
+ udev_monitor->sock = fd;
+ }
+
+ udev_monitor->snl.nl.nl_family = AF_NETLINK;
+ udev_monitor->snl.nl.nl_groups = group;
+
+ /* default destination for sending */
+ udev_monitor->snl_destination.nl.nl_family = AF_NETLINK;
+ udev_monitor->snl_destination.nl.nl_groups = UDEV_MONITOR_UDEV;
+
+ return udev_monitor;
+}
+
+/**
+ * udev_monitor_new_from_netlink:
+ * @udev: udev library context
+ * @name: name of event source
+ *
+ * Create new udev monitor and connect to a specified event
+ * source. Valid sources identifiers are "udev" and "kernel".
+ *
+ * Applications should usually not connect directly to the
+ * "kernel" events, because the devices might not be useable
+ * at that time, before udev has configured them, and created
+ * device nodes. Accessing devices at the same time as udev,
+ * might result in unpredictable behavior. The "udev" events
+ * are sent out after udev has finished its event processing,
+ * all rules have been processed, and needed device nodes are
+ * created.
+ *
+ * The initial refcount is 1, and needs to be decremented to
+ * release the resources of the udev monitor.
+ *
+ * Returns: a new udev monitor, or #NULL, in case of an error
+ **/
+_public_ struct udev_monitor *udev_monitor_new_from_netlink(struct udev *udev, const char *name)
+{
+ return udev_monitor_new_from_netlink_fd(udev, name, -1);
+}
+
+static inline void bpf_stmt(struct sock_filter *inss, unsigned int *i,
+ unsigned short code, unsigned int data)
+{
+ struct sock_filter *ins = &inss[*i];
+
+ ins->code = code;
+ ins->k = data;
+ (*i)++;
+}
+
+static inline void bpf_jmp(struct sock_filter *inss, unsigned int *i,
+ unsigned short code, unsigned int data,
+ unsigned short jt, unsigned short jf)
+{
+ struct sock_filter *ins = &inss[*i];
+
+ ins->code = code;
+ ins->jt = jt;
+ ins->jf = jf;
+ ins->k = data;
+ (*i)++;
+}
+
+/**
+ * udev_monitor_filter_update:
+ * @udev_monitor: monitor
+ *
+ * Update the installed socket filter. This is only needed,
+ * if the filter was removed or changed.
+ *
+ * Returns: 0 on success, otherwise a negative error value.
+ */
+_public_ int udev_monitor_filter_update(struct udev_monitor *udev_monitor)
+{
+ struct sock_filter ins[512];
+ struct sock_fprog filter;
+ unsigned int i;
+ struct udev_list_entry *list_entry;
+ int err;
+
+ if (udev_list_get_entry(&udev_monitor->filter_subsystem_list) == NULL &&
+ udev_list_get_entry(&udev_monitor->filter_tag_list) == NULL)
+ return 0;
+
+ memset(ins, 0x00, sizeof(ins));
+ i = 0;
+
+ /* load magic in A */
+ bpf_stmt(ins, &i, BPF_LD|BPF_W|BPF_ABS, offsetof(struct udev_monitor_netlink_header, magic));
+ /* jump if magic matches */
+ bpf_jmp(ins, &i, BPF_JMP|BPF_JEQ|BPF_K, UDEV_MONITOR_MAGIC, 1, 0);
+ /* wrong magic, pass packet */
+ bpf_stmt(ins, &i, BPF_RET|BPF_K, 0xffffffff);
+
+ if (udev_list_get_entry(&udev_monitor->filter_tag_list) != NULL) {
+ int tag_matches;
+
+ /* count tag matches, to calculate end of tag match block */
+ tag_matches = 0;
+ udev_list_entry_foreach(list_entry, udev_list_get_entry(&udev_monitor->filter_tag_list))
+ tag_matches++;
+
+ /* add all tags matches */
+ udev_list_entry_foreach(list_entry, udev_list_get_entry(&udev_monitor->filter_tag_list)) {
+ uint64_t tag_bloom_bits = util_string_bloom64(udev_list_entry_get_name(list_entry));
+ uint32_t tag_bloom_hi = tag_bloom_bits >> 32;
+ uint32_t tag_bloom_lo = tag_bloom_bits & 0xffffffff;
+
+ /* load device bloom bits in A */
+ bpf_stmt(ins, &i, BPF_LD|BPF_W|BPF_ABS, offsetof(struct udev_monitor_netlink_header, filter_tag_bloom_hi));
+ /* clear bits (tag bits & bloom bits) */
+ bpf_stmt(ins, &i, BPF_ALU|BPF_AND|BPF_K, tag_bloom_hi);
+ /* jump to next tag if it does not match */
+ bpf_jmp(ins, &i, BPF_JMP|BPF_JEQ|BPF_K, tag_bloom_hi, 0, 3);
+
+ /* load device bloom bits in A */
+ bpf_stmt(ins, &i, BPF_LD|BPF_W|BPF_ABS, offsetof(struct udev_monitor_netlink_header, filter_tag_bloom_lo));
+ /* clear bits (tag bits & bloom bits) */
+ bpf_stmt(ins, &i, BPF_ALU|BPF_AND|BPF_K, tag_bloom_lo);
+ /* jump behind end of tag match block if tag matches */
+ tag_matches--;
+ bpf_jmp(ins, &i, BPF_JMP|BPF_JEQ|BPF_K, tag_bloom_lo, 1 + (tag_matches * 6), 0);
+ }
+
+ /* nothing matched, drop packet */
+ bpf_stmt(ins, &i, BPF_RET|BPF_K, 0);
+ }
+
+ /* add all subsystem matches */
+ if (udev_list_get_entry(&udev_monitor->filter_subsystem_list) != NULL) {
+ udev_list_entry_foreach(list_entry, udev_list_get_entry(&udev_monitor->filter_subsystem_list)) {
+ unsigned int hash = util_string_hash32(udev_list_entry_get_name(list_entry));
+
+ /* load device subsystem value in A */
+ bpf_stmt(ins, &i, BPF_LD|BPF_W|BPF_ABS, offsetof(struct udev_monitor_netlink_header, filter_subsystem_hash));
+ if (udev_list_entry_get_value(list_entry) == NULL) {
+ /* jump if subsystem does not match */
+ bpf_jmp(ins, &i, BPF_JMP|BPF_JEQ|BPF_K, hash, 0, 1);
+ } else {
+ /* jump if subsystem does not match */
+ bpf_jmp(ins, &i, BPF_JMP|BPF_JEQ|BPF_K, hash, 0, 3);
+
+ /* load device devtype value in A */
+ bpf_stmt(ins, &i, BPF_LD|BPF_W|BPF_ABS, offsetof(struct udev_monitor_netlink_header, filter_devtype_hash));
+ /* jump if value does not match */
+ hash = util_string_hash32(udev_list_entry_get_value(list_entry));
+ bpf_jmp(ins, &i, BPF_JMP|BPF_JEQ|BPF_K, hash, 0, 1);
+ }
+
+ /* matched, pass packet */
+ bpf_stmt(ins, &i, BPF_RET|BPF_K, 0xffffffff);
+
+ if (i+1 >= ELEMENTSOF(ins))
+ return -1;
+ }
+
+ /* nothing matched, drop packet */
+ bpf_stmt(ins, &i, BPF_RET|BPF_K, 0);
+ }
+
+ /* matched, pass packet */
+ bpf_stmt(ins, &i, BPF_RET|BPF_K, 0xffffffff);
+
+ /* install filter */
+ memset(&filter, 0x00, sizeof(filter));
+ filter.len = i;
+ filter.filter = ins;
+ err = setsockopt(udev_monitor->sock, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter));
+ return err;
+}
+
+int udev_monitor_allow_unicast_sender(struct udev_monitor *udev_monitor, struct udev_monitor *sender)
+{
+ udev_monitor->snl_trusted_sender.nl.nl_pid = sender->snl.nl.nl_pid;
+ return 0;
+}
+/**
+ * udev_monitor_enable_receiving:
+ * @udev_monitor: the monitor which should receive events
+ *
+ * Binds the @udev_monitor socket to the event source.
+ *
+ * Returns: 0 on success, otherwise a negative error value.
+ */
+_public_ int udev_monitor_enable_receiving(struct udev_monitor *udev_monitor)
+{
+ int err = 0;
+ const int on = 1;
+
+ if (udev_monitor->snl.nl.nl_family == 0)
+ return -EINVAL;
+
+ udev_monitor_filter_update(udev_monitor);
+
+ if (!udev_monitor->bound) {
+ err = bind(udev_monitor->sock,
+ &udev_monitor->snl.sa, sizeof(struct sockaddr_nl));
+ if (err == 0)
+ udev_monitor->bound = true;
+ }
+
+ if (err >= 0) {
+ union sockaddr_union snl;
+ socklen_t addrlen;
+
+ /*
+ * get the address the kernel has assigned us
+ * it is usually, but not necessarily the pid
+ */
+ addrlen = sizeof(struct sockaddr_nl);
+ err = getsockname(udev_monitor->sock, &snl.sa, &addrlen);
+ if (err == 0)
+ udev_monitor->snl.nl.nl_pid = snl.nl.nl_pid;
+ } else {
+ udev_err(udev_monitor->udev, "bind failed: %m\n");
+ return err;
+ }
+
+ /* enable receiving of sender credentials */
+ setsockopt(udev_monitor->sock, SOL_SOCKET, SO_PASSCRED, &on, sizeof(on));
+ return 0;
+}
+
+/**
+ * udev_monitor_set_receive_buffer_size:
+ * @udev_monitor: the monitor which should receive events
+ * @size: the size in bytes
+ *
+ * Set the size of the kernel socket buffer. This call needs the
+ * appropriate privileges to succeed.
+ *
+ * Returns: 0 on success, otherwise -1 on error.
+ */
+_public_ int udev_monitor_set_receive_buffer_size(struct udev_monitor *udev_monitor, int size)
+{
+ if (udev_monitor == NULL)
+ return -1;
+ return setsockopt(udev_monitor->sock, SOL_SOCKET, SO_RCVBUFFORCE, &size, sizeof(size));
+}
+
+int udev_monitor_disconnect(struct udev_monitor *udev_monitor)
+{
+ int err;
+
+ err = close(udev_monitor->sock);
+ udev_monitor->sock = -1;
+ return err;
+}
+
+/**
+ * udev_monitor_ref:
+ * @udev_monitor: udev monitor
+ *
+ * Take a reference of a udev monitor.
+ *
+ * Returns: the passed udev monitor
+ **/
+_public_ struct udev_monitor *udev_monitor_ref(struct udev_monitor *udev_monitor)
+{
+ if (udev_monitor == NULL)
+ return NULL;
+ udev_monitor->refcount++;
+ return udev_monitor;
+}
+
+/**
+ * udev_monitor_unref:
+ * @udev_monitor: udev monitor
+ *
+ * Drop a reference of a udev monitor. If the refcount reaches zero,
+ * the bound socket will be closed, and the resources of the monitor
+ * will be released.
+ *
+ * Returns: the passed udev monitor if it has still an active reference, or #NULL otherwise.
+ **/
+_public_ struct udev_monitor *udev_monitor_unref(struct udev_monitor *udev_monitor)
+{
+ if (udev_monitor == NULL)
+ return NULL;
+ udev_monitor->refcount--;
+ if (udev_monitor->refcount > 0)
+ return udev_monitor;
+ if (udev_monitor->sock >= 0)
+ close(udev_monitor->sock);
+ udev_list_cleanup(&udev_monitor->filter_subsystem_list);
+ udev_list_cleanup(&udev_monitor->filter_tag_list);
+ free(udev_monitor);
+ return NULL;
+}
+
+/**
+ * udev_monitor_get_udev:
+ * @udev_monitor: udev monitor
+ *
+ * Retrieve the udev library context the monitor was created with.
+ *
+ * Returns: the udev library context
+ **/
+_public_ struct udev *udev_monitor_get_udev(struct udev_monitor *udev_monitor)
+{
+ if (udev_monitor == NULL)
+ return NULL;
+ return udev_monitor->udev;
+}
+
+/**
+ * udev_monitor_get_fd:
+ * @udev_monitor: udev monitor
+ *
+ * Retrieve the socket file descriptor associated with the monitor.
+ *
+ * Returns: the socket file descriptor
+ **/
+_public_ int udev_monitor_get_fd(struct udev_monitor *udev_monitor)
+{
+ if (udev_monitor == NULL)
+ return -1;
+ return udev_monitor->sock;
+}
+
+static int passes_filter(struct udev_monitor *udev_monitor, struct udev_device *udev_device)
+{
+ struct udev_list_entry *list_entry;
+
+ if (udev_list_get_entry(&udev_monitor->filter_subsystem_list) == NULL)
+ goto tag;
+ udev_list_entry_foreach(list_entry, udev_list_get_entry(&udev_monitor->filter_subsystem_list)) {
+ const char *subsys = udev_list_entry_get_name(list_entry);
+ const char *dsubsys = udev_device_get_subsystem(udev_device);
+ const char *devtype;
+ const char *ddevtype;
+
+ if (!streq(dsubsys, subsys))
+ continue;
+
+ devtype = udev_list_entry_get_value(list_entry);
+ if (devtype == NULL)
+ goto tag;
+ ddevtype = udev_device_get_devtype(udev_device);
+ if (ddevtype == NULL)
+ continue;
+ if (streq(ddevtype, devtype))
+ goto tag;
+ }
+ return 0;
+
+tag:
+ if (udev_list_get_entry(&udev_monitor->filter_tag_list) == NULL)
+ return 1;
+ udev_list_entry_foreach(list_entry, udev_list_get_entry(&udev_monitor->filter_tag_list)) {
+ const char *tag = udev_list_entry_get_name(list_entry);
+
+ if (udev_device_has_tag(udev_device, tag))
+ return 1;
+ }
+ return 0;
+}
+
+/**
+ * udev_monitor_receive_device:
+ * @udev_monitor: udev monitor
+ *
+ * Receive data from the udev monitor socket, allocate a new udev
+ * device, fill in the received data, and return the device.
+ *
+ * Only socket connections with uid=0 are accepted.
+ *
+ * The monitor socket is by default set to NONBLOCK. A variant of poll() on
+ * the file descriptor returned by udev_monitor_get_fd() should to be used to
+ * wake up when new devices arrive, or alternatively the file descriptor
+ * switched into blocking mode.
+ *
+ * The initial refcount is 1, and needs to be decremented to
+ * release the resources of the udev device.
+ *
+ * Returns: a new udev device, or #NULL, in case of an error
+ **/
+_public_ struct udev_device *udev_monitor_receive_device(struct udev_monitor *udev_monitor)
+{
+ struct udev_device *udev_device;
+ struct msghdr smsg;
+ struct iovec iov;
+ char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
+ struct cmsghdr *cmsg;
+ union sockaddr_union snl;
+ struct ucred *cred;
+ char buf[8192];
+ ssize_t buflen;
+ ssize_t bufpos;
+ struct udev_monitor_netlink_header *nlh;
+
+retry:
+ if (udev_monitor == NULL)
+ return NULL;
+ iov.iov_base = &buf;
+ iov.iov_len = sizeof(buf);
+ memset (&smsg, 0x00, sizeof(struct msghdr));
+ smsg.msg_iov = &iov;
+ smsg.msg_iovlen = 1;
+ smsg.msg_control = cred_msg;
+ smsg.msg_controllen = sizeof(cred_msg);
+
+ if (udev_monitor->snl.nl.nl_family != 0) {
+ smsg.msg_name = &snl;
+ smsg.msg_namelen = sizeof(snl);
+ }
+
+ buflen = recvmsg(udev_monitor->sock, &smsg, 0);
+ if (buflen < 0) {
+ if (errno != EINTR)
+ udev_dbg(udev_monitor->udev, "unable to receive message\n");
+ return NULL;
+ }
+
+ if (buflen < 32 || (size_t)buflen >= sizeof(buf)) {
+ udev_dbg(udev_monitor->udev, "invalid message length\n");
+ return NULL;
+ }
+
+ if (udev_monitor->snl.nl.nl_family != 0) {
+ if (snl.nl.nl_groups == 0) {
+ /* unicast message, check if we trust the sender */
+ if (udev_monitor->snl_trusted_sender.nl.nl_pid == 0 ||
+ snl.nl.nl_pid != udev_monitor->snl_trusted_sender.nl.nl_pid) {
+ udev_dbg(udev_monitor->udev, "unicast netlink message ignored\n");
+ return NULL;
+ }
+ } else if (snl.nl.nl_groups == UDEV_MONITOR_KERNEL) {
+ if (snl.nl.nl_pid > 0) {
+ udev_dbg(udev_monitor->udev, "multicast kernel netlink message from pid %d ignored\n",
+ snl.nl.nl_pid);
+ return NULL;
+ }
+ }
+ }
+
+ cmsg = CMSG_FIRSTHDR(&smsg);
+ if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
+ udev_dbg(udev_monitor->udev, "no sender credentials received, message ignored\n");
+ return NULL;
+ }
+
+ cred = (struct ucred *)CMSG_DATA(cmsg);
+ if (cred->uid != 0) {
+ udev_dbg(udev_monitor->udev, "sender uid=%d, message ignored\n", cred->uid);
+ return NULL;
+ }
+
+ if (memcmp(buf, "libudev", 8) == 0) {
+ /* udev message needs proper version magic */
+ nlh = (struct udev_monitor_netlink_header *) buf;
+ if (nlh->magic != htonl(UDEV_MONITOR_MAGIC)) {
+ udev_err(udev_monitor->udev, "unrecognized message signature (%x != %x)\n",
+ nlh->magic, htonl(UDEV_MONITOR_MAGIC));
+ return NULL;
+ }
+ if (nlh->properties_off+32 > (size_t)buflen)
+ return NULL;
+ bufpos = nlh->properties_off;
+ } else {
+ /* kernel message with header */
+ bufpos = strlen(buf) + 1;
+ if ((size_t)bufpos < sizeof("a@/d") || bufpos >= buflen) {
+ udev_dbg(udev_monitor->udev, "invalid message length\n");
+ return NULL;
+ }
+
+ /* check message header */
+ if (strstr(buf, "@/") == NULL) {
+ udev_dbg(udev_monitor->udev, "unrecognized message header\n");
+ return NULL;
+ }
+ }
+
+ udev_device = udev_device_new(udev_monitor->udev);
+ if (udev_device == NULL)
+ return NULL;
+ udev_device_set_info_loaded(udev_device);
+
+ while (bufpos < buflen) {
+ char *key;
+ size_t keylen;
+
+ key = &buf[bufpos];
+ keylen = strlen(key);
+ if (keylen == 0)
+ break;
+ bufpos += keylen + 1;
+ udev_device_add_property_from_string_parse(udev_device, key);
+ }
+
+ if (udev_device_add_property_from_string_parse_finish(udev_device) < 0) {
+ udev_dbg(udev_monitor->udev, "missing values, invalid device\n");
+ udev_device_unref(udev_device);
+ return NULL;
+ }
+
+ /* skip device, if it does not pass the current filter */
+ if (!passes_filter(udev_monitor, udev_device)) {
+ struct pollfd pfd[1];
+ int rc;
+
+ udev_device_unref(udev_device);
+
+ /* if something is queued, get next device */
+ pfd[0].fd = udev_monitor->sock;
+ pfd[0].events = POLLIN;
+ rc = poll(pfd, 1, 0);
+ if (rc > 0)
+ goto retry;
+ return NULL;
+ }
+
+ return udev_device;
+}
+
+int udev_monitor_send_device(struct udev_monitor *udev_monitor,
+ struct udev_monitor *destination, struct udev_device *udev_device)
+{
+ const char *buf;
+ ssize_t blen;
+ ssize_t count;
+ struct msghdr smsg;
+ struct iovec iov[2];
+ const char *val;
+ struct udev_monitor_netlink_header nlh;
+ struct udev_list_entry *list_entry;
+ uint64_t tag_bloom_bits;
+
+ if (udev_monitor->snl.nl.nl_family == 0)
+ return -EINVAL;
+
+ blen = udev_device_get_properties_monitor_buf(udev_device, &buf);
+ if (blen < 32)
+ return -EINVAL;
+
+ /* add versioned header */
+ memset(&nlh, 0x00, sizeof(struct udev_monitor_netlink_header));
+ memcpy(nlh.prefix, "libudev", 8);
+ nlh.magic = htonl(UDEV_MONITOR_MAGIC);
+ nlh.header_size = sizeof(struct udev_monitor_netlink_header);
+ val = udev_device_get_subsystem(udev_device);
+ nlh.filter_subsystem_hash = htonl(util_string_hash32(val));
+ val = udev_device_get_devtype(udev_device);
+ if (val != NULL)
+ nlh.filter_devtype_hash = htonl(util_string_hash32(val));
+ iov[0].iov_base = &nlh;
+ iov[0].iov_len = sizeof(struct udev_monitor_netlink_header);
+
+ /* add tag bloom filter */
+ tag_bloom_bits = 0;
+ udev_list_entry_foreach(list_entry, udev_device_get_tags_list_entry(udev_device))
+ tag_bloom_bits |= util_string_bloom64(udev_list_entry_get_name(list_entry));
+ if (tag_bloom_bits > 0) {
+ nlh.filter_tag_bloom_hi = htonl(tag_bloom_bits >> 32);
+ nlh.filter_tag_bloom_lo = htonl(tag_bloom_bits & 0xffffffff);
+ }
+
+ /* add properties list */
+ nlh.properties_off = iov[0].iov_len;
+ nlh.properties_len = blen;
+ iov[1].iov_base = (char *)buf;
+ iov[1].iov_len = blen;
+
+ memset(&smsg, 0x00, sizeof(struct msghdr));
+ smsg.msg_iov = iov;
+ smsg.msg_iovlen = 2;
+ /*
+ * Use custom address for target, or the default one.
+ *
+ * If we send to a multicast group, we will get
+ * ECONNREFUSED, which is expected.
+ */
+ if (destination != NULL)
+ smsg.msg_name = &destination->snl;
+ else
+ smsg.msg_name = &udev_monitor->snl_destination;
+ smsg.msg_namelen = sizeof(struct sockaddr_nl);
+ count = sendmsg(udev_monitor->sock, &smsg, 0);
+ udev_dbg(udev_monitor->udev, "passed %zi bytes to netlink monitor %p\n", count, udev_monitor);
+ return count;
+}
+
+/**
+ * udev_monitor_filter_add_match_subsystem_devtype:
+ * @udev_monitor: the monitor
+ * @subsystem: the subsystem value to match the incoming devices against
+ * @devtype: the devtype value to match the incoming devices against
+ *
+ * This filter is efficiently executed inside the kernel, and libudev subscribers
+ * will usually not be woken up for devices which do not match.
+ *
+ * The filter must be installed before the monitor is switched to listening mode.
+ *
+ * Returns: 0 on success, otherwise a negative error value.
+ */
+_public_ int udev_monitor_filter_add_match_subsystem_devtype(struct udev_monitor *udev_monitor, const char *subsystem, const char *devtype)
+{
+ if (udev_monitor == NULL)
+ return -EINVAL;
+ if (subsystem == NULL)
+ return -EINVAL;
+ if (udev_list_entry_add(&udev_monitor->filter_subsystem_list, subsystem, devtype) == NULL)
+ return -ENOMEM;
+ return 0;
+}
+
+/**
+ * udev_monitor_filter_add_match_tag:
+ * @udev_monitor: the monitor
+ * @tag: the name of a tag
+ *
+ * This filter is efficiently executed inside the kernel, and libudev subscribers
+ * will usually not be woken up for devices which do not match.
+ *
+ * The filter must be installed before the monitor is switched to listening mode.
+ *
+ * Returns: 0 on success, otherwise a negative error value.
+ */
+_public_ int udev_monitor_filter_add_match_tag(struct udev_monitor *udev_monitor, const char *tag)
+{
+ if (udev_monitor == NULL)
+ return -EINVAL;
+ if (tag == NULL)
+ return -EINVAL;
+ if (udev_list_entry_add(&udev_monitor->filter_tag_list, tag, NULL) == NULL)
+ return -ENOMEM;
+ return 0;
+}
+
+/**
+ * udev_monitor_filter_remove:
+ * @udev_monitor: monitor
+ *
+ * Remove all filters from monitor.
+ *
+ * Returns: 0 on success, otherwise a negative error value.
+ */
+_public_ int udev_monitor_filter_remove(struct udev_monitor *udev_monitor)
+{
+ static struct sock_fprog filter = { 0, NULL };
+
+ udev_list_cleanup(&udev_monitor->filter_subsystem_list);
+ return setsockopt(udev_monitor->sock, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter));
+}
diff --git a/src/libudev/libudev-private.h b/src/libudev/libudev-private.h
new file mode 100644
index 0000000000..54c51acc23
--- /dev/null
+++ b/src/libudev/libudev-private.h
@@ -0,0 +1,179 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2008-2012 Kay Sievers <kay@vrfy.org>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#ifndef _LIBUDEV_PRIVATE_H_
+#define _LIBUDEV_PRIVATE_H_
+
+#include <syslog.h>
+#include <signal.h>
+#include <stdint.h>
+#include <stdbool.h>
+
+#include "libudev.h"
+#include "macro.h"
+#include "util.h"
+#include "mkdir.h"
+#include "strxcpyx.h"
+
+#define READ_END 0
+#define WRITE_END 1
+
+/* avoid (sometimes expensive) calculations of parameters for debug output */
+#define udev_log_cond(udev, prio, arg...) \
+ do { \
+ if (udev_get_log_priority(udev) >= prio) \
+ udev_log(udev, prio, __FILE__, __LINE__, __FUNCTION__, ## arg); \
+ } while (0)
+
+#define udev_dbg(udev, arg...) udev_log_cond(udev, LOG_DEBUG, ## arg)
+#define udev_info(udev, arg...) udev_log_cond(udev, LOG_INFO, ## arg)
+#define udev_err(udev, arg...) udev_log_cond(udev, LOG_ERR, ## arg)
+
+/* libudev.c */
+void udev_log(struct udev *udev,
+ int priority, const char *file, int line, const char *fn,
+ const char *format, ...)
+ __attribute__((format(printf, 6, 7)));
+int udev_get_rules_path(struct udev *udev, char **path[], usec_t *ts_usec[]);
+struct udev_list_entry *udev_add_property(struct udev *udev, const char *key, const char *value);
+struct udev_list_entry *udev_get_properties_list_entry(struct udev *udev);
+
+/* libudev-device.c */
+struct udev_device *udev_device_new(struct udev *udev);
+mode_t udev_device_get_devnode_mode(struct udev_device *udev_device);
+uid_t udev_device_get_devnode_uid(struct udev_device *udev_device);
+gid_t udev_device_get_devnode_gid(struct udev_device *udev_device);
+int udev_device_set_subsystem(struct udev_device *udev_device, const char *subsystem);
+int udev_device_set_syspath(struct udev_device *udev_device, const char *syspath);
+int udev_device_set_devnode(struct udev_device *udev_device, const char *devnode);
+int udev_device_add_devlink(struct udev_device *udev_device, const char *devlink);
+void udev_device_cleanup_devlinks_list(struct udev_device *udev_device);
+struct udev_list_entry *udev_device_add_property(struct udev_device *udev_device, const char *key, const char *value);
+void udev_device_add_property_from_string_parse(struct udev_device *udev_device, const char *property);
+int udev_device_add_property_from_string_parse_finish(struct udev_device *udev_device);
+char **udev_device_get_properties_envp(struct udev_device *udev_device);
+ssize_t udev_device_get_properties_monitor_buf(struct udev_device *udev_device, const char **buf);
+int udev_device_read_db(struct udev_device *udev_device, const char *dbfile);
+int udev_device_read_uevent_file(struct udev_device *udev_device);
+int udev_device_set_action(struct udev_device *udev_device, const char *action);
+const char *udev_device_get_devpath_old(struct udev_device *udev_device);
+const char *udev_device_get_id_filename(struct udev_device *udev_device);
+void udev_device_set_is_initialized(struct udev_device *udev_device);
+int udev_device_add_tag(struct udev_device *udev_device, const char *tag);
+void udev_device_cleanup_tags_list(struct udev_device *udev_device);
+usec_t udev_device_get_usec_initialized(struct udev_device *udev_device);
+void udev_device_set_usec_initialized(struct udev_device *udev_device, usec_t usec_initialized);
+int udev_device_get_devlink_priority(struct udev_device *udev_device);
+int udev_device_set_devlink_priority(struct udev_device *udev_device, int prio);
+int udev_device_get_watch_handle(struct udev_device *udev_device);
+int udev_device_set_watch_handle(struct udev_device *udev_device, int handle);
+int udev_device_get_ifindex(struct udev_device *udev_device);
+void udev_device_set_info_loaded(struct udev_device *device);
+bool udev_device_get_db_persist(struct udev_device *udev_device);
+void udev_device_set_db_persist(struct udev_device *udev_device);
+
+/* libudev-device-private.c */
+int udev_device_update_db(struct udev_device *udev_device);
+int udev_device_delete_db(struct udev_device *udev_device);
+int udev_device_tag_index(struct udev_device *dev, struct udev_device *dev_old, bool add);
+
+/* libudev-monitor.c - netlink/unix socket communication */
+int udev_monitor_disconnect(struct udev_monitor *udev_monitor);
+int udev_monitor_allow_unicast_sender(struct udev_monitor *udev_monitor, struct udev_monitor *sender);
+int udev_monitor_send_device(struct udev_monitor *udev_monitor,
+ struct udev_monitor *destination, struct udev_device *udev_device);
+struct udev_monitor *udev_monitor_new_from_netlink_fd(struct udev *udev, const char *name, int fd);
+
+/* libudev-list.c */
+struct udev_list_node {
+ struct udev_list_node *next, *prev;
+};
+struct udev_list {
+ struct udev *udev;
+ struct udev_list_node node;
+ struct udev_list_entry **entries;
+ unsigned int entries_cur;
+ unsigned int entries_max;
+ bool unique;
+};
+#define UDEV_LIST(list) struct udev_list_node list = { &(list), &(list) }
+void udev_list_node_init(struct udev_list_node *list);
+int udev_list_node_is_empty(struct udev_list_node *list);
+void udev_list_node_append(struct udev_list_node *new, struct udev_list_node *list);
+void udev_list_node_remove(struct udev_list_node *entry);
+#define udev_list_node_foreach(node, list) \
+ for (node = (list)->next; \
+ node != list; \
+ node = (node)->next)
+#define udev_list_node_foreach_safe(node, tmp, list) \
+ for (node = (list)->next, tmp = (node)->next; \
+ node != list; \
+ node = tmp, tmp = (tmp)->next)
+void udev_list_init(struct udev *udev, struct udev_list *list, bool unique);
+void udev_list_cleanup(struct udev_list *list);
+struct udev_list_entry *udev_list_get_entry(struct udev_list *list);
+struct udev_list_entry *udev_list_entry_add(struct udev_list *list, const char *name, const char *value);
+void udev_list_entry_delete(struct udev_list_entry *entry);
+void udev_list_entry_insert_before(struct udev_list_entry *new, struct udev_list_entry *entry);
+void udev_list_entry_append(struct udev_list_entry *new, struct udev_list *list);
+int udev_list_entry_get_num(struct udev_list_entry *list_entry);
+void udev_list_entry_set_num(struct udev_list_entry *list_entry, int num);
+#define udev_list_entry_foreach_safe(entry, tmp, first) \
+ for (entry = first, tmp = udev_list_entry_get_next(entry); \
+ entry != NULL; \
+ entry = tmp, tmp = udev_list_entry_get_next(tmp))
+
+/* libudev-queue.c */
+unsigned long long int udev_get_kernel_seqnum(struct udev *udev);
+int udev_queue_read_seqnum(FILE *queue_file, unsigned long long int *seqnum);
+ssize_t udev_queue_read_devpath(FILE *queue_file, char *devpath, size_t size);
+ssize_t udev_queue_skip_devpath(FILE *queue_file);
+
+/* libudev-queue-private.c */
+struct udev_queue_export *udev_queue_export_new(struct udev *udev);
+struct udev_queue_export *udev_queue_export_unref(struct udev_queue_export *udev_queue_export);
+void udev_queue_export_cleanup(struct udev_queue_export *udev_queue_export);
+int udev_queue_export_device_queued(struct udev_queue_export *udev_queue_export, struct udev_device *udev_device);
+int udev_queue_export_device_finished(struct udev_queue_export *udev_queue_export, struct udev_device *udev_device);
+
+/* libudev-hwdb.c */
+bool udev_hwdb_validate(struct udev_hwdb *hwdb);
+
+/* libudev-util.c */
+#define UTIL_PATH_SIZE 1024
+#define UTIL_NAME_SIZE 512
+#define UTIL_LINE_SIZE 16384
+#define UDEV_ALLOWED_CHARS_INPUT "/ $%?,"
+ssize_t util_get_sys_core_link_value(struct udev *udev, const char *slink, const char *syspath, char *value, size_t size);
+int util_resolve_sys_link(struct udev *udev, char *syspath, size_t size);
+int util_log_priority(const char *priority);
+size_t util_path_encode(const char *src, char *dest, size_t size);
+void util_remove_trailing_chars(char *path, char c);
+int util_replace_whitespace(const char *str, char *to, size_t len);
+int util_replace_chars(char *str, const char *white);
+unsigned int util_string_hash32(const char *key);
+uint64_t util_string_bloom64(const char *str);
+
+/* libudev-util-private.c */
+int util_delete_path(struct udev *udev, const char *path);
+uid_t util_lookup_user(struct udev *udev, const char *user);
+gid_t util_lookup_group(struct udev *udev, const char *group);
+int util_resolve_subsys_kernel(struct udev *udev, const char *string, char *result, size_t maxsize, int read_value);
+ssize_t print_kmsg(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
+#endif
diff --git a/src/libudev/libudev-queue-private.c b/src/libudev/libudev-queue-private.c
new file mode 100644
index 0000000000..80d7ceef2b
--- /dev/null
+++ b/src/libudev/libudev-queue-private.c
@@ -0,0 +1,406 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2008-2012 Kay Sievers <kay@vrfy.org>
+ Copyright 2009 Alan Jenkins <alan-jenkins@tuffmail.co.uk>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+/*
+ * DISCLAIMER - The file format mentioned here is private to udev/libudev,
+ * and may be changed without notice.
+ *
+ * The udev event queue is exported as a binary log file.
+ * Each log record consists of a sequence number followed by the device path.
+ *
+ * When a new event is queued, its details are appended to the log.
+ * When the event finishes, a second record is appended to the log
+ * with the same sequence number but a devpath len of 0.
+ *
+ * Example:
+ * { 0x0000000000000001 }
+ * { 0x0000000000000001, 0x0019, "/devices/virtual/mem/null" },
+ * { 0x0000000000000002, 0x001b, "/devices/virtual/mem/random" },
+ * { 0x0000000000000001, 0x0000 },
+ * { 0x0000000000000003, 0x0019, "/devices/virtual/mem/zero" },
+ *
+ * Events 2 and 3 are still queued, but event 1 has finished.
+ *
+ * The queue does not grow indefinitely. It is periodically re-created
+ * to remove finished events. Atomic rename() makes this transparent to readers.
+ *
+ * The queue file starts with a single sequence number which specifies the
+ * minimum sequence number in the log that follows. Any events prior to this
+ * sequence number have already finished.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <dirent.h>
+#include <limits.h>
+#include <errno.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+
+#include "libudev.h"
+#include "libudev-private.h"
+
+static int rebuild_queue_file(struct udev_queue_export *udev_queue_export);
+
+struct udev_queue_export {
+ struct udev *udev;
+ int queued_count; /* number of unfinished events exported in queue file */
+ FILE *queue_file;
+ unsigned long long int seqnum_max; /* earliest sequence number in queue file */
+ unsigned long long int seqnum_min; /* latest sequence number in queue file */
+ int waste_bytes; /* queue file bytes wasted on finished events */
+};
+
+struct udev_queue_export *udev_queue_export_new(struct udev *udev)
+{
+ struct udev_queue_export *udev_queue_export;
+ unsigned long long int initial_seqnum;
+
+ if (udev == NULL)
+ return NULL;
+
+ udev_queue_export = calloc(1, sizeof(struct udev_queue_export));
+ if (udev_queue_export == NULL)
+ return NULL;
+ udev_queue_export->udev = udev;
+
+ initial_seqnum = udev_get_kernel_seqnum(udev);
+ udev_queue_export->seqnum_min = initial_seqnum;
+ udev_queue_export->seqnum_max = initial_seqnum;
+
+ udev_queue_export_cleanup(udev_queue_export);
+ if (rebuild_queue_file(udev_queue_export) != 0) {
+ free(udev_queue_export);
+ return NULL;
+ }
+
+ return udev_queue_export;
+}
+
+struct udev_queue_export *udev_queue_export_unref(struct udev_queue_export *udev_queue_export)
+{
+ if (udev_queue_export == NULL)
+ return NULL;
+ if (udev_queue_export->queue_file != NULL)
+ fclose(udev_queue_export->queue_file);
+ free(udev_queue_export);
+ return NULL;
+}
+
+void udev_queue_export_cleanup(struct udev_queue_export *udev_queue_export)
+{
+ if (udev_queue_export == NULL)
+ return;
+ unlink("/run/udev/queue.tmp");
+ unlink("/run/udev/queue.bin");
+}
+
+static int skip_to(FILE *file, long offset)
+{
+ long old_offset;
+
+ /* fseek may drop buffered data, avoid it for small seeks */
+ old_offset = ftell(file);
+ if (offset > old_offset && offset - old_offset <= BUFSIZ) {
+ size_t skip_bytes = offset - old_offset;
+ char *buf = alloca(skip_bytes);
+
+ if (fread(buf, skip_bytes, 1, file) != skip_bytes)
+ return -1;
+ }
+
+ return fseek(file, offset, SEEK_SET);
+}
+
+struct queue_devpaths {
+ unsigned int devpaths_first; /* index of first queued event */
+ unsigned int devpaths_size;
+ long devpaths[]; /* seqnum -> offset of devpath in queue file (or 0) */
+};
+
+/*
+ * Returns a table mapping seqnum to devpath file offset for currently queued events.
+ * devpaths[i] represents the event with seqnum = i + udev_queue_export->seqnum_min.
+ */
+static struct queue_devpaths *build_index(struct udev_queue_export *udev_queue_export)
+{
+ struct queue_devpaths *devpaths;
+ unsigned long long int range;
+ long devpath_offset;
+ ssize_t devpath_len;
+ unsigned long long int seqnum;
+ unsigned long long int n;
+ unsigned int i;
+
+ /* seek to the first event in the file */
+ rewind(udev_queue_export->queue_file);
+ udev_queue_read_seqnum(udev_queue_export->queue_file, &seqnum);
+
+ /* allocate the table */
+ range = udev_queue_export->seqnum_min - udev_queue_export->seqnum_max;
+ if (range - 1 > INT_MAX) {
+ udev_err(udev_queue_export->udev, "queue file overflow\n");
+ return NULL;
+ }
+ devpaths = calloc(1, sizeof(struct queue_devpaths) + (range + 1) * sizeof(long));
+ if (devpaths == NULL)
+ return NULL;
+ devpaths->devpaths_size = range + 1;
+
+ /* read all records and populate the table */
+ for (;;) {
+ if (udev_queue_read_seqnum(udev_queue_export->queue_file, &seqnum) < 0)
+ break;
+ n = seqnum - udev_queue_export->seqnum_max;
+ if (n >= devpaths->devpaths_size)
+ goto read_error;
+
+ devpath_offset = ftell(udev_queue_export->queue_file);
+ devpath_len = udev_queue_skip_devpath(udev_queue_export->queue_file);
+ if (devpath_len < 0)
+ goto read_error;
+
+ if (devpath_len > 0)
+ devpaths->devpaths[n] = devpath_offset;
+ else
+ devpaths->devpaths[n] = 0;
+ }
+
+ /* find first queued event */
+ for (i = 0; i < devpaths->devpaths_size; i++) {
+ if (devpaths->devpaths[i] != 0)
+ break;
+ }
+ devpaths->devpaths_first = i;
+
+ return devpaths;
+
+read_error:
+ udev_err(udev_queue_export->udev, "queue file corrupted\n");
+ free(devpaths);
+ return NULL;
+}
+
+static int rebuild_queue_file(struct udev_queue_export *udev_queue_export)
+{
+ unsigned long long int seqnum;
+ struct queue_devpaths *devpaths = NULL;
+ FILE *new_queue_file = NULL;
+ unsigned int i;
+
+ /* read old queue file */
+ if (udev_queue_export->queue_file != NULL) {
+ devpaths = build_index(udev_queue_export);
+ if (devpaths != NULL)
+ udev_queue_export->seqnum_max += devpaths->devpaths_first;
+ }
+ if (devpaths == NULL) {
+ udev_queue_export->queued_count = 0;
+ udev_queue_export->seqnum_max = udev_queue_export->seqnum_min;
+ }
+
+ /* create new queue file */
+ new_queue_file = fopen("/run/udev/queue.tmp", "w+e");
+ if (new_queue_file == NULL)
+ goto error;
+ seqnum = udev_queue_export->seqnum_max;
+ fwrite(&seqnum, 1, sizeof(unsigned long long int), new_queue_file);
+
+ /* copy unfinished events only to the new file */
+ if (devpaths != NULL) {
+ for (i = devpaths->devpaths_first; i < devpaths->devpaths_size; i++) {
+ char devpath[UTIL_PATH_SIZE];
+ int err;
+ unsigned short devpath_len;
+
+ if (devpaths->devpaths[i] != 0)
+ {
+ skip_to(udev_queue_export->queue_file, devpaths->devpaths[i]);
+ err = udev_queue_read_devpath(udev_queue_export->queue_file, devpath, sizeof(devpath));
+ devpath_len = err;
+
+ fwrite(&seqnum, sizeof(unsigned long long int), 1, new_queue_file);
+ fwrite(&devpath_len, sizeof(unsigned short), 1, new_queue_file);
+ fwrite(devpath, 1, devpath_len, new_queue_file);
+ }
+ seqnum++;
+ }
+ free(devpaths);
+ devpaths = NULL;
+ }
+ fflush(new_queue_file);
+ if (ferror(new_queue_file))
+ goto error;
+
+ /* rename the new file on top of the old one */
+ if (rename("/run/udev/queue.tmp", "/run/udev/queue.bin") != 0)
+ goto error;
+
+ if (udev_queue_export->queue_file != NULL)
+ fclose(udev_queue_export->queue_file);
+ udev_queue_export->queue_file = new_queue_file;
+ udev_queue_export->waste_bytes = 0;
+
+ return 0;
+
+error:
+ udev_err(udev_queue_export->udev, "failed to create queue file: %m\n");
+ udev_queue_export_cleanup(udev_queue_export);
+
+ if (udev_queue_export->queue_file != NULL) {
+ fclose(udev_queue_export->queue_file);
+ udev_queue_export->queue_file = NULL;
+ }
+ if (new_queue_file != NULL)
+ fclose(new_queue_file);
+
+ if (devpaths != NULL)
+ free(devpaths);
+ udev_queue_export->queued_count = 0;
+ udev_queue_export->waste_bytes = 0;
+ udev_queue_export->seqnum_max = udev_queue_export->seqnum_min;
+
+ return -1;
+}
+
+static int write_queue_record(struct udev_queue_export *udev_queue_export,
+ unsigned long long int seqnum, const char *devpath, size_t devpath_len)
+{
+ unsigned short len;
+
+ if (udev_queue_export->queue_file == NULL)
+ return -1;
+
+ if (fwrite(&seqnum, sizeof(unsigned long long int), 1, udev_queue_export->queue_file) != 1)
+ goto write_error;
+
+ len = (devpath_len < USHRT_MAX) ? devpath_len : USHRT_MAX;
+ if (fwrite(&len, sizeof(unsigned short), 1, udev_queue_export->queue_file) != 1)
+ goto write_error;
+ if (len > 0) {
+ if (fwrite(devpath, 1, len, udev_queue_export->queue_file) != len)
+ goto write_error;
+ }
+
+ /* *must* flush output; caller may fork */
+ if (fflush(udev_queue_export->queue_file) != 0)
+ goto write_error;
+
+ return 0;
+
+write_error:
+ /* if we failed half way through writing a record to a file,
+ we should not try to write any further records to it. */
+ udev_err(udev_queue_export->udev, "error writing to queue file: %m\n");
+ fclose(udev_queue_export->queue_file);
+ udev_queue_export->queue_file = NULL;
+
+ return -1;
+}
+
+enum device_state {
+ DEVICE_QUEUED,
+ DEVICE_FINISHED,
+};
+
+static inline size_t queue_record_size(size_t devpath_len)
+{
+ return sizeof(unsigned long long int) + sizeof(unsigned short int) + devpath_len;
+}
+
+static int update_queue(struct udev_queue_export *udev_queue_export,
+ struct udev_device *udev_device, enum device_state state)
+{
+ unsigned long long int seqnum = udev_device_get_seqnum(udev_device);
+ const char *devpath = NULL;
+ size_t devpath_len = 0;
+ int bytes;
+ int err;
+
+ /* FINISHED records have a zero length devpath */
+ if (state == DEVICE_QUEUED) {
+ devpath = udev_device_get_devpath(udev_device);
+ devpath_len = strlen(devpath);
+ }
+
+ /* recover from an earlier failed rebuild */
+ if (udev_queue_export->queue_file == NULL) {
+ if (rebuild_queue_file(udev_queue_export) != 0)
+ return -1;
+ }
+
+ /* if we're removing the last event from the queue, that's the best time to rebuild it */
+ if (state != DEVICE_QUEUED && udev_queue_export->queued_count == 1) {
+ /* we don't need to read the old queue file */
+ fclose(udev_queue_export->queue_file);
+ udev_queue_export->queue_file = NULL;
+ rebuild_queue_file(udev_queue_export);
+ return 0;
+ }
+
+ /* try to rebuild the queue files before they grow larger than one page. */
+ bytes = ftell(udev_queue_export->queue_file) + queue_record_size(devpath_len);
+ if ((udev_queue_export->waste_bytes > bytes / 2) && bytes > 4096)
+ rebuild_queue_file(udev_queue_export);
+
+ /* don't record a finished event, if we already dropped the event in a failed rebuild */
+ if (seqnum < udev_queue_export->seqnum_max)
+ return 0;
+
+ /* now write to the queue */
+ if (state == DEVICE_QUEUED) {
+ udev_queue_export->queued_count++;
+ udev_queue_export->seqnum_min = seqnum;
+ } else {
+ udev_queue_export->waste_bytes += queue_record_size(devpath_len) + queue_record_size(0);
+ udev_queue_export->queued_count--;
+ }
+ err = write_queue_record(udev_queue_export, seqnum, devpath, devpath_len);
+
+ /* try to handle ENOSPC */
+ if (err != 0 && udev_queue_export->queued_count == 0) {
+ udev_queue_export_cleanup(udev_queue_export);
+ err = rebuild_queue_file(udev_queue_export);
+ }
+
+ return err;
+}
+
+static int update(struct udev_queue_export *udev_queue_export,
+ struct udev_device *udev_device, enum device_state state)
+{
+ if (update_queue(udev_queue_export, udev_device, state) != 0)
+ return -1;
+
+ return 0;
+}
+
+int udev_queue_export_device_queued(struct udev_queue_export *udev_queue_export, struct udev_device *udev_device)
+{
+ return update(udev_queue_export, udev_device, DEVICE_QUEUED);
+}
+
+int udev_queue_export_device_finished(struct udev_queue_export *udev_queue_export, struct udev_device *udev_device)
+{
+ return update(udev_queue_export, udev_device, DEVICE_FINISHED);
+}
diff --git a/src/libudev/libudev-queue.c b/src/libudev/libudev-queue.c
new file mode 100644
index 0000000000..0dd20313d9
--- /dev/null
+++ b/src/libudev/libudev-queue.c
@@ -0,0 +1,480 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2008-2012 Kay Sievers <kay@vrfy.org>
+ Copyright 2009 Alan Jenkins <alan-jenkins@tuffmail.co.uk>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <unistd.h>
+#include <errno.h>
+#include <string.h>
+#include <dirent.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <sys/stat.h>
+
+#include "libudev.h"
+#include "libudev-private.h"
+
+/**
+ * SECTION:libudev-queue
+ * @short_description: access to currently active events
+ *
+ * The udev daemon processes events asynchronously. All events which do not have
+ * interdependencies run in parallel. This exports the current state of the
+ * event processing queue, and the current event sequence numbers from the kernel
+ * and the udev daemon.
+ */
+
+/**
+ * udev_queue:
+ *
+ * Opaque object representing the current event queue in the udev daemon.
+ */
+struct udev_queue {
+ struct udev *udev;
+ int refcount;
+ struct udev_list queue_list;
+};
+
+/**
+ * udev_queue_new:
+ * @udev: udev library context
+ *
+ * The initial refcount is 1, and needs to be decremented to
+ * release the resources of the udev queue context.
+ *
+ * Returns: the udev queue context, or #NULL on error.
+ **/
+_public_ struct udev_queue *udev_queue_new(struct udev *udev)
+{
+ struct udev_queue *udev_queue;
+
+ if (udev == NULL)
+ return NULL;
+
+ udev_queue = calloc(1, sizeof(struct udev_queue));
+ if (udev_queue == NULL)
+ return NULL;
+ udev_queue->refcount = 1;
+ udev_queue->udev = udev;
+ udev_list_init(udev, &udev_queue->queue_list, false);
+ return udev_queue;
+}
+
+/**
+ * udev_queue_ref:
+ * @udev_queue: udev queue context
+ *
+ * Take a reference of a udev queue context.
+ *
+ * Returns: the same udev queue context.
+ **/
+_public_ struct udev_queue *udev_queue_ref(struct udev_queue *udev_queue)
+{
+ if (udev_queue == NULL)
+ return NULL;
+ udev_queue->refcount++;
+ return udev_queue;
+}
+
+/**
+ * udev_queue_unref:
+ * @udev_queue: udev queue context
+ *
+ * Drop a reference of a udev queue context. If the refcount reaches zero,
+ * the resources of the queue context will be released.
+ *
+ * Returns: the passed queue context if it has still an active reference, or #NULL otherwise.
+ **/
+_public_ struct udev_queue *udev_queue_unref(struct udev_queue *udev_queue)
+{
+ if (udev_queue == NULL)
+ return NULL;
+ udev_queue->refcount--;
+ if (udev_queue->refcount > 0)
+ return udev_queue;
+ udev_list_cleanup(&udev_queue->queue_list);
+ free(udev_queue);
+ return NULL;
+}
+
+/**
+ * udev_queue_get_udev:
+ * @udev_queue: udev queue context
+ *
+ * Retrieve the udev library context the queue context was created with.
+ *
+ * Returns: the udev library context.
+ **/
+_public_ struct udev *udev_queue_get_udev(struct udev_queue *udev_queue)
+{
+ if (udev_queue == NULL)
+ return NULL;
+ return udev_queue->udev;
+}
+
+unsigned long long int udev_get_kernel_seqnum(struct udev *udev)
+{
+ unsigned long long int seqnum;
+ int fd;
+ char buf[32];
+ ssize_t len;
+
+ fd = open("/sys/kernel/uevent_seqnum", O_RDONLY|O_CLOEXEC);
+ if (fd < 0)
+ return 0;
+ len = read(fd, buf, sizeof(buf));
+ close(fd);
+ if (len <= 2)
+ return 0;
+ buf[len-1] = '\0';
+ seqnum = strtoull(buf, NULL, 10);
+ return seqnum;
+}
+
+/**
+ * udev_queue_get_kernel_seqnum:
+ * @udev_queue: udev queue context
+ *
+ * Get the current kernel event sequence number.
+ *
+ * Returns: the sequence number.
+ **/
+_public_ unsigned long long int udev_queue_get_kernel_seqnum(struct udev_queue *udev_queue)
+{
+ unsigned long long int seqnum;
+
+ if (udev_queue == NULL)
+ return -EINVAL;
+
+ seqnum = udev_get_kernel_seqnum(udev_queue->udev);
+ return seqnum;
+}
+
+int udev_queue_read_seqnum(FILE *queue_file, unsigned long long int *seqnum)
+{
+ if (fread(seqnum, sizeof(unsigned long long int), 1, queue_file) != 1)
+ return -1;
+
+ return 0;
+}
+
+ssize_t udev_queue_skip_devpath(FILE *queue_file)
+{
+ unsigned short int len;
+
+ if (fread(&len, sizeof(unsigned short int), 1, queue_file) == 1) {
+ char *devpath = alloca(len);
+
+ /* use fread to skip, fseek might drop buffered data */
+ if (fread(devpath, 1, len, queue_file) == len)
+ return len;
+ }
+
+ return -1;
+}
+
+ssize_t udev_queue_read_devpath(FILE *queue_file, char *devpath, size_t size)
+{
+ unsigned short int read_bytes = 0;
+ unsigned short int len;
+
+ if (fread(&len, sizeof(unsigned short int), 1, queue_file) != 1)
+ return -1;
+
+ read_bytes = (len < size - 1) ? len : size - 1;
+ if (fread(devpath, 1, read_bytes, queue_file) != read_bytes)
+ return -1;
+ devpath[read_bytes] = '\0';
+
+ /* if devpath was too long, skip unread characters */
+ if (read_bytes != len) {
+ unsigned short int skip_bytes = len - read_bytes;
+ char *buf = alloca(skip_bytes);
+
+ if (fread(buf, 1, skip_bytes, queue_file) != skip_bytes)
+ return -1;
+ }
+
+ return read_bytes;
+}
+
+static FILE *open_queue_file(struct udev_queue *udev_queue, unsigned long long int *seqnum_start)
+{
+ FILE *queue_file;
+
+ queue_file = fopen("/run/udev/queue.bin", "re");
+ if (queue_file == NULL)
+ return NULL;
+
+ if (udev_queue_read_seqnum(queue_file, seqnum_start) < 0) {
+ udev_err(udev_queue->udev, "corrupt queue file\n");
+ fclose(queue_file);
+ return NULL;
+ }
+
+ return queue_file;
+}
+
+/**
+ * udev_queue_get_udev_seqnum:
+ * @udev_queue: udev queue context
+ *
+ * Get the last known udev event sequence number.
+ *
+ * Returns: the sequence number.
+ **/
+_public_ unsigned long long int udev_queue_get_udev_seqnum(struct udev_queue *udev_queue)
+{
+ unsigned long long int seqnum_udev;
+ FILE *queue_file;
+
+ queue_file = open_queue_file(udev_queue, &seqnum_udev);
+ if (queue_file == NULL)
+ return 0;
+
+ for (;;) {
+ unsigned long long int seqnum;
+ ssize_t devpath_len;
+
+ if (udev_queue_read_seqnum(queue_file, &seqnum) < 0)
+ break;
+ devpath_len = udev_queue_skip_devpath(queue_file);
+ if (devpath_len < 0)
+ break;
+ if (devpath_len > 0)
+ seqnum_udev = seqnum;
+ }
+
+ fclose(queue_file);
+ return seqnum_udev;
+}
+
+/**
+ * udev_queue_get_udev_is_active:
+ * @udev_queue: udev queue context
+ *
+ * Check if udev is active on the system.
+ *
+ * Returns: a flag indicating if udev is active.
+ **/
+_public_ int udev_queue_get_udev_is_active(struct udev_queue *udev_queue)
+{
+ unsigned long long int seqnum_start;
+ FILE *queue_file;
+
+ queue_file = open_queue_file(udev_queue, &seqnum_start);
+ if (queue_file == NULL)
+ return 0;
+
+ fclose(queue_file);
+ return 1;
+}
+
+/**
+ * udev_queue_get_queue_is_empty:
+ * @udev_queue: udev queue context
+ *
+ * Check if udev is currently processing any events.
+ *
+ * Returns: a flag indicating if udev is currently handling events.
+ **/
+_public_ int udev_queue_get_queue_is_empty(struct udev_queue *udev_queue)
+{
+ unsigned long long int seqnum_kernel;
+ unsigned long long int seqnum_udev = 0;
+ int queued = 0;
+ int is_empty = 0;
+ FILE *queue_file;
+
+ if (udev_queue == NULL)
+ return -EINVAL;
+ queue_file = open_queue_file(udev_queue, &seqnum_udev);
+ if (queue_file == NULL)
+ return 1;
+
+ for (;;) {
+ unsigned long long int seqnum;
+ ssize_t devpath_len;
+
+ if (udev_queue_read_seqnum(queue_file, &seqnum) < 0)
+ break;
+ devpath_len = udev_queue_skip_devpath(queue_file);
+ if (devpath_len < 0)
+ break;
+
+ if (devpath_len > 0) {
+ queued++;
+ seqnum_udev = seqnum;
+ } else {
+ queued--;
+ }
+ }
+
+ if (queued > 0)
+ goto out;
+
+ seqnum_kernel = udev_queue_get_kernel_seqnum(udev_queue);
+ if (seqnum_udev < seqnum_kernel)
+ goto out;
+
+ is_empty = 1;
+
+out:
+ fclose(queue_file);
+ return is_empty;
+}
+
+/**
+ * udev_queue_get_seqnum_sequence_is_finished:
+ * @udev_queue: udev queue context
+ * @start: first event sequence number
+ * @end: last event sequence number
+ *
+ * Check if udev is currently processing any events in a given sequence number range.
+ *
+ * Returns: a flag indicating if any of the sequence numbers in the given range is currently active.
+ **/
+_public_ int udev_queue_get_seqnum_sequence_is_finished(struct udev_queue *udev_queue,
+ unsigned long long int start, unsigned long long int end)
+{
+ unsigned long long int seqnum;
+ ssize_t devpath_len;
+ int unfinished;
+ FILE *queue_file;
+
+ if (udev_queue == NULL)
+ return -EINVAL;
+ queue_file = open_queue_file(udev_queue, &seqnum);
+ if (queue_file == NULL)
+ return 1;
+ if (start < seqnum)
+ start = seqnum;
+ if (start > end) {
+ fclose(queue_file);
+ return 1;
+ }
+ if (end - start > INT_MAX - 1) {
+ fclose(queue_file);
+ return -EOVERFLOW;
+ }
+
+ /*
+ * we might start with 0, and handle the initial seqnum
+ * only when we find an entry in the queue file
+ **/
+ unfinished = end - start;
+
+ do {
+ if (udev_queue_read_seqnum(queue_file, &seqnum) < 0)
+ break;
+ devpath_len = udev_queue_skip_devpath(queue_file);
+ if (devpath_len < 0)
+ break;
+
+ /*
+ * we might start with an empty or re-build queue file, where
+ * the initial seqnum is not recorded as finished
+ */
+ if (start == seqnum && devpath_len > 0)
+ unfinished++;
+
+ if (devpath_len == 0) {
+ if (seqnum >= start && seqnum <= end)
+ unfinished--;
+ }
+ } while (unfinished > 0);
+
+ fclose(queue_file);
+
+ return (unfinished == 0);
+}
+
+/**
+ * udev_queue_get_seqnum_is_finished:
+ * @udev_queue: udev queue context
+ * @seqnum: sequence number
+ *
+ * Check if udev is currently processing a given sequence number.
+ *
+ * Returns: a flag indicating if the given sequence number is currently active.
+ **/
+_public_ int udev_queue_get_seqnum_is_finished(struct udev_queue *udev_queue, unsigned long long int seqnum)
+{
+ if (!udev_queue_get_seqnum_sequence_is_finished(udev_queue, seqnum, seqnum))
+ return 0;
+
+ return 1;
+}
+
+/**
+ * udev_queue_get_queued_list_entry:
+ * @udev_queue: udev queue context
+ *
+ * Get the first entry of the list of queued events.
+ *
+ * Returns: a udev_list_entry.
+ **/
+_public_ struct udev_list_entry *udev_queue_get_queued_list_entry(struct udev_queue *udev_queue)
+{
+ unsigned long long int seqnum;
+ FILE *queue_file;
+
+ if (udev_queue == NULL)
+ return NULL;
+ udev_list_cleanup(&udev_queue->queue_list);
+
+ queue_file = open_queue_file(udev_queue, &seqnum);
+ if (queue_file == NULL)
+ return NULL;
+
+ for (;;) {
+ char syspath[UTIL_PATH_SIZE];
+ char *s;
+ size_t l;
+ ssize_t len;
+ char seqnum_str[32];
+ struct udev_list_entry *list_entry;
+
+ if (udev_queue_read_seqnum(queue_file, &seqnum) < 0)
+ break;
+ snprintf(seqnum_str, sizeof(seqnum_str), "%llu", seqnum);
+
+ s = syspath;
+ l = strpcpy(&s, sizeof(syspath), "/sys");
+ len = udev_queue_read_devpath(queue_file, s, l);
+ if (len < 0)
+ break;
+
+ if (len > 0) {
+ udev_list_entry_add(&udev_queue->queue_list, syspath, seqnum_str);
+ } else {
+ udev_list_entry_foreach(list_entry, udev_list_get_entry(&udev_queue->queue_list)) {
+ if (streq(seqnum_str, udev_list_entry_get_value(list_entry))) {
+ udev_list_entry_delete(list_entry);
+ break;
+ }
+ }
+ }
+ }
+ fclose(queue_file);
+
+ return udev_list_get_entry(&udev_queue->queue_list);
+}
diff --git a/src/libudev/libudev-util.c b/src/libudev/libudev-util.c
new file mode 100644
index 0000000000..714dc50ae9
--- /dev/null
+++ b/src/libudev/libudev-util.c
@@ -0,0 +1,659 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2008-2012 Kay Sievers <kay@vrfy.org>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <unistd.h>
+#include <errno.h>
+#include <string.h>
+#include <dirent.h>
+#include <ctype.h>
+#include <fcntl.h>
+#include <time.h>
+#include <pwd.h>
+#include <grp.h>
+#include <sys/stat.h>
+#include <sys/param.h>
+
+#include "libudev.h"
+#include "libudev-private.h"
+
+/**
+ * SECTION:libudev-util
+ * @short_description: utils
+ *
+ * Utilities useful when dealing with devices and device node names.
+ */
+
+int util_delete_path(struct udev *udev, const char *path)
+{
+ char p[UTIL_PATH_SIZE];
+ char *pos;
+ int err = 0;
+
+ if (path[0] == '/')
+ while(path[1] == '/')
+ path++;
+ strscpy(p, sizeof(p), path);
+ pos = strrchr(p, '/');
+ if (pos == p || pos == NULL)
+ return 0;
+
+ for (;;) {
+ *pos = '\0';
+ pos = strrchr(p, '/');
+
+ /* don't remove the last one */
+ if ((pos == p) || (pos == NULL))
+ break;
+
+ err = rmdir(p);
+ if (err < 0) {
+ if (errno == ENOENT)
+ err = 0;
+ break;
+ }
+ }
+ return err;
+}
+
+uid_t util_lookup_user(struct udev *udev, const char *user)
+{
+ char *endptr;
+ struct passwd pwbuf;
+ struct passwd *pw;
+ uid_t uid;
+ size_t buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
+ char *buf = alloca(buflen);
+
+ if (streq(user, "root"))
+ return 0;
+ uid = strtoul(user, &endptr, 10);
+ if (endptr[0] == '\0')
+ return uid;
+
+ errno = getpwnam_r(user, &pwbuf, buf, buflen, &pw);
+ if (pw != NULL)
+ return pw->pw_uid;
+ if (errno == 0 || errno == ENOENT || errno == ESRCH)
+ udev_err(udev, "specified user '%s' unknown\n", user);
+ else
+ udev_err(udev, "error resolving user '%s': %m\n", user);
+ return 0;
+}
+
+gid_t util_lookup_group(struct udev *udev, const char *group)
+{
+ char *endptr;
+ struct group grbuf;
+ struct group *gr;
+ gid_t gid = 0;
+ size_t buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
+ char *buf = NULL;
+
+ if (streq(group, "root"))
+ return 0;
+ gid = strtoul(group, &endptr, 10);
+ if (endptr[0] == '\0')
+ return gid;
+ gid = 0;
+ for (;;) {
+ char *newbuf;
+
+ newbuf = realloc(buf, buflen);
+ if (!newbuf)
+ break;
+ buf = newbuf;
+ errno = getgrnam_r(group, &grbuf, buf, buflen, &gr);
+ if (gr != NULL) {
+ gid = gr->gr_gid;
+ } else if (errno == ERANGE) {
+ buflen *= 2;
+ continue;
+ } else if (errno == 0 || errno == ENOENT || errno == ESRCH) {
+ udev_err(udev, "specified group '%s' unknown\n", group);
+ } else {
+ udev_err(udev, "error resolving group '%s': %m\n", group);
+ }
+ break;
+ }
+ free(buf);
+ return gid;
+}
+
+/* handle "[<SUBSYSTEM>/<KERNEL>]<attribute>" format */
+int util_resolve_subsys_kernel(struct udev *udev, const char *string,
+ char *result, size_t maxsize, int read_value)
+{
+ char temp[UTIL_PATH_SIZE];
+ char *subsys;
+ char *sysname;
+ struct udev_device *dev;
+ char *attr;
+
+ if (string[0] != '[')
+ return -1;
+
+ strscpy(temp, sizeof(temp), string);
+
+ subsys = &temp[1];
+
+ sysname = strchr(subsys, '/');
+ if (sysname == NULL)
+ return -1;
+ sysname[0] = '\0';
+ sysname = &sysname[1];
+
+ attr = strchr(sysname, ']');
+ if (attr == NULL)
+ return -1;
+ attr[0] = '\0';
+ attr = &attr[1];
+ if (attr[0] == '/')
+ attr = &attr[1];
+ if (attr[0] == '\0')
+ attr = NULL;
+
+ if (read_value && attr == NULL)
+ return -1;
+
+ dev = udev_device_new_from_subsystem_sysname(udev, subsys, sysname);
+ if (dev == NULL)
+ return -1;
+
+ if (read_value) {
+ const char *val;
+
+ val = udev_device_get_sysattr_value(dev, attr);
+ if (val != NULL)
+ strscpy(result, maxsize, val);
+ else
+ result[0] = '\0';
+ udev_dbg(udev, "value '[%s/%s]%s' is '%s'\n", subsys, sysname, attr, result);
+ } else {
+ size_t l;
+ char *s;
+
+ s = result;
+ l = strpcpyl(&s, maxsize, udev_device_get_syspath(dev), NULL);
+ if (attr != NULL)
+ strpcpyl(&s, l, "/", attr, NULL);
+ udev_dbg(udev, "path '[%s/%s]%s' is '%s'\n", subsys, sysname, attr, result);
+ }
+ udev_device_unref(dev);
+ return 0;
+}
+ssize_t util_get_sys_core_link_value(struct udev *udev, const char *slink, const char *syspath, char *value, size_t size)
+{
+ char path[UTIL_PATH_SIZE];
+ char target[UTIL_PATH_SIZE];
+ ssize_t len;
+ const char *pos;
+
+ strscpyl(path, sizeof(path), syspath, "/", slink, NULL);
+ len = readlink(path, target, sizeof(target));
+ if (len <= 0 || len == (ssize_t)sizeof(target))
+ return -1;
+ target[len] = '\0';
+ pos = strrchr(target, '/');
+ if (pos == NULL)
+ return -1;
+ pos = &pos[1];
+ return strscpy(value, size, pos);
+}
+
+int util_resolve_sys_link(struct udev *udev, char *syspath, size_t size)
+{
+ char link_target[UTIL_PATH_SIZE];
+
+ ssize_t len;
+ int i;
+ int back;
+ char *base = NULL;
+
+ len = readlink(syspath, link_target, sizeof(link_target));
+ if (len <= 0 || len == (ssize_t)sizeof(link_target))
+ return -1;
+ link_target[len] = '\0';
+
+ for (back = 0; startswith(&link_target[back * 3], "../"); back++)
+ ;
+ for (i = 0; i <= back; i++) {
+ base = strrchr(syspath, '/');
+ if (base == NULL)
+ return -EINVAL;
+ base[0] = '\0';
+ }
+
+ strscpyl(base, size - (base - syspath), "/", &link_target[back * 3], NULL);
+ return 0;
+}
+
+int util_log_priority(const char *priority)
+{
+ char *endptr;
+ int prio;
+
+ prio = strtol(priority, &endptr, 10);
+ if (endptr[0] == '\0' || isspace(endptr[0]))
+ return prio;
+ if (startswith(priority, "err"))
+ return LOG_ERR;
+ if (startswith(priority, "info"))
+ return LOG_INFO;
+ if (startswith(priority, "debug"))
+ return LOG_DEBUG;
+ return 0;
+}
+
+size_t util_path_encode(const char *src, char *dest, size_t size)
+{
+ size_t i, j;
+
+ for (i = 0, j = 0; src[i] != '\0'; i++) {
+ if (src[i] == '/') {
+ if (j+4 >= size) {
+ j = 0;
+ break;
+ }
+ memcpy(&dest[j], "\\x2f", 4);
+ j += 4;
+ } else if (src[i] == '\\') {
+ if (j+4 >= size) {
+ j = 0;
+ break;
+ }
+ memcpy(&dest[j], "\\x5c", 4);
+ j += 4;
+ } else {
+ if (j+1 >= size) {
+ j = 0;
+ break;
+ }
+ dest[j] = src[i];
+ j++;
+ }
+ }
+ dest[j] = '\0';
+ return j;
+}
+
+void util_remove_trailing_chars(char *path, char c)
+{
+ size_t len;
+
+ if (path == NULL)
+ return;
+ len = strlen(path);
+ while (len > 0 && path[len-1] == c)
+ path[--len] = '\0';
+}
+
+/* count of characters used to encode one unicode char */
+static int utf8_encoded_expected_len(const char *str)
+{
+ unsigned char c = (unsigned char)str[0];
+
+ if (c < 0x80)
+ return 1;
+ if ((c & 0xe0) == 0xc0)
+ return 2;
+ if ((c & 0xf0) == 0xe0)
+ return 3;
+ if ((c & 0xf8) == 0xf0)
+ return 4;
+ if ((c & 0xfc) == 0xf8)
+ return 5;
+ if ((c & 0xfe) == 0xfc)
+ return 6;
+ return 0;
+}
+
+/* decode one unicode char */
+static int utf8_encoded_to_unichar(const char *str)
+{
+ int unichar;
+ int len;
+ int i;
+
+ len = utf8_encoded_expected_len(str);
+ switch (len) {
+ case 1:
+ return (int)str[0];
+ case 2:
+ unichar = str[0] & 0x1f;
+ break;
+ case 3:
+ unichar = (int)str[0] & 0x0f;
+ break;
+ case 4:
+ unichar = (int)str[0] & 0x07;
+ break;
+ case 5:
+ unichar = (int)str[0] & 0x03;
+ break;
+ case 6:
+ unichar = (int)str[0] & 0x01;
+ break;
+ default:
+ return -1;
+ }
+
+ for (i = 1; i < len; i++) {
+ if (((int)str[i] & 0xc0) != 0x80)
+ return -1;
+ unichar <<= 6;
+ unichar |= (int)str[i] & 0x3f;
+ }
+
+ return unichar;
+}
+
+/* expected size used to encode one unicode char */
+static int utf8_unichar_to_encoded_len(int unichar)
+{
+ if (unichar < 0x80)
+ return 1;
+ if (unichar < 0x800)
+ return 2;
+ if (unichar < 0x10000)
+ return 3;
+ if (unichar < 0x200000)
+ return 4;
+ if (unichar < 0x4000000)
+ return 5;
+ return 6;
+}
+
+/* check if unicode char has a valid numeric range */
+static int utf8_unichar_valid_range(int unichar)
+{
+ if (unichar > 0x10ffff)
+ return 0;
+ if ((unichar & 0xfffff800) == 0xd800)
+ return 0;
+ if ((unichar > 0xfdcf) && (unichar < 0xfdf0))
+ return 0;
+ if ((unichar & 0xffff) == 0xffff)
+ return 0;
+ return 1;
+}
+
+/* validate one encoded unicode char and return its length */
+static int utf8_encoded_valid_unichar(const char *str)
+{
+ int len;
+ int unichar;
+ int i;
+
+ len = utf8_encoded_expected_len(str);
+ if (len == 0)
+ return -1;
+
+ /* ascii is valid */
+ if (len == 1)
+ return 1;
+
+ /* check if expected encoded chars are available */
+ for (i = 0; i < len; i++)
+ if ((str[i] & 0x80) != 0x80)
+ return -1;
+
+ unichar = utf8_encoded_to_unichar(str);
+
+ /* check if encoded length matches encoded value */
+ if (utf8_unichar_to_encoded_len(unichar) != len)
+ return -1;
+
+ /* check if value has valid range */
+ if (!utf8_unichar_valid_range(unichar))
+ return -1;
+
+ return len;
+}
+
+int util_replace_whitespace(const char *str, char *to, size_t len)
+{
+ size_t i, j;
+
+ /* strip trailing whitespace */
+ len = strnlen(str, len);
+ while (len && isspace(str[len-1]))
+ len--;
+
+ /* strip leading whitespace */
+ i = 0;
+ while (isspace(str[i]) && (i < len))
+ i++;
+
+ j = 0;
+ while (i < len) {
+ /* substitute multiple whitespace with a single '_' */
+ if (isspace(str[i])) {
+ while (isspace(str[i]))
+ i++;
+ to[j++] = '_';
+ }
+ to[j++] = str[i++];
+ }
+ to[j] = '\0';
+ return 0;
+}
+
+static int is_whitelisted(char c, const char *white)
+{
+ if ((c >= '0' && c <= '9') ||
+ (c >= 'A' && c <= 'Z') ||
+ (c >= 'a' && c <= 'z') ||
+ strchr("#+-.:=@_", c) != NULL ||
+ (white != NULL && strchr(white, c) != NULL))
+ return 1;
+ return 0;
+}
+
+/* allow chars in whitelist, plain ascii, hex-escaping and valid utf8 */
+int util_replace_chars(char *str, const char *white)
+{
+ size_t i = 0;
+ int replaced = 0;
+
+ while (str[i] != '\0') {
+ int len;
+
+ if (is_whitelisted(str[i], white)) {
+ i++;
+ continue;
+ }
+
+ /* accept hex encoding */
+ if (str[i] == '\\' && str[i+1] == 'x') {
+ i += 2;
+ continue;
+ }
+
+ /* accept valid utf8 */
+ len = utf8_encoded_valid_unichar(&str[i]);
+ if (len > 1) {
+ i += len;
+ continue;
+ }
+
+ /* if space is allowed, replace whitespace with ordinary space */
+ if (isspace(str[i]) && white != NULL && strchr(white, ' ') != NULL) {
+ str[i] = ' ';
+ i++;
+ replaced++;
+ continue;
+ }
+
+ /* everything else is replaced with '_' */
+ str[i] = '_';
+ i++;
+ replaced++;
+ }
+ return replaced;
+}
+
+/**
+ * udev_util_encode_string:
+ * @str: input string to be encoded
+ * @str_enc: output string to store the encoded input string
+ * @len: maximum size of the output string, which may be
+ * four times as long as the input string
+ *
+ * Encode all potentially unsafe characters of a string to the
+ * corresponding 2 char hex value prefixed by '\x'.
+ *
+ * Returns: 0 if the entire string was copied, non-zero otherwise.
+ **/
+_public_ int udev_util_encode_string(const char *str, char *str_enc, size_t len)
+{
+ size_t i, j;
+
+ if (str == NULL || str_enc == NULL)
+ return -1;
+
+ for (i = 0, j = 0; str[i] != '\0'; i++) {
+ int seqlen;
+
+ seqlen = utf8_encoded_valid_unichar(&str[i]);
+ if (seqlen > 1) {
+ if (len-j < (size_t)seqlen)
+ goto err;
+ memcpy(&str_enc[j], &str[i], seqlen);
+ j += seqlen;
+ i += (seqlen-1);
+ } else if (str[i] == '\\' || !is_whitelisted(str[i], NULL)) {
+ if (len-j < 4)
+ goto err;
+ sprintf(&str_enc[j], "\\x%02x", (unsigned char) str[i]);
+ j += 4;
+ } else {
+ if (len-j < 1)
+ goto err;
+ str_enc[j] = str[i];
+ j++;
+ }
+ }
+ if (len-j < 1)
+ goto err;
+ str_enc[j] = '\0';
+ return 0;
+err:
+ return -1;
+}
+
+/*
+ * http://sites.google.com/site/murmurhash/
+ *
+ * All code is released to the public domain. For business purposes,
+ * Murmurhash is under the MIT license.
+ *
+ */
+static unsigned int murmur_hash2(const char *key, size_t len, unsigned int seed)
+{
+ /*
+ * 'm' and 'r' are mixing constants generated offline.
+ * They're not really 'magic', they just happen to work well.
+ */
+ const unsigned int m = 0x5bd1e995;
+ const int r = 24;
+
+ /* initialize the hash to a 'random' value */
+ unsigned int h = seed ^ len;
+
+ /* mix 4 bytes at a time into the hash */
+ const unsigned char * data = (const unsigned char *)key;
+
+ while(len >= sizeof(unsigned int)) {
+ unsigned int k;
+
+ memcpy(&k, data, sizeof(k));
+ k *= m;
+ k ^= k >> r;
+ k *= m;
+ h *= m;
+ h ^= k;
+
+ data += sizeof(k);
+ len -= sizeof(k);
+ }
+
+ /* handle the last few bytes of the input array */
+ switch(len) {
+ case 3:
+ h ^= data[2] << 16;
+ case 2:
+ h ^= data[1] << 8;
+ case 1:
+ h ^= data[0];
+ h *= m;
+ };
+
+ /* do a few final mixes of the hash to ensure the last few bytes are well-incorporated */
+ h ^= h >> 13;
+ h *= m;
+ h ^= h >> 15;
+
+ return h;
+}
+
+unsigned int util_string_hash32(const char *str)
+{
+ return murmur_hash2(str, strlen(str), 0);
+}
+
+/* get a bunch of bit numbers out of the hash, and set the bits in our bit field */
+uint64_t util_string_bloom64(const char *str)
+{
+ uint64_t bits = 0;
+ unsigned int hash = util_string_hash32(str);
+
+ bits |= 1LLU << (hash & 63);
+ bits |= 1LLU << ((hash >> 6) & 63);
+ bits |= 1LLU << ((hash >> 12) & 63);
+ bits |= 1LLU << ((hash >> 18) & 63);
+ return bits;
+}
+
+ssize_t print_kmsg(const char *fmt, ...)
+{
+ int fd;
+ va_list ap;
+ char text[1024];
+ ssize_t len;
+ ssize_t ret;
+
+ fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
+ if (fd < 0)
+ return -errno;
+
+ len = snprintf(text, sizeof(text), "<30>systemd-udevd[%u]: ", getpid());
+
+ va_start(ap, fmt);
+ len += vsnprintf(text + len, sizeof(text) - len, fmt, ap);
+ va_end(ap);
+
+ ret = write(fd, text, len);
+ if (ret < 0)
+ ret = -errno;
+ close(fd);
+ return ret;
+}
diff --git a/src/libudev/libudev.c b/src/libudev/libudev.c
new file mode 100644
index 0000000000..208039a1b2
--- /dev/null
+++ b/src/libudev/libudev.c
@@ -0,0 +1,314 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2008-2012 Kay Sievers <kay@vrfy.org>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <stdarg.h>
+#include <unistd.h>
+#include <errno.h>
+#include <string.h>
+#include <ctype.h>
+#include <time.h>
+
+#include "libudev.h"
+#include "libudev-private.h"
+#include "missing.h"
+
+/**
+ * SECTION:libudev
+ * @short_description: libudev context
+ *
+ * The context contains the default values read from the udev config file,
+ * and is passed to all library operations.
+ */
+
+/**
+ * udev:
+ *
+ * Opaque object representing the library context.
+ */
+struct udev {
+ int refcount;
+ void (*log_fn)(struct udev *udev,
+ int priority, const char *file, int line, const char *fn,
+ const char *format, va_list args);
+ void *userdata;
+ struct udev_list properties_list;
+ int log_priority;
+};
+
+void udev_log(struct udev *udev,
+ int priority, const char *file, int line, const char *fn,
+ const char *format, ...)
+{
+ va_list args;
+
+ va_start(args, format);
+ udev->log_fn(udev, priority, file, line, fn, format, args);
+ va_end(args);
+}
+
+static void log_stderr(struct udev *udev,
+ int priority, const char *file, int line, const char *fn,
+ const char *format, va_list args)
+{
+ fprintf(stderr, "libudev: %s: ", fn);
+ vfprintf(stderr, format, args);
+}
+
+/**
+ * udev_get_userdata:
+ * @udev: udev library context
+ *
+ * Retrieve stored data pointer from library context. This might be useful
+ * to access from callbacks like a custom logging function.
+ *
+ * Returns: stored userdata
+ **/
+_public_ void *udev_get_userdata(struct udev *udev)
+{
+ if (udev == NULL)
+ return NULL;
+ return udev->userdata;
+}
+
+/**
+ * udev_set_userdata:
+ * @udev: udev library context
+ * @userdata: data pointer
+ *
+ * Store custom @userdata in the library context.
+ **/
+_public_ void udev_set_userdata(struct udev *udev, void *userdata)
+{
+ if (udev == NULL)
+ return;
+ udev->userdata = userdata;
+}
+
+/**
+ * udev_new:
+ *
+ * Create udev library context. This reads the udev configuration
+ * file, and fills in the default values.
+ *
+ * The initial refcount is 1, and needs to be decremented to
+ * release the resources of the udev library context.
+ *
+ * Returns: a new udev library context
+ **/
+_public_ struct udev *udev_new(void)
+{
+ struct udev *udev;
+ const char *env;
+ FILE *f;
+
+ udev = calloc(1, sizeof(struct udev));
+ if (udev == NULL)
+ return NULL;
+ udev->refcount = 1;
+ udev->log_fn = log_stderr;
+ udev->log_priority = LOG_ERR;
+ udev_list_init(udev, &udev->properties_list, true);
+
+ f = fopen("/etc/udev/udev.conf", "re");
+ if (f != NULL) {
+ char line[UTIL_LINE_SIZE];
+ int line_nr = 0;
+
+ while (fgets(line, sizeof(line), f)) {
+ size_t len;
+ char *key;
+ char *val;
+
+ line_nr++;
+
+ /* find key */
+ key = line;
+ while (isspace(key[0]))
+ key++;
+
+ /* comment or empty line */
+ if (key[0] == '#' || key[0] == '\0')
+ continue;
+
+ /* split key/value */
+ val = strchr(key, '=');
+ if (val == NULL) {
+ udev_err(udev, "missing <key>=<value> in /etc/udev/udev.conf[%i]; skip line\n", line_nr);
+ continue;
+ }
+ val[0] = '\0';
+ val++;
+
+ /* find value */
+ while (isspace(val[0]))
+ val++;
+
+ /* terminate key */
+ len = strlen(key);
+ if (len == 0)
+ continue;
+ while (isspace(key[len-1]))
+ len--;
+ key[len] = '\0';
+
+ /* terminate value */
+ len = strlen(val);
+ if (len == 0)
+ continue;
+ while (isspace(val[len-1]))
+ len--;
+ val[len] = '\0';
+
+ if (len == 0)
+ continue;
+
+ /* unquote */
+ if (val[0] == '"' || val[0] == '\'') {
+ if (val[len-1] != val[0]) {
+ udev_err(udev, "inconsistent quoting in /etc/udev/udev.conf[%i]; skip line\n", line_nr);
+ continue;
+ }
+ val[len-1] = '\0';
+ val++;
+ }
+
+ if (streq(key, "udev_log")) {
+ udev_set_log_priority(udev, util_log_priority(val));
+ continue;
+ }
+ }
+ fclose(f);
+ }
+
+ /* environment overrides config */
+ env = secure_getenv("UDEV_LOG");
+ if (env != NULL)
+ udev_set_log_priority(udev, util_log_priority(env));
+
+ return udev;
+}
+
+/**
+ * udev_ref:
+ * @udev: udev library context
+ *
+ * Take a reference of the udev library context.
+ *
+ * Returns: the passed udev library context
+ **/
+_public_ struct udev *udev_ref(struct udev *udev)
+{
+ if (udev == NULL)
+ return NULL;
+ udev->refcount++;
+ return udev;
+}
+
+/**
+ * udev_unref:
+ * @udev: udev library context
+ *
+ * Drop a reference of the udev library context. If the refcount
+ * reaches zero, the resources of the context will be released.
+ *
+ * Returns: the passed udev library context if it has still an active reference, or #NULL otherwise.
+ **/
+_public_ struct udev *udev_unref(struct udev *udev)
+{
+ if (udev == NULL)
+ return NULL;
+ udev->refcount--;
+ if (udev->refcount > 0)
+ return udev;
+ udev_list_cleanup(&udev->properties_list);
+ free(udev);
+ return NULL;
+}
+
+/**
+ * udev_set_log_fn:
+ * @udev: udev library context
+ * @log_fn: function to be called for logging messages
+ *
+ * The built-in logging writes to stderr. It can be
+ * overridden by a custom function, to plug log messages
+ * into the users' logging functionality.
+ *
+ **/
+_public_ void udev_set_log_fn(struct udev *udev,
+ void (*log_fn)(struct udev *udev,
+ int priority, const char *file, int line, const char *fn,
+ const char *format, va_list args))
+{
+ udev->log_fn = log_fn;
+ udev_dbg(udev, "custom logging function %p registered\n", log_fn);
+}
+
+/**
+ * udev_get_log_priority:
+ * @udev: udev library context
+ *
+ * The initial logging priority is read from the udev config file
+ * at startup.
+ *
+ * Returns: the current logging priority
+ **/
+_public_ int udev_get_log_priority(struct udev *udev)
+{
+ return udev->log_priority;
+}
+
+/**
+ * udev_set_log_priority:
+ * @udev: udev library context
+ * @priority: the new logging priority
+ *
+ * Set the current logging priority. The value controls which messages
+ * are logged.
+ **/
+_public_ void udev_set_log_priority(struct udev *udev, int priority)
+{
+ char num[32];
+
+ udev->log_priority = priority;
+ snprintf(num, sizeof(num), "%u", udev->log_priority);
+ udev_add_property(udev, "UDEV_LOG", num);
+}
+
+struct udev_list_entry *udev_add_property(struct udev *udev, const char *key, const char *value)
+{
+ if (value == NULL) {
+ struct udev_list_entry *list_entry;
+
+ list_entry = udev_get_properties_list_entry(udev);
+ list_entry = udev_list_entry_get_by_name(list_entry, key);
+ if (list_entry != NULL)
+ udev_list_entry_delete(list_entry);
+ return NULL;
+ }
+ return udev_list_entry_add(&udev->properties_list, key, value);
+}
+
+struct udev_list_entry *udev_get_properties_list_entry(struct udev *udev)
+{
+ return udev_list_get_entry(&udev->properties_list);
+}
diff --git a/src/libudev/libudev.h b/src/libudev/libudev.h
new file mode 100644
index 0000000000..61567b1d67
--- /dev/null
+++ b/src/libudev/libudev.h
@@ -0,0 +1,205 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2008-2012 Kay Sievers <kay@vrfy.org>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#ifndef _LIBUDEV_H_
+#define _LIBUDEV_H_
+
+#include <stdarg.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * udev - library context
+ *
+ * reads the udev config and system environment
+ * allows custom logging
+ */
+struct udev;
+struct udev *udev_ref(struct udev *udev);
+struct udev *udev_unref(struct udev *udev);
+struct udev *udev_new(void);
+void udev_set_log_fn(struct udev *udev,
+ void (*log_fn)(struct udev *udev,
+ int priority, const char *file, int line, const char *fn,
+ const char *format, va_list args));
+int udev_get_log_priority(struct udev *udev);
+void udev_set_log_priority(struct udev *udev, int priority);
+void *udev_get_userdata(struct udev *udev);
+void udev_set_userdata(struct udev *udev, void *userdata);
+
+/*
+ * udev_list
+ *
+ * access to libudev generated lists
+ */
+struct udev_list_entry;
+struct udev_list_entry *udev_list_entry_get_next(struct udev_list_entry *list_entry);
+struct udev_list_entry *udev_list_entry_get_by_name(struct udev_list_entry *list_entry, const char *name);
+const char *udev_list_entry_get_name(struct udev_list_entry *list_entry);
+const char *udev_list_entry_get_value(struct udev_list_entry *list_entry);
+/**
+ * udev_list_entry_foreach:
+ * @list_entry: entry to store the current position
+ * @first_entry: first entry to start with
+ *
+ * Helper to iterate over all entries of a list.
+ */
+#define udev_list_entry_foreach(list_entry, first_entry) \
+ for (list_entry = first_entry; \
+ list_entry != NULL; \
+ list_entry = udev_list_entry_get_next(list_entry))
+
+/*
+ * udev_device
+ *
+ * access to sysfs/kernel devices
+ */
+struct udev_device;
+struct udev_device *udev_device_ref(struct udev_device *udev_device);
+struct udev_device *udev_device_unref(struct udev_device *udev_device);
+struct udev *udev_device_get_udev(struct udev_device *udev_device);
+struct udev_device *udev_device_new_from_syspath(struct udev *udev, const char *syspath);
+struct udev_device *udev_device_new_from_devnum(struct udev *udev, char type, dev_t devnum);
+struct udev_device *udev_device_new_from_subsystem_sysname(struct udev *udev, const char *subsystem, const char *sysname);
+struct udev_device *udev_device_new_from_device_id(struct udev *udev, char *id);
+struct udev_device *udev_device_new_from_environment(struct udev *udev);
+/* udev_device_get_parent_*() does not take a reference on the returned device, it is automatically unref'd with the parent */
+struct udev_device *udev_device_get_parent(struct udev_device *udev_device);
+struct udev_device *udev_device_get_parent_with_subsystem_devtype(struct udev_device *udev_device,
+ const char *subsystem, const char *devtype);
+/* retrieve device properties */
+const char *udev_device_get_devpath(struct udev_device *udev_device);
+const char *udev_device_get_subsystem(struct udev_device *udev_device);
+const char *udev_device_get_devtype(struct udev_device *udev_device);
+const char *udev_device_get_syspath(struct udev_device *udev_device);
+const char *udev_device_get_sysname(struct udev_device *udev_device);
+const char *udev_device_get_sysnum(struct udev_device *udev_device);
+const char *udev_device_get_devnode(struct udev_device *udev_device);
+int udev_device_get_is_initialized(struct udev_device *udev_device);
+struct udev_list_entry *udev_device_get_devlinks_list_entry(struct udev_device *udev_device);
+struct udev_list_entry *udev_device_get_properties_list_entry(struct udev_device *udev_device);
+struct udev_list_entry *udev_device_get_tags_list_entry(struct udev_device *udev_device);
+struct udev_list_entry *udev_device_get_sysattr_list_entry(struct udev_device *udev_device);
+const char *udev_device_get_property_value(struct udev_device *udev_device, const char *key);
+const char *udev_device_get_driver(struct udev_device *udev_device);
+dev_t udev_device_get_devnum(struct udev_device *udev_device);
+const char *udev_device_get_action(struct udev_device *udev_device);
+unsigned long long int udev_device_get_seqnum(struct udev_device *udev_device);
+unsigned long long int udev_device_get_usec_since_initialized(struct udev_device *udev_device);
+const char *udev_device_get_sysattr_value(struct udev_device *udev_device, const char *sysattr);
+int udev_device_set_sysattr_value(struct udev_device *udev_device, const char *sysattr, char *value);
+int udev_device_has_tag(struct udev_device *udev_device, const char *tag);
+
+/*
+ * udev_monitor
+ *
+ * access to kernel uevents and udev events
+ */
+struct udev_monitor;
+struct udev_monitor *udev_monitor_ref(struct udev_monitor *udev_monitor);
+struct udev_monitor *udev_monitor_unref(struct udev_monitor *udev_monitor);
+struct udev *udev_monitor_get_udev(struct udev_monitor *udev_monitor);
+/* kernel and udev generated events over netlink */
+struct udev_monitor *udev_monitor_new_from_netlink(struct udev *udev, const char *name);
+/* bind socket */
+int udev_monitor_enable_receiving(struct udev_monitor *udev_monitor);
+int udev_monitor_set_receive_buffer_size(struct udev_monitor *udev_monitor, int size);
+int udev_monitor_get_fd(struct udev_monitor *udev_monitor);
+struct udev_device *udev_monitor_receive_device(struct udev_monitor *udev_monitor);
+/* in-kernel socket filters to select messages that get delivered to a listener */
+int udev_monitor_filter_add_match_subsystem_devtype(struct udev_monitor *udev_monitor,
+ const char *subsystem, const char *devtype);
+int udev_monitor_filter_add_match_tag(struct udev_monitor *udev_monitor, const char *tag);
+int udev_monitor_filter_update(struct udev_monitor *udev_monitor);
+int udev_monitor_filter_remove(struct udev_monitor *udev_monitor);
+
+/*
+ * udev_enumerate
+ *
+ * search sysfs for specific devices and provide a sorted list
+ */
+struct udev_enumerate;
+struct udev_enumerate *udev_enumerate_ref(struct udev_enumerate *udev_enumerate);
+struct udev_enumerate *udev_enumerate_unref(struct udev_enumerate *udev_enumerate);
+struct udev *udev_enumerate_get_udev(struct udev_enumerate *udev_enumerate);
+struct udev_enumerate *udev_enumerate_new(struct udev *udev);
+/* device properties filter */
+int udev_enumerate_add_match_subsystem(struct udev_enumerate *udev_enumerate, const char *subsystem);
+int udev_enumerate_add_nomatch_subsystem(struct udev_enumerate *udev_enumerate, const char *subsystem);
+int udev_enumerate_add_match_sysattr(struct udev_enumerate *udev_enumerate, const char *sysattr, const char *value);
+int udev_enumerate_add_nomatch_sysattr(struct udev_enumerate *udev_enumerate, const char *sysattr, const char *value);
+int udev_enumerate_add_match_property(struct udev_enumerate *udev_enumerate, const char *property, const char *value);
+int udev_enumerate_add_match_sysname(struct udev_enumerate *udev_enumerate, const char *sysname);
+int udev_enumerate_add_match_tag(struct udev_enumerate *udev_enumerate, const char *tag);
+int udev_enumerate_add_match_parent(struct udev_enumerate *udev_enumerate, struct udev_device *parent);
+int udev_enumerate_add_match_is_initialized(struct udev_enumerate *udev_enumerate);
+int udev_enumerate_add_syspath(struct udev_enumerate *udev_enumerate, const char *syspath);
+/* run enumeration with active filters */
+int udev_enumerate_scan_devices(struct udev_enumerate *udev_enumerate);
+int udev_enumerate_scan_subsystems(struct udev_enumerate *udev_enumerate);
+/* return device list */
+struct udev_list_entry *udev_enumerate_get_list_entry(struct udev_enumerate *udev_enumerate);
+
+/*
+ * udev_queue
+ *
+ * access to the currently running udev events
+ */
+struct udev_queue;
+struct udev_queue *udev_queue_ref(struct udev_queue *udev_queue);
+struct udev_queue *udev_queue_unref(struct udev_queue *udev_queue);
+struct udev *udev_queue_get_udev(struct udev_queue *udev_queue);
+struct udev_queue *udev_queue_new(struct udev *udev);
+unsigned long long int udev_queue_get_kernel_seqnum(struct udev_queue *udev_queue);
+unsigned long long int udev_queue_get_udev_seqnum(struct udev_queue *udev_queue);
+int udev_queue_get_udev_is_active(struct udev_queue *udev_queue);
+int udev_queue_get_queue_is_empty(struct udev_queue *udev_queue);
+int udev_queue_get_seqnum_is_finished(struct udev_queue *udev_queue, unsigned long long int seqnum);
+int udev_queue_get_seqnum_sequence_is_finished(struct udev_queue *udev_queue,
+ unsigned long long int start, unsigned long long int end);
+struct udev_list_entry *udev_queue_get_queued_list_entry(struct udev_queue *udev_queue);
+
+/*
+ * udev_hwdb
+ *
+ * access to the static hardware properties database
+ */
+struct udev_hwdb;
+struct udev_hwdb *udev_hwdb_new(struct udev *udev);
+struct udev_hwdb *udev_hwdb_ref(struct udev_hwdb *hwdb);
+struct udev_hwdb *udev_hwdb_unref(struct udev_hwdb *hwdb);
+struct udev_list_entry *udev_hwdb_get_properties_list_entry(struct udev_hwdb *hwdb, const char *modalias, unsigned int flags);
+
+/*
+ * udev_util
+ *
+ * udev specific utilities
+ */
+int udev_util_encode_string(const char *str, char *str_enc, size_t len);
+
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif
diff --git a/src/libudev/libudev.pc.in b/src/libudev/libudev.pc.in
new file mode 100644
index 0000000000..2b183e9dc7
--- /dev/null
+++ b/src/libudev/libudev.pc.in
@@ -0,0 +1,18 @@
+# This file is part of systemd.
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 of the License, or
+# (at your option) any later version.
+
+prefix=@prefix@
+exec_prefix=@exec_prefix@
+libdir=@libdir@
+includedir=@includedir@
+
+Name: libudev
+Description: Library to access udev device information
+Version: @VERSION@
+Libs: -L${libdir} -ludev
+Libs.private: -lrt
+Cflags: -I${includedir}
diff --git a/src/libudev/libudev.sym b/src/libudev/libudev.sym
new file mode 100644
index 0000000000..8e09430aec
--- /dev/null
+++ b/src/libudev/libudev.sym
@@ -0,0 +1,113 @@
+/***
+ This file is part of systemd.
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+***/
+
+LIBUDEV_183 {
+global:
+ udev_device_get_action;
+ udev_device_get_devlinks_list_entry;
+ udev_device_get_devnode;
+ udev_device_get_devnum;
+ udev_device_get_devpath;
+ udev_device_get_devtype;
+ udev_device_get_driver;
+ udev_device_get_is_initialized;
+ udev_device_get_parent;
+ udev_device_get_parent_with_subsystem_devtype;
+ udev_device_get_properties_list_entry;
+ udev_device_get_property_value;
+ udev_device_get_seqnum;
+ udev_device_get_subsystem;
+ udev_device_get_sysattr_list_entry;
+ udev_device_get_sysattr_value;
+ udev_device_get_sysname;
+ udev_device_get_sysnum;
+ udev_device_get_syspath;
+ udev_device_get_tags_list_entry;
+ udev_device_get_udev;
+ udev_device_get_usec_since_initialized;
+ udev_device_has_tag;
+ udev_device_new_from_devnum;
+ udev_device_new_from_environment;
+ udev_device_new_from_subsystem_sysname;
+ udev_device_new_from_syspath;
+ udev_device_ref;
+ udev_device_unref;
+ udev_enumerate_add_match_is_initialized;
+ udev_enumerate_add_match_parent;
+ udev_enumerate_add_match_property;
+ udev_enumerate_add_match_subsystem;
+ udev_enumerate_add_match_sysattr;
+ udev_enumerate_add_match_sysname;
+ udev_enumerate_add_match_tag;
+ udev_enumerate_add_nomatch_subsystem;
+ udev_enumerate_add_nomatch_sysattr;
+ udev_enumerate_add_syspath;
+ udev_enumerate_get_list_entry;
+ udev_enumerate_get_udev;
+ udev_enumerate_new;
+ udev_enumerate_ref;
+ udev_enumerate_scan_devices;
+ udev_enumerate_scan_subsystems;
+ udev_enumerate_unref;
+ udev_get_log_priority;
+ udev_get_userdata;
+ udev_list_entry_get_by_name;
+ udev_list_entry_get_name;
+ udev_list_entry_get_next;
+ udev_list_entry_get_value;
+ udev_monitor_enable_receiving;
+ udev_monitor_filter_add_match_subsystem_devtype;
+ udev_monitor_filter_add_match_tag;
+ udev_monitor_filter_remove;
+ udev_monitor_filter_update;
+ udev_monitor_get_fd;
+ udev_monitor_get_udev;
+ udev_monitor_new_from_netlink;
+ udev_monitor_receive_device;
+ udev_monitor_ref;
+ udev_monitor_set_receive_buffer_size;
+ udev_monitor_unref;
+ udev_new;
+ udev_queue_get_kernel_seqnum;
+ udev_queue_get_queue_is_empty;
+ udev_queue_get_queued_list_entry;
+ udev_queue_get_seqnum_is_finished;
+ udev_queue_get_seqnum_sequence_is_finished;
+ udev_queue_get_udev;
+ udev_queue_get_udev_is_active;
+ udev_queue_get_udev_seqnum;
+ udev_queue_new;
+ udev_queue_ref;
+ udev_queue_unref;
+ udev_ref;
+ udev_set_log_fn;
+ udev_set_log_priority;
+ udev_set_userdata;
+ udev_unref;
+ udev_util_encode_string;
+local:
+ *;
+};
+
+LIBUDEV_189 {
+global:
+ udev_device_new_from_device_id;
+} LIBUDEV_183;
+
+LIBUDEV_196 {
+global:
+ udev_hwdb_new;
+ udev_hwdb_ref;
+ udev_hwdb_unref;
+ udev_hwdb_get_properties_list_entry;
+} LIBUDEV_189;
+
+LIBUDEV_199 {
+ udev_device_set_sysattr_value;
+} LIBUDEV_196;
diff --git a/src/locale/kbd-model-map b/src/locale/kbd-model-map
new file mode 100644
index 0000000000..1fe9bca6ce
--- /dev/null
+++ b/src/locale/kbd-model-map
@@ -0,0 +1,77 @@
+# Generated from system-config-keyboard's model list
+# consolelayout xlayout xmodel xvariant xoptions
+sg ch pc105 de_nodeadkeys terminate:ctrl_alt_bksp
+nl nl pc105 - terminate:ctrl_alt_bksp
+mk-utf mk,us pc105 - terminate:ctrl_alt_bksp,grp:shifts_toggle,grp_led:scroll
+trq tr pc105 - terminate:ctrl_alt_bksp
+guj in,us pc105 guj terminate:ctrl_alt_bksp,grp:shifts_toggle,grp_led:scroll
+uk gb pc105 - terminate:ctrl_alt_bksp
+is-latin1 is pc105 - terminate:ctrl_alt_bksp
+de de pc105 - terminate:ctrl_alt_bksp
+gur gur,us pc105 - terminate:ctrl_alt_bksp,grp:shifts_toggle,grp_led:scroll
+la-latin1 latam pc105 - terminate:ctrl_alt_bksp
+us us pc105+inet - terminate:ctrl_alt_bksp
+ko kr pc105 - terminate:ctrl_alt_bksp
+ro-std ro pc105 std terminate:ctrl_alt_bksp
+de-latin1 de pc105 - terminate:ctrl_alt_bksp
+tml-inscript in,us pc105 tam terminate:ctrl_alt_bksp,grp:shifts_toggle,grp_led:scroll
+slovene si pc105 - terminate:ctrl_alt_bksp
+hu101 hu pc105 qwerty terminate:ctrl_alt_bksp
+jp106 jp jp106 - terminate:ctrl_alt_bksp
+croat hr pc105 - terminate:ctrl_alt_bksp
+ben-probhat in,us pc105 ben_probhat terminate:ctrl_alt_bksp,grp:shifts_toggle,grp_led:scroll
+fi-latin1 fi pc105 - terminate:ctrl_alt_bksp
+it2 it pc105 - terminate:ctrl_alt_bksp
+hu hu pc105 - terminate:ctrl_alt_bksp
+sr-latin rs pc105 latin terminate:ctrl_alt_bksp
+fi fi pc105 - terminate:ctrl_alt_bksp
+fr_CH ch pc105 fr terminate:ctrl_alt_bksp
+dk-latin1 dk pc105 - terminate:ctrl_alt_bksp
+fr fr pc105 - terminate:ctrl_alt_bksp
+it it pc105 - terminate:ctrl_alt_bksp
+tml-uni in,us pc105 tam_TAB terminate:ctrl_alt_bksp,grp:shifts_toggle,grp_led:scroll
+ua-utf ua,us pc105 - terminate:ctrl_alt_bksp,grp:shifts_toggle,grp_led:scroll
+fr-latin1 fr pc105 - terminate:ctrl_alt_bksp
+sg-latin1 ch pc105 de_nodeadkeys terminate:ctrl_alt_bksp
+be-latin1 be pc105 - terminate:ctrl_alt_bksp
+dk dk pc105 - terminate:ctrl_alt_bksp
+fr-pc fr pc105 - terminate:ctrl_alt_bksp
+bg_pho-utf8 bg,us pc105 ,phonetic terminate:ctrl_alt_bksp,grp:shifts_toggle,grp_led:scroll
+it-ibm it pc105 - terminate:ctrl_alt_bksp
+cz-us-qwertz cz,us pc105 - terminate:ctrl_alt_bksp,grp:shifts_toggle,grp_led:scroll
+ar-digits ara,us pc105 digits terminate:ctrl_alt_bksp,grp:shifts_toggle,grp_led:scroll
+br-abnt2 br abnt2 - terminate:ctrl_alt_bksp
+ro ro pc105 - terminate:ctrl_alt_bksp
+us-acentos us pc105 intl terminate:ctrl_alt_bksp
+pt-latin1 pt pc105 - terminate:ctrl_alt_bksp
+ro-std-cedilla ro pc105 std_cedilla terminate:ctrl_alt_bksp
+tj tj pc105 - terminate:ctrl_alt_bksp
+ar-qwerty ara,us pc105 qwerty terminate:ctrl_alt_bksp,grp:shifts_toggle,grp_led:scroll
+ar-azerty-digits ara,us pc105 azerty_digits terminate:ctrl_alt_bksp,grp:shifts_toggle,grp_led:scroll
+ben in,us pc105 ben terminate:ctrl_alt_bksp,grp:shifts_toggle,grp_led:scroll
+de-latin1-nodeadkeys de pc105 nodeadkeys terminate:ctrl_alt_bksp
+no no pc105 - terminate:ctrl_alt_bksp
+bg_bds-utf8 bg,us pc105 - terminate:ctrl_alt_bksp,grp:shifts_toggle,grp_led:scroll
+dvorak us pc105 dvorak terminate:ctrl_alt_bksp
+dvorak us pc105 dvorak-alt-intl terminate:ctrl_alt_bksp
+ru ru,us pc105 - terminate:ctrl_alt_bksp,grp:shifts_toggle,grp_led:scroll
+cz-lat2 cz pc105 qwerty terminate:ctrl_alt_bksp
+pl2 pl pc105 - terminate:ctrl_alt_bksp
+es es pc105 - terminate:ctrl_alt_bksp
+ro-cedilla ro pc105 cedilla terminate:ctrl_alt_bksp
+ie ie pc105 - terminate:ctrl_alt_bksp
+ar-azerty ara,us pc105 azerty terminate:ctrl_alt_bksp,grp:shifts_toggle,grp_led:scroll
+ar-qwerty-digits ara,us pc105 qwerty_digits terminate:ctrl_alt_bksp,grp:shifts_toggle,grp_led:scroll
+et ee pc105 - terminate:ctrl_alt_bksp
+sk-qwerty sk pc105 - terminate:ctrl_alt_bksp,qwerty
+dev dev,us pc105 - terminate:ctrl_alt_bksp,grp:shifts_toggle,grp_led:scroll
+fr-latin9 fr pc105 latin9 terminate:ctrl_alt_bksp
+fr_CH-latin1 ch pc105 fr terminate:ctrl_alt_bksp
+cf ca pc105 - terminate:ctrl_alt_bksp
+sv-latin1 se pc105 - terminate:ctrl_alt_bksp
+sr-cy rs pc105 - terminate:ctrl_alt_bksp
+gr gr,us pc105 - terminate:ctrl_alt_bksp,grp:shifts_toggle,grp_led:scroll
+by by,us pc105 - terminate:ctrl_alt_bksp,grp:shifts_toggle,grp_led:scroll
+il il pc105 - terminate:ctrl_alt_bksp
+kazakh kz,us pc105 - terminate:ctrl_alt_bksp,grp:shifts_toggle,grp_led:scroll
+lt lt pc105 - terminate:ctrl_alt_bksp
diff --git a/src/locale/localectl.c b/src/locale/localectl.c
new file mode 100644
index 0000000000..50250c4b47
--- /dev/null
+++ b/src/locale/localectl.c
@@ -0,0 +1,936 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <locale.h>
+#include <stdlib.h>
+#include <stdbool.h>
+#include <unistd.h>
+#include <getopt.h>
+#include <string.h>
+#include <ftw.h>
+#include <sys/mman.h>
+#include <fcntl.h>
+
+#include "dbus-common.h"
+#include "util.h"
+#include "spawn-polkit-agent.h"
+#include "build.h"
+#include "strv.h"
+#include "pager.h"
+#include "set.h"
+#include "path-util.h"
+#include "utf8.h"
+
+static bool arg_no_pager = false;
+static enum transport {
+ TRANSPORT_NORMAL,
+ TRANSPORT_SSH,
+ TRANSPORT_POLKIT
+} arg_transport = TRANSPORT_NORMAL;
+static bool arg_ask_password = true;
+static const char *arg_host = NULL;
+static bool arg_convert = true;
+
+static void pager_open_if_enabled(void) {
+
+ if (arg_no_pager)
+ return;
+
+ pager_open(false);
+}
+
+static void polkit_agent_open_if_enabled(void) {
+
+ /* Open the polkit agent as a child process if necessary */
+
+ if (!arg_ask_password)
+ return;
+
+ polkit_agent_open();
+}
+
+typedef struct StatusInfo {
+ char **locale;
+ const char *vconsole_keymap;
+ const char *vconsole_keymap_toggle;
+ const char *x11_layout;
+ const char *x11_model;
+ const char *x11_variant;
+ const char *x11_options;
+} StatusInfo;
+
+static void print_status_info(StatusInfo *i) {
+ assert(i);
+
+ if (strv_isempty(i->locale))
+ puts(" System Locale: n/a\n");
+ else {
+ char **j;
+
+ printf(" System Locale: %s\n", i->locale[0]);
+ STRV_FOREACH(j, i->locale + 1)
+ printf(" %s\n", *j);
+ }
+
+ printf(" VC Keymap: %s\n", strna(i->vconsole_keymap));
+ if (!isempty(i->vconsole_keymap_toggle))
+ printf("VC Toggle Keymap: %s\n", i->vconsole_keymap_toggle);
+
+ printf(" X11 Layout: %s\n", strna(i->x11_layout));
+ if (!isempty(i->x11_model))
+ printf(" X11 Model: %s\n", i->x11_model);
+ if (!isempty(i->x11_variant))
+ printf(" X11 Variant: %s\n", i->x11_variant);
+ if (!isempty(i->x11_options))
+ printf(" X11 Options: %s\n", i->x11_options);
+}
+
+static int status_property(const char *name, DBusMessageIter *iter, StatusInfo *i) {
+ int r;
+
+ assert(name);
+ assert(iter);
+
+ switch (dbus_message_iter_get_arg_type(iter)) {
+
+ case DBUS_TYPE_STRING: {
+ const char *s;
+
+ dbus_message_iter_get_basic(iter, &s);
+ if (!isempty(s)) {
+ if (streq(name, "VConsoleKeymap"))
+ i->vconsole_keymap = s;
+ else if (streq(name, "VConsoleKeymapToggle"))
+ i->vconsole_keymap_toggle = s;
+ else if (streq(name, "X11Layout"))
+ i->x11_layout = s;
+ else if (streq(name, "X11Model"))
+ i->x11_model = s;
+ else if (streq(name, "X11Variant"))
+ i->x11_variant = s;
+ else if (streq(name, "X11Options"))
+ i->x11_options = s;
+ }
+ break;
+ }
+
+ case DBUS_TYPE_ARRAY:
+
+ if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
+ char **l;
+
+ r = bus_parse_strv_iter(iter, &l);
+ if (r < 0)
+ return r;
+
+ if (streq(name, "Locale")) {
+ strv_free(i->locale);
+ i->locale = l;
+ l = NULL;
+ }
+
+ strv_free(l);
+ }
+ }
+
+ return 0;
+}
+
+static int show_status(DBusConnection *bus, char **args, unsigned n) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ const char *interface = "";
+ int r;
+ DBusMessageIter iter, sub, sub2, sub3;
+ StatusInfo info = {};
+
+ assert(args);
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.locale1",
+ "/org/freedesktop/locale1",
+ "org.freedesktop.DBus.Properties",
+ "GetAll",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &interface,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+
+ if (!dbus_message_iter_init(reply, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
+ dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_recurse(&iter, &sub);
+
+ while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ const char *name;
+
+ if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_recurse(&sub, &sub2);
+
+ if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_recurse(&sub2, &sub3);
+
+ r = status_property(name, &sub3, &info);
+ if (r < 0) {
+ log_error("Failed to parse reply.");
+ return r;
+ }
+
+ dbus_message_iter_next(&sub);
+ }
+
+ print_status_info(&info);
+ strv_free(info.locale);
+ return 0;
+}
+
+static int set_locale(DBusConnection *bus, char **args, unsigned n) {
+ _cleanup_dbus_message_unref_ DBusMessage *m = NULL, *reply = NULL;
+ dbus_bool_t interactive = true;
+ DBusError error;
+ DBusMessageIter iter;
+ int r;
+
+ assert(bus);
+ assert(args);
+
+ dbus_error_init(&error);
+
+ polkit_agent_open_if_enabled();
+
+ m = dbus_message_new_method_call(
+ "org.freedesktop.locale1",
+ "/org/freedesktop/locale1",
+ "org.freedesktop.locale1",
+ "SetLocale");
+ if (!m)
+ return log_oom();
+
+ dbus_message_iter_init_append(m, &iter);
+
+ r = bus_append_strv_iter(&iter, args + 1);
+ if (r < 0)
+ return log_oom();
+
+ if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &interactive))
+ return log_oom();
+
+ reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
+ if (!reply) {
+ log_error("Failed to issue method call: %s", bus_error_message(&error));
+ r = -EIO;
+ goto finish;
+ }
+
+ r = 0;
+
+finish:
+ dbus_error_free(&error);
+ return r;
+}
+
+static int add_locales_from_archive(Set *locales) {
+ /* Stolen from glibc... */
+
+ struct locarhead {
+ uint32_t magic;
+ /* Serial number. */
+ uint32_t serial;
+ /* Name hash table. */
+ uint32_t namehash_offset;
+ uint32_t namehash_used;
+ uint32_t namehash_size;
+ /* String table. */
+ uint32_t string_offset;
+ uint32_t string_used;
+ uint32_t string_size;
+ /* Table with locale records. */
+ uint32_t locrectab_offset;
+ uint32_t locrectab_used;
+ uint32_t locrectab_size;
+ /* MD5 sum hash table. */
+ uint32_t sumhash_offset;
+ uint32_t sumhash_used;
+ uint32_t sumhash_size;
+ };
+
+ struct namehashent {
+ /* Hash value of the name. */
+ uint32_t hashval;
+ /* Offset of the name in the string table. */
+ uint32_t name_offset;
+ /* Offset of the locale record. */
+ uint32_t locrec_offset;
+ };
+
+ const struct locarhead *h;
+ const struct namehashent *e;
+ const void *p = MAP_FAILED;
+ _cleanup_close_ int fd = -1;
+ size_t sz = 0;
+ struct stat st;
+ unsigned i;
+ int r;
+
+ fd = open("/usr/lib/locale/locale-archive", O_RDONLY|O_NOCTTY|O_CLOEXEC);
+ if (fd < 0) {
+ if (errno != ENOENT)
+ log_error("Failed to open locale archive: %m");
+ r = -errno;
+ goto finish;
+ }
+
+ if (fstat(fd, &st) < 0) {
+ log_error("fstat() failed: %m");
+ r = -errno;
+ goto finish;
+ }
+
+ if (!S_ISREG(st.st_mode)) {
+ log_error("Archive file is not regular");
+ r = -EBADMSG;
+ goto finish;
+ }
+
+ if (st.st_size < (off_t) sizeof(struct locarhead)) {
+ log_error("Archive has invalid size");
+ r = -EBADMSG;
+ goto finish;
+ }
+
+ p = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
+ if (p == MAP_FAILED) {
+ log_error("Failed to map archive: %m");
+ r = -errno;
+ goto finish;
+ }
+
+ h = (const struct locarhead *) p;
+ if (h->magic != 0xde020109 ||
+ h->namehash_offset + h->namehash_size > st.st_size ||
+ h->string_offset + h->string_size > st.st_size ||
+ h->locrectab_offset + h->locrectab_size > st.st_size ||
+ h->sumhash_offset + h->sumhash_size > st.st_size) {
+ log_error("Invalid archive file.");
+ r = -EBADMSG;
+ goto finish;
+ }
+
+ e = (const struct namehashent*) ((const uint8_t*) p + h->namehash_offset);
+ for (i = 0; i < h->namehash_size; i++) {
+ char *z;
+
+ if (e[i].locrec_offset == 0)
+ continue;
+
+ if (!utf8_is_valid((char*) p + e[i].name_offset))
+ continue;
+
+ z = strdup((char*) p + e[i].name_offset);
+ if (!z) {
+ r = log_oom();
+ goto finish;
+ }
+
+ r = set_consume(locales, z);
+ if (r < 0) {
+ log_error("Failed to add locale: %s", strerror(-r));
+ goto finish;
+ }
+ }
+
+ r = 0;
+
+ finish:
+ if (p != MAP_FAILED)
+ munmap((void*) p, sz);
+
+ return r;
+}
+
+static int add_locales_from_libdir (Set *locales) {
+ _cleanup_closedir_ DIR *dir;
+ struct dirent *entry;
+ int r;
+
+ dir = opendir("/usr/lib/locale");
+ if (!dir) {
+ log_error("Failed to open locale directory: %m");
+ return -errno;
+ }
+
+ errno = 0;
+ while ((entry = readdir(dir))) {
+ char *z;
+
+ if (entry->d_type != DT_DIR)
+ continue;
+
+ if (ignore_file(entry->d_name))
+ continue;
+
+ z = strdup(entry->d_name);
+ if (!z)
+ return log_oom();
+
+ r = set_consume(locales, z);
+ if (r < 0 && r != -EEXIST) {
+ log_error("Failed to add locale: %s", strerror(-r));
+ return r;
+ }
+
+ errno = 0;
+ }
+
+ if (errno > 0) {
+ log_error("Failed to read locale directory: %m");
+ return -errno;
+ }
+
+ return 0;
+}
+
+static int list_locales(DBusConnection *bus, char **args, unsigned n) {
+ _cleanup_set_free_ Set *locales;
+ _cleanup_strv_free_ char **l = NULL;
+ int r;
+
+ locales = set_new(string_hash_func, string_compare_func);
+ if (!locales)
+ return log_oom();
+
+ r = add_locales_from_archive(locales);
+ if (r < 0 && r != -ENOENT)
+ return r;
+
+ r = add_locales_from_libdir(locales);
+ if (r < 0)
+ return r;
+
+ l = set_get_strv(locales);
+ if (!l)
+ return log_oom();
+
+ strv_sort(l);
+
+ pager_open_if_enabled();
+
+ strv_print(l);
+
+ return 0;
+}
+
+static int set_vconsole_keymap(DBusConnection *bus, char **args, unsigned n) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ dbus_bool_t interactive = true, b;
+ const char *map, *toggle_map;
+
+ assert(bus);
+ assert(args);
+
+ if (n > 3) {
+ log_error("Too many arguments.");
+ return -EINVAL;
+ }
+
+ polkit_agent_open_if_enabled();
+
+ map = args[1];
+ toggle_map = n > 2 ? args[2] : "";
+ b = arg_convert;
+
+ return bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.locale1",
+ "/org/freedesktop/locale1",
+ "org.freedesktop.locale1",
+ "SetVConsoleKeyboard",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &map,
+ DBUS_TYPE_STRING, &toggle_map,
+ DBUS_TYPE_BOOLEAN, &b,
+ DBUS_TYPE_BOOLEAN, &interactive,
+ DBUS_TYPE_INVALID);
+}
+
+static Set *keymaps = NULL;
+
+static int nftw_cb(
+ const char *fpath,
+ const struct stat *sb,
+ int tflag,
+ struct FTW *ftwbuf) {
+
+ char *p, *e;
+ int r;
+
+ if (tflag != FTW_F)
+ return 0;
+
+ if (!endswith(fpath, ".map") &&
+ !endswith(fpath, ".map.gz"))
+ return 0;
+
+ p = strdup(path_get_file_name(fpath));
+ if (!p)
+ return log_oom();
+
+ e = endswith(p, ".map");
+ if (e)
+ *e = 0;
+
+ e = endswith(p, ".map.gz");
+ if (e)
+ *e = 0;
+
+ r = set_consume(keymaps, p);
+ if (r < 0 && r != -EEXIST) {
+ log_error("Can't add keymap: %s", strerror(-r));
+ return r;
+ }
+
+ return 0;
+}
+
+static int list_vconsole_keymaps(DBusConnection *bus, char **args, unsigned n) {
+ _cleanup_strv_free_ char **l = NULL;
+
+ keymaps = set_new(string_hash_func, string_compare_func);
+ if (!keymaps)
+ return log_oom();
+
+ nftw("/usr/share/kbd/keymaps/", nftw_cb, 20, FTW_MOUNT|FTW_PHYS);
+ nftw("/usr/lib/kbd/keymaps/", nftw_cb, 20, FTW_MOUNT|FTW_PHYS);
+ nftw("/lib/kbd/keymaps/", nftw_cb, 20, FTW_MOUNT|FTW_PHYS);
+
+ l = set_get_strv(keymaps);
+ if (!l) {
+ set_free_free(keymaps);
+ return log_oom();
+ }
+
+ set_free(keymaps);
+
+ if (strv_isempty(l)) {
+ log_error("Couldn't find any console keymaps.");
+ return -ENOENT;
+ }
+
+ strv_sort(l);
+
+ pager_open_if_enabled();
+
+ strv_print(l);
+
+ return 0;
+}
+
+static int set_x11_keymap(DBusConnection *bus, char **args, unsigned n) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ dbus_bool_t interactive = true, b;
+ const char *layout, *model, *variant, *options;
+
+ assert(bus);
+ assert(args);
+
+ if (n > 5) {
+ log_error("Too many arguments.");
+ return -EINVAL;
+ }
+
+ polkit_agent_open_if_enabled();
+
+ layout = args[1];
+ model = n > 2 ? args[2] : "";
+ variant = n > 3 ? args[3] : "";
+ options = n > 4 ? args[4] : "";
+ b = arg_convert;
+
+ return bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.locale1",
+ "/org/freedesktop/locale1",
+ "org.freedesktop.locale1",
+ "SetX11Keyboard",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &layout,
+ DBUS_TYPE_STRING, &model,
+ DBUS_TYPE_STRING, &variant,
+ DBUS_TYPE_STRING, &options,
+ DBUS_TYPE_BOOLEAN, &b,
+ DBUS_TYPE_BOOLEAN, &interactive,
+ DBUS_TYPE_INVALID);
+}
+
+static int list_x11_keymaps(DBusConnection *bus, char **args, unsigned n) {
+ _cleanup_fclose_ FILE *f = NULL;
+ _cleanup_strv_free_ char **list = NULL;
+ char line[LINE_MAX];
+ enum {
+ NONE,
+ MODELS,
+ LAYOUTS,
+ VARIANTS,
+ OPTIONS
+ } state = NONE, look_for;
+ int r;
+
+ if (n > 2) {
+ log_error("Too many arguments.");
+ return -EINVAL;
+ }
+
+ f = fopen("/usr/share/X11/xkb/rules/base.lst", "re");
+ if (!f) {
+ log_error("Failed to open keyboard mapping list. %m");
+ return -errno;
+ }
+
+ if (streq(args[0], "list-x11-keymap-models"))
+ look_for = MODELS;
+ else if (streq(args[0], "list-x11-keymap-layouts"))
+ look_for = LAYOUTS;
+ else if (streq(args[0], "list-x11-keymap-variants"))
+ look_for = VARIANTS;
+ else if (streq(args[0], "list-x11-keymap-options"))
+ look_for = OPTIONS;
+ else
+ assert_not_reached("Wrong parameter");
+
+ FOREACH_LINE(line, f, break) {
+ char *l, *w;
+
+ l = strstrip(line);
+
+ if (isempty(l))
+ continue;
+
+ if (l[0] == '!') {
+ if (startswith(l, "! model"))
+ state = MODELS;
+ else if (startswith(l, "! layout"))
+ state = LAYOUTS;
+ else if (startswith(l, "! variant"))
+ state = VARIANTS;
+ else if (startswith(l, "! option"))
+ state = OPTIONS;
+ else
+ state = NONE;
+
+ continue;
+ }
+
+ if (state != look_for)
+ continue;
+
+ w = l + strcspn(l, WHITESPACE);
+
+ if (n > 1) {
+ char *e;
+
+ if (*w == 0)
+ continue;
+
+ *w = 0;
+ w++;
+ w += strspn(w, WHITESPACE);
+
+ e = strchr(w, ':');
+ if (!e)
+ continue;
+
+ *e = 0;
+
+ if (!streq(w, args[1]))
+ continue;
+ } else
+ *w = 0;
+
+ r = strv_extend(&list, l);
+ if (r < 0)
+ return log_oom();
+ }
+
+ if (strv_isempty(list)) {
+ log_error("Couldn't find any entries.");
+ return -ENOENT;
+ }
+
+ strv_sort(list);
+ strv_uniq(list);
+
+ pager_open_if_enabled();
+
+ strv_print(list);
+ return 0;
+}
+
+static int help(void) {
+
+ printf("%s [OPTIONS...] COMMAND ...\n\n"
+ "Query or change system locale and keyboard settings.\n\n"
+ " -h --help Show this help\n"
+ " --version Show package version\n"
+ " --no-convert Don't convert keyboard mappings\n"
+ " --no-pager Do not pipe output into a pager\n"
+ " --no-ask-password Do not prompt for password\n"
+ " -H --host=[USER@]HOST Operate on remote host\n\n"
+ "Commands:\n"
+ " status Show current locale settings\n"
+ " set-locale LOCALE... Set system locale\n"
+ " list-locales Show known locales\n"
+ " set-keymap MAP [MAP] Set virtual console keyboard mapping\n"
+ " list-keymaps Show known virtual console keyboard mappings\n"
+ " set-x11-keymap LAYOUT [MODEL] [VARIANT] [OPTIONS]\n"
+ " Set X11 keyboard mapping\n"
+ " list-x11-keymap-models Show known X11 keyboard mapping models\n"
+ " list-x11-keymap-layouts Show known X11 keyboard mapping layouts\n"
+ " list-x11-keymap-variants [LAYOUT]\n"
+ " Show known X11 keyboard mapping variants\n"
+ " list-x11-keymap-options Show known X11 keyboard mapping options\n",
+ program_invocation_short_name);
+
+ return 0;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+
+ enum {
+ ARG_VERSION = 0x100,
+ ARG_NO_PAGER,
+ ARG_NO_CONVERT,
+ ARG_NO_ASK_PASSWORD
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "version", no_argument, NULL, ARG_VERSION },
+ { "no-pager", no_argument, NULL, ARG_NO_PAGER },
+ { "host", required_argument, NULL, 'H' },
+ { "privileged", no_argument, NULL, 'P' },
+ { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
+ { "no-convert", no_argument, NULL, ARG_NO_CONVERT },
+ { NULL, 0, NULL, 0 }
+ };
+
+ int c;
+
+ assert(argc >= 0);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "has:H:P", options, NULL)) >= 0) {
+
+ switch (c) {
+
+ case 'h':
+ help();
+ return 0;
+
+ case ARG_VERSION:
+ puts(PACKAGE_STRING);
+ puts(SYSTEMD_FEATURES);
+ return 0;
+
+ case 'P':
+ arg_transport = TRANSPORT_POLKIT;
+ break;
+
+ case 'H':
+ arg_transport = TRANSPORT_SSH;
+ arg_host = optarg;
+ break;
+
+ case ARG_NO_CONVERT:
+ arg_convert = false;
+ break;
+
+ case ARG_NO_PAGER:
+ arg_no_pager = true;
+ break;
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ log_error("Unknown option code %c", c);
+ return -EINVAL;
+ }
+ }
+
+ return 1;
+}
+
+static int localectl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
+
+ static const struct {
+ const char* verb;
+ const enum {
+ MORE,
+ LESS,
+ EQUAL
+ } argc_cmp;
+ const int argc;
+ int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
+ } verbs[] = {
+ { "status", LESS, 1, show_status },
+ { "set-locale", MORE, 2, set_locale },
+ { "list-locales", EQUAL, 1, list_locales },
+ { "set-keymap", MORE, 2, set_vconsole_keymap },
+ { "list-keymaps", EQUAL, 1, list_vconsole_keymaps },
+ { "set-x11-keymap", MORE, 2, set_x11_keymap },
+ { "list-x11-keymap-models", EQUAL, 1, list_x11_keymaps },
+ { "list-x11-keymap-layouts", EQUAL, 1, list_x11_keymaps },
+ { "list-x11-keymap-variants", LESS, 2, list_x11_keymaps },
+ { "list-x11-keymap-options", EQUAL, 1, list_x11_keymaps },
+ };
+
+ int left;
+ unsigned i;
+
+ assert(argc >= 0);
+ assert(argv);
+ assert(error);
+
+ left = argc - optind;
+
+ if (left <= 0)
+ /* Special rule: no arguments means "status" */
+ i = 0;
+ else {
+ if (streq(argv[optind], "help")) {
+ help();
+ return 0;
+ }
+
+ for (i = 0; i < ELEMENTSOF(verbs); i++)
+ if (streq(argv[optind], verbs[i].verb))
+ break;
+
+ if (i >= ELEMENTSOF(verbs)) {
+ log_error("Unknown operation %s", argv[optind]);
+ return -EINVAL;
+ }
+ }
+
+ switch (verbs[i].argc_cmp) {
+
+ case EQUAL:
+ if (left != verbs[i].argc) {
+ log_error("Invalid number of arguments.");
+ return -EINVAL;
+ }
+
+ break;
+
+ case MORE:
+ if (left < verbs[i].argc) {
+ log_error("Too few arguments.");
+ return -EINVAL;
+ }
+
+ break;
+
+ case LESS:
+ if (left > verbs[i].argc) {
+ log_error("Too many arguments.");
+ return -EINVAL;
+ }
+
+ break;
+
+ default:
+ assert_not_reached("Unknown comparison operator.");
+ }
+
+ if (!bus) {
+ log_error("Failed to get D-Bus connection: %s", error->message);
+ return -EIO;
+ }
+
+ return verbs[i].dispatch(bus, argv + optind, left);
+}
+
+int main(int argc, char *argv[]) {
+ int r, retval = EXIT_FAILURE;
+ DBusConnection *bus = NULL;
+ DBusError error;
+
+ dbus_error_init(&error);
+
+ setlocale(LC_ALL, "");
+ log_parse_environment();
+ log_open();
+
+ r = parse_argv(argc, argv);
+ if (r < 0)
+ goto finish;
+ else if (r == 0) {
+ retval = EXIT_SUCCESS;
+ goto finish;
+ }
+
+ if (arg_transport == TRANSPORT_NORMAL)
+ bus = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error);
+ else if (arg_transport == TRANSPORT_POLKIT)
+ bus_connect_system_polkit(&bus, &error);
+ else if (arg_transport == TRANSPORT_SSH)
+ bus_connect_system_ssh(NULL, arg_host, &bus, &error);
+ else
+ assert_not_reached("Uh, invalid transport...");
+
+ r = localectl_main(bus, argc, argv, &error);
+ retval = r < 0 ? EXIT_FAILURE : r;
+
+finish:
+ if (bus) {
+ dbus_connection_flush(bus);
+ dbus_connection_close(bus);
+ dbus_connection_unref(bus);
+ }
+
+ dbus_error_free(&error);
+ dbus_shutdown();
+
+ pager_close();
+
+ return retval;
+}
diff --git a/src/locale/localed.c b/src/locale/localed.c
new file mode 100644
index 0000000000..e160c046a4
--- /dev/null
+++ b/src/locale/localed.c
@@ -0,0 +1,1405 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <dbus/dbus.h>
+
+#include <errno.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "util.h"
+#include "mkdir.h"
+#include "strv.h"
+#include "dbus-common.h"
+#include "polkit.h"
+#include "def.h"
+#include "env-util.h"
+#include "fileio.h"
+#include "fileio-label.h"
+#include "label.h"
+
+#define INTERFACE \
+ " <interface name=\"org.freedesktop.locale1\">\n" \
+ " <property name=\"Locale\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"VConsoleKeymap\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"VConsoleKeymapToggle\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"X11Layout\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"X11Model\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"X11Variant\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"X11Options\" type=\"s\" access=\"read\"/>\n" \
+ " <method name=\"SetLocale\">\n" \
+ " <arg name=\"locale\" type=\"as\" direction=\"in\"/>\n" \
+ " <arg name=\"user_interaction\" type=\"b\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"SetVConsoleKeyboard\">\n" \
+ " <arg name=\"keymap\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"keymap_toggle\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"convert\" type=\"b\" direction=\"in\"/>\n" \
+ " <arg name=\"user_interaction\" type=\"b\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"SetX11Keyboard\">\n" \
+ " <arg name=\"layout\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"model\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"variant\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"options\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"convert\" type=\"b\" direction=\"in\"/>\n" \
+ " <arg name=\"user_interaction\" type=\"b\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " </interface>\n"
+
+#define INTROSPECTION \
+ DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE \
+ "<node>\n" \
+ INTERFACE \
+ BUS_PROPERTIES_INTERFACE \
+ BUS_INTROSPECTABLE_INTERFACE \
+ BUS_PEER_INTERFACE \
+ "</node>\n"
+
+#define INTERFACES_LIST \
+ BUS_GENERIC_INTERFACES_LIST \
+ "org.freedesktop.locale1\0"
+
+const char locale_interface[] _introspect_("locale1") = INTERFACE;
+
+enum {
+ /* We don't list LC_ALL here on purpose. People should be
+ * using LANG instead. */
+
+ PROP_LANG,
+ PROP_LANGUAGE,
+ PROP_LC_CTYPE,
+ PROP_LC_NUMERIC,
+ PROP_LC_TIME,
+ PROP_LC_COLLATE,
+ PROP_LC_MONETARY,
+ PROP_LC_MESSAGES,
+ PROP_LC_PAPER,
+ PROP_LC_NAME,
+ PROP_LC_ADDRESS,
+ PROP_LC_TELEPHONE,
+ PROP_LC_MEASUREMENT,
+ PROP_LC_IDENTIFICATION,
+ _PROP_MAX
+};
+
+static const char * const names[_PROP_MAX] = {
+ [PROP_LANG] = "LANG",
+ [PROP_LANGUAGE] = "LANGUAGE",
+ [PROP_LC_CTYPE] = "LC_CTYPE",
+ [PROP_LC_NUMERIC] = "LC_NUMERIC",
+ [PROP_LC_TIME] = "LC_TIME",
+ [PROP_LC_COLLATE] = "LC_COLLATE",
+ [PROP_LC_MONETARY] = "LC_MONETARY",
+ [PROP_LC_MESSAGES] = "LC_MESSAGES",
+ [PROP_LC_PAPER] = "LC_PAPER",
+ [PROP_LC_NAME] = "LC_NAME",
+ [PROP_LC_ADDRESS] = "LC_ADDRESS",
+ [PROP_LC_TELEPHONE] = "LC_TELEPHONE",
+ [PROP_LC_MEASUREMENT] = "LC_MEASUREMENT",
+ [PROP_LC_IDENTIFICATION] = "LC_IDENTIFICATION"
+};
+
+static char *data[_PROP_MAX] = {};
+
+typedef struct State {
+ char *x11_layout, *x11_model, *x11_variant, *x11_options;
+ char *vc_keymap, *vc_keymap_toggle;
+} State;
+
+static State state;
+
+static usec_t remain_until = 0;
+
+static int free_and_set(char **s, const char *v) {
+ int r;
+ char *t;
+
+ assert(s);
+
+ r = strdup_or_null(isempty(v) ? NULL : v, &t);
+ if (r < 0)
+ return r;
+
+ free(*s);
+ *s = t;
+
+ return 0;
+}
+
+static void free_data_locale(void) {
+ int p;
+
+ for (p = 0; p < _PROP_MAX; p++) {
+ free(data[p]);
+ data[p] = NULL;
+ }
+}
+
+static void free_data_x11(void) {
+ free(state.x11_layout);
+ free(state.x11_model);
+ free(state.x11_variant);
+ free(state.x11_options);
+
+ state.x11_layout = state.x11_model = state.x11_variant = state.x11_options = NULL;
+}
+
+static void free_data_vconsole(void) {
+ free(state.vc_keymap);
+ free(state.vc_keymap_toggle);
+
+ state.vc_keymap = state.vc_keymap_toggle = NULL;
+}
+
+static void simplify(void) {
+ int p;
+
+ for (p = 1; p < _PROP_MAX; p++)
+ if (isempty(data[p]) || streq_ptr(data[PROP_LANG], data[p])) {
+ free(data[p]);
+ data[p] = NULL;
+ }
+}
+
+static int read_data_locale(void) {
+ int r;
+
+ free_data_locale();
+
+ r = parse_env_file("/etc/locale.conf", NEWLINE,
+ "LANG", &data[PROP_LANG],
+ "LANGUAGE", &data[PROP_LANGUAGE],
+ "LC_CTYPE", &data[PROP_LC_CTYPE],
+ "LC_NUMERIC", &data[PROP_LC_NUMERIC],
+ "LC_TIME", &data[PROP_LC_TIME],
+ "LC_COLLATE", &data[PROP_LC_COLLATE],
+ "LC_MONETARY", &data[PROP_LC_MONETARY],
+ "LC_MESSAGES", &data[PROP_LC_MESSAGES],
+ "LC_PAPER", &data[PROP_LC_PAPER],
+ "LC_NAME", &data[PROP_LC_NAME],
+ "LC_ADDRESS", &data[PROP_LC_ADDRESS],
+ "LC_TELEPHONE", &data[PROP_LC_TELEPHONE],
+ "LC_MEASUREMENT", &data[PROP_LC_MEASUREMENT],
+ "LC_IDENTIFICATION", &data[PROP_LC_IDENTIFICATION],
+ NULL);
+
+ if (r == -ENOENT) {
+ int p;
+
+ /* Fill in what we got passed from systemd. */
+
+ for (p = 0; p < _PROP_MAX; p++) {
+ char *e, *d;
+
+ assert(names[p]);
+
+ e = getenv(names[p]);
+ if (e) {
+ d = strdup(e);
+ if (!d)
+ return -ENOMEM;
+ } else
+ d = NULL;
+
+ free(data[p]);
+ data[p] = d;
+ }
+
+ r = 0;
+ }
+
+ simplify();
+ return r;
+}
+
+static void free_data(void) {
+ free_data_locale();
+ free_data_vconsole();
+ free_data_x11();
+}
+
+static int read_data_vconsole(void) {
+ int r;
+
+ free_data_vconsole();
+
+ r = parse_env_file("/etc/vconsole.conf", NEWLINE,
+ "KEYMAP", &state.vc_keymap,
+ "KEYMAP_TOGGLE", &state.vc_keymap_toggle,
+ NULL);
+
+ if (r < 0 && r != -ENOENT)
+ return r;
+
+ return 0;
+}
+
+static int read_data_x11(void) {
+ FILE *f;
+ char line[LINE_MAX];
+ bool in_section = false;
+
+ free_data_x11();
+
+ f = fopen("/etc/X11/xorg.conf.d/00-keyboard.conf", "re");
+ if (!f)
+ return errno == ENOENT ? 0 : -errno;
+
+ while (fgets(line, sizeof(line), f)) {
+ char *l;
+
+ char_array_0(line);
+ l = strstrip(line);
+
+ if (l[0] == 0 || l[0] == '#')
+ continue;
+
+ if (in_section && first_word(l, "Option")) {
+ char **a;
+
+ a = strv_split_quoted(l);
+ if (!a) {
+ fclose(f);
+ return -ENOMEM;
+ }
+
+ if (strv_length(a) == 3) {
+
+ if (streq(a[1], "XkbLayout")) {
+ free(state.x11_layout);
+ state.x11_layout = a[2];
+ a[2] = NULL;
+ } else if (streq(a[1], "XkbModel")) {
+ free(state.x11_model);
+ state.x11_model = a[2];
+ a[2] = NULL;
+ } else if (streq(a[1], "XkbVariant")) {
+ free(state.x11_variant);
+ state.x11_variant = a[2];
+ a[2] = NULL;
+ } else if (streq(a[1], "XkbOptions")) {
+ free(state.x11_options);
+ state.x11_options = a[2];
+ a[2] = NULL;
+ }
+ }
+
+ strv_free(a);
+
+ } else if (!in_section && first_word(l, "Section")) {
+ char **a;
+
+ a = strv_split_quoted(l);
+ if (!a) {
+ fclose(f);
+ return -ENOMEM;
+ }
+
+ if (strv_length(a) == 2 && streq(a[1], "InputClass"))
+ in_section = true;
+
+ strv_free(a);
+ } else if (in_section && first_word(l, "EndSection"))
+ in_section = false;
+ }
+
+ fclose(f);
+
+ return 0;
+}
+
+static int read_data(void) {
+ int r, q, p;
+
+ r = read_data_locale();
+ q = read_data_vconsole();
+ p = read_data_x11();
+
+ return r < 0 ? r : q < 0 ? q : p;
+}
+
+static int write_data_locale(void) {
+ int r, p;
+ char **l = NULL;
+
+ r = load_env_file("/etc/locale.conf", NULL, &l);
+ if (r < 0 && r != -ENOENT)
+ return r;
+
+ for (p = 0; p < _PROP_MAX; p++) {
+ char *t, **u;
+
+ assert(names[p]);
+
+ if (isempty(data[p])) {
+ l = strv_env_unset(l, names[p]);
+ continue;
+ }
+
+ if (asprintf(&t, "%s=%s", names[p], data[p]) < 0) {
+ strv_free(l);
+ return -ENOMEM;
+ }
+
+ u = strv_env_set(l, t);
+ free(t);
+ strv_free(l);
+
+ if (!u)
+ return -ENOMEM;
+
+ l = u;
+ }
+
+ if (strv_isempty(l)) {
+ strv_free(l);
+
+ if (unlink("/etc/locale.conf") < 0)
+ return errno == ENOENT ? 0 : -errno;
+
+ return 0;
+ }
+
+ r = write_env_file_label("/etc/locale.conf", l);
+ strv_free(l);
+
+ return r;
+}
+
+static void push_data(DBusConnection *bus) {
+ char **l_set = NULL, **l_unset = NULL, **t;
+ int c_set = 0, c_unset = 0, p;
+ DBusError error;
+ DBusMessage *m = NULL, *reply = NULL;
+ DBusMessageIter iter, sub;
+
+ dbus_error_init(&error);
+
+ assert(bus);
+
+ l_set = new0(char*, _PROP_MAX);
+ l_unset = new0(char*, _PROP_MAX);
+ if (!l_set || !l_unset) {
+ log_oom();
+ goto finish;
+ }
+
+ for (p = 0; p < _PROP_MAX; p++) {
+ assert(names[p]);
+
+ if (isempty(data[p]))
+ l_unset[c_set++] = (char*) names[p];
+ else {
+ char *s;
+
+ if (asprintf(&s, "%s=%s", names[p], data[p]) < 0) {
+ log_oom();
+ goto finish;
+ }
+
+ l_set[c_unset++] = s;
+ }
+ }
+
+ assert(c_set + c_unset == _PROP_MAX);
+ m = dbus_message_new_method_call("org.freedesktop.systemd1", "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager", "UnsetAndSetEnvironment");
+ if (!m) {
+ log_error("Could not allocate message.");
+ goto finish;
+ }
+
+ dbus_message_iter_init_append(m, &iter);
+
+ if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
+ log_oom();
+ goto finish;
+ }
+
+ STRV_FOREACH(t, l_unset)
+ if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, t)) {
+ log_oom();
+ goto finish;
+ }
+
+ if (!dbus_message_iter_close_container(&iter, &sub) ||
+ !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
+ log_oom();
+ goto finish;
+ }
+
+ STRV_FOREACH(t, l_set)
+ if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, t)) {
+ log_oom();
+ goto finish;
+ }
+
+ if (!dbus_message_iter_close_container(&iter, &sub)) {
+ log_oom();
+ goto finish;
+ }
+
+ reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
+ if (!reply) {
+ log_error("Failed to set locale information: %s", bus_error_message(&error));
+ goto finish;
+ }
+
+finish:
+ if (m)
+ dbus_message_unref(m);
+
+ if (reply)
+ dbus_message_unref(reply);
+
+ dbus_error_free(&error);
+
+ strv_free(l_set);
+ free(l_unset);
+}
+
+static int write_data_vconsole(void) {
+ int r;
+ char **l = NULL;
+
+ r = load_env_file("/etc/vconsole.conf", NULL, &l);
+ if (r < 0 && r != -ENOENT)
+ return r;
+
+ if (isempty(state.vc_keymap))
+ l = strv_env_unset(l, "KEYMAP");
+ else {
+ char *s, **u;
+
+ s = strappend("KEYMAP=", state.vc_keymap);
+ if (!s) {
+ strv_free(l);
+ return -ENOMEM;
+ }
+
+ u = strv_env_set(l, s);
+ free(s);
+ strv_free(l);
+
+ if (!u)
+ return -ENOMEM;
+
+ l = u;
+ }
+
+ if (isempty(state.vc_keymap_toggle))
+ l = strv_env_unset(l, "KEYMAP_TOGGLE");
+ else {
+ char *s, **u;
+
+ s = strappend("KEYMAP_TOGGLE=", state.vc_keymap_toggle);
+ if (!s) {
+ strv_free(l);
+ return -ENOMEM;
+ }
+
+ u = strv_env_set(l, s);
+ free(s);
+ strv_free(l);
+
+ if (!u)
+ return -ENOMEM;
+
+ l = u;
+ }
+
+ if (strv_isempty(l)) {
+ strv_free(l);
+
+ if (unlink("/etc/vconsole.conf") < 0)
+ return errno == ENOENT ? 0 : -errno;
+
+ return 0;
+ }
+
+ r = write_env_file_label("/etc/vconsole.conf", l);
+ strv_free(l);
+
+ return r;
+}
+
+static int write_data_x11(void) {
+ FILE *f;
+ char *temp_path;
+ int r;
+
+ if (isempty(state.x11_layout) &&
+ isempty(state.x11_model) &&
+ isempty(state.x11_variant) &&
+ isempty(state.x11_options)) {
+
+ if (unlink("/etc/X11/xorg.conf.d/00-keyboard.conf") < 0)
+ return errno == ENOENT ? 0 : -errno;
+
+ return 0;
+ }
+
+ mkdir_p_label("/etc/X11/xorg.conf.d", 0755);
+
+ r = fopen_temporary("/etc/X11/xorg.conf.d/00-keyboard.conf", &f, &temp_path);
+ if (r < 0)
+ return r;
+
+ fchmod(fileno(f), 0644);
+
+ fputs("# Read and parsed by systemd-localed. It's probably wise not to edit this file\n"
+ "# manually too freely.\n"
+ "Section \"InputClass\"\n"
+ " Identifier \"system-keyboard\"\n"
+ " MatchIsKeyboard \"on\"\n", f);
+
+ if (!isempty(state.x11_layout))
+ fprintf(f, " Option \"XkbLayout\" \"%s\"\n", state.x11_layout);
+
+ if (!isempty(state.x11_model))
+ fprintf(f, " Option \"XkbModel\" \"%s\"\n", state.x11_model);
+
+ if (!isempty(state.x11_variant))
+ fprintf(f, " Option \"XkbVariant\" \"%s\"\n", state.x11_variant);
+
+ if (!isempty(state.x11_options))
+ fprintf(f, " Option \"XkbOptions\" \"%s\"\n", state.x11_options);
+
+ fputs("EndSection\n", f);
+ fflush(f);
+
+ if (ferror(f) || rename(temp_path, "/etc/X11/xorg.conf.d/00-keyboard.conf") < 0) {
+ r = -errno;
+ unlink("/etc/X11/xorg.conf.d/00-keyboard.conf");
+ unlink(temp_path);
+ } else
+ r = 0;
+
+ fclose(f);
+ free(temp_path);
+
+ return r;
+}
+
+static int load_vconsole_keymap(DBusConnection *bus, DBusError *error) {
+ DBusMessage *m = NULL, *reply = NULL;
+ const char *name = "systemd-vconsole-setup.service", *mode = "replace";
+ int r;
+ DBusError _error;
+
+ assert(bus);
+
+ if (!error) {
+ dbus_error_init(&_error);
+ error = &_error;
+ }
+
+ m = dbus_message_new_method_call(
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "RestartUnit");
+ if (!m) {
+ log_error("Could not allocate message.");
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ if (!dbus_message_append_args(m,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_STRING, &mode,
+ DBUS_TYPE_INVALID)) {
+ log_error("Could not append arguments to message.");
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error);
+ if (!reply) {
+ log_error("Failed to issue method call: %s", bus_error_message(error));
+ r = -EIO;
+ goto finish;
+ }
+
+ r = 0;
+
+finish:
+ if (m)
+ dbus_message_unref(m);
+
+ if (reply)
+ dbus_message_unref(reply);
+
+ if (error == &_error)
+ dbus_error_free(error);
+
+ return r;
+}
+
+static char *strnulldash(const char *s) {
+ return s == NULL || *s == 0 || (s[0] == '-' && s[1] == 0) ? NULL : (char*) s;
+}
+
+static int read_next_mapping(FILE *f, unsigned *n, char ***a) {
+ assert(f);
+ assert(n);
+ assert(a);
+
+ for (;;) {
+ char line[LINE_MAX];
+ char *l, **b;
+
+ errno = 0;
+ if (!fgets(line, sizeof(line), f)) {
+
+ if (ferror(f))
+ return errno ? -errno : -EIO;
+
+ return 0;
+ }
+
+ (*n) ++;
+
+ l = strstrip(line);
+ if (l[0] == 0 || l[0] == '#')
+ continue;
+
+ b = strv_split_quoted(l);
+ if (!b)
+ return -ENOMEM;
+
+ if (strv_length(b) < 5) {
+ log_error("Invalid line "SYSTEMD_KBD_MODEL_MAP":%u, ignoring.", *n);
+ strv_free(b);
+ continue;
+
+ }
+
+ *a = b;
+ return 1;
+ }
+}
+
+static int convert_vconsole_to_x11(DBusConnection *connection) {
+ bool modified = false;
+
+ assert(connection);
+
+ if (isempty(state.vc_keymap)) {
+
+ modified =
+ !isempty(state.x11_layout) ||
+ !isempty(state.x11_model) ||
+ !isempty(state.x11_variant) ||
+ !isempty(state.x11_options);
+
+ free_data_x11();
+ } else {
+ FILE *f;
+ unsigned n = 0;
+
+ f = fopen(SYSTEMD_KBD_MODEL_MAP, "re");
+ if (!f)
+ return -errno;
+
+ for (;;) {
+ char **a;
+ int r;
+
+ r = read_next_mapping(f, &n, &a);
+ if (r < 0) {
+ fclose(f);
+ return r;
+ }
+
+ if (r == 0)
+ break;
+
+ if (!streq(state.vc_keymap, a[0])) {
+ strv_free(a);
+ continue;
+ }
+
+ if (!streq_ptr(state.x11_layout, strnulldash(a[1])) ||
+ !streq_ptr(state.x11_model, strnulldash(a[2])) ||
+ !streq_ptr(state.x11_variant, strnulldash(a[3])) ||
+ !streq_ptr(state.x11_options, strnulldash(a[4]))) {
+
+ if (free_and_set(&state.x11_layout, strnulldash(a[1])) < 0 ||
+ free_and_set(&state.x11_model, strnulldash(a[2])) < 0 ||
+ free_and_set(&state.x11_variant, strnulldash(a[3])) < 0 ||
+ free_and_set(&state.x11_options, strnulldash(a[4])) < 0) {
+ strv_free(a);
+ fclose(f);
+ return -ENOMEM;
+ }
+
+ modified = true;
+ }
+
+ strv_free(a);
+ break;
+ }
+
+ fclose(f);
+ }
+
+ if (modified) {
+ dbus_bool_t b;
+ DBusMessage *changed;
+ int r;
+
+ r = write_data_x11();
+ if (r < 0)
+ log_error("Failed to set X11 keyboard layout: %s", strerror(-r));
+
+ changed = bus_properties_changed_new(
+ "/org/freedesktop/locale1",
+ "org.freedesktop.locale1",
+ "X11Layout\0"
+ "X11Model\0"
+ "X11Variant\0"
+ "X11Options\0");
+
+ if (!changed)
+ return -ENOMEM;
+
+ b = dbus_connection_send(connection, changed, NULL);
+ dbus_message_unref(changed);
+
+ if (!b)
+ return -ENOMEM;
+ }
+
+ return 0;
+}
+
+static int convert_x11_to_vconsole(DBusConnection *connection) {
+ bool modified = false;
+
+ assert(connection);
+
+ if (isempty(state.x11_layout)) {
+
+ modified =
+ !isempty(state.vc_keymap) ||
+ !isempty(state.vc_keymap_toggle);
+
+ free_data_x11();
+ } else {
+ FILE *f;
+ unsigned n = 0;
+ unsigned best_matching = 0;
+ char *new_keymap = NULL;
+
+ f = fopen(SYSTEMD_KBD_MODEL_MAP, "re");
+ if (!f)
+ return -errno;
+
+ for (;;) {
+ char **a;
+ unsigned matching = 0;
+ int r;
+
+ r = read_next_mapping(f, &n, &a);
+ if (r < 0) {
+ fclose(f);
+ return r;
+ }
+
+ if (r == 0)
+ break;
+
+ /* Determine how well matching this entry is */
+ if (streq_ptr(state.x11_layout, a[1]))
+ /* If we got an exact match, this is best */
+ matching = 10;
+ else {
+ size_t x;
+
+ x = strcspn(state.x11_layout, ",");
+
+ /* We have multiple X layouts, look
+ * for an entry that matches our key
+ * with the everything but the first
+ * layout stripped off. */
+ if (x > 0 &&
+ strlen(a[1]) == x &&
+ strneq(state.x11_layout, a[1], x))
+ matching = 5;
+ else {
+ size_t w;
+
+ /* If that didn't work, strip
+ * off the other layouts from
+ * the entry, too */
+
+ w = strcspn(a[1], ",");
+
+ if (x > 0 && x == w &&
+ memcmp(state.x11_layout, a[1], x) == 0)
+ matching = 1;
+ }
+ }
+
+ if (matching > 0 &&
+ streq_ptr(state.x11_model, a[2])) {
+ matching++;
+
+ if (streq_ptr(state.x11_variant, a[3])) {
+ matching++;
+
+ if (streq_ptr(state.x11_options, a[4]))
+ matching++;
+ }
+ }
+
+ /* The best matching entry so far, then let's
+ * save that */
+ if (matching > best_matching) {
+ best_matching = matching;
+
+ free(new_keymap);
+ new_keymap = strdup(a[0]);
+
+ if (!new_keymap) {
+ strv_free(a);
+ fclose(f);
+ return -ENOMEM;
+ }
+ }
+
+ strv_free(a);
+ }
+
+ fclose(f);
+
+ if (!streq_ptr(state.vc_keymap, new_keymap)) {
+ free(state.vc_keymap);
+ state.vc_keymap = new_keymap;
+
+ free(state.vc_keymap_toggle);
+ state.vc_keymap_toggle = NULL;
+
+ modified = true;
+ } else
+ free(new_keymap);
+ }
+
+ if (modified) {
+ dbus_bool_t b;
+ DBusMessage *changed;
+ int r;
+
+ r = write_data_vconsole();
+ if (r < 0)
+ log_error("Failed to set virtual console keymap: %s", strerror(-r));
+
+ changed = bus_properties_changed_new(
+ "/org/freedesktop/locale1",
+ "org.freedesktop.locale1",
+ "VConsoleKeymap\0"
+ "VConsoleKeymapToggle\0");
+
+ if (!changed)
+ return -ENOMEM;
+
+ b = dbus_connection_send(connection, changed, NULL);
+ dbus_message_unref(changed);
+
+ if (!b)
+ return -ENOMEM;
+
+ return load_vconsole_keymap(connection, NULL);
+ }
+
+ return 0;
+}
+
+static int append_locale(DBusMessageIter *i, const char *property, void *userdata) {
+ int r, c = 0, p;
+ char **l;
+
+ l = new0(char*, _PROP_MAX+1);
+ if (!l)
+ return -ENOMEM;
+
+ for (p = 0; p < _PROP_MAX; p++) {
+ char *t;
+
+ if (isempty(data[p]))
+ continue;
+
+ if (asprintf(&t, "%s=%s", names[p], data[p]) < 0) {
+ strv_free(l);
+ return -ENOMEM;
+ }
+
+ l[c++] = t;
+ }
+
+ r = bus_property_append_strv(i, property, (void*) l);
+ strv_free(l);
+
+ return r;
+}
+
+static const BusProperty bus_locale_properties[] = {
+ { "Locale", append_locale, "as", 0 },
+ { "X11Layout", bus_property_append_string, "s", offsetof(State, x11_layout), true },
+ { "X11Model", bus_property_append_string, "s", offsetof(State, x11_model), true },
+ { "X11Variant", bus_property_append_string, "s", offsetof(State, x11_variant), true },
+ { "X11Options", bus_property_append_string, "s", offsetof(State, x11_options), true },
+ { "VConsoleKeymap", bus_property_append_string, "s", offsetof(State, vc_keymap), true },
+ { "VConsoleKeymapToggle", bus_property_append_string, "s", offsetof(State, vc_keymap_toggle), true },
+ { NULL, }
+};
+
+static const BusBoundProperties bps[] = {
+ { "org.freedesktop.locale1", bus_locale_properties, &state },
+ { NULL, }
+};
+
+static DBusHandlerResult locale_message_handler(
+ DBusConnection *connection,
+ DBusMessage *message,
+ void *userdata) {
+
+ DBusMessage *reply = NULL, *changed = NULL;
+ DBusError error;
+ int r;
+
+ assert(connection);
+ assert(message);
+
+ dbus_error_init(&error);
+
+ if (dbus_message_is_method_call(message, "org.freedesktop.locale1", "SetLocale")) {
+ char **l = NULL, **i;
+ dbus_bool_t interactive;
+ DBusMessageIter iter;
+ bool modified = false;
+ bool passed[_PROP_MAX] = {};
+ int p;
+
+ if (!dbus_message_iter_init(message, &iter))
+ return bus_send_error_reply(connection, message, NULL, -EINVAL);
+
+ r = bus_parse_strv_iter(&iter, &l);
+ if (r < 0) {
+ if (r == -ENOMEM)
+ goto oom;
+
+ return bus_send_error_reply(connection, message, NULL, r);
+ }
+
+ if (!dbus_message_iter_next(&iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_BOOLEAN) {
+ strv_free(l);
+ return bus_send_error_reply(connection, message, NULL, -EINVAL);
+ }
+
+ dbus_message_iter_get_basic(&iter, &interactive);
+
+ /* Check whether a variable changed and if so valid */
+ STRV_FOREACH(i, l) {
+ bool valid = false;
+
+ for (p = 0; p < _PROP_MAX; p++) {
+ size_t k;
+
+ k = strlen(names[p]);
+ if (startswith(*i, names[p]) &&
+ (*i)[k] == '=' &&
+ string_is_safe((*i) + k + 1)) {
+ valid = true;
+ passed[p] = true;
+
+ if (!streq_ptr(*i + k + 1, data[p]))
+ modified = true;
+
+ break;
+ }
+ }
+
+ if (!valid) {
+ strv_free(l);
+ return bus_send_error_reply(connection, message, NULL, -EINVAL);
+ }
+ }
+
+ /* Check whether a variable is unset */
+ if (!modified) {
+ for (p = 0; p < _PROP_MAX; p++)
+ if (!isempty(data[p]) && !passed[p]) {
+ modified = true;
+ break;
+ }
+ }
+
+ if (modified) {
+
+ r = verify_polkit(connection, message, "org.freedesktop.locale1.set-locale", interactive, NULL, &error);
+ if (r < 0) {
+ strv_free(l);
+ return bus_send_error_reply(connection, message, &error, r);
+ }
+
+ STRV_FOREACH(i, l) {
+ for (p = 0; p < _PROP_MAX; p++) {
+ size_t k;
+
+ k = strlen(names[p]);
+ if (startswith(*i, names[p]) && (*i)[k] == '=') {
+ char *t;
+
+ t = strdup(*i + k + 1);
+ if (!t) {
+ strv_free(l);
+ goto oom;
+ }
+
+ free(data[p]);
+ data[p] = t;
+
+ break;
+ }
+ }
+ }
+
+ strv_free(l);
+
+ for (p = 0; p < _PROP_MAX; p++) {
+ if (passed[p])
+ continue;
+
+ free(data[p]);
+ data[p] = NULL;
+ }
+
+ simplify();
+
+ r = write_data_locale();
+ if (r < 0) {
+ log_error("Failed to set locale: %s", strerror(-r));
+ return bus_send_error_reply(connection, message, NULL, r);
+ }
+
+ push_data(connection);
+
+ log_info("Changed locale information.");
+
+ changed = bus_properties_changed_new(
+ "/org/freedesktop/locale1",
+ "org.freedesktop.locale1",
+ "Locale\0");
+ if (!changed)
+ goto oom;
+ } else
+ strv_free(l);
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.locale1", "SetVConsoleKeyboard")) {
+
+ const char *keymap, *keymap_toggle;
+ dbus_bool_t convert, interactive;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &keymap,
+ DBUS_TYPE_STRING, &keymap_toggle,
+ DBUS_TYPE_BOOLEAN, &convert,
+ DBUS_TYPE_BOOLEAN, &interactive,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ if (isempty(keymap))
+ keymap = NULL;
+
+ if (isempty(keymap_toggle))
+ keymap_toggle = NULL;
+
+ if (!streq_ptr(keymap, state.vc_keymap) ||
+ !streq_ptr(keymap_toggle, state.vc_keymap_toggle)) {
+
+ if ((keymap && (!filename_is_safe(keymap) || !string_is_safe(keymap))) ||
+ (keymap_toggle && (!filename_is_safe(keymap_toggle) || !string_is_safe(keymap_toggle))))
+ return bus_send_error_reply(connection, message, NULL, -EINVAL);
+
+ r = verify_polkit(connection, message, "org.freedesktop.locale1.set-keyboard", interactive, NULL, &error);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ if (free_and_set(&state.vc_keymap, keymap) < 0 ||
+ free_and_set(&state.vc_keymap_toggle, keymap_toggle) < 0)
+ goto oom;
+
+ r = write_data_vconsole();
+ if (r < 0) {
+ log_error("Failed to set virtual console keymap: %s", strerror(-r));
+ return bus_send_error_reply(connection, message, NULL, r);
+ }
+
+ log_info("Changed virtual console keymap to '%s'", strempty(state.vc_keymap));
+
+ r = load_vconsole_keymap(connection, NULL);
+ if (r < 0)
+ log_error("Failed to request keymap reload: %s", strerror(-r));
+
+ changed = bus_properties_changed_new(
+ "/org/freedesktop/locale1",
+ "org.freedesktop.locale1",
+ "VConsoleKeymap\0"
+ "VConsoleKeymapToggle\0");
+ if (!changed)
+ goto oom;
+
+ if (convert) {
+ r = convert_vconsole_to_x11(connection);
+
+ if (r < 0)
+ log_error("Failed to convert keymap data: %s", strerror(-r));
+ }
+ }
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.locale1", "SetX11Keyboard")) {
+
+ const char *layout, *model, *variant, *options;
+ dbus_bool_t convert, interactive;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &layout,
+ DBUS_TYPE_STRING, &model,
+ DBUS_TYPE_STRING, &variant,
+ DBUS_TYPE_STRING, &options,
+ DBUS_TYPE_BOOLEAN, &convert,
+ DBUS_TYPE_BOOLEAN, &interactive,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ if (isempty(layout))
+ layout = NULL;
+
+ if (isempty(model))
+ model = NULL;
+
+ if (isempty(variant))
+ variant = NULL;
+
+ if (isempty(options))
+ options = NULL;
+
+ if (!streq_ptr(layout, state.x11_layout) ||
+ !streq_ptr(model, state.x11_model) ||
+ !streq_ptr(variant, state.x11_variant) ||
+ !streq_ptr(options, state.x11_options)) {
+
+ if ((layout && !string_is_safe(layout)) ||
+ (model && !string_is_safe(model)) ||
+ (variant && !string_is_safe(variant)) ||
+ (options && !string_is_safe(options)))
+ return bus_send_error_reply(connection, message, NULL, -EINVAL);
+
+ r = verify_polkit(connection, message, "org.freedesktop.locale1.set-keyboard", interactive, NULL, &error);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ if (free_and_set(&state.x11_layout, layout) < 0 ||
+ free_and_set(&state.x11_model, model) < 0 ||
+ free_and_set(&state.x11_variant, variant) < 0 ||
+ free_and_set(&state.x11_options, options) < 0)
+ goto oom;
+
+ r = write_data_x11();
+ if (r < 0) {
+ log_error("Failed to set X11 keyboard layout: %s", strerror(-r));
+ return bus_send_error_reply(connection, message, NULL, r);
+ }
+
+ log_info("Changed X11 keyboard layout to '%s'", strempty(state.x11_layout));
+
+ changed = bus_properties_changed_new(
+ "/org/freedesktop/locale1",
+ "org.freedesktop.locale1",
+ "X11Layout\0"
+ "X11Model\0"
+ "X11Variant\0"
+ "X11Options\0");
+ if (!changed)
+ goto oom;
+
+ if (convert) {
+ r = convert_x11_to_vconsole(connection);
+
+ if (r < 0)
+ log_error("Failed to convert keymap data: %s", strerror(-r));
+ }
+ }
+ } else
+ return bus_default_message_handler(connection, message, INTROSPECTION, INTERFACES_LIST, bps);
+
+ if (!(reply = dbus_message_new_method_return(message)))
+ goto oom;
+
+ if (!bus_maybe_send_reply(connection, message, reply))
+ goto oom;
+
+ dbus_message_unref(reply);
+ reply = NULL;
+
+ if (changed) {
+
+ if (!dbus_connection_send(connection, changed, NULL))
+ goto oom;
+
+ dbus_message_unref(changed);
+ }
+
+ return DBUS_HANDLER_RESULT_HANDLED;
+
+oom:
+ if (reply)
+ dbus_message_unref(reply);
+
+ if (changed)
+ dbus_message_unref(changed);
+
+ dbus_error_free(&error);
+
+ return DBUS_HANDLER_RESULT_NEED_MEMORY;
+}
+
+static int connect_bus(DBusConnection **_bus) {
+ static const DBusObjectPathVTable locale_vtable = {
+ .message_function = locale_message_handler
+ };
+ DBusError error;
+ DBusConnection *bus = NULL;
+ int r;
+
+ assert(_bus);
+
+ dbus_error_init(&error);
+
+ bus = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error);
+ if (!bus) {
+ log_error("Failed to get system D-Bus connection: %s", bus_error_message(&error));
+ r = -ECONNREFUSED;
+ goto fail;
+ }
+
+ dbus_connection_set_exit_on_disconnect(bus, FALSE);
+
+ if (!dbus_connection_register_object_path(bus, "/org/freedesktop/locale1", &locale_vtable, NULL) ||
+ !dbus_connection_add_filter(bus, bus_exit_idle_filter, &remain_until, NULL)) {
+ r = log_oom();
+ goto fail;
+ }
+
+ r = dbus_bus_request_name(bus, "org.freedesktop.locale1", DBUS_NAME_FLAG_DO_NOT_QUEUE, &error);
+ if (dbus_error_is_set(&error)) {
+ log_error("Failed to register name on bus: %s", bus_error_message(&error));
+ r = -EEXIST;
+ goto fail;
+ }
+
+ if (r != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) {
+ log_error("Failed to acquire name.");
+ r = -EEXIST;
+ goto fail;
+ }
+
+ if (_bus)
+ *_bus = bus;
+
+ return 0;
+
+fail:
+ dbus_connection_close(bus);
+ dbus_connection_unref(bus);
+
+ dbus_error_free(&error);
+
+ return r;
+}
+
+int main(int argc, char *argv[]) {
+ int r;
+ DBusConnection *bus = NULL;
+ bool exiting = false;
+
+ log_set_target(LOG_TARGET_AUTO);
+ log_parse_environment();
+ log_open();
+ label_init("/etc");
+ umask(0022);
+
+ if (argc == 2 && streq(argv[1], "--introspect")) {
+ fputs(DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE
+ "<node>\n", stdout);
+ fputs(locale_interface, stdout);
+ fputs("</node>\n", stdout);
+ return 0;
+ }
+
+ if (argc != 1) {
+ log_error("This program takes no arguments.");
+ r = -EINVAL;
+ goto finish;
+ }
+
+ r = read_data();
+ if (r < 0) {
+ log_error("Failed to read locale data: %s", strerror(-r));
+ goto finish;
+ }
+
+ r = connect_bus(&bus);
+ if (r < 0)
+ goto finish;
+
+ remain_until = now(CLOCK_MONOTONIC) + DEFAULT_EXIT_USEC;
+ for (;;) {
+
+ if (!dbus_connection_read_write_dispatch(bus, exiting ? -1 : (int) (DEFAULT_EXIT_USEC/USEC_PER_MSEC)))
+ break;
+
+ if (!exiting && remain_until < now(CLOCK_MONOTONIC)) {
+ exiting = true;
+ bus_async_unregister_and_exit(bus, "org.freedesktop.locale1");
+ }
+ }
+
+ r = 0;
+
+finish:
+ free_data();
+
+ if (bus) {
+ dbus_connection_flush(bus);
+ dbus_connection_close(bus);
+ dbus_connection_unref(bus);
+ }
+
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/src/locale/org.freedesktop.locale1.conf b/src/locale/org.freedesktop.locale1.conf
new file mode 100644
index 0000000000..79d0ecd2bb
--- /dev/null
+++ b/src/locale/org.freedesktop.locale1.conf
@@ -0,0 +1,27 @@
+<?xml version="1.0"?> <!--*-nxml-*-->
+<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
+ "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
+
+<!--
+ This file is part of systemd.
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+-->
+
+<busconfig>
+
+ <policy user="root">
+ <allow own="org.freedesktop.locale1"/>
+ <allow send_destination="org.freedesktop.locale1"/>
+ <allow receive_sender="org.freedesktop.locale1"/>
+ </policy>
+
+ <policy context="default">
+ <allow send_destination="org.freedesktop.locale1"/>
+ <allow receive_sender="org.freedesktop.locale1"/>
+ </policy>
+
+</busconfig>
diff --git a/src/locale/org.freedesktop.locale1.policy.in b/src/locale/org.freedesktop.locale1.policy.in
new file mode 100644
index 0000000000..df63845e9b
--- /dev/null
+++ b/src/locale/org.freedesktop.locale1.policy.in
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="UTF-8"?> <!--*-nxml-*-->
+<!DOCTYPE policyconfig PUBLIC "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
+ "http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd">
+
+<!--
+ This file is part of systemd.
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+-->
+
+<policyconfig>
+
+ <vendor>The systemd Project</vendor>
+ <vendor_url>http://www.freedesktop.org/wiki/Software/systemd</vendor_url>
+
+ <action id="org.freedesktop.locale1.set-locale">
+ <_description>Set system locale</_description>
+ <_message>Authentication is required to set the system locale.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.locale1.set-keyboard</annotate>
+ </action>
+
+ <action id="org.freedesktop.locale1.set-keyboard">
+ <_description>Set system keyboard settings</_description>
+ <_message>Authentication is required to set the system keyboard settings.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ </action>
+
+</policyconfig>
diff --git a/src/locale/org.freedesktop.locale1.service b/src/locale/org.freedesktop.locale1.service
new file mode 100644
index 0000000000..025f9a0fc2
--- /dev/null
+++ b/src/locale/org.freedesktop.locale1.service
@@ -0,0 +1,12 @@
+# This file is part of systemd.
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 of the License, or
+# (at your option) any later version.
+
+[D-BUS Service]
+Name=org.freedesktop.locale1
+Exec=/bin/false
+User=root
+SystemdService=dbus-org.freedesktop.locale1.service
diff --git a/src/login/70-power-switch.rules b/src/login/70-power-switch.rules
new file mode 100644
index 0000000000..36fb827315
--- /dev/null
+++ b/src/login/70-power-switch.rules
@@ -0,0 +1,13 @@
+# This file is part of systemd.
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 of the License, or
+# (at your option) any later version.
+
+ACTION=="remove", GOTO="power_switch_end"
+
+SUBSYSTEM=="input", KERNEL=="event*", SUBSYSTEMS=="acpi", TAG+="power-switch"
+SUBSYSTEM=="input", KERNEL=="event*", KERNELS=="thinkpad_acpi", TAG+="power-switch"
+
+LABEL="power_switch_end"
diff --git a/src/login/70-uaccess.rules b/src/login/70-uaccess.rules
new file mode 100644
index 0000000000..a118f8e887
--- /dev/null
+++ b/src/login/70-uaccess.rules
@@ -0,0 +1,74 @@
+# This file is part of systemd.
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 of the License, or
+# (at your option) any later version.
+
+ACTION=="remove", GOTO="uaccess_end"
+ENV{MAJOR}=="", GOTO="uaccess_end"
+
+# PTP/MTP protocol devices, cameras, portable media players
+SUBSYSTEM=="usb", ENV{ID_USB_INTERFACES}=="*:060101:*", TAG+="uaccess"
+
+# Digicams with proprietary protocol
+ENV{ID_GPHOTO2}=="*?", TAG+="uaccess"
+
+# SCSI and USB scanners
+ENV{libsane_matched}=="yes", TAG+="uaccess"
+
+# HPLIP devices (necessary for ink level check and HP tool maintenance)
+ENV{ID_HPLIP}=="1", TAG+="uaccess"
+
+# optical drives
+SUBSYSTEM=="block", ENV{ID_CDROM}=="1", TAG+="uaccess"
+SUBSYSTEM=="scsi_generic", SUBSYSTEMS=="scsi", ATTRS{type}=="4|5", TAG+="uaccess"
+
+# Sound devices
+SUBSYSTEM=="sound", TAG+="uaccess"
+
+# ffado is an userspace driver for firewire sound cards
+SUBSYSTEM=="firewire", ENV{ID_FFADO}=="1", TAG+="uaccess"
+
+# Webcams, frame grabber, TV cards
+SUBSYSTEM=="video4linux", TAG+="uaccess"
+SUBSYSTEM=="dvb", TAG+="uaccess"
+
+# IIDC devices: industrial cameras and some webcams
+SUBSYSTEM=="firewire", ATTR{units}=="*0x00a02d:0x00010*", TAG+="uaccess"
+SUBSYSTEM=="firewire", ATTR{units}=="*0x00b09d:0x00010*", TAG+="uaccess"
+# AV/C devices: camcorders, set-top boxes, TV sets, audio devices, and more
+SUBSYSTEM=="firewire", ATTR{units}=="*0x00a02d:0x010001*", TAG+="uaccess"
+SUBSYSTEM=="firewire", ATTR{units}=="*0x00a02d:0x014001*", TAG+="uaccess"
+
+# DRI video devices
+SUBSYSTEM=="drm", KERNEL=="card*", TAG+="uaccess"
+
+# KVM
+SUBSYSTEM=="misc", KERNEL=="kvm", TAG+="uaccess"
+
+# smart-card readers
+ENV{ID_SMARTCARD_READER}=="*?", TAG+="uaccess"
+
+# (USB) authentication devices
+ENV{ID_SECURITY_TOKEN}=="*?", TAG+="uaccess"
+
+# PDA devices
+ENV{ID_PDA}=="*?", TAG+="uaccess"
+
+# Programmable remote control
+ENV{ID_REMOTE_CONTROL}=="1", TAG+="uaccess"
+
+# joysticks
+SUBSYSTEM=="input", ENV{ID_INPUT_JOYSTICK}=="?*", TAG+="uaccess"
+
+# color measurement devices
+ENV{COLOR_MEASUREMENT_DEVICE}=="*?", TAG+="uaccess"
+
+# DDC/CI device, usually high-end monitors such as the DreamColor
+ENV{DDC_DEVICE}=="*?", TAG+="uaccess"
+
+# media player raw devices (for user-mode drivers, Android SDK, etc.)
+SUBSYSTEM=="usb", ENV{ID_MEDIA_PLAYER}=="?*", TAG+="uaccess"
+
+LABEL="uaccess_end"
diff --git a/src/login/71-seat.rules.in b/src/login/71-seat.rules.in
new file mode 100644
index 0000000000..ad26acbbb3
--- /dev/null
+++ b/src/login/71-seat.rules.in
@@ -0,0 +1,48 @@
+# This file is part of systemd.
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 of the License, or
+# (at your option) any later version.
+
+ACTION=="remove", GOTO="seat_end"
+
+TAG=="uaccess", SUBSYSTEM!="sound", TAG+="seat"
+SUBSYSTEM=="sound", KERNEL=="card*", TAG+="seat"
+SUBSYSTEM=="input", KERNEL=="input*", TAG+="seat"
+SUBSYSTEM=="graphics", KERNEL=="fb[0-9]*", TAG+="seat", TAG+="master-of-seat"
+SUBSYSTEM=="usb", ATTR{bDeviceClass}=="09", TAG+="seat"
+
+# 'Plugable' USB hub, sound, network, graphics adapter
+SUBSYSTEM=="usb", ATTR{idVendor}=="2230", ATTR{idProduct}=="000[13]", ENV{ID_AUTOSEAT}="1"
+
+# Mimo 720, with integrated USB hub, displaylink graphics, and e2i
+# touchscreen. This device carries no proper VID/PID in the USB hub,
+# but it does carry good ID data in the graphics component, hence we
+# check it from the parent. There's a bit of a race here however,
+# given that the child devices might not exist yet at the time this
+# rule is executed. To work around this we'll trigger the parent from
+# the child if we notice that the parent wasn't recognized yet.
+
+# Match parent
+SUBSYSTEM=="usb", ATTR{idVendor}=="058f", ATTR{idProduct}=="6254", \
+ ATTR{%k.2/idVendor}=="17e9", ATTR{%k.2/idProduct}=="401a", ATTR{%k.2/product}=="mimo inc", \
+ ENV{ID_AUTOSEAT}="1", ENV{ID_AVOID_LOOP}="1"
+
+# Match child, look for parent's ID_AVOID_LOOP
+SUBSYSTEM=="usb", ATTR{idVendor}=="17e9", ATTR{idProduct}=="401a", ATTR{product}=="mimo inc", \
+ ATTR{../idVendor}=="058f", ATTR{../idProduct}=="6254", \
+ IMPORT{parent}="ID_AVOID_LOOP"
+
+# Match child, retrigger parent
+SUBSYSTEM=="usb", ATTR{idVendor}=="17e9", ATTR{idProduct}=="401a", ATTR{product}=="mimo inc", \
+ ATTR{../idVendor}=="058f", ATTR{../idProduct}=="6254", \
+ ENV{ID_AVOID_LOOP}=="", \
+ RUN+="@rootbindir@/udevadm trigger --parent-match=%p/.."
+
+TAG=="seat", ENV{ID_PATH}=="", IMPORT{builtin}="path_id"
+TAG=="seat", ENV{ID_FOR_SEAT}=="", ENV{ID_PATH_TAG}!="", ENV{ID_FOR_SEAT}="$env{SUBSYSTEM}-$env{ID_PATH_TAG}"
+
+SUBSYSTEM=="input", ATTR{name}=="Wiebetech LLC Wiebetech", RUN+="@rootbindir@/loginctl lock-sessions"
+
+LABEL="seat_end"
diff --git a/src/login/73-seat-late.rules.in b/src/login/73-seat-late.rules.in
new file mode 100644
index 0000000000..901df750fd
--- /dev/null
+++ b/src/login/73-seat-late.rules.in
@@ -0,0 +1,17 @@
+# This file is part of systemd.
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 of the License, or
+# (at your option) any later version.
+
+ACTION=="remove", GOTO="seat_late_end"
+
+ENV{ID_SEAT}=="", ENV{ID_AUTOSEAT}=="1", ENV{ID_FOR_SEAT}!="", ENV{ID_SEAT}="seat-$env{ID_FOR_SEAT}"
+ENV{ID_SEAT}=="", IMPORT{parent}="ID_SEAT"
+
+ENV{ID_SEAT}!="", TAG+="$env{ID_SEAT}"
+
+TAG=="uaccess", ENV{MAJOR}!="", RUN{builtin}+="uaccess"
+
+LABEL="seat_late_end"
diff --git a/src/login/inhibit.c b/src/login/inhibit.c
new file mode 100644
index 0000000000..29e50c1447
--- /dev/null
+++ b/src/login/inhibit.c
@@ -0,0 +1,310 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <getopt.h>
+#include <assert.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <dbus.h>
+#include <unistd.h>
+
+#include "dbus-common.h"
+#include "util.h"
+#include "build.h"
+#include "strv.h"
+
+static const char* arg_what = "idle:sleep:shutdown";
+static const char* arg_who = NULL;
+static const char* arg_why = "Unknown reason";
+static const char* arg_mode = "block";
+
+static enum {
+ ACTION_INHIBIT,
+ ACTION_LIST
+} arg_action = ACTION_INHIBIT;
+
+static int inhibit(DBusConnection *bus, DBusError *error) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ int r;
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "Inhibit",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &arg_what,
+ DBUS_TYPE_STRING, &arg_who,
+ DBUS_TYPE_STRING, &arg_why,
+ DBUS_TYPE_STRING, &arg_mode,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+
+ if (!dbus_message_get_args(reply, error,
+ DBUS_TYPE_UNIX_FD, &r,
+ DBUS_TYPE_INVALID))
+ return -EIO;
+
+ return r;
+}
+
+static int print_inhibitors(DBusConnection *bus, DBusError *error) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ unsigned n = 0;
+ DBusMessageIter iter, sub, sub2;
+ int r;
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "ListInhibitors",
+ &reply,
+ NULL,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+
+ if (!dbus_message_iter_init(reply, &iter))
+ return -ENOMEM;
+
+ if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY)
+ return -EIO;
+
+ dbus_message_iter_recurse(&iter, &sub);
+ while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ const char *what, *who, *why, *mode;
+ _cleanup_free_ char *comm = NULL, *u = NULL;
+ dbus_uint32_t uid, pid;
+
+ if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT)
+ return -EIO;
+
+ dbus_message_iter_recurse(&sub, &sub2);
+
+ if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &what, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &who, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &why, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &mode, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &uid, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, false) < 0)
+ return -EIO;
+
+ get_process_comm(pid, &comm);
+ u = uid_to_name(uid);
+
+ printf(" Who: %s (UID %lu/%s, PID %lu/%s)\n"
+ " What: %s\n"
+ " Why: %s\n"
+ " Mode: %s\n\n",
+ who, (unsigned long) uid, strna(u), (unsigned long) pid, strna(comm),
+ what,
+ why,
+ mode);
+
+ dbus_message_iter_next(&sub);
+
+ n++;
+ }
+
+ printf("%u inhibitors listed.\n", n);
+ return 0;
+}
+
+static int help(void) {
+
+ printf("%s [OPTIONS...] {COMMAND} ...\n\n"
+ "Execute a process while inhibiting shutdown/sleep/idle.\n\n"
+ " -h --help Show this help\n"
+ " --version Show package version\n"
+ " --what=WHAT Operations to inhibit, colon separated list of:\n"
+ " shutdown, sleep, idle, handle-power-key,\n"
+ " handle-suspend-key, handle-hibernate-key,\n"
+ " handle-lid-switch\n"
+ " --who=STRING A descriptive string who is inhibiting\n"
+ " --why=STRING A descriptive string why is being inhibited\n"
+ " --mode=MODE One of block or delay\n"
+ " --list List active inhibitors\n",
+ program_invocation_short_name);
+
+ return 0;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+
+ enum {
+ ARG_VERSION = 0x100,
+ ARG_WHAT,
+ ARG_WHO,
+ ARG_WHY,
+ ARG_MODE,
+ ARG_LIST,
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "version", no_argument, NULL, ARG_VERSION },
+ { "what", required_argument, NULL, ARG_WHAT },
+ { "who", required_argument, NULL, ARG_WHO },
+ { "why", required_argument, NULL, ARG_WHY },
+ { "mode", required_argument, NULL, ARG_MODE },
+ { "list", no_argument, NULL, ARG_LIST },
+ { NULL, 0, NULL, 0 }
+ };
+
+ int c;
+
+ assert(argc >= 0);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "+h", options, NULL)) >= 0) {
+
+ switch (c) {
+
+ case 'h':
+ help();
+ return 0;
+
+ case ARG_VERSION:
+ puts(PACKAGE_STRING);
+ puts(SYSTEMD_FEATURES);
+ return 0;
+
+ case ARG_WHAT:
+ arg_what = optarg;
+ break;
+
+ case ARG_WHO:
+ arg_who = optarg;
+ break;
+
+ case ARG_WHY:
+ arg_why = optarg;
+ break;
+
+ case ARG_MODE:
+ arg_mode = optarg;
+ break;
+
+ case ARG_LIST:
+ arg_action = ACTION_LIST;
+ break;
+
+ default:
+ log_error("Unknown option code %c", c);
+ return -EINVAL;
+ }
+ }
+
+ if (arg_action == ACTION_INHIBIT && argc == 1)
+ arg_action = ACTION_LIST;
+
+ else if (arg_action == ACTION_INHIBIT && optind >= argc) {
+ log_error("Missing command line to execute.");
+ return -EINVAL;
+ }
+
+ return 1;
+}
+
+int main(int argc, char *argv[]) {
+ int r, exit_code = 0;
+ DBusConnection *bus = NULL;
+ DBusError error;
+ _cleanup_close_ int fd = -1;
+
+ dbus_error_init(&error);
+
+ log_parse_environment();
+ log_open();
+
+ r = parse_argv(argc, argv);
+ if (r <= 0)
+ goto finish;
+
+ bus = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error);
+ if (!bus) {
+ log_error("Failed to connect to bus: %s", bus_error_message(&error));
+ r = -EIO;
+ goto finish;
+ }
+
+ if (arg_action == ACTION_LIST) {
+
+ r = print_inhibitors(bus, &error);
+ if (r < 0) {
+ log_error("Failed to list inhibitors: %s", bus_error(&error, r));
+ goto finish;
+ }
+
+ } else {
+ char *w = NULL;
+ pid_t pid;
+
+ if (!arg_who)
+ arg_who = w = strv_join(argv + optind, " ");
+
+ fd = inhibit(bus, &error);
+ free(w);
+
+ if (fd < 0) {
+ log_error("Failed to inhibit: %s", bus_error(&error, r));
+ r = fd;
+ goto finish;
+ }
+
+ pid = fork();
+ if (pid < 0) {
+ log_error("Failed to fork: %m");
+ r = -errno;
+ goto finish;
+ }
+
+ if (pid == 0) {
+ /* Child */
+
+ close_nointr_nofail(fd);
+ close_all_fds(NULL, 0);
+
+ execvp(argv[optind], argv + optind);
+ log_error("Failed to execute %s: %m", argv[optind]);
+ _exit(EXIT_FAILURE);
+ }
+
+ r = wait_for_terminate_and_warn(argv[optind], pid);
+ if (r >= 0)
+ exit_code = r;
+ }
+
+finish:
+ if (bus) {
+ dbus_connection_close(bus);
+ dbus_connection_unref(bus);
+ }
+
+ dbus_error_free(&error);
+
+ return r < 0 ? EXIT_FAILURE : exit_code;
+}
diff --git a/src/login/libsystemd-login.pc.in b/src/login/libsystemd-login.pc.in
new file mode 100644
index 0000000000..7b2a7245fc
--- /dev/null
+++ b/src/login/libsystemd-login.pc.in
@@ -0,0 +1,18 @@
+# This file is part of systemd.
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 of the License, or
+# (at your option) any later version.
+
+prefix=@prefix@
+exec_prefix=@exec_prefix@
+libdir=@libdir@
+includedir=@includedir@
+
+Name: systemd
+Description: systemd Login Utility Library
+URL: @PACKAGE_URL@
+Version: @PACKAGE_VERSION@
+Libs: -L${libdir} -lsystemd-login
+Cflags: -I${includedir}
diff --git a/src/login/libsystemd-login.sym b/src/login/libsystemd-login.sym
new file mode 100644
index 0000000000..925fb91095
--- /dev/null
+++ b/src/login/libsystemd-login.sym
@@ -0,0 +1,77 @@
+/***
+ This file is part of systemd.
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+***/
+
+/* Original symbols from systemd v31 */
+
+LIBSYSTEMD_LOGIN_31 {
+global:
+ sd_get_seats;
+ sd_get_sessions;
+ sd_get_uids;
+ sd_login_monitor_flush;
+ sd_login_monitor_get_fd;
+ sd_login_monitor_new;
+ sd_login_monitor_unref;
+ sd_pid_get_owner_uid;
+ sd_pid_get_session;
+ sd_seat_can_multi_session;
+ sd_seat_get_active;
+ sd_seat_get_sessions;
+ sd_session_get_seat;
+ sd_session_get_uid;
+ sd_session_is_active;
+ sd_uid_get_seats;
+ sd_uid_get_sessions;
+ sd_uid_get_state;
+ sd_uid_is_on_seat;
+local:
+ *;
+};
+
+LIBSYSTEMD_LOGIN_38 {
+global:
+ sd_pid_get_unit;
+ sd_session_get_service;
+} LIBSYSTEMD_LOGIN_31;
+
+LIBSYSTEMD_LOGIN_43 {
+global:
+ sd_session_get_type;
+ sd_session_get_class;
+ sd_session_get_display;
+} LIBSYSTEMD_LOGIN_38;
+
+LIBSYSTEMD_LOGIN_186 {
+global:
+ sd_session_get_state;
+ sd_seat_can_tty;
+ sd_seat_can_graphical;
+} LIBSYSTEMD_LOGIN_43;
+
+LIBSYSTEMD_LOGIN_198 {
+global:
+ sd_session_get_tty;
+} LIBSYSTEMD_LOGIN_186;
+
+LIBSYSTEMD_LOGIN_201 {
+global:
+ sd_login_monitor_get_events;
+ sd_login_monitor_get_timeout;
+} LIBSYSTEMD_LOGIN_198;
+
+LIBSYSTEMD_LOGIN_202 {
+global:
+ sd_pid_get_user_unit;
+ sd_pid_get_machine_name;
+} LIBSYSTEMD_LOGIN_201;
+
+LIBSYSTEMD_LOGIN_203 {
+global:
+ sd_get_machine_names;
+} LIBSYSTEMD_LOGIN_202;
diff --git a/src/login/loginctl.c b/src/login/loginctl.c
new file mode 100644
index 0000000000..caaea8dfaa
--- /dev/null
+++ b/src/login/loginctl.c
@@ -0,0 +1,1592 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <dbus/dbus.h>
+#include <unistd.h>
+#include <errno.h>
+#include <string.h>
+#include <getopt.h>
+#include <pwd.h>
+#include <locale.h>
+
+#include "log.h"
+#include "util.h"
+#include "macro.h"
+#include "pager.h"
+#include "dbus-common.h"
+#include "build.h"
+#include "strv.h"
+#include "cgroup-show.h"
+#include "sysfs-show.h"
+#include "spawn-polkit-agent.h"
+
+static char **arg_property = NULL;
+static bool arg_all = false;
+static bool arg_full = false;
+static bool arg_no_pager = false;
+static const char *arg_kill_who = NULL;
+static int arg_signal = SIGTERM;
+static enum transport {
+ TRANSPORT_NORMAL,
+ TRANSPORT_SSH,
+ TRANSPORT_POLKIT
+} arg_transport = TRANSPORT_NORMAL;
+static bool arg_ask_password = true;
+static const char *arg_host = NULL;
+
+static void pager_open_if_enabled(void) {
+
+ /* Cache result before we open the pager */
+ if (arg_no_pager)
+ return;
+
+ pager_open(false);
+}
+
+static void polkit_agent_open_if_enabled(void) {
+
+ /* Open the polkit agent as a child process if necessary */
+
+ if (!arg_ask_password)
+ return;
+
+ polkit_agent_open();
+}
+
+static int list_sessions(DBusConnection *bus, char **args, unsigned n) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ int r;
+ DBusMessageIter iter, sub, sub2;
+ unsigned k = 0;
+
+ pager_open_if_enabled();
+
+ r = bus_method_call_with_reply (
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "ListSessions",
+ &reply,
+ NULL,
+ DBUS_TYPE_INVALID);
+ if (r)
+ return r;
+
+ if (!dbus_message_iter_init(reply, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
+ dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_recurse(&iter, &sub);
+
+ if (on_tty())
+ printf("%10s %10s %-16s %-16s\n", "SESSION", "UID", "USER", "SEAT");
+
+ while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ const char *id, *user, *seat, *object;
+ uint32_t uid;
+
+ if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_recurse(&sub, &sub2);
+
+ if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &uid, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &user, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &seat, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &object, false) < 0) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ printf("%10s %10u %-16s %-16s\n", id, (unsigned) uid, user, seat);
+
+ k++;
+
+ dbus_message_iter_next(&sub);
+ }
+
+ if (on_tty())
+ printf("\n%u sessions listed.\n", k);
+
+ return 0;
+}
+
+static int list_users(DBusConnection *bus, char **args, unsigned n) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ int r;
+ DBusMessageIter iter, sub, sub2;
+ unsigned k = 0;
+
+ pager_open_if_enabled();
+
+ r = bus_method_call_with_reply (
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "ListUsers",
+ &reply,
+ NULL,
+ DBUS_TYPE_INVALID);
+ if (r)
+ return r;
+
+ if (!dbus_message_iter_init(reply, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
+ dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_recurse(&iter, &sub);
+
+ if (on_tty())
+ printf("%10s %-16s\n", "UID", "USER");
+
+ while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ const char *user, *object;
+ uint32_t uid;
+
+ if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_recurse(&sub, &sub2);
+
+ if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &uid, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &user, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &object, false) < 0) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ printf("%10u %-16s\n", (unsigned) uid, user);
+
+ k++;
+
+ dbus_message_iter_next(&sub);
+ }
+
+ if (on_tty())
+ printf("\n%u users listed.\n", k);
+
+ return 0;
+}
+
+static int list_seats(DBusConnection *bus, char **args, unsigned n) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ int r;
+ DBusMessageIter iter, sub, sub2;
+ unsigned k = 0;
+
+ pager_open_if_enabled();
+
+ r = bus_method_call_with_reply (
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "ListSeats",
+ &reply,
+ NULL,
+ DBUS_TYPE_INVALID);
+ if (r)
+ return r;
+
+ if (!dbus_message_iter_init(reply, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
+ dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_recurse(&iter, &sub);
+
+ if (on_tty())
+ printf("%-16s\n", "SEAT");
+
+ while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ const char *seat, *object;
+
+ if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_recurse(&sub, &sub2);
+
+ if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &seat, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &object, false) < 0) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ printf("%-16s\n", seat);
+
+ k++;
+
+ dbus_message_iter_next(&sub);
+ }
+
+ if (on_tty())
+ printf("\n%u seats listed.\n", k);
+
+ return 0;
+}
+
+typedef struct SessionStatusInfo {
+ const char *id;
+ uid_t uid;
+ const char *name;
+ usec_t timestamp;
+ const char *default_control_group;
+ int vtnr;
+ const char *seat;
+ const char *tty;
+ const char *display;
+ bool remote;
+ const char *remote_host;
+ const char *remote_user;
+ const char *service;
+ pid_t leader;
+ const char *type;
+ const char *class;
+ const char *state;
+} SessionStatusInfo;
+
+typedef struct UserStatusInfo {
+ uid_t uid;
+ const char *name;
+ usec_t timestamp;
+ const char *default_control_group;
+ const char *state;
+ char **sessions;
+ const char *display;
+} UserStatusInfo;
+
+typedef struct SeatStatusInfo {
+ const char *id;
+ const char *active_session;
+ char **sessions;
+} SeatStatusInfo;
+
+static void print_session_status_info(SessionStatusInfo *i) {
+ char since1[FORMAT_TIMESTAMP_RELATIVE_MAX], *s1;
+ char since2[FORMAT_TIMESTAMP_MAX], *s2;
+ assert(i);
+
+ printf("%s - ", strna(i->id));
+
+ if (i->name)
+ printf("%s (%u)\n", i->name, (unsigned) i->uid);
+ else
+ printf("%u\n", (unsigned) i->uid);
+
+ s1 = format_timestamp_relative(since1, sizeof(since1), i->timestamp);
+ s2 = format_timestamp(since2, sizeof(since2), i->timestamp);
+
+ if (s1)
+ printf("\t Since: %s; %s\n", s2, s1);
+ else if (s2)
+ printf("\t Since: %s\n", s2);
+
+ if (i->leader > 0) {
+ char *t = NULL;
+
+ printf("\t Leader: %u", (unsigned) i->leader);
+
+ get_process_comm(i->leader, &t);
+ if (t) {
+ printf(" (%s)", t);
+ free(t);
+ }
+
+ printf("\n");
+ }
+
+ if (i->seat) {
+ printf("\t Seat: %s", i->seat);
+
+ if (i->vtnr > 0)
+ printf("; vc%i", i->vtnr);
+
+ printf("\n");
+ }
+
+ if (i->tty)
+ printf("\t TTY: %s\n", i->tty);
+ else if (i->display)
+ printf("\t Display: %s\n", i->display);
+
+ if (i->remote_host && i->remote_user)
+ printf("\t Remote: %s@%s\n", i->remote_user, i->remote_host);
+ else if (i->remote_host)
+ printf("\t Remote: %s\n", i->remote_host);
+ else if (i->remote_user)
+ printf("\t Remote: user %s\n", i->remote_user);
+ else if (i->remote)
+ printf("\t Remote: Yes\n");
+
+ if (i->service) {
+ printf("\t Service: %s", i->service);
+
+ if (i->type)
+ printf("; type %s", i->type);
+
+ if (i->class)
+ printf("; class %s", i->class);
+
+ printf("\n");
+ } else if (i->type) {
+ printf("\t Type: %s\n", i->type);
+
+ if (i->class)
+ printf("; class %s", i->class);
+ } else if (i->class)
+ printf("\t Class: %s\n", i->class);
+
+ if (i->state)
+ printf("\t State: %s\n", i->state);
+
+ if (i->default_control_group) {
+ unsigned c;
+ int output_flags =
+ arg_all * OUTPUT_SHOW_ALL |
+ arg_full * OUTPUT_FULL_WIDTH;
+
+ printf("\t CGroup: %s\n", i->default_control_group);
+
+ if (arg_transport != TRANSPORT_SSH) {
+ c = columns();
+ if (c > 18)
+ c -= 18;
+ else
+ c = 0;
+
+ show_cgroup_and_extra_by_spec(i->default_control_group,
+ "\t\t ", c, false, &i->leader,
+ i->leader > 0 ? 1 : 0,
+ output_flags);
+ }
+ }
+}
+
+static void print_user_status_info(UserStatusInfo *i) {
+ char since1[FORMAT_TIMESTAMP_RELATIVE_MAX], *s1;
+ char since2[FORMAT_TIMESTAMP_MAX], *s2;
+ assert(i);
+
+ if (i->name)
+ printf("%s (%u)\n", i->name, (unsigned) i->uid);
+ else
+ printf("%u\n", (unsigned) i->uid);
+
+ s1 = format_timestamp_relative(since1, sizeof(since1), i->timestamp);
+ s2 = format_timestamp(since2, sizeof(since2), i->timestamp);
+
+ if (s1)
+ printf("\t Since: %s; %s\n", s2, s1);
+ else if (s2)
+ printf("\t Since: %s\n", s2);
+
+ if (!isempty(i->state))
+ printf("\t State: %s\n", i->state);
+
+ if (!strv_isempty(i->sessions)) {
+ char **l;
+ printf("\tSessions:");
+
+ STRV_FOREACH(l, i->sessions) {
+ if (streq_ptr(*l, i->display))
+ printf(" *%s", *l);
+ else
+ printf(" %s", *l);
+ }
+
+ printf("\n");
+ }
+
+ if (i->default_control_group) {
+ unsigned c;
+ int output_flags =
+ arg_all * OUTPUT_SHOW_ALL |
+ arg_full * OUTPUT_FULL_WIDTH;
+
+ printf("\t CGroup: %s\n", i->default_control_group);
+
+ if (arg_transport != TRANSPORT_SSH) {
+ c = columns();
+ if (c > 18)
+ c -= 18;
+ else
+ c = 0;
+
+ show_cgroup_by_path(i->default_control_group, "\t\t ",
+ c, false, output_flags);
+ }
+ }
+}
+
+static void print_seat_status_info(SeatStatusInfo *i) {
+ assert(i);
+
+ printf("%s\n", strna(i->id));
+
+ if (!strv_isempty(i->sessions)) {
+ char **l;
+ printf("\tSessions:");
+
+ STRV_FOREACH(l, i->sessions) {
+ if (streq_ptr(*l, i->active_session))
+ printf(" *%s", *l);
+ else
+ printf(" %s", *l);
+ }
+
+ printf("\n");
+ }
+
+ if (arg_transport != TRANSPORT_SSH) {
+ unsigned c;
+
+ c = columns();
+ if (c > 21)
+ c -= 21;
+ else
+ c = 0;
+
+ printf("\t Devices:\n");
+
+ show_sysfs(i->id, "\t\t ", c);
+ }
+}
+
+static int status_property_session(const char *name, DBusMessageIter *iter, SessionStatusInfo *i) {
+ assert(name);
+ assert(iter);
+ assert(i);
+
+ switch (dbus_message_iter_get_arg_type(iter)) {
+
+ case DBUS_TYPE_STRING: {
+ const char *s;
+
+ dbus_message_iter_get_basic(iter, &s);
+
+ if (!isempty(s)) {
+ if (streq(name, "Id"))
+ i->id = s;
+ else if (streq(name, "Name"))
+ i->name = s;
+ else if (streq(name, "DefaultControlGroup"))
+ i->default_control_group = s;
+ else if (streq(name, "TTY"))
+ i->tty = s;
+ else if (streq(name, "Display"))
+ i->display = s;
+ else if (streq(name, "RemoteHost"))
+ i->remote_host = s;
+ else if (streq(name, "RemoteUser"))
+ i->remote_user = s;
+ else if (streq(name, "Service"))
+ i->service = s;
+ else if (streq(name, "Type"))
+ i->type = s;
+ else if (streq(name, "Class"))
+ i->class = s;
+ else if (streq(name, "State"))
+ i->state = s;
+ }
+ break;
+ }
+
+ case DBUS_TYPE_UINT32: {
+ uint32_t u;
+
+ dbus_message_iter_get_basic(iter, &u);
+
+ if (streq(name, "VTNr"))
+ i->vtnr = (int) u;
+ else if (streq(name, "Leader"))
+ i->leader = (pid_t) u;
+
+ break;
+ }
+
+ case DBUS_TYPE_BOOLEAN: {
+ dbus_bool_t b;
+
+ dbus_message_iter_get_basic(iter, &b);
+
+ if (streq(name, "Remote"))
+ i->remote = b;
+
+ break;
+ }
+
+ case DBUS_TYPE_UINT64: {
+ uint64_t u;
+
+ dbus_message_iter_get_basic(iter, &u);
+
+ if (streq(name, "Timestamp"))
+ i->timestamp = (usec_t) u;
+
+ break;
+ }
+
+ case DBUS_TYPE_STRUCT: {
+ DBusMessageIter sub;
+
+ dbus_message_iter_recurse(iter, &sub);
+
+ if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "User")) {
+ uint32_t u;
+
+ dbus_message_iter_get_basic(&sub, &u);
+ i->uid = (uid_t) u;
+
+ } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Seat")) {
+ const char *s;
+
+ dbus_message_iter_get_basic(&sub, &s);
+
+ if (!isempty(s))
+ i->seat = s;
+ }
+
+ break;
+ }
+ }
+
+ return 0;
+}
+
+static int status_property_user(const char *name, DBusMessageIter *iter, UserStatusInfo *i) {
+ assert(name);
+ assert(iter);
+ assert(i);
+
+ switch (dbus_message_iter_get_arg_type(iter)) {
+
+ case DBUS_TYPE_STRING: {
+ const char *s;
+
+ dbus_message_iter_get_basic(iter, &s);
+
+ if (!isempty(s)) {
+ if (streq(name, "Name"))
+ i->name = s;
+ else if (streq(name, "DefaultControlGroup"))
+ i->default_control_group = s;
+ else if (streq(name, "State"))
+ i->state = s;
+ }
+ break;
+ }
+
+ case DBUS_TYPE_UINT32: {
+ uint32_t u;
+
+ dbus_message_iter_get_basic(iter, &u);
+
+ if (streq(name, "UID"))
+ i->uid = (uid_t) u;
+
+ break;
+ }
+
+ case DBUS_TYPE_UINT64: {
+ uint64_t u;
+
+ dbus_message_iter_get_basic(iter, &u);
+
+ if (streq(name, "Timestamp"))
+ i->timestamp = (usec_t) u;
+
+ break;
+ }
+
+ case DBUS_TYPE_STRUCT: {
+ DBusMessageIter sub;
+
+ dbus_message_iter_recurse(iter, &sub);
+
+ if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Display")) {
+ const char *s;
+
+ dbus_message_iter_get_basic(&sub, &s);
+
+ if (!isempty(s))
+ i->display = s;
+ }
+
+ break;
+ }
+
+ case DBUS_TYPE_ARRAY: {
+
+ if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Sessions")) {
+ DBusMessageIter sub, sub2;
+
+ dbus_message_iter_recurse(iter, &sub);
+ while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
+ const char *id;
+ const char *path;
+
+ dbus_message_iter_recurse(&sub, &sub2);
+
+ if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) >= 0 &&
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &path, false) >= 0) {
+ char **l;
+
+ l = strv_append(i->sessions, id);
+ if (!l)
+ return -ENOMEM;
+
+ strv_free(i->sessions);
+ i->sessions = l;
+ }
+
+ dbus_message_iter_next(&sub);
+ }
+
+ return 0;
+ }
+ }
+ }
+
+ return 0;
+}
+
+static int status_property_seat(const char *name, DBusMessageIter *iter, SeatStatusInfo *i) {
+ assert(name);
+ assert(iter);
+ assert(i);
+
+ switch (dbus_message_iter_get_arg_type(iter)) {
+
+ case DBUS_TYPE_STRING: {
+ const char *s;
+
+ dbus_message_iter_get_basic(iter, &s);
+
+ if (!isempty(s)) {
+ if (streq(name, "Id"))
+ i->id = s;
+ }
+ break;
+ }
+
+ case DBUS_TYPE_STRUCT: {
+ DBusMessageIter sub;
+
+ dbus_message_iter_recurse(iter, &sub);
+
+ if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "ActiveSession")) {
+ const char *s;
+
+ dbus_message_iter_get_basic(&sub, &s);
+
+ if (!isempty(s))
+ i->active_session = s;
+ }
+
+ break;
+ }
+
+ case DBUS_TYPE_ARRAY: {
+
+ if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Sessions")) {
+ DBusMessageIter sub, sub2;
+
+ dbus_message_iter_recurse(iter, &sub);
+ while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
+ const char *id;
+ const char *path;
+
+ dbus_message_iter_recurse(&sub, &sub2);
+
+ if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) >= 0 &&
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &path, false) >= 0) {
+ char **l;
+
+ l = strv_append(i->sessions, id);
+ if (!l)
+ return -ENOMEM;
+
+ strv_free(i->sessions);
+ i->sessions = l;
+ }
+
+ dbus_message_iter_next(&sub);
+ }
+
+ return 0;
+ }
+ }
+ }
+
+ return 0;
+}
+
+static int print_property(const char *name, DBusMessageIter *iter) {
+ assert(name);
+ assert(iter);
+
+ if (arg_property && !strv_find(arg_property, name))
+ return 0;
+
+ switch (dbus_message_iter_get_arg_type(iter)) {
+
+ case DBUS_TYPE_STRUCT: {
+ DBusMessageIter sub;
+
+ dbus_message_iter_recurse(iter, &sub);
+
+ if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING &&
+ (streq(name, "Display") || streq(name, "ActiveSession"))) {
+ const char *s;
+
+ dbus_message_iter_get_basic(&sub, &s);
+
+ if (arg_all || !isempty(s))
+ printf("%s=%s\n", name, s);
+ return 0;
+ }
+ break;
+ }
+
+ case DBUS_TYPE_ARRAY:
+
+ if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Sessions")) {
+ DBusMessageIter sub, sub2;
+ bool found = false;
+
+ dbus_message_iter_recurse(iter, &sub);
+ while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
+ const char *id;
+ const char *path;
+
+ dbus_message_iter_recurse(&sub, &sub2);
+
+ if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) >= 0 &&
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &path, false) >= 0) {
+ if (found)
+ printf(" %s", id);
+ else {
+ printf("%s=%s", name, id);
+ found = true;
+ }
+ }
+
+ dbus_message_iter_next(&sub);
+ }
+
+ if (!found && arg_all)
+ printf("%s=\n", name);
+ else if (found)
+ printf("\n");
+
+ return 0;
+ }
+
+ break;
+ }
+
+ if (generic_print_property(name, iter, arg_all) > 0)
+ return 0;
+
+ if (arg_all)
+ printf("%s=[unprintable]\n", name);
+
+ return 0;
+}
+
+static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ const char *interface = "";
+ int r;
+ DBusMessageIter iter, sub, sub2, sub3;
+ SessionStatusInfo session_info = {};
+ UserStatusInfo user_info = {};
+ SeatStatusInfo seat_info = {};
+
+ assert(path);
+ assert(new_line);
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.login1",
+ path,
+ "org.freedesktop.DBus.Properties",
+ "GetAll",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &interface,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ goto finish;
+
+ if (!dbus_message_iter_init(reply, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
+ dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
+ log_error("Failed to parse reply.");
+ r = -EIO;
+ goto finish;
+ }
+
+ dbus_message_iter_recurse(&iter, &sub);
+
+ if (*new_line)
+ printf("\n");
+
+ *new_line = true;
+
+ while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ const char *name;
+
+ if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
+ log_error("Failed to parse reply.");
+ r = -EIO;
+ goto finish;
+ }
+
+ dbus_message_iter_recurse(&sub, &sub2);
+
+ if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
+ log_error("Failed to parse reply.");
+ r = -EIO;
+ goto finish;
+ }
+
+ if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
+ log_error("Failed to parse reply.");
+ r = -EIO;
+ goto finish;
+ }
+
+ dbus_message_iter_recurse(&sub2, &sub3);
+
+ if (show_properties)
+ r = print_property(name, &sub3);
+ else if (strstr(verb, "session"))
+ r = status_property_session(name, &sub3, &session_info);
+ else if (strstr(verb, "user"))
+ r = status_property_user(name, &sub3, &user_info);
+ else
+ r = status_property_seat(name, &sub3, &seat_info);
+
+ if (r < 0) {
+ log_error("Failed to parse reply.");
+ goto finish;
+ }
+
+ dbus_message_iter_next(&sub);
+ }
+
+ if (!show_properties) {
+ if (strstr(verb, "session"))
+ print_session_status_info(&session_info);
+ else if (strstr(verb, "user"))
+ print_user_status_info(&user_info);
+ else
+ print_seat_status_info(&seat_info);
+ }
+
+ r = 0;
+
+finish:
+ strv_free(seat_info.sessions);
+ strv_free(user_info.sessions);
+
+ return r;
+}
+
+static int show(DBusConnection *bus, char **args, unsigned n) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ int r, ret = 0;
+ DBusError error;
+ unsigned i;
+ bool show_properties, new_line = false;
+
+ assert(bus);
+ assert(args);
+
+ dbus_error_init(&error);
+
+ show_properties = !strstr(args[0], "status");
+
+ pager_open_if_enabled();
+
+ if (show_properties && n <= 1) {
+ /* If not argument is specified inspect the manager
+ * itself */
+
+ ret = show_one(args[0], bus, "/org/freedesktop/login1", show_properties, &new_line);
+ goto finish;
+ }
+
+ for (i = 1; i < n; i++) {
+ const char *path = NULL;
+
+ if (strstr(args[0], "session")) {
+
+ ret = bus_method_call_with_reply (
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "GetSession",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &args[i],
+ DBUS_TYPE_INVALID);
+
+ } else if (strstr(args[0], "user")) {
+ uid_t uid;
+ uint32_t u;
+
+ ret = get_user_creds((const char**) (args+i), &uid, NULL, NULL, NULL);
+ if (ret < 0) {
+ log_error("User %s unknown.", args[i]);
+ goto finish;
+ }
+
+ u = (uint32_t) uid;
+ ret = bus_method_call_with_reply (
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "GetUser",
+ &reply,
+ NULL,
+ DBUS_TYPE_UINT32, &u,
+ DBUS_TYPE_INVALID);
+ } else {
+
+ ret = bus_method_call_with_reply (
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "GetSeat",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &args[i],
+ DBUS_TYPE_INVALID);
+ }
+ if (ret)
+ goto finish;
+
+ if (!dbus_message_get_args(reply, &error,
+ DBUS_TYPE_OBJECT_PATH, &path,
+ DBUS_TYPE_INVALID)) {
+ log_error("Failed to parse reply: %s", bus_error_message(&error));
+ ret = -EIO;
+ goto finish;
+ }
+
+ r = show_one(args[0], bus, path, show_properties, &new_line);
+ if (r != 0)
+ ret = r;
+ }
+
+finish:
+ dbus_error_free(&error);
+
+ return ret;
+}
+
+static int activate(DBusConnection *bus, char **args, unsigned n) {
+ int ret = 0;
+ unsigned i;
+
+ assert(args);
+
+ for (i = 1; i < n; i++) {
+
+ ret = bus_method_call_with_reply (
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ streq(args[0], "lock-session") ? "LockSession" :
+ streq(args[0], "unlock-session") ? "UnlockSession" :
+ streq(args[0], "terminate-session") ? "TerminateSession" :
+ "ActivateSession",
+ NULL,
+ NULL,
+ DBUS_TYPE_STRING, &args[i],
+ DBUS_TYPE_INVALID);
+ if (ret)
+ goto finish;
+ }
+
+finish:
+ return ret;
+}
+
+static int kill_session(DBusConnection *bus, char **args, unsigned n) {
+ unsigned i;
+
+ assert(args);
+
+ if (!arg_kill_who)
+ arg_kill_who = "all";
+
+ for (i = 1; i < n; i++) {
+ int r;
+
+ r = bus_method_call_with_reply (
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "KillSession",
+ NULL,
+ NULL,
+ DBUS_TYPE_STRING, &args[i],
+ DBUS_TYPE_STRING, &arg_kill_who,
+ DBUS_TYPE_INT32, &arg_signal,
+ DBUS_TYPE_INVALID);
+ if (r)
+ return r;
+ }
+
+ return 0;
+}
+
+static int enable_linger(DBusConnection *bus, char **args, unsigned n) {
+ unsigned i;
+ dbus_bool_t b, interactive = true;
+
+ assert(args);
+
+ polkit_agent_open_if_enabled();
+
+ b = streq(args[0], "enable-linger");
+
+ for (i = 1; i < n; i++) {
+ uint32_t u;
+ uid_t uid;
+ int r;
+
+ r = get_user_creds((const char**) (args+i), &uid, NULL, NULL, NULL);
+ if (r < 0) {
+ log_error("Failed to resolve user %s: %s", args[i], strerror(-r));
+ return r;
+ }
+
+ u = (uint32_t) uid;
+ r = bus_method_call_with_reply (
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "SetUserLinger",
+ NULL,
+ NULL,
+ DBUS_TYPE_UINT32, &u,
+ DBUS_TYPE_BOOLEAN, &b,
+ DBUS_TYPE_BOOLEAN, &interactive,
+ DBUS_TYPE_INVALID);
+ if (r)
+ return r;
+ }
+
+ return 0;
+}
+
+static int terminate_user(DBusConnection *bus, char **args, unsigned n) {
+ unsigned i;
+
+ assert(args);
+
+ for (i = 1; i < n; i++) {
+ uint32_t u;
+ uid_t uid;
+ int r;
+
+ r = get_user_creds((const char**) (args+i), &uid, NULL, NULL, NULL);
+ if (r < 0) {
+ log_error("Failed to look up user %s: %s", args[i], strerror(-r));
+ return r;
+ }
+
+ u = (uint32_t) uid;
+ r = bus_method_call_with_reply (
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "TerminateUser",
+ NULL,
+ NULL,
+ DBUS_TYPE_UINT32, &u,
+ DBUS_TYPE_INVALID);
+ if (r)
+ return r;
+ }
+
+ return 0;
+}
+
+static int kill_user(DBusConnection *bus, char **args, unsigned n) {
+ unsigned i;
+
+ assert(args);
+
+ if (!arg_kill_who)
+ arg_kill_who = "all";
+
+ for (i = 1; i < n; i++) {
+ uid_t uid;
+ uint32_t u;
+ int r;
+
+ r = get_user_creds((const char**) (args+i), &uid, NULL, NULL, NULL);
+ if (r < 0) {
+ log_error("Failed to look up user %s: %s", args[i], strerror(-r));
+ return r;
+ }
+
+ u = (uint32_t) uid;
+ r = bus_method_call_with_reply (
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "KillUser",
+ NULL,
+ NULL,
+ DBUS_TYPE_UINT32, &u,
+ DBUS_TYPE_INT32, &arg_signal,
+ DBUS_TYPE_INVALID);
+ if (r)
+ return r;
+ }
+
+ return 0;
+}
+
+static int attach(DBusConnection *bus, char **args, unsigned n) {
+ unsigned i;
+ dbus_bool_t interactive = true;
+
+ assert(args);
+
+ polkit_agent_open_if_enabled();
+
+ for (i = 2; i < n; i++) {
+ int r;
+
+ r = bus_method_call_with_reply (
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "AttachDevice",
+ NULL,
+ NULL,
+ DBUS_TYPE_STRING, &args[1],
+ DBUS_TYPE_STRING, &args[i],
+ DBUS_TYPE_BOOLEAN, &interactive,
+ DBUS_TYPE_INVALID);
+ if (r)
+ return r;
+ }
+
+ return 0;
+}
+
+static int flush_devices(DBusConnection *bus, char **args, unsigned n) {
+ dbus_bool_t interactive = true;
+
+ assert(args);
+
+ polkit_agent_open_if_enabled();
+
+ return bus_method_call_with_reply (
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "FlushDevices",
+ NULL,
+ NULL,
+ DBUS_TYPE_BOOLEAN, &interactive,
+ DBUS_TYPE_INVALID);
+}
+
+static int lock_sessions(DBusConnection *bus, char **args, unsigned n) {
+ assert(args);
+
+ polkit_agent_open_if_enabled();
+
+ return bus_method_call_with_reply (
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ streq(args[0], "lock-sessions") ? "LockSessions" : "UnlockSessions",
+ NULL,
+ NULL,
+ DBUS_TYPE_INVALID);
+}
+
+static int terminate_seat(DBusConnection *bus, char **args, unsigned n) {
+ unsigned i;
+
+ assert(args);
+
+ for (i = 1; i < n; i++) {
+ int r;
+
+ r = bus_method_call_with_reply (
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "TerminateSeat",
+ NULL,
+ NULL,
+ DBUS_TYPE_STRING, &args[i],
+ DBUS_TYPE_INVALID);
+ if (r)
+ return r;
+ }
+
+ return 0;
+}
+
+static int help(void) {
+
+ printf("%s [OPTIONS...] {COMMAND} ...\n\n"
+ "Send control commands to or query the login manager.\n\n"
+ " -h --help Show this help\n"
+ " --version Show package version\n"
+ " -p --property=NAME Show only properties by this name\n"
+ " -a --all Show all properties, including empty ones\n"
+ " --kill-who=WHO Who to send signal to\n"
+ " --full Do not ellipsize output\n"
+ " -s --signal=SIGNAL Which signal to send\n"
+ " --no-ask-password Don't prompt for password\n"
+ " -H --host=[USER@]HOST Show information for remote host\n"
+ " -P --privileged Acquire privileges before execution\n"
+ " --no-pager Do not pipe output into a pager\n\n"
+ "Commands:\n"
+ " list-sessions List sessions\n"
+ " session-status [ID...] Show session status\n"
+ " show-session [ID...] Show properties of one or more sessions\n"
+ " activate [ID] Activate a session\n"
+ " lock-session [ID...] Screen lock one or more sessions\n"
+ " unlock-session [ID...] Screen unlock one or more sessions\n"
+ " lock-sessions Screen lock all current sessions\n"
+ " unlock-sessions Screen unlock all current sessions\n"
+ " terminate-session [ID...] Terminate one or more sessions\n"
+ " kill-session [ID...] Send signal to processes of a session\n"
+ " list-users List users\n"
+ " user-status [USER...] Show user status\n"
+ " show-user [USER...] Show properties of one or more users\n"
+ " enable-linger [USER...] Enable linger state of one or more users\n"
+ " disable-linger [USER...] Disable linger state of one or more users\n"
+ " terminate-user [USER...] Terminate all sessions of one or more users\n"
+ " kill-user [USER...] Send signal to processes of a user\n"
+ " list-seats List seats\n"
+ " seat-status [NAME...] Show seat status\n"
+ " show-seat [NAME...] Show properties of one or more seats\n"
+ " attach [NAME] [DEVICE...] Attach one or more devices to a seat\n"
+ " flush-devices Flush all device associations\n"
+ " terminate-seat [NAME...] Terminate all sessions on one or more seats\n",
+ program_invocation_short_name);
+
+ return 0;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+
+ enum {
+ ARG_VERSION = 0x100,
+ ARG_NO_PAGER,
+ ARG_KILL_WHO,
+ ARG_NO_ASK_PASSWORD,
+ ARG_FULL,
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "version", no_argument, NULL, ARG_VERSION },
+ { "property", required_argument, NULL, 'p' },
+ { "all", no_argument, NULL, 'a' },
+ { "no-pager", no_argument, NULL, ARG_NO_PAGER },
+ { "kill-who", required_argument, NULL, ARG_KILL_WHO },
+ { "signal", required_argument, NULL, 's' },
+ { "host", required_argument, NULL, 'H' },
+ { "privileged", no_argument, NULL, 'P' },
+ { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
+ { "full", no_argument, NULL, ARG_FULL },
+ { NULL, 0, NULL, 0 }
+ };
+
+ int c;
+
+ assert(argc >= 0);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "hp:as:H:P", options, NULL)) >= 0) {
+
+ switch (c) {
+
+ case 'h':
+ help();
+ return 0;
+
+ case ARG_VERSION:
+ puts(PACKAGE_STRING);
+ puts(SYSTEMD_FEATURES);
+ return 0;
+
+ case 'p': {
+ char **l;
+
+ l = strv_append(arg_property, optarg);
+ if (!l)
+ return -ENOMEM;
+
+ strv_free(arg_property);
+ arg_property = l;
+
+ /* If the user asked for a particular
+ * property, show it to him, even if it is
+ * empty. */
+ arg_all = true;
+ break;
+ }
+
+ case 'a':
+ arg_all = true;
+ break;
+
+ case ARG_NO_PAGER:
+ arg_no_pager = true;
+ break;
+
+ case ARG_NO_ASK_PASSWORD:
+ arg_ask_password = false;
+ break;
+
+ case ARG_KILL_WHO:
+ arg_kill_who = optarg;
+ break;
+
+ case 's':
+ arg_signal = signal_from_string_try_harder(optarg);
+ if (arg_signal < 0) {
+ log_error("Failed to parse signal string %s.", optarg);
+ return -EINVAL;
+ }
+ break;
+
+ case 'P':
+ arg_transport = TRANSPORT_POLKIT;
+ break;
+
+ case 'H':
+ arg_transport = TRANSPORT_SSH;
+ arg_host = optarg;
+ break;
+
+ case ARG_FULL:
+ arg_full = true;
+ break;
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ log_error("Unknown option code %c", c);
+ return -EINVAL;
+ }
+ }
+
+ return 1;
+}
+
+static int loginctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
+
+ static const struct {
+ const char* verb;
+ const enum {
+ MORE,
+ LESS,
+ EQUAL
+ } argc_cmp;
+ const int argc;
+ int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
+ } verbs[] = {
+ { "list-sessions", LESS, 1, list_sessions },
+ { "session-status", MORE, 2, show },
+ { "show-session", MORE, 1, show },
+ { "activate", EQUAL, 2, activate },
+ { "lock-session", MORE, 2, activate },
+ { "unlock-session", MORE, 2, activate },
+ { "lock-sessions", EQUAL, 1, lock_sessions },
+ { "unlock-sessions", EQUAL, 1, lock_sessions },
+ { "terminate-session", MORE, 2, activate },
+ { "kill-session", MORE, 2, kill_session },
+ { "list-users", EQUAL, 1, list_users },
+ { "user-status", MORE, 2, show },
+ { "show-user", MORE, 1, show },
+ { "enable-linger", MORE, 2, enable_linger },
+ { "disable-linger", MORE, 2, enable_linger },
+ { "terminate-user", MORE, 2, terminate_user },
+ { "kill-user", MORE, 2, kill_user },
+ { "list-seats", EQUAL, 1, list_seats },
+ { "seat-status", MORE, 2, show },
+ { "show-seat", MORE, 1, show },
+ { "attach", MORE, 3, attach },
+ { "flush-devices", EQUAL, 1, flush_devices },
+ { "terminate-seat", MORE, 2, terminate_seat },
+ };
+
+ int left;
+ unsigned i;
+
+ assert(argc >= 0);
+ assert(argv);
+ assert(error);
+
+ left = argc - optind;
+
+ if (left <= 0)
+ /* Special rule: no arguments means "list-sessions" */
+ i = 0;
+ else {
+ if (streq(argv[optind], "help")) {
+ help();
+ return 0;
+ }
+
+ for (i = 0; i < ELEMENTSOF(verbs); i++)
+ if (streq(argv[optind], verbs[i].verb))
+ break;
+
+ if (i >= ELEMENTSOF(verbs)) {
+ log_error("Unknown operation %s", argv[optind]);
+ return -EINVAL;
+ }
+ }
+
+ switch (verbs[i].argc_cmp) {
+
+ case EQUAL:
+ if (left != verbs[i].argc) {
+ log_error("Invalid number of arguments.");
+ return -EINVAL;
+ }
+
+ break;
+
+ case MORE:
+ if (left < verbs[i].argc) {
+ log_error("Too few arguments.");
+ return -EINVAL;
+ }
+
+ break;
+
+ case LESS:
+ if (left > verbs[i].argc) {
+ log_error("Too many arguments.");
+ return -EINVAL;
+ }
+
+ break;
+
+ default:
+ assert_not_reached("Unknown comparison operator.");
+ }
+
+ if (!bus) {
+ log_error("Failed to get D-Bus connection: %s", error->message);
+ return -EIO;
+ }
+
+ return verbs[i].dispatch(bus, argv + optind, left);
+}
+
+int main(int argc, char*argv[]) {
+ int r, retval = EXIT_FAILURE;
+ DBusConnection *bus = NULL;
+ DBusError error;
+
+ dbus_error_init(&error);
+
+ setlocale(LC_ALL, "");
+ log_parse_environment();
+ log_open();
+
+ r = parse_argv(argc, argv);
+ if (r < 0)
+ goto finish;
+ else if (r == 0) {
+ retval = EXIT_SUCCESS;
+ goto finish;
+ }
+
+ if (arg_transport == TRANSPORT_NORMAL)
+ bus = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error);
+ else if (arg_transport == TRANSPORT_POLKIT)
+ bus_connect_system_polkit(&bus, &error);
+ else if (arg_transport == TRANSPORT_SSH)
+ bus_connect_system_ssh(NULL, arg_host, &bus, &error);
+ else
+ assert_not_reached("Uh, invalid transport...");
+
+ r = loginctl_main(bus, argc, argv, &error);
+ retval = r < 0 ? EXIT_FAILURE : r;
+
+finish:
+ if (bus) {
+ dbus_connection_flush(bus);
+ dbus_connection_close(bus);
+ dbus_connection_unref(bus);
+ }
+
+ dbus_error_free(&error);
+ dbus_shutdown();
+
+ strv_free(arg_property);
+
+ pager_close();
+
+ return retval;
+}
diff --git a/src/login/logind-acl.c b/src/login/logind-acl.c
new file mode 100644
index 0000000000..cb045a9928
--- /dev/null
+++ b/src/login/logind-acl.c
@@ -0,0 +1,248 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <sys/acl.h>
+#include <acl/libacl.h>
+#include <errno.h>
+#include <string.h>
+
+#include "logind-acl.h"
+#include "util.h"
+#include "acl-util.h"
+
+static int flush_acl(acl_t acl) {
+ acl_entry_t i;
+ int found;
+ bool changed = false;
+
+ assert(acl);
+
+ for (found = acl_get_entry(acl, ACL_FIRST_ENTRY, &i);
+ found > 0;
+ found = acl_get_entry(acl, ACL_NEXT_ENTRY, &i)) {
+
+ acl_tag_t tag;
+
+ if (acl_get_tag_type(i, &tag) < 0)
+ return -errno;
+
+ if (tag != ACL_USER)
+ continue;
+
+ if (acl_delete_entry(acl, i) < 0)
+ return -errno;
+
+ changed = true;
+ }
+
+ if (found < 0)
+ return -errno;
+
+ return changed;
+}
+
+int devnode_acl(const char *path,
+ bool flush,
+ bool del, uid_t old_uid,
+ bool add, uid_t new_uid) {
+
+ acl_t acl;
+ int r = 0;
+ bool changed = false;
+
+ assert(path);
+
+ acl = acl_get_file(path, ACL_TYPE_ACCESS);
+ if (!acl)
+ return -errno;
+
+ if (flush) {
+
+ r = flush_acl(acl);
+ if (r < 0)
+ goto finish;
+ if (r > 0)
+ changed = true;
+
+ } else if (del && old_uid > 0) {
+ acl_entry_t entry;
+
+ r = acl_find_uid(acl, old_uid, &entry);
+ if (r < 0)
+ goto finish;
+
+ if (r > 0) {
+ if (acl_delete_entry(acl, entry) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ changed = true;
+ }
+ }
+
+ if (add && new_uid > 0) {
+ acl_entry_t entry;
+ acl_permset_t permset;
+ int rd, wt;
+
+ r = acl_find_uid(acl, new_uid, &entry);
+ if (r < 0)
+ goto finish;
+
+ if (r == 0) {
+ if (acl_create_entry(&acl, &entry) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ if (acl_set_tag_type(entry, ACL_USER) < 0 ||
+ acl_set_qualifier(entry, &new_uid) < 0) {
+ r = -errno;
+ goto finish;
+ }
+ }
+
+ if (acl_get_permset(entry, &permset) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ rd = acl_get_perm(permset, ACL_READ);
+ if (rd < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ wt = acl_get_perm(permset, ACL_WRITE);
+ if (wt < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ if (!rd || !wt) {
+
+ if (acl_add_perm(permset, ACL_READ|ACL_WRITE) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ changed = true;
+ }
+ }
+
+ if (!changed)
+ goto finish;
+
+ if (acl_calc_mask(&acl) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ if (acl_set_file(path, ACL_TYPE_ACCESS, acl) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ r = 0;
+
+finish:
+ acl_free(acl);
+
+ return r;
+}
+
+int devnode_acl_all(struct udev *udev,
+ const char *seat,
+ bool flush,
+ bool del, uid_t old_uid,
+ bool add, uid_t new_uid) {
+
+ struct udev_list_entry *item = NULL, *first = NULL;
+ struct udev_enumerate *e;
+ int r;
+
+ assert(udev);
+
+ if (isempty(seat))
+ seat = "seat0";
+
+ e = udev_enumerate_new(udev);
+ if (!e)
+ return -ENOMEM;
+
+ /* We can only match by one tag in libudev. We choose
+ * "uaccess" for that. If we could match for two tags here we
+ * could add the seat name as second match tag, but this would
+ * be hardly optimizable in libudev, and hence checking the
+ * second tag manually in our loop is a good solution. */
+
+ r = udev_enumerate_add_match_tag(e, "uaccess");
+ if (r < 0)
+ goto finish;
+
+ r = udev_enumerate_scan_devices(e);
+ if (r < 0)
+ goto finish;
+
+ first = udev_enumerate_get_list_entry(e);
+ udev_list_entry_foreach(item, first) {
+ struct udev_device *d;
+ const char *node, *sn;
+
+ d = udev_device_new_from_syspath(udev, udev_list_entry_get_name(item));
+ if (!d) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ sn = udev_device_get_property_value(d, "ID_SEAT");
+ if (isempty(sn))
+ sn = "seat0";
+
+ if (!streq(seat, sn)) {
+ udev_device_unref(d);
+ continue;
+ }
+
+ node = udev_device_get_devnode(d);
+ if (!node) {
+ /* In case people mistag devices with nodes, we need to ignore this */
+ udev_device_unref(d);
+ continue;
+ }
+
+ log_debug("Fixing up %s for seat %s...", node, sn);
+
+ r = devnode_acl(node, flush, del, old_uid, add, new_uid);
+ udev_device_unref(d);
+
+ if (r < 0)
+ goto finish;
+ }
+
+finish:
+ if (e)
+ udev_enumerate_unref(e);
+
+ return r;
+}
diff --git a/src/login/logind-acl.h b/src/login/logind-acl.h
new file mode 100644
index 0000000000..ec09843a78
--- /dev/null
+++ b/src/login/logind-acl.h
@@ -0,0 +1,57 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/types.h>
+#include <stdbool.h>
+#include <libudev.h>
+
+#ifdef HAVE_ACL
+
+int devnode_acl(const char *path,
+ bool flush,
+ bool del, uid_t old_uid,
+ bool add, uid_t new_uid);
+
+int devnode_acl_all(struct udev *udev,
+ const char *seat,
+ bool flush,
+ bool del, uid_t old_uid,
+ bool add, uid_t new_uid);
+#else
+
+static inline int devnode_acl(const char *path,
+ bool flush,
+ bool del, uid_t old_uid,
+ bool add, uid_t new_uid) {
+ return 0;
+}
+
+static inline int devnode_acl_all(struct udev *udev,
+ const char *seat,
+ bool flush,
+ bool del, uid_t old_uid,
+ bool add, uid_t new_uid) {
+ return 0;
+}
+
+#endif
diff --git a/src/login/logind-action.c b/src/login/logind-action.c
new file mode 100644
index 0000000000..c930591023
--- /dev/null
+++ b/src/login/logind-action.c
@@ -0,0 +1,151 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <unistd.h>
+
+#include <systemd/sd-messages.h>
+
+#include "conf-parser.h"
+#include "special.h"
+#include "dbus-common.h"
+#include "logind-action.h"
+#include "sleep-config.h"
+
+int manager_handle_action(
+ Manager *m,
+ InhibitWhat inhibit_key,
+ HandleAction handle,
+ bool ignore_inhibited,
+ bool is_edge) {
+
+ static const char * const message_table[_HANDLE_ACTION_MAX] = {
+ [HANDLE_POWEROFF] = "Powering Off...",
+ [HANDLE_REBOOT] = "Rebooting...",
+ [HANDLE_HALT] = "Halting...",
+ [HANDLE_KEXEC] = "Rebooting via kexec...",
+ [HANDLE_SUSPEND] = "Suspending...",
+ [HANDLE_HIBERNATE] = "Hibernating...",
+ [HANDLE_HYBRID_SLEEP] = "Hibernating and suspending..."
+ };
+
+ static const char * const target_table[_HANDLE_ACTION_MAX] = {
+ [HANDLE_POWEROFF] = SPECIAL_POWEROFF_TARGET,
+ [HANDLE_REBOOT] = SPECIAL_REBOOT_TARGET,
+ [HANDLE_HALT] = SPECIAL_HALT_TARGET,
+ [HANDLE_KEXEC] = SPECIAL_KEXEC_TARGET,
+ [HANDLE_SUSPEND] = SPECIAL_SUSPEND_TARGET,
+ [HANDLE_HIBERNATE] = SPECIAL_HIBERNATE_TARGET,
+ [HANDLE_HYBRID_SLEEP] = SPECIAL_HYBRID_SLEEP_TARGET
+ };
+
+ DBusError error;
+ int r;
+ InhibitWhat inhibit_operation;
+ bool supported;
+
+ assert(m);
+
+ if (m->action_what) {
+ log_debug("Action already in progress, ignoring.");
+ return -EALREADY;
+ }
+
+ /* If the key handling is turned off, don't do anything */
+ if (handle == HANDLE_IGNORE) {
+ log_debug("Refusing operation, as it is turned off.");
+ return 0;
+ }
+
+ if (handle == HANDLE_SUSPEND)
+ supported = can_sleep("suspend") > 0;
+ else if (handle == HANDLE_HIBERNATE)
+ supported = can_sleep("hibernate") > 0;
+ else if (handle == HANDLE_HYBRID_SLEEP)
+ supported = can_sleep("hybrid-sleep") > 0;
+ else if (handle == HANDLE_KEXEC)
+ supported = access("/sbin/kexec", X_OK) >= 0;
+ else
+ supported = true;
+
+ if (!supported) {
+ log_warning("Requested operation not supported, ignoring.");
+ return -ENOTSUP;
+ }
+
+ /* If the key handling is inhibited, don't do anything */
+ if (inhibit_key > 0) {
+ if (manager_is_inhibited(m, inhibit_key, INHIBIT_BLOCK, NULL, true, false, 0)) {
+ log_debug("Refusing operation, %s is inhibited.", inhibit_what_to_string(inhibit_key));
+ return 0;
+ }
+ }
+
+ /* Locking is handled differently from the rest. */
+ if (handle == HANDLE_LOCK) {
+ log_info("Locking sessions...");
+ session_send_lock_all(m, true);
+ return 1;
+ }
+
+ inhibit_operation = handle == HANDLE_SUSPEND || handle == HANDLE_HIBERNATE || handle == HANDLE_HYBRID_SLEEP ? INHIBIT_SLEEP : INHIBIT_SHUTDOWN;
+
+ /* If the actual operation is inhibited, warn and fail */
+ if (!ignore_inhibited &&
+ manager_is_inhibited(m, inhibit_operation, INHIBIT_BLOCK, NULL, false, false, 0)) {
+
+ /* If this is just a recheck of the lid switch then don't warn about anything */
+ if (!is_edge) {
+ log_debug("Refusing operation, %s is inhibited.", inhibit_what_to_string(inhibit_operation));
+ return 0;
+ }
+
+ log_error("Refusing operation, %s is inhibited.", inhibit_what_to_string(inhibit_operation));
+ warn_melody();
+ return -EPERM;
+ }
+
+ log_info("%s", message_table[handle]);
+
+ dbus_error_init(&error);
+ r = bus_manager_shutdown_or_sleep_now_or_later(m, target_table[handle], inhibit_operation, &error);
+ if (r < 0) {
+ log_error("Failed to execute operation: %s", bus_error_message(&error));
+ dbus_error_free(&error);
+ return r;
+ }
+
+ return 1;
+}
+
+static const char* const handle_action_table[_HANDLE_ACTION_MAX] = {
+ [HANDLE_IGNORE] = "ignore",
+ [HANDLE_POWEROFF] = "poweroff",
+ [HANDLE_REBOOT] = "reboot",
+ [HANDLE_HALT] = "halt",
+ [HANDLE_KEXEC] = "kexec",
+ [HANDLE_SUSPEND] = "suspend",
+ [HANDLE_HIBERNATE] = "hibernate",
+ [HANDLE_HYBRID_SLEEP] = "hybrid-sleep",
+ [HANDLE_LOCK] = "lock"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(handle_action, HandleAction);
+DEFINE_CONFIG_PARSE_ENUM(config_parse_handle_action, handle_action, HandleAction, "Failed to parse handle action setting");
diff --git a/src/login/logind-action.h b/src/login/logind-action.h
new file mode 100644
index 0000000000..552713637d
--- /dev/null
+++ b/src/login/logind-action.h
@@ -0,0 +1,54 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef foologindactionhfoo
+#define foologindactionhfoo
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+typedef enum HandleAction {
+ HANDLE_IGNORE,
+ HANDLE_POWEROFF,
+ HANDLE_REBOOT,
+ HANDLE_HALT,
+ HANDLE_KEXEC,
+ HANDLE_SUSPEND,
+ HANDLE_HIBERNATE,
+ HANDLE_HYBRID_SLEEP,
+ HANDLE_LOCK,
+ _HANDLE_ACTION_MAX,
+ _HANDLE_ACTION_INVALID = -1
+} HandleAction;
+
+#include "logind.h"
+#include "logind-inhibit.h"
+
+int manager_handle_action(
+ Manager *m,
+ InhibitWhat inhibit_key,
+ HandleAction handle,
+ bool ignore_inhibited,
+ bool is_edge);
+
+const char* handle_action_to_string(HandleAction h) _const_;
+HandleAction handle_action_from_string(const char *s) _pure_;
+
+int config_parse_handle_action(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+
+#endif
diff --git a/src/login/logind-button.c b/src/login/logind-button.c
new file mode 100644
index 0000000000..ea45c28eef
--- /dev/null
+++ b/src/login/logind-button.c
@@ -0,0 +1,261 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <string.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <sys/ioctl.h>
+#include <unistd.h>
+#include <linux/input.h>
+#include <sys/epoll.h>
+
+#include "conf-parser.h"
+#include "util.h"
+#include "logind-button.h"
+#include "special.h"
+#include "dbus-common.h"
+#include "sd-messages.h"
+
+Button* button_new(Manager *m, const char *name) {
+ Button *b;
+
+ assert(m);
+ assert(name);
+
+ b = new0(Button, 1);
+ if (!b)
+ return NULL;
+
+ b->name = strdup(name);
+ if (!b->name) {
+ free(b);
+ return NULL;
+ }
+
+ if (hashmap_put(m->buttons, b->name, b) < 0) {
+ free(b->name);
+ free(b);
+ return NULL;
+ }
+
+ b->manager = m;
+ b->fd = -1;
+
+ return b;
+}
+
+void button_free(Button *b) {
+ assert(b);
+
+ hashmap_remove(b->manager->buttons, b->name);
+
+ if (b->fd >= 0) {
+ hashmap_remove(b->manager->button_fds, INT_TO_PTR(b->fd + 1));
+ assert_se(epoll_ctl(b->manager->epoll_fd, EPOLL_CTL_DEL, b->fd, NULL) == 0);
+
+ /* If the device has been unplugged close() returns
+ * ENODEV, let's ignore this, hence we don't use
+ * close_nointr_nofail() */
+ close(b->fd);
+ }
+
+ free(b->name);
+ free(b->seat);
+ free(b);
+}
+
+int button_set_seat(Button *b, const char *sn) {
+ char *s;
+
+ assert(b);
+ assert(sn);
+
+ s = strdup(sn);
+ if (!s)
+ return -ENOMEM;
+
+ free(b->seat);
+ b->seat = s;
+
+ return 0;
+}
+
+int button_open(Button *b) {
+ char name[256], *p;
+ struct epoll_event ev;
+ int r;
+
+ assert(b);
+
+ if (b->fd >= 0) {
+ close(b->fd);
+ b->fd = -1;
+ }
+
+ p = strappend("/dev/input/", b->name);
+ if (!p)
+ return log_oom();
+
+ b->fd = open(p, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
+ free(p);
+ if (b->fd < 0) {
+ log_warning("Failed to open %s: %m", b->name);
+ return -errno;
+ }
+
+ if (ioctl(b->fd, EVIOCGNAME(sizeof(name)), name) < 0) {
+ log_error("Failed to get input name: %m");
+ r = -errno;
+ goto fail;
+ }
+
+ zero(ev);
+ ev.events = EPOLLIN;
+ ev.data.u32 = FD_OTHER_BASE + b->fd;
+
+ if (epoll_ctl(b->manager->epoll_fd, EPOLL_CTL_ADD, b->fd, &ev) < 0) {
+ log_error("Failed to add to epoll: %m");
+ r = -errno;
+ goto fail;
+ }
+
+ r = hashmap_put(b->manager->button_fds, INT_TO_PTR(b->fd + 1), b);
+ if (r < 0) {
+ log_error("Failed to add to hash map: %s", strerror(-r));
+ assert_se(epoll_ctl(b->manager->epoll_fd, EPOLL_CTL_DEL, b->fd, NULL) == 0);
+ goto fail;
+ }
+
+ log_info("Watching system buttons on /dev/input/%s (%s)", b->name, name);
+
+ return 0;
+
+fail:
+ close(b->fd);
+ b->fd = -1;
+ return r;
+}
+
+static int button_handle(
+ Button *b,
+ InhibitWhat inhibit_key,
+ HandleAction handle,
+ bool ignore_inhibited,
+ bool is_edge) {
+
+ int r;
+
+ assert(b);
+
+ r = manager_handle_action(b->manager, inhibit_key, handle, ignore_inhibited, is_edge);
+ if (r > 0)
+ /* We are executing the operation, so make sure we don't
+ * execute another one until the lid is opened/closed again */
+ b->lid_close_queued = false;
+
+ return r;
+}
+
+int button_process(Button *b) {
+ struct input_event ev;
+ ssize_t l;
+
+ assert(b);
+
+ l = read(b->fd, &ev, sizeof(ev));
+ if (l < 0)
+ return errno != EAGAIN ? -errno : 0;
+ if ((size_t) l < sizeof(ev))
+ return -EIO;
+
+ if (ev.type == EV_KEY && ev.value > 0) {
+
+ switch (ev.code) {
+
+ case KEY_POWER:
+ case KEY_POWER2:
+ log_struct(LOG_INFO,
+ "MESSAGE=Power key pressed.",
+ MESSAGE_ID(SD_MESSAGE_POWER_KEY),
+ NULL);
+ return button_handle(b, INHIBIT_HANDLE_POWER_KEY, b->manager->handle_power_key, b->manager->power_key_ignore_inhibited, true);
+
+ /* The kernel is a bit confused here:
+
+ KEY_SLEEP = suspend-to-ram, which everybody else calls "suspend"
+ KEY_SUSPEND = suspend-to-disk, which everybody else calls "hibernate"
+ */
+
+ case KEY_SLEEP:
+ log_struct(LOG_INFO,
+ "MESSAGE=Suspend key pressed.",
+ MESSAGE_ID(SD_MESSAGE_SUSPEND_KEY),
+ NULL);
+ return button_handle(b, INHIBIT_HANDLE_SUSPEND_KEY, b->manager->handle_suspend_key, b->manager->suspend_key_ignore_inhibited, true);
+
+ case KEY_SUSPEND:
+ log_struct(LOG_INFO,
+ "MESSAGE=Hibernate key pressed.",
+ MESSAGE_ID(SD_MESSAGE_HIBERNATE_KEY),
+ NULL);
+ return button_handle(b, INHIBIT_HANDLE_HIBERNATE_KEY, b->manager->handle_hibernate_key, b->manager->hibernate_key_ignore_inhibited, true);
+ }
+
+ } else if (ev.type == EV_SW && ev.value > 0) {
+
+ switch (ev.code) {
+
+ case SW_LID:
+ log_struct(LOG_INFO,
+ "MESSAGE=Lid closed.",
+ MESSAGE_ID(SD_MESSAGE_LID_CLOSED),
+ NULL);
+ b->lid_close_queued = true;
+
+ return button_handle(b, INHIBIT_HANDLE_LID_SWITCH, b->manager->handle_lid_switch, b->manager->lid_switch_ignore_inhibited, true);
+ }
+
+ } else if (ev.type == EV_SW && ev.value == 0) {
+
+ switch (ev.code) {
+
+ case SW_LID:
+ log_struct(LOG_INFO,
+ "MESSAGE=Lid opened.",
+ MESSAGE_ID(SD_MESSAGE_LID_OPENED),
+ NULL);
+ b->lid_close_queued = false;
+ break;
+ }
+ }
+
+ return 0;
+}
+
+int button_recheck(Button *b) {
+ assert(b);
+
+ if (!b->lid_close_queued)
+ return 0;
+
+ return button_handle(b, INHIBIT_HANDLE_LID_SWITCH, b->manager->handle_lid_switch, b->manager->lid_switch_ignore_inhibited, false);
+}
diff --git a/src/login/logind-button.h b/src/login/logind-button.h
new file mode 100644
index 0000000000..1c5a84553d
--- /dev/null
+++ b/src/login/logind-button.h
@@ -0,0 +1,48 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef foologindbuttonhfoo
+#define foologindbuttonhfoo
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+typedef struct Button Button;
+
+#include "list.h"
+#include "util.h"
+#include "logind.h"
+
+struct Button {
+ Manager *manager;
+
+ char *name;
+ char *seat;
+ int fd;
+
+ bool lid_close_queued;
+};
+
+Button* button_new(Manager *m, const char *name);
+void button_free(Button*b);
+int button_open(Button *b);
+int button_process(Button *b);
+int button_recheck(Button *b);
+int button_set_seat(Button *b, const char *sn);
+
+#endif
diff --git a/src/login/logind-dbus.c b/src/login/logind-dbus.c
new file mode 100644
index 0000000000..4a84b860f1
--- /dev/null
+++ b/src/login/logind-dbus.c
@@ -0,0 +1,2446 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <string.h>
+#include <unistd.h>
+#include <pwd.h>
+
+#include "logind.h"
+#include "dbus-common.h"
+#include "strv.h"
+#include "mkdir.h"
+#include "path-util.h"
+#include "polkit.h"
+#include "special.h"
+#include "sleep-config.h"
+#include "systemd/sd-id128.h"
+#include "systemd/sd-messages.h"
+#include "fileio-label.h"
+#include "label.h"
+
+#define BUS_MANAGER_INTERFACE \
+ " <interface name=\"org.freedesktop.login1.Manager\">\n" \
+ " <method name=\"GetSession\">\n" \
+ " <arg name=\"id\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"session\" type=\"o\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"GetSessionByPID\">\n" \
+ " <arg name=\"pid\" type=\"u\" direction=\"in\"/>\n" \
+ " <arg name=\"session\" type=\"o\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"GetUser\">\n" \
+ " <arg name=\"uid\" type=\"u\" direction=\"in\"/>\n" \
+ " <arg name=\"user\" type=\"o\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"GetSeat\">\n" \
+ " <arg name=\"id\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"seat\" type=\"o\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"ListSessions\">\n" \
+ " <arg name=\"sessions\" type=\"a(susso)\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"ListUsers\">\n" \
+ " <arg name=\"users\" type=\"a(uso)\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"ListSeats\">\n" \
+ " <arg name=\"seats\" type=\"a(so)\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"CreateSession\">\n" \
+ " <arg name=\"uid\" type=\"u\" direction=\"in\"/>\n" \
+ " <arg name=\"leader\" type=\"u\" direction=\"in\"/>\n" \
+ " <arg name=\"service\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"type\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"class\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"seat\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"vtnr\" type=\"u\" direction=\"in\"/>\n" \
+ " <arg name=\"tty\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"display\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"remote\" type=\"b\" direction=\"in\"/>\n" \
+ " <arg name=\"remote_user\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"remote_host\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"controllers\" type=\"as\" direction=\"in\"/>\n" \
+ " <arg name=\"reset_controllers\" type=\"as\" direction=\"in\"/>\n" \
+ " <arg name=\"kill_processes\" type=\"b\" direction=\"in\"/>\n" \
+ " <arg name=\"id\" type=\"s\" direction=\"out\"/>\n" \
+ " <arg name=\"path\" type=\"o\" direction=\"out\"/>\n" \
+ " <arg name=\"runtime_path\" type=\"o\" direction=\"out\"/>\n" \
+ " <arg name=\"fd\" type=\"h\" direction=\"out\"/>\n" \
+ " <arg name=\"seat\" type=\"s\" direction=\"out\"/>\n" \
+ " <arg name=\"vtnr\" type=\"u\" direction=\"out\"/>\n" \
+ " <arg name=\"existing\" type=\"b\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"ReleaseSession\">\n" \
+ " <arg name=\"id\" type=\"s\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"ActivateSession\">\n" \
+ " <arg name=\"id\" type=\"s\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"ActivateSessionOnSeat\">\n" \
+ " <arg name=\"id\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"seat\" type=\"s\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"LockSession\">\n" \
+ " <arg name=\"id\" type=\"s\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"UnlockSession\">\n" \
+ " <arg name=\"id\" type=\"s\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"LockSessions\"/>\n" \
+ " <method name=\"UnlockSessions\"/>\n" \
+ " <method name=\"KillSession\">\n" \
+ " <arg name=\"id\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"who\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"signal\" type=\"s\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"KillUser\">\n" \
+ " <arg name=\"uid\" type=\"u\" direction=\"in\"/>\n" \
+ " <arg name=\"signal\" type=\"s\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"TerminateSession\">\n" \
+ " <arg name=\"id\" type=\"s\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"TerminateUser\">\n" \
+ " <arg name=\"uid\" type=\"u\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"TerminateSeat\">\n" \
+ " <arg name=\"id\" type=\"s\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"SetUserLinger\">\n" \
+ " <arg name=\"uid\" type=\"u\" direction=\"in\"/>\n" \
+ " <arg name=\"b\" type=\"b\" direction=\"in\"/>\n" \
+ " <arg name=\"interactive\" type=\"b\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"AttachDevice\">\n" \
+ " <arg name=\"seat\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"sysfs\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"interactive\" type=\"b\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"FlushDevices\">\n" \
+ " <arg name=\"interactive\" type=\"b\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"PowerOff\">\n" \
+ " <arg name=\"interactive\" type=\"b\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"Reboot\">\n" \
+ " <arg name=\"interactive\" type=\"b\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"Suspend\">\n" \
+ " <arg name=\"interactive\" type=\"b\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"Hibernate\">\n" \
+ " <arg name=\"interactive\" type=\"b\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"HybridSleep\">\n" \
+ " <arg name=\"interactive\" type=\"b\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"CanPowerOff\">\n" \
+ " <arg name=\"result\" type=\"s\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"CanReboot\">\n" \
+ " <arg name=\"result\" type=\"s\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"CanSuspend\">\n" \
+ " <arg name=\"result\" type=\"s\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"CanHibernate\">\n" \
+ " <arg name=\"result\" type=\"s\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"CanHybridSleep\">\n" \
+ " <arg name=\"result\" type=\"s\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"Inhibit\">\n" \
+ " <arg name=\"what\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"who\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"why\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"mode\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"fd\" type=\"h\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <method name=\"ListInhibitors\">\n" \
+ " <arg name=\"inhibitors\" type=\"a(ssssuu)\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " <signal name=\"SessionNew\">\n" \
+ " <arg name=\"id\" type=\"s\"/>\n" \
+ " <arg name=\"path\" type=\"o\"/>\n" \
+ " </signal>\n" \
+ " <signal name=\"SessionRemoved\">\n" \
+ " <arg name=\"id\" type=\"s\"/>\n" \
+ " <arg name=\"path\" type=\"o\"/>\n" \
+ " </signal>\n" \
+ " <signal name=\"UserNew\">\n" \
+ " <arg name=\"uid\" type=\"u\"/>\n" \
+ " <arg name=\"path\" type=\"o\"/>\n" \
+ " </signal>\n" \
+ " <signal name=\"UserRemoved\">\n" \
+ " <arg name=\"uid\" type=\"u\"/>\n" \
+ " <arg name=\"path\" type=\"o\"/>\n" \
+ " </signal>\n" \
+ " <signal name=\"SeatNew\">\n" \
+ " <arg name=\"id\" type=\"s\"/>\n" \
+ " <arg name=\"path\" type=\"o\"/>\n" \
+ " </signal>\n" \
+ " <signal name=\"SeatRemoved\">\n" \
+ " <arg name=\"id\" type=\"s\"/>\n" \
+ " <arg name=\"path\" type=\"o\"/>\n" \
+ " </signal>\n" \
+ " <signal name=\"PrepareForShutdown\">\n" \
+ " <arg name=\"active\" type=\"b\"/>\n" \
+ " </signal>\n" \
+ " <signal name=\"PrepareForSleep\">\n" \
+ " <arg name=\"active\" type=\"b\"/>\n" \
+ " </signal>\n" \
+ " <property name=\"ControlGroupHierarchy\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"Controllers\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"ResetControllers\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"NAutoVTs\" type=\"u\" access=\"read\"/>\n" \
+ " <property name=\"KillOnlyUsers\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"KillExcludeUsers\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"KillUserProcesses\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"IdleHint\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"IdleSinceHint\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"IdleSinceHintMonotonic\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"BlockInhibited\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"DelayInhibited\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"InhibitDelayMaxUSec\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"HandlePowerKey\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"HandleSuspendKey\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"HandleHibernateKey\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"HandleLidSwitch\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"IdleAction\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"IdleActionUSec\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"PreparingForShutdown\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"PreparingForSleep\" type=\"b\" access=\"read\"/>\n" \
+ " </interface>\n"
+
+#define INTROSPECTION_BEGIN \
+ DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE \
+ "<node>\n" \
+ BUS_MANAGER_INTERFACE \
+ BUS_PROPERTIES_INTERFACE \
+ BUS_PEER_INTERFACE \
+ BUS_INTROSPECTABLE_INTERFACE
+
+#define INTROSPECTION_END \
+ "</node>\n"
+
+#define INTERFACES_LIST \
+ BUS_GENERIC_INTERFACES_LIST \
+ "org.freedesktop.login1.Manager\0"
+
+static int bus_manager_append_idle_hint(DBusMessageIter *i, const char *property, void *data) {
+ Manager *m = data;
+ dbus_bool_t b;
+
+ assert(i);
+ assert(property);
+ assert(m);
+
+ b = manager_get_idle_hint(m, NULL) > 0;
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_BOOLEAN, &b))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_manager_append_idle_hint_since(DBusMessageIter *i, const char *property, void *data) {
+ Manager *m = data;
+ dual_timestamp t;
+ uint64_t u;
+
+ assert(i);
+ assert(property);
+ assert(m);
+
+ manager_get_idle_hint(m, &t);
+ u = streq(property, "IdleSinceHint") ? t.realtime : t.monotonic;
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT64, &u))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_manager_append_inhibited(DBusMessageIter *i, const char *property, void *data) {
+ Manager *m = data;
+ InhibitWhat w;
+ const char *p;
+
+ w = manager_inhibit_what(m, streq(property, "BlockInhibited") ? INHIBIT_BLOCK : INHIBIT_DELAY);
+ p = inhibit_what_to_string(w);
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_STRING, &p))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_manager_append_preparing(DBusMessageIter *i, const char *property, void *data) {
+ Manager *m = data;
+ dbus_bool_t b;
+
+ assert(i);
+ assert(property);
+
+ if (streq(property, "PreparingForShutdown"))
+ b = !!(m->action_what & INHIBIT_SHUTDOWN);
+ else
+ b = !!(m->action_what & INHIBIT_SLEEP);
+
+ dbus_message_iter_append_basic(i, DBUS_TYPE_BOOLEAN, &b);
+ return 0;
+}
+
+static int bus_manager_create_session(Manager *m, DBusMessage *message, DBusMessage **_reply) {
+ const char *type, *class, *cseat, *tty, *display, *remote_user, *remote_host, *service;
+ uint32_t uid, leader, audit_id = 0;
+ dbus_bool_t remote, kill_processes, exists;
+ _cleanup_strv_free_ char **controllers = NULL, **reset_controllers = NULL;
+ _cleanup_free_ char *cgroup = NULL, *id = NULL, *p = NULL;
+ SessionType t;
+ SessionClass c;
+ DBusMessageIter iter;
+ int r;
+ uint32_t vtnr = 0;
+ _cleanup_close_ int fifo_fd = -1;
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ Session *session = NULL;
+ User *user = NULL;
+ Seat *seat = NULL;
+ bool b;
+
+ assert(m);
+ assert(message);
+ assert(_reply);
+
+ if (!dbus_message_iter_init(message, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_UINT32)
+ return -EINVAL;
+
+ dbus_message_iter_get_basic(&iter, &uid);
+
+ if (!dbus_message_iter_next(&iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_UINT32)
+ return -EINVAL;
+
+ dbus_message_iter_get_basic(&iter, &leader);
+
+ if (leader <= 0 ||
+ !dbus_message_iter_next(&iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING)
+ return -EINVAL;
+
+ dbus_message_iter_get_basic(&iter, &service);
+
+ if (!dbus_message_iter_next(&iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING)
+ return -EINVAL;
+
+ dbus_message_iter_get_basic(&iter, &type);
+ if (isempty(type))
+ t = _SESSION_TYPE_INVALID;
+ else {
+ t = session_type_from_string(type);
+ if (t < 0)
+ return -EINVAL;
+ }
+
+ if (!dbus_message_iter_next(&iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING)
+ return -EINVAL;
+
+ dbus_message_iter_get_basic(&iter, &class);
+ if (isempty(class))
+ c = _SESSION_CLASS_INVALID;
+ else {
+ c = session_class_from_string(class);
+ if (c < 0)
+ return -EINVAL;
+ }
+
+ if (!dbus_message_iter_next(&iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING)
+ return -EINVAL;
+
+ dbus_message_iter_get_basic(&iter, &cseat);
+
+ if (isempty(cseat))
+ seat = NULL;
+ else {
+ seat = hashmap_get(m->seats, cseat);
+ if (!seat)
+ return -ENOENT;
+ }
+
+ if (!dbus_message_iter_next(&iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_UINT32)
+ return -EINVAL;
+
+ dbus_message_iter_get_basic(&iter, &vtnr);
+
+ if (!dbus_message_iter_next(&iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING)
+ return -EINVAL;
+
+ dbus_message_iter_get_basic(&iter, &tty);
+
+ if (tty_is_vc(tty)) {
+ int v;
+
+ if (!seat)
+ seat = m->vtconsole;
+ else if (seat != m->vtconsole)
+ return -EINVAL;
+
+ v = vtnr_from_tty(tty);
+
+ if (v <= 0)
+ return v < 0 ? v : -EINVAL;
+
+ if (vtnr <= 0)
+ vtnr = (uint32_t) v;
+ else if (vtnr != (uint32_t) v)
+ return -EINVAL;
+ } else if (tty_is_console(tty)) {
+
+ if (!seat)
+ seat = m->vtconsole;
+ else if (seat != m->vtconsole)
+ return -EINVAL;
+
+ if (vtnr != 0)
+ return -EINVAL;
+ }
+
+ if (seat) {
+ if (seat_can_multi_session(seat)) {
+ if (vtnr > 63)
+ return -EINVAL;
+ } else {
+ if (vtnr != 0)
+ return -EINVAL;
+ }
+ }
+
+ if (!dbus_message_iter_next(&iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING)
+ return -EINVAL;
+
+ dbus_message_iter_get_basic(&iter, &display);
+
+ if (!dbus_message_iter_next(&iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_BOOLEAN)
+ return -EINVAL;
+
+ if (t == _SESSION_TYPE_INVALID) {
+ if (!isempty(display))
+ t = SESSION_X11;
+ else if (!isempty(tty))
+ t = SESSION_TTY;
+ else
+ t = SESSION_UNSPECIFIED;
+ }
+
+ if (c == _SESSION_CLASS_INVALID) {
+ if (!isempty(display) || !isempty(tty))
+ c = SESSION_USER;
+ else
+ c = SESSION_BACKGROUND;
+ }
+
+ dbus_message_iter_get_basic(&iter, &remote);
+
+ if (!dbus_message_iter_next(&iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING)
+ return -EINVAL;
+
+ dbus_message_iter_get_basic(&iter, &remote_user);
+
+ if (!dbus_message_iter_next(&iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING)
+ return -EINVAL;
+
+ dbus_message_iter_get_basic(&iter, &remote_host);
+
+ if (!dbus_message_iter_next(&iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
+ dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRING)
+ return -EINVAL;
+
+ r = bus_parse_strv_iter(&iter, &controllers);
+ if (r < 0)
+ return -EINVAL;
+
+ if (!dbus_message_iter_next(&iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
+ dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRING) {
+ r = -EINVAL;
+ goto fail;
+ }
+
+ r = bus_parse_strv_iter(&iter, &reset_controllers);
+ if (r < 0)
+ goto fail;
+
+ if (!dbus_message_iter_next(&iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_BOOLEAN) {
+ r = -EINVAL;
+ goto fail;
+ }
+
+ dbus_message_iter_get_basic(&iter, &kill_processes);
+
+ r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, leader, &cgroup);
+ if (r < 0)
+ goto fail;
+
+ r = manager_get_session_by_cgroup(m, cgroup, &session);
+ if (r < 0)
+ goto fail;
+
+ if (session) {
+ fifo_fd = session_create_fifo(session);
+ if (fifo_fd < 0) {
+ r = fifo_fd;
+ goto fail;
+ }
+
+ /* Session already exists, client is probably
+ * something like "su" which changes uid but
+ * is still the same audit session */
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ p = session_bus_path(session);
+ if (!p) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ cseat = session->seat ? session->seat->id : "";
+ vtnr = session->vtnr;
+ exists = true;
+
+ b = dbus_message_append_args(
+ reply,
+ DBUS_TYPE_STRING, &session->id,
+ DBUS_TYPE_OBJECT_PATH, &p,
+ DBUS_TYPE_STRING, &session->user->runtime_path,
+ DBUS_TYPE_UNIX_FD, &fifo_fd,
+ DBUS_TYPE_STRING, &cseat,
+ DBUS_TYPE_UINT32, &vtnr,
+ DBUS_TYPE_BOOLEAN, &exists,
+ DBUS_TYPE_INVALID);
+ if (!b) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ *_reply = reply;
+ reply = NULL;
+
+ return 0;
+ }
+
+ audit_session_from_pid(leader, &audit_id);
+ if (audit_id > 0) {
+ /* Keep our session IDs and the audit session IDs in sync */
+
+ if (asprintf(&id, "%lu", (unsigned long) audit_id) < 0) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ /* Wut? There's already a session by this name and we
+ * didn't find it above? Weird, then let's not trust
+ * the audit data and let's better register a new
+ * ID */
+ if (hashmap_get(m->sessions, id)) {
+ audit_id = 0;
+
+ free(id);
+ id = NULL;
+ }
+ }
+
+ if (!id) {
+ do {
+ free(id);
+ id = NULL;
+
+ if (asprintf(&id, "c%lu", ++m->session_counter) < 0) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ } while (hashmap_get(m->sessions, id));
+ }
+
+ r = manager_add_user_by_uid(m, uid, &user);
+ if (r < 0)
+ goto fail;
+
+ r = manager_add_session(m, user, id, &session);
+ if (r < 0)
+ goto fail;
+
+ session->leader = leader;
+ session->audit_id = audit_id;
+ session->type = t;
+ session->class = c;
+ session->remote = remote;
+ session->kill_processes = kill_processes;
+ session->vtnr = vtnr;
+
+ session->controllers = cg_shorten_controllers(controllers);
+ session->reset_controllers = cg_shorten_controllers(reset_controllers);
+ controllers = reset_controllers = NULL;
+
+ if (!isempty(tty)) {
+ session->tty = strdup(tty);
+ if (!session->tty) {
+ r = -ENOMEM;
+ goto fail;
+ }
+ }
+
+ if (!isempty(display)) {
+ session->display = strdup(display);
+ if (!session->display) {
+ r = -ENOMEM;
+ goto fail;
+ }
+ }
+
+ if (!isempty(remote_user)) {
+ session->remote_user = strdup(remote_user);
+ if (!session->remote_user) {
+ r = -ENOMEM;
+ goto fail;
+ }
+ }
+
+ if (!isempty(remote_host)) {
+ session->remote_host = strdup(remote_host);
+ if (!session->remote_host) {
+ r = -ENOMEM;
+ goto fail;
+ }
+ }
+
+ if (!isempty(service)) {
+ session->service = strdup(service);
+ if (!session->service) {
+ r = -ENOMEM;
+ goto fail;
+ }
+ }
+
+ fifo_fd = session_create_fifo(session);
+ if (fifo_fd < 0) {
+ r = fifo_fd;
+ goto fail;
+ }
+
+ if (seat) {
+ r = seat_attach_session(seat, session);
+ if (r < 0)
+ goto fail;
+ }
+
+ r = session_start(session);
+ if (r < 0)
+ goto fail;
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ p = session_bus_path(session);
+ if (!p) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ cseat = seat ? seat->id : "";
+ exists = false;
+ b = dbus_message_append_args(
+ reply,
+ DBUS_TYPE_STRING, &session->id,
+ DBUS_TYPE_OBJECT_PATH, &p,
+ DBUS_TYPE_STRING, &session->user->runtime_path,
+ DBUS_TYPE_UNIX_FD, &fifo_fd,
+ DBUS_TYPE_STRING, &cseat,
+ DBUS_TYPE_UINT32, &vtnr,
+ DBUS_TYPE_BOOLEAN, &exists,
+ DBUS_TYPE_INVALID);
+
+ if (!b) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ *_reply = reply;
+ reply = NULL;
+
+ return 0;
+
+fail:
+ if (session)
+ session_add_to_gc_queue(session);
+
+ if (user)
+ user_add_to_gc_queue(user);
+
+ return r;
+}
+
+static int bus_manager_inhibit(
+ Manager *m,
+ DBusConnection *connection,
+ DBusMessage *message,
+ DBusError *error,
+ DBusMessage **_reply) {
+
+ Inhibitor *i = NULL;
+ char *id = NULL;
+ const char *who, *why, *what, *mode;
+ pid_t pid;
+ InhibitWhat w;
+ InhibitMode mm;
+ unsigned long ul;
+ int r, fifo_fd = -1;
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+
+ assert(m);
+ assert(connection);
+ assert(message);
+ assert(error);
+ assert(_reply);
+
+ if (!dbus_message_get_args(
+ message,
+ error,
+ DBUS_TYPE_STRING, &what,
+ DBUS_TYPE_STRING, &who,
+ DBUS_TYPE_STRING, &why,
+ DBUS_TYPE_STRING, &mode,
+ DBUS_TYPE_INVALID)) {
+ r = -EIO;
+ goto fail;
+ }
+
+ w = inhibit_what_from_string(what);
+ if (w <= 0) {
+ r = -EINVAL;
+ goto fail;
+ }
+
+ mm = inhibit_mode_from_string(mode);
+ if (mm < 0) {
+ r = -EINVAL;
+ goto fail;
+ }
+
+ /* Delay is only supported for shutdown/sleep */
+ if (mm == INHIBIT_DELAY && (w & ~(INHIBIT_SHUTDOWN|INHIBIT_SLEEP))) {
+ r = -EINVAL;
+ goto fail;
+ }
+
+ /* Don't allow taking delay locks while we are already
+ * executing the operation. We shouldn't create the impression
+ * that the lock was successful if the machine is about to go
+ * down/suspend any moment. */
+ if (m->action_what & w) {
+ r = -EALREADY;
+ goto fail;
+ }
+
+ r = verify_polkit(connection, message,
+ w == INHIBIT_SHUTDOWN ? (mm == INHIBIT_BLOCK ? "org.freedesktop.login1.inhibit-block-shutdown" : "org.freedesktop.login1.inhibit-delay-shutdown") :
+ w == INHIBIT_SLEEP ? (mm == INHIBIT_BLOCK ? "org.freedesktop.login1.inhibit-block-sleep" : "org.freedesktop.login1.inhibit-delay-sleep") :
+ w == INHIBIT_IDLE ? "org.freedesktop.login1.inhibit-block-idle" :
+ w == INHIBIT_HANDLE_POWER_KEY ? "org.freedesktop.login1.inhibit-handle-power-key" :
+ w == INHIBIT_HANDLE_SUSPEND_KEY ? "org.freedesktop.login1.inhibit-handle-suspend-key" :
+ w == INHIBIT_HANDLE_HIBERNATE_KEY ? "org.freedesktop.login1.inhibit-handle-hibernate-key" :
+ "org.freedesktop.login1.inhibit-handle-lid-switch",
+ false, NULL, error);
+ if (r < 0)
+ goto fail;
+
+ ul = dbus_bus_get_unix_user(connection, dbus_message_get_sender(message), error);
+ if (ul == (unsigned long) -1) {
+ r = -EIO;
+ goto fail;
+ }
+
+ pid = bus_get_unix_process_id(connection, dbus_message_get_sender(message), error);
+ if (pid <= 0) {
+ r = -EIO;
+ goto fail;
+ }
+
+ do {
+ free(id);
+ id = NULL;
+
+ if (asprintf(&id, "%lu", ++m->inhibit_counter) < 0) {
+ r = -ENOMEM;
+ goto fail;
+ }
+ } while (hashmap_get(m->inhibitors, id));
+
+ r = manager_add_inhibitor(m, id, &i);
+ free(id);
+
+ if (r < 0)
+ goto fail;
+
+ i->what = w;
+ i->mode = mm;
+ i->pid = pid;
+ i->uid = (uid_t) ul;
+ i->why = strdup(why);
+ i->who = strdup(who);
+
+ if (!i->why || !i->who) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ fifo_fd = inhibitor_create_fifo(i);
+ if (fifo_fd < 0) {
+ r = fifo_fd;
+ goto fail;
+ }
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ if (!dbus_message_append_args(
+ reply,
+ DBUS_TYPE_UNIX_FD, &fifo_fd,
+ DBUS_TYPE_INVALID)) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ close_nointr_nofail(fifo_fd);
+ *_reply = reply;
+ reply = NULL;
+
+ inhibitor_start(i);
+
+ return 0;
+
+fail:
+ if (i)
+ inhibitor_free(i);
+
+ if (fifo_fd >= 0)
+ close_nointr_nofail(fifo_fd);
+
+ return r;
+}
+
+static int trigger_device(Manager *m, struct udev_device *d) {
+ struct udev_enumerate *e;
+ struct udev_list_entry *first, *item;
+ int r;
+
+ assert(m);
+
+ e = udev_enumerate_new(m->udev);
+ if (!e) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ if (d) {
+ if (udev_enumerate_add_match_parent(e, d) < 0) {
+ r = -EIO;
+ goto finish;
+ }
+ }
+
+ if (udev_enumerate_scan_devices(e) < 0) {
+ r = -EIO;
+ goto finish;
+ }
+
+ first = udev_enumerate_get_list_entry(e);
+ udev_list_entry_foreach(item, first) {
+ char *t;
+ const char *p;
+
+ p = udev_list_entry_get_name(item);
+
+ t = strappend(p, "/uevent");
+ if (!t) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ write_string_file(t, "change");
+ free(t);
+ }
+
+ r = 0;
+
+finish:
+ if (e)
+ udev_enumerate_unref(e);
+
+ return r;
+}
+
+static int attach_device(Manager *m, const char *seat, const char *sysfs) {
+ struct udev_device *d;
+ _cleanup_free_ char *rule = NULL, *file = NULL;
+ const char *id_for_seat;
+ int r;
+
+ assert(m);
+ assert(seat);
+ assert(sysfs);
+
+ d = udev_device_new_from_syspath(m->udev, sysfs);
+ if (!d)
+ return -ENODEV;
+
+ if (!udev_device_has_tag(d, "seat")) {
+ r = -ENODEV;
+ goto finish;
+ }
+
+ id_for_seat = udev_device_get_property_value(d, "ID_FOR_SEAT");
+ if (!id_for_seat) {
+ r = -ENODEV;
+ goto finish;
+ }
+
+ if (asprintf(&file, "/etc/udev/rules.d/72-seat-%s.rules", id_for_seat) < 0) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ if (asprintf(&rule, "TAG==\"seat\", ENV{ID_FOR_SEAT}==\"%s\", ENV{ID_SEAT}=\"%s\"", id_for_seat, seat) < 0) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ mkdir_p_label("/etc/udev/rules.d", 0755);
+ label_init("/etc");
+ r = write_string_file_atomic_label(file, rule);
+ if (r < 0)
+ goto finish;
+
+ r = trigger_device(m, d);
+
+finish:
+ if (d)
+ udev_device_unref(d);
+
+ return r;
+}
+
+static int flush_devices(Manager *m) {
+ _cleanup_closedir_ DIR *d;
+
+ assert(m);
+
+ d = opendir("/etc/udev/rules.d");
+ if (!d) {
+ if (errno != ENOENT)
+ log_warning("Failed to open /etc/udev/rules.d: %m");
+ } else {
+ struct dirent *de;
+
+ while ((de = readdir(d))) {
+
+ if (!dirent_is_file(de))
+ continue;
+
+ if (!startswith(de->d_name, "72-seat-"))
+ continue;
+
+ if (!endswith(de->d_name, ".rules"))
+ continue;
+
+ if (unlinkat(dirfd(d), de->d_name, 0) < 0)
+ log_warning("Failed to unlink %s: %m", de->d_name);
+ }
+ }
+
+ return trigger_device(m, NULL);
+}
+
+static int have_multiple_sessions(
+ Manager *m,
+ uid_t uid) {
+
+ Session *session;
+ Iterator i;
+
+ assert(m);
+
+ /* Check for other users' sessions. Greeter sessions do not
+ * count, and non-login sessions do not count either. */
+ HASHMAP_FOREACH(session, m->sessions, i)
+ if (session->class == SESSION_USER &&
+ session->user->uid != uid)
+ return true;
+
+ return false;
+}
+
+static int bus_manager_log_shutdown(
+ Manager *m,
+ InhibitWhat w,
+ const char *unit_name) {
+
+ const char *p, *q;
+
+ assert(m);
+ assert(unit_name);
+
+ if (w != INHIBIT_SHUTDOWN)
+ return 0;
+
+ if (streq(unit_name, SPECIAL_POWEROFF_TARGET)) {
+ p = "MESSAGE=System is powering down.";
+ q = "SHUTDOWN=power-off";
+ } else if (streq(unit_name, SPECIAL_HALT_TARGET)) {
+ p = "MESSAGE=System is halting.";
+ q = "SHUTDOWN=halt";
+ } else if (streq(unit_name, SPECIAL_REBOOT_TARGET)) {
+ p = "MESSAGE=System is rebooting.";
+ q = "SHUTDOWN=reboot";
+ } else if (streq(unit_name, SPECIAL_KEXEC_TARGET)) {
+ p = "MESSAGE=System is rebooting with kexec.";
+ q = "SHUTDOWN=kexec";
+ } else {
+ p = "MESSAGE=System is shutting down.";
+ q = NULL;
+ }
+
+ return log_struct(LOG_NOTICE, MESSAGE_ID(SD_MESSAGE_SHUTDOWN),
+ p,
+ q, NULL);
+}
+
+static int execute_shutdown_or_sleep(
+ Manager *m,
+ InhibitWhat w,
+ const char *unit_name,
+ DBusError *error) {
+
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ const char *mode = "replace-irreversibly", *p;
+ int r;
+ char *c;
+
+ assert(m);
+ assert(w >= 0);
+ assert(w < _INHIBIT_WHAT_MAX);
+ assert(unit_name);
+
+ bus_manager_log_shutdown(m, w, unit_name);
+
+ r = bus_method_call_with_reply(
+ m->bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "StartUnit",
+ &reply,
+ error,
+ DBUS_TYPE_STRING, &unit_name,
+ DBUS_TYPE_STRING, &mode,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+
+ if (!dbus_message_get_args(
+ reply,
+ error,
+ DBUS_TYPE_OBJECT_PATH, &p,
+ DBUS_TYPE_INVALID))
+ return -EINVAL;
+
+ c = strdup(p);
+ if (!c)
+ return -ENOMEM;
+
+ m->action_unit = unit_name;
+ free(m->action_job);
+ m->action_job = c;
+ m->action_what = w;
+
+ return 0;
+}
+
+static int delay_shutdown_or_sleep(
+ Manager *m,
+ InhibitWhat w,
+ const char *unit_name) {
+
+ assert(m);
+ assert(w >= 0);
+ assert(w < _INHIBIT_WHAT_MAX);
+ assert(unit_name);
+
+ m->action_timestamp = now(CLOCK_MONOTONIC);
+ m->action_unit = unit_name;
+ m->action_what = w;
+
+ return 0;
+}
+
+static int bus_manager_can_shutdown_or_sleep(
+ Manager *m,
+ DBusConnection *connection,
+ DBusMessage *message,
+ InhibitWhat w,
+ const char *action,
+ const char *action_multiple_sessions,
+ const char *action_ignore_inhibit,
+ const char *sleep_verb,
+ DBusError *error,
+ DBusMessage **_reply) {
+
+ bool multiple_sessions, challenge, blocked, b;
+ const char *result = NULL;
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ int r;
+ unsigned long ul;
+
+ assert(m);
+ assert(connection);
+ assert(message);
+ assert(w >= 0);
+ assert(w <= _INHIBIT_WHAT_MAX);
+ assert(action);
+ assert(action_multiple_sessions);
+ assert(action_ignore_inhibit);
+ assert(error);
+ assert(_reply);
+
+ if (sleep_verb) {
+ r = can_sleep(sleep_verb);
+ if (r < 0)
+ return r;
+ if (r == 0) {
+ result = "na";
+ goto finish;
+ }
+ }
+
+ ul = dbus_bus_get_unix_user(connection, dbus_message_get_sender(message), error);
+ if (ul == (unsigned long) -1)
+ return -EIO;
+
+ r = have_multiple_sessions(m, (uid_t) ul);
+ if (r < 0)
+ return r;
+
+ multiple_sessions = r > 0;
+ blocked = manager_is_inhibited(m, w, INHIBIT_BLOCK, NULL, false, true, (uid_t) ul);
+
+ if (multiple_sessions) {
+ r = verify_polkit(connection, message, action_multiple_sessions, false, &challenge, error);
+ if (r < 0)
+ return r;
+
+ if (r > 0)
+ result = "yes";
+ else if (challenge)
+ result = "challenge";
+ else
+ result = "no";
+ }
+
+ if (blocked) {
+ r = verify_polkit(connection, message, action_ignore_inhibit, false, &challenge, error);
+ if (r < 0)
+ return r;
+
+ if (r > 0 && !result)
+ result = "yes";
+ else if (challenge && (!result || streq(result, "yes")))
+ result = "challenge";
+ else
+ result = "no";
+ }
+
+ if (!multiple_sessions && !blocked) {
+ /* If neither inhibit nor multiple sessions
+ * apply then just check the normal policy */
+
+ r = verify_polkit(connection, message, action, false, &challenge, error);
+ if (r < 0)
+ return r;
+
+ if (r > 0)
+ result = "yes";
+ else if (challenge)
+ result = "challenge";
+ else
+ result = "no";
+ }
+
+finish:
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ return -ENOMEM;
+
+ b = dbus_message_append_args(
+ reply,
+ DBUS_TYPE_STRING, &result,
+ DBUS_TYPE_INVALID);
+ if (!b)
+ return -ENOMEM;
+
+ *_reply = reply;
+ reply = NULL;
+ return 0;
+}
+
+static int send_prepare_for(Manager *m, InhibitWhat w, bool _active) {
+ static const char * const signal_name[_INHIBIT_WHAT_MAX] = {
+ [INHIBIT_SHUTDOWN] = "PrepareForShutdown",
+ [INHIBIT_SLEEP] = "PrepareForSleep"
+ };
+
+ dbus_bool_t active = _active;
+ _cleanup_dbus_message_unref_ DBusMessage *message = NULL;
+
+ assert(m);
+ assert(w >= 0);
+ assert(w < _INHIBIT_WHAT_MAX);
+ assert(signal_name[w]);
+
+ message = dbus_message_new_signal("/org/freedesktop/login1", "org.freedesktop.login1.Manager", signal_name[w]);
+ if (!message)
+ return -ENOMEM;
+
+ if (!dbus_message_append_args(message, DBUS_TYPE_BOOLEAN, &active, DBUS_TYPE_INVALID) ||
+ !dbus_connection_send(m->bus, message, NULL))
+ return -ENOMEM;
+
+ return 0;
+}
+
+int bus_manager_shutdown_or_sleep_now_or_later(
+ Manager *m,
+ const char *unit_name,
+ InhibitWhat w,
+ DBusError *error) {
+
+ bool delayed;
+ int r;
+
+ assert(m);
+ assert(unit_name);
+ assert(w >= 0);
+ assert(w <= _INHIBIT_WHAT_MAX);
+ assert(!m->action_job);
+
+ /* Tell everybody to prepare for shutdown/sleep */
+ send_prepare_for(m, w, true);
+
+ delayed =
+ m->inhibit_delay_max > 0 &&
+ manager_is_inhibited(m, w, INHIBIT_DELAY, NULL, false, false, 0);
+
+ if (delayed)
+ /* Shutdown is delayed, keep in mind what we
+ * want to do, and start a timeout */
+ r = delay_shutdown_or_sleep(m, w, unit_name);
+ else
+ /* Shutdown is not delayed, execute it
+ * immediately */
+ r = execute_shutdown_or_sleep(m, w, unit_name, error);
+
+ return r;
+}
+
+static int bus_manager_do_shutdown_or_sleep(
+ Manager *m,
+ DBusConnection *connection,
+ DBusMessage *message,
+ const char *unit_name,
+ InhibitWhat w,
+ const char *action,
+ const char *action_multiple_sessions,
+ const char *action_ignore_inhibit,
+ const char *sleep_verb,
+ DBusError *error,
+ DBusMessage **_reply) {
+
+ dbus_bool_t interactive;
+ bool multiple_sessions, blocked;
+ DBusMessage *reply = NULL;
+ int r;
+ unsigned long ul;
+
+ assert(m);
+ assert(connection);
+ assert(message);
+ assert(unit_name);
+ assert(w >= 0);
+ assert(w <= _INHIBIT_WHAT_MAX);
+ assert(action);
+ assert(action_multiple_sessions);
+ assert(action_ignore_inhibit);
+ assert(error);
+ assert(_reply);
+
+ /* Don't allow multiple jobs being executed at the same time */
+ if (m->action_what)
+ return -EALREADY;
+
+ if (!dbus_message_get_args(
+ message,
+ error,
+ DBUS_TYPE_BOOLEAN, &interactive,
+ DBUS_TYPE_INVALID))
+ return -EINVAL;
+
+ if (sleep_verb) {
+ r = can_sleep(sleep_verb);
+ if (r < 0)
+ return r;
+
+ if (r == 0)
+ return -ENOTSUP;
+ }
+
+ ul = dbus_bus_get_unix_user(connection, dbus_message_get_sender(message), error);
+ if (ul == (unsigned long) -1)
+ return -EIO;
+
+ r = have_multiple_sessions(m, (uid_t) ul);
+ if (r < 0)
+ return r;
+
+ multiple_sessions = r > 0;
+ blocked = manager_is_inhibited(m, w, INHIBIT_BLOCK, NULL, false, true, (uid_t) ul);
+
+ if (multiple_sessions) {
+ r = verify_polkit(connection, message, action_multiple_sessions, interactive, NULL, error);
+ if (r < 0)
+ return r;
+ }
+
+ if (blocked) {
+ r = verify_polkit(connection, message, action_ignore_inhibit, interactive, NULL, error);
+ if (r < 0)
+ return r;
+ }
+
+ if (!multiple_sessions && !blocked) {
+ r = verify_polkit(connection, message, action, interactive, NULL, error);
+ if (r < 0)
+ return r;
+ }
+
+ r = bus_manager_shutdown_or_sleep_now_or_later(m, unit_name, w, error);
+ if (r < 0)
+ return r;
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ return -ENOMEM;
+
+ *_reply = reply;
+ return 0;
+}
+
+static DEFINE_BUS_PROPERTY_APPEND_ENUM(bus_manager_append_handle_action, handle_action, HandleAction);
+
+static const BusProperty bus_login_manager_properties[] = {
+ { "ControlGroupHierarchy", bus_property_append_string, "s", offsetof(Manager, cgroup_path), true },
+ { "Controllers", bus_property_append_strv, "as", offsetof(Manager, controllers), true },
+ { "ResetControllers", bus_property_append_strv, "as", offsetof(Manager, reset_controllers), true },
+ { "NAutoVTs", bus_property_append_unsigned, "u", offsetof(Manager, n_autovts) },
+ { "KillOnlyUsers", bus_property_append_strv, "as", offsetof(Manager, kill_only_users), true },
+ { "KillExcludeUsers", bus_property_append_strv, "as", offsetof(Manager, kill_exclude_users), true },
+ { "KillUserProcesses", bus_property_append_bool, "b", offsetof(Manager, kill_user_processes) },
+ { "IdleHint", bus_manager_append_idle_hint, "b", 0 },
+ { "IdleSinceHint", bus_manager_append_idle_hint_since, "t", 0 },
+ { "IdleSinceHintMonotonic", bus_manager_append_idle_hint_since, "t", 0 },
+ { "BlockInhibited", bus_manager_append_inhibited, "s", 0 },
+ { "DelayInhibited", bus_manager_append_inhibited, "s", 0 },
+ { "InhibitDelayMaxUSec", bus_property_append_usec, "t", offsetof(Manager, inhibit_delay_max) },
+ { "HandlePowerKey", bus_manager_append_handle_action, "s", offsetof(Manager, handle_power_key) },
+ { "HandleSuspendKey", bus_manager_append_handle_action, "s", offsetof(Manager, handle_suspend_key) },
+ { "HandleHibernateKey", bus_manager_append_handle_action, "s", offsetof(Manager, handle_hibernate_key)},
+ { "HandleLidSwitch", bus_manager_append_handle_action, "s", offsetof(Manager, handle_lid_switch) },
+ { "IdleAction", bus_manager_append_handle_action, "s", offsetof(Manager, idle_action) },
+ { "IdleActionUSec", bus_property_append_usec, "t", offsetof(Manager, idle_action_usec) },
+ { "PreparingForShutdown", bus_manager_append_preparing, "b", 0 },
+ { "PreparingForSleep", bus_manager_append_preparing, "b", 0 },
+ { NULL, }
+};
+
+static DBusHandlerResult manager_message_handler(
+ DBusConnection *connection,
+ DBusMessage *message,
+ void *userdata) {
+
+ Manager *m = userdata;
+
+ DBusError error;
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ int r;
+
+ assert(connection);
+ assert(message);
+ assert(m);
+
+ dbus_error_init(&error);
+
+ if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "GetSession")) {
+ const char *name;
+ char *p;
+ Session *session;
+ bool b;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ session = hashmap_get(m->sessions, name);
+ if (!session)
+ return bus_send_error_reply(connection, message, &error, -ENOENT);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ p = session_bus_path(session);
+ if (!p)
+ goto oom;
+
+ b = dbus_message_append_args(
+ reply,
+ DBUS_TYPE_OBJECT_PATH, &p,
+ DBUS_TYPE_INVALID);
+ free(p);
+
+ if (!b)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "GetSessionByPID")) {
+ uint32_t pid;
+ char *p;
+ Session *session;
+ bool b;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_UINT32, &pid,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ r = manager_get_session_by_pid(m, pid, &session);
+ if (r <= 0)
+ return bus_send_error_reply(connection, message, NULL, r < 0 ? r : -ENOENT);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ p = session_bus_path(session);
+ if (!p)
+ goto oom;
+
+ b = dbus_message_append_args(
+ reply,
+ DBUS_TYPE_OBJECT_PATH, &p,
+ DBUS_TYPE_INVALID);
+ free(p);
+
+ if (!b)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "GetUser")) {
+ uint32_t uid;
+ char *p;
+ User *user;
+ bool b;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_UINT32, &uid,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ user = hashmap_get(m->users, ULONG_TO_PTR((unsigned long) uid));
+ if (!user)
+ return bus_send_error_reply(connection, message, &error, -ENOENT);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ p = user_bus_path(user);
+ if (!p)
+ goto oom;
+
+ b = dbus_message_append_args(
+ reply,
+ DBUS_TYPE_OBJECT_PATH, &p,
+ DBUS_TYPE_INVALID);
+ free(p);
+
+ if (!b)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "GetSeat")) {
+ const char *name;
+ char *p;
+ Seat *seat;
+ bool b;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ seat = hashmap_get(m->seats, name);
+ if (!seat)
+ return bus_send_error_reply(connection, message, &error, -ENOENT);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ p = seat_bus_path(seat);
+ if (!p)
+ goto oom;
+
+ b = dbus_message_append_args(
+ reply,
+ DBUS_TYPE_OBJECT_PATH, &p,
+ DBUS_TYPE_INVALID);
+ free(p);
+
+ if (!b)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "ListSessions")) {
+ char *p;
+ Session *session;
+ Iterator i;
+ DBusMessageIter iter, sub;
+ const char *empty = "";
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ dbus_message_iter_init_append(reply, &iter);
+
+ if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "(susso)", &sub))
+ goto oom;
+
+ HASHMAP_FOREACH(session, m->sessions, i) {
+ DBusMessageIter sub2;
+ uint32_t uid;
+
+ if (!dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, NULL, &sub2))
+ goto oom;
+
+ uid = session->user->uid;
+
+ p = session_bus_path(session);
+ if (!p)
+ goto oom;
+
+ if (!dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &session->id) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_UINT32, &uid) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &session->user->name) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, session->seat ? (const char**) &session->seat->id : &empty) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_OBJECT_PATH, &p)) {
+ free(p);
+ goto oom;
+ }
+
+ free(p);
+
+ if (!dbus_message_iter_close_container(&sub, &sub2))
+ goto oom;
+ }
+
+ if (!dbus_message_iter_close_container(&iter, &sub))
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "ListUsers")) {
+ char *p;
+ User *user;
+ Iterator i;
+ DBusMessageIter iter, sub;
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ dbus_message_iter_init_append(reply, &iter);
+
+ if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "(uso)", &sub))
+ goto oom;
+
+ HASHMAP_FOREACH(user, m->users, i) {
+ DBusMessageIter sub2;
+ uint32_t uid;
+
+ if (!dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, NULL, &sub2))
+ goto oom;
+
+ uid = user->uid;
+
+ p = user_bus_path(user);
+ if (!p)
+ goto oom;
+
+ if (!dbus_message_iter_append_basic(&sub2, DBUS_TYPE_UINT32, &uid) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &user->name) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_OBJECT_PATH, &p)) {
+ free(p);
+ goto oom;
+ }
+
+ free(p);
+
+ if (!dbus_message_iter_close_container(&sub, &sub2))
+ goto oom;
+ }
+
+ if (!dbus_message_iter_close_container(&iter, &sub))
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "ListSeats")) {
+ char *p;
+ Seat *seat;
+ Iterator i;
+ DBusMessageIter iter, sub;
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ dbus_message_iter_init_append(reply, &iter);
+
+ if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "(so)", &sub))
+ goto oom;
+
+ HASHMAP_FOREACH(seat, m->seats, i) {
+ DBusMessageIter sub2;
+
+ if (!dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, NULL, &sub2))
+ goto oom;
+
+ p = seat_bus_path(seat);
+ if (!p)
+ goto oom;
+
+ if (!dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &seat->id) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_OBJECT_PATH, &p)) {
+ free(p);
+ goto oom;
+ }
+
+ free(p);
+
+ if (!dbus_message_iter_close_container(&sub, &sub2))
+ goto oom;
+ }
+
+ if (!dbus_message_iter_close_container(&iter, &sub))
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "ListInhibitors")) {
+ Inhibitor *inhibitor;
+ Iterator i;
+ DBusMessageIter iter, sub;
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ dbus_message_iter_init_append(reply, &iter);
+
+ if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "(ssssuu)", &sub))
+ goto oom;
+
+ HASHMAP_FOREACH(inhibitor, m->inhibitors, i) {
+ DBusMessageIter sub2;
+ dbus_uint32_t uid, pid;
+ const char *what, *who, *why, *mode;
+
+ if (!dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, NULL, &sub2))
+ goto oom;
+
+ what = strempty(inhibit_what_to_string(inhibitor->what));
+ who = strempty(inhibitor->who);
+ why = strempty(inhibitor->why);
+ mode = strempty(inhibit_mode_to_string(inhibitor->mode));
+ uid = (dbus_uint32_t) inhibitor->uid;
+ pid = (dbus_uint32_t) inhibitor->pid;
+
+ if (!dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &what) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &who) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &why) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &mode) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_UINT32, &uid) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_UINT32, &pid))
+ goto oom;
+
+ if (!dbus_message_iter_close_container(&sub, &sub2))
+ goto oom;
+ }
+
+ if (!dbus_message_iter_close_container(&iter, &sub))
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "Inhibit")) {
+
+ r = bus_manager_inhibit(m, connection, message, &error, &reply);
+
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "CreateSession")) {
+
+ r = bus_manager_create_session(m, message, &reply);
+
+ /* Don't delay the work on OOM here, since it might be
+ * triggered by a low RLIMIT_NOFILE here (since we
+ * send a dupped fd to the client), and we'd rather
+ * see this fail quickly then be retried later */
+
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "ReleaseSession")) {
+ const char *name;
+ Session *session;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ session = hashmap_get(m->sessions, name);
+ if (!session)
+ return bus_send_error_reply(connection, message, &error, -ENOENT);
+
+ /* We use the FIFO to detect stray sessions where the
+ process invoking PAM dies abnormally. We need to make
+ sure that that process is not killed if at the clean
+ end of the session it closes the FIFO. Hence, with
+ this call explicitly turn off the FIFO logic, so that
+ the PAM code can finish clean up on its own */
+ session_remove_fifo(session);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "ActivateSession")) {
+ const char *name;
+ Session *session;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ session = hashmap_get(m->sessions, name);
+ if (!session)
+ return bus_send_error_reply(connection, message, &error, -ENOENT);
+
+ r = session_activate(session);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "ActivateSessionOnSeat")) {
+ const char *session_name, *seat_name;
+ Session *session;
+ Seat *seat;
+
+ /* Same as ActivateSession() but refuses to work if
+ * the seat doesn't match */
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &session_name,
+ DBUS_TYPE_STRING, &seat_name,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ session = hashmap_get(m->sessions, session_name);
+ if (!session)
+ return bus_send_error_reply(connection, message, &error, -ENOENT);
+
+ seat = hashmap_get(m->seats, seat_name);
+ if (!seat)
+ return bus_send_error_reply(connection, message, &error, -ENOENT);
+
+ if (session->seat != seat)
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ r = session_activate(session);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "LockSession") ||
+ dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "UnlockSession")) {
+ const char *name;
+ Session *session;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ session = hashmap_get(m->sessions, name);
+ if (!session)
+ return bus_send_error_reply(connection, message, NULL, -ENOENT);
+
+ if (session_send_lock(session, streq(dbus_message_get_member(message), "LockSession")) < 0)
+ goto oom;
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "LockSessions") ||
+ dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "UnlockSessions")) {
+
+ r = session_send_lock_all(m, streq(dbus_message_get_member(message), "LockSessions"));
+ if (r < 0)
+ bus_send_error_reply(connection, message, NULL, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "KillSession")) {
+ const char *swho;
+ int32_t signo;
+ KillWho who;
+ const char *name;
+ Session *session;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_STRING, &swho,
+ DBUS_TYPE_INT32, &signo,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ if (isempty(swho))
+ who = KILL_ALL;
+ else {
+ who = kill_who_from_string(swho);
+ if (who < 0)
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+ }
+
+ if (signo <= 0 || signo >= _NSIG)
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ session = hashmap_get(m->sessions, name);
+ if (!session)
+ return bus_send_error_reply(connection, message, &error, -ENOENT);
+
+ r = session_kill(session, who, signo);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "KillUser")) {
+ uint32_t uid;
+ User *user;
+ int32_t signo;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_UINT32, &uid,
+ DBUS_TYPE_INT32, &signo,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ if (signo <= 0 || signo >= _NSIG)
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ user = hashmap_get(m->users, ULONG_TO_PTR((unsigned long) uid));
+ if (!user)
+ return bus_send_error_reply(connection, message, &error, -ENOENT);
+
+ r = user_kill(user, signo);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "TerminateSession")) {
+ const char *name;
+ Session *session;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ session = hashmap_get(m->sessions, name);
+ if (!session)
+ return bus_send_error_reply(connection, message, &error, -ENOENT);
+
+ r = session_stop(session);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "TerminateUser")) {
+ uint32_t uid;
+ User *user;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_UINT32, &uid,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ user = hashmap_get(m->users, ULONG_TO_PTR((unsigned long) uid));
+ if (!user)
+ return bus_send_error_reply(connection, message, &error, -ENOENT);
+
+ r = user_stop(user);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "TerminateSeat")) {
+ const char *name;
+ Seat *seat;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ seat = hashmap_get(m->seats, name);
+ if (!seat)
+ return bus_send_error_reply(connection, message, &error, -ENOENT);
+
+ r = seat_stop_sessions(seat);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "SetUserLinger")) {
+ uint32_t uid;
+ struct passwd *pw;
+ dbus_bool_t b, interactive;
+ char *path;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_UINT32, &uid,
+ DBUS_TYPE_BOOLEAN, &b,
+ DBUS_TYPE_BOOLEAN, &interactive,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ errno = 0;
+ pw = getpwuid(uid);
+ if (!pw)
+ return bus_send_error_reply(connection, message, NULL, errno ? -errno : -EINVAL);
+
+ r = verify_polkit(connection, message, "org.freedesktop.login1.set-user-linger", interactive, NULL, &error);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ mkdir_p_label("/var/lib/systemd", 0755);
+
+ r = mkdir_safe_label("/var/lib/systemd/linger", 0755, 0, 0);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ path = strappend("/var/lib/systemd/linger/", pw->pw_name);
+ if (!path)
+ goto oom;
+
+ if (b) {
+ User *u;
+
+ r = touch(path);
+ free(path);
+
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ if (manager_add_user_by_uid(m, uid, &u) >= 0)
+ user_start(u);
+
+ } else {
+ User *u;
+
+ r = unlink(path);
+ free(path);
+
+ if (r < 0 && errno != ENOENT)
+ return bus_send_error_reply(connection, message, &error, -errno);
+
+ u = hashmap_get(m->users, ULONG_TO_PTR((unsigned long) uid));
+ if (u)
+ user_add_to_gc_queue(u);
+ }
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "AttachDevice")) {
+ const char *sysfs, *seat;
+ dbus_bool_t interactive;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &seat,
+ DBUS_TYPE_STRING, &sysfs,
+ DBUS_TYPE_BOOLEAN, &interactive,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ if (!path_startswith(sysfs, "/sys") || !seat_name_is_valid(seat))
+ return bus_send_error_reply(connection, message, NULL, -EINVAL);
+
+ r = verify_polkit(connection, message, "org.freedesktop.login1.attach-device", interactive, NULL, &error);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ r = attach_device(m, seat, sysfs);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, -EINVAL);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "FlushDevices")) {
+ dbus_bool_t interactive;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_BOOLEAN, &interactive,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ r = verify_polkit(connection, message, "org.freedesktop.login1.flush-devices", interactive, NULL, &error);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ r = flush_devices(m);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, -EINVAL);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "PowerOff")) {
+
+ r = bus_manager_do_shutdown_or_sleep(
+ m, connection, message,
+ SPECIAL_POWEROFF_TARGET,
+ INHIBIT_SHUTDOWN,
+ "org.freedesktop.login1.power-off",
+ "org.freedesktop.login1.power-off-multiple-sessions",
+ "org.freedesktop.login1.power-off-ignore-inhibit",
+ NULL,
+ &error, &reply);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "Reboot")) {
+ r = bus_manager_do_shutdown_or_sleep(
+ m, connection, message,
+ SPECIAL_REBOOT_TARGET,
+ INHIBIT_SHUTDOWN,
+ "org.freedesktop.login1.reboot",
+ "org.freedesktop.login1.reboot-multiple-sessions",
+ "org.freedesktop.login1.reboot-ignore-inhibit",
+ NULL,
+ &error, &reply);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "Suspend")) {
+ r = bus_manager_do_shutdown_or_sleep(
+ m, connection, message,
+ SPECIAL_SUSPEND_TARGET,
+ INHIBIT_SLEEP,
+ "org.freedesktop.login1.suspend",
+ "org.freedesktop.login1.suspend-multiple-sessions",
+ "org.freedesktop.login1.suspend-ignore-inhibit",
+ "suspend",
+ &error, &reply);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "Hibernate")) {
+ r = bus_manager_do_shutdown_or_sleep(
+ m, connection, message,
+ SPECIAL_HIBERNATE_TARGET,
+ INHIBIT_SLEEP,
+ "org.freedesktop.login1.hibernate",
+ "org.freedesktop.login1.hibernate-multiple-sessions",
+ "org.freedesktop.login1.hibernate-ignore-inhibit",
+ "hibernate",
+ &error, &reply);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "HybridSleep")) {
+ r = bus_manager_do_shutdown_or_sleep(
+ m, connection, message,
+ SPECIAL_HYBRID_SLEEP_TARGET,
+ INHIBIT_SLEEP,
+ "org.freedesktop.login1.hibernate",
+ "org.freedesktop.login1.hibernate-multiple-sessions",
+ "org.freedesktop.login1.hibernate-ignore-inhibit",
+ "hybrid-sleep",
+ &error, &reply);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "CanPowerOff")) {
+
+ r = bus_manager_can_shutdown_or_sleep(
+ m, connection, message,
+ INHIBIT_SHUTDOWN,
+ "org.freedesktop.login1.power-off",
+ "org.freedesktop.login1.power-off-multiple-sessions",
+ "org.freedesktop.login1.power-off-ignore-inhibit",
+ NULL,
+ &error, &reply);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "CanReboot")) {
+ r = bus_manager_can_shutdown_or_sleep(
+ m, connection, message,
+ INHIBIT_SHUTDOWN,
+ "org.freedesktop.login1.reboot",
+ "org.freedesktop.login1.reboot-multiple-sessions",
+ "org.freedesktop.login1.reboot-ignore-inhibit",
+ NULL,
+ &error, &reply);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "CanSuspend")) {
+ r = bus_manager_can_shutdown_or_sleep(
+ m, connection, message,
+ INHIBIT_SLEEP,
+ "org.freedesktop.login1.suspend",
+ "org.freedesktop.login1.suspend-multiple-sessions",
+ "org.freedesktop.login1.suspend-ignore-inhibit",
+ "suspend",
+ &error, &reply);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "CanHibernate")) {
+ r = bus_manager_can_shutdown_or_sleep(
+ m, connection, message,
+ INHIBIT_SLEEP,
+ "org.freedesktop.login1.hibernate",
+ "org.freedesktop.login1.hibernate-multiple-sessions",
+ "org.freedesktop.login1.hibernate-ignore-inhibit",
+ "hibernate",
+ &error, &reply);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Manager", "CanHybridSleep")) {
+ r = bus_manager_can_shutdown_or_sleep(
+ m, connection, message,
+ INHIBIT_SLEEP,
+ "org.freedesktop.login1.hibernate",
+ "org.freedesktop.login1.hibernate-multiple-sessions",
+ "org.freedesktop.login1.hibernate-ignore-inhibit",
+ "hybrid-sleep",
+ &error, &reply);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.DBus.Introspectable", "Introspect")) {
+ char *introspection = NULL;
+ FILE *f;
+ Iterator i;
+ Session *session;
+ Seat *seat;
+ User *user;
+ size_t size;
+ char *p;
+
+ if (!(reply = dbus_message_new_method_return(message)))
+ goto oom;
+
+ /* We roll our own introspection code here, instead of
+ * relying on bus_default_message_handler() because we
+ * need to generate our introspection string
+ * dynamically. */
+
+ if (!(f = open_memstream(&introspection, &size)))
+ goto oom;
+
+ fputs(INTROSPECTION_BEGIN, f);
+
+ HASHMAP_FOREACH(seat, m->seats, i) {
+ p = bus_path_escape(seat->id);
+
+ if (p) {
+ fprintf(f, "<node name=\"seat/%s\"/>", p);
+ free(p);
+ }
+ }
+
+ HASHMAP_FOREACH(user, m->users, i)
+ fprintf(f, "<node name=\"user/%llu\"/>", (unsigned long long) user->uid);
+
+ HASHMAP_FOREACH(session, m->sessions, i) {
+ p = bus_path_escape(session->id);
+
+ if (p) {
+ fprintf(f, "<node name=\"session/%s\"/>", p);
+ free(p);
+ }
+ }
+
+ fputs(INTROSPECTION_END, f);
+
+ if (ferror(f)) {
+ fclose(f);
+ free(introspection);
+ goto oom;
+ }
+
+ fclose(f);
+
+ if (!introspection)
+ goto oom;
+
+ if (!dbus_message_append_args(reply, DBUS_TYPE_STRING, &introspection, DBUS_TYPE_INVALID)) {
+ free(introspection);
+ goto oom;
+ }
+
+ free(introspection);
+ } else {
+ const BusBoundProperties bps[] = {
+ { "org.freedesktop.login1.Manager", bus_login_manager_properties, m },
+ { NULL, }
+ };
+ return bus_default_message_handler(connection, message, NULL, INTERFACES_LIST, bps);
+ }
+
+ if (reply) {
+ if (!bus_maybe_send_reply(connection, message, reply))
+ goto oom;
+ }
+
+ return DBUS_HANDLER_RESULT_HANDLED;
+
+oom:
+ dbus_error_free(&error);
+
+ return DBUS_HANDLER_RESULT_NEED_MEMORY;
+}
+
+const DBusObjectPathVTable bus_manager_vtable = {
+ .message_function = manager_message_handler
+};
+
+DBusHandlerResult bus_message_filter(
+ DBusConnection *connection,
+ DBusMessage *message,
+ void *userdata) {
+
+ Manager *m = userdata;
+ DBusError error;
+
+ assert(m);
+ assert(connection);
+ assert(message);
+
+ dbus_error_init(&error);
+
+ if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Agent", "Released")) {
+ const char *cgroup;
+
+ if (!dbus_message_get_args(message, &error,
+ DBUS_TYPE_STRING, &cgroup,
+ DBUS_TYPE_INVALID))
+ log_error("Failed to parse Released message: %s", bus_error_message(&error));
+ else
+ manager_cgroup_notify_empty(m, cgroup);
+
+ } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
+ uint32_t id;
+ const char *path, *result, *unit;
+
+ if (!dbus_message_get_args(message, &error,
+ DBUS_TYPE_UINT32, &id,
+ DBUS_TYPE_OBJECT_PATH, &path,
+ DBUS_TYPE_STRING, &unit,
+ DBUS_TYPE_STRING, &result,
+ DBUS_TYPE_INVALID))
+ log_error("Failed to parse JobRemoved message: %s", bus_error_message(&error));
+
+ else if (m->action_job && streq(m->action_job, path)) {
+ log_info("Operation finished.");
+
+ /* Tell people that they now may take a lock again */
+ send_prepare_for(m, m->action_what, false);
+
+ free(m->action_job);
+ m->action_job = NULL;
+ m->action_unit = NULL;
+ m->action_what = 0;
+ }
+ }
+
+ dbus_error_free(&error);
+
+ return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
+}
+
+int manager_send_changed(Manager *manager, const char *properties) {
+ _cleanup_dbus_message_unref_ DBusMessage *m = NULL;
+
+ assert(manager);
+
+ m = bus_properties_changed_new("/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ properties);
+ if (!m)
+ return -ENOMEM;
+
+ if (!dbus_connection_send(manager->bus, m, NULL))
+ return -ENOMEM;
+
+ return 0;
+}
+
+int manager_dispatch_delayed(Manager *manager) {
+ DBusError error;
+ int r;
+
+ assert(manager);
+
+ if (manager->action_what == 0 || manager->action_job)
+ return 0;
+
+ /* Continue delay? */
+ if (manager_is_inhibited(manager, manager->action_what, INHIBIT_DELAY, NULL, false, false, 0)) {
+
+ if (manager->action_timestamp + manager->inhibit_delay_max > now(CLOCK_MONOTONIC))
+ return 0;
+
+ log_info("Delay lock is active but inhibitor timeout is reached.");
+ }
+
+ /* Actually do the operation */
+ dbus_error_init(&error);
+ r = execute_shutdown_or_sleep(manager, manager->action_what, manager->action_unit, &error);
+ if (r < 0) {
+ log_warning("Failed to send delayed message: %s", bus_error(&error, r));
+ dbus_error_free(&error);
+
+ manager->action_unit = NULL;
+ manager->action_what = 0;
+ return r;
+ }
+
+ return 1;
+}
diff --git a/src/login/logind-device.c b/src/login/logind-device.c
new file mode 100644
index 0000000000..51b15358ba
--- /dev/null
+++ b/src/login/logind-device.c
@@ -0,0 +1,96 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <string.h>
+
+#include "logind-device.h"
+#include "util.h"
+
+Device* device_new(Manager *m, const char *sysfs) {
+ Device *d;
+
+ assert(m);
+ assert(sysfs);
+
+ d = new0(Device, 1);
+ if (!d)
+ return NULL;
+
+ d->sysfs = strdup(sysfs);
+ if (!d->sysfs) {
+ free(d);
+ return NULL;
+ }
+
+ if (hashmap_put(m->devices, d->sysfs, d) < 0) {
+ free(d->sysfs);
+ free(d);
+ return NULL;
+ }
+
+ d->manager = m;
+ dual_timestamp_get(&d->timestamp);
+
+ return d;
+}
+
+void device_free(Device *d) {
+ assert(d);
+
+ device_detach(d);
+
+ hashmap_remove(d->manager->devices, d->sysfs);
+
+ free(d->sysfs);
+ free(d);
+}
+
+void device_detach(Device *d) {
+ Seat *s;
+ assert(d);
+
+ if (!d->seat)
+ return;
+
+ s = d->seat;
+ LIST_REMOVE(Device, devices, d->seat->devices, d);
+ d->seat = NULL;
+
+ seat_add_to_gc_queue(s);
+ seat_send_changed(s, "CanGraphical\0");
+}
+
+void device_attach(Device *d, Seat *s) {
+ assert(d);
+ assert(s);
+
+ if (d->seat == s)
+ return;
+
+ if (d->seat)
+ device_detach(d);
+
+ d->seat = s;
+ LIST_PREPEND(Device, devices, s->devices, d);
+
+ seat_send_changed(s, "CanGraphical\0");
+}
diff --git a/src/login/logind-device.h b/src/login/logind-device.h
new file mode 100644
index 0000000000..3b153568cb
--- /dev/null
+++ b/src/login/logind-device.h
@@ -0,0 +1,45 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+typedef struct Device Device;
+
+#include "list.h"
+#include "util.h"
+#include "logind.h"
+#include "logind-seat.h"
+
+struct Device {
+ Manager *manager;
+
+ char *sysfs;
+ Seat *seat;
+
+ dual_timestamp timestamp;
+
+ LIST_FIELDS(struct Device, devices);
+};
+
+Device* device_new(Manager *m, const char *sysfs);
+void device_free(Device *d);
+void device_attach(Device *d, Seat *s);
+void device_detach(Device *d);
diff --git a/src/login/logind-gperf.gperf b/src/login/logind-gperf.gperf
new file mode 100644
index 0000000000..735d2dbc9c
--- /dev/null
+++ b/src/login/logind-gperf.gperf
@@ -0,0 +1,34 @@
+%{
+#include <stddef.h>
+#include "conf-parser.h"
+#include "logind.h"
+%}
+struct ConfigPerfItem;
+%null_strings
+%language=ANSI-C
+%define slot-name section_and_lvalue
+%define hash-function-name logind_gperf_hash
+%define lookup-function-name logind_gperf_lookup
+%readonly-tables
+%omit-struct-type
+%struct-type
+%includes
+%%
+Login.NAutoVTs, config_parse_unsigned, 0, offsetof(Manager, n_autovts)
+Login.ReserveVT, config_parse_unsigned, 0, offsetof(Manager, reserve_vt)
+Login.KillUserProcesses, config_parse_bool, 0, offsetof(Manager, kill_user_processes)
+Login.KillOnlyUsers, config_parse_strv, 0, offsetof(Manager, kill_only_users)
+Login.KillExcludeUsers, config_parse_strv, 0, offsetof(Manager, kill_exclude_users)
+Login.Controllers, config_parse_strv, 0, offsetof(Manager, controllers)
+Login.ResetControllers, config_parse_strv, 0, offsetof(Manager, reset_controllers)
+Login.InhibitDelayMaxSec, config_parse_sec, 0, offsetof(Manager, inhibit_delay_max)
+Login.HandlePowerKey, config_parse_handle_action, 0, offsetof(Manager, handle_power_key)
+Login.HandleSuspendKey, config_parse_handle_action, 0, offsetof(Manager, handle_suspend_key)
+Login.HandleHibernateKey, config_parse_handle_action, 0, offsetof(Manager, handle_hibernate_key)
+Login.HandleLidSwitch, config_parse_handle_action, 0, offsetof(Manager, handle_lid_switch)
+Login.PowerKeyIgnoreInhibited, config_parse_bool, 0, offsetof(Manager, power_key_ignore_inhibited)
+Login.SuspendKeyIgnoreInhibited, config_parse_bool, 0, offsetof(Manager, suspend_key_ignore_inhibited)
+Login.HibernateKeyIgnoreInhibited, config_parse_bool, 0, offsetof(Manager, hibernate_key_ignore_inhibited)
+Login.LidSwitchIgnoreInhibited, config_parse_bool, 0, offsetof(Manager, lid_switch_ignore_inhibited)
+Login.IdleAction, config_parse_handle_action, 0, offsetof(Manager, idle_action)
+Login.IdleActionSec, config_parse_sec, 0, offsetof(Manager, idle_action_usec)
diff --git a/src/login/logind-inhibit.c b/src/login/logind-inhibit.c
new file mode 100644
index 0000000000..e77088364a
--- /dev/null
+++ b/src/login/logind-inhibit.c
@@ -0,0 +1,473 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <fcntl.h>
+#include <sys/epoll.h>
+#include <string.h>
+#include <errno.h>
+#include <unistd.h>
+
+#include "util.h"
+#include "mkdir.h"
+#include "path-util.h"
+#include "logind-inhibit.h"
+#include "fileio.h"
+
+Inhibitor* inhibitor_new(Manager *m, const char* id) {
+ Inhibitor *i;
+
+ assert(m);
+
+ i = new0(Inhibitor, 1);
+ if (!i)
+ return NULL;
+
+ i->state_file = strappend("/run/systemd/inhibit/", id);
+ if (!i->state_file) {
+ free(i);
+ return NULL;
+ }
+
+ i->id = path_get_file_name(i->state_file);
+
+ if (hashmap_put(m->inhibitors, i->id, i) < 0) {
+ free(i->state_file);
+ free(i);
+ return NULL;
+ }
+
+ i->manager = m;
+ i->fifo_fd = -1;
+
+ return i;
+}
+
+void inhibitor_free(Inhibitor *i) {
+ assert(i);
+
+ free(i->who);
+ free(i->why);
+
+ hashmap_remove(i->manager->inhibitors, i->id);
+ inhibitor_remove_fifo(i);
+
+ if (i->state_file) {
+ unlink(i->state_file);
+ free(i->state_file);
+ }
+
+ free(i);
+}
+
+int inhibitor_save(Inhibitor *i) {
+ char *temp_path, *cc;
+ int r;
+ FILE *f;
+
+ assert(i);
+
+ r = mkdir_safe_label("/run/systemd/inhibit", 0755, 0, 0);
+ if (r < 0)
+ goto finish;
+
+ r = fopen_temporary(i->state_file, &f, &temp_path);
+ if (r < 0)
+ goto finish;
+
+ fchmod(fileno(f), 0644);
+
+ fprintf(f,
+ "# This is private data. Do not parse.\n"
+ "WHAT=%s\n"
+ "MODE=%s\n"
+ "UID=%lu\n"
+ "PID=%lu\n",
+ inhibit_what_to_string(i->what),
+ inhibit_mode_to_string(i->mode),
+ (unsigned long) i->uid,
+ (unsigned long) i->pid);
+
+ if (i->who) {
+ cc = cescape(i->who);
+ if (!cc)
+ r = -ENOMEM;
+ else {
+ fprintf(f, "WHO=%s\n", cc);
+ free(cc);
+ }
+ }
+
+ if (i->why) {
+ cc = cescape(i->why);
+ if (!cc)
+ r = -ENOMEM;
+ else {
+ fprintf(f, "WHY=%s\n", cc);
+ free(cc);
+ }
+ }
+
+ if (i->fifo_path)
+ fprintf(f, "FIFO=%s\n", i->fifo_path);
+
+ fflush(f);
+
+ if (ferror(f) || rename(temp_path, i->state_file) < 0) {
+ r = -errno;
+ unlink(i->state_file);
+ unlink(temp_path);
+ }
+
+ fclose(f);
+ free(temp_path);
+
+finish:
+ if (r < 0)
+ log_error("Failed to save inhibit data for %s: %s", i->id, strerror(-r));
+
+ return r;
+}
+
+int inhibitor_start(Inhibitor *i) {
+ assert(i);
+
+ if (i->started)
+ return 0;
+
+ dual_timestamp_get(&i->since);
+
+ log_debug("Inhibitor %s (%s) pid=%lu uid=%lu mode=%s started.",
+ strna(i->who), strna(i->why),
+ (unsigned long) i->pid, (unsigned long) i->uid,
+ inhibit_mode_to_string(i->mode));
+
+ inhibitor_save(i);
+
+ i->started = true;
+
+ manager_send_changed(i->manager, i->mode == INHIBIT_BLOCK ? "BlockInhibited\0" : "DelayInhibited\0");
+
+ return 0;
+}
+
+int inhibitor_stop(Inhibitor *i) {
+ assert(i);
+
+ if (i->started)
+ log_debug("Inhibitor %s (%s) pid=%lu uid=%lu mode=%s stopped.",
+ strna(i->who), strna(i->why),
+ (unsigned long) i->pid, (unsigned long) i->uid,
+ inhibit_mode_to_string(i->mode));
+
+ if (i->state_file)
+ unlink(i->state_file);
+
+ i->started = false;
+
+ manager_send_changed(i->manager, i->mode == INHIBIT_BLOCK ? "BlockInhibited\0" : "DelayInhibited\0");
+
+ return 0;
+}
+
+int inhibitor_load(Inhibitor *i) {
+ InhibitWhat w;
+ InhibitMode mm;
+ int r;
+ char *cc,
+ *what = NULL,
+ *uid = NULL,
+ *pid = NULL,
+ *who = NULL,
+ *why = NULL,
+ *mode = NULL;
+
+ r = parse_env_file(i->state_file, NEWLINE,
+ "WHAT", &what,
+ "UID", &uid,
+ "PID", &pid,
+ "WHO", &who,
+ "WHY", &why,
+ "MODE", &mode,
+ "FIFO", &i->fifo_path,
+ NULL);
+ if (r < 0)
+ goto finish;
+
+ w = what ? inhibit_what_from_string(what) : 0;
+ if (w >= 0)
+ i->what = w;
+
+ mm = mode ? inhibit_mode_from_string(mode) : INHIBIT_BLOCK;
+ if (mm >= 0)
+ i->mode = mm;
+
+ if (uid) {
+ r = parse_uid(uid, &i->uid);
+ if (r < 0)
+ goto finish;
+ }
+
+ if (pid) {
+ r = parse_pid(pid, &i->pid);
+ if (r < 0)
+ goto finish;
+ }
+
+ if (who) {
+ cc = cunescape(who);
+ if (!cc) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ free(i->who);
+ i->who = cc;
+ }
+
+ if (why) {
+ cc = cunescape(why);
+ if (!cc) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ free(i->why);
+ i->why = cc;
+ }
+
+ if (i->fifo_path) {
+ int fd;
+
+ fd = inhibitor_create_fifo(i);
+ if (fd >= 0)
+ close_nointr_nofail(fd);
+ }
+
+finish:
+ free(what);
+ free(uid);
+ free(pid);
+ free(who);
+ free(why);
+
+ return r;
+}
+
+int inhibitor_create_fifo(Inhibitor *i) {
+ int r;
+
+ assert(i);
+
+ /* Create FIFO */
+ if (!i->fifo_path) {
+ r = mkdir_safe_label("/run/systemd/inhibit", 0755, 0, 0);
+ if (r < 0)
+ return r;
+
+ if (asprintf(&i->fifo_path, "/run/systemd/inhibit/%s.ref", i->id) < 0)
+ return -ENOMEM;
+
+ if (mkfifo(i->fifo_path, 0600) < 0 && errno != EEXIST)
+ return -errno;
+ }
+
+ /* Open reading side */
+ if (i->fifo_fd < 0) {
+ struct epoll_event ev = {};
+
+ i->fifo_fd = open(i->fifo_path, O_RDONLY|O_CLOEXEC|O_NDELAY);
+ if (i->fifo_fd < 0)
+ return -errno;
+
+ r = hashmap_put(i->manager->inhibitor_fds, INT_TO_PTR(i->fifo_fd + 1), i);
+ if (r < 0)
+ return r;
+
+ ev.events = 0;
+ ev.data.u32 = FD_OTHER_BASE + i->fifo_fd;
+
+ if (epoll_ctl(i->manager->epoll_fd, EPOLL_CTL_ADD, i->fifo_fd, &ev) < 0)
+ return -errno;
+ }
+
+ /* Open writing side */
+ r = open(i->fifo_path, O_WRONLY|O_CLOEXEC|O_NDELAY);
+ if (r < 0)
+ return -errno;
+
+ return r;
+}
+
+void inhibitor_remove_fifo(Inhibitor *i) {
+ assert(i);
+
+ if (i->fifo_fd >= 0) {
+ assert_se(hashmap_remove(i->manager->inhibitor_fds, INT_TO_PTR(i->fifo_fd + 1)) == i);
+ assert_se(epoll_ctl(i->manager->epoll_fd, EPOLL_CTL_DEL, i->fifo_fd, NULL) == 0);
+ close_nointr_nofail(i->fifo_fd);
+ i->fifo_fd = -1;
+ }
+
+ if (i->fifo_path) {
+ unlink(i->fifo_path);
+ free(i->fifo_path);
+ i->fifo_path = NULL;
+ }
+}
+
+InhibitWhat manager_inhibit_what(Manager *m, InhibitMode mm) {
+ Inhibitor *i;
+ Iterator j;
+ InhibitWhat what = 0;
+
+ assert(m);
+
+ HASHMAP_FOREACH(i, m->inhibitor_fds, j)
+ if (i->mode == mm)
+ what |= i->what;
+
+ return what;
+}
+
+static int pid_is_active(Manager *m, pid_t pid) {
+ Session *s;
+ int r;
+
+ r = manager_get_session_by_pid(m, pid, &s);
+ if (r < 0)
+ return r;
+
+ /* If there's no session assigned to it, then it's globally
+ * active on all ttys */
+ if (r == 0)
+ return 1;
+
+ return session_is_active(s);
+}
+
+bool manager_is_inhibited(
+ Manager *m,
+ InhibitWhat w,
+ InhibitMode mm,
+ dual_timestamp *since,
+ bool ignore_inactive,
+ bool ignore_uid,
+ uid_t uid) {
+
+ Inhibitor *i;
+ Iterator j;
+ struct dual_timestamp ts = { 0, 0 };
+ bool inhibited = false;
+
+ assert(m);
+ assert(w > 0 && w < _INHIBIT_WHAT_MAX);
+
+ HASHMAP_FOREACH(i, m->inhibitor_fds, j) {
+ if (!(i->what & w))
+ continue;
+
+ if (i->mode != mm)
+ continue;
+
+ if (ignore_inactive && pid_is_active(m, i->pid) <= 0)
+ continue;
+
+ if (ignore_uid && i->uid == uid)
+ continue;
+
+ if (!inhibited ||
+ i->since.monotonic < ts.monotonic)
+ ts = i->since;
+
+ inhibited = true;
+ }
+
+ if (since)
+ *since = ts;
+
+ return inhibited;
+}
+
+const char *inhibit_what_to_string(InhibitWhat w) {
+ static __thread char buffer[97];
+ char *p;
+
+ if (w < 0 || w >= _INHIBIT_WHAT_MAX)
+ return NULL;
+
+ p = buffer;
+ if (w & INHIBIT_SHUTDOWN)
+ p = stpcpy(p, "shutdown:");
+ if (w & INHIBIT_SLEEP)
+ p = stpcpy(p, "sleep:");
+ if (w & INHIBIT_IDLE)
+ p = stpcpy(p, "idle:");
+ if (w & INHIBIT_HANDLE_POWER_KEY)
+ p = stpcpy(p, "handle-power-key:");
+ if (w & INHIBIT_HANDLE_SUSPEND_KEY)
+ p = stpcpy(p, "handle-suspend-key:");
+ if (w & INHIBIT_HANDLE_HIBERNATE_KEY)
+ p = stpcpy(p, "handle-hibernate-key:");
+ if (w & INHIBIT_HANDLE_LID_SWITCH)
+ p = stpcpy(p, "handle-lid-switch:");
+
+ if (p > buffer)
+ *(p-1) = 0;
+ else
+ *p = 0;
+
+ return buffer;
+}
+
+InhibitWhat inhibit_what_from_string(const char *s) {
+ InhibitWhat what = 0;
+ char *w, *state;
+ size_t l;
+
+ FOREACH_WORD_SEPARATOR(w, l, s, ":", state) {
+ if (l == 8 && strneq(w, "shutdown", l))
+ what |= INHIBIT_SHUTDOWN;
+ else if (l == 5 && strneq(w, "sleep", l))
+ what |= INHIBIT_SLEEP;
+ else if (l == 4 && strneq(w, "idle", l))
+ what |= INHIBIT_IDLE;
+ else if (l == 16 && strneq(w, "handle-power-key", l))
+ what |= INHIBIT_HANDLE_POWER_KEY;
+ else if (l == 18 && strneq(w, "handle-suspend-key", l))
+ what |= INHIBIT_HANDLE_SUSPEND_KEY;
+ else if (l == 20 && strneq(w, "handle-hibernate-key", l))
+ what |= INHIBIT_HANDLE_HIBERNATE_KEY;
+ else if (l == 17 && strneq(w, "handle-lid-switch", l))
+ what |= INHIBIT_HANDLE_LID_SWITCH;
+ else
+ return _INHIBIT_WHAT_INVALID;
+ }
+
+ return what;
+}
+
+static const char* const inhibit_mode_table[_INHIBIT_MODE_MAX] = {
+ [INHIBIT_BLOCK] = "block",
+ [INHIBIT_DELAY] = "delay"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(inhibit_mode, InhibitMode);
diff --git a/src/login/logind-inhibit.h b/src/login/logind-inhibit.h
new file mode 100644
index 0000000000..4c158ee0fe
--- /dev/null
+++ b/src/login/logind-inhibit.h
@@ -0,0 +1,95 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef foologindinhibithfoo
+#define foologindinhibithfoo
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+typedef struct Inhibitor Inhibitor;
+
+#include "list.h"
+#include "util.h"
+
+typedef enum InhibitWhat {
+ INHIBIT_SHUTDOWN = 1,
+ INHIBIT_SLEEP = 2,
+ INHIBIT_IDLE = 4,
+ INHIBIT_HANDLE_POWER_KEY = 8,
+ INHIBIT_HANDLE_SUSPEND_KEY = 16,
+ INHIBIT_HANDLE_HIBERNATE_KEY = 32,
+ INHIBIT_HANDLE_LID_SWITCH = 64,
+ _INHIBIT_WHAT_MAX = 128,
+ _INHIBIT_WHAT_INVALID = -1
+} InhibitWhat;
+
+typedef enum InhibitMode {
+ INHIBIT_BLOCK,
+ INHIBIT_DELAY,
+ _INHIBIT_MODE_MAX,
+ _INHIBIT_MODE_INVALID = -1
+} InhibitMode;
+
+#include "logind.h"
+#include "logind-seat.h"
+
+struct Inhibitor {
+ Manager *manager;
+
+ char *id;
+ char *state_file;
+
+ bool started;
+
+ InhibitWhat what;
+ char *who;
+ char *why;
+ InhibitMode mode;
+
+ pid_t pid;
+ uid_t uid;
+
+ dual_timestamp since;
+
+ char *fifo_path;
+ int fifo_fd;
+};
+
+Inhibitor* inhibitor_new(Manager *m, const char *id);
+void inhibitor_free(Inhibitor *i);
+
+int inhibitor_save(Inhibitor *i);
+int inhibitor_load(Inhibitor *i);
+
+int inhibitor_start(Inhibitor *i);
+int inhibitor_stop(Inhibitor *i);
+
+int inhibitor_create_fifo(Inhibitor *i);
+void inhibitor_remove_fifo(Inhibitor *i);
+
+InhibitWhat manager_inhibit_what(Manager *m, InhibitMode mm);
+bool manager_is_inhibited(Manager *m, InhibitWhat w, InhibitMode mm, dual_timestamp *since, bool ignore_inactive, bool ignore_uid, uid_t uid);
+
+const char *inhibit_what_to_string(InhibitWhat k);
+InhibitWhat inhibit_what_from_string(const char *s);
+
+const char *inhibit_mode_to_string(InhibitMode k);
+InhibitMode inhibit_mode_from_string(const char *s);
+
+#endif
diff --git a/src/login/logind-seat-dbus.c b/src/login/logind-seat-dbus.c
new file mode 100644
index 0000000000..5c535ba0ec
--- /dev/null
+++ b/src/login/logind-seat-dbus.c
@@ -0,0 +1,412 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <string.h>
+
+#include "logind.h"
+#include "logind-seat.h"
+#include "dbus-common.h"
+#include "util.h"
+
+#define BUS_SEAT_INTERFACE \
+ " <interface name=\"org.freedesktop.login1.Seat\">\n" \
+ " <method name=\"Terminate\"/>\n" \
+ " <method name=\"ActivateSession\">\n" \
+ " <arg name=\"id\" type=\"s\"/>\n" \
+ " </method>\n" \
+ " <property name=\"Id\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"ActiveSession\" type=\"so\" access=\"read\"/>\n" \
+ " <property name=\"CanMultiSession\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"CanTTY\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"CanGraphical\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"Sessions\" type=\"a(so)\" access=\"read\"/>\n" \
+ " <property name=\"IdleHint\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"IdleSinceHint\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"IdleSinceHintMonotonic\" type=\"t\" access=\"read\"/>\n" \
+ " </interface>\n" \
+
+#define INTROSPECTION \
+ DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE \
+ "<node>\n" \
+ BUS_SEAT_INTERFACE \
+ BUS_PROPERTIES_INTERFACE \
+ BUS_PEER_INTERFACE \
+ BUS_INTROSPECTABLE_INTERFACE \
+ "</node>\n"
+
+#define INTERFACES_LIST \
+ BUS_GENERIC_INTERFACES_LIST \
+ "org.freedesktop.login1.Seat\0"
+
+static int bus_seat_append_active(DBusMessageIter *i, const char *property, void *data) {
+ DBusMessageIter sub;
+ Seat *s = data;
+ const char *id, *path;
+ _cleanup_free_ char *p = NULL;
+
+ assert(i);
+ assert(property);
+ assert(s);
+
+ if (!dbus_message_iter_open_container(i, DBUS_TYPE_STRUCT, NULL, &sub))
+ return -ENOMEM;
+
+ if (s->active) {
+ id = s->active->id;
+ path = p = session_bus_path(s->active);
+
+ if (!p)
+ return -ENOMEM;
+ } else {
+ id = "";
+ path = "/";
+ }
+
+ if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &id) ||
+ !dbus_message_iter_append_basic(&sub, DBUS_TYPE_OBJECT_PATH, &path))
+ return -ENOMEM;
+
+ if (!dbus_message_iter_close_container(i, &sub))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_seat_append_sessions(DBusMessageIter *i, const char *property, void *data) {
+ DBusMessageIter sub, sub2;
+ Seat *s = data;
+ Session *session;
+
+ assert(i);
+ assert(property);
+ assert(s);
+
+ if (!dbus_message_iter_open_container(i, DBUS_TYPE_ARRAY, "(so)", &sub))
+ return -ENOMEM;
+
+ LIST_FOREACH(sessions_by_seat, session, s->sessions) {
+ _cleanup_free_ char *p = NULL;
+
+ if (!dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, NULL, &sub2))
+ return -ENOMEM;
+
+ p = session_bus_path(session);
+ if (!p)
+ return -ENOMEM;
+
+ if (!dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &session->id) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_OBJECT_PATH, &p))
+ return -ENOMEM;
+
+ if (!dbus_message_iter_close_container(&sub, &sub2))
+ return -ENOMEM;
+ }
+
+ if (!dbus_message_iter_close_container(i, &sub))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_seat_append_can_multi_session(DBusMessageIter *i, const char *property, void *data) {
+ Seat *s = data;
+ dbus_bool_t b;
+
+ assert(i);
+ assert(property);
+ assert(s);
+
+ b = seat_can_multi_session(s);
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_BOOLEAN, &b))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_seat_append_can_tty(DBusMessageIter *i, const char *property, void *data) {
+ Seat *s = data;
+ dbus_bool_t b;
+
+ assert(i);
+ assert(property);
+ assert(s);
+
+ b = seat_can_tty(s);
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_BOOLEAN, &b))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_seat_append_can_graphical(DBusMessageIter *i, const char *property, void *data) {
+ Seat *s = data;
+ dbus_bool_t b;
+
+ assert(i);
+ assert(property);
+ assert(s);
+
+ b = seat_can_graphical(s);
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_BOOLEAN, &b))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_seat_append_idle_hint(DBusMessageIter *i, const char *property, void *data) {
+ Seat *s = data;
+ dbus_bool_t b;
+
+ assert(i);
+ assert(property);
+ assert(s);
+
+ b = seat_get_idle_hint(s, NULL) > 0;
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_BOOLEAN, &b))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_seat_append_idle_hint_since(DBusMessageIter *i, const char *property, void *data) {
+ Seat *s = data;
+ dual_timestamp t;
+ uint64_t k;
+
+ assert(i);
+ assert(property);
+ assert(s);
+
+ seat_get_idle_hint(s, &t);
+ k = streq(property, "IdleSinceHint") ? t.realtime : t.monotonic;
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT64, &k))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int get_seat_for_path(Manager *m, const char *path, Seat **_s) {
+ Seat *s;
+ char *id;
+
+ assert(m);
+ assert(path);
+ assert(_s);
+
+ if (!startswith(path, "/org/freedesktop/login1/seat/"))
+ return -EINVAL;
+
+ id = bus_path_unescape(path + 29);
+ if (!id)
+ return -ENOMEM;
+
+ s = hashmap_get(m->seats, id);
+ free(id);
+
+ if (!s)
+ return -ENOENT;
+
+ *_s = s;
+ return 0;
+}
+
+static const BusProperty bus_login_seat_properties[] = {
+ { "Id", bus_property_append_string, "s", offsetof(Seat, id), true },
+ { "ActiveSession", bus_seat_append_active, "(so)", 0 },
+ { "CanMultiSession", bus_seat_append_can_multi_session, "b", 0 },
+ { "CanTTY", bus_seat_append_can_tty, "b", 0 },
+ { "CanGraphical", bus_seat_append_can_graphical, "b", 0 },
+ { "Sessions", bus_seat_append_sessions, "a(so)", 0 },
+ { "IdleHint", bus_seat_append_idle_hint, "b", 0 },
+ { "IdleSinceHint", bus_seat_append_idle_hint_since, "t", 0 },
+ { "IdleSinceHintMonotonic", bus_seat_append_idle_hint_since, "t", 0 },
+ { NULL, }
+};
+
+static DBusHandlerResult seat_message_dispatch(
+ Seat *s,
+ DBusConnection *connection,
+ DBusMessage *message) {
+
+ DBusError error;
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ int r;
+
+ assert(s);
+ assert(connection);
+ assert(message);
+
+ dbus_error_init(&error);
+
+ if (dbus_message_is_method_call(message, "org.freedesktop.login1.Seat", "Terminate")) {
+
+ r = seat_stop_sessions(s);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Seat", "ActivateSession")) {
+ const char *name;
+ Session *session;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ session = hashmap_get(s->manager->sessions, name);
+ if (!session || session->seat != s)
+ return bus_send_error_reply(connection, message, &error, -ENOENT);
+
+ r = session_activate(session);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+ } else {
+ const BusBoundProperties bps[] = {
+ { "org.freedesktop.login1.Seat", bus_login_seat_properties, s },
+ { NULL, }
+ };
+ return bus_default_message_handler(connection, message, INTROSPECTION, INTERFACES_LIST, bps);
+ }
+
+ if (reply) {
+ if (!bus_maybe_send_reply(connection, message, reply))
+ goto oom;
+ }
+
+ return DBUS_HANDLER_RESULT_HANDLED;
+
+oom:
+ dbus_error_free(&error);
+
+ return DBUS_HANDLER_RESULT_NEED_MEMORY;
+}
+
+static DBusHandlerResult seat_message_handler(
+ DBusConnection *connection,
+ DBusMessage *message,
+ void *userdata) {
+
+ Manager *m = userdata;
+ Seat *s;
+ int r;
+
+ r = get_seat_for_path(m, dbus_message_get_path(message), &s);
+ if (r < 0) {
+
+ if (r == -ENOMEM)
+ return DBUS_HANDLER_RESULT_NEED_MEMORY;
+
+ if (r == -ENOENT) {
+ DBusError e;
+
+ dbus_error_init(&e);
+ dbus_set_error_const(&e, DBUS_ERROR_UNKNOWN_OBJECT, "Unknown seat");
+ return bus_send_error_reply(connection, message, &e, r);
+ }
+
+ return bus_send_error_reply(connection, message, NULL, r);
+ }
+
+ return seat_message_dispatch(s, connection, message);
+}
+
+const DBusObjectPathVTable bus_seat_vtable = {
+ .message_function = seat_message_handler
+};
+
+char *seat_bus_path(Seat *s) {
+ _cleanup_free_ char *t;
+
+ assert(s);
+
+ t = bus_path_escape(s->id);
+ if (!t)
+ return NULL;
+
+ return strappend("/org/freedesktop/login1/seat/", t);
+}
+
+int seat_send_signal(Seat *s, bool new_seat) {
+ _cleanup_dbus_message_unref_ DBusMessage *m = NULL;
+ _cleanup_free_ char *p = NULL;
+
+ assert(s);
+
+ m = dbus_message_new_signal("/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ new_seat ? "SeatNew" : "SeatRemoved");
+ if (!m)
+ return -ENOMEM;
+
+ p = seat_bus_path(s);
+ if (!p)
+ return -ENOMEM;
+
+ if (!dbus_message_append_args(
+ m,
+ DBUS_TYPE_STRING, &s->id,
+ DBUS_TYPE_OBJECT_PATH, &p,
+ DBUS_TYPE_INVALID))
+ return -ENOMEM;
+
+ if (!dbus_connection_send(s->manager->bus, m, NULL))
+ return -ENOMEM;
+
+ return 0;
+}
+
+int seat_send_changed(Seat *s, const char *properties) {
+ _cleanup_dbus_message_unref_ DBusMessage *m = NULL;
+ _cleanup_free_ char *p = NULL;
+
+ assert(s);
+
+ if (!s->started)
+ return 0;
+
+ p = seat_bus_path(s);
+ if (!p)
+ return -ENOMEM;
+
+ m = bus_properties_changed_new(p, "org.freedesktop.login1.Seat", properties);
+ if (!m)
+ return -ENOMEM;
+
+ if (!dbus_connection_send(s->manager->bus, m, NULL))
+ return -ENOMEM;
+
+ return 0;
+}
diff --git a/src/login/logind-seat.c b/src/login/logind-seat.c
new file mode 100644
index 0000000000..470d08bc05
--- /dev/null
+++ b/src/login/logind-seat.c
@@ -0,0 +1,543 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <errno.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/ioctl.h>
+#include <linux/vt.h>
+#include <string.h>
+
+#include "systemd/sd-id128.h"
+#include "systemd/sd-messages.h"
+#include "logind-seat.h"
+#include "logind-acl.h"
+#include "util.h"
+#include "mkdir.h"
+#include "path-util.h"
+
+Seat *seat_new(Manager *m, const char *id) {
+ Seat *s;
+
+ assert(m);
+ assert(id);
+
+ s = new0(Seat, 1);
+ if (!s)
+ return NULL;
+
+ s->state_file = strappend("/run/systemd/seats/", id);
+ if (!s->state_file) {
+ free(s);
+ return NULL;
+ }
+
+ s->id = path_get_file_name(s->state_file);
+ s->manager = m;
+
+ if (hashmap_put(m->seats, s->id, s) < 0) {
+ free(s->state_file);
+ free(s);
+ return NULL;
+ }
+
+ return s;
+}
+
+void seat_free(Seat *s) {
+ assert(s);
+
+ if (s->in_gc_queue)
+ LIST_REMOVE(Seat, gc_queue, s->manager->seat_gc_queue, s);
+
+ while (s->sessions)
+ session_free(s->sessions);
+
+ assert(!s->active);
+
+ while (s->devices)
+ device_free(s->devices);
+
+ hashmap_remove(s->manager->seats, s->id);
+
+ free(s->state_file);
+ free(s);
+}
+
+int seat_save(Seat *s) {
+ int r;
+ FILE *f;
+ char *temp_path;
+
+ assert(s);
+
+ if (!s->started)
+ return 0;
+
+ r = mkdir_safe_label("/run/systemd/seats", 0755, 0, 0);
+ if (r < 0)
+ goto finish;
+
+ r = fopen_temporary(s->state_file, &f, &temp_path);
+ if (r < 0)
+ goto finish;
+
+ fchmod(fileno(f), 0644);
+
+ fprintf(f,
+ "# This is private data. Do not parse.\n"
+ "IS_VTCONSOLE=%i\n"
+ "CAN_MULTI_SESSION=%i\n"
+ "CAN_TTY=%i\n"
+ "CAN_GRAPHICAL=%i\n",
+ seat_is_vtconsole(s),
+ seat_can_multi_session(s),
+ seat_can_tty(s),
+ seat_can_graphical(s));
+
+ if (s->active) {
+ assert(s->active->user);
+
+ fprintf(f,
+ "ACTIVE=%s\n"
+ "ACTIVE_UID=%lu\n",
+ s->active->id,
+ (unsigned long) s->active->user->uid);
+ }
+
+ if (s->sessions) {
+ Session *i;
+
+ fputs("SESSIONS=", f);
+ LIST_FOREACH(sessions_by_seat, i, s->sessions) {
+ fprintf(f,
+ "%s%c",
+ i->id,
+ i->sessions_by_seat_next ? ' ' : '\n');
+ }
+
+ fputs("UIDS=", f);
+ LIST_FOREACH(sessions_by_seat, i, s->sessions)
+ fprintf(f,
+ "%lu%c",
+ (unsigned long) i->user->uid,
+ i->sessions_by_seat_next ? ' ' : '\n');
+ }
+
+ fflush(f);
+
+ if (ferror(f) || rename(temp_path, s->state_file) < 0) {
+ r = -errno;
+ unlink(s->state_file);
+ unlink(temp_path);
+ }
+
+ fclose(f);
+ free(temp_path);
+
+finish:
+ if (r < 0)
+ log_error("Failed to save seat data for %s: %s", s->id, strerror(-r));
+
+ return r;
+}
+
+int seat_load(Seat *s) {
+ assert(s);
+
+ /* There isn't actually anything to read here ... */
+
+ return 0;
+}
+
+static int vt_allocate(int vtnr) {
+ int fd, r;
+ char *p;
+
+ assert(vtnr >= 1);
+
+ if (asprintf(&p, "/dev/tty%i", vtnr) < 0)
+ return -ENOMEM;
+
+ fd = open_terminal(p, O_RDWR|O_NOCTTY|O_CLOEXEC);
+ free(p);
+
+ r = fd < 0 ? -errno : 0;
+
+ if (fd >= 0)
+ close_nointr_nofail(fd);
+
+ return r;
+}
+
+int seat_preallocate_vts(Seat *s) {
+ int r = 0;
+ unsigned i;
+
+ assert(s);
+ assert(s->manager);
+
+ log_debug("Preallocating VTs...");
+
+ if (s->manager->n_autovts <= 0)
+ return 0;
+
+ if (!seat_can_multi_session(s))
+ return 0;
+
+ for (i = 1; i <= s->manager->n_autovts; i++) {
+ int q;
+
+ q = vt_allocate(i);
+ if (q < 0) {
+ log_error("Failed to preallocate VT %i: %s", i, strerror(-q));
+ r = q;
+ }
+ }
+
+ return r;
+}
+
+int seat_apply_acls(Seat *s, Session *old_active) {
+ int r;
+
+ assert(s);
+
+ r = devnode_acl_all(s->manager->udev,
+ s->id,
+ false,
+ !!old_active, old_active ? old_active->user->uid : 0,
+ !!s->active, s->active ? s->active->user->uid : 0);
+
+ if (r < 0)
+ log_error("Failed to apply ACLs: %s", strerror(-r));
+
+ return r;
+}
+
+int seat_set_active(Seat *s, Session *session) {
+ Session *old_active;
+
+ assert(s);
+ assert(!session || session->seat == s);
+
+ if (session == s->active)
+ return 0;
+
+ old_active = s->active;
+ s->active = session;
+
+ seat_apply_acls(s, old_active);
+
+ if (session && session->started)
+ session_send_changed(session, "Active\0");
+
+ if (!session || session->started)
+ seat_send_changed(s, "ActiveSession\0");
+
+ seat_save(s);
+
+ if (session) {
+ session_save(session);
+ user_save(session->user);
+ }
+
+ if (old_active) {
+ session_save(old_active);
+ if (!session || session->user != old_active->user)
+ user_save(old_active->user);
+ }
+
+ return 0;
+}
+
+int seat_active_vt_changed(Seat *s, int vtnr) {
+ Session *i, *new_active = NULL;
+ int r;
+
+ assert(s);
+ assert(vtnr >= 1);
+
+ if (!seat_can_multi_session(s))
+ return -EINVAL;
+
+ log_debug("VT changed to %i", vtnr);
+
+ LIST_FOREACH(sessions_by_seat, i, s->sessions)
+ if (i->vtnr == vtnr) {
+ new_active = i;
+ break;
+ }
+
+ r = seat_set_active(s, new_active);
+ manager_spawn_autovt(s->manager, vtnr);
+
+ return r;
+}
+
+int seat_read_active_vt(Seat *s) {
+ char t[64];
+ ssize_t k;
+ int r, vtnr;
+
+ assert(s);
+
+ if (!seat_can_multi_session(s))
+ return 0;
+
+ lseek(s->manager->console_active_fd, SEEK_SET, 0);
+
+ k = read(s->manager->console_active_fd, t, sizeof(t)-1);
+ if (k <= 0) {
+ log_error("Failed to read current console: %s", k < 0 ? strerror(-errno) : "EOF");
+ return k < 0 ? -errno : -EIO;
+ }
+
+ t[k] = 0;
+ truncate_nl(t);
+
+ if (!startswith(t, "tty")) {
+ log_error("Hm, /sys/class/tty/tty0/active is badly formatted.");
+ return -EIO;
+ }
+
+ r = safe_atoi(t+3, &vtnr);
+ if (r < 0) {
+ log_error("Failed to parse VT number %s", t+3);
+ return r;
+ }
+
+ if (vtnr <= 0) {
+ log_error("VT number invalid: %s", t+3);
+ return -EIO;
+ }
+
+ return seat_active_vt_changed(s, vtnr);
+}
+
+int seat_start(Seat *s) {
+ assert(s);
+
+ if (s->started)
+ return 0;
+
+ log_struct(LOG_INFO,
+ MESSAGE_ID(SD_MESSAGE_SEAT_START),
+ "SEAT_ID=%s", s->id,
+ "MESSAGE=New seat %s.", s->id,
+ NULL);
+
+ /* Initialize VT magic stuff */
+ seat_preallocate_vts(s);
+
+ /* Read current VT */
+ seat_read_active_vt(s);
+
+ s->started = true;
+
+ /* Save seat data */
+ seat_save(s);
+
+ seat_send_signal(s, true);
+
+ return 0;
+}
+
+int seat_stop(Seat *s) {
+ int r = 0;
+
+ assert(s);
+
+ if (s->started)
+ log_struct(LOG_INFO,
+ MESSAGE_ID(SD_MESSAGE_SEAT_STOP),
+ "SEAT_ID=%s", s->id,
+ "MESSAGE=Removed seat %s.", s->id,
+ NULL);
+
+ seat_stop_sessions(s);
+
+ unlink(s->state_file);
+ seat_add_to_gc_queue(s);
+
+ if (s->started)
+ seat_send_signal(s, false);
+
+ s->started = false;
+
+ return r;
+}
+
+int seat_stop_sessions(Seat *s) {
+ Session *session;
+ int r = 0, k;
+
+ assert(s);
+
+ LIST_FOREACH(sessions_by_seat, session, s->sessions) {
+ k = session_stop(session);
+ if (k < 0)
+ r = k;
+ }
+
+ return r;
+}
+
+int seat_attach_session(Seat *s, Session *session) {
+ assert(s);
+ assert(session);
+ assert(!session->seat);
+
+ session->seat = s;
+ LIST_PREPEND(Session, sessions_by_seat, s->sessions, session);
+
+ seat_send_changed(s, "Sessions\0");
+
+ /* Note that even if a seat is not multi-session capable it
+ * still might have multiple sessions on it since old, dead
+ * sessions might continue to be tracked until all their
+ * processes are gone. The most recently added session
+ * (i.e. the first in s->sessions) is the one that matters. */
+
+ if (!seat_can_multi_session(s))
+ seat_set_active(s, session);
+
+ return 0;
+}
+
+bool seat_is_vtconsole(Seat *s) {
+ assert(s);
+
+ return s->manager->vtconsole == s;
+}
+
+bool seat_can_multi_session(Seat *s) {
+ assert(s);
+
+ if (!seat_is_vtconsole(s))
+ return false;
+
+ /* If we can't watch which VT is in the foreground, we don't
+ * support VT switching */
+
+ return s->manager->console_active_fd >= 0;
+}
+
+bool seat_can_tty(Seat *s) {
+ assert(s);
+
+ return seat_is_vtconsole(s);
+}
+
+bool seat_can_graphical(Seat *s) {
+ assert(s);
+
+ return !!s->devices;
+}
+
+int seat_get_idle_hint(Seat *s, dual_timestamp *t) {
+ Session *session;
+ bool idle_hint = true;
+ dual_timestamp ts = { 0, 0 };
+
+ assert(s);
+
+ LIST_FOREACH(sessions_by_seat, session, s->sessions) {
+ dual_timestamp k;
+ int ih;
+
+ ih = session_get_idle_hint(session, &k);
+ if (ih < 0)
+ return ih;
+
+ if (!ih) {
+ if (!idle_hint) {
+ if (k.monotonic > ts.monotonic)
+ ts = k;
+ } else {
+ idle_hint = false;
+ ts = k;
+ }
+ } else if (idle_hint) {
+
+ if (k.monotonic > ts.monotonic)
+ ts = k;
+ }
+ }
+
+ if (t)
+ *t = ts;
+
+ return idle_hint;
+}
+
+int seat_check_gc(Seat *s, bool drop_not_started) {
+ assert(s);
+
+ if (drop_not_started && !s->started)
+ return 0;
+
+ if (seat_is_vtconsole(s))
+ return 1;
+
+ return !!s->devices;
+}
+
+void seat_add_to_gc_queue(Seat *s) {
+ assert(s);
+
+ if (s->in_gc_queue)
+ return;
+
+ LIST_PREPEND(Seat, gc_queue, s->manager->seat_gc_queue, s);
+ s->in_gc_queue = true;
+}
+
+static bool seat_name_valid_char(char c) {
+ return
+ (c >= 'a' && c <= 'z') ||
+ (c >= 'A' && c <= 'Z') ||
+ (c >= '0' && c <= '9') ||
+ c == '-' ||
+ c == '_';
+}
+
+bool seat_name_is_valid(const char *name) {
+ const char *p;
+
+ assert(name);
+
+ if (!startswith(name, "seat"))
+ return false;
+
+ if (!name[4])
+ return false;
+
+ for (p = name; *p; p++)
+ if (!seat_name_valid_char(*p))
+ return false;
+
+ if (strlen(name) > 255)
+ return false;
+
+ return true;
+}
diff --git a/src/login/logind-seat.h b/src/login/logind-seat.h
new file mode 100644
index 0000000000..c8ab17f7cf
--- /dev/null
+++ b/src/login/logind-seat.h
@@ -0,0 +1,83 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+typedef struct Seat Seat;
+
+#include "list.h"
+#include "util.h"
+#include "logind.h"
+#include "logind-device.h"
+#include "logind-session.h"
+
+struct Seat {
+ Manager *manager;
+ char *id;
+
+ char *state_file;
+
+ LIST_HEAD(Device, devices);
+
+ Session *active;
+ LIST_HEAD(Session, sessions);
+
+ bool in_gc_queue:1;
+ bool started:1;
+
+ LIST_FIELDS(Seat, gc_queue);
+};
+
+Seat *seat_new(Manager *m, const char *id);
+void seat_free(Seat *s);
+
+int seat_save(Seat *s);
+int seat_load(Seat *s);
+
+int seat_apply_acls(Seat *s, Session *old_active);
+int seat_set_active(Seat *s, Session *session);
+int seat_active_vt_changed(Seat *s, int vtnr);
+int seat_read_active_vt(Seat *s);
+int seat_preallocate_vts(Seat *s);
+
+int seat_attach_session(Seat *s, Session *session);
+
+bool seat_is_vtconsole(Seat *s);
+bool seat_can_multi_session(Seat *s);
+bool seat_can_tty(Seat *s);
+bool seat_can_graphical(Seat *s);
+
+int seat_get_idle_hint(Seat *s, dual_timestamp *t);
+
+int seat_start(Seat *s);
+int seat_stop(Seat *s);
+int seat_stop_sessions(Seat *s);
+
+int seat_check_gc(Seat *s, bool drop_not_started);
+void seat_add_to_gc_queue(Seat *s);
+
+bool seat_name_is_valid(const char *name);
+char *seat_bus_path(Seat *s);
+
+extern const DBusObjectPathVTable bus_seat_vtable;
+
+int seat_send_signal(Seat *s, bool new_seat);
+int seat_send_changed(Seat *s, const char *properties);
diff --git a/src/login/logind-session-dbus.c b/src/login/logind-session-dbus.c
new file mode 100644
index 0000000000..ec823af547
--- /dev/null
+++ b/src/login/logind-session-dbus.c
@@ -0,0 +1,554 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <string.h>
+
+#include "logind.h"
+#include "logind-session.h"
+#include "dbus-common.h"
+#include "util.h"
+
+#define BUS_SESSION_INTERFACE \
+ " <interface name=\"org.freedesktop.login1.Session\">\n" \
+ " <method name=\"Terminate\"/>\n" \
+ " <method name=\"Activate\"/>\n" \
+ " <method name=\"Lock\"/>\n" \
+ " <method name=\"Unlock\"/>\n" \
+ " <method name=\"SetIdleHint\">\n" \
+ " <arg name=\"b\" type=\"b\"/>\n" \
+ " </method>\n" \
+ " <method name=\"Kill\">\n" \
+ " <arg name=\"who\" type=\"s\"/>\n" \
+ " <arg name=\"signal\" type=\"s\"/>\n" \
+ " </method>\n" \
+ " <signal name=\"Lock\"/>\n" \
+ " <signal name=\"Unlock\"/>\n" \
+ " <property name=\"Id\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"User\" type=\"(uo)\" access=\"read\"/>\n" \
+ " <property name=\"Name\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"Timestamp\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"TimestampMonotonic\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"DefaultControlGroup\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"VTNr\" type=\"u\" access=\"read\"/>\n" \
+ " <property name=\"Seat\" type=\"(so)\" access=\"read\"/>\n" \
+ " <property name=\"TTY\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"Display\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"Remote\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"RemoteHost\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"RemoteUser\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"Service\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"Leader\" type=\"u\" access=\"read\"/>\n" \
+ " <property name=\"Audit\" type=\"u\" access=\"read\"/>\n" \
+ " <property name=\"Type\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"Class\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"Active\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"State\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"Controllers\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"ResetControllers\" type=\"as\" access=\"read\"/>\n" \
+ " <property name=\"KillProcesses\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"IdleHint\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"IdleSinceHint\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"IdleSinceHintMonotonic\" type=\"t\" access=\"read\"/>\n" \
+ " </interface>\n"
+
+#define INTROSPECTION \
+ DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE \
+ "<node>\n" \
+ BUS_SESSION_INTERFACE \
+ BUS_PROPERTIES_INTERFACE \
+ BUS_PEER_INTERFACE \
+ BUS_INTROSPECTABLE_INTERFACE \
+ "</node>\n"
+
+#define INTERFACES_LIST \
+ BUS_GENERIC_INTERFACES_LIST \
+ "org.freedesktop.login1.Session\0"
+
+static int bus_session_append_seat(DBusMessageIter *i, const char *property, void *data) {
+ DBusMessageIter sub;
+ Session *s = data;
+ const char *id, *path;
+ char *p = NULL;
+
+ assert(i);
+ assert(property);
+ assert(s);
+
+ if (!dbus_message_iter_open_container(i, DBUS_TYPE_STRUCT, NULL, &sub))
+ return -ENOMEM;
+
+ if (s->seat) {
+ id = s->seat->id;
+ path = p = seat_bus_path(s->seat);
+
+ if (!p)
+ return -ENOMEM;
+ } else {
+ id = "";
+ path = "/";
+ }
+
+ if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &id) ||
+ !dbus_message_iter_append_basic(&sub, DBUS_TYPE_OBJECT_PATH, &path))
+ return -ENOMEM;
+
+ if (!dbus_message_iter_close_container(i, &sub))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_session_append_user(DBusMessageIter *i, const char *property, void *data) {
+ DBusMessageIter sub;
+ User *u = data;
+ _cleanup_free_ char *p = NULL;
+
+ assert(i);
+ assert(property);
+ assert(u);
+
+ if (!dbus_message_iter_open_container(i, DBUS_TYPE_STRUCT, NULL, &sub))
+ return -ENOMEM;
+
+ p = user_bus_path(u);
+ if (!p)
+ return -ENOMEM;
+
+ if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_UINT32, &u->uid) ||
+ !dbus_message_iter_append_basic(&sub, DBUS_TYPE_OBJECT_PATH, &p))
+ return -ENOMEM;
+
+ if (!dbus_message_iter_close_container(i, &sub))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_session_append_active(DBusMessageIter *i, const char *property, void *data) {
+ Session *s = data;
+ dbus_bool_t b;
+
+ assert(i);
+ assert(property);
+ assert(s);
+
+ b = session_is_active(s);
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_BOOLEAN, &b))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_session_append_idle_hint(DBusMessageIter *i, const char *property, void *data) {
+ Session *s = data;
+ int b;
+
+ assert(i);
+ assert(property);
+ assert(s);
+
+ b = session_get_idle_hint(s, NULL) > 0;
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_BOOLEAN, &b))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_session_append_idle_hint_since(DBusMessageIter *i, const char *property, void *data) {
+ Session *s = data;
+ dual_timestamp t;
+ uint64_t u;
+ int r;
+
+ assert(i);
+ assert(property);
+ assert(s);
+
+ r = session_get_idle_hint(s, &t);
+ if (r < 0)
+ return r;
+
+ u = streq(property, "IdleSinceHint") ? t.realtime : t.monotonic;
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT64, &u))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_session_append_default_cgroup(DBusMessageIter *i, const char *property, void *data) {
+ Session *s = data;
+ _cleanup_free_ char *t = NULL;
+ int r;
+ bool success;
+
+ assert(i);
+ assert(property);
+ assert(s);
+
+ r = cg_join_spec(SYSTEMD_CGROUP_CONTROLLER, s->cgroup_path, &t);
+ if (r < 0)
+ return r;
+
+ success = dbus_message_iter_append_basic(i, DBUS_TYPE_STRING, &t);
+ return success ? 0 : -ENOMEM;
+}
+
+static DEFINE_BUS_PROPERTY_APPEND_ENUM(bus_session_append_type, session_type, SessionType);
+static DEFINE_BUS_PROPERTY_APPEND_ENUM(bus_session_append_class, session_class, SessionClass);
+
+static int bus_session_append_state(DBusMessageIter *i, const char *property, void *data) {
+ Session *s = data;
+ const char *state;
+
+ assert(i);
+ assert(property);
+ assert(s);
+
+ state = session_state_to_string(session_get_state(s));
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_STRING, &state))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int get_session_for_path(Manager *m, const char *path, Session **_s) {
+ Session *s;
+ char *id;
+
+ assert(m);
+ assert(path);
+ assert(_s);
+
+ if (!startswith(path, "/org/freedesktop/login1/session/"))
+ return -EINVAL;
+
+ id = bus_path_unescape(path + 32);
+ if (!id)
+ return -ENOMEM;
+
+ s = hashmap_get(m->sessions, id);
+ free(id);
+
+ if (!s)
+ return -ENOENT;
+
+ *_s = s;
+ return 0;
+}
+
+static const BusProperty bus_login_session_properties[] = {
+ { "Id", bus_property_append_string, "s", offsetof(Session, id), true },
+ { "Timestamp", bus_property_append_usec, "t", offsetof(Session, timestamp.realtime) },
+ { "TimestampMonotonic", bus_property_append_usec, "t", offsetof(Session, timestamp.monotonic) },
+ { "DefaultControlGroup", bus_session_append_default_cgroup, "s", 0, },
+ { "VTNr", bus_property_append_uint32, "u", offsetof(Session, vtnr) },
+ { "Seat", bus_session_append_seat, "(so)", 0 },
+ { "TTY", bus_property_append_string, "s", offsetof(Session, tty), true },
+ { "Display", bus_property_append_string, "s", offsetof(Session, display), true },
+ { "Remote", bus_property_append_bool, "b", offsetof(Session, remote) },
+ { "RemoteUser", bus_property_append_string, "s", offsetof(Session, remote_user), true },
+ { "RemoteHost", bus_property_append_string, "s", offsetof(Session, remote_host), true },
+ { "Service", bus_property_append_string, "s", offsetof(Session, service), true },
+ { "Leader", bus_property_append_pid, "u", offsetof(Session, leader) },
+ { "Audit", bus_property_append_uint32, "u", offsetof(Session, audit_id) },
+ { "Type", bus_session_append_type, "s", offsetof(Session, type) },
+ { "Class", bus_session_append_class, "s", offsetof(Session, class) },
+ { "Active", bus_session_append_active, "b", 0 },
+ { "State", bus_session_append_state, "s", 0 },
+ { "Controllers", bus_property_append_strv, "as", offsetof(Session, controllers), true },
+ { "ResetControllers", bus_property_append_strv, "as", offsetof(Session, reset_controllers), true },
+ { "KillProcesses", bus_property_append_bool, "b", offsetof(Session, kill_processes) },
+ { "IdleHint", bus_session_append_idle_hint, "b", 0 },
+ { "IdleSinceHint", bus_session_append_idle_hint_since, "t", 0 },
+ { "IdleSinceHintMonotonic", bus_session_append_idle_hint_since, "t", 0 },
+ { NULL, }
+};
+
+static const BusProperty bus_login_session_user_properties[] = {
+ { "User", bus_session_append_user, "(uo)", 0 },
+ { "Name", bus_property_append_string, "s", offsetof(User, name), true },
+ { NULL, }
+};
+
+static DBusHandlerResult session_message_dispatch(
+ Session *s,
+ DBusConnection *connection,
+ DBusMessage *message) {
+
+ DBusError error;
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ int r;
+
+ assert(s);
+ assert(connection);
+ assert(message);
+
+ dbus_error_init(&error);
+
+ if (dbus_message_is_method_call(message, "org.freedesktop.login1.Session", "Terminate")) {
+
+ r = session_stop(s);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Session", "Activate")) {
+
+ r = session_activate(s);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Session", "Lock") ||
+ dbus_message_is_method_call(message, "org.freedesktop.login1.Session", "Unlock")) {
+
+ if (session_send_lock(s, streq(dbus_message_get_member(message), "Lock")) < 0)
+ goto oom;
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Session", "SetIdleHint")) {
+ dbus_bool_t b;
+ unsigned long ul;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_BOOLEAN, &b,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ ul = dbus_bus_get_unix_user(connection, dbus_message_get_sender(message), &error);
+ if (ul == (unsigned long) -1)
+ return bus_send_error_reply(connection, message, &error, -EIO);
+
+ if (ul != 0 && ul != s->user->uid)
+ return bus_send_error_reply(connection, message, NULL, -EPERM);
+
+ session_set_idle_hint(s, b);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.Session", "Kill")) {
+ const char *swho;
+ int32_t signo;
+ KillWho who;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &swho,
+ DBUS_TYPE_INT32, &signo,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ if (isempty(swho))
+ who = KILL_ALL;
+ else {
+ who = kill_who_from_string(swho);
+ if (who < 0)
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+ }
+
+ if (signo <= 0 || signo >= _NSIG)
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ r = session_kill(s, who, signo);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else {
+ const BusBoundProperties bps[] = {
+ { "org.freedesktop.login1.Session", bus_login_session_properties, s },
+ { "org.freedesktop.login1.Session", bus_login_session_user_properties, s->user },
+ { NULL, }
+ };
+ return bus_default_message_handler(connection, message, INTROSPECTION, INTERFACES_LIST, bps);
+ }
+
+ if (reply) {
+ if (!bus_maybe_send_reply(connection, message, reply))
+ goto oom;
+ }
+
+ return DBUS_HANDLER_RESULT_HANDLED;
+
+oom:
+ dbus_error_free(&error);
+
+ return DBUS_HANDLER_RESULT_NEED_MEMORY;
+}
+
+static DBusHandlerResult session_message_handler(
+ DBusConnection *connection,
+ DBusMessage *message,
+ void *userdata) {
+
+ Manager *m = userdata;
+ Session *s;
+ int r;
+
+ r = get_session_for_path(m, dbus_message_get_path(message), &s);
+ if (r < 0) {
+
+ if (r == -ENOMEM)
+ return DBUS_HANDLER_RESULT_NEED_MEMORY;
+
+ if (r == -ENOENT) {
+ DBusError e;
+
+ dbus_error_init(&e);
+ dbus_set_error_const(&e, DBUS_ERROR_UNKNOWN_OBJECT, "Unknown session");
+ return bus_send_error_reply(connection, message, &e, r);
+ }
+
+ return bus_send_error_reply(connection, message, NULL, r);
+ }
+
+ return session_message_dispatch(s, connection, message);
+}
+
+const DBusObjectPathVTable bus_session_vtable = {
+ .message_function = session_message_handler
+};
+
+char *session_bus_path(Session *s) {
+ _cleanup_free_ char *t;
+
+ assert(s);
+
+ t = bus_path_escape(s->id);
+ if (!t)
+ return NULL;
+
+ return strappend("/org/freedesktop/login1/session/", t);
+}
+
+int session_send_signal(Session *s, bool new_session) {
+ _cleanup_dbus_message_unref_ DBusMessage *m = NULL;
+ _cleanup_free_ char *p = NULL;
+
+ assert(s);
+
+ m = dbus_message_new_signal("/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ new_session ? "SessionNew" : "SessionRemoved");
+
+ if (!m)
+ return -ENOMEM;
+
+ p = session_bus_path(s);
+ if (!p)
+ return -ENOMEM;
+
+ if (!dbus_message_append_args(
+ m,
+ DBUS_TYPE_STRING, &s->id,
+ DBUS_TYPE_OBJECT_PATH, &p,
+ DBUS_TYPE_INVALID))
+ return -ENOMEM;
+
+ if (!dbus_connection_send(s->manager->bus, m, NULL))
+ return -ENOMEM;
+
+ return 0;
+}
+
+int session_send_changed(Session *s, const char *properties) {
+ _cleanup_dbus_message_unref_ DBusMessage *m = NULL;
+ _cleanup_free_ char *p = NULL;
+
+ assert(s);
+
+ if (!s->started)
+ return 0;
+
+ p = session_bus_path(s);
+ if (!p)
+ return -ENOMEM;
+
+ m = bus_properties_changed_new(p, "org.freedesktop.login1.Session", properties);
+ if (!m)
+ return -ENOMEM;
+
+ if (!dbus_connection_send(s->manager->bus, m, NULL))
+ return -ENOMEM;
+
+ return 0;
+}
+
+int session_send_lock(Session *s, bool lock) {
+ _cleanup_dbus_message_unref_ DBusMessage *m = NULL;
+ bool b;
+ _cleanup_free_ char *p = NULL;
+
+ assert(s);
+
+ p = session_bus_path(s);
+ if (!p)
+ return -ENOMEM;
+
+ m = dbus_message_new_signal(p, "org.freedesktop.login1.Session", lock ? "Lock" : "Unlock");
+
+ if (!m)
+ return -ENOMEM;
+
+ b = dbus_connection_send(s->manager->bus, m, NULL);
+ if (!b)
+ return -ENOMEM;
+
+ return 0;
+}
+
+int session_send_lock_all(Manager *m, bool lock) {
+ Session *session;
+ Iterator i;
+ int r = 0;
+
+ assert(m);
+
+ HASHMAP_FOREACH(session, m->sessions, i) {
+ int k;
+
+ k = session_send_lock(session, lock);
+ if (k < 0)
+ r = k;
+ }
+
+ return r;
+}
diff --git a/src/login/logind-session.c b/src/login/logind-session.c
new file mode 100644
index 0000000000..662273b07f
--- /dev/null
+++ b/src/login/logind-session.c
@@ -0,0 +1,1080 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/epoll.h>
+#include <fcntl.h>
+
+#include "systemd/sd-id128.h"
+#include "systemd/sd-messages.h"
+#include "strv.h"
+#include "util.h"
+#include "mkdir.h"
+#include "path-util.h"
+#include "cgroup-util.h"
+#include "logind-session.h"
+#include "fileio.h"
+
+Session* session_new(Manager *m, User *u, const char *id) {
+ Session *s;
+
+ assert(m);
+ assert(id);
+
+ s = new0(Session, 1);
+ if (!s)
+ return NULL;
+
+ s->state_file = strappend("/run/systemd/sessions/", id);
+ if (!s->state_file) {
+ free(s);
+ return NULL;
+ }
+
+ s->id = path_get_file_name(s->state_file);
+
+ if (hashmap_put(m->sessions, s->id, s) < 0) {
+ free(s->state_file);
+ free(s);
+ return NULL;
+ }
+
+ s->manager = m;
+ s->fifo_fd = -1;
+ s->user = u;
+
+ LIST_PREPEND(Session, sessions_by_user, u->sessions, s);
+
+ return s;
+}
+
+void session_free(Session *s) {
+ assert(s);
+
+ if (s->in_gc_queue)
+ LIST_REMOVE(Session, gc_queue, s->manager->session_gc_queue, s);
+
+ if (s->user) {
+ LIST_REMOVE(Session, sessions_by_user, s->user->sessions, s);
+
+ if (s->user->display == s)
+ s->user->display = NULL;
+ }
+
+ if (s->seat) {
+ if (s->seat->active == s)
+ s->seat->active = NULL;
+
+ LIST_REMOVE(Session, sessions_by_seat, s->seat->sessions, s);
+ }
+
+ if (s->cgroup_path)
+ hashmap_remove(s->manager->session_cgroups, s->cgroup_path);
+
+ free(s->cgroup_path);
+ strv_free(s->controllers);
+
+ free(s->tty);
+ free(s->display);
+ free(s->remote_host);
+ free(s->remote_user);
+ free(s->service);
+
+ hashmap_remove(s->manager->sessions, s->id);
+ session_remove_fifo(s);
+
+ free(s->state_file);
+ free(s);
+}
+
+int session_save(Session *s) {
+ FILE *f;
+ int r = 0;
+ char *temp_path;
+
+ assert(s);
+
+ if (!s->started)
+ return 0;
+
+ r = mkdir_safe_label("/run/systemd/sessions", 0755, 0, 0);
+ if (r < 0)
+ goto finish;
+
+ r = fopen_temporary(s->state_file, &f, &temp_path);
+ if (r < 0)
+ goto finish;
+
+ assert(s->user);
+
+ fchmod(fileno(f), 0644);
+
+ fprintf(f,
+ "# This is private data. Do not parse.\n"
+ "UID=%lu\n"
+ "USER=%s\n"
+ "ACTIVE=%i\n"
+ "STATE=%s\n"
+ "REMOTE=%i\n"
+ "KILL_PROCESSES=%i\n",
+ (unsigned long) s->user->uid,
+ s->user->name,
+ session_is_active(s),
+ session_state_to_string(session_get_state(s)),
+ s->remote,
+ s->kill_processes);
+
+ if (s->type >= 0)
+ fprintf(f,
+ "TYPE=%s\n",
+ session_type_to_string(s->type));
+
+ if (s->class >= 0)
+ fprintf(f,
+ "CLASS=%s\n",
+ session_class_to_string(s->class));
+
+ if (s->cgroup_path)
+ fprintf(f,
+ "CGROUP=%s\n",
+ s->cgroup_path);
+
+ if (s->fifo_path)
+ fprintf(f,
+ "FIFO=%s\n",
+ s->fifo_path);
+
+ if (s->seat)
+ fprintf(f,
+ "SEAT=%s\n",
+ s->seat->id);
+
+ if (s->tty)
+ fprintf(f,
+ "TTY=%s\n",
+ s->tty);
+
+ if (s->display)
+ fprintf(f,
+ "DISPLAY=%s\n",
+ s->display);
+
+ if (s->remote_host)
+ fprintf(f,
+ "REMOTE_HOST=%s\n",
+ s->remote_host);
+
+ if (s->remote_user)
+ fprintf(f,
+ "REMOTE_USER=%s\n",
+ s->remote_user);
+
+ if (s->service)
+ fprintf(f,
+ "SERVICE=%s\n",
+ s->service);
+
+ if (s->seat && seat_can_multi_session(s->seat))
+ fprintf(f,
+ "VTNR=%i\n",
+ s->vtnr);
+
+ if (s->leader > 0)
+ fprintf(f,
+ "LEADER=%lu\n",
+ (unsigned long) s->leader);
+
+ if (s->audit_id > 0)
+ fprintf(f,
+ "AUDIT=%llu\n",
+ (unsigned long long) s->audit_id);
+
+ fflush(f);
+
+ if (ferror(f) || rename(temp_path, s->state_file) < 0) {
+ r = -errno;
+ unlink(s->state_file);
+ unlink(temp_path);
+ }
+
+ fclose(f);
+ free(temp_path);
+
+finish:
+ if (r < 0)
+ log_error("Failed to save session data for %s: %s", s->id, strerror(-r));
+
+ return r;
+}
+
+int session_load(Session *s) {
+ char *remote = NULL,
+ *kill_processes = NULL,
+ *seat = NULL,
+ *vtnr = NULL,
+ *leader = NULL,
+ *audit_id = NULL,
+ *type = NULL,
+ *class = NULL;
+
+ int k, r;
+
+ assert(s);
+
+ r = parse_env_file(s->state_file, NEWLINE,
+ "REMOTE", &remote,
+ "KILL_PROCESSES", &kill_processes,
+ "CGROUP", &s->cgroup_path,
+ "FIFO", &s->fifo_path,
+ "SEAT", &seat,
+ "TTY", &s->tty,
+ "DISPLAY", &s->display,
+ "REMOTE_HOST", &s->remote_host,
+ "REMOTE_USER", &s->remote_user,
+ "SERVICE", &s->service,
+ "VTNR", &vtnr,
+ "LEADER", &leader,
+ "TYPE", &type,
+ "CLASS", &class,
+ NULL);
+
+ if (r < 0)
+ goto finish;
+
+ if (remote) {
+ k = parse_boolean(remote);
+ if (k >= 0)
+ s->remote = k;
+ }
+
+ if (kill_processes) {
+ k = parse_boolean(kill_processes);
+ if (k >= 0)
+ s->kill_processes = k;
+ }
+
+ if (seat && !s->seat) {
+ Seat *o;
+
+ o = hashmap_get(s->manager->seats, seat);
+ if (o)
+ seat_attach_session(o, s);
+ }
+
+ if (vtnr && s->seat && seat_can_multi_session(s->seat)) {
+ int v;
+
+ k = safe_atoi(vtnr, &v);
+ if (k >= 0 && v >= 1)
+ s->vtnr = v;
+ }
+
+ if (leader) {
+ k = parse_pid(leader, &s->leader);
+ if (k >= 0)
+ audit_session_from_pid(s->leader, &s->audit_id);
+ }
+
+ if (type) {
+ SessionType t;
+
+ t = session_type_from_string(type);
+ if (t >= 0)
+ s->type = t;
+ }
+
+ if (class) {
+ SessionClass c;
+
+ c = session_class_from_string(class);
+ if (c >= 0)
+ s->class = c;
+ }
+
+ if (s->fifo_path) {
+ int fd;
+
+ /* If we open an unopened pipe for reading we will not
+ get an EOF. to trigger an EOF we hence open it for
+ reading, but close it right-away which then will
+ trigger the EOF. */
+
+ fd = session_create_fifo(s);
+ if (fd >= 0)
+ close_nointr_nofail(fd);
+ }
+
+finish:
+ free(remote);
+ free(kill_processes);
+ free(seat);
+ free(vtnr);
+ free(leader);
+ free(audit_id);
+ free(class);
+
+ return r;
+}
+
+int session_activate(Session *s) {
+ int r;
+
+ assert(s);
+
+ if (s->vtnr < 0)
+ return -ENOTSUP;
+
+ if (!s->seat)
+ return -ENOTSUP;
+
+ if (s->seat->active == s)
+ return 0;
+
+ assert(seat_is_vtconsole(s->seat));
+
+ r = chvt(s->vtnr);
+ if (r < 0)
+ return r;
+
+ return seat_set_active(s->seat, s);
+}
+
+static int session_link_x11_socket(Session *s) {
+ char *t, *f, *c;
+ size_t k;
+
+ assert(s);
+ assert(s->user);
+ assert(s->user->runtime_path);
+
+ if (s->user->display)
+ return 0;
+
+ if (!s->display || !display_is_local(s->display))
+ return 0;
+
+ k = strspn(s->display+1, "0123456789");
+ f = new(char, sizeof("/tmp/.X11-unix/X") + k);
+ if (!f)
+ return log_oom();
+
+ c = stpcpy(f, "/tmp/.X11-unix/X");
+ memcpy(c, s->display+1, k);
+ c[k] = 0;
+
+ if (access(f, F_OK) < 0) {
+ log_warning("Session %s has display %s with non-existing socket %s.", s->id, s->display, f);
+ free(f);
+ return -ENOENT;
+ }
+
+ /* Note that this cannot be in a subdir to avoid
+ * vulnerabilities since we are privileged but the runtime
+ * path is owned by the user */
+
+ t = strappend(s->user->runtime_path, "/X11-display");
+ if (!t) {
+ free(f);
+ return log_oom();
+ }
+
+ if (link(f, t) < 0) {
+ if (errno == EEXIST) {
+ unlink(t);
+
+ if (link(f, t) >= 0)
+ goto done;
+ }
+
+ if (symlink(f, t) < 0) {
+
+ if (errno == EEXIST) {
+ unlink(t);
+
+ if (symlink(f, t) >= 0)
+ goto done;
+ }
+
+ log_error("Failed to link %s to %s: %m", f, t);
+ free(f);
+ free(t);
+ return -errno;
+ }
+ }
+
+done:
+ log_info("Linked %s to %s.", f, t);
+ free(f);
+ free(t);
+
+ s->user->display = s;
+
+ return 0;
+}
+
+static int session_create_one_group(Session *s, const char *controller, const char *path) {
+ int r;
+
+ assert(s);
+ assert(path);
+
+ if (s->leader > 0) {
+ r = cg_create_and_attach(controller, path, s->leader);
+ if (r < 0)
+ r = cg_create(controller, path, NULL);
+ } else
+ r = cg_create(controller, path, NULL);
+
+ if (r < 0)
+ return r;
+
+ r = cg_set_task_access(controller, path, 0644, s->user->uid, s->user->gid, -1);
+ if (r >= 0)
+ r = cg_set_group_access(controller, path, 0755, s->user->uid, s->user->gid);
+
+ return r;
+}
+
+static int session_create_cgroup(Session *s) {
+ char **k;
+ char *p;
+ int r;
+
+ assert(s);
+ assert(s->user);
+ assert(s->user->cgroup_path);
+
+ if (!s->cgroup_path) {
+ _cleanup_free_ char *name = NULL, *escaped = NULL;
+
+ name = strappend(s->id, ".session");
+ if (!name)
+ return log_oom();
+
+ escaped = cg_escape(name);
+ if (!escaped)
+ return log_oom();
+
+ p = strjoin(s->user->cgroup_path, "/", escaped, NULL);
+ if (!p)
+ return log_oom();
+ } else
+ p = s->cgroup_path;
+
+ r = session_create_one_group(s, SYSTEMD_CGROUP_CONTROLLER, p);
+ if (r < 0) {
+ log_error("Failed to create "SYSTEMD_CGROUP_CONTROLLER":%s: %s", p, strerror(-r));
+ free(p);
+ s->cgroup_path = NULL;
+ return r;
+ }
+
+ s->cgroup_path = p;
+
+ STRV_FOREACH(k, s->controllers) {
+
+ if (strv_contains(s->reset_controllers, *k))
+ continue;
+
+ r = session_create_one_group(s, *k, p);
+ if (r < 0)
+ log_warning("Failed to create %s:%s: %s", *k, p, strerror(-r));
+ }
+
+ STRV_FOREACH(k, s->manager->controllers) {
+
+ if (strv_contains(s->reset_controllers, *k) ||
+ strv_contains(s->manager->reset_controllers, *k) ||
+ strv_contains(s->controllers, *k))
+ continue;
+
+ r = session_create_one_group(s, *k, p);
+ if (r < 0)
+ log_warning("Failed to create %s:%s: %s", *k, p, strerror(-r));
+ }
+
+ if (s->leader > 0) {
+
+ STRV_FOREACH(k, s->reset_controllers) {
+ r = cg_attach(*k, "/", s->leader);
+ if (r < 0)
+ log_warning("Failed to reset controller %s: %s", *k, strerror(-r));
+
+ }
+
+ STRV_FOREACH(k, s->manager->reset_controllers) {
+
+ if (strv_contains(s->reset_controllers, *k) ||
+ strv_contains(s->controllers, *k))
+ continue;
+
+ r = cg_attach(*k, "/", s->leader);
+ if (r < 0)
+ log_warning("Failed to reset controller %s: %s", *k, strerror(-r));
+
+ }
+ }
+
+ r = hashmap_put(s->manager->session_cgroups, s->cgroup_path, s);
+ if (r < 0)
+ log_warning("Failed to create mapping between cgroup and session");
+
+ return 0;
+}
+
+int session_start(Session *s) {
+ int r;
+
+ assert(s);
+ assert(s->user);
+
+ if (s->started)
+ return 0;
+
+ r = user_start(s->user);
+ if (r < 0)
+ return r;
+
+ log_struct(s->type == SESSION_TTY || s->type == SESSION_X11 ? LOG_INFO : LOG_DEBUG,
+ MESSAGE_ID(SD_MESSAGE_SESSION_START),
+ "SESSION_ID=%s", s->id,
+ "USER_ID=%s", s->user->name,
+ "LEADER=%lu", (unsigned long) s->leader,
+ "MESSAGE=New session %s of user %s.", s->id, s->user->name,
+ NULL);
+
+ /* Create cgroup */
+ r = session_create_cgroup(s);
+ if (r < 0)
+ return r;
+
+ /* Create X11 symlink */
+ session_link_x11_socket(s);
+
+ dual_timestamp_get(&s->timestamp);
+
+ if (s->seat)
+ seat_read_active_vt(s->seat);
+
+ s->started = true;
+
+ /* Save session data */
+ session_save(s);
+ user_save(s->user);
+
+ session_send_signal(s, true);
+
+ if (s->seat) {
+ seat_save(s->seat);
+
+ if (s->seat->active == s)
+ seat_send_changed(s->seat, "Sessions\0ActiveSession\0");
+ else
+ seat_send_changed(s->seat, "Sessions\0");
+ }
+
+ user_send_changed(s->user, "Sessions\0");
+
+ return 0;
+}
+
+static bool session_shall_kill(Session *s) {
+ assert(s);
+
+ if (!s->kill_processes)
+ return false;
+
+ if (strv_contains(s->manager->kill_exclude_users, s->user->name))
+ return false;
+
+ if (strv_isempty(s->manager->kill_only_users))
+ return true;
+
+ return strv_contains(s->manager->kill_only_users, s->user->name);
+}
+
+static int session_terminate_cgroup(Session *s) {
+ int r;
+ char **k;
+
+ assert(s);
+
+ if (!s->cgroup_path)
+ return 0;
+
+ cg_trim(SYSTEMD_CGROUP_CONTROLLER, s->cgroup_path, false);
+
+ if (session_shall_kill(s)) {
+
+ r = cg_kill_recursive_and_wait(SYSTEMD_CGROUP_CONTROLLER, s->cgroup_path, true);
+ if (r < 0)
+ log_error("Failed to kill session cgroup: %s", strerror(-r));
+
+ } else {
+ if (s->leader > 0) {
+ Session *t;
+
+ /* We still send a HUP to the leader process,
+ * even if we are not supposed to kill the
+ * whole cgroup. But let's first check the
+ * leader still exists and belongs to our
+ * session... */
+
+ r = manager_get_session_by_pid(s->manager, s->leader, &t);
+ if (r > 0 && t == s) {
+ kill(s->leader, SIGTERM); /* for normal processes */
+ kill(s->leader, SIGHUP); /* for shells */
+ kill(s->leader, SIGCONT); /* in case they are stopped */
+ }
+ }
+
+ r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, s->cgroup_path, true);
+ if (r < 0)
+ log_error("Failed to check session cgroup: %s", strerror(-r));
+ else if (r > 0) {
+ r = cg_delete(SYSTEMD_CGROUP_CONTROLLER, s->cgroup_path);
+ if (r < 0)
+ log_error("Failed to delete session cgroup: %s", strerror(-r));
+ }
+ }
+
+ STRV_FOREACH(k, s->user->manager->controllers)
+ cg_trim(*k, s->cgroup_path, true);
+
+ hashmap_remove(s->manager->session_cgroups, s->cgroup_path);
+
+ free(s->cgroup_path);
+ s->cgroup_path = NULL;
+
+ return 0;
+}
+
+static int session_unlink_x11_socket(Session *s) {
+ char *t;
+ int r;
+
+ assert(s);
+ assert(s->user);
+
+ if (s->user->display != s)
+ return 0;
+
+ s->user->display = NULL;
+
+ t = strappend(s->user->runtime_path, "/X11-display");
+ if (!t)
+ return log_oom();
+
+ r = unlink(t);
+ free(t);
+
+ return r < 0 ? -errno : 0;
+}
+
+int session_stop(Session *s) {
+ int r = 0, k;
+
+ assert(s);
+
+ if (s->started)
+ log_struct(s->type == SESSION_TTY || s->type == SESSION_X11 ? LOG_INFO : LOG_DEBUG,
+ MESSAGE_ID(SD_MESSAGE_SESSION_STOP),
+ "SESSION_ID=%s", s->id,
+ "USER_ID=%s", s->user->name,
+ "LEADER=%lu", (unsigned long) s->leader,
+ "MESSAGE=Removed session %s.", s->id,
+ NULL);
+
+ /* Kill cgroup */
+ k = session_terminate_cgroup(s);
+ if (k < 0)
+ r = k;
+
+ /* Remove X11 symlink */
+ session_unlink_x11_socket(s);
+
+ unlink(s->state_file);
+ session_add_to_gc_queue(s);
+ user_add_to_gc_queue(s->user);
+
+ if (s->started)
+ session_send_signal(s, false);
+
+ s->started = false;
+
+ if (s->seat) {
+ if (s->seat->active == s)
+ seat_set_active(s->seat, NULL);
+
+ seat_send_changed(s->seat, "Sessions\0");
+ seat_save(s->seat);
+ }
+
+ user_send_changed(s->user, "Sessions\0");
+ user_save(s->user);
+
+ return r;
+}
+
+bool session_is_active(Session *s) {
+ assert(s);
+
+ if (!s->seat)
+ return true;
+
+ return s->seat->active == s;
+}
+
+static int get_tty_atime(const char *tty, usec_t *atime) {
+ _cleanup_free_ char *p = NULL;
+ struct stat st;
+
+ assert(tty);
+ assert(atime);
+
+ if (!path_is_absolute(tty)) {
+ p = strappend("/dev/", tty);
+ if (!p)
+ return -ENOMEM;
+
+ tty = p;
+ } else if (!path_startswith(tty, "/dev/"))
+ return -ENOENT;
+
+ if (lstat(tty, &st) < 0)
+ return -errno;
+
+ *atime = timespec_load(&st.st_atim);
+ return 0;
+}
+
+static int get_process_ctty_atime(pid_t pid, usec_t *atime) {
+ _cleanup_free_ char *p = NULL;
+ int r;
+
+ assert(pid > 0);
+ assert(atime);
+
+ r = get_ctty(pid, NULL, &p);
+ if (r < 0)
+ return r;
+
+ return get_tty_atime(p, atime);
+}
+
+int session_get_idle_hint(Session *s, dual_timestamp *t) {
+ usec_t atime = 0, n;
+ int r;
+
+ assert(s);
+
+ /* Explicit idle hint is set */
+ if (s->idle_hint) {
+ if (t)
+ *t = s->idle_hint_timestamp;
+
+ return s->idle_hint;
+ }
+
+ /* Graphical sessions should really implement a real
+ * idle hint logic */
+ if (s->display)
+ goto dont_know;
+
+ /* For sessions with an explicitly configured tty, let's check
+ * its atime */
+ if (s->tty) {
+ r = get_tty_atime(s->tty, &atime);
+ if (r >= 0)
+ goto found_atime;
+ }
+
+ /* For sessions with a leader but no explicitly configured
+ * tty, let's check the controlling tty of the leader */
+ if (s->leader > 0) {
+ r = get_process_ctty_atime(s->leader, &atime);
+ if (r >= 0)
+ goto found_atime;
+ }
+
+ /* For other TTY sessions, let's find the most recent atime of
+ * the ttys of any of the processes of the session */
+ if (s->cgroup_path) {
+ _cleanup_fclose_ FILE *f = NULL;
+
+ if (cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, s->cgroup_path, &f) >= 0) {
+ pid_t pid;
+
+ atime = 0;
+ while (cg_read_pid(f, &pid) > 0) {
+ usec_t a;
+
+ if (get_process_ctty_atime(pid, &a) >= 0)
+ if (atime == 0 || atime < a)
+ atime = a;
+ }
+
+ if (atime != 0)
+ goto found_atime;
+ }
+ }
+
+dont_know:
+ if (t)
+ *t = s->idle_hint_timestamp;
+
+ return 0;
+
+found_atime:
+ if (t)
+ dual_timestamp_from_realtime(t, atime);
+
+ n = now(CLOCK_REALTIME);
+
+ if (s->manager->idle_action_usec <= 0)
+ return 0;
+
+ return atime + s->manager->idle_action_usec <= n;
+}
+
+void session_set_idle_hint(Session *s, bool b) {
+ assert(s);
+
+ if (s->idle_hint == b)
+ return;
+
+ s->idle_hint = b;
+ dual_timestamp_get(&s->idle_hint_timestamp);
+
+ session_send_changed(s,
+ "IdleHint\0"
+ "IdleSinceHint\0"
+ "IdleSinceHintMonotonic\0");
+
+ if (s->seat)
+ seat_send_changed(s->seat,
+ "IdleHint\0"
+ "IdleSinceHint\0"
+ "IdleSinceHintMonotonic\0");
+
+ user_send_changed(s->user,
+ "IdleHint\0"
+ "IdleSinceHint\0"
+ "IdleSinceHintMonotonic\0");
+
+ manager_send_changed(s->manager,
+ "IdleHint\0"
+ "IdleSinceHint\0"
+ "IdleSinceHintMonotonic\0");
+}
+
+int session_create_fifo(Session *s) {
+ int r;
+
+ assert(s);
+
+ /* Create FIFO */
+ if (!s->fifo_path) {
+ r = mkdir_safe_label("/run/systemd/sessions", 0755, 0, 0);
+ if (r < 0)
+ return r;
+
+ if (asprintf(&s->fifo_path, "/run/systemd/sessions/%s.ref", s->id) < 0)
+ return -ENOMEM;
+
+ if (mkfifo(s->fifo_path, 0600) < 0 && errno != EEXIST)
+ return -errno;
+ }
+
+ /* Open reading side */
+ if (s->fifo_fd < 0) {
+ struct epoll_event ev = {};
+
+ s->fifo_fd = open(s->fifo_path, O_RDONLY|O_CLOEXEC|O_NDELAY);
+ if (s->fifo_fd < 0)
+ return -errno;
+
+ r = hashmap_put(s->manager->session_fds, INT_TO_PTR(s->fifo_fd + 1), s);
+ if (r < 0)
+ return r;
+
+ ev.events = 0;
+ ev.data.u32 = FD_OTHER_BASE + s->fifo_fd;
+
+ if (epoll_ctl(s->manager->epoll_fd, EPOLL_CTL_ADD, s->fifo_fd, &ev) < 0)
+ return -errno;
+ }
+
+ /* Open writing side */
+ r = open(s->fifo_path, O_WRONLY|O_CLOEXEC|O_NDELAY);
+ if (r < 0)
+ return -errno;
+
+ return r;
+}
+
+void session_remove_fifo(Session *s) {
+ assert(s);
+
+ if (s->fifo_fd >= 0) {
+ assert_se(hashmap_remove(s->manager->session_fds, INT_TO_PTR(s->fifo_fd + 1)) == s);
+ assert_se(epoll_ctl(s->manager->epoll_fd, EPOLL_CTL_DEL, s->fifo_fd, NULL) == 0);
+ close_nointr_nofail(s->fifo_fd);
+ s->fifo_fd = -1;
+
+ session_save(s);
+ user_save(s->user);
+ }
+
+ if (s->fifo_path) {
+ unlink(s->fifo_path);
+ free(s->fifo_path);
+ s->fifo_path = NULL;
+ }
+}
+
+int session_check_gc(Session *s, bool drop_not_started) {
+ int r;
+
+ assert(s);
+
+ if (drop_not_started && !s->started)
+ return 0;
+
+ if (s->fifo_fd >= 0) {
+
+ r = pipe_eof(s->fifo_fd);
+ if (r < 0)
+ return r;
+
+ if (r == 0)
+ return 1;
+ }
+
+ if (s->cgroup_path) {
+
+ r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, s->cgroup_path, false);
+ if (r < 0)
+ return r;
+
+ if (r <= 0)
+ return 1;
+ }
+
+ return 0;
+}
+
+void session_add_to_gc_queue(Session *s) {
+ assert(s);
+
+ if (s->in_gc_queue)
+ return;
+
+ LIST_PREPEND(Session, gc_queue, s->manager->session_gc_queue, s);
+ s->in_gc_queue = true;
+}
+
+SessionState session_get_state(Session *s) {
+ assert(s);
+
+ if (s->fifo_fd < 0)
+ return SESSION_CLOSING;
+
+ if (session_is_active(s))
+ return SESSION_ACTIVE;
+
+ return SESSION_ONLINE;
+}
+
+int session_kill(Session *s, KillWho who, int signo) {
+ int r = 0;
+ Set *pid_set = NULL;
+
+ assert(s);
+
+ if (!s->cgroup_path)
+ return -ESRCH;
+
+ if (s->leader <= 0 && who == KILL_LEADER)
+ return -ESRCH;
+
+ if (s->leader > 0)
+ if (kill(s->leader, signo) < 0)
+ r = -errno;
+
+ if (who == KILL_ALL) {
+ int q;
+
+ pid_set = set_new(trivial_hash_func, trivial_compare_func);
+ if (!pid_set)
+ return -ENOMEM;
+
+ if (s->leader > 0) {
+ q = set_put(pid_set, LONG_TO_PTR(s->leader));
+ if (q < 0)
+ r = q;
+ }
+
+ q = cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, s->cgroup_path, signo, false, true, false, pid_set);
+ if (q < 0)
+ if (q != -EAGAIN && q != -ESRCH && q != -ENOENT)
+ r = q;
+ }
+
+ if (pid_set)
+ set_free(pid_set);
+
+ return r;
+}
+
+static const char* const session_state_table[_SESSION_TYPE_MAX] = {
+ [SESSION_ONLINE] = "online",
+ [SESSION_ACTIVE] = "active",
+ [SESSION_CLOSING] = "closing"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(session_state, SessionState);
+
+static const char* const session_type_table[_SESSION_TYPE_MAX] = {
+ [SESSION_TTY] = "tty",
+ [SESSION_X11] = "x11",
+ [SESSION_UNSPECIFIED] = "unspecified"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(session_type, SessionType);
+
+static const char* const session_class_table[_SESSION_CLASS_MAX] = {
+ [SESSION_USER] = "user",
+ [SESSION_GREETER] = "greeter",
+ [SESSION_LOCK_SCREEN] = "lock-screen",
+ [SESSION_BACKGROUND] = "background"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(session_class, SessionClass);
+
+static const char* const kill_who_table[_KILL_WHO_MAX] = {
+ [KILL_LEADER] = "leader",
+ [KILL_ALL] = "all"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(kill_who, KillWho);
diff --git a/src/login/logind-session.h b/src/login/logind-session.h
new file mode 100644
index 0000000000..a73df3a3bc
--- /dev/null
+++ b/src/login/logind-session.h
@@ -0,0 +1,148 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+typedef struct Session Session;
+
+#include "list.h"
+#include "util.h"
+#include "logind.h"
+#include "logind-seat.h"
+#include "logind-user.h"
+
+typedef enum SessionState {
+ SESSION_ONLINE, /* Logged in */
+ SESSION_ACTIVE, /* Logged in and in the fg */
+ SESSION_CLOSING, /* Logged out, but processes still remain */
+ _SESSION_STATE_MAX,
+ _SESSION_STATE_INVALID = -1
+} SessionState;
+
+typedef enum SessionClass {
+ SESSION_USER,
+ SESSION_GREETER,
+ SESSION_LOCK_SCREEN,
+ SESSION_BACKGROUND,
+ _SESSION_CLASS_MAX,
+ _SESSION_CLASS_INVALID = -1
+} SessionClass;
+
+typedef enum SessionType {
+ SESSION_UNSPECIFIED,
+ SESSION_TTY,
+ SESSION_X11,
+ _SESSION_TYPE_MAX,
+ _SESSION_TYPE_INVALID = -1
+} SessionType;
+
+typedef enum KillWho {
+ KILL_LEADER,
+ KILL_ALL,
+ _KILL_WHO_MAX,
+ _KILL_WHO_INVALID = -1
+} KillWho;
+
+struct Session {
+ Manager *manager;
+
+ char *id;
+ SessionType type;
+ SessionClass class;
+
+ char *state_file;
+
+ User *user;
+
+ dual_timestamp timestamp;
+
+ char *tty;
+ char *display;
+
+ bool remote;
+ char *remote_user;
+ char *remote_host;
+
+ char *service;
+
+ int vtnr;
+ Seat *seat;
+
+ pid_t leader;
+ uint32_t audit_id;
+
+ int fifo_fd;
+ char *fifo_path;
+
+ char *cgroup_path;
+ char **controllers, **reset_controllers;
+
+ bool idle_hint;
+ dual_timestamp idle_hint_timestamp;
+
+ bool kill_processes;
+ bool in_gc_queue:1;
+ bool started:1;
+
+ LIST_FIELDS(Session, sessions_by_user);
+ LIST_FIELDS(Session, sessions_by_seat);
+
+ LIST_FIELDS(Session, gc_queue);
+};
+
+Session *session_new(Manager *m, User *u, const char *id);
+void session_free(Session *s);
+int session_check_gc(Session *s, bool drop_not_started);
+void session_add_to_gc_queue(Session *s);
+int session_activate(Session *s);
+bool session_is_active(Session *s);
+int session_get_idle_hint(Session *s, dual_timestamp *t);
+void session_set_idle_hint(Session *s, bool b);
+int session_create_fifo(Session *s);
+void session_remove_fifo(Session *s);
+int session_start(Session *s);
+int session_stop(Session *s);
+int session_save(Session *s);
+int session_load(Session *s);
+int session_kill(Session *s, KillWho who, int signo);
+
+char *session_bus_path(Session *s);
+
+SessionState session_get_state(Session *u);
+
+extern const DBusObjectPathVTable bus_session_vtable;
+
+int session_send_signal(Session *s, bool new_session);
+int session_send_changed(Session *s, const char *properties);
+int session_send_lock(Session *s, bool lock);
+int session_send_lock_all(Manager *m, bool lock);
+
+const char* session_state_to_string(SessionState t) _const_;
+SessionState session_state_from_string(const char *s) _pure_;
+
+const char* session_type_to_string(SessionType t) _const_;
+SessionType session_type_from_string(const char *s) _pure_;
+
+const char* session_class_to_string(SessionClass t) _const_;
+SessionClass session_class_from_string(const char *s) _pure_;
+
+const char *kill_who_to_string(KillWho k) _const_;
+KillWho kill_who_from_string(const char *s) _pure_;
diff --git a/src/login/logind-user-dbus.c b/src/login/logind-user-dbus.c
new file mode 100644
index 0000000000..3ec3ff8e61
--- /dev/null
+++ b/src/login/logind-user-dbus.c
@@ -0,0 +1,411 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <string.h>
+
+#include "logind.h"
+#include "logind-user.h"
+#include "dbus-common.h"
+
+#define BUS_USER_INTERFACE \
+ " <interface name=\"org.freedesktop.login1.User\">\n" \
+ " <method name=\"Terminate\"/>\n" \
+ " <method name=\"Kill\">\n" \
+ " <arg name=\"signal\" type=\"s\"/>\n" \
+ " </method>\n" \
+ " <property name=\"UID\" type=\"u\" access=\"read\"/>\n" \
+ " <property name=\"GID\" type=\"u\" access=\"read\"/>\n" \
+ " <property name=\"Name\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"Timestamp\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"TimestampMonotonic\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"RuntimePath\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"DefaultControlGroup\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"Service\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"Display\" type=\"(so)\" access=\"read\"/>\n" \
+ " <property name=\"State\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"Sessions\" type=\"a(so)\" access=\"read\"/>\n" \
+ " <property name=\"IdleHint\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"IdleSinceHint\" type=\"t\" access=\"read\"/>\n" \
+ " <property name=\"IdleSinceHintMonotonic\" type=\"t\" access=\"read\"/>\n" \
+ " </interface>\n" \
+
+#define INTROSPECTION \
+ DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE \
+ "<node>\n" \
+ BUS_USER_INTERFACE \
+ BUS_PROPERTIES_INTERFACE \
+ BUS_PEER_INTERFACE \
+ BUS_INTROSPECTABLE_INTERFACE \
+ "</node>\n"
+
+#define INTERFACES_LIST \
+ BUS_GENERIC_INTERFACES_LIST \
+ "org.freedesktop.login1.User\0"
+
+static int bus_user_append_display(DBusMessageIter *i, const char *property, void *data) {
+ DBusMessageIter sub;
+ User *u = data;
+ const char *id, *path;
+ _cleanup_free_ char *p = NULL;
+
+ assert(i);
+ assert(property);
+ assert(u);
+
+ if (!dbus_message_iter_open_container(i, DBUS_TYPE_STRUCT, NULL, &sub))
+ return -ENOMEM;
+
+ if (u->display) {
+ id = u->display->id;
+ path = p = session_bus_path(u->display);
+
+ if (!p)
+ return -ENOMEM;
+ } else {
+ id = "";
+ path = "/";
+ }
+
+ if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &id) ||
+ !dbus_message_iter_append_basic(&sub, DBUS_TYPE_OBJECT_PATH, &path))
+ return -ENOMEM;
+
+ if (!dbus_message_iter_close_container(i, &sub))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_user_append_state(DBusMessageIter *i, const char *property, void *data) {
+ User *u = data;
+ const char *state;
+
+ assert(i);
+ assert(property);
+ assert(u);
+
+ state = user_state_to_string(user_get_state(u));
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_STRING, &state))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_user_append_sessions(DBusMessageIter *i, const char *property, void *data) {
+ DBusMessageIter sub, sub2;
+ User *u = data;
+ Session *session;
+
+ assert(i);
+ assert(property);
+ assert(u);
+
+ if (!dbus_message_iter_open_container(i, DBUS_TYPE_ARRAY, "(so)", &sub))
+ return -ENOMEM;
+
+ LIST_FOREACH(sessions_by_user, session, u->sessions) {
+ char *p;
+
+ if (!dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, NULL, &sub2))
+ return -ENOMEM;
+
+ p = session_bus_path(session);
+ if (!p)
+ return -ENOMEM;
+
+ if (!dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &session->id) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_OBJECT_PATH, &p)) {
+ free(p);
+ return -ENOMEM;
+ }
+
+ free(p);
+
+ if (!dbus_message_iter_close_container(&sub, &sub2))
+ return -ENOMEM;
+ }
+
+ if (!dbus_message_iter_close_container(i, &sub))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_user_append_idle_hint(DBusMessageIter *i, const char *property, void *data) {
+ User *u = data;
+ dbus_bool_t b;
+
+ assert(i);
+ assert(property);
+ assert(u);
+
+ b = user_get_idle_hint(u, NULL) > 0;
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_BOOLEAN, &b))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_user_append_idle_hint_since(DBusMessageIter *i, const char *property, void *data) {
+ User *u = data;
+ dual_timestamp t;
+ uint64_t k;
+
+ assert(i);
+ assert(property);
+ assert(u);
+
+ user_get_idle_hint(u, &t);
+ k = streq(property, "IdleSinceHint") ? t.realtime : t.monotonic;
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT64, &k))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int bus_user_append_default_cgroup(DBusMessageIter *i, const char *property, void *data) {
+ User *u = data;
+ _cleanup_free_ char *t = NULL;
+ int r;
+ bool success;
+
+ assert(i);
+ assert(property);
+ assert(u);
+
+ r = cg_join_spec(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, &t);
+ if (r < 0)
+ return r;
+
+ success = dbus_message_iter_append_basic(i, DBUS_TYPE_STRING, &t);
+ return success ? 0 : -ENOMEM;
+}
+
+static int get_user_for_path(Manager *m, const char *path, User **_u) {
+ User *u;
+ unsigned long lu;
+ int r;
+
+ assert(m);
+ assert(path);
+ assert(_u);
+
+ if (!startswith(path, "/org/freedesktop/login1/user/"))
+ return -EINVAL;
+
+ r = safe_atolu(path + 29, &lu);
+ if (r < 0)
+ return r;
+
+ u = hashmap_get(m->users, ULONG_TO_PTR(lu));
+ if (!u)
+ return -ENOENT;
+
+ *_u = u;
+ return 0;
+}
+
+static const BusProperty bus_login_user_properties[] = {
+ { "UID", bus_property_append_uid, "u", offsetof(User, uid) },
+ { "GID", bus_property_append_gid, "u", offsetof(User, gid) },
+ { "Name", bus_property_append_string, "s", offsetof(User, name), true },
+ { "Timestamp", bus_property_append_usec, "t", offsetof(User, timestamp.realtime) },
+ { "TimestampMonotonic", bus_property_append_usec, "t", offsetof(User, timestamp.monotonic) },
+ { "RuntimePath", bus_property_append_string, "s", offsetof(User, runtime_path), true },
+ { "DefaultControlGroup", bus_user_append_default_cgroup, "s", 0 },
+ { "Service", bus_property_append_string, "s", offsetof(User, service), true },
+ { "Display", bus_user_append_display, "(so)", 0 },
+ { "State", bus_user_append_state, "s", 0 },
+ { "Sessions", bus_user_append_sessions, "a(so)", 0 },
+ { "IdleHint", bus_user_append_idle_hint, "b", 0 },
+ { "IdleSinceHint", bus_user_append_idle_hint_since, "t", 0 },
+ { "IdleSinceHintMonotonic", bus_user_append_idle_hint_since, "t", 0 },
+ { NULL, }
+};
+
+static DBusHandlerResult user_message_dispatch(
+ User *u,
+ DBusConnection *connection,
+ DBusMessage *message) {
+
+ DBusError error;
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ int r;
+
+ assert(u);
+ assert(connection);
+ assert(message);
+
+ if (dbus_message_is_method_call(message, "org.freedesktop.login1.User", "Terminate")) {
+
+ r = user_stop(u);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.login1.User", "Kill")) {
+ int32_t signo;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_INT32, &signo,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ if (signo <= 0 || signo >= _NSIG)
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ r = user_kill(u, signo);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, NULL, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ } else {
+ const BusBoundProperties bps[] = {
+ { "org.freedesktop.login1.User", bus_login_user_properties, u },
+ { NULL, }
+ };
+
+ return bus_default_message_handler(connection, message, INTROSPECTION, INTERFACES_LIST, bps);
+ }
+
+ if (reply) {
+ if (!bus_maybe_send_reply(connection, message, reply))
+ goto oom;
+ }
+
+ return DBUS_HANDLER_RESULT_HANDLED;
+
+oom:
+ dbus_error_free(&error);
+
+ return DBUS_HANDLER_RESULT_NEED_MEMORY;
+}
+
+static DBusHandlerResult user_message_handler(
+ DBusConnection *connection,
+ DBusMessage *message,
+ void *userdata) {
+
+ Manager *m = userdata;
+ User *u;
+ int r;
+
+ r = get_user_for_path(m, dbus_message_get_path(message), &u);
+ if (r < 0) {
+
+ if (r == -ENOMEM)
+ return DBUS_HANDLER_RESULT_NEED_MEMORY;
+
+ if (r == -ENOENT) {
+ DBusError e;
+
+ dbus_error_init(&e);
+ dbus_set_error_const(&e, DBUS_ERROR_UNKNOWN_OBJECT, "Unknown user");
+ return bus_send_error_reply(connection, message, &e, r);
+ }
+
+ return bus_send_error_reply(connection, message, NULL, r);
+ }
+
+ return user_message_dispatch(u, connection, message);
+}
+
+const DBusObjectPathVTable bus_user_vtable = {
+ .message_function = user_message_handler
+};
+
+char *user_bus_path(User *u) {
+ char *s;
+
+ assert(u);
+
+ if (asprintf(&s, "/org/freedesktop/login1/user/%llu", (unsigned long long) u->uid) < 0)
+ return NULL;
+
+ return s;
+}
+
+int user_send_signal(User *u, bool new_user) {
+ _cleanup_dbus_message_unref_ DBusMessage *m = NULL;
+ _cleanup_free_ char *p = NULL;
+ uint32_t uid;
+
+ assert(u);
+
+ m = dbus_message_new_signal("/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ new_user ? "UserNew" : "UserRemoved");
+
+ if (!m)
+ return -ENOMEM;
+
+ p = user_bus_path(u);
+ if (!p)
+ return -ENOMEM;
+
+ uid = u->uid;
+
+ if (!dbus_message_append_args(
+ m,
+ DBUS_TYPE_UINT32, &uid,
+ DBUS_TYPE_OBJECT_PATH, &p,
+ DBUS_TYPE_INVALID))
+ return -ENOMEM;
+
+ if (!dbus_connection_send(u->manager->bus, m, NULL))
+ return -ENOMEM;
+
+ return 0;
+}
+
+int user_send_changed(User *u, const char *properties) {
+ _cleanup_dbus_message_unref_ DBusMessage *m = NULL;
+ _cleanup_free_ char *p = NULL;
+
+ assert(u);
+
+ if (!u->started)
+ return 0;
+
+ p = user_bus_path(u);
+ if (!p)
+ return -ENOMEM;
+
+ m = bus_properties_changed_new(p, "org.freedesktop.login1.User", properties);
+ if (!m)
+ return -ENOMEM;
+
+ if (!dbus_connection_send(u->manager->bus, m, NULL))
+ return -ENOMEM;
+
+ return 0;
+}
diff --git a/src/login/logind-user.c b/src/login/logind-user.c
new file mode 100644
index 0000000000..9e2cbf646b
--- /dev/null
+++ b/src/login/logind-user.c
@@ -0,0 +1,667 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+
+#include "logind-user.h"
+#include "util.h"
+#include "mkdir.h"
+#include "cgroup-util.h"
+#include "hashmap.h"
+#include "strv.h"
+#include "fileio.h"
+
+User* user_new(Manager *m, uid_t uid, gid_t gid, const char *name) {
+ User *u;
+
+ assert(m);
+ assert(name);
+
+ u = new0(User, 1);
+ if (!u)
+ return NULL;
+
+ u->name = strdup(name);
+ if (!u->name) {
+ free(u);
+ return NULL;
+ }
+
+ if (asprintf(&u->state_file, "/run/systemd/users/%lu", (unsigned long) uid) < 0) {
+ free(u->name);
+ free(u);
+ return NULL;
+ }
+
+ if (hashmap_put(m->users, ULONG_TO_PTR((unsigned long) uid), u) < 0) {
+ free(u->state_file);
+ free(u->name);
+ free(u);
+ return NULL;
+ }
+
+ u->manager = m;
+ u->uid = uid;
+ u->gid = gid;
+
+ return u;
+}
+
+void user_free(User *u) {
+ assert(u);
+
+ if (u->in_gc_queue)
+ LIST_REMOVE(User, gc_queue, u->manager->user_gc_queue, u);
+
+ while (u->sessions)
+ session_free(u->sessions);
+
+ if (u->cgroup_path)
+ hashmap_remove(u->manager->user_cgroups, u->cgroup_path);
+ free(u->cgroup_path);
+
+ free(u->service);
+ free(u->runtime_path);
+
+ hashmap_remove(u->manager->users, ULONG_TO_PTR((unsigned long) u->uid));
+
+ free(u->name);
+ free(u->state_file);
+ free(u);
+}
+
+int user_save(User *u) {
+ FILE *f;
+ int r;
+ char *temp_path;
+
+ assert(u);
+ assert(u->state_file);
+
+ if (!u->started)
+ return 0;
+
+ r = mkdir_safe_label("/run/systemd/users", 0755, 0, 0);
+ if (r < 0)
+ goto finish;
+
+ r = fopen_temporary(u->state_file, &f, &temp_path);
+ if (r < 0)
+ goto finish;
+
+ fchmod(fileno(f), 0644);
+
+ fprintf(f,
+ "# This is private data. Do not parse.\n"
+ "NAME=%s\n"
+ "STATE=%s\n",
+ u->name,
+ user_state_to_string(user_get_state(u)));
+
+ if (u->cgroup_path)
+ fprintf(f,
+ "CGROUP=%s\n",
+ u->cgroup_path);
+
+ if (u->runtime_path)
+ fprintf(f,
+ "RUNTIME=%s\n",
+ u->runtime_path);
+
+ if (u->service)
+ fprintf(f,
+ "SERVICE=%s\n",
+ u->service);
+
+ if (u->display)
+ fprintf(f,
+ "DISPLAY=%s\n",
+ u->display->id);
+
+ if (u->sessions) {
+ Session *i;
+ bool first;
+
+ fputs("SESSIONS=", f);
+ first = true;
+ LIST_FOREACH(sessions_by_user, i, u->sessions) {
+ if (first)
+ first = false;
+ else
+ fputc(' ', f);
+
+ fputs(i->id, f);
+ }
+
+ fputs("\nSEATS=", f);
+ first = true;
+ LIST_FOREACH(sessions_by_user, i, u->sessions) {
+ if (!i->seat)
+ continue;
+
+ if (first)
+ first = false;
+ else
+ fputc(' ', f);
+
+ fputs(i->seat->id, f);
+ }
+
+ fputs("\nACTIVE_SESSIONS=", f);
+ first = true;
+ LIST_FOREACH(sessions_by_user, i, u->sessions) {
+ if (!session_is_active(i))
+ continue;
+
+ if (first)
+ first = false;
+ else
+ fputc(' ', f);
+
+ fputs(i->id, f);
+ }
+
+ fputs("\nONLINE_SESSIONS=", f);
+ first = true;
+ LIST_FOREACH(sessions_by_user, i, u->sessions) {
+ if (session_get_state(i) == SESSION_CLOSING)
+ continue;
+
+ if (first)
+ first = false;
+ else
+ fputc(' ', f);
+
+ fputs(i->id, f);
+ }
+
+ fputs("\nACTIVE_SEATS=", f);
+ first = true;
+ LIST_FOREACH(sessions_by_user, i, u->sessions) {
+ if (!session_is_active(i) || !i->seat)
+ continue;
+
+ if (first)
+ first = false;
+ else
+ fputc(' ', f);
+
+ fputs(i->seat->id, f);
+ }
+
+ fputs("\nONLINE_SEATS=", f);
+ first = true;
+ LIST_FOREACH(sessions_by_user, i, u->sessions) {
+ if (session_get_state(i) == SESSION_CLOSING || !i->seat)
+ continue;
+
+ if (first)
+ first = false;
+ else
+ fputc(' ', f);
+
+ fputs(i->seat->id, f);
+ }
+ fputc('\n', f);
+ }
+
+ fflush(f);
+
+ if (ferror(f) || rename(temp_path, u->state_file) < 0) {
+ r = -errno;
+ unlink(u->state_file);
+ unlink(temp_path);
+ }
+
+ fclose(f);
+ free(temp_path);
+
+finish:
+ if (r < 0)
+ log_error("Failed to save user data for %s: %s", u->name, strerror(-r));
+
+ return r;
+}
+
+int user_load(User *u) {
+ int r;
+ char *display = NULL;
+ Session *s = NULL;
+
+ assert(u);
+
+ r = parse_env_file(u->state_file, NEWLINE,
+ "CGROUP", &u->cgroup_path,
+ "RUNTIME", &u->runtime_path,
+ "SERVICE", &u->service,
+ "DISPLAY", &display,
+ NULL);
+ if (r < 0) {
+ free(display);
+
+ if (r == -ENOENT)
+ return 0;
+
+ log_error("Failed to read %s: %s", u->state_file, strerror(-r));
+ return r;
+ }
+
+ if (display) {
+ s = hashmap_get(u->manager->sessions, display);
+ free(display);
+ }
+
+ if (s && s->display && display_is_local(s->display))
+ u->display = s;
+
+ return r;
+}
+
+static int user_mkdir_runtime_path(User *u) {
+ char *p;
+ int r;
+
+ assert(u);
+
+ r = mkdir_safe_label("/run/user", 0755, 0, 0);
+ if (r < 0) {
+ log_error("Failed to create /run/user: %s", strerror(-r));
+ return r;
+ }
+
+ if (!u->runtime_path) {
+ if (asprintf(&p, "/run/user/%lu", (unsigned long) u->uid) < 0)
+ return log_oom();
+ } else
+ p = u->runtime_path;
+
+ r = mkdir_safe_label(p, 0700, u->uid, u->gid);
+ if (r < 0) {
+ log_error("Failed to create runtime directory %s: %s", p, strerror(-r));
+ free(p);
+ u->runtime_path = NULL;
+ return r;
+ }
+
+ u->runtime_path = p;
+ return 0;
+}
+
+static int user_create_cgroup(User *u) {
+ char **k;
+ char *p;
+ int r;
+
+ assert(u);
+
+ if (!u->cgroup_path) {
+ _cleanup_free_ char *name = NULL, *escaped = NULL;
+
+ if (asprintf(&name, "%lu.user", (unsigned long) u->uid) < 0)
+ return log_oom();
+
+ escaped = cg_escape(name);
+ if (!escaped)
+ return log_oom();
+
+ p = strjoin(u->manager->cgroup_path, "/", escaped, NULL);
+ if (!p)
+ return log_oom();
+ } else
+ p = u->cgroup_path;
+
+ r = cg_create(SYSTEMD_CGROUP_CONTROLLER, p, NULL);
+ if (r < 0) {
+ log_error("Failed to create cgroup "SYSTEMD_CGROUP_CONTROLLER":%s: %s", p, strerror(-r));
+ free(p);
+ u->cgroup_path = NULL;
+ return r;
+ }
+
+ u->cgroup_path = p;
+
+ STRV_FOREACH(k, u->manager->controllers) {
+
+ if (strv_contains(u->manager->reset_controllers, *k))
+ continue;
+
+ r = cg_create(*k, p, NULL);
+ if (r < 0)
+ log_warning("Failed to create cgroup %s:%s: %s", *k, p, strerror(-r));
+ }
+
+ r = hashmap_put(u->manager->user_cgroups, u->cgroup_path, u);
+ if (r < 0)
+ log_warning("Failed to create mapping between cgroup and user");
+
+ return 0;
+}
+
+static int user_start_service(User *u) {
+ assert(u);
+
+ /* FIXME: Fill me in later ... */
+
+ return 0;
+}
+
+int user_start(User *u) {
+ int r;
+
+ assert(u);
+
+ if (u->started)
+ return 0;
+
+ log_debug("New user %s logged in.", u->name);
+
+ /* Make XDG_RUNTIME_DIR */
+ r = user_mkdir_runtime_path(u);
+ if (r < 0)
+ return r;
+
+ /* Create cgroup */
+ r = user_create_cgroup(u);
+ if (r < 0)
+ return r;
+
+ /* Spawn user systemd */
+ r = user_start_service(u);
+ if (r < 0)
+ return r;
+
+ dual_timestamp_get(&u->timestamp);
+
+ u->started = true;
+
+ /* Save new user data */
+ user_save(u);
+
+ user_send_signal(u, true);
+
+ return 0;
+}
+
+static int user_stop_service(User *u) {
+ assert(u);
+
+ if (!u->service)
+ return 0;
+
+ return 0;
+}
+
+static int user_shall_kill(User *u) {
+ assert(u);
+
+ if (!u->manager->kill_user_processes)
+ return false;
+
+ if (strv_contains(u->manager->kill_exclude_users, u->name))
+ return false;
+
+ if (strv_isempty(u->manager->kill_only_users))
+ return true;
+
+ return strv_contains(u->manager->kill_only_users, u->name);
+}
+
+static int user_terminate_cgroup(User *u) {
+ int r;
+ char **k;
+
+ assert(u);
+
+ if (!u->cgroup_path)
+ return 0;
+
+ cg_trim(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, false);
+
+ if (user_shall_kill(u)) {
+
+ r = cg_kill_recursive_and_wait(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, true);
+ if (r < 0)
+ log_error("Failed to kill user cgroup: %s", strerror(-r));
+ } else {
+
+ r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, true);
+ if (r < 0)
+ log_error("Failed to check user cgroup: %s", strerror(-r));
+ else if (r > 0) {
+ r = cg_delete(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path);
+ if (r < 0)
+ log_error("Failed to delete user cgroup: %s", strerror(-r));
+ } else
+ r = -EBUSY;
+ }
+
+ STRV_FOREACH(k, u->manager->controllers)
+ cg_trim(*k, u->cgroup_path, true);
+
+ hashmap_remove(u->manager->user_cgroups, u->cgroup_path);
+
+ free(u->cgroup_path);
+ u->cgroup_path = NULL;
+
+ return r;
+}
+
+static int user_remove_runtime_path(User *u) {
+ int r;
+
+ assert(u);
+
+ if (!u->runtime_path)
+ return 0;
+
+ r = rm_rf(u->runtime_path, false, true, false);
+ if (r < 0)
+ log_error("Failed to remove runtime directory %s: %s", u->runtime_path, strerror(-r));
+
+ free(u->runtime_path);
+ u->runtime_path = NULL;
+
+ return r;
+}
+
+int user_stop(User *u) {
+ Session *s;
+ int r = 0, k;
+ assert(u);
+
+ if (u->started)
+ log_debug("User %s logged out.", u->name);
+
+ LIST_FOREACH(sessions_by_user, s, u->sessions) {
+ k = session_stop(s);
+ if (k < 0)
+ r = k;
+ }
+
+ /* Kill systemd */
+ k = user_stop_service(u);
+ if (k < 0)
+ r = k;
+
+ /* Kill cgroup */
+ k = user_terminate_cgroup(u);
+ if (k < 0)
+ r = k;
+
+ /* Kill XDG_RUNTIME_DIR */
+ k = user_remove_runtime_path(u);
+ if (k < 0)
+ r = k;
+
+ unlink(u->state_file);
+ user_add_to_gc_queue(u);
+
+ if (u->started)
+ user_send_signal(u, false);
+
+ u->started = false;
+
+ return r;
+}
+
+int user_get_idle_hint(User *u, dual_timestamp *t) {
+ Session *s;
+ bool idle_hint = true;
+ dual_timestamp ts = { 0, 0 };
+
+ assert(u);
+
+ LIST_FOREACH(sessions_by_user, s, u->sessions) {
+ dual_timestamp k;
+ int ih;
+
+ ih = session_get_idle_hint(s, &k);
+ if (ih < 0)
+ return ih;
+
+ if (!ih) {
+ if (!idle_hint) {
+ if (k.monotonic < ts.monotonic)
+ ts = k;
+ } else {
+ idle_hint = false;
+ ts = k;
+ }
+ } else if (idle_hint) {
+
+ if (k.monotonic > ts.monotonic)
+ ts = k;
+ }
+ }
+
+ if (t)
+ *t = ts;
+
+ return idle_hint;
+}
+
+static int user_check_linger_file(User *u) {
+ char *p;
+ int r;
+
+ if (asprintf(&p, "/var/lib/systemd/linger/%s", u->name) < 0)
+ return -ENOMEM;
+
+ r = access(p, F_OK) >= 0;
+ free(p);
+
+ return r;
+}
+
+int user_check_gc(User *u, bool drop_not_started) {
+ int r;
+
+ assert(u);
+
+ if (drop_not_started && !u->started)
+ return 0;
+
+ if (u->sessions)
+ return 1;
+
+ if (user_check_linger_file(u) > 0)
+ return 1;
+
+ if (u->cgroup_path) {
+ r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, false);
+ if (r < 0)
+ return r;
+
+ if (r <= 0)
+ return 1;
+ }
+
+ return 0;
+}
+
+void user_add_to_gc_queue(User *u) {
+ assert(u);
+
+ if (u->in_gc_queue)
+ return;
+
+ LIST_PREPEND(User, gc_queue, u->manager->user_gc_queue, u);
+ u->in_gc_queue = true;
+}
+
+UserState user_get_state(User *u) {
+ Session *i;
+ bool all_closing = true;
+
+ assert(u);
+
+
+ LIST_FOREACH(sessions_by_user, i, u->sessions) {
+ if (session_is_active(i))
+ return USER_ACTIVE;
+ if (session_get_state(i) != SESSION_CLOSING)
+ all_closing = false;
+ }
+
+ if (u->sessions)
+ return all_closing ? USER_CLOSING : USER_ONLINE;
+
+ if (user_check_linger_file(u) > 0)
+ return USER_LINGERING;
+
+ return USER_CLOSING;
+}
+
+int user_kill(User *u, int signo) {
+ int r = 0, q;
+ Set *pid_set = NULL;
+
+ assert(u);
+
+ if (!u->cgroup_path)
+ return -ESRCH;
+
+ pid_set = set_new(trivial_hash_func, trivial_compare_func);
+ if (!pid_set)
+ return -ENOMEM;
+
+ q = cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, signo, false, true, false, pid_set);
+ if (q < 0)
+ if (q != -EAGAIN && q != -ESRCH && q != -ENOENT)
+ r = q;
+
+ if (pid_set)
+ set_free(pid_set);
+
+ return r;
+}
+
+static const char* const user_state_table[_USER_STATE_MAX] = {
+ [USER_OFFLINE] = "offline",
+ [USER_LINGERING] = "lingering",
+ [USER_ONLINE] = "online",
+ [USER_ACTIVE] = "active",
+ [USER_CLOSING] = "closing"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(user_state, UserState);
diff --git a/src/login/logind-user.h b/src/login/logind-user.h
new file mode 100644
index 0000000000..080354da74
--- /dev/null
+++ b/src/login/logind-user.h
@@ -0,0 +1,84 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+typedef struct User User;
+
+#include "list.h"
+#include "util.h"
+#include "logind.h"
+#include "logind-session.h"
+
+typedef enum UserState {
+ USER_OFFLINE, /* Not logged in at all */
+ USER_LINGERING, /* Lingering has been enabled by the admin for this user */
+ USER_ONLINE, /* User logged in */
+ USER_ACTIVE, /* User logged in and has a session in the fg */
+ USER_CLOSING, /* User logged out, but processes still remain and lingering is not enabled */
+ _USER_STATE_MAX,
+ _USER_STATE_INVALID = -1
+} UserState;
+
+struct User {
+ Manager *manager;
+
+ uid_t uid;
+ gid_t gid;
+ char *name;
+
+ char *state_file;
+ char *runtime_path;
+ char *service;
+ char *cgroup_path;
+
+ Session *display;
+
+ dual_timestamp timestamp;
+
+ bool in_gc_queue:1;
+ bool started:1;
+
+ LIST_HEAD(Session, sessions);
+ LIST_FIELDS(User, gc_queue);
+};
+
+User* user_new(Manager *m, uid_t uid, gid_t gid, const char *name);
+void user_free(User *u);
+int user_check_gc(User *u, bool drop_not_started);
+void user_add_to_gc_queue(User *u);
+int user_start(User *u);
+int user_stop(User *u);
+UserState user_get_state(User *u);
+int user_get_idle_hint(User *u, dual_timestamp *t);
+int user_save(User *u);
+int user_load(User *u);
+int user_kill(User *u, int signo);
+
+char *user_bus_path(User *s);
+
+extern const DBusObjectPathVTable bus_user_vtable;
+
+int user_send_signal(User *u, bool new_user);
+int user_send_changed(User *u, const char *properties);
+
+const char* user_state_to_string(UserState s) _const_;
+UserState user_state_from_string(const char *s) _pure_;
diff --git a/src/login/logind.c b/src/login/logind.c
new file mode 100644
index 0000000000..5a394401dc
--- /dev/null
+++ b/src/login/logind.c
@@ -0,0 +1,1767 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <pwd.h>
+#include <libudev.h>
+#include <fcntl.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/epoll.h>
+#include <sys/ioctl.h>
+#include <linux/vt.h>
+#include <sys/timerfd.h>
+
+#include <systemd/sd-daemon.h>
+
+#include "logind.h"
+#include "dbus-common.h"
+#include "dbus-loop.h"
+#include "strv.h"
+#include "conf-parser.h"
+#include "mkdir.h"
+
+Manager *manager_new(void) {
+ Manager *m;
+
+ m = new0(Manager, 1);
+ if (!m)
+ return NULL;
+
+ m->console_active_fd = -1;
+ m->bus_fd = -1;
+ m->udev_seat_fd = -1;
+ m->udev_vcsa_fd = -1;
+ m->udev_button_fd = -1;
+ m->epoll_fd = -1;
+ m->reserve_vt_fd = -1;
+
+ m->n_autovts = 6;
+ m->reserve_vt = 6;
+ m->inhibit_delay_max = 5 * USEC_PER_SEC;
+ m->handle_power_key = HANDLE_POWEROFF;
+ m->handle_suspend_key = HANDLE_SUSPEND;
+ m->handle_hibernate_key = HANDLE_HIBERNATE;
+ m->handle_lid_switch = HANDLE_SUSPEND;
+ m->lid_switch_ignore_inhibited = true;
+
+ m->idle_action_fd = -1;
+ m->idle_action_usec = 30 * USEC_PER_MINUTE;
+ m->idle_action = HANDLE_IGNORE;
+ m->idle_action_not_before_usec = now(CLOCK_MONOTONIC);
+
+ m->devices = hashmap_new(string_hash_func, string_compare_func);
+ m->seats = hashmap_new(string_hash_func, string_compare_func);
+ m->sessions = hashmap_new(string_hash_func, string_compare_func);
+ m->users = hashmap_new(trivial_hash_func, trivial_compare_func);
+ m->inhibitors = hashmap_new(string_hash_func, string_compare_func);
+ m->buttons = hashmap_new(string_hash_func, string_compare_func);
+
+ m->user_cgroups = hashmap_new(string_hash_func, string_compare_func);
+ m->session_cgroups = hashmap_new(string_hash_func, string_compare_func);
+
+ m->session_fds = hashmap_new(trivial_hash_func, trivial_compare_func);
+ m->inhibitor_fds = hashmap_new(trivial_hash_func, trivial_compare_func);
+ m->button_fds = hashmap_new(trivial_hash_func, trivial_compare_func);
+
+ if (!m->devices || !m->seats || !m->sessions || !m->users || !m->inhibitors || !m->buttons ||
+ !m->user_cgroups || !m->session_cgroups ||
+ !m->session_fds || !m->inhibitor_fds || !m->button_fds) {
+ manager_free(m);
+ return NULL;
+ }
+
+ m->reset_controllers = strv_new("cpu", NULL);
+ m->kill_exclude_users = strv_new("root", NULL);
+ if (!m->reset_controllers || !m->kill_exclude_users) {
+ manager_free(m);
+ return NULL;
+ }
+
+ m->udev = udev_new();
+ if (!m->udev) {
+ manager_free(m);
+ return NULL;
+ }
+
+ if (cg_get_user_path(&m->cgroup_path) < 0) {
+ manager_free(m);
+ return NULL;
+ }
+
+ return m;
+}
+
+void manager_free(Manager *m) {
+ Session *session;
+ User *u;
+ Device *d;
+ Seat *s;
+ Inhibitor *i;
+ Button *b;
+
+ assert(m);
+
+ while ((session = hashmap_first(m->sessions)))
+ session_free(session);
+
+ while ((u = hashmap_first(m->users)))
+ user_free(u);
+
+ while ((d = hashmap_first(m->devices)))
+ device_free(d);
+
+ while ((s = hashmap_first(m->seats)))
+ seat_free(s);
+
+ while ((i = hashmap_first(m->inhibitors)))
+ inhibitor_free(i);
+
+ while ((b = hashmap_first(m->buttons)))
+ button_free(b);
+
+ hashmap_free(m->devices);
+ hashmap_free(m->seats);
+ hashmap_free(m->sessions);
+ hashmap_free(m->users);
+ hashmap_free(m->inhibitors);
+ hashmap_free(m->buttons);
+
+ hashmap_free(m->user_cgroups);
+ hashmap_free(m->session_cgroups);
+
+ hashmap_free(m->session_fds);
+ hashmap_free(m->inhibitor_fds);
+ hashmap_free(m->button_fds);
+
+ if (m->console_active_fd >= 0)
+ close_nointr_nofail(m->console_active_fd);
+
+ if (m->udev_seat_monitor)
+ udev_monitor_unref(m->udev_seat_monitor);
+ if (m->udev_vcsa_monitor)
+ udev_monitor_unref(m->udev_vcsa_monitor);
+ if (m->udev_button_monitor)
+ udev_monitor_unref(m->udev_button_monitor);
+
+ if (m->udev)
+ udev_unref(m->udev);
+
+ if (m->bus) {
+ dbus_connection_flush(m->bus);
+ dbus_connection_close(m->bus);
+ dbus_connection_unref(m->bus);
+ }
+
+ if (m->bus_fd >= 0)
+ close_nointr_nofail(m->bus_fd);
+
+ if (m->epoll_fd >= 0)
+ close_nointr_nofail(m->epoll_fd);
+
+ if (m->reserve_vt_fd >= 0)
+ close_nointr_nofail(m->reserve_vt_fd);
+
+ if (m->idle_action_fd >= 0)
+ close_nointr_nofail(m->idle_action_fd);
+
+ strv_free(m->controllers);
+ strv_free(m->reset_controllers);
+ strv_free(m->kill_only_users);
+ strv_free(m->kill_exclude_users);
+
+ free(m->action_job);
+
+ free(m->cgroup_path);
+ free(m);
+}
+
+int manager_add_device(Manager *m, const char *sysfs, Device **_device) {
+ Device *d;
+
+ assert(m);
+ assert(sysfs);
+
+ d = hashmap_get(m->devices, sysfs);
+ if (d) {
+ if (_device)
+ *_device = d;
+
+ return 0;
+ }
+
+ d = device_new(m, sysfs);
+ if (!d)
+ return -ENOMEM;
+
+ if (_device)
+ *_device = d;
+
+ return 0;
+}
+
+int manager_add_seat(Manager *m, const char *id, Seat **_seat) {
+ Seat *s;
+
+ assert(m);
+ assert(id);
+
+ s = hashmap_get(m->seats, id);
+ if (s) {
+ if (_seat)
+ *_seat = s;
+
+ return 0;
+ }
+
+ s = seat_new(m, id);
+ if (!s)
+ return -ENOMEM;
+
+ if (_seat)
+ *_seat = s;
+
+ return 0;
+}
+
+int manager_add_session(Manager *m, User *u, const char *id, Session **_session) {
+ Session *s;
+
+ assert(m);
+ assert(id);
+
+ s = hashmap_get(m->sessions, id);
+ if (s) {
+ if (_session)
+ *_session = s;
+
+ return 0;
+ }
+
+ s = session_new(m, u, id);
+ if (!s)
+ return -ENOMEM;
+
+ if (_session)
+ *_session = s;
+
+ return 0;
+}
+
+int manager_add_user(Manager *m, uid_t uid, gid_t gid, const char *name, User **_user) {
+ User *u;
+
+ assert(m);
+ assert(name);
+
+ u = hashmap_get(m->users, ULONG_TO_PTR((unsigned long) uid));
+ if (u) {
+ if (_user)
+ *_user = u;
+
+ return 0;
+ }
+
+ u = user_new(m, uid, gid, name);
+ if (!u)
+ return -ENOMEM;
+
+ if (_user)
+ *_user = u;
+
+ return 0;
+}
+
+int manager_add_user_by_name(Manager *m, const char *name, User **_user) {
+ uid_t uid;
+ gid_t gid;
+ int r;
+
+ assert(m);
+ assert(name);
+
+ r = get_user_creds(&name, &uid, &gid, NULL, NULL);
+ if (r < 0)
+ return r;
+
+ return manager_add_user(m, uid, gid, name, _user);
+}
+
+int manager_add_user_by_uid(Manager *m, uid_t uid, User **_user) {
+ struct passwd *p;
+
+ assert(m);
+
+ errno = 0;
+ p = getpwuid(uid);
+ if (!p)
+ return errno ? -errno : -ENOENT;
+
+ return manager_add_user(m, uid, p->pw_gid, p->pw_name, _user);
+}
+
+int manager_add_inhibitor(Manager *m, const char* id, Inhibitor **_inhibitor) {
+ Inhibitor *i;
+
+ assert(m);
+ assert(id);
+
+ i = hashmap_get(m->inhibitors, id);
+ if (i) {
+ if (_inhibitor)
+ *_inhibitor = i;
+
+ return 0;
+ }
+
+ i = inhibitor_new(m, id);
+ if (!i)
+ return -ENOMEM;
+
+ if (_inhibitor)
+ *_inhibitor = i;
+
+ return 0;
+}
+
+int manager_add_button(Manager *m, const char *name, Button **_button) {
+ Button *b;
+
+ assert(m);
+ assert(name);
+
+ b = hashmap_get(m->buttons, name);
+ if (b) {
+ if (_button)
+ *_button = b;
+
+ return 0;
+ }
+
+ b = button_new(m, name);
+ if (!b)
+ return -ENOMEM;
+
+ if (_button)
+ *_button = b;
+
+ return 0;
+}
+
+int manager_process_seat_device(Manager *m, struct udev_device *d) {
+ Device *device;
+ int r;
+
+ assert(m);
+
+ if (streq_ptr(udev_device_get_action(d), "remove")) {
+
+ device = hashmap_get(m->devices, udev_device_get_syspath(d));
+ if (!device)
+ return 0;
+
+ seat_add_to_gc_queue(device->seat);
+ device_free(device);
+
+ } else {
+ const char *sn;
+ Seat *seat;
+
+ sn = udev_device_get_property_value(d, "ID_SEAT");
+ if (isempty(sn))
+ sn = "seat0";
+
+ if (!seat_name_is_valid(sn)) {
+ log_warning("Device with invalid seat name %s found, ignoring.", sn);
+ return 0;
+ }
+
+ r = manager_add_device(m, udev_device_get_syspath(d), &device);
+ if (r < 0)
+ return r;
+
+ r = manager_add_seat(m, sn, &seat);
+ if (r < 0) {
+ if (!device->seat)
+ device_free(device);
+
+ return r;
+ }
+
+ device_attach(device, seat);
+ seat_start(seat);
+ }
+
+ return 0;
+}
+
+int manager_process_button_device(Manager *m, struct udev_device *d) {
+ Button *b;
+
+ int r;
+
+ assert(m);
+
+ if (streq_ptr(udev_device_get_action(d), "remove")) {
+
+ b = hashmap_get(m->buttons, udev_device_get_sysname(d));
+ if (!b)
+ return 0;
+
+ button_free(b);
+
+ } else {
+ const char *sn;
+
+ r = manager_add_button(m, udev_device_get_sysname(d), &b);
+ if (r < 0)
+ return r;
+
+ sn = udev_device_get_property_value(d, "ID_SEAT");
+ if (isempty(sn))
+ sn = "seat0";
+
+ button_set_seat(b, sn);
+ button_open(b);
+ }
+
+ return 0;
+}
+
+int manager_enumerate_devices(Manager *m) {
+ struct udev_list_entry *item = NULL, *first = NULL;
+ struct udev_enumerate *e;
+ int r;
+
+ assert(m);
+
+ /* Loads devices from udev and creates seats for them as
+ * necessary */
+
+ e = udev_enumerate_new(m->udev);
+ if (!e) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ r = udev_enumerate_add_match_tag(e, "master-of-seat");
+ if (r < 0)
+ goto finish;
+
+ r = udev_enumerate_scan_devices(e);
+ if (r < 0)
+ goto finish;
+
+ first = udev_enumerate_get_list_entry(e);
+ udev_list_entry_foreach(item, first) {
+ struct udev_device *d;
+ int k;
+
+ d = udev_device_new_from_syspath(m->udev, udev_list_entry_get_name(item));
+ if (!d) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ k = manager_process_seat_device(m, d);
+ udev_device_unref(d);
+
+ if (k < 0)
+ r = k;
+ }
+
+finish:
+ if (e)
+ udev_enumerate_unref(e);
+
+ return r;
+}
+
+int manager_enumerate_buttons(Manager *m) {
+ struct udev_list_entry *item = NULL, *first = NULL;
+ struct udev_enumerate *e;
+ int r;
+
+ assert(m);
+
+ /* Loads buttons from udev */
+
+ if (m->handle_power_key == HANDLE_IGNORE &&
+ m->handle_suspend_key == HANDLE_IGNORE &&
+ m->handle_hibernate_key == HANDLE_IGNORE &&
+ m->handle_lid_switch == HANDLE_IGNORE)
+ return 0;
+
+ e = udev_enumerate_new(m->udev);
+ if (!e) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ r = udev_enumerate_add_match_subsystem(e, "input");
+ if (r < 0)
+ goto finish;
+
+ r = udev_enumerate_add_match_tag(e, "power-switch");
+ if (r < 0)
+ goto finish;
+
+ r = udev_enumerate_scan_devices(e);
+ if (r < 0)
+ goto finish;
+
+ first = udev_enumerate_get_list_entry(e);
+ udev_list_entry_foreach(item, first) {
+ struct udev_device *d;
+ int k;
+
+ d = udev_device_new_from_syspath(m->udev, udev_list_entry_get_name(item));
+ if (!d) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ k = manager_process_button_device(m, d);
+ udev_device_unref(d);
+
+ if (k < 0)
+ r = k;
+ }
+
+finish:
+ if (e)
+ udev_enumerate_unref(e);
+
+ return r;
+}
+
+int manager_enumerate_seats(Manager *m) {
+ DIR *d;
+ struct dirent *de;
+ int r = 0;
+
+ assert(m);
+
+ /* This loads data about seats stored on disk, but does not
+ * actually create any seats. Removes data of seats that no
+ * longer exist. */
+
+ d = opendir("/run/systemd/seats");
+ if (!d) {
+ if (errno == ENOENT)
+ return 0;
+
+ log_error("Failed to open /run/systemd/seats: %m");
+ return -errno;
+ }
+
+ while ((de = readdir(d))) {
+ Seat *s;
+ int k;
+
+ if (!dirent_is_file(de))
+ continue;
+
+ s = hashmap_get(m->seats, de->d_name);
+ if (!s) {
+ unlinkat(dirfd(d), de->d_name, 0);
+ continue;
+ }
+
+ k = seat_load(s);
+ if (k < 0)
+ r = k;
+ }
+
+ closedir(d);
+
+ return r;
+}
+
+static int manager_enumerate_users_from_cgroup(Manager *m) {
+ _cleanup_closedir_ DIR *d = NULL;
+ int r = 0, k;
+ char *name;
+
+ r = cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_path, &d);
+ if (r < 0) {
+ if (r == -ENOENT)
+ return 0;
+
+ log_error("Failed to open %s: %s", m->cgroup_path, strerror(-r));
+ return r;
+ }
+
+ while ((k = cg_read_subgroup(d, &name)) > 0) {
+ User *user;
+ char *e;
+
+ e = endswith(name, ".user");
+ if (e) {
+ *e = 0;
+
+ k = manager_add_user_by_name(m, name, &user);
+ if (k < 0) {
+ free(name);
+ r = k;
+ continue;
+ }
+
+ user_add_to_gc_queue(user);
+
+ if (!user->cgroup_path) {
+ user->cgroup_path = strjoin(m->cgroup_path, "/", name, NULL);
+ if (!user->cgroup_path) {
+ k = log_oom();
+ free(name);
+ break;
+ }
+ }
+ }
+
+ free(name);
+ }
+
+ if (k < 0)
+ r = k;
+
+ return r;
+}
+
+static int manager_enumerate_linger_users(Manager *m) {
+ DIR *d;
+ struct dirent *de;
+ int r = 0;
+
+ d = opendir("/var/lib/systemd/linger");
+ if (!d) {
+ if (errno == ENOENT)
+ return 0;
+
+ log_error("Failed to open /var/lib/systemd/linger/: %m");
+ return -errno;
+ }
+
+ while ((de = readdir(d))) {
+ int k;
+
+ if (!dirent_is_file(de))
+ continue;
+
+ k = manager_add_user_by_name(m, de->d_name, NULL);
+ if (k < 0) {
+ log_notice("Couldn't add lingering user %s: %s", de->d_name, strerror(-k));
+ r = k;
+ }
+ }
+
+ closedir(d);
+
+ return r;
+}
+
+int manager_enumerate_users(Manager *m) {
+ DIR *d;
+ struct dirent *de;
+ int r, k;
+
+ assert(m);
+
+ /* First, enumerate user cgroups */
+ r = manager_enumerate_users_from_cgroup(m);
+
+ /* Second, add lingering users on top */
+ k = manager_enumerate_linger_users(m);
+ if (k < 0)
+ r = k;
+
+ /* Third, read in user data stored on disk */
+ d = opendir("/run/systemd/users");
+ if (!d) {
+ if (errno == ENOENT)
+ return 0;
+
+ log_error("Failed to open /run/systemd/users: %m");
+ return -errno;
+ }
+
+ while ((de = readdir(d))) {
+ uid_t uid;
+ User *u;
+
+ if (!dirent_is_file(de))
+ continue;
+
+ k = parse_uid(de->d_name, &uid);
+ if (k < 0) {
+ log_error("Failed to parse file name %s: %s", de->d_name, strerror(-k));
+ continue;
+ }
+
+ u = hashmap_get(m->users, ULONG_TO_PTR(uid));
+ if (!u) {
+ unlinkat(dirfd(d), de->d_name, 0);
+ continue;
+ }
+
+ k = user_load(u);
+ if (k < 0)
+ r = k;
+ }
+
+ closedir(d);
+
+ return r;
+}
+
+static int manager_enumerate_sessions_from_cgroup(Manager *m) {
+ User *u;
+ Iterator i;
+ int r = 0;
+
+ HASHMAP_FOREACH(u, m->users, i) {
+ _cleanup_closedir_ DIR *d = NULL;
+ char *name;
+ int k;
+
+ if (!u->cgroup_path)
+ continue;
+
+ k = cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, &d);
+ if (k < 0) {
+ if (k == -ENOENT)
+ continue;
+
+ log_error("Failed to open %s: %s", u->cgroup_path, strerror(-k));
+ r = k;
+ continue;
+ }
+
+ while ((k = cg_read_subgroup(d, &name)) > 0) {
+ Session *session;
+ char *e;
+
+ e = endswith(name, ".session");
+ if (e) {
+ *e = 0;
+
+ k = manager_add_session(m, u, name, &session);
+ if (k < 0) {
+ free(name);
+ r = k;
+ continue;
+ }
+
+ session_add_to_gc_queue(session);
+
+ if (!session->cgroup_path) {
+ session->cgroup_path = strjoin(m->cgroup_path, "/", name, NULL);
+ if (!session->cgroup_path) {
+ k = log_oom();
+ free(name);
+ break;
+ }
+ }
+ }
+
+ free(name);
+ }
+
+ if (k < 0)
+ r = k;
+ }
+
+ return r;
+}
+
+int manager_enumerate_sessions(Manager *m) {
+ DIR *d;
+ struct dirent *de;
+ int r = 0;
+
+ assert(m);
+
+ /* First enumerate session cgroups */
+ r = manager_enumerate_sessions_from_cgroup(m);
+
+ /* Second, read in session data stored on disk */
+ d = opendir("/run/systemd/sessions");
+ if (!d) {
+ if (errno == ENOENT)
+ return 0;
+
+ log_error("Failed to open /run/systemd/sessions: %m");
+ return -errno;
+ }
+
+ while ((de = readdir(d))) {
+ struct Session *s;
+ int k;
+
+ if (!dirent_is_file(de))
+ continue;
+
+ s = hashmap_get(m->sessions, de->d_name);
+ if (!s) {
+ unlinkat(dirfd(d), de->d_name, 0);
+ continue;
+ }
+
+ k = session_load(s);
+ if (k < 0)
+ r = k;
+ }
+
+ closedir(d);
+
+ return r;
+}
+
+int manager_enumerate_inhibitors(Manager *m) {
+ DIR *d;
+ struct dirent *de;
+ int r = 0;
+
+ assert(m);
+
+ d = opendir("/run/systemd/inhibit");
+ if (!d) {
+ if (errno == ENOENT)
+ return 0;
+
+ log_error("Failed to open /run/systemd/inhibit: %m");
+ return -errno;
+ }
+
+ while ((de = readdir(d))) {
+ int k;
+ Inhibitor *i;
+
+ if (!dirent_is_file(de))
+ continue;
+
+ k = manager_add_inhibitor(m, de->d_name, &i);
+ if (k < 0) {
+ log_notice("Couldn't add inhibitor %s: %s", de->d_name, strerror(-k));
+ r = k;
+ continue;
+ }
+
+ k = inhibitor_load(i);
+ if (k < 0)
+ r = k;
+ }
+
+ closedir(d);
+
+ return r;
+}
+
+int manager_dispatch_seat_udev(Manager *m) {
+ struct udev_device *d;
+ int r;
+
+ assert(m);
+
+ d = udev_monitor_receive_device(m->udev_seat_monitor);
+ if (!d)
+ return -ENOMEM;
+
+ r = manager_process_seat_device(m, d);
+ udev_device_unref(d);
+
+ return r;
+}
+
+int manager_dispatch_vcsa_udev(Manager *m) {
+ struct udev_device *d;
+ int r = 0;
+ const char *name;
+
+ assert(m);
+
+ d = udev_monitor_receive_device(m->udev_vcsa_monitor);
+ if (!d)
+ return -ENOMEM;
+
+ name = udev_device_get_sysname(d);
+
+ /* Whenever a VCSA device is removed try to reallocate our
+ * VTs, to make sure our auto VTs never go away. */
+
+ if (name && startswith(name, "vcsa") && streq_ptr(udev_device_get_action(d), "remove"))
+ r = seat_preallocate_vts(m->vtconsole);
+
+ udev_device_unref(d);
+
+ return r;
+}
+
+int manager_dispatch_button_udev(Manager *m) {
+ struct udev_device *d;
+ int r;
+
+ assert(m);
+
+ d = udev_monitor_receive_device(m->udev_button_monitor);
+ if (!d)
+ return -ENOMEM;
+
+ r = manager_process_button_device(m, d);
+ udev_device_unref(d);
+
+ return r;
+}
+
+int manager_dispatch_console(Manager *m) {
+ assert(m);
+
+ if (m->vtconsole)
+ seat_read_active_vt(m->vtconsole);
+
+ return 0;
+}
+
+static int vt_is_busy(int vtnr) {
+ struct vt_stat vt_stat;
+ int r = 0, fd;
+
+ assert(vtnr >= 1);
+
+ /* We explicitly open /dev/tty1 here instead of /dev/tty0. If
+ * we'd open the latter we'd open the foreground tty which
+ * hence would be unconditionally busy. By opening /dev/tty1
+ * we avoid this. Since tty1 is special and needs to be an
+ * explicitly loaded getty or DM this is safe. */
+
+ fd = open_terminal("/dev/tty1", O_RDWR|O_NOCTTY|O_CLOEXEC);
+ if (fd < 0)
+ return -errno;
+
+ if (ioctl(fd, VT_GETSTATE, &vt_stat) < 0)
+ r = -errno;
+ else
+ r = !!(vt_stat.v_state & (1 << vtnr));
+
+ close_nointr_nofail(fd);
+
+ return r;
+}
+
+int manager_spawn_autovt(Manager *m, int vtnr) {
+ int r;
+ char *name = NULL;
+ const char *mode = "fail";
+
+ assert(m);
+ assert(vtnr >= 1);
+
+ if ((unsigned) vtnr > m->n_autovts &&
+ (unsigned) vtnr != m->reserve_vt)
+ return 0;
+
+ if ((unsigned) vtnr != m->reserve_vt) {
+ /* If this is the reserved TTY, we'll start the getty
+ * on it in any case, but otherwise only if it is not
+ * busy. */
+
+ r = vt_is_busy(vtnr);
+ if (r < 0)
+ return r;
+ else if (r > 0)
+ return -EBUSY;
+ }
+
+ if (asprintf(&name, "autovt@tty%i.service", vtnr) < 0) {
+ log_error("Could not allocate service name.");
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ r = bus_method_call_with_reply (
+ m->bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "StartUnit",
+ NULL,
+ NULL,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_STRING, &mode,
+ DBUS_TYPE_INVALID);
+
+finish:
+ free(name);
+
+ return r;
+}
+
+static int manager_reserve_vt(Manager *m) {
+ _cleanup_free_ char *p = NULL;
+
+ assert(m);
+
+ if (m->reserve_vt <= 0)
+ return 0;
+
+ if (asprintf(&p, "/dev/tty%u", m->reserve_vt) < 0)
+ return log_oom();
+
+ m->reserve_vt_fd = open(p, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
+ if (m->reserve_vt_fd < 0) {
+
+ /* Don't complain on VT-less systems */
+ if (errno != ENOENT)
+ log_warning("Failed to pin reserved VT: %m");
+ return -errno;
+ }
+
+ return 0;
+}
+
+int manager_get_session_by_cgroup(Manager *m, const char *cgroup, Session **session) {
+ Session *s;
+ char *p;
+
+ assert(m);
+ assert(cgroup);
+ assert(session);
+
+ s = hashmap_get(m->session_cgroups, cgroup);
+ if (s) {
+ *session = s;
+ return 1;
+ }
+
+ p = strdupa(cgroup);
+
+ for (;;) {
+ char *e;
+
+ e = strrchr(p, '/');
+ if (!e || e == p) {
+ *session = NULL;
+ return 0;
+ }
+
+ *e = 0;
+
+ s = hashmap_get(m->session_cgroups, p);
+ if (s) {
+ *session = s;
+ return 1;
+ }
+ }
+}
+
+int manager_get_user_by_cgroup(Manager *m, const char *cgroup, User **user) {
+ User *u;
+ char *p;
+
+ assert(m);
+ assert(cgroup);
+ assert(user);
+
+ u = hashmap_get(m->user_cgroups, cgroup);
+ if (u) {
+ *user = u;
+ return 1;
+ }
+
+ p = strdupa(cgroup);
+ if (!p)
+ return log_oom();
+
+ for (;;) {
+ char *e;
+
+ e = strrchr(p, '/');
+ if (!e || e == p) {
+ *user = NULL;
+ return 0;
+ }
+
+ *e = 0;
+
+ u = hashmap_get(m->user_cgroups, p);
+ if (u) {
+ *user = u;
+ return 1;
+ }
+ }
+}
+
+int manager_get_session_by_pid(Manager *m, pid_t pid, Session **session) {
+ _cleanup_free_ char *p = NULL;
+ int r;
+
+ assert(m);
+ assert(pid >= 1);
+ assert(session);
+
+ r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &p);
+ if (r < 0)
+ return r;
+
+ return manager_get_session_by_cgroup(m, p, session);
+}
+
+void manager_cgroup_notify_empty(Manager *m, const char *cgroup) {
+ Session *s;
+ User *u;
+ int r;
+
+ r = manager_get_session_by_cgroup(m, cgroup, &s);
+ if (r > 0)
+ session_add_to_gc_queue(s);
+
+ r = manager_get_user_by_cgroup(m, cgroup, &u);
+ if (r > 0)
+ user_add_to_gc_queue(u);
+}
+
+static void manager_dispatch_other(Manager *m, int fd) {
+ Session *s;
+ Inhibitor *i;
+ Button *b;
+
+ assert_se(m);
+ assert_se(fd >= 0);
+
+ s = hashmap_get(m->session_fds, INT_TO_PTR(fd + 1));
+ if (s) {
+ assert(s->fifo_fd == fd);
+ session_remove_fifo(s);
+ session_stop(s);
+ return;
+ }
+
+ i = hashmap_get(m->inhibitor_fds, INT_TO_PTR(fd + 1));
+ if (i) {
+ assert(i->fifo_fd == fd);
+ inhibitor_stop(i);
+ inhibitor_free(i);
+ return;
+ }
+
+ b = hashmap_get(m->button_fds, INT_TO_PTR(fd + 1));
+ if (b) {
+ assert(b->fd == fd);
+ button_process(b);
+ return;
+ }
+
+ assert_not_reached("Got event for unknown fd");
+}
+
+static int manager_connect_bus(Manager *m) {
+ DBusError error;
+ int r;
+ struct epoll_event ev = {
+ .events = EPOLLIN,
+ .data.u32 = FD_BUS,
+ };
+
+ assert(m);
+ assert(!m->bus);
+ assert(m->bus_fd < 0);
+
+ dbus_error_init(&error);
+
+ m->bus = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error);
+ if (!m->bus) {
+ log_error("Failed to get system D-Bus connection: %s", bus_error_message(&error));
+ r = -ECONNREFUSED;
+ goto fail;
+ }
+
+ if (!dbus_connection_register_object_path(m->bus, "/org/freedesktop/login1", &bus_manager_vtable, m) ||
+ !dbus_connection_register_fallback(m->bus, "/org/freedesktop/login1/seat", &bus_seat_vtable, m) ||
+ !dbus_connection_register_fallback(m->bus, "/org/freedesktop/login1/session", &bus_session_vtable, m) ||
+ !dbus_connection_register_fallback(m->bus, "/org/freedesktop/login1/user", &bus_user_vtable, m) ||
+ !dbus_connection_add_filter(m->bus, bus_message_filter, m, NULL)) {
+ r = log_oom();
+ goto fail;
+ }
+
+ dbus_bus_add_match(m->bus,
+ "type='signal',"
+ "interface='org.freedesktop.systemd1.Agent',"
+ "member='Released',"
+ "path='/org/freedesktop/systemd1/agent'",
+ &error);
+
+ if (dbus_error_is_set(&error)) {
+ log_error("Failed to register match: %s", bus_error_message(&error));
+ r = -EIO;
+ goto fail;
+ }
+
+ r = dbus_bus_request_name(m->bus, "org.freedesktop.login1", DBUS_NAME_FLAG_DO_NOT_QUEUE, &error);
+ if (dbus_error_is_set(&error)) {
+ log_error("Failed to register name on bus: %s", bus_error_message(&error));
+ r = -EIO;
+ goto fail;
+ }
+
+ if (r != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) {
+ log_error("Failed to acquire name.");
+ r = -EEXIST;
+ goto fail;
+ }
+
+ m->bus_fd = bus_loop_open(m->bus);
+ if (m->bus_fd < 0) {
+ r = m->bus_fd;
+ goto fail;
+ }
+
+ if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->bus_fd, &ev) < 0)
+ goto fail;
+
+ return 0;
+
+fail:
+ dbus_error_free(&error);
+
+ return r;
+}
+
+static int manager_connect_console(Manager *m) {
+ struct epoll_event ev = {
+ .events = 0,
+ .data.u32 = FD_CONSOLE,
+ };
+
+ assert(m);
+ assert(m->console_active_fd < 0);
+
+ /* On certain architectures (S390 and Xen, and containers),
+ /dev/tty0 does not exist, so don't fail if we can't open
+ it. */
+ if (access("/dev/tty0", F_OK) < 0) {
+ m->console_active_fd = -1;
+ return 0;
+ }
+
+ m->console_active_fd = open("/sys/class/tty/tty0/active", O_RDONLY|O_NOCTTY|O_CLOEXEC);
+ if (m->console_active_fd < 0) {
+
+ /* On some systems the device node /dev/tty0 may exist
+ * even though /sys/class/tty/tty0 does not. */
+ if (errno == ENOENT)
+ return 0;
+
+ log_error("Failed to open /sys/class/tty/tty0/active: %m");
+ return -errno;
+ }
+
+ if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->console_active_fd, &ev) < 0)
+ return -errno;
+
+ return 0;
+}
+
+static int manager_connect_udev(Manager *m) {
+ int r;
+ struct epoll_event ev = {
+ .events = EPOLLIN,
+ .data.u32 = FD_SEAT_UDEV,
+ };
+
+ assert(m);
+ assert(!m->udev_seat_monitor);
+ assert(!m->udev_vcsa_monitor);
+ assert(!m->udev_button_monitor);
+
+ m->udev_seat_monitor = udev_monitor_new_from_netlink(m->udev, "udev");
+ if (!m->udev_seat_monitor)
+ return -ENOMEM;
+
+ r = udev_monitor_filter_add_match_tag(m->udev_seat_monitor, "master-of-seat");
+ if (r < 0)
+ return r;
+
+ r = udev_monitor_enable_receiving(m->udev_seat_monitor);
+ if (r < 0)
+ return r;
+
+ m->udev_seat_fd = udev_monitor_get_fd(m->udev_seat_monitor);
+
+ if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->udev_seat_fd, &ev) < 0)
+ return -errno;
+
+ /* Don't watch keys if nobody cares */
+ if (m->handle_power_key != HANDLE_IGNORE ||
+ m->handle_suspend_key != HANDLE_IGNORE ||
+ m->handle_hibernate_key != HANDLE_IGNORE ||
+ m->handle_lid_switch != HANDLE_IGNORE) {
+
+ m->udev_button_monitor = udev_monitor_new_from_netlink(m->udev, "udev");
+ if (!m->udev_button_monitor)
+ return -ENOMEM;
+
+ r = udev_monitor_filter_add_match_tag(m->udev_button_monitor, "power-switch");
+ if (r < 0)
+ return r;
+
+ r = udev_monitor_filter_add_match_subsystem_devtype(m->udev_button_monitor, "input", NULL);
+ if (r < 0)
+ return r;
+
+ r = udev_monitor_enable_receiving(m->udev_button_monitor);
+ if (r < 0)
+ return r;
+
+ m->udev_button_fd = udev_monitor_get_fd(m->udev_button_monitor);
+
+ zero(ev);
+ ev.events = EPOLLIN;
+ ev.data.u32 = FD_BUTTON_UDEV;
+ if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->udev_button_fd, &ev) < 0)
+ return -errno;
+ }
+
+ /* Don't bother watching VCSA devices, if nobody cares */
+ if (m->n_autovts > 0 && m->console_active_fd >= 0) {
+
+ m->udev_vcsa_monitor = udev_monitor_new_from_netlink(m->udev, "udev");
+ if (!m->udev_vcsa_monitor)
+ return -ENOMEM;
+
+ r = udev_monitor_filter_add_match_subsystem_devtype(m->udev_vcsa_monitor, "vc", NULL);
+ if (r < 0)
+ return r;
+
+ r = udev_monitor_enable_receiving(m->udev_vcsa_monitor);
+ if (r < 0)
+ return r;
+
+ m->udev_vcsa_fd = udev_monitor_get_fd(m->udev_vcsa_monitor);
+
+ zero(ev);
+ ev.events = EPOLLIN;
+ ev.data.u32 = FD_VCSA_UDEV;
+ if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->udev_vcsa_fd, &ev) < 0)
+ return -errno;
+ }
+
+ return 0;
+}
+
+void manager_gc(Manager *m, bool drop_not_started) {
+ Seat *seat;
+ Session *session;
+ User *user;
+
+ assert(m);
+
+ while ((seat = m->seat_gc_queue)) {
+ LIST_REMOVE(Seat, gc_queue, m->seat_gc_queue, seat);
+ seat->in_gc_queue = false;
+
+ if (seat_check_gc(seat, drop_not_started) == 0) {
+ seat_stop(seat);
+ seat_free(seat);
+ }
+ }
+
+ while ((session = m->session_gc_queue)) {
+ LIST_REMOVE(Session, gc_queue, m->session_gc_queue, session);
+ session->in_gc_queue = false;
+
+ if (session_check_gc(session, drop_not_started) == 0) {
+ session_stop(session);
+ session_free(session);
+ }
+ }
+
+ while ((user = m->user_gc_queue)) {
+ LIST_REMOVE(User, gc_queue, m->user_gc_queue, user);
+ user->in_gc_queue = false;
+
+ if (user_check_gc(user, drop_not_started) == 0) {
+ user_stop(user);
+ user_free(user);
+ }
+ }
+}
+
+int manager_get_idle_hint(Manager *m, dual_timestamp *t) {
+ Session *s;
+ bool idle_hint;
+ dual_timestamp ts = { 0, 0 };
+ Iterator i;
+
+ assert(m);
+
+ idle_hint = !manager_is_inhibited(m, INHIBIT_IDLE, INHIBIT_BLOCK, t, false, false, 0);
+
+ HASHMAP_FOREACH(s, m->sessions, i) {
+ dual_timestamp k;
+ int ih;
+
+ ih = session_get_idle_hint(s, &k);
+ if (ih < 0)
+ return ih;
+
+ if (!ih) {
+ if (!idle_hint) {
+ if (k.monotonic < ts.monotonic)
+ ts = k;
+ } else {
+ idle_hint = false;
+ ts = k;
+ }
+ } else if (idle_hint) {
+
+ if (k.monotonic > ts.monotonic)
+ ts = k;
+ }
+ }
+
+ if (t)
+ *t = ts;
+
+ return idle_hint;
+}
+
+int manager_dispatch_idle_action(Manager *m) {
+ struct dual_timestamp since;
+ struct itimerspec its = {};
+ int r;
+ usec_t n;
+
+ assert(m);
+
+ if (m->idle_action == HANDLE_IGNORE ||
+ m->idle_action_usec <= 0) {
+ r = 0;
+ goto finish;
+ }
+
+ n = now(CLOCK_MONOTONIC);
+
+ r = manager_get_idle_hint(m, &since);
+ if (r <= 0)
+ /* Not idle. Let's check if after a timeout it might be idle then. */
+ timespec_store(&its.it_value, n + m->idle_action_usec);
+ else {
+ /* Idle! Let's see if it's time to do something, or if
+ * we shall sleep for longer. */
+
+ if (n >= since.monotonic + m->idle_action_usec &&
+ (m->idle_action_not_before_usec <= 0 || n >= m->idle_action_not_before_usec + m->idle_action_usec)) {
+ log_info("System idle. Taking action.");
+
+ manager_handle_action(m, 0, m->idle_action, false, false);
+ m->idle_action_not_before_usec = n;
+ }
+
+ timespec_store(&its.it_value, MAX(since.monotonic, m->idle_action_not_before_usec) + m->idle_action_usec);
+ }
+
+ if (m->idle_action_fd < 0) {
+ struct epoll_event ev = {
+ .events = EPOLLIN,
+ .data.u32 = FD_IDLE_ACTION,
+ };
+
+ m->idle_action_fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC);
+ if (m->idle_action_fd < 0) {
+ log_error("Failed to create idle action timer: %m");
+ r = -errno;
+ goto finish;
+ }
+
+ if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->idle_action_fd, &ev) < 0) {
+ log_error("Failed to add idle action timer to epoll: %m");
+ r = -errno;
+ goto finish;
+ }
+ }
+
+ if (timerfd_settime(m->idle_action_fd, TFD_TIMER_ABSTIME, &its, NULL) < 0) {
+ log_error("Failed to reset timerfd: %m");
+ r = -errno;
+ goto finish;
+ }
+
+ return 0;
+
+finish:
+ if (m->idle_action_fd >= 0) {
+ close_nointr_nofail(m->idle_action_fd);
+ m->idle_action_fd = -1;
+ }
+
+ return r;
+}
+int manager_startup(Manager *m) {
+ int r;
+ Seat *seat;
+ Session *session;
+ User *user;
+ Inhibitor *inhibitor;
+ Iterator i;
+
+ assert(m);
+ assert(m->epoll_fd <= 0);
+
+ cg_shorten_controllers(m->reset_controllers);
+ cg_shorten_controllers(m->controllers);
+
+ m->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
+ if (m->epoll_fd < 0)
+ return -errno;
+
+ /* Connect to console */
+ r = manager_connect_console(m);
+ if (r < 0)
+ return r;
+
+ /* Connect to udev */
+ r = manager_connect_udev(m);
+ if (r < 0)
+ return r;
+
+ /* Connect to the bus */
+ r = manager_connect_bus(m);
+ if (r < 0)
+ return r;
+
+ /* Instantiate magic seat 0 */
+ r = manager_add_seat(m, "seat0", &m->vtconsole);
+ if (r < 0)
+ return r;
+
+ /* Deserialize state */
+ manager_enumerate_devices(m);
+ manager_enumerate_seats(m);
+ manager_enumerate_users(m);
+ manager_enumerate_sessions(m);
+ manager_enumerate_inhibitors(m);
+ manager_enumerate_buttons(m);
+
+ /* Remove stale objects before we start them */
+ manager_gc(m, false);
+
+ /* Reserve the special reserved VT */
+ manager_reserve_vt(m);
+
+ /* And start everything */
+ HASHMAP_FOREACH(seat, m->seats, i)
+ seat_start(seat);
+
+ HASHMAP_FOREACH(user, m->users, i)
+ user_start(user);
+
+ HASHMAP_FOREACH(session, m->sessions, i)
+ session_start(session);
+
+ HASHMAP_FOREACH(inhibitor, m->inhibitors, i)
+ inhibitor_start(inhibitor);
+
+ manager_dispatch_idle_action(m);
+
+ return 0;
+}
+
+static int manager_recheck_buttons(Manager *m) {
+ Iterator i;
+ Button *b;
+ int r = 0;
+
+ assert(m);
+
+ HASHMAP_FOREACH(b, m->buttons, i) {
+ int q;
+
+ q = button_recheck(b);
+ if (q > 0)
+ return 1;
+ if (q < 0)
+ r = q;
+ }
+
+ return r;
+}
+
+int manager_run(Manager *m) {
+ assert(m);
+
+ for (;;) {
+ struct epoll_event event;
+ int n;
+ int msec = -1;
+
+ manager_gc(m, true);
+
+ if (manager_dispatch_delayed(m) > 0)
+ continue;
+
+ if (manager_recheck_buttons(m) > 0)
+ continue;
+
+ if (dbus_connection_dispatch(m->bus) != DBUS_DISPATCH_COMPLETE)
+ continue;
+
+ manager_gc(m, true);
+
+ if (m->action_what != 0 && !m->action_job) {
+ usec_t x, y;
+
+ x = now(CLOCK_MONOTONIC);
+ y = m->action_timestamp + m->inhibit_delay_max;
+
+ msec = x >= y ? 0 : (int) ((y - x) / USEC_PER_MSEC);
+ }
+
+ n = epoll_wait(m->epoll_fd, &event, 1, msec);
+ if (n < 0) {
+ if (errno == EINTR || errno == EAGAIN)
+ continue;
+
+ log_error("epoll() failed: %m");
+ return -errno;
+ }
+
+ if (n == 0)
+ continue;
+
+ switch (event.data.u32) {
+
+ case FD_SEAT_UDEV:
+ manager_dispatch_seat_udev(m);
+ break;
+
+ case FD_VCSA_UDEV:
+ manager_dispatch_vcsa_udev(m);
+ break;
+
+ case FD_BUTTON_UDEV:
+ manager_dispatch_button_udev(m);
+ break;
+
+ case FD_CONSOLE:
+ manager_dispatch_console(m);
+ break;
+
+ case FD_IDLE_ACTION:
+ manager_dispatch_idle_action(m);
+ break;
+
+ case FD_BUS:
+ bus_loop_dispatch(m->bus_fd);
+ break;
+
+ default:
+ if (event.data.u32 >= FD_OTHER_BASE)
+ manager_dispatch_other(m, event.data.u32 - FD_OTHER_BASE);
+ }
+ }
+
+ return 0;
+}
+
+static int manager_parse_config_file(Manager *m) {
+ static const char fn[] = "/etc/systemd/logind.conf";
+ _cleanup_fclose_ FILE *f = NULL;
+ int r;
+
+ assert(m);
+
+ f = fopen(fn, "re");
+ if (!f) {
+ if (errno == ENOENT)
+ return 0;
+
+ log_warning("Failed to open configuration file %s: %m", fn);
+ return -errno;
+ }
+
+ r = config_parse(NULL, fn, f, "Login\0", config_item_perf_lookup,
+ (void*) logind_gperf_lookup, false, false, m);
+ if (r < 0)
+ log_warning("Failed to parse configuration file: %s", strerror(-r));
+
+ return r;
+}
+
+int main(int argc, char *argv[]) {
+ Manager *m = NULL;
+ int r;
+
+ log_set_target(LOG_TARGET_AUTO);
+ log_set_facility(LOG_AUTH);
+ log_parse_environment();
+ log_open();
+
+ umask(0022);
+
+ if (argc != 1) {
+ log_error("This program takes no arguments.");
+ r = -EINVAL;
+ goto finish;
+ }
+
+ /* Always create the directories people can create inotify
+ * watches in. Note that some applications might check for the
+ * existence of /run/systemd/seats/ to determine whether
+ * logind is available, so please always make sure this check
+ * stays in. */
+ mkdir_label("/run/systemd/seats", 0755);
+ mkdir_label("/run/systemd/users", 0755);
+ mkdir_label("/run/systemd/sessions", 0755);
+
+ m = manager_new();
+ if (!m) {
+ r = log_oom();
+ goto finish;
+ }
+
+ manager_parse_config_file(m);
+
+ r = manager_startup(m);
+ if (r < 0) {
+ log_error("Failed to fully start up daemon: %s", strerror(-r));
+ goto finish;
+ }
+
+ log_debug("systemd-logind running as pid %lu", (unsigned long) getpid());
+
+ sd_notify(false,
+ "READY=1\n"
+ "STATUS=Processing requests...");
+
+ r = manager_run(m);
+
+ log_debug("systemd-logind stopped as pid %lu", (unsigned long) getpid());
+
+finish:
+ sd_notify(false,
+ "STATUS=Shutting down...");
+
+ if (m)
+ manager_free(m);
+
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/src/login/logind.conf b/src/login/logind.conf
new file mode 100644
index 0000000000..0861d73e0b
--- /dev/null
+++ b/src/login/logind.conf
@@ -0,0 +1,28 @@
+# This file is part of systemd.
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 of the License, or
+# (at your option) any later version.
+#
+# See logind.conf(5) for details
+
+[Login]
+#NAutoVTs=6
+#ReserveVT=6
+#KillUserProcesses=no
+#KillOnlyUsers=
+#KillExcludeUsers=root
+#Controllers=
+#ResetControllers=cpu
+#InhibitDelayMaxSec=5
+#HandlePowerKey=poweroff
+#HandleSuspendKey=suspend
+#HandleHibernateKey=hibernate
+#HandleLidSwitch=suspend
+#PowerKeyIgnoreInhibited=no
+#SuspendKeyIgnoreInhibited=no
+#HibernateKeyIgnoreInhibited=no
+#LidSwitchIgnoreInhibited=yes
+#IdleAction=ignore
+#IdleActionSec=30min
diff --git a/src/login/logind.h b/src/login/logind.h
new file mode 100644
index 0000000000..904dc20467
--- /dev/null
+++ b/src/login/logind.h
@@ -0,0 +1,189 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdbool.h>
+#include <inttypes.h>
+#include <dbus/dbus.h>
+#include <libudev.h>
+
+#include "util.h"
+#include "audit.h"
+#include "list.h"
+#include "hashmap.h"
+#include "cgroup-util.h"
+
+typedef struct Manager Manager;
+
+#include "logind-device.h"
+#include "logind-seat.h"
+#include "logind-session.h"
+#include "logind-user.h"
+#include "logind-inhibit.h"
+#include "logind-button.h"
+#include "logind-action.h"
+
+struct Manager {
+ DBusConnection *bus;
+
+ Hashmap *devices;
+ Hashmap *seats;
+ Hashmap *sessions;
+ Hashmap *users;
+ Hashmap *inhibitors;
+ Hashmap *buttons;
+
+ LIST_HEAD(Seat, seat_gc_queue);
+ LIST_HEAD(Session, session_gc_queue);
+ LIST_HEAD(User, user_gc_queue);
+
+ struct udev *udev;
+ struct udev_monitor *udev_seat_monitor, *udev_vcsa_monitor, *udev_button_monitor;
+
+ int udev_seat_fd;
+ int udev_vcsa_fd;
+ int udev_button_fd;
+
+ int console_active_fd;
+ int bus_fd;
+ int epoll_fd;
+
+ unsigned n_autovts;
+
+ unsigned reserve_vt;
+ int reserve_vt_fd;
+
+ Seat *vtconsole;
+
+ char *cgroup_path;
+ char **controllers, **reset_controllers;
+
+ char **kill_only_users, **kill_exclude_users;
+
+ bool kill_user_processes;
+
+ unsigned long session_counter;
+ unsigned long inhibit_counter;
+
+ Hashmap *session_cgroups;
+ Hashmap *user_cgroups;
+
+ Hashmap *session_fds;
+ Hashmap *inhibitor_fds;
+ Hashmap *button_fds;
+
+ usec_t inhibit_delay_max;
+
+ /* If an action is currently being executed or is delayed,
+ * this is != 0 and encodes what is being done */
+ InhibitWhat action_what;
+
+ /* If a shutdown/suspend was delayed due to a inhibitor this
+ contains the unit name we are supposed to start after the
+ delay is over */
+ const char *action_unit;
+
+ /* If a shutdown/suspend is currently executed, then this is
+ * the job of it */
+ char *action_job;
+ usec_t action_timestamp;
+
+ int idle_action_fd; /* the timer_fd */
+ usec_t idle_action_usec;
+ usec_t idle_action_not_before_usec;
+ HandleAction idle_action;
+
+ HandleAction handle_power_key;
+ HandleAction handle_suspend_key;
+ HandleAction handle_hibernate_key;
+ HandleAction handle_lid_switch;
+
+ bool power_key_ignore_inhibited;
+ bool suspend_key_ignore_inhibited;
+ bool hibernate_key_ignore_inhibited;
+ bool lid_switch_ignore_inhibited;
+};
+
+enum {
+ FD_SEAT_UDEV,
+ FD_VCSA_UDEV,
+ FD_BUTTON_UDEV,
+ FD_CONSOLE,
+ FD_BUS,
+ FD_IDLE_ACTION,
+ FD_OTHER_BASE
+};
+
+Manager *manager_new(void);
+void manager_free(Manager *m);
+
+int manager_add_device(Manager *m, const char *sysfs, Device **_device);
+int manager_add_button(Manager *m, const char *name, Button **_button);
+int manager_add_seat(Manager *m, const char *id, Seat **_seat);
+int manager_add_session(Manager *m, User *u, const char *id, Session **_session);
+int manager_add_user(Manager *m, uid_t uid, gid_t gid, const char *name, User **_user);
+int manager_add_user_by_name(Manager *m, const char *name, User **_user);
+int manager_add_user_by_uid(Manager *m, uid_t uid, User **_user);
+int manager_add_inhibitor(Manager *m, const char* id, Inhibitor **_inhibitor);
+
+int manager_process_seat_device(Manager *m, struct udev_device *d);
+int manager_process_button_device(Manager *m, struct udev_device *d);
+
+int manager_dispatch_seat_udev(Manager *m);
+int manager_dispatch_vcsa_udev(Manager *m);
+int manager_dispatch_button_udev(Manager *m);
+int manager_dispatch_console(Manager *m);
+int manager_dispatch_idle_action(Manager *m);
+
+int manager_enumerate_devices(Manager *m);
+int manager_enumerate_buttons(Manager *m);
+int manager_enumerate_seats(Manager *m);
+int manager_enumerate_sessions(Manager *m);
+int manager_enumerate_users(Manager *m);
+int manager_enumerate_inhibitors(Manager *m);
+
+int manager_startup(Manager *m);
+int manager_run(Manager *m);
+int manager_spawn_autovt(Manager *m, int vtnr);
+
+void manager_cgroup_notify_empty(Manager *m, const char *cgroup);
+
+void manager_gc(Manager *m, bool drop_not_started);
+
+int manager_get_idle_hint(Manager *m, dual_timestamp *t);
+
+int manager_get_user_by_cgroup(Manager *m, const char *cgroup, User **user);
+int manager_get_session_by_cgroup(Manager *m, const char *cgroup, Session **session);
+int manager_get_session_by_pid(Manager *m, pid_t pid, Session **session);
+
+extern const DBusObjectPathVTable bus_manager_vtable;
+
+DBusHandlerResult bus_message_filter(DBusConnection *c, DBusMessage *message, void *userdata);
+
+int bus_manager_shutdown_or_sleep_now_or_later(Manager *m, const char *unit_name, InhibitWhat w, DBusError *error);
+
+int manager_send_changed(Manager *manager, const char *properties);
+
+int manager_dispatch_delayed(Manager *manager);
+
+/* gperf lookup function */
+const struct ConfigPerfItem* logind_gperf_lookup(const char *key, unsigned length);
diff --git a/src/login/multi-seat-x.c b/src/login/multi-seat-x.c
new file mode 100644
index 0000000000..83760d4191
--- /dev/null
+++ b/src/login/multi-seat-x.c
@@ -0,0 +1,108 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <string.h>
+#include <unistd.h>
+
+#include "util.h"
+#include "mkdir.h"
+
+int main(int argc, char *argv[]) {
+
+ int i;
+ const char *seat = NULL;
+ char **new_argv;
+ _cleanup_free_ char *path = NULL;
+ int r;
+ _cleanup_fclose_ FILE *f = NULL;
+
+ /* This binary will go away as soon as X natively takes the
+ * arguments in question as command line parameters, instead
+ * of requiring them in the configuration file. */
+
+ /* If this file is removed, don't forget to remove the code
+ * that invokes this in gdm and other display managers. */
+
+ for (i = 1; i < argc; i++)
+ if (streq(argv[i], "-seat"))
+ seat = argv[i+1];
+
+ if (isempty(seat) || streq(seat, "seat0")) {
+ argv[0] = (char*) X_SERVER;
+ execv(X_SERVER, argv);
+ log_error("Failed to execute real X server: %m");
+ goto fail;
+ }
+
+ r = mkdir_safe_label("/run/systemd/multi-session-x", 0755, 0, 0);
+ if (r < 0) {
+ log_error("Failed to create directory: %s", strerror(-r));
+ goto fail;
+ }
+
+ path = strappend("/run/systemd/multi-session-x/", seat);
+ if (!path) {
+ log_oom();
+ goto fail;
+ }
+
+ f = fopen(path, "we");
+ if (!f) {
+ log_error("Failed to write configuration file: %m");
+ goto fail;
+ }
+
+ fprintf(f,
+ "Section \"ServerFlags\"\n"
+ " Option \"AutoAddDevices\" \"True\"\n"
+ " Option \"AllowEmptyInput\" \"True\"\n"
+ " Option \"DontVTSwitch\" \"True\"\n"
+ "EndSection\n"
+ "Section \"InputClass\"\n"
+ " Identifier \"Force Input Devices to Seat\"\n"
+ " Option \"GrabDevice\" \"True\"\n"
+ "EndSection\n");
+
+ fflush(f);
+
+ if (ferror(f)) {
+ log_error("Failed to write configuration file: %m");
+ goto fail;
+ }
+
+ fclose(f);
+ f = NULL;
+
+ new_argv = newa(char*, argc + 3 + 1);
+ memcpy(new_argv, argv, sizeof(char*) * (argc + 2 + 1));
+
+ new_argv[0] = (char*) X_SERVER;
+ new_argv[argc+0] = (char*) "-config";
+ new_argv[argc+1] = path;
+ new_argv[argc+2] = (char*) "-sharevts";
+ new_argv[argc+3] = NULL;
+
+ execv(X_SERVER, new_argv);
+ log_error("Failed to execute real X server: %m");
+
+fail:
+ return EXIT_FAILURE;
+}
diff --git a/src/login/org.freedesktop.login1.conf b/src/login/org.freedesktop.login1.conf
new file mode 100644
index 0000000000..6c1f2f57e5
--- /dev/null
+++ b/src/login/org.freedesktop.login1.conf
@@ -0,0 +1,150 @@
+<?xml version="1.0"?> <!--*-nxml-*-->
+<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
+ "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
+
+<!--
+ This file is part of systemd.
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+-->
+
+<busconfig>
+
+ <policy user="root">
+ <allow own="org.freedesktop.login1"/>
+ <allow send_destination="org.freedesktop.login1"/>
+ <allow receive_sender="org.freedesktop.login1"/>
+ </policy>
+
+ <policy context="default">
+ <deny send_destination="org.freedesktop.login1"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.DBus.Introspectable"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.DBus.Peer"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.DBus.Properties"
+ send_member="Get"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.DBus.Properties"
+ send_member="GetAll"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="GetSession"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="GetSessionByPID"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="GetUser"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="GetSeat"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="ListSessions"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="ListUsers"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="ListSeats"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="ListInhibitors"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="Inhibit"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="SetUserLinger"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="ActivateSession"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="ActivateSessionOnSeat"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="PowerOff"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="Reboot"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="Suspend"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="Hibernate"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="HybridSleep"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="CanPowerOff"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="CanReboot"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="CanSuspend"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="CanHibernate"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="CanHybridSleep"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="AttachDevice"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="FlushDevices"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Seat"
+ send_member="ActivateSession"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Session"
+ send_member="Activate"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Session"
+ send_member="SetIdleHint"/>
+
+ <allow receive_sender="org.freedesktop.login1"/>
+ </policy>
+
+</busconfig>
diff --git a/src/login/org.freedesktop.login1.policy.in b/src/login/org.freedesktop.login1.policy.in
new file mode 100644
index 0000000000..0c551d4f9b
--- /dev/null
+++ b/src/login/org.freedesktop.login1.policy.in
@@ -0,0 +1,273 @@
+<?xml version="1.0" encoding="UTF-8"?> <!--*-nxml-*-->
+<!DOCTYPE policyconfig PUBLIC "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
+ "http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd">
+
+<!--
+ This file is part of systemd.
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+-->
+
+<policyconfig>
+
+ <vendor>The systemd Project</vendor>
+ <vendor_url>http://www.freedesktop.org/wiki/Software/systemd</vendor_url>
+
+ <action id="org.freedesktop.login1.inhibit-block-shutdown">
+ <_description>Allow applications to inhibit system shutdown</_description>
+ <_message>Authentication is required to allow an application to inhibit system shutdown.</_message>
+ <defaults>
+ <allow_any>no</allow_any>
+ <allow_inactive>yes</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.inhibit-delay-shutdown org.freedesktop.login1.inhibit-block-sleep org.freedesktop.login1.inhibit-delay-sleep org.freedesktop.login1.inhibit-block-idle</annotate>
+ </action>
+
+ <action id="org.freedesktop.login1.inhibit-delay-shutdown">
+ <_description>Allow applications to delay system shutdown</_description>
+ <_message>Authentication is required to allow an application to delay system shutdown.</_message>
+ <defaults>
+ <allow_any>yes</allow_any>
+ <allow_inactive>yes</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.inhibit-delay-sleep</annotate>
+ </action>
+
+ <action id="org.freedesktop.login1.inhibit-block-sleep">
+ <_description>Allow applications to inhibit system sleep</_description>
+ <_message>Authentication is required to allow an application to inhibit system sleep.</_message>
+ <defaults>
+ <allow_any>no</allow_any>
+ <allow_inactive>yes</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.inhibit-delay-sleep org.freedesktop.login1.inhibit-block-idle</annotate>
+ </action>
+
+ <action id="org.freedesktop.login1.inhibit-delay-sleep">
+ <_description>Allow applications to delay system sleep</_description>
+ <_message>Authentication is required to allow an application to delay system sleep.</_message>
+ <defaults>
+ <allow_any>yes</allow_any>
+ <allow_inactive>yes</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ </action>
+
+ <action id="org.freedesktop.login1.inhibit-block-idle">
+ <_description>Allow applications to inhibit automatic system suspend</_description>
+ <_message>Authentication is required to allow an application to inhibit automatic system suspend.</_message>
+ <defaults>
+ <allow_any>yes</allow_any>
+ <allow_inactive>yes</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ </action>
+
+ <action id="org.freedesktop.login1.inhibit-handle-power-key">
+ <_description>Allow applications to inhibit system handling of the power key</_description>
+ <_message>Authentication is required to allow an application to inhibit system handling of the power key.</_message>
+ <defaults>
+ <allow_any>no</allow_any>
+ <allow_inactive>yes</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.inhibit-handle-suspend-key org.freedesktop.login1.inhibit-handle-hibernate-key org.freedesktop.login1.inhibit-handle-lid-switch</annotate>
+ </action>
+
+ <action id="org.freedesktop.login1.inhibit-handle-suspend-key">
+ <_description>Allow applications to inhibit system handling of the suspend key</_description>
+ <_message>Authentication is required to allow an application to inhibit system handling of the suspend key.</_message>
+ <defaults>
+ <allow_any>no</allow_any>
+ <allow_inactive>yes</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.inhibit-handle-hibernate-key org.freedesktop.login1.inhibit-handle-lid-switch</annotate>
+ </action>
+
+ <action id="org.freedesktop.login1.inhibit-handle-hibernate-key">
+ <_description>Allow applications to inhibit system handling of the hibernate key</_description>
+ <_message>Authentication is required to allow an application to inhibit system handling of the hibernate key.</_message>
+ <defaults>
+ <allow_any>no</allow_any>
+ <allow_inactive>yes</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ </action>
+
+ <action id="org.freedesktop.login1.inhibit-handle-lid-switch">
+ <_description>Allow applications to inhibit system handling of the lid switch</_description>
+ <_message>Authentication is required to allow an application to inhibit system handling of the lid switch.</_message>
+ <defaults>
+ <allow_any>no</allow_any>
+ <allow_inactive>yes</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ </action>
+
+ <action id="org.freedesktop.login1.set-user-linger">
+ <_description>Allow non-logged-in users to run programs</_description>
+ <_message>Authentication is required to allow a non-logged-in user to run programs.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ </action>
+
+ <action id="org.freedesktop.login1.attach-device">
+ <_description>Allow attaching devices to seats</_description>
+ <_message>Authentication is required for attaching a device to a seat.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.flush-devices</annotate>
+ </action>
+
+ <action id="org.freedesktop.login1.flush-devices">
+ <_description>Flush device to seat attachments</_description>
+ <_message>Authentication is required for resetting how devices are attached to seats.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ </action>
+
+ <action id="org.freedesktop.login1.power-off">
+ <_description>Power off the system</_description>
+ <_message>Authentication is required for powering off the system.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ </action>
+
+ <action id="org.freedesktop.login1.power-off-multiple-sessions">
+ <_description>Power off the system while other users are logged in</_description>
+ <_message>Authentication is required for powering off the system while other users are logged in.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.power-off</annotate>
+ </action>
+
+ <action id="org.freedesktop.login1.power-off-ignore-inhibit">
+ <_description>Power off the system while an application asked to inhibit it</_description>
+ <_message>Authentication is required for powering off the system while an application asked to inhibit it.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.power-off</annotate>
+ </action>
+
+ <action id="org.freedesktop.login1.reboot">
+ <_description>Reboot the system</_description>
+ <_message>Authentication is required for rebooting the system.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ </action>
+
+ <action id="org.freedesktop.login1.reboot-multiple-sessions">
+ <_description>Reboot the system while other users are logged in</_description>
+ <_message>Authentication is required for rebooting the system while other users are logged in.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.reboot</annotate>
+ </action>
+
+ <action id="org.freedesktop.login1.reboot-ignore-inhibit">
+ <_description>Reboot the system while an application asked to inhibit it</_description>
+ <_message>Authentication is required for rebooting the system while an application asked to inhibit it.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.reboot</annotate>
+ </action>
+
+ <action id="org.freedesktop.login1.suspend">
+ <_description>Suspend the system</_description>
+ <_message>Authentication is required for suspending the system.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ </action>
+
+ <action id="org.freedesktop.login1.suspend-multiple-sessions">
+ <_description>Suspend the system while other users are logged in</_description>
+ <_message>Authentication is required for suspending the system while other users are logged in.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.suspend</annotate>
+ </action>
+
+ <action id="org.freedesktop.login1.suspend-ignore-inhibit">
+ <_description>Suspend the system while an application asked to inhibit it</_description>
+ <_message>Authentication is required for suspending the system while an application asked to inhibit it.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.suspend</annotate>
+ </action>
+
+ <action id="org.freedesktop.login1.hibernate">
+ <_description>Hibernate the system</_description>
+ <_message>Authentication is required for hibernating the system.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ </action>
+
+ <action id="org.freedesktop.login1.hibernate-multiple-sessions">
+ <_description>Hibernate the system while other users are logged in</_description>
+ <_message>Authentication is required for hibernating the system while other users are logged in.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.hibernate</annotate>
+ </action>
+
+ <action id="org.freedesktop.login1.hibernate-ignore-inhibit">
+ <_description>Hibernate the system while an application asked to inhibit it</_description>
+ <_message>Authentication is required for hibernating the system while an application asked to inhibit it.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.hibernate</annotate>
+ </action>
+
+</policyconfig>
diff --git a/src/login/org.freedesktop.login1.service b/src/login/org.freedesktop.login1.service
new file mode 100644
index 0000000000..762dae2bb3
--- /dev/null
+++ b/src/login/org.freedesktop.login1.service
@@ -0,0 +1,12 @@
+# This file is part of systemd.
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 of the License, or
+# (at your option) any later version.
+
+[D-BUS Service]
+Name=org.freedesktop.login1
+Exec=/bin/false
+User=root
+SystemdService=dbus-org.freedesktop.login1.service
diff --git a/src/login/pam-module.c b/src/login/pam-module.c
new file mode 100644
index 0000000000..13290fd8ea
--- /dev/null
+++ b/src/login/pam-module.c
@@ -0,0 +1,723 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <fcntl.h>
+#include <sys/file.h>
+#include <pwd.h>
+#include <endian.h>
+#include <sys/capability.h>
+
+#include <security/pam_modules.h>
+#include <security/_pam_macros.h>
+#include <security/pam_modutil.h>
+#include <security/pam_ext.h>
+#include <security/pam_misc.h>
+
+#include "util.h"
+#include "audit.h"
+#include "macro.h"
+#include "strv.h"
+#include "dbus-common.h"
+#include "def.h"
+#include "socket-util.h"
+#include "fileio.h"
+
+static int parse_argv(pam_handle_t *handle,
+ int argc, const char **argv,
+ char ***controllers,
+ char ***reset_controllers,
+ bool *kill_processes,
+ char ***kill_only_users,
+ char ***kill_exclude_users,
+ const char **class,
+ bool *debug) {
+
+ unsigned i;
+
+ assert(argc >= 0);
+ assert(argc == 0 || argv);
+
+ for (i = 0; i < (unsigned) argc; i++) {
+ int k;
+
+ if (startswith(argv[i], "kill-session-processes=")) {
+ if ((k = parse_boolean(argv[i] + 23)) < 0) {
+ pam_syslog(handle, LOG_ERR, "Failed to parse kill-session-processes= argument.");
+ return k;
+ }
+
+ if (kill_processes)
+ *kill_processes = k;
+
+ } else if (startswith(argv[i], "kill-session=")) {
+ /* As compatibility for old versions */
+
+ if ((k = parse_boolean(argv[i] + 13)) < 0) {
+ pam_syslog(handle, LOG_ERR, "Failed to parse kill-session= argument.");
+ return k;
+ }
+
+ if (kill_processes)
+ *kill_processes = k;
+
+ } else if (startswith(argv[i], "controllers=")) {
+
+ if (controllers) {
+ char **l;
+
+ if (!(l = strv_split(argv[i] + 12, ","))) {
+ pam_syslog(handle, LOG_ERR, "Out of memory.");
+ return -ENOMEM;
+ }
+
+ strv_free(*controllers);
+ *controllers = l;
+ }
+
+ } else if (startswith(argv[i], "reset-controllers=")) {
+
+ if (reset_controllers) {
+ char **l;
+
+ if (!(l = strv_split(argv[i] + 18, ","))) {
+ pam_syslog(handle, LOG_ERR, "Out of memory.");
+ return -ENOMEM;
+ }
+
+ strv_free(*reset_controllers);
+ *reset_controllers = l;
+ }
+
+ } else if (startswith(argv[i], "kill-only-users=")) {
+
+ if (kill_only_users) {
+ char **l;
+
+ if (!(l = strv_split(argv[i] + 16, ","))) {
+ pam_syslog(handle, LOG_ERR, "Out of memory.");
+ return -ENOMEM;
+ }
+
+ strv_free(*kill_only_users);
+ *kill_only_users = l;
+ }
+
+ } else if (startswith(argv[i], "kill-exclude-users=")) {
+
+ if (kill_exclude_users) {
+ char **l;
+
+ if (!(l = strv_split(argv[i] + 19, ","))) {
+ pam_syslog(handle, LOG_ERR, "Out of memory.");
+ return -ENOMEM;
+ }
+
+ strv_free(*kill_exclude_users);
+ *kill_exclude_users = l;
+ }
+
+ } else if (startswith(argv[i], "class=")) {
+
+ if (class)
+ *class = argv[i] + 6;
+
+ } else if (startswith(argv[i], "debug=")) {
+ if ((k = parse_boolean(argv[i] + 6)) < 0) {
+ pam_syslog(handle, LOG_ERR, "Failed to parse debug= argument.");
+ return k;
+ }
+
+ if (debug)
+ *debug = k;
+
+ } else if (startswith(argv[i], "create-session=") ||
+ startswith(argv[i], "kill-user=")) {
+
+ pam_syslog(handle, LOG_WARNING, "Option %s not supported anymore, ignoring.", argv[i]);
+
+ } else {
+ pam_syslog(handle, LOG_ERR, "Unknown parameter '%s'.", argv[i]);
+ return -EINVAL;
+ }
+ }
+
+ return 0;
+}
+
+static int get_user_data(
+ pam_handle_t *handle,
+ const char **ret_username,
+ struct passwd **ret_pw) {
+
+ const char *username = NULL;
+ struct passwd *pw = NULL;
+ uid_t uid;
+ int r;
+
+ assert(handle);
+ assert(ret_username);
+ assert(ret_pw);
+
+ r = audit_loginuid_from_pid(0, &uid);
+ if (r >= 0)
+ pw = pam_modutil_getpwuid(handle, uid);
+ else {
+ r = pam_get_user(handle, &username, NULL);
+ if (r != PAM_SUCCESS) {
+ pam_syslog(handle, LOG_ERR, "Failed to get user name.");
+ return r;
+ }
+
+ if (isempty(username)) {
+ pam_syslog(handle, LOG_ERR, "User name not valid.");
+ return PAM_AUTH_ERR;
+ }
+
+ pw = pam_modutil_getpwnam(handle, username);
+ }
+
+ if (!pw) {
+ pam_syslog(handle, LOG_ERR, "Failed to get user data.");
+ return PAM_USER_UNKNOWN;
+ }
+
+ *ret_pw = pw;
+ *ret_username = username ? username : pw->pw_name;
+
+ return PAM_SUCCESS;
+}
+
+static bool check_user_lists(
+ pam_handle_t *handle,
+ uid_t uid,
+ char **kill_only_users,
+ char **kill_exclude_users) {
+
+ const char *name = NULL;
+ char **l;
+
+ assert(handle);
+
+ if (uid == 0)
+ name = "root"; /* Avoid obvious NSS requests, to suppress network traffic */
+ else {
+ struct passwd *pw;
+
+ pw = pam_modutil_getpwuid(handle, uid);
+ if (pw)
+ name = pw->pw_name;
+ }
+
+ STRV_FOREACH(l, kill_exclude_users) {
+ uid_t u;
+
+ if (parse_uid(*l, &u) >= 0)
+ if (u == uid)
+ return false;
+
+ if (name && streq(name, *l))
+ return false;
+ }
+
+ if (strv_isempty(kill_only_users))
+ return true;
+
+ STRV_FOREACH(l, kill_only_users) {
+ uid_t u;
+
+ if (parse_uid(*l, &u) >= 0)
+ if (u == uid)
+ return true;
+
+ if (name && streq(name, *l))
+ return true;
+ }
+
+ return false;
+}
+
+static int get_seat_from_display(const char *display, const char **seat, uint32_t *vtnr) {
+ _cleanup_free_ char *p = NULL;
+ int r;
+ _cleanup_close_ int fd = -1;
+ union sockaddr_union sa = {
+ .un.sun_family = AF_UNIX,
+ };
+ struct ucred ucred;
+ socklen_t l;
+ _cleanup_free_ char *tty = NULL;
+ int v;
+
+ assert(display);
+ assert(vtnr);
+
+ /* We deduce the X11 socket from the display name, then use
+ * SO_PEERCRED to determine the X11 server process, ask for
+ * the controlling tty of that and if it's a VC then we know
+ * the seat and the virtual terminal. Sounds ugly, is only
+ * semi-ugly. */
+
+ r = socket_from_display(display, &p);
+ if (r < 0)
+ return r;
+ strncpy(sa.un.sun_path, p, sizeof(sa.un.sun_path)-1);
+
+ fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0);
+ if (fd < 0)
+ return -errno;
+
+ if (connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + strlen(sa.un.sun_path)) < 0)
+ return -errno;
+
+ l = sizeof(ucred);
+ r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &ucred, &l);
+ if (r < 0)
+ return -errno;
+
+ r = get_ctty(ucred.pid, NULL, &tty);
+ if (r < 0)
+ return r;
+
+ v = vtnr_from_tty(tty);
+ if (v < 0)
+ return v;
+ else if (v == 0)
+ return -ENOENT;
+
+ if (seat)
+ *seat = "seat0";
+ *vtnr = (uint32_t) v;
+
+ return 0;
+}
+
+_public_ PAM_EXTERN int pam_sm_open_session(
+ pam_handle_t *handle,
+ int flags,
+ int argc, const char **argv) {
+
+ struct passwd *pw;
+ bool kill_processes = false, debug = false;
+ const char *username, *id, *object_path, *runtime_path, *service = NULL, *tty = NULL, *display = NULL, *remote_user = NULL, *remote_host = NULL, *seat = NULL, *type = NULL, *class = NULL, *class_pam = NULL, *cvtnr = NULL;
+ char **controllers = NULL, **reset_controllers = NULL, **kill_only_users = NULL, **kill_exclude_users = NULL;
+ DBusError error;
+ uint32_t uid, pid;
+ DBusMessageIter iter;
+ dbus_bool_t kp;
+ int session_fd = -1;
+ DBusConnection *bus = NULL;
+ DBusMessage *m = NULL, *reply = NULL;
+ dbus_bool_t remote, existing;
+ int r;
+ uint32_t vtnr = 0;
+
+ assert(handle);
+
+ dbus_error_init(&error);
+
+ /* pam_syslog(handle, LOG_INFO, "pam-systemd initializing"); */
+
+ /* Make this a NOP on non-logind systems */
+ if (!logind_running())
+ return PAM_SUCCESS;
+
+ if (parse_argv(handle,
+ argc, argv,
+ &controllers, &reset_controllers,
+ &kill_processes, &kill_only_users, &kill_exclude_users,
+ &class_pam, &debug) < 0) {
+ r = PAM_SESSION_ERR;
+ goto finish;
+ }
+
+ r = get_user_data(handle, &username, &pw);
+ if (r != PAM_SUCCESS)
+ goto finish;
+
+ /* Make sure we don't enter a loop by talking to
+ * systemd-logind when it is actually waiting for the
+ * background to finish start-up. If the service is
+ * "systemd-shared" we simply set XDG_RUNTIME_DIR and
+ * leave. */
+
+ pam_get_item(handle, PAM_SERVICE, (const void**) &service);
+ if (streq_ptr(service, "systemd-shared")) {
+ char *p, *rt = NULL;
+
+ if (asprintf(&p, "/run/systemd/users/%lu", (unsigned long) pw->pw_uid) < 0) {
+ r = PAM_BUF_ERR;
+ goto finish;
+ }
+
+ r = parse_env_file(p, NEWLINE,
+ "RUNTIME", &rt,
+ NULL);
+ free(p);
+
+ if (r < 0 && r != -ENOENT) {
+ r = PAM_SESSION_ERR;
+ free(rt);
+ goto finish;
+ }
+
+ if (rt) {
+ r = pam_misc_setenv(handle, "XDG_RUNTIME_DIR", rt, 0);
+ free(rt);
+
+ if (r != PAM_SUCCESS) {
+ pam_syslog(handle, LOG_ERR, "Failed to set runtime dir.");
+ goto finish;
+ }
+ }
+
+ r = PAM_SUCCESS;
+ goto finish;
+ }
+
+ if (kill_processes)
+ kill_processes = check_user_lists(handle, pw->pw_uid, kill_only_users, kill_exclude_users);
+
+ dbus_connection_set_change_sigpipe(FALSE);
+
+ bus = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error);
+ if (!bus) {
+ pam_syslog(handle, LOG_ERR, "Failed to connect to system bus: %s", bus_error_message(&error));
+ r = PAM_SESSION_ERR;
+ goto finish;
+ }
+
+ m = dbus_message_new_method_call(
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "CreateSession");
+ if (!m) {
+ pam_syslog(handle, LOG_ERR, "Could not allocate create session message.");
+ r = PAM_BUF_ERR;
+ goto finish;
+ }
+
+ uid = pw->pw_uid;
+ pid = getpid();
+
+ pam_get_item(handle, PAM_XDISPLAY, (const void**) &display);
+ pam_get_item(handle, PAM_TTY, (const void**) &tty);
+ pam_get_item(handle, PAM_RUSER, (const void**) &remote_user);
+ pam_get_item(handle, PAM_RHOST, (const void**) &remote_host);
+
+ seat = pam_getenv(handle, "XDG_SEAT");
+ if (isempty(seat))
+ seat = getenv("XDG_SEAT");
+
+ cvtnr = pam_getenv(handle, "XDG_VTNR");
+ if (isempty(cvtnr))
+ cvtnr = getenv("XDG_VTNR");
+
+ service = strempty(service);
+ tty = strempty(tty);
+ display = strempty(display);
+ remote_user = strempty(remote_user);
+ remote_host = strempty(remote_host);
+ seat = strempty(seat);
+
+ if (strchr(tty, ':')) {
+ /* A tty with a colon is usually an X11 display,
+ * placed there to show up in utmp. We rearrange
+ * things and don't pretend that an X display was a
+ * tty. */
+
+ if (isempty(display))
+ display = tty;
+ tty = "";
+ } else if (streq(tty, "cron")) {
+ /* cron has been setting PAM_TTY to "cron" for a very
+ * long time and it probably shouldn't stop doing that
+ * for compatibility reasons. */
+ tty = "";
+ type = "unspecified";
+ } else if (streq(tty, "ssh")) {
+ /* ssh has been setting PAM_TTY to "ssh" for a very
+ * long time and probably shouldn't stop doing that
+ * for compatibility reasons. */
+ tty = "";
+ type ="tty";
+ }
+
+ /* If this fails vtnr will be 0, that's intended */
+ if (!isempty(cvtnr))
+ safe_atou32(cvtnr, &vtnr);
+
+ if (!isempty(display) && vtnr <= 0) {
+ if (isempty(seat))
+ get_seat_from_display(display, &seat, &vtnr);
+ else if (streq(seat, "seat0"))
+ get_seat_from_display(display, NULL, &vtnr);
+ }
+
+ if (!type)
+ type = !isempty(display) ? "x11" :
+ !isempty(tty) ? "tty" : "unspecified";
+
+ class = pam_getenv(handle, "XDG_SESSION_CLASS");
+ if (isempty(class))
+ class = getenv("XDG_SESSION_CLASS");
+ if (isempty(class))
+ class = class_pam;
+ if (isempty(class))
+ class = streq(type, "unspecified") ? "background" : "user";
+
+ remote = !isempty(remote_host) &&
+ !streq(remote_host, "localhost") &&
+ !streq(remote_host, "localhost.localdomain");
+
+ if (!dbus_message_append_args(m,
+ DBUS_TYPE_UINT32, &uid,
+ DBUS_TYPE_UINT32, &pid,
+ DBUS_TYPE_STRING, &service,
+ DBUS_TYPE_STRING, &type,
+ DBUS_TYPE_STRING, &class,
+ DBUS_TYPE_STRING, &seat,
+ DBUS_TYPE_UINT32, &vtnr,
+ DBUS_TYPE_STRING, &tty,
+ DBUS_TYPE_STRING, &display,
+ DBUS_TYPE_BOOLEAN, &remote,
+ DBUS_TYPE_STRING, &remote_user,
+ DBUS_TYPE_STRING, &remote_host,
+ DBUS_TYPE_INVALID)) {
+ pam_syslog(handle, LOG_ERR, "Could not attach parameters to message.");
+ r = PAM_BUF_ERR;
+ goto finish;
+ }
+
+ dbus_message_iter_init_append(m, &iter);
+
+ r = bus_append_strv_iter(&iter, controllers);
+ if (r < 0) {
+ pam_syslog(handle, LOG_ERR, "Could not attach parameter to message.");
+ r = PAM_BUF_ERR;
+ goto finish;
+ }
+
+ r = bus_append_strv_iter(&iter, reset_controllers);
+ if (r < 0) {
+ pam_syslog(handle, LOG_ERR, "Could not attach parameter to message.");
+ r = PAM_BUF_ERR;
+ goto finish;
+ }
+
+ kp = kill_processes;
+ if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &kp)) {
+ pam_syslog(handle, LOG_ERR, "Could not attach parameter to message.");
+ r = PAM_BUF_ERR;
+ goto finish;
+ }
+
+ if (debug)
+ pam_syslog(handle, LOG_DEBUG, "Asking logind to create session: "
+ "uid=%u pid=%u service=%s type=%s class=%s seat=%s vtnr=%u tty=%s display=%s remote=%s remote_user=%s remote_host=%s",
+ uid, pid, service, type, class, seat, vtnr, tty, display, yes_no(remote), remote_user, remote_host);
+
+ reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
+ if (!reply) {
+ pam_syslog(handle, LOG_ERR, "Failed to create session: %s", bus_error_message(&error));
+ r = PAM_SESSION_ERR;
+ goto finish;
+ }
+
+ if (!dbus_message_get_args(reply, &error,
+ DBUS_TYPE_STRING, &id,
+ DBUS_TYPE_OBJECT_PATH, &object_path,
+ DBUS_TYPE_STRING, &runtime_path,
+ DBUS_TYPE_UNIX_FD, &session_fd,
+ DBUS_TYPE_STRING, &seat,
+ DBUS_TYPE_UINT32, &vtnr,
+ DBUS_TYPE_BOOLEAN, &existing,
+ DBUS_TYPE_INVALID)) {
+ pam_syslog(handle, LOG_ERR, "Failed to parse message: %s", bus_error_message(&error));
+ r = PAM_SESSION_ERR;
+ goto finish;
+ }
+
+ if (debug)
+ pam_syslog(handle, LOG_DEBUG, "Reply from logind: "
+ "id=%s object_path=%s runtime_path=%s session_fd=%d seat=%s vtnr=%u",
+ id, object_path, runtime_path, session_fd, seat, vtnr);
+
+ r = pam_misc_setenv(handle, "XDG_SESSION_ID", id, 0);
+ if (r != PAM_SUCCESS) {
+ pam_syslog(handle, LOG_ERR, "Failed to set session id.");
+ goto finish;
+ }
+
+ r = pam_misc_setenv(handle, "XDG_RUNTIME_DIR", runtime_path, 0);
+ if (r != PAM_SUCCESS) {
+ pam_syslog(handle, LOG_ERR, "Failed to set runtime dir.");
+ goto finish;
+ }
+
+ if (!isempty(seat)) {
+ r = pam_misc_setenv(handle, "XDG_SEAT", seat, 0);
+ if (r != PAM_SUCCESS) {
+ pam_syslog(handle, LOG_ERR, "Failed to set seat.");
+ goto finish;
+ }
+ }
+
+ if (vtnr > 0) {
+ char buf[11];
+ snprintf(buf, sizeof(buf), "%u", vtnr);
+ char_array_0(buf);
+
+ r = pam_misc_setenv(handle, "XDG_VTNR", buf, 0);
+ if (r != PAM_SUCCESS) {
+ pam_syslog(handle, LOG_ERR, "Failed to set virtual terminal number.");
+ goto finish;
+ }
+ }
+
+ r = pam_set_data(handle, "systemd.existing", INT_TO_PTR(!!existing), NULL);
+ if (r != PAM_SUCCESS) {
+ pam_syslog(handle, LOG_ERR, "Failed to install existing flag.");
+ return r;
+ }
+
+ if (session_fd >= 0) {
+ r = pam_set_data(handle, "systemd.session-fd", INT_TO_PTR(session_fd+1), NULL);
+ if (r != PAM_SUCCESS) {
+ pam_syslog(handle, LOG_ERR, "Failed to install session fd.");
+ return r;
+ }
+ }
+
+ session_fd = -1;
+
+ r = PAM_SUCCESS;
+
+finish:
+ strv_free(controllers);
+ strv_free(reset_controllers);
+ strv_free(kill_only_users);
+ strv_free(kill_exclude_users);
+
+ dbus_error_free(&error);
+
+ if (bus) {
+ dbus_connection_close(bus);
+ dbus_connection_unref(bus);
+ }
+
+ if (m)
+ dbus_message_unref(m);
+
+ if (reply)
+ dbus_message_unref(reply);
+
+ if (session_fd >= 0)
+ close_nointr_nofail(session_fd);
+
+ return r;
+}
+
+_public_ PAM_EXTERN int pam_sm_close_session(
+ pam_handle_t *handle,
+ int flags,
+ int argc, const char **argv) {
+
+ const void *p = NULL, *existing = NULL;
+ const char *id;
+ DBusConnection *bus = NULL;
+ DBusMessage *m = NULL, *reply = NULL;
+ DBusError error;
+ int r;
+
+ assert(handle);
+
+ dbus_error_init(&error);
+
+ /* Only release session if it wasn't pre-existing when we
+ * tried to create it */
+ pam_get_data(handle, "systemd.existing", &existing);
+
+ id = pam_getenv(handle, "XDG_SESSION_ID");
+ if (id && !existing) {
+
+ /* Before we go and close the FIFO we need to tell
+ * logind that this is a clean session shutdown, so
+ * that it doesn't just go and slaughter us
+ * immediately after closing the fd */
+
+ bus = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error);
+ if (!bus) {
+ pam_syslog(handle, LOG_ERR, "Failed to connect to system bus: %s", bus_error_message(&error));
+ r = PAM_SESSION_ERR;
+ goto finish;
+ }
+
+ m = dbus_message_new_method_call(
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "ReleaseSession");
+ if (!m) {
+ pam_syslog(handle, LOG_ERR, "Could not allocate release session message.");
+ r = PAM_BUF_ERR;
+ goto finish;
+ }
+
+ if (!dbus_message_append_args(m,
+ DBUS_TYPE_STRING, &id,
+ DBUS_TYPE_INVALID)) {
+ pam_syslog(handle, LOG_ERR, "Could not attach parameters to message.");
+ r = PAM_BUF_ERR;
+ goto finish;
+ }
+
+ reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
+ if (!reply) {
+ pam_syslog(handle, LOG_ERR, "Failed to release session: %s", bus_error_message(&error));
+ r = PAM_SESSION_ERR;
+ goto finish;
+ }
+ }
+
+ r = PAM_SUCCESS;
+
+finish:
+ pam_get_data(handle, "systemd.session-fd", &p);
+ if (p)
+ close_nointr(PTR_TO_INT(p) - 1);
+
+ dbus_error_free(&error);
+
+ if (bus) {
+ dbus_connection_close(bus);
+ dbus_connection_unref(bus);
+ }
+
+ if (m)
+ dbus_message_unref(m);
+
+ if (reply)
+ dbus_message_unref(reply);
+
+ return r;
+}
diff --git a/src/login/sd-login.c b/src/login/sd-login.c
new file mode 100644
index 0000000000..d0dc42f685
--- /dev/null
+++ b/src/login/sd-login.c
@@ -0,0 +1,762 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <unistd.h>
+#include <string.h>
+#include <errno.h>
+#include <sys/inotify.h>
+#include <sys/poll.h>
+
+#include "util.h"
+#include "cgroup-util.h"
+#include "macro.h"
+#include "sd-login.h"
+#include "strv.h"
+#include "fileio.h"
+
+_public_ int sd_pid_get_session(pid_t pid, char **session) {
+ if (pid < 0)
+ return -EINVAL;
+
+ if (!session)
+ return -EINVAL;
+
+ return cg_pid_get_session(pid, session);
+}
+
+_public_ int sd_pid_get_unit(pid_t pid, char **unit) {
+
+ if (pid < 0)
+ return -EINVAL;
+ if (!unit)
+ return -EINVAL;
+
+ return cg_pid_get_unit(pid, unit);
+}
+
+_public_ int sd_pid_get_user_unit(pid_t pid, char **unit) {
+
+ if (pid < 0)
+ return -EINVAL;
+ if (!unit)
+ return -EINVAL;
+
+ return cg_pid_get_user_unit(pid, unit);
+}
+
+_public_ int sd_pid_get_machine_name(pid_t pid, char **name) {
+
+ if (pid < 0)
+ return -EINVAL;
+ if (!name)
+ return -EINVAL;
+
+ return cg_pid_get_machine_name(pid, name);
+}
+
+_public_ int sd_pid_get_owner_uid(pid_t pid, uid_t *uid) {
+
+ if (pid < 0)
+ return -EINVAL;
+
+ if (!uid)
+ return -EINVAL;
+
+ return cg_pid_get_owner_uid(pid, uid);
+}
+
+_public_ int sd_uid_get_state(uid_t uid, char**state) {
+ char *p, *s = NULL;
+ int r;
+
+ if (!state)
+ return -EINVAL;
+
+ if (asprintf(&p, "/run/systemd/users/%lu", (unsigned long) uid) < 0)
+ return -ENOMEM;
+
+ r = parse_env_file(p, NEWLINE, "STATE", &s, NULL);
+ free(p);
+
+ if (r == -ENOENT) {
+ free(s);
+ s = strdup("offline");
+ if (!s)
+ return -ENOMEM;
+
+ *state = s;
+ return 0;
+ } else if (r < 0) {
+ free(s);
+ return r;
+ } else if (!s)
+ return -EIO;
+
+ *state = s;
+ return 0;
+}
+
+_public_ int sd_uid_is_on_seat(uid_t uid, int require_active, const char *seat) {
+ char *w, *state;
+ _cleanup_free_ char *t = NULL, *s = NULL, *p = NULL;
+ size_t l;
+ int r;
+ const char *variable;
+
+ if (!seat)
+ return -EINVAL;
+
+ variable = require_active ? "ACTIVE_UID" : "UIDS";
+
+ p = strappend("/run/systemd/seats/", seat);
+ if (!p)
+ return -ENOMEM;
+
+ r = parse_env_file(p, NEWLINE, variable, &s, NULL);
+
+ if (r < 0)
+ return r;
+
+ if (!s)
+ return -EIO;
+
+ if (asprintf(&t, "%lu", (unsigned long) uid) < 0)
+ return -ENOMEM;
+
+ FOREACH_WORD(w, l, s, state) {
+ if (strneq(t, w, l))
+ return 1;
+ }
+
+ return 0;
+}
+
+static int uid_get_array(uid_t uid, const char *variable, char ***array) {
+ _cleanup_free_ char *p = NULL, *s = NULL;
+ char **a;
+ int r;
+
+ if (asprintf(&p, "/run/systemd/users/%lu", (unsigned long) uid) < 0)
+ return -ENOMEM;
+
+ r = parse_env_file(p, NEWLINE,
+ variable, &s,
+ NULL);
+ if (r < 0) {
+ if (r == -ENOENT) {
+ if (array)
+ *array = NULL;
+ return 0;
+ }
+
+ return r;
+ }
+
+ if (!s) {
+ if (array)
+ *array = NULL;
+ return 0;
+ }
+
+ a = strv_split(s, " ");
+
+ if (!a)
+ return -ENOMEM;
+
+ strv_uniq(a);
+ r = strv_length(a);
+
+ if (array)
+ *array = a;
+ else
+ strv_free(a);
+
+ return r;
+}
+
+_public_ int sd_uid_get_sessions(uid_t uid, int require_active, char ***sessions) {
+ return uid_get_array(
+ uid,
+ require_active == 0 ? "ONLINE_SESSIONS" :
+ require_active > 0 ? "ACTIVE_SESSIONS" :
+ "SESSIONS",
+ sessions);
+}
+
+_public_ int sd_uid_get_seats(uid_t uid, int require_active, char ***seats) {
+ return uid_get_array(
+ uid,
+ require_active == 0 ? "ONLINE_SEATS" :
+ require_active > 0 ? "ACTIVE_SEATS" :
+ "SEATS",
+ seats);
+}
+
+static int file_of_session(const char *session, char **_p) {
+ char *p;
+ int r;
+
+ assert(_p);
+
+ if (session)
+ p = strappend("/run/systemd/sessions/", session);
+ else {
+ char *buf;
+
+ r = sd_pid_get_session(0, &buf);
+ if (r < 0)
+ return r;
+
+ p = strappend("/run/systemd/sessions/", buf);
+ free(buf);
+ }
+
+ if (!p)
+ return -ENOMEM;
+
+ *_p = p;
+ return 0;
+}
+
+_public_ int sd_session_is_active(const char *session) {
+ int r;
+ _cleanup_free_ char *p = NULL, *s = NULL;
+
+ r = file_of_session(session, &p);
+ if (r < 0)
+ return r;
+
+ r = parse_env_file(p, NEWLINE, "ACTIVE", &s, NULL);
+
+ if (r < 0)
+ return r;
+
+ if (!s)
+ return -EIO;
+
+ r = parse_boolean(s);
+
+ return r;
+}
+
+_public_ int sd_session_get_state(const char *session, char **state) {
+ _cleanup_free_ char *p = NULL, *s = NULL;
+ int r;
+
+ if (!state)
+ return -EINVAL;
+
+ r = file_of_session(session, &p);
+ if (r < 0)
+ return r;
+
+ r = parse_env_file(p, NEWLINE, "STATE", &s, NULL);
+
+ if (r < 0)
+ return r;
+ else if (!s)
+ return -EIO;
+
+ *state = s;
+ s = NULL;
+
+ return 0;
+}
+
+_public_ int sd_session_get_uid(const char *session, uid_t *uid) {
+ int r;
+ _cleanup_free_ char *p = NULL, *s = NULL;
+
+ if (!uid)
+ return -EINVAL;
+
+ r = file_of_session(session, &p);
+ if (r < 0)
+ return r;
+
+ r = parse_env_file(p, NEWLINE, "UID", &s, NULL);
+
+ if (r < 0)
+ return r;
+
+ if (!s)
+ return -EIO;
+
+ r = parse_uid(s, uid);
+
+ return r;
+}
+
+static int session_get_string(const char *session, const char *field, char **value) {
+ _cleanup_free_ char *p = NULL, *s = NULL;
+ int r;
+
+ if (!value)
+ return -EINVAL;
+
+ r = file_of_session(session, &p);
+ if (r < 0)
+ return r;
+
+ r = parse_env_file(p, NEWLINE, field, &s, NULL);
+
+ if (r < 0)
+ return r;
+
+ if (isempty(s))
+ return -ENOENT;
+
+ *value = s;
+ s = NULL;
+ return 0;
+}
+
+_public_ int sd_session_get_seat(const char *session, char **seat) {
+ return session_get_string(session, "SEAT", seat);
+}
+
+_public_ int sd_session_get_tty(const char *session, char **tty) {
+ return session_get_string(session, "TTY", tty);
+}
+
+_public_ int sd_session_get_service(const char *session, char **service) {
+ return session_get_string(session, "SERVICE", service);
+}
+
+_public_ int sd_session_get_type(const char *session, char **type) {
+ return session_get_string(session, "TYPE", type);
+}
+
+_public_ int sd_session_get_class(const char *session, char **class) {
+ return session_get_string(session, "CLASS", class);
+}
+
+_public_ int sd_session_get_display(const char *session, char **display) {
+ return session_get_string(session, "DISPLAY", display);
+}
+
+static int file_of_seat(const char *seat, char **_p) {
+ char *p;
+ int r;
+
+ assert(_p);
+
+ if (seat)
+ p = strappend("/run/systemd/seats/", seat);
+ else {
+ _cleanup_free_ char *buf = NULL;
+
+ r = sd_session_get_seat(NULL, &buf);
+ if (r < 0)
+ return r;
+
+ p = strappend("/run/systemd/seats/", buf);
+ }
+
+ if (!p)
+ return -ENOMEM;
+
+ *_p = p;
+ p = NULL;
+ return 0;
+}
+
+_public_ int sd_seat_get_active(const char *seat, char **session, uid_t *uid) {
+ _cleanup_free_ char *p = NULL, *s = NULL, *t = NULL;
+ int r;
+
+ if (!session && !uid)
+ return -EINVAL;
+
+ r = file_of_seat(seat, &p);
+ if (r < 0)
+ return r;
+
+ r = parse_env_file(p, NEWLINE,
+ "ACTIVE", &s,
+ "ACTIVE_UID", &t,
+ NULL);
+ if (r < 0)
+ return r;
+
+ if (session && !s)
+ return -ENOENT;
+
+ if (uid && !t)
+ return -ENOENT;
+
+ if (uid && t) {
+ r = parse_uid(t, uid);
+ if (r < 0)
+ return r;
+ }
+
+ if (session && s) {
+ *session = s;
+ s = NULL;
+ }
+
+ return 0;
+}
+
+_public_ int sd_seat_get_sessions(const char *seat, char ***sessions, uid_t **uids, unsigned *n_uids) {
+ _cleanup_free_ char *p = NULL, *s = NULL, *t = NULL;
+ _cleanup_strv_free_ char **a = NULL;
+ _cleanup_free_ uid_t *b = NULL;
+ unsigned n = 0;
+ int r;
+
+ r = file_of_seat(seat, &p);
+ if (r < 0)
+ return r;
+
+ r = parse_env_file(p, NEWLINE,
+ "SESSIONS", &s,
+ "ACTIVE_SESSIONS", &t,
+ NULL);
+
+ if (r < 0)
+ return r;
+
+ if (s) {
+ a = strv_split(s, " ");
+ if (!a)
+ return -ENOMEM;
+ }
+
+ if (uids && t) {
+ char *w, *state;
+ size_t l;
+
+ FOREACH_WORD(w, l, t, state)
+ n++;
+
+ if (n > 0) {
+ unsigned i = 0;
+
+ b = new(uid_t, n);
+ if (!b)
+ return -ENOMEM;
+
+ FOREACH_WORD(w, l, t, state) {
+ _cleanup_free_ char *k = NULL;
+
+ k = strndup(w, l);
+ if (!k)
+ return -ENOMEM;
+
+ r = parse_uid(k, b + i);
+
+ if (r < 0)
+ continue;
+
+ i++;
+ }
+ }
+ }
+
+ r = strv_length(a);
+
+ if (sessions) {
+ *sessions = a;
+ a = NULL;
+ }
+
+ if (uids) {
+ *uids = b;
+ b = NULL;
+ }
+
+ if (n_uids)
+ *n_uids = n;
+
+ return r;
+}
+
+static int seat_get_can(const char *seat, const char *variable) {
+ _cleanup_free_ char *p = NULL, *s = NULL;
+ int r;
+
+ r = file_of_seat(seat, &p);
+ if (r < 0)
+ return r;
+
+ r = parse_env_file(p, NEWLINE,
+ variable, &s,
+ NULL);
+ if (r < 0)
+ return r;
+
+ if (s)
+ r = parse_boolean(s);
+ else
+ r = 0;
+
+ return r;
+}
+
+_public_ int sd_seat_can_multi_session(const char *seat) {
+ return seat_get_can(seat, "CAN_MULTI_SESSION");
+}
+
+_public_ int sd_seat_can_tty(const char *seat) {
+ return seat_get_can(seat, "CAN_TTY");
+}
+
+_public_ int sd_seat_can_graphical(const char *seat) {
+ return seat_get_can(seat, "CAN_GRAPHICAL");
+}
+
+_public_ int sd_get_seats(char ***seats) {
+ return get_files_in_directory("/run/systemd/seats/", seats);
+}
+
+_public_ int sd_get_sessions(char ***sessions) {
+ return get_files_in_directory("/run/systemd/sessions/", sessions);
+}
+
+_public_ int sd_get_uids(uid_t **users) {
+ _cleanup_closedir_ DIR *d;
+ int r = 0;
+ unsigned n = 0;
+ _cleanup_free_ uid_t *l = NULL;
+
+ d = opendir("/run/systemd/users/");
+ if (!d)
+ return -errno;
+
+ for (;;) {
+ struct dirent *de;
+ union dirent_storage buf;
+ int k;
+ uid_t uid;
+
+ k = readdir_r(d, &buf.de, &de);
+ if (k != 0)
+ return -k;
+
+ if (!de)
+ break;
+
+ dirent_ensure_type(d, de);
+
+ if (!dirent_is_file(de))
+ continue;
+
+ k = parse_uid(de->d_name, &uid);
+ if (k < 0)
+ continue;
+
+ if (users) {
+ if ((unsigned) r >= n) {
+ uid_t *t;
+
+ n = MAX(16, 2*r);
+ t = realloc(l, sizeof(uid_t) * n);
+ if (!t)
+ return -ENOMEM;
+
+ l = t;
+ }
+
+ assert((unsigned) r < n);
+ l[r++] = uid;
+ } else
+ r++;
+ }
+
+ if (users) {
+ *users = l;
+ l = NULL;
+ }
+
+ return r;
+}
+
+_public_ int sd_get_machine_names(char ***machines) {
+ _cleanup_closedir_ DIR *d = NULL;
+ _cleanup_strv_free_ char **l = NULL;
+ _cleanup_free_ char *md = NULL;
+ char *n;
+ int c = 0, r;
+
+ r = cg_get_machine_path(NULL, &md);
+ if (r < 0)
+ return r;
+
+ r = cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER, md, &d);
+ if (r < 0)
+ return r;
+
+ while ((r = cg_read_subgroup(d, &n)) > 0) {
+
+ r = strv_push(&l, n);
+ if (r < 0) {
+ free(n);
+ return -ENOMEM;
+ }
+
+ c++;
+ }
+
+ if (r < 0)
+ return r;
+
+ if (machines) {
+ *machines = l;
+ l = NULL;
+ }
+
+ return c;
+}
+
+static inline int MONITOR_TO_FD(sd_login_monitor *m) {
+ return (int) (unsigned long) m - 1;
+}
+
+static inline sd_login_monitor* FD_TO_MONITOR(int fd) {
+ return (sd_login_monitor*) (unsigned long) (fd + 1);
+}
+
+_public_ int sd_login_monitor_new(const char *category, sd_login_monitor **m) {
+ int fd, k;
+ bool good = false;
+
+ if (!m)
+ return -EINVAL;
+
+ fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
+ if (fd < 0)
+ return -errno;
+
+ if (!category || streq(category, "seat")) {
+ k = inotify_add_watch(fd, "/run/systemd/seats/", IN_MOVED_TO|IN_DELETE);
+ if (k < 0) {
+ close_nointr_nofail(fd);
+ return -errno;
+ }
+
+ good = true;
+ }
+
+ if (!category || streq(category, "session")) {
+ k = inotify_add_watch(fd, "/run/systemd/sessions/", IN_MOVED_TO|IN_DELETE);
+ if (k < 0) {
+ close_nointr_nofail(fd);
+ return -errno;
+ }
+
+ good = true;
+ }
+
+ if (!category || streq(category, "uid")) {
+ k = inotify_add_watch(fd, "/run/systemd/users/", IN_MOVED_TO|IN_DELETE);
+ if (k < 0) {
+ close_nointr_nofail(fd);
+ return -errno;
+ }
+
+ good = true;
+ }
+
+ if (!category || streq(category, "machine")) {
+ _cleanup_free_ char *md = NULL, *p = NULL;
+ int r;
+
+ r = cg_get_machine_path(NULL, &md);
+ if (r < 0)
+ return r;
+
+ r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, md, NULL, &p);
+ if (r < 0)
+ return r;
+
+ k = inotify_add_watch(fd, p, IN_MOVED_TO|IN_CREATE|IN_DELETE);
+ if (k < 0) {
+ close_nointr_nofail(fd);
+ return -errno;
+ }
+
+ good = true;
+ }
+
+ if (!good) {
+ close_nointr(fd);
+ return -EINVAL;
+ }
+
+ *m = FD_TO_MONITOR(fd);
+ return 0;
+}
+
+_public_ sd_login_monitor* sd_login_monitor_unref(sd_login_monitor *m) {
+ int fd;
+
+ if (!m)
+ return NULL;
+
+ fd = MONITOR_TO_FD(m);
+ close_nointr(fd);
+
+ return NULL;
+}
+
+_public_ int sd_login_monitor_flush(sd_login_monitor *m) {
+
+ if (!m)
+ return -EINVAL;
+
+ return flush_fd(MONITOR_TO_FD(m));
+}
+
+_public_ int sd_login_monitor_get_fd(sd_login_monitor *m) {
+
+ if (!m)
+ return -EINVAL;
+
+ return MONITOR_TO_FD(m);
+}
+
+_public_ int sd_login_monitor_get_events(sd_login_monitor *m) {
+
+ if (!m)
+ return -EINVAL;
+
+ /* For now we will only return POLLIN here, since we don't
+ * need anything else ever for inotify. However, let's have
+ * this API to keep our options open should we later on need
+ * it. */
+ return POLLIN;
+}
+
+_public_ int sd_login_monitor_get_timeout(sd_login_monitor *m, uint64_t *timeout_usec) {
+
+ if (!m)
+ return -EINVAL;
+ if (!timeout_usec)
+ return -EINVAL;
+
+ /* For now we will only return (uint64_t) -1, since we don't
+ * need any timeout. However, let's have this API to keep our
+ * options open should we later on need it. */
+ *timeout_usec = (uint64_t) -1;
+ return 0;
+}
diff --git a/src/login/sysfs-show.c b/src/login/sysfs-show.c
new file mode 100644
index 0000000000..3c03bd1f2e
--- /dev/null
+++ b/src/login/sysfs-show.c
@@ -0,0 +1,194 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <string.h>
+#include <libudev.h>
+
+#include "util.h"
+#include "sysfs-show.h"
+#include "path-util.h"
+
+static int show_sysfs_one(
+ struct udev *udev,
+ const char *seat,
+ struct udev_list_entry **item,
+ const char *sub,
+ const char *prefix,
+ unsigned n_columns) {
+
+ assert(udev);
+ assert(seat);
+ assert(item);
+ assert(prefix);
+
+ while (*item) {
+ struct udev_list_entry *next, *lookahead;
+ struct udev_device *d;
+ const char *sn, *name, *sysfs, *subsystem, *sysname;
+ char *l, *k;
+ bool is_master;
+
+ sysfs = udev_list_entry_get_name(*item);
+ if (!path_startswith(sysfs, sub))
+ return 0;
+
+ d = udev_device_new_from_syspath(udev, sysfs);
+ if (!d) {
+ *item = udev_list_entry_get_next(*item);
+ continue;
+ }
+
+ sn = udev_device_get_property_value(d, "ID_SEAT");
+ if (isempty(sn))
+ sn = "seat0";
+
+ /* Explicitly also check for tag 'seat' here */
+ if (!streq(seat, sn) || !udev_device_has_tag(d, "seat")) {
+ udev_device_unref(d);
+ *item = udev_list_entry_get_next(*item);
+ continue;
+ }
+
+ is_master = udev_device_has_tag(d, "master-of-seat");
+
+ name = udev_device_get_sysattr_value(d, "name");
+ if (!name)
+ name = udev_device_get_sysattr_value(d, "id");
+ subsystem = udev_device_get_subsystem(d);
+ sysname = udev_device_get_sysname(d);
+
+ /* Look if there's more coming after this */
+ lookahead = next = udev_list_entry_get_next(*item);
+ while (lookahead) {
+ const char *lookahead_sysfs;
+
+ lookahead_sysfs = udev_list_entry_get_name(lookahead);
+
+ if (path_startswith(lookahead_sysfs, sub) &&
+ !path_startswith(lookahead_sysfs, sysfs)) {
+ struct udev_device *lookahead_d;
+
+ lookahead_d = udev_device_new_from_syspath(udev, lookahead_sysfs);
+ if (lookahead_d) {
+ const char *lookahead_sn;
+ bool found;
+
+ lookahead_sn = udev_device_get_property_value(d, "ID_SEAT");
+ if (isempty(lookahead_sn))
+ lookahead_sn = "seat0";
+
+ found = streq(seat, lookahead_sn) && udev_device_has_tag(lookahead_d, "seat");
+ udev_device_unref(lookahead_d);
+
+ if (found)
+ break;
+ }
+ }
+
+ lookahead = udev_list_entry_get_next(lookahead);
+ }
+
+ k = ellipsize(sysfs, n_columns, 20);
+ printf("%s%s%s\n", prefix, draw_special_char(lookahead ? DRAW_TREE_BRANCH : DRAW_TREE_RIGHT),
+ k ? k : sysfs);
+ free(k);
+
+ if (asprintf(&l,
+ "%s%s:%s%s%s%s",
+ is_master ? "[MASTER] " : "",
+ subsystem, sysname,
+ name ? " \"" : "", name ? name : "", name ? "\"" : "") < 0) {
+ udev_device_unref(d);
+ return -ENOMEM;
+ }
+
+ k = ellipsize(l, n_columns, 70);
+ printf("%s%s%s\n", prefix, lookahead ? draw_special_char(DRAW_TREE_VERT) : " ",
+ k ? k : l);
+ free(k);
+ free(l);
+
+ *item = next;
+ if (*item) {
+ char *p;
+
+ p = strappend(prefix, lookahead ? draw_special_char(DRAW_TREE_VERT) : " ");
+ show_sysfs_one(udev, seat, item, sysfs, p ? p : prefix, n_columns - 2);
+ free(p);
+ }
+
+ udev_device_unref(d);
+ }
+
+ return 0;
+}
+
+int show_sysfs(const char *seat, const char *prefix, unsigned n_columns) {
+ struct udev *udev;
+ struct udev_list_entry *first = NULL;
+ struct udev_enumerate *e;
+ int r;
+
+ if (n_columns <= 0)
+ n_columns = columns();
+
+ if (!prefix)
+ prefix = "";
+
+ if (isempty(seat))
+ seat = "seat0";
+
+ udev = udev_new();
+ if (!udev)
+ return -ENOMEM;
+
+ e = udev_enumerate_new(udev);
+ if (!e) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ if (!streq(seat, "seat0"))
+ r = udev_enumerate_add_match_tag(e, seat);
+ else
+ r = udev_enumerate_add_match_tag(e, "seat");
+
+ if (r < 0)
+ goto finish;
+
+ r = udev_enumerate_scan_devices(e);
+ if (r < 0)
+ goto finish;
+
+ first = udev_enumerate_get_list_entry(e);
+ if (first)
+ show_sysfs_one(udev, seat, &first, "/", prefix, n_columns);
+
+finish:
+ if (e)
+ udev_enumerate_unref(e);
+
+ if (udev)
+ udev_unref(udev);
+
+ return r;
+}
diff --git a/src/login/test-inhibit.c b/src/login/test-inhibit.c
new file mode 100644
index 0000000000..7b6deffc3e
--- /dev/null
+++ b/src/login/test-inhibit.c
@@ -0,0 +1,139 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <unistd.h>
+
+#include <dbus/dbus.h>
+
+#include "macro.h"
+#include "util.h"
+#include "dbus-common.h"
+
+static int inhibit(DBusConnection *bus, const char *what) {
+ DBusMessage *m, *reply;
+ DBusError error;
+ const char *who = "Test Tool", *reason = "Just because!", *mode = "block";
+ int fd;
+
+ dbus_error_init(&error);
+
+ m = dbus_message_new_method_call(
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "Inhibit");
+ assert(m);
+
+ assert_se(dbus_message_append_args(m,
+ DBUS_TYPE_STRING, &what,
+ DBUS_TYPE_STRING, &who,
+ DBUS_TYPE_STRING, &reason,
+ DBUS_TYPE_STRING, &mode,
+ DBUS_TYPE_INVALID));
+
+ reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
+ assert(reply);
+
+ assert(dbus_message_get_args(reply, &error,
+ DBUS_TYPE_UNIX_FD, &fd,
+ DBUS_TYPE_INVALID));
+
+ dbus_message_unref(m);
+ dbus_message_unref(reply);
+
+ return fd;
+}
+
+static void print_inhibitors(DBusConnection *bus) {
+ DBusMessage *m, *reply;
+ DBusError error;
+ unsigned n = 0;
+ DBusMessageIter iter, sub, sub2;
+
+ dbus_error_init(&error);
+
+ m = dbus_message_new_method_call(
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "ListInhibitors");
+ assert(m);
+
+ reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
+ assert(reply);
+
+ assert(dbus_message_iter_init(reply, &iter));
+ dbus_message_iter_recurse(&iter, &sub);
+
+ while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ const char *what, *who, *why, *mode;
+ dbus_uint32_t uid, pid;
+
+ dbus_message_iter_recurse(&sub, &sub2);
+
+ assert_se(bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &what, true) >= 0);
+ assert_se(bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &who, true) >= 0);
+ assert_se(bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &why, true) >= 0);
+ assert_se(bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &mode, true) >= 0);
+ assert_se(bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &uid, true) >= 0);
+ assert_se(bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, false) >= 0);
+
+ printf("what=<%s> who=<%s> why=<%s> mode=<%s> uid=<%lu> pid=<%lu>\n",
+ what, who, why, mode, (unsigned long) uid, (unsigned long) pid);
+
+ dbus_message_iter_next(&sub);
+
+ n++;
+ }
+
+ printf("%u inhibitors\n", n);
+
+ dbus_message_unref(m);
+ dbus_message_unref(reply);
+}
+
+int main(int argc, char*argv[]) {
+ DBusConnection *bus;
+ int fd1, fd2;
+
+ bus = dbus_bus_get_private(DBUS_BUS_SYSTEM, NULL);
+ assert(bus);
+
+ print_inhibitors(bus);
+
+ fd1 = inhibit(bus, "sleep");
+ assert(fd1 >= 0);
+ print_inhibitors(bus);
+
+ fd2 = inhibit(bus, "idle:shutdown");
+ assert(fd2 >= 0);
+ print_inhibitors(bus);
+
+ close_nointr_nofail(fd1);
+ sleep(1);
+ print_inhibitors(bus);
+
+ close_nointr_nofail(fd2);
+ sleep(1);
+ print_inhibitors(bus);
+
+ return 0;
+}
diff --git a/src/login/test-login.c b/src/login/test-login.c
new file mode 100644
index 0000000000..945cb38be9
--- /dev/null
+++ b/src/login/test-login.c
@@ -0,0 +1,220 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/poll.h>
+#include <string.h>
+
+#include <systemd/sd-login.h>
+
+#include "util.h"
+#include "strv.h"
+
+int main(int argc, char* argv[]) {
+ int r, k;
+ uid_t u, u2;
+ char *seat, *type, *class, *display;
+ char *session;
+ char *state;
+ char *session2;
+ char *t;
+ char **seats, **sessions, **machines;
+ uid_t *uids;
+ unsigned n;
+ struct pollfd pollfd;
+ sd_login_monitor *m;
+
+ assert_se(sd_pid_get_session(0, &session) == 0);
+ printf("session = %s\n", session);
+
+ assert_se(sd_pid_get_owner_uid(0, &u2) == 0);
+ printf("user = %lu\n", (unsigned long) u2);
+
+ r = sd_uid_get_sessions(u2, false, &sessions);
+ assert_se(r >= 0);
+ assert_se(r == (int) strv_length(sessions));
+ assert_se(t = strv_join(sessions, ", "));
+ strv_free(sessions);
+ printf("sessions = %s\n", t);
+ free(t);
+
+ assert_se(r == sd_uid_get_sessions(u2, false, NULL));
+
+ r = sd_uid_get_seats(u2, false, &seats);
+ assert_se(r >= 0);
+ assert_se(r == (int) strv_length(seats));
+ assert_se(t = strv_join(seats, ", "));
+ strv_free(seats);
+ printf("seats = %s\n", t);
+ free(t);
+
+ assert_se(r == sd_uid_get_seats(u2, false, NULL));
+
+ r = sd_session_is_active(session);
+ assert_se(r >= 0);
+ printf("active = %s\n", yes_no(r));
+
+ r = sd_session_get_state(session, &state);
+ assert_se(r >= 0);
+ printf("state = %s\n", state);
+ free(state);
+
+ assert_se(sd_session_get_uid(session, &u) >= 0);
+ printf("uid = %lu\n", (unsigned long) u);
+ assert_se(u == u2);
+
+ assert_se(sd_session_get_type(session, &type) >= 0);
+ printf("type = %s\n", type);
+ free(type);
+
+ assert_se(sd_session_get_class(session, &class) >= 0);
+ printf("class = %s\n", class);
+ free(class);
+
+ assert_se(sd_session_get_display(session, &display) >= 0);
+ printf("display = %s\n", display);
+ free(display);
+
+ assert_se(sd_session_get_seat(session, &seat) >= 0);
+ printf("seat = %s\n", seat);
+
+ r = sd_seat_can_multi_session(seat);
+ assert_se(r >= 0);
+ printf("can do multi session = %s\n", yes_no(r));
+
+ r = sd_seat_can_tty(seat);
+ assert_se(r >= 0);
+ printf("can do tty = %s\n", yes_no(r));
+
+ r = sd_seat_can_graphical(seat);
+ assert_se(r >= 0);
+ printf("can do graphical = %s\n", yes_no(r));
+
+ assert_se(sd_uid_get_state(u, &state) >= 0);
+ printf("state = %s\n", state);
+
+ assert_se(sd_uid_is_on_seat(u, 0, seat) > 0);
+
+ k = sd_uid_is_on_seat(u, 1, seat);
+ assert_se(k >= 0);
+ assert_se(!!r == !!r);
+
+ assert_se(sd_seat_get_active(seat, &session2, &u2) >= 0);
+ printf("session2 = %s\n", session2);
+ printf("uid2 = %lu\n", (unsigned long) u2);
+
+ r = sd_seat_get_sessions(seat, &sessions, &uids, &n);
+ assert_se(r >= 0);
+ printf("n_sessions = %i\n", r);
+ assert_se(r == (int) strv_length(sessions));
+ assert_se(t = strv_join(sessions, ", "));
+ strv_free(sessions);
+ printf("sessions = %s\n", t);
+ free(t);
+ printf("uids =");
+ for (k = 0; k < (int) n; k++)
+ printf(" %lu", (unsigned long) uids[k]);
+ printf("\n");
+ free(uids);
+
+ assert_se(sd_seat_get_sessions(seat, NULL, NULL, NULL) == r);
+
+ free(session);
+ free(state);
+ free(session2);
+ free(seat);
+
+ r = sd_get_seats(&seats);
+ assert_se(r >= 0);
+ assert_se(r == (int) strv_length(seats));
+ assert_se(t = strv_join(seats, ", "));
+ strv_free(seats);
+ printf("n_seats = %i\n", r);
+ printf("seats = %s\n", t);
+ free(t);
+
+ assert_se(sd_get_seats(NULL) == r);
+
+ r = sd_seat_get_active(NULL, &t, NULL);
+ assert_se(r >= 0);
+ printf("active session on current seat = %s\n", t);
+ free(t);
+
+ r = sd_get_sessions(&sessions);
+ assert_se(r >= 0);
+ assert_se(r == (int) strv_length(sessions));
+ assert_se(t = strv_join(sessions, ", "));
+ strv_free(sessions);
+ printf("n_sessions = %i\n", r);
+ printf("sessions = %s\n", t);
+ free(t);
+
+ assert_se(sd_get_sessions(NULL) == r);
+
+ r = sd_get_uids(&uids);
+ assert_se(r >= 0);
+
+ printf("uids =");
+ for (k = 0; k < r; k++)
+ printf(" %lu", (unsigned long) uids[k]);
+ printf("\n");
+ free(uids);
+
+ printf("n_uids = %i\n", r);
+ assert_se(sd_get_uids(NULL) == r);
+
+ r = sd_get_machine_names(&machines);
+ assert_se(r >= 0);
+ assert_se(r == (int) strv_length(machines));
+ assert_se(t = strv_join(machines, ", "));
+ strv_free(machines);
+ printf("n_machines = %i\n", r);
+ printf("machines = %s\n", t);
+ free(t);
+
+ r = sd_login_monitor_new("session", &m);
+ assert_se(r >= 0);
+
+ for (n = 0; n < 5; n++) {
+ usec_t timeout, nw;
+
+ zero(pollfd);
+ assert_se((pollfd.fd = sd_login_monitor_get_fd(m)) >= 0);
+ assert_se((pollfd.events = sd_login_monitor_get_events(m)) >= 0);
+
+ assert_se(sd_login_monitor_get_timeout(m, &timeout) >= 0);
+
+ nw = now(CLOCK_MONOTONIC);
+
+ r = poll(&pollfd, 1,
+ timeout == (uint64_t) -1 ? -1 :
+ timeout > nw ? (int) ((timeout - nw) / 1000) :
+ 0);
+
+ assert_se(r >= 0);
+
+ sd_login_monitor_flush(m);
+ printf("Wake!\n");
+ }
+
+ sd_login_monitor_unref(m);
+
+ return 0;
+}
diff --git a/src/login/user-sessions.c b/src/login/user-sessions.c
new file mode 100644
index 0000000000..41d32044e9
--- /dev/null
+++ b/src/login/user-sessions.c
@@ -0,0 +1,102 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+
+#include "log.h"
+#include "util.h"
+#include "cgroup-util.h"
+#include "fileio.h"
+
+int main(int argc, char*argv[]) {
+ int ret = EXIT_FAILURE;
+
+ if (argc != 2) {
+ log_error("This program requires one argument.");
+ return EXIT_FAILURE;
+ }
+
+ log_set_target(LOG_TARGET_AUTO);
+ log_parse_environment();
+ log_open();
+
+ umask(0022);
+
+ if (streq(argv[1], "start")) {
+ int q = 0, r = 0;
+
+ if (unlink("/run/nologin") < 0 && errno != ENOENT) {
+ log_error("Failed to remove /run/nologin file: %m");
+ r = -errno;
+ }
+
+ if (unlink("/etc/nologin") < 0 && errno != ENOENT) {
+
+ /* If the file doesn't exist and /etc simply
+ * was read-only (in which case unlink()
+ * returns EROFS even if the file doesn't
+ * exist), don't complain */
+
+ if (errno != EROFS || access("/etc/nologin", F_OK) >= 0) {
+ log_error("Failed to remove /etc/nologin file: %m");
+ q = -errno;
+ }
+ }
+
+ if (r < 0 || q < 0)
+ goto finish;
+
+ } else if (streq(argv[1], "stop")) {
+ int r, q;
+ char *cgroup_user_tree = NULL;
+
+ r = write_string_file_atomic("/run/nologin", "System is going down.");
+ if (r < 0)
+ log_error("Failed to create /run/nologin: %s", strerror(-r));
+
+ q = cg_get_user_path(&cgroup_user_tree);
+ if (q < 0) {
+ log_error("Failed to determine use path: %s", strerror(-q));
+ goto finish;
+ }
+
+ q = cg_kill_recursive_and_wait(SYSTEMD_CGROUP_CONTROLLER, cgroup_user_tree, true);
+ free(cgroup_user_tree);
+ if (q < 0) {
+ log_error("Failed to kill sessions: %s", strerror(-q));
+ goto finish;
+ }
+
+ if (r < 0)
+ goto finish;
+
+ } else {
+ log_error("Unknown verb %s.", argv[1]);
+ goto finish;
+ }
+
+ ret = EXIT_SUCCESS;
+
+finish:
+ return ret;
+}
diff --git a/src/machine-id-setup/machine-id-setup-main.c b/src/machine-id-setup/machine-id-setup-main.c
new file mode 100644
index 0000000000..eb2d514855
--- /dev/null
+++ b/src/machine-id-setup/machine-id-setup-main.c
@@ -0,0 +1,101 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <unistd.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <getopt.h>
+#include <errno.h>
+
+#include "machine-id-setup.h"
+#include "log.h"
+#include "build.h"
+
+static int help(void) {
+
+ printf("%s [OPTIONS...]\n\n"
+ "Initialize /etc/machine-id from a random source.\n\n"
+ " -h --help Show this help\n"
+ " --version Show package version\n",
+ program_invocation_short_name);
+
+ return 0;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+
+ enum {
+ ARG_VERSION = 0x100
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "version", no_argument, NULL, ARG_VERSION },
+ { NULL, 0, NULL, 0 }
+ };
+
+ int c;
+
+ assert(argc >= 0);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "hqcv", options, NULL)) >= 0) {
+
+ switch (c) {
+
+ case 'h':
+ help();
+ return 0;
+
+ case ARG_VERSION:
+ puts(PACKAGE_STRING);
+ puts(SYSTEMD_FEATURES);
+ return 0;
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ log_error("Unknown option code %c", c);
+ return -EINVAL;
+ }
+ }
+
+ if (optind < argc) {
+ help();
+ return -EINVAL;
+ }
+
+ return 1;
+}
+
+int main(int argc, char *argv[]) {
+ int r;
+
+ log_parse_environment();
+ log_open();
+
+ r = parse_argv(argc, argv);
+ if (r <= 0)
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+
+ return machine_id_setup() < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/src/modules-load/modules-load.c b/src/modules-load/modules-load.c
new file mode 100644
index 0000000000..7b19ee02ef
--- /dev/null
+++ b/src/modules-load/modules-load.c
@@ -0,0 +1,327 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <unistd.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <limits.h>
+#include <dirent.h>
+#include <getopt.h>
+#include <libkmod.h>
+
+#include "log.h"
+#include "util.h"
+#include "strv.h"
+#include "conf-files.h"
+#include "virt.h"
+#include "fileio.h"
+
+static char **arg_proc_cmdline_modules = NULL;
+
+static const char conf_file_dirs[] =
+ "/etc/modules-load.d\0"
+ "/run/modules-load.d\0"
+ "/usr/local/lib/modules-load.d\0"
+ "/usr/lib/modules-load.d\0"
+#ifdef HAVE_SPLIT_USR
+ "/lib/modules-load.d\0"
+#endif
+ ;
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wformat-nonliteral"
+static void systemd_kmod_log(void *data, int priority, const char *file, int line,
+ const char *fn, const char *format, va_list args)
+{
+ log_metav(priority, file, line, fn, format, args);
+}
+#pragma GCC diagnostic pop
+
+static int add_modules(const char *p) {
+ char **t;
+ _cleanup_strv_free_ char **k = NULL;
+
+ k = strv_split(p, ",");
+ if (!k)
+ return log_oom();
+
+ t = strv_merge(arg_proc_cmdline_modules, k);
+ if (!t)
+ return log_oom();
+
+ strv_free(arg_proc_cmdline_modules);
+ arg_proc_cmdline_modules = t;
+
+ return 0;
+}
+
+static int parse_proc_cmdline(void) {
+ _cleanup_free_ char *line = NULL;
+ char *w, *state;
+ int r;
+ size_t l;
+
+ if (detect_container(NULL) > 0)
+ return 0;
+
+ r = read_one_line_file("/proc/cmdline", &line);
+ if (r < 0) {
+ log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
+ return 0;
+ }
+
+ FOREACH_WORD_QUOTED(w, l, line, state) {
+ _cleanup_free_ char *word;
+
+ word = strndup(w, l);
+ if (!word)
+ return log_oom();
+
+ if (startswith(word, "modules-load=")) {
+
+ r = add_modules(word + 13);
+ if (r < 0)
+ return r;
+
+ } else if (startswith(word, "rd.modules-load=")) {
+
+ if (in_initrd()) {
+ r = add_modules(word + 16);
+ if (r < 0)
+ return r;
+ }
+
+ }
+ }
+
+ return 0;
+}
+
+static int load_module(struct kmod_ctx *ctx, const char *m) {
+ const int probe_flags = KMOD_PROBE_APPLY_BLACKLIST;
+ struct kmod_list *itr, *modlist = NULL;
+ int r = 0;
+
+ log_debug("load: %s\n", m);
+
+ r = kmod_module_new_from_lookup(ctx, m, &modlist);
+ if (r < 0) {
+ log_error("Failed to lookup alias '%s': %s", m, strerror(-r));
+ return r;
+ }
+
+ if (!modlist) {
+ log_error("Failed to find module '%s'", m);
+ return -ENOENT;
+ }
+
+ kmod_list_foreach(itr, modlist) {
+ struct kmod_module *mod;
+ int state, err;
+
+ mod = kmod_module_get_module(itr);
+ state = kmod_module_get_initstate(mod);
+
+ switch (state) {
+ case KMOD_MODULE_BUILTIN:
+ log_info("Module '%s' is builtin", kmod_module_get_name(mod));
+ break;
+
+ case KMOD_MODULE_LIVE:
+ log_debug("Module '%s' is already loaded", kmod_module_get_name(mod));
+ break;
+
+ default:
+ err = kmod_module_probe_insert_module(mod, probe_flags,
+ NULL, NULL, NULL, NULL);
+
+ if (err == 0)
+ log_info("Inserted module '%s'", kmod_module_get_name(mod));
+ else if (err == KMOD_PROBE_APPLY_BLACKLIST)
+ log_info("Module '%s' is blacklisted", kmod_module_get_name(mod));
+ else {
+ log_error("Failed to insert '%s': %s", kmod_module_get_name(mod),
+ strerror(-err));
+ r = err;
+ }
+ }
+
+ kmod_module_unref(mod);
+ }
+
+ kmod_module_unref_list(modlist);
+
+ return r;
+}
+
+static int apply_file(struct kmod_ctx *ctx, const char *path, bool ignore_enoent) {
+ _cleanup_fclose_ FILE *f = NULL;
+ int r;
+
+ assert(ctx);
+ assert(path);
+
+ r = search_and_fopen_nulstr(path, "re", conf_file_dirs, &f);
+ if (r < 0) {
+ if (ignore_enoent && r == -ENOENT)
+ return 0;
+
+ log_error("Failed to open %s, ignoring: %s", path, strerror(-r));
+ return r;
+ }
+
+ log_debug("apply: %s\n", path);
+ for (;;) {
+ char line[LINE_MAX], *l;
+ int k;
+
+ if (!fgets(line, sizeof(line), f)) {
+ if (feof(f))
+ break;
+
+ log_error("Failed to read file '%s', ignoring: %m", path);
+ return -errno;
+ }
+
+ l = strstrip(line);
+ if (!*l)
+ continue;
+ if (strchr(COMMENTS "\n", *l))
+ continue;
+
+ k = load_module(ctx, l);
+ if (k < 0 && r == 0)
+ r = k;
+ }
+
+ return r;
+}
+
+static int help(void) {
+
+ printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
+ "Loads statically configured kernel modules.\n\n"
+ " -h --help Show this help\n",
+ program_invocation_short_name);
+
+ return 0;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { NULL, 0, NULL, 0 }
+ };
+
+ int c;
+
+ assert(argc >= 0);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
+
+ switch (c) {
+
+ case 'h':
+ help();
+ return 0;
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ log_error("Unknown option code %c", c);
+ return -EINVAL;
+ }
+ }
+
+ return 1;
+}
+
+int main(int argc, char *argv[]) {
+ int r, k;
+ struct kmod_ctx *ctx;
+
+ r = parse_argv(argc, argv);
+ if (r <= 0)
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+
+ log_set_target(LOG_TARGET_AUTO);
+ log_parse_environment();
+ log_open();
+
+ umask(0022);
+
+ if (parse_proc_cmdline() < 0)
+ return EXIT_FAILURE;
+
+ ctx = kmod_new(NULL, NULL);
+ if (!ctx) {
+ log_error("Failed to allocate memory for kmod.");
+ goto finish;
+ }
+
+ kmod_load_resources(ctx);
+ kmod_set_log_fn(ctx, systemd_kmod_log, NULL);
+
+ r = 0;
+
+ if (argc > optind) {
+ int i;
+
+ for (i = optind; i < argc; i++) {
+ k = apply_file(ctx, argv[i], false);
+ if (k < 0 && r == 0)
+ r = k;
+ }
+
+ } else {
+ _cleanup_free_ char **files = NULL;
+ char **fn, **i;
+
+ STRV_FOREACH(i, arg_proc_cmdline_modules) {
+ k = load_module(ctx, *i);
+ if (k < 0)
+ r = EXIT_FAILURE;
+ }
+
+ r = conf_files_list_nulstr(&files, ".conf", NULL, conf_file_dirs);
+ if (r < 0) {
+ log_error("Failed to enumerate modules-load.d files: %s", strerror(-r));
+ goto finish;
+ }
+
+ STRV_FOREACH(fn, files) {
+ k = apply_file(ctx, *fn, true);
+ if (k < 0 && r == 0)
+ r = k;
+ }
+ }
+
+finish:
+ kmod_unref(ctx);
+ strv_free(arg_proc_cmdline_modules);
+
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/src/notify/notify.c b/src/notify/notify.c
new file mode 100644
index 0000000000..1e9766f862
--- /dev/null
+++ b/src/notify/notify.c
@@ -0,0 +1,228 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include <getopt.h>
+#include <error.h>
+#include <errno.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <systemd/sd-daemon.h>
+
+#include "strv.h"
+#include "util.h"
+#include "log.h"
+#include "sd-readahead.h"
+#include "build.h"
+#include "env-util.h"
+
+static bool arg_ready = false;
+static pid_t arg_pid = 0;
+static const char *arg_status = NULL;
+static bool arg_booted = false;
+static const char *arg_readahead = NULL;
+
+static int help(void) {
+
+ printf("%s [OPTIONS...] [VARIABLE=VALUE...]\n\n"
+ "Notify the init system about service status updates.\n\n"
+ " -h --help Show this help\n"
+ " --version Show package version\n"
+ " --ready Inform the init system about service start-up completion\n"
+ " --pid[=PID] Set main pid of daemon\n"
+ " --status=TEXT Set status text\n"
+ " --booted Returns 0 if the system was booted up with systemd, non-zero otherwise\n"
+ " --readahead=ACTION Controls read-ahead operations\n",
+ program_invocation_short_name);
+
+ return 0;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+
+ enum {
+ ARG_READY = 0x100,
+ ARG_VERSION,
+ ARG_PID,
+ ARG_STATUS,
+ ARG_BOOTED,
+ ARG_READAHEAD
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "version", no_argument, NULL, ARG_VERSION },
+ { "ready", no_argument, NULL, ARG_READY },
+ { "pid", optional_argument, NULL, ARG_PID },
+ { "status", required_argument, NULL, ARG_STATUS },
+ { "booted", no_argument, NULL, ARG_BOOTED },
+ { "readahead", required_argument, NULL, ARG_READAHEAD },
+ { NULL, 0, NULL, 0 }
+ };
+
+ int c;
+
+ assert(argc >= 0);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
+
+ switch (c) {
+
+ case 'h':
+ help();
+ return 0;
+
+ case ARG_VERSION:
+ puts(PACKAGE_STRING);
+ puts(SYSTEMD_FEATURES);
+ return 0;
+
+ case ARG_READY:
+ arg_ready = true;
+ break;
+
+ case ARG_PID:
+
+ if (optarg) {
+ if (parse_pid(optarg, &arg_pid) < 0) {
+ log_error("Failed to parse PID %s.", optarg);
+ return -EINVAL;
+ }
+ } else
+ arg_pid = getppid();
+
+ break;
+
+ case ARG_STATUS:
+ arg_status = optarg;
+ break;
+
+ case ARG_BOOTED:
+ arg_booted = true;
+ break;
+
+ case ARG_READAHEAD:
+ arg_readahead = optarg;
+ break;
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ log_error("Unknown option code %c", c);
+ return -EINVAL;
+ }
+ }
+
+ if (optind >= argc &&
+ !arg_ready &&
+ !arg_status &&
+ !arg_pid &&
+ !arg_booted &&
+ !arg_readahead) {
+ help();
+ return -EINVAL;
+ }
+
+ return 1;
+}
+
+int main(int argc, char* argv[]) {
+ char* our_env[4], **final_env = NULL;
+ unsigned i = 0;
+ char *status = NULL, *cpid = NULL, *n = NULL;
+ int r, retval = EXIT_FAILURE;
+
+ log_parse_environment();
+ log_open();
+
+ if ((r = parse_argv(argc, argv)) <= 0) {
+ retval = r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+ goto finish;
+ }
+
+ if (arg_booted)
+ return sd_booted() <= 0;
+
+ if (arg_readahead) {
+ if ((r = sd_readahead(arg_readahead)) < 0) {
+ log_error("Failed to issue read-ahead control command: %s", strerror(-r));
+ goto finish;
+ }
+ }
+
+ if (arg_ready)
+ our_env[i++] = (char*) "READY=1";
+
+ if (arg_status) {
+ if (!(status = strappend("STATUS=", arg_status))) {
+ log_error("Failed to allocate STATUS string.");
+ goto finish;
+ }
+
+ our_env[i++] = status;
+ }
+
+ if (arg_pid > 0) {
+ if (asprintf(&cpid, "MAINPID=%lu", (unsigned long) arg_pid) < 0) {
+ log_error("Failed to allocate MAINPID string.");
+ goto finish;
+ }
+
+ our_env[i++] = cpid;
+ }
+
+ our_env[i++] = NULL;
+
+ if (!(final_env = strv_env_merge(2, our_env, argv + optind))) {
+ log_error("Failed to merge string sets.");
+ goto finish;
+ }
+
+ if (strv_length(final_env) <= 0) {
+ retval = EXIT_SUCCESS;
+ goto finish;
+ }
+
+ if (!(n = strv_join(final_env, "\n"))) {
+ log_error("Failed to concatenate strings.");
+ goto finish;
+ }
+
+ if ((r = sd_notify(false, n)) < 0) {
+ log_error("Failed to notify init system: %s", strerror(-r));
+ goto finish;
+ }
+
+ retval = r <= 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+
+finish:
+ free(status);
+ free(cpid);
+ free(n);
+
+ strv_free(final_env);
+
+ return retval;
+}
diff --git a/src/nspawn/nspawn.c b/src/nspawn/nspawn.c
new file mode 100644
index 0000000000..09153c87ce
--- /dev/null
+++ b/src/nspawn/nspawn.c
@@ -0,0 +1,1750 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <signal.h>
+#include <sched.h>
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/syscall.h>
+#include <sys/mount.h>
+#include <sys/wait.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <errno.h>
+#include <sys/prctl.h>
+#include <sys/capability.h>
+#include <getopt.h>
+#include <sys/poll.h>
+#include <sys/epoll.h>
+#include <termios.h>
+#include <sys/signalfd.h>
+#include <grp.h>
+#include <linux/fs.h>
+#include <sys/un.h>
+#include <sys/socket.h>
+
+#ifdef HAVE_XATTR
+#include <attr/xattr.h>
+#endif
+
+#include <systemd/sd-daemon.h>
+
+#include "log.h"
+#include "util.h"
+#include "mkdir.h"
+#include "macro.h"
+#include "audit.h"
+#include "missing.h"
+#include "cgroup-util.h"
+#include "strv.h"
+#include "path-util.h"
+#include "loopback-setup.h"
+#include "sd-id128.h"
+#include "dev-setup.h"
+#include "fdset.h"
+#include "build.h"
+#include "fileio.h"
+
+#ifndef TTY_GID
+#define TTY_GID 5
+#endif
+
+typedef enum LinkJournal {
+ LINK_NO,
+ LINK_AUTO,
+ LINK_HOST,
+ LINK_GUEST
+} LinkJournal;
+
+static char *arg_directory = NULL;
+static char *arg_user = NULL;
+static char **arg_controllers = NULL;
+static char *arg_uuid = NULL;
+static char *arg_machine = NULL;
+static bool arg_private_network = false;
+static bool arg_read_only = false;
+static bool arg_boot = false;
+static LinkJournal arg_link_journal = LINK_AUTO;
+static uint64_t arg_retain =
+ (1ULL << CAP_CHOWN) |
+ (1ULL << CAP_DAC_OVERRIDE) |
+ (1ULL << CAP_DAC_READ_SEARCH) |
+ (1ULL << CAP_FOWNER) |
+ (1ULL << CAP_FSETID) |
+ (1ULL << CAP_IPC_OWNER) |
+ (1ULL << CAP_KILL) |
+ (1ULL << CAP_LEASE) |
+ (1ULL << CAP_LINUX_IMMUTABLE) |
+ (1ULL << CAP_NET_BIND_SERVICE) |
+ (1ULL << CAP_NET_BROADCAST) |
+ (1ULL << CAP_NET_RAW) |
+ (1ULL << CAP_SETGID) |
+ (1ULL << CAP_SETFCAP) |
+ (1ULL << CAP_SETPCAP) |
+ (1ULL << CAP_SETUID) |
+ (1ULL << CAP_SYS_ADMIN) |
+ (1ULL << CAP_SYS_CHROOT) |
+ (1ULL << CAP_SYS_NICE) |
+ (1ULL << CAP_SYS_PTRACE) |
+ (1ULL << CAP_SYS_TTY_CONFIG) |
+ (1ULL << CAP_SYS_RESOURCE) |
+ (1ULL << CAP_SYS_BOOT) |
+ (1ULL << CAP_AUDIT_WRITE) |
+ (1ULL << CAP_AUDIT_CONTROL);
+static char **arg_bind = NULL;
+static char **arg_bind_ro = NULL;
+
+static int help(void) {
+
+ printf("%s [OPTIONS...] [PATH] [ARGUMENTS...]\n\n"
+ "Spawn a minimal namespace container for debugging, testing and building.\n\n"
+ " -h --help Show this help\n"
+ " --version Print version string\n"
+ " -D --directory=NAME Root directory for the container\n"
+ " -b --boot Boot up full system (i.e. invoke init)\n"
+ " -u --user=USER Run the command under specified user or uid\n"
+ " -C --controllers=LIST Put the container in specified comma-separated\n"
+ " cgroup hierarchies\n"
+ " --uuid=UUID Set a specific machine UUID for the container\n"
+ " -M --machine=NAME Set the machine name for the container\n"
+ " --private-network Disable network in container\n"
+ " --read-only Mount the root directory read-only\n"
+ " --capability=CAP In addition to the default, retain specified\n"
+ " capability\n"
+ " --link-journal=MODE Link up guest journal, one of no, auto, guest, host\n"
+ " -j Equivalent to --link-journal=host\n"
+ " --bind=PATH[:PATH] Bind mount a file or directory from the host into\n"
+ " the container\n"
+ " --bind-ro=PATH[:PATH] Similar, but creates a read-only bind mount\n",
+ program_invocation_short_name);
+
+ return 0;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+
+ enum {
+ ARG_VERSION = 0x100,
+ ARG_PRIVATE_NETWORK,
+ ARG_UUID,
+ ARG_READ_ONLY,
+ ARG_CAPABILITY,
+ ARG_LINK_JOURNAL,
+ ARG_BIND,
+ ARG_BIND_RO
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "version", no_argument, NULL, ARG_VERSION },
+ { "directory", required_argument, NULL, 'D' },
+ { "user", required_argument, NULL, 'u' },
+ { "controllers", required_argument, NULL, 'C' },
+ { "private-network", no_argument, NULL, ARG_PRIVATE_NETWORK },
+ { "boot", no_argument, NULL, 'b' },
+ { "uuid", required_argument, NULL, ARG_UUID },
+ { "read-only", no_argument, NULL, ARG_READ_ONLY },
+ { "capability", required_argument, NULL, ARG_CAPABILITY },
+ { "link-journal", required_argument, NULL, ARG_LINK_JOURNAL },
+ { "bind", required_argument, NULL, ARG_BIND },
+ { "bind-ro", required_argument, NULL, ARG_BIND_RO },
+ { "machine", required_argument, NULL, 'M' },
+ { NULL, 0, NULL, 0 }
+ };
+
+ int c;
+
+ assert(argc >= 0);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "+hD:u:C:bM:j", options, NULL)) >= 0) {
+
+ switch (c) {
+
+ case 'h':
+ help();
+ return 0;
+
+ case ARG_VERSION:
+ puts(PACKAGE_STRING);
+ puts(SYSTEMD_FEATURES);
+ return 0;
+
+ case 'D':
+ free(arg_directory);
+ arg_directory = canonicalize_file_name(optarg);
+ if (!arg_directory) {
+ log_error("Failed to canonicalize root directory.");
+ return -ENOMEM;
+ }
+
+ break;
+
+ case 'u':
+ free(arg_user);
+ arg_user = strdup(optarg);
+ if (!arg_user)
+ return log_oom();
+
+ break;
+
+ case 'C':
+ strv_free(arg_controllers);
+ arg_controllers = strv_split(optarg, ",");
+ if (!arg_controllers)
+ return log_oom();
+
+ cg_shorten_controllers(arg_controllers);
+ break;
+
+ case ARG_PRIVATE_NETWORK:
+ arg_private_network = true;
+ break;
+
+ case 'b':
+ arg_boot = true;
+ break;
+
+ case ARG_UUID:
+ if (!id128_is_valid(optarg)) {
+ log_error("Invalid UUID: %s", optarg);
+ return -EINVAL;
+ }
+
+ arg_uuid = optarg;
+ break;
+
+ case 'M':
+ if (!hostname_is_valid(optarg)) {
+ log_error("Invalid machine name: %s", optarg);
+ return -EINVAL;
+ }
+
+ free(arg_machine);
+ arg_machine = strdup(optarg);
+ if (!arg_machine)
+ return log_oom();
+
+ break;
+
+ case ARG_READ_ONLY:
+ arg_read_only = true;
+ break;
+
+ case ARG_CAPABILITY: {
+ char *state, *word;
+ size_t length;
+
+ FOREACH_WORD_SEPARATOR(word, length, optarg, ",", state) {
+ cap_value_t cap;
+ char *t;
+
+ t = strndup(word, length);
+ if (!t)
+ return log_oom();
+
+ if (cap_from_name(t, &cap) < 0) {
+ log_error("Failed to parse capability %s.", t);
+ free(t);
+ return -EINVAL;
+ }
+
+ free(t);
+ arg_retain |= 1ULL << (uint64_t) cap;
+ }
+
+ break;
+ }
+
+ case 'j':
+ arg_link_journal = LINK_GUEST;
+ break;
+
+ case ARG_LINK_JOURNAL:
+ if (streq(optarg, "auto"))
+ arg_link_journal = LINK_AUTO;
+ else if (streq(optarg, "no"))
+ arg_link_journal = LINK_NO;
+ else if (streq(optarg, "guest"))
+ arg_link_journal = LINK_GUEST;
+ else if (streq(optarg, "host"))
+ arg_link_journal = LINK_HOST;
+ else {
+ log_error("Failed to parse link journal mode %s", optarg);
+ return -EINVAL;
+ }
+
+ break;
+
+ case ARG_BIND:
+ case ARG_BIND_RO: {
+ _cleanup_free_ char *a = NULL, *b = NULL;
+ char *e;
+ char ***x;
+ int r;
+
+ x = c == ARG_BIND ? &arg_bind : &arg_bind_ro;
+
+ e = strchr(optarg, ':');
+ if (e) {
+ a = strndup(optarg, e - optarg);
+ b = strdup(e + 1);
+ } else {
+ a = strdup(optarg);
+ b = strdup(optarg);
+ }
+
+ if (!a || !b)
+ return log_oom();
+
+ if (!path_is_absolute(a) || !path_is_absolute(b)) {
+ log_error("Invalid bind mount specification: %s", optarg);
+ return -EINVAL;
+ }
+
+ r = strv_extend(x, a);
+ if (r < 0)
+ return r;
+
+ r = strv_extend(x, b);
+ if (r < 0)
+ return r;
+
+ break;
+ }
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ log_error("Unknown option code %c", c);
+ return -EINVAL;
+ }
+ }
+
+ return 1;
+}
+
+static int mount_all(const char *dest) {
+
+ typedef struct MountPoint {
+ const char *what;
+ const char *where;
+ const char *type;
+ const char *options;
+ unsigned long flags;
+ bool fatal;
+ } MountPoint;
+
+ static const MountPoint mount_table[] = {
+ { "proc", "/proc", "proc", NULL, MS_NOSUID|MS_NOEXEC|MS_NODEV, true },
+ { "/proc/sys", "/proc/sys", NULL, NULL, MS_BIND, true }, /* Bind mount first */
+ { NULL, "/proc/sys", NULL, NULL, MS_BIND|MS_RDONLY|MS_REMOUNT, true }, /* Then, make it r/o */
+ { "sysfs", "/sys", "sysfs", NULL, MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV, true },
+ { "tmpfs", "/dev", "tmpfs", "mode=755", MS_NOSUID|MS_STRICTATIME, true },
+ { "devpts", "/dev/pts", "devpts","newinstance,ptmxmode=0666,mode=620,gid=" STRINGIFY(TTY_GID), MS_NOSUID|MS_NOEXEC, true },
+ { "tmpfs", "/dev/shm", "tmpfs", "mode=1777", MS_NOSUID|MS_NODEV|MS_STRICTATIME, true },
+ { "tmpfs", "/run", "tmpfs", "mode=755", MS_NOSUID|MS_NODEV|MS_STRICTATIME, true },
+#ifdef HAVE_SELINUX
+ { "/sys/fs/selinux", "/sys/fs/selinux", NULL, NULL, MS_BIND, false }, /* Bind mount first */
+ { NULL, "/sys/fs/selinux", NULL, NULL, MS_BIND|MS_RDONLY|MS_REMOUNT, false }, /* Then, make it r/o */
+#endif
+ };
+
+ unsigned k;
+ int r = 0;
+
+ for (k = 0; k < ELEMENTSOF(mount_table); k++) {
+ _cleanup_free_ char *where = NULL;
+ int t;
+
+ where = strjoin(dest, "/", mount_table[k].where, NULL);
+ if (!where)
+ return log_oom();
+
+ t = path_is_mount_point(where, true);
+ if (t < 0) {
+ log_error("Failed to detect whether %s is a mount point: %s", where, strerror(-t));
+
+ if (r == 0)
+ r = t;
+
+ continue;
+ }
+
+ /* Skip this entry if it is not a remount. */
+ if (mount_table[k].what && t > 0)
+ continue;
+
+ mkdir_p(where, 0755);
+
+ if (mount(mount_table[k].what,
+ where,
+ mount_table[k].type,
+ mount_table[k].flags,
+ mount_table[k].options) < 0 &&
+ mount_table[k].fatal) {
+
+ log_error("mount(%s) failed: %m", where);
+
+ if (r == 0)
+ r = -errno;
+ }
+ }
+
+ return r;
+}
+
+static int mount_binds(const char *dest, char **l, unsigned long flags) {
+ char **x, **y;
+
+ STRV_FOREACH_PAIR(x, y, l) {
+ _cleanup_free_ char *where = NULL;
+
+ where = strjoin(dest, "/", *y, NULL);
+ if (!where)
+ return log_oom();
+
+ mkdir_p_label(where, 0755);
+
+ if (mount(*x, where, "bind", MS_BIND, NULL) < 0) {
+ log_error("mount(%s) failed: %m", where);
+ return -errno;
+ }
+
+ if (flags && mount(NULL, where, NULL, MS_REMOUNT|MS_BIND|flags, NULL) < 0) {
+ log_error("mount(%s) failed: %m", where);
+ return -errno;
+ }
+ }
+
+ return 0;
+}
+
+static int setup_timezone(const char *dest) {
+ _cleanup_free_ char *where = NULL, *p = NULL, *q = NULL, *check = NULL, *what = NULL;
+ char *z, *y;
+ int r;
+
+ assert(dest);
+
+ /* Fix the timezone, if possible */
+ r = readlink_malloc("/etc/localtime", &p);
+ if (r < 0) {
+ log_warning("/etc/localtime is not a symlink, not updating container timezone.");
+ return 0;
+ }
+
+ z = path_startswith(p, "../usr/share/zoneinfo/");
+ if (!z)
+ z = path_startswith(p, "/usr/share/zoneinfo/");
+ if (!z) {
+ log_warning("/etc/localtime does not point into /usr/share/zoneinfo/, not updating container timezone.");
+ return 0;
+ }
+
+ where = strappend(dest, "/etc/localtime");
+ if (!where)
+ return log_oom();
+
+ r = readlink_malloc(where, &q);
+ if (r >= 0) {
+ y = path_startswith(q, "../usr/share/zoneinfo/");
+ if (!y)
+ y = path_startswith(q, "/usr/share/zoneinfo/");
+
+
+ /* Already pointing to the right place? Then do nothing .. */
+ if (y && streq(y, z))
+ return 0;
+ }
+
+ check = strjoin(dest, "/usr/share/zoneinfo/", z, NULL);
+ if (!check)
+ return log_oom();
+
+ if (access(check, F_OK) < 0) {
+ log_warning("Timezone %s does not exist in container, not updating container timezone.", z);
+ return 0;
+ }
+
+ what = strappend("../usr/share/zoneinfo/", z);
+ if (!what)
+ return log_oom();
+
+ unlink(where);
+ if (symlink(what, where) < 0) {
+ log_error("Failed to correct timezone of container: %m");
+ return 0;
+ }
+
+ return 0;
+}
+
+static int setup_resolv_conf(const char *dest) {
+ char _cleanup_free_ *where = NULL;
+ _cleanup_close_ int fd = -1;
+
+ assert(dest);
+
+ if (arg_private_network)
+ return 0;
+
+ /* Fix resolv.conf, if possible */
+ where = strappend(dest, "/etc/resolv.conf");
+ if (!where)
+ return log_oom();
+
+ fd = open(where, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0644);
+
+ /* We don't really care for the results of this really. If it
+ * fails, it fails, but meh... */
+ if (mount("/etc/resolv.conf", where, "bind", MS_BIND, NULL) < 0)
+ log_warning("Failed to bind mount /etc/resolv.conf: %m");
+ else
+ if (mount("/etc/resolv.conf", where, "bind",
+ MS_BIND|MS_REMOUNT|MS_RDONLY, NULL) < 0) {
+ log_error("Failed to remount /etc/resolv.conf readonly: %m");
+ return -errno;
+ }
+
+ return 0;
+}
+
+static int setup_boot_id(const char *dest) {
+ _cleanup_free_ char *from = NULL, *to = NULL;
+ sd_id128_t rnd;
+ char as_uuid[37];
+ int r;
+
+ assert(dest);
+
+ /* Generate a new randomized boot ID, so that each boot-up of
+ * the container gets a new one */
+
+ from = strappend(dest, "/dev/proc-sys-kernel-random-boot-id");
+ to = strappend(dest, "/proc/sys/kernel/random/boot_id");
+ if (!from || !to)
+ return log_oom();
+
+ r = sd_id128_randomize(&rnd);
+ if (r < 0) {
+ log_error("Failed to generate random boot id: %s", strerror(-r));
+ return r;
+ }
+
+ snprintf(as_uuid, sizeof(as_uuid),
+ "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
+ SD_ID128_FORMAT_VAL(rnd));
+ char_array_0(as_uuid);
+
+ r = write_string_file(from, as_uuid);
+ if (r < 0) {
+ log_error("Failed to write boot id: %s", strerror(-r));
+ return r;
+ }
+
+ if (mount(from, to, "bind", MS_BIND, NULL) < 0) {
+ log_error("Failed to bind mount boot id: %m");
+ r = -errno;
+ } else if (mount(from, to, "bind", MS_BIND|MS_REMOUNT|MS_RDONLY, NULL))
+ log_warning("Failed to make boot id read-only: %m");
+
+ unlink(from);
+ return r;
+}
+
+static int copy_devnodes(const char *dest) {
+
+ static const char devnodes[] =
+ "null\0"
+ "zero\0"
+ "full\0"
+ "random\0"
+ "urandom\0"
+ "tty\0";
+
+ const char *d;
+ int r = 0;
+ _cleanup_umask_ mode_t u;
+
+ assert(dest);
+
+ u = umask(0000);
+
+ NULSTR_FOREACH(d, devnodes) {
+ struct stat st;
+ _cleanup_free_ char *from = NULL, *to = NULL;
+
+ asprintf(&from, "/dev/%s", d);
+ asprintf(&to, "%s/dev/%s", dest, d);
+
+ if (!from || !to) {
+ log_oom();
+
+ if (r == 0)
+ r = -ENOMEM;
+
+ break;
+ }
+
+ if (stat(from, &st) < 0) {
+
+ if (errno != ENOENT) {
+ log_error("Failed to stat %s: %m", from);
+ if (r == 0)
+ r = -errno;
+ }
+
+ } else if (!S_ISCHR(st.st_mode) && !S_ISBLK(st.st_mode)) {
+
+ log_error("%s is not a char or block device, cannot copy", from);
+ if (r == 0)
+ r = -EIO;
+
+ } else if (mknod(to, st.st_mode, st.st_rdev) < 0) {
+
+ log_error("mknod(%s) failed: %m", dest);
+ if (r == 0)
+ r = -errno;
+ }
+ }
+
+ return r;
+}
+
+static int setup_ptmx(const char *dest) {
+ _cleanup_free_ char *p = NULL;
+
+ p = strappend(dest, "/dev/ptmx");
+ if (!p)
+ return log_oom();
+
+ if (symlink("pts/ptmx", p) < 0) {
+ log_error("Failed to create /dev/ptmx symlink: %m");
+ return -errno;
+ }
+
+ return 0;
+}
+
+static int setup_dev_console(const char *dest, const char *console) {
+ struct stat st;
+ _cleanup_free_ char *to = NULL;
+ int r;
+ _cleanup_umask_ mode_t u;
+
+ assert(dest);
+ assert(console);
+
+ u = umask(0000);
+
+ if (stat(console, &st) < 0) {
+ log_error("Failed to stat %s: %m", console);
+ return -errno;
+
+ } else if (!S_ISCHR(st.st_mode)) {
+ log_error("/dev/console is not a char device");
+ return -EIO;
+ }
+
+ r = chmod_and_chown(console, 0600, 0, 0);
+ if (r < 0) {
+ log_error("Failed to correct access mode for TTY: %s", strerror(-r));
+ return r;
+ }
+
+ if (asprintf(&to, "%s/dev/console", dest) < 0)
+ return log_oom();
+
+ /* We need to bind mount the right tty to /dev/console since
+ * ptys can only exist on pts file systems. To have something
+ * to bind mount things on we create a device node first, that
+ * has the right major/minor (note that the major minor
+ * doesn't actually matter here, since we mount it over
+ * anyway). */
+
+ if (mknod(to, (st.st_mode & ~07777) | 0600, st.st_rdev) < 0) {
+ log_error("mknod() for /dev/console failed: %m");
+ return -errno;
+ }
+
+ if (mount(console, to, "bind", MS_BIND, NULL) < 0) {
+ log_error("Bind mount for /dev/console failed: %m");
+ return -errno;
+ }
+
+ return 0;
+}
+
+static int setup_kmsg(const char *dest, int kmsg_socket) {
+ _cleanup_free_ char *from = NULL, *to = NULL;
+ int r, fd, k;
+ _cleanup_umask_ mode_t u;
+ union {
+ struct cmsghdr cmsghdr;
+ uint8_t buf[CMSG_SPACE(sizeof(int))];
+ } control = {};
+ struct msghdr mh = {
+ .msg_control = &control,
+ .msg_controllen = sizeof(control),
+ };
+ struct cmsghdr *cmsg;
+
+ assert(dest);
+ assert(kmsg_socket >= 0);
+
+ u = umask(0000);
+
+ /* We create the kmsg FIFO as /dev/kmsg, but immediately
+ * delete it after bind mounting it to /proc/kmsg. While FIFOs
+ * on the reading side behave very similar to /proc/kmsg,
+ * their writing side behaves differently from /dev/kmsg in
+ * that writing blocks when nothing is reading. In order to
+ * avoid any problems with containers deadlocking due to this
+ * we simply make /dev/kmsg unavailable to the container. */
+ if (asprintf(&from, "%s/dev/kmsg", dest) < 0 ||
+ asprintf(&to, "%s/proc/kmsg", dest) < 0)
+ return log_oom();
+
+ if (mkfifo(from, 0600) < 0) {
+ log_error("mkfifo() for /dev/kmsg failed: %m");
+ return -errno;
+ }
+
+ r = chmod_and_chown(from, 0600, 0, 0);
+ if (r < 0) {
+ log_error("Failed to correct access mode for /dev/kmsg: %s", strerror(-r));
+ return r;
+ }
+
+ if (mount(from, to, "bind", MS_BIND, NULL) < 0) {
+ log_error("Bind mount for /proc/kmsg failed: %m");
+ return -errno;
+ }
+
+ fd = open(from, O_RDWR|O_NDELAY|O_CLOEXEC);
+ if (fd < 0) {
+ log_error("Failed to open fifo: %m");
+ return -errno;
+ }
+
+ cmsg = CMSG_FIRSTHDR(&mh);
+ cmsg->cmsg_level = SOL_SOCKET;
+ cmsg->cmsg_type = SCM_RIGHTS;
+ cmsg->cmsg_len = CMSG_LEN(sizeof(int));
+ memcpy(CMSG_DATA(cmsg), &fd, sizeof(int));
+
+ mh.msg_controllen = cmsg->cmsg_len;
+
+ /* Store away the fd in the socket, so that it stays open as
+ * long as we run the child */
+ k = sendmsg(kmsg_socket, &mh, MSG_DONTWAIT|MSG_NOSIGNAL);
+ close_nointr_nofail(fd);
+
+ if (k < 0) {
+ log_error("Failed to send FIFO fd: %m");
+ return -errno;
+ }
+
+ /* And now make the FIFO unavailable as /dev/kmsg... */
+ unlink(from);
+ return 0;
+}
+
+static int setup_hostname(void) {
+
+ if (sethostname(arg_machine, strlen(arg_machine)) < 0)
+ return -errno;
+
+ return 0;
+}
+
+static int setup_journal(const char *directory) {
+ sd_id128_t machine_id;
+ _cleanup_free_ char *p = NULL, *b = NULL, *q = NULL, *d = NULL;
+ char *id;
+ int r;
+
+ if (arg_link_journal == LINK_NO)
+ return 0;
+
+ p = strappend(directory, "/etc/machine-id");
+ if (!p)
+ return log_oom();
+
+ r = read_one_line_file(p, &b);
+ if (r == -ENOENT && arg_link_journal == LINK_AUTO)
+ return 0;
+ else if (r < 0) {
+ log_error("Failed to read machine ID from %s: %s", p, strerror(-r));
+ return r;
+ }
+
+ id = strstrip(b);
+ if (isempty(id) && arg_link_journal == LINK_AUTO)
+ return 0;
+
+ /* Verify validity */
+ r = sd_id128_from_string(id, &machine_id);
+ if (r < 0) {
+ log_error("Failed to parse machine ID from %s: %s", p, strerror(-r));
+ return r;
+ }
+
+ free(p);
+ p = strappend("/var/log/journal/", id);
+ q = strjoin(directory, "/var/log/journal/", id, NULL);
+ if (!p || !q)
+ return log_oom();
+
+ if (path_is_mount_point(p, false) > 0) {
+ if (arg_link_journal != LINK_AUTO) {
+ log_error("%s: already a mount point, refusing to use for journal", p);
+ return -EEXIST;
+ }
+
+ return 0;
+ }
+
+ if (path_is_mount_point(q, false) > 0) {
+ if (arg_link_journal != LINK_AUTO) {
+ log_error("%s: already a mount point, refusing to use for journal", q);
+ return -EEXIST;
+ }
+
+ return 0;
+ }
+
+ r = readlink_and_make_absolute(p, &d);
+ if (r >= 0) {
+ if ((arg_link_journal == LINK_GUEST ||
+ arg_link_journal == LINK_AUTO) &&
+ path_equal(d, q)) {
+
+ r = mkdir_p(q, 0755);
+ if (r < 0)
+ log_warning("failed to create directory %s: %m", q);
+ return 0;
+ }
+
+ if (unlink(p) < 0) {
+ log_error("Failed to remove symlink %s: %m", p);
+ return -errno;
+ }
+ } else if (r == -EINVAL) {
+
+ if (arg_link_journal == LINK_GUEST &&
+ rmdir(p) < 0) {
+
+ if (errno == ENOTDIR) {
+ log_error("%s already exists and is neither a symlink nor a directory", p);
+ return r;
+ } else {
+ log_error("Failed to remove %s: %m", p);
+ return -errno;
+ }
+ }
+ } else if (r != -ENOENT) {
+ log_error("readlink(%s) failed: %m", p);
+ return r;
+ }
+
+ if (arg_link_journal == LINK_GUEST) {
+
+ if (symlink(q, p) < 0) {
+ log_error("Failed to symlink %s to %s: %m", q, p);
+ return -errno;
+ }
+
+ r = mkdir_p(q, 0755);
+ if (r < 0)
+ log_warning("failed to create directory %s: %m", q);
+ return 0;
+ }
+
+ if (arg_link_journal == LINK_HOST) {
+ r = mkdir_p(p, 0755);
+ if (r < 0) {
+ log_error("Failed to create %s: %m", p);
+ return r;
+ }
+
+ } else if (access(p, F_OK) < 0)
+ return 0;
+
+ if (dir_is_empty(q) == 0) {
+ log_error("%s not empty.", q);
+ return -ENOTEMPTY;
+ }
+
+ r = mkdir_p(q, 0755);
+ if (r < 0) {
+ log_error("Failed to create %s: %m", q);
+ return r;
+ }
+
+ if (mount(p, q, "bind", MS_BIND, NULL) < 0) {
+ log_error("Failed to bind mount journal from host into guest: %m");
+ return -errno;
+ }
+
+ return 0;
+}
+
+static int setup_cgroup(const char *path) {
+ char **c;
+ int r;
+
+ r = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, path, 1);
+ if (r < 0) {
+ log_error("Failed to create cgroup: %s", strerror(-r));
+ return r;
+ }
+
+ STRV_FOREACH(c, arg_controllers) {
+ r = cg_create_and_attach(*c, path, 1);
+ if (r < 0)
+ log_warning("Failed to create cgroup in controller %s: %s", *c, strerror(-r));
+ }
+
+ return 0;
+}
+
+static int save_attributes(const char *cgroup, pid_t pid, const char *uuid, const char *directory) {
+#ifdef HAVE_XATTR
+ _cleanup_free_ char *path = NULL;
+ char buf[DECIMAL_STR_MAX(pid_t)];
+ int r = 0, k;
+
+ assert(cgroup);
+ assert(pid >= 0);
+ assert(arg_directory);
+
+ assert_se(snprintf(buf, sizeof(buf), "%lu", (unsigned long) pid) < (int) sizeof(buf));
+
+ r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, cgroup, NULL, &path);
+ if (r < 0) {
+ log_error("Failed to get path: %s", strerror(-r));
+ return r;
+ }
+
+ r = setxattr(path, "trusted.init_pid", buf, strlen(buf), XATTR_CREATE);
+ if (r < 0)
+ log_warning("Failed to set %s attribute on %s: %m", "trusted.init_pid", path);
+
+ if (uuid) {
+ k = setxattr(path, "trusted.machine_id", uuid, strlen(uuid), XATTR_CREATE);
+ if (k < 0) {
+ log_warning("Failed to set %s attribute on %s: %m", "trusted.machine_id", path);
+ if (r == 0)
+ r = k;
+ }
+ }
+
+ k = setxattr(path, "trusted.root_directory", directory, strlen(directory), XATTR_CREATE);
+ if (k < 0) {
+ log_warning("Failed to set %s attribute on %s: %m", "trusted.root_directory", path);
+ if (r == 0)
+ r = k;
+ }
+ return r;
+#else
+ return 0;
+#endif
+}
+
+static int drop_capabilities(void) {
+ return capability_bounding_set_drop(~arg_retain, false);
+}
+
+static int process_pty(int master, pid_t pid, sigset_t *mask) {
+
+ char in_buffer[LINE_MAX], out_buffer[LINE_MAX];
+ size_t in_buffer_full = 0, out_buffer_full = 0;
+ struct epoll_event stdin_ev, stdout_ev, master_ev, signal_ev;
+ bool stdin_readable = false, stdout_writable = false, master_readable = false, master_writable = false;
+ int ep = -1, signal_fd = -1, r;
+ bool tried_orderly_shutdown = false;
+
+ assert(master >= 0);
+ assert(pid > 0);
+ assert(mask);
+
+ fd_nonblock(STDIN_FILENO, 1);
+ fd_nonblock(STDOUT_FILENO, 1);
+ fd_nonblock(master, 1);
+
+ signal_fd = signalfd(-1, mask, SFD_NONBLOCK|SFD_CLOEXEC);
+ if (signal_fd < 0) {
+ log_error("signalfd(): %m");
+ r = -errno;
+ goto finish;
+ }
+
+ ep = epoll_create1(EPOLL_CLOEXEC);
+ if (ep < 0) {
+ log_error("Failed to create epoll: %m");
+ r = -errno;
+ goto finish;
+ }
+
+ /* We read from STDIN only if this is actually a TTY,
+ * otherwise we assume non-interactivity. */
+ if (isatty(STDIN_FILENO)) {
+ zero(stdin_ev);
+ stdin_ev.events = EPOLLIN|EPOLLET;
+ stdin_ev.data.fd = STDIN_FILENO;
+
+ if (epoll_ctl(ep, EPOLL_CTL_ADD, STDIN_FILENO, &stdin_ev) < 0) {
+ log_error("Failed to register STDIN in epoll: %m");
+ r = -errno;
+ goto finish;
+ }
+ }
+
+ zero(stdout_ev);
+ stdout_ev.events = EPOLLOUT|EPOLLET;
+ stdout_ev.data.fd = STDOUT_FILENO;
+
+ zero(master_ev);
+ master_ev.events = EPOLLIN|EPOLLOUT|EPOLLET;
+ master_ev.data.fd = master;
+
+ zero(signal_ev);
+ signal_ev.events = EPOLLIN;
+ signal_ev.data.fd = signal_fd;
+
+ if (epoll_ctl(ep, EPOLL_CTL_ADD, STDOUT_FILENO, &stdout_ev) < 0) {
+ if (errno != EPERM) {
+ log_error("Failed to register stdout in epoll: %m");
+ r = -errno;
+ goto finish;
+ }
+ /* stdout without epoll support. Likely redirected to regular file. */
+ stdout_writable = true;
+ }
+
+ if (epoll_ctl(ep, EPOLL_CTL_ADD, master, &master_ev) < 0 ||
+ epoll_ctl(ep, EPOLL_CTL_ADD, signal_fd, &signal_ev) < 0) {
+ log_error("Failed to register fds in epoll: %m");
+ r = -errno;
+ goto finish;
+ }
+
+ for (;;) {
+ struct epoll_event ev[16];
+ ssize_t k;
+ int i, nfds;
+
+ nfds = epoll_wait(ep, ev, ELEMENTSOF(ev), -1);
+ if (nfds < 0) {
+
+ if (errno == EINTR || errno == EAGAIN)
+ continue;
+
+ log_error("epoll_wait(): %m");
+ r = -errno;
+ goto finish;
+ }
+
+ assert(nfds >= 1);
+
+ for (i = 0; i < nfds; i++) {
+ if (ev[i].data.fd == STDIN_FILENO) {
+
+ if (ev[i].events & (EPOLLIN|EPOLLHUP))
+ stdin_readable = true;
+
+ } else if (ev[i].data.fd == STDOUT_FILENO) {
+
+ if (ev[i].events & (EPOLLOUT|EPOLLHUP))
+ stdout_writable = true;
+
+ } else if (ev[i].data.fd == master) {
+
+ if (ev[i].events & (EPOLLIN|EPOLLHUP))
+ master_readable = true;
+
+ if (ev[i].events & (EPOLLOUT|EPOLLHUP))
+ master_writable = true;
+
+ } else if (ev[i].data.fd == signal_fd) {
+ struct signalfd_siginfo sfsi;
+ ssize_t n;
+
+ n = read(signal_fd, &sfsi, sizeof(sfsi));
+ if (n != sizeof(sfsi)) {
+
+ if (n >= 0) {
+ log_error("Failed to read from signalfd: invalid block size");
+ r = -EIO;
+ goto finish;
+ }
+
+ if (errno != EINTR && errno != EAGAIN) {
+ log_error("Failed to read from signalfd: %m");
+ r = -errno;
+ goto finish;
+ }
+ } else {
+
+ if (sfsi.ssi_signo == SIGWINCH) {
+ struct winsize ws;
+
+ /* The window size changed, let's forward that. */
+ if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) >= 0)
+ ioctl(master, TIOCSWINSZ, &ws);
+ } else if (sfsi.ssi_signo == SIGTERM && arg_boot && !tried_orderly_shutdown) {
+
+ log_info("Trying to halt container. Send SIGTERM again to trigger immediate termination.");
+
+ /* This only works for systemd... */
+ tried_orderly_shutdown = true;
+ kill(pid, SIGRTMIN+3);
+
+ } else {
+ r = 0;
+ goto finish;
+ }
+ }
+ }
+ }
+
+ while ((stdin_readable && in_buffer_full <= 0) ||
+ (master_writable && in_buffer_full > 0) ||
+ (master_readable && out_buffer_full <= 0) ||
+ (stdout_writable && out_buffer_full > 0)) {
+
+ if (stdin_readable && in_buffer_full < LINE_MAX) {
+
+ k = read(STDIN_FILENO, in_buffer + in_buffer_full, LINE_MAX - in_buffer_full);
+ if (k < 0) {
+
+ if (errno == EAGAIN || errno == EPIPE || errno == ECONNRESET || errno == EIO)
+ stdin_readable = false;
+ else {
+ log_error("read(): %m");
+ r = -errno;
+ goto finish;
+ }
+ } else
+ in_buffer_full += (size_t) k;
+ }
+
+ if (master_writable && in_buffer_full > 0) {
+
+ k = write(master, in_buffer, in_buffer_full);
+ if (k < 0) {
+
+ if (errno == EAGAIN || errno == EPIPE || errno == ECONNRESET || errno == EIO)
+ master_writable = false;
+ else {
+ log_error("write(): %m");
+ r = -errno;
+ goto finish;
+ }
+
+ } else {
+ assert(in_buffer_full >= (size_t) k);
+ memmove(in_buffer, in_buffer + k, in_buffer_full - k);
+ in_buffer_full -= k;
+ }
+ }
+
+ if (master_readable && out_buffer_full < LINE_MAX) {
+
+ k = read(master, out_buffer + out_buffer_full, LINE_MAX - out_buffer_full);
+ if (k < 0) {
+
+ if (errno == EAGAIN || errno == EPIPE || errno == ECONNRESET || errno == EIO)
+ master_readable = false;
+ else {
+ log_error("read(): %m");
+ r = -errno;
+ goto finish;
+ }
+ } else
+ out_buffer_full += (size_t) k;
+ }
+
+ if (stdout_writable && out_buffer_full > 0) {
+
+ k = write(STDOUT_FILENO, out_buffer, out_buffer_full);
+ if (k < 0) {
+
+ if (errno == EAGAIN || errno == EPIPE || errno == ECONNRESET || errno == EIO)
+ stdout_writable = false;
+ else {
+ log_error("write(): %m");
+ r = -errno;
+ goto finish;
+ }
+
+ } else {
+ assert(out_buffer_full >= (size_t) k);
+ memmove(out_buffer, out_buffer + k, out_buffer_full - k);
+ out_buffer_full -= k;
+ }
+ }
+ }
+ }
+
+finish:
+ if (ep >= 0)
+ close_nointr_nofail(ep);
+
+ if (signal_fd >= 0)
+ close_nointr_nofail(signal_fd);
+
+ return r;
+}
+
+int main(int argc, char *argv[]) {
+ pid_t pid = 0;
+ int r = EXIT_FAILURE, k;
+ _cleanup_free_ char *newcg = NULL;
+ _cleanup_close_ int master = -1;
+ int n_fd_passed;
+ const char *console = NULL;
+ struct termios saved_attr, raw_attr;
+ sigset_t mask;
+ bool saved_attr_valid = false;
+ struct winsize ws;
+ int kmsg_socket_pair[2] = { -1, -1 };
+ FDSet *fds = NULL;
+
+ log_parse_environment();
+ log_open();
+
+ k = parse_argv(argc, argv);
+ if (k < 0)
+ goto finish;
+ else if (k == 0) {
+ r = EXIT_SUCCESS;
+ goto finish;
+ }
+
+ if (arg_directory) {
+ char *p;
+
+ p = path_make_absolute_cwd(arg_directory);
+ free(arg_directory);
+ arg_directory = p;
+ } else
+ arg_directory = get_current_dir_name();
+
+ if (!arg_directory) {
+ log_error("Failed to determine path, please use -D.");
+ goto finish;
+ }
+
+ path_kill_slashes(arg_directory);
+
+ if (!arg_machine) {
+ arg_machine = strdup(path_get_file_name(arg_directory));
+ if (!arg_machine) {
+ log_oom();
+ goto finish;
+ }
+
+ hostname_cleanup(arg_machine, false);
+ if (isempty(arg_machine)) {
+ log_error("Failed to determine machine name automatically, please use -M.");
+ goto finish;
+ }
+ }
+
+ if (geteuid() != 0) {
+ log_error("Need to be root.");
+ goto finish;
+ }
+
+ if (sd_booted() <= 0) {
+ log_error("Not running on a systemd system.");
+ goto finish;
+ }
+
+ if (path_equal(arg_directory, "/")) {
+ log_error("Spawning container on root directory not supported.");
+ goto finish;
+ }
+
+ if (path_is_os_tree(arg_directory) <= 0) {
+ log_error("Directory %s doesn't look like an OS root directory (/etc/os-release is missing). Refusing.", arg_directory);
+ goto finish;
+ }
+
+ log_close();
+ n_fd_passed = sd_listen_fds(false);
+ if (n_fd_passed > 0) {
+ k = fdset_new_listen_fds(&fds, false);
+ if (k < 0) {
+ log_error("Failed to collect file descriptors: %s", strerror(-k));
+ goto finish;
+ }
+ }
+ fdset_close_others(fds);
+ log_open();
+
+ k = cg_get_machine_path(arg_machine, &newcg);
+ if (k < 0) {
+ log_error("Failed to determine machine cgroup path: %s", strerror(-k));
+ goto finish;
+ }
+
+ k = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, newcg, true);
+ if (k <= 0 && k != -ENOENT) {
+ log_error("Container already running.");
+
+ free(newcg);
+ newcg = NULL;
+
+ goto finish;
+ }
+
+ master = posix_openpt(O_RDWR|O_NOCTTY|O_CLOEXEC|O_NDELAY);
+ if (master < 0) {
+ log_error("Failed to acquire pseudo tty: %m");
+ goto finish;
+ }
+
+ console = ptsname(master);
+ if (!console) {
+ log_error("Failed to determine tty name: %m");
+ goto finish;
+ }
+
+ log_info("Spawning namespace container on %s (console is %s).", arg_directory, console);
+
+ if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) >= 0)
+ ioctl(master, TIOCSWINSZ, &ws);
+
+ if (unlockpt(master) < 0) {
+ log_error("Failed to unlock tty: %m");
+ goto finish;
+ }
+
+ if (tcgetattr(STDIN_FILENO, &saved_attr) >= 0) {
+ saved_attr_valid = true;
+
+ raw_attr = saved_attr;
+ cfmakeraw(&raw_attr);
+ raw_attr.c_lflag &= ~ECHO;
+ }
+
+ if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_NONBLOCK|SOCK_CLOEXEC, 0, kmsg_socket_pair) < 0) {
+ log_error("Failed to create kmsg socket pair.");
+ goto finish;
+ }
+
+ sd_notify(0, "READY=1");
+
+ assert_se(sigemptyset(&mask) == 0);
+ sigset_add_many(&mask, SIGCHLD, SIGWINCH, SIGTERM, SIGINT, -1);
+ assert_se(sigprocmask(SIG_BLOCK, &mask, NULL) == 0);
+
+ for (;;) {
+ siginfo_t status;
+ int pipefd[2], pipefd2[2];
+
+ if (pipe2(pipefd, O_NONBLOCK|O_CLOEXEC) < 0) {
+ log_error("pipe2(): %m");
+ goto finish;
+ }
+
+ if (pipe2(pipefd2, O_NONBLOCK|O_CLOEXEC) < 0) {
+ log_error("pipe2(): %m");
+ close_pipe(pipefd);
+ goto finish;
+ }
+
+ pid = syscall(__NR_clone, SIGCHLD|CLONE_NEWIPC|CLONE_NEWNS|CLONE_NEWPID|CLONE_NEWUTS|(arg_private_network ? CLONE_NEWNET : 0), NULL);
+ if (pid < 0) {
+ if (errno == EINVAL)
+ log_error("clone() failed, do you have namespace support enabled in your kernel? (You need UTS, IPC, PID and NET namespacing built in): %m");
+ else
+ log_error("clone() failed: %m");
+
+ goto finish;
+ }
+
+ if (pid == 0) {
+ /* child */
+ const char *home = NULL;
+ uid_t uid = (uid_t) -1;
+ gid_t gid = (gid_t) -1;
+ unsigned n_env = 2;
+ const char *envp[] = {
+ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
+ "container=systemd-nspawn", /* LXC sets container=lxc, so follow the scheme here */
+ NULL, /* TERM */
+ NULL, /* HOME */
+ NULL, /* USER */
+ NULL, /* LOGNAME */
+ NULL, /* container_uuid */
+ NULL, /* LISTEN_FDS */
+ NULL, /* LISTEN_PID */
+ NULL
+ };
+
+ envp[n_env] = strv_find_prefix(environ, "TERM=");
+ if (envp[n_env])
+ n_env ++;
+
+ /* Wait for the parent process to log our PID */
+ close_nointr_nofail(pipefd[1]);
+ fd_wait_for_event(pipefd[0], POLLHUP, -1);
+ close_nointr_nofail(pipefd[0]);
+
+ close_nointr_nofail(master);
+ master = -1;
+
+ if (saved_attr_valid) {
+ if (tcsetattr(STDIN_FILENO, TCSANOW, &raw_attr) < 0) {
+ log_error("Failed to set terminal attributes: %m");
+ goto child_fail;
+ }
+ }
+
+ close_nointr(STDIN_FILENO);
+ close_nointr(STDOUT_FILENO);
+ close_nointr(STDERR_FILENO);
+
+ close_nointr_nofail(kmsg_socket_pair[0]);
+ kmsg_socket_pair[0] = -1;
+
+ reset_all_signal_handlers();
+
+ assert_se(sigemptyset(&mask) == 0);
+ assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
+
+ k = open_terminal(console, O_RDWR);
+ if (k != STDIN_FILENO) {
+ if (k >= 0) {
+ close_nointr_nofail(k);
+ k = -EINVAL;
+ }
+
+ log_error("Failed to open console: %s", strerror(-k));
+ goto child_fail;
+ }
+
+ if (dup2(STDIN_FILENO, STDOUT_FILENO) != STDOUT_FILENO ||
+ dup2(STDIN_FILENO, STDERR_FILENO) != STDERR_FILENO) {
+ log_error("Failed to duplicate console: %m");
+ goto child_fail;
+ }
+
+ if (setsid() < 0) {
+ log_error("setsid() failed: %m");
+ goto child_fail;
+ }
+
+ if (prctl(PR_SET_PDEATHSIG, SIGKILL) < 0) {
+ log_error("PR_SET_PDEATHSIG failed: %m");
+ goto child_fail;
+ }
+
+ if (setup_cgroup(newcg) < 0)
+ goto child_fail;
+
+ close_pipe(pipefd2);
+
+ /* Mark everything as slave, so that we still
+ * receive mounts from the real root, but don't
+ * propagate mounts to the real root. */
+ if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL) < 0) {
+ log_error("MS_SLAVE|MS_REC failed: %m");
+ goto child_fail;
+ }
+
+ /* Turn directory into bind mount */
+ if (mount(arg_directory, arg_directory, "bind", MS_BIND|MS_REC, NULL) < 0) {
+ log_error("Failed to make bind mount.");
+ goto child_fail;
+ }
+
+ if (arg_read_only)
+ if (mount(arg_directory, arg_directory, "bind", MS_BIND|MS_REMOUNT|MS_RDONLY|MS_REC, NULL) < 0) {
+ log_error("Failed to make read-only.");
+ goto child_fail;
+ }
+
+ if (mount_all(arg_directory) < 0)
+ goto child_fail;
+
+ if (copy_devnodes(arg_directory) < 0)
+ goto child_fail;
+
+ if (setup_ptmx(arg_directory) < 0)
+ goto child_fail;
+
+ dev_setup(arg_directory);
+
+ if (setup_dev_console(arg_directory, console) < 0)
+ goto child_fail;
+
+ if (setup_kmsg(arg_directory, kmsg_socket_pair[1]) < 0)
+ goto child_fail;
+
+ close_nointr_nofail(kmsg_socket_pair[1]);
+ kmsg_socket_pair[1] = -1;
+
+ if (setup_boot_id(arg_directory) < 0)
+ goto child_fail;
+
+ if (setup_timezone(arg_directory) < 0)
+ goto child_fail;
+
+ if (setup_resolv_conf(arg_directory) < 0)
+ goto child_fail;
+
+ if (setup_journal(arg_directory) < 0)
+ goto child_fail;
+
+ if (mount_binds(arg_directory, arg_bind, 0) < 0)
+ goto child_fail;
+
+ if (mount_binds(arg_directory, arg_bind_ro, MS_RDONLY) < 0)
+ goto child_fail;
+
+ if (chdir(arg_directory) < 0) {
+ log_error("chdir(%s) failed: %m", arg_directory);
+ goto child_fail;
+ }
+
+ if (mount(arg_directory, "/", NULL, MS_MOVE, NULL) < 0) {
+ log_error("mount(MS_MOVE) failed: %m");
+ goto child_fail;
+ }
+
+ if (chroot(".") < 0) {
+ log_error("chroot() failed: %m");
+ goto child_fail;
+ }
+
+ if (chdir("/") < 0) {
+ log_error("chdir() failed: %m");
+ goto child_fail;
+ }
+
+ umask(0022);
+
+ loopback_setup();
+
+ if (drop_capabilities() < 0) {
+ log_error("drop_capabilities() failed: %m");
+ goto child_fail;
+ }
+
+ if (arg_user) {
+
+ /* Note that this resolves user names
+ * inside the container, and hence
+ * accesses the NSS modules from the
+ * container and not the host. This is
+ * a bit weird... */
+
+ if (get_user_creds((const char**)&arg_user, &uid, &gid, &home, NULL) < 0) {
+ log_error("get_user_creds() failed: %m");
+ goto child_fail;
+ }
+
+ if (mkdir_parents_label(home, 0775) < 0) {
+ log_error("mkdir_parents_label() failed: %m");
+ goto child_fail;
+ }
+
+ if (mkdir_safe_label(home, 0775, uid, gid) < 0) {
+ log_error("mkdir_safe_label() failed: %m");
+ goto child_fail;
+ }
+
+ if (initgroups((const char*)arg_user, gid) < 0) {
+ log_error("initgroups() failed: %m");
+ goto child_fail;
+ }
+
+ if (setresgid(gid, gid, gid) < 0) {
+ log_error("setregid() failed: %m");
+ goto child_fail;
+ }
+
+ if (setresuid(uid, uid, uid) < 0) {
+ log_error("setreuid() failed: %m");
+ goto child_fail;
+ }
+ } else {
+ /* Reset everything fully to 0, just in case */
+
+ if (setgroups(0, NULL) < 0) {
+ log_error("setgroups() failed: %m");
+ goto child_fail;
+ }
+
+ if (setresgid(0, 0, 0) < 0) {
+ log_error("setregid() failed: %m");
+ goto child_fail;
+ }
+
+ if (setresuid(0, 0, 0) < 0) {
+ log_error("setreuid() failed: %m");
+ goto child_fail;
+ }
+ }
+
+ if ((asprintf((char**)(envp + n_env++), "HOME=%s", home ? home: "/root") < 0) ||
+ (asprintf((char**)(envp + n_env++), "USER=%s", arg_user ? arg_user : "root") < 0) ||
+ (asprintf((char**)(envp + n_env++), "LOGNAME=%s", arg_user ? arg_user : "root") < 0)) {
+ log_oom();
+ goto child_fail;
+ }
+
+ if (arg_uuid) {
+ if (asprintf((char**)(envp + n_env++), "container_uuid=%s", arg_uuid) < 0) {
+ log_oom();
+ goto child_fail;
+ }
+ }
+
+ if (fdset_size(fds) > 0) {
+ k = fdset_cloexec(fds, false);
+ if (k < 0) {
+ log_error("Failed to unset O_CLOEXEC for file descriptors.");
+ goto child_fail;
+ }
+
+ if ((asprintf((char **)(envp + n_env++), "LISTEN_FDS=%u", n_fd_passed) < 0) ||
+ (asprintf((char **)(envp + n_env++), "LISTEN_PID=%lu", (unsigned long) 1) < 0)) {
+ log_oom();
+ goto child_fail;
+ }
+ }
+
+ setup_hostname();
+
+ if (arg_boot) {
+ char **a;
+ size_t l;
+
+ /* Automatically search for the init system */
+
+ l = 1 + argc - optind;
+ a = newa(char*, l + 1);
+ memcpy(a + 1, argv + optind, l * sizeof(char*));
+
+ a[0] = (char*) "/usr/lib/systemd/systemd";
+ execve(a[0], a, (char**) envp);
+
+ a[0] = (char*) "/lib/systemd/systemd";
+ execve(a[0], a, (char**) envp);
+
+ a[0] = (char*) "/sbin/init";
+ execve(a[0], a, (char**) envp);
+ } else if (argc > optind)
+ execvpe(argv[optind], argv + optind, (char**) envp);
+ else {
+ chdir(home ? home : "/root");
+ execle("/bin/bash", "-bash", NULL, (char**) envp);
+ }
+
+ log_error("execv() failed: %m");
+
+ child_fail:
+ _exit(EXIT_FAILURE);
+ }
+
+ log_info("Init process in the container running as PID %lu.", (unsigned long) pid);
+ close_nointr_nofail(pipefd[0]);
+ close_nointr_nofail(pipefd[1]);
+
+ /* Wait for the child process to establish cgroup hierarchy */
+ close_nointr_nofail(pipefd2[1]);
+ fd_wait_for_event(pipefd2[0], POLLHUP, -1);
+ close_nointr_nofail(pipefd2[0]);
+
+ save_attributes(newcg, pid, arg_uuid, arg_directory);
+
+ fdset_free(fds);
+ fds = NULL;
+
+ if (process_pty(master, pid, &mask) < 0)
+ goto finish;
+
+ if (saved_attr_valid)
+ tcsetattr(STDIN_FILENO, TCSANOW, &saved_attr);
+
+ k = wait_for_terminate(pid, &status);
+ if (k < 0) {
+ r = EXIT_FAILURE;
+ break;
+ }
+
+ if (status.si_code == CLD_EXITED) {
+ r = status.si_status;
+ if (status.si_status != 0) {
+ log_error("Container failed with error code %i.", status.si_status);
+ break;
+ }
+
+ log_debug("Container exited successfully.");
+ break;
+ } else if (status.si_code == CLD_KILLED &&
+ status.si_status == SIGINT) {
+ log_info("Container has been shut down.");
+ r = 0;
+ break;
+ } else if (status.si_code == CLD_KILLED &&
+ status.si_status == SIGHUP) {
+ log_info("Container is being rebooted.");
+ continue;
+ } else if (status.si_code == CLD_KILLED ||
+ status.si_code == CLD_DUMPED) {
+
+ log_error("Container terminated by signal %s.", signal_to_string(status.si_status));
+ r = EXIT_FAILURE;
+ break;
+ } else {
+ log_error("Container failed due to unknown reason.");
+ r = EXIT_FAILURE;
+ break;
+ }
+ }
+
+finish:
+ if (saved_attr_valid)
+ tcsetattr(STDIN_FILENO, TCSANOW, &saved_attr);
+
+ close_pipe(kmsg_socket_pair);
+
+ if (newcg)
+ cg_kill_recursive_and_wait(SYSTEMD_CGROUP_CONTROLLER, newcg, true);
+
+ free(arg_directory);
+ free(arg_machine);
+ strv_free(arg_controllers);
+
+ fdset_free(fds);
+
+ return r;
+}
diff --git a/src/nss-myhostname/ifconf.h b/src/nss-myhostname/ifconf.h
new file mode 100644
index 0000000000..2764a0aa0f
--- /dev/null
+++ b/src/nss-myhostname/ifconf.h
@@ -0,0 +1,73 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef fooifconfhfoo
+#define fooifconfhfoo
+
+#include <sys/socket.h>
+
+/***
+ This file is part of systemd.
+
+ Copyright 2008-2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <inttypes.h>
+#include <sys/types.h>
+#include <assert.h>
+
+struct address {
+ unsigned char family;
+ uint8_t address[16];
+ unsigned char scope;
+ int ifindex;
+};
+
+#define _public_ __attribute__ ((visibility("default")))
+#define _hidden_ __attribute__ ((visibility("hidden")))
+
+int ifconf_acquire_addresses(struct address **_list, unsigned *_n_list) _hidden_;
+
+static inline size_t PROTO_ADDRESS_SIZE(int proto) {
+ assert(proto == AF_INET || proto == AF_INET6);
+
+ return proto == AF_INET6 ? 16 : 4;
+}
+
+static inline int address_compare(const void *_a, const void *_b) {
+ const struct address *a = _a, *b = _b;
+
+ /* Order lowest scope first, IPv4 before IPv6, lowest interface index first */
+
+ if (a->scope < b->scope)
+ return -1;
+ if (a->scope > b->scope)
+ return 1;
+
+ if (a->family == AF_INET && b->family == AF_INET6)
+ return -1;
+ if (a->family == AF_INET6 && b->family == AF_INET)
+ return 1;
+
+ if (a->ifindex < b->ifindex)
+ return -1;
+ if (a->ifindex > b->ifindex)
+ return 1;
+
+ return 0;
+}
+
+
+#endif
diff --git a/src/nss-myhostname/netlink.c b/src/nss-myhostname/netlink.c
new file mode 100644
index 0000000000..b1ef912c8a
--- /dev/null
+++ b/src/nss-myhostname/netlink.c
@@ -0,0 +1,206 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2008-2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <asm/types.h>
+#include <inttypes.h>
+#include <linux/netlink.h>
+#include <linux/rtnetlink.h>
+#include <string.h>
+#include <assert.h>
+#include <errno.h>
+#include <limits.h>
+#include <arpa/inet.h>
+#include <unistd.h>
+#include <inttypes.h>
+#include <stdlib.h>
+
+#include "ifconf.h"
+
+#define SEQ 4711
+
+static int read_reply(int fd, struct address **list, unsigned *n_list) {
+ ssize_t bytes;
+ struct cmsghdr *cmsg;
+ struct ucred *ucred;
+ struct nlmsghdr *p;
+ uint8_t cred_buffer[CMSG_SPACE(sizeof(struct ucred))];
+ struct {
+ struct nlmsghdr hdr;
+ struct ifaddrmsg ifaddrmsg;
+ uint8_t payload[16*1024];
+ } resp;
+ struct iovec iov = {
+ .iov_base = &resp,
+ .iov_len = sizeof(resp),
+ };
+ struct msghdr msg = {
+ .msg_name = NULL,
+ .msg_namelen = 0,
+ .msg_iov = &iov,
+ .msg_iovlen = 1,
+ .msg_control = cred_buffer,
+ .msg_controllen = sizeof(cred_buffer),
+ .msg_flags = 0,
+ };
+
+ assert(fd >= 0);
+ assert(list);
+
+ bytes = recvmsg(fd, &msg, 0);
+ if (bytes < 0)
+ return -errno;
+
+ cmsg = CMSG_FIRSTHDR(&msg);
+ if (!cmsg || cmsg->cmsg_type != SCM_CREDENTIALS)
+ return -EIO;
+
+ ucred = (struct ucred*) CMSG_DATA(cmsg);
+ if (ucred->uid != 0 || ucred->pid != 0)
+ return 0;
+
+ for (p = &resp.hdr; bytes > 0; p = NLMSG_NEXT(p, bytes)) {
+ struct ifaddrmsg *ifaddrmsg;
+ struct rtattr *a;
+ size_t l;
+ void *local = NULL, *address = NULL;
+
+ if (!NLMSG_OK(p, (size_t) bytes))
+ return -EIO;
+
+ if (p->nlmsg_seq != SEQ)
+ continue;
+
+ if (p->nlmsg_type == NLMSG_DONE)
+ return 1;
+
+ if (p->nlmsg_type == NLMSG_ERROR) {
+ struct nlmsgerr *nlmsgerr;
+
+ nlmsgerr = NLMSG_DATA(p);
+ return -nlmsgerr->error;
+ }
+
+ if (p->nlmsg_type != RTM_NEWADDR)
+ continue;
+
+ ifaddrmsg = NLMSG_DATA(p);
+
+ if (ifaddrmsg->ifa_family != AF_INET &&
+ ifaddrmsg->ifa_family != AF_INET6)
+ continue;
+
+ if (ifaddrmsg->ifa_scope == RT_SCOPE_HOST ||
+ ifaddrmsg->ifa_scope == RT_SCOPE_NOWHERE)
+ continue;
+
+ if (ifaddrmsg->ifa_flags & IFA_F_DEPRECATED)
+ continue;
+
+ l = NLMSG_PAYLOAD(p, sizeof(struct ifaddrmsg));
+ a = IFA_RTA(ifaddrmsg);
+
+ while (RTA_OK(a, l)) {
+
+ if (a->rta_type == IFA_ADDRESS)
+ address = RTA_DATA(a);
+ else if (a->rta_type == IFA_LOCAL)
+ local = RTA_DATA(a);
+
+ a = RTA_NEXT(a, l);
+ }
+
+ if (local)
+ address = local;
+
+ if (!address)
+ continue;
+
+ *list = realloc(*list, (*n_list+1) * sizeof(struct address));
+ if (!*list)
+ return -ENOMEM;
+
+ (*list)[*n_list].family = ifaddrmsg->ifa_family;
+ (*list)[*n_list].scope = ifaddrmsg->ifa_scope;
+ memcpy((*list)[*n_list].address,
+ address, ifaddrmsg->ifa_family == AF_INET ? 4 : 16);
+ (*list)[*n_list].ifindex = ifaddrmsg->ifa_index;
+
+ (*n_list)++;
+ }
+
+ return 0;
+}
+
+
+int ifconf_acquire_addresses(struct address **_list, unsigned *_n_list) {
+
+ struct {
+ struct nlmsghdr hdr;
+ struct rtgenmsg gen;
+ } req = { {
+ .nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg)),
+ .nlmsg_type = RTM_GETADDR,
+ .nlmsg_flags = NLM_F_REQUEST|NLM_F_DUMP|NLM_F_ACK,
+ .nlmsg_seq = SEQ,
+ .nlmsg_pid = 0,
+ }, {
+ .rtgen_family = AF_UNSPEC,
+ }
+ };
+ int r, on = 1;
+ struct address *list = NULL;
+ unsigned n_list = 0;
+ int fd;
+
+ fd = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
+ if (fd < 0)
+ return -errno;
+
+ if (setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &on, sizeof(on)) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ if (send(fd, &req, req.hdr.nlmsg_len, 0) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ while((r = read_reply(fd, &list, &n_list)) == 0)
+ ;
+
+finish:
+ close(fd);
+
+ if (r < 0) {
+ free(list);
+ return r;
+ }
+
+ qsort(list, n_list, sizeof(struct address), address_compare);
+
+ *_list = list;
+ *_n_list = n_list;
+
+ return 0;
+}
diff --git a/src/nss-myhostname/nss-myhostname.c b/src/nss-myhostname/nss-myhostname.c
new file mode 100644
index 0000000000..60e256d54f
--- /dev/null
+++ b/src/nss-myhostname/nss-myhostname.c
@@ -0,0 +1,533 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2008-2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <limits.h>
+#include <nss.h>
+#include <sys/types.h>
+#include <netdb.h>
+#include <errno.h>
+#include <string.h>
+#include <unistd.h>
+#include <net/if.h>
+#include <stdlib.h>
+#include <arpa/inet.h>
+
+#include "ifconf.h"
+#include "macro.h"
+
+/* Ensure that glibc's assert is used. We cannot use assert from macro.h, as
+ * libnss_myhostname will be linked into arbitrary programs which will, in turn
+ * attempt to write to the journal via log_dispatch() */
+#include <assert.h>
+
+/* We use 127.0.0.2 as IPv4 address. This has the advantage over
+ * 127.0.0.1 that it can be translated back to the local hostname. For
+ * IPv6 we use ::1 which unfortunately will not translate back to the
+ * hostname but instead something like "localhost6" or so. */
+
+#define LOCALADDRESS_IPV4 (htonl(0x7F000002))
+#define LOCALADDRESS_IPV6 &in6addr_loopback
+#define LOOPBACK_INTERFACE "lo"
+
+enum nss_status _nss_myhostname_gethostbyname4_r(
+ const char *name,
+ struct gaih_addrtuple **pat,
+ char *buffer, size_t buflen,
+ int *errnop, int *h_errnop,
+ int32_t *ttlp) _public_;
+
+enum nss_status _nss_myhostname_gethostbyname3_r(
+ const char *name,
+ int af,
+ struct hostent *host,
+ char *buffer, size_t buflen,
+ int *errnop, int *h_errnop,
+ int32_t *ttlp,
+ char **canonp) _public_;
+
+enum nss_status _nss_myhostname_gethostbyname2_r(
+ const char *name,
+ int af,
+ struct hostent *host,
+ char *buffer, size_t buflen,
+ int *errnop, int *h_errnop) _public_;
+
+enum nss_status _nss_myhostname_gethostbyname_r(
+ const char *name,
+ struct hostent *host,
+ char *buffer, size_t buflen,
+ int *errnop, int *h_errnop) _public_;
+
+enum nss_status _nss_myhostname_gethostbyaddr2_r(
+ const void* addr, socklen_t len,
+ int af,
+ struct hostent *host,
+ char *buffer, size_t buflen,
+ int *errnop, int *h_errnop,
+ int32_t *ttlp) _public_;
+
+enum nss_status _nss_myhostname_gethostbyaddr_r(
+ const void* addr, socklen_t len,
+ int af,
+ struct hostent *host,
+ char *buffer, size_t buflen,
+ int *errnop, int *h_errnop) _public_;
+
+enum nss_status _nss_myhostname_gethostbyname4_r(
+ const char *name,
+ struct gaih_addrtuple **pat,
+ char *buffer, size_t buflen,
+ int *errnop, int *h_errnop,
+ int32_t *ttlp) {
+
+ unsigned lo_ifi;
+ char hn[HOST_NAME_MAX+1] = {};
+ const char *canonical = NULL;
+ size_t l, idx, ms;
+ char *r_name;
+ struct gaih_addrtuple *r_tuple, *r_tuple_prev = NULL;
+ struct address *addresses = NULL, *a;
+ unsigned n_addresses = 0, n;
+ uint32_t local_address_ipv4;
+
+ if (strcasecmp(name, "localhost") == 0) {
+ /* We respond to 'localhost', so that /etc/hosts
+ * is optional */
+
+ canonical = "localhost";
+ local_address_ipv4 = htonl(INADDR_LOOPBACK);
+ } else {
+ /* We respond to our local host name */
+
+ if (gethostname(hn, sizeof(hn)-1) < 0) {
+ *errnop = errno;
+ *h_errnop = NO_RECOVERY;
+ return NSS_STATUS_UNAVAIL;
+ }
+
+ if (strcasecmp(name, hn) != 0) {
+ *errnop = ENOENT;
+ *h_errnop = HOST_NOT_FOUND;
+ return NSS_STATUS_NOTFOUND;
+ }
+
+ /* If this fails, n_addresses is 0. Which is fine */
+ ifconf_acquire_addresses(&addresses, &n_addresses);
+
+ canonical = hn;
+ local_address_ipv4 = LOCALADDRESS_IPV4;
+ }
+
+ /* If this call fails we fill in 0 as scope. Which is fine */
+ lo_ifi = n_addresses <= 0 ? if_nametoindex(LOOPBACK_INTERFACE) : 0;
+
+ l = strlen(canonical);
+ ms = ALIGN(l+1)+ALIGN(sizeof(struct gaih_addrtuple))*(n_addresses > 0 ? n_addresses : 2);
+ if (buflen < ms) {
+ *errnop = ENOMEM;
+ *h_errnop = NO_RECOVERY;
+ free(addresses);
+ return NSS_STATUS_TRYAGAIN;
+ }
+
+ /* First, fill in hostname */
+ r_name = buffer;
+ memcpy(r_name, canonical, l+1);
+ idx = ALIGN(l+1);
+
+ if (n_addresses <= 0) {
+ /* Second, fill in IPv6 tuple */
+ r_tuple = (struct gaih_addrtuple*) (buffer + idx);
+ r_tuple->next = r_tuple_prev;
+ r_tuple->name = r_name;
+ r_tuple->family = AF_INET6;
+ memcpy(r_tuple->addr, LOCALADDRESS_IPV6, 16);
+ r_tuple->scopeid = (uint32_t) lo_ifi;
+
+ idx += ALIGN(sizeof(struct gaih_addrtuple));
+ r_tuple_prev = r_tuple;
+
+ /* Third, fill in IPv4 tuple */
+ r_tuple = (struct gaih_addrtuple*) (buffer + idx);
+ r_tuple->next = r_tuple_prev;
+ r_tuple->name = r_name;
+ r_tuple->family = AF_INET;
+ *(uint32_t*) r_tuple->addr = local_address_ipv4;
+ r_tuple->scopeid = (uint32_t) lo_ifi;
+
+ idx += ALIGN(sizeof(struct gaih_addrtuple));
+ r_tuple_prev = r_tuple;
+ }
+
+ /* Fourth, fill actual addresses in, but in backwards order */
+ for (a = addresses + n_addresses - 1, n = 0; n < n_addresses; n++, a--) {
+ r_tuple = (struct gaih_addrtuple*) (buffer + idx);
+ r_tuple->next = r_tuple_prev;
+ r_tuple->name = r_name;
+ r_tuple->family = a->family;
+ r_tuple->scopeid = a->ifindex;
+ memcpy(r_tuple->addr, a->address, 16);
+
+ idx += ALIGN(sizeof(struct gaih_addrtuple));
+ r_tuple_prev = r_tuple;
+ }
+
+ /* Verify the size matches */
+ assert(idx == ms);
+
+ /* Nscd expects us to store the first record in **pat. */
+ if (*pat)
+ **pat = *r_tuple_prev;
+ else
+ *pat = r_tuple_prev;
+
+ if (ttlp)
+ *ttlp = 0;
+
+ free(addresses);
+
+ return NSS_STATUS_SUCCESS;
+}
+
+static enum nss_status fill_in_hostent(
+ const char *canonical, const char *additional,
+ int af,
+ struct address *addresses, unsigned n_addresses,
+ uint32_t local_address_ipv4,
+ struct hostent *result,
+ char *buffer, size_t buflen,
+ int *errnop, int *h_errnop,
+ int32_t *ttlp,
+ char **canonp) {
+
+ size_t l_canonical, l_additional, idx, ms;
+ char *r_addr, *r_name, *r_aliases, *r_alias = NULL, *r_addr_list;
+ size_t alen;
+ struct address *a;
+ unsigned n, c;
+
+ alen = PROTO_ADDRESS_SIZE(af);
+
+ for (a = addresses, n = 0, c = 0; n < n_addresses; a++, n++)
+ if (af == a->family)
+ c++;
+
+ l_canonical = strlen(canonical);
+ l_additional = additional ? strlen(additional) : 0;
+ ms = ALIGN(l_canonical+1)+
+ (additional ? ALIGN(l_additional+1) : 0) +
+ sizeof(char*)+
+ (additional ? sizeof(char*) : 0) +
+ (c > 0 ? c : 1)*ALIGN(alen)+
+ (c > 0 ? c+1 : 2)*sizeof(char*);
+
+ if (buflen < ms) {
+ *errnop = ENOMEM;
+ *h_errnop = NO_RECOVERY;
+ free(addresses);
+ return NSS_STATUS_TRYAGAIN;
+ }
+
+ /* First, fill in hostnames */
+ r_name = buffer;
+ memcpy(r_name, canonical, l_canonical+1);
+ idx = ALIGN(l_canonical+1);
+
+ if (additional) {
+ r_alias = buffer + idx;
+ memcpy(r_alias, additional, l_additional+1);
+ idx += ALIGN(l_additional+1);
+ }
+
+ /* Second, create aliases array */
+ r_aliases = buffer + idx;
+ if (additional) {
+ ((char**) r_aliases)[0] = r_alias;
+ ((char**) r_aliases)[1] = NULL;
+ idx += 2*sizeof(char*);
+ } else {
+ ((char**) r_aliases)[0] = NULL;
+ idx += sizeof(char*);
+ }
+
+ /* Third, add addresses */
+ r_addr = buffer + idx;
+ if (c > 0) {
+ unsigned i = 0;
+
+ for (a = addresses, n = 0; n < n_addresses; a++, n++) {
+ if (af != a->family)
+ continue;
+
+ memcpy(r_addr + i*ALIGN(alen), a->address, alen);
+ i++;
+ }
+
+ assert(i == c);
+ idx += c*ALIGN(alen);
+ } else {
+ if (af == AF_INET)
+ *(uint32_t*) r_addr = local_address_ipv4;
+ else
+ memcpy(r_addr, LOCALADDRESS_IPV6, 16);
+
+ idx += ALIGN(alen);
+ }
+
+ /* Fourth, add address pointer array */
+ r_addr_list = buffer + idx;
+ if (c > 0) {
+ unsigned i = 0;
+
+ for (a = addresses, n = 0; n < n_addresses; a++, n++) {
+ if (af != a->family)
+ continue;
+
+ ((char**) r_addr_list)[i] = (r_addr + i*ALIGN(alen));
+ i++;
+ }
+
+ assert(i == c);
+ ((char**) r_addr_list)[c] = NULL;
+ idx += (c+1)*sizeof(char*);
+
+ } else {
+ ((char**) r_addr_list)[0] = r_addr;
+ ((char**) r_addr_list)[1] = NULL;
+ idx += 2*sizeof(char*);
+ }
+
+ /* Verify the size matches */
+ assert(idx == ms);
+
+ result->h_name = r_name;
+ result->h_aliases = (char**) r_aliases;
+ result->h_addrtype = af;
+ result->h_length = alen;
+ result->h_addr_list = (char**) r_addr_list;
+
+ if (ttlp)
+ *ttlp = 0;
+
+ if (canonp)
+ *canonp = r_name;
+
+ free(addresses);
+
+ return NSS_STATUS_SUCCESS;
+}
+
+enum nss_status _nss_myhostname_gethostbyname3_r(
+ const char *name,
+ int af,
+ struct hostent *host,
+ char *buffer, size_t buflen,
+ int *errnop, int *h_errnop,
+ int32_t *ttlp,
+ char **canonp) {
+
+ char hn[HOST_NAME_MAX+1] = {};
+ struct address *addresses = NULL;
+ unsigned n_addresses = 0;
+ const char *canonical, *additional = NULL;
+ uint32_t local_address_ipv4;
+
+ if (af == AF_UNSPEC)
+ af = AF_INET;
+
+ if (af != AF_INET && af != AF_INET6) {
+ *errnop = EAFNOSUPPORT;
+ *h_errnop = NO_DATA;
+ return NSS_STATUS_UNAVAIL;
+ }
+
+ if (strcasecmp(name, "localhost") == 0) {
+ canonical = "localhost";
+ local_address_ipv4 = htonl(INADDR_LOOPBACK);
+ } else {
+ if (gethostname(hn, sizeof(hn)-1) < 0) {
+ *errnop = errno;
+ *h_errnop = NO_RECOVERY;
+ return NSS_STATUS_UNAVAIL;
+ }
+
+ if (strcasecmp(name, hn) != 0) {
+ *errnop = ENOENT;
+ *h_errnop = HOST_NOT_FOUND;
+ return NSS_STATUS_NOTFOUND;
+ }
+
+ ifconf_acquire_addresses(&addresses, &n_addresses);
+
+ canonical = hn;
+ additional = n_addresses <= 0 && af == AF_INET6 ? "localhost" : NULL;
+ local_address_ipv4 = LOCALADDRESS_IPV4;
+ }
+
+ return fill_in_hostent(
+ canonical, additional,
+ af,
+ addresses, n_addresses,
+ local_address_ipv4,
+ host,
+ buffer, buflen,
+ errnop, h_errnop,
+ ttlp,
+ canonp);
+}
+
+enum nss_status _nss_myhostname_gethostbyname2_r(
+ const char *name,
+ int af,
+ struct hostent *host,
+ char *buffer, size_t buflen,
+ int *errnop, int *h_errnop) {
+
+ return _nss_myhostname_gethostbyname3_r(
+ name,
+ af,
+ host,
+ buffer, buflen,
+ errnop, h_errnop,
+ NULL,
+ NULL);
+}
+
+enum nss_status _nss_myhostname_gethostbyname_r(
+ const char *name,
+ struct hostent *host,
+ char *buffer, size_t buflen,
+ int *errnop, int *h_errnop) {
+
+ return _nss_myhostname_gethostbyname3_r(
+ name,
+ AF_UNSPEC,
+ host,
+ buffer, buflen,
+ errnop, h_errnop,
+ NULL,
+ NULL);
+}
+
+enum nss_status _nss_myhostname_gethostbyaddr2_r(
+ const void* addr, socklen_t len,
+ int af,
+ struct hostent *host,
+ char *buffer, size_t buflen,
+ int *errnop, int *h_errnop,
+ int32_t *ttlp) {
+
+ char hn[HOST_NAME_MAX+1] = {};
+ struct address *addresses = NULL;
+ struct address *a;
+ unsigned n_addresses = 0, n;
+ uint32_t local_address_ipv4 = LOCALADDRESS_IPV4;
+ const char *canonical = NULL, *additional = NULL;
+
+ if (len != PROTO_ADDRESS_SIZE(af)) {
+ *errnop = EINVAL;
+ *h_errnop = NO_RECOVERY;
+ return NSS_STATUS_UNAVAIL;
+ }
+
+ if (af == AF_INET) {
+
+ if ((*(uint32_t*) addr) == LOCALADDRESS_IPV4)
+ goto found;
+
+ if ((*(uint32_t*) addr) == htonl(INADDR_LOOPBACK)) {
+ canonical = "localhost";
+ local_address_ipv4 = htonl(INADDR_LOOPBACK);
+ goto found;
+ }
+
+ } else if (af == AF_INET6) {
+
+ if (memcmp(addr, LOCALADDRESS_IPV6, 16) == 0) {
+ additional = "localhost";
+ goto found;
+ }
+
+ } else {
+ *errnop = EAFNOSUPPORT;
+ *h_errnop = NO_DATA;
+ return NSS_STATUS_UNAVAIL;
+ }
+
+ ifconf_acquire_addresses(&addresses, &n_addresses);
+
+ for (a = addresses, n = 0; n < n_addresses; n++, a++) {
+ if (af != a->family)
+ continue;
+
+ if (memcmp(addr, a->address, PROTO_ADDRESS_SIZE(af)) == 0)
+ goto found;
+ }
+
+ *errnop = ENOENT;
+ *h_errnop = HOST_NOT_FOUND;
+
+ free(addresses);
+
+ return NSS_STATUS_NOTFOUND;
+
+found:
+ if (!canonical) {
+ if (gethostname(hn, sizeof(hn)-1) < 0) {
+ *errnop = errno;
+ *h_errnop = NO_RECOVERY;
+
+ free(addresses);
+
+ return NSS_STATUS_UNAVAIL;
+ }
+
+ canonical = hn;
+ }
+
+ return fill_in_hostent(
+ canonical, additional,
+ af,
+ addresses, n_addresses,
+ local_address_ipv4,
+ host,
+ buffer, buflen,
+ errnop, h_errnop,
+ ttlp,
+ NULL);
+
+}
+
+enum nss_status _nss_myhostname_gethostbyaddr_r(
+ const void* addr, socklen_t len,
+ int af,
+ struct hostent *host,
+ char *buffer, size_t buflen,
+ int *errnop, int *h_errnop) {
+
+ return _nss_myhostname_gethostbyaddr2_r(
+ addr, len,
+ af,
+ host,
+ buffer, buflen,
+ errnop, h_errnop,
+ NULL);
+}
diff --git a/src/python-systemd/__init__.py b/src/python-systemd/__init__.py
new file mode 100644
index 0000000000..0d56b992f4
--- /dev/null
+++ b/src/python-systemd/__init__.py
@@ -0,0 +1,18 @@
+# -*- Mode: python; indent-tabs-mode: nil -*- */
+#
+# This file is part of systemd.
+#
+# Copyright 2012 David Strauss
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 of the License, or
+# (at your option) any later version.
+#
+# systemd is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with systemd; If not, see <http://www.gnu.org/licenses/>.
diff --git a/src/python-systemd/_daemon.c b/src/python-systemd/_daemon.c
new file mode 100644
index 0000000000..d3b4807368
--- /dev/null
+++ b/src/python-systemd/_daemon.c
@@ -0,0 +1,325 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Zbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#define PY_SSIZE_T_CLEAN
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wredundant-decls"
+#include <Python.h>
+#pragma GCC diagnostic pop
+
+#include <stdbool.h>
+#include <assert.h>
+#include <sys/socket.h>
+
+#include <systemd/sd-daemon.h>
+#include "pyutil.h"
+
+PyDoc_STRVAR(module__doc__,
+ "Python interface to the libsystemd-daemon library.\n\n"
+ "Provides _listen_fds, notify, booted, and is_* functions\n"
+ "which wrap sd_listen_fds, sd_notify, sd_booted, sd_is_* and\n"
+ "useful for socket activation and checking if the system is\n"
+ "running under systemd."
+);
+
+static PyObject* set_error(int r, const char* invalid_message) {
+ assert (r < 0);
+
+ if (r == -EINVAL && invalid_message)
+ PyErr_SetString(PyExc_ValueError, invalid_message);
+ else if (r == -ENOMEM)
+ PyErr_SetString(PyExc_MemoryError, "Not enough memory");
+ else {
+ errno = -r;
+ PyErr_SetFromErrno(PyExc_OSError);
+ }
+
+ return NULL;
+}
+
+
+#if PY_MAJOR_VERSION >=3 && PY_MINOR_VERSION >= 1
+static int Unicode_FSConverter(PyObject* obj, void *_result) {
+ PyObject **result = _result;
+
+ assert(result);
+
+ if (!obj)
+ /* cleanup: we don't return Py_CLEANUP_SUPPORTED, so
+ * we can assume that it was PyUnicode_FSConverter. */
+ return PyUnicode_FSConverter(obj, result);
+
+ if (obj == Py_None) {
+ *result = NULL;
+ return 1;
+ }
+
+ return PyUnicode_FSConverter(obj, result);
+}
+#endif
+
+
+PyDoc_STRVAR(booted__doc__,
+ "booted() -> bool\n\n"
+ "Return True iff this system is running under systemd.\n"
+ "Wraps sd_daemon_booted(3)."
+);
+
+static PyObject* booted(PyObject *self, PyObject *args) {
+ int r;
+ assert(args == NULL);
+
+ r = sd_booted();
+ if (r < 0)
+ return set_error(r, NULL);
+
+ return PyBool_FromLong(r);
+}
+
+
+PyDoc_STRVAR(listen_fds__doc__,
+ "_listen_fds(unset_environment=True) -> int\n\n"
+ "Return the number of descriptors passed to this process by the init system\n"
+ "as part of the socket-based activation logic.\n"
+ "Wraps sd_listen_fds(3)."
+);
+
+static PyObject* listen_fds(PyObject *self, PyObject *args) {
+ int r;
+ int unset = true;
+
+#if PY_MAJOR_VERSION >=3 && PY_MINOR_VERSION >= 3
+ if (!PyArg_ParseTuple(args, "|p:_listen_fds", &unset))
+ return NULL;
+#else
+ PyObject *obj = NULL;
+ if (!PyArg_ParseTuple(args, "|O:_listen_fds", &obj))
+ return NULL;
+ if (obj != NULL)
+ unset = PyObject_IsTrue(obj);
+ if (unset < 0)
+ return NULL;
+#endif
+
+ r = sd_listen_fds(unset);
+ if (r < 0)
+ return set_error(r, NULL);
+
+ return long_FromLong(r);
+}
+
+PyDoc_STRVAR(is_fifo__doc__,
+ "_is_fifo(fd, path) -> bool\n\n"
+ "Returns True iff the descriptor refers to a FIFO or a pipe.\n"
+ "Wraps sd_is_fifo(3)."
+);
+
+
+static PyObject* is_fifo(PyObject *self, PyObject *args) {
+ int r;
+ int fd;
+ const char *path = NULL;
+
+#if PY_MAJOR_VERSION >=3 && PY_MINOR_VERSION >= 1
+ if (!PyArg_ParseTuple(args, "i|O&:_is_fifo",
+ &fd, Unicode_FSConverter, &path))
+ return NULL;
+#else
+ if (!PyArg_ParseTuple(args, "i|z:_is_fifo", &fd, &path))
+ return NULL;
+#endif
+
+ r = sd_is_fifo(fd, path);
+ if (r < 0)
+ return set_error(r, NULL);
+
+ return PyBool_FromLong(r);
+}
+
+
+PyDoc_STRVAR(is_mq__doc__,
+ "_is_mq(fd, path) -> bool\n\n"
+ "Returns True iff the descriptor refers to a POSIX message queue.\n"
+ "Wraps sd_is_mq(3)."
+);
+
+static PyObject* is_mq(PyObject *self, PyObject *args) {
+ int r;
+ int fd;
+ const char *path = NULL;
+
+#if PY_MAJOR_VERSION >=3 && PY_MINOR_VERSION >= 1
+ if (!PyArg_ParseTuple(args, "i|O&:_is_mq",
+ &fd, Unicode_FSConverter, &path))
+ return NULL;
+#else
+ if (!PyArg_ParseTuple(args, "i|z:_is_mq", &fd, &path))
+ return NULL;
+#endif
+
+ r = sd_is_mq(fd, path);
+ if (r < 0)
+ return set_error(r, NULL);
+
+ return PyBool_FromLong(r);
+}
+
+
+
+PyDoc_STRVAR(is_socket__doc__,
+ "_is_socket(fd, family=AF_UNSPEC, type=0, listening=-1) -> bool\n\n"
+ "Returns True iff the descriptor refers to a socket.\n"
+ "Wraps sd_is_socket(3).\n\n"
+ "Constants for `family` are defined in the socket module."
+);
+
+static PyObject* is_socket(PyObject *self, PyObject *args) {
+ int r;
+ int fd, family = AF_UNSPEC, type = 0, listening = -1;
+
+ if (!PyArg_ParseTuple(args, "i|iii:_is_socket",
+ &fd, &family, &type, &listening))
+ return NULL;
+
+ r = sd_is_socket(fd, family, type, listening);
+ if (r < 0)
+ return set_error(r, NULL);
+
+ return PyBool_FromLong(r);
+}
+
+
+PyDoc_STRVAR(is_socket_inet__doc__,
+ "_is_socket_inet(fd, family=AF_UNSPEC, type=0, listening=-1, port=0) -> bool\n\n"
+ "Wraps sd_is_socket_inet(3).\n\n"
+ "Constants for `family` are defined in the socket module."
+);
+
+static PyObject* is_socket_inet(PyObject *self, PyObject *args) {
+ int r;
+ int fd, family = AF_UNSPEC, type = 0, listening = -1, port = 0;
+
+ if (!PyArg_ParseTuple(args, "i|iiii:_is_socket_inet",
+ &fd, &family, &type, &listening, &port))
+ return NULL;
+
+ if (port < 0 || port > INT16_MAX)
+ return set_error(-EINVAL, "port must fit into uint16_t");
+
+ r = sd_is_socket_inet(fd, family, type, listening, (uint16_t) port);
+ if (r < 0)
+ return set_error(r, NULL);
+
+ return PyBool_FromLong(r);
+}
+
+
+PyDoc_STRVAR(is_socket_unix__doc__,
+ "_is_socket_unix(fd, type, listening, path) -> bool\n\n"
+ "Wraps sd_is_socket_unix(3)."
+);
+
+static PyObject* is_socket_unix(PyObject *self, PyObject *args) {
+ int r;
+ int fd, type = 0, listening = -1;
+ char* path = NULL;
+ Py_ssize_t length = 0;
+
+#if PY_MAJOR_VERSION >=3 && PY_MINOR_VERSION >= 1
+ _cleanup_Py_DECREF_ PyObject *_path = NULL;
+ if (!PyArg_ParseTuple(args, "i|iiO&:_is_socket_unix",
+ &fd, &type, &listening, Unicode_FSConverter, &_path))
+ return NULL;
+ if (_path) {
+ assert(PyBytes_Check(_path));
+ if (PyBytes_AsStringAndSize(_path, &path, &length))
+ return NULL;
+ }
+#else
+ if (!PyArg_ParseTuple(args, "i|iiz#:_is_socket_unix",
+ &fd, &type, &listening, &path, &length))
+ return NULL;
+#endif
+
+ r = sd_is_socket_unix(fd, type, listening, path, length);
+ if (r < 0)
+ return set_error(r, NULL);
+
+ return PyBool_FromLong(r);
+}
+
+
+static PyMethodDef methods[] = {
+ { "booted", booted, METH_NOARGS, booted__doc__},
+ { "_listen_fds", listen_fds, METH_VARARGS, listen_fds__doc__},
+ { "_is_fifo", is_fifo, METH_VARARGS, is_fifo__doc__},
+ { "_is_mq", is_mq, METH_VARARGS, is_mq__doc__},
+ { "_is_socket", is_socket, METH_VARARGS, is_socket__doc__},
+ { "_is_socket_inet", is_socket_inet, METH_VARARGS, is_socket_inet__doc__},
+ { "_is_socket_unix", is_socket_unix, METH_VARARGS, is_socket_unix__doc__},
+ { NULL, NULL, 0, NULL } /* Sentinel */
+};
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wmissing-prototypes"
+
+#if PY_MAJOR_VERSION < 3
+
+PyMODINIT_FUNC init_daemon(void) {
+ PyObject *m;
+
+ m = Py_InitModule3("_daemon", methods, module__doc__);
+ if (m == NULL)
+ return;
+
+ PyModule_AddIntConstant(m, "LISTEN_FDS_START", SD_LISTEN_FDS_START);
+ PyModule_AddStringConstant(m, "__version__", PACKAGE_VERSION);
+}
+
+#else
+
+static struct PyModuleDef module = {
+ PyModuleDef_HEAD_INIT,
+ "_daemon", /* name of module */
+ module__doc__, /* module documentation, may be NULL */
+ 0, /* size of per-interpreter state of the module */
+ methods
+};
+
+PyMODINIT_FUNC PyInit__daemon(void) {
+ PyObject *m;
+
+ m = PyModule_Create(&module);
+ if (m == NULL)
+ return NULL;
+
+ if (PyModule_AddIntConstant(m, "LISTEN_FDS_START", SD_LISTEN_FDS_START) ||
+ PyModule_AddStringConstant(m, "__version__", PACKAGE_VERSION)) {
+ Py_DECREF(m);
+ return NULL;
+ }
+
+ return m;
+}
+
+#endif
+
+#pragma GCC diagnostic pop
diff --git a/src/python-systemd/_journal.c b/src/python-systemd/_journal.c
new file mode 100644
index 0000000000..f8e0b4f7f2
--- /dev/null
+++ b/src/python-systemd/_journal.c
@@ -0,0 +1,158 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 David Strauss <david@davidstrauss.net>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <Python.h>
+
+#include <alloca.h>
+
+#define SD_JOURNAL_SUPPRESS_LOCATION
+#include <systemd/sd-journal.h>
+
+PyDoc_STRVAR(journal_sendv__doc__,
+ "sendv('FIELD=value', 'FIELD=value', ...) -> None\n\n"
+ "Send an entry to the journal."
+);
+
+static PyObject *journal_sendv(PyObject *self, PyObject *args) {
+ struct iovec *iov = NULL;
+ int argc;
+ int i, r;
+ PyObject *ret = NULL;
+ PyObject **encoded;
+
+ /* Allocate an array for the argument strings */
+ argc = PyTuple_Size(args);
+ encoded = alloca(argc * sizeof(PyObject*));
+ memset(encoded, 0, argc * sizeof(PyObject*));
+
+ /* Allocate sufficient iovector space for the arguments. */
+ iov = alloca(argc * sizeof(struct iovec));
+
+ /* Iterate through the Python arguments and fill the iovector. */
+ for (i = 0; i < argc; ++i) {
+ PyObject *item = PyTuple_GetItem(args, i);
+ char *stritem;
+ Py_ssize_t length;
+
+ if (PyUnicode_Check(item)) {
+ encoded[i] = PyUnicode_AsEncodedString(item, "utf-8", "strict");
+ if (encoded[i] == NULL)
+ goto out;
+ item = encoded[i];
+ }
+ if (PyBytes_AsStringAndSize(item, &stritem, &length))
+ goto out;
+
+ iov[i].iov_base = stritem;
+ iov[i].iov_len = length;
+ }
+
+ /* Send the iovector to the journal. */
+ r = sd_journal_sendv(iov, argc);
+ if (r < 0) {
+ errno = -r;
+ PyErr_SetFromErrno(PyExc_IOError);
+ goto out;
+ }
+
+ /* End with success. */
+ Py_INCREF(Py_None);
+ ret = Py_None;
+
+out:
+ for (i = 0; i < argc; ++i)
+ Py_XDECREF(encoded[i]);
+
+ return ret;
+}
+
+PyDoc_STRVAR(journal_stream_fd__doc__,
+ "stream_fd(identifier, priority, level_prefix) -> fd\n\n"
+ "Open a stream to journal by calling sd_journal_stream_fd(3)."
+);
+
+static PyObject* journal_stream_fd(PyObject *self, PyObject *args) {
+ const char* identifier;
+ int priority, level_prefix;
+ int fd;
+
+ if (!PyArg_ParseTuple(args, "sii:stream_fd",
+ &identifier, &priority, &level_prefix))
+ return NULL;
+
+ fd = sd_journal_stream_fd(identifier, priority, level_prefix);
+ if (fd < 0) {
+ errno = -fd;
+ return PyErr_SetFromErrno(PyExc_IOError);
+ }
+
+ return PyLong_FromLong(fd);
+}
+
+static PyMethodDef methods[] = {
+ { "sendv", journal_sendv, METH_VARARGS, journal_sendv__doc__ },
+ { "stream_fd", journal_stream_fd, METH_VARARGS, journal_stream_fd__doc__ },
+ { NULL, NULL, 0, NULL } /* Sentinel */
+};
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wmissing-prototypes"
+
+#if PY_MAJOR_VERSION < 3
+
+PyMODINIT_FUNC init_journal(void) {
+ PyObject *m;
+
+ m = Py_InitModule("_journal", methods);
+ if (m == NULL)
+ return;
+
+ PyModule_AddStringConstant(m, "__version__", PACKAGE_VERSION);
+}
+
+#else
+
+static struct PyModuleDef module = {
+ PyModuleDef_HEAD_INIT,
+ "_journal", /* name of module */
+ NULL, /* module documentation, may be NULL */
+ -1, /* size of per-interpreter state of the module */
+ methods
+};
+
+PyMODINIT_FUNC PyInit__journal(void) {
+ PyObject *m;
+
+ m = PyModule_Create(&module);
+ if (m == NULL)
+ return NULL;
+
+ if (PyModule_AddStringConstant(m, "__version__", PACKAGE_VERSION)) {
+ Py_DECREF(m);
+ return NULL;
+ }
+
+ return m;
+}
+
+#endif
+
+#pragma GCC diagnostic pop
diff --git a/src/python-systemd/_reader.c b/src/python-systemd/_reader.c
new file mode 100644
index 0000000000..d20c58d2a8
--- /dev/null
+++ b/src/python-systemd/_reader.c
@@ -0,0 +1,1131 @@
+/*-*- Mode: C; c-basic-offset: 4; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Steven Hiscocks, Zbigniew Jędrzejewski-Szmek
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <Python.h>
+#include <structmember.h>
+#include <datetime.h>
+#include <time.h>
+#include <stdio.h>
+
+#include <systemd/sd-journal.h>
+
+#include "pyutil.h"
+#include "macro.h"
+#include "util.h"
+#include "build.h"
+
+typedef struct {
+ PyObject_HEAD
+ sd_journal *j;
+} Reader;
+static PyTypeObject ReaderType;
+
+static int set_error(int r, const char* path, const char* invalid_message) {
+ if (r >= 0)
+ return r;
+ if (r == -EINVAL && invalid_message)
+ PyErr_SetString(PyExc_ValueError, invalid_message);
+ else if (r == -ENOMEM)
+ PyErr_SetString(PyExc_MemoryError, "Not enough memory");
+ else {
+ errno = -r;
+ PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
+ }
+ return -1;
+}
+
+
+PyDoc_STRVAR(module__doc__,
+ "Class to reads the systemd journal similar to journalctl.");
+
+
+#if PY_MAJOR_VERSION >= 3
+static PyTypeObject MonotonicType;
+
+PyDoc_STRVAR(MonotonicType__doc__,
+ "A tuple of (timestamp, bootid) for holding monotonic timestamps");
+
+static PyStructSequence_Field MonotonicType_fields[] = {
+ {(char*) "timestamp", (char*) "Time"},
+ {(char*) "bootid", (char*) "Unique identifier of the boot"},
+ {} /* Sentinel */
+};
+
+static PyStructSequence_Desc Monotonic_desc = {
+ (char*) "journal.Monotonic",
+ MonotonicType__doc__,
+ MonotonicType_fields,
+ 2,
+};
+#endif
+
+
+static void Reader_dealloc(Reader* self)
+{
+ sd_journal_close(self->j);
+ Py_TYPE(self)->tp_free((PyObject*)self);
+}
+
+PyDoc_STRVAR(Reader__doc__,
+ "_Reader([flags | path]) -> ...\n\n"
+ "_Reader allows filtering and retrieval of Journal entries.\n"
+ "Note: this is a low-level interface, and probably not what you\n"
+ "want, use systemd.journal.Reader instead.\n\n"
+ "Argument `flags` sets open flags of the journal, which can be one\n"
+ "of, or ORed combination of constants: LOCAL_ONLY (default) opens\n"
+ "journal on local machine only; RUNTIME_ONLY opens only\n"
+ "volatile journal files; and SYSTEM_ONLY opens only\n"
+ "journal files of system services and the kernel.\n\n"
+ "Argument `path` is the directory of journal files. Note that\n"
+ "`flags` and `path` are exclusive.\n\n"
+ "_Reader implements the context manager protocol: the journal\n"
+ "will be closed when exiting the block.");
+static int Reader_init(Reader *self, PyObject *args, PyObject *keywds)
+{
+ int flags = 0, r;
+ char *path = NULL;
+
+ static const char* const kwlist[] = {"flags", "path", NULL};
+ if (!PyArg_ParseTupleAndKeywords(args, keywds, "|iz", (char**) kwlist,
+ &flags, &path))
+ return -1;
+
+ if (!flags)
+ flags = SD_JOURNAL_LOCAL_ONLY;
+ else
+ if (path) {
+ PyErr_SetString(PyExc_ValueError, "cannot use both flags and path");
+ return -1;
+ }
+
+ Py_BEGIN_ALLOW_THREADS
+ if (path)
+ r = sd_journal_open_directory(&self->j, path, 0);
+ else
+ r = sd_journal_open(&self->j, flags);
+ Py_END_ALLOW_THREADS
+
+ return set_error(r, path, "Invalid flags or path");
+}
+
+
+PyDoc_STRVAR(Reader_fileno__doc__,
+ "fileno() -> int\n\n"
+ "Get a file descriptor to poll for changes in the journal.\n"
+ "This method invokes sd_journal_get_fd().\n"
+ "See man:sd_journal_get_fd(3).");
+static PyObject* Reader_fileno(Reader *self, PyObject *args)
+{
+ int fd = sd_journal_get_fd(self->j);
+ set_error(fd, NULL, NULL);
+ if (fd < 0)
+ return NULL;
+ return long_FromLong(fd);
+}
+
+
+PyDoc_STRVAR(Reader_reliable_fd__doc__,
+ "reliable_fd() -> bool\n\n"
+ "Returns True iff the journal can be polled reliably.\n"
+ "This method invokes sd_journal_reliable_fd().\n"
+ "See man:sd_journal_reliable_fd(3).");
+static PyObject* Reader_reliable_fd(Reader *self, PyObject *args)
+{
+ int r = sd_journal_reliable_fd(self->j);
+ set_error(r, NULL, NULL);
+ if (r < 0)
+ return NULL;
+ return PyBool_FromLong(r);
+}
+
+
+PyDoc_STRVAR(Reader_get_events__doc__,
+ "get_events() -> int\n\n"
+ "Returns a mask of poll() events to wait for on the file\n"
+ "descriptor returned by .fileno().\n\n"
+ "See man:sd_journal_get_events(3) for further discussion.");
+static PyObject* Reader_get_events(Reader *self, PyObject *args)
+{
+ int r = sd_journal_get_events(self->j);
+ set_error(r, NULL, NULL);
+ if (r < 0)
+ return NULL;
+ return long_FromLong(r);
+}
+
+
+PyDoc_STRVAR(Reader_get_timeout__doc__,
+ "get_timeout() -> int or None\n\n"
+ "Returns a timeout value for usage in poll(), the time since the\n"
+ "epoch of clock_gettime(2) in microseconds, or None if no timeout\n"
+ "is necessary.\n\n"
+ "The return value must be converted to a relative timeout in \n"
+ "milliseconds if it is to be used as an argument for poll().\n"
+ "See man:sd_journal_get_timeout(3) for further discussion.");
+static PyObject* Reader_get_timeout(Reader *self, PyObject *args)
+{
+ int r;
+ uint64_t t;
+
+ r = sd_journal_get_timeout(self->j, &t);
+ set_error(r, NULL, NULL);
+ if (r < 0)
+ return NULL;
+
+ if (t == (uint64_t) -1)
+ Py_RETURN_NONE;
+
+ assert_cc(sizeof(unsigned long long) == sizeof(t));
+ return PyLong_FromUnsignedLongLong(t);
+}
+
+
+PyDoc_STRVAR(Reader_get_timeout_ms__doc__,
+ "get_timeout_ms() -> int\n\n"
+ "Returns a timeout value suitable for usage in poll(), the value\n"
+ "returned by .get_timeout() converted to relative ms, or -1 if\n"
+ "no timeout is necessary.");
+static PyObject* Reader_get_timeout_ms(Reader *self, PyObject *args)
+{
+ int r;
+ uint64_t t;
+
+ r = sd_journal_get_timeout(self->j, &t);
+ set_error(r, NULL, NULL);
+ if (r < 0)
+ return NULL;
+
+ return absolute_timeout(t);
+}
+
+
+PyDoc_STRVAR(Reader_close__doc__,
+ "close() -> None\n\n"
+ "Free resources allocated by this Reader object.\n"
+ "This method invokes sd_journal_close().\n"
+ "See man:sd_journal_close(3).");
+static PyObject* Reader_close(Reader *self, PyObject *args)
+{
+ assert(self);
+ assert(!args);
+
+ sd_journal_close(self->j);
+ self->j = NULL;
+ Py_RETURN_NONE;
+}
+
+
+PyDoc_STRVAR(Reader_get_usage__doc__,
+ "get_usage() -> int\n\n"
+ "Returns the total disk space currently used by journal\n"
+ "files (in bytes). If `SD_JOURNAL_LOCAL_ONLY` was\n"
+ "passed when opening the journal this value will only reflect\n"
+ "the size of journal files of the local host, otherwise\n"
+ "of all hosts.\n\n"
+ "This method invokes sd_journal_get_usage().\n"
+ "See man:sd_journal_get_usage(3).");
+static PyObject* Reader_get_usage(Reader *self, PyObject *args)
+{
+ int r;
+ uint64_t bytes;
+
+ r = sd_journal_get_usage(self->j, &bytes);
+ if (set_error(r, NULL, NULL))
+ return NULL;
+
+ assert_cc(sizeof(unsigned long long) == sizeof(bytes));
+ return PyLong_FromUnsignedLongLong(bytes);
+}
+
+
+PyDoc_STRVAR(Reader___enter____doc__,
+ "__enter__() -> self\n\n"
+ "Part of the context manager protocol.\n"
+ "Returns self.\n");
+static PyObject* Reader___enter__(PyObject *self, PyObject *args)
+{
+ assert(self);
+ assert(!args);
+
+ Py_INCREF(self);
+ return self;
+}
+
+PyDoc_STRVAR(Reader___exit____doc__,
+ "__exit__(type, value, traceback) -> None\n\n"
+ "Part of the context manager protocol.\n"
+ "Closes the journal.\n");
+static PyObject* Reader___exit__(Reader *self, PyObject *args)
+{
+ assert(self);
+
+ sd_journal_close(self->j);
+ self->j = NULL;
+ Py_RETURN_NONE;
+}
+
+
+PyDoc_STRVAR(Reader_next__doc__,
+ "next([skip]) -> bool\n\n"
+ "Go to the next log entry. Optional skip value means to go to\n"
+ "the `skip`\\-th log entry.\n"
+ "Returns False if at end of file, True otherwise.");
+static PyObject* Reader_next(Reader *self, PyObject *args)
+{
+ int64_t skip = 1LL;
+ int r;
+
+ if (!PyArg_ParseTuple(args, "|L:next", &skip))
+ return NULL;
+
+ if (skip == 0LL) {
+ PyErr_SetString(PyExc_ValueError, "skip must be nonzero");
+ return NULL;
+ }
+
+ Py_BEGIN_ALLOW_THREADS
+ if (skip == 1LL)
+ r = sd_journal_next(self->j);
+ else if (skip == -1LL)
+ r = sd_journal_previous(self->j);
+ else if (skip > 1LL)
+ r = sd_journal_next_skip(self->j, skip);
+ else if (skip < -1LL)
+ r = sd_journal_previous_skip(self->j, -skip);
+ else
+ assert_not_reached("should not be here");
+ Py_END_ALLOW_THREADS
+
+ set_error(r, NULL, NULL);
+ if (r < 0)
+ return NULL;
+ return PyBool_FromLong(r);
+}
+
+PyDoc_STRVAR(Reader_previous__doc__,
+ "previous([skip]) -> bool\n\n"
+ "Go to the previous log entry. Optional skip value means to \n"
+ "go to the `skip`\\-th previous log entry.\n"
+ "Returns False if at start of file, True otherwise.");
+static PyObject* Reader_previous(Reader *self, PyObject *args)
+{
+ int64_t skip = 1LL;
+ if (!PyArg_ParseTuple(args, "|L:previous", &skip))
+ return NULL;
+
+ return PyObject_CallMethod((PyObject *)self, (char*) "_next",
+ (char*) "L", -skip);
+}
+
+
+static int extract(const char* msg, size_t msg_len,
+ PyObject **key, PyObject **value) {
+ PyObject *k = NULL, *v;
+ const char *delim_ptr;
+
+ delim_ptr = memchr(msg, '=', msg_len);
+ if (!delim_ptr) {
+ PyErr_SetString(PyExc_OSError,
+ "journal gave us a field without '='");
+ return -1;
+ }
+
+ if (key) {
+ k = unicode_FromStringAndSize(msg, delim_ptr - (const char*) msg);
+ if (!k)
+ return -1;
+ }
+
+ if (value) {
+ v = PyBytes_FromStringAndSize(delim_ptr + 1,
+ (const char*) msg + msg_len - (delim_ptr + 1));
+ if (!v) {
+ Py_XDECREF(k);
+ return -1;
+ }
+
+ *value = v;
+ }
+
+ if (key)
+ *key = k;
+
+ return 0;
+}
+
+PyDoc_STRVAR(Reader_get__doc__,
+ "get(str) -> str\n\n"
+ "Return data associated with this key in current log entry.\n"
+ "Throws KeyError is the data is not available.");
+static PyObject* Reader_get(Reader *self, PyObject *args)
+{
+ const char* field;
+ const void* msg;
+ size_t msg_len;
+ PyObject *value;
+ int r;
+
+ assert(self);
+ assert(args);
+
+ if (!PyArg_ParseTuple(args, "s:get", &field))
+ return NULL;
+
+ r = sd_journal_get_data(self->j, field, &msg, &msg_len);
+ if (r == -ENOENT) {
+ PyErr_SetString(PyExc_KeyError, field);
+ return NULL;
+ } else if (set_error(r, NULL, "field name is not valid"))
+ return NULL;
+
+ r = extract(msg, msg_len, NULL, &value);
+ if (r < 0)
+ return NULL;
+ return value;
+}
+
+
+PyDoc_STRVAR(Reader_get_all__doc__,
+ "_get_all() -> dict\n\n"
+ "Return dictionary of the current log entry.");
+static PyObject* Reader_get_all(Reader *self, PyObject *args)
+{
+ PyObject *dict;
+ const void *msg;
+ size_t msg_len;
+ int r;
+
+ dict = PyDict_New();
+ if (!dict)
+ return NULL;
+
+ SD_JOURNAL_FOREACH_DATA(self->j, msg, msg_len) {
+ _cleanup_Py_DECREF_ PyObject *key = NULL, *value = NULL;
+
+ r = extract(msg, msg_len, &key, &value);
+ if (r < 0)
+ goto error;
+
+ if (PyDict_Contains(dict, key)) {
+ PyObject *cur_value = PyDict_GetItem(dict, key);
+
+ if (PyList_CheckExact(cur_value)) {
+ r = PyList_Append(cur_value, value);
+ if (r < 0)
+ goto error;
+ } else {
+ _cleanup_Py_DECREF_ PyObject *tmp_list = PyList_New(0);
+ if (!tmp_list)
+ goto error;
+
+ r = PyList_Append(tmp_list, cur_value);
+ if (r < 0)
+ goto error;
+
+ r = PyList_Append(tmp_list, value);
+ if (r < 0)
+ goto error;
+
+ r = PyDict_SetItem(dict, key, tmp_list);
+ if (r < 0)
+ goto error;
+ }
+ } else {
+ r = PyDict_SetItem(dict, key, value);
+ if (r < 0)
+ goto error;
+ }
+ }
+
+ return dict;
+
+error:
+ Py_DECREF(dict);
+ return NULL;
+}
+
+
+PyDoc_STRVAR(Reader_get_realtime__doc__,
+ "get_realtime() -> int\n\n"
+ "Return the realtime timestamp for the current journal entry\n"
+ "in microseconds.\n\n"
+ "Wraps sd_journal_get_realtime_usec().\n"
+ "See man:sd_journal_get_realtime_usec(3).");
+static PyObject* Reader_get_realtime(Reader *self, PyObject *args)
+{
+ uint64_t timestamp;
+ int r;
+
+ assert(self);
+ assert(!args);
+
+ r = sd_journal_get_realtime_usec(self->j, &timestamp);
+ if (set_error(r, NULL, NULL))
+ return NULL;
+
+ assert_cc(sizeof(unsigned long long) == sizeof(timestamp));
+ return PyLong_FromUnsignedLongLong(timestamp);
+}
+
+
+PyDoc_STRVAR(Reader_get_monotonic__doc__,
+ "get_monotonic() -> (timestamp, bootid)\n\n"
+ "Return the monotonic timestamp for the current journal entry\n"
+ "as a tuple of time in microseconds and bootid.\n\n"
+ "Wraps sd_journal_get_monotonic_usec().\n"
+ "See man:sd_journal_get_monotonic_usec(3).");
+static PyObject* Reader_get_monotonic(Reader *self, PyObject *args)
+{
+ uint64_t timestamp;
+ sd_id128_t id;
+ PyObject *monotonic, *bootid, *tuple;
+ int r;
+
+ assert(self);
+ assert(!args);
+
+ r = sd_journal_get_monotonic_usec(self->j, &timestamp, &id);
+ if (set_error(r, NULL, NULL))
+ return NULL;
+
+ assert_cc(sizeof(unsigned long long) == sizeof(timestamp));
+ monotonic = PyLong_FromUnsignedLongLong(timestamp);
+ bootid = PyBytes_FromStringAndSize((const char*) &id.bytes, sizeof(id.bytes));
+#if PY_MAJOR_VERSION >= 3
+ tuple = PyStructSequence_New(&MonotonicType);
+#else
+ tuple = PyTuple_New(2);
+#endif
+ if (!monotonic || !bootid || !tuple) {
+ Py_XDECREF(monotonic);
+ Py_XDECREF(bootid);
+ Py_XDECREF(tuple);
+ return NULL;
+ }
+
+#if PY_MAJOR_VERSION >= 3
+ PyStructSequence_SET_ITEM(tuple, 0, monotonic);
+ PyStructSequence_SET_ITEM(tuple, 1, bootid);
+#else
+ PyTuple_SET_ITEM(tuple, 0, monotonic);
+ PyTuple_SET_ITEM(tuple, 1, bootid);
+#endif
+
+ return tuple;
+}
+
+PyDoc_STRVAR(Reader_add_match__doc__,
+ "add_match(match) -> None\n\n"
+ "Add a match to filter journal log entries. All matches of different\n"
+ "fields are combined with logical AND, and matches of the same field\n"
+ "are automatically combined with logical OR.\n"
+ "Match is a string of the form \"FIELD=value\".");
+static PyObject* Reader_add_match(Reader *self, PyObject *args, PyObject *keywds)
+{
+ char *match;
+ int match_len, r;
+ if (!PyArg_ParseTuple(args, "s#:add_match", &match, &match_len))
+ return NULL;
+
+ r = sd_journal_add_match(self->j, match, match_len);
+ set_error(r, NULL, "Invalid match");
+ if (r < 0)
+ return NULL;
+
+ Py_RETURN_NONE;
+}
+
+
+PyDoc_STRVAR(Reader_add_disjunction__doc__,
+ "add_disjunction() -> None\n\n"
+ "Inserts a logical OR between matches added since previous\n"
+ "add_disjunction() or add_conjunction() and the next\n"
+ "add_disjunction() or add_conjunction().\n\n"
+ "See man:sd_journal_add_disjunction(3) for explanation.");
+static PyObject* Reader_add_disjunction(Reader *self, PyObject *args)
+{
+ int r;
+ r = sd_journal_add_disjunction(self->j);
+ set_error(r, NULL, NULL);
+ if (r < 0)
+ return NULL;
+ Py_RETURN_NONE;
+}
+
+
+PyDoc_STRVAR(Reader_add_conjunction__doc__,
+ "add_conjunction() -> None\n\n"
+ "Inserts a logical AND between matches added since previous\n"
+ "add_disjunction() or add_conjunction() and the next\n"
+ "add_disjunction() or add_conjunction().\n\n"
+ "See man:sd_journal_add_disjunction(3) for explanation.");
+static PyObject* Reader_add_conjunction(Reader *self, PyObject *args)
+{
+ int r;
+ r = sd_journal_add_conjunction(self->j);
+ set_error(r, NULL, NULL);
+ if (r < 0)
+ return NULL;
+ Py_RETURN_NONE;
+}
+
+
+PyDoc_STRVAR(Reader_flush_matches__doc__,
+ "flush_matches() -> None\n\n"
+ "Clear all current match filters.");
+static PyObject* Reader_flush_matches(Reader *self, PyObject *args)
+{
+ sd_journal_flush_matches(self->j);
+ Py_RETURN_NONE;
+}
+
+
+PyDoc_STRVAR(Reader_seek_head__doc__,
+ "seek_head() -> None\n\n"
+ "Jump to the beginning of the journal.\n"
+ "This method invokes sd_journal_seek_head().\n"
+ "See man:sd_journal_seek_head(3).");
+static PyObject* Reader_seek_head(Reader *self, PyObject *args)
+{
+ int r;
+ Py_BEGIN_ALLOW_THREADS
+ r = sd_journal_seek_head(self->j);
+ Py_END_ALLOW_THREADS
+ if (set_error(r, NULL, NULL))
+ return NULL;
+ Py_RETURN_NONE;
+}
+
+
+PyDoc_STRVAR(Reader_seek_tail__doc__,
+ "seek_tail() -> None\n\n"
+ "Jump to the end of the journal.\n"
+ "This method invokes sd_journal_seek_tail().\n"
+ "See man:sd_journal_seek_tail(3).");
+static PyObject* Reader_seek_tail(Reader *self, PyObject *args)
+{
+ int r;
+ Py_BEGIN_ALLOW_THREADS
+ r = sd_journal_seek_tail(self->j);
+ Py_END_ALLOW_THREADS
+ if (set_error(r, NULL, NULL))
+ return NULL;
+ Py_RETURN_NONE;
+}
+
+
+PyDoc_STRVAR(Reader_seek_realtime__doc__,
+ "seek_realtime(realtime) -> None\n\n"
+ "Seek to nearest matching journal entry to `realtime`. Argument\n"
+ "`realtime` in specified in seconds.");
+static PyObject* Reader_seek_realtime(Reader *self, PyObject *args)
+{
+ uint64_t timestamp;
+ int r;
+
+ if (!PyArg_ParseTuple(args, "K:seek_realtime", &timestamp))
+ return NULL;
+
+ Py_BEGIN_ALLOW_THREADS
+ r = sd_journal_seek_realtime_usec(self->j, timestamp);
+ Py_END_ALLOW_THREADS
+ if (set_error(r, NULL, NULL))
+ return NULL;
+ Py_RETURN_NONE;
+}
+
+
+PyDoc_STRVAR(Reader_seek_monotonic__doc__,
+ "seek_monotonic(monotonic[, bootid]) -> None\n\n"
+ "Seek to nearest matching journal entry to `monotonic`. Argument\n"
+ "`monotonic` is an timestamp from boot in microseconds.\n"
+ "Argument `bootid` is a string representing which boot the\n"
+ "monotonic time is reference to. Defaults to current bootid.");
+static PyObject* Reader_seek_monotonic(Reader *self, PyObject *args)
+{
+ char *bootid = NULL;
+ uint64_t timestamp;
+ sd_id128_t id;
+ int r;
+
+ if (!PyArg_ParseTuple(args, "K|z:seek_monotonic", &timestamp, &bootid))
+ return NULL;
+
+ if (bootid) {
+ r = sd_id128_from_string(bootid, &id);
+ if (set_error(r, NULL, "Invalid bootid"))
+ return NULL;
+ } else {
+ Py_BEGIN_ALLOW_THREADS
+ r = sd_id128_get_boot(&id);
+ Py_END_ALLOW_THREADS
+ if (set_error(r, NULL, NULL))
+ return NULL;
+ }
+
+ Py_BEGIN_ALLOW_THREADS
+ r = sd_journal_seek_monotonic_usec(self->j, id, timestamp);
+ Py_END_ALLOW_THREADS
+ if (set_error(r, NULL, NULL))
+ return NULL;
+
+ Py_RETURN_NONE;
+}
+
+
+PyDoc_STRVAR(Reader_process__doc__,
+ "process() -> state change (integer)\n\n"
+ "Process events and reset the readable state of the file\n"
+ "descriptor returned by .fileno().\n\n"
+ "Will return constants: NOP if no change; APPEND if new\n"
+ "entries have been added to the end of the journal; and\n"
+ "INVALIDATE if journal files have been added or removed.\n\n"
+ "See man:sd_journal_process(3) for further discussion.");
+static PyObject* Reader_process(Reader *self, PyObject *args)
+{
+ int r;
+
+ assert(!args);
+
+ Py_BEGIN_ALLOW_THREADS
+ r = sd_journal_process(self->j);
+ Py_END_ALLOW_THREADS
+ if (set_error(r, NULL, NULL) < 0)
+ return NULL;
+
+ return long_FromLong(r);
+}
+
+
+PyDoc_STRVAR(Reader_wait__doc__,
+ "wait([timeout]) -> state change (integer)\n\n"
+ "Wait for a change in the journal. Argument `timeout` specifies\n"
+ "the maximum number of microseconds to wait before returning\n"
+ "regardless of wheter the journal has changed. If `timeout` is -1,\n"
+ "then block forever.\n\n"
+ "Will return constants: NOP if no change; APPEND if new\n"
+ "entries have been added to the end of the journal; and\n"
+ "INVALIDATE if journal files have been added or removed.\n\n"
+ "See man:sd_journal_wait(3) for further discussion.");
+static PyObject* Reader_wait(Reader *self, PyObject *args)
+{
+ int r;
+ int64_t timeout;
+
+ if (!PyArg_ParseTuple(args, "|L:wait", &timeout))
+ return NULL;
+
+ Py_BEGIN_ALLOW_THREADS
+ r = sd_journal_wait(self->j, timeout);
+ Py_END_ALLOW_THREADS
+ if (set_error(r, NULL, NULL) < 0)
+ return NULL;
+
+ return long_FromLong(r);
+}
+
+
+PyDoc_STRVAR(Reader_seek_cursor__doc__,
+ "seek_cursor(cursor) -> None\n\n"
+ "Seek to journal entry by given unique reference `cursor`.");
+static PyObject* Reader_seek_cursor(Reader *self, PyObject *args)
+{
+ const char *cursor;
+ int r;
+
+ if (!PyArg_ParseTuple(args, "s:seek_cursor", &cursor))
+ return NULL;
+
+ Py_BEGIN_ALLOW_THREADS
+ r = sd_journal_seek_cursor(self->j, cursor);
+ Py_END_ALLOW_THREADS
+ if (set_error(r, NULL, "Invalid cursor"))
+ return NULL;
+ Py_RETURN_NONE;
+}
+
+
+PyDoc_STRVAR(Reader_get_cursor__doc__,
+ "get_cursor() -> str\n\n"
+ "Return a cursor string for the current journal entry.\n\n"
+ "Wraps sd_journal_get_cursor(). See man:sd_journal_get_cursor(3).");
+static PyObject* Reader_get_cursor(Reader *self, PyObject *args)
+{
+ _cleanup_free_ char *cursor = NULL;
+ int r;
+
+ assert(self);
+ assert(!args);
+
+ r = sd_journal_get_cursor(self->j, &cursor);
+ if (set_error(r, NULL, NULL))
+ return NULL;
+
+ return unicode_FromString(cursor);
+}
+
+
+PyDoc_STRVAR(Reader_test_cursor__doc__,
+ "test_cursor(str) -> bool\n\n"
+ "Test whether the cursor string matches current journal entry.\n\n"
+ "Wraps sd_journal_test_cursor(). See man:sd_journal_test_cursor(3).");
+static PyObject* Reader_test_cursor(Reader *self, PyObject *args)
+{
+ const char *cursor;
+ int r;
+
+ assert(self);
+ assert(args);
+
+ if (!PyArg_ParseTuple(args, "s:test_cursor", &cursor))
+ return NULL;
+
+ r = sd_journal_test_cursor(self->j, cursor);
+ set_error(r, NULL, NULL);
+ if (r < 0)
+ return NULL;
+
+ return PyBool_FromLong(r);
+}
+
+PyDoc_STRVAR(Reader_query_unique__doc__,
+ "query_unique(field) -> a set of values\n\n"
+ "Return a set of unique values appearing in journal for the\n"
+ "given `field`. Note this does not respect any journal matches.");
+static PyObject* Reader_query_unique(Reader *self, PyObject *args)
+{
+ char *query;
+ int r;
+ const void *uniq;
+ size_t uniq_len;
+ PyObject *value_set, *key, *value;
+
+ if (!PyArg_ParseTuple(args, "s:query_unique", &query))
+ return NULL;
+
+ Py_BEGIN_ALLOW_THREADS
+ r = sd_journal_query_unique(self->j, query);
+ Py_END_ALLOW_THREADS
+ if (set_error(r, NULL, "Invalid field name"))
+ return NULL;
+
+ value_set = PySet_New(0);
+ key = unicode_FromString(query);
+
+ SD_JOURNAL_FOREACH_UNIQUE(self->j, uniq, uniq_len) {
+ const char *delim_ptr;
+
+ delim_ptr = memchr(uniq, '=', uniq_len);
+ value = PyBytes_FromStringAndSize(
+ delim_ptr + 1,
+ (const char*) uniq + uniq_len - (delim_ptr + 1));
+ PySet_Add(value_set, value);
+ Py_DECREF(value);
+ }
+ Py_DECREF(key);
+ return value_set;
+}
+
+
+PyDoc_STRVAR(Reader_get_catalog__doc__,
+ "get_catalog() -> str\n\n"
+ "Retrieve a message catalog entry for the current journal entry.\n"
+ "Will throw IndexError if the entry has no MESSAGE_ID\n"
+ "and KeyError is the id is specified, but hasn't been found\n"
+ "in the catalog.\n\n"
+ "Wraps man:sd_journal_get_catalog(3).");
+static PyObject* Reader_get_catalog(Reader *self, PyObject *args)
+{
+ int r;
+ _cleanup_free_ char *msg = NULL;
+
+ assert(self);
+ assert(!args);
+
+ Py_BEGIN_ALLOW_THREADS
+ r = sd_journal_get_catalog(self->j, &msg);
+ Py_END_ALLOW_THREADS
+ if (r == -ENOENT) {
+ const void* mid;
+ size_t mid_len;
+
+ r = sd_journal_get_data(self->j, "MESSAGE_ID", &mid, &mid_len);
+ if (r == 0) {
+ const int l = sizeof("MESSAGE_ID");
+ assert(mid_len > l);
+ PyErr_Format(PyExc_KeyError, "%.*s", (int) mid_len - l,
+ (const char*) mid + l);
+ } else if (r == -ENOENT)
+ PyErr_SetString(PyExc_IndexError, "no MESSAGE_ID field");
+ else
+ set_error(r, NULL, NULL);
+ return NULL;
+ } else if (set_error(r, NULL, NULL))
+ return NULL;
+
+ return unicode_FromString(msg);
+}
+
+
+PyDoc_STRVAR(get_catalog__doc__,
+ "get_catalog(id128) -> str\n\n"
+ "Retrieve a message catalog entry for the given id.\n"
+ "Wraps man:sd_journal_get_catalog_for_message_id(3).");
+static PyObject* get_catalog(PyObject *self, PyObject *args)
+{
+ int r;
+ char *id_ = NULL;
+ sd_id128_t id;
+ _cleanup_free_ char *msg = NULL;
+
+ assert(!self);
+ assert(args);
+
+ if (!PyArg_ParseTuple(args, "z:get_catalog", &id_))
+ return NULL;
+
+ r = sd_id128_from_string(id_, &id);
+ if (set_error(r, NULL, "Invalid id128"))
+ return NULL;
+
+ Py_BEGIN_ALLOW_THREADS
+ r = sd_journal_get_catalog_for_message_id(id, &msg);
+ Py_END_ALLOW_THREADS
+ if (set_error(r, NULL, NULL))
+ return NULL;
+
+ return unicode_FromString(msg);
+}
+
+
+PyDoc_STRVAR(data_threshold__doc__,
+ "Threshold for field size truncation in bytes.\n\n"
+ "Fields longer than this will be truncated to the threshold size.\n"
+ "Defaults to 64Kb.");
+
+static PyObject* Reader_get_data_threshold(Reader *self, void *closure)
+{
+ size_t cvalue;
+ int r;
+
+ r = sd_journal_get_data_threshold(self->j, &cvalue);
+ if (set_error(r, NULL, NULL))
+ return NULL;
+
+ return long_FromSize_t(cvalue);
+}
+
+static int Reader_set_data_threshold(Reader *self, PyObject *value, void *closure)
+{
+ int r;
+ if (value == NULL) {
+ PyErr_SetString(PyExc_AttributeError, "Cannot delete data threshold");
+ return -1;
+ }
+ if (!long_Check(value)){
+ PyErr_SetString(PyExc_TypeError, "Data threshold must be an int");
+ return -1;
+ }
+ r = sd_journal_set_data_threshold(self->j, (size_t) long_AsLong(value));
+ return set_error(r, NULL, NULL);
+}
+
+
+PyDoc_STRVAR(closed__doc__,
+ "True iff journal is closed");
+static PyObject* Reader_get_closed(Reader *self, void *closure)
+{
+ return PyBool_FromLong(self->j == NULL);
+}
+
+
+static PyGetSetDef Reader_getsetters[] = {
+ {(char*) "data_threshold",
+ (getter) Reader_get_data_threshold,
+ (setter) Reader_set_data_threshold,
+ (char*) data_threshold__doc__,
+ NULL},
+ {(char*) "closed",
+ (getter) Reader_get_closed,
+ NULL,
+ (char*) closed__doc__,
+ NULL},
+ {} /* Sentinel */
+};
+
+static PyMethodDef Reader_methods[] = {
+ {"fileno", (PyCFunction) Reader_fileno, METH_NOARGS, Reader_fileno__doc__},
+ {"reliable_fd", (PyCFunction) Reader_reliable_fd, METH_NOARGS, Reader_reliable_fd__doc__},
+ {"get_events", (PyCFunction) Reader_get_events, METH_NOARGS, Reader_get_events__doc__},
+ {"get_timeout", (PyCFunction) Reader_get_timeout, METH_NOARGS, Reader_get_timeout__doc__},
+ {"get_timeout_ms", (PyCFunction) Reader_get_timeout_ms, METH_NOARGS, Reader_get_timeout_ms__doc__},
+ {"close", (PyCFunction) Reader_close, METH_NOARGS, Reader_close__doc__},
+ {"get_usage", (PyCFunction) Reader_get_usage, METH_NOARGS, Reader_get_usage__doc__},
+ {"__enter__", (PyCFunction) Reader___enter__, METH_NOARGS, Reader___enter____doc__},
+ {"__exit__", (PyCFunction) Reader___exit__, METH_VARARGS, Reader___exit____doc__},
+ {"_next", (PyCFunction) Reader_next, METH_VARARGS, Reader_next__doc__},
+ {"_previous", (PyCFunction) Reader_previous, METH_VARARGS, Reader_previous__doc__},
+ {"_get", (PyCFunction) Reader_get, METH_VARARGS, Reader_get__doc__},
+ {"_get_all", (PyCFunction) Reader_get_all, METH_NOARGS, Reader_get_all__doc__},
+ {"_get_realtime", (PyCFunction) Reader_get_realtime, METH_NOARGS, Reader_get_realtime__doc__},
+ {"_get_monotonic", (PyCFunction) Reader_get_monotonic, METH_NOARGS, Reader_get_monotonic__doc__},
+ {"add_match", (PyCFunction) Reader_add_match, METH_VARARGS|METH_KEYWORDS, Reader_add_match__doc__},
+ {"add_disjunction", (PyCFunction) Reader_add_disjunction, METH_NOARGS, Reader_add_disjunction__doc__},
+ {"add_conjunction", (PyCFunction) Reader_add_conjunction, METH_NOARGS, Reader_add_conjunction__doc__},
+ {"flush_matches", (PyCFunction) Reader_flush_matches, METH_NOARGS, Reader_flush_matches__doc__},
+ {"seek_head", (PyCFunction) Reader_seek_head, METH_NOARGS, Reader_seek_head__doc__},
+ {"seek_tail", (PyCFunction) Reader_seek_tail, METH_NOARGS, Reader_seek_tail__doc__},
+ {"seek_realtime", (PyCFunction) Reader_seek_realtime, METH_VARARGS, Reader_seek_realtime__doc__},
+ {"seek_monotonic", (PyCFunction) Reader_seek_monotonic, METH_VARARGS, Reader_seek_monotonic__doc__},
+ {"process", (PyCFunction) Reader_process, METH_NOARGS, Reader_process__doc__},
+ {"wait", (PyCFunction) Reader_wait, METH_VARARGS, Reader_wait__doc__},
+ {"seek_cursor", (PyCFunction) Reader_seek_cursor, METH_VARARGS, Reader_seek_cursor__doc__},
+ {"_get_cursor", (PyCFunction) Reader_get_cursor, METH_NOARGS, Reader_get_cursor__doc__},
+ {"test_cursor", (PyCFunction) Reader_test_cursor, METH_VARARGS, Reader_test_cursor__doc__},
+ {"query_unique", (PyCFunction) Reader_query_unique, METH_VARARGS, Reader_query_unique__doc__},
+ {"get_catalog", (PyCFunction) Reader_get_catalog, METH_NOARGS, Reader_get_catalog__doc__},
+ {} /* Sentinel */
+};
+
+static PyTypeObject ReaderType = {
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_reader._Reader", /*tp_name*/
+ sizeof(Reader), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ (destructor)Reader_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash */
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ 0, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
+ Reader__doc__, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ Reader_methods, /* tp_methods */
+ 0, /* tp_members */
+ Reader_getsetters, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc) Reader_init, /* tp_init */
+ 0, /* tp_alloc */
+ PyType_GenericNew, /* tp_new */
+};
+
+static PyMethodDef methods[] = {
+ { "_get_catalog", get_catalog, METH_VARARGS, get_catalog__doc__},
+ { NULL, NULL, 0, NULL } /* Sentinel */
+};
+
+#if PY_MAJOR_VERSION >= 3
+static PyModuleDef module = {
+ PyModuleDef_HEAD_INIT,
+ "_reader",
+ module__doc__,
+ -1,
+ methods,
+ NULL, NULL, NULL, NULL
+};
+#endif
+
+#if PY_MAJOR_VERSION >= 3
+static bool initialized = false;
+#endif
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wmissing-prototypes"
+
+PyMODINIT_FUNC
+#if PY_MAJOR_VERSION >= 3
+PyInit__reader(void)
+#else
+init_reader(void)
+#endif
+{
+ PyObject* m;
+
+ PyDateTime_IMPORT;
+
+ if (PyType_Ready(&ReaderType) < 0)
+#if PY_MAJOR_VERSION >= 3
+ return NULL;
+#else
+ return;
+#endif
+
+#if PY_MAJOR_VERSION >= 3
+ m = PyModule_Create(&module);
+ if (m == NULL)
+ return NULL;
+
+ if (!initialized) {
+ PyStructSequence_InitType(&MonotonicType, &Monotonic_desc);
+ initialized = true;
+ }
+#else
+ m = Py_InitModule3("_reader", methods, module__doc__);
+ if (m == NULL)
+ return;
+#endif
+
+ Py_INCREF(&ReaderType);
+#if PY_MAJOR_VERSION >= 3
+ Py_INCREF(&MonotonicType);
+#endif
+ if (PyModule_AddObject(m, "_Reader", (PyObject *) &ReaderType) ||
+#if PY_MAJOR_VERSION >= 3
+ PyModule_AddObject(m, "Monotonic", (PyObject*) &MonotonicType) ||
+#endif
+ PyModule_AddIntConstant(m, "NOP", SD_JOURNAL_NOP) ||
+ PyModule_AddIntConstant(m, "APPEND", SD_JOURNAL_APPEND) ||
+ PyModule_AddIntConstant(m, "INVALIDATE", SD_JOURNAL_INVALIDATE) ||
+ PyModule_AddIntConstant(m, "LOCAL_ONLY", SD_JOURNAL_LOCAL_ONLY) ||
+ PyModule_AddIntConstant(m, "RUNTIME_ONLY", SD_JOURNAL_RUNTIME_ONLY) ||
+ PyModule_AddIntConstant(m, "SYSTEM_ONLY", SD_JOURNAL_SYSTEM_ONLY) ||
+ PyModule_AddStringConstant(m, "__version__", PACKAGE_VERSION)) {
+#if PY_MAJOR_VERSION >= 3
+ Py_DECREF(m);
+ return NULL;
+#endif
+ }
+
+#if PY_MAJOR_VERSION >= 3
+ return m;
+#endif
+}
+
+#pragma GCC diagnostic pop
diff --git a/src/python-systemd/daemon.py b/src/python-systemd/daemon.py
new file mode 100644
index 0000000000..e2829d1671
--- /dev/null
+++ b/src/python-systemd/daemon.py
@@ -0,0 +1,54 @@
+from ._daemon import (__version__,
+ booted,
+ _listen_fds,
+ _is_fifo,
+ _is_socket,
+ _is_socket_inet,
+ _is_socket_unix,
+ _is_mq,
+ LISTEN_FDS_START)
+from socket import AF_UNSPEC as _AF_UNSPEC
+
+def _convert_fileobj(fileobj):
+ try:
+ return fileobj.fileno()
+ except AttributeError:
+ return fileobj
+
+def is_fifo(fileobj, path=None):
+ fd = _convert_fileobj(fileobj)
+ return _is_fifo(fd, path)
+
+def is_socket(fileobj, family=_AF_UNSPEC, type=0, listening=-1):
+ fd = _convert_fileobj(fileobj)
+ return _is_socket(fd, family, type, listening)
+
+def is_socket_inet(fileobj, family=_AF_UNSPEC, type=0, listening=-1, port=0):
+ fd = _convert_fileobj(fileobj)
+ return _is_socket_inet(fd, family, type, listening)
+
+def is_socket_unix(fileobj, type=0, listening=-1, path=None):
+ fd = _convert_fileobj(fileobj)
+ return _is_socket_unix(fd, type, listening, path)
+
+def is_mq(fileobj, path=None):
+ fd = _convert_fileobj(fileobj)
+ return _is_mq(fd, path)
+
+def listen_fds(unset_environment=True):
+ """Return a list of socket activated descriptors
+
+ Example::
+
+ (in primary window)
+ $ systemd-activate -l 2000 python3 -c \\
+ 'from systemd.daemon import listen_fds; print(listen_fds())'
+ (in another window)
+ $ telnet localhost 2000
+ (in primary window)
+ ...
+ Execing python3 (...)
+ [3]
+ """
+ num = _listen_fds(unset_environment)
+ return list(range(LISTEN_FDS_START, LISTEN_FDS_START + num))
diff --git a/src/python-systemd/id128-constants.h b/src/python-systemd/id128-constants.h
new file mode 100644
index 0000000000..aa1cfcf923
--- /dev/null
+++ b/src/python-systemd/id128-constants.h
@@ -0,0 +1,32 @@
+add_id(m, "SD_MESSAGE_JOURNAL_START", SD_MESSAGE_JOURNAL_START) JOINER
+add_id(m, "SD_MESSAGE_JOURNAL_STOP", SD_MESSAGE_JOURNAL_STOP) JOINER
+add_id(m, "SD_MESSAGE_JOURNAL_DROPPED", SD_MESSAGE_JOURNAL_DROPPED) JOINER
+add_id(m, "SD_MESSAGE_JOURNAL_MISSED", SD_MESSAGE_JOURNAL_MISSED) JOINER
+add_id(m, "SD_MESSAGE_COREDUMP", SD_MESSAGE_COREDUMP) JOINER
+add_id(m, "SD_MESSAGE_SESSION_START", SD_MESSAGE_SESSION_START) JOINER
+add_id(m, "SD_MESSAGE_SESSION_STOP", SD_MESSAGE_SESSION_STOP) JOINER
+add_id(m, "SD_MESSAGE_SEAT_START", SD_MESSAGE_SEAT_START) JOINER
+add_id(m, "SD_MESSAGE_SEAT_STOP", SD_MESSAGE_SEAT_STOP) JOINER
+add_id(m, "SD_MESSAGE_TIME_CHANGE", SD_MESSAGE_TIME_CHANGE) JOINER
+add_id(m, "SD_MESSAGE_TIMEZONE_CHANGE", SD_MESSAGE_TIMEZONE_CHANGE) JOINER
+add_id(m, "SD_MESSAGE_STARTUP_FINISHED", SD_MESSAGE_STARTUP_FINISHED) JOINER
+add_id(m, "SD_MESSAGE_SLEEP_START", SD_MESSAGE_SLEEP_START) JOINER
+add_id(m, "SD_MESSAGE_SLEEP_STOP", SD_MESSAGE_SLEEP_STOP) JOINER
+add_id(m, "SD_MESSAGE_SHUTDOWN", SD_MESSAGE_SHUTDOWN) JOINER
+add_id(m, "SD_MESSAGE_UNIT_STARTING", SD_MESSAGE_UNIT_STARTING) JOINER
+add_id(m, "SD_MESSAGE_UNIT_STARTED", SD_MESSAGE_UNIT_STARTED) JOINER
+add_id(m, "SD_MESSAGE_UNIT_STOPPING", SD_MESSAGE_UNIT_STOPPING) JOINER
+add_id(m, "SD_MESSAGE_UNIT_STOPPED", SD_MESSAGE_UNIT_STOPPED) JOINER
+add_id(m, "SD_MESSAGE_UNIT_FAILED", SD_MESSAGE_UNIT_FAILED) JOINER
+add_id(m, "SD_MESSAGE_UNIT_RELOADING", SD_MESSAGE_UNIT_RELOADING) JOINER
+add_id(m, "SD_MESSAGE_UNIT_RELOADED", SD_MESSAGE_UNIT_RELOADED) JOINER
+add_id(m, "SD_MESSAGE_SPAWN_FAILED", SD_MESSAGE_SPAWN_FAILED) JOINER
+add_id(m, "SD_MESSAGE_FORWARD_SYSLOG_MISSED", SD_MESSAGE_FORWARD_SYSLOG_MISSED) JOINER
+add_id(m, "SD_MESSAGE_OVERMOUNTING", SD_MESSAGE_OVERMOUNTING) JOINER
+add_id(m, "SD_MESSAGE_LID_OPENED", SD_MESSAGE_LID_OPENED) JOINER
+add_id(m, "SD_MESSAGE_LID_CLOSED", SD_MESSAGE_LID_CLOSED) JOINER
+add_id(m, "SD_MESSAGE_POWER_KEY", SD_MESSAGE_POWER_KEY) JOINER
+add_id(m, "SD_MESSAGE_SUSPEND_KEY", SD_MESSAGE_SUSPEND_KEY) JOINER
+add_id(m, "SD_MESSAGE_HIBERNATE_KEY", SD_MESSAGE_HIBERNATE_KEY) JOINER
+add_id(m, "SD_MESSAGE_CONFIG_ERROR", SD_MESSAGE_CONFIG_ERROR) JOINER
+add_id(m, "SD_MESSAGE_BOOTCHART", SD_MESSAGE_BOOTCHART) JOINER
diff --git a/src/python-systemd/id128.c b/src/python-systemd/id128.c
new file mode 100644
index 0000000000..ec1d9fb4a2
--- /dev/null
+++ b/src/python-systemd/id128.c
@@ -0,0 +1,161 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Zbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <Python.h>
+
+#include <systemd/sd-messages.h>
+
+#include "pyutil.h"
+
+PyDoc_STRVAR(module__doc__,
+ "Python interface to the libsystemd-id128 library.\n\n"
+ "Provides SD_MESSAGE_* constants and functions to query and generate\n"
+ "128-bit unique identifiers."
+);
+
+PyDoc_STRVAR(randomize__doc__,
+ "randomize() -> UUID\n\n"
+ "Return a new random 128-bit unique identifier.\n"
+ "Wraps sd_id128_randomize(3)."
+);
+
+PyDoc_STRVAR(get_machine__doc__,
+ "get_machine() -> UUID\n\n"
+ "Return a 128-bit unique identifier for this machine.\n"
+ "Wraps sd_id128_get_machine(3)."
+);
+
+PyDoc_STRVAR(get_boot__doc__,
+ "get_boot() -> UUID\n\n"
+ "Return a 128-bit unique identifier for this boot.\n"
+ "Wraps sd_id128_get_boot(3)."
+);
+
+static PyObject* make_uuid(sd_id128_t id) {
+ _cleanup_Py_DECREF_ PyObject
+ *uuid = NULL, *UUID = NULL, *bytes = NULL,
+ *args = NULL, *kwargs = NULL;
+
+ uuid = PyImport_ImportModule("uuid");
+ if (!uuid)
+ return NULL;
+
+ UUID = PyObject_GetAttrString(uuid, "UUID");
+ bytes = PyBytes_FromStringAndSize((const char*) &id.bytes, sizeof(id.bytes));
+ args = Py_BuildValue("()");
+ kwargs = PyDict_New();
+ if (!UUID || !bytes || !args || !kwargs)
+ return NULL;
+
+ if (PyDict_SetItemString(kwargs, "bytes", bytes) < 0)
+ return NULL;
+
+ return PyObject_Call(UUID, args, kwargs);
+}
+
+#define helper(name) \
+ static PyObject *name(PyObject *self, PyObject *args) { \
+ sd_id128_t id; \
+ int r; \
+ \
+ assert(args == NULL); \
+ \
+ r = sd_id128_##name(&id); \
+ if (r < 0) { \
+ errno = -r; \
+ return PyErr_SetFromErrno(PyExc_IOError); \
+ } \
+ \
+ return make_uuid(id); \
+ }
+
+helper(randomize)
+helper(get_machine)
+helper(get_boot)
+
+static PyMethodDef methods[] = {
+ { "randomize", randomize, METH_NOARGS, randomize__doc__},
+ { "get_machine", get_machine, METH_NOARGS, get_machine__doc__},
+ { "get_boot", get_boot, METH_NOARGS, get_boot__doc__},
+ { NULL, NULL, 0, NULL } /* Sentinel */
+};
+
+static int add_id(PyObject *module, const char* name, sd_id128_t id) {
+ PyObject *obj;
+
+ obj = make_uuid(id);
+ if (!obj)
+ return -1;
+
+ return PyModule_AddObject(module, name, obj);
+}
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wmissing-prototypes"
+
+#if PY_MAJOR_VERSION < 3
+
+PyMODINIT_FUNC initid128(void) {
+ PyObject *m;
+
+ m = Py_InitModule3("id128", methods, module__doc__);
+ if (m == NULL)
+ return;
+
+ /* a series of lines like 'add_id() ;' follow */
+#define JOINER ;
+#include "id128-constants.h"
+#undef JOINER
+ PyModule_AddStringConstant(m, "__version__", PACKAGE_VERSION);
+}
+
+#else
+
+static struct PyModuleDef module = {
+ PyModuleDef_HEAD_INIT,
+ "id128", /* name of module */
+ module__doc__, /* module documentation, may be NULL */
+ -1, /* size of per-interpreter state of the module */
+ methods
+};
+
+PyMODINIT_FUNC PyInit_id128(void) {
+ PyObject *m;
+
+ m = PyModule_Create(&module);
+ if (m == NULL)
+ return NULL;
+
+ if ( /* a series of lines like 'add_id() ||' follow */
+#define JOINER ||
+#include "id128-constants.h"
+#undef JOINER
+ PyModule_AddStringConstant(m, "__version__", PACKAGE_VERSION)) {
+ Py_DECREF(m);
+ return NULL;
+ }
+
+ return m;
+}
+
+#endif
+
+#pragma GCC diagnostic pop
diff --git a/src/python-systemd/journal.py b/src/python-systemd/journal.py
new file mode 100644
index 0000000000..9ef1ede229
--- /dev/null
+++ b/src/python-systemd/journal.py
@@ -0,0 +1,541 @@
+# -*- Mode: python; coding:utf-8; indent-tabs-mode: nil -*- */
+#
+# This file is part of systemd.
+#
+# Copyright 2012 David Strauss <david@davidstrauss.net>
+# Copyright 2012 Zbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
+# Copyright 2012 Marti Raudsepp <marti@juffo.org>
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 of the License, or
+# (at your option) any later version.
+#
+# systemd is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with systemd; If not, see <http://www.gnu.org/licenses/>.
+
+from __future__ import division
+
+import sys as _sys
+import datetime as _datetime
+import uuid as _uuid
+import traceback as _traceback
+import os as _os
+import logging as _logging
+if _sys.version_info >= (3,3):
+ from collections import ChainMap as _ChainMap
+from syslog import (LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR,
+ LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG)
+from ._journal import __version__, sendv, stream_fd
+from ._reader import (_Reader, NOP, APPEND, INVALIDATE,
+ LOCAL_ONLY, RUNTIME_ONLY, SYSTEM_ONLY,
+ _get_catalog)
+from . import id128 as _id128
+
+if _sys.version_info >= (3,):
+ from ._reader import Monotonic
+else:
+ Monotonic = tuple
+
+def _convert_monotonic(m):
+ return Monotonic((_datetime.timedelta(microseconds=m[0]),
+ _uuid.UUID(bytes=m[1])))
+
+def _convert_source_monotonic(s):
+ return _datetime.timedelta(microseconds=int(s))
+
+def _convert_realtime(t):
+ return _datetime.datetime.fromtimestamp(t / 1000000)
+
+def _convert_timestamp(s):
+ return _datetime.datetime.fromtimestamp(int(s) / 1000000)
+
+if _sys.version_info >= (3,):
+ def _convert_uuid(s):
+ return _uuid.UUID(s.decode())
+else:
+ _convert_uuid = _uuid.UUID
+
+DEFAULT_CONVERTERS = {
+ 'MESSAGE_ID': _convert_uuid,
+ '_MACHINE_ID': _convert_uuid,
+ '_BOOT_ID': _convert_uuid,
+ 'PRIORITY': int,
+ 'LEADER': int,
+ 'SESSION_ID': int,
+ 'USERSPACE_USEC': int,
+ 'INITRD_USEC': int,
+ 'KERNEL_USEC': int,
+ '_UID': int,
+ '_GID': int,
+ '_PID': int,
+ 'SYSLOG_FACILITY': int,
+ 'SYSLOG_PID': int,
+ '_AUDIT_SESSION': int,
+ '_AUDIT_LOGINUID': int,
+ '_SYSTEMD_SESSION': int,
+ '_SYSTEMD_OWNER_UID': int,
+ 'CODE_LINE': int,
+ 'ERRNO': int,
+ 'EXIT_STATUS': int,
+ '_SOURCE_REALTIME_TIMESTAMP': _convert_timestamp,
+ '__REALTIME_TIMESTAMP': _convert_realtime,
+ '_SOURCE_MONOTONIC_TIMESTAMP': _convert_source_monotonic,
+ '__MONOTONIC_TIMESTAMP': _convert_monotonic,
+ 'COREDUMP': bytes,
+ 'COREDUMP_PID': int,
+ 'COREDUMP_UID': int,
+ 'COREDUMP_GID': int,
+ 'COREDUMP_SESSION': int,
+ 'COREDUMP_SIGNAL': int,
+ 'COREDUMP_TIMESTAMP': _convert_timestamp,
+}
+
+_IDENT_LETTER = set('ABCDEFGHIJKLMNOPQRTSUVWXYZ_')
+
+def _valid_field_name(s):
+ return not (set(s) - _IDENT_LETTER)
+
+class Reader(_Reader):
+ """Reader allows the access and filtering of systemd journal
+ entries. Note that in order to access the system journal, a
+ non-root user must be in the `systemd-journal` group.
+
+ Example usage to print out all informational or higher level
+ messages for systemd-udevd for this boot:
+
+ >>> j = journal.Reader()
+ >>> j.this_boot()
+ >>> j.log_level(journal.LOG_INFO)
+ >>> j.add_match(_SYSTEMD_UNIT="systemd-udevd.service")
+ >>> for entry in j:
+ ... print(entry['MESSAGE'])
+
+ See systemd.journal-fields(7) for more info on typical fields
+ found in the journal.
+ """
+ def __init__(self, flags=0, path=None, converters=None):
+ """Create an instance of Reader, which allows filtering and
+ return of journal entries.
+
+ Argument `flags` sets open flags of the journal, which can be one
+ of, or ORed combination of constants: LOCAL_ONLY (default) opens
+ journal on local machine only; RUNTIME_ONLY opens only
+ volatile journal files; and SYSTEM_ONLY opens only
+ journal files of system services and the kernel.
+
+ Argument `path` is the directory of journal files. Note that
+ `flags` and `path` are exclusive.
+
+ Argument `converters` is a dictionary which updates the
+ DEFAULT_CONVERTERS to convert journal field values. Field
+ names are used as keys into this dictionary. The values must
+ be single argument functions, which take a `bytes` object and
+ return a converted value. When there's no entry for a field
+ name, then the default UTF-8 decoding will be attempted. If
+ the conversion fails with a ValueError, unconverted bytes
+ object will be returned. (Note that ValueEror is a superclass
+ of UnicodeDecodeError).
+
+ Reader implements the context manager protocol: the journal
+ will be closed when exiting the block.
+ """
+ super(Reader, self).__init__(flags, path)
+ if _sys.version_info >= (3,3):
+ self.converters = _ChainMap()
+ if converters is not None:
+ self.converters.maps.append(converters)
+ self.converters.maps.append(DEFAULT_CONVERTERS)
+ else:
+ self.converters = DEFAULT_CONVERTERS.copy()
+ if converters is not None:
+ self.converters.update(converters)
+
+ def _convert_field(self, key, value):
+ """Convert value using self.converters[key]
+
+ If `key` is not present in self.converters, a standard unicode
+ decoding will be attempted. If the conversion (either
+ key-specific or the default one) fails with a ValueError, the
+ original bytes object will be returned.
+ """
+ convert = self.converters.get(key, bytes.decode)
+ try:
+ return convert(value)
+ except ValueError:
+ # Leave in default bytes
+ return value
+
+ def _convert_entry(self, entry):
+ """Convert entire journal entry utilising _covert_field"""
+ result = {}
+ for key, value in entry.items():
+ if isinstance(value, list):
+ result[key] = [self._convert_field(key, val) for val in value]
+ else:
+ result[key] = self._convert_field(key, value)
+ return result
+
+ def __iter__(self):
+ """Part of iterator protocol.
+ Returns self.
+ """
+ return self
+
+ if _sys.version_info >= (3,):
+ def __next__(self):
+ """Part of iterator protocol.
+ Returns self.get_next().
+ """
+ return self.get_next()
+ else:
+ def next(self):
+ """Part of iterator protocol.
+ Returns self.get_next().
+ """
+ return self.get_next()
+
+ def add_match(self, *args, **kwargs):
+ """Add one or more matches to the filter journal log entries.
+ All matches of different field are combined in a logical AND,
+ and matches of the same field are automatically combined in a
+ logical OR.
+ Matches can be passed as strings of form "FIELD=value", or
+ keyword arguments FIELD="value".
+ """
+ args = list(args)
+ args.extend(_make_line(key, val) for key, val in kwargs.items())
+ for arg in args:
+ super(Reader, self).add_match(arg)
+
+ def get_next(self, skip=1):
+ """Return the next log entry as a mapping type, currently
+ a standard dictionary of fields.
+
+ Optional skip value will return the `skip`\-th log entry.
+
+ Entries will be processed with converters specified during
+ Reader creation.
+ """
+ if super(Reader, self)._next(skip):
+ entry = super(Reader, self)._get_all()
+ if entry:
+ entry['__REALTIME_TIMESTAMP'] = self._get_realtime()
+ entry['__MONOTONIC_TIMESTAMP'] = self._get_monotonic()
+ entry['__CURSOR'] = self._get_cursor()
+ return self._convert_entry(entry)
+ return dict()
+
+ def get_previous(self, skip=1):
+ """Return the previous log entry as a mapping type,
+ currently a standard dictionary of fields.
+
+ Optional skip value will return the -`skip`\-th log entry.
+
+ Entries will be processed with converters specified during
+ Reader creation.
+
+ Equivalent to get_next(-skip).
+ """
+ return self.get_next(-skip)
+
+ def query_unique(self, field):
+ """Return unique values appearing in the journal for given `field`.
+
+ Note this does not respect any journal matches.
+
+ Entries will be processed with converters specified during
+ Reader creation.
+ """
+ return set(self._convert_field(field, value)
+ for value in super(Reader, self).query_unique(field))
+
+ def wait(self, timeout=None):
+ """Wait for a change in the journal. `timeout` is the maximum
+ time in seconds to wait, or None, to wait forever.
+
+ Returns one of NOP (no change), APPEND (new entries have been
+ added to the end of the journal), or INVALIDATE (journal files
+ have been added or removed).
+ """
+ us = -1 if timeout is None else int(timeout * 1000000)
+ return super(Reader, self).wait(us)
+
+ def seek_realtime(self, realtime):
+ """Seek to a matching journal entry nearest to `realtime` time.
+
+ Argument `realtime` must be either an integer unix timestamp
+ or datetime.datetime instance.
+ """
+ if isinstance(realtime, _datetime.datetime):
+ realtime = float(realtime.strftime("%s.%f")) * 1000000
+ return super(Reader, self).seek_realtime(int(realtime))
+
+ def seek_monotonic(self, monotonic, bootid=None):
+ """Seek to a matching journal entry nearest to `monotonic` time.
+
+ Argument `monotonic` is a timestamp from boot in either
+ seconds or a datetime.timedelta instance. Argument `bootid`
+ is a string or UUID representing which boot the monotonic time
+ is reference to. Defaults to current bootid.
+ """
+ if isinstance(monotonic, _datetime.timedelta):
+ monotonic = monotonic.totalseconds()
+ monotonic = int(monotonic * 1000000)
+ if isinstance(bootid, _uuid.UUID):
+ bootid = bootid.get_hex()
+ return super(Reader, self).seek_monotonic(monotonic, bootid)
+
+ def log_level(self, level):
+ """Set maximum log `level` by setting matches for PRIORITY.
+ """
+ if 0 <= level <= 7:
+ for i in range(level+1):
+ self.add_match(PRIORITY="%d" % i)
+ else:
+ raise ValueError("Log level must be 0 <= level <= 7")
+
+ def messageid_match(self, messageid):
+ """Add match for log entries with specified `messageid`.
+
+ `messageid` can be string of hexadicimal digits or a UUID
+ instance. Standard message IDs can be found in systemd.id128.
+
+ Equivalent to add_match(MESSAGE_ID=`messageid`).
+ """
+ if isinstance(messageid, _uuid.UUID):
+ messageid = messageid.get_hex()
+ self.add_match(MESSAGE_ID=messageid)
+
+ def this_boot(self, bootid=None):
+ """Add match for _BOOT_ID equal to current boot ID or the specified boot ID.
+
+ If specified, bootid should be either a UUID or a 32 digit hex number.
+
+ Equivalent to add_match(_BOOT_ID='bootid').
+ """
+ if bootid is None:
+ bootid = _id128.get_boot().hex
+ else:
+ bootid = getattr(bootid, 'hex', bootid)
+ self.add_match(_BOOT_ID=bootid)
+
+ def this_machine(self, machineid=None):
+ """Add match for _MACHINE_ID equal to the ID of this machine.
+
+ If specified, machineid should be either a UUID or a 32 digit hex number.
+
+ Equivalent to add_match(_MACHINE_ID='machineid').
+ """
+ if machineid is None:
+ machineid = _id128.get_machine().hex
+ else:
+ machineid = getattr(machineid, 'hex', machineid)
+ self.add_match(_MACHINE_ID=machineid)
+
+
+def get_catalog(mid):
+ if isinstance(mid, _uuid.UUID):
+ mid = mid.get_hex()
+ return _get_catalog(mid)
+
+def _make_line(field, value):
+ if isinstance(value, bytes):
+ return field.encode('utf-8') + b'=' + value
+ else:
+ return field + '=' + value
+
+def send(MESSAGE, MESSAGE_ID=None,
+ CODE_FILE=None, CODE_LINE=None, CODE_FUNC=None,
+ **kwargs):
+ r"""Send a message to the journal.
+
+ >>> journal.send('Hello world')
+ >>> journal.send('Hello, again, world', FIELD2='Greetings!')
+ >>> journal.send('Binary message', BINARY=b'\xde\xad\xbe\xef')
+
+ Value of the MESSAGE argument will be used for the MESSAGE=
+ field. MESSAGE must be a string and will be sent as UTF-8 to
+ the journal.
+
+ MESSAGE_ID can be given to uniquely identify the type of
+ message. It must be a string or a uuid.UUID object.
+
+ CODE_LINE, CODE_FILE, and CODE_FUNC can be specified to
+ identify the caller. Unless at least on of the three is given,
+ values are extracted from the stack frame of the caller of
+ send(). CODE_FILE and CODE_FUNC must be strings, CODE_LINE
+ must be an integer.
+
+ Additional fields for the journal entry can only be specified
+ as keyword arguments. The payload can be either a string or
+ bytes. A string will be sent as UTF-8, and bytes will be sent
+ as-is to the journal.
+
+ Other useful fields include PRIORITY, SYSLOG_FACILITY,
+ SYSLOG_IDENTIFIER, SYSLOG_PID.
+ """
+
+ args = ['MESSAGE=' + MESSAGE]
+
+ if MESSAGE_ID is not None:
+ id = getattr(MESSAGE_ID, 'hex', MESSAGE_ID)
+ args.append('MESSAGE_ID=' + id)
+
+ if CODE_LINE == CODE_FILE == CODE_FUNC == None:
+ CODE_FILE, CODE_LINE, CODE_FUNC = \
+ _traceback.extract_stack(limit=2)[0][:3]
+ if CODE_FILE is not None:
+ args.append('CODE_FILE=' + CODE_FILE)
+ if CODE_LINE is not None:
+ args.append('CODE_LINE={:d}'.format(CODE_LINE))
+ if CODE_FUNC is not None:
+ args.append('CODE_FUNC=' + CODE_FUNC)
+
+ args.extend(_make_line(key, val) for key, val in kwargs.items())
+ return sendv(*args)
+
+def stream(identifier, priority=LOG_DEBUG, level_prefix=False):
+ r"""Return a file object wrapping a stream to journal.
+
+ Log messages written to this file as simple newline sepearted
+ text strings are written to the journal.
+
+ The file will be line buffered, so messages are actually sent
+ after a newline character is written.
+
+ >>> stream = journal.stream('myapp')
+ >>> stream
+ <open file '<fdopen>', mode 'w' at 0x...>
+ >>> stream.write('message...\n')
+
+ will produce the following message in the journal::
+
+ PRIORITY=7
+ SYSLOG_IDENTIFIER=myapp
+ MESSAGE=message...
+
+ Using the interface with print might be more convinient:
+
+ >>> from __future__ import print_function
+ >>> print('message...', file=stream)
+
+ priority is the syslog priority, one of `LOG_EMERG`,
+ `LOG_ALERT`, `LOG_CRIT`, `LOG_ERR`, `LOG_WARNING`,
+ `LOG_NOTICE`, `LOG_INFO`, `LOG_DEBUG`.
+
+ level_prefix is a boolean. If true, kernel-style log priority
+ level prefixes (such as '<1>') are interpreted. See
+ sd-daemon(3) for more information.
+ """
+
+ fd = stream_fd(identifier, priority, level_prefix)
+ return _os.fdopen(fd, 'w', 1)
+
+class JournalHandler(_logging.Handler):
+ """Journal handler class for the Python logging framework.
+
+ Please see the Python logging module documentation for an
+ overview: http://docs.python.org/library/logging.html.
+
+ To create a custom logger whose messages go only to journal:
+
+ >>> log = logging.getLogger('custom_logger_name')
+ >>> log.propagate = False
+ >>> log.addHandler(journal.JournalHandler())
+ >>> log.warn("Some message: %s", detail)
+
+ Note that by default, message levels `INFO` and `DEBUG` are
+ ignored by the logging framework. To enable those log levels:
+
+ >>> log.setLevel(logging.DEBUG)
+
+ To redirect all logging messages to journal regardless of where
+ they come from, attach it to the root logger:
+
+ >>> logging.root.addHandler(journal.JournalHandler())
+
+ For more complex configurations when using `dictConfig` or
+ `fileConfig`, specify `systemd.journal.JournalHandler` as the
+ handler class. Only standard handler configuration options
+ are supported: `level`, `formatter`, `filters`.
+
+ To attach journal MESSAGE_ID, an extra field is supported:
+
+ >>> import uuid
+ >>> mid = uuid.UUID('0123456789ABCDEF0123456789ABCDEF')
+ >>> log.warn("Message with ID", extra={'MESSAGE_ID': mid})
+
+ Fields to be attached to all messages sent through this
+ handler can be specified as keyword arguments. This probably
+ makes sense only for SYSLOG_IDENTIFIER and similar fields
+ which are constant for the whole program:
+
+ >>> journal.JournalHandler(SYSLOG_IDENTIFIER='my-cool-app')
+
+ The following journal fields will be sent:
+ `MESSAGE`, `PRIORITY`, `THREAD_NAME`, `CODE_FILE`, `CODE_LINE`,
+ `CODE_FUNC`, `LOGGER` (name as supplied to getLogger call),
+ `MESSAGE_ID` (optional, see above), `SYSLOG_IDENTIFIER` (defaults
+ to sys.argv[0]).
+ """
+
+ def __init__(self, level=_logging.NOTSET, **kwargs):
+ super(JournalHandler, self).__init__(level)
+
+ for name in kwargs:
+ if not _valid_field_name(name):
+ raise ValueError('Invalid field name: ' + name)
+ if 'SYSLOG_IDENTIFIER' not in kwargs:
+ kwargs['SYSLOG_IDENTIFIER'] = _sys.argv[0]
+ self._extra = kwargs
+
+ def emit(self, record):
+ """Write record as journal event.
+
+ MESSAGE is taken from the message provided by the
+ user, and PRIORITY, LOGGER, THREAD_NAME,
+ CODE_{FILE,LINE,FUNC} fields are appended
+ automatically. In addition, record.MESSAGE_ID will be
+ used if present.
+ """
+ try:
+ msg = self.format(record)
+ pri = self.mapPriority(record.levelno)
+ mid = getattr(record, 'MESSAGE_ID', None)
+ send(msg,
+ MESSAGE_ID=mid,
+ PRIORITY=format(pri),
+ LOGGER=record.name,
+ THREAD_NAME=record.threadName,
+ CODE_FILE=record.pathname,
+ CODE_LINE=record.lineno,
+ CODE_FUNC=record.funcName,
+ **self._extra)
+ except Exception:
+ self.handleError(record)
+
+ @staticmethod
+ def mapPriority(levelno):
+ """Map logging levels to journald priorities.
+
+ Since Python log level numbers are "sparse", we have
+ to map numbers in between the standard levels too.
+ """
+ if levelno <= _logging.DEBUG:
+ return LOG_DEBUG
+ elif levelno <= _logging.INFO:
+ return LOG_INFO
+ elif levelno <= _logging.WARNING:
+ return LOG_WARNING
+ elif levelno <= _logging.ERROR:
+ return LOG_ERR
+ elif levelno <= _logging.CRITICAL:
+ return LOG_CRIT
+ else:
+ return LOG_ALERT
diff --git a/src/python-systemd/login.c b/src/python-systemd/login.c
new file mode 100644
index 0000000000..1dbe5ac5bf
--- /dev/null
+++ b/src/python-systemd/login.c
@@ -0,0 +1,176 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Zbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#define PY_SSIZE_T_CLEAN
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wredundant-decls"
+#include <Python.h>
+#pragma GCC diagnostic pop
+
+#include "systemd/sd-login.h"
+#include "pyutil.h"
+#include "util.h"
+#include "strv.h"
+
+PyDoc_STRVAR(module__doc__,
+ "Python interface to the libsystemd-login library."
+);
+
+#define helper(name) \
+static PyObject* name(PyObject *self, PyObject *args) { \
+ _cleanup_strv_free_ char **list = NULL; \
+ int r; \
+ PyObject *ans; \
+ \
+ assert(args == NULL); \
+ \
+ r = sd_get_##name(&list); \
+ if (r < 0) { \
+ errno = -r; \
+ return PyErr_SetFromErrno(PyExc_IOError); \
+ } \
+ \
+ ans = PyList_New(r); \
+ if (!ans) \
+ return NULL; \
+ \
+ for (r--; r >= 0; r--) { \
+ PyObject *s = unicode_FromString(list[r]); \
+ if (!s) { \
+ Py_DECREF(ans); \
+ return NULL; \
+ } \
+ \
+ PyList_SetItem(ans, r, s); \
+ } \
+ \
+ return ans; \
+}
+
+helper(seats)
+helper(sessions)
+helper(machine_names)
+#undef helper
+
+static PyObject* uids(PyObject *self, PyObject *args) {
+ _cleanup_free_ uid_t *list = NULL;
+ int r;
+ PyObject *ans;
+
+ assert(args == NULL);
+
+ r = sd_get_uids(&list);
+ if (r < 0) {
+ errno = -r;
+ return PyErr_SetFromErrno(PyExc_IOError);
+ }
+
+ ans = PyList_New(r);
+ if (!ans)
+ return NULL;
+
+ for (r--; r >= 0; r--) {
+ PyObject *s = long_FromLong(list[r]);
+ if (!s) {
+ Py_DECREF(ans);
+ return NULL;
+ }
+
+ PyList_SetItem(ans, r, s);
+ }
+
+ return ans;
+}
+
+PyDoc_STRVAR(seats__doc__,
+ "seats() -> list\n\n"
+ "Returns a list of currently available local seats.\n"
+ "Wraps sd_get_seats(3)."
+);
+
+PyDoc_STRVAR(sessions__doc__,
+ "sessions() -> list\n\n"
+ "Returns a list of current login sessions.\n"
+ "Wraps sd_get_sessions(3)."
+);
+
+PyDoc_STRVAR(machine_names__doc__,
+ "machine_names() -> list\n\n"
+ "Returns a list of currently running virtual machines\n"
+ "and containers on the system.\n"
+ "Wraps sd_get_machine_names(3)."
+);
+
+PyDoc_STRVAR(uids__doc__,
+ "uids() -> list\n\n"
+ "Returns a list of uids of users who currently have login sessions.\n"
+ "Wraps sd_get_uids(3)."
+);
+
+static PyMethodDef methods[] = {
+ { "seats", seats, METH_NOARGS, seats__doc__},
+ { "sessions", sessions, METH_NOARGS, sessions__doc__},
+ { "machine_names", machine_names, METH_NOARGS, machine_names__doc__},
+ { "uids", uids, METH_NOARGS, uids__doc__},
+ {} /* Sentinel */
+};
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wmissing-prototypes"
+
+#if PY_MAJOR_VERSION < 3
+
+PyMODINIT_FUNC initlogin(void) {
+ PyObject *m;
+
+ m = Py_InitModule3("login", methods, module__doc__);
+ if (m == NULL)
+ return;
+ PyModule_AddStringConstant(m, "__version__", PACKAGE_VERSION);
+}
+#else
+
+static struct PyModuleDef module = {
+ PyModuleDef_HEAD_INIT,
+ "login", /* name of module */
+ module__doc__, /* module documentation, may be NULL */
+ -1, /* size of per-interpreter state of the module */
+ methods
+};
+
+PyMODINIT_FUNC PyInit_login(void) {
+ PyObject *m;
+
+ m = PyModule_Create(&module);
+ if (m == NULL)
+ return NULL;
+
+ if (PyModule_AddStringConstant(m, "__version__", PACKAGE_VERSION)) {
+ Py_DECREF(m);
+ return NULL;
+ }
+
+ return m;
+}
+
+#endif
+
+#pragma GCC diagnostic pop
diff --git a/src/python-systemd/pyutil.c b/src/python-systemd/pyutil.c
new file mode 100644
index 0000000000..9510acdddb
--- /dev/null
+++ b/src/python-systemd/pyutil.c
@@ -0,0 +1,46 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Zbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <Python.h>
+#include "pyutil.h"
+
+void cleanup_Py_DECREFp(PyObject **p) {
+ if (!*p)
+ return;
+
+ Py_DECREF(*p);
+}
+
+PyObject* absolute_timeout(uint64_t t) {
+ if (t == (uint64_t) -1)
+ return PyLong_FromLong(-1);
+ else {
+ struct timespec ts;
+ uint64_t n;
+ int msec;
+
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ n = (uint64_t) ts.tv_sec * 1000000 + ts.tv_nsec / 1000;
+ msec = t > n ? (int) ((t - n + 999) / 1000) : 0;
+
+ return PyLong_FromLong(msec);
+ }
+}
diff --git a/src/python-systemd/pyutil.h b/src/python-systemd/pyutil.h
new file mode 100644
index 0000000000..5c7ea37cdb
--- /dev/null
+++ b/src/python-systemd/pyutil.h
@@ -0,0 +1,49 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Zbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#ifndef Py_TYPE
+/* avoid duplication warnings from errors in Python 2.7 headers */
+# include <Python.h>
+#endif
+
+void cleanup_Py_DECREFp(PyObject **p);
+PyObject* absolute_timeout(uint64_t t);
+
+#define _cleanup_Py_DECREF_ __attribute__((cleanup(cleanup_Py_DECREFp)))
+
+#if PY_MAJOR_VERSION >=3
+# define unicode_FromStringAndSize PyUnicode_FromStringAndSize
+# define unicode_FromString PyUnicode_FromString
+# define long_FromLong PyLong_FromLong
+# define long_FromSize_t PyLong_FromSize_t
+# define long_Check PyLong_Check
+# define long_AsLong PyLong_AsLong
+#else
+/* Python 3 type naming convention is used */
+# define unicode_FromStringAndSize PyString_FromStringAndSize
+# define unicode_FromString PyString_FromString
+# define long_FromLong PyInt_FromLong
+# define long_FromSize_t PyInt_FromSize_t
+# define long_Check PyInt_Check
+# define long_AsLong PyInt_AsLong
+#endif
diff --git a/src/quotacheck/quotacheck.c b/src/quotacheck/quotacheck.c
new file mode 100644
index 0000000000..1f63785041
--- /dev/null
+++ b/src/quotacheck/quotacheck.c
@@ -0,0 +1,122 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include <stdbool.h>
+#include <string.h>
+#include <errno.h>
+#include <unistd.h>
+
+#include "util.h"
+#include "virt.h"
+#include "fileio.h"
+
+static bool arg_skip = false;
+static bool arg_force = false;
+
+static int parse_proc_cmdline(void) {
+ _cleanup_free_ char *line = NULL;
+ char *w, *state;
+ size_t l;
+ int r;
+
+ if (detect_container(NULL) > 0)
+ return 0;
+
+ r = read_one_line_file("/proc/cmdline", &line);
+ if (r < 0) {
+ log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
+ return 0;
+ }
+
+ FOREACH_WORD_QUOTED(w, l, line, state) {
+
+ if (strneq(w, "quotacheck.mode=auto", l))
+ arg_force = arg_skip = false;
+ else if (strneq(w, "quotacheck.mode=force", l))
+ arg_force = true;
+ else if (strneq(w, "quotacheck.mode=skip", l))
+ arg_skip = true;
+ else if (startswith(w, "quotacheck"))
+ log_warning("Invalid quotacheck parameter. Ignoring.");
+#ifdef HAVE_SYSV_COMPAT
+ else if (strneq(w, "forcequotacheck", l)) {
+ log_error("Please use 'quotacheck.mode=force' rather than 'forcequotacheck' on the kernel command line.");
+ arg_force = true;
+ }
+#endif
+ }
+ return 0;
+}
+
+static void test_files(void) {
+#ifdef HAVE_SYSV_COMPAT
+ if (access("/forcequotacheck", F_OK) >= 0) {
+ log_error("Please pass 'quotacheck.mode=force' on the kernel command line rather than creating /forcequotacheck on the root file system.");
+ arg_force = true;
+ }
+#endif
+}
+
+int main(int argc, char *argv[]) {
+
+ static const char * const cmdline[] = {
+ QUOTACHECK,
+ "-anug",
+ NULL
+ };
+
+ pid_t pid;
+
+ if (argc > 1) {
+ log_error("This program takes no arguments.");
+ return EXIT_FAILURE;
+ }
+
+ log_set_target(LOG_TARGET_AUTO);
+ log_parse_environment();
+ log_open();
+
+ umask(0022);
+
+ parse_proc_cmdline();
+ test_files();
+
+ if (!arg_force) {
+ if (arg_skip)
+ return EXIT_SUCCESS;
+
+ if (access("/run/systemd/quotacheck", F_OK) < 0)
+ return EXIT_SUCCESS;
+ }
+
+ pid = fork();
+ if (pid < 0) {
+ log_error("fork(): %m");
+ return EXIT_FAILURE;
+ } else if (pid == 0) {
+ /* Child */
+ execv(cmdline[0], (char**) cmdline);
+ _exit(1); /* Operational error */
+ }
+
+ return wait_for_terminate_and_warn("quotacheck", pid) >= 0 ? EXIT_SUCCESS : EXIT_FAILURE;
+}
diff --git a/src/random-seed/random-seed.c b/src/random-seed/random-seed.c
new file mode 100644
index 0000000000..fdcaa1e154
--- /dev/null
+++ b/src/random-seed/random-seed.c
@@ -0,0 +1,149 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <unistd.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <string.h>
+#include <sys/stat.h>
+
+#include "log.h"
+#include "util.h"
+#include "mkdir.h"
+
+#define POOL_SIZE_MIN 512
+
+int main(int argc, char *argv[]) {
+ int seed_fd = -1, random_fd = -1;
+ int ret = EXIT_FAILURE;
+ void* buf;
+ size_t buf_size = 0;
+ ssize_t r;
+ FILE *f;
+
+ if (argc != 2) {
+ log_error("This program requires one argument.");
+ return EXIT_FAILURE;
+ }
+
+ log_set_target(LOG_TARGET_AUTO);
+ log_parse_environment();
+ log_open();
+
+ umask(0022);
+
+ /* Read pool size, if possible */
+ if ((f = fopen("/proc/sys/kernel/random/poolsize", "re"))) {
+ if (fscanf(f, "%zu", &buf_size) > 0) {
+ /* poolsize is in bits on 2.6, but we want bytes */
+ buf_size /= 8;
+ }
+
+ fclose(f);
+ }
+
+ if (buf_size <= POOL_SIZE_MIN)
+ buf_size = POOL_SIZE_MIN;
+
+ if (!(buf = malloc(buf_size))) {
+ log_error("Failed to allocate buffer.");
+ goto finish;
+ }
+
+ if (mkdir_parents_label(RANDOM_SEED, 0755) < 0) {
+ log_error("Failed to create directories parents of %s: %m", RANDOM_SEED);
+ goto finish;
+ }
+
+ /* When we load the seed we read it and write it to the device
+ * and then immediately update the saved seed with new data,
+ * to make sure the next boot gets seeded differently. */
+
+ if (streq(argv[1], "load")) {
+
+ if ((seed_fd = open(RANDOM_SEED, O_RDWR|O_CLOEXEC|O_NOCTTY|O_CREAT, 0600)) < 0) {
+ if ((seed_fd = open(RANDOM_SEED, O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0) {
+ log_error("Failed to open random seed: %m");
+ goto finish;
+ }
+ }
+
+ if ((random_fd = open("/dev/urandom", O_RDWR|O_CLOEXEC|O_NOCTTY, 0600)) < 0) {
+ if ((random_fd = open("/dev/urandom", O_WRONLY|O_CLOEXEC|O_NOCTTY, 0600)) < 0) {
+ log_error("Failed to open /dev/urandom: %m");
+ goto finish;
+ }
+ }
+
+ if ((r = loop_read(seed_fd, buf, buf_size, false)) <= 0) {
+
+ if (r != 0)
+ log_error("Failed to read seed file: %m");
+ } else {
+ lseek(seed_fd, 0, SEEK_SET);
+
+ if ((r = loop_write(random_fd, buf, (size_t) r, false)) <= 0)
+ log_error("Failed to write seed to /dev/urandom: %s",
+ r < 0 ? strerror(errno) : "short write");
+ }
+
+ } else if (streq(argv[1], "save")) {
+
+ if ((seed_fd = open(RANDOM_SEED, O_WRONLY|O_CLOEXEC|O_NOCTTY|O_CREAT, 0600)) < 0) {
+ log_error("Failed to open random seed: %m");
+ goto finish;
+ }
+
+ if ((random_fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0) {
+ log_error("Failed to open /dev/urandom: %m");
+ goto finish;
+ }
+ } else {
+ log_error("Unknown verb %s.", argv[1]);
+ goto finish;
+ }
+
+ /* This is just a safety measure. Given that we are root and
+ * most likely created the file ourselves the mode and owner
+ * should be correct anyway. */
+ fchmod(seed_fd, 0600);
+ fchown(seed_fd, 0, 0);
+
+ if ((r = loop_read(random_fd, buf, buf_size, false)) <= 0)
+ log_error("Failed to read new seed from /dev/urandom: %s", r < 0 ? strerror(errno) : "EOF");
+ else {
+ if ((r = loop_write(seed_fd, buf, (size_t) r, false)) <= 0)
+ log_error("Failed to write new random seed file: %s", r < 0 ? strerror(errno) : "short write");
+ }
+
+ ret = EXIT_SUCCESS;
+
+finish:
+ if (random_fd >= 0)
+ close_nointr_nofail(random_fd);
+
+ if (seed_fd >= 0)
+ close_nointr_nofail(seed_fd);
+
+ free(buf);
+
+ return ret;
+}
diff --git a/src/rc-local-generator/rc-local-generator.c b/src/rc-local-generator/rc-local-generator.c
new file mode 100644
index 0000000000..9265501250
--- /dev/null
+++ b/src/rc-local-generator/rc-local-generator.c
@@ -0,0 +1,115 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+ Copyright 2011 Michal Schmidt
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <stdio.h>
+#include <unistd.h>
+
+#include "log.h"
+#include "util.h"
+#include "mkdir.h"
+
+#ifndef RC_LOCAL_SCRIPT_PATH_START
+#define RC_LOCAL_SCRIPT_PATH_START "/etc/rc.d/rc.local"
+#endif
+
+#ifndef RC_LOCAL_SCRIPT_PATH_STOP
+#define RC_LOCAL_SCRIPT_PATH_STOP "/sbin/halt.local"
+#endif
+
+const char *arg_dest = "/tmp";
+
+static int add_symlink(const char *service, const char *where) {
+ char *from = NULL, *to = NULL;
+ int r;
+
+ assert(service);
+
+ asprintf(&from, SYSTEM_DATA_UNIT_PATH "/%s", service);
+ asprintf(&to, "%s/%s.wants/%s", arg_dest, where, service);
+
+ if (!from || !to) {
+ r = log_oom();
+ goto finish;
+ }
+
+ mkdir_parents_label(to, 0755);
+
+ r = symlink(from, to);
+ if (r < 0) {
+ if (errno == EEXIST)
+ r = 0;
+ else {
+ log_error("Failed to create symlink %s: %m", to);
+ r = -errno;
+ }
+ }
+
+finish:
+ free(from);
+ free(to);
+
+ return r;
+}
+
+static bool file_is_executable(const char *f) {
+ struct stat st;
+
+ if (stat(f, &st) < 0)
+ return false;
+
+ return S_ISREG(st.st_mode) && (st.st_mode & 0111);
+}
+
+int main(int argc, char *argv[]) {
+ int r = EXIT_SUCCESS;
+
+ if (argc > 1 && argc != 4) {
+ log_error("This program takes three or no arguments.");
+ return EXIT_FAILURE;
+ }
+
+ if (argc > 1)
+ arg_dest = argv[1];
+
+ log_set_target(LOG_TARGET_SAFE);
+ log_parse_environment();
+ log_open();
+
+ umask(0022);
+
+ if (file_is_executable(RC_LOCAL_SCRIPT_PATH_START)) {
+ log_debug("Automatically adding rc-local.service.");
+
+ if (add_symlink("rc-local.service", "multi-user.target") < 0)
+ r = EXIT_FAILURE;
+ }
+
+ if (file_is_executable(RC_LOCAL_SCRIPT_PATH_STOP)) {
+ log_debug("Automatically adding halt-local.service.");
+
+ if (add_symlink("halt-local.service", "final.target") < 0)
+ r = EXIT_FAILURE;
+ }
+
+ return r;
+}
diff --git a/src/readahead/readahead-analyze.c b/src/readahead/readahead-analyze.c
new file mode 100644
index 0000000000..76db3cb7e4
--- /dev/null
+++ b/src/readahead/readahead-analyze.c
@@ -0,0 +1,146 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Auke Kok <auke-jan.h.kok@intel.com>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdbool.h>
+#include <unistd.h>
+#include <inttypes.h>
+#include <linux/limits.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <string.h>
+
+#include "readahead-common.h"
+
+int main_analyze(const char *pack_path) {
+ char line[LINE_MAX];
+ _cleanup_fclose_ FILE *pack = NULL;
+ int a;
+ int missing = 0;
+ size_t tsize = 0;
+
+ if (!pack_path)
+ pack_path = "/.readahead";
+
+ pack = fopen(pack_path, "re");
+ if (!pack) {
+ log_error("Pack file missing.");
+ goto fail;
+ }
+
+ if (!fgets(line, sizeof(line), pack)) {
+ log_error("Pack file corrupt.");
+ goto fail;
+ }
+
+ char_array_0(line);
+
+ if (!endswith(line, READAHEAD_PACK_FILE_VERSION)) {
+ log_error("Pack file version incompatible with this parser.");
+ goto fail;
+ }
+
+ if ((a = getc(pack)) == EOF) {
+ log_error("Pack file corrupt.");
+ goto fail;
+ }
+
+ fputs(" pct sections size: path\n"
+ " === ======== ====: ====\n", stdout);
+
+ for (;;) {
+ char path[PATH_MAX];
+ struct stat st;
+ uint64_t inode;
+ int pages = 0;
+ int sections = 0;
+
+ if (!fgets(path, sizeof(path), pack))
+ break; /* done */
+
+ path[strlen(path)-1] = 0;
+
+ if (fread(&inode, sizeof(inode), 1, pack) != 1) {
+ log_error("Pack file corrupt.");
+ goto fail;
+ }
+
+ for (;;) {
+ uint32_t b, c;
+
+ if (fread(&b, sizeof(b), 1, pack) != 1 ||
+ fread(&c, sizeof(c), 1, pack) != 1) {
+ log_error("Pack file corrupt.");
+ goto fail;
+ }
+ if ((b == 0) && (c == 0))
+ break;
+
+ /* Uncomment this to get all the chunks separately
+ printf(" %d: %d %d\n", sections, b, c);
+ */
+
+ pages += (c - b);
+ sections++;
+ }
+
+ if (stat(path, &st) == 0) {
+ off_t size;
+
+ if (sections == 0)
+ size = st.st_size;
+ else
+ size = pages * page_size();
+
+ tsize += size;
+
+ printf(" %4jd%% (%2d) %12jd: %s\n",
+ (intmax_t) (sections && st.st_size ? size * 100 / st.st_size : 100),
+ sections ? sections : 1,
+ (intmax_t) size,
+ path);
+ } else {
+ printf(" %4dp (%2d) %12s: %s (MISSING)\n",
+ sections ? pages : -1,
+ sections ? sections : 1,
+ "???",
+ path);
+ missing++;
+ }
+
+ }
+
+ printf("\nHOST: %s"
+ "TYPE: %c\n"
+ "MISSING: %d\n"
+ "TOTAL: %zu\n",
+ line,
+ a,
+ missing,
+ tsize);
+
+ return EXIT_SUCCESS;
+
+fail:
+ return EXIT_FAILURE;
+}
diff --git a/src/readahead/readahead-collect.c b/src/readahead/readahead-collect.c
new file mode 100644
index 0000000000..ccd8408c1b
--- /dev/null
+++ b/src/readahead/readahead-collect.c
@@ -0,0 +1,652 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <inttypes.h>
+#include <fcntl.h>
+#include <linux/limits.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/select.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <linux/fanotify.h>
+#include <sys/signalfd.h>
+#include <sys/poll.h>
+#include <sys/mman.h>
+#include <linux/fs.h>
+#include <linux/fiemap.h>
+#include <sys/ioctl.h>
+#include <sys/vfs.h>
+#include <getopt.h>
+#include <sys/inotify.h>
+#include <math.h>
+
+#ifdef HAVE_FANOTIFY_INIT
+#include <sys/fanotify.h>
+#endif
+
+#include <systemd/sd-daemon.h>
+
+#include "missing.h"
+#include "util.h"
+#include "set.h"
+#include "ioprio.h"
+#include "readahead-common.h"
+#include "virt.h"
+
+/* fixme:
+ *
+ * - detect ssd on btrfs/lvm...
+ * - read ahead directories
+ * - gzip?
+ * - remount rw?
+ * - handle files where nothing is in mincore
+ * - does ioprio_set work with fadvise()?
+ */
+
+static ReadaheadShared *shared = NULL;
+static usec_t starttime;
+
+/* Avoid collisions with the NULL pointer */
+#define SECTOR_TO_PTR(s) ULONG_TO_PTR((s)+1)
+#define PTR_TO_SECTOR(p) (PTR_TO_ULONG(p)-1)
+
+static int btrfs_defrag(int fd) {
+ struct btrfs_ioctl_vol_args data = { .fd = fd };
+
+ return ioctl(fd, BTRFS_IOC_DEFRAG, &data);
+}
+
+static int pack_file(FILE *pack, const char *fn, bool on_btrfs) {
+ struct stat st;
+ void *start = MAP_FAILED;
+ uint8_t *vec;
+ uint32_t b, c;
+ uint64_t inode;
+ size_t l, pages;
+ bool mapped;
+ int r = 0, fd = -1, k;
+
+ assert(pack);
+ assert(fn);
+
+ fd = open(fn, O_RDONLY|O_CLOEXEC|O_NOATIME|O_NOCTTY|O_NOFOLLOW);
+ if (fd < 0) {
+
+ if (errno == ENOENT)
+ return 0;
+
+ if (errno == EPERM || errno == EACCES)
+ return 0;
+
+ log_warning("open(%s) failed: %m", fn);
+ r = -errno;
+ goto finish;
+ }
+
+ k = file_verify(fd, fn, arg_file_size_max, &st);
+ if (k <= 0) {
+ r = k;
+ goto finish;
+ }
+
+ if (on_btrfs)
+ btrfs_defrag(fd);
+
+ l = PAGE_ALIGN(st.st_size);
+ start = mmap(NULL, l, PROT_READ, MAP_SHARED, fd, 0);
+ if (start == MAP_FAILED) {
+ log_warning("mmap(%s) failed: %m", fn);
+ r = -errno;
+ goto finish;
+ }
+
+ pages = l / page_size();
+ vec = alloca(pages);
+ memset(vec, 0, pages);
+ if (mincore(start, l, vec) < 0) {
+ log_warning("mincore(%s) failed: %m", fn);
+ r = -errno;
+ goto finish;
+ }
+
+ fputs(fn, pack);
+ fputc('\n', pack);
+
+ /* Store the inode, so that we notice when the file is deleted */
+ inode = (uint64_t) st.st_ino;
+ fwrite(&inode, sizeof(inode), 1, pack);
+
+ mapped = false;
+ for (c = 0; c < pages; c++) {
+ bool new_mapped = !!(vec[c] & 1);
+
+ if (!mapped && new_mapped)
+ b = c;
+ else if (mapped && !new_mapped) {
+ fwrite(&b, sizeof(b), 1, pack);
+ fwrite(&c, sizeof(c), 1, pack);
+
+ log_debug("%s: page %u to %u", fn, b, c);
+ }
+
+ mapped = new_mapped;
+ }
+
+ /* We don't write any range data if we should read the entire file */
+ if (mapped && b > 0) {
+ fwrite(&b, sizeof(b), 1, pack);
+ fwrite(&c, sizeof(c), 1, pack);
+
+ log_debug("%s: page %u to %u", fn, b, c);
+ }
+
+ /* End marker */
+ b = 0;
+ fwrite(&b, sizeof(b), 1, pack);
+ fwrite(&b, sizeof(b), 1, pack);
+
+finish:
+ if (start != MAP_FAILED)
+ munmap(start, l);
+
+ if (fd >= 0)
+ close_nointr_nofail(fd);
+
+ return r;
+}
+
+static unsigned long fd_first_block(int fd) {
+ struct {
+ struct fiemap fiemap;
+ struct fiemap_extent extent;
+ } data = {
+ .fiemap.fm_length = ~0ULL,
+ .fiemap.fm_extent_count = 1,
+ };
+
+ if (ioctl(fd, FS_IOC_FIEMAP, &data) < 0)
+ return 0;
+
+ if (data.fiemap.fm_mapped_extents <= 0)
+ return 0;
+
+ if (data.fiemap.fm_extents[0].fe_flags & FIEMAP_EXTENT_UNKNOWN)
+ return 0;
+
+ return (unsigned long) data.fiemap.fm_extents[0].fe_physical;
+}
+
+struct item {
+ const char *path;
+ unsigned long block;
+ unsigned long bin;
+};
+
+static int qsort_compare(const void *a, const void *b) {
+ const struct item *i, *j;
+
+ i = a;
+ j = b;
+
+ /* sort by bin first */
+ if (i->bin < j->bin)
+ return -1;
+ if (i->bin > j->bin)
+ return 1;
+
+ /* then sort by sector */
+ if (i->block < j->block)
+ return -1;
+ if (i->block > j->block)
+ return 1;
+
+ return strcmp(i->path, j->path);
+}
+
+static int collect(const char *root) {
+ enum {
+ FD_FANOTIFY, /* Get the actual fs events */
+ FD_SIGNAL,
+ FD_INOTIFY, /* We get notifications to quit early via this fd */
+ _FD_MAX
+ };
+ struct pollfd pollfd[_FD_MAX] = {};
+ int fanotify_fd = -1, signal_fd = -1, inotify_fd = -1, r = 0;
+ pid_t my_pid;
+ Hashmap *files = NULL;
+ Iterator i;
+ char *p, *q;
+ sigset_t mask;
+ FILE *pack = NULL;
+ char *pack_fn_new = NULL, *pack_fn = NULL;
+ bool on_ssd, on_btrfs;
+ struct statfs sfs;
+ usec_t not_after;
+ uint64_t previous_block_readahead;
+ bool previous_block_readahead_set = false;
+
+ assert(root);
+
+ if (asprintf(&pack_fn, "%s/.readahead", root) < 0) {
+ r = log_oom();
+ goto finish;
+ }
+
+ starttime = now(CLOCK_MONOTONIC);
+
+ /* If there's no pack file yet we lower the kernel readahead
+ * so that mincore() is accurate. If there is a pack file
+ * already we assume it is accurate enough so that kernel
+ * readahead is never triggered. */
+ previous_block_readahead_set =
+ access(pack_fn, F_OK) < 0 &&
+ block_get_readahead(root, &previous_block_readahead) >= 0 &&
+ block_set_readahead(root, 8*1024) >= 0;
+
+ if (ioprio_set(IOPRIO_WHO_PROCESS, getpid(), IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0)) < 0)
+ log_warning("Failed to set IDLE IO priority class: %m");
+
+ assert_se(sigemptyset(&mask) == 0);
+ sigset_add_many(&mask, SIGINT, SIGTERM, -1);
+ assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
+
+ if ((signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0) {
+ log_error("signalfd(): %m");
+ r = -errno;
+ goto finish;
+ }
+
+ files = hashmap_new(string_hash_func, string_compare_func);
+ if (!files) {
+ log_error("Failed to allocate set.");
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ fanotify_fd = fanotify_init(FAN_CLOEXEC|FAN_NONBLOCK, O_RDONLY|O_LARGEFILE|O_CLOEXEC|O_NOATIME);
+ if (fanotify_fd < 0) {
+ log_error("Failed to create fanotify object: %m");
+ r = -errno;
+ goto finish;
+ }
+
+ if (fanotify_mark(fanotify_fd, FAN_MARK_ADD|FAN_MARK_MOUNT, FAN_OPEN, AT_FDCWD, root) < 0) {
+ log_error("Failed to mark %s: %m", root);
+ r = -errno;
+ goto finish;
+ }
+
+ inotify_fd = open_inotify();
+ if (inotify_fd < 0) {
+ r = inotify_fd;
+ goto finish;
+ }
+
+ not_after = now(CLOCK_MONOTONIC) + arg_timeout;
+
+ my_pid = getpid();
+
+ pollfd[FD_FANOTIFY].fd = fanotify_fd;
+ pollfd[FD_FANOTIFY].events = POLLIN;
+ pollfd[FD_SIGNAL].fd = signal_fd;
+ pollfd[FD_SIGNAL].events = POLLIN;
+ pollfd[FD_INOTIFY].fd = inotify_fd;
+ pollfd[FD_INOTIFY].events = POLLIN;
+
+ sd_notify(0,
+ "READY=1\n"
+ "STATUS=Collecting readahead data");
+
+ log_debug("Collecting...");
+
+ if (access("/run/systemd/readahead/cancel", F_OK) >= 0) {
+ log_debug("Collection canceled");
+ r = -ECANCELED;
+ goto finish;
+ }
+
+ if (access("/run/systemd/readahead/done", F_OK) >= 0) {
+ log_debug("Got termination request");
+ goto done;
+ }
+
+ for (;;) {
+ union {
+ struct fanotify_event_metadata metadata;
+ char buffer[4096];
+ } data;
+ ssize_t n;
+ struct fanotify_event_metadata *m;
+ usec_t t;
+ int h;
+
+ if (hashmap_size(files) > arg_files_max) {
+ log_debug("Reached maximum number of read ahead files, ending collection.");
+ break;
+ }
+
+ t = now(CLOCK_MONOTONIC);
+ if (t >= not_after) {
+ log_debug("Reached maximum collection time, ending collection.");
+ break;
+ }
+
+ if ((h = poll(pollfd, _FD_MAX, (int) ((not_after - t) / USEC_PER_MSEC))) < 0) {
+
+ if (errno == EINTR)
+ continue;
+
+ log_error("poll(): %m");
+ r = -errno;
+ goto finish;
+ }
+
+ if (h == 0) {
+ log_debug("Reached maximum collection time, ending collection.");
+ break;
+ }
+
+ if (pollfd[FD_SIGNAL].revents) {
+ log_debug("Got signal.");
+ break;
+ }
+
+ if (pollfd[FD_INOTIFY].revents) {
+ uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
+ struct inotify_event *e;
+
+ if ((n = read(inotify_fd, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
+ if (errno == EINTR || errno == EAGAIN)
+ continue;
+
+ log_error("Failed to read inotify event: %m");
+ r = -errno;
+ goto finish;
+ }
+
+ e = (struct inotify_event*) inotify_buffer;
+ while (n > 0) {
+ size_t step;
+
+ if ((e->mask & IN_CREATE) && streq(e->name, "cancel")) {
+ log_debug("Collection canceled");
+ r = -ECANCELED;
+ goto finish;
+ }
+
+ if ((e->mask & IN_CREATE) && streq(e->name, "done")) {
+ log_debug("Got termination request");
+ goto done;
+ }
+
+ step = sizeof(struct inotify_event) + e->len;
+ assert(step <= (size_t) n);
+
+ e = (struct inotify_event*) ((uint8_t*) e + step);
+ n -= step;
+ }
+ }
+
+ if ((n = read(fanotify_fd, &data, sizeof(data))) < 0) {
+
+ if (errno == EINTR || errno == EAGAIN)
+ continue;
+
+ /* fanotify sometimes returns EACCES on read()
+ * where it shouldn't. For now let's just
+ * ignore it here (which is safe), but
+ * eventually this should be
+ * dropped when the kernel is fixed.
+ *
+ * https://bugzilla.redhat.com/show_bug.cgi?id=707577 */
+ if (errno == EACCES)
+ continue;
+
+ log_error("Failed to read event: %m");
+ r = -errno;
+ goto finish;
+ }
+
+ for (m = &data.metadata; FAN_EVENT_OK(m, n); m = FAN_EVENT_NEXT(m, n)) {
+ char fn[PATH_MAX];
+ int k;
+
+ if (m->fd < 0)
+ goto next_iteration;
+
+ if (m->pid == my_pid)
+ goto next_iteration;
+
+ __sync_synchronize();
+ if (m->pid == shared->replay)
+ goto next_iteration;
+
+ snprintf(fn, sizeof(fn), "/proc/self/fd/%i", m->fd);
+ char_array_0(fn);
+
+ if ((k = readlink_malloc(fn, &p)) >= 0) {
+ if (startswith(p, "/tmp") ||
+ endswith(p, " (deleted)") ||
+ hashmap_get(files, p))
+ /* Not interesting, or
+ * already read */
+ free(p);
+ else {
+ unsigned long ul;
+ usec_t entrytime;
+ struct item *entry;
+
+ entry = new0(struct item, 1);
+ if (!entry) {
+ r = log_oom();
+ goto finish;
+ }
+
+ ul = fd_first_block(m->fd);
+
+ entrytime = now(CLOCK_MONOTONIC);
+
+ entry->block = ul;
+ entry->path = strdup(p);
+ if (!entry->path) {
+ free(entry);
+ r = log_oom();
+ goto finish;
+ }
+ entry->bin = (entrytime - starttime) / 2000000;
+
+ k = hashmap_put(files, p, entry);
+ if (k < 0) {
+ log_warning("hashmap_put() failed: %s", strerror(-k));
+ free(p);
+ }
+ }
+
+ } else
+ log_warning("readlink(%s) failed: %s", fn, strerror(-k));
+
+ next_iteration:
+ if (m->fd >= 0)
+ close_nointr_nofail(m->fd);
+ }
+ }
+
+done:
+ if (fanotify_fd >= 0) {
+ close_nointr_nofail(fanotify_fd);
+ fanotify_fd = -1;
+ }
+
+ log_debug("Writing Pack File...");
+
+ on_ssd = fs_on_ssd(root) > 0;
+ log_debug("On SSD: %s", yes_no(on_ssd));
+
+ on_btrfs = statfs(root, &sfs) >= 0 && F_TYPE_CMP(sfs.f_type, BTRFS_SUPER_MAGIC);
+ log_debug("On btrfs: %s", yes_no(on_btrfs));
+
+ if (asprintf(&pack_fn_new, "%s/.readahead.new", root) < 0) {
+ r = log_oom();
+ goto finish;
+ }
+
+ pack = fopen(pack_fn_new, "we");
+ if (!pack) {
+ log_error("Failed to open pack file: %m");
+ r = -errno;
+ goto finish;
+ }
+
+ fputs(CANONICAL_HOST READAHEAD_PACK_FILE_VERSION, pack);
+ putc(on_ssd ? 'S' : 'R', pack);
+
+ if (on_ssd || on_btrfs) {
+
+ /* On SSD or on btrfs, just write things out in the
+ * order the files were accessed. */
+
+ HASHMAP_FOREACH_KEY(q, p, files, i)
+ pack_file(pack, p, on_btrfs);
+ } else {
+ struct item *ordered, *j;
+ unsigned k, n;
+
+ /* On rotating media, order things by the block
+ * numbers */
+
+ log_debug("Ordering...");
+
+ n = hashmap_size(files);
+ if (!(ordered = new(struct item, n))) {
+ r = log_oom();
+ goto finish;
+ }
+
+ j = ordered;
+ HASHMAP_FOREACH_KEY(q, p, files, i) {
+ memcpy(j, q, sizeof(struct item));
+ j++;
+ }
+
+ assert(ordered + n == j);
+
+ qsort(ordered, n, sizeof(struct item), qsort_compare);
+
+ for (k = 0; k < n; k++)
+ pack_file(pack, ordered[k].path, on_btrfs);
+
+ free(ordered);
+ }
+
+ log_debug("Finalizing...");
+
+ fflush(pack);
+
+ if (ferror(pack)) {
+ log_error("Failed to write pack file.");
+ r = -EIO;
+ goto finish;
+ }
+
+ if (rename(pack_fn_new, pack_fn) < 0) {
+ log_error("Failed to rename readahead file: %m");
+ r = -errno;
+ goto finish;
+ }
+
+ fclose(pack);
+ pack = NULL;
+
+ log_debug("Done.");
+
+finish:
+ if (fanotify_fd >= 0)
+ close_nointr_nofail(fanotify_fd);
+
+ if (signal_fd >= 0)
+ close_nointr_nofail(signal_fd);
+
+ if (inotify_fd >= 0)
+ close_nointr_nofail(inotify_fd);
+
+ if (pack) {
+ fclose(pack);
+ unlink(pack_fn_new);
+ }
+ free(pack_fn_new);
+ free(pack_fn);
+
+ while ((p = hashmap_steal_first_key(files)))
+ free(p);
+
+ hashmap_free(files);
+
+ if (previous_block_readahead_set) {
+ uint64_t bytes;
+
+ /* Restore the original kernel readahead setting if we
+ * changed it, and nobody has overwritten it since
+ * yet. */
+ if (block_get_readahead(root, &bytes) >= 0 && bytes == 8*1024)
+ block_set_readahead(root, previous_block_readahead);
+ }
+
+ return r;
+}
+
+int main_collect(const char *root) {
+
+ if (!root)
+ root = "/";
+
+ /* Skip this step on read-only media. Note that we check the
+ * underlying block device here, not he read-only flag of the
+ * file system on top, since that one is most likely mounted
+ * read-only anyway at boot, even if the underlying block
+ * device is theoretically writable. */
+ if (fs_on_read_only(root) > 0) {
+ log_info("Disabling readahead collector due to read-only media.");
+ return EXIT_SUCCESS;
+ }
+
+ if (!enough_ram()) {
+ log_info("Disabling readahead collector due to low memory.");
+ return EXIT_SUCCESS;
+ }
+
+ shared = shared_get();
+ if (!shared)
+ return EXIT_FAILURE;
+
+ shared->collect = getpid();
+ __sync_synchronize();
+
+ if (collect(root) < 0)
+ return EXIT_FAILURE;
+
+ return EXIT_SUCCESS;
+}
diff --git a/src/readahead/readahead-common.c b/src/readahead/readahead-common.c
new file mode 100644
index 0000000000..a234a89954
--- /dev/null
+++ b/src/readahead/readahead-common.c
@@ -0,0 +1,414 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/sysinfo.h>
+#include <sys/inotify.h>
+#include <fcntl.h>
+#include <sys/mman.h>
+#include <unistd.h>
+#include <libudev.h>
+
+#include "log.h"
+#include "readahead-common.h"
+#include "util.h"
+#include "missing.h"
+#include "fileio.h"
+
+int file_verify(int fd, const char *fn, off_t file_size_max, struct stat *st) {
+ assert(fd >= 0);
+ assert(fn);
+ assert(st);
+
+ if (fstat(fd, st) < 0) {
+ log_warning("fstat(%s) failed: %m", fn);
+ return -errno;
+ }
+
+ if (!S_ISREG(st->st_mode)) {
+ log_debug("Not preloading special file %s", fn);
+ return 0;
+ }
+
+ if (st->st_size <= 0 || st->st_size > file_size_max) {
+ log_debug("Not preloading file %s with size out of bounds %llu", fn, (unsigned long long) st->st_size);
+ return 0;
+ }
+
+ return 1;
+}
+
+int fs_on_ssd(const char *p) {
+ struct stat st;
+ struct udev *udev = NULL;
+ struct udev_device *udev_device = NULL, *look_at = NULL;
+ bool b = false;
+ const char *devtype, *rotational, *model, *id;
+ int r;
+
+ assert(p);
+
+ if (stat(p, &st) < 0)
+ return -errno;
+
+ if (major(st.st_dev) == 0) {
+ _cleanup_fclose_ FILE *f = NULL;
+ int mount_id;
+ struct file_handle *h;
+
+ /* Might be btrfs, which exposes "ssd" as mount flag if it is on ssd.
+ *
+ * We first determine the mount ID here, if we can,
+ * and then lookup the mount ID in mountinfo to find
+ * the mount options. */
+
+ h = alloca(MAX_HANDLE_SZ);
+ h->handle_bytes = MAX_HANDLE_SZ;
+ r = name_to_handle_at(AT_FDCWD, p, h, &mount_id, AT_SYMLINK_FOLLOW);
+ if (r < 0)
+ return false;
+
+ f = fopen("/proc/self/mountinfo", "re");
+ if (!f)
+ return false;
+
+ for (;;) {
+ char line[LINE_MAX], *e;
+ _cleanup_free_ char *opts = NULL;
+ int mid;
+
+ if (!fgets(line, sizeof(line), f))
+ return false;
+
+ truncate_nl(line);
+
+ if (sscanf(line, "%i", &mid) != 1)
+ continue;
+
+ if (mid != mount_id)
+ continue;
+
+ e = strstr(line, " - ");
+ if (!e)
+ continue;
+
+ if (sscanf(e+3, "%*s %*s %ms", &opts) != 1)
+ continue;
+
+ if (streq(opts, "ssd") || startswith(opts, "ssd,") || endswith(opts, ",ssd") || strstr(opts, ",ssd,"))
+ return true;
+ }
+
+ return false;
+ }
+
+ udev = udev_new();
+ if (!udev)
+ return -ENOMEM;
+
+ udev_device = udev_device_new_from_devnum(udev, 'b', st.st_dev);
+ if (!udev_device)
+ goto finish;
+
+ devtype = udev_device_get_property_value(udev_device, "DEVTYPE");
+ if (devtype && streq(devtype, "partition"))
+ look_at = udev_device_get_parent(udev_device);
+ else
+ look_at = udev_device;
+
+ if (!look_at)
+ goto finish;
+
+ /* First, try high-level property */
+ id = udev_device_get_property_value(look_at, "ID_SSD");
+ if (id) {
+ b = streq(id, "1");
+ goto finish;
+ }
+
+ /* Second, try kernel attribute */
+ rotational = udev_device_get_sysattr_value(look_at, "queue/rotational");
+ if (rotational) {
+ b = streq(rotational, "0");
+ goto finish;
+ }
+
+ /* Finally, fallback to heuristics */
+ look_at = udev_device_get_parent(look_at);
+ if (!look_at)
+ goto finish;
+
+ model = udev_device_get_sysattr_value(look_at, "model");
+ if (model)
+ b = !!strstr(model, "SSD");
+
+finish:
+ if (udev_device)
+ udev_device_unref(udev_device);
+
+ if (udev)
+ udev_unref(udev);
+
+ return b;
+}
+
+int fs_on_read_only(const char *p) {
+ struct stat st;
+ struct udev *udev = NULL;
+ struct udev_device *udev_device = NULL;
+ bool b = false;
+ const char *read_only;
+
+ assert(p);
+
+ if (stat(p, &st) < 0)
+ return -errno;
+
+ if (major(st.st_dev) == 0)
+ return false;
+
+ if (!(udev = udev_new()))
+ return -ENOMEM;
+
+ if (!(udev_device = udev_device_new_from_devnum(udev, 'b', st.st_dev)))
+ goto finish;
+
+ if ((read_only = udev_device_get_sysattr_value(udev_device, "ro")))
+ if ((b = streq(read_only, "1")))
+ goto finish;
+
+finish:
+ if (udev_device)
+ udev_device_unref(udev_device);
+
+ if (udev)
+ udev_unref(udev);
+
+ return b;
+}
+
+bool enough_ram(void) {
+ struct sysinfo si;
+
+ assert_se(sysinfo(&si) >= 0);
+
+ /* Enable readahead only with at least 128MB memory */
+ return si.totalram > 127 * 1024*1024 / si.mem_unit;
+}
+
+static void mkdirs(void) {
+ if (mkdir("/run/systemd", 0755) && errno != EEXIST)
+ log_warning("Failed to create /run/systemd: %m");
+ if (mkdir("/run/systemd/readahead", 0755) && errno != EEXIST)
+ log_warning("Failed to create /run/systemd: %m");
+}
+
+int open_inotify(void) {
+ int fd;
+
+ fd = inotify_init1(IN_CLOEXEC|IN_NONBLOCK);
+ if (fd < 0) {
+ log_error("Failed to create inotify handle: %m");
+ return -errno;
+ }
+
+ mkdirs();
+
+ if (inotify_add_watch(fd, "/run/systemd/readahead", IN_CREATE) < 0) {
+ log_error("Failed to watch /run/systemd/readahead: %m");
+ close_nointr_nofail(fd);
+ return -errno;
+ }
+
+ return fd;
+}
+
+ReadaheadShared *shared_get(void) {
+ int _cleanup_close_ fd = -1;
+ ReadaheadShared *m = NULL;
+
+ mkdirs();
+
+ fd = open("/run/systemd/readahead/shared", O_CREAT|O_RDWR|O_CLOEXEC, 0644);
+ if (fd < 0) {
+ log_error("Failed to create shared memory segment: %m");
+ return NULL;
+ }
+
+ if (ftruncate(fd, sizeof(ReadaheadShared)) < 0) {
+ log_error("Failed to truncate shared memory segment: %m");
+ return NULL;
+ }
+
+ m = mmap(NULL, sizeof(ReadaheadShared), PROT_WRITE|PROT_READ, MAP_SHARED, fd, 0);
+ if (m == MAP_FAILED) {
+ log_error("Failed to mmap shared memory segment: %m");
+ return NULL;
+ }
+
+ return m;
+}
+
+/* We use 20K instead of the more human digestable 16K here. Why?
+ Simply so that it is more unlikely that users end up picking this
+ value too so that we can recognize better whether the user changed
+ the value while we had it temporarily bumped. */
+#define BUMP_REQUEST_NR (20*1024)
+
+int block_bump_request_nr(const char *p) {
+ struct stat st;
+ uint64_t u;
+ char *ap = NULL, *line = NULL;
+ int r;
+ dev_t d;
+
+ assert(p);
+
+ if (stat(p, &st) < 0)
+ return -errno;
+
+ if (major(st.st_dev) == 0)
+ return 0;
+
+ d = st.st_dev;
+ block_get_whole_disk(d, &d);
+
+ if (asprintf(&ap, "/sys/dev/block/%u:%u/queue/nr_requests", major(d), minor(d)) < 0) {
+ r= -ENOMEM;
+ goto finish;
+ }
+
+ r = read_one_line_file(ap, &line);
+ if (r < 0) {
+ if (r == -ENOENT)
+ r = 0;
+ goto finish;
+ }
+
+ r = safe_atou64(line, &u);
+ if (r >= 0 && u >= BUMP_REQUEST_NR) {
+ r = 0;
+ goto finish;
+ }
+
+ free(line);
+ line = NULL;
+
+ if (asprintf(&line, "%lu", (unsigned long) BUMP_REQUEST_NR) < 0) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ r = write_string_file(ap, line);
+ if (r < 0)
+ goto finish;
+
+ log_info("Bumped block_nr parameter of %u:%u to %lu. This is a temporary hack and should be removed one day.", major(d), minor(d), (unsigned long) BUMP_REQUEST_NR);
+ r = 1;
+
+finish:
+ free(ap);
+ free(line);
+
+ return r;
+}
+
+int block_get_readahead(const char *p, uint64_t *bytes) {
+ struct stat st;
+ char *ap = NULL, *line = NULL;
+ int r;
+ dev_t d;
+ uint64_t u;
+
+ assert(p);
+ assert(bytes);
+
+ if (stat(p, &st) < 0)
+ return -errno;
+
+ if (major(st.st_dev) == 0)
+ return 0;
+
+ d = st.st_dev;
+ block_get_whole_disk(d, &d);
+
+ if (asprintf(&ap, "/sys/dev/block/%u:%u/bdi/read_ahead_kb", major(d), minor(d)) < 0) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ r = read_one_line_file(ap, &line);
+ if (r < 0)
+ goto finish;
+
+ r = safe_atou64(line, &u);
+ if (r < 0)
+ goto finish;
+
+ *bytes = u * 1024ULL;
+
+finish:
+ free(ap);
+ free(line);
+
+ return r;
+}
+
+int block_set_readahead(const char *p, uint64_t bytes) {
+ struct stat st;
+ char *ap = NULL, *line = NULL;
+ int r;
+ dev_t d;
+
+ assert(p);
+ assert(bytes);
+
+ if (stat(p, &st) < 0)
+ return -errno;
+
+ if (major(st.st_dev) == 0)
+ return 0;
+
+ d = st.st_dev;
+ block_get_whole_disk(d, &d);
+
+ if (asprintf(&ap, "/sys/dev/block/%u:%u/bdi/read_ahead_kb", major(d), minor(d)) < 0) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ if (asprintf(&line, "%llu", (unsigned long long) bytes / 1024ULL) < 0) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ r = write_string_file(ap, line);
+ if (r < 0)
+ goto finish;
+
+finish:
+ free(ap);
+ free(line);
+
+ return r;
+}
diff --git a/src/readahead/readahead-common.h b/src/readahead/readahead-common.h
new file mode 100644
index 0000000000..b34f3aadd7
--- /dev/null
+++ b/src/readahead/readahead-common.h
@@ -0,0 +1,61 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/stat.h>
+#include <sys/types.h>
+
+#include "macro.h"
+#include "util.h"
+
+#define READAHEAD_FILE_SIZE_MAX (10*1024*1024)
+
+#define READAHEAD_PACK_FILE_VERSION ";VERSION=2\n"
+
+extern unsigned arg_files_max;
+extern off_t arg_file_size_max;
+extern usec_t arg_timeout;
+
+int file_verify(int fd, const char *fn, off_t file_size_max, struct stat *st);
+
+int fs_on_ssd(const char *p);
+int fs_on_read_only(const char *p);
+
+bool enough_ram(void);
+
+int open_inotify(void);
+
+typedef struct ReadaheadShared {
+ pid_t collect;
+ pid_t replay;
+} _packed_ ReadaheadShared;
+
+ReadaheadShared *shared_get(void);
+
+int block_bump_request_nr(const char *p);
+
+int block_get_readahead(const char *p, uint64_t *bytes);
+int block_set_readahead(const char *p, uint64_t bytes);
+
+int main_collect(const char *root);
+int main_replay(const char *root);
+int main_analyze(const char *pack_path);
diff --git a/src/readahead/readahead-replay.c b/src/readahead/readahead-replay.c
new file mode 100644
index 0000000000..cb04e5f9cd
--- /dev/null
+++ b/src/readahead/readahead-replay.c
@@ -0,0 +1,311 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <inttypes.h>
+#include <fcntl.h>
+#include <linux/limits.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/select.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <getopt.h>
+#include <sys/inotify.h>
+
+#include <systemd/sd-daemon.h>
+
+#include "missing.h"
+#include "util.h"
+#include "set.h"
+#include "ioprio.h"
+#include "readahead-common.h"
+#include "virt.h"
+
+static ReadaheadShared *shared = NULL;
+
+static int unpack_file(FILE *pack) {
+ char fn[PATH_MAX];
+ int r = 0, fd = -1;
+ bool any = false;
+ struct stat st;
+ uint64_t inode;
+
+ assert(pack);
+
+ if (!fgets(fn, sizeof(fn), pack))
+ return 0;
+
+ char_array_0(fn);
+ truncate_nl(fn);
+
+ fd = open(fn, O_RDONLY|O_CLOEXEC|O_NOATIME|O_NOCTTY|O_NOFOLLOW);
+ if (fd < 0) {
+
+ if (errno != ENOENT && errno != EPERM && errno != EACCES && errno != ELOOP)
+ log_warning("open(%s) failed: %m", fn);
+
+ } else if (file_verify(fd, fn, arg_file_size_max, &st) <= 0) {
+ close_nointr_nofail(fd);
+ fd = -1;
+ }
+
+ if (fread(&inode, sizeof(inode), 1, pack) != 1) {
+ log_error("Premature end of pack file.");
+ r = -EIO;
+ goto finish;
+ }
+
+ if (fd >= 0) {
+ /* If the inode changed the file got deleted, so just
+ * ignore this entry */
+ if (st.st_ino != (uint64_t) inode) {
+ close_nointr_nofail(fd);
+ fd = -1;
+ }
+ }
+
+ for (;;) {
+ uint32_t b, c;
+
+ if (fread(&b, sizeof(b), 1, pack) != 1 ||
+ fread(&c, sizeof(c), 1, pack) != 1) {
+ log_error("Premature end of pack file.");
+ r = -EIO;
+ goto finish;
+ }
+
+ if (b == 0 && c == 0)
+ break;
+
+ if (c <= b) {
+ log_error("Invalid pack file.");
+ r = -EIO;
+ goto finish;
+ }
+
+ log_debug("%s: page %u to %u", fn, b, c);
+
+ any = true;
+
+ if (fd >= 0)
+ if (posix_fadvise(fd, b * page_size(), (c - b) * page_size(), POSIX_FADV_WILLNEED) < 0) {
+ log_warning("posix_fadvise() failed: %m");
+ goto finish;
+ }
+ }
+
+ if (!any && fd >= 0) {
+ /* if no range is encoded in the pack file this is
+ * intended to mean that the whole file shall be
+ * read */
+
+ if (posix_fadvise(fd, 0, st.st_size, POSIX_FADV_WILLNEED) < 0) {
+ log_warning("posix_fadvise() failed: %m");
+ goto finish;
+ }
+ }
+
+finish:
+ if (fd >= 0)
+ close_nointr_nofail(fd);
+
+ return r;
+}
+
+static int replay(const char *root) {
+ FILE *pack = NULL;
+ char line[LINE_MAX];
+ int r = 0;
+ char *pack_fn = NULL;
+ int c;
+ bool on_ssd, ready = false;
+ int prio;
+ int inotify_fd = -1;
+
+ assert(root);
+
+ block_bump_request_nr(root);
+
+ if (asprintf(&pack_fn, "%s/.readahead", root) < 0) {
+ r = log_oom();
+ goto finish;
+ }
+
+ pack = fopen(pack_fn, "re");
+ if (!pack) {
+ if (errno == ENOENT)
+ log_debug("No pack file found.");
+ else {
+ log_error("Failed to open pack file: %m");
+ r = -errno;
+ }
+
+ goto finish;
+ }
+
+ posix_fadvise(fileno(pack), 0, 0, POSIX_FADV_WILLNEED);
+
+ if ((inotify_fd = open_inotify()) < 0) {
+ r = inotify_fd;
+ goto finish;
+ }
+
+ if (!(fgets(line, sizeof(line), pack))) {
+ log_error("Premature end of pack file.");
+ r = -EIO;
+ goto finish;
+ }
+
+ char_array_0(line);
+
+ if (!streq(line, CANONICAL_HOST READAHEAD_PACK_FILE_VERSION)) {
+ log_debug("Pack file host or version type mismatch.");
+ goto finish;
+ }
+
+ if ((c = getc(pack)) == EOF) {
+ log_debug("Premature end of pack file.");
+ r = -EIO;
+ goto finish;
+ }
+
+ /* We do not retest SSD here, so that we can start replaying
+ * before udev is up.*/
+ on_ssd = c == 'S';
+ log_debug("On SSD: %s", yes_no(on_ssd));
+
+ if (on_ssd)
+ prio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0);
+ else
+ /* We are not using RT here, since we'd starve IO that
+ we didn't record (which is for example blkid, since
+ its disk accesses go directly to the block device and
+ are thus not visible in fallocate) to death. However,
+ we do ask for an IO prio that is slightly higher than
+ the default (which is BE. 4) */
+ prio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 2);
+
+ if (ioprio_set(IOPRIO_WHO_PROCESS, getpid(), prio) < 0)
+ log_warning("Failed to set IDLE IO priority class: %m");
+
+ sd_notify(0, "STATUS=Replaying readahead data");
+
+ log_debug("Replaying...");
+
+ if (access("/run/systemd/readahead/noreplay", F_OK) >= 0) {
+ log_debug("Got termination request");
+ goto done;
+ }
+
+ while (!feof(pack) && !ferror(pack)) {
+ uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
+ int k;
+ ssize_t n;
+
+ if ((n = read(inotify_fd, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
+ if (errno != EINTR && errno != EAGAIN) {
+ log_error("Failed to read inotify event: %m");
+ r = -errno;
+ goto finish;
+ }
+ } else {
+ struct inotify_event *e = (struct inotify_event*) inotify_buffer;
+
+ while (n > 0) {
+ size_t step;
+
+ if ((e->mask & IN_CREATE) && streq(e->name, "noreplay")) {
+ log_debug("Got termination request");
+ goto done;
+ }
+
+ step = sizeof(struct inotify_event) + e->len;
+ assert(step <= (size_t) n);
+
+ e = (struct inotify_event*) ((uint8_t*) e + step);
+ n -= step;
+ }
+ }
+
+ if ((k = unpack_file(pack)) < 0) {
+ r = k;
+ goto finish;
+ }
+
+ if (!ready) {
+ /* We delay the ready notification until we
+ * queued at least one read */
+ sd_notify(0, "READY=1");
+ ready = true;
+ }
+ }
+
+done:
+ if (!ready)
+ sd_notify(0, "READY=1");
+
+ if (ferror(pack)) {
+ log_error("Failed to read pack file.");
+ r = -EIO;
+ goto finish;
+ }
+
+ log_debug("Done.");
+
+finish:
+ if (pack)
+ fclose(pack);
+
+ if (inotify_fd >= 0)
+ close_nointr_nofail(inotify_fd);
+
+ free(pack_fn);
+
+ return r;
+}
+
+int main_replay(const char *root) {
+
+ if (!root)
+ root = "/";
+
+ if (!enough_ram()) {
+ log_info("Disabling readahead replay due to low memory.");
+ return EXIT_SUCCESS;
+ }
+
+ shared = shared_get();
+ if (!shared)
+ return EXIT_FAILURE;
+
+ shared->replay = getpid();
+ __sync_synchronize();
+
+ if (replay(root) < 0)
+ return EXIT_FAILURE;
+
+ return EXIT_SUCCESS;
+}
diff --git a/src/readahead/readahead.c b/src/readahead/readahead.c
new file mode 100644
index 0000000000..29255c9f07
--- /dev/null
+++ b/src/readahead/readahead.c
@@ -0,0 +1,158 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include <getopt.h>
+#include <stddef.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <errno.h>
+#include <string.h>
+
+#include "util.h"
+#include "def.h"
+#include "readahead-common.h"
+
+unsigned arg_files_max = 16*1024;
+off_t arg_file_size_max = READAHEAD_FILE_SIZE_MAX;
+usec_t arg_timeout = 2*USEC_PER_MINUTE;
+
+static int help(void) {
+
+ printf("%s [OPTIONS...] collect [DIRECTORY]\n\n"
+ "Collect read-ahead data on early boot.\n\n"
+ " -h --help Show this help\n"
+ " --max-files=INT Maximum number of files to read ahead\n"
+ " --file-size-max=BYTES Maximum size of files to read ahead\n"
+ " --timeout=USEC Maximum time to spend collecting data\n\n\n",
+ program_invocation_short_name);
+
+ printf("%s [OPTIONS...] replay [DIRECTORY]\n\n"
+ "Replay collected read-ahead data on early boot.\n\n"
+ " -h --help Show this help\n"
+ " --file-size-max=BYTES Maximum size of files to read ahead\n\n\n",
+ program_invocation_short_name);
+
+ printf("%s [OPTIONS...] analyze [PACK FILE]\n\n"
+ "Analyze collected read-ahead data.\n\n"
+ " -h --help Show this help\n",
+ program_invocation_short_name);
+
+ return 0;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+
+ enum {
+ ARG_FILES_MAX = 0x100,
+ ARG_FILE_SIZE_MAX,
+ ARG_TIMEOUT
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "files-max", required_argument, NULL, ARG_FILES_MAX },
+ { "file-size-max", required_argument, NULL, ARG_FILE_SIZE_MAX },
+ { "timeout", required_argument, NULL, ARG_TIMEOUT },
+ { NULL, 0, NULL, 0 }
+ };
+
+ int c;
+
+ assert(argc >= 0);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
+
+ switch (c) {
+
+ case 'h':
+ help();
+ return 0;
+
+ case ARG_FILES_MAX:
+ if (safe_atou(optarg, &arg_files_max) < 0 || arg_files_max <= 0) {
+ log_error("Failed to parse maximum number of files %s.", optarg);
+ return -EINVAL;
+ }
+ break;
+
+ case ARG_FILE_SIZE_MAX: {
+ unsigned long long ull;
+
+ if (safe_atollu(optarg, &ull) < 0 || ull <= 0) {
+ log_error("Failed to parse maximum file size %s.", optarg);
+ return -EINVAL;
+ }
+
+ arg_file_size_max = (off_t) ull;
+ break;
+ }
+
+ case ARG_TIMEOUT:
+ if (parse_sec(optarg, &arg_timeout) < 0 || arg_timeout <= 0) {
+ log_error("Failed to parse timeout %s.", optarg);
+ return -EINVAL;
+ }
+
+ break;
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ log_error("Unknown option code %c", c);
+ return -EINVAL;
+ }
+ }
+
+ if (optind != argc-1 &&
+ optind != argc-2) {
+ help();
+ return -EINVAL;
+ }
+
+ return 1;
+}
+
+int main(int argc, char *argv[]) {
+ int r;
+
+ log_set_target(LOG_TARGET_SAFE);
+ log_parse_environment();
+ log_open();
+
+ umask(0022);
+
+ r = parse_argv(argc, argv);
+ if (r <= 0)
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+
+ if (streq(argv[optind], "collect"))
+ return main_collect(argv[optind+1]);
+ else if (streq(argv[optind], "replay"))
+ return main_replay(argv[optind+1]);
+ else if (streq(argv[optind], "analyze"))
+ return main_analyze(argv[optind+1]);
+
+ log_error("Unknown verb %s.", argv[optind]);
+ return EXIT_FAILURE;
+}
diff --git a/src/readahead/sd-readahead.c b/src/readahead/sd-readahead.c
new file mode 100644
index 0000000000..675d82cdd1
--- /dev/null
+++ b/src/readahead/sd-readahead.c
@@ -0,0 +1,89 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ Copyright 2010 Lennart Poettering
+
+ Permission is hereby granted, free of charge, to any person
+ obtaining a copy of this software and associated documentation files
+ (the "Software"), to deal in the Software without restriction,
+ including without limitation the rights to use, copy, modify, merge,
+ publish, distribute, sublicense, and/or sell copies of the Software,
+ and to permit persons to whom the Software is furnished to do so,
+ subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+***/
+
+#ifndef _GNU_SOURCE
+# define _GNU_SOURCE
+#endif
+
+#include <unistd.h>
+#include <errno.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <fcntl.h>
+#include <string.h>
+
+#include "sd-readahead.h"
+
+#if (__GNUC__ >= 4)
+# ifdef SD_EXPORT_SYMBOLS
+/* Export symbols */
+# define _sd_export_ __attribute__ ((visibility("default")))
+# else
+/* Don't export the symbols */
+# define _sd_export_ __attribute__ ((visibility("hidden")))
+# endif
+#else
+# define _sd_export_
+#endif
+
+static int touch(const char *path) {
+
+#if !defined(DISABLE_SYSTEMD) && defined(__linux__)
+ int fd;
+
+ mkdir("/run/systemd", 0755);
+ mkdir("/run/systemd/readahead", 0755);
+
+ fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0666);
+ if (fd < 0)
+ return -errno;
+
+ for (;;) {
+ if (close(fd) >= 0)
+ break;
+
+ if (errno != EINTR)
+ return -errno;
+ }
+
+#endif
+ return 0;
+}
+
+_sd_export_ int sd_readahead(const char *action) {
+
+ if (!action)
+ return -EINVAL;
+
+ if (strcmp(action, "cancel") == 0)
+ return touch("/run/systemd/readahead/cancel");
+ else if (strcmp(action, "done") == 0)
+ return touch("/run/systemd/readahead/done");
+ else if (strcmp(action, "noreplay") == 0)
+ return touch("/run/systemd/readahead/noreplay");
+
+ return -EINVAL;
+}
diff --git a/src/remount-fs/remount-fs.c b/src/remount-fs/remount-fs.c
new file mode 100644
index 0000000000..f432718d6b
--- /dev/null
+++ b/src/remount-fs/remount-fs.c
@@ -0,0 +1,169 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <unistd.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/wait.h>
+#include <mntent.h>
+
+#include "log.h"
+#include "util.h"
+#include "path-util.h"
+#include "set.h"
+#include "mount-setup.h"
+#include "exit-status.h"
+
+/* Goes through /etc/fstab and remounts all API file systems, applying
+ * options that are in /etc/fstab that systemd might not have
+ * respected */
+
+int main(int argc, char *argv[]) {
+ int ret = EXIT_FAILURE;
+ FILE *f = NULL;
+ struct mntent* me;
+ Hashmap *pids = NULL;
+
+ if (argc > 1) {
+ log_error("This program takes no argument.");
+ return EXIT_FAILURE;
+ }
+
+ log_set_target(LOG_TARGET_AUTO);
+ log_parse_environment();
+ log_open();
+
+ umask(0022);
+
+ f = setmntent("/etc/fstab", "r");
+ if (!f) {
+ if (errno == ENOENT) {
+ ret = EXIT_SUCCESS;
+ goto finish;
+ }
+
+ log_error("Failed to open /etc/fstab: %m");
+ goto finish;
+ }
+
+ pids = hashmap_new(trivial_hash_func, trivial_compare_func);
+ if (!pids) {
+ log_error("Failed to allocate set");
+ goto finish;
+ }
+
+ ret = EXIT_SUCCESS;
+
+ while ((me = getmntent(f))) {
+ pid_t pid;
+ int k;
+ char *s;
+
+ /* Remount the root fs, /usr and all API VFS */
+ if (!mount_point_is_api(me->mnt_dir) &&
+ !path_equal(me->mnt_dir, "/") &&
+ !path_equal(me->mnt_dir, "/usr"))
+ continue;
+
+ log_debug("Remounting %s", me->mnt_dir);
+
+ pid = fork();
+ if (pid < 0) {
+ log_error("Failed to fork: %m");
+ ret = EXIT_FAILURE;
+ continue;
+ }
+
+ if (pid == 0) {
+ const char *arguments[5];
+ /* Child */
+
+ arguments[0] = "/bin/mount";
+ arguments[1] = me->mnt_dir;
+ arguments[2] = "-o";
+ arguments[3] = "remount";
+ arguments[4] = NULL;
+
+ execv("/bin/mount", (char **) arguments);
+
+ log_error("Failed to execute /bin/mount: %m");
+ _exit(EXIT_FAILURE);
+ }
+
+ /* Parent */
+
+ s = strdup(me->mnt_dir);
+ if (!s) {
+ log_oom();
+ ret = EXIT_FAILURE;
+ continue;
+ }
+
+
+ k = hashmap_put(pids, UINT_TO_PTR(pid), s);
+ if (k < 0) {
+ log_error("Failed to add PID to set: %s", strerror(-k));
+ ret = EXIT_FAILURE;
+ continue;
+ }
+ }
+
+ while (!hashmap_isempty(pids)) {
+ siginfo_t si = {};
+ char *s;
+
+ if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
+
+ if (errno == EINTR)
+ continue;
+
+ log_error("waitid() failed: %m");
+ ret = EXIT_FAILURE;
+ break;
+ }
+
+ s = hashmap_remove(pids, UINT_TO_PTR(si.si_pid));
+ if (s) {
+ if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
+ if (si.si_code == CLD_EXITED)
+ log_error("/bin/mount for %s exited with exit status %i.", s, si.si_status);
+ else
+ log_error("/bin/mount for %s terminated by signal %s.", s, signal_to_string(si.si_status));
+
+ ret = EXIT_FAILURE;
+ }
+
+ free(s);
+ }
+ }
+
+finish:
+
+ if (pids)
+ hashmap_free_free(pids);
+
+ if (f)
+ endmntent(f);
+
+ return ret;
+}
diff --git a/src/reply-password/reply-password.c b/src/reply-password/reply-password.c
new file mode 100644
index 0000000000..2f168985b4
--- /dev/null
+++ b/src/reply-password/reply-password.c
@@ -0,0 +1,109 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/socket.h>
+#include <sys/poll.h>
+#include <sys/types.h>
+#include <assert.h>
+#include <string.h>
+#include <errno.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/un.h>
+#include <sys/stat.h>
+#include <sys/signalfd.h>
+#include <getopt.h>
+#include <stddef.h>
+
+#include "log.h"
+#include "macro.h"
+#include "util.h"
+
+static int send_on_socket(int fd, const char *socket_name, const void *packet, size_t size) {
+ union {
+ struct sockaddr sa;
+ struct sockaddr_un un;
+ } sa = {
+ .un.sun_family = AF_UNIX,
+ };
+
+ assert(fd >= 0);
+ assert(socket_name);
+ assert(packet);
+
+ strncpy(sa.un.sun_path, socket_name, sizeof(sa.un.sun_path));
+
+ if (sendto(fd, packet, size, MSG_NOSIGNAL, &sa.sa, offsetof(struct sockaddr_un, sun_path) + strlen(socket_name)) < 0) {
+ log_error("Failed to send: %m");
+ return -1;
+ }
+
+ return 0;
+}
+
+int main(int argc, char *argv[]) {
+ int fd = -1, r = EXIT_FAILURE;
+ char packet[LINE_MAX];
+ size_t length;
+
+ log_set_target(LOG_TARGET_AUTO);
+ log_parse_environment();
+ log_open();
+
+ if (argc != 3) {
+ log_error("Wrong number of arguments.");
+ goto finish;
+ }
+
+ if (streq(argv[1], "1")) {
+
+ packet[0] = '+';
+ if (!fgets(packet+1, sizeof(packet)-1, stdin)) {
+ log_error("Failed to read password: %m");
+ goto finish;
+ }
+
+ truncate_nl(packet+1);
+ length = 1 + strlen(packet+1) + 1;
+ } else if (streq(argv[1], "0")) {
+ packet[0] = '-';
+ length = 1;
+ } else {
+ log_error("Invalid first argument %s", argv[1]);
+ goto finish;
+ }
+
+ if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0)) < 0) {
+ log_error("socket() failed: %m");
+ goto finish;
+ }
+
+ if (send_on_socket(fd, argv[2], packet, length) < 0)
+ goto finish;
+
+ r = EXIT_SUCCESS;
+
+finish:
+ if (fd >= 0)
+ close_nointr_nofail(fd);
+
+ return r;
+}
diff --git a/src/shared/MurmurHash3.c b/src/shared/MurmurHash3.c
new file mode 100644
index 0000000000..aa1387373f
--- /dev/null
+++ b/src/shared/MurmurHash3.c
@@ -0,0 +1,349 @@
+//-----------------------------------------------------------------------------
+// MurmurHash3 was written by Austin Appleby, and is placed in the public
+// domain. The author hereby disclaims copyright to this source code.
+
+// Note - The x86 and x64 versions do _not_ produce the same results, as the
+// algorithms are optimized for their respective platforms. You can still
+// compile and run any of them on any platform, but your performance with the
+// non-native version will be less than optimal.
+
+#include "MurmurHash3.h"
+
+//-----------------------------------------------------------------------------
+// Platform-specific functions and macros
+
+// Microsoft Visual Studio
+
+#if defined(_MSC_VER)
+
+#define FORCE_INLINE __forceinline
+
+#include <stdlib.h>
+
+#define ROTL32(x,y) _rotl(x,y)
+#define ROTL64(x,y) _rotl64(x,y)
+
+#define BIG_CONSTANT(x) (x)
+
+// Other compilers
+
+#else // defined(_MSC_VER)
+
+#define FORCE_INLINE inline __attribute__((always_inline))
+
+static inline uint32_t rotl32 ( uint32_t x, int8_t r )
+{
+ return (x << r) | (x >> (32 - r));
+}
+
+static inline uint64_t rotl64 ( uint64_t x, int8_t r )
+{
+ return (x << r) | (x >> (64 - r));
+}
+
+#define ROTL32(x,y) rotl32(x,y)
+#define ROTL64(x,y) rotl64(x,y)
+
+#define BIG_CONSTANT(x) (x##LLU)
+
+#endif // !defined(_MSC_VER)
+
+//-----------------------------------------------------------------------------
+// Block read - if your platform needs to do endian-swapping or can only
+// handle aligned reads, do the conversion here
+
+static FORCE_INLINE uint32_t getblock32 ( const uint32_t * p, int i )
+{
+ return p[i];
+}
+
+static FORCE_INLINE uint64_t getblock64 ( const uint64_t * p, int i )
+{
+ return p[i];
+}
+
+//-----------------------------------------------------------------------------
+// Finalization mix - force all bits of a hash block to avalanche
+
+static FORCE_INLINE uint32_t fmix32 ( uint32_t h )
+{
+ h ^= h >> 16;
+ h *= 0x85ebca6b;
+ h ^= h >> 13;
+ h *= 0xc2b2ae35;
+ h ^= h >> 16;
+
+ return h;
+}
+
+//----------
+
+static FORCE_INLINE uint64_t fmix64 ( uint64_t k )
+{
+ k ^= k >> 33;
+ k *= BIG_CONSTANT(0xff51afd7ed558ccd);
+ k ^= k >> 33;
+ k *= BIG_CONSTANT(0xc4ceb9fe1a85ec53);
+ k ^= k >> 33;
+
+ return k;
+}
+
+//-----------------------------------------------------------------------------
+
+void MurmurHash3_x86_32 ( const void * key, size_t len,
+ uint32_t seed, void * out )
+{
+ const uint8_t * data = (const uint8_t*)key;
+ const int nblocks = len / 4;
+
+ uint32_t h1 = seed;
+
+ const uint32_t c1 = 0xcc9e2d51;
+ const uint32_t c2 = 0x1b873593;
+
+ const uint8_t * tail;
+ uint32_t k1;
+
+ //----------
+ // body
+
+ const uint32_t * blocks = (const uint32_t *)(data + nblocks*4);
+
+ for(int i = -nblocks; i; i++)
+ {
+ k1 = getblock32(blocks,i);
+
+ k1 *= c1;
+ k1 = ROTL32(k1,15);
+ k1 *= c2;
+
+ h1 ^= k1;
+ h1 = ROTL32(h1,13);
+ h1 = h1*5+0xe6546b64;
+ }
+
+ //----------
+ // tail
+
+ tail = (const uint8_t*)(data + nblocks*4);
+
+ k1 = 0;
+
+ switch(len & 3)
+ {
+ case 3: k1 ^= tail[2] << 16;
+ case 2: k1 ^= tail[1] << 8;
+ case 1: k1 ^= tail[0];
+ k1 *= c1; k1 = ROTL32(k1,15); k1 *= c2; h1 ^= k1;
+ };
+
+ //----------
+ // finalization
+
+ h1 ^= len;
+
+ h1 = fmix32(h1);
+
+ *(uint32_t*)out = h1;
+}
+
+//-----------------------------------------------------------------------------
+
+void MurmurHash3_x86_128 ( const void * key, const size_t len,
+ uint32_t seed, void * out )
+{
+ const uint8_t * data = (const uint8_t*)key;
+ const int nblocks = len / 16;
+
+ uint32_t h1 = seed;
+ uint32_t h2 = seed;
+ uint32_t h3 = seed;
+ uint32_t h4 = seed;
+
+ const uint32_t c1 = 0x239b961b;
+ const uint32_t c2 = 0xab0e9789;
+ const uint32_t c3 = 0x38b34ae5;
+ const uint32_t c4 = 0xa1e38b93;
+
+ const uint8_t * tail;
+
+ uint32_t k1;
+ uint32_t k2;
+ uint32_t k3;
+ uint32_t k4;
+
+ //----------
+ // body
+
+ const uint32_t * blocks = (const uint32_t *)(data + nblocks*16);
+
+ for(int i = -nblocks; i; i++)
+ {
+ k1 = getblock32(blocks,i*4+0);
+ k2 = getblock32(blocks,i*4+1);
+ k3 = getblock32(blocks,i*4+2);
+ k4 = getblock32(blocks,i*4+3);
+
+ k1 *= c1; k1 = ROTL32(k1,15); k1 *= c2; h1 ^= k1;
+
+ h1 = ROTL32(h1,19); h1 += h2; h1 = h1*5+0x561ccd1b;
+
+ k2 *= c2; k2 = ROTL32(k2,16); k2 *= c3; h2 ^= k2;
+
+ h2 = ROTL32(h2,17); h2 += h3; h2 = h2*5+0x0bcaa747;
+
+ k3 *= c3; k3 = ROTL32(k3,17); k3 *= c4; h3 ^= k3;
+
+ h3 = ROTL32(h3,15); h3 += h4; h3 = h3*5+0x96cd1c35;
+
+ k4 *= c4; k4 = ROTL32(k4,18); k4 *= c1; h4 ^= k4;
+
+ h4 = ROTL32(h4,13); h4 += h1; h4 = h4*5+0x32ac3b17;
+ }
+
+ //----------
+ // tail
+
+ tail = (const uint8_t*)(data + nblocks*16);
+
+ k1 = 0;
+ k2 = 0;
+ k3 = 0;
+ k4 = 0;
+
+ switch(len & 15)
+ {
+ case 15: k4 ^= tail[14] << 16;
+ case 14: k4 ^= tail[13] << 8;
+ case 13: k4 ^= tail[12] << 0;
+ k4 *= c4; k4 = ROTL32(k4,18); k4 *= c1; h4 ^= k4;
+
+ case 12: k3 ^= tail[11] << 24;
+ case 11: k3 ^= tail[10] << 16;
+ case 10: k3 ^= tail[ 9] << 8;
+ case 9: k3 ^= tail[ 8] << 0;
+ k3 *= c3; k3 = ROTL32(k3,17); k3 *= c4; h3 ^= k3;
+
+ case 8: k2 ^= tail[ 7] << 24;
+ case 7: k2 ^= tail[ 6] << 16;
+ case 6: k2 ^= tail[ 5] << 8;
+ case 5: k2 ^= tail[ 4] << 0;
+ k2 *= c2; k2 = ROTL32(k2,16); k2 *= c3; h2 ^= k2;
+
+ case 4: k1 ^= tail[ 3] << 24;
+ case 3: k1 ^= tail[ 2] << 16;
+ case 2: k1 ^= tail[ 1] << 8;
+ case 1: k1 ^= tail[ 0] << 0;
+ k1 *= c1; k1 = ROTL32(k1,15); k1 *= c2; h1 ^= k1;
+ };
+
+ //----------
+ // finalization
+
+ h1 ^= len; h2 ^= len; h3 ^= len; h4 ^= len;
+
+ h1 += h2; h1 += h3; h1 += h4;
+ h2 += h1; h3 += h1; h4 += h1;
+
+ h1 = fmix32(h1);
+ h2 = fmix32(h2);
+ h3 = fmix32(h3);
+ h4 = fmix32(h4);
+
+ h1 += h2; h1 += h3; h1 += h4;
+ h2 += h1; h3 += h1; h4 += h1;
+
+ ((uint32_t*)out)[0] = h1;
+ ((uint32_t*)out)[1] = h2;
+ ((uint32_t*)out)[2] = h3;
+ ((uint32_t*)out)[3] = h4;
+}
+
+//-----------------------------------------------------------------------------
+
+void MurmurHash3_x64_128 ( const void * key, const size_t len,
+ const uint32_t seed, void * out )
+{
+ const uint8_t * data = (const uint8_t*)key;
+ const int nblocks = len / 16;
+
+ uint64_t h1 = seed;
+ uint64_t h2 = seed;
+
+ const uint64_t c1 = BIG_CONSTANT(0x87c37b91114253d5);
+ const uint64_t c2 = BIG_CONSTANT(0x4cf5ad432745937f);
+
+ const uint8_t *tail;
+
+ uint64_t k1;
+ uint64_t k2;
+
+ //----------
+ // body
+
+ const uint64_t * blocks = (const uint64_t *)(data);
+
+ for(int i = 0; i < nblocks; i++)
+ {
+ k1 = getblock64(blocks,i*2+0);
+ k2 = getblock64(blocks,i*2+1);
+
+ k1 *= c1; k1 = ROTL64(k1,31); k1 *= c2; h1 ^= k1;
+
+ h1 = ROTL64(h1,27); h1 += h2; h1 = h1*5+0x52dce729;
+
+ k2 *= c2; k2 = ROTL64(k2,33); k2 *= c1; h2 ^= k2;
+
+ h2 = ROTL64(h2,31); h2 += h1; h2 = h2*5+0x38495ab5;
+ }
+
+ //----------
+ // tail
+
+ tail = (const uint8_t*)(data + nblocks*16);
+
+ k1 = 0;
+ k2 = 0;
+
+ switch(len & 15)
+ {
+ case 15: k2 ^= (uint64_t)(tail[14]) << 48;
+ case 14: k2 ^= (uint64_t)(tail[13]) << 40;
+ case 13: k2 ^= (uint64_t)(tail[12]) << 32;
+ case 12: k2 ^= (uint64_t)(tail[11]) << 24;
+ case 11: k2 ^= (uint64_t)(tail[10]) << 16;
+ case 10: k2 ^= (uint64_t)(tail[ 9]) << 8;
+ case 9: k2 ^= (uint64_t)(tail[ 8]) << 0;
+ k2 *= c2; k2 = ROTL64(k2,33); k2 *= c1; h2 ^= k2;
+
+ case 8: k1 ^= (uint64_t)(tail[ 7]) << 56;
+ case 7: k1 ^= (uint64_t)(tail[ 6]) << 48;
+ case 6: k1 ^= (uint64_t)(tail[ 5]) << 40;
+ case 5: k1 ^= (uint64_t)(tail[ 4]) << 32;
+ case 4: k1 ^= (uint64_t)(tail[ 3]) << 24;
+ case 3: k1 ^= (uint64_t)(tail[ 2]) << 16;
+ case 2: k1 ^= (uint64_t)(tail[ 1]) << 8;
+ case 1: k1 ^= (uint64_t)(tail[ 0]) << 0;
+ k1 *= c1; k1 = ROTL64(k1,31); k1 *= c2; h1 ^= k1;
+ };
+
+ //----------
+ // finalization
+
+ h1 ^= len; h2 ^= len;
+
+ h1 += h2;
+ h2 += h1;
+
+ h1 = fmix64(h1);
+ h2 = fmix64(h2);
+
+ h1 += h2;
+ h2 += h1;
+
+ ((uint64_t*)out)[0] = h1;
+ ((uint64_t*)out)[1] = h2;
+}
+
+//-----------------------------------------------------------------------------
diff --git a/src/shared/MurmurHash3.h b/src/shared/MurmurHash3.h
new file mode 100644
index 0000000000..07c474eba4
--- /dev/null
+++ b/src/shared/MurmurHash3.h
@@ -0,0 +1,38 @@
+//-----------------------------------------------------------------------------
+// MurmurHash3 was written by Austin Appleby, and is placed in the public
+// domain. The author hereby disclaims copyright to this source code.
+
+#ifndef _MURMURHASH3_H_
+#define _MURMURHASH3_H_
+
+//-----------------------------------------------------------------------------
+// Platform-specific functions and macros
+
+// Microsoft Visual Studio
+
+#if defined(_MSC_VER)
+
+typedef unsigned char uint8_t;
+typedef unsigned long uint32_t;
+typedef unsigned __int64 uint64_t;
+
+// Other compilers
+
+#else // defined(_MSC_VER)
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#endif // !defined(_MSC_VER)
+
+//-----------------------------------------------------------------------------
+
+void MurmurHash3_x86_32 ( const void * key, size_t len, uint32_t seed, void * out );
+
+void MurmurHash3_x86_128 ( const void * key, size_t len, uint32_t seed, void * out );
+
+void MurmurHash3_x64_128 ( const void * key, size_t len, uint32_t seed, void * out );
+
+//-----------------------------------------------------------------------------
+
+#endif // _MURMURHASH3_H_
diff --git a/src/shared/acl-util.c b/src/shared/acl-util.c
new file mode 100644
index 0000000000..48bb12f46b
--- /dev/null
+++ b/src/shared/acl-util.c
@@ -0,0 +1,126 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011,2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <sys/acl.h>
+#include <acl/libacl.h>
+#include <errno.h>
+#include <stdbool.h>
+
+#include "acl-util.h"
+#include "util.h"
+#include "strv.h"
+
+int acl_find_uid(acl_t acl, uid_t uid, acl_entry_t *entry) {
+ acl_entry_t i;
+ int found;
+
+ assert(acl);
+ assert(entry);
+
+ for (found = acl_get_entry(acl, ACL_FIRST_ENTRY, &i);
+ found > 0;
+ found = acl_get_entry(acl, ACL_NEXT_ENTRY, &i)) {
+
+ acl_tag_t tag;
+ uid_t *u;
+ bool b;
+
+ if (acl_get_tag_type(i, &tag) < 0)
+ return -errno;
+
+ if (tag != ACL_USER)
+ continue;
+
+ u = acl_get_qualifier(i);
+ if (!u)
+ return -errno;
+
+ b = *u == uid;
+ acl_free(u);
+
+ if (b) {
+ *entry = i;
+ return 1;
+ }
+ }
+
+ if (found < 0)
+ return -errno;
+
+ return 0;
+}
+
+int search_acl_groups(char*** dst, const char* path, bool* belong) {
+ acl_t acl;
+
+ assert(path);
+ assert(belong);
+
+ acl = acl_get_file(path, ACL_TYPE_DEFAULT);
+ if (acl) {
+ acl_entry_t entry;
+ int r;
+
+ r = acl_get_entry(acl, ACL_FIRST_ENTRY, &entry);
+ while (r > 0) {
+ acl_tag_t tag;
+ gid_t *gid;
+ char *name;
+
+ r = acl_get_tag_type(entry, &tag);
+ if (r < 0)
+ break;
+
+ if (tag != ACL_GROUP)
+ goto next;
+
+ gid = acl_get_qualifier(entry);
+ if (!gid)
+ break;
+
+ if (in_gid(*gid) > 0) {
+ *belong = true;
+ break;
+ }
+
+ name = gid_to_name(*gid);
+ if (!name) {
+ acl_free(acl);
+ return log_oom();
+ }
+
+ r = strv_push(dst, name);
+ if (r < 0) {
+ free(name);
+ acl_free(acl);
+ return log_oom();
+ }
+
+ next:
+ r = acl_get_entry(acl, ACL_NEXT_ENTRY, &entry);
+ }
+
+ acl_free(acl);
+ }
+
+ return 0;
+}
diff --git a/src/shared/acl-util.h b/src/shared/acl-util.h
new file mode 100644
index 0000000000..23090d9984
--- /dev/null
+++ b/src/shared/acl-util.h
@@ -0,0 +1,27 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdbool.h>
+
+int acl_find_uid(acl_t acl, uid_t uid, acl_entry_t *entry);
+int search_acl_groups(char*** dst, const char* path, bool* belong);
diff --git a/src/shared/ask-password-api.c b/src/shared/ask-password-api.c
new file mode 100644
index 0000000000..4557155d45
--- /dev/null
+++ b/src/shared/ask-password-api.c
@@ -0,0 +1,575 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+#include <stdbool.h>
+#include <termios.h>
+#include <unistd.h>
+#include <sys/poll.h>
+#include <sys/inotify.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <sys/socket.h>
+#include <string.h>
+#include <sys/un.h>
+#include <stddef.h>
+#include <sys/signalfd.h>
+
+#include "util.h"
+#include "mkdir.h"
+#include "strv.h"
+
+#include "ask-password-api.h"
+
+static void backspace_chars(int ttyfd, size_t p) {
+
+ if (ttyfd < 0)
+ return;
+
+ while (p > 0) {
+ p--;
+
+ loop_write(ttyfd, "\b \b", 3, false);
+ }
+}
+
+int ask_password_tty(
+ const char *message,
+ usec_t until,
+ const char *flag_file,
+ char **_passphrase) {
+
+ struct termios old_termios, new_termios;
+ char passphrase[LINE_MAX];
+ size_t p = 0;
+ int r, ttyfd = -1, notify = -1;
+ struct pollfd pollfd[2];
+ bool reset_tty = false;
+ bool silent_mode = false;
+ bool dirty = false;
+ enum {
+ POLL_TTY,
+ POLL_INOTIFY
+ };
+
+ assert(message);
+ assert(_passphrase);
+
+ if (flag_file) {
+ if ((notify = inotify_init1(IN_CLOEXEC|IN_NONBLOCK)) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ if (inotify_add_watch(notify, flag_file, IN_ATTRIB /* for the link count */) < 0) {
+ r = -errno;
+ goto finish;
+ }
+ }
+
+ if ((ttyfd = open("/dev/tty", O_RDWR|O_NOCTTY|O_CLOEXEC)) >= 0) {
+
+ if (tcgetattr(ttyfd, &old_termios) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ loop_write(ttyfd, ANSI_HIGHLIGHT_ON, sizeof(ANSI_HIGHLIGHT_ON)-1, false);
+ loop_write(ttyfd, message, strlen(message), false);
+ loop_write(ttyfd, " ", 1, false);
+ loop_write(ttyfd, ANSI_HIGHLIGHT_OFF, sizeof(ANSI_HIGHLIGHT_OFF)-1, false);
+
+ new_termios = old_termios;
+ new_termios.c_lflag &= ~(ICANON|ECHO);
+ new_termios.c_cc[VMIN] = 1;
+ new_termios.c_cc[VTIME] = 0;
+
+ if (tcsetattr(ttyfd, TCSADRAIN, &new_termios) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ reset_tty = true;
+ }
+
+ zero(pollfd);
+ pollfd[POLL_TTY].fd = ttyfd >= 0 ? ttyfd : STDIN_FILENO;
+ pollfd[POLL_TTY].events = POLLIN;
+ pollfd[POLL_INOTIFY].fd = notify;
+ pollfd[POLL_INOTIFY].events = POLLIN;
+
+ for (;;) {
+ char c;
+ int sleep_for = -1, k;
+ ssize_t n;
+
+ if (until > 0) {
+ usec_t y;
+
+ y = now(CLOCK_MONOTONIC);
+
+ if (y > until) {
+ r = -ETIME;
+ goto finish;
+ }
+
+ sleep_for = (int) ((until - y) / USEC_PER_MSEC);
+ }
+
+ if (flag_file)
+ if (access(flag_file, F_OK) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ if ((k = poll(pollfd, notify > 0 ? 2 : 1, sleep_for)) < 0) {
+
+ if (errno == EINTR)
+ continue;
+
+ r = -errno;
+ goto finish;
+ } else if (k == 0) {
+ r = -ETIME;
+ goto finish;
+ }
+
+ if (notify > 0 && pollfd[POLL_INOTIFY].revents != 0)
+ flush_fd(notify);
+
+ if (pollfd[POLL_TTY].revents == 0)
+ continue;
+
+ if ((n = read(ttyfd >= 0 ? ttyfd : STDIN_FILENO, &c, 1)) < 0) {
+
+ if (errno == EINTR || errno == EAGAIN)
+ continue;
+
+ r = -errno;
+ goto finish;
+
+ } else if (n == 0)
+ break;
+
+ if (c == '\n')
+ break;
+ else if (c == 21) { /* C-u */
+
+ if (!silent_mode)
+ backspace_chars(ttyfd, p);
+ p = 0;
+
+ } else if (c == '\b' || c == 127) {
+
+ if (p > 0) {
+
+ if (!silent_mode)
+ backspace_chars(ttyfd, 1);
+
+ p--;
+ } else if (!dirty && !silent_mode) {
+
+ silent_mode = true;
+
+ /* There are two ways to enter silent
+ * mode. Either by pressing backspace
+ * as first key (and only as first key),
+ * or ... */
+ if (ttyfd >= 0)
+ loop_write(ttyfd, "(no echo) ", 10, false);
+
+ } else if (ttyfd >= 0)
+ loop_write(ttyfd, "\a", 1, false);
+
+ } else if (c == '\t' && !silent_mode) {
+
+ backspace_chars(ttyfd, p);
+ silent_mode = true;
+
+ /* ... or by pressing TAB at any time. */
+
+ if (ttyfd >= 0)
+ loop_write(ttyfd, "(no echo) ", 10, false);
+ } else {
+ passphrase[p++] = c;
+
+ if (!silent_mode && ttyfd >= 0)
+ loop_write(ttyfd, "*", 1, false);
+
+ dirty = true;
+ }
+ }
+
+ passphrase[p] = 0;
+
+ if (!(*_passphrase = strdup(passphrase))) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ r = 0;
+
+finish:
+ if (notify >= 0)
+ close_nointr_nofail(notify);
+
+ if (ttyfd >= 0) {
+
+ if (reset_tty) {
+ loop_write(ttyfd, "\n", 1, false);
+ tcsetattr(ttyfd, TCSADRAIN, &old_termios);
+ }
+
+ close_nointr_nofail(ttyfd);
+ }
+
+ return r;
+}
+
+static int create_socket(char **name) {
+ int fd;
+ union {
+ struct sockaddr sa;
+ struct sockaddr_un un;
+ } sa = {
+ .un.sun_family = AF_UNIX,
+ };
+ int one = 1, r;
+ char *c;
+
+ assert(name);
+
+ fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
+ if (fd < 0) {
+ log_error("socket() failed: %m");
+ return -errno;
+ }
+
+ snprintf(sa.un.sun_path, sizeof(sa.un.sun_path)-1, "/run/systemd/ask-password/sck.%llu", random_ull());
+
+ RUN_WITH_UMASK(0177) {
+ r = bind(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + strlen(sa.un.sun_path));
+ }
+
+ if (r < 0) {
+ r = -errno;
+ log_error("bind() failed: %m");
+ goto fail;
+ }
+
+ if (setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one)) < 0) {
+ r = -errno;
+ log_error("SO_PASSCRED failed: %m");
+ goto fail;
+ }
+
+ c = strdup(sa.un.sun_path);
+ if (!c) {
+ r = log_oom();
+ goto fail;
+ }
+
+ *name = c;
+ return fd;
+
+fail:
+ close_nointr_nofail(fd);
+
+ return r;
+}
+
+int ask_password_agent(
+ const char *message,
+ const char *icon,
+ usec_t until,
+ bool accept_cached,
+ char ***_passphrases) {
+
+ enum {
+ FD_SOCKET,
+ FD_SIGNAL,
+ _FD_MAX
+ };
+
+ char temp[] = "/run/systemd/ask-password/tmp.XXXXXX";
+ char final[sizeof(temp)] = "";
+ int fd = -1, r;
+ FILE *f = NULL;
+ char *socket_name = NULL;
+ int socket_fd = -1, signal_fd = -1;
+ sigset_t mask, oldmask;
+ struct pollfd pollfd[_FD_MAX];
+
+ assert(_passphrases);
+
+ assert_se(sigemptyset(&mask) == 0);
+ sigset_add_many(&mask, SIGINT, SIGTERM, -1);
+ assert_se(sigprocmask(SIG_BLOCK, &mask, &oldmask) == 0);
+
+ mkdir_p_label("/run/systemd/ask-password", 0755);
+
+ RUN_WITH_UMASK(0022) {
+ fd = mkostemp(temp, O_CLOEXEC|O_CREAT|O_WRONLY);
+ }
+
+ if (fd < 0) {
+ log_error("Failed to create password file: %m");
+ r = -errno;
+ goto finish;
+ }
+
+ fchmod(fd, 0644);
+
+ if (!(f = fdopen(fd, "w"))) {
+ log_error("Failed to allocate FILE: %m");
+ r = -errno;
+ goto finish;
+ }
+
+ fd = -1;
+
+ if ((signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0) {
+ log_error("signalfd(): %m");
+ r = -errno;
+ goto finish;
+ }
+
+ if ((socket_fd = create_socket(&socket_name)) < 0) {
+ r = socket_fd;
+ goto finish;
+ }
+
+ fprintf(f,
+ "[Ask]\n"
+ "PID=%lu\n"
+ "Socket=%s\n"
+ "AcceptCached=%i\n"
+ "NotAfter=%llu\n",
+ (unsigned long) getpid(),
+ socket_name,
+ accept_cached ? 1 : 0,
+ (unsigned long long) until);
+
+ if (message)
+ fprintf(f, "Message=%s\n", message);
+
+ if (icon)
+ fprintf(f, "Icon=%s\n", icon);
+
+ fflush(f);
+
+ if (ferror(f)) {
+ log_error("Failed to write query file: %m");
+ r = -errno;
+ goto finish;
+ }
+
+ memcpy(final, temp, sizeof(temp));
+
+ final[sizeof(final)-11] = 'a';
+ final[sizeof(final)-10] = 's';
+ final[sizeof(final)-9] = 'k';
+
+ if (rename(temp, final) < 0) {
+ log_error("Failed to rename query file: %m");
+ r = -errno;
+ goto finish;
+ }
+
+ zero(pollfd);
+ pollfd[FD_SOCKET].fd = socket_fd;
+ pollfd[FD_SOCKET].events = POLLIN;
+ pollfd[FD_SIGNAL].fd = signal_fd;
+ pollfd[FD_SIGNAL].events = POLLIN;
+
+ for (;;) {
+ char passphrase[LINE_MAX+1];
+ struct msghdr msghdr;
+ struct iovec iovec;
+ struct ucred *ucred;
+ union {
+ struct cmsghdr cmsghdr;
+ uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
+ } control;
+ ssize_t n;
+ int k;
+ usec_t t;
+
+ t = now(CLOCK_MONOTONIC);
+
+ if (until > 0 && until <= t) {
+ log_notice("Timed out");
+ r = -ETIME;
+ goto finish;
+ }
+
+ if ((k = poll(pollfd, _FD_MAX, until > 0 ? (int) ((until-t)/USEC_PER_MSEC) : -1)) < 0) {
+
+ if (errno == EINTR)
+ continue;
+
+ log_error("poll() failed: %m");
+ r = -errno;
+ goto finish;
+ }
+
+ if (k <= 0) {
+ log_notice("Timed out");
+ r = -ETIME;
+ goto finish;
+ }
+
+ if (pollfd[FD_SIGNAL].revents & POLLIN) {
+ r = -EINTR;
+ goto finish;
+ }
+
+ if (pollfd[FD_SOCKET].revents != POLLIN) {
+ log_error("Unexpected poll() event.");
+ r = -EIO;
+ goto finish;
+ }
+
+ zero(iovec);
+ iovec.iov_base = passphrase;
+ iovec.iov_len = sizeof(passphrase);
+
+ zero(control);
+ zero(msghdr);
+ msghdr.msg_iov = &iovec;
+ msghdr.msg_iovlen = 1;
+ msghdr.msg_control = &control;
+ msghdr.msg_controllen = sizeof(control);
+
+ if ((n = recvmsg(socket_fd, &msghdr, 0)) < 0) {
+
+ if (errno == EAGAIN ||
+ errno == EINTR)
+ continue;
+
+ log_error("recvmsg() failed: %m");
+ r = -errno;
+ goto finish;
+ }
+
+ if (n <= 0) {
+ log_error("Message too short");
+ continue;
+ }
+
+ if (msghdr.msg_controllen < CMSG_LEN(sizeof(struct ucred)) ||
+ control.cmsghdr.cmsg_level != SOL_SOCKET ||
+ control.cmsghdr.cmsg_type != SCM_CREDENTIALS ||
+ control.cmsghdr.cmsg_len != CMSG_LEN(sizeof(struct ucred))) {
+ log_warning("Received message without credentials. Ignoring.");
+ continue;
+ }
+
+ ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
+ if (ucred->uid != 0) {
+ log_warning("Got request from unprivileged user. Ignoring.");
+ continue;
+ }
+
+ if (passphrase[0] == '+') {
+ char **l;
+
+ if (n == 1)
+ l = strv_new("", NULL);
+ else
+ l = strv_parse_nulstr(passphrase+1, n-1);
+ /* An empty message refers to the empty password */
+
+ if (!l) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ if (strv_length(l) <= 0) {
+ strv_free(l);
+ log_error("Invalid packet");
+ continue;
+ }
+
+ *_passphrases = l;
+
+ } else if (passphrase[0] == '-') {
+ r = -ECANCELED;
+ goto finish;
+ } else {
+ log_error("Invalid packet");
+ continue;
+ }
+
+ break;
+ }
+
+ r = 0;
+
+finish:
+ if (fd >= 0)
+ close_nointr_nofail(fd);
+
+ if (socket_name) {
+ unlink(socket_name);
+ free(socket_name);
+ }
+
+ if (socket_fd >= 0)
+ close_nointr_nofail(socket_fd);
+
+ if (signal_fd >= 0)
+ close_nointr_nofail(signal_fd);
+
+ if (f)
+ fclose(f);
+
+ unlink(temp);
+
+ if (final[0])
+ unlink(final);
+
+ assert_se(sigprocmask(SIG_SETMASK, &oldmask, NULL) == 0);
+
+ return r;
+}
+
+int ask_password_auto(const char *message, const char *icon, usec_t until, bool accept_cached, char ***_passphrases) {
+ assert(message);
+ assert(_passphrases);
+
+ if (isatty(STDIN_FILENO)) {
+ int r;
+ char *s = NULL, **l = NULL;
+
+ if ((r = ask_password_tty(message, until, NULL, &s)) < 0)
+ return r;
+
+ l = strv_new(s, NULL);
+ free(s);
+
+ if (!l)
+ return -ENOMEM;
+
+ *_passphrases = l;
+ return r;
+
+ } else
+ return ask_password_agent(message, icon, until, accept_cached, _passphrases);
+}
diff --git a/src/shared/ask-password-api.h b/src/shared/ask-password-api.h
new file mode 100644
index 0000000000..288a0f48cf
--- /dev/null
+++ b/src/shared/ask-password-api.h
@@ -0,0 +1,30 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "util.h"
+
+int ask_password_tty(const char *message, usec_t until, const char *flag_file, char **_passphrase);
+
+int ask_password_agent(const char *message, const char *icon, usec_t until, bool accept_cached, char ***_passphrases);
+
+int ask_password_auto(const char *message, const char *icon, usec_t until, bool accept_cached, char ***_passphrases);
diff --git a/src/shared/audit.c b/src/shared/audit.c
new file mode 100644
index 0000000000..97560cc9a3
--- /dev/null
+++ b/src/shared/audit.c
@@ -0,0 +1,128 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <ctype.h>
+#include <sys/prctl.h>
+#include <sys/capability.h>
+
+#include "macro.h"
+#include "audit.h"
+#include "util.h"
+#include "log.h"
+#include "fileio.h"
+#include "virt.h"
+
+int audit_session_from_pid(pid_t pid, uint32_t *id) {
+ char *s;
+ uint32_t u;
+ int r;
+
+ assert(id);
+
+ if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
+ return -ENOENT;
+
+ /* Audit doesn't support containers right now */
+ if (detect_container(NULL) > 0)
+ return -ENOTSUP;
+
+ if (pid == 0)
+ r = read_one_line_file("/proc/self/sessionid", &s);
+ else {
+ char *p;
+
+ if (asprintf(&p, "/proc/%lu/sessionid", (unsigned long) pid) < 0)
+ return -ENOMEM;
+
+ r = read_one_line_file(p, &s);
+ free(p);
+ }
+
+ if (r < 0)
+ return r;
+
+ r = safe_atou32(s, &u);
+ free(s);
+
+ if (r < 0)
+ return r;
+
+ if (u == (uint32_t) -1 || u <= 0)
+ return -ENOENT;
+
+ *id = u;
+ return 0;
+}
+
+int audit_loginuid_from_pid(pid_t pid, uid_t *uid) {
+ char *s;
+ uid_t u;
+ int r;
+
+ assert(uid);
+
+ /* Only use audit login uid if we are executed with sufficient
+ * capabilities so that pam_loginuid could do its job. If we
+ * are lacking the CAP_AUDIT_CONTROL capabality we most likely
+ * are being run in a container and /proc/self/loginuid is
+ * useless since it probably contains a uid of the host
+ * system. */
+
+ if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
+ return -ENOENT;
+
+ /* Audit doesn't support containers right now */
+ if (detect_container(NULL) > 0)
+ return -ENOTSUP;
+
+ if (pid == 0)
+ r = read_one_line_file("/proc/self/loginuid", &s);
+ else {
+ char *p;
+
+ if (asprintf(&p, "/proc/%lu/loginuid", (unsigned long) pid) < 0)
+ return -ENOMEM;
+
+ r = read_one_line_file(p, &s);
+ free(p);
+ }
+
+ if (r < 0)
+ return r;
+
+ r = parse_uid(s, &u);
+ free(s);
+
+ if (r < 0)
+ return r;
+
+ if (u == (uid_t) -1)
+ return -ENOENT;
+
+ *uid = (uid_t) u;
+ return 0;
+}
diff --git a/src/shared/audit.h b/src/shared/audit.h
new file mode 100644
index 0000000000..490a0b0320
--- /dev/null
+++ b/src/shared/audit.h
@@ -0,0 +1,32 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef fooaudithfoo
+#define fooaudithfoo
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/types.h>
+
+#include "capability.h"
+
+int audit_session_from_pid(pid_t pid, uint32_t *id);
+int audit_loginuid_from_pid(pid_t pid, uid_t *uid);
+
+#endif
diff --git a/src/shared/calendarspec.c b/src/shared/calendarspec.c
new file mode 100644
index 0000000000..7979e2384f
--- /dev/null
+++ b/src/shared/calendarspec.c
@@ -0,0 +1,927 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdlib.h>
+#include <string.h>
+
+#include "calendarspec.h"
+
+static void free_chain(CalendarComponent *c) {
+ CalendarComponent *n;
+
+ while (c) {
+ n = c->next;
+ free(c);
+ c = n;
+ }
+}
+
+void calendar_spec_free(CalendarSpec *c) {
+ assert(c);
+
+ free_chain(c->year);
+ free_chain(c->month);
+ free_chain(c->day);
+ free_chain(c->hour);
+ free_chain(c->minute);
+ free_chain(c->second);
+
+ free(c);
+}
+
+static int component_compare(const void *_a, const void *_b) {
+ CalendarComponent * const *a = _a, * const *b = _b;
+
+ if ((*a)->value < (*b)->value)
+ return -1;
+ if ((*a)->value > (*b)->value)
+ return 1;
+
+ if ((*a)->repeat < (*b)->repeat)
+ return -1;
+ if ((*a)->repeat > (*b)->repeat)
+ return 1;
+
+ return 0;
+}
+
+static void sort_chain(CalendarComponent **c) {
+ unsigned n = 0, k;
+ CalendarComponent **b, *i, **j, *next;
+
+ assert(c);
+
+ for (i = *c; i; i = i->next)
+ n++;
+
+ if (n <= 1)
+ return;
+
+ j = b = alloca(sizeof(CalendarComponent*) * n);
+ for (i = *c; i; i = i->next)
+ *(j++) = i;
+
+ qsort(b, n, sizeof(CalendarComponent*), component_compare);
+
+ b[n-1]->next = NULL;
+ next = b[n-1];
+
+ /* Drop non-unique entries */
+ for (k = n-1; k > 0; k--) {
+ if (b[k-1]->value == next->value &&
+ b[k-1]->repeat == next->repeat) {
+ free(b[k-1]);
+ continue;
+ }
+
+ b[k-1]->next = next;
+ next = b[k-1];
+ }
+
+ *c = next;
+}
+
+static void fix_year(CalendarComponent *c) {
+ /* Turns 12 → 2012, 89 → 1989 */
+
+ while(c) {
+ CalendarComponent *n = c->next;
+
+ if (c->value >= 0 && c->value < 70)
+ c->value += 2000;
+
+ if (c->value >= 70 && c->value < 100)
+ c->value += 1900;
+
+ c = n;
+ }
+}
+
+int calendar_spec_normalize(CalendarSpec *c) {
+ assert(c);
+
+ if (c->weekdays_bits <= 0 || c->weekdays_bits >= 127)
+ c->weekdays_bits = -1;
+
+ fix_year(c->year);
+
+ sort_chain(&c->year);
+ sort_chain(&c->month);
+ sort_chain(&c->day);
+ sort_chain(&c->hour);
+ sort_chain(&c->minute);
+ sort_chain(&c->second);
+
+ return 0;
+}
+
+_pure_ static bool chain_valid(CalendarComponent *c, int from, int to) {
+ if (!c)
+ return true;
+
+ if (c->value < from || c->value > to)
+ return false;
+
+ if (c->value + c->repeat > to)
+ return false;
+
+ if (c->next)
+ return chain_valid(c->next, from, to);
+
+ return true;
+}
+
+_pure_ bool calendar_spec_valid(CalendarSpec *c) {
+ assert(c);
+
+ if (c->weekdays_bits > 127)
+ return false;
+
+ if (!chain_valid(c->year, 1970, 2199))
+ return false;
+
+ if (!chain_valid(c->month, 1, 12))
+ return false;
+
+ if (!chain_valid(c->day, 1, 31))
+ return false;
+
+ if (!chain_valid(c->hour, 0, 23))
+ return false;
+
+ if (!chain_valid(c->minute, 0, 59))
+ return false;
+
+ if (!chain_valid(c->second, 0, 59))
+ return false;
+
+ return true;
+}
+
+static void format_weekdays(FILE *f, const CalendarSpec *c) {
+ static const char *const days[] = {
+ "Mon",
+ "Tue",
+ "Wed",
+ "Thu",
+ "Fri",
+ "Sat",
+ "Sun"
+ };
+
+ int l, x;
+ bool need_colon = false;
+
+ assert(f);
+ assert(c);
+ assert(c->weekdays_bits > 0 && c->weekdays_bits <= 127);
+
+ for (x = 0, l = -1; x < (int) ELEMENTSOF(days); x++) {
+
+ if (c->weekdays_bits & (1 << x)) {
+
+ if (l < 0) {
+ if (need_colon)
+ fputc(',', f);
+ else
+ need_colon = true;
+
+ fputs(days[x], f);
+ l = x;
+ }
+
+ } else if (l >= 0) {
+
+ if (x > l + 1) {
+ fputc(x > l + 2 ? '-' : ',', f);
+ fputs(days[x-1], f);
+ }
+
+ l = -1;
+ }
+ }
+
+ if (l >= 0 && x > l + 1) {
+ fputc(x > l + 2 ? '-' : ',', f);
+ fputs(days[x-1], f);
+ }
+}
+
+static void format_chain(FILE *f, int space, const CalendarComponent *c) {
+ assert(f);
+
+ if (!c) {
+ fputc('*', f);
+ return;
+ }
+
+ assert(c->value >= 0);
+ fprintf(f, "%0*i", space, c->value);
+
+ if (c->repeat > 0)
+ fprintf(f, "/%i", c->repeat);
+
+ if (c->next) {
+ fputc(',', f);
+ format_chain(f, space, c->next);
+ }
+}
+
+int calendar_spec_to_string(const CalendarSpec *c, char **p) {
+ char *buf = NULL;
+ size_t sz = 0;
+ FILE *f;
+
+ assert(c);
+ assert(p);
+
+ f = open_memstream(&buf, &sz);
+ if (!f)
+ return -ENOMEM;
+
+ if (c->weekdays_bits > 0 && c->weekdays_bits <= 127) {
+ format_weekdays(f, c);
+ fputc(' ', f);
+ }
+
+ format_chain(f, 4, c->year);
+ fputc('-', f);
+ format_chain(f, 2, c->month);
+ fputc('-', f);
+ format_chain(f, 2, c->day);
+ fputc(' ', f);
+ format_chain(f, 2, c->hour);
+ fputc(':', f);
+ format_chain(f, 2, c->minute);
+ fputc(':', f);
+ format_chain(f, 2, c->second);
+
+ fflush(f);
+
+ if (ferror(f)) {
+ free(buf);
+ fclose(f);
+ return -ENOMEM;
+ }
+
+ fclose(f);
+
+ *p = buf;
+ return 0;
+}
+
+static int parse_weekdays(const char **p, CalendarSpec *c) {
+ static const struct {
+ const char *name;
+ const int nr;
+ } day_nr[] = {
+ { "Monday", 0 },
+ { "Mon", 0 },
+ { "Tuesday", 1 },
+ { "Tue", 1 },
+ { "Wednesday", 2 },
+ { "Wed", 2 },
+ { "Thursday", 3 },
+ { "Thu", 3 },
+ { "Friday", 4 },
+ { "Fri", 4 },
+ { "Saturday", 5 },
+ { "Sat", 5 },
+ { "Sunday", 6 },
+ { "Sun", 6 }
+ };
+
+ int l = -1;
+ bool first = true;
+
+ assert(p);
+ assert(*p);
+ assert(c);
+
+ for (;;) {
+ unsigned i;
+
+ if (!first && **p == ' ')
+ return 0;
+
+ for (i = 0; i < ELEMENTSOF(day_nr); i++) {
+ size_t skip;
+
+ if (!startswith_no_case(*p, day_nr[i].name))
+ continue;
+
+ skip = strlen(day_nr[i].name);
+
+ if ((*p)[skip] != '-' &&
+ (*p)[skip] != ',' &&
+ (*p)[skip] != ' ' &&
+ (*p)[skip] != 0)
+ return -EINVAL;
+
+ c->weekdays_bits |= 1 << day_nr[i].nr;
+
+ if (l >= 0) {
+ int j;
+
+ if (l > day_nr[i].nr)
+ return -EINVAL;
+
+ for (j = l + 1; j < day_nr[i].nr; j++)
+ c->weekdays_bits |= 1 << j;
+ }
+
+ *p += skip;
+ break;
+ }
+
+ /* Couldn't find this prefix, so let's assume the
+ weekday was not specified and let's continue with
+ the date */
+ if (i >= ELEMENTSOF(day_nr))
+ return first ? 0 : -EINVAL;
+
+ /* We reached the end of the string */
+ if (**p == 0)
+ return 0;
+
+ /* We reached the end of the weekday spec part */
+ if (**p == ' ') {
+ *p += strspn(*p, " ");
+ return 0;
+ }
+
+ if (**p == '-') {
+ if (l >= 0)
+ return -EINVAL;
+
+ l = day_nr[i].nr;
+ } else
+ l = -1;
+
+ *p += 1;
+ first = false;
+ }
+}
+
+static int prepend_component(const char **p, CalendarComponent **c) {
+ unsigned long value, repeat = 0;
+ char *e = NULL, *ee = NULL;
+ CalendarComponent *cc;
+
+ assert(p);
+ assert(c);
+
+ errno = 0;
+ value = strtoul(*p, &e, 10);
+ if (errno > 0)
+ return -errno;
+ if (e == *p)
+ return -EINVAL;
+ if ((unsigned long) (int) value != value)
+ return -ERANGE;
+
+ if (*e == '/') {
+ repeat = strtoul(e+1, &ee, 10);
+ if (errno > 0)
+ return -errno;
+ if (ee == e+1)
+ return -EINVAL;
+ if ((unsigned long) (int) repeat != repeat)
+ return -ERANGE;
+ if (repeat <= 0)
+ return -ERANGE;
+
+ e = ee;
+ }
+
+ if (*e != 0 && *e != ' ' && *e != ',' && *e != '-' && *e != ':')
+ return -EINVAL;
+
+ cc = new0(CalendarComponent, 1);
+ if (!cc)
+ return -ENOMEM;
+
+ cc->value = value;
+ cc->repeat = repeat;
+ cc->next = *c;
+
+ *p = e;
+ *c = cc;
+
+ if (*e ==',') {
+ *p += 1;
+ return prepend_component(p, c);
+ }
+
+ return 0;
+}
+
+static int parse_chain(const char **p, CalendarComponent **c) {
+ const char *t;
+ CalendarComponent *cc = NULL;
+ int r;
+
+ assert(p);
+ assert(c);
+
+ t = *p;
+
+ if (t[0] == '*') {
+ *p = t + 1;
+ *c = NULL;
+ return 0;
+ }
+
+ r = prepend_component(&t, &cc);
+ if (r < 0) {
+ free_chain(cc);
+ return r;
+ }
+
+ *p = t;
+ *c = cc;
+ return 0;
+}
+
+static int const_chain(int value, CalendarComponent **c) {
+ CalendarComponent *cc = NULL;
+
+ assert(c);
+
+ cc = new0(CalendarComponent, 1);
+ if (!cc)
+ return -ENOMEM;
+
+ cc->value = value;
+ cc->repeat = 0;
+ cc->next = NULL;
+
+ *c = cc;
+
+ return 0;
+}
+
+static int parse_date(const char **p, CalendarSpec *c) {
+ const char *t;
+ int r;
+ CalendarComponent *first, *second, *third;
+
+ assert(p);
+ assert(*p);
+ assert(c);
+
+ t = *p;
+
+ if (*t == 0)
+ return 0;
+
+ r = parse_chain(&t, &first);
+ if (r < 0)
+ return r;
+
+ /* Already the end? A ':' as separator? In that case this was a time, not a date */
+ if (*t == 0 || *t == ':') {
+ free_chain(first);
+ return 0;
+ }
+
+ if (*t != '-') {
+ free_chain(first);
+ return -EINVAL;
+ }
+
+ t++;
+ r = parse_chain(&t, &second);
+ if (r < 0) {
+ free_chain(first);
+ return r;
+ }
+
+ /* Got two parts, hence it's month and day */
+ if (*t == ' ' || *t == 0) {
+ *p = t + strspn(t, " ");
+ c->month = first;
+ c->day = second;
+ return 0;
+ }
+
+ if (*t != '-') {
+ free_chain(first);
+ free_chain(second);
+ return -EINVAL;
+ }
+
+ t++;
+ r = parse_chain(&t, &third);
+ if (r < 0) {
+ free_chain(first);
+ free_chain(second);
+ return r;
+ }
+
+ /* Got tree parts, hence it is year, month and day */
+ if (*t == ' ' || *t == 0) {
+ *p = t + strspn(t, " ");
+ c->year = first;
+ c->month = second;
+ c->day = third;
+ return 0;
+ }
+
+ free_chain(first);
+ free_chain(second);
+ free_chain(third);
+ return -EINVAL;
+}
+
+static int parse_time(const char **p, CalendarSpec *c) {
+ CalendarComponent *h = NULL, *m = NULL, *s = NULL;
+ const char *t;
+ int r;
+
+ assert(p);
+ assert(*p);
+ assert(c);
+
+ t = *p;
+
+ if (*t == 0) {
+ /* If no time is specified at all, but a date of some
+ * kind, then this means 00:00:00 */
+ if (c->day || c->weekdays_bits > 0)
+ goto null_hour;
+
+ goto finish;
+ }
+
+ r = parse_chain(&t, &h);
+ if (r < 0)
+ goto fail;
+
+ if (*t != ':') {
+ r = -EINVAL;
+ goto fail;
+ }
+
+ t++;
+ r = parse_chain(&t, &m);
+ if (r < 0)
+ goto fail;
+
+ /* Already at the end? Then it's hours and minutes, and seconds are 0 */
+ if (*t == 0) {
+ if (m != NULL)
+ goto null_second;
+
+ goto finish;
+ }
+
+ if (*t != ':') {
+ r = -EINVAL;
+ goto fail;
+ }
+
+ t++;
+ r = parse_chain(&t, &s);
+ if (r < 0)
+ goto fail;
+
+ /* At the end? Then it's hours, minutes and seconds */
+ if (*t == 0)
+ goto finish;
+
+ r = -EINVAL;
+ goto fail;
+
+null_hour:
+ r = const_chain(0, &h);
+ if (r < 0)
+ goto fail;
+
+ r = const_chain(0, &m);
+ if (r < 0)
+ goto fail;
+
+null_second:
+ r = const_chain(0, &s);
+ if (r < 0)
+ goto fail;
+
+finish:
+ *p = t;
+ c->hour = h;
+ c->minute = m;
+ c->second = s;
+ return 0;
+
+fail:
+ free_chain(h);
+ free_chain(m);
+ free_chain(s);
+ return r;
+}
+
+int calendar_spec_from_string(const char *p, CalendarSpec **spec) {
+ CalendarSpec *c;
+ int r;
+
+ assert(p);
+ assert(spec);
+
+ if (isempty(p))
+ return -EINVAL;
+
+ c = new0(CalendarSpec, 1);
+ if (!c)
+ return -ENOMEM;
+
+ if (strcaseeq(p, "hourly")) {
+ r = const_chain(0, &c->minute);
+ if (r < 0)
+ goto fail;
+ r = const_chain(0, &c->second);
+ if (r < 0)
+ goto fail;
+
+ } else if (strcaseeq(p, "daily")) {
+ r = const_chain(0, &c->hour);
+ if (r < 0)
+ goto fail;
+ r = const_chain(0, &c->minute);
+ if (r < 0)
+ goto fail;
+ r = const_chain(0, &c->second);
+ if (r < 0)
+ goto fail;
+
+ } else if (strcaseeq(p, "monthly")) {
+ r = const_chain(1, &c->day);
+ if (r < 0)
+ goto fail;
+ r = const_chain(0, &c->hour);
+ if (r < 0)
+ goto fail;
+ r = const_chain(0, &c->minute);
+ if (r < 0)
+ goto fail;
+ r = const_chain(0, &c->second);
+ if (r < 0)
+ goto fail;
+
+ } else if (strcaseeq(p, "weekly")) {
+
+ c->weekdays_bits = 1;
+
+ r = const_chain(0, &c->hour);
+ if (r < 0)
+ goto fail;
+ r = const_chain(0, &c->minute);
+ if (r < 0)
+ goto fail;
+ r = const_chain(0, &c->second);
+ if (r < 0)
+ goto fail;
+
+ } else {
+ r = parse_weekdays(&p, c);
+ if (r < 0)
+ goto fail;
+
+ r = parse_date(&p, c);
+ if (r < 0)
+ goto fail;
+
+ r = parse_time(&p, c);
+ if (r < 0)
+ goto fail;
+
+ if (*p != 0) {
+ r = -EINVAL;
+ goto fail;
+ }
+ }
+
+ r = calendar_spec_normalize(c);
+ if (r < 0)
+ goto fail;
+
+ if (!calendar_spec_valid(c)) {
+ r = -EINVAL;
+ goto fail;
+ }
+
+ *spec = c;
+ return 0;
+
+fail:
+ calendar_spec_free(c);
+ return r;
+}
+
+static int find_matching_component(const CalendarComponent *c, int *val) {
+ const CalendarComponent *n;
+ int d = -1;
+ bool d_set = false;
+ int r;
+
+ assert(val);
+
+ if (!c)
+ return 0;
+
+ while (c) {
+ n = c->next;
+
+ if (c->value >= *val) {
+
+ if (!d_set || c->value < d) {
+ d = c->value;
+ d_set = true;
+ }
+
+ } else if (c->repeat > 0) {
+ int k;
+
+ k = c->value + c->repeat * ((*val - c->value + c->repeat -1) / c->repeat);
+
+ if (!d_set || k < d) {
+ d = k;
+ d_set = true;
+ }
+ }
+
+ c = n;
+ }
+
+ if (!d_set)
+ return -ENOENT;
+
+ r = *val != d;
+ *val = d;
+ return r;
+}
+
+static bool tm_out_of_bounds(const struct tm *tm) {
+ struct tm t;
+ assert(tm);
+
+ t = *tm;
+
+ if (mktime(&t) == (time_t) -1)
+ return true;
+
+ /* Did any normalization take place? If so, it was out of bounds before */
+ return
+ t.tm_year != tm->tm_year ||
+ t.tm_mon != tm->tm_mon ||
+ t.tm_mday != tm->tm_mday ||
+ t.tm_hour != tm->tm_hour ||
+ t.tm_min != tm->tm_min ||
+ t.tm_sec != tm->tm_sec;
+}
+
+static bool matches_weekday(int weekdays_bits, const struct tm *tm) {
+ struct tm t;
+ int k;
+
+ if (weekdays_bits < 0 || weekdays_bits >= 127)
+ return true;
+
+ t = *tm;
+ if (mktime(&t) == (time_t) -1)
+ return false;
+
+ k = t.tm_wday == 0 ? 6 : t.tm_wday - 1;
+ return (weekdays_bits & (1 << k));
+}
+
+static int find_next(const CalendarSpec *spec, struct tm *tm) {
+ struct tm c;
+ int r;
+
+ assert(spec);
+ assert(tm);
+
+ c = *tm;
+
+ for (;;) {
+ /* Normalize the current date */
+ mktime(&c);
+ c.tm_isdst = -1;
+
+ c.tm_year += 1900;
+ r = find_matching_component(spec->year, &c.tm_year);
+ c.tm_year -= 1900;
+
+ if (r > 0) {
+ c.tm_mon = 0;
+ c.tm_mday = 1;
+ c.tm_hour = c.tm_min = c.tm_sec = 0;
+ }
+ if (r < 0 || tm_out_of_bounds(&c))
+ return r;
+
+ c.tm_mon += 1;
+ r = find_matching_component(spec->month, &c.tm_mon);
+ c.tm_mon -= 1;
+
+ if (r > 0) {
+ c.tm_mday = 1;
+ c.tm_hour = c.tm_min = c.tm_sec = 0;
+ }
+ if (r < 0 || tm_out_of_bounds(&c)) {
+ c.tm_year ++;
+ c.tm_mon = 0;
+ c.tm_mday = 1;
+ c.tm_hour = c.tm_min = c.tm_sec = 0;
+ continue;
+ }
+
+ r = find_matching_component(spec->day, &c.tm_mday);
+ if (r > 0)
+ c.tm_hour = c.tm_min = c.tm_sec = 0;
+ if (r < 0 || tm_out_of_bounds(&c)) {
+ c.tm_mon ++;
+ c.tm_mday = 1;
+ c.tm_hour = c.tm_min = c.tm_sec = 0;
+ continue;
+ }
+
+ if (!matches_weekday(spec->weekdays_bits, &c)) {
+ c.tm_mday++;
+ c.tm_hour = c.tm_min = c.tm_sec = 0;
+ continue;
+ }
+
+ r = find_matching_component(spec->hour, &c.tm_hour);
+ if (r > 0)
+ c.tm_min = c.tm_sec = 0;
+ if (r < 0 || tm_out_of_bounds(&c)) {
+ c.tm_mday ++;
+ c.tm_hour = c.tm_min = c.tm_sec = 0;
+ continue;
+ }
+
+ r = find_matching_component(spec->minute, &c.tm_min);
+ if (r > 0)
+ c.tm_sec = 0;
+ if (r < 0 || tm_out_of_bounds(&c)) {
+ c.tm_hour ++;
+ c.tm_min = c.tm_sec = 0;
+ continue;
+ }
+
+ r = find_matching_component(spec->second, &c.tm_sec);
+ if (r < 0 || tm_out_of_bounds(&c)) {
+ c.tm_min ++;
+ c.tm_sec = 0;
+ continue;
+ }
+
+
+ *tm = c;
+ return 0;
+ }
+}
+
+int calendar_spec_next_usec(const CalendarSpec *spec, usec_t usec, usec_t *next) {
+ struct tm tm;
+ time_t t;
+ int r;
+
+ assert(spec);
+ assert(next);
+
+ t = (time_t) (usec / USEC_PER_SEC) + 1;
+ assert_se(localtime_r(&t, &tm));
+
+ r = find_next(spec, &tm);
+ if (r < 0)
+ return r;
+
+ t = mktime(&tm);
+ if (t == (time_t) -1)
+ return -EINVAL;
+
+
+ *next = (usec_t) t * USEC_PER_SEC;
+ return 0;
+}
diff --git a/src/shared/calendarspec.h b/src/shared/calendarspec.h
new file mode 100644
index 0000000000..7baf318249
--- /dev/null
+++ b/src/shared/calendarspec.h
@@ -0,0 +1,57 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+/* A structure for specifying (possibly repetitive) points in calendar
+ * time, a la cron */
+
+#include <stdbool.h>
+#include "util.h"
+
+typedef struct CalendarComponent {
+ int value;
+ int repeat;
+
+ struct CalendarComponent *next;
+} CalendarComponent;
+
+typedef struct CalendarSpec {
+ int weekdays_bits;
+
+ CalendarComponent *year;
+ CalendarComponent *month;
+ CalendarComponent *day;
+
+ CalendarComponent *hour;
+ CalendarComponent *minute;
+ CalendarComponent *second;
+} CalendarSpec;
+
+void calendar_spec_free(CalendarSpec *c);
+
+int calendar_spec_normalize(CalendarSpec *spec);
+bool calendar_spec_valid(CalendarSpec *spec);
+
+int calendar_spec_to_string(const CalendarSpec *spec, char **p);
+int calendar_spec_from_string(const char *p, CalendarSpec **spec);
+
+int calendar_spec_next_usec(const CalendarSpec *spec, usec_t usec, usec_t *next);
diff --git a/src/shared/capability.c b/src/shared/capability.c
new file mode 100644
index 0000000000..321952067d
--- /dev/null
+++ b/src/shared/capability.c
@@ -0,0 +1,225 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#include <stdio.h>
+#include <sys/types.h>
+#include <stdarg.h>
+#include <ctype.h>
+#include <sys/capability.h>
+#include <sys/prctl.h>
+
+#include "macro.h"
+#include "capability.h"
+#include "util.h"
+#include "log.h"
+#include "fileio.h"
+
+int have_effective_cap(int value) {
+ cap_t cap;
+ cap_flag_value_t fv;
+ int r;
+
+ cap = cap_get_proc();
+ if (!cap)
+ return -errno;
+
+ if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
+ r = -errno;
+ else
+ r = fv == CAP_SET;
+
+ cap_free(cap);
+ return r;
+}
+
+unsigned long cap_last_cap(void) {
+ static __thread unsigned long saved;
+ static __thread bool valid = false;
+ unsigned long p;
+
+ if (valid)
+ return saved;
+
+ p = (unsigned long) CAP_LAST_CAP;
+
+ if (prctl(PR_CAPBSET_READ, p) < 0) {
+
+ /* Hmm, look downwards, until we find one that
+ * works */
+ for (p--; p > 0; p --)
+ if (prctl(PR_CAPBSET_READ, p) >= 0)
+ break;
+
+ } else {
+
+ /* Hmm, look upwards, until we find one that doesn't
+ * work */
+ for (;; p++)
+ if (prctl(PR_CAPBSET_READ, p+1) < 0)
+ break;
+ }
+
+ saved = p;
+ valid = true;
+
+ return p;
+}
+
+int capability_bounding_set_drop(uint64_t drop, bool right_now) {
+ unsigned long i;
+ cap_t after_cap = NULL, temp_cap = NULL;
+ cap_flag_value_t fv;
+ int r;
+
+ /* If we are run as PID 1 we will lack CAP_SETPCAP by default
+ * in the effective set (yes, the kernel drops that when
+ * executing init!), so get it back temporarily so that we can
+ * call PR_CAPBSET_DROP. */
+
+ after_cap = cap_get_proc();
+ if (!after_cap)
+ return -errno;
+
+ if (cap_get_flag(after_cap, CAP_SETPCAP, CAP_EFFECTIVE, &fv) < 0) {
+ cap_free(after_cap);
+ return -errno;
+ }
+
+ if (fv != CAP_SET) {
+ static const cap_value_t v = CAP_SETPCAP;
+
+ temp_cap = cap_dup(after_cap);
+ if (!temp_cap) {
+ r = -errno;
+ goto finish;
+ }
+
+ if (cap_set_flag(temp_cap, CAP_EFFECTIVE, 1, &v, CAP_SET) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ if (cap_set_proc(temp_cap) < 0) {
+ r = -errno;
+ goto finish;
+ }
+ }
+
+ for (i = 0; i <= cap_last_cap(); i++) {
+
+ if (drop & ((uint64_t) 1ULL << (uint64_t) i)) {
+ cap_value_t v;
+
+ /* Drop it from the bounding set */
+ if (prctl(PR_CAPBSET_DROP, i) < 0) {
+ r = -errno;
+ goto finish;
+ }
+ v = i;
+
+ /* Also drop it from the inheritable set, so
+ * that anything we exec() loses the
+ * capability for good. */
+ if (cap_set_flag(after_cap, CAP_INHERITABLE, 1, &v, CAP_CLEAR) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ /* If we shall apply this right now drop it
+ * also from our own capability sets. */
+ if (right_now) {
+ if (cap_set_flag(after_cap, CAP_PERMITTED, 1, &v, CAP_CLEAR) < 0 ||
+ cap_set_flag(after_cap, CAP_EFFECTIVE, 1, &v, CAP_CLEAR) < 0) {
+ r = -errno;
+ goto finish;
+ }
+ }
+ }
+ }
+
+ r = 0;
+
+finish:
+ if (temp_cap)
+ cap_free(temp_cap);
+
+ if (after_cap) {
+ cap_set_proc(after_cap);
+ cap_free(after_cap);
+ }
+
+ return r;
+}
+
+static int drop_from_file(const char *fn, uint64_t drop) {
+ int r, k;
+ uint32_t hi, lo;
+ uint64_t current, after;
+ char *p;
+
+ r = read_one_line_file(fn, &p);
+ if (r < 0)
+ return r;
+
+ assert_cc(sizeof(hi) == sizeof(unsigned));
+ assert_cc(sizeof(lo) == sizeof(unsigned));
+
+ k = sscanf(p, "%u %u", &lo, &hi);
+ free(p);
+
+ if (k != 2)
+ return -EIO;
+
+ current = (uint64_t) lo | ((uint64_t) hi << 32ULL);
+ after = current & ~drop;
+
+ if (current == after)
+ return 0;
+
+ lo = (unsigned) (after & 0xFFFFFFFFULL);
+ hi = (unsigned) ((after >> 32ULL) & 0xFFFFFFFFULL);
+
+ if (asprintf(&p, "%u %u", lo, hi) < 0)
+ return -ENOMEM;
+
+ r = write_string_file(fn, p);
+ free(p);
+
+ return r;
+}
+
+int capability_bounding_set_drop_usermode(uint64_t drop) {
+ int r;
+
+ r = drop_from_file("/proc/sys/kernel/usermodehelper/inheritable", drop);
+ if (r < 0)
+ return r;
+
+ r = drop_from_file("/proc/sys/kernel/usermodehelper/bset", drop);
+ if (r < 0)
+ return r;
+
+ return r;
+}
diff --git a/src/shared/capability.h b/src/shared/capability.h
new file mode 100644
index 0000000000..6cb31bb510
--- /dev/null
+++ b/src/shared/capability.h
@@ -0,0 +1,33 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef foocapabilityhfoo
+#define foocapabilityhfoo
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <inttypes.h>
+#include <stdbool.h>
+
+unsigned long cap_last_cap(void);
+int have_effective_cap(int value);
+int capability_bounding_set_drop(uint64_t drop, bool right_now);
+int capability_bounding_set_drop_usermode(uint64_t drop);
+
+#endif
diff --git a/src/shared/cgroup-label.c b/src/shared/cgroup-label.c
new file mode 100644
index 0000000000..5b5163c250
--- /dev/null
+++ b/src/shared/cgroup-label.c
@@ -0,0 +1,77 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <unistd.h>
+#include <signal.h>
+#include <string.h>
+#include <stdlib.h>
+#include <dirent.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <ftw.h>
+
+#include "cgroup-util.h"
+#include "log.h"
+#include "set.h"
+#include "macro.h"
+#include "util.h"
+#include "mkdir.h"
+
+int cg_create(const char *controller, const char *path, const char *suffix) {
+ _cleanup_free_ char *fs = NULL;
+ int r;
+
+ r = cg_get_path_and_check(controller, path, suffix, &fs);
+ if (r < 0)
+ return r;
+
+ r = mkdir_parents_label(fs, 0755);
+ if (r < 0)
+ return r;
+
+ if (mkdir(fs, 0755) < 0) {
+
+ if (errno == EEXIST)
+ return 0;
+
+ return -errno;
+ }
+
+ return 1;
+}
+
+int cg_create_and_attach(const char *controller, const char *path, pid_t pid) {
+ int r, q;
+
+ assert(pid >= 0);
+
+ r = cg_create(controller, path, NULL);
+ if (r < 0)
+ return r;
+
+ q = cg_attach(controller, path, pid);
+ if (q < 0)
+ return q;
+
+ /* This does not remove the cgroup on failure */
+ return r;
+}
diff --git a/src/shared/cgroup-show.c b/src/shared/cgroup-show.c
new file mode 100644
index 0000000000..83cc0731b8
--- /dev/null
+++ b/src/shared/cgroup-show.c
@@ -0,0 +1,300 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include <string.h>
+#include <dirent.h>
+#include <errno.h>
+
+#include "util.h"
+#include "macro.h"
+#include "path-util.h"
+#include "cgroup-util.h"
+#include "cgroup-show.h"
+
+static int compare(const void *a, const void *b) {
+ const pid_t *p = a, *q = b;
+
+ if (*p < *q)
+ return -1;
+ if (*p > *q)
+ return 1;
+ return 0;
+}
+
+static void show_pid_array(int pids[], unsigned n_pids, const char *prefix, unsigned n_columns, bool extra, bool more, bool kernel_threads, OutputFlags flags) {
+ unsigned i, m, pid_width;
+ pid_t biggest = 0;
+
+ /* Filter duplicates */
+ m = 0;
+ for (i = 0; i < n_pids; i++) {
+ unsigned j;
+
+ if (pids[i] > biggest)
+ biggest = pids[i];
+
+ for (j = i+1; j < n_pids; j++)
+ if (pids[i] == pids[j])
+ break;
+
+ if (j >= n_pids)
+ pids[m++] = pids[i];
+ }
+ n_pids = m;
+ pid_width = DECIMAL_STR_WIDTH(biggest);
+
+ /* And sort */
+ qsort(pids, n_pids, sizeof(pid_t), compare);
+
+ if(flags & OUTPUT_FULL_WIDTH)
+ n_columns = 0;
+ else {
+ if (n_columns > pid_width+2)
+ n_columns -= pid_width+2;
+ else
+ n_columns = 20;
+ }
+ for (i = 0; i < n_pids; i++) {
+ char *t = NULL;
+
+ get_process_cmdline(pids[i], n_columns, true, &t);
+
+ printf("%s%s%*lu %s\n",
+ prefix,
+ draw_special_char(extra ? DRAW_TRIANGULAR_BULLET :
+ ((more || i < n_pids-1) ? DRAW_TREE_BRANCH : DRAW_TREE_RIGHT)),
+ pid_width,
+ (unsigned long) pids[i],
+ strna(t));
+
+ free(t);
+ }
+}
+
+
+static int show_cgroup_one_by_path(const char *path, const char *prefix, unsigned n_columns, bool more, bool kernel_threads, OutputFlags flags) {
+ char *fn;
+ _cleanup_fclose_ FILE *f = NULL;
+ size_t n = 0, n_allocated = 0;
+ _cleanup_free_ pid_t *pids = NULL;
+ char *p = NULL;
+ pid_t pid;
+ int r;
+
+ r = cg_mangle_path(path, &p);
+ if (r < 0)
+ return r;
+
+ fn = strappend(p, "/cgroup.procs");
+ free(p);
+ if (!fn)
+ return -ENOMEM;
+
+ f = fopen(fn, "re");
+ free(fn);
+ if (!f)
+ return -errno;
+
+ while ((r = cg_read_pid(f, &pid)) > 0) {
+
+ if (!kernel_threads && is_kernel_thread(pid) > 0)
+ continue;
+
+ if (n >= n_allocated) {
+ pid_t *npids;
+
+ n_allocated = MAX(16U, n*2U);
+
+ npids = realloc(pids, sizeof(pid_t) * n_allocated);
+ if (!npids)
+ return -ENOMEM;
+
+ pids = npids;
+ }
+
+ assert(n < n_allocated);
+ pids[n++] = pid;
+ }
+
+ if (r < 0)
+ return r;
+
+ if (n > 0)
+ show_pid_array(pids, n, prefix, n_columns, false, more, kernel_threads, flags);
+
+ return 0;
+}
+
+int show_cgroup_by_path(const char *path, const char *prefix, unsigned n_columns, bool kernel_threads, OutputFlags flags) {
+ _cleanup_free_ char *fn = NULL, *p1 = NULL, *last = NULL, *p2 = NULL;
+ _cleanup_closedir_ DIR *d = NULL;
+ char *gn = NULL;
+ bool shown_pids = false;
+ int r;
+
+ assert(path);
+
+ if (n_columns <= 0)
+ n_columns = columns();
+
+ if (!prefix)
+ prefix = "";
+
+ r = cg_mangle_path(path, &fn);
+ if (r < 0)
+ return r;
+
+ d = opendir(fn);
+ if (!d)
+ return -errno;
+
+ while ((r = cg_read_subgroup(d, &gn)) > 0) {
+ _cleanup_free_ char *k = NULL;
+
+ k = strjoin(fn, "/", gn, NULL);
+ free(gn);
+ if (!k)
+ return -ENOMEM;
+
+ if (!(flags & OUTPUT_SHOW_ALL) && cg_is_empty_recursive(NULL, k, false) > 0)
+ continue;
+
+ if (!shown_pids) {
+ show_cgroup_one_by_path(path, prefix, n_columns, true, kernel_threads, flags);
+ shown_pids = true;
+ }
+
+ if (last) {
+ printf("%s%s%s\n", prefix, draw_special_char(DRAW_TREE_BRANCH),
+ path_get_file_name(last));
+
+ if (!p1) {
+ p1 = strappend(prefix, draw_special_char(DRAW_TREE_VERT));
+ if (!p1)
+ return -ENOMEM;
+ }
+
+ show_cgroup_by_path(last, p1, n_columns-2, kernel_threads, flags);
+ free(last);
+ }
+
+ last = k;
+ k = NULL;
+ }
+
+ if (r < 0)
+ return r;
+
+ if (!shown_pids)
+ show_cgroup_one_by_path(path, prefix, n_columns, !!last, kernel_threads, flags);
+
+ if (last) {
+ printf("%s%s%s\n", prefix, draw_special_char(DRAW_TREE_RIGHT),
+ path_get_file_name(last));
+
+ if (!p2) {
+ p2 = strappend(prefix, " ");
+ if (!p2)
+ return -ENOMEM;
+ }
+
+ show_cgroup_by_path(last, p2, n_columns-2, kernel_threads, flags);
+ }
+
+ return 0;
+}
+
+int show_cgroup(const char *controller, const char *path, const char *prefix, unsigned n_columns, bool kernel_threads, OutputFlags flags) {
+ _cleanup_free_ char *p = NULL;
+ int r;
+
+ assert(path);
+
+ r = cg_get_path(controller, path, NULL, &p);
+ if (r < 0)
+ return r;
+
+ return show_cgroup_by_path(p, prefix, n_columns, kernel_threads, flags);
+}
+
+static int show_extra_pids(const char *controller, const char *path, const char *prefix, unsigned n_columns, const pid_t pids[], unsigned n_pids, OutputFlags flags) {
+ _cleanup_free_ pid_t *copy = NULL;
+ unsigned i, j;
+ int r;
+
+ assert(controller);
+ assert(path);
+
+ if (n_pids <= 0)
+ return 0;
+
+ if (n_columns <= 0)
+ n_columns = columns();
+
+ prefix = strempty(prefix);
+
+ copy = new(pid_t, n_pids);
+ if (!copy)
+ return -ENOMEM;
+
+ for (i = 0, j = 0; i < n_pids; i++) {
+ _cleanup_free_ char *k = NULL;
+
+ r = cg_pid_get_path(controller, pids[i], &k);
+ if (r < 0)
+ return r;
+
+ if (path_startswith(k, path))
+ continue;
+
+ copy[j++] = pids[i];
+ }
+
+ show_pid_array(copy, j, prefix, n_columns, true, false, false, flags);
+
+ return 0;
+}
+
+int show_cgroup_and_extra(const char *controller, const char *path, const char *prefix, unsigned n_columns, bool kernel_threads, const pid_t extra_pids[], unsigned n_extra_pids, OutputFlags flags) {
+ int r;
+
+ assert(path);
+
+ r = show_cgroup(controller, path, prefix, n_columns, kernel_threads, flags);
+ if (r < 0)
+ return r;
+
+ return show_extra_pids(controller, path, prefix, n_columns, extra_pids, n_extra_pids, flags);
+}
+
+int show_cgroup_and_extra_by_spec(const char *spec, const char *prefix, unsigned n_columns, bool kernel_threads, const pid_t extra_pids[], unsigned n_extra_pids, OutputFlags flags) {
+ _cleanup_free_ char *controller = NULL, *path = NULL;
+ int r;
+
+ assert(spec);
+
+ r = cg_split_spec(spec, &controller, &path);
+ if (r < 0)
+ return r;
+
+ return show_cgroup_and_extra(controller, path, prefix, n_columns, kernel_threads, extra_pids, n_extra_pids, flags);
+}
diff --git a/src/shared/cgroup-show.h b/src/shared/cgroup-show.h
new file mode 100644
index 0000000000..72bc8a650f
--- /dev/null
+++ b/src/shared/cgroup-show.h
@@ -0,0 +1,36 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef foocgroupshowhfoo
+#define foocgroupshowhfoo
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdbool.h>
+#include <sys/types.h>
+#include "util.h"
+#include "logs-show.h"
+
+int show_cgroup_by_path(const char *path, const char *prefix, unsigned columns, bool kernel_threads, OutputFlags flags);
+int show_cgroup(const char *controller, const char *path, const char *prefix, unsigned columns, bool kernel_threads, OutputFlags flags);
+
+int show_cgroup_and_extra_by_spec(const char *spec, const char *prefix, unsigned n_columns, bool kernel_threads, const pid_t extra_pids[], unsigned n_extra_pids, OutputFlags flags);
+int show_cgroup_and_extra(const char *controller, const char *path, const char *prefix, unsigned n_columns, bool kernel_threads, const pid_t extra_pids[], unsigned n_extra_pids, OutputFlags flags);
+
+#endif
diff --git a/src/shared/cgroup-util.c b/src/shared/cgroup-util.c
new file mode 100644
index 0000000000..43c415d760
--- /dev/null
+++ b/src/shared/cgroup-util.c
@@ -0,0 +1,1603 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <unistd.h>
+#include <signal.h>
+#include <string.h>
+#include <stdlib.h>
+#include <dirent.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <ftw.h>
+
+#include "cgroup-util.h"
+#include "log.h"
+#include "set.h"
+#include "macro.h"
+#include "util.h"
+#include "path-util.h"
+#include "strv.h"
+#include "unit-name.h"
+#include "fileio.h"
+
+int cg_enumerate_processes(const char *controller, const char *path, FILE **_f) {
+ _cleanup_free_ char *fs = NULL;
+ FILE *f;
+ int r;
+
+ assert(_f);
+
+ r = cg_get_path(controller, path, "cgroup.procs", &fs);
+ if (r < 0)
+ return r;
+
+ f = fopen(fs, "re");
+ if (!f)
+ return -errno;
+
+ *_f = f;
+ return 0;
+}
+
+int cg_enumerate_tasks(const char *controller, const char *path, FILE **_f) {
+ _cleanup_free_ char *fs = NULL;
+ FILE *f;
+ int r;
+
+ assert(_f);
+
+ r = cg_get_path(controller, path, "tasks", &fs);
+ if (r < 0)
+ return r;
+
+ f = fopen(fs, "re");
+ if (!f)
+ return -errno;
+
+ *_f = f;
+ return 0;
+}
+
+int cg_read_pid(FILE *f, pid_t *_pid) {
+ unsigned long ul;
+
+ /* Note that the cgroup.procs might contain duplicates! See
+ * cgroups.txt for details. */
+
+ assert(f);
+ assert(_pid);
+
+ errno = 0;
+ if (fscanf(f, "%lu", &ul) != 1) {
+
+ if (feof(f))
+ return 0;
+
+ return errno ? -errno : -EIO;
+ }
+
+ if (ul <= 0)
+ return -EIO;
+
+ *_pid = (pid_t) ul;
+ return 1;
+}
+
+int cg_enumerate_subgroups(const char *controller, const char *path, DIR **_d) {
+ _cleanup_free_ char *fs = NULL;
+ int r;
+ DIR *d;
+
+ assert(_d);
+
+ /* This is not recursive! */
+
+ r = cg_get_path(controller, path, NULL, &fs);
+ if (r < 0)
+ return r;
+
+ d = opendir(fs);
+ if (!d)
+ return -errno;
+
+ *_d = d;
+ return 0;
+}
+
+int cg_read_subgroup(DIR *d, char **fn) {
+ struct dirent *de;
+
+ assert(d);
+ assert(fn);
+
+ FOREACH_DIRENT(de, d, return -errno) {
+ char *b;
+
+ if (de->d_type != DT_DIR)
+ continue;
+
+ if (streq(de->d_name, ".") ||
+ streq(de->d_name, ".."))
+ continue;
+
+ b = strdup(de->d_name);
+ if (!b)
+ return -ENOMEM;
+
+ *fn = b;
+ return 1;
+ }
+
+ return 0;
+}
+
+int cg_rmdir(const char *controller, const char *path, bool honour_sticky) {
+ _cleanup_free_ char *p = NULL;
+ int r;
+
+ r = cg_get_path(controller, path, NULL, &p);
+ if (r < 0)
+ return r;
+
+ if (honour_sticky) {
+ char *tasks;
+
+ /* If the sticky bit is set don't remove the directory */
+
+ tasks = strappend(p, "/tasks");
+ if (!tasks)
+ return -ENOMEM;
+
+ r = file_is_priv_sticky(tasks);
+ free(tasks);
+
+ if (r > 0)
+ return 0;
+ }
+
+ r = rmdir(p);
+ if (r < 0 && errno != ENOENT)
+ return -errno;
+
+ return 0;
+}
+
+int cg_kill(const char *controller, const char *path, int sig, bool sigcont, bool ignore_self, Set *s) {
+ _cleanup_set_free_ Set *allocated_set = NULL;
+ bool done = false;
+ int r, ret = 0;
+ pid_t my_pid;
+
+ assert(sig >= 0);
+
+ /* This goes through the tasks list and kills them all. This
+ * is repeated until no further processes are added to the
+ * tasks list, to properly handle forking processes */
+
+ if (!s) {
+ s = allocated_set = set_new(trivial_hash_func, trivial_compare_func);
+ if (!s)
+ return -ENOMEM;
+ }
+
+ my_pid = getpid();
+
+ do {
+ _cleanup_fclose_ FILE *f = NULL;
+ pid_t pid = 0;
+ done = true;
+
+ r = cg_enumerate_processes(controller, path, &f);
+ if (r < 0) {
+ if (ret >= 0 && r != -ENOENT)
+ return r;
+
+ return ret;
+ }
+
+ while ((r = cg_read_pid(f, &pid)) > 0) {
+
+ if (ignore_self && pid == my_pid)
+ continue;
+
+ if (set_get(s, LONG_TO_PTR(pid)) == LONG_TO_PTR(pid))
+ continue;
+
+ /* If we haven't killed this process yet, kill
+ * it */
+ if (kill(pid, sig) < 0) {
+ if (ret >= 0 && errno != ESRCH)
+ ret = -errno;
+ } else if (ret == 0) {
+
+ if (sigcont)
+ kill(pid, SIGCONT);
+
+ ret = 1;
+ }
+
+ done = false;
+
+ r = set_put(s, LONG_TO_PTR(pid));
+ if (r < 0) {
+ if (ret >= 0)
+ return r;
+
+ return ret;
+ }
+ }
+
+ if (r < 0) {
+ if (ret >= 0)
+ return r;
+
+ return ret;
+ }
+
+ /* To avoid racing against processes which fork
+ * quicker than we can kill them we repeat this until
+ * no new pids need to be killed. */
+
+ } while (!done);
+
+ return ret;
+}
+
+int cg_kill_recursive(const char *controller, const char *path, int sig, bool sigcont, bool ignore_self, bool rem, Set *s) {
+ _cleanup_set_free_ Set *allocated_set = NULL;
+ _cleanup_closedir_ DIR *d = NULL;
+ int r, ret = 0;
+ char *fn;
+
+ assert(path);
+ assert(sig >= 0);
+
+ if (!s) {
+ s = allocated_set = set_new(trivial_hash_func, trivial_compare_func);
+ if (!s)
+ return -ENOMEM;
+ }
+
+ ret = cg_kill(controller, path, sig, sigcont, ignore_self, s);
+
+ r = cg_enumerate_subgroups(controller, path, &d);
+ if (r < 0) {
+ if (ret >= 0 && r != -ENOENT)
+ return r;
+
+ return ret;
+ }
+
+ while ((r = cg_read_subgroup(d, &fn)) > 0) {
+ _cleanup_free_ char *p = NULL;
+
+ p = strjoin(path, "/", fn, NULL);
+ free(fn);
+ if (!p)
+ return -ENOMEM;
+
+ r = cg_kill_recursive(controller, p, sig, sigcont, ignore_self, rem, s);
+ if (ret >= 0 && r != 0)
+ ret = r;
+ }
+
+ if (ret >= 0 && r < 0)
+ ret = r;
+
+ if (rem) {
+ r = cg_rmdir(controller, path, true);
+ if (r < 0 && ret >= 0 && r != -ENOENT && r != -EBUSY)
+ return r;
+ }
+
+ return ret;
+}
+
+int cg_kill_recursive_and_wait(const char *controller, const char *path, bool rem) {
+ unsigned i;
+
+ assert(path);
+
+ /* This safely kills all processes; first it sends a SIGTERM,
+ * then checks 8 times after 200ms whether the group is now
+ * empty, then kills everything that is left with SIGKILL and
+ * finally checks 5 times after 200ms each whether the group
+ * is finally empty. */
+
+ for (i = 0; i < 15; i++) {
+ int sig, r;
+
+ if (i <= 0)
+ sig = SIGTERM;
+ else if (i == 9)
+ sig = SIGKILL;
+ else
+ sig = 0;
+
+ r = cg_kill_recursive(controller, path, sig, true, true, rem, NULL);
+ if (r <= 0)
+ return r;
+
+ usleep(200 * USEC_PER_MSEC);
+ }
+
+ return 0;
+}
+
+int cg_migrate(const char *cfrom, const char *pfrom, const char *cto, const char *pto, bool ignore_self) {
+ bool done = false;
+ _cleanup_set_free_ Set *s = NULL;
+ int r, ret = 0;
+ pid_t my_pid;
+
+ assert(cfrom);
+ assert(pfrom);
+ assert(cto);
+ assert(pto);
+
+ s = set_new(trivial_hash_func, trivial_compare_func);
+ if (!s)
+ return -ENOMEM;
+
+ my_pid = getpid();
+
+ do {
+ _cleanup_fclose_ FILE *f = NULL;
+ pid_t pid = 0;
+ done = true;
+
+ r = cg_enumerate_tasks(cfrom, pfrom, &f);
+ if (r < 0) {
+ if (ret >= 0 && r != -ENOENT)
+ return r;
+
+ return ret;
+ }
+
+ while ((r = cg_read_pid(f, &pid)) > 0) {
+
+ /* This might do weird stuff if we aren't a
+ * single-threaded program. However, we
+ * luckily know we are not */
+ if (ignore_self && pid == my_pid)
+ continue;
+
+ if (set_get(s, LONG_TO_PTR(pid)) == LONG_TO_PTR(pid))
+ continue;
+
+ r = cg_attach(cto, pto, pid);
+ if (r < 0) {
+ if (ret >= 0 && r != -ESRCH)
+ ret = r;
+ } else if (ret == 0)
+ ret = 1;
+
+ done = false;
+
+ r = set_put(s, LONG_TO_PTR(pid));
+ if (r < 0) {
+ if (ret >= 0)
+ return r;
+
+ return ret;
+ }
+ }
+
+ if (r < 0) {
+ if (ret >= 0)
+ return r;
+
+ return ret;
+ }
+ } while (!done);
+
+ return ret;
+}
+
+int cg_migrate_recursive(const char *cfrom, const char *pfrom, const char *cto, const char *pto, bool ignore_self, bool rem) {
+ _cleanup_closedir_ DIR *d = NULL;
+ int r, ret = 0;
+ char *fn;
+
+ assert(cfrom);
+ assert(pfrom);
+ assert(cto);
+ assert(pto);
+
+ ret = cg_migrate(cfrom, pfrom, cto, pto, ignore_self);
+
+ r = cg_enumerate_subgroups(cfrom, pfrom, &d);
+ if (r < 0) {
+ if (ret >= 0 && r != -ENOENT)
+ return r;
+
+ return ret;
+ }
+
+ while ((r = cg_read_subgroup(d, &fn)) > 0) {
+ _cleanup_free_ char *p = NULL;
+
+ p = strjoin(pfrom, "/", fn, NULL);
+ free(fn);
+ if (!p) {
+ if (ret >= 0)
+ return -ENOMEM;
+
+ return ret;
+ }
+
+ r = cg_migrate_recursive(cfrom, p, cto, pto, ignore_self, rem);
+ if (r != 0 && ret >= 0)
+ ret = r;
+ }
+
+ if (r < 0 && ret >= 0)
+ ret = r;
+
+ if (rem) {
+ r = cg_rmdir(cfrom, pfrom, true);
+ if (r < 0 && ret >= 0 && r != -ENOENT && r != -EBUSY)
+ return r;
+ }
+
+ return ret;
+}
+
+static const char *normalize_controller(const char *controller) {
+
+ assert(controller);
+
+ if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
+ return "systemd";
+ else if (startswith(controller, "name="))
+ return controller + 5;
+ else
+ return controller;
+}
+
+static int join_path(const char *controller, const char *path, const char *suffix, char **fs) {
+ char *t = NULL;
+
+ if (controller) {
+ if (path && suffix)
+ t = strjoin("/sys/fs/cgroup/", controller, "/", path, "/", suffix, NULL);
+ else if (path)
+ t = strjoin("/sys/fs/cgroup/", controller, "/", path, NULL);
+ else if (suffix)
+ t = strjoin("/sys/fs/cgroup/", controller, "/", suffix, NULL);
+ else
+ t = strappend("/sys/fs/cgroup/", controller);
+ } else {
+ if (path && suffix)
+ t = strjoin(path, "/", suffix, NULL);
+ else if (path)
+ t = strdup(path);
+ else
+ return -EINVAL;
+ }
+
+ if (!t)
+ return -ENOMEM;
+
+ path_kill_slashes(t);
+
+ *fs = t;
+ return 0;
+}
+
+int cg_get_path(const char *controller, const char *path, const char *suffix, char **fs) {
+ const char *p;
+ static __thread bool good = false;
+
+ assert(fs);
+
+ if (controller && !cg_controller_is_valid(controller, true))
+ return -EINVAL;
+
+ if (_unlikely_(!good)) {
+ int r;
+
+ r = path_is_mount_point("/sys/fs/cgroup", false);
+ if (r <= 0)
+ return r < 0 ? r : -ENOENT;
+
+ /* Cache this to save a few stat()s */
+ good = true;
+ }
+
+ p = controller ? normalize_controller(controller) : NULL;
+
+ return join_path(p, path, suffix, fs);
+}
+
+static int check_hierarchy(const char *p) {
+ char *cc;
+
+ assert(p);
+
+ /* Check if this controller actually really exists */
+ cc = alloca(sizeof("/sys/fs/cgroup/") + strlen(p));
+ strcpy(stpcpy(cc, "/sys/fs/cgroup/"), p);
+ if (access(cc, F_OK) < 0)
+ return -errno;
+
+ return 0;
+}
+
+int cg_get_path_and_check(const char *controller, const char *path, const char *suffix, char **fs) {
+ const char *p;
+ int r;
+
+ assert(fs);
+
+ if (!cg_controller_is_valid(controller, true))
+ return -EINVAL;
+
+ /* Normalize the controller syntax */
+ p = normalize_controller(controller);
+
+ /* Check if this controller actually really exists */
+ r = check_hierarchy(p);
+ if (r < 0)
+ return r;
+
+ return join_path(p, path, suffix, fs);
+}
+
+static int trim_cb(const char *path, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
+ char *p;
+ bool is_sticky;
+
+ if (typeflag != FTW_DP)
+ return 0;
+
+ if (ftwbuf->level < 1)
+ return 0;
+
+ p = strappend(path, "/tasks");
+ if (!p) {
+ errno = ENOMEM;
+ return 1;
+ }
+
+ is_sticky = file_is_priv_sticky(p) > 0;
+ free(p);
+
+ if (is_sticky)
+ return 0;
+
+ rmdir(path);
+ return 0;
+}
+
+int cg_trim(const char *controller, const char *path, bool delete_root) {
+ _cleanup_free_ char *fs = NULL;
+ int r = 0;
+
+ assert(path);
+
+ r = cg_get_path(controller, path, NULL, &fs);
+ if (r < 0)
+ return r;
+
+ errno = 0;
+ if (nftw(fs, trim_cb, 64, FTW_DEPTH|FTW_MOUNT|FTW_PHYS) != 0)
+ r = errno ? -errno : -EIO;
+
+ if (delete_root) {
+ bool is_sticky;
+ char *p;
+
+ p = strappend(fs, "/tasks");
+ if (!p)
+ return -ENOMEM;
+
+ is_sticky = file_is_priv_sticky(p) > 0;
+ free(p);
+
+ if (!is_sticky)
+ if (rmdir(fs) < 0 && errno != ENOENT && r == 0)
+ return -errno;
+ }
+
+ return r;
+}
+
+int cg_delete(const char *controller, const char *path) {
+ _cleanup_free_ char *parent = NULL;
+ int r;
+
+ assert(path);
+
+ r = path_get_parent(path, &parent);
+ if (r < 0)
+ return r;
+
+ r = cg_migrate_recursive(controller, path, controller, parent, false, true);
+ return r == -ENOENT ? 0 : r;
+}
+
+int cg_attach(const char *controller, const char *path, pid_t pid) {
+ _cleanup_free_ char *fs = NULL;
+ char c[DECIMAL_STR_MAX(pid_t) + 2];
+ int r;
+
+ assert(path);
+ assert(pid >= 0);
+
+ r = cg_get_path_and_check(controller, path, "tasks", &fs);
+ if (r < 0)
+ return r;
+
+ if (pid == 0)
+ pid = getpid();
+
+ snprintf(c, sizeof(c), "%lu\n", (unsigned long) pid);
+
+ return write_string_file(fs, c);
+}
+
+int cg_set_group_access(
+ const char *controller,
+ const char *path,
+ mode_t mode,
+ uid_t uid,
+ gid_t gid) {
+
+ _cleanup_free_ char *fs = NULL;
+ int r;
+
+ assert(path);
+
+ if (mode != (mode_t) -1)
+ mode &= 0777;
+
+ r = cg_get_path(controller, path, NULL, &fs);
+ if (r < 0)
+ return r;
+
+ return chmod_and_chown(fs, mode, uid, gid);
+}
+
+int cg_set_task_access(
+ const char *controller,
+ const char *path,
+ mode_t mode,
+ uid_t uid,
+ gid_t gid,
+ int sticky) {
+
+ _cleanup_free_ char *fs = NULL, *procs = NULL;
+ int r;
+
+ assert(path);
+
+ if (mode == (mode_t) -1 && uid == (uid_t) -1 && gid == (gid_t) -1 && sticky < 0)
+ return 0;
+
+ if (mode != (mode_t) -1)
+ mode &= 0666;
+
+ r = cg_get_path(controller, path, "tasks", &fs);
+ if (r < 0)
+ return r;
+
+ if (sticky >= 0 && mode != (mode_t) -1)
+ /* Both mode and sticky param are passed */
+ mode |= (sticky ? S_ISVTX : 0);
+ else if ((sticky >= 0 && mode == (mode_t) -1) ||
+ (mode != (mode_t) -1 && sticky < 0)) {
+ struct stat st;
+
+ /* Only one param is passed, hence read the current
+ * mode from the file itself */
+
+ r = lstat(fs, &st);
+ if (r < 0)
+ return -errno;
+
+ if (mode == (mode_t) -1)
+ /* No mode set, we just shall set the sticky bit */
+ mode = (st.st_mode & ~S_ISVTX) | (sticky ? S_ISVTX : 0);
+ else
+ /* Only mode set, leave sticky bit untouched */
+ mode = (st.st_mode & ~0777) | mode;
+ }
+
+ r = chmod_and_chown(fs, mode, uid, gid);
+ if (r < 0)
+ return r;
+
+ /* Always keep values for "cgroup.procs" in sync with "tasks" */
+ r = cg_get_path(controller, path, "cgroup.procs", &procs);
+ if (r < 0)
+ return r;
+
+ return chmod_and_chown(procs, mode, uid, gid);
+}
+
+int cg_pid_get_path(const char *controller, pid_t pid, char **path) {
+ _cleanup_fclose_ FILE *f = NULL;
+ char line[LINE_MAX];
+ const char *fs;
+ size_t cs;
+
+ assert(path);
+ assert(pid >= 0);
+
+ if (controller) {
+ if (!cg_controller_is_valid(controller, true))
+ return -EINVAL;
+
+ controller = normalize_controller(controller);
+ } else
+ controller = SYSTEMD_CGROUP_CONTROLLER;
+
+ if (pid == 0)
+ fs = "/proc/self/cgroup";
+ else
+ fs = procfs_file_alloca(pid, "cgroup");
+
+ f = fopen(fs, "re");
+ if (!f)
+ return errno == ENOENT ? -ESRCH : -errno;
+
+ cs = strlen(controller);
+
+ FOREACH_LINE(line, f, return -errno) {
+ char *l, *p, *w, *e;
+ size_t k;
+ char *state;
+ bool found = false;
+
+ truncate_nl(line);
+
+ l = strchr(line, ':');
+ if (!l)
+ continue;
+
+ l++;
+ e = strchr(l, ':');
+ if (!e)
+ continue;
+
+ *e = 0;
+
+ FOREACH_WORD_SEPARATOR(w, k, l, ",", state) {
+
+ if (k == cs && memcmp(w, controller, cs) == 0) {
+ found = true;
+ break;
+ }
+
+ if (k == 5 + cs &&
+ memcmp(w, "name=", 5) == 0 &&
+ memcmp(w+5, controller, cs) == 0) {
+ found = true;
+ break;
+ }
+ }
+
+ if (!found)
+ continue;
+
+ p = strdup(e + 1);
+ if (!p)
+ return -ENOMEM;
+
+ *path = p;
+ return 0;
+ }
+
+ return -ENOENT;
+}
+
+int cg_install_release_agent(const char *controller, const char *agent) {
+ _cleanup_free_ char *fs = NULL, *contents = NULL;
+ char *sc;
+ int r;
+
+ assert(agent);
+
+ r = cg_get_path(controller, NULL, "release_agent", &fs);
+ if (r < 0)
+ return r;
+
+ r = read_one_line_file(fs, &contents);
+ if (r < 0)
+ return r;
+
+ sc = strstrip(contents);
+ if (sc[0] == 0) {
+ r = write_string_file(fs, agent);
+ if (r < 0)
+ return r;
+ } else if (!streq(sc, agent))
+ return -EEXIST;
+
+ free(fs);
+ fs = NULL;
+ r = cg_get_path(controller, NULL, "notify_on_release", &fs);
+ if (r < 0)
+ return r;
+
+ free(contents);
+ contents = NULL;
+ r = read_one_line_file(fs, &contents);
+ if (r < 0)
+ return r;
+
+ sc = strstrip(contents);
+ if (streq(sc, "0")) {
+ r = write_string_file(fs, "1");
+ if (r < 0)
+ return r;
+
+ return 1;
+ }
+
+ if (!streq(sc, "1"))
+ return -EIO;
+
+ return 0;
+}
+
+int cg_is_empty(const char *controller, const char *path, bool ignore_self) {
+ _cleanup_fclose_ FILE *f = NULL;
+ pid_t pid = 0, self_pid;
+ bool found = false;
+ int r;
+
+ assert(path);
+
+ r = cg_enumerate_tasks(controller, path, &f);
+ if (r < 0)
+ return r == -ENOENT ? 1 : r;
+
+ self_pid = getpid();
+
+ while ((r = cg_read_pid(f, &pid)) > 0) {
+
+ if (ignore_self && pid == self_pid)
+ continue;
+
+ found = true;
+ break;
+ }
+
+ if (r < 0)
+ return r;
+
+ return !found;
+}
+
+int cg_is_empty_by_spec(const char *spec, bool ignore_self) {
+ _cleanup_free_ char *controller = NULL, *path = NULL;
+ int r;
+
+ assert(spec);
+
+ r = cg_split_spec(spec, &controller, &path);
+ if (r < 0)
+ return r;
+
+ return cg_is_empty(controller, path, ignore_self);
+}
+
+int cg_is_empty_recursive(const char *controller, const char *path, bool ignore_self) {
+ _cleanup_closedir_ DIR *d = NULL;
+ char *fn;
+ int r;
+
+ assert(path);
+
+ r = cg_is_empty(controller, path, ignore_self);
+ if (r <= 0)
+ return r;
+
+ r = cg_enumerate_subgroups(controller, path, &d);
+ if (r < 0)
+ return r == -ENOENT ? 1 : r;
+
+ while ((r = cg_read_subgroup(d, &fn)) > 0) {
+ _cleanup_free_ char *p = NULL;
+
+ p = strjoin(path, "/", fn, NULL);
+ free(fn);
+ if (!p)
+ return -ENOMEM;
+
+ r = cg_is_empty_recursive(controller, p, ignore_self);
+ if (r <= 0)
+ return r;
+ }
+
+ if (r < 0)
+ return r;
+
+ return 1;
+}
+
+int cg_split_spec(const char *spec, char **controller, char **path) {
+ const char *e;
+ char *t = NULL, *u = NULL;
+ _cleanup_free_ char *v = NULL;
+
+ assert(spec);
+
+ if (*spec == '/') {
+ if (!path_is_safe(spec))
+ return -EINVAL;
+
+ if (path) {
+ t = strdup(spec);
+ if (!t)
+ return -ENOMEM;
+
+ path_kill_slashes(t);
+ *path = t;
+ }
+
+ if (controller)
+ *controller = NULL;
+
+ return 0;
+ }
+
+ e = strchr(spec, ':');
+ if (!e) {
+ if (!cg_controller_is_valid(spec, true))
+ return -EINVAL;
+
+ if (controller) {
+ t = strdup(normalize_controller(spec));
+ if (!t)
+ return -ENOMEM;
+
+ *controller = t;
+ }
+
+ if (path)
+ *path = NULL;
+
+ return 0;
+ }
+
+ v = strndup(spec, e-spec);
+ if (!v)
+ return -ENOMEM;
+ t = strdup(normalize_controller(v));
+ if (!t)
+ return -ENOMEM;
+ if (!cg_controller_is_valid(t, true)) {
+ free(t);
+ return -EINVAL;
+ }
+
+ u = strdup(e+1);
+ if (!u) {
+ free(t);
+ return -ENOMEM;
+ }
+ if (!path_is_safe(u) ||
+ !path_is_absolute(u)) {
+ free(t);
+ free(u);
+ return -EINVAL;
+ }
+
+ path_kill_slashes(u);
+
+ if (controller)
+ *controller = t;
+ else
+ free(t);
+
+ if (path)
+ *path = u;
+ else
+ free(u);
+
+ return 0;
+}
+
+int cg_join_spec(const char *controller, const char *path, char **spec) {
+ char *s;
+
+ assert(path);
+
+ if (!controller)
+ controller = "systemd";
+ else {
+ if (!cg_controller_is_valid(controller, true))
+ return -EINVAL;
+
+ controller = normalize_controller(controller);
+ }
+
+ if (!path_is_absolute(path))
+ return -EINVAL;
+
+ s = strjoin(controller, ":", path, NULL);
+ if (!s)
+ return -ENOMEM;
+
+ path_kill_slashes(s + strlen(controller) + 1);
+
+ *spec = s;
+ return 0;
+}
+
+int cg_mangle_path(const char *path, char **result) {
+ _cleanup_free_ char *c = NULL, *p = NULL;
+ char *t;
+ int r;
+
+ assert(path);
+ assert(result);
+
+ /* First check if it already is a filesystem path */
+ if (path_startswith(path, "/sys/fs/cgroup")) {
+
+ t = strdup(path);
+ if (!t)
+ return -ENOMEM;
+
+ path_kill_slashes(t);
+ *result = t;
+ return 0;
+ }
+
+ /* Otherwise treat it as cg spec */
+ r = cg_split_spec(path, &c, &p);
+ if (r < 0)
+ return r;
+
+ return cg_get_path(c ? c : SYSTEMD_CGROUP_CONTROLLER, p ? p : "/", NULL, result);
+}
+
+int cg_get_system_path(char **path) {
+ char *p;
+ int r;
+
+ assert(path);
+
+ r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &p);
+ if (r < 0) {
+ p = strdup("/system");
+ if (!p)
+ return -ENOMEM;
+ }
+
+ if (endswith(p, "/system"))
+ *path = p;
+ else {
+ char *q;
+
+ q = strappend(p, "/system");
+ free(p);
+ if (!q)
+ return -ENOMEM;
+
+ *path = q;
+ }
+
+ return 0;
+}
+
+int cg_get_root_path(char **path) {
+ char *root, *e;
+ int r;
+
+ assert(path);
+
+ r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &root);
+ if (r < 0)
+ return r;
+
+ e = endswith(root, "/system");
+ if (e == root)
+ e[1] = 0;
+ else if (e)
+ *e = 0;
+
+ *path = root;
+ return 0;
+}
+
+int cg_get_user_path(char **path) {
+ _cleanup_free_ char *root = NULL;
+ char *p;
+
+ assert(path);
+
+ /* Figure out the place to put user cgroups below. We use the
+ * same as PID 1 has but with the "/system" suffix replaced by
+ * "/user" */
+
+ if (cg_get_root_path(&root) < 0 || streq(root, "/"))
+ p = strdup("/user");
+ else
+ p = strappend(root, "/user");
+
+ if (!p)
+ return -ENOMEM;
+
+ *path = p;
+ return 0;
+}
+
+int cg_get_machine_path(const char *machine, char **path) {
+ _cleanup_free_ char *root = NULL, *escaped = NULL;
+ char *p;
+
+ assert(path);
+
+ if (machine) {
+ const char *name = strappenda(machine, ".nspawn");
+
+ escaped = cg_escape(name);
+ if (!escaped)
+ return -ENOMEM;
+ }
+
+ p = strjoin(cg_get_root_path(&root) >= 0 && !streq(root, "/") ? root : "",
+ "/machine", machine ? "/" : "", machine ? escaped : "", NULL);
+ if (!p)
+ return -ENOMEM;
+
+ *path = p;
+ return 0;
+}
+
+char **cg_shorten_controllers(char **controllers) {
+ char **f, **t;
+
+ if (!controllers)
+ return controllers;
+
+ for (f = controllers, t = controllers; *f; f++) {
+ const char *p;
+ int r;
+
+ p = normalize_controller(*f);
+
+ if (streq(p, "systemd")) {
+ free(*f);
+ continue;
+ }
+
+ if (!cg_controller_is_valid(p, true)) {
+ log_warning("Controller %s is not valid, removing from controllers list.", p);
+ free(*f);
+ continue;
+ }
+
+ r = check_hierarchy(p);
+ if (r < 0) {
+ log_debug("Controller %s is not available, removing from controllers list.", p);
+ free(*f);
+ continue;
+ }
+
+ *(t++) = *f;
+ }
+
+ *t = NULL;
+ return strv_uniq(controllers);
+}
+
+int cg_pid_get_path_shifted(pid_t pid, char **root, char **cgroup) {
+ _cleanup_free_ char *cg_root = NULL;
+ char *cg_process, *p;
+ int r;
+
+ r = cg_get_root_path(&cg_root);
+ if (r < 0)
+ return r;
+
+ r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &cg_process);
+ if (r < 0)
+ return r;
+
+ p = path_startswith(cg_process, cg_root);
+ if (p)
+ p--;
+ else
+ p = cg_process;
+
+ if (cgroup) {
+ char* c;
+
+ c = strdup(p);
+ if (!c) {
+ free(cg_process);
+ return -ENOMEM;
+ }
+
+ *cgroup = c;
+ }
+
+ if (root) {
+ cg_process[p-cg_process] = 0;
+ *root = cg_process;
+ } else
+ free(cg_process);
+
+ return 0;
+}
+
+int cg_path_decode_unit(const char *cgroup, char **unit){
+ char *p, *e, *c, *s, *k;
+
+ assert(cgroup);
+ assert(unit);
+
+ e = strchrnul(cgroup, '/');
+ c = strndupa(cgroup, e - cgroup);
+ c = cg_unescape(c);
+
+ /* Could this be a valid unit name? */
+ if (!unit_name_is_valid(c, true))
+ return -EINVAL;
+
+ if (!unit_name_is_template(c))
+ s = strdup(c);
+ else {
+ if (*e != '/')
+ return -EINVAL;
+
+ e += strspn(e, "/");
+
+ p = strchrnul(e, '/');
+ k = strndupa(e, p - e);
+ k = cg_unescape(k);
+
+ if (!unit_name_is_valid(k, false))
+ return -EINVAL;
+
+ s = strdup(k);
+ }
+
+ if (!s)
+ return -ENOMEM;
+
+ *unit = s;
+ return 0;
+}
+
+int cg_path_get_unit(const char *path, char **unit) {
+ const char *e;
+
+ assert(path);
+ assert(unit);
+
+ e = path_startswith(path, "/system/");
+ if (!e)
+ return -ENOENT;
+
+ return cg_path_decode_unit(e, unit);
+}
+
+int cg_pid_get_unit(pid_t pid, char **unit) {
+ _cleanup_free_ char *cgroup = NULL;
+ int r;
+
+ assert(unit);
+
+ r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
+ if (r < 0)
+ return r;
+
+ return cg_path_get_unit(cgroup, unit);
+}
+
+_pure_ static const char *skip_label(const char *e) {
+ assert(e);
+
+ e = strchr(e, '/');
+ if (!e)
+ return NULL;
+
+ e += strspn(e, "/");
+ return e;
+}
+
+int cg_path_get_user_unit(const char *path, char **unit) {
+ const char *e;
+
+ assert(path);
+ assert(unit);
+
+ /* We always have to parse the path from the beginning as unit
+ * cgroups might have arbitrary child cgroups and we shouldn't get
+ * confused by those */
+
+ e = path_startswith(path, "/user/");
+ if (!e)
+ return -ENOENT;
+
+ /* Skip the user name */
+ e = skip_label(e);
+ if (!e)
+ return -ENOENT;
+
+ /* Skip the session ID */
+ e = skip_label(e);
+ if (!e)
+ return -ENOENT;
+
+ /* Skip the systemd cgroup */
+ e = skip_label(e);
+ if (!e)
+ return -ENOENT;
+
+ return cg_path_decode_unit(e, unit);
+}
+
+int cg_pid_get_user_unit(pid_t pid, char **unit) {
+ _cleanup_free_ char *cgroup = NULL;
+ int r;
+
+ assert(unit);
+
+ r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
+ if (r < 0)
+ return r;
+
+ return cg_path_get_user_unit(cgroup, unit);
+}
+
+int cg_path_get_machine_name(const char *path, char **machine) {
+ const char *e, *n;
+ char *s, *r;
+
+ assert(path);
+ assert(machine);
+
+ e = path_startswith(path, "/machine/");
+ if (!e)
+ return -ENOENT;
+
+ n = strchrnul(e, '/');
+ if (e == n)
+ return -ENOENT;
+
+ s = strndupa(e, n - e);
+
+ r = strdup(cg_unescape(s));
+ if (!r)
+ return -ENOMEM;
+
+ *machine = r;
+ return 0;
+}
+
+int cg_pid_get_machine_name(pid_t pid, char **machine) {
+ _cleanup_free_ char *cgroup = NULL;
+ int r;
+
+ assert(machine);
+
+ r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
+ if (r < 0)
+ return r;
+
+ return cg_path_get_machine_name(cgroup, machine);
+}
+
+int cg_path_get_session(const char *path, char **session) {
+ const char *e, *n;
+ char *s;
+
+ assert(path);
+ assert(session);
+
+ e = path_startswith(path, "/user/");
+ if (!e)
+ return -ENOENT;
+
+ /* Skip the user name */
+ e = skip_label(e);
+ if (!e)
+ return -ENOENT;
+
+ n = strchrnul(e, '/');
+ if (n - e < 8)
+ return -ENOENT;
+ if (memcmp(n - 8, ".session", 8) != 0)
+ return -ENOENT;
+
+ s = strndup(e, n - e - 8);
+ if (!s)
+ return -ENOMEM;
+
+ *session = s;
+ return 0;
+}
+
+int cg_pid_get_session(pid_t pid, char **session) {
+ _cleanup_free_ char *cgroup = NULL;
+ int r;
+
+ assert(session);
+
+ r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
+ if (r < 0)
+ return r;
+
+ return cg_path_get_session(cgroup, session);
+}
+
+int cg_path_get_owner_uid(const char *path, uid_t *uid) {
+ const char *e, *n;
+ char *s;
+
+ assert(path);
+ assert(uid);
+
+ e = path_startswith(path, "/user/");
+ if (!e)
+ return -ENOENT;
+
+ n = strchrnul(e, '/');
+ if (n - e < 5)
+ return -ENOENT;
+ if (memcmp(n - 5, ".user", 5) != 0)
+ return -ENOENT;
+
+ s = strndupa(e, n - e - 5);
+ if (!s)
+ return -ENOMEM;
+
+ return parse_uid(s, uid);
+}
+
+int cg_pid_get_owner_uid(pid_t pid, uid_t *uid) {
+ _cleanup_free_ char *cgroup = NULL;
+ int r;
+
+ assert(uid);
+
+ r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
+ if (r < 0)
+ return r;
+
+ return cg_path_get_owner_uid(cgroup, uid);
+}
+
+int cg_controller_from_attr(const char *attr, char **controller) {
+ const char *dot;
+ char *c;
+
+ assert(attr);
+ assert(controller);
+
+ if (!filename_is_safe(attr))
+ return -EINVAL;
+
+ dot = strchr(attr, '.');
+ if (!dot) {
+ *controller = NULL;
+ return 0;
+ }
+
+ c = strndup(attr, dot - attr);
+ if (!c)
+ return -ENOMEM;
+
+ if (!cg_controller_is_valid(c, false)) {
+ free(c);
+ return -EINVAL;
+ }
+
+ *controller = c;
+ return 1;
+}
+
+char *cg_escape(const char *p) {
+ bool need_prefix = false;
+
+ /* This implements very minimal escaping for names to be used
+ * as file names in the cgroup tree: any name which might
+ * conflict with a kernel name or is prefixed with '_' is
+ * prefixed with a '_'. That way, when reading cgroup names it
+ * is sufficient to remove a single prefixing underscore if
+ * there is one. */
+
+ /* The return value of this function (unlike cg_unescape())
+ * needs free()! */
+
+ if (p[0] == 0 ||
+ p[0] == '_' ||
+ p[0] == '.' ||
+ streq(p, "notify_on_release") ||
+ streq(p, "release_agent") ||
+ streq(p, "tasks"))
+ need_prefix = true;
+ else {
+ const char *dot;
+
+ dot = strrchr(p, '.');
+ if (dot) {
+
+ if (dot - p == 6 && memcmp(p, "cgroup", 6) == 0)
+ need_prefix = true;
+ else {
+ char *n;
+
+ n = strndupa(p, dot - p);
+
+ if (check_hierarchy(n) >= 0)
+ need_prefix = true;
+ }
+ }
+ }
+
+ if (need_prefix)
+ return strappend("_", p);
+ else
+ return strdup(p);
+}
+
+char *cg_unescape(const char *p) {
+ assert(p);
+
+ /* The return value of this function (unlike cg_escape())
+ * doesn't need free()! */
+
+ if (p[0] == '_')
+ return (char*) p+1;
+
+ return (char*) p;
+}
+
+#define CONTROLLER_VALID \
+ "0123456789" \
+ "abcdefghijklmnopqrstuvwxyz" \
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
+ "_"
+
+bool cg_controller_is_valid(const char *p, bool allow_named) {
+ const char *t, *s;
+
+ if (!p)
+ return false;
+
+ if (allow_named) {
+ s = startswith(p, "name=");
+ if (s)
+ p = s;
+ }
+
+ if (*p == 0 || *p == '_')
+ return false;
+
+ for (t = p; *t; t++)
+ if (!strchr(CONTROLLER_VALID, *t))
+ return false;
+
+ if (t - p > FILENAME_MAX)
+ return false;
+
+ return true;
+}
diff --git a/src/shared/cgroup-util.h b/src/shared/cgroup-util.h
new file mode 100644
index 0000000000..25dd277ba5
--- /dev/null
+++ b/src/shared/cgroup-util.h
@@ -0,0 +1,115 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/types.h>
+#include <stdio.h>
+#include <dirent.h>
+
+#include "set.h"
+#include "def.h"
+
+/*
+ * General rules:
+ *
+ * We accept named hierarchies in the syntax "foo" and "name=foo".
+ *
+ * We expect that named hierarchies do not conflict in name with a
+ * kernel hierarchy, modulo the "name=" prefix.
+ *
+ * We always generate "normalized" controller names, i.e. without the
+ * "name=" prefix.
+ *
+ * We require absolute cgroup paths. When returning, we will always
+ * generate paths with multiple adjacent / removed.
+ */
+
+int cg_enumerate_processes(const char *controller, const char *path, FILE **_f);
+int cg_enumerate_tasks(const char *controller, const char *path, FILE **_f);
+int cg_read_pid(FILE *f, pid_t *_pid);
+
+int cg_enumerate_subgroups(const char *controller, const char *path, DIR **_d);
+int cg_read_subgroup(DIR *d, char **fn);
+
+int cg_kill(const char *controller, const char *path, int sig, bool sigcont, bool ignore_self, Set *s);
+int cg_kill_recursive(const char *controller, const char *path, int sig, bool sigcont, bool ignore_self, bool remove, Set *s);
+int cg_kill_recursive_and_wait(const char *controller, const char *path, bool remove);
+
+int cg_migrate(const char *cfrom, const char *pfrom, const char *cto, const char *pto, bool ignore_self);
+int cg_migrate_recursive(const char *cfrom, const char *pfrom, const char *cto, const char *pto, bool ignore_self, bool remove);
+
+int cg_split_spec(const char *spec, char **controller, char **path);
+int cg_join_spec(const char *controller, const char *path, char **spec);
+int cg_mangle_path(const char *path, char **result);
+
+int cg_get_path(const char *controller, const char *path, const char *suffix, char **fs);
+int cg_get_path_and_check(const char *controller, const char *path, const char *suffix, char **fs);
+
+int cg_pid_get_path(const char *controller, pid_t pid, char **path);
+
+int cg_trim(const char *controller, const char *path, bool delete_root);
+
+int cg_rmdir(const char *controller, const char *path, bool honour_sticky);
+int cg_delete(const char *controller, const char *path);
+
+int cg_create(const char *controller, const char *path, const char *suffix);
+int cg_attach(const char *controller, const char *path, pid_t pid);
+int cg_create_and_attach(const char *controller, const char *path, pid_t pid);
+
+int cg_set_group_access(const char *controller, const char *path, mode_t mode, uid_t uid, gid_t gid);
+int cg_set_task_access(const char *controller, const char *path, mode_t mode, uid_t uid, gid_t gid, int sticky);
+
+int cg_install_release_agent(const char *controller, const char *agent);
+
+int cg_is_empty(const char *controller, const char *path, bool ignore_self);
+int cg_is_empty_by_spec(const char *spec, bool ignore_self);
+int cg_is_empty_recursive(const char *controller, const char *path, bool ignore_self);
+
+int cg_get_root_path(char **path);
+int cg_get_system_path(char **path);
+int cg_get_user_path(char **path);
+int cg_get_machine_path(const char *machine, char **path);
+
+int cg_path_get_session(const char *path, char **session);
+int cg_path_get_owner_uid(const char *path, uid_t *uid);
+int cg_path_get_unit(const char *path, char **unit);
+int cg_path_get_user_unit(const char *path, char **unit);
+int cg_path_get_machine_name(const char *path, char **machine);
+
+int cg_pid_get_path_shifted(pid_t pid, char **root, char **cgroup);
+
+int cg_pid_get_session(pid_t pid, char **session);
+int cg_pid_get_owner_uid(pid_t pid, uid_t *uid);
+int cg_pid_get_unit(pid_t pid, char **unit);
+int cg_pid_get_user_unit(pid_t pid, char **unit);
+int cg_pid_get_machine_name(pid_t pid, char **machine);
+
+int cg_path_decode_unit(const char *cgroup, char **unit);
+
+char **cg_shorten_controllers(char **controllers);
+
+int cg_controller_from_attr(const char *attr, char **controller);
+
+char *cg_escape(const char *p);
+char *cg_unescape(const char *p) _pure_;
+
+bool cg_controller_is_valid(const char *p, bool allow_named);
diff --git a/src/shared/conf-files.c b/src/shared/conf-files.c
new file mode 100644
index 0000000000..6d99739353
--- /dev/null
+++ b/src/shared/conf-files.c
@@ -0,0 +1,178 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <sys/stat.h>
+#include <dirent.h>
+
+#include "macro.h"
+#include "util.h"
+#include "missing.h"
+#include "log.h"
+#include "strv.h"
+#include "path-util.h"
+#include "hashmap.h"
+#include "conf-files.h"
+
+static int files_add(Hashmap *h, const char *root, const char *path, const char *suffix) {
+ _cleanup_closedir_ DIR *dir = NULL;
+ _cleanup_free_ char *dirpath = NULL;
+
+ if (asprintf(&dirpath, "%s%s", root ? root : "", path) < 0)
+ return -ENOMEM;
+
+ dir = opendir(dirpath);
+ if (!dir) {
+ if (errno == ENOENT)
+ return 0;
+ return -errno;
+ }
+
+ for (;;) {
+ struct dirent *de;
+ union dirent_storage buf;
+ char *p;
+ int r;
+
+ r = readdir_r(dir, &buf.de, &de);
+ if (r != 0)
+ return -r;
+
+ if (!de)
+ break;
+
+ if (!dirent_is_file_with_suffix(de, suffix))
+ continue;
+
+ p = strjoin(dirpath, "/", de->d_name, NULL);
+ if (!p)
+ return -ENOMEM;
+
+ r = hashmap_put(h, path_get_file_name(p), p);
+ if (r == -EEXIST) {
+ log_debug("Skipping overridden file: %s.", p);
+ free(p);
+ } else if (r < 0) {
+ free(p);
+ return r;
+ } else if (r == 0) {
+ log_debug("Duplicate file %s", p);
+ free(p);
+ }
+ }
+
+ return 0;
+}
+
+static int base_cmp(const void *a, const void *b) {
+ const char *s1, *s2;
+
+ s1 = *(char * const *)a;
+ s2 = *(char * const *)b;
+ return strcmp(path_get_file_name(s1), path_get_file_name(s2));
+}
+
+static int conf_files_list_strv_internal(char ***strv, const char *suffix, const char *root, char **dirs) {
+ Hashmap *fh;
+ char **files, **p;
+ int r;
+
+ assert(strv);
+ assert(suffix);
+
+ /* This alters the dirs string array */
+ if (!path_strv_canonicalize_uniq(dirs))
+ return -ENOMEM;
+
+ fh = hashmap_new(string_hash_func, string_compare_func);
+ if (!fh)
+ return -ENOMEM;
+
+ STRV_FOREACH(p, dirs) {
+ r = files_add(fh, root, *p, suffix);
+ if (r == -ENOMEM) {
+ hashmap_free_free(fh);
+ return r;
+ } else if (r < 0)
+ log_debug("Failed to search for files in %s: %s",
+ *p, strerror(-r));
+ }
+
+ files = hashmap_get_strv(fh);
+ if (files == NULL) {
+ hashmap_free_free(fh);
+ return -ENOMEM;
+ }
+
+ qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);
+ *strv = files;
+
+ hashmap_free(fh);
+ return 0;
+}
+
+int conf_files_list_strv(char ***strv, const char *suffix, const char *root, const char* const* dirs) {
+ _cleanup_strv_free_ char **copy = NULL;
+
+ assert(strv);
+ assert(suffix);
+
+ copy = strv_copy((char**) dirs);
+ if (!copy)
+ return -ENOMEM;
+
+ return conf_files_list_strv_internal(strv, suffix, root, copy);
+}
+
+int conf_files_list(char ***strv, const char *suffix, const char *root, const char *dir, ...) {
+ _cleanup_strv_free_ char **dirs = NULL;
+ va_list ap;
+
+ assert(strv);
+ assert(suffix);
+
+ va_start(ap, dir);
+ dirs = strv_new_ap(dir, ap);
+ va_end(ap);
+
+ if (!dirs)
+ return -ENOMEM;
+
+ return conf_files_list_strv_internal(strv, suffix, root, dirs);
+}
+
+int conf_files_list_nulstr(char ***strv, const char *suffix, const char *root, const char *d) {
+ _cleanup_strv_free_ char **dirs = NULL;
+
+ assert(strv);
+ assert(suffix);
+
+ dirs = strv_split_nulstr(d);
+ if (!dirs)
+ return -ENOMEM;
+
+ return conf_files_list_strv_internal(strv, suffix, root, dirs);
+}
diff --git a/src/shared/conf-files.h b/src/shared/conf-files.h
new file mode 100644
index 0000000000..3bd3d2f3d4
--- /dev/null
+++ b/src/shared/conf-files.h
@@ -0,0 +1,32 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef fooconffileshfoo
+#define fooconffileshfoo
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010-2012 Lennart Poettering
+ Copyright 2010-2012 Kay Sievers
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "macro.h"
+
+int conf_files_list(char ***strv, const char *suffix, const char *root, const char *dir, ...);
+int conf_files_list_strv(char ***strv, const char *suffix, const char *root, const char* const* dirs);
+int conf_files_list_nulstr(char ***strv, const char *suffix, const char *root, const char *dirs);
+
+#endif
diff --git a/src/shared/conf-parser.c b/src/shared/conf-parser.c
new file mode 100644
index 0000000000..2303d9a50b
--- /dev/null
+++ b/src/shared/conf-parser.c
@@ -0,0 +1,920 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <string.h>
+#include <stdio.h>
+#include <errno.h>
+#include <assert.h>
+#include <stdlib.h>
+
+#include "conf-parser.h"
+#include "util.h"
+#include "macro.h"
+#include "strv.h"
+#include "log.h"
+#include "utf8.h"
+#include "path-util.h"
+#include "set.h"
+#include "exit-status.h"
+#include "sd-messages.h"
+
+int log_syntax_internal(const char *unit, int level,
+ const char *file, unsigned line, const char *func,
+ const char *config_file, unsigned config_line,
+ int error, const char *format, ...) {
+
+ _cleanup_free_ char *msg = NULL;
+ int r;
+ va_list ap;
+
+ va_start(ap, format);
+ r = vasprintf(&msg, format, ap);
+ va_end(ap);
+ if (r < 0)
+ return log_oom();
+
+ if (unit)
+ r = log_struct_internal(level,
+ file, line, func,
+ getpid() == 1 ? "UNIT=%s" : "USER_UNIT=%s", unit,
+ MESSAGE_ID(SD_MESSAGE_CONFIG_ERROR),
+ "CONFIG_FILE=%s", config_file,
+ "CONFIG_LINE=%u", config_line,
+ "ERRNO=%d", error > 0 ? error : EINVAL,
+ "MESSAGE=[%s:%u] %s", config_file, config_line, msg,
+ NULL);
+ else
+ r = log_struct_internal(level,
+ file, line, func,
+ MESSAGE_ID(SD_MESSAGE_CONFIG_ERROR),
+ "CONFIG_FILE=%s", config_file,
+ "CONFIG_LINE=%u", config_line,
+ "ERRNO=%d", error > 0 ? error : EINVAL,
+ "MESSAGE=[%s:%u] %s", config_file, config_line, msg,
+ NULL);
+
+ return r;
+}
+
+int config_item_table_lookup(
+ void *table,
+ const char *section,
+ const char *lvalue,
+ ConfigParserCallback *func,
+ int *ltype,
+ void **data,
+ void *userdata) {
+
+ ConfigTableItem *t;
+
+ assert(table);
+ assert(lvalue);
+ assert(func);
+ assert(ltype);
+ assert(data);
+
+ for (t = table; t->lvalue; t++) {
+
+ if (!streq(lvalue, t->lvalue))
+ continue;
+
+ if (!streq_ptr(section, t->section))
+ continue;
+
+ *func = t->parse;
+ *ltype = t->ltype;
+ *data = t->data;
+ return 1;
+ }
+
+ return 0;
+}
+
+int config_item_perf_lookup(
+ void *table,
+ const char *section,
+ const char *lvalue,
+ ConfigParserCallback *func,
+ int *ltype,
+ void **data,
+ void *userdata) {
+
+ ConfigPerfItemLookup lookup = (ConfigPerfItemLookup) table;
+ const ConfigPerfItem *p;
+
+ assert(table);
+ assert(lvalue);
+ assert(func);
+ assert(ltype);
+ assert(data);
+
+ if (!section)
+ p = lookup(lvalue, strlen(lvalue));
+ else {
+ char *key;
+
+ key = strjoin(section, ".", lvalue, NULL);
+ if (!key)
+ return -ENOMEM;
+
+ p = lookup(key, strlen(key));
+ free(key);
+ }
+
+ if (!p)
+ return 0;
+
+ *func = p->parse;
+ *ltype = p->ltype;
+ *data = (uint8_t*) userdata + p->offset;
+ return 1;
+}
+
+/* Run the user supplied parser for an assignment */
+static int next_assignment(const char *unit,
+ const char *filename,
+ unsigned line,
+ ConfigItemLookup lookup,
+ void *table,
+ const char *section,
+ const char *lvalue,
+ const char *rvalue,
+ bool relaxed,
+ void *userdata) {
+
+ ConfigParserCallback func = NULL;
+ int ltype = 0;
+ void *data = NULL;
+ int r;
+
+ assert(filename);
+ assert(line > 0);
+ assert(lookup);
+ assert(lvalue);
+ assert(rvalue);
+
+ r = lookup(table, section, lvalue, &func, &ltype, &data, userdata);
+ if (r < 0)
+ return r;
+
+ if (r > 0) {
+ if (func)
+ return func(unit, filename, line, section, lvalue, ltype,
+ rvalue, data, userdata);
+
+ return 0;
+ }
+
+ /* Warn about unknown non-extension fields. */
+ if (!relaxed && !startswith(lvalue, "X-"))
+ log_syntax(unit, LOG_WARNING, filename, line, EINVAL,
+ "Unknown lvalue '%s' in section '%s'", lvalue, section);
+
+ return 0;
+}
+
+/* Parse a variable assignment line */
+static int parse_line(const char* unit,
+ const char *filename,
+ unsigned line,
+ const char *sections,
+ ConfigItemLookup lookup,
+ void *table,
+ bool relaxed,
+ bool allow_include,
+ char **section,
+ char *l,
+ void *userdata) {
+
+ char *e;
+
+ assert(filename);
+ assert(line > 0);
+ assert(lookup);
+ assert(l);
+
+ l = strstrip(l);
+
+ if (!*l)
+ return 0;
+
+ if (strchr(COMMENTS "\n", *l))
+ return 0;
+
+ if (startswith(l, ".include ")) {
+ _cleanup_free_ char *fn = NULL;
+
+ if (!allow_include) {
+ log_syntax(unit, LOG_ERR, filename, line, EBADMSG,
+ ".include not allowed here. Ignoring.");
+ return 0;
+ }
+
+ fn = file_in_same_dir(filename, strstrip(l+9));
+ if (!fn)
+ return -ENOMEM;
+
+ return config_parse(unit, fn, NULL, sections, lookup, table, relaxed, false, userdata);
+ }
+
+ if (*l == '[') {
+ size_t k;
+ char *n;
+
+ k = strlen(l);
+ assert(k > 0);
+
+ if (l[k-1] != ']') {
+ log_syntax(unit, LOG_ERR, filename, line, EBADMSG,
+ "Invalid section header '%s'", l);
+ return -EBADMSG;
+ }
+
+ n = strndup(l+1, k-2);
+ if (!n)
+ return -ENOMEM;
+
+ if (sections && !nulstr_contains(sections, n)) {
+
+ if (!relaxed)
+ log_syntax(unit, LOG_WARNING, filename, line, EINVAL,
+ "Unknown section '%s'. Ignoring.", n);
+
+ free(n);
+ *section = NULL;
+ } else {
+ free(*section);
+ *section = n;
+ }
+
+ return 0;
+ }
+
+ if (sections && !*section) {
+
+ if (!relaxed)
+ log_syntax(unit, LOG_WARNING, filename, line, EINVAL,
+ "Assignment outside of section. Ignoring.");
+
+ return 0;
+ }
+
+ e = strchr(l, '=');
+ if (!e) {
+ log_syntax(unit, LOG_WARNING, filename, line, EINVAL, "Missing '='.");
+ return -EBADMSG;
+ }
+
+ *e = 0;
+ e++;
+
+ return next_assignment(unit,
+ filename,
+ line,
+ lookup,
+ table,
+ *section,
+ strstrip(l),
+ strstrip(e),
+ relaxed,
+ userdata);
+}
+
+/* Go through the file and parse each line */
+int config_parse(const char *unit,
+ const char *filename,
+ FILE *f,
+ const char *sections,
+ ConfigItemLookup lookup,
+ void *table,
+ bool relaxed,
+ bool allow_include,
+ void *userdata) {
+
+ _cleanup_free_ char *section = NULL, *continuation = NULL;
+ _cleanup_fclose_ FILE *ours = NULL;
+ unsigned line = 0;
+ int r;
+
+ assert(filename);
+ assert(lookup);
+
+ if (!f) {
+ f = ours = fopen(filename, "re");
+ if (!f) {
+ log_error("Failed to open configuration file '%s': %m", filename);
+ return -errno;
+ }
+ }
+
+ while (!feof(f)) {
+ char l[LINE_MAX], *p, *c = NULL, *e;
+ bool escaped = false;
+
+ if (!fgets(l, sizeof(l), f)) {
+ if (feof(f))
+ break;
+
+ log_error("Failed to read configuration file '%s': %m", filename);
+ return -errno;
+ }
+
+ truncate_nl(l);
+
+ if (continuation) {
+ c = strappend(continuation, l);
+ if (!c)
+ return -ENOMEM;
+
+ free(continuation);
+ continuation = NULL;
+ p = c;
+ } else
+ p = l;
+
+ for (e = p; *e; e++) {
+ if (escaped)
+ escaped = false;
+ else if (*e == '\\')
+ escaped = true;
+ }
+
+ if (escaped) {
+ *(e-1) = ' ';
+
+ if (c)
+ continuation = c;
+ else {
+ continuation = strdup(l);
+ if (!continuation)
+ return -ENOMEM;
+ }
+
+ continue;
+ }
+
+ r = parse_line(unit,
+ filename,
+ ++line,
+ sections,
+ lookup,
+ table,
+ relaxed,
+ allow_include,
+ &section,
+ p,
+ userdata);
+ free(c);
+
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+#define DEFINE_PARSER(type, vartype, conv_func) \
+ int config_parse_##type(const char *unit, \
+ const char *filename, \
+ unsigned line, \
+ const char *section, \
+ const char *lvalue, \
+ int ltype, \
+ const char *rvalue, \
+ void *data, \
+ void *userdata) { \
+ \
+ vartype *i = data; \
+ int r; \
+ \
+ assert(filename); \
+ assert(lvalue); \
+ assert(rvalue); \
+ assert(data); \
+ \
+ r = conv_func(rvalue, i); \
+ if (r < 0) \
+ log_syntax(unit, LOG_ERR, filename, line, -r, \
+ "Failed to parse %s value, ignoring: %s", \
+ #vartype, rvalue); \
+ \
+ return 0; \
+ }
+
+DEFINE_PARSER(int, int, safe_atoi)
+DEFINE_PARSER(long, long, safe_atoli)
+DEFINE_PARSER(uint64, uint64_t, safe_atou64)
+DEFINE_PARSER(unsigned, unsigned, safe_atou)
+DEFINE_PARSER(double, double, safe_atod)
+DEFINE_PARSER(nsec, nsec_t, parse_nsec)
+DEFINE_PARSER(sec, usec_t, parse_sec)
+
+
+int config_parse_bytes_size(const char* unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ size_t *sz = data;
+ off_t o;
+ int r;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ r = parse_bytes(rvalue, &o);
+ if (r < 0 || (off_t) (size_t) o != o) {
+ log_syntax(unit, LOG_ERR, filename, line, -r,
+ "Failed to parse byte value, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ *sz = (size_t) o;
+ return 0;
+}
+
+
+int config_parse_bytes_off(const char* unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ off_t *bytes = data;
+ int r;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ assert_cc(sizeof(off_t) == sizeof(uint64_t));
+
+ r = parse_bytes(rvalue, bytes);
+ if (r < 0)
+ log_syntax(unit, LOG_ERR, filename, line, -r,
+ "Failed to parse bytes value, ignoring: %s", rvalue);
+
+ return 0;
+}
+
+int config_parse_bool(const char* unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ int k;
+ bool *b = data;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ k = parse_boolean(rvalue);
+ if (k < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, -k,
+ "Failed to parse boolean value, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ *b = !!k;
+ return 0;
+}
+
+int config_parse_tristate(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ int k;
+ int *b = data;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ /* Tristates are like booleans, but can also take the 'default' value, i.e. "-1" */
+
+ k = parse_boolean(rvalue);
+ if (k < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, -k,
+ "Failed to parse boolean value, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ *b = !!k;
+ return 0;
+}
+
+int config_parse_string(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ char **s = data;
+ char *n;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ n = strdup(rvalue);
+ if (!n)
+ return log_oom();
+
+ if (!utf8_is_valid(n)) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "String is not UTF-8 clean, ignoring assignment: %s", rvalue);
+ free(n);
+ return 0;
+ }
+
+ free(*s);
+ if (*n)
+ *s = n;
+ else {
+ free(n);
+ *s = NULL;
+ }
+
+ return 0;
+}
+
+int config_parse_path(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ char **s = data;
+ char *n;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ if (!utf8_is_valid(rvalue)) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Path is not UTF-8 clean, ignoring assignment: %s", rvalue);
+ return 0;
+ }
+
+ if (!path_is_absolute(rvalue)) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Not an absolute path, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ n = strdup(rvalue);
+ if (!n)
+ return log_oom();
+
+ path_kill_slashes(n);
+
+ free(*s);
+ *s = n;
+
+ return 0;
+}
+
+int config_parse_strv(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ char *** sv = data, *w, *state;
+ size_t l;
+ int r;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ if (isempty(rvalue)) {
+ char **empty;
+
+ /* Empty assignment resets the list. As a special rule
+ * we actually fill in a real empty array here rather
+ * than NULL, since some code wants to know if
+ * something was set at all... */
+ empty = strv_new(NULL, NULL);
+ if (!empty)
+ return log_oom();
+
+ strv_free(*sv);
+ *sv = empty;
+ return 0;
+ }
+
+ FOREACH_WORD_QUOTED(w, l, rvalue, state) {
+ _cleanup_free_ char *n;
+
+ n = cunescape_length(w, l);
+ if (!n)
+ return log_oom();
+
+ if (!utf8_is_valid(n)) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "String is not UTF-8 clean, ignoring: %s", rvalue);
+ continue;
+ }
+
+ r = strv_extend(sv, n);
+ if (r < 0)
+ return log_oom();
+ }
+
+ return 0;
+}
+
+int config_parse_path_strv(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ char*** sv = data, *w, *state;
+ size_t l;
+ int r;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ if (isempty(rvalue)) {
+ /* Empty assignment resets the list */
+ strv_free(*sv);
+ *sv = NULL;
+ return 0;
+ }
+
+ FOREACH_WORD_QUOTED(w, l, rvalue, state) {
+ _cleanup_free_ char *n;
+
+ n = strndup(w, l);
+ if (!n)
+ return log_oom();
+
+ if (!utf8_is_valid(n)) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Path is not UTF-8 clean, ignoring assignment: %s", rvalue);
+ continue;
+ }
+
+ if (!path_is_absolute(n)) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Not an absolute path, ignoring: %s", rvalue);
+ continue;
+ }
+
+ path_kill_slashes(n);
+ r = strv_extend(sv, n);
+ if (r < 0)
+ return log_oom();
+ }
+
+ return 0;
+}
+
+int config_parse_mode(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ mode_t *m = data;
+ long l;
+ char *x = NULL;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ errno = 0;
+ l = strtol(rvalue, &x, 8);
+ if (!x || x == rvalue || *x || errno) {
+ log_syntax(unit, LOG_ERR, filename, line, errno,
+ "Failed to parse mode value, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ if (l < 0000 || l > 07777) {
+ log_syntax(unit, LOG_ERR, filename, line, ERANGE,
+ "Mode value out of range, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ *m = (mode_t) l;
+ return 0;
+}
+
+int config_parse_facility(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+
+ int *o = data, x;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ x = log_facility_unshifted_from_string(rvalue);
+ if (x < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Failed to parse log facility, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ *o = (x << 3) | LOG_PRI(*o);
+
+ return 0;
+}
+
+int config_parse_level(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+
+ int *o = data, x;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ x = log_level_from_string(rvalue);
+ if (x < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, EINVAL,
+ "Failed to parse log level, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ *o = (*o & LOG_FACMASK) | x;
+ return 0;
+}
+
+int config_parse_set_status(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ char *w;
+ size_t l;
+ char *state;
+ int r;
+ ExitStatusSet *status_set = data;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ if (isempty(rvalue)) {
+ /* Empty assignment resets the list */
+
+ set_free(status_set->signal);
+ set_free(status_set->code);
+
+ status_set->signal = status_set->code = NULL;
+ return 0;
+ }
+
+ FOREACH_WORD(w, l, rvalue, state) {
+ int val;
+ char *temp;
+
+ temp = strndup(w, l);
+ if (!temp)
+ return log_oom();
+
+ r = safe_atoi(temp, &val);
+ if (r < 0) {
+ val = signal_from_string_try_harder(temp);
+ free(temp);
+
+ if (val > 0) {
+ r = set_ensure_allocated(&status_set->signal, trivial_hash_func, trivial_compare_func);
+ if (r < 0)
+ return log_oom();
+
+ r = set_put(status_set->signal, INT_TO_PTR(val));
+ if (r < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, -r,
+ "Unable to store: %s", w);
+ return r;
+ }
+ } else {
+ log_syntax(unit, LOG_ERR, filename, line, -val,
+ "Failed to parse value, ignoring: %s", w);
+ return 0;
+ }
+ } else {
+ free(temp);
+
+ if (val < 0 || val > 255)
+ log_syntax(unit, LOG_ERR, filename, line, ERANGE,
+ "Value %d is outside range 0-255, ignoring", val);
+ else {
+ r = set_ensure_allocated(&status_set->code, trivial_hash_func, trivial_compare_func);
+ if (r < 0)
+ return log_oom();
+
+ r = set_put(status_set->code, INT_TO_PTR(val));
+ if (r < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, -r,
+ "Unable to store: %s", w);
+ return r;
+ }
+ }
+ }
+ }
+
+ return 0;
+}
diff --git a/src/shared/conf-parser.h b/src/shared/conf-parser.h
new file mode 100644
index 0000000000..08428a514a
--- /dev/null
+++ b/src/shared/conf-parser.h
@@ -0,0 +1,151 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include <stdbool.h>
+
+#include "macro.h"
+
+/* An abstract parser for simple, line based, shallow configuration
+ * files consisting of variable assignments only. */
+
+/* Prototype for a parser for a specific configuration setting */
+typedef int (*ConfigParserCallback)(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata);
+
+/* Wraps information for parsing a specific configuration variable, to
+ * be stored in a simple array */
+typedef struct ConfigTableItem {
+ const char *section; /* Section */
+ const char *lvalue; /* Name of the variable */
+ ConfigParserCallback parse; /* Function that is called to parse the variable's value */
+ int ltype; /* Distinguish different variables passed to the same callback */
+ void *data; /* Where to store the variable's data */
+} ConfigTableItem;
+
+/* Wraps information for parsing a specific configuration variable, to
+ * ve srored in a gperf perfect hashtable */
+typedef struct ConfigPerfItem {
+ const char *section_and_lvalue; /* Section + "." + name of the variable */
+ ConfigParserCallback parse; /* Function that is called to parse the variable's value */
+ int ltype; /* Distinguish different variables passed to the same callback */
+ size_t offset; /* Offset where to store data, from the beginning of userdata */
+} ConfigPerfItem;
+
+/* Prototype for a low-level gperf lookup function */
+typedef const ConfigPerfItem* (*ConfigPerfItemLookup)(const char *section_and_lvalue, unsigned length);
+
+/* Prototype for a generic high-level lookup function */
+typedef int (*ConfigItemLookup)(
+ void *table,
+ const char *section,
+ const char *lvalue,
+ ConfigParserCallback *func,
+ int *ltype,
+ void **data,
+ void *userdata);
+
+/* Linear table search implementation of ConfigItemLookup, based on
+ * ConfigTableItem arrays */
+int config_item_table_lookup(void *table, const char *section, const char *lvalue, ConfigParserCallback *func, int *ltype, void **data, void *userdata);
+
+/* gperf implementation of ConfigItemLookup, based on gperf
+ * ConfigPerfItem tables */
+int config_item_perf_lookup(void *table, const char *section, const char *lvalue, ConfigParserCallback *func, int *ltype, void **data, void *userdata);
+
+int config_parse(const char *unit,
+ const char *filename,
+ FILE *f,
+ const char *sections, /* nulstr */
+ ConfigItemLookup lookup,
+ void *table,
+ bool relaxed,
+ bool allow_include,
+ void *userdata);
+
+/* Generic parsers */
+int config_parse_int(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_unsigned(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_long(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_uint64(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_double(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_bytes_size(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_bytes_off(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_bool(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_tristate(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_string(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_path(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_strv(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_path_strv(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_sec(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_nsec(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_mode(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_facility(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_level(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_set_status(const char *unit, const char *filename, unsigned line, const char *section, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+
+int log_syntax_internal(const char *unit, int level,
+ const char *file, unsigned line, const char *func,
+ const char *config_file, unsigned config_line,
+ int error, const char *format, ...) _printf_attr_(9, 10);
+
+#define log_syntax(unit, level, config_file, config_line, error, ...) \
+ log_syntax_internal(unit, level, \
+ __FILE__, __LINE__, __func__, \
+ config_file, config_line, \
+ error, __VA_ARGS__)
+
+#define DEFINE_CONFIG_PARSE_ENUM(function,name,type,msg) \
+ int function(const char *unit, \
+ const char *filename, \
+ unsigned line, \
+ const char *section, \
+ const char *lvalue, \
+ int ltype, \
+ const char *rvalue, \
+ void *data, \
+ void *userdata) { \
+ \
+ type *i = data, x; \
+ \
+ assert(filename); \
+ assert(lvalue); \
+ assert(rvalue); \
+ assert(data); \
+ \
+ if ((x = name##_from_string(rvalue)) < 0) { \
+ log_syntax(unit, LOG_ERR, filename, line, -x, \
+ msg ", ignoring: %s", rvalue); \
+ return 0; \
+ } \
+ \
+ *i = x; \
+ return 0; \
+ }
diff --git a/src/shared/dbus-common.c b/src/shared/dbus-common.c
new file mode 100644
index 0000000000..b8c15cb9fc
--- /dev/null
+++ b/src/shared/dbus-common.c
@@ -0,0 +1,1428 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <sys/socket.h>
+#include <errno.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <dbus/dbus.h>
+#include <string.h>
+#include <sys/epoll.h>
+
+#include "log.h"
+#include "dbus-common.h"
+#include "util.h"
+#include "missing.h"
+#include "def.h"
+#include "strv.h"
+
+int bus_check_peercred(DBusConnection *c) {
+ int fd;
+ struct ucred ucred;
+ socklen_t l;
+
+ assert(c);
+
+ assert_se(dbus_connection_get_unix_fd(c, &fd));
+
+ l = sizeof(struct ucred);
+ if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &ucred, &l) < 0) {
+ log_error("SO_PEERCRED failed: %m");
+ return -errno;
+ }
+
+ if (l != sizeof(struct ucred)) {
+ log_error("SO_PEERCRED returned wrong size.");
+ return -E2BIG;
+ }
+
+ if (ucred.uid != 0 && ucred.uid != geteuid())
+ return -EPERM;
+
+ return 1;
+}
+
+static int sync_auth(DBusConnection *bus, DBusError *error) {
+ usec_t begin, tstamp;
+
+ assert(bus);
+
+ /* This complexity should probably move into D-Bus itself:
+ *
+ * https://bugs.freedesktop.org/show_bug.cgi?id=35189 */
+
+ begin = tstamp = now(CLOCK_MONOTONIC);
+ for (;;) {
+
+ if (tstamp > begin + DEFAULT_TIMEOUT_USEC)
+ break;
+
+ if (dbus_connection_get_is_authenticated(bus))
+ break;
+
+ if (!dbus_connection_read_write_dispatch(bus, ((begin + DEFAULT_TIMEOUT_USEC - tstamp) + USEC_PER_MSEC - 1) / USEC_PER_MSEC))
+ break;
+
+ tstamp = now(CLOCK_MONOTONIC);
+ }
+
+ if (!dbus_connection_get_is_connected(bus)) {
+ dbus_set_error_const(error, DBUS_ERROR_NO_SERVER, "Connection terminated during authentication.");
+ return -ECONNREFUSED;
+ }
+
+ if (!dbus_connection_get_is_authenticated(bus)) {
+ dbus_set_error_const(error, DBUS_ERROR_TIMEOUT, "Failed to authenticate in time.");
+ return -EACCES;
+ }
+
+ return 0;
+}
+
+int bus_connect(DBusBusType t, DBusConnection **_bus, bool *_private, DBusError *error) {
+ DBusConnection *bus = NULL;
+ int r;
+ bool private = true;
+
+ assert(_bus);
+
+ if (geteuid() == 0 && t == DBUS_BUS_SYSTEM) {
+ /* If we are root, then let's talk directly to the
+ * system instance, instead of going via the bus */
+
+ bus = dbus_connection_open_private("unix:path=/run/systemd/private", error);
+ if (!bus)
+ return -EIO;
+
+ } else {
+ if (t == DBUS_BUS_SESSION) {
+ const char *e;
+
+ /* If we are supposed to talk to the instance,
+ * try via XDG_RUNTIME_DIR first, then
+ * fallback to normal bus access */
+
+ e = secure_getenv("XDG_RUNTIME_DIR");
+ if (e) {
+ char *p;
+
+ if (asprintf(&p, "unix:path=%s/systemd/private", e) < 0)
+ return -ENOMEM;
+
+ bus = dbus_connection_open_private(p, NULL);
+ free(p);
+ }
+ }
+
+ if (!bus) {
+ bus = dbus_bus_get_private(t, error);
+ if (!bus)
+ return -EIO;
+
+ private = false;
+ }
+ }
+
+ dbus_connection_set_exit_on_disconnect(bus, FALSE);
+
+ if (private) {
+ if (bus_check_peercred(bus) < 0) {
+ dbus_connection_close(bus);
+ dbus_connection_unref(bus);
+
+ dbus_set_error_const(error, DBUS_ERROR_ACCESS_DENIED, "Failed to verify owner of bus.");
+ return -EACCES;
+ }
+ }
+
+ r = sync_auth(bus, error);
+ if (r < 0) {
+ dbus_connection_close(bus);
+ dbus_connection_unref(bus);
+ return r;
+ }
+
+ if (_private)
+ *_private = private;
+
+ *_bus = bus;
+ return 0;
+}
+
+int bus_connect_system_ssh(const char *user, const char *host, DBusConnection **_bus, DBusError *error) {
+ DBusConnection *bus;
+ char *p = NULL;
+ int r;
+
+ assert(_bus);
+ assert(user || host);
+
+ if (user && host)
+ asprintf(&p, "unixexec:path=ssh,argv1=-xT,argv2=%s@%s,argv3=systemd-stdio-bridge", user, host);
+ else if (user)
+ asprintf(&p, "unixexec:path=ssh,argv1=-xT,argv2=%s@localhost,argv3=systemd-stdio-bridge", user);
+ else if (host)
+ asprintf(&p, "unixexec:path=ssh,argv1=-xT,argv2=%s,argv3=systemd-stdio-bridge", host);
+
+ if (!p) {
+ dbus_set_error_const(error, DBUS_ERROR_NO_MEMORY, NULL);
+ return -ENOMEM;
+ }
+
+ bus = dbus_connection_open_private(p, error);
+ free(p);
+
+ if (!bus)
+ return -EIO;
+
+ dbus_connection_set_exit_on_disconnect(bus, FALSE);
+
+ if ((r = sync_auth(bus, error)) < 0) {
+ dbus_connection_close(bus);
+ dbus_connection_unref(bus);
+ return r;
+ }
+
+ if (!dbus_bus_register(bus, error)) {
+ dbus_connection_close(bus);
+ dbus_connection_unref(bus);
+ return r;
+ }
+
+ *_bus = bus;
+ return 0;
+}
+
+int bus_connect_system_polkit(DBusConnection **_bus, DBusError *error) {
+ DBusConnection *bus;
+ int r;
+
+ assert(_bus);
+
+ /* Don't bother with PolicyKit if we are root */
+ if (geteuid() == 0)
+ return bus_connect(DBUS_BUS_SYSTEM, _bus, NULL, error);
+
+ bus = dbus_connection_open_private("unixexec:path=pkexec,argv1=" SYSTEMD_STDIO_BRIDGE_BINARY_PATH, error);
+ if (!bus)
+ return -EIO;
+
+ dbus_connection_set_exit_on_disconnect(bus, FALSE);
+
+ r = sync_auth(bus, error);
+ if (r < 0) {
+ dbus_connection_close(bus);
+ dbus_connection_unref(bus);
+ return r;
+ }
+
+ if (!dbus_bus_register(bus, error)) {
+ dbus_connection_close(bus);
+ dbus_connection_unref(bus);
+ return r;
+ }
+
+ *_bus = bus;
+ return 0;
+}
+
+const char *bus_error_message(const DBusError *error) {
+ if (!error)
+ return NULL;
+
+ /* Sometimes the D-Bus server is a little bit too verbose with
+ * its error messages, so let's override them here */
+ if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED))
+ return "Access denied";
+
+ return error->message;
+}
+
+const char *bus_error(const DBusError *error, int err) {
+ if (error && dbus_error_is_set(error))
+ return bus_error_message(error);
+
+ return strerror(err < 0 ? -err : err);
+}
+
+DBusHandlerResult bus_default_message_handler(
+ DBusConnection *c,
+ DBusMessage *message,
+ const char *introspection,
+ const char *interfaces,
+ const BusBoundProperties *bound_properties) {
+
+ DBusError error;
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ int r;
+
+ assert(c);
+ assert(message);
+
+ dbus_error_init(&error);
+
+ if (dbus_message_is_method_call(message, "org.freedesktop.DBus.Introspectable", "Introspect") && introspection) {
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ if (!dbus_message_append_args(reply, DBUS_TYPE_STRING, &introspection, DBUS_TYPE_INVALID))
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.DBus.Properties", "Get") && bound_properties) {
+ const char *interface, *property;
+ const BusBoundProperties *bp;
+ const BusProperty *p;
+ void *data;
+ DBusMessageIter iter, sub;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &interface,
+ DBUS_TYPE_STRING, &property,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(c, message, &error, -EINVAL);
+
+ for (bp = bound_properties; bp->interface; bp++) {
+ if (!streq(bp->interface, interface))
+ continue;
+
+ for (p = bp->properties; p->property; p++)
+ if (streq(p->property, property))
+ goto get_prop;
+ }
+
+ /* no match */
+ if (!nulstr_contains(interfaces, interface))
+ dbus_set_error_const(&error, DBUS_ERROR_UNKNOWN_INTERFACE, "Unknown interface");
+ else
+ dbus_set_error_const(&error, DBUS_ERROR_UNKNOWN_PROPERTY, "Unknown property");
+
+ return bus_send_error_reply(c, message, &error, -EINVAL);
+
+get_prop:
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ dbus_message_iter_init_append(reply, &iter);
+
+ if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_VARIANT, p->signature, &sub))
+ goto oom;
+
+ data = (char*)bp->base + p->offset;
+ if (p->indirect)
+ data = *(void**)data;
+
+ r = p->append(&sub, property, data);
+ if (r == -ENOMEM)
+ goto oom;
+ if (r < 0)
+ return bus_send_error_reply(c, message, NULL, r);
+
+ if (!dbus_message_iter_close_container(&iter, &sub))
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.DBus.Properties", "GetAll") && bound_properties) {
+ const char *interface;
+ const BusBoundProperties *bp;
+ const BusProperty *p;
+ DBusMessageIter iter, sub, sub2, sub3;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &interface,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(c, message, &error, -EINVAL);
+
+ if (interface[0] && !nulstr_contains(interfaces, interface)) {
+ dbus_set_error_const(&error, DBUS_ERROR_UNKNOWN_INTERFACE, "Unknown interface");
+ return bus_send_error_reply(c, message, &error, -EINVAL);
+ }
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ dbus_message_iter_init_append(reply, &iter);
+
+ if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}", &sub))
+ goto oom;
+
+ for (bp = bound_properties; bp->interface; bp++) {
+ if (interface[0] && !streq(bp->interface, interface))
+ continue;
+
+ for (p = bp->properties; p->property; p++) {
+ void *data;
+
+ if (!dbus_message_iter_open_container(&sub, DBUS_TYPE_DICT_ENTRY, NULL, &sub2) ||
+ !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &p->property) ||
+ !dbus_message_iter_open_container(&sub2, DBUS_TYPE_VARIANT, p->signature, &sub3))
+ goto oom;
+
+ data = (char*)bp->base + p->offset;
+ if (p->indirect)
+ data = *(void**)data;
+ r = p->append(&sub3, p->property, data);
+ if (r == -ENOMEM)
+ goto oom;
+ if (r < 0)
+ return bus_send_error_reply(c, message, NULL, r);
+
+ if (!dbus_message_iter_close_container(&sub2, &sub3) ||
+ !dbus_message_iter_close_container(&sub, &sub2))
+ goto oom;
+ }
+ }
+
+ if (!dbus_message_iter_close_container(&iter, &sub))
+ goto oom;
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.DBus.Properties", "Set") && bound_properties) {
+ const char *interface, *property;
+ DBusMessageIter iter;
+ const BusBoundProperties *bp;
+ const BusProperty *p;
+ DBusMessageIter sub;
+ char *sig;
+ void *data;
+ DBusMessage *changed;
+
+ if (!dbus_message_iter_init(message, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING)
+ return bus_send_error_reply(c, message, NULL, -EINVAL);
+
+ dbus_message_iter_get_basic(&iter, &interface);
+
+ if (!dbus_message_iter_next(&iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING)
+ return bus_send_error_reply(c, message, NULL, -EINVAL);
+
+ dbus_message_iter_get_basic(&iter, &property);
+
+ if (!dbus_message_iter_next(&iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT ||
+ dbus_message_iter_has_next(&iter))
+ return bus_send_error_reply(c, message, NULL, -EINVAL);
+
+ for (bp = bound_properties; bp->interface; bp++) {
+ if (!streq(bp->interface, interface))
+ continue;
+
+ for (p = bp->properties; p->property; p++)
+ if (streq(p->property, property))
+ goto set_prop;
+ }
+
+ /* no match */
+ if (!nulstr_contains(interfaces, interface))
+ dbus_set_error_const(&error, DBUS_ERROR_UNKNOWN_INTERFACE, "Unknown interface");
+ else
+ dbus_set_error_const(&error, DBUS_ERROR_UNKNOWN_PROPERTY, "Unknown property");
+
+ return bus_send_error_reply(c, message, &error, -EINVAL);
+
+set_prop:
+ if (!p->set) {
+ dbus_set_error_const(&error, DBUS_ERROR_PROPERTY_READ_ONLY, "Property read-only");
+ return bus_send_error_reply(c, message, &error, -EINVAL);
+ }
+
+ dbus_message_iter_recurse(&iter, &sub);
+
+ sig = dbus_message_iter_get_signature(&sub);
+ if (!sig)
+ goto oom;
+
+ if (!streq(sig, p->signature)) {
+ dbus_free(sig);
+ return bus_send_error_reply(c, message, NULL, -EINVAL);
+ }
+ dbus_free(sig);
+
+ data = (uint8_t*) bp->base + p->offset;
+ if (p->indirect)
+ data = *(void**)data;
+
+ r = p->set(&sub, property, data);
+ if (r == -ENOMEM)
+ goto oom;
+ else if (r < 0)
+ return bus_send_error_reply(c, message, NULL, r);
+
+ reply = dbus_message_new_method_return(message);
+ if (!reply)
+ goto oom;
+
+ /* Send out a signal about this, but it doesn't really
+ * matter if this fails, so eat all errors */
+ changed = bus_properties_changed_one_new(
+ dbus_message_get_path(message),
+ interface,
+ property);
+ if (changed) {
+ dbus_connection_send(c, changed, NULL);
+ dbus_message_unref(changed);
+ }
+
+
+ } else {
+ const char *interface = dbus_message_get_interface(message);
+
+ if (!interface || !nulstr_contains(interfaces, interface)) {
+ dbus_set_error_const(&error, DBUS_ERROR_UNKNOWN_INTERFACE, "Unknown interface");
+ return bus_send_error_reply(c, message, &error, -EINVAL);
+ }
+ }
+
+ if (reply) {
+ if (!bus_maybe_send_reply(c, message, reply))
+ goto oom;
+
+ return DBUS_HANDLER_RESULT_HANDLED;
+ }
+
+ return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
+
+oom:
+ dbus_error_free(&error);
+
+ return DBUS_HANDLER_RESULT_NEED_MEMORY;
+}
+
+int bus_property_append_string(DBusMessageIter *i, const char *property, void *data) {
+ const char *t = data;
+
+ assert(i);
+ assert(property);
+
+ if (!t)
+ t = "";
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_STRING, &t))
+ return -ENOMEM;
+
+ return 0;
+}
+
+int bus_property_append_strv(DBusMessageIter *i, const char *property, void *data) {
+ char **t = data;
+
+ assert(i);
+ assert(property);
+
+ return bus_append_strv_iter(i, t);
+}
+
+int bus_property_append_bool(DBusMessageIter *i, const char *property, void *data) {
+ bool *b = data;
+ dbus_bool_t db;
+
+ assert(i);
+ assert(property);
+ assert(b);
+
+ db = *b;
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_BOOLEAN, &db))
+ return -ENOMEM;
+
+ return 0;
+}
+
+int bus_property_append_tristate_false(DBusMessageIter *i, const char *property, void *data) {
+ int *b = data;
+ dbus_bool_t db;
+
+ assert(i);
+ assert(property);
+ assert(b);
+
+ db = *b > 0;
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_BOOLEAN, &db))
+ return -ENOMEM;
+
+ return 0;
+}
+
+int bus_property_append_uint64(DBusMessageIter *i, const char *property, void *data) {
+ assert(i);
+ assert(property);
+ assert(data);
+
+ /* Let's ensure that usec_t is actually 64bit, and hence this
+ * function can be used for usec_t */
+ assert_cc(sizeof(uint64_t) == sizeof(usec_t));
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT64, data))
+ return -ENOMEM;
+
+ return 0;
+}
+
+int bus_property_append_uint32(DBusMessageIter *i, const char *property, void *data) {
+ assert(i);
+ assert(property);
+ assert(data);
+
+ /* Let's ensure that pid_t, mode_t, uid_t, gid_t are actually
+ * 32bit, and hence this function can be used for
+ * pid_t/mode_t/uid_t/gid_t */
+ assert_cc(sizeof(uint32_t) == sizeof(pid_t));
+ assert_cc(sizeof(uint32_t) == sizeof(mode_t));
+ assert_cc(sizeof(uint32_t) == sizeof(unsigned));
+ assert_cc(sizeof(uint32_t) == sizeof(uid_t));
+ assert_cc(sizeof(uint32_t) == sizeof(gid_t));
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT32, data))
+ return -ENOMEM;
+
+ return 0;
+}
+
+int bus_property_append_int32(DBusMessageIter *i, const char *property, void *data) {
+ assert(i);
+ assert(property);
+ assert(data);
+
+ assert_cc(sizeof(int32_t) == sizeof(int));
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_INT32, data))
+ return -ENOMEM;
+
+ return 0;
+}
+
+int bus_property_append_size(DBusMessageIter *i, const char *property, void *data) {
+ uint64_t u;
+
+ assert(i);
+ assert(property);
+ assert(data);
+
+ u = (uint64_t) *(size_t*) data;
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT64, &u))
+ return -ENOMEM;
+
+ return 0;
+}
+
+int bus_property_append_ul(DBusMessageIter *i, const char *property, void *data) {
+ uint64_t u;
+
+ assert(i);
+ assert(property);
+ assert(data);
+
+ u = (uint64_t) *(unsigned long*) data;
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT64, &u))
+ return -ENOMEM;
+
+ return 0;
+}
+
+int bus_property_append_long(DBusMessageIter *i, const char *property, void *data) {
+ int64_t l;
+
+ assert(i);
+ assert(property);
+ assert(data);
+
+ l = (int64_t) *(long*) data;
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_INT64, &l))
+ return -ENOMEM;
+
+ return 0;
+}
+
+int bus_property_set_uint64(DBusMessageIter *i, const char *property, void *data) {
+ uint64_t *t = data;
+
+ assert(i);
+ assert(property);
+
+ dbus_message_iter_get_basic(i, t);
+ return 0;
+}
+
+const char *bus_errno_to_dbus(int error) {
+
+ switch(error) {
+
+ case -EINVAL:
+ return DBUS_ERROR_INVALID_ARGS;
+
+ case -ENOMEM:
+ return DBUS_ERROR_NO_MEMORY;
+
+ case -EPERM:
+ case -EACCES:
+ return DBUS_ERROR_ACCESS_DENIED;
+
+ case -ESRCH:
+ return DBUS_ERROR_UNIX_PROCESS_ID_UNKNOWN;
+
+ case -ENOENT:
+ return DBUS_ERROR_FILE_NOT_FOUND;
+
+ case -EEXIST:
+ return DBUS_ERROR_FILE_EXISTS;
+
+ case -ETIMEDOUT:
+ case -ETIME:
+ return DBUS_ERROR_TIMEOUT;
+
+ case -EIO:
+ return DBUS_ERROR_IO_ERROR;
+
+ case -ENETRESET:
+ case -ECONNABORTED:
+ case -ECONNRESET:
+ return DBUS_ERROR_DISCONNECTED;
+ }
+
+ return DBUS_ERROR_FAILED;
+}
+
+dbus_bool_t bus_maybe_send_reply (DBusConnection *c,
+ DBusMessage *message,
+ DBusMessage *reply)
+{
+ /* Some parts of systemd "reply" to signals, which of course
+ * have the no-reply flag set. We will be defensive here and
+ * still send out a reply if we're passed a signal.
+ */
+ if (dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_METHOD_CALL &&
+ dbus_message_get_no_reply(message))
+ return TRUE;
+ return dbus_connection_send(c, reply, NULL);
+}
+
+DBusHandlerResult bus_send_error_reply(DBusConnection *c, DBusMessage *message, DBusError *berror, int error) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ const char *name, *text;
+
+ if (berror && dbus_error_is_set(berror)) {
+ name = berror->name;
+ text = berror->message;
+ } else {
+ name = bus_errno_to_dbus(error);
+ text = strerror(-error);
+ }
+
+ reply = dbus_message_new_error(message, name, text);
+ if (!reply)
+ goto oom;
+
+ if (!bus_maybe_send_reply(c, message, reply))
+ goto oom;
+
+ if (berror)
+ dbus_error_free(berror);
+
+ return DBUS_HANDLER_RESULT_HANDLED;
+
+oom:
+ if (reply)
+ dbus_message_unref(reply);
+
+ if (berror)
+ dbus_error_free(berror);
+
+ return DBUS_HANDLER_RESULT_NEED_MEMORY;
+}
+
+DBusMessage* bus_properties_changed_new(const char *path, const char *interface, const char *properties) {
+ DBusMessage *m;
+ DBusMessageIter iter, sub;
+ const char *i;
+
+ assert(interface);
+ assert(properties);
+
+ m = dbus_message_new_signal(path, "org.freedesktop.DBus.Properties", "PropertiesChanged");
+ if (!m)
+ goto oom;
+
+ dbus_message_iter_init_append(m, &iter);
+
+ /* We won't send any property values, since they might be
+ * large and sometimes not cheap to generated */
+
+ if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &interface) ||
+ !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}", &sub) ||
+ !dbus_message_iter_close_container(&iter, &sub) ||
+ !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub))
+ goto oom;
+
+ NULSTR_FOREACH(i, properties)
+ if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &i))
+ goto oom;
+
+ if (!dbus_message_iter_close_container(&iter, &sub))
+ goto oom;
+
+ return m;
+
+oom:
+ if (m)
+ dbus_message_unref(m);
+
+ return NULL;
+}
+
+DBusMessage* bus_properties_changed_one_new(const char *path, const char *interface, const char *property) {
+ DBusMessage *m;
+ DBusMessageIter iter, sub;
+
+ assert(interface);
+ assert(property);
+
+ m = dbus_message_new_signal(path, "org.freedesktop.DBus.Properties", "PropertiesChanged");
+ if (!m)
+ goto oom;
+
+ dbus_message_iter_init_append(m, &iter);
+
+ /* We won't send any property values, since they might be
+ * large and sometimes not cheap to generated */
+
+ if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &interface) ||
+ !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}", &sub) ||
+ !dbus_message_iter_close_container(&iter, &sub) ||
+ !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub))
+ goto oom;
+
+ if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &property))
+ goto oom;
+
+ if (!dbus_message_iter_close_container(&iter, &sub))
+ goto oom;
+
+ return m;
+
+oom:
+ if (m)
+ dbus_message_unref(m);
+
+ return NULL;
+}
+
+uint32_t bus_flags_to_events(DBusWatch *bus_watch) {
+ unsigned flags;
+ uint32_t events = 0;
+
+ assert(bus_watch);
+
+ /* no watch flags for disabled watches */
+ if (!dbus_watch_get_enabled(bus_watch))
+ return 0;
+
+ flags = dbus_watch_get_flags(bus_watch);
+
+ if (flags & DBUS_WATCH_READABLE)
+ events |= EPOLLIN;
+ if (flags & DBUS_WATCH_WRITABLE)
+ events |= EPOLLOUT;
+
+ return events | EPOLLHUP | EPOLLERR;
+}
+
+unsigned bus_events_to_flags(uint32_t events) {
+ unsigned flags = 0;
+
+ if (events & EPOLLIN)
+ flags |= DBUS_WATCH_READABLE;
+ if (events & EPOLLOUT)
+ flags |= DBUS_WATCH_WRITABLE;
+ if (events & EPOLLHUP)
+ flags |= DBUS_WATCH_HANGUP;
+ if (events & EPOLLERR)
+ flags |= DBUS_WATCH_ERROR;
+
+ return flags;
+}
+
+int bus_parse_strv(DBusMessage *m, char ***_l) {
+ DBusMessageIter iter;
+
+ assert(m);
+ assert(_l);
+
+ if (!dbus_message_iter_init(m, &iter))
+ return -EINVAL;
+
+ return bus_parse_strv_iter(&iter, _l);
+}
+
+int bus_parse_strv_iter(DBusMessageIter *iter, char ***_l) {
+ DBusMessageIter sub;
+ unsigned n = 0, i = 0;
+ char **l;
+
+ assert(iter);
+ assert(_l);
+
+ if (dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_ARRAY ||
+ dbus_message_iter_get_element_type(iter) != DBUS_TYPE_STRING)
+ return -EINVAL;
+
+ dbus_message_iter_recurse(iter, &sub);
+
+ while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ n++;
+ dbus_message_iter_next(&sub);
+ }
+
+ l = new(char*, n+1);
+ if (!l)
+ return -ENOMEM;
+
+ dbus_message_iter_recurse(iter, &sub);
+
+ while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ const char *s;
+
+ assert_se(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
+ dbus_message_iter_get_basic(&sub, &s);
+
+ if (!(l[i++] = strdup(s))) {
+ strv_free(l);
+ return -ENOMEM;
+ }
+
+ dbus_message_iter_next(&sub);
+ }
+
+ assert(i == n);
+ l[i] = NULL;
+
+ if (_l)
+ *_l = l;
+
+ return 0;
+}
+
+int bus_parse_strv_pairs_iter(DBusMessageIter *iter, char ***_l) {
+ DBusMessageIter sub, sub2;
+ unsigned n = 0, i = 0;
+ char **l;
+
+ assert(iter);
+ assert(_l);
+
+ if (dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_ARRAY ||
+ dbus_message_iter_get_element_type(iter) != DBUS_TYPE_STRUCT)
+ return -EINVAL;
+
+ dbus_message_iter_recurse(iter, &sub);
+
+ while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ n++;
+ dbus_message_iter_next(&sub);
+ }
+
+ l = new(char*, n*2+1);
+ if (!l)
+ return -ENOMEM;
+
+ dbus_message_iter_recurse(iter, &sub);
+
+ while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ const char *a, *b;
+
+ assert_se(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT);
+
+ dbus_message_iter_recurse(&sub, &sub2);
+
+ if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &a, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &b, false) < 0)
+ return -EINVAL;
+
+ l[i] = strdup(a);
+ if (!l[i]) {
+ strv_free(l);
+ return -ENOMEM;
+ }
+
+ l[++i] = strdup(b);
+ if (!l[i]) {
+ strv_free(l);
+ return -ENOMEM;
+ }
+
+ i++;
+ dbus_message_iter_next(&sub);
+ }
+
+ assert(i == n*2);
+ l[i] = NULL;
+
+ if (_l)
+ *_l = l;
+
+ return 0;
+}
+
+int bus_parse_unit_info(DBusMessageIter *iter, struct unit_info *u) {
+ DBusMessageIter sub;
+
+ assert(iter);
+ assert(u);
+
+ if (dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_STRUCT)
+ return -EINVAL;
+
+ dbus_message_iter_recurse(iter, &sub);
+
+ if (bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &u->id, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &u->description, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &u->following, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ return 0;
+}
+
+int bus_append_strv_iter(DBusMessageIter *iter, char **l) {
+ DBusMessageIter sub;
+
+ assert(iter);
+
+ if (!dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY, "s", &sub))
+ return -ENOMEM;
+
+ STRV_FOREACH(l, l)
+ if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, l))
+ return -ENOMEM;
+
+ if (!dbus_message_iter_close_container(iter, &sub))
+ return -ENOMEM;
+
+ return 0;
+}
+
+int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
+
+ assert(iter);
+ assert(data);
+
+ if (dbus_message_iter_get_arg_type(iter) != type)
+ return -EIO;
+
+ dbus_message_iter_get_basic(iter, data);
+
+ if (!dbus_message_iter_next(iter) != !next)
+ return -EIO;
+
+ return 0;
+}
+
+int generic_print_property(const char *name, DBusMessageIter *iter, bool all) {
+ assert(name);
+ assert(iter);
+
+ switch (dbus_message_iter_get_arg_type(iter)) {
+
+ case DBUS_TYPE_STRING: {
+ const char *s;
+ dbus_message_iter_get_basic(iter, &s);
+
+ if (all || !isempty(s))
+ printf("%s=%s\n", name, s);
+
+ return 1;
+ }
+
+ case DBUS_TYPE_BOOLEAN: {
+ dbus_bool_t b;
+
+ dbus_message_iter_get_basic(iter, &b);
+ printf("%s=%s\n", name, yes_no(b));
+
+ return 1;
+ }
+
+ case DBUS_TYPE_UINT64: {
+ uint64_t u;
+ dbus_message_iter_get_basic(iter, &u);
+
+ /* Yes, heuristics! But we can change this check
+ * should it turn out to not be sufficient */
+
+ if (endswith(name, "Timestamp")) {
+ char timestamp[FORMAT_TIMESTAMP_MAX], *t;
+
+ t = format_timestamp(timestamp, sizeof(timestamp), u);
+ if (t || all)
+ printf("%s=%s\n", name, strempty(t));
+
+ } else if (strstr(name, "USec")) {
+ char timespan[FORMAT_TIMESPAN_MAX];
+
+ printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u, 0));
+ } else
+ printf("%s=%llu\n", name, (unsigned long long) u);
+
+ return 1;
+ }
+
+ case DBUS_TYPE_UINT32: {
+ uint32_t u;
+ dbus_message_iter_get_basic(iter, &u);
+
+ if (strstr(name, "UMask") || strstr(name, "Mode"))
+ printf("%s=%04o\n", name, u);
+ else
+ printf("%s=%u\n", name, (unsigned) u);
+
+ return 1;
+ }
+
+ case DBUS_TYPE_INT32: {
+ int32_t i;
+ dbus_message_iter_get_basic(iter, &i);
+
+ printf("%s=%i\n", name, (int) i);
+ return 1;
+ }
+
+ case DBUS_TYPE_DOUBLE: {
+ double d;
+ dbus_message_iter_get_basic(iter, &d);
+
+ printf("%s=%g\n", name, d);
+ return 1;
+ }
+
+ case DBUS_TYPE_ARRAY:
+
+ if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
+ DBusMessageIter sub;
+ bool space = false;
+
+ dbus_message_iter_recurse(iter, &sub);
+ if (all ||
+ dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ printf("%s=", name);
+
+ while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ const char *s;
+
+ assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
+ dbus_message_iter_get_basic(&sub, &s);
+ printf("%s%s", space ? " " : "", s);
+
+ space = true;
+ dbus_message_iter_next(&sub);
+ }
+
+ puts("");
+ }
+
+ return 1;
+
+ } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
+ DBusMessageIter sub;
+
+ dbus_message_iter_recurse(iter, &sub);
+ if (all ||
+ dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ printf("%s=", name);
+
+ while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ uint8_t u;
+
+ assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
+ dbus_message_iter_get_basic(&sub, &u);
+ printf("%02x", u);
+
+ dbus_message_iter_next(&sub);
+ }
+
+ puts("");
+ }
+
+ return 1;
+
+ } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_UINT32) {
+ DBusMessageIter sub;
+
+ dbus_message_iter_recurse(iter, &sub);
+ if (all ||
+ dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ printf("%s=", name);
+
+ while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ uint32_t u;
+
+ assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32);
+ dbus_message_iter_get_basic(&sub, &u);
+ printf("%08x", u);
+
+ dbus_message_iter_next(&sub);
+ }
+
+ puts("");
+ }
+
+ return 1;
+ }
+
+ break;
+ }
+
+ return 0;
+}
+
+static void release_name_pending_cb(DBusPendingCall *pending, void *userdata) {
+ DBusMessage *reply;
+ DBusConnection *bus = userdata;
+
+ assert_se(reply = dbus_pending_call_steal_reply(pending));
+ dbus_message_unref(reply);
+
+ dbus_connection_close(bus);
+}
+
+void bus_async_unregister_and_exit(DBusConnection *bus, const char *name) {
+ _cleanup_dbus_message_unref_ DBusMessage *m = NULL;
+ DBusPendingCall *pending = NULL;
+
+ assert(bus);
+
+ /* We unregister the name here, but we continue to process
+ * requests, until we get the response for it, so that all
+ * requests are guaranteed to be processed. */
+
+ m = dbus_message_new_method_call(
+ DBUS_SERVICE_DBUS,
+ DBUS_PATH_DBUS,
+ DBUS_INTERFACE_DBUS,
+ "ReleaseName");
+ if (!m)
+ goto oom;
+
+ if (!dbus_message_append_args(
+ m,
+ DBUS_TYPE_STRING,
+ &name,
+ DBUS_TYPE_INVALID))
+ goto oom;
+
+ if (!dbus_connection_send_with_reply(bus, m, &pending, -1))
+ goto oom;
+
+ if (!dbus_pending_call_set_notify(pending, release_name_pending_cb, bus, NULL))
+ goto oom;
+
+ dbus_pending_call_unref(pending);
+
+ return;
+
+oom:
+ log_oom();
+
+ if (pending) {
+ dbus_pending_call_cancel(pending);
+ dbus_pending_call_unref(pending);
+ }
+}
+
+DBusHandlerResult bus_exit_idle_filter(DBusConnection *bus, DBusMessage *m, void *userdata) {
+ usec_t *remain_until = userdata;
+
+ assert(bus);
+ assert(m);
+ assert(remain_until);
+
+ /* Every time we get a new message we reset out timeout */
+ *remain_until = now(CLOCK_MONOTONIC) + DEFAULT_EXIT_USEC;
+
+ if (dbus_message_is_signal(m, DBUS_INTERFACE_LOCAL, "Disconnected"))
+ dbus_connection_close(bus);
+
+ return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
+}
+
+/* This mimics dbus_bus_get_unix_user() */
+pid_t bus_get_unix_process_id(
+ DBusConnection *connection,
+ const char *name,
+ DBusError *error) {
+
+ _cleanup_dbus_message_unref_ DBusMessage *m = NULL, *reply = NULL;
+ uint32_t pid = 0;
+
+ m = dbus_message_new_method_call(
+ DBUS_SERVICE_DBUS,
+ DBUS_PATH_DBUS,
+ DBUS_INTERFACE_DBUS,
+ "GetConnectionUnixProcessID");
+ if (!m) {
+ dbus_set_error_const(error, DBUS_ERROR_NO_MEMORY, NULL);
+ return 0;
+ }
+
+ if (!dbus_message_append_args(
+ m,
+ DBUS_TYPE_STRING, &name,
+ DBUS_TYPE_INVALID)) {
+ dbus_set_error_const(error, DBUS_ERROR_NO_MEMORY, NULL);
+ return 0;
+ }
+
+ reply = dbus_connection_send_with_reply_and_block(connection, m, -1, error);
+ if (!reply)
+ return 0;
+
+ if (dbus_set_error_from_message(error, reply))
+ return 0;
+
+ if (!dbus_message_get_args(
+ reply, error,
+ DBUS_TYPE_UINT32, &pid,
+ DBUS_TYPE_INVALID))
+ return 0;
+
+ return (pid_t) pid;
+}
+
+bool bus_error_is_no_service(const DBusError *error) {
+ assert(error);
+
+ if (!dbus_error_is_set(error))
+ return false;
+
+ if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
+ return true;
+
+ if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
+ return true;
+
+ return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
+}
+
+int bus_method_call_with_reply(
+ DBusConnection *bus,
+ const char *destination,
+ const char *path,
+ const char *interface,
+ const char *method,
+ DBusMessage **return_reply,
+ DBusError *return_error,
+ int first_arg_type, ...) {
+
+ DBusError error;
+ _cleanup_dbus_message_unref_ DBusMessage *m = NULL;
+ DBusMessage *reply;
+ va_list ap;
+ int r = 0;
+
+ dbus_error_init(&error);
+ assert(bus);
+
+ m = dbus_message_new_method_call(destination, path, interface, method);
+ if (!m) {
+ r = log_oom();
+ goto finish;
+ }
+
+ va_start(ap, first_arg_type);
+ if (!dbus_message_append_args_valist(m, first_arg_type, ap)) {
+ va_end(ap);
+ r = log_oom();
+ goto finish;
+ }
+ va_end(ap);
+
+ reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
+ if (!reply) {
+ if (!return_error)
+ log_error("Failed to issue method call: %s", bus_error_message(&error));
+
+ if (bus_error_is_no_service(&error))
+ r = -ENOENT;
+ else if (dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED))
+ r = -EACCES;
+ else if (dbus_error_has_name(&error, DBUS_ERROR_NO_REPLY))
+ r = -ETIMEDOUT;
+ else
+ r = -EIO;
+ goto finish;
+ }
+
+ if (return_reply)
+ *return_reply = reply;
+ else
+ dbus_message_unref(reply);
+
+finish:
+ if (return_error)
+ *return_error = error;
+ else
+ dbus_error_free(&error);
+
+ return r;
+}
+
+void bus_message_unrefp(DBusMessage **reply) {
+ if (!reply)
+ return;
+
+ if (!*reply)
+ return;
+
+ dbus_message_unref(*reply);
+}
+
+const char *bus_message_get_sender_with_fallback(DBusMessage *m) {
+ const char *s;
+
+ assert(m);
+
+ s = dbus_message_get_sender(m);
+ if (s)
+ return s;
+
+ /* When the message came in from a direct connection the
+ * message will have no sender. We fix that here. */
+
+ return ":no-sender";
+}
diff --git a/src/shared/dbus-common.h b/src/shared/dbus-common.h
new file mode 100644
index 0000000000..9752f08c05
--- /dev/null
+++ b/src/shared/dbus-common.h
@@ -0,0 +1,246 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <dbus/dbus.h>
+#include <inttypes.h>
+#include <sys/types.h>
+
+#include "macro.h"
+
+#ifndef DBUS_ERROR_UNKNOWN_OBJECT
+#define DBUS_ERROR_UNKNOWN_OBJECT "org.freedesktop.DBus.Error.UnknownObject"
+#endif
+
+#ifndef DBUS_ERROR_UNKNOWN_INTERFACE
+#define DBUS_ERROR_UNKNOWN_INTERFACE "org.freedesktop.DBus.Error.UnknownInterface"
+#endif
+
+#ifndef DBUS_ERROR_UNKNOWN_PROPERTY
+#define DBUS_ERROR_UNKNOWN_PROPERTY "org.freedesktop.DBus.Error.UnknownProperty"
+#endif
+
+#ifndef DBUS_ERROR_PROPERTY_READ_ONLY
+#define DBUS_ERROR_PROPERTY_READ_ONLY "org.freedesktop.DBus.Error.PropertyReadOnly"
+#endif
+
+#define BUS_PROPERTIES_INTERFACE \
+ " <interface name=\"org.freedesktop.DBus.Properties\">\n" \
+ " <method name=\"Get\">\n" \
+ " <arg name=\"interface\" direction=\"in\" type=\"s\"/>\n" \
+ " <arg name=\"property\" direction=\"in\" type=\"s\"/>\n" \
+ " <arg name=\"value\" direction=\"out\" type=\"v\"/>\n" \
+ " </method>\n" \
+ " <method name=\"GetAll\">\n" \
+ " <arg name=\"interface\" direction=\"in\" type=\"s\"/>\n" \
+ " <arg name=\"properties\" direction=\"out\" type=\"a{sv}\"/>\n" \
+ " </method>\n" \
+ " <method name=\"Set\">\n" \
+ " <arg name=\"interface\" direction=\"in\" type=\"s\"/>\n" \
+ " <arg name=\"property\" direction=\"in\" type=\"s\"/>\n" \
+ " <arg name=\"value\" direction=\"in\" type=\"v\"/>\n" \
+ " </method>\n" \
+ " <signal name=\"PropertiesChanged\">\n" \
+ " <arg type=\"s\" name=\"interface\"/>\n" \
+ " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n" \
+ " <arg type=\"as\" name=\"invalidated_properties\"/>\n" \
+ " </signal>\n" \
+ " </interface>\n"
+
+#define BUS_INTROSPECTABLE_INTERFACE \
+ " <interface name=\"org.freedesktop.DBus.Introspectable\">\n" \
+ " <method name=\"Introspect\">\n" \
+ " <arg name=\"data\" type=\"s\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " </interface>\n"
+
+#define BUS_PEER_INTERFACE \
+ "<interface name=\"org.freedesktop.DBus.Peer\">\n" \
+ " <method name=\"Ping\"/>\n" \
+ " <method name=\"GetMachineId\">\n" \
+ " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ "</interface>\n"
+
+#define BUS_GENERIC_INTERFACES_LIST \
+ "org.freedesktop.DBus.Properties\0" \
+ "org.freedesktop.DBus.Introspectable\0" \
+ "org.freedesktop.DBus.Peer\0"
+
+int bus_check_peercred(DBusConnection *c);
+
+int bus_connect(DBusBusType t, DBusConnection **_bus, bool *private_bus, DBusError *error);
+
+int bus_connect_system_ssh(const char *user, const char *host, DBusConnection **_bus, DBusError *error);
+int bus_connect_system_polkit(DBusConnection **_bus, DBusError *error);
+
+const char *bus_error_message(const DBusError *error);
+const char *bus_error(const DBusError *e, int r);
+
+typedef int (*BusPropertyCallback)(DBusMessageIter *iter, const char *property, void *data);
+typedef int (*BusPropertySetCallback)(DBusMessageIter *iter, const char *property, void *data);
+
+typedef struct BusProperty {
+ const char *property; /* name of the property */
+ BusPropertyCallback append; /* Function that is called to serialize this property */
+ const char *signature;
+ const uint16_t offset; /* Offset from BusBoundProperties::base address to the property data.
+ * uint16_t is sufficient, because we have no structs too big.
+ * -Werror=overflow will catch it if this does not hold. */
+ bool indirect; /* data is indirect, ie. not base+offset, but *(base+offset) */
+ BusPropertySetCallback set; /* Optional: Function that is called to set this property */
+} BusProperty;
+
+typedef struct BusBoundProperties {
+ const char *interface; /* interface of the properties */
+ const BusProperty *properties; /* array of properties, ended by a NULL-filled element */
+ const void *const base; /* base pointer to which the offset must be added to reach data */
+} BusBoundProperties;
+
+dbus_bool_t bus_maybe_send_reply (DBusConnection *c,
+ DBusMessage *message,
+ DBusMessage *reply);
+
+DBusHandlerResult bus_send_error_reply(
+ DBusConnection *c,
+ DBusMessage *message,
+ DBusError *bus_error,
+ int error);
+
+DBusHandlerResult bus_default_message_handler(
+ DBusConnection *c,
+ DBusMessage *message,
+ const char *introspection,
+ const char *interfaces,
+ const BusBoundProperties *bound_properties);
+
+int bus_property_append_string(DBusMessageIter *i, const char *property, void *data);
+int bus_property_append_strv(DBusMessageIter *i, const char *property, void *data);
+int bus_property_append_bool(DBusMessageIter *i, const char *property, void *data);
+int bus_property_append_tristate_false(DBusMessageIter *i, const char *property, void *data);
+int bus_property_append_int32(DBusMessageIter *i, const char *property, void *data);
+int bus_property_append_uint32(DBusMessageIter *i, const char *property, void *data);
+int bus_property_append_uint64(DBusMessageIter *i, const char *property, void *data);
+int bus_property_append_size(DBusMessageIter *i, const char *property, void *data);
+int bus_property_append_ul(DBusMessageIter *i, const char *property, void *data);
+int bus_property_append_long(DBusMessageIter *i, const char *property, void *data);
+
+#define bus_property_append_int bus_property_append_int32
+#define bus_property_append_pid bus_property_append_uint32
+#define bus_property_append_uid bus_property_append_uint32
+#define bus_property_append_gid bus_property_append_uint32
+#define bus_property_append_mode bus_property_append_uint32
+#define bus_property_append_unsigned bus_property_append_uint32
+#define bus_property_append_usec bus_property_append_uint64
+
+int bus_property_set_uint64(DBusMessageIter *i, const char *property, void *data);
+#define bus_property_set_usec bus_property_set_uint64
+
+#define DEFINE_BUS_PROPERTY_APPEND_ENUM(function,name,type) \
+ int function(DBusMessageIter *i, const char *property, void *data) { \
+ const char *value; \
+ type *field = data; \
+ \
+ assert(i); \
+ assert(property); \
+ \
+ value = strempty(name##_to_string(*field)); \
+ \
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_STRING, &value)) \
+ return -ENOMEM; \
+ \
+ return 0; \
+ }
+
+#define DEFINE_BUS_PROPERTY_SET_ENUM(function,name,type) \
+ int function(DBusMessageIter *i, const char *property, void *data) { \
+ const char *value; \
+ type f, *field = data; \
+ \
+ assert(i); \
+ assert(property); \
+ \
+ dbus_message_iter_get_basic(i, &value); \
+ \
+ f = name##_from_string(value); \
+ if (f < 0) \
+ return f; \
+ \
+ *field = f; \
+ return 0; \
+ }
+
+const char *bus_errno_to_dbus(int error) _const_;
+
+DBusMessage* bus_properties_changed_new(const char *path, const char *interface, const char *properties);
+DBusMessage* bus_properties_changed_one_new(const char *path, const char *interface, const char *property);
+
+uint32_t bus_flags_to_events(DBusWatch *bus_watch) _pure_;
+unsigned bus_events_to_flags(uint32_t events) _const_;
+
+int bus_parse_strv(DBusMessage *m, char ***_l);
+int bus_parse_strv_iter(DBusMessageIter *iter, char ***_l);
+int bus_parse_strv_pairs_iter(DBusMessageIter *iter, char ***_l);
+
+struct unit_info {
+ const char *id;
+ const char *description;
+ const char *load_state;
+ const char *active_state;
+ const char *sub_state;
+ const char *following;
+ const char *unit_path;
+ uint32_t job_id;
+ const char *job_type;
+ const char *job_path;
+};
+
+int bus_parse_unit_info(DBusMessageIter *iter, struct unit_info *u);
+
+int bus_append_strv_iter(DBusMessageIter *iter, char **l);
+
+int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next);
+
+int generic_print_property(const char *name, DBusMessageIter *iter, bool all);
+
+void bus_async_unregister_and_exit(DBusConnection *bus, const char *name);
+
+DBusHandlerResult bus_exit_idle_filter(DBusConnection *bus, DBusMessage *m, void *userdata);
+
+pid_t bus_get_unix_process_id(DBusConnection *connection, const char *name, DBusError *error);
+
+bool bus_error_is_no_service(const DBusError *error);
+int bus_method_call_with_reply(DBusConnection *bus,
+ const char *destination,
+ const char *path,
+ const char *interface,
+ const char *method,
+ DBusMessage **return_reply,
+ DBusError *return_error,
+ int first_arg_type, ...);
+
+const char *bus_message_get_sender_with_fallback(DBusMessage *m);
+
+void bus_message_unrefp(DBusMessage **reply);
+
+#define _cleanup_dbus_message_unref_ __attribute__((cleanup(bus_message_unrefp)))
+#define _cleanup_dbus_error_free_ __attribute__((cleanup(dbus_error_free)))
diff --git a/src/shared/dbus-loop.c b/src/shared/dbus-loop.c
new file mode 100644
index 0000000000..c533242220
--- /dev/null
+++ b/src/shared/dbus-loop.c
@@ -0,0 +1,249 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdbool.h>
+#include <assert.h>
+#include <sys/epoll.h>
+#include <string.h>
+#include <errno.h>
+#include <sys/timerfd.h>
+#include <unistd.h>
+
+#include "dbus-loop.h"
+#include "dbus-common.h"
+#include "util.h"
+
+/* Minimal implementation of the dbus loop which integrates all dbus
+ * events into a single epoll fd which we can triviall integrate with
+ * other loops. Note that this is not used in the main systemd daemon
+ * since we run a more elaborate mainloop there. */
+
+typedef struct EpollData {
+ int fd;
+ void *object;
+ bool is_timeout:1;
+ bool fd_is_dupped:1;
+} EpollData;
+
+static dbus_bool_t add_watch(DBusWatch *watch, void *data) {
+ _cleanup_free_ EpollData *e = NULL;
+ struct epoll_event ev = {};
+
+ assert(watch);
+
+ e = new0(EpollData, 1);
+ if (!e)
+ return FALSE;
+
+ e->fd = dbus_watch_get_unix_fd(watch);
+ e->object = watch;
+ e->is_timeout = false;
+
+ ev.events = bus_flags_to_events(watch);
+ ev.data.ptr = e;
+
+ if (epoll_ctl(PTR_TO_INT(data), EPOLL_CTL_ADD, e->fd, &ev) < 0) {
+
+ if (errno != EEXIST)
+ return FALSE;
+
+ /* Hmm, bloody D-Bus creates multiple watches on the
+ * same fd. epoll() does not like that. As a dirty
+ * hack we simply dup() the fd and hence get a second
+ * one we can safely add to the epoll(). */
+
+ e->fd = dup(e->fd);
+ if (e->fd < 0)
+ return FALSE;
+
+ if (epoll_ctl(PTR_TO_INT(data), EPOLL_CTL_ADD, e->fd, &ev) < 0) {
+ close_nointr_nofail(e->fd);
+ return FALSE;
+ }
+
+ e->fd_is_dupped = true;
+ }
+
+ dbus_watch_set_data(watch, e, NULL);
+ e = NULL; /* prevent freeing */
+
+ return TRUE;
+}
+
+static void remove_watch(DBusWatch *watch, void *data) {
+ _cleanup_free_ EpollData *e = NULL;
+
+ assert(watch);
+
+ e = dbus_watch_get_data(watch);
+ if (!e)
+ return;
+
+ assert_se(epoll_ctl(PTR_TO_INT(data), EPOLL_CTL_DEL, e->fd, NULL) >= 0);
+
+ if (e->fd_is_dupped)
+ close_nointr_nofail(e->fd);
+}
+
+static void toggle_watch(DBusWatch *watch, void *data) {
+ EpollData *e;
+ struct epoll_event ev = {};
+
+ assert(watch);
+
+ e = dbus_watch_get_data(watch);
+ if (!e)
+ return;
+
+ ev.data.ptr = e;
+ ev.events = bus_flags_to_events(watch);
+
+ assert_se(epoll_ctl(PTR_TO_INT(data), EPOLL_CTL_MOD, e->fd, &ev) == 0);
+}
+
+static int timeout_arm(EpollData *e) {
+ struct itimerspec its = {};
+
+ assert(e);
+ assert(e->is_timeout);
+
+ if (dbus_timeout_get_enabled(e->object)) {
+ timespec_store(&its.it_value, dbus_timeout_get_interval(e->object) * USEC_PER_MSEC);
+ its.it_interval = its.it_value;
+ }
+
+ if (timerfd_settime(e->fd, 0, &its, NULL) < 0)
+ return -errno;
+
+ return 0;
+}
+
+static dbus_bool_t add_timeout(DBusTimeout *timeout, void *data) {
+ EpollData *e;
+ struct epoll_event ev = {};
+
+ assert(timeout);
+
+ e = new0(EpollData, 1);
+ if (!e)
+ return FALSE;
+
+ e->fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC);
+ if (e->fd < 0)
+ goto fail;
+
+ e->object = timeout;
+ e->is_timeout = true;
+
+ if (timeout_arm(e) < 0)
+ goto fail;
+
+ ev.events = EPOLLIN;
+ ev.data.ptr = e;
+
+ if (epoll_ctl(PTR_TO_INT(data), EPOLL_CTL_ADD, e->fd, &ev) < 0)
+ goto fail;
+
+ dbus_timeout_set_data(timeout, e, NULL);
+
+ return TRUE;
+
+fail:
+ if (e->fd >= 0)
+ close_nointr_nofail(e->fd);
+
+ free(e);
+ return FALSE;
+}
+
+static void remove_timeout(DBusTimeout *timeout, void *data) {
+ _cleanup_free_ EpollData *e = NULL;
+
+ assert(timeout);
+
+ e = dbus_timeout_get_data(timeout);
+ if (!e)
+ return;
+
+ assert_se(epoll_ctl(PTR_TO_INT(data), EPOLL_CTL_DEL, e->fd, NULL) >= 0);
+ close_nointr_nofail(e->fd);
+}
+
+static void toggle_timeout(DBusTimeout *timeout, void *data) {
+ EpollData *e;
+ int r;
+
+ assert(timeout);
+
+ e = dbus_timeout_get_data(timeout);
+ if (!e)
+ return;
+
+ r = timeout_arm(e);
+ if (r < 0)
+ log_error("Failed to rearm timer: %s", strerror(-r));
+}
+
+int bus_loop_open(DBusConnection *c) {
+ int fd;
+
+ assert(c);
+
+ fd = epoll_create1(EPOLL_CLOEXEC);
+ if (fd < 0)
+ return -errno;
+
+ if (!dbus_connection_set_watch_functions(c, add_watch, remove_watch, toggle_watch, INT_TO_PTR(fd), NULL) ||
+ !dbus_connection_set_timeout_functions(c, add_timeout, remove_timeout, toggle_timeout, INT_TO_PTR(fd), NULL)) {
+ close_nointr_nofail(fd);
+ return -ENOMEM;
+ }
+
+ return fd;
+}
+
+int bus_loop_dispatch(int fd) {
+ int n;
+ struct epoll_event event = {};
+ EpollData *d;
+
+ assert(fd >= 0);
+
+ n = epoll_wait(fd, &event, 1, 0);
+ if (n < 0)
+ return errno == EAGAIN || errno == EINTR ? 0 : -errno;
+
+ assert_se(d = event.data.ptr);
+
+ if (d->is_timeout) {
+ DBusTimeout *t = d->object;
+
+ if (dbus_timeout_get_enabled(t))
+ dbus_timeout_handle(t);
+ } else {
+ DBusWatch *w = d->object;
+
+ if (dbus_watch_get_enabled(w))
+ dbus_watch_handle(w, bus_events_to_flags(event.events));
+ }
+
+ return 0;
+}
diff --git a/src/shared/dbus-loop.h b/src/shared/dbus-loop.h
new file mode 100644
index 0000000000..a5e768d931
--- /dev/null
+++ b/src/shared/dbus-loop.h
@@ -0,0 +1,27 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <dbus/dbus.h>
+
+int bus_loop_open(DBusConnection *c);
+int bus_loop_dispatch(int fd);
diff --git a/src/shared/def.h b/src/shared/def.h
new file mode 100644
index 0000000000..5ba170f965
--- /dev/null
+++ b/src/shared/def.h
@@ -0,0 +1,35 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "util.h"
+
+#define DEFAULT_TIMEOUT_USEC (90*USEC_PER_SEC)
+#define DEFAULT_RESTART_USEC (100*USEC_PER_MSEC)
+#define DEFAULT_CONFIRM_USEC (30*USEC_PER_SEC)
+
+#define DEFAULT_EXIT_USEC (5*USEC_PER_MINUTE)
+
+#define SYSTEMD_CGROUP_CONTROLLER "name=systemd"
+
+#define SIGNALS_CRASH_HANDLER SIGSEGV,SIGILL,SIGFPE,SIGBUS,SIGQUIT,SIGABRT
+#define SIGNALS_IGNORE SIGKILL,SIGPIPE
diff --git a/src/shared/dev-setup.c b/src/shared/dev-setup.c
new file mode 100644
index 0000000000..b0ac02d461
--- /dev/null
+++ b/src/shared/dev-setup.c
@@ -0,0 +1,78 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010-2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <sys/stat.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+#include <unistd.h>
+
+#include "dev-setup.h"
+#include "log.h"
+#include "macro.h"
+#include "util.h"
+#include "label.h"
+
+static int symlink_and_label(const char *old_path, const char *new_path) {
+ int r;
+
+ assert(old_path);
+ assert(new_path);
+
+ r = label_context_set(new_path, S_IFLNK);
+ if (r < 0)
+ return r;
+
+ if (symlink(old_path, new_path) < 0)
+ r = -errno;
+
+ label_context_clear();
+
+ return r;
+}
+
+void dev_setup(const char *prefix) {
+ const char *j, *k;
+
+ static const char symlinks[] =
+ "/proc/kcore\0" "/dev/core\0"
+ "/proc/self/fd\0" "/dev/fd\0"
+ "/proc/self/fd/0\0" "/dev/stdin\0"
+ "/proc/self/fd/1\0" "/dev/stdout\0"
+ "/proc/self/fd/2\0" "/dev/stderr\0";
+
+ NULSTR_FOREACH_PAIR(j, k, symlinks) {
+
+ if (prefix) {
+ char *linkname;
+
+ if (asprintf(&linkname, "%s/%s", prefix, k) < 0) {
+ log_oom();
+ break;
+ }
+
+ symlink_and_label(j, linkname);
+ free(linkname);
+ } else
+ symlink_and_label(j, k);
+ }
+}
diff --git a/src/shared/dev-setup.h b/src/shared/dev-setup.h
new file mode 100644
index 0000000000..320c0b30ba
--- /dev/null
+++ b/src/shared/dev-setup.h
@@ -0,0 +1,24 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010-2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+void dev_setup(const char *pathprefix);
diff --git a/src/shared/efivars.c b/src/shared/efivars.c
new file mode 100644
index 0000000000..8d004bad33
--- /dev/null
+++ b/src/shared/efivars.c
@@ -0,0 +1,503 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <unistd.h>
+#include <string.h>
+#include <fcntl.h>
+#include <ctype.h>
+
+#include "util.h"
+#include "utf8.h"
+#include "efivars.h"
+
+#ifdef ENABLE_EFI
+
+bool is_efi_boot(void) {
+ return access("/sys/firmware/efi", F_OK) >= 0;
+}
+
+static int read_flag(const char *varname) {
+ int r;
+ void *v;
+ size_t s;
+ uint8_t b;
+
+ r = efi_get_variable(EFI_VENDOR_GLOBAL, varname, NULL, &v, &s);
+ if (r < 0)
+ return r;
+
+ if (s != 1) {
+ r = -EINVAL;
+ goto finish;
+ }
+
+ b = *(uint8_t *)v;
+ r = b > 0;
+finish:
+ free(v);
+ return r;
+}
+
+int is_efi_secure_boot(void) {
+ return read_flag("SecureBoot");
+}
+
+int is_efi_secure_boot_setup_mode(void) {
+ return read_flag("SetupMode");
+}
+
+int efi_get_variable(
+ sd_id128_t vendor,
+ const char *name,
+ uint32_t *attribute,
+ void **value,
+ size_t *size) {
+
+ _cleanup_close_ int fd = -1;
+ _cleanup_free_ char *p = NULL;
+ uint32_t a;
+ ssize_t n;
+ struct stat st;
+ void *r;
+
+ assert(name);
+ assert(value);
+ assert(size);
+
+ if (asprintf(&p,
+ "/sys/firmware/efi/efivars/%s-%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
+ name, SD_ID128_FORMAT_VAL(vendor)) < 0)
+ return -ENOMEM;
+
+ fd = open(p, O_RDONLY|O_NOCTTY|O_CLOEXEC);
+ if (fd < 0)
+ return -errno;
+
+ if (fstat(fd, &st) < 0)
+ return -errno;
+ if (st.st_size < 4)
+ return -EIO;
+ if (st.st_size > 4*1024*1024 + 4)
+ return -E2BIG;
+
+ n = read(fd, &a, sizeof(a));
+ if (n < 0)
+ return -errno;
+ if (n != sizeof(a))
+ return -EIO;
+
+ r = malloc(st.st_size - 4 + 2);
+ if (!r)
+ return -ENOMEM;
+
+ n = read(fd, r, (size_t) st.st_size - 4);
+ if (n < 0) {
+ free(r);
+ return -errno;
+ }
+ if (n != (ssize_t) st.st_size - 4) {
+ free(r);
+ return -EIO;
+ }
+
+ /* Always NUL terminate (2 bytes, to protect UTF-16) */
+ ((char*) r)[st.st_size - 4] = 0;
+ ((char*) r)[st.st_size - 4 + 1] = 0;
+
+ *value = r;
+ *size = (size_t) st.st_size - 4;
+
+ if (attribute)
+ *attribute = a;
+
+ return 0;
+}
+
+int efi_get_variable_string(sd_id128_t vendor, const char *name, char **p) {
+ _cleanup_free_ void *s = NULL;
+ size_t ss;
+ int r;
+ char *x;
+
+ r = efi_get_variable(vendor, name, NULL, &s, &ss);
+ if (r < 0)
+ return r;
+
+ x = utf16_to_utf8(s, ss);
+ if (!x)
+ return -ENOMEM;
+
+ *p = x;
+ return 0;
+}
+
+static size_t utf16_size(const uint16_t *s) {
+ size_t l = 0;
+
+ while (s[l] > 0)
+ l++;
+
+ return (l+1) * sizeof(uint16_t);
+}
+
+static void efi_guid_to_id128(const void *guid, sd_id128_t *id128) {
+ struct uuid {
+ uint32_t u1;
+ uint16_t u2;
+ uint16_t u3;
+ uint8_t u4[8];
+ } _packed_;
+ const struct uuid *uuid = guid;
+
+ id128->bytes[0] = (uuid->u1 >> 24) & 0xff;
+ id128->bytes[1] = (uuid->u1 >> 16) & 0xff;
+ id128->bytes[2] = (uuid->u1 >> 8) & 0xff;
+ id128->bytes[3] = (uuid->u1) & 0xff;
+ id128->bytes[4] = (uuid->u2 >> 8) & 0xff;
+ id128->bytes[5] = (uuid->u2) & 0xff;
+ id128->bytes[6] = (uuid->u3 >> 8) & 0xff;
+ id128->bytes[7] = (uuid->u3) & 0xff;
+ memcpy(&id128->bytes[8], uuid->u4, sizeof(uuid->u4));
+}
+
+int efi_get_boot_option(
+ uint16_t id,
+ char **title,
+ sd_id128_t *part_uuid,
+ char **path) {
+
+ struct boot_option {
+ uint32_t attr;
+ uint16_t path_len;
+ uint16_t title[];
+ } _packed_;
+
+ struct drive_path {
+ uint32_t part_nr;
+ uint64_t part_start;
+ uint64_t part_size;
+ char signature[16];
+ uint8_t mbr_type;
+ uint8_t signature_type;
+ } _packed_;
+
+ struct device_path {
+ uint8_t type;
+ uint8_t sub_type;
+ uint16_t length;
+ union {
+ uint16_t path[0];
+ struct drive_path drive;
+ };
+ } _packed_;
+
+ char boot_id[9];
+ _cleanup_free_ uint8_t *buf = NULL;
+ size_t l;
+ struct boot_option *header;
+ size_t title_size;
+ char *s = NULL;
+ char *p = NULL;
+ sd_id128_t p_uuid = SD_ID128_NULL;
+ int err;
+
+ snprintf(boot_id, sizeof(boot_id), "Boot%04X", id);
+ err = efi_get_variable(EFI_VENDOR_GLOBAL, boot_id, NULL, (void **)&buf, &l);
+ if (err < 0)
+ return err;
+ if (l < sizeof(struct boot_option))
+ return -ENOENT;
+
+ header = (struct boot_option *)buf;
+ title_size = utf16_size(header->title);
+ if (title_size > l - offsetof(struct boot_option, title))
+ return -EINVAL;
+
+ if (title) {
+ s = utf16_to_utf8(header->title, title_size);
+ if (!s) {
+ err = -ENOMEM;
+ goto err;
+ }
+ }
+
+ if (header->path_len > 0) {
+ uint8_t *dbuf;
+ size_t dnext;
+
+ dbuf = buf + offsetof(struct boot_option, title) + title_size;
+ dnext = 0;
+ while (dnext < header->path_len) {
+ struct device_path *dpath;
+
+ dpath = (struct device_path *)(dbuf + dnext);
+ if (dpath->length < 4)
+ break;
+
+ /* Type 0x7F – End of Hardware Device Path, Sub-Type 0xFF – End Entire Device Path */
+ if (dpath->type == 0x7f && dpath->sub_type == 0xff)
+ break;
+
+ dnext += dpath->length;
+
+ /* Type 0x04 – Media Device Path */
+ if (dpath->type != 0x04)
+ continue;
+
+ /* Sub-Type 1 – Hard Drive */
+ if (dpath->sub_type == 0x01) {
+ /* 0x02 – GUID Partition Table */
+ if (dpath->drive.mbr_type != 0x02)
+ continue;
+
+ /* 0x02 – GUID signature */
+ if (dpath->drive.signature_type != 0x02)
+ continue;
+
+ if (part_uuid)
+ efi_guid_to_id128(dpath->drive.signature, &p_uuid);
+ continue;
+ }
+
+ /* Sub-Type 4 – File Path */
+ if (dpath->sub_type == 0x04 && !p && path) {
+ p = utf16_to_utf8(dpath->path, dpath->length-4);
+ continue;
+ }
+ }
+ }
+
+ if (title)
+ *title = s;
+ if (part_uuid)
+ *part_uuid = p_uuid;
+ if (path)
+ *path = p;
+
+ return 0;
+err:
+ free(s);
+ free(p);
+ return err;
+}
+
+int efi_get_boot_order(uint16_t **order) {
+ void *buf;
+ size_t l;
+ int r;
+
+ r = efi_get_variable(EFI_VENDOR_GLOBAL, "BootOrder", NULL, &buf, &l);
+ if (r < 0)
+ return r;
+
+ if (l <= 0) {
+ free(buf);
+ return -ENOENT;
+ }
+
+ if ((l % sizeof(uint16_t) > 0) ||
+ (l / sizeof(uint16_t) > INT_MAX)) {
+ free(buf);
+ return -EINVAL;
+ }
+
+ *order = buf;
+ return (int) (l / sizeof(uint16_t));
+}
+
+static int boot_id_hex(const char s[4]) {
+ int i;
+ int id = 0;
+
+ for (i = 0; i < 4; i++)
+ if (s[i] >= '0' && s[i] <= '9')
+ id |= (s[i] - '0') << (3 - i) * 4;
+ else if (s[i] >= 'A' && s[i] <= 'F')
+ id |= (s[i] - 'A' + 10) << (3 - i) * 4;
+ else
+ return -1;
+
+ return id;
+}
+
+static int cmp_uint16(const void *_a, const void *_b) {
+ const uint16_t *a = _a, *b = _b;
+
+ return (int)*a - (int)*b;
+}
+
+int efi_get_boot_options(uint16_t **options) {
+ _cleanup_closedir_ DIR *dir = NULL;
+ struct dirent *de;
+ uint16_t *list = NULL;
+ int count = 0, r;
+
+ assert(options);
+
+ dir = opendir("/sys/firmware/efi/efivars/");
+ if (!dir)
+ return -errno;
+
+ FOREACH_DIRENT(de, dir, r = -errno; goto fail) {
+ int id;
+ uint16_t *t;
+
+ if (strncmp(de->d_name, "Boot", 4) != 0)
+ continue;
+
+ if (strlen(de->d_name) != 45)
+ continue;
+
+ if (strcmp(de->d_name + 8, "-8be4df61-93ca-11d2-aa0d-00e098032b8c") != 0)
+ continue;
+
+ id = boot_id_hex(de->d_name + 4);
+ if (id < 0)
+ continue;
+
+ t = realloc(list, (count + 1) * sizeof(uint16_t));
+ if (!t) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ list = t;
+ list[count ++] = id;
+ }
+
+ qsort(list, count, sizeof(uint16_t), cmp_uint16);
+
+ *options = list;
+ return count;
+
+fail:
+ free(list);
+ return r;
+}
+
+static int read_usec(sd_id128_t vendor, const char *name, usec_t *u) {
+ _cleanup_free_ char *j = NULL;
+ int r;
+ uint64_t x;
+
+ assert(name);
+ assert(u);
+
+ r = efi_get_variable_string(EFI_VENDOR_LOADER, name, &j);
+ if (r < 0)
+ return r;
+
+ r = safe_atou64(j, &x);
+ if (r < 0)
+ return r;
+
+ *u = x;
+ return 0;
+}
+
+static int get_boot_usec(usec_t *firmware, usec_t *loader) {
+ uint64_t x, y;
+ int r;
+
+ assert(firmware);
+ assert(loader);
+
+ r = read_usec(EFI_VENDOR_LOADER, "LoaderTimeInitUSec", &x);
+ if (r < 0)
+ return r;
+
+ r = read_usec(EFI_VENDOR_LOADER, "LoaderTimeExecUSec", &y);
+ if (r < 0)
+ return r;
+
+ if (y == 0 || y < x)
+ return -EIO;
+
+ if (y > USEC_PER_HOUR)
+ return -EIO;
+
+ *firmware = x;
+ *loader = y;
+
+ return 0;
+}
+
+int efi_get_boot_timestamps(const dual_timestamp *n, dual_timestamp *firmware, dual_timestamp *loader) {
+ usec_t x, y, a;
+ int r;
+ dual_timestamp _n;
+
+ assert(firmware);
+ assert(loader);
+
+ if (!n) {
+ dual_timestamp_get(&_n);
+ n = &_n;
+ }
+
+ r = get_boot_usec(&x, &y);
+ if (r < 0)
+ return r;
+
+ /* Let's convert this to timestamps where the firmware
+ * began/loader began working. To make this more confusing:
+ * since usec_t is unsigned and the kernel's monotonic clock
+ * begins at kernel initialization we'll actually initialize
+ * the monotonic timestamps here as negative of the actual
+ * value. */
+
+ firmware->monotonic = y;
+ loader->monotonic = y - x;
+
+ a = n->monotonic + firmware->monotonic;
+ firmware->realtime = n->realtime > a ? n->realtime - a : 0;
+
+ a = n->monotonic + loader->monotonic;
+ loader->realtime = n->realtime > a ? n->realtime - a : 0;
+
+ return 0;
+}
+
+int efi_get_loader_device_part_uuid(sd_id128_t *u) {
+ _cleanup_free_ char *p = NULL;
+ int r, parsed[16];
+ unsigned i;
+
+ assert(u);
+
+ r = efi_get_variable_string(EFI_VENDOR_LOADER, "LoaderDevicePartUUID", &p);
+ if (r < 0)
+ return r;
+
+ if (sscanf(p, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
+ &parsed[0], &parsed[1], &parsed[2], &parsed[3],
+ &parsed[4], &parsed[5], &parsed[6], &parsed[7],
+ &parsed[8], &parsed[9], &parsed[10], &parsed[11],
+ &parsed[12], &parsed[13], &parsed[14], &parsed[15]) != 16)
+ return -EIO;
+
+ for (i = 0; i < ELEMENTSOF(parsed); i++)
+ u->bytes[i] = parsed[i];
+
+ return 0;
+}
+
+#endif
diff --git a/src/shared/efivars.h b/src/shared/efivars.h
new file mode 100644
index 0000000000..2b88c6075c
--- /dev/null
+++ b/src/shared/efivars.h
@@ -0,0 +1,47 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/types.h>
+#include <inttypes.h>
+#include <stdbool.h>
+
+#include "sd-id128.h"
+#include "time-util.h"
+
+#define EFI_VENDOR_LOADER SD_ID128_MAKE(4a,67,b0,82,0a,4c,41,cf,b6,c7,44,0b,29,bb,8c,4f)
+#define EFI_VENDOR_GLOBAL SD_ID128_MAKE(8b,e4,df,61,93,ca,11,d2,aa,0d,00,e0,98,03,2b,8c)
+
+bool is_efi_boot(void);
+int is_efi_secure_boot(void);
+int is_efi_secure_boot_setup_mode(void);
+
+int efi_get_variable(sd_id128_t vendor, const char *name, uint32_t *attribute, void **value, size_t *size);
+int efi_get_variable_string(sd_id128_t vendor, const char *name, char **p);
+
+int efi_get_boot_option(uint16_t nr, char **title, sd_id128_t *partuuid, char **path);
+int efi_get_boot_order(uint16_t **order);
+int efi_get_boot_options(uint16_t **options);
+
+int efi_get_boot_timestamps(const dual_timestamp *n, dual_timestamp *firmware, dual_timestamp *loader);
+
+int efi_get_loader_device_part_uuid(sd_id128_t *u);
diff --git a/src/shared/env-util.c b/src/shared/env-util.c
new file mode 100644
index 0000000000..6a52fb960d
--- /dev/null
+++ b/src/shared/env-util.c
@@ -0,0 +1,415 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <limits.h>
+#include <sys/param.h>
+#include <unistd.h>
+
+#include "strv.h"
+#include "utf8.h"
+#include "util.h"
+#include "env-util.h"
+
+#define VALID_CHARS_ENV_NAME \
+ "0123456789" \
+ "abcdefghijklmnopqrstuvwxyz" \
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
+ "_"
+
+#ifndef ARG_MAX
+#define ARG_MAX ((size_t) sysconf(_SC_ARG_MAX))
+#endif
+
+static bool env_name_is_valid_n(const char *e, size_t n) {
+ const char *p;
+
+ if (!e)
+ return false;
+
+ if (n <= 0)
+ return false;
+
+ if (e[0] >= '0' && e[0] <= '9')
+ return false;
+
+ /* POSIX says the overall size of the environment block cannot
+ * be > ARG_MAX, an individual assignment hence cannot be
+ * either. Discounting the equal sign and trailing NUL this
+ * hence leaves ARG_MAX-2 as longest possible variable
+ * name. */
+ if (n > ARG_MAX - 2)
+ return false;
+
+ for (p = e; p < e + n; p++)
+ if (!strchr(VALID_CHARS_ENV_NAME, *p))
+ return false;
+
+ return true;
+}
+
+bool env_name_is_valid(const char *e) {
+ if (!e)
+ return false;
+
+ return env_name_is_valid_n(e, strlen(e));
+}
+
+bool env_value_is_valid(const char *e) {
+ if (!e)
+ return false;
+
+ if (!utf8_is_valid(e))
+ return false;
+
+ if (string_has_cc(e))
+ return false;
+
+ /* POSIX says the overall size of the environment block cannot
+ * be > ARG_MAX, an individual assignment hence cannot be
+ * either. Discounting the shortest possible variable name of
+ * length 1, the equal sign and trailing NUL this hence leaves
+ * ARG_MAX-3 as longest possible variable value. */
+ if (strlen(e) > ARG_MAX - 3)
+ return false;
+
+ return true;
+}
+
+bool env_assignment_is_valid(const char *e) {
+ const char *eq;
+
+ eq = strchr(e, '=');
+ if (!eq)
+ return false;
+
+ if (!env_name_is_valid_n(e, eq - e))
+ return false;
+
+ if (!env_value_is_valid(eq + 1))
+ return false;
+
+ /* POSIX says the overall size of the environment block cannot
+ * be > ARG_MAX, hence the individual variable assignments
+ * cannot be either, but let's leave room for one trailing NUL
+ * byte. */
+ if (strlen(e) > ARG_MAX - 1)
+ return false;
+
+ return true;
+}
+
+bool strv_env_is_valid(char **e) {
+ char **p, **q;
+
+ STRV_FOREACH(p, e) {
+ size_t k;
+
+ if (!env_assignment_is_valid(*p))
+ return false;
+
+ /* Check if there are duplicate assginments */
+ k = strcspn(*p, "=");
+ STRV_FOREACH(q, p + 1)
+ if (strneq(*p, *q, k) && (*q)[k] == '=')
+ return false;
+ }
+
+ return true;
+}
+
+bool strv_env_name_or_assignment_is_valid(char **l) {
+ char **p, **q;
+
+ STRV_FOREACH(p, l) {
+ if (!env_assignment_is_valid(*p) && !env_name_is_valid(*p))
+ return false;
+
+ STRV_FOREACH(q, p + 1)
+ if (streq(*p, *q))
+ return false;
+ }
+
+ return true;
+}
+
+static int env_append(char **r, char ***k, char **a) {
+ assert(r);
+ assert(k);
+
+ if (!a)
+ return 0;
+
+ /* Add the entries of a to *k unless they already exist in *r
+ * in which case they are overridden instead. This assumes
+ * there is enough space in the r array. */
+
+ for (; *a; a++) {
+ char **j;
+ size_t n;
+
+ n = strcspn(*a, "=");
+
+ if ((*a)[n] == '=')
+ n++;
+
+ for (j = r; j < *k; j++)
+ if (strneq(*j, *a, n))
+ break;
+
+ if (j >= *k)
+ (*k)++;
+ else
+ free(*j);
+
+ *j = strdup(*a);
+ if (!*j)
+ return -ENOMEM;
+ }
+
+ return 0;
+}
+
+char **strv_env_merge(unsigned n_lists, ...) {
+ size_t n = 0;
+ char **l, **k, **r;
+ va_list ap;
+ unsigned i;
+
+ /* Merges an arbitrary number of environment sets */
+
+ va_start(ap, n_lists);
+ for (i = 0; i < n_lists; i++) {
+ l = va_arg(ap, char**);
+ n += strv_length(l);
+ }
+ va_end(ap);
+
+ r = new(char*, n+1);
+ if (!r)
+ return NULL;
+
+ k = r;
+
+ va_start(ap, n_lists);
+ for (i = 0; i < n_lists; i++) {
+ l = va_arg(ap, char**);
+ if (env_append(r, &k, l) < 0)
+ goto fail;
+ }
+ va_end(ap);
+
+ *k = NULL;
+
+ return r;
+
+fail:
+ va_end(ap);
+ strv_free(r);
+
+ return NULL;
+}
+
+_pure_ static bool env_match(const char *t, const char *pattern) {
+ assert(t);
+ assert(pattern);
+
+ /* pattern a matches string a
+ * a matches a=
+ * a matches a=b
+ * a= matches a=
+ * a=b matches a=b
+ * a= does not match a
+ * a=b does not match a=
+ * a=b does not match a
+ * a=b does not match a=c */
+
+ if (streq(t, pattern))
+ return true;
+
+ if (!strchr(pattern, '=')) {
+ size_t l = strlen(pattern);
+
+ return strneq(t, pattern, l) && t[l] == '=';
+ }
+
+ return false;
+}
+
+char **strv_env_delete(char **x, unsigned n_lists, ...) {
+ size_t n, i = 0;
+ char **k, **r;
+ va_list ap;
+
+ /* Deletes every entry from x that is mentioned in the other
+ * string lists */
+
+ n = strv_length(x);
+
+ r = new(char*, n+1);
+ if (!r)
+ return NULL;
+
+ STRV_FOREACH(k, x) {
+ unsigned v;
+
+ va_start(ap, n_lists);
+ for (v = 0; v < n_lists; v++) {
+ char **l, **j;
+
+ l = va_arg(ap, char**);
+ STRV_FOREACH(j, l)
+ if (env_match(*k, *j))
+ goto skip;
+ }
+ va_end(ap);
+
+ r[i] = strdup(*k);
+ if (!r[i]) {
+ strv_free(r);
+ return NULL;
+ }
+
+ i++;
+ continue;
+
+ skip:
+ va_end(ap);
+ }
+
+ r[i] = NULL;
+
+ assert(i <= n);
+
+ return r;
+}
+
+char **strv_env_unset(char **l, const char *p) {
+
+ char **f, **t;
+
+ if (!l)
+ return NULL;
+
+ assert(p);
+
+ /* Drops every occurrence of the env var setting p in the
+ * string list. edits in-place. */
+
+ for (f = t = l; *f; f++) {
+
+ if (env_match(*f, p)) {
+ free(*f);
+ continue;
+ }
+
+ *(t++) = *f;
+ }
+
+ *t = NULL;
+ return l;
+}
+
+char **strv_env_set(char **x, const char *p) {
+
+ char **k, **r;
+ char* m[2] = { (char*) p, NULL };
+
+ /* Overrides the env var setting of p, returns a new copy */
+
+ r = new(char*, strv_length(x)+2);
+ if (!r)
+ return NULL;
+
+ k = r;
+ if (env_append(r, &k, x) < 0)
+ goto fail;
+
+ if (env_append(r, &k, m) < 0)
+ goto fail;
+
+ *k = NULL;
+
+ return r;
+
+fail:
+ strv_free(r);
+ return NULL;
+}
+
+char *strv_env_get_n(char **l, const char *name, size_t k) {
+ char **i;
+
+ assert(name);
+
+ if (k <= 0)
+ return NULL;
+
+ STRV_FOREACH(i, l)
+ if (strneq(*i, name, k) &&
+ (*i)[k] == '=')
+ return *i + k + 1;
+
+ return NULL;
+}
+
+char *strv_env_get(char **l, const char *name) {
+ assert(name);
+
+ return strv_env_get_n(l, name, strlen(name));
+}
+
+char **strv_env_clean_log(char **e, const char *message) {
+ char **p, **q;
+ int k = 0;
+
+ STRV_FOREACH(p, e) {
+ size_t n;
+ bool duplicate = false;
+
+ if (!env_assignment_is_valid(*p)) {
+ if (message)
+ log_error("Ignoring invalid environment '%s': %s", *p, message);
+ free(*p);
+ continue;
+ }
+
+ n = strcspn(*p, "=");
+ STRV_FOREACH(q, p + 1)
+ if (strneq(*p, *q, n) && (*q)[n] == '=') {
+ duplicate = true;
+ break;
+ }
+
+ if (duplicate) {
+ free(*p);
+ continue;
+ }
+
+ e[k++] = *p;
+ }
+
+ e[k] = NULL;
+ return e;
+}
+
+char **strv_env_clean(char **e) {
+ return strv_env_clean_log(e, NULL);
+}
diff --git a/src/shared/env-util.h b/src/shared/env-util.h
new file mode 100644
index 0000000000..8d2114b64c
--- /dev/null
+++ b/src/shared/env-util.h
@@ -0,0 +1,44 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdbool.h>
+#include <sys/types.h>
+
+bool env_name_is_valid(const char *e);
+bool env_value_is_valid(const char *e);
+bool env_assignment_is_valid(const char *e);
+
+bool strv_env_is_valid(char **e);
+char **strv_env_clean(char **l);
+char **strv_env_clean_log(char **e, const char *message);
+
+bool strv_env_name_or_assignment_is_valid(char **l);
+
+char **strv_env_merge(unsigned n_lists, ...);
+char **strv_env_delete(char **x, unsigned n_lists, ...); /* New copy */
+
+char **strv_env_set(char **x, const char *p); /* New copy ... */
+char **strv_env_unset(char **l, const char *p); /* In place ... */
+
+char *strv_env_get_n(char **l, const char *name, size_t k) _pure_;
+char *strv_env_get(char **x, const char *n) _pure_;
diff --git a/src/shared/exit-status.c b/src/shared/exit-status.c
new file mode 100644
index 0000000000..45131f2b2a
--- /dev/null
+++ b/src/shared/exit-status.c
@@ -0,0 +1,192 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdlib.h>
+#include <sys/wait.h>
+
+#include "exit-status.h"
+#include "set.h"
+#include "macro.h"
+
+const char* exit_status_to_string(ExitStatus status, ExitStatusLevel level) {
+
+ /* We cast to int here, so that -Wenum doesn't complain that
+ * EXIT_SUCCESS/EXIT_FAILURE aren't in the enum */
+
+ switch ((int) status) {
+
+ case EXIT_SUCCESS:
+ return "SUCCESS";
+
+ case EXIT_FAILURE:
+ return "FAILURE";
+ }
+
+
+ if (level == EXIT_STATUS_SYSTEMD || level == EXIT_STATUS_LSB) {
+ switch ((int) status) {
+
+ case EXIT_CHDIR:
+ return "CHDIR";
+
+ case EXIT_NICE:
+ return "NICE";
+
+ case EXIT_FDS:
+ return "FDS";
+
+ case EXIT_EXEC:
+ return "EXEC";
+
+ case EXIT_MEMORY:
+ return "MEMORY";
+
+ case EXIT_LIMITS:
+ return "LIMITS";
+
+ case EXIT_OOM_ADJUST:
+ return "OOM_ADJUST";
+
+ case EXIT_SIGNAL_MASK:
+ return "SIGNAL_MASK";
+
+ case EXIT_STDIN:
+ return "STDIN";
+
+ case EXIT_STDOUT:
+ return "STDOUT";
+
+ case EXIT_CHROOT:
+ return "CHROOT";
+
+ case EXIT_IOPRIO:
+ return "IOPRIO";
+
+ case EXIT_TIMERSLACK:
+ return "TIMERSLACK";
+
+ case EXIT_SECUREBITS:
+ return "SECUREBITS";
+
+ case EXIT_SETSCHEDULER:
+ return "SETSCHEDULER";
+
+ case EXIT_CPUAFFINITY:
+ return "CPUAFFINITY";
+
+ case EXIT_GROUP:
+ return "GROUP";
+
+ case EXIT_USER:
+ return "USER";
+
+ case EXIT_CAPABILITIES:
+ return "CAPABILITIES";
+
+ case EXIT_CGROUP:
+ return "CGROUP";
+
+ case EXIT_SETSID:
+ return "SETSID";
+
+ case EXIT_CONFIRM:
+ return "CONFIRM";
+
+ case EXIT_STDERR:
+ return "STDERR";
+
+ case EXIT_TCPWRAP:
+ return "TCPWRAP";
+
+ case EXIT_PAM:
+ return "PAM";
+
+ case EXIT_NETWORK:
+ return "NETWORK";
+
+ case EXIT_NAMESPACE:
+ return "NAMESPACE";
+
+ case EXIT_NO_NEW_PRIVILEGES:
+ return "NO_NEW_PRIVILEGES";
+
+ case EXIT_SECCOMP:
+ return "SECCOMP";
+ }
+ }
+
+ if (level == EXIT_STATUS_LSB) {
+ switch ((int) status) {
+
+ case EXIT_INVALIDARGUMENT:
+ return "INVALIDARGUMENT";
+
+ case EXIT_NOTIMPLEMENTED:
+ return "NOTIMPLEMENTED";
+
+ case EXIT_NOPERMISSION:
+ return "NOPERMISSION";
+
+ case EXIT_NOTINSTALLED:
+ return "NOTINSSTALLED";
+
+ case EXIT_NOTCONFIGURED:
+ return "NOTCONFIGURED";
+
+ case EXIT_NOTRUNNING:
+ return "NOTRUNNING";
+ }
+ }
+
+ return NULL;
+}
+
+
+bool is_clean_exit(int code, int status, ExitStatusSet *success_status) {
+
+ if (code == CLD_EXITED)
+ return status == 0 ||
+ (success_status &&
+ set_contains(success_status->code, INT_TO_PTR(status)));
+
+ /* If a daemon does not implement handlers for some of the
+ * signals that's not considered an unclean shutdown */
+ if (code == CLD_KILLED)
+ return
+ status == SIGHUP ||
+ status == SIGINT ||
+ status == SIGTERM ||
+ status == SIGPIPE ||
+ (success_status &&
+ set_contains(success_status->signal, INT_TO_PTR(status)));
+
+ return false;
+}
+
+bool is_clean_exit_lsb(int code, int status, ExitStatusSet *success_status) {
+
+ if (is_clean_exit(code, status, success_status))
+ return true;
+
+ return
+ code == CLD_EXITED &&
+ (status == EXIT_NOTINSTALLED || status == EXIT_NOTCONFIGURED);
+}
diff --git a/src/shared/exit-status.h b/src/shared/exit-status.h
new file mode 100644
index 0000000000..1f035a3007
--- /dev/null
+++ b/src/shared/exit-status.h
@@ -0,0 +1,88 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdbool.h>
+#include "set.h"
+typedef enum ExitStatus {
+ /* EXIT_SUCCESS defined by libc */
+ /* EXIT_FAILURE defined by libc */
+ EXIT_INVALIDARGUMENT = 2,
+ EXIT_NOTIMPLEMENTED = 3,
+ EXIT_NOPERMISSION = 4,
+ EXIT_NOTINSTALLED = 5,
+ EXIT_NOTCONFIGURED = 6,
+ EXIT_NOTRUNNING = 7,
+
+ /* The LSB suggests that error codes >= 200 are "reserved". We
+ * use them here under the assumption that they hence are
+ * unused by init scripts.
+ *
+ * http://refspecs.freestandards.org/LSB_3.1.0/LSB-Core-generic/LSB-Core-generic/iniscrptact.html */
+
+ EXIT_CHDIR = 200,
+ EXIT_NICE,
+ EXIT_FDS,
+ EXIT_EXEC,
+ EXIT_MEMORY,
+ EXIT_LIMITS,
+ EXIT_OOM_ADJUST,
+ EXIT_SIGNAL_MASK,
+ EXIT_STDIN,
+ EXIT_STDOUT,
+ EXIT_CHROOT, /* 210 */
+ EXIT_IOPRIO,
+ EXIT_TIMERSLACK,
+ EXIT_SECUREBITS,
+ EXIT_SETSCHEDULER,
+ EXIT_CPUAFFINITY,
+ EXIT_GROUP,
+ EXIT_USER,
+ EXIT_CAPABILITIES,
+ EXIT_CGROUP,
+ EXIT_SETSID, /* 220 */
+ EXIT_CONFIRM,
+ EXIT_STDERR,
+ EXIT_TCPWRAP,
+ EXIT_PAM,
+ EXIT_NETWORK,
+ EXIT_NAMESPACE,
+ EXIT_NO_NEW_PRIVILEGES,
+ EXIT_SECCOMP
+} ExitStatus;
+
+typedef enum ExitStatusLevel {
+ EXIT_STATUS_MINIMAL,
+ EXIT_STATUS_SYSTEMD,
+ EXIT_STATUS_LSB,
+ EXIT_STATUS_FULL = EXIT_STATUS_LSB
+} ExitStatusLevel;
+
+typedef struct ExitStatusSet {
+ Set *code;
+ Set *signal;
+} ExitStatusSet;
+
+const char* exit_status_to_string(ExitStatus status, ExitStatusLevel level) _const_;
+
+bool is_clean_exit(int code, int status, ExitStatusSet *success_status);
+bool is_clean_exit_lsb(int code, int status, ExitStatusSet *success_status);
diff --git a/src/shared/fdset.c b/src/shared/fdset.c
new file mode 100644
index 0000000000..fd27398ebb
--- /dev/null
+++ b/src/shared/fdset.c
@@ -0,0 +1,236 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <dirent.h>
+#include <fcntl.h>
+#include <unistd.h>
+
+#include "set.h"
+#include "util.h"
+#include "macro.h"
+#include "fdset.h"
+#include "sd-daemon.h"
+
+#define MAKE_SET(s) ((Set*) s)
+#define MAKE_FDSET(s) ((FDSet*) s)
+
+/* Make sure we can distuingish fd 0 and NULL */
+#define FD_TO_PTR(fd) INT_TO_PTR((fd)+1)
+#define PTR_TO_FD(p) (PTR_TO_INT(p)-1)
+
+FDSet *fdset_new(void) {
+ return MAKE_FDSET(set_new(trivial_hash_func, trivial_compare_func));
+}
+
+void fdset_free(FDSet *s) {
+ void *p;
+
+ while ((p = set_steal_first(MAKE_SET(s)))) {
+ /* Valgrind's fd might have ended up in this set here,
+ * due to fdset_new_fill(). We'll ignore all failures
+ * here, so that the EBADFD that valgrind will return
+ * us on close() doesn't influence us */
+
+ /* When reloading duplicates of the private bus
+ * connection fds and suchlike are closed here, which
+ * has no effect at all, since they are only
+ * duplicates. So don't be surprised about these log
+ * messages. */
+
+ log_debug("Closing left-over fd %i", PTR_TO_FD(p));
+ close_nointr(PTR_TO_FD(p));
+ }
+
+ set_free(MAKE_SET(s));
+}
+
+int fdset_put(FDSet *s, int fd) {
+ assert(s);
+ assert(fd >= 0);
+
+ return set_put(MAKE_SET(s), FD_TO_PTR(fd));
+}
+
+int fdset_put_dup(FDSet *s, int fd) {
+ int copy, r;
+
+ assert(s);
+ assert(fd >= 0);
+
+ copy = fcntl(fd, F_DUPFD_CLOEXEC, 3);
+ if (copy < 0)
+ return -errno;
+
+ r = fdset_put(s, copy);
+ if (r < 0) {
+ close_nointr_nofail(copy);
+ return r;
+ }
+
+ return copy;
+}
+
+bool fdset_contains(FDSet *s, int fd) {
+ assert(s);
+ assert(fd >= 0);
+
+ return !!set_get(MAKE_SET(s), FD_TO_PTR(fd));
+}
+
+int fdset_remove(FDSet *s, int fd) {
+ assert(s);
+ assert(fd >= 0);
+
+ return set_remove(MAKE_SET(s), FD_TO_PTR(fd)) ? fd : -ENOENT;
+}
+
+int fdset_new_fill(FDSet **_s) {
+ DIR *d;
+ struct dirent *de;
+ int r = 0;
+ FDSet *s;
+
+ assert(_s);
+
+ /* Creates an fdset and fills in all currently open file
+ * descriptors. */
+
+ d = opendir("/proc/self/fd");
+ if (!d)
+ return -errno;
+
+ s = fdset_new();
+ if (!s) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ while ((de = readdir(d))) {
+ int fd = -1;
+
+ if (ignore_file(de->d_name))
+ continue;
+
+ r = safe_atoi(de->d_name, &fd);
+ if (r < 0)
+ goto finish;
+
+ if (fd < 3)
+ continue;
+
+ if (fd == dirfd(d))
+ continue;
+
+ r = fdset_put(s, fd);
+ if (r < 0)
+ goto finish;
+ }
+
+ r = 0;
+ *_s = s;
+ s = NULL;
+
+finish:
+ closedir(d);
+
+ /* We won't close the fds here! */
+ if (s)
+ set_free(MAKE_SET(s));
+
+ return r;
+}
+
+int fdset_cloexec(FDSet *fds, bool b) {
+ Iterator i;
+ void *p;
+ int r;
+
+ assert(fds);
+
+ SET_FOREACH(p, MAKE_SET(fds), i)
+ if ((r = fd_cloexec(PTR_TO_FD(p), b)) < 0)
+ return r;
+
+ return 0;
+}
+
+int fdset_new_listen_fds(FDSet **_s, bool unset) {
+ int n, fd, r;
+ FDSet *s;
+
+ assert(_s);
+
+ /* Creates an fdset and fills in all passed file descriptors */
+
+ s = fdset_new();
+ if (!s) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ n = sd_listen_fds(unset);
+ for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd ++) {
+ r = fdset_put(s, fd);
+ if (r < 0)
+ goto fail;
+ }
+
+ *_s = s;
+ return 0;
+
+
+fail:
+ if (s)
+ set_free(MAKE_SET(s));
+
+ return r;
+}
+
+int fdset_close_others(FDSet *fds) {
+ void *e;
+ Iterator i;
+ int *a;
+ unsigned j, m;
+
+ j = 0, m = fdset_size(fds);
+ a = alloca(sizeof(int) * m);
+ SET_FOREACH(e, MAKE_SET(fds), i)
+ a[j++] = PTR_TO_FD(e);
+
+ assert(j == m);
+
+ return close_all_fds(a, j);
+}
+
+unsigned fdset_size(FDSet *fds) {
+ return set_size(MAKE_SET(fds));
+}
+
+int fdset_iterate(FDSet *s, Iterator *i) {
+ void *p;
+
+ p = set_iterate(MAKE_SET(s), i);
+ if (!p)
+ return -ENOENT;
+
+ return PTR_TO_FD(p);
+}
diff --git a/src/shared/fdset.h b/src/shared/fdset.h
new file mode 100644
index 0000000000..a7bd5e2b40
--- /dev/null
+++ b/src/shared/fdset.h
@@ -0,0 +1,49 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "set.h"
+
+typedef struct FDSet FDSet;
+
+FDSet* fdset_new(void);
+void fdset_free(FDSet *s);
+
+int fdset_put(FDSet *s, int fd);
+int fdset_put_dup(FDSet *s, int fd);
+
+bool fdset_contains(FDSet *s, int fd);
+int fdset_remove(FDSet *s, int fd);
+
+int fdset_new_fill(FDSet **_s);
+int fdset_new_listen_fds(FDSet **_s, bool unset);
+
+int fdset_cloexec(FDSet *fds, bool b);
+
+int fdset_close_others(FDSet *fds);
+
+unsigned fdset_size(FDSet *fds);
+
+int fdset_iterate(FDSet *s, Iterator *i);
+
+#define FDSET_FOREACH(fd, fds, i) \
+ for ((i) = ITERATOR_FIRST, (fd) = fdset_iterate((fds), &(i)); (fd) >= 0; (fd) = fdset_iterate((fds), &(i)))
diff --git a/src/shared/fileio-label.c b/src/shared/fileio-label.c
new file mode 100644
index 0000000000..0711826e85
--- /dev/null
+++ b/src/shared/fileio-label.c
@@ -0,0 +1,55 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+ Copyright 2010 Harald Hoyer
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include "fileio-label.h"
+#include "label.h"
+
+int write_string_file_atomic_label(const char *fn, const char *line) {
+ int r;
+
+ r = label_context_set(fn, S_IFREG);
+ if (r < 0)
+ return r;
+
+ write_string_file_atomic(fn, line);
+
+ label_context_clear();
+
+ return r;
+}
+
+int write_env_file_label(const char *fname, char **l) {
+ int r;
+
+ r = label_context_set(fname, S_IFREG);
+ if (r < 0)
+ return r;
+
+ write_env_file(fname, l);
+
+ label_context_clear();
+
+ return r;
+}
diff --git a/src/shared/fileio-label.h b/src/shared/fileio-label.h
new file mode 100644
index 0000000000..fce4fe0d73
--- /dev/null
+++ b/src/shared/fileio-label.h
@@ -0,0 +1,29 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+ Copyright 2010 Harald Hoyer
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include "fileio.h"
+
+int write_string_file_atomic_label(const char *fn, const char *line);
+int write_env_file_label(const char *fname, char **l);
diff --git a/src/shared/fileio.c b/src/shared/fileio.c
new file mode 100644
index 0000000000..ad068bf30d
--- /dev/null
+++ b/src/shared/fileio.c
@@ -0,0 +1,596 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <unistd.h>
+#include "fileio.h"
+#include "util.h"
+#include "strv.h"
+
+
+int write_string_to_file(FILE *f, const char *line) {
+ errno = 0;
+ fputs(line, f);
+ if (!endswith(line, "\n"))
+ fputc('\n', f);
+
+ fflush(f);
+
+ if (ferror(f))
+ return errno ? -errno : -EIO;
+
+ return 0;
+}
+
+int write_string_file(const char *fn, const char *line) {
+ _cleanup_fclose_ FILE *f = NULL;
+
+ assert(fn);
+ assert(line);
+
+ f = fopen(fn, "we");
+ if (!f)
+ return -errno;
+
+ return write_string_to_file(f, line);
+}
+
+int write_string_file_atomic(const char *fn, const char *line) {
+ _cleanup_fclose_ FILE *f = NULL;
+ _cleanup_free_ char *p = NULL;
+ int r;
+
+ assert(fn);
+ assert(line);
+
+ r = fopen_temporary(fn, &f, &p);
+ if (r < 0)
+ return r;
+
+ fchmod_umask(fileno(f), 0644);
+
+ errno = 0;
+ fputs(line, f);
+ if (!endswith(line, "\n"))
+ fputc('\n', f);
+
+ fflush(f);
+
+ if (ferror(f))
+ r = errno ? -errno : -EIO;
+ else {
+ if (rename(p, fn) < 0)
+ r = -errno;
+ else
+ r = 0;
+ }
+
+ if (r < 0)
+ unlink(p);
+
+ return r;
+}
+
+int read_one_line_file(const char *fn, char **line) {
+ _cleanup_fclose_ FILE *f = NULL;
+ char t[LINE_MAX], *c;
+
+ assert(fn);
+ assert(line);
+
+ f = fopen(fn, "re");
+ if (!f)
+ return -errno;
+
+ if (!fgets(t, sizeof(t), f)) {
+
+ if (ferror(f))
+ return errno ? -errno : -EIO;
+
+ t[0] = 0;
+ }
+
+ c = strdup(t);
+ if (!c)
+ return -ENOMEM;
+ truncate_nl(c);
+
+ *line = c;
+ return 0;
+}
+
+int read_full_file(const char *fn, char **contents, size_t *size) {
+ _cleanup_fclose_ FILE *f = NULL;
+ size_t n, l;
+ _cleanup_free_ char *buf = NULL;
+ struct stat st;
+
+ assert(fn);
+ assert(contents);
+
+ f = fopen(fn, "re");
+ if (!f)
+ return -errno;
+
+ if (fstat(fileno(f), &st) < 0)
+ return -errno;
+
+ /* Safety check */
+ if (st.st_size > 4*1024*1024)
+ return -E2BIG;
+
+ n = st.st_size > 0 ? st.st_size : LINE_MAX;
+ l = 0;
+
+ for (;;) {
+ char *t;
+ size_t k;
+
+ t = realloc(buf, n+1);
+ if (!t)
+ return -ENOMEM;
+
+ buf = t;
+ k = fread(buf + l, 1, n - l, f);
+
+ if (k <= 0) {
+ if (ferror(f))
+ return -errno;
+
+ break;
+ }
+
+ l += k;
+ n *= 2;
+
+ /* Safety check */
+ if (n > 4*1024*1024)
+ return -E2BIG;
+ }
+
+ buf[l] = 0;
+ *contents = buf;
+ buf = NULL;
+
+ if (size)
+ *size = l;
+
+ return 0;
+}
+
+static int parse_env_file_internal(
+ const char *fname,
+ const char *newline,
+ int (*push) (const char *key, char *value, void *userdata),
+ void *userdata) {
+
+ _cleanup_free_ char *contents = NULL, *key = NULL;
+ size_t key_alloc = 0, n_key = 0, value_alloc = 0, n_value = 0, last_value_whitespace = (size_t) -1, last_key_whitespace = (size_t) -1;
+ char *p, *value = NULL;
+ int r;
+
+ enum {
+ PRE_KEY,
+ KEY,
+ PRE_VALUE,
+ VALUE,
+ VALUE_ESCAPE,
+ SINGLE_QUOTE_VALUE,
+ SINGLE_QUOTE_VALUE_ESCAPE,
+ DOUBLE_QUOTE_VALUE,
+ DOUBLE_QUOTE_VALUE_ESCAPE,
+ COMMENT,
+ COMMENT_ESCAPE
+ } state = PRE_KEY;
+
+ assert(fname);
+ assert(newline);
+
+ r = read_full_file(fname, &contents, NULL);
+ if (r < 0)
+ return r;
+
+ for (p = contents; *p; p++) {
+ char c = *p;
+
+ switch (state) {
+
+ case PRE_KEY:
+ if (strchr(COMMENTS, c))
+ state = COMMENT;
+ else if (!strchr(WHITESPACE, c)) {
+ state = KEY;
+ last_key_whitespace = (size_t) -1;
+
+ if (!greedy_realloc((void**) &key, &key_alloc, n_key+2)) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ key[n_key++] = c;
+ }
+ break;
+
+ case KEY:
+ if (strchr(newline, c)) {
+ state = PRE_KEY;
+ n_key = 0;
+ } else if (c == '=') {
+ state = PRE_VALUE;
+ last_value_whitespace = (size_t) -1;
+ } else {
+ if (!strchr(WHITESPACE, c))
+ last_key_whitespace = (size_t) -1;
+ else if (last_key_whitespace == (size_t) -1)
+ last_key_whitespace = n_key;
+
+ if (!greedy_realloc((void**) &key, &key_alloc, n_key+2)) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ key[n_key++] = c;
+ }
+
+ break;
+
+ case PRE_VALUE:
+ if (strchr(newline, c)) {
+ state = PRE_KEY;
+ key[n_key] = 0;
+
+ if (value)
+ value[n_value] = 0;
+
+ /* strip trailing whitespace from key */
+ if (last_key_whitespace != (size_t) -1)
+ key[last_key_whitespace] = 0;
+
+ r = push(key, value, userdata);
+ if (r < 0)
+ goto fail;
+
+ n_key = 0;
+ value = NULL;
+ value_alloc = n_value = 0;
+
+ } else if (c == '\'')
+ state = SINGLE_QUOTE_VALUE;
+ else if (c == '\"')
+ state = DOUBLE_QUOTE_VALUE;
+ else if (c == '\\')
+ state = VALUE_ESCAPE;
+ else if (!strchr(WHITESPACE, c)) {
+ state = VALUE;
+
+ if (!greedy_realloc((void**) &value, &value_alloc, n_value+2)) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ value[n_value++] = c;
+ }
+
+ break;
+
+ case VALUE:
+ if (strchr(newline, c)) {
+ state = PRE_KEY;
+
+ key[n_key] = 0;
+
+ if (value)
+ value[n_value] = 0;
+
+ /* Chomp off trailing whitespace from value */
+ if (last_value_whitespace != (size_t) -1)
+ value[last_value_whitespace] = 0;
+
+ /* strip trailing whitespace from key */
+ if (last_key_whitespace != (size_t) -1)
+ key[last_key_whitespace] = 0;
+
+ r = push(key, value, userdata);
+ if (r < 0)
+ goto fail;
+
+ n_key = 0;
+ value = NULL;
+ value_alloc = n_value = 0;
+
+ } else if (c == '\\') {
+ state = VALUE_ESCAPE;
+ last_value_whitespace = (size_t) -1;
+ } else {
+ if (!strchr(WHITESPACE, c))
+ last_value_whitespace = (size_t) -1;
+ else if (last_value_whitespace == (size_t) -1)
+ last_value_whitespace = n_value;
+
+ if (!greedy_realloc((void**) &value, &value_alloc, n_value+2)) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ value[n_value++] = c;
+ }
+
+ break;
+
+ case VALUE_ESCAPE:
+ state = VALUE;
+
+ if (!strchr(newline, c)) {
+ /* Escaped newlines we eat up entirely */
+ if (!greedy_realloc((void**) &value, &value_alloc, n_value+2)) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ value[n_value++] = c;
+ }
+ break;
+
+ case SINGLE_QUOTE_VALUE:
+ if (c == '\'')
+ state = PRE_VALUE;
+ else if (c == '\\')
+ state = SINGLE_QUOTE_VALUE_ESCAPE;
+ else {
+ if (!greedy_realloc((void**) &value, &value_alloc, n_value+2)) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ value[n_value++] = c;
+ }
+
+ break;
+
+ case SINGLE_QUOTE_VALUE_ESCAPE:
+ state = SINGLE_QUOTE_VALUE;
+
+ if (!strchr(newline, c)) {
+ if (!greedy_realloc((void**) &value, &value_alloc, n_value+2)) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ value[n_value++] = c;
+ }
+ break;
+
+ case DOUBLE_QUOTE_VALUE:
+ if (c == '\"')
+ state = PRE_VALUE;
+ else if (c == '\\')
+ state = DOUBLE_QUOTE_VALUE_ESCAPE;
+ else {
+ if (!greedy_realloc((void**) &value, &value_alloc, n_value+2)) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ value[n_value++] = c;
+ }
+
+ break;
+
+ case DOUBLE_QUOTE_VALUE_ESCAPE:
+ state = DOUBLE_QUOTE_VALUE;
+
+ if (!strchr(newline, c)) {
+ if (!greedy_realloc((void**) &value, &value_alloc, n_value+2)) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ value[n_value++] = c;
+ }
+ break;
+
+ case COMMENT:
+ if (c == '\\')
+ state = COMMENT_ESCAPE;
+ else if (strchr(newline, c))
+ state = PRE_KEY;
+ break;
+
+ case COMMENT_ESCAPE:
+ state = COMMENT;
+ break;
+ }
+ }
+
+ if (state == PRE_VALUE ||
+ state == VALUE ||
+ state == VALUE_ESCAPE ||
+ state == SINGLE_QUOTE_VALUE ||
+ state == SINGLE_QUOTE_VALUE_ESCAPE ||
+ state == DOUBLE_QUOTE_VALUE ||
+ state == DOUBLE_QUOTE_VALUE_ESCAPE) {
+
+ key[n_key] = 0;
+
+ if (value)
+ value[n_value] = 0;
+
+ if (state == VALUE)
+ if (last_value_whitespace != (size_t) -1)
+ value[last_value_whitespace] = 0;
+
+ /* strip trailing whitespace from key */
+ if (last_key_whitespace != (size_t) -1)
+ key[last_key_whitespace] = 0;
+
+ r = push(key, value, userdata);
+ if (r < 0)
+ goto fail;
+ }
+
+ return 0;
+
+fail:
+ free(value);
+ return r;
+}
+
+static int parse_env_file_push(const char *key, char *value, void *userdata) {
+ const char *k;
+ va_list* ap = (va_list*) userdata;
+ va_list aq;
+
+ va_copy(aq, *ap);
+
+ while ((k = va_arg(aq, const char *))) {
+ char **v;
+
+ v = va_arg(aq, char **);
+
+ if (streq(key, k)) {
+ va_end(aq);
+ free(*v);
+ *v = value;
+ return 1;
+ }
+ }
+
+ va_end(aq);
+
+ free(value);
+ return 0;
+}
+
+int parse_env_file(
+ const char *fname,
+ const char *newline, ...) {
+
+ va_list ap;
+ int r;
+
+ if (!newline)
+ newline = NEWLINE;
+
+ va_start(ap, newline);
+ r = parse_env_file_internal(fname, newline, parse_env_file_push, &ap);
+ va_end(ap);
+
+ return r;
+}
+
+static int load_env_file_push(const char *key, char *value, void *userdata) {
+ char ***m = userdata;
+ char *p;
+ int r;
+
+ p = strjoin(key, "=", strempty(value), NULL);
+ if (!p)
+ return -ENOMEM;
+
+ r = strv_push(m, p);
+ if (r < 0) {
+ free(p);
+ return r;
+ }
+
+ free(value);
+ return 0;
+}
+
+int load_env_file(const char *fname, const char *newline, char ***rl) {
+ char **m = NULL;
+ int r;
+
+ if (!newline)
+ newline = NEWLINE;
+
+ r = parse_env_file_internal(fname, newline, load_env_file_push, &m);
+ if (r < 0) {
+ strv_free(m);
+ return r;
+ }
+
+ *rl = m;
+ return 0;
+}
+
+static void write_env_var(FILE *f, const char *v) {
+ const char *p;
+
+ p = strchr(v, '=');
+ if (!p) {
+ /* Fallback */
+ fputs(v, f);
+ fputc('\n', f);
+ return;
+ }
+
+ p++;
+ fwrite(v, 1, p-v, f);
+
+ if (string_has_cc(p) || chars_intersect(p, WHITESPACE "\'\"\\`$")) {
+ fputc('\"', f);
+
+ for (; *p; p++) {
+ if (strchr("\'\"\\`$", *p))
+ fputc('\\', f);
+
+ fputc(*p, f);
+ }
+
+ fputc('\"', f);
+ } else
+ fputs(p, f);
+
+ fputc('\n', f);
+}
+
+int write_env_file(const char *fname, char **l) {
+ char **i;
+ _cleanup_free_ char *p = NULL;
+ _cleanup_fclose_ FILE *f = NULL;
+ int r;
+
+ r = fopen_temporary(fname, &f, &p);
+ if (r < 0)
+ return r;
+
+ fchmod_umask(fileno(f), 0644);
+
+ errno = 0;
+ STRV_FOREACH(i, l)
+ write_env_var(f, *i);
+
+ fflush(f);
+
+ if (ferror(f))
+ r = errno ? -errno : -EIO;
+ else {
+ if (rename(p, fname) < 0)
+ r = -errno;
+ else
+ r = 0;
+ }
+
+ if (r < 0)
+ unlink(p);
+
+ return r;
+}
diff --git a/src/shared/fileio.h b/src/shared/fileio.h
new file mode 100644
index 0000000000..0ca6878ea4
--- /dev/null
+++ b/src/shared/fileio.h
@@ -0,0 +1,37 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+#include <stddef.h>
+#include <stdio.h>
+
+#include "macro.h"
+
+int write_string_to_file(FILE *f, const char *line);
+int write_string_file(const char *fn, const char *line);
+int write_string_file_atomic(const char *fn, const char *line);
+
+int read_one_line_file(const char *fn, char **line);
+int read_full_file(const char *fn, char **contents, size_t *size);
+
+int parse_env_file(const char *fname, const char *separator, ...) _sentinel_;
+int load_env_file(const char *fname, const char *separator, char ***l);
+int write_env_file(const char *fname, char **l);
diff --git a/src/shared/hashmap.c b/src/shared/hashmap.c
new file mode 100644
index 0000000000..9f7db34397
--- /dev/null
+++ b/src/shared/hashmap.c
@@ -0,0 +1,862 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+
+#include "util.h"
+#include "hashmap.h"
+#include "macro.h"
+
+#define NBUCKETS 127
+
+struct hashmap_entry {
+ const void *key;
+ void *value;
+ struct hashmap_entry *bucket_next, *bucket_previous;
+ struct hashmap_entry *iterate_next, *iterate_previous;
+};
+
+struct Hashmap {
+ hash_func_t hash_func;
+ compare_func_t compare_func;
+
+ struct hashmap_entry *iterate_list_head, *iterate_list_tail;
+ unsigned n_entries;
+
+ bool from_pool;
+};
+
+#define BY_HASH(h) ((struct hashmap_entry**) ((uint8_t*) (h) + ALIGN(sizeof(Hashmap))))
+
+struct pool {
+ struct pool *next;
+ unsigned n_tiles;
+ unsigned n_used;
+};
+
+static struct pool *first_hashmap_pool = NULL;
+static void *first_hashmap_tile = NULL;
+
+static struct pool *first_entry_pool = NULL;
+static void *first_entry_tile = NULL;
+
+static void* allocate_tile(struct pool **first_pool, void **first_tile, size_t tile_size) {
+ unsigned i;
+
+ if (*first_tile) {
+ void *r;
+
+ r = *first_tile;
+ *first_tile = * (void**) (*first_tile);
+ return r;
+ }
+
+ if (_unlikely_(!*first_pool) || _unlikely_((*first_pool)->n_used >= (*first_pool)->n_tiles)) {
+ unsigned n;
+ size_t size;
+ struct pool *p;
+
+ n = *first_pool ? (*first_pool)->n_tiles : 0;
+ n = MAX(512U, n * 2);
+ size = PAGE_ALIGN(ALIGN(sizeof(struct pool)) + n*tile_size);
+ n = (size - ALIGN(sizeof(struct pool))) / tile_size;
+
+ p = malloc(size);
+ if (!p)
+ return NULL;
+
+ p->next = *first_pool;
+ p->n_tiles = n;
+ p->n_used = 0;
+
+ *first_pool = p;
+ }
+
+ i = (*first_pool)->n_used++;
+
+ return ((uint8_t*) (*first_pool)) + ALIGN(sizeof(struct pool)) + i*tile_size;
+}
+
+static void deallocate_tile(void **first_tile, void *p) {
+ * (void**) p = *first_tile;
+ *first_tile = p;
+}
+
+#ifdef VALGRIND
+
+static void drop_pool(struct pool *p) {
+ while (p) {
+ struct pool *n;
+ n = p->next;
+ free(p);
+ p = n;
+ }
+}
+
+__attribute__((destructor)) static void cleanup_pool(void) {
+ /* Be nice to valgrind */
+
+ drop_pool(first_hashmap_pool);
+ drop_pool(first_entry_pool);
+}
+
+#endif
+
+unsigned string_hash_func(const void *p) {
+ unsigned hash = 5381;
+ const signed char *c;
+
+ /* DJB's hash function */
+
+ for (c = p; *c; c++)
+ hash = (hash << 5) + hash + (unsigned) *c;
+
+ return hash;
+}
+
+int string_compare_func(const void *a, const void *b) {
+ return strcmp(a, b);
+}
+
+unsigned trivial_hash_func(const void *p) {
+ return PTR_TO_UINT(p);
+}
+
+int trivial_compare_func(const void *a, const void *b) {
+ return a < b ? -1 : (a > b ? 1 : 0);
+}
+
+unsigned uint64_hash_func(const void *p) {
+ uint64_t u;
+
+ assert_cc(sizeof(uint64_t) == 2*sizeof(unsigned));
+
+ u = *(const uint64_t*) p;
+
+ return (unsigned) ((u >> 32) ^ u);
+}
+
+int uint64_compare_func(const void *_a, const void *_b) {
+ uint64_t a, b;
+
+ a = *(const uint64_t*) _a;
+ b = *(const uint64_t*) _b;
+
+ return a < b ? -1 : (a > b ? 1 : 0);
+}
+
+Hashmap *hashmap_new(hash_func_t hash_func, compare_func_t compare_func) {
+ bool b;
+ Hashmap *h;
+ size_t size;
+
+ b = is_main_thread();
+
+ size = ALIGN(sizeof(Hashmap)) + NBUCKETS * sizeof(struct hashmap_entry*);
+
+ if (b) {
+ h = allocate_tile(&first_hashmap_pool, &first_hashmap_tile, size);
+ if (!h)
+ return NULL;
+
+ memset(h, 0, size);
+ } else {
+ h = malloc0(size);
+
+ if (!h)
+ return NULL;
+ }
+
+ h->hash_func = hash_func ? hash_func : trivial_hash_func;
+ h->compare_func = compare_func ? compare_func : trivial_compare_func;
+
+ h->n_entries = 0;
+ h->iterate_list_head = h->iterate_list_tail = NULL;
+
+ h->from_pool = b;
+
+ return h;
+}
+
+int hashmap_ensure_allocated(Hashmap **h, hash_func_t hash_func, compare_func_t compare_func) {
+ assert(h);
+
+ if (*h)
+ return 0;
+
+ if (!(*h = hashmap_new(hash_func, compare_func)))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static void link_entry(Hashmap *h, struct hashmap_entry *e, unsigned hash) {
+ assert(h);
+ assert(e);
+
+ /* Insert into hash table */
+ e->bucket_next = BY_HASH(h)[hash];
+ e->bucket_previous = NULL;
+ if (BY_HASH(h)[hash])
+ BY_HASH(h)[hash]->bucket_previous = e;
+ BY_HASH(h)[hash] = e;
+
+ /* Insert into iteration list */
+ e->iterate_previous = h->iterate_list_tail;
+ e->iterate_next = NULL;
+ if (h->iterate_list_tail) {
+ assert(h->iterate_list_head);
+ h->iterate_list_tail->iterate_next = e;
+ } else {
+ assert(!h->iterate_list_head);
+ h->iterate_list_head = e;
+ }
+ h->iterate_list_tail = e;
+
+ h->n_entries++;
+ assert(h->n_entries >= 1);
+}
+
+static void unlink_entry(Hashmap *h, struct hashmap_entry *e, unsigned hash) {
+ assert(h);
+ assert(e);
+
+ /* Remove from iteration list */
+ if (e->iterate_next)
+ e->iterate_next->iterate_previous = e->iterate_previous;
+ else
+ h->iterate_list_tail = e->iterate_previous;
+
+ if (e->iterate_previous)
+ e->iterate_previous->iterate_next = e->iterate_next;
+ else
+ h->iterate_list_head = e->iterate_next;
+
+ /* Remove from hash table bucket list */
+ if (e->bucket_next)
+ e->bucket_next->bucket_previous = e->bucket_previous;
+
+ if (e->bucket_previous)
+ e->bucket_previous->bucket_next = e->bucket_next;
+ else
+ BY_HASH(h)[hash] = e->bucket_next;
+
+ assert(h->n_entries >= 1);
+ h->n_entries--;
+}
+
+static void remove_entry(Hashmap *h, struct hashmap_entry *e) {
+ unsigned hash;
+
+ assert(h);
+ assert(e);
+
+ hash = h->hash_func(e->key) % NBUCKETS;
+
+ unlink_entry(h, e, hash);
+
+ if (h->from_pool)
+ deallocate_tile(&first_entry_tile, e);
+ else
+ free(e);
+}
+
+void hashmap_free(Hashmap*h) {
+
+ /* Free the hashmap, but nothing in it */
+
+ if (!h)
+ return;
+
+ hashmap_clear(h);
+
+ if (h->from_pool)
+ deallocate_tile(&first_hashmap_tile, h);
+ else
+ free(h);
+}
+
+void hashmap_free_free(Hashmap *h) {
+
+ /* Free the hashmap and all data objects in it, but not the
+ * keys */
+
+ if (!h)
+ return;
+
+ hashmap_clear_free(h);
+ hashmap_free(h);
+}
+
+void hashmap_free_free_free(Hashmap *h) {
+
+ /* Free the hashmap and all data and key objects in it */
+
+ if (!h)
+ return;
+
+ hashmap_clear_free_free(h);
+ hashmap_free(h);
+}
+
+void hashmap_clear(Hashmap *h) {
+ if (!h)
+ return;
+
+ while (h->iterate_list_head)
+ remove_entry(h, h->iterate_list_head);
+}
+
+void hashmap_clear_free(Hashmap *h) {
+ void *p;
+
+ if (!h)
+ return;
+
+ while ((p = hashmap_steal_first(h)))
+ free(p);
+}
+
+void hashmap_clear_free_free(Hashmap *h) {
+ if (!h)
+ return;
+
+ while (h->iterate_list_head) {
+ void *a, *b;
+
+ a = h->iterate_list_head->value;
+ b = (void*) h->iterate_list_head->key;
+ remove_entry(h, h->iterate_list_head);
+ free(a);
+ free(b);
+ }
+}
+
+
+static struct hashmap_entry *hash_scan(Hashmap *h, unsigned hash, const void *key) {
+ struct hashmap_entry *e;
+ assert(h);
+ assert(hash < NBUCKETS);
+
+ for (e = BY_HASH(h)[hash]; e; e = e->bucket_next)
+ if (h->compare_func(e->key, key) == 0)
+ return e;
+
+ return NULL;
+}
+
+int hashmap_put(Hashmap *h, const void *key, void *value) {
+ struct hashmap_entry *e;
+ unsigned hash;
+
+ assert(h);
+
+ hash = h->hash_func(key) % NBUCKETS;
+
+ e = hash_scan(h, hash, key);
+ if (e) {
+
+ if (e->value == value)
+ return 0;
+
+ return -EEXIST;
+ }
+
+ if (h->from_pool)
+ e = allocate_tile(&first_entry_pool, &first_entry_tile, sizeof(struct hashmap_entry));
+ else
+ e = new(struct hashmap_entry, 1);
+
+ if (!e)
+ return -ENOMEM;
+
+ e->key = key;
+ e->value = value;
+
+ link_entry(h, e, hash);
+
+ return 1;
+}
+
+int hashmap_replace(Hashmap *h, const void *key, void *value) {
+ struct hashmap_entry *e;
+ unsigned hash;
+
+ assert(h);
+
+ hash = h->hash_func(key) % NBUCKETS;
+ e = hash_scan(h, hash, key);
+ if (e) {
+ e->key = key;
+ e->value = value;
+ return 0;
+ }
+
+ return hashmap_put(h, key, value);
+}
+
+int hashmap_update(Hashmap *h, const void *key, void *value) {
+ struct hashmap_entry *e;
+ unsigned hash;
+
+ assert(h);
+
+ hash = h->hash_func(key) % NBUCKETS;
+ e = hash_scan(h, hash, key);
+ if (!e)
+ return -ENOENT;
+
+ e->value = value;
+ return 0;
+}
+
+void* hashmap_get(Hashmap *h, const void *key) {
+ unsigned hash;
+ struct hashmap_entry *e;
+
+ if (!h)
+ return NULL;
+
+ hash = h->hash_func(key) % NBUCKETS;
+ e = hash_scan(h, hash, key);
+ if (!e)
+ return NULL;
+
+ return e->value;
+}
+
+void* hashmap_get2(Hashmap *h, const void *key, void **key2) {
+ unsigned hash;
+ struct hashmap_entry *e;
+
+ if (!h)
+ return NULL;
+
+ hash = h->hash_func(key) % NBUCKETS;
+ e = hash_scan(h, hash, key);
+ if (!e)
+ return NULL;
+
+ if (key2)
+ *key2 = (void*) e->key;
+
+ return e->value;
+}
+
+bool hashmap_contains(Hashmap *h, const void *key) {
+ unsigned hash;
+
+ if (!h)
+ return false;
+
+ hash = h->hash_func(key) % NBUCKETS;
+
+ if (!hash_scan(h, hash, key))
+ return false;
+
+ return true;
+}
+
+void* hashmap_remove(Hashmap *h, const void *key) {
+ struct hashmap_entry *e;
+ unsigned hash;
+ void *data;
+
+ if (!h)
+ return NULL;
+
+ hash = h->hash_func(key) % NBUCKETS;
+
+ if (!(e = hash_scan(h, hash, key)))
+ return NULL;
+
+ data = e->value;
+ remove_entry(h, e);
+
+ return data;
+}
+
+int hashmap_remove_and_put(Hashmap *h, const void *old_key, const void *new_key, void *value) {
+ struct hashmap_entry *e;
+ unsigned old_hash, new_hash;
+
+ if (!h)
+ return -ENOENT;
+
+ old_hash = h->hash_func(old_key) % NBUCKETS;
+ if (!(e = hash_scan(h, old_hash, old_key)))
+ return -ENOENT;
+
+ new_hash = h->hash_func(new_key) % NBUCKETS;
+ if (hash_scan(h, new_hash, new_key))
+ return -EEXIST;
+
+ unlink_entry(h, e, old_hash);
+
+ e->key = new_key;
+ e->value = value;
+
+ link_entry(h, e, new_hash);
+
+ return 0;
+}
+
+int hashmap_remove_and_replace(Hashmap *h, const void *old_key, const void *new_key, void *value) {
+ struct hashmap_entry *e, *k;
+ unsigned old_hash, new_hash;
+
+ if (!h)
+ return -ENOENT;
+
+ old_hash = h->hash_func(old_key) % NBUCKETS;
+ if (!(e = hash_scan(h, old_hash, old_key)))
+ return -ENOENT;
+
+ new_hash = h->hash_func(new_key) % NBUCKETS;
+
+ if ((k = hash_scan(h, new_hash, new_key)))
+ if (e != k)
+ remove_entry(h, k);
+
+ unlink_entry(h, e, old_hash);
+
+ e->key = new_key;
+ e->value = value;
+
+ link_entry(h, e, new_hash);
+
+ return 0;
+}
+
+void* hashmap_remove_value(Hashmap *h, const void *key, void *value) {
+ struct hashmap_entry *e;
+ unsigned hash;
+
+ if (!h)
+ return NULL;
+
+ hash = h->hash_func(key) % NBUCKETS;
+
+ if (!(e = hash_scan(h, hash, key)))
+ return NULL;
+
+ if (e->value != value)
+ return NULL;
+
+ remove_entry(h, e);
+
+ return value;
+}
+
+void *hashmap_iterate(Hashmap *h, Iterator *i, const void **key) {
+ struct hashmap_entry *e;
+
+ assert(i);
+
+ if (!h)
+ goto at_end;
+
+ if (*i == ITERATOR_LAST)
+ goto at_end;
+
+ if (*i == ITERATOR_FIRST && !h->iterate_list_head)
+ goto at_end;
+
+ e = *i == ITERATOR_FIRST ? h->iterate_list_head : (struct hashmap_entry*) *i;
+
+ if (e->iterate_next)
+ *i = (Iterator) e->iterate_next;
+ else
+ *i = ITERATOR_LAST;
+
+ if (key)
+ *key = e->key;
+
+ return e->value;
+
+at_end:
+ *i = ITERATOR_LAST;
+
+ if (key)
+ *key = NULL;
+
+ return NULL;
+}
+
+void *hashmap_iterate_backwards(Hashmap *h, Iterator *i, const void **key) {
+ struct hashmap_entry *e;
+
+ assert(i);
+
+ if (!h)
+ goto at_beginning;
+
+ if (*i == ITERATOR_FIRST)
+ goto at_beginning;
+
+ if (*i == ITERATOR_LAST && !h->iterate_list_tail)
+ goto at_beginning;
+
+ e = *i == ITERATOR_LAST ? h->iterate_list_tail : (struct hashmap_entry*) *i;
+
+ if (e->iterate_previous)
+ *i = (Iterator) e->iterate_previous;
+ else
+ *i = ITERATOR_FIRST;
+
+ if (key)
+ *key = e->key;
+
+ return e->value;
+
+at_beginning:
+ *i = ITERATOR_FIRST;
+
+ if (key)
+ *key = NULL;
+
+ return NULL;
+}
+
+void *hashmap_iterate_skip(Hashmap *h, const void *key, Iterator *i) {
+ unsigned hash;
+ struct hashmap_entry *e;
+
+ if (!h)
+ return NULL;
+
+ hash = h->hash_func(key) % NBUCKETS;
+
+ if (!(e = hash_scan(h, hash, key)))
+ return NULL;
+
+ *i = (Iterator) e;
+
+ return e->value;
+}
+
+void* hashmap_first(Hashmap *h) {
+
+ if (!h)
+ return NULL;
+
+ if (!h->iterate_list_head)
+ return NULL;
+
+ return h->iterate_list_head->value;
+}
+
+void* hashmap_first_key(Hashmap *h) {
+
+ if (!h)
+ return NULL;
+
+ if (!h->iterate_list_head)
+ return NULL;
+
+ return (void*) h->iterate_list_head->key;
+}
+
+void* hashmap_last(Hashmap *h) {
+
+ if (!h)
+ return NULL;
+
+ if (!h->iterate_list_tail)
+ return NULL;
+
+ return h->iterate_list_tail->value;
+}
+
+void* hashmap_steal_first(Hashmap *h) {
+ void *data;
+
+ if (!h)
+ return NULL;
+
+ if (!h->iterate_list_head)
+ return NULL;
+
+ data = h->iterate_list_head->value;
+ remove_entry(h, h->iterate_list_head);
+
+ return data;
+}
+
+void* hashmap_steal_first_key(Hashmap *h) {
+ void *key;
+
+ if (!h)
+ return NULL;
+
+ if (!h->iterate_list_head)
+ return NULL;
+
+ key = (void*) h->iterate_list_head->key;
+ remove_entry(h, h->iterate_list_head);
+
+ return key;
+}
+
+unsigned hashmap_size(Hashmap *h) {
+
+ if (!h)
+ return 0;
+
+ return h->n_entries;
+}
+
+bool hashmap_isempty(Hashmap *h) {
+
+ if (!h)
+ return true;
+
+ return h->n_entries == 0;
+}
+
+int hashmap_merge(Hashmap *h, Hashmap *other) {
+ struct hashmap_entry *e;
+
+ assert(h);
+
+ if (!other)
+ return 0;
+
+ for (e = other->iterate_list_head; e; e = e->iterate_next) {
+ int r;
+
+ if ((r = hashmap_put(h, e->key, e->value)) < 0)
+ if (r != -EEXIST)
+ return r;
+ }
+
+ return 0;
+}
+
+void hashmap_move(Hashmap *h, Hashmap *other) {
+ struct hashmap_entry *e, *n;
+
+ assert(h);
+
+ /* The same as hashmap_merge(), but every new item from other
+ * is moved to h. This function is guaranteed to succeed. */
+
+ if (!other)
+ return;
+
+ for (e = other->iterate_list_head; e; e = n) {
+ unsigned h_hash, other_hash;
+
+ n = e->iterate_next;
+
+ h_hash = h->hash_func(e->key) % NBUCKETS;
+
+ if (hash_scan(h, h_hash, e->key))
+ continue;
+
+ other_hash = other->hash_func(e->key) % NBUCKETS;
+
+ unlink_entry(other, e, other_hash);
+ link_entry(h, e, h_hash);
+ }
+}
+
+int hashmap_move_one(Hashmap *h, Hashmap *other, const void *key) {
+ unsigned h_hash, other_hash;
+ struct hashmap_entry *e;
+
+ if (!other)
+ return 0;
+
+ assert(h);
+
+ h_hash = h->hash_func(key) % NBUCKETS;
+ if (hash_scan(h, h_hash, key))
+ return -EEXIST;
+
+ other_hash = other->hash_func(key) % NBUCKETS;
+ if (!(e = hash_scan(other, other_hash, key)))
+ return -ENOENT;
+
+ unlink_entry(other, e, other_hash);
+ link_entry(h, e, h_hash);
+
+ return 0;
+}
+
+Hashmap *hashmap_copy(Hashmap *h) {
+ Hashmap *copy;
+
+ assert(h);
+
+ if (!(copy = hashmap_new(h->hash_func, h->compare_func)))
+ return NULL;
+
+ if (hashmap_merge(copy, h) < 0) {
+ hashmap_free(copy);
+ return NULL;
+ }
+
+ return copy;
+}
+
+char **hashmap_get_strv(Hashmap *h) {
+ char **sv;
+ Iterator it;
+ char *item;
+ int n;
+
+ sv = new(char*, h->n_entries+1);
+ if (!sv)
+ return NULL;
+
+ n = 0;
+ HASHMAP_FOREACH(item, h, it)
+ sv[n++] = item;
+ sv[n] = NULL;
+
+ return sv;
+}
+
+void *hashmap_next(Hashmap *h, const void *key) {
+ unsigned hash;
+ struct hashmap_entry *e;
+
+ assert(h);
+ assert(key);
+
+ if (!h)
+ return NULL;
+
+ hash = h->hash_func(key) % NBUCKETS;
+ e = hash_scan(h, hash, key);
+ if (!e)
+ return NULL;
+
+ e = e->iterate_next;
+ if (!e)
+ return NULL;
+
+ return e->value;
+}
diff --git a/src/shared/hashmap.h b/src/shared/hashmap.h
new file mode 100644
index 0000000000..15b7e27585
--- /dev/null
+++ b/src/shared/hashmap.h
@@ -0,0 +1,105 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdbool.h>
+
+#include "macro.h"
+
+/* Pretty straightforward hash table implementation. As a minor
+ * optimization a NULL hashmap object will be treated as empty hashmap
+ * for all read operations. That way it is not necessary to
+ * instantiate an object for each Hashmap use. */
+
+typedef struct Hashmap Hashmap;
+typedef struct _IteratorStruct _IteratorStruct;
+typedef _IteratorStruct* Iterator;
+
+#define ITERATOR_FIRST ((Iterator) 0)
+#define ITERATOR_LAST ((Iterator) -1)
+
+typedef unsigned (*hash_func_t)(const void *p);
+typedef int (*compare_func_t)(const void *a, const void *b);
+
+unsigned string_hash_func(const void *p) _pure_;
+int string_compare_func(const void *a, const void *b) _pure_;
+
+/* This will compare the passed pointers directly, and will not
+ * dereference them. This is hence not useful for strings or
+ * suchlike. */
+unsigned trivial_hash_func(const void *p) _const_;
+int trivial_compare_func(const void *a, const void *b) _const_;
+
+unsigned uint64_hash_func(const void *p) _pure_;
+int uint64_compare_func(const void *a, const void *b) _pure_;
+
+Hashmap *hashmap_new(hash_func_t hash_func, compare_func_t compare_func);
+void hashmap_free(Hashmap *h);
+void hashmap_free_free(Hashmap *h);
+void hashmap_free_free_free(Hashmap *h);
+Hashmap *hashmap_copy(Hashmap *h);
+int hashmap_ensure_allocated(Hashmap **h, hash_func_t hash_func, compare_func_t compare_func);
+
+int hashmap_put(Hashmap *h, const void *key, void *value);
+int hashmap_update(Hashmap *h, const void *key, void *value);
+int hashmap_replace(Hashmap *h, const void *key, void *value);
+void *hashmap_get(Hashmap *h, const void *key);
+void *hashmap_get2(Hashmap *h, const void *key, void **rkey);
+bool hashmap_contains(Hashmap *h, const void *key);
+void *hashmap_remove(Hashmap *h, const void *key);
+void *hashmap_remove_value(Hashmap *h, const void *key, void *value);
+int hashmap_remove_and_put(Hashmap *h, const void *old_key, const void *new_key, void *value);
+int hashmap_remove_and_replace(Hashmap *h, const void *old_key, const void *new_key, void *value);
+
+int hashmap_merge(Hashmap *h, Hashmap *other);
+void hashmap_move(Hashmap *h, Hashmap *other);
+int hashmap_move_one(Hashmap *h, Hashmap *other, const void *key);
+
+unsigned hashmap_size(Hashmap *h) _pure_;
+bool hashmap_isempty(Hashmap *h) _pure_;
+
+void *hashmap_iterate(Hashmap *h, Iterator *i, const void **key);
+void *hashmap_iterate_backwards(Hashmap *h, Iterator *i, const void **key);
+void *hashmap_iterate_skip(Hashmap *h, const void *key, Iterator *i);
+
+void hashmap_clear(Hashmap *h);
+void hashmap_clear_free(Hashmap *h);
+void hashmap_clear_free_free(Hashmap *h);
+
+void *hashmap_steal_first(Hashmap *h);
+void *hashmap_steal_first_key(Hashmap *h);
+void *hashmap_first(Hashmap *h) _pure_;
+void *hashmap_first_key(Hashmap *h) _pure_;
+void *hashmap_last(Hashmap *h) _pure_;
+
+void *hashmap_next(Hashmap *h, const void *key);
+
+char **hashmap_get_strv(Hashmap *h);
+
+#define HASHMAP_FOREACH(e, h, i) \
+ for ((i) = ITERATOR_FIRST, (e) = hashmap_iterate((h), &(i), NULL); (e); (e) = hashmap_iterate((h), &(i), NULL))
+
+#define HASHMAP_FOREACH_KEY(e, k, h, i) \
+ for ((i) = ITERATOR_FIRST, (e) = hashmap_iterate((h), &(i), (const void**) &(k)); (e); (e) = hashmap_iterate((h), &(i), (const void**) &(k)))
+
+#define HASHMAP_FOREACH_BACKWARDS(e, h, i) \
+ for ((i) = ITERATOR_LAST, (e) = hashmap_iterate_backwards((h), &(i), NULL); (e); (e) = hashmap_iterate_backwards((h), &(i), NULL))
diff --git a/src/shared/hwclock.c b/src/shared/hwclock.c
new file mode 100644
index 0000000000..cc11faa6c3
--- /dev/null
+++ b/src/shared/hwclock.c
@@ -0,0 +1,160 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010-2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <signal.h>
+#include <stdio.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <sys/ioctl.h>
+#include <stdarg.h>
+#include <ctype.h>
+#include <sys/prctl.h>
+#include <sys/time.h>
+#include <linux/rtc.h>
+
+#include "macro.h"
+#include "util.h"
+#include "log.h"
+#include "strv.h"
+#include "hwclock.h"
+#include "fileio.h"
+
+int hwclock_get_time(struct tm *tm) {
+ int fd;
+ int err = 0;
+
+ assert(tm);
+
+ fd = open("/dev/rtc", O_RDONLY|O_CLOEXEC);
+ if (fd < 0)
+ return -errno;
+
+ /* This leaves the timezone fields of struct tm
+ * uninitialized! */
+ if (ioctl(fd, RTC_RD_TIME, tm) < 0)
+ err = -errno;
+
+ /* We don't know daylight saving, so we reset this in order not
+ * to confused mktime(). */
+ tm->tm_isdst = -1;
+
+ close_nointr_nofail(fd);
+
+ return err;
+}
+
+int hwclock_set_time(const struct tm *tm) {
+ int fd;
+ int err = 0;
+
+ assert(tm);
+
+ fd = open("/dev/rtc", O_RDONLY|O_CLOEXEC);
+ if (fd < 0)
+ return -errno;
+
+ if (ioctl(fd, RTC_SET_TIME, tm) < 0)
+ err = -errno;
+
+ close_nointr_nofail(fd);
+
+ return err;
+}
+
+int hwclock_is_localtime(void) {
+ _cleanup_fclose_ FILE *f;
+
+ /*
+ * The third line of adjtime is "UTC" or "LOCAL" or nothing.
+ * # /etc/adjtime
+ * 0.0 0 0
+ * 0
+ * UTC
+ */
+ f = fopen("/etc/adjtime", "re");
+ if (f) {
+ char line[LINE_MAX];
+ bool b;
+
+ b = fgets(line, sizeof(line), f) &&
+ fgets(line, sizeof(line), f) &&
+ fgets(line, sizeof(line), f);
+ if (!b)
+ return -EIO;
+
+ truncate_nl(line);
+ return streq(line, "LOCAL");
+
+ } else if (errno != ENOENT)
+ return -errno;
+
+ return 0;
+}
+
+int hwclock_set_timezone(int *min) {
+ const struct timeval *tv_null = NULL;
+ struct timespec ts;
+ struct tm *tm;
+ int minutesdelta;
+ struct timezone tz;
+
+ assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
+ assert_se(tm = localtime(&ts.tv_sec));
+ minutesdelta = tm->tm_gmtoff / 60;
+
+ tz.tz_minuteswest = -minutesdelta;
+ tz.tz_dsttime = 0; /* DST_NONE*/
+
+ /*
+ * If the hardware clock does not run in UTC, but in local time:
+ * The very first time we set the kernel's timezone, it will warp
+ * the clock so that it runs in UTC instead of local time.
+ */
+ if (settimeofday(tv_null, &tz) < 0)
+ return -errno;
+ if (min)
+ *min = minutesdelta;
+ return 0;
+}
+
+int hwclock_reset_timezone(void) {
+ const struct timeval *tv_null = NULL;
+ struct timezone tz;
+
+ tz.tz_minuteswest = 0;
+ tz.tz_dsttime = 0; /* DST_NONE*/
+
+ /*
+ * The very first time we set the kernel's timezone, it will warp
+ * the clock. Do a dummy call here, so the time warping is sealed
+ * and we set only the time zone with next call.
+ */
+ if (settimeofday(tv_null, &tz) < 0)
+ return -errno;
+
+ return 0;
+}
diff --git a/src/shared/hwclock.h b/src/shared/hwclock.h
new file mode 100644
index 0000000000..b2bdc78f0c
--- /dev/null
+++ b/src/shared/hwclock.h
@@ -0,0 +1,31 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef foohwclockhfoo
+#define foohwclockhfoo
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010-2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+int hwclock_is_localtime(void);
+int hwclock_set_timezone(int *min);
+int hwclock_reset_timezone(void);
+int hwclock_get_time(struct tm *tm);
+int hwclock_set_time(const struct tm *tm);
+
+#endif
diff --git a/src/shared/install-printf.c b/src/shared/install-printf.c
new file mode 100644
index 0000000000..c44459b4e0
--- /dev/null
+++ b/src/shared/install-printf.c
@@ -0,0 +1,132 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Zbigniew Jędrzejewski-Szmek
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <stdlib.h>
+
+#include "specifier.h"
+#include "unit-name.h"
+#include "util.h"
+#include "install-printf.h"
+
+static char *specifier_prefix_and_instance(char specifier, void *data, void *userdata) {
+ InstallInfo *i = userdata;
+ assert(i);
+
+ return unit_name_to_prefix_and_instance(i->name);
+}
+
+static char *specifier_prefix(char specifier, void *data, void *userdata) {
+ InstallInfo *i = userdata;
+ assert(i);
+
+ return unit_name_to_prefix(i->name);
+}
+
+static char *specifier_instance(char specifier, void *data, void *userdata) {
+ InstallInfo *i = userdata;
+ char *instance;
+ int r;
+
+ assert(i);
+
+ r = unit_name_to_instance(i->name, &instance);
+ if (r < 0)
+ return NULL;
+ if (instance != NULL)
+ return instance;
+ else
+ return strdup("");
+}
+
+static char *specifier_user_name(char specifier, void *data, void *userdata) {
+ InstallInfo *i = userdata;
+ const char *username;
+ _cleanup_free_ char *tmp = NULL;
+ char *printed = NULL;
+
+ assert(i);
+
+ if (i->user)
+ username = i->user;
+ else
+ /* get USER env from env or our own uid */
+ username = tmp = getusername_malloc();
+
+ switch (specifier) {
+ case 'u':
+ printed = strdup(username);
+ break;
+ case 'U': {
+ /* fish username from passwd */
+ uid_t uid;
+ int r;
+
+ r = get_user_creds(&username, &uid, NULL, NULL, NULL);
+ if (r < 0)
+ return NULL;
+
+ if (asprintf(&printed, "%d", uid) < 0)
+ return NULL;
+ break;
+ }}
+
+ return printed;
+}
+
+
+char *install_full_printf(InstallInfo *i, const char *format) {
+
+ /* This is similar to unit_full_printf() but does not support
+ * anything path-related.
+ *
+ * %n: the full id of the unit (foo@bar.waldo)
+ * %N: the id of the unit without the suffix (foo@bar)
+ * %p: the prefix (foo)
+ * %i: the instance (bar)
+
+ * %U the UID of the configured user or running user
+ * %u the username of the configured user or running user
+ * %m the machine ID of the running system
+ * %H the host name of the running system
+ * %b the boot ID of the running system
+ */
+
+ const Specifier table[] = {
+ { 'n', specifier_string, i->name },
+ { 'N', specifier_prefix_and_instance, NULL },
+ { 'p', specifier_prefix, NULL },
+ { 'i', specifier_instance, NULL },
+
+ { 'U', specifier_user_name, NULL },
+ { 'u', specifier_user_name, NULL },
+
+ { 'm', specifier_machine_id, NULL },
+ { 'H', specifier_host_name, NULL },
+ { 'b', specifier_boot_id, NULL },
+ { 0, NULL, NULL }
+ };
+
+ assert(i);
+ assert(format);
+
+ return specifier_printf(format, table, i);
+}
diff --git a/src/shared/install-printf.h b/src/shared/install-printf.h
new file mode 100644
index 0000000000..46f5294d21
--- /dev/null
+++ b/src/shared/install-printf.h
@@ -0,0 +1,25 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Zbigniew Jędrzejewski-Szmek
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#pragma once
+
+#include "install.h"
+char *install_full_printf(InstallInfo *i, const char *format);
diff --git a/src/shared/install.c b/src/shared/install.c
new file mode 100644
index 0000000000..edf4d2a9fe
--- /dev/null
+++ b/src/shared/install.c
@@ -0,0 +1,1945 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty <of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <string.h>
+#include <fnmatch.h>
+
+#include "util.h"
+#include "mkdir.h"
+#include "hashmap.h"
+#include "set.h"
+#include "path-util.h"
+#include "path-lookup.h"
+#include "strv.h"
+#include "unit-name.h"
+#include "install.h"
+#include "conf-parser.h"
+#include "conf-files.h"
+#include "specifier.h"
+#include "install-printf.h"
+
+typedef struct {
+ Hashmap *will_install;
+ Hashmap *have_installed;
+} InstallContext;
+
+#define _cleanup_lookup_paths_free_ \
+ __attribute__((cleanup(lookup_paths_free)))
+#define _cleanup_install_context_done_ \
+ __attribute__((cleanup(install_context_done)))
+
+static int lookup_paths_init_from_scope(LookupPaths *paths, UnitFileScope scope) {
+ assert(paths);
+ assert(scope >= 0);
+ assert(scope < _UNIT_FILE_SCOPE_MAX);
+
+ zero(*paths);
+
+ return lookup_paths_init(paths,
+ scope == UNIT_FILE_SYSTEM ? SYSTEMD_SYSTEM : SYSTEMD_USER,
+ scope == UNIT_FILE_USER,
+ NULL, NULL, NULL);
+}
+
+static int get_config_path(UnitFileScope scope, bool runtime, const char *root_dir, char **ret) {
+ char *p = NULL;
+ int r;
+
+ assert(scope >= 0);
+ assert(scope < _UNIT_FILE_SCOPE_MAX);
+ assert(ret);
+
+ switch (scope) {
+
+ case UNIT_FILE_SYSTEM:
+
+ if (root_dir && runtime)
+ asprintf(&p, "%s/run/systemd/system", root_dir);
+ else if (runtime)
+ p = strdup("/run/systemd/system");
+ else if (root_dir)
+ asprintf(&p, "%s/%s", root_dir, SYSTEM_CONFIG_UNIT_PATH);
+ else
+ p = strdup(SYSTEM_CONFIG_UNIT_PATH);
+
+ break;
+
+ case UNIT_FILE_GLOBAL:
+
+ if (root_dir)
+ return -EINVAL;
+
+ if (runtime)
+ p = strdup("/run/systemd/user");
+ else
+ p = strdup(USER_CONFIG_UNIT_PATH);
+ break;
+
+ case UNIT_FILE_USER:
+
+ if (root_dir || runtime)
+ return -EINVAL;
+
+ r = user_config_home(&p);
+ if (r <= 0)
+ return r < 0 ? r : -ENOENT;
+
+ break;
+
+ default:
+ assert_not_reached("Bad scope");
+ }
+
+ if (!p)
+ return -ENOMEM;
+
+ *ret = p;
+ return 0;
+}
+
+static int add_file_change(
+ UnitFileChange **changes,
+ unsigned *n_changes,
+ UnitFileChangeType type,
+ const char *path,
+ const char *source) {
+
+ UnitFileChange *c;
+ unsigned i;
+
+ assert(path);
+ assert(!changes == !n_changes);
+
+ if (!changes)
+ return 0;
+
+ c = realloc(*changes, (*n_changes + 1) * sizeof(UnitFileChange));
+ if (!c)
+ return -ENOMEM;
+
+ *changes = c;
+ i = *n_changes;
+
+ c[i].type = type;
+ c[i].path = strdup(path);
+ if (!c[i].path)
+ return -ENOMEM;
+
+ if (source) {
+ c[i].source = strdup(source);
+ if (!c[i].source) {
+ free(c[i].path);
+ return -ENOMEM;
+ }
+ } else
+ c[i].source = NULL;
+
+ *n_changes = i+1;
+ return 0;
+}
+
+static int mark_symlink_for_removal(
+ Set **remove_symlinks_to,
+ const char *p) {
+
+ char *n;
+ int r;
+
+ assert(p);
+
+ r = set_ensure_allocated(remove_symlinks_to, string_hash_func, string_compare_func);
+ if (r < 0)
+ return r;
+
+ n = strdup(p);
+ if (!n)
+ return -ENOMEM;
+
+ path_kill_slashes(n);
+
+ r = set_consume(*remove_symlinks_to, n);
+ if (r < 0)
+ return r == -EEXIST ? 0 : r;
+
+ return 0;
+}
+
+static int remove_marked_symlinks_fd(
+ Set *remove_symlinks_to,
+ int fd,
+ const char *path,
+ const char *config_path,
+ bool *deleted,
+ UnitFileChange **changes,
+ unsigned *n_changes,
+ char** files) {
+
+ int r = 0;
+ _cleanup_closedir_ DIR *d = NULL;
+
+ assert(remove_symlinks_to);
+ assert(fd >= 0);
+ assert(path);
+ assert(config_path);
+ assert(deleted);
+
+ d = fdopendir(fd);
+ if (!d) {
+ close_nointr_nofail(fd);
+ return -errno;
+ }
+
+ rewinddir(d);
+
+ for (;;) {
+ struct dirent *de;
+ union dirent_storage buf;
+ int k;
+
+ k = readdir_r(d, &buf.de, &de);
+ if (k != 0) {
+ r = -errno;
+ break;
+ }
+
+ if (!de)
+ break;
+
+ if (ignore_file(de->d_name))
+ continue;
+
+ dirent_ensure_type(d, de);
+
+ if (de->d_type == DT_DIR) {
+ int nfd, q;
+ _cleanup_free_ char *p = NULL;
+
+ nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW);
+ if (nfd < 0) {
+ if (errno == ENOENT)
+ continue;
+
+ if (r == 0)
+ r = -errno;
+ continue;
+ }
+
+ p = path_make_absolute(de->d_name, path);
+ if (!p) {
+ close_nointr_nofail(nfd);
+ return -ENOMEM;
+ }
+
+ /* This will close nfd, regardless whether it succeeds or not */
+ q = remove_marked_symlinks_fd(remove_symlinks_to, nfd, p, config_path, deleted, changes, n_changes, files);
+
+ if (r == 0)
+ r = q;
+
+ } else if (de->d_type == DT_LNK) {
+ _cleanup_free_ char *p = NULL, *dest = NULL;
+ int q;
+ bool found;
+
+ p = path_make_absolute(de->d_name, path);
+ if (!p)
+ return -ENOMEM;
+
+ q = readlink_and_canonicalize(p, &dest);
+ if (q < 0) {
+ if (q == -ENOENT)
+ continue;
+
+ if (r == 0)
+ r = q;
+ continue;
+ }
+
+ found =
+ set_get(remove_symlinks_to, dest) ||
+ set_get(remove_symlinks_to, path_get_file_name(dest));
+
+ if (unit_name_is_instance(p))
+ found = found && strv_contains(files, path_get_file_name(p));
+
+ if (found) {
+
+ if (unlink(p) < 0 && errno != ENOENT) {
+
+ if (r == 0)
+ r = -errno;
+ } else {
+ rmdir_parents(p, config_path);
+ path_kill_slashes(p);
+
+ add_file_change(changes, n_changes, UNIT_FILE_UNLINK, p, NULL);
+
+ if (!set_get(remove_symlinks_to, p)) {
+
+ q = mark_symlink_for_removal(&remove_symlinks_to, p);
+ if (q < 0) {
+ if (r == 0)
+ r = q;
+ } else
+ *deleted = true;
+ }
+ }
+ }
+ }
+ }
+
+ return r;
+}
+
+static int remove_marked_symlinks(
+ Set *remove_symlinks_to,
+ const char *config_path,
+ UnitFileChange **changes,
+ unsigned *n_changes,
+ char** files) {
+
+ int fd, r = 0;
+ bool deleted;
+
+ assert(config_path);
+
+ if (set_size(remove_symlinks_to) <= 0)
+ return 0;
+
+ fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW);
+ if (fd < 0)
+ return -errno;
+
+ do {
+ int q, cfd;
+ deleted = false;
+
+ cfd = dup(fd);
+ if (cfd < 0) {
+ r = -errno;
+ break;
+ }
+
+ /* This takes possession of cfd and closes it */
+ q = remove_marked_symlinks_fd(remove_symlinks_to, cfd, config_path, config_path, &deleted, changes, n_changes, files);
+ if (r == 0)
+ r = q;
+ } while (deleted);
+
+ close_nointr_nofail(fd);
+
+ return r;
+}
+
+static int find_symlinks_fd(
+ const char *name,
+ int fd,
+ const char *path,
+ const char *config_path,
+ bool *same_name_link) {
+
+ int r = 0;
+ _cleanup_closedir_ DIR *d = NULL;
+
+ assert(name);
+ assert(fd >= 0);
+ assert(path);
+ assert(config_path);
+ assert(same_name_link);
+
+ d = fdopendir(fd);
+ if (!d) {
+ close_nointr_nofail(fd);
+ return -errno;
+ }
+
+ for (;;) {
+ int k;
+ struct dirent *de;
+ union dirent_storage buf;
+
+ k = readdir_r(d, &buf.de, &de);
+ if (k != 0)
+ return -errno;
+
+ if (!de)
+ return r;
+
+ if (ignore_file(de->d_name))
+ continue;
+
+ dirent_ensure_type(d, de);
+
+ if (de->d_type == DT_DIR) {
+ int nfd, q;
+ _cleanup_free_ char *p = NULL;
+
+ nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW);
+ if (nfd < 0) {
+ if (errno == ENOENT)
+ continue;
+
+ if (r == 0)
+ r = -errno;
+ continue;
+ }
+
+ p = path_make_absolute(de->d_name, path);
+ if (!p) {
+ close_nointr_nofail(nfd);
+ return -ENOMEM;
+ }
+
+ /* This will close nfd, regardless whether it succeeds or not */
+ q = find_symlinks_fd(name, nfd, p, config_path, same_name_link);
+
+ if (q > 0)
+ return 1;
+
+ if (r == 0)
+ r = q;
+
+ } else if (de->d_type == DT_LNK) {
+ _cleanup_free_ char *p = NULL, *dest = NULL;
+ bool found_path, found_dest, b = false;
+ int q;
+
+ /* Acquire symlink name */
+ p = path_make_absolute(de->d_name, path);
+ if (!p)
+ return -ENOMEM;
+
+ /* Acquire symlink destination */
+ q = readlink_and_canonicalize(p, &dest);
+ if (q < 0) {
+ if (q == -ENOENT)
+ continue;
+
+ if (r == 0)
+ r = q;
+ continue;
+ }
+
+ /* Check if the symlink itself matches what we
+ * are looking for */
+ if (path_is_absolute(name))
+ found_path = path_equal(p, name);
+ else
+ found_path = streq(de->d_name, name);
+
+ /* Check if what the symlink points to
+ * matches what we are looking for */
+ if (path_is_absolute(name))
+ found_dest = path_equal(dest, name);
+ else
+ found_dest = streq(path_get_file_name(dest), name);
+
+ if (found_path && found_dest) {
+ _cleanup_free_ char *t = NULL;
+
+ /* Filter out same name links in the main
+ * config path */
+ t = path_make_absolute(name, config_path);
+ if (!t)
+ return -ENOMEM;
+
+ b = path_equal(t, p);
+ }
+
+ if (b)
+ *same_name_link = true;
+ else if (found_path || found_dest)
+ return 1;
+ }
+ }
+
+ return r;
+}
+
+static int find_symlinks(
+ const char *name,
+ const char *config_path,
+ bool *same_name_link) {
+
+ int fd;
+
+ assert(name);
+ assert(config_path);
+ assert(same_name_link);
+
+ fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW);
+ if (fd < 0) {
+ if (errno == ENOENT)
+ return 0;
+ return -errno;
+ }
+
+ /* This takes possession of fd and closes it */
+ return find_symlinks_fd(name, fd, config_path, config_path, same_name_link);
+}
+
+static int find_symlinks_in_scope(
+ UnitFileScope scope,
+ const char *root_dir,
+ const char *name,
+ UnitFileState *state) {
+
+ int r;
+ _cleanup_free_ char *path = NULL;
+ bool same_name_link_runtime = false, same_name_link = false;
+
+ assert(scope >= 0);
+ assert(scope < _UNIT_FILE_SCOPE_MAX);
+ assert(name);
+
+ if (scope == UNIT_FILE_SYSTEM || scope == UNIT_FILE_GLOBAL) {
+
+ /* First look in runtime config path */
+ r = get_config_path(scope, true, root_dir, &path);
+ if (r < 0)
+ return r;
+
+ r = find_symlinks(name, path, &same_name_link_runtime);
+ if (r < 0)
+ return r;
+ else if (r > 0) {
+ *state = UNIT_FILE_ENABLED_RUNTIME;
+ return r;
+ }
+ }
+
+ /* Then look in the normal config path */
+ r = get_config_path(scope, false, root_dir, &path);
+ if (r < 0)
+ return r;
+
+ r = find_symlinks(name, path, &same_name_link);
+ if (r < 0)
+ return r;
+ else if (r > 0) {
+ *state = UNIT_FILE_ENABLED;
+ return r;
+ }
+
+ /* Hmm, we didn't find it, but maybe we found the same name
+ * link? */
+ if (same_name_link_runtime) {
+ *state = UNIT_FILE_LINKED_RUNTIME;
+ return 1;
+ } else if (same_name_link) {
+ *state = UNIT_FILE_LINKED;
+ return 1;
+ }
+
+ return 0;
+}
+
+int unit_file_mask(
+ UnitFileScope scope,
+ bool runtime,
+ const char *root_dir,
+ char *files[],
+ bool force,
+ UnitFileChange **changes,
+ unsigned *n_changes) {
+
+ char **i;
+ _cleanup_free_ char *prefix;
+ int r;
+
+ assert(scope >= 0);
+ assert(scope < _UNIT_FILE_SCOPE_MAX);
+
+ r = get_config_path(scope, runtime, root_dir, &prefix);
+ if (r < 0)
+ return r;
+
+ STRV_FOREACH(i, files) {
+ _cleanup_free_ char *path = NULL;
+
+ if (!unit_name_is_valid(*i, true)) {
+ if (r == 0)
+ r = -EINVAL;
+ continue;
+ }
+
+ path = path_make_absolute(*i, prefix);
+ if (!path) {
+ r = -ENOMEM;
+ break;
+ }
+
+ if (symlink("/dev/null", path) >= 0) {
+ add_file_change(changes, n_changes, UNIT_FILE_SYMLINK, path, "/dev/null");
+
+ continue;
+ }
+
+ if (errno == EEXIST) {
+
+ if (null_or_empty_path(path) > 0)
+ continue;
+
+ if (force) {
+ unlink(path);
+
+ if (symlink("/dev/null", path) >= 0) {
+
+ add_file_change(changes, n_changes, UNIT_FILE_UNLINK, path, NULL);
+ add_file_change(changes, n_changes, UNIT_FILE_SYMLINK, path, "/dev/null");
+
+ continue;
+ }
+ }
+
+ if (r == 0)
+ r = -EEXIST;
+ } else {
+ if (r == 0)
+ r = -errno;
+ }
+ }
+
+ return r;
+}
+
+int unit_file_unmask(
+ UnitFileScope scope,
+ bool runtime,
+ const char *root_dir,
+ char *files[],
+ UnitFileChange **changes,
+ unsigned *n_changes) {
+
+ char **i, *config_path = NULL;
+ int r, q;
+ Set *remove_symlinks_to = NULL;
+
+ assert(scope >= 0);
+ assert(scope < _UNIT_FILE_SCOPE_MAX);
+
+ r = get_config_path(scope, runtime, root_dir, &config_path);
+ if (r < 0)
+ goto finish;
+
+ STRV_FOREACH(i, files) {
+ char *path;
+
+ if (!unit_name_is_valid(*i, true)) {
+ if (r == 0)
+ r = -EINVAL;
+ continue;
+ }
+
+ path = path_make_absolute(*i, config_path);
+ if (!path) {
+ r = -ENOMEM;
+ break;
+ }
+
+ q = null_or_empty_path(path);
+ if (q > 0) {
+ if (unlink(path) >= 0) {
+ mark_symlink_for_removal(&remove_symlinks_to, path);
+ add_file_change(changes, n_changes, UNIT_FILE_UNLINK, path, NULL);
+
+ free(path);
+ continue;
+ }
+
+ q = -errno;
+ }
+
+ if (q != -ENOENT && r == 0)
+ r = q;
+
+ free(path);
+ }
+
+
+finish:
+ q = remove_marked_symlinks(remove_symlinks_to, config_path, changes, n_changes, files);
+ if (r == 0)
+ r = q;
+
+ set_free_free(remove_symlinks_to);
+ free(config_path);
+
+ return r;
+}
+
+int unit_file_link(
+ UnitFileScope scope,
+ bool runtime,
+ const char *root_dir,
+ char *files[],
+ bool force,
+ UnitFileChange **changes,
+ unsigned *n_changes) {
+
+ _cleanup_lookup_paths_free_ LookupPaths paths = {};
+ char **i;
+ _cleanup_free_ char *config_path = NULL;
+ int r, q;
+
+ assert(scope >= 0);
+ assert(scope < _UNIT_FILE_SCOPE_MAX);
+
+ r = lookup_paths_init_from_scope(&paths, scope);
+ if (r < 0)
+ return r;
+
+ r = get_config_path(scope, runtime, root_dir, &config_path);
+ if (r < 0)
+ return r;
+
+ STRV_FOREACH(i, files) {
+ _cleanup_free_ char *path = NULL;
+ char *fn;
+ struct stat st;
+
+ fn = path_get_file_name(*i);
+
+ if (!path_is_absolute(*i) ||
+ !unit_name_is_valid(fn, true)) {
+ if (r == 0)
+ r = -EINVAL;
+ continue;
+ }
+
+ if (lstat(*i, &st) < 0) {
+ if (r == 0)
+ r = -errno;
+ continue;
+ }
+
+ if (!S_ISREG(st.st_mode)) {
+ r = -ENOENT;
+ continue;
+ }
+
+ q = in_search_path(*i, paths.unit_path);
+ if (q < 0)
+ return q;
+
+ if (q > 0)
+ continue;
+
+ path = path_make_absolute(fn, config_path);
+ if (!path)
+ return -ENOMEM;
+
+ if (symlink(*i, path) >= 0) {
+ add_file_change(changes, n_changes, UNIT_FILE_SYMLINK, path, *i);
+ continue;
+ }
+
+ if (errno == EEXIST) {
+ _cleanup_free_ char *dest = NULL;
+
+ q = readlink_and_make_absolute(path, &dest);
+
+ if (q < 0 && errno != ENOENT) {
+ if (r == 0)
+ r = q;
+ continue;
+ }
+
+ if (q >= 0 && path_equal(dest, *i))
+ continue;
+
+ if (force) {
+ unlink(path);
+
+ if (symlink(*i, path) >= 0) {
+
+ add_file_change(changes, n_changes, UNIT_FILE_UNLINK, path, NULL);
+ add_file_change(changes, n_changes, UNIT_FILE_SYMLINK, path, *i);
+
+ continue;
+ }
+ }
+
+ if (r == 0)
+ r = -EEXIST;
+ } else {
+ if (r == 0)
+ r = -errno;
+ }
+ }
+
+ return r;
+}
+
+void unit_file_list_free(Hashmap *h) {
+ UnitFileList *i;
+
+ while ((i = hashmap_steal_first(h))) {
+ free(i->path);
+ free(i);
+ }
+
+ hashmap_free(h);
+}
+
+void unit_file_changes_free(UnitFileChange *changes, unsigned n_changes) {
+ unsigned i;
+
+ assert(changes || n_changes == 0);
+
+ if (!changes)
+ return;
+
+ for (i = 0; i < n_changes; i++) {
+ free(changes[i].path);
+ free(changes[i].source);
+ }
+
+ free(changes);
+}
+
+static void install_info_free(InstallInfo *i) {
+ assert(i);
+
+ free(i->name);
+ free(i->path);
+ strv_free(i->aliases);
+ strv_free(i->wanted_by);
+ strv_free(i->required_by);
+ free(i);
+}
+
+static void install_info_hashmap_free(Hashmap *m) {
+ InstallInfo *i;
+
+ if (!m)
+ return;
+
+ while ((i = hashmap_steal_first(m)))
+ install_info_free(i);
+
+ hashmap_free(m);
+}
+
+static void install_context_done(InstallContext *c) {
+ assert(c);
+
+ install_info_hashmap_free(c->will_install);
+ install_info_hashmap_free(c->have_installed);
+
+ c->will_install = c->have_installed = NULL;
+}
+
+static int install_info_add(
+ InstallContext *c,
+ const char *name,
+ const char *path) {
+ InstallInfo *i = NULL;
+ int r;
+
+ assert(c);
+ assert(name || path);
+
+ if (!name)
+ name = path_get_file_name(path);
+
+ if (!unit_name_is_valid(name, true))
+ return -EINVAL;
+
+ if (hashmap_get(c->have_installed, name) ||
+ hashmap_get(c->will_install, name))
+ return 0;
+
+ r = hashmap_ensure_allocated(&c->will_install, string_hash_func, string_compare_func);
+ if (r < 0)
+ return r;
+
+ i = new0(InstallInfo, 1);
+ if (!i)
+ return -ENOMEM;
+
+ i->name = strdup(name);
+ if (!i->name) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ if (path) {
+ i->path = strdup(path);
+ if (!i->path) {
+ r = -ENOMEM;
+ goto fail;
+ }
+ }
+
+ r = hashmap_put(c->will_install, i->name, i);
+ if (r < 0)
+ goto fail;
+
+ return 0;
+
+fail:
+ if (i)
+ install_info_free(i);
+
+ return r;
+}
+
+static int install_info_add_auto(
+ InstallContext *c,
+ const char *name_or_path) {
+
+ assert(c);
+ assert(name_or_path);
+
+ if (path_is_absolute(name_or_path))
+ return install_info_add(c, NULL, name_or_path);
+ else
+ return install_info_add(c, name_or_path, NULL);
+}
+
+static int config_parse_also(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ char *w;
+ size_t l;
+ char *state;
+ InstallContext *c = data;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+
+ FOREACH_WORD_QUOTED(w, l, rvalue, state) {
+ _cleanup_free_ char *n;
+ int r;
+
+ n = strndup(w, l);
+ if (!n)
+ return -ENOMEM;
+
+ r = install_info_add(c, n, NULL);
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static int config_parse_user(const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ InstallInfo *i = data;
+ char* printed;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+
+ printed = install_full_printf(i, rvalue);
+ if (!printed)
+ return -ENOMEM;
+
+ free(i->user);
+ i->user = printed;
+
+ return 0;
+}
+
+static int unit_file_load(
+ InstallContext *c,
+ InstallInfo *info,
+ const char *path,
+ bool allow_symlink) {
+
+ const ConfigTableItem items[] = {
+ { "Install", "Alias", config_parse_strv, 0, &info->aliases },
+ { "Install", "WantedBy", config_parse_strv, 0, &info->wanted_by },
+ { "Install", "RequiredBy", config_parse_strv, 0, &info->required_by },
+ { "Install", "Also", config_parse_also, 0, c },
+ { "Exec", "User", config_parse_user, 0, info },
+ { NULL, NULL, NULL, 0, NULL }
+ };
+
+ int fd;
+ _cleanup_fclose_ FILE *f = NULL;
+ int r;
+
+ assert(c);
+ assert(info);
+ assert(path);
+
+ fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY|(allow_symlink ? 0 : O_NOFOLLOW));
+ if (fd < 0)
+ return -errno;
+
+ f = fdopen(fd, "re");
+ if (!f) {
+ close_nointr_nofail(fd);
+ return -ENOMEM;
+ }
+
+ r = config_parse(NULL, path, f, NULL,
+ config_item_table_lookup, (void*) items, true, true, info);
+ if (r < 0)
+ return r;
+
+ return
+ strv_length(info->aliases) +
+ strv_length(info->wanted_by) +
+ strv_length(info->required_by);
+}
+
+static int unit_file_search(
+ InstallContext *c,
+ InstallInfo *info,
+ LookupPaths *paths,
+ const char *root_dir,
+ bool allow_symlink) {
+
+ char **p;
+ int r;
+
+ assert(c);
+ assert(info);
+ assert(paths);
+
+ if (info->path)
+ return unit_file_load(c, info, info->path, allow_symlink);
+
+ assert(info->name);
+
+ STRV_FOREACH(p, paths->unit_path) {
+ char *path = NULL;
+
+ if (isempty(root_dir))
+ asprintf(&path, "%s/%s", *p, info->name);
+ else
+ asprintf(&path, "%s/%s/%s", root_dir, *p, info->name);
+
+ if (!path)
+ return -ENOMEM;
+
+ r = unit_file_load(c, info, path, allow_symlink);
+
+ if (r >= 0)
+ info->path = path;
+ else {
+ if (r == -ENOENT && unit_name_is_instance(info->name)) {
+ /* unit file doesn't exist, however instance enablement was request */
+ /* we will check if it is possible to load template unit file */
+ char *template = NULL,
+ *template_path = NULL,
+ *template_dir = NULL;
+
+ template = unit_name_template(info->name);
+ if (!template) {
+ free(path);
+ return -ENOMEM;
+ }
+
+ /* we will reuse path variable since we don't need it anymore */
+ template_dir = path;
+ *(strrchr(path, '/') + 1) = '\0';
+
+ template_path = strjoin(template_dir, template, NULL);
+ if (!template_path) {
+ free(path);
+ free(template);
+ return -ENOMEM;
+ }
+
+ /* let's try to load template unit */
+ r = unit_file_load(c, info, template_path, allow_symlink);
+ if (r >= 0) {
+ info->path = strdup(template_path);
+ if (!info->path) {
+ free(path);
+ free(template);
+ free(template_path);
+ return -ENOMEM;
+ }
+ }
+
+ free(template);
+ free(template_path);
+ }
+ free(path);
+ }
+
+ if (r != -ENOENT && r != -ELOOP)
+ return r;
+ }
+
+ return -ENOENT;
+}
+
+static int unit_file_can_install(
+ LookupPaths *paths,
+ const char *root_dir,
+ const char *name,
+ bool allow_symlink) {
+
+ _cleanup_install_context_done_ InstallContext c = {};
+ InstallInfo *i;
+ int r;
+
+ assert(paths);
+ assert(name);
+
+ r = install_info_add_auto(&c, name);
+ if (r < 0)
+ return r;
+
+ assert_se(i = hashmap_first(c.will_install));
+
+ r = unit_file_search(&c, i, paths, root_dir, allow_symlink);
+
+ if (r >= 0)
+ r =
+ strv_length(i->aliases) +
+ strv_length(i->wanted_by) +
+ strv_length(i->required_by);
+
+ return r;
+}
+
+static int create_symlink(
+ const char *old_path,
+ const char *new_path,
+ bool force,
+ UnitFileChange **changes,
+ unsigned *n_changes) {
+
+ _cleanup_free_ char *dest = NULL;
+ int r;
+
+ assert(old_path);
+ assert(new_path);
+
+ mkdir_parents_label(new_path, 0755);
+
+ if (symlink(old_path, new_path) >= 0) {
+ add_file_change(changes, n_changes, UNIT_FILE_SYMLINK, new_path, old_path);
+ return 0;
+ }
+
+ if (errno != EEXIST)
+ return -errno;
+
+ r = readlink_and_make_absolute(new_path, &dest);
+ if (r < 0)
+ return r;
+
+ if (path_equal(dest, old_path))
+ return 0;
+
+ if (!force)
+ return -EEXIST;
+
+ unlink(new_path);
+
+ if (symlink(old_path, new_path) >= 0) {
+ add_file_change(changes, n_changes, UNIT_FILE_UNLINK, new_path, NULL);
+ add_file_change(changes, n_changes, UNIT_FILE_SYMLINK, new_path, old_path);
+ return 0;
+ }
+
+ return -errno;
+}
+
+static int install_info_symlink_alias(
+ InstallInfo *i,
+ const char *config_path,
+ bool force,
+ UnitFileChange **changes,
+ unsigned *n_changes) {
+
+ char **s;
+ int r = 0, q;
+
+ assert(i);
+ assert(config_path);
+
+ STRV_FOREACH(s, i->aliases) {
+ _cleanup_free_ char *alias_path = NULL, *dst = NULL;
+
+ dst = install_full_printf(i, *s);
+ if (!dst)
+ return -ENOMEM;
+
+ alias_path = path_make_absolute(dst, config_path);
+ if (!alias_path)
+ return -ENOMEM;
+
+ q = create_symlink(i->path, alias_path, force, changes, n_changes);
+ if (r == 0)
+ r = q;
+ }
+
+ return r;
+}
+
+static int install_info_symlink_wants(
+ InstallInfo *i,
+ const char *config_path,
+ bool force,
+ UnitFileChange **changes,
+ unsigned *n_changes) {
+
+ char **s;
+ int r = 0, q;
+
+ assert(i);
+ assert(config_path);
+
+ STRV_FOREACH(s, i->wanted_by) {
+ _cleanup_free_ char *path = NULL, *dst = NULL;
+
+ dst = install_full_printf(i, *s);
+ if (!dst)
+ return -ENOMEM;
+
+ if (!unit_name_is_valid(dst, true)) {
+ r = -EINVAL;
+ continue;
+ }
+
+ if (asprintf(&path, "%s/%s.wants/%s", config_path, dst, i->name) < 0)
+ return -ENOMEM;
+
+ q = create_symlink(i->path, path, force, changes, n_changes);
+
+ if (r == 0)
+ r = q;
+ }
+
+ return r;
+}
+
+static int install_info_symlink_requires(
+ InstallInfo *i,
+ const char *config_path,
+ bool force,
+ UnitFileChange **changes,
+ unsigned *n_changes) {
+
+ char **s;
+ int r = 0, q;
+
+ assert(i);
+ assert(config_path);
+
+ STRV_FOREACH(s, i->required_by) {
+ _cleanup_free_ char *path = NULL, *dst = NULL;
+
+ dst = install_full_printf(i, *s);
+ if (!dst)
+ return -ENOMEM;
+
+ if (!unit_name_is_valid(dst, true)) {
+ r = -EINVAL;
+ continue;
+ }
+
+ if (asprintf(&path, "%s/%s.requires/%s", config_path, dst, i->name) < 0)
+ return -ENOMEM;
+
+ q = create_symlink(i->path, path, force, changes, n_changes);
+
+ if (r == 0)
+ r = q;
+ }
+
+ return r;
+}
+
+static int install_info_symlink_link(
+ InstallInfo *i,
+ LookupPaths *paths,
+ const char *config_path,
+ bool force,
+ UnitFileChange **changes,
+ unsigned *n_changes) {
+
+ int r;
+ _cleanup_free_ char *path = NULL;
+
+ assert(i);
+ assert(paths);
+ assert(config_path);
+ assert(i->path);
+
+ r = in_search_path(i->path, paths->unit_path);
+ if (r != 0)
+ return r;
+
+ if (asprintf(&path, "%s/%s", config_path, i->name) < 0)
+ return -ENOMEM;
+
+ r = create_symlink(i->path, path, force, changes, n_changes);
+ return r;
+}
+
+static int install_info_apply(
+ InstallInfo *i,
+ LookupPaths *paths,
+ const char *config_path,
+ bool force,
+ UnitFileChange **changes,
+ unsigned *n_changes) {
+
+ int r, q;
+
+ assert(i);
+ assert(paths);
+ assert(config_path);
+
+ r = install_info_symlink_alias(i, config_path, force, changes, n_changes);
+
+ q = install_info_symlink_wants(i, config_path, force, changes, n_changes);
+ if (r == 0)
+ r = q;
+
+ q = install_info_symlink_requires(i, config_path, force, changes, n_changes);
+ if (r == 0)
+ r = q;
+
+ q = install_info_symlink_link(i, paths, config_path, force, changes, n_changes);
+ if (r == 0)
+ r = q;
+
+ return r;
+}
+
+static int install_context_apply(
+ InstallContext *c,
+ LookupPaths *paths,
+ const char *config_path,
+ const char *root_dir,
+ bool force,
+ UnitFileChange **changes,
+ unsigned *n_changes) {
+
+ InstallInfo *i;
+ int r = 0, q;
+
+ assert(c);
+ assert(paths);
+ assert(config_path);
+
+ while ((i = hashmap_first(c->will_install))) {
+
+ q = hashmap_ensure_allocated(&c->have_installed, string_hash_func, string_compare_func);
+ if (q < 0)
+ return q;
+
+ assert_se(hashmap_move_one(c->have_installed, c->will_install, i->name) == 0);
+
+ q = unit_file_search(c, i, paths, root_dir, false);
+ if (q < 0) {
+ if (r >= 0)
+ r = q;
+
+ return r;
+ } else if (r >= 0)
+ r += q;
+
+ q = install_info_apply(i, paths, config_path, force, changes, n_changes);
+ if (r >= 0 && q < 0)
+ r = q;
+ }
+
+ return r;
+}
+
+static int install_context_mark_for_removal(
+ InstallContext *c,
+ LookupPaths *paths,
+ Set **remove_symlinks_to,
+ const char *config_path,
+ const char *root_dir) {
+
+ InstallInfo *i;
+ int r = 0, q;
+
+ assert(c);
+ assert(paths);
+ assert(config_path);
+
+ /* Marks all items for removal */
+
+ while ((i = hashmap_first(c->will_install))) {
+
+ q = hashmap_ensure_allocated(&c->have_installed, string_hash_func, string_compare_func);
+ if (q < 0)
+ return q;
+
+ assert_se(hashmap_move_one(c->have_installed, c->will_install, i->name) == 0);
+
+ q = unit_file_search(c, i, paths, root_dir, false);
+ if (q < 0) {
+ if (r >= 0)
+ r = q;
+
+ return r;
+ } else if (r >= 0)
+ r += q;
+
+ if (unit_name_is_instance(i->name)) {
+ char *unit_file = NULL;
+
+ unit_file = path_get_file_name(i->path);
+
+ if (unit_name_is_instance(unit_file))
+ /* unit file named as instance exists, thus all symlinks pointing to it, will be removed */
+ q = mark_symlink_for_removal(remove_symlinks_to, i->name);
+ else
+ /* does not exist, thus we will mark for removal symlinks to template unit file */
+ q = mark_symlink_for_removal(remove_symlinks_to, unit_file);
+ } else
+ q = mark_symlink_for_removal(remove_symlinks_to, i->name);
+
+ if (r >= 0 && q < 0)
+ r = q;
+ }
+
+ return r;
+}
+
+int unit_file_enable(
+ UnitFileScope scope,
+ bool runtime,
+ const char *root_dir,
+ char *files[],
+ bool force,
+ UnitFileChange **changes,
+ unsigned *n_changes) {
+
+ _cleanup_lookup_paths_free_ LookupPaths paths = {};
+ _cleanup_install_context_done_ InstallContext c = {};
+ char **i;
+ _cleanup_free_ char *config_path = NULL;
+ int r;
+
+ assert(scope >= 0);
+ assert(scope < _UNIT_FILE_SCOPE_MAX);
+
+ r = lookup_paths_init_from_scope(&paths, scope);
+ if (r < 0)
+ return r;
+
+ r = get_config_path(scope, runtime, root_dir, &config_path);
+ if (r < 0)
+ return r;
+
+ STRV_FOREACH(i, files) {
+ r = install_info_add_auto(&c, *i);
+ if (r < 0)
+ return r;
+ }
+
+ /* This will return the number of symlink rules that were
+ supposed to be created, not the ones actually created. This is
+ useful to determine whether the passed files had any
+ installation data at all. */
+ r = install_context_apply(&c, &paths, config_path, root_dir, force, changes, n_changes);
+ return r;
+}
+
+int unit_file_disable(
+ UnitFileScope scope,
+ bool runtime,
+ const char *root_dir,
+ char *files[],
+ UnitFileChange **changes,
+ unsigned *n_changes) {
+
+ _cleanup_lookup_paths_free_ LookupPaths paths = {};
+ _cleanup_install_context_done_ InstallContext c = {};
+ char **i;
+ _cleanup_free_ char *config_path = NULL;
+ _cleanup_set_free_free_ Set *remove_symlinks_to = NULL;
+ int r, q;
+
+ assert(scope >= 0);
+ assert(scope < _UNIT_FILE_SCOPE_MAX);
+
+ r = lookup_paths_init_from_scope(&paths, scope);
+ if (r < 0)
+ return r;
+
+ r = get_config_path(scope, runtime, root_dir, &config_path);
+ if (r < 0)
+ return r;
+
+ STRV_FOREACH(i, files) {
+ r = install_info_add_auto(&c, *i);
+ if (r < 0)
+ return r;
+ }
+
+ r = install_context_mark_for_removal(&c, &paths, &remove_symlinks_to, config_path, root_dir);
+
+ q = remove_marked_symlinks(remove_symlinks_to, config_path, changes, n_changes, files);
+ if (r == 0)
+ r = q;
+
+ return r;
+}
+
+int unit_file_reenable(
+ UnitFileScope scope,
+ bool runtime,
+ const char *root_dir,
+ char *files[],
+ bool force,
+ UnitFileChange **changes,
+ unsigned *n_changes) {
+
+ _cleanup_lookup_paths_free_ LookupPaths paths = {};
+ _cleanup_install_context_done_ InstallContext c = {};
+ char **i;
+ _cleanup_free_ char *config_path = NULL;
+ _cleanup_set_free_free_ Set *remove_symlinks_to = NULL;
+ int r, q;
+
+ assert(scope >= 0);
+ assert(scope < _UNIT_FILE_SCOPE_MAX);
+
+ r = lookup_paths_init_from_scope(&paths, scope);
+ if (r < 0)
+ return r;
+
+ r = get_config_path(scope, runtime, root_dir, &config_path);
+ if (r < 0)
+ return r;
+
+ STRV_FOREACH(i, files) {
+ r = mark_symlink_for_removal(&remove_symlinks_to, *i);
+ if (r < 0)
+ return r;
+
+ r = install_info_add_auto(&c, *i);
+ if (r < 0)
+ return r;
+ }
+
+ r = remove_marked_symlinks(remove_symlinks_to, config_path, changes, n_changes, files);
+
+ /* Returns number of symlinks that where supposed to be installed. */
+ q = install_context_apply(&c, &paths, config_path, root_dir, force, changes, n_changes);
+ if (r == 0)
+ r = q;
+
+ return r;
+}
+
+UnitFileState unit_file_get_state(
+ UnitFileScope scope,
+ const char *root_dir,
+ const char *name) {
+
+ _cleanup_lookup_paths_free_ LookupPaths paths = {};
+ UnitFileState state = _UNIT_FILE_STATE_INVALID;
+ char **i;
+ _cleanup_free_ char *path = NULL;
+ int r;
+
+ assert(scope >= 0);
+ assert(scope < _UNIT_FILE_SCOPE_MAX);
+ assert(name);
+
+ if (root_dir && scope != UNIT_FILE_SYSTEM)
+ return -EINVAL;
+
+ if (!unit_name_is_valid(name, true))
+ return -EINVAL;
+
+ r = lookup_paths_init_from_scope(&paths, scope);
+ if (r < 0)
+ return r;
+
+ STRV_FOREACH(i, paths.unit_path) {
+ struct stat st;
+
+ free(path);
+ path = NULL;
+
+ if (root_dir)
+ asprintf(&path, "%s/%s/%s", root_dir, *i, name);
+ else
+ asprintf(&path, "%s/%s", *i, name);
+
+ if (!path)
+ return -ENOMEM;
+
+ if (lstat(path, &st) < 0) {
+ r = -errno;
+ if (errno == ENOENT)
+ continue;
+
+ return -errno;
+ }
+
+ if (!S_ISREG(st.st_mode) && !S_ISLNK(st.st_mode))
+ return -ENOENT;
+
+ r = null_or_empty_path(path);
+ if (r < 0 && r != -ENOENT)
+ return r;
+ else if (r > 0) {
+ state = path_startswith(*i, "/run") ?
+ UNIT_FILE_MASKED_RUNTIME : UNIT_FILE_MASKED;
+ return state;
+ }
+
+ r = find_symlinks_in_scope(scope, root_dir, name, &state);
+ if (r < 0)
+ return r;
+ else if (r > 0)
+ return state;
+
+ r = unit_file_can_install(&paths, root_dir, path, true);
+ if (r < 0 && errno != ENOENT)
+ return r;
+ else if (r > 0)
+ return UNIT_FILE_DISABLED;
+ else if (r == 0)
+ return UNIT_FILE_STATIC;
+ }
+
+ return r < 0 ? r : state;
+}
+
+int unit_file_query_preset(UnitFileScope scope, const char *name) {
+ _cleanup_strv_free_ char **files = NULL;
+ char **i;
+ int r;
+
+ assert(scope >= 0);
+ assert(scope < _UNIT_FILE_SCOPE_MAX);
+ assert(name);
+
+ if (scope == UNIT_FILE_SYSTEM)
+ r = conf_files_list(&files, ".preset", NULL,
+ "/etc/systemd/system-preset",
+ "/usr/local/lib/systemd/system-preset",
+ "/usr/lib/systemd/system-preset",
+#ifdef HAVE_SPLIT_USR
+ "/lib/systemd/system-preset",
+#endif
+ NULL);
+ else if (scope == UNIT_FILE_GLOBAL)
+ r = conf_files_list(&files, ".preset", NULL,
+ "/etc/systemd/user-preset",
+ "/usr/local/lib/systemd/user-preset",
+ "/usr/lib/systemd/user-preset",
+ NULL);
+ else
+ return 1;
+
+ if (r < 0)
+ return r;
+
+ STRV_FOREACH(i, files) {
+ _cleanup_fclose_ FILE *f;
+
+ f = fopen(*i, "re");
+ if (!f) {
+ if (errno == ENOENT)
+ continue;
+
+ return -errno;
+ }
+
+ for (;;) {
+ char line[LINE_MAX], *l;
+
+ if (!fgets(line, sizeof(line), f))
+ break;
+
+ l = strstrip(line);
+ if (!*l)
+ continue;
+
+ if (strchr(COMMENTS "\n", *l))
+ continue;
+
+ if (first_word(l, "enable")) {
+ l += 6;
+ l += strspn(l, WHITESPACE);
+
+ if (fnmatch(l, name, FNM_NOESCAPE) == 0)
+ return 1;
+
+ } else if (first_word(l, "disable")) {
+ l += 7;
+ l += strspn(l, WHITESPACE);
+
+ if (fnmatch(l, name, FNM_NOESCAPE) == 0)
+ return 0;
+
+ } else
+ log_debug("Couldn't parse line '%s'", l);
+ }
+ }
+
+ /* Default is "enable" */
+ return 1;
+}
+
+int unit_file_preset(
+ UnitFileScope scope,
+ bool runtime,
+ const char *root_dir,
+ char *files[],
+ bool force,
+ UnitFileChange **changes,
+ unsigned *n_changes) {
+
+ _cleanup_lookup_paths_free_ LookupPaths paths = {};
+ _cleanup_install_context_done_ InstallContext plus = {}, minus = {};
+ char **i;
+ _cleanup_free_ char *config_path = NULL;
+ _cleanup_set_free_free_ Set *remove_symlinks_to = NULL;
+ int r, q;
+
+ assert(scope >= 0);
+ assert(scope < _UNIT_FILE_SCOPE_MAX);
+
+ r = lookup_paths_init_from_scope(&paths, scope);
+ if (r < 0)
+ return r;
+
+ r = get_config_path(scope, runtime, root_dir, &config_path);
+ if (r < 0)
+ return r;
+
+ STRV_FOREACH(i, files) {
+
+ if (!unit_name_is_valid(*i, true))
+ return -EINVAL;
+
+ r = unit_file_query_preset(scope, *i);
+ if (r < 0)
+ return r;
+
+ if (r)
+ r = install_info_add_auto(&plus, *i);
+ else
+ r = install_info_add_auto(&minus, *i);
+
+ if (r < 0)
+ return r;
+ }
+
+ r = install_context_mark_for_removal(&minus, &paths, &remove_symlinks_to,
+ config_path, root_dir);
+
+ q = remove_marked_symlinks(remove_symlinks_to, config_path,
+ changes, n_changes, files);
+ if (r == 0)
+ r = q;
+
+ /* Returns number of symlinks that where supposed to be installed. */
+ q = install_context_apply(&plus, &paths, config_path, root_dir, force,
+ changes, n_changes);
+ if (r == 0)
+ r = q;
+
+ return r;
+}
+
+static void unitfilelist_free(UnitFileList **f) {
+ if (!*f)
+ return;
+
+ free((*f)->path);
+ free(*f);
+}
+
+int unit_file_get_list(
+ UnitFileScope scope,
+ const char *root_dir,
+ Hashmap *h) {
+
+ _cleanup_lookup_paths_free_ LookupPaths paths = {};
+ char **i;
+ _cleanup_free_ char *buf = NULL;
+ _cleanup_closedir_ DIR *d = NULL;
+ int r;
+
+ assert(scope >= 0);
+ assert(scope < _UNIT_FILE_SCOPE_MAX);
+ assert(h);
+
+ if (root_dir && scope != UNIT_FILE_SYSTEM)
+ return -EINVAL;
+
+ r = lookup_paths_init_from_scope(&paths, scope);
+ if (r < 0)
+ return r;
+
+ STRV_FOREACH(i, paths.unit_path) {
+ const char *units_dir;
+
+ free(buf);
+ buf = NULL;
+
+ if (root_dir) {
+ if (asprintf(&buf, "%s/%s", root_dir, *i) < 0)
+ return -ENOMEM;
+
+ units_dir = buf;
+ } else
+ units_dir = *i;
+
+ if (d)
+ closedir(d);
+
+ d = opendir(units_dir);
+ if (!d) {
+ if (errno == ENOENT)
+ continue;
+
+ return -errno;
+ }
+
+ for (;;) {
+ struct dirent *de;
+ union dirent_storage buffer;
+ UnitFileList __attribute__((cleanup(unitfilelist_free)))
+ *f = NULL;
+
+ r = readdir_r(d, &buffer.de, &de);
+ if (r != 0)
+ return -r;
+
+ if (!de)
+ break;
+
+ if (ignore_file(de->d_name))
+ continue;
+
+ if (!unit_name_is_valid(de->d_name, true))
+ continue;
+
+ if (hashmap_get(h, de->d_name))
+ continue;
+
+ r = dirent_ensure_type(d, de);
+ if (r < 0) {
+ if (r == -ENOENT)
+ continue;
+
+ return r;
+ }
+
+ if (de->d_type != DT_LNK && de->d_type != DT_REG)
+ continue;
+
+ f = new0(UnitFileList, 1);
+ if (!f)
+ return -ENOMEM;
+
+ f->path = path_make_absolute(de->d_name, units_dir);
+ if (!f->path)
+ return -ENOMEM;
+
+ r = null_or_empty_path(f->path);
+ if (r < 0 && r != -ENOENT)
+ return r;
+ else if (r > 0) {
+ f->state =
+ path_startswith(*i, "/run") ?
+ UNIT_FILE_MASKED_RUNTIME : UNIT_FILE_MASKED;
+ goto found;
+ }
+
+ r = find_symlinks_in_scope(scope, root_dir, de->d_name, &f->state);
+ if (r < 0)
+ return r;
+ else if (r > 0) {
+ f->state = UNIT_FILE_ENABLED;
+ goto found;
+ }
+
+ r = unit_file_can_install(&paths, root_dir, f->path, true);
+ if (r == -EINVAL || /* Invalid setting? */
+ r == -EBADMSG || /* Invalid format? */
+ r == -ENOENT /* Included file not found? */)
+ f->state = UNIT_FILE_INVALID;
+ else if (r < 0)
+ return r;
+ else if (r > 0)
+ f->state = UNIT_FILE_DISABLED;
+ else
+ f->state = UNIT_FILE_STATIC;
+
+ found:
+ r = hashmap_put(h, path_get_file_name(f->path), f);
+ if (r < 0)
+ return r;
+ f = NULL; /* prevent cleanup */
+ }
+ }
+
+ return r;
+}
+
+static const char* const unit_file_state_table[_UNIT_FILE_STATE_MAX] = {
+ [UNIT_FILE_ENABLED] = "enabled",
+ [UNIT_FILE_ENABLED_RUNTIME] = "enabled-runtime",
+ [UNIT_FILE_LINKED] = "linked",
+ [UNIT_FILE_LINKED_RUNTIME] = "linked-runtime",
+ [UNIT_FILE_MASKED] = "masked",
+ [UNIT_FILE_MASKED_RUNTIME] = "masked-runtime",
+ [UNIT_FILE_STATIC] = "static",
+ [UNIT_FILE_DISABLED] = "disabled",
+ [UNIT_FILE_INVALID] = "invalid",
+};
+
+DEFINE_STRING_TABLE_LOOKUP(unit_file_state, UnitFileState);
+
+static const char* const unit_file_change_type_table[_UNIT_FILE_CHANGE_TYPE_MAX] = {
+ [UNIT_FILE_SYMLINK] = "symlink",
+ [UNIT_FILE_UNLINK] = "unlink",
+};
+
+DEFINE_STRING_TABLE_LOOKUP(unit_file_change_type, UnitFileChangeType);
diff --git a/src/shared/install.h b/src/shared/install.h
new file mode 100644
index 0000000000..94516c9d05
--- /dev/null
+++ b/src/shared/install.h
@@ -0,0 +1,97 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "hashmap.h"
+
+typedef enum UnitFileScope {
+ UNIT_FILE_SYSTEM,
+ UNIT_FILE_GLOBAL,
+ UNIT_FILE_USER,
+ _UNIT_FILE_SCOPE_MAX,
+ _UNIT_FILE_SCOPE_INVALID = -1
+} UnitFileScope;
+
+typedef enum UnitFileState {
+ UNIT_FILE_ENABLED,
+ UNIT_FILE_ENABLED_RUNTIME,
+ UNIT_FILE_LINKED,
+ UNIT_FILE_LINKED_RUNTIME,
+ UNIT_FILE_MASKED,
+ UNIT_FILE_MASKED_RUNTIME,
+ UNIT_FILE_STATIC,
+ UNIT_FILE_DISABLED,
+ UNIT_FILE_INVALID,
+ _UNIT_FILE_STATE_MAX,
+ _UNIT_FILE_STATE_INVALID = -1
+} UnitFileState;
+
+typedef enum UnitFileChangeType {
+ UNIT_FILE_SYMLINK,
+ UNIT_FILE_UNLINK,
+ _UNIT_FILE_CHANGE_TYPE_MAX,
+ _UNIT_FILE_CHANGE_TYPE_INVALID = -1
+} UnitFileChangeType;
+
+typedef struct UnitFileChange {
+ UnitFileChangeType type;
+ char *path;
+ char *source;
+} UnitFileChange;
+
+typedef struct UnitFileList {
+ char *path;
+ UnitFileState state;
+} UnitFileList;
+
+typedef struct {
+ char *name;
+ char *path;
+ char *user;
+
+ char **aliases;
+ char **wanted_by;
+ char **required_by;
+} InstallInfo;
+
+int unit_file_enable(UnitFileScope scope, bool runtime, const char *root_dir, char *files[], bool force, UnitFileChange **changes, unsigned *n_changes);
+int unit_file_disable(UnitFileScope scope, bool runtime, const char *root_dir, char *files[], UnitFileChange **changes, unsigned *n_changes);
+int unit_file_reenable(UnitFileScope scope, bool runtime, const char *root_dir, char *files[], bool force, UnitFileChange **changes, unsigned *n_changes);
+int unit_file_link(UnitFileScope scope, bool runtime, const char *root_dir, char *files[], bool force, UnitFileChange **changes, unsigned *n_changes);
+int unit_file_preset(UnitFileScope scope, bool runtime, const char *root_dir, char *files[], bool force, UnitFileChange **changes, unsigned *n_changes);
+int unit_file_mask(UnitFileScope scope, bool runtime, const char *root_dir, char *files[], bool force, UnitFileChange **changes, unsigned *n_changes);
+int unit_file_unmask(UnitFileScope scope, bool runtime, const char *root_dir, char *files[], UnitFileChange **changes, unsigned *n_changes);
+
+UnitFileState unit_file_get_state(UnitFileScope scope, const char *root_dir, const char *filename);
+
+int unit_file_get_list(UnitFileScope scope, const char *root_dir, Hashmap *h);
+
+void unit_file_list_free(Hashmap *h);
+void unit_file_changes_free(UnitFileChange *changes, unsigned n_changes);
+
+int unit_file_query_preset(UnitFileScope scope, const char *name);
+
+const char *unit_file_state_to_string(UnitFileState s) _const_;
+UnitFileState unit_file_state_from_string(const char *s) _pure_;
+
+const char *unit_file_change_type_to_string(UnitFileChangeType s) _const_;
+UnitFileChangeType unit_file_change_type_from_string(const char *s) _pure_;
diff --git a/src/shared/ioprio.h b/src/shared/ioprio.h
new file mode 100644
index 0000000000..9800fc2553
--- /dev/null
+++ b/src/shared/ioprio.h
@@ -0,0 +1,57 @@
+#ifndef IOPRIO_H
+#define IOPRIO_H
+
+/* This is minimal version of Linux' linux/ioprio.h header file, which
+ * is licensed GPL2 */
+
+#include <unistd.h>
+#include <sys/syscall.h>
+
+/*
+ * Gives us 8 prio classes with 13-bits of data for each class
+ */
+#define IOPRIO_BITS (16)
+#define IOPRIO_CLASS_SHIFT (13)
+#define IOPRIO_PRIO_MASK ((1UL << IOPRIO_CLASS_SHIFT) - 1)
+
+#define IOPRIO_PRIO_CLASS(mask) ((mask) >> IOPRIO_CLASS_SHIFT)
+#define IOPRIO_PRIO_DATA(mask) ((mask) & IOPRIO_PRIO_MASK)
+#define IOPRIO_PRIO_VALUE(class, data) (((class) << IOPRIO_CLASS_SHIFT) | data)
+
+#define ioprio_valid(mask) (IOPRIO_PRIO_CLASS((mask)) != IOPRIO_CLASS_NONE)
+
+/*
+ * These are the io priority groups as implemented by CFQ. RT is the realtime
+ * class, it always gets premium service. BE is the best-effort scheduling
+ * class, the default for any process. IDLE is the idle scheduling class, it
+ * is only served when no one else is using the disk.
+ */
+enum {
+ IOPRIO_CLASS_NONE,
+ IOPRIO_CLASS_RT,
+ IOPRIO_CLASS_BE,
+ IOPRIO_CLASS_IDLE,
+};
+
+/*
+ * 8 best effort priority levels are supported
+ */
+#define IOPRIO_BE_NR (8)
+
+enum {
+ IOPRIO_WHO_PROCESS = 1,
+ IOPRIO_WHO_PGRP,
+ IOPRIO_WHO_USER,
+};
+
+static inline int ioprio_set(int which, int who, int ioprio)
+{
+ return syscall(__NR_ioprio_set, which, who, ioprio);
+}
+
+static inline int ioprio_get(int which, int who)
+{
+ return syscall(__NR_ioprio_get, which, who);
+}
+
+#endif
diff --git a/src/shared/label.c b/src/shared/label.c
new file mode 100644
index 0000000000..1fe4574633
--- /dev/null
+++ b/src/shared/label.c
@@ -0,0 +1,386 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <malloc.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+
+#include "label.h"
+#include "strv.h"
+#include "util.h"
+#include "path-util.h"
+
+#ifdef HAVE_SELINUX
+#include "selinux-util.h"
+#include <selinux/selinux.h>
+#include <selinux/label.h>
+
+static struct selabel_handle *label_hnd = NULL;
+
+#endif
+
+int label_init(const char *prefix) {
+ int r = 0;
+
+#ifdef HAVE_SELINUX
+ usec_t before_timestamp, after_timestamp;
+ struct mallinfo before_mallinfo, after_mallinfo;
+
+ if (!use_selinux())
+ return 0;
+
+ if (label_hnd)
+ return 0;
+
+ before_mallinfo = mallinfo();
+ before_timestamp = now(CLOCK_MONOTONIC);
+
+ if (prefix) {
+ struct selinux_opt options[] = {
+ { .type = SELABEL_OPT_SUBSET, .value = prefix },
+ };
+
+ label_hnd = selabel_open(SELABEL_CTX_FILE, options, ELEMENTSOF(options));
+ } else
+ label_hnd = selabel_open(SELABEL_CTX_FILE, NULL, 0);
+
+ if (!label_hnd) {
+ log_full(security_getenforce() == 1 ? LOG_ERR : LOG_DEBUG,
+ "Failed to initialize SELinux context: %m");
+ r = security_getenforce() == 1 ? -errno : 0;
+ } else {
+ char timespan[FORMAT_TIMESPAN_MAX];
+ int l;
+
+ after_timestamp = now(CLOCK_MONOTONIC);
+ after_mallinfo = mallinfo();
+
+ l = after_mallinfo.uordblks > before_mallinfo.uordblks ? after_mallinfo.uordblks - before_mallinfo.uordblks : 0;
+
+ log_debug("Successfully loaded SELinux database in %s, size on heap is %iK.",
+ format_timespan(timespan, sizeof(timespan), after_timestamp - before_timestamp, 0),
+ (l+1023)/1024);
+ }
+#endif
+
+ return r;
+}
+
+int label_fix(const char *path, bool ignore_enoent, bool ignore_erofs) {
+ int r = 0;
+
+#ifdef HAVE_SELINUX
+ struct stat st;
+ security_context_t fcon;
+
+ if (!use_selinux() || !label_hnd)
+ return 0;
+
+ r = lstat(path, &st);
+ if (r == 0) {
+ r = selabel_lookup_raw(label_hnd, &fcon, path, st.st_mode);
+
+ /* If there's no label to set, then exit without warning */
+ if (r < 0 && errno == ENOENT)
+ return 0;
+
+ if (r == 0) {
+ r = lsetfilecon(path, fcon);
+ freecon(fcon);
+
+ /* If the FS doesn't support labels, then exit without warning */
+ if (r < 0 && errno == ENOTSUP)
+ return 0;
+ }
+ }
+
+ if (r < 0) {
+ /* Ignore ENOENT in some cases */
+ if (ignore_enoent && errno == ENOENT)
+ return 0;
+
+ if (ignore_erofs && errno == EROFS)
+ return 0;
+
+ log_full(security_getenforce() == 1 ? LOG_ERR : LOG_DEBUG,
+ "Unable to fix label of %s: %m", path);
+ r = security_getenforce() == 1 ? -errno : 0;
+ }
+#endif
+
+ return r;
+}
+
+void label_finish(void) {
+
+#ifdef HAVE_SELINUX
+ if (use_selinux() && label_hnd)
+ selabel_close(label_hnd);
+#endif
+}
+
+int label_get_create_label_from_exe(const char *exe, char **label) {
+
+ int r = 0;
+
+#ifdef HAVE_SELINUX
+ security_context_t mycon = NULL, fcon = NULL;
+ security_class_t sclass;
+
+ if (!use_selinux()) {
+ *label = NULL;
+ return 0;
+ }
+
+ r = getcon(&mycon);
+ if (r < 0)
+ goto fail;
+
+ r = getfilecon(exe, &fcon);
+ if (r < 0)
+ goto fail;
+
+ sclass = string_to_security_class("process");
+ r = security_compute_create(mycon, fcon, sclass, (security_context_t *) label);
+ if (r == 0)
+ log_debug("SELinux Socket context for %s will be set to %s", exe, *label);
+
+fail:
+ if (r < 0 && security_getenforce() == 1)
+ r = -errno;
+
+ freecon(mycon);
+ freecon(fcon);
+#endif
+
+ return r;
+}
+
+int label_context_set(const char *path, mode_t mode) {
+ int r = 0;
+
+#ifdef HAVE_SELINUX
+ security_context_t filecon = NULL;
+
+ if (!use_selinux() || !label_hnd)
+ return 0;
+
+ r = selabel_lookup_raw(label_hnd, &filecon, path, mode);
+ if (r < 0 && errno != ENOENT)
+ r = -errno;
+ else if (r == 0) {
+ r = setfscreatecon(filecon);
+ if (r < 0) {
+ log_error("Failed to set SELinux file context on %s: %m", path);
+ r = -errno;
+ }
+
+ freecon(filecon);
+ }
+
+ if (r < 0 && security_getenforce() == 0)
+ r = 0;
+#endif
+
+ return r;
+}
+
+int label_socket_set(const char *label) {
+
+#ifdef HAVE_SELINUX
+ if (!use_selinux())
+ return 0;
+
+ if (setsockcreatecon((security_context_t) label) < 0) {
+ log_full(security_getenforce() == 1 ? LOG_ERR : LOG_DEBUG,
+ "Failed to set SELinux context (%s) on socket: %m", label);
+
+ if (security_getenforce() == 1)
+ return -errno;
+ }
+#endif
+
+ return 0;
+}
+
+void label_context_clear(void) {
+
+#ifdef HAVE_SELINUX
+ if (!use_selinux())
+ return;
+
+ setfscreatecon(NULL);
+#endif
+}
+
+void label_socket_clear(void) {
+
+#ifdef HAVE_SELINUX
+ if (!use_selinux())
+ return;
+
+ setsockcreatecon(NULL);
+#endif
+}
+
+void label_free(const char *label) {
+
+#ifdef HAVE_SELINUX
+ if (!use_selinux())
+ return;
+
+ freecon((security_context_t) label);
+#endif
+}
+
+int label_mkdir(const char *path, mode_t mode, bool apply) {
+
+ /* Creates a directory and labels it according to the SELinux policy */
+#ifdef HAVE_SELINUX
+ int r;
+ security_context_t fcon = NULL;
+
+ if (!apply || !use_selinux() || !label_hnd)
+ goto skipped;
+
+ if (path_is_absolute(path))
+ r = selabel_lookup_raw(label_hnd, &fcon, path, S_IFDIR);
+ else {
+ char *newpath;
+
+ newpath = path_make_absolute_cwd(path);
+ if (!newpath)
+ return -ENOMEM;
+
+ r = selabel_lookup_raw(label_hnd, &fcon, newpath, S_IFDIR);
+ free(newpath);
+ }
+
+ if (r == 0)
+ r = setfscreatecon(fcon);
+
+ if (r < 0 && errno != ENOENT) {
+ log_error("Failed to set security context %s for %s: %m", fcon, path);
+
+ if (security_getenforce() == 1) {
+ r = -errno;
+ goto finish;
+ }
+ }
+
+ r = mkdir(path, mode);
+ if (r < 0)
+ r = -errno;
+
+finish:
+ setfscreatecon(NULL);
+ freecon(fcon);
+
+ return r;
+
+skipped:
+#endif
+ return mkdir(path, mode) < 0 ? -errno : 0;
+}
+
+int label_bind(int fd, const struct sockaddr *addr, socklen_t addrlen) {
+
+ /* Binds a socket and label its file system object according to the SELinux policy */
+
+#ifdef HAVE_SELINUX
+ int r;
+ security_context_t fcon = NULL;
+ const struct sockaddr_un *un;
+ char *path = NULL;
+
+ assert(fd >= 0);
+ assert(addr);
+ assert(addrlen >= sizeof(sa_family_t));
+
+ if (!use_selinux() || !label_hnd)
+ goto skipped;
+
+ /* Filter out non-local sockets */
+ if (addr->sa_family != AF_UNIX)
+ goto skipped;
+
+ /* Filter out anonymous sockets */
+ if (addrlen < sizeof(sa_family_t) + 1)
+ goto skipped;
+
+ /* Filter out abstract namespace sockets */
+ un = (const struct sockaddr_un*) addr;
+ if (un->sun_path[0] == 0)
+ goto skipped;
+
+ path = strndup(un->sun_path, addrlen - offsetof(struct sockaddr_un, sun_path));
+ if (!path)
+ return -ENOMEM;
+
+ if (path_is_absolute(path))
+ r = selabel_lookup_raw(label_hnd, &fcon, path, S_IFSOCK);
+ else {
+ char *newpath;
+
+ newpath = path_make_absolute_cwd(path);
+
+ if (!newpath) {
+ free(path);
+ return -ENOMEM;
+ }
+
+ r = selabel_lookup_raw(label_hnd, &fcon, newpath, S_IFSOCK);
+ free(newpath);
+ }
+
+ if (r == 0)
+ r = setfscreatecon(fcon);
+
+ if (r < 0 && errno != ENOENT) {
+ log_error("Failed to set security context %s for %s: %m", fcon, path);
+
+ if (security_getenforce() == 1) {
+ r = -errno;
+ goto finish;
+ }
+ }
+
+ r = bind(fd, addr, addrlen);
+ if (r < 0)
+ r = -errno;
+
+finish:
+ setfscreatecon(NULL);
+ freecon(fcon);
+ free(path);
+
+ return r;
+
+skipped:
+#endif
+ return bind(fd, addr, addrlen) < 0 ? -errno : 0;
+}
diff --git a/src/shared/label.h b/src/shared/label.h
new file mode 100644
index 0000000000..dda4d1c024
--- /dev/null
+++ b/src/shared/label.h
@@ -0,0 +1,51 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/types.h>
+#include <stdbool.h>
+#include <sys/socket.h>
+
+int label_init(const char *prefix);
+void label_finish(void);
+
+int label_fix(const char *path, bool ignore_enoent, bool ignore_erofs);
+
+int label_socket_set(const char *label);
+void label_socket_clear(void);
+
+int label_context_set(const char *path, mode_t mode);
+void label_context_clear(void);
+
+void label_free(const char *label);
+
+int label_get_create_label_from_exe(const char *exe, char **label);
+
+int label_mkdir(const char *path, mode_t mode, bool apply);
+
+void label_retest_selinux(void);
+
+int label_bind(int fd, const struct sockaddr *addr, socklen_t addrlen);
+
+int label_write_one_line_file_atomic(const char *fn, const char *line);
+int label_write_env_file(const char *fname, char **l);
+int label_fopen_temporary(const char *path, FILE **_f, char **_temp_path);
diff --git a/src/shared/linux/auto_dev-ioctl.h b/src/shared/linux/auto_dev-ioctl.h
new file mode 100644
index 0000000000..850f39b33e
--- /dev/null
+++ b/src/shared/linux/auto_dev-ioctl.h
@@ -0,0 +1,229 @@
+/*
+ * Copyright 2008 Red Hat, Inc. All rights reserved.
+ * Copyright 2008 Ian Kent <raven@themaw.net>
+ *
+ * This file is part of the Linux kernel and is made available under
+ * the terms of the GNU General Public License, version 2, or at your
+ * option, any later version, incorporated herein by reference.
+ */
+
+#ifndef _LINUX_AUTO_DEV_IOCTL_H
+#define _LINUX_AUTO_DEV_IOCTL_H
+
+#include <linux/auto_fs.h>
+
+#ifdef __KERNEL__
+#include <linux/string.h>
+#else
+#include <string.h>
+#endif /* __KERNEL__ */
+
+#define AUTOFS_DEVICE_NAME "autofs"
+
+#define AUTOFS_DEV_IOCTL_VERSION_MAJOR 1
+#define AUTOFS_DEV_IOCTL_VERSION_MINOR 0
+
+#define AUTOFS_DEVID_LEN 16
+
+#define AUTOFS_DEV_IOCTL_SIZE sizeof(struct autofs_dev_ioctl)
+
+/*
+ * An ioctl interface for autofs mount point control.
+ */
+
+struct args_protover {
+ __u32 version;
+};
+
+struct args_protosubver {
+ __u32 sub_version;
+};
+
+struct args_openmount {
+ __u32 devid;
+};
+
+struct args_ready {
+ __u32 token;
+};
+
+struct args_fail {
+ __u32 token;
+ __s32 status;
+};
+
+struct args_setpipefd {
+ __s32 pipefd;
+};
+
+struct args_timeout {
+ __u64 timeout;
+};
+
+struct args_requester {
+ __u32 uid;
+ __u32 gid;
+};
+
+struct args_expire {
+ __u32 how;
+};
+
+struct args_askumount {
+ __u32 may_umount;
+};
+
+struct args_ismountpoint {
+ union {
+ struct args_in {
+ __u32 type;
+ } in;
+ struct args_out {
+ __u32 devid;
+ __u32 magic;
+ } out;
+ };
+};
+
+/*
+ * All the ioctls use this structure.
+ * When sending a path size must account for the total length
+ * of the chunk of memory otherwise is is the size of the
+ * structure.
+ */
+
+struct autofs_dev_ioctl {
+ __u32 ver_major;
+ __u32 ver_minor;
+ __u32 size; /* total size of data passed in
+ * including this struct */
+ __s32 ioctlfd; /* automount command fd */
+
+ /* Command parameters */
+
+ union {
+ struct args_protover protover;
+ struct args_protosubver protosubver;
+ struct args_openmount openmount;
+ struct args_ready ready;
+ struct args_fail fail;
+ struct args_setpipefd setpipefd;
+ struct args_timeout timeout;
+ struct args_requester requester;
+ struct args_expire expire;
+ struct args_askumount askumount;
+ struct args_ismountpoint ismountpoint;
+ };
+
+ char path[0];
+};
+
+static inline void init_autofs_dev_ioctl(struct autofs_dev_ioctl *in)
+{
+ memset(in, 0, sizeof(struct autofs_dev_ioctl));
+ in->ver_major = AUTOFS_DEV_IOCTL_VERSION_MAJOR;
+ in->ver_minor = AUTOFS_DEV_IOCTL_VERSION_MINOR;
+ in->size = sizeof(struct autofs_dev_ioctl);
+ in->ioctlfd = -1;
+ return;
+}
+
+/*
+ * If you change this make sure you make the corresponding change
+ * to autofs-dev-ioctl.c:lookup_ioctl()
+ */
+enum {
+ /* Get various version info */
+ AUTOFS_DEV_IOCTL_VERSION_CMD = 0x71,
+ AUTOFS_DEV_IOCTL_PROTOVER_CMD,
+ AUTOFS_DEV_IOCTL_PROTOSUBVER_CMD,
+
+ /* Open mount ioctl fd */
+ AUTOFS_DEV_IOCTL_OPENMOUNT_CMD,
+
+ /* Close mount ioctl fd */
+ AUTOFS_DEV_IOCTL_CLOSEMOUNT_CMD,
+
+ /* Mount/expire status returns */
+ AUTOFS_DEV_IOCTL_READY_CMD,
+ AUTOFS_DEV_IOCTL_FAIL_CMD,
+
+ /* Activate/deactivate autofs mount */
+ AUTOFS_DEV_IOCTL_SETPIPEFD_CMD,
+ AUTOFS_DEV_IOCTL_CATATONIC_CMD,
+
+ /* Expiry timeout */
+ AUTOFS_DEV_IOCTL_TIMEOUT_CMD,
+
+ /* Get mount last requesting uid and gid */
+ AUTOFS_DEV_IOCTL_REQUESTER_CMD,
+
+ /* Check for eligible expire candidates */
+ AUTOFS_DEV_IOCTL_EXPIRE_CMD,
+
+ /* Request busy status */
+ AUTOFS_DEV_IOCTL_ASKUMOUNT_CMD,
+
+ /* Check if path is a mountpoint */
+ AUTOFS_DEV_IOCTL_ISMOUNTPOINT_CMD,
+};
+
+#define AUTOFS_IOCTL 0x93
+
+#define AUTOFS_DEV_IOCTL_VERSION \
+ _IOWR(AUTOFS_IOCTL, \
+ AUTOFS_DEV_IOCTL_VERSION_CMD, struct autofs_dev_ioctl)
+
+#define AUTOFS_DEV_IOCTL_PROTOVER \
+ _IOWR(AUTOFS_IOCTL, \
+ AUTOFS_DEV_IOCTL_PROTOVER_CMD, struct autofs_dev_ioctl)
+
+#define AUTOFS_DEV_IOCTL_PROTOSUBVER \
+ _IOWR(AUTOFS_IOCTL, \
+ AUTOFS_DEV_IOCTL_PROTOSUBVER_CMD, struct autofs_dev_ioctl)
+
+#define AUTOFS_DEV_IOCTL_OPENMOUNT \
+ _IOWR(AUTOFS_IOCTL, \
+ AUTOFS_DEV_IOCTL_OPENMOUNT_CMD, struct autofs_dev_ioctl)
+
+#define AUTOFS_DEV_IOCTL_CLOSEMOUNT \
+ _IOWR(AUTOFS_IOCTL, \
+ AUTOFS_DEV_IOCTL_CLOSEMOUNT_CMD, struct autofs_dev_ioctl)
+
+#define AUTOFS_DEV_IOCTL_READY \
+ _IOWR(AUTOFS_IOCTL, \
+ AUTOFS_DEV_IOCTL_READY_CMD, struct autofs_dev_ioctl)
+
+#define AUTOFS_DEV_IOCTL_FAIL \
+ _IOWR(AUTOFS_IOCTL, \
+ AUTOFS_DEV_IOCTL_FAIL_CMD, struct autofs_dev_ioctl)
+
+#define AUTOFS_DEV_IOCTL_SETPIPEFD \
+ _IOWR(AUTOFS_IOCTL, \
+ AUTOFS_DEV_IOCTL_SETPIPEFD_CMD, struct autofs_dev_ioctl)
+
+#define AUTOFS_DEV_IOCTL_CATATONIC \
+ _IOWR(AUTOFS_IOCTL, \
+ AUTOFS_DEV_IOCTL_CATATONIC_CMD, struct autofs_dev_ioctl)
+
+#define AUTOFS_DEV_IOCTL_TIMEOUT \
+ _IOWR(AUTOFS_IOCTL, \
+ AUTOFS_DEV_IOCTL_TIMEOUT_CMD, struct autofs_dev_ioctl)
+
+#define AUTOFS_DEV_IOCTL_REQUESTER \
+ _IOWR(AUTOFS_IOCTL, \
+ AUTOFS_DEV_IOCTL_REQUESTER_CMD, struct autofs_dev_ioctl)
+
+#define AUTOFS_DEV_IOCTL_EXPIRE \
+ _IOWR(AUTOFS_IOCTL, \
+ AUTOFS_DEV_IOCTL_EXPIRE_CMD, struct autofs_dev_ioctl)
+
+#define AUTOFS_DEV_IOCTL_ASKUMOUNT \
+ _IOWR(AUTOFS_IOCTL, \
+ AUTOFS_DEV_IOCTL_ASKUMOUNT_CMD, struct autofs_dev_ioctl)
+
+#define AUTOFS_DEV_IOCTL_ISMOUNTPOINT \
+ _IOWR(AUTOFS_IOCTL, \
+ AUTOFS_DEV_IOCTL_ISMOUNTPOINT_CMD, struct autofs_dev_ioctl)
+
+#endif /* _LINUX_AUTO_DEV_IOCTL_H */
diff --git a/src/shared/linux/fanotify.h b/src/shared/linux/fanotify.h
new file mode 100644
index 0000000000..63531a6b4d
--- /dev/null
+++ b/src/shared/linux/fanotify.h
@@ -0,0 +1,98 @@
+#ifndef _LINUX_FANOTIFY_H
+#define _LINUX_FANOTIFY_H
+
+#include <linux/types.h>
+
+/* the following events that user-space can register for */
+#define FAN_ACCESS 0x00000001 /* File was accessed */
+#define FAN_MODIFY 0x00000002 /* File was modified */
+#define FAN_CLOSE_WRITE 0x00000008 /* Unwrittable file closed */
+#define FAN_CLOSE_NOWRITE 0x00000010 /* Writtable file closed */
+#define FAN_OPEN 0x00000020 /* File was opened */
+
+#define FAN_EVENT_ON_CHILD 0x08000000 /* interested in child events */
+
+/* FIXME currently Q's have no limit.... */
+#define FAN_Q_OVERFLOW 0x00004000 /* Event queued overflowed */
+
+#define FAN_OPEN_PERM 0x00010000 /* File open in perm check */
+#define FAN_ACCESS_PERM 0x00020000 /* File accessed in perm check */
+
+/* helper events */
+#define FAN_CLOSE (FAN_CLOSE_WRITE | FAN_CLOSE_NOWRITE) /* close */
+
+/* flags used for fanotify_init() */
+#define FAN_CLOEXEC 0x00000001
+#define FAN_NONBLOCK 0x00000002
+
+#define FAN_ALL_INIT_FLAGS (FAN_CLOEXEC | FAN_NONBLOCK)
+
+/* flags used for fanotify_modify_mark() */
+#define FAN_MARK_ADD 0x00000001
+#define FAN_MARK_REMOVE 0x00000002
+#define FAN_MARK_DONT_FOLLOW 0x00000004
+#define FAN_MARK_ONLYDIR 0x00000008
+#define FAN_MARK_MOUNT 0x00000010
+#define FAN_MARK_IGNORED_MASK 0x00000020
+#define FAN_MARK_IGNORED_SURV_MODIFY 0x00000040
+#define FAN_MARK_FLUSH 0x00000080
+
+#define FAN_ALL_MARK_FLAGS (FAN_MARK_ADD |\
+ FAN_MARK_REMOVE |\
+ FAN_MARK_DONT_FOLLOW |\
+ FAN_MARK_ONLYDIR |\
+ FAN_MARK_MOUNT |\
+ FAN_MARK_IGNORED_MASK |\
+ FAN_MARK_IGNORED_SURV_MODIFY)
+
+/*
+ * All of the events - we build the list by hand so that we can add flags in
+ * the future and not break backward compatibility. Apps will get only the
+ * events that they originally wanted. Be sure to add new events here!
+ */
+#define FAN_ALL_EVENTS (FAN_ACCESS |\
+ FAN_MODIFY |\
+ FAN_CLOSE |\
+ FAN_OPEN)
+
+/*
+ * All events which require a permission response from userspace
+ */
+#define FAN_ALL_PERM_EVENTS (FAN_OPEN_PERM |\
+ FAN_ACCESS_PERM)
+
+#define FAN_ALL_OUTGOING_EVENTS (FAN_ALL_EVENTS |\
+ FAN_ALL_PERM_EVENTS |\
+ FAN_Q_OVERFLOW)
+
+#define FANOTIFY_METADATA_VERSION 2
+
+struct fanotify_event_metadata {
+ __u32 event_len;
+ __u32 vers;
+ __u64 mask;
+ __s32 fd;
+ __s32 pid;
+} __attribute__ ((packed));
+
+struct fanotify_response {
+ __s32 fd;
+ __u32 response;
+} __attribute__ ((packed));
+
+/* Legit userspace responses to a _PERM event */
+#define FAN_ALLOW 0x01
+#define FAN_DENY 0x02
+
+/* Helper functions to deal with fanotify_event_metadata buffers */
+#define FAN_EVENT_METADATA_LEN (sizeof(struct fanotify_event_metadata))
+
+#define FAN_EVENT_NEXT(meta, len) ((len) -= (meta)->event_len, \
+ (struct fanotify_event_metadata*)(((char *)(meta)) + \
+ (meta)->event_len))
+
+#define FAN_EVENT_OK(meta, len) ((long)(len) >= (long)FAN_EVENT_METADATA_LEN && \
+ (long)(meta)->event_len >= (long)FAN_EVENT_METADATA_LEN && \
+ (long)(meta)->event_len <= (long)(len))
+
+#endif /* _LINUX_FANOTIFY_H */
diff --git a/src/shared/linux/seccomp-bpf.h b/src/shared/linux/seccomp-bpf.h
new file mode 100644
index 0000000000..1e3d136739
--- /dev/null
+++ b/src/shared/linux/seccomp-bpf.h
@@ -0,0 +1,76 @@
+/*
+ * seccomp example for x86 (32-bit and 64-bit) with BPF macros
+ *
+ * Copyright (c) 2012 The Chromium OS Authors <chromium-os-dev@chromium.org>
+ * Authors:
+ * Will Drewry <wad@chromium.org>
+ * Kees Cook <keescook@chromium.org>
+ *
+ * The code may be used by anyone for any purpose, and can serve as a
+ * starting point for developing applications using mode 2 seccomp.
+ */
+#ifndef _SECCOMP_BPF_H_
+#define _SECCOMP_BPF_H_
+
+#include <stdio.h>
+#include <stddef.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <signal.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <sys/prctl.h>
+
+#include <linux/unistd.h>
+#include <linux/audit.h>
+#include <linux/filter.h>
+#include <linux/seccomp.h>
+
+#ifndef SECCOMP_MODE_FILTER
+# define SECCOMP_MODE_FILTER 2 /* uses user-supplied filter. */
+# define SECCOMP_RET_KILL 0x00000000U /* kill the task immediately */
+# define SECCOMP_RET_TRAP 0x00030000U /* disallow and force a SIGSYS */
+# define SECCOMP_RET_ALLOW 0x7fff0000U /* allow */
+struct seccomp_data {
+ int nr;
+ __u32 arch;
+ __u64 instruction_pointer;
+ __u64 args[6];
+};
+#endif
+#ifndef SYS_SECCOMP
+# define SYS_SECCOMP 1
+#endif
+
+#define syscall_nr (offsetof(struct seccomp_data, nr))
+#define arch_nr (offsetof(struct seccomp_data, arch))
+
+#if defined(__i386__)
+# define REG_SYSCALL REG_EAX
+# define ARCH_NR AUDIT_ARCH_I386
+#elif defined(__x86_64__)
+# define REG_SYSCALL REG_RAX
+# define ARCH_NR AUDIT_ARCH_X86_64
+#else
+# warning "Platform does not support seccomp filter yet"
+# define REG_SYSCALL 0
+# define ARCH_NR 0
+#endif
+
+#define VALIDATE_ARCHITECTURE \
+ BPF_STMT(BPF_LD+BPF_W+BPF_ABS, arch_nr), \
+ BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, ARCH_NR, 1, 0), \
+ BPF_STMT(BPF_RET+BPF_K, SECCOMP_RET_KILL)
+
+#define EXAMINE_SYSCALL \
+ BPF_STMT(BPF_LD+BPF_W+BPF_ABS, syscall_nr)
+
+#define ALLOW_SYSCALL(name) \
+ BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, __NR_##name, 0, 1), \
+ BPF_STMT(BPF_RET+BPF_K, SECCOMP_RET_ALLOW)
+
+#define _KILL_PROCESS \
+ BPF_STMT(BPF_RET+BPF_K, SECCOMP_RET_KILL)
+
+#endif /* _SECCOMP_BPF_H_ */
diff --git a/src/shared/linux/seccomp.h b/src/shared/linux/seccomp.h
new file mode 100644
index 0000000000..9c03683fa0
--- /dev/null
+++ b/src/shared/linux/seccomp.h
@@ -0,0 +1,47 @@
+#ifndef _LINUX_SECCOMP_H
+#define _LINUX_SECCOMP_H
+
+
+#include <linux/types.h>
+
+
+/* Valid values for seccomp.mode and prctl(PR_SET_SECCOMP, <mode>) */
+#define SECCOMP_MODE_DISABLED 0 /* seccomp is not in use. */
+#define SECCOMP_MODE_STRICT 1 /* uses hard-coded filter. */
+#define SECCOMP_MODE_FILTER 2 /* uses user-supplied filter. */
+
+/*
+ * All BPF programs must return a 32-bit value.
+ * The bottom 16-bits are for optional return data.
+ * The upper 16-bits are ordered from least permissive values to most.
+ *
+ * The ordering ensures that a min_t() over composed return values always
+ * selects the least permissive choice.
+ */
+#define SECCOMP_RET_KILL 0x00000000U /* kill the task immediately */
+#define SECCOMP_RET_TRAP 0x00030000U /* disallow and force a SIGSYS */
+#define SECCOMP_RET_ERRNO 0x00050000U /* returns an errno */
+#define SECCOMP_RET_TRACE 0x7ff00000U /* pass to a tracer or disallow */
+#define SECCOMP_RET_ALLOW 0x7fff0000U /* allow */
+
+/* Masks for the return value sections. */
+#define SECCOMP_RET_ACTION 0x7fff0000U
+#define SECCOMP_RET_DATA 0x0000ffffU
+
+/**
+ * struct seccomp_data - the format the BPF program executes over.
+ * @nr: the system call number
+ * @arch: indicates system call convention as an AUDIT_ARCH_* value
+ * as defined in <linux/audit.h>.
+ * @instruction_pointer: at the time of the system call.
+ * @args: up to 6 system call arguments always stored as 64-bit values
+ * regardless of the architecture.
+ */
+struct seccomp_data {
+ int nr;
+ __u32 arch;
+ __u64 instruction_pointer;
+ __u64 args[6];
+};
+
+#endif /* _LINUX_SECCOMP_H */
diff --git a/src/shared/list.h b/src/shared/list.h
new file mode 100644
index 0000000000..47f275a019
--- /dev/null
+++ b/src/shared/list.h
@@ -0,0 +1,125 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+/* The head of the linked list. Use this in the structure that shall
+ * contain the head of the linked list */
+#define LIST_HEAD(t,name) \
+ t *name
+
+/* The pointers in the linked list's items. Use this in the item structure */
+#define LIST_FIELDS(t,name) \
+ t *name##_next, *name##_prev
+
+/* Initialize the list's head */
+#define LIST_HEAD_INIT(t,head) \
+ do { \
+ (head) = NULL; } \
+ while(false)
+
+/* Initialize a list item */
+#define LIST_INIT(t,name,item) \
+ do { \
+ t *_item = (item); \
+ assert(_item); \
+ _item->name##_prev = _item->name##_next = NULL; \
+ } while(false)
+
+/* Prepend an item to the list */
+#define LIST_PREPEND(t,name,head,item) \
+ do { \
+ t **_head = &(head), *_item = (item); \
+ assert(_item); \
+ if ((_item->name##_next = *_head)) \
+ _item->name##_next->name##_prev = _item; \
+ _item->name##_prev = NULL; \
+ *_head = _item; \
+ } while(false)
+
+/* Remove an item from the list */
+#define LIST_REMOVE(t,name,head,item) \
+ do { \
+ t **_head = &(head), *_item = (item); \
+ assert(_item); \
+ if (_item->name##_next) \
+ _item->name##_next->name##_prev = _item->name##_prev; \
+ if (_item->name##_prev) \
+ _item->name##_prev->name##_next = _item->name##_next; \
+ else { \
+ assert(*_head == _item); \
+ *_head = _item->name##_next; \
+ } \
+ _item->name##_next = _item->name##_prev = NULL; \
+ } while(false)
+
+/* Find the head of the list */
+#define LIST_FIND_HEAD(t,name,item,head) \
+ do { \
+ t *_item = (item); \
+ assert(_item); \
+ while (_item->name##_prev) \
+ _item = _item->name##_prev; \
+ (head) = _item; \
+ } while (false)
+
+/* Find the head of the list */
+#define LIST_FIND_TAIL(t,name,item,tail) \
+ do { \
+ t *_item = (item); \
+ assert(_item); \
+ while (_item->name##_next) \
+ _item = _item->name##_next; \
+ (tail) = _item; \
+ } while (false)
+
+/* Insert an item after another one (a = where, b = what) */
+#define LIST_INSERT_AFTER(t,name,head,a,b) \
+ do { \
+ t **_head = &(head), *_a = (a), *_b = (b); \
+ assert(_b); \
+ if (!_a) { \
+ if ((_b->name##_next = *_head)) \
+ _b->name##_next->name##_prev = _b; \
+ _b->name##_prev = NULL; \
+ *_head = _b; \
+ } else { \
+ if ((_b->name##_next = _a->name##_next)) \
+ _b->name##_next->name##_prev = _b; \
+ _b->name##_prev = _a; \
+ _a->name##_next = _b; \
+ } \
+ } while(false)
+
+#define LIST_JUST_US(name,item) \
+ (!(item)->name##_prev && !(item)->name##_next) \
+
+#define LIST_FOREACH(name,i,head) \
+ for ((i) = (head); (i); (i) = (i)->name##_next)
+
+#define LIST_FOREACH_SAFE(name,i,n,head) \
+ for ((i) = (head); (i) && (((n) = (i)->name##_next), 1); (i) = (n))
+
+#define LIST_FOREACH_BEFORE(name,i,p) \
+ for ((i) = (p)->name##_prev; (i); (i) = (i)->name##_prev)
+
+#define LIST_FOREACH_AFTER(name,i,p) \
+ for ((i) = (p)->name##_next; (i); (i) = (i)->name##_next)
diff --git a/src/shared/log.c b/src/shared/log.c
new file mode 100644
index 0000000000..27317f7ed3
--- /dev/null
+++ b/src/shared/log.c
@@ -0,0 +1,927 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdarg.h>
+#include <stdio.h>
+#include <errno.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <stddef.h>
+#include <printf.h>
+
+#include "log.h"
+#include "util.h"
+#include "missing.h"
+#include "macro.h"
+#include "socket-util.h"
+
+#define SNDBUF_SIZE (8*1024*1024)
+
+static LogTarget log_target = LOG_TARGET_CONSOLE;
+static int log_max_level = LOG_INFO;
+static int log_facility = LOG_DAEMON;
+
+static int console_fd = STDERR_FILENO;
+static int syslog_fd = -1;
+static int kmsg_fd = -1;
+static int journal_fd = -1;
+
+static bool syslog_is_stream = false;
+
+static bool show_color = false;
+static bool show_location = false;
+
+/* Akin to glibc's __abort_msg; which is private and we hence cannot
+ * use here. */
+static char *log_abort_msg = NULL;
+
+void log_close_console(void) {
+
+ if (console_fd < 0)
+ return;
+
+ if (getpid() == 1) {
+ if (console_fd >= 3)
+ close_nointr_nofail(console_fd);
+
+ console_fd = -1;
+ }
+}
+
+static int log_open_console(void) {
+
+ if (console_fd >= 0)
+ return 0;
+
+ if (getpid() == 1) {
+ console_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
+ if (console_fd < 0)
+ return console_fd;
+ } else
+ console_fd = STDERR_FILENO;
+
+ return 0;
+}
+
+void log_close_kmsg(void) {
+
+ if (kmsg_fd < 0)
+ return;
+
+ close_nointr_nofail(kmsg_fd);
+ kmsg_fd = -1;
+}
+
+static int log_open_kmsg(void) {
+
+ if (kmsg_fd >= 0)
+ return 0;
+
+ kmsg_fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
+ if (kmsg_fd < 0)
+ return -errno;
+
+ return 0;
+}
+
+void log_close_syslog(void) {
+
+ if (syslog_fd < 0)
+ return;
+
+ close_nointr_nofail(syslog_fd);
+ syslog_fd = -1;
+}
+
+static int create_log_socket(int type) {
+ int fd;
+
+ /* All output to the syslog/journal fds we do asynchronously,
+ * and if the buffers are full we just drop the messages */
+
+ fd = socket(AF_UNIX, type|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
+ if (fd < 0)
+ return -errno;
+
+ fd_inc_sndbuf(fd, SNDBUF_SIZE);
+
+ return fd;
+}
+
+static int log_open_syslog(void) {
+ int r;
+ union sockaddr_union sa = {
+ .un.sun_family = AF_UNIX,
+ .un.sun_path = "/dev/log",
+ };
+
+ if (syslog_fd >= 0)
+ return 0;
+
+ syslog_fd = create_log_socket(SOCK_DGRAM);
+ if (syslog_fd < 0) {
+ r = syslog_fd;
+ goto fail;
+ }
+
+ if (connect(syslog_fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + strlen(sa.un.sun_path)) < 0) {
+ close_nointr_nofail(syslog_fd);
+
+ /* Some legacy syslog systems still use stream
+ * sockets. They really shouldn't. But what can we
+ * do... */
+ syslog_fd = create_log_socket(SOCK_STREAM);
+ if (syslog_fd < 0) {
+ r = syslog_fd;
+ goto fail;
+ }
+
+ if (connect(syslog_fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + strlen(sa.un.sun_path)) < 0) {
+ r = -errno;
+ goto fail;
+ }
+
+ syslog_is_stream = true;
+ } else
+ syslog_is_stream = false;
+
+ return 0;
+
+fail:
+ log_close_syslog();
+ return r;
+}
+
+void log_close_journal(void) {
+
+ if (journal_fd < 0)
+ return;
+
+ close_nointr_nofail(journal_fd);
+ journal_fd = -1;
+}
+
+static int log_open_journal(void) {
+ union sockaddr_union sa = {
+ .un.sun_family = AF_UNIX,
+ .un.sun_path = "/run/systemd/journal/socket",
+ };
+ int r;
+
+ if (journal_fd >= 0)
+ return 0;
+
+ journal_fd = create_log_socket(SOCK_DGRAM);
+ if (journal_fd < 0) {
+ r = journal_fd;
+ goto fail;
+ }
+
+ if (connect(journal_fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + strlen(sa.un.sun_path)) < 0) {
+ r = -errno;
+ goto fail;
+ }
+
+ return 0;
+
+fail:
+ log_close_journal();
+ return r;
+}
+
+int log_open(void) {
+ int r;
+
+ /* If we don't use the console we close it here, to not get
+ * killed by SAK. If we don't use syslog we close it here so
+ * that we are not confused by somebody deleting the socket in
+ * the fs. If we don't use /dev/kmsg we still keep it open,
+ * because there is no reason to close it. */
+
+ if (log_target == LOG_TARGET_NULL) {
+ log_close_journal();
+ log_close_syslog();
+ log_close_console();
+ return 0;
+ }
+
+ if ((log_target != LOG_TARGET_AUTO && log_target != LOG_TARGET_SAFE) ||
+ getpid() == 1 ||
+ isatty(STDERR_FILENO) <= 0) {
+
+ if (log_target == LOG_TARGET_AUTO ||
+ log_target == LOG_TARGET_JOURNAL_OR_KMSG ||
+ log_target == LOG_TARGET_JOURNAL) {
+ r = log_open_journal();
+ if (r >= 0) {
+ log_close_syslog();
+ log_close_console();
+ return r;
+ }
+ }
+
+ if (log_target == LOG_TARGET_SYSLOG_OR_KMSG ||
+ log_target == LOG_TARGET_SYSLOG) {
+ r = log_open_syslog();
+ if (r >= 0) {
+ log_close_journal();
+ log_close_console();
+ return r;
+ }
+ }
+
+ if (log_target == LOG_TARGET_AUTO ||
+ log_target == LOG_TARGET_SAFE ||
+ log_target == LOG_TARGET_JOURNAL_OR_KMSG ||
+ log_target == LOG_TARGET_SYSLOG_OR_KMSG ||
+ log_target == LOG_TARGET_KMSG) {
+ r = log_open_kmsg();
+ if (r >= 0) {
+ log_close_journal();
+ log_close_syslog();
+ log_close_console();
+ return r;
+ }
+ }
+ }
+
+ log_close_journal();
+ log_close_syslog();
+
+ /* Get the real /dev/console if we are PID=1, hence reopen */
+ log_close_console();
+ return log_open_console();
+}
+
+void log_set_target(LogTarget target) {
+ assert(target >= 0);
+ assert(target < _LOG_TARGET_MAX);
+
+ log_target = target;
+}
+
+void log_close(void) {
+ log_close_journal();
+ log_close_syslog();
+ log_close_kmsg();
+ log_close_console();
+}
+
+void log_forget_fds(void) {
+ console_fd = kmsg_fd = syslog_fd = journal_fd = -1;
+}
+
+void log_set_max_level(int level) {
+ assert((level & LOG_PRIMASK) == level);
+
+ log_max_level = level;
+}
+
+void log_set_facility(int facility) {
+ log_facility = facility;
+}
+
+static int write_to_console(
+ int level,
+ const char*file,
+ int line,
+ const char *func,
+ const char *object_name,
+ const char *object,
+ const char *buffer) {
+
+ char location[64];
+ struct iovec iovec[5] = {};
+ unsigned n = 0;
+ bool highlight;
+
+ if (console_fd < 0)
+ return 0;
+
+ highlight = LOG_PRI(level) <= LOG_ERR && show_color;
+
+ if (show_location) {
+ snprintf(location, sizeof(location), "(%s:%u) ", file, line);
+ char_array_0(location);
+ IOVEC_SET_STRING(iovec[n++], location);
+ }
+
+ if (highlight)
+ IOVEC_SET_STRING(iovec[n++], ANSI_HIGHLIGHT_RED_ON);
+ IOVEC_SET_STRING(iovec[n++], buffer);
+ if (highlight)
+ IOVEC_SET_STRING(iovec[n++], ANSI_HIGHLIGHT_OFF);
+ IOVEC_SET_STRING(iovec[n++], "\n");
+
+ if (writev(console_fd, iovec, n) < 0)
+ return -errno;
+
+ return 1;
+}
+
+static int write_to_syslog(
+ int level,
+ const char*file,
+ int line,
+ const char *func,
+ const char *object_name,
+ const char *object,
+ const char *buffer) {
+
+ char header_priority[16], header_time[64], header_pid[16];
+ struct iovec iovec[5] = {};
+ struct msghdr msghdr = {
+ .msg_iov = iovec,
+ .msg_iovlen = ELEMENTSOF(iovec),
+ };
+ time_t t;
+ struct tm *tm;
+
+ if (syslog_fd < 0)
+ return 0;
+
+ snprintf(header_priority, sizeof(header_priority), "<%i>", level);
+ char_array_0(header_priority);
+
+ t = (time_t) (now(CLOCK_REALTIME) / USEC_PER_SEC);
+ tm = localtime(&t);
+ if (!tm)
+ return -EINVAL;
+
+ if (strftime(header_time, sizeof(header_time), "%h %e %T ", tm) <= 0)
+ return -EINVAL;
+
+ snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) getpid());
+ char_array_0(header_pid);
+
+ IOVEC_SET_STRING(iovec[0], header_priority);
+ IOVEC_SET_STRING(iovec[1], header_time);
+ IOVEC_SET_STRING(iovec[2], program_invocation_short_name);
+ IOVEC_SET_STRING(iovec[3], header_pid);
+ IOVEC_SET_STRING(iovec[4], buffer);
+
+ /* When using syslog via SOCK_STREAM separate the messages by NUL chars */
+ if (syslog_is_stream)
+ iovec[4].iov_len++;
+
+ for (;;) {
+ ssize_t n;
+
+ n = sendmsg(syslog_fd, &msghdr, MSG_NOSIGNAL);
+ if (n < 0)
+ return -errno;
+
+ if (!syslog_is_stream ||
+ (size_t) n >= IOVEC_TOTAL_SIZE(iovec, ELEMENTSOF(iovec)))
+ break;
+
+ IOVEC_INCREMENT(iovec, ELEMENTSOF(iovec), n);
+ }
+
+ return 1;
+}
+
+static int write_to_kmsg(
+ int level,
+ const char*file,
+ int line,
+ const char *func,
+ const char *object_name,
+ const char *object,
+ const char *buffer) {
+
+ char header_priority[16], header_pid[16];
+ struct iovec iovec[5] = {};
+
+ if (kmsg_fd < 0)
+ return 0;
+
+ snprintf(header_priority, sizeof(header_priority), "<%i>", level);
+ char_array_0(header_priority);
+
+ snprintf(header_pid, sizeof(header_pid), "[%lu]: ", (unsigned long) getpid());
+ char_array_0(header_pid);
+
+ IOVEC_SET_STRING(iovec[0], header_priority);
+ IOVEC_SET_STRING(iovec[1], program_invocation_short_name);
+ IOVEC_SET_STRING(iovec[2], header_pid);
+ IOVEC_SET_STRING(iovec[3], buffer);
+ IOVEC_SET_STRING(iovec[4], "\n");
+
+ if (writev(kmsg_fd, iovec, ELEMENTSOF(iovec)) < 0)
+ return -errno;
+
+ return 1;
+}
+
+static int log_do_header(char *header, size_t size,
+ int level,
+ const char *file, int line, const char *func,
+ const char *object_name, const char *object) {
+ snprintf(header, size,
+ "PRIORITY=%i\n"
+ "SYSLOG_FACILITY=%i\n"
+ "%s%.*s%s"
+ "%s%.*i%s"
+ "%s%.*s%s"
+ "%s%.*s%s"
+ "SYSLOG_IDENTIFIER=%s\n",
+ LOG_PRI(level),
+ LOG_FAC(level),
+ file ? "CODE_FILE=" : "",
+ file ? LINE_MAX : 0, file, /* %.0s means no output */
+ file ? "\n" : "",
+ line ? "CODE_LINE=" : "",
+ line ? 1 : 0, line, /* %.0d means no output too, special case for 0 */
+ line ? "\n" : "",
+ func ? "CODE_FUNCTION=" : "",
+ func ? LINE_MAX : 0, func,
+ func ? "\n" : "",
+ object ? object_name : "",
+ object ? LINE_MAX : 0, object, /* %.0s means no output */
+ object ? "\n" : "",
+ program_invocation_short_name);
+ header[size - 1] = '\0';
+ return 0;
+}
+
+static int write_to_journal(
+ int level,
+ const char*file,
+ int line,
+ const char *func,
+ const char *object_name,
+ const char *object,
+ const char *buffer) {
+
+ char header[LINE_MAX];
+ struct iovec iovec[4] = {};
+ struct msghdr mh = {};
+
+ if (journal_fd < 0)
+ return 0;
+
+ log_do_header(header, sizeof(header), level,
+ file, line, func, object_name, object);
+
+ IOVEC_SET_STRING(iovec[0], header);
+ IOVEC_SET_STRING(iovec[1], "MESSAGE=");
+ IOVEC_SET_STRING(iovec[2], buffer);
+ IOVEC_SET_STRING(iovec[3], "\n");
+
+ mh.msg_iov = iovec;
+ mh.msg_iovlen = ELEMENTSOF(iovec);
+
+ if (sendmsg(journal_fd, &mh, MSG_NOSIGNAL) < 0)
+ return -errno;
+
+ return 1;
+}
+
+static int log_dispatch(
+ int level,
+ const char*file,
+ int line,
+ const char *func,
+ const char *object_name,
+ const char *object,
+ char *buffer) {
+
+ int r = 0;
+
+ if (log_target == LOG_TARGET_NULL)
+ return 0;
+
+ /* Patch in LOG_DAEMON facility if necessary */
+ if ((level & LOG_FACMASK) == 0)
+ level = log_facility | LOG_PRI(level);
+
+ do {
+ char *e;
+ int k = 0;
+
+ buffer += strspn(buffer, NEWLINE);
+
+ if (buffer[0] == 0)
+ break;
+
+ if ((e = strpbrk(buffer, NEWLINE)))
+ *(e++) = 0;
+
+ if (log_target == LOG_TARGET_AUTO ||
+ log_target == LOG_TARGET_JOURNAL_OR_KMSG ||
+ log_target == LOG_TARGET_JOURNAL) {
+
+ k = write_to_journal(level, file, line, func,
+ object_name, object, buffer);
+ if (k < 0) {
+ if (k != -EAGAIN)
+ log_close_journal();
+ log_open_kmsg();
+ } else if (k > 0)
+ r++;
+ }
+
+ if (log_target == LOG_TARGET_SYSLOG_OR_KMSG ||
+ log_target == LOG_TARGET_SYSLOG) {
+
+ k = write_to_syslog(level, file, line, func,
+ object_name, object, buffer);
+ if (k < 0) {
+ if (k != -EAGAIN)
+ log_close_syslog();
+ log_open_kmsg();
+ } else if (k > 0)
+ r++;
+ }
+
+ if (k <= 0 &&
+ (log_target == LOG_TARGET_AUTO ||
+ log_target == LOG_TARGET_SAFE ||
+ log_target == LOG_TARGET_SYSLOG_OR_KMSG ||
+ log_target == LOG_TARGET_JOURNAL_OR_KMSG ||
+ log_target == LOG_TARGET_KMSG)) {
+
+ k = write_to_kmsg(level, file, line, func,
+ object_name, object, buffer);
+ if (k < 0) {
+ log_close_kmsg();
+ log_open_console();
+ } else if (k > 0)
+ r++;
+ }
+
+ if (k <= 0) {
+ k = write_to_console(level, file, line, func,
+ object_name, object, buffer);
+ if (k < 0)
+ return k;
+ }
+
+ buffer = e;
+ } while (buffer);
+
+ return r;
+}
+
+int log_dump_internal(
+ int level,
+ const char*file,
+ int line,
+ const char *func,
+ char *buffer) {
+
+ PROTECT_ERRNO;
+
+ /* This modifies the buffer... */
+
+ if (_likely_(LOG_PRI(level) > log_max_level))
+ return 0;
+
+ return log_dispatch(level, file, line, func, NULL, NULL, buffer);
+}
+
+int log_metav(
+ int level,
+ const char*file,
+ int line,
+ const char *func,
+ const char *format,
+ va_list ap) {
+
+ PROTECT_ERRNO;
+ char buffer[LINE_MAX];
+
+ if (_likely_(LOG_PRI(level) > log_max_level))
+ return 0;
+
+ vsnprintf(buffer, sizeof(buffer), format, ap);
+ char_array_0(buffer);
+
+ return log_dispatch(level, file, line, func, NULL, NULL, buffer);
+}
+
+int log_meta(
+ int level,
+ const char*file,
+ int line,
+ const char *func,
+ const char *format, ...) {
+
+ int r;
+ va_list ap;
+
+ va_start(ap, format);
+ r = log_metav(level, file, line, func, format, ap);
+ va_end(ap);
+
+ return r;
+}
+
+int log_metav_object(
+ int level,
+ const char*file,
+ int line,
+ const char *func,
+ const char *object_name,
+ const char *object,
+ const char *format,
+ va_list ap) {
+
+ PROTECT_ERRNO;
+ char buffer[LINE_MAX];
+
+ if (_likely_(LOG_PRI(level) > log_max_level))
+ return 0;
+
+ vsnprintf(buffer, sizeof(buffer), format, ap);
+ char_array_0(buffer);
+
+ return log_dispatch(level, file, line, func,
+ object_name, object, buffer);
+}
+
+int log_meta_object(
+ int level,
+ const char*file,
+ int line,
+ const char *func,
+ const char *object_name,
+ const char *object,
+ const char *format, ...) {
+
+ int r;
+ va_list ap;
+
+ va_start(ap, format);
+ r = log_metav_object(level, file, line, func,
+ object_name, object, format, ap);
+ va_end(ap);
+
+ return r;
+}
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wformat-nonliteral"
+_noreturn_ static void log_assert(const char *text, const char *file, int line, const char *func, const char *format) {
+ static char buffer[LINE_MAX];
+
+ snprintf(buffer, sizeof(buffer), format, text, file, line, func);
+
+ char_array_0(buffer);
+ log_abort_msg = buffer;
+
+ log_dispatch(LOG_CRIT, file, line, func, NULL, NULL, buffer);
+ abort();
+}
+#pragma GCC diagnostic pop
+
+_noreturn_ void log_assert_failed(const char *text, const char *file, int line, const char *func) {
+ log_assert(text, file, line, func, "Assertion '%s' failed at %s:%u, function %s(). Aborting.");
+}
+
+_noreturn_ void log_assert_failed_unreachable(const char *text, const char *file, int line, const char *func) {
+ log_assert(text, file, line, func, "Code should not be reached '%s' at %s:%u, function %s(). Aborting.");
+}
+
+int log_oom_internal(const char *file, int line, const char *func) {
+ log_meta(LOG_ERR, file, line, func, "Out of memory.");
+ return -ENOMEM;
+}
+
+int log_struct_internal(
+ int level,
+ const char *file,
+ int line,
+ const char *func,
+ const char *format, ...) {
+
+ PROTECT_ERRNO;
+ va_list ap;
+ int r;
+
+ if (_likely_(LOG_PRI(level) > log_max_level))
+ return 0;
+
+ if (log_target == LOG_TARGET_NULL)
+ return 0;
+
+ if ((level & LOG_FACMASK) == 0)
+ level = log_facility | LOG_PRI(level);
+
+ if ((log_target == LOG_TARGET_AUTO ||
+ log_target == LOG_TARGET_JOURNAL_OR_KMSG ||
+ log_target == LOG_TARGET_JOURNAL) &&
+ journal_fd >= 0) {
+
+ char header[LINE_MAX];
+ struct iovec iovec[17] = {};
+ unsigned n = 0, i;
+ struct msghdr mh = {
+ .msg_iov = iovec,
+ };
+ static const char nl = '\n';
+
+ /* If the journal is available do structured logging */
+ log_do_header(header, sizeof(header), level,
+ file, line, func, NULL, NULL);
+ IOVEC_SET_STRING(iovec[n++], header);
+
+ va_start(ap, format);
+ while (format && n + 1 < ELEMENTSOF(iovec)) {
+ char *buf;
+ va_list aq;
+
+ /* We need to copy the va_list structure,
+ * since vasprintf() leaves it afterwards at
+ * an undefined location */
+
+ va_copy(aq, ap);
+ if (vasprintf(&buf, format, aq) < 0) {
+ va_end(aq);
+ r = -ENOMEM;
+ goto finish;
+ }
+ va_end(aq);
+
+ /* Now, jump enough ahead, so that we point to
+ * the next format string */
+ VA_FORMAT_ADVANCE(format, ap);
+
+ IOVEC_SET_STRING(iovec[n++], buf);
+
+ iovec[n].iov_base = (char*) &nl;
+ iovec[n].iov_len = 1;
+ n++;
+
+ format = va_arg(ap, char *);
+ }
+
+ mh.msg_iovlen = n;
+
+ if (sendmsg(journal_fd, &mh, MSG_NOSIGNAL) < 0)
+ r = -errno;
+ else
+ r = 1;
+
+ finish:
+ va_end(ap);
+ for (i = 1; i < n; i += 2)
+ free(iovec[i].iov_base);
+
+ } else {
+ char buf[LINE_MAX];
+ bool found = false;
+
+ /* Fallback if journal logging is not available */
+
+ va_start(ap, format);
+ while (format) {
+ va_list aq;
+
+ va_copy(aq, ap);
+ vsnprintf(buf, sizeof(buf), format, aq);
+ va_end(aq);
+ char_array_0(buf);
+
+ if (startswith(buf, "MESSAGE=")) {
+ found = true;
+ break;
+ }
+
+ VA_FORMAT_ADVANCE(format, ap);
+
+ format = va_arg(ap, char *);
+ }
+ va_end(ap);
+
+ if (found)
+ r = log_dispatch(level, file, line, func,
+ NULL, NULL, buf + 8);
+ else
+ r = -EINVAL;
+ }
+
+ return r;
+}
+
+int log_set_target_from_string(const char *e) {
+ LogTarget t;
+
+ t = log_target_from_string(e);
+ if (t < 0)
+ return -EINVAL;
+
+ log_set_target(t);
+ return 0;
+}
+
+int log_set_max_level_from_string(const char *e) {
+ int t;
+
+ t = log_level_from_string(e);
+ if (t < 0)
+ return t;
+
+ log_set_max_level(t);
+ return 0;
+}
+
+void log_parse_environment(void) {
+ const char *e;
+
+ e = secure_getenv("SYSTEMD_LOG_TARGET");
+ if (e && log_set_target_from_string(e) < 0)
+ log_warning("Failed to parse log target %s. Ignoring.", e);
+
+ e = secure_getenv("SYSTEMD_LOG_LEVEL");
+ if (e && log_set_max_level_from_string(e) < 0)
+ log_warning("Failed to parse log level %s. Ignoring.", e);
+
+ e = secure_getenv("SYSTEMD_LOG_COLOR");
+ if (e && log_show_color_from_string(e) < 0)
+ log_warning("Failed to parse bool %s. Ignoring.", e);
+
+ e = secure_getenv("SYSTEMD_LOG_LOCATION");
+ if (e && log_show_location_from_string(e) < 0)
+ log_warning("Failed to parse bool %s. Ignoring.", e);
+}
+
+LogTarget log_get_target(void) {
+ return log_target;
+}
+
+int log_get_max_level(void) {
+ return log_max_level;
+}
+
+void log_show_color(bool b) {
+ show_color = b;
+}
+
+void log_show_location(bool b) {
+ show_location = b;
+}
+
+int log_show_color_from_string(const char *e) {
+ int t;
+
+ t = parse_boolean(e);
+ if (t < 0)
+ return t;
+
+ log_show_color(t);
+ return 0;
+}
+
+int log_show_location_from_string(const char *e) {
+ int t;
+
+ t = parse_boolean(e);
+ if (t < 0)
+ return t;
+
+ log_show_location(t);
+ return 0;
+}
+
+bool log_on_console(void) {
+ if (log_target == LOG_TARGET_CONSOLE)
+ return true;
+
+ return syslog_fd < 0 && kmsg_fd < 0 && journal_fd < 0;
+}
+
+static const char *const log_target_table[] = {
+ [LOG_TARGET_CONSOLE] = "console",
+ [LOG_TARGET_KMSG] = "kmsg",
+ [LOG_TARGET_JOURNAL] = "journal",
+ [LOG_TARGET_JOURNAL_OR_KMSG] = "journal-or-kmsg",
+ [LOG_TARGET_SYSLOG] = "syslog",
+ [LOG_TARGET_SYSLOG_OR_KMSG] = "syslog-or-kmsg",
+ [LOG_TARGET_AUTO] = "auto",
+ [LOG_TARGET_SAFE] = "safe",
+ [LOG_TARGET_NULL] = "null"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(log_target, LogTarget);
diff --git a/src/shared/log.h b/src/shared/log.h
new file mode 100644
index 0000000000..979f833d57
--- /dev/null
+++ b/src/shared/log.h
@@ -0,0 +1,159 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <syslog.h>
+#include <stdbool.h>
+#include <stdarg.h>
+#include <errno.h>
+
+#include "macro.h"
+#include "sd-id128.h"
+
+typedef enum LogTarget{
+ LOG_TARGET_CONSOLE,
+ LOG_TARGET_KMSG,
+ LOG_TARGET_JOURNAL,
+ LOG_TARGET_JOURNAL_OR_KMSG,
+ LOG_TARGET_SYSLOG,
+ LOG_TARGET_SYSLOG_OR_KMSG,
+ LOG_TARGET_AUTO, /* console if stderr is tty, JOURNAL_OR_KMSG otherwise */
+ LOG_TARGET_SAFE, /* console if stderr is tty, KMSG otherwise */
+ LOG_TARGET_NULL,
+ _LOG_TARGET_MAX,
+ _LOG_TARGET_INVALID = -1
+} LogTarget;
+
+void log_set_target(LogTarget target);
+void log_set_max_level(int level);
+void log_set_facility(int facility);
+
+int log_set_target_from_string(const char *e);
+int log_set_max_level_from_string(const char *e);
+
+void log_show_color(bool b);
+void log_show_location(bool b);
+
+int log_show_color_from_string(const char *e);
+int log_show_location_from_string(const char *e);
+
+LogTarget log_get_target(void) _pure_;
+int log_get_max_level(void) _pure_;
+
+int log_open(void);
+void log_close(void);
+void log_forget_fds(void);
+
+void log_close_syslog(void);
+void log_close_journal(void);
+void log_close_kmsg(void);
+void log_close_console(void);
+
+void log_parse_environment(void);
+
+int log_meta(
+ int level,
+ const char*file,
+ int line,
+ const char *func,
+ const char *format, ...) _printf_attr_(5,6);
+
+int log_metav(
+ int level,
+ const char*file,
+ int line,
+ const char *func,
+ const char *format,
+ va_list ap) _printf_attr_(5,0);
+
+int log_meta_object(
+ int level,
+ const char*file,
+ int line,
+ const char *func,
+ const char *object_name,
+ const char *object,
+ const char *format, ...) _printf_attr_(7,8);
+
+int log_metav_object(
+ int level,
+ const char*file,
+ int line,
+ const char *func,
+ const char *object_name,
+ const char *object,
+ const char *format,
+ va_list ap) _printf_attr_(7,0);
+
+int log_struct_internal(
+ int level,
+ const char *file,
+ int line,
+ const char *func,
+ const char *format, ...) _printf_attr_(5,0) _sentinel_;
+
+int log_oom_internal(
+ const char *file,
+ int line,
+ const char *func);
+
+/* This modifies the buffer passed! */
+int log_dump_internal(
+ int level,
+ const char*file,
+ int line,
+ const char *func,
+ char *buffer);
+
+_noreturn_ void log_assert_failed(
+ const char *text,
+ const char *file,
+ int line,
+ const char *func);
+
+_noreturn_ void log_assert_failed_unreachable(
+ const char *text,
+ const char *file,
+ int line,
+ const char *func);
+
+#define log_full(level, ...) log_meta(level, __FILE__, __LINE__, __func__, __VA_ARGS__)
+
+#define log_debug(...) log_meta(LOG_DEBUG, __FILE__, __LINE__, __func__, __VA_ARGS__)
+#define log_info(...) log_meta(LOG_INFO, __FILE__, __LINE__, __func__, __VA_ARGS__)
+#define log_notice(...) log_meta(LOG_NOTICE, __FILE__, __LINE__, __func__, __VA_ARGS__)
+#define log_warning(...) log_meta(LOG_WARNING, __FILE__, __LINE__, __func__, __VA_ARGS__)
+#define log_error(...) log_meta(LOG_ERR, __FILE__, __LINE__, __func__, __VA_ARGS__)
+
+#define log_struct(level, ...) log_struct_internal(level, __FILE__, __LINE__, __func__, __VA_ARGS__)
+
+#define log_oom() log_oom_internal(__FILE__, __LINE__, __func__)
+
+/* This modifies the buffer passed! */
+#define log_dump(level, buffer) log_dump_internal(level, __FILE__, __LINE__, __func__, buffer)
+
+bool log_on_console(void) _pure_;
+
+const char *log_target_to_string(LogTarget target) _const_;
+LogTarget log_target_from_string(const char *s) _pure_;
+
+#define MESSAGE_ID(x) "MESSAGE_ID=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(x)
diff --git a/src/shared/logs-show.c b/src/shared/logs-show.c
new file mode 100644
index 0000000000..116dc8a36c
--- /dev/null
+++ b/src/shared/logs-show.c
@@ -0,0 +1,985 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <time.h>
+#include <assert.h>
+#include <errno.h>
+#include <sys/poll.h>
+#include <string.h>
+
+#include "logs-show.h"
+#include "log.h"
+#include "util.h"
+#include "utf8.h"
+#include "hashmap.h"
+#include "journal-internal.h"
+
+#define PRINT_THRESHOLD 128
+#define JSON_THRESHOLD 4096
+
+static int print_catalog(FILE *f, sd_journal *j) {
+ int r;
+ _cleanup_free_ char *t = NULL, *z = NULL;
+
+
+ r = sd_journal_get_catalog(j, &t);
+ if (r < 0)
+ return r;
+
+ z = strreplace(strstrip(t), "\n", "\n-- ");
+ if (!z)
+ return log_oom();
+
+ fputs("-- ", f);
+ fputs(z, f);
+ fputc('\n', f);
+
+ return 0;
+}
+
+static int parse_field(const void *data, size_t length, const char *field, char **target, size_t *target_size) {
+ size_t fl, nl;
+ void *buf;
+
+ assert(data);
+ assert(field);
+ assert(target);
+ assert(target_size);
+
+ fl = strlen(field);
+ if (length < fl)
+ return 0;
+
+ if (memcmp(data, field, fl))
+ return 0;
+
+ nl = length - fl;
+ buf = malloc(nl+1);
+ if (!buf)
+ return log_oom();
+
+ memcpy(buf, (const char*) data + fl, nl);
+ ((char*)buf)[nl] = 0;
+
+ free(*target);
+ *target = buf;
+ *target_size = nl;
+
+ return 1;
+}
+
+static bool shall_print(const char *p, size_t l, OutputFlags flags) {
+ assert(p);
+
+ if (flags & OUTPUT_SHOW_ALL)
+ return true;
+
+ if (l >= PRINT_THRESHOLD)
+ return false;
+
+ if (!utf8_is_printable_n(p, l))
+ return false;
+
+ return true;
+}
+
+static int output_short(
+ FILE *f,
+ sd_journal *j,
+ OutputMode mode,
+ unsigned n_columns,
+ OutputFlags flags) {
+
+ int r;
+ const void *data;
+ size_t length;
+ size_t n = 0;
+ _cleanup_free_ char *hostname = NULL, *identifier = NULL, *comm = NULL, *pid = NULL, *fake_pid = NULL, *message = NULL, *realtime = NULL, *monotonic = NULL, *priority = NULL;
+ size_t hostname_len = 0, identifier_len = 0, comm_len = 0, pid_len = 0, fake_pid_len = 0, message_len = 0, realtime_len = 0, monotonic_len = 0, priority_len = 0;
+ int p = LOG_INFO;
+ const char *color_on = "", *color_off = "";
+
+ assert(f);
+ assert(j);
+
+ sd_journal_set_data_threshold(j, flags & OUTPUT_SHOW_ALL ? 0 : PRINT_THRESHOLD);
+
+ SD_JOURNAL_FOREACH_DATA(j, data, length) {
+
+ r = parse_field(data, length, "PRIORITY=", &priority, &priority_len);
+ if (r < 0)
+ return r;
+ else if (r > 0)
+ continue;
+
+ r = parse_field(data, length, "_HOSTNAME=", &hostname, &hostname_len);
+ if (r < 0)
+ return r;
+ else if (r > 0)
+ continue;
+
+ r = parse_field(data, length, "SYSLOG_IDENTIFIER=", &identifier, &identifier_len);
+ if (r < 0)
+ return r;
+ else if (r > 0)
+ continue;
+
+ r = parse_field(data, length, "_COMM=", &comm, &comm_len);
+ if (r < 0)
+ return r;
+ else if (r > 0)
+ continue;
+
+ r = parse_field(data, length, "_PID=", &pid, &pid_len);
+ if (r < 0)
+ return r;
+ else if (r > 0)
+ continue;
+
+ r = parse_field(data, length, "SYSLOG_PID=", &fake_pid, &fake_pid_len);
+ if (r < 0)
+ return r;
+ else if (r > 0)
+ continue;
+
+ r = parse_field(data, length, "_SOURCE_REALTIME_TIMESTAMP=", &realtime, &realtime_len);
+ if (r < 0)
+ return r;
+ else if (r > 0)
+ continue;
+
+ r = parse_field(data, length, "_SOURCE_MONOTONIC_TIMESTAMP=", &monotonic, &monotonic_len);
+ if (r < 0)
+ return r;
+ else if (r > 0)
+ continue;
+
+ r = parse_field(data, length, "MESSAGE=", &message, &message_len);
+ if (r < 0)
+ return r;
+ }
+
+ if (!message)
+ return 0;
+
+ if (!(flags & OUTPUT_SHOW_ALL))
+ strip_tab_ansi(&message, &message_len);
+
+ if (priority_len == 1 && *priority >= '0' && *priority <= '7')
+ p = *priority - '0';
+
+ if (mode == OUTPUT_SHORT_MONOTONIC) {
+ uint64_t t;
+ sd_id128_t boot_id;
+
+ r = -ENOENT;
+
+ if (monotonic)
+ r = safe_atou64(monotonic, &t);
+
+ if (r < 0)
+ r = sd_journal_get_monotonic_usec(j, &t, &boot_id);
+
+ if (r < 0) {
+ log_error("Failed to get monotonic: %s", strerror(-r));
+ return r;
+ }
+
+ fprintf(f, "[%5llu.%06llu]",
+ (unsigned long long) (t / USEC_PER_SEC),
+ (unsigned long long) (t % USEC_PER_SEC));
+
+ n += 1 + 5 + 1 + 6 + 1;
+
+ } else {
+ char buf[64];
+ uint64_t x;
+ time_t t;
+ struct tm tm;
+
+ r = -ENOENT;
+
+ if (realtime)
+ r = safe_atou64(realtime, &x);
+
+ if (r < 0)
+ r = sd_journal_get_realtime_usec(j, &x);
+
+ if (r < 0) {
+ log_error("Failed to get realtime: %s", strerror(-r));
+ return r;
+ }
+
+ t = (time_t) (x / USEC_PER_SEC);
+ if (strftime(buf, sizeof(buf), "%b %d %H:%M:%S", localtime_r(&t, &tm)) <= 0) {
+ log_error("Failed to format time.");
+ return r;
+ }
+
+ fputs(buf, f);
+ n += strlen(buf);
+ }
+
+ if (hostname && shall_print(hostname, hostname_len, flags)) {
+ fprintf(f, " %.*s", (int) hostname_len, hostname);
+ n += hostname_len + 1;
+ }
+
+ if (identifier && shall_print(identifier, identifier_len, flags)) {
+ fprintf(f, " %.*s", (int) identifier_len, identifier);
+ n += identifier_len + 1;
+ } else if (comm && shall_print(comm, comm_len, flags)) {
+ fprintf(f, " %.*s", (int) comm_len, comm);
+ n += comm_len + 1;
+ } else
+ fputc(' ', f);
+
+ if (pid && shall_print(pid, pid_len, flags)) {
+ fprintf(f, "[%.*s]", (int) pid_len, pid);
+ n += pid_len + 2;
+ } else if (fake_pid && shall_print(fake_pid, fake_pid_len, flags)) {
+ fprintf(f, "[%.*s]", (int) fake_pid_len, fake_pid);
+ n += fake_pid_len + 2;
+ }
+
+ if (flags & OUTPUT_COLOR) {
+ if (p <= LOG_ERR) {
+ color_on = ANSI_HIGHLIGHT_RED_ON;
+ color_off = ANSI_HIGHLIGHT_OFF;
+ } else if (p <= LOG_NOTICE) {
+ color_on = ANSI_HIGHLIGHT_ON;
+ color_off = ANSI_HIGHLIGHT_OFF;
+ }
+ }
+
+ if (flags & OUTPUT_SHOW_ALL)
+ fprintf(f, ": %s%.*s%s\n", color_on, (int) message_len, message, color_off);
+ else if (!utf8_is_printable_n(message, message_len)) {
+ char bytes[FORMAT_BYTES_MAX];
+ fprintf(f, ": [%s blob data]\n", format_bytes(bytes, sizeof(bytes), message_len));
+ } else if ((flags & OUTPUT_FULL_WIDTH) || (message_len + n + 1 < n_columns))
+ fprintf(f, ": %s%.*s%s\n", color_on, (int) message_len, message, color_off);
+ else if (n < n_columns && n_columns - n - 2 >= 3) {
+ _cleanup_free_ char *e;
+
+ e = ellipsize_mem(message, message_len, n_columns - n - 2, 90);
+
+ if (!e)
+ fprintf(f, ": %s%.*s%s\n", color_on, (int) message_len, message, color_off);
+ else
+ fprintf(f, ": %s%s%s\n", color_on, e, color_off);
+ } else
+ fputs("\n", f);
+
+ if (flags & OUTPUT_CATALOG)
+ print_catalog(f, j);
+
+ return 0;
+}
+
+static int output_verbose(
+ FILE *f,
+ sd_journal *j,
+ OutputMode mode,
+ unsigned n_columns,
+ OutputFlags flags) {
+
+ const void *data;
+ size_t length;
+ _cleanup_free_ char *cursor = NULL;
+ uint64_t realtime;
+ char ts[FORMAT_TIMESTAMP_MAX];
+ int r;
+
+ assert(f);
+ assert(j);
+
+ sd_journal_set_data_threshold(j, 0);
+
+ r = sd_journal_get_realtime_usec(j, &realtime);
+ if (r < 0) {
+ log_error("Failed to get realtime timestamp: %s", strerror(-r));
+ return r;
+ }
+
+ r = sd_journal_get_cursor(j, &cursor);
+ if (r < 0) {
+ log_error("Failed to get cursor: %s", strerror(-r));
+ return r;
+ }
+
+ fprintf(f, "%s [%s]\n",
+ format_timestamp(ts, sizeof(ts), realtime),
+ cursor);
+
+ SD_JOURNAL_FOREACH_DATA(j, data, length) {
+ if (!shall_print(data, length, flags)) {
+ const char *c;
+ char bytes[FORMAT_BYTES_MAX];
+
+ c = memchr(data, '=', length);
+ if (!c) {
+ log_error("Invalid field.");
+ return -EINVAL;
+ }
+
+ fprintf(f, "\t%.*s=[%s blob data]\n",
+ (int) (c - (const char*) data),
+ (const char*) data,
+ format_bytes(bytes, sizeof(bytes), length - (c - (const char *) data) - 1));
+ } else
+ fprintf(f, "\t%.*s\n", (int) length, (const char*) data);
+ }
+
+ if (flags & OUTPUT_CATALOG)
+ print_catalog(f, j);
+
+ return 0;
+}
+
+static int output_export(
+ FILE *f,
+ sd_journal *j,
+ OutputMode mode,
+ unsigned n_columns,
+ OutputFlags flags) {
+
+ sd_id128_t boot_id;
+ char sid[33];
+ int r;
+ usec_t realtime, monotonic;
+ _cleanup_free_ char *cursor = NULL;
+ const void *data;
+ size_t length;
+
+ assert(j);
+
+ sd_journal_set_data_threshold(j, 0);
+
+ r = sd_journal_get_realtime_usec(j, &realtime);
+ if (r < 0) {
+ log_error("Failed to get realtime timestamp: %s", strerror(-r));
+ return r;
+ }
+
+ r = sd_journal_get_monotonic_usec(j, &monotonic, &boot_id);
+ if (r < 0) {
+ log_error("Failed to get monotonic timestamp: %s", strerror(-r));
+ return r;
+ }
+
+ r = sd_journal_get_cursor(j, &cursor);
+ if (r < 0) {
+ log_error("Failed to get cursor: %s", strerror(-r));
+ return r;
+ }
+
+ fprintf(f,
+ "__CURSOR=%s\n"
+ "__REALTIME_TIMESTAMP=%llu\n"
+ "__MONOTONIC_TIMESTAMP=%llu\n"
+ "_BOOT_ID=%s\n",
+ cursor,
+ (unsigned long long) realtime,
+ (unsigned long long) monotonic,
+ sd_id128_to_string(boot_id, sid));
+
+ SD_JOURNAL_FOREACH_DATA(j, data, length) {
+
+ /* We already printed the boot id, from the data in
+ * the header, hence let's suppress it here */
+ if (length >= 9 &&
+ memcmp(data, "_BOOT_ID=", 9) == 0)
+ continue;
+
+ if (!utf8_is_printable_n(data, length)) {
+ const char *c;
+ uint64_t le64;
+
+ c = memchr(data, '=', length);
+ if (!c) {
+ log_error("Invalid field.");
+ return -EINVAL;
+ }
+
+ fwrite(data, c - (const char*) data, 1, f);
+ fputc('\n', f);
+ le64 = htole64(length - (c - (const char*) data) - 1);
+ fwrite(&le64, sizeof(le64), 1, f);
+ fwrite(c + 1, length - (c - (const char*) data) - 1, 1, f);
+ } else
+ fwrite(data, length, 1, f);
+
+ fputc('\n', f);
+ }
+
+ fputc('\n', f);
+
+ return 0;
+}
+
+void json_escape(
+ FILE *f,
+ const char* p,
+ size_t l,
+ OutputFlags flags) {
+
+ assert(f);
+ assert(p);
+
+ if (!(flags & OUTPUT_SHOW_ALL) && l >= JSON_THRESHOLD)
+
+ fputs("null", f);
+
+ else if (!utf8_is_printable_n(p, l)) {
+ bool not_first = false;
+
+ fputs("[ ", f);
+
+ while (l > 0) {
+ if (not_first)
+ fprintf(f, ", %u", (uint8_t) *p);
+ else {
+ not_first = true;
+ fprintf(f, "%u", (uint8_t) *p);
+ }
+
+ p++;
+ l--;
+ }
+
+ fputs(" ]", f);
+ } else {
+ fputc('\"', f);
+
+ while (l > 0) {
+ if (*p == '"' || *p == '\\') {
+ fputc('\\', f);
+ fputc(*p, f);
+ } else if (*p < ' ')
+ fprintf(f, "\\u%04x", *p);
+ else
+ fputc(*p, f);
+
+ p++;
+ l--;
+ }
+
+ fputc('\"', f);
+ }
+}
+
+static int output_json(
+ FILE *f,
+ sd_journal *j,
+ OutputMode mode,
+ unsigned n_columns,
+ OutputFlags flags) {
+
+ uint64_t realtime, monotonic;
+ _cleanup_free_ char *cursor = NULL;
+ const void *data;
+ size_t length;
+ sd_id128_t boot_id;
+ char sid[33], *k;
+ int r;
+ Hashmap *h = NULL;
+ bool done, separator;
+
+ assert(j);
+
+ sd_journal_set_data_threshold(j, flags & OUTPUT_SHOW_ALL ? 0 : JSON_THRESHOLD);
+
+ r = sd_journal_get_realtime_usec(j, &realtime);
+ if (r < 0) {
+ log_error("Failed to get realtime timestamp: %s", strerror(-r));
+ return r;
+ }
+
+ r = sd_journal_get_monotonic_usec(j, &monotonic, &boot_id);
+ if (r < 0) {
+ log_error("Failed to get monotonic timestamp: %s", strerror(-r));
+ return r;
+ }
+
+ r = sd_journal_get_cursor(j, &cursor);
+ if (r < 0) {
+ log_error("Failed to get cursor: %s", strerror(-r));
+ return r;
+ }
+
+ if (mode == OUTPUT_JSON_PRETTY)
+ fprintf(f,
+ "{\n"
+ "\t\"__CURSOR\" : \"%s\",\n"
+ "\t\"__REALTIME_TIMESTAMP\" : \"%llu\",\n"
+ "\t\"__MONOTONIC_TIMESTAMP\" : \"%llu\",\n"
+ "\t\"_BOOT_ID\" : \"%s\"",
+ cursor,
+ (unsigned long long) realtime,
+ (unsigned long long) monotonic,
+ sd_id128_to_string(boot_id, sid));
+ else {
+ if (mode == OUTPUT_JSON_SSE)
+ fputs("data: ", f);
+
+ fprintf(f,
+ "{ \"__CURSOR\" : \"%s\", "
+ "\"__REALTIME_TIMESTAMP\" : \"%llu\", "
+ "\"__MONOTONIC_TIMESTAMP\" : \"%llu\", "
+ "\"_BOOT_ID\" : \"%s\"",
+ cursor,
+ (unsigned long long) realtime,
+ (unsigned long long) monotonic,
+ sd_id128_to_string(boot_id, sid));
+ }
+
+ h = hashmap_new(string_hash_func, string_compare_func);
+ if (!h)
+ return -ENOMEM;
+
+ /* First round, iterate through the entry and count how often each field appears */
+ SD_JOURNAL_FOREACH_DATA(j, data, length) {
+ const char *eq;
+ char *n;
+ unsigned u;
+
+ if (length >= 9 &&
+ memcmp(data, "_BOOT_ID=", 9) == 0)
+ continue;
+
+ eq = memchr(data, '=', length);
+ if (!eq)
+ continue;
+
+ n = strndup(data, eq - (const char*) data);
+ if (!n) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ u = PTR_TO_UINT(hashmap_get(h, n));
+ if (u == 0) {
+ r = hashmap_put(h, n, UINT_TO_PTR(1));
+ if (r < 0) {
+ free(n);
+ goto finish;
+ }
+ } else {
+ r = hashmap_update(h, n, UINT_TO_PTR(u + 1));
+ free(n);
+ if (r < 0)
+ goto finish;
+ }
+ }
+
+ separator = true;
+ do {
+ done = true;
+
+ SD_JOURNAL_FOREACH_DATA(j, data, length) {
+ const char *eq;
+ char *kk, *n;
+ size_t m;
+ unsigned u;
+
+ /* We already printed the boot id, from the data in
+ * the header, hence let's suppress it here */
+ if (length >= 9 &&
+ memcmp(data, "_BOOT_ID=", 9) == 0)
+ continue;
+
+ eq = memchr(data, '=', length);
+ if (!eq)
+ continue;
+
+ if (separator) {
+ if (mode == OUTPUT_JSON_PRETTY)
+ fputs(",\n\t", f);
+ else
+ fputs(", ", f);
+ }
+
+ m = eq - (const char*) data;
+
+ n = strndup(data, m);
+ if (!n) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ u = PTR_TO_UINT(hashmap_get2(h, n, (void**) &kk));
+ if (u == 0) {
+ /* We already printed this, let's jump to the next */
+ free(n);
+ separator = false;
+
+ continue;
+ } else if (u == 1) {
+ /* Field only appears once, output it directly */
+
+ json_escape(f, data, m, flags);
+ fputs(" : ", f);
+
+ json_escape(f, eq + 1, length - m - 1, flags);
+
+ hashmap_remove(h, n);
+ free(kk);
+ free(n);
+
+ separator = true;
+
+ continue;
+
+ } else {
+ /* Field appears multiple times, output it as array */
+ json_escape(f, data, m, flags);
+ fputs(" : [ ", f);
+ json_escape(f, eq + 1, length - m - 1, flags);
+
+ /* Iterate through the end of the list */
+
+ while (sd_journal_enumerate_data(j, &data, &length) > 0) {
+ if (length < m + 1)
+ continue;
+
+ if (memcmp(data, n, m) != 0)
+ continue;
+
+ if (((const char*) data)[m] != '=')
+ continue;
+
+ fputs(", ", f);
+ json_escape(f, (const char*) data + m + 1, length - m - 1, flags);
+ }
+
+ fputs(" ]", f);
+
+ hashmap_remove(h, n);
+ free(kk);
+ free(n);
+
+ /* Iterate data fields form the beginning */
+ done = false;
+ separator = true;
+
+ break;
+ }
+ }
+
+ } while (!done);
+
+ if (mode == OUTPUT_JSON_PRETTY)
+ fputs("\n}\n", f);
+ else if (mode == OUTPUT_JSON_SSE)
+ fputs("}\n\n", f);
+ else
+ fputs(" }\n", f);
+
+ r = 0;
+
+finish:
+ while ((k = hashmap_steal_first_key(h)))
+ free(k);
+
+ hashmap_free(h);
+
+ return r;
+}
+
+static int output_cat(
+ FILE *f,
+ sd_journal *j,
+ OutputMode mode,
+ unsigned n_columns,
+ OutputFlags flags) {
+
+ const void *data;
+ size_t l;
+ int r;
+
+ assert(j);
+ assert(f);
+
+ sd_journal_set_data_threshold(j, 0);
+
+ r = sd_journal_get_data(j, "MESSAGE", &data, &l);
+ if (r < 0) {
+ /* An entry without MESSAGE=? */
+ if (r == -ENOENT)
+ return 0;
+
+ log_error("Failed to get data: %s", strerror(-r));
+ return r;
+ }
+
+ assert(l >= 8);
+
+ fwrite((const char*) data + 8, 1, l - 8, f);
+ fputc('\n', f);
+
+ return 0;
+}
+
+static int (*output_funcs[_OUTPUT_MODE_MAX])(
+ FILE *f,
+ sd_journal*j,
+ OutputMode mode,
+ unsigned n_columns,
+ OutputFlags flags) = {
+
+ [OUTPUT_SHORT] = output_short,
+ [OUTPUT_SHORT_MONOTONIC] = output_short,
+ [OUTPUT_VERBOSE] = output_verbose,
+ [OUTPUT_EXPORT] = output_export,
+ [OUTPUT_JSON] = output_json,
+ [OUTPUT_JSON_PRETTY] = output_json,
+ [OUTPUT_JSON_SSE] = output_json,
+ [OUTPUT_CAT] = output_cat
+};
+
+int output_journal(
+ FILE *f,
+ sd_journal *j,
+ OutputMode mode,
+ unsigned n_columns,
+ OutputFlags flags) {
+
+ int ret;
+ assert(mode >= 0);
+ assert(mode < _OUTPUT_MODE_MAX);
+
+ if (n_columns <= 0)
+ n_columns = columns();
+
+ ret = output_funcs[mode](f, j, mode, n_columns, flags);
+ fflush(stdout);
+ return ret;
+}
+
+static int show_journal(FILE *f,
+ sd_journal *j,
+ OutputMode mode,
+ unsigned n_columns,
+ usec_t not_before,
+ unsigned how_many,
+ OutputFlags flags) {
+
+ int r;
+ unsigned line = 0;
+ bool need_seek = false;
+ int warn_cutoff = flags & OUTPUT_WARN_CUTOFF;
+
+ assert(j);
+ assert(mode >= 0);
+ assert(mode < _OUTPUT_MODE_MAX);
+
+ /* Seek to end */
+ r = sd_journal_seek_tail(j);
+ if (r < 0)
+ goto finish;
+
+ r = sd_journal_previous_skip(j, how_many);
+ if (r < 0)
+ goto finish;
+
+ for (;;) {
+ for (;;) {
+ usec_t usec;
+
+ if (need_seek) {
+ r = sd_journal_next(j);
+ if (r < 0)
+ goto finish;
+ }
+
+ if (r == 0)
+ break;
+
+ need_seek = true;
+
+ if (not_before > 0) {
+ r = sd_journal_get_monotonic_usec(j, &usec, NULL);
+
+ /* -ESTALE is returned if the
+ timestamp is not from this boot */
+ if (r == -ESTALE)
+ continue;
+ else if (r < 0)
+ goto finish;
+
+ if (usec < not_before)
+ continue;
+ }
+
+ line ++;
+
+ r = output_journal(f, j, mode, n_columns, flags);
+ if (r < 0)
+ goto finish;
+ }
+
+ if (warn_cutoff && line < how_many && not_before > 0) {
+ sd_id128_t boot_id;
+ usec_t cutoff;
+
+ /* Check whether the cutoff line is too early */
+
+ r = sd_id128_get_boot(&boot_id);
+ if (r < 0)
+ goto finish;
+
+ r = sd_journal_get_cutoff_monotonic_usec(j, boot_id, &cutoff, NULL);
+ if (r < 0)
+ goto finish;
+
+ if (r > 0 && not_before < cutoff)
+ fprintf(f, "Warning: Journal has been rotated since unit was started. Log output is incomplete or unavailable.\n");
+
+ warn_cutoff = false;
+ }
+
+ if (!(flags & OUTPUT_FOLLOW))
+ break;
+
+ r = sd_journal_wait(j, (usec_t) -1);
+ if (r < 0)
+ goto finish;
+
+ }
+
+finish:
+ return r;
+}
+
+int add_matches_for_unit(sd_journal *j, const char *unit) {
+ int r;
+ _cleanup_free_ char *m1 = NULL, *m2 = NULL, *m3 = NULL;
+
+ assert(j);
+ assert(unit);
+
+ if (asprintf(&m1, "_SYSTEMD_UNIT=%s", unit) < 0 ||
+ asprintf(&m2, "COREDUMP_UNIT=%s", unit) < 0 ||
+ asprintf(&m3, "UNIT=%s", unit) < 0)
+ return -ENOMEM;
+
+ (void)(
+ /* Look for messages from the service itself */
+ (r = sd_journal_add_match(j, m1, 0)) ||
+
+ /* Look for coredumps of the service */
+ (r = sd_journal_add_disjunction(j)) ||
+ (r = sd_journal_add_match(j,
+ "MESSAGE_ID=fc2e22bc6ee647b6b90729ab34a250b1", 0)) ||
+ (r = sd_journal_add_match(j, m2, 0)) ||
+
+ /* Look for messages from PID 1 about this service */
+ (r = sd_journal_add_disjunction(j)) ||
+ (r = sd_journal_add_match(j, "_PID=1", 0)) ||
+ (r = sd_journal_add_match(j, m3, 0))
+ );
+ return r;
+}
+
+int add_matches_for_user_unit(sd_journal *j, const char *unit, uid_t uid) {
+ int r;
+ _cleanup_free_ char *m1 = NULL, *m2 = NULL, *m3 = NULL, *m4 = NULL;
+
+ assert(j);
+ assert(unit);
+
+ if (asprintf(&m1, "_SYSTEMD_USER_UNIT=%s", unit) < 0 ||
+ asprintf(&m2, "USER_UNIT=%s", unit) < 0 ||
+ asprintf(&m3, "COREDUMP_USER_UNIT=%s", unit) < 0 ||
+ asprintf(&m4, "_UID=%d", uid) < 0)
+ return -ENOMEM;
+
+ (void) (
+ /* Look for messages from the user service itself */
+ (r = sd_journal_add_match(j, m1, 0)) ||
+ (r = sd_journal_add_match(j, m4, 0)) ||
+
+ /* Look for messages from systemd about this service */
+ (r = sd_journal_add_disjunction(j)) ||
+ (r = sd_journal_add_match(j, m2, 0)) ||
+ (r = sd_journal_add_match(j, m4, 0)) ||
+
+ /* Look for coredumps of the service */
+ (r = sd_journal_add_disjunction(j)) ||
+ (r = sd_journal_add_match(j, m3, 0)) ||
+ (r = sd_journal_add_match(j, m4, 0))
+ );
+ return r;
+}
+
+int show_journal_by_unit(
+ FILE *f,
+ const char *unit,
+ OutputMode mode,
+ unsigned n_columns,
+ usec_t not_before,
+ unsigned how_many,
+ uid_t uid,
+ OutputFlags flags,
+ bool system) {
+
+ _cleanup_journal_close_ sd_journal*j = NULL;
+ int r;
+ int jflags = SD_JOURNAL_LOCAL_ONLY | system * SD_JOURNAL_SYSTEM_ONLY;
+
+ assert(mode >= 0);
+ assert(mode < _OUTPUT_MODE_MAX);
+ assert(unit);
+
+ if (how_many <= 0)
+ return 0;
+
+ r = sd_journal_open(&j, jflags);
+ if (r < 0)
+ return r;
+
+ if (system)
+ r = add_matches_for_unit(j, unit);
+ else
+ r = add_matches_for_user_unit(j, unit, uid);
+ if (r < 0)
+ return r;
+
+ r = show_journal(f, j, mode, n_columns, not_before, how_many, flags);
+ if (r < 0)
+ return r;
+
+ return 0;
+}
+
+static const char *const output_mode_table[_OUTPUT_MODE_MAX] = {
+ [OUTPUT_SHORT] = "short",
+ [OUTPUT_SHORT_MONOTONIC] = "short-monotonic",
+ [OUTPUT_VERBOSE] = "verbose",
+ [OUTPUT_EXPORT] = "export",
+ [OUTPUT_JSON] = "json",
+ [OUTPUT_JSON_PRETTY] = "json-pretty",
+ [OUTPUT_JSON_SSE] = "json-sse",
+ [OUTPUT_CAT] = "cat"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(output_mode, OutputMode);
diff --git a/src/shared/logs-show.h b/src/shared/logs-show.h
new file mode 100644
index 0000000000..b0f93a661a
--- /dev/null
+++ b/src/shared/logs-show.h
@@ -0,0 +1,67 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdbool.h>
+#include <unistd.h>
+#include <sys/types.h>
+
+#include <systemd/sd-journal.h>
+
+#include "util.h"
+#include "output-mode.h"
+
+int output_journal(
+ FILE *f,
+ sd_journal *j,
+ OutputMode mode,
+ unsigned n_columns,
+ OutputFlags flags);
+
+int add_matches_for_unit(
+ sd_journal *j,
+ const char *unit);
+
+int add_matches_for_user_unit(
+ sd_journal *j,
+ const char *unit,
+ uid_t uid);
+
+int show_journal_by_unit(
+ FILE *f,
+ const char *unit,
+ OutputMode mode,
+ unsigned n_columns,
+ usec_t not_before,
+ unsigned how_many,
+ uid_t uid,
+ OutputFlags flags,
+ bool system);
+
+void json_escape(
+ FILE *f,
+ const char* p,
+ size_t l,
+ OutputFlags flags);
+
+const char* output_mode_to_string(OutputMode m) _const_;
+OutputMode output_mode_from_string(const char *s) _pure_;
diff --git a/src/shared/macro.h b/src/shared/macro.h
new file mode 100644
index 0000000000..0874102ece
--- /dev/null
+++ b/src/shared/macro.h
@@ -0,0 +1,285 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <sys/param.h>
+#include <sys/types.h>
+#include <sys/uio.h>
+#include <inttypes.h>
+
+#define _printf_attr_(a,b) __attribute__ ((format (printf, a, b)))
+#define _alloc_(...) __attribute__ ((alloc_size(__VA_ARGS__)))
+#define _sentinel_ __attribute__ ((sentinel))
+#define _noreturn_ __attribute__((noreturn))
+#define _unused_ __attribute__ ((unused))
+#define _destructor_ __attribute__ ((destructor))
+#define _pure_ __attribute__ ((pure))
+#define _const_ __attribute__ ((const))
+#define _deprecated_ __attribute__ ((deprecated))
+#define _packed_ __attribute__ ((packed))
+#define _malloc_ __attribute__ ((malloc))
+#define _weak_ __attribute__ ((weak))
+#define _likely_(x) (__builtin_expect(!!(x),1))
+#define _unlikely_(x) (__builtin_expect(!!(x),0))
+#define _public_ __attribute__ ((visibility("default")))
+#define _hidden_ __attribute__ ((visibility("hidden")))
+#define _weakref_(x) __attribute__((weakref(#x)))
+#define _introspect_(x) __attribute__((section("introspect." x)))
+#define _alignas_(x) __attribute__((aligned(__alignof(x))))
+#define _cleanup_(x) __attribute__((cleanup(x)))
+
+/* automake test harness */
+#define EXIT_TEST_SKIP 77
+
+#define XSTRINGIFY(x) #x
+#define STRINGIFY(x) XSTRINGIFY(x)
+
+/* Rounds up */
+
+#define ALIGN4(l) (((l) + 3) & ~3)
+#define ALIGN8(l) (((l) + 7) & ~7)
+
+#if __SIZEOF_POINTER__ == 8
+#define ALIGN(l) ALIGN8(l)
+#elif __SIZEOF_POINTER__ == 4
+#define ALIGN(l) ALIGN4(l)
+#else
+#error "Wut? Pointers are neither 4 nor 8 bytes long?"
+#endif
+
+#define ALIGN_PTR(p) ((void*) ALIGN((unsigned long) p))
+#define ALIGN4_PTR(p) ((void*) ALIGN4((unsigned long) p))
+#define ALIGN8_PTR(p) ((void*) ALIGN8((unsigned long) p))
+
+static inline size_t ALIGN_TO(size_t l, size_t ali) {
+ return ((l + ali - 1) & ~(ali - 1));
+}
+
+#define ALIGN_TO_PTR(p, ali) ((void*) ALIGN_TO((unsigned long) p))
+
+#define ELEMENTSOF(x) (sizeof(x)/sizeof((x)[0]))
+
+/*
+ * container_of - cast a member of a structure out to the containing structure
+ * @ptr: the pointer to the member.
+ * @type: the type of the container struct this is embedded in.
+ * @member: the name of the member within the struct.
+ *
+ */
+#define container_of(ptr, type, member) \
+ __extension__ ({ \
+ const typeof( ((type *)0)->member ) *__mptr = (ptr); \
+ (type *)( (char *)__mptr - offsetof(type,member) ); \
+ })
+
+#undef MAX
+#define MAX(a,b) \
+ __extension__ ({ \
+ typeof(a) _a = (a); \
+ typeof(b) _b = (b); \
+ _a > _b ? _a : _b; \
+ })
+
+#define MAX3(x,y,z) \
+ __extension__ ({ \
+ typeof(x) _c = MAX(x,y); \
+ MAX(_c, z); \
+ })
+
+#undef MIN
+#define MIN(a,b) \
+ __extension__ ({ \
+ typeof(a) _a = (a); \
+ typeof(b) _b = (b); \
+ _a < _b ? _a : _b; \
+ })
+
+#ifndef CLAMP
+#define CLAMP(x, low, high) \
+ __extension__ ({ \
+ typeof(x) _x = (x); \
+ typeof(low) _low = (low); \
+ typeof(high) _high = (high); \
+ ((_x > _high) ? _high : ((_x < _low) ? _low : _x)); \
+ })
+#endif
+
+#define assert_se(expr) \
+ do { \
+ if (_unlikely_(!(expr))) \
+ log_assert_failed(#expr, __FILE__, __LINE__, __PRETTY_FUNCTION__); \
+ } while (false) \
+
+/* We override the glibc assert() here. */
+#undef assert
+#ifdef NDEBUG
+#define assert(expr) do {} while(false)
+#else
+#define assert(expr) assert_se(expr)
+#endif
+
+#define assert_not_reached(t) \
+ do { \
+ log_assert_failed_unreachable(t, __FILE__, __LINE__, __PRETTY_FUNCTION__); \
+ } while (false)
+
+#if defined(static_assert)
+#define assert_cc(expr) \
+ do { \
+ static_assert(expr, #expr); \
+ } while (false)
+#else
+#define assert_cc(expr) \
+ do { \
+ switch (0) { \
+ case 0: \
+ case !!(expr): \
+ ; \
+ } \
+ } while (false)
+#endif
+
+#define PTR_TO_UINT(p) ((unsigned int) ((uintptr_t) (p)))
+#define UINT_TO_PTR(u) ((void*) ((uintptr_t) (u)))
+
+#define PTR_TO_UINT32(p) ((uint32_t) ((uintptr_t) (p)))
+#define UINT32_TO_PTR(u) ((void*) ((uintptr_t) (u)))
+
+#define PTR_TO_ULONG(p) ((unsigned long) ((uintptr_t) (p)))
+#define ULONG_TO_PTR(u) ((void*) ((uintptr_t) (u)))
+
+#define PTR_TO_INT(p) ((int) ((intptr_t) (p)))
+#define INT_TO_PTR(u) ((void*) ((intptr_t) (u)))
+
+#define TO_INT32(p) ((int32_t) ((intptr_t) (p)))
+#define INT32_TO_PTR(u) ((void*) ((intptr_t) (u)))
+
+#define PTR_TO_LONG(p) ((long) ((intptr_t) (p)))
+#define LONG_TO_PTR(u) ((void*) ((intptr_t) (u)))
+
+#define memzero(x,l) (memset((x), 0, (l)))
+#define zero(x) (memzero(&(x), sizeof(x)))
+
+#define CHAR_TO_STR(x) ((char[2]) { x, 0 })
+
+#define char_array_0(x) x[sizeof(x)-1] = 0;
+
+#define IOVEC_SET_STRING(i, s) \
+ do { \
+ struct iovec *_i = &(i); \
+ char *_s = (char *)(s); \
+ _i->iov_base = _s; \
+ _i->iov_len = strlen(_s); \
+ } while(false)
+
+static inline size_t IOVEC_TOTAL_SIZE(const struct iovec *i, unsigned n) {
+ unsigned j;
+ size_t r = 0;
+
+ for (j = 0; j < n; j++)
+ r += i[j].iov_len;
+
+ return r;
+}
+
+static inline size_t IOVEC_INCREMENT(struct iovec *i, unsigned n, size_t k) {
+ unsigned j;
+
+ for (j = 0; j < n; j++) {
+ size_t sub;
+
+ if (_unlikely_(k <= 0))
+ break;
+
+ sub = MIN(i[j].iov_len, k);
+ i[j].iov_len -= sub;
+ i[j].iov_base = (uint8_t*) i[j].iov_base + sub;
+ k -= sub;
+ }
+
+ return k;
+}
+
+#define VA_FORMAT_ADVANCE(format, ap) \
+do { \
+ int _argtypes[128]; \
+ size_t _i, _k; \
+ _k = parse_printf_format((format), ELEMENTSOF(_argtypes), _argtypes); \
+ assert(_k < ELEMENTSOF(_argtypes)); \
+ for (_i = 0; _i < _k; _i++) { \
+ if (_argtypes[_i] & PA_FLAG_PTR) { \
+ (void) va_arg(ap, void*); \
+ continue; \
+ } \
+ \
+ switch (_argtypes[_i]) { \
+ case PA_INT: \
+ case PA_INT|PA_FLAG_SHORT: \
+ case PA_CHAR: \
+ (void) va_arg(ap, int); \
+ break; \
+ case PA_INT|PA_FLAG_LONG: \
+ (void) va_arg(ap, long int); \
+ break; \
+ case PA_INT|PA_FLAG_LONG_LONG: \
+ (void) va_arg(ap, long long int); \
+ break; \
+ case PA_WCHAR: \
+ (void) va_arg(ap, wchar_t); \
+ break; \
+ case PA_WSTRING: \
+ case PA_STRING: \
+ case PA_POINTER: \
+ (void) va_arg(ap, void*); \
+ break; \
+ case PA_FLOAT: \
+ case PA_DOUBLE: \
+ (void) va_arg(ap, double); \
+ break; \
+ case PA_DOUBLE|PA_FLAG_LONG_DOUBLE: \
+ (void) va_arg(ap, long double); \
+ break; \
+ default: \
+ assert_not_reached("Unknown format string argument."); \
+ } \
+ } \
+} while(false)
+
+ /* Because statfs.t_type can be int on some architecures, we have to cast
+ * the const magic to the type, otherwise the compiler warns about
+ * signed/unsigned comparison, because the magic can be 32 bit unsigned.
+ */
+#define F_TYPE_CMP(a, b) (a == (typeof(a)) b)
+
+
+/* Returns the number of chars needed to format variables of the
+ * specified type as a decimal string. Adds in extra space for a
+ * negative '-' prefix. */
+
+#define DECIMAL_STR_MAX(type) \
+ (1+(sizeof(type) <= 1 ? 3 : \
+ sizeof(type) <= 2 ? 5 : \
+ sizeof(type) <= 4 ? 10 : \
+ sizeof(type) <= 8 ? 20 : sizeof(int[-2*(sizeof(type) > 8)])))
+
+#include "log.h"
diff --git a/src/shared/missing.h b/src/shared/missing.h
new file mode 100644
index 0000000000..d4ba0d3dcf
--- /dev/null
+++ b/src/shared/missing.h
@@ -0,0 +1,267 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+/* Missing glibc definitions to access certain kernel APIs */
+
+#include <sys/resource.h>
+#include <sys/syscall.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <linux/oom.h>
+
+#ifdef HAVE_AUDIT
+#include <libaudit.h>
+#endif
+
+#include "macro.h"
+
+#ifdef ARCH_MIPS
+#include <asm/sgidefs.h>
+#endif
+
+#ifndef RLIMIT_RTTIME
+#define RLIMIT_RTTIME 15
+#endif
+
+#ifndef F_LINUX_SPECIFIC_BASE
+#define F_LINUX_SPECIFIC_BASE 1024
+#endif
+
+#ifndef F_SETPIPE_SZ
+#define F_SETPIPE_SZ (F_LINUX_SPECIFIC_BASE + 7)
+#endif
+
+#ifndef F_GETPIPE_SZ
+#define F_GETPIPE_SZ (F_LINUX_SPECIFIC_BASE + 8)
+#endif
+
+#ifndef IP_FREEBIND
+#define IP_FREEBIND 15
+#endif
+
+#ifndef OOM_SCORE_ADJ_MIN
+#define OOM_SCORE_ADJ_MIN (-1000)
+#endif
+
+#ifndef OOM_SCORE_ADJ_MAX
+#define OOM_SCORE_ADJ_MAX 1000
+#endif
+
+#ifndef AUDIT_SERVICE_START
+#define AUDIT_SERVICE_START 1130 /* Service (daemon) start */
+#endif
+
+#ifndef AUDIT_SERVICE_STOP
+#define AUDIT_SERVICE_STOP 1131 /* Service (daemon) stop */
+#endif
+
+#ifndef TIOCVHANGUP
+#define TIOCVHANGUP 0x5437
+#endif
+
+#ifndef IP_TRANSPARENT
+#define IP_TRANSPARENT 19
+#endif
+
+#if !HAVE_DECL_PIVOT_ROOT
+static inline int pivot_root(const char *new_root, const char *put_old) {
+ return syscall(SYS_pivot_root, new_root, put_old);
+}
+#endif
+
+#ifdef __x86_64__
+# ifndef __NR_fanotify_init
+# define __NR_fanotify_init 300
+# endif
+# ifndef __NR_fanotify_mark
+# define __NR_fanotify_mark 301
+# endif
+#elif defined _MIPS_SIM
+# if _MIPS_SIM == _MIPS_SIM_ABI32
+# ifndef __NR_fanotify_init
+# define __NR_fanotify_init 4336
+# endif
+# ifndef __NR_fanotify_mark
+# define __NR_fanotify_mark 4337
+# endif
+# elif _MIPS_SIM == _MIPS_SIM_NABI32
+# ifndef __NR_fanotify_init
+# define __NR_fanotify_init 6300
+# endif
+# ifndef __NR_fanotify_mark
+# define __NR_fanotify_mark 6301
+# endif
+# elif _MIPS_SIM == _MIPS_SIM_ABI64
+# ifndef __NR_fanotify_init
+# define __NR_fanotify_init 5295
+# endif
+# ifndef __NR_fanotify_mark
+# define __NR_fanotify_mark 5296
+# endif
+# endif
+#else
+# ifndef __NR_fanotify_init
+# define __NR_fanotify_init 338
+# endif
+# ifndef __NR_fanotify_mark
+# define __NR_fanotify_mark 339
+# endif
+#endif
+
+#ifndef HAVE_FANOTIFY_INIT
+static inline int fanotify_init(unsigned int flags, unsigned int event_f_flags) {
+ return syscall(__NR_fanotify_init, flags, event_f_flags);
+}
+#endif
+
+#ifndef HAVE_FANOTIFY_MARK
+static inline int fanotify_mark(int fanotify_fd, unsigned int flags, uint64_t mask,
+ int dfd, const char *pathname) {
+#if defined _MIPS_SIM && _MIPS_SIM == _MIPS_SIM_ABI32 || defined __powerpc__ && !defined __powerpc64__
+ union {
+ uint64_t _64;
+ uint32_t _32[2];
+ } _mask;
+ _mask._64 = mask;
+
+ return syscall(__NR_fanotify_mark, fanotify_fd, flags,
+ _mask._32[0], _mask._32[1], dfd, pathname);
+#else
+ return syscall(__NR_fanotify_mark, fanotify_fd, flags, mask, dfd, pathname);
+#endif
+}
+#endif
+
+#ifndef BTRFS_IOCTL_MAGIC
+#define BTRFS_IOCTL_MAGIC 0x94
+#endif
+
+#ifndef BTRFS_PATH_NAME_MAX
+#define BTRFS_PATH_NAME_MAX 4087
+#endif
+
+struct btrfs_ioctl_vol_args {
+ int64_t fd;
+ char name[BTRFS_PATH_NAME_MAX + 1];
+};
+
+#ifndef BTRFS_IOC_DEFRAG
+#define BTRFS_IOC_DEFRAG _IOW(BTRFS_IOCTL_MAGIC, 2, struct btrfs_ioctl_vol_args)
+#endif
+
+#ifndef BTRFS_SUPER_MAGIC
+#define BTRFS_SUPER_MAGIC 0x9123683E
+#endif
+
+#ifndef MS_MOVE
+#define MS_MOVE 8192
+#endif
+
+#ifndef MS_PRIVATE
+#define MS_PRIVATE (1 << 18)
+#endif
+
+#if !HAVE_DECL_GETTID
+static inline pid_t gettid(void) {
+ return (pid_t) syscall(SYS_gettid);
+}
+#endif
+
+#ifndef SCM_SECURITY
+#define SCM_SECURITY 0x03
+#endif
+
+#ifndef MS_STRICTATIME
+#define MS_STRICTATIME (1<<24)
+#endif
+
+#ifndef MS_REC
+#define MS_REC 16384
+#endif
+
+#ifndef MS_SHARED
+#define MS_SHARED (1<<20)
+#endif
+
+#ifndef PR_SET_NO_NEW_PRIVS
+#define PR_SET_NO_NEW_PRIVS 38
+#endif
+
+#ifndef PR_SET_CHILD_SUBREAPER
+#define PR_SET_CHILD_SUBREAPER 36
+#endif
+
+#ifndef MAX_HANDLE_SZ
+#define MAX_HANDLE_SZ 128
+#endif
+
+#if defined __x86_64__
+# ifndef __NR_name_to_handle_at
+# define __NR_name_to_handle_at 303
+# endif
+#elif defined __i386__
+# ifndef __NR_name_to_handle_at
+# define __NR_name_to_handle_at 341
+# endif
+#elif defined __arm__
+# ifndef __NR_name_to_handle_at
+# define __NR_name_to_handle_at 370
+# endif
+#elif defined __powerpc__
+# ifndef __NR_name_to_handle_at
+# define __NR_name_to_handle_at 345
+# endif
+#else
+# ifndef __NR_name_to_handle_at
+# error __NR_name_to_handle_at is not defined
+# endif
+#endif
+
+#if !HAVE_DECL_NAME_TO_HANDLE_AT
+struct file_handle {
+ unsigned int handle_bytes;
+ int handle_type;
+ unsigned char f_handle[0];
+};
+
+static inline int name_to_handle_at(int fd, const char *name, struct file_handle *handle, int *mnt_id, int flags) {
+ return syscall(__NR_name_to_handle_at, fd, name, handle, mnt_id, flags);
+}
+#endif
+
+#ifndef HAVE_SECURE_GETENV
+# ifdef HAVE___SECURE_GETENV
+# define secure_getenv __secure_getenv
+# else
+# error neither secure_getenv nor __secure_getenv are available
+# endif
+#endif
+
+#ifndef CIFS_MAGIC_NUMBER
+#define CIFS_MAGIC_NUMBER 0xFF534D42
+#endif
+
+#ifndef TFD_TIMER_CANCEL_ON_SET
+#define TFD_TIMER_CANCEL_ON_SET (1 << 1)
+#endif
diff --git a/src/shared/mkdir.c b/src/shared/mkdir.c
new file mode 100644
index 0000000000..0e51b64f69
--- /dev/null
+++ b/src/shared/mkdir.c
@@ -0,0 +1,147 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <stdio.h>
+
+#include "mkdir.h"
+#include "label.h"
+#include "util.h"
+
+int mkdir_label(const char *path, mode_t mode) {
+ return label_mkdir(path, mode, true);
+}
+
+static int makedir_safe(const char *path, mode_t mode, uid_t uid, gid_t gid, bool apply) {
+ struct stat st;
+
+ if (label_mkdir(path, mode, apply) >= 0)
+ if (chmod_and_chown(path, mode, uid, gid) < 0)
+ return -errno;
+
+ if (lstat(path, &st) < 0)
+ return -errno;
+
+ if ((st.st_mode & 0777) != mode ||
+ st.st_uid != uid ||
+ st.st_gid != gid ||
+ !S_ISDIR(st.st_mode)) {
+ errno = EEXIST;
+ return -errno;
+ }
+
+ return 0;
+}
+
+int mkdir_safe(const char *path, mode_t mode, uid_t uid, gid_t gid) {
+ return makedir_safe(path, mode, uid, gid, false);
+}
+
+int mkdir_safe_label(const char *path, mode_t mode, uid_t uid, gid_t gid) {
+ return makedir_safe(path, mode, uid, gid, true);
+}
+
+static int makedir_parents(const char *path, mode_t mode, bool apply) {
+ struct stat st;
+ const char *p, *e;
+
+ assert(path);
+
+ /* return immediately if directory exists */
+ e = strrchr(path, '/');
+ if (!e)
+ return -EINVAL;
+ p = strndupa(path, e - path);
+ if (stat(p, &st) >= 0) {
+ if ((st.st_mode & S_IFMT) == S_IFDIR)
+ return 0;
+ else
+ return -ENOTDIR;
+ }
+
+ /* create every parent directory in the path, except the last component */
+ p = path + strspn(path, "/");
+ for (;;) {
+ int r;
+ char *t;
+
+ e = p + strcspn(p, "/");
+ p = e + strspn(e, "/");
+
+ /* Is this the last component? If so, then we're
+ * done */
+ if (*p == 0)
+ return 0;
+
+ t = strndup(path, e - path);
+ if (!t)
+ return -ENOMEM;
+
+ r = label_mkdir(t, mode, apply);
+ free(t);
+
+ if (r < 0 && errno != EEXIST)
+ return -errno;
+ }
+}
+
+int mkdir_parents(const char *path, mode_t mode) {
+ return makedir_parents(path, mode, false);
+}
+
+int mkdir_parents_label(const char *path, mode_t mode) {
+ return makedir_parents(path, mode, true);
+}
+
+static int is_dir(const char* path) {
+ struct stat st;
+ if (stat(path, &st) < 0)
+ return -errno;
+ return S_ISDIR(st.st_mode);
+}
+
+static int makedir_p(const char *path, mode_t mode, bool apply) {
+ int r;
+
+ /* Like mkdir -p */
+
+ r = makedir_parents(path, mode, apply);
+ if (r < 0)
+ return r;
+
+ r = label_mkdir(path, mode, apply);
+ if (r < 0 && (errno != EEXIST || is_dir(path) <= 0))
+ return -errno;
+
+ return 0;
+}
+
+int mkdir_p(const char *path, mode_t mode) {
+ return makedir_p(path, mode, false);
+}
+
+int mkdir_p_label(const char *path, mode_t mode) {
+ return makedir_p(path, mode, true);
+}
diff --git a/src/shared/mkdir.h b/src/shared/mkdir.h
new file mode 100644
index 0000000000..ce1c35e9ba
--- /dev/null
+++ b/src/shared/mkdir.h
@@ -0,0 +1,32 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef foomkdirhfoo
+#define foomkdirhfoo
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+int mkdir_label(const char *path, mode_t mode);
+int mkdir_safe(const char *path, mode_t mode, uid_t uid, gid_t gid);
+int mkdir_safe_label(const char *path, mode_t mode, uid_t uid, gid_t gid);
+int mkdir_parents(const char *path, mode_t mode);
+int mkdir_parents_label(const char *path, mode_t mode);
+int mkdir_p(const char *path, mode_t mode);
+int mkdir_p_label(const char *path, mode_t mode);
+#endif
diff --git a/src/shared/output-mode.h b/src/shared/output-mode.h
new file mode 100644
index 0000000000..0efd430c5d
--- /dev/null
+++ b/src/shared/output-mode.h
@@ -0,0 +1,44 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+typedef enum OutputMode {
+ OUTPUT_SHORT,
+ OUTPUT_SHORT_MONOTONIC,
+ OUTPUT_VERBOSE,
+ OUTPUT_EXPORT,
+ OUTPUT_JSON,
+ OUTPUT_JSON_PRETTY,
+ OUTPUT_JSON_SSE,
+ OUTPUT_CAT,
+ _OUTPUT_MODE_MAX,
+ _OUTPUT_MODE_INVALID = -1
+} OutputMode;
+
+typedef enum OutputFlags {
+ OUTPUT_SHOW_ALL = 1 << 0,
+ OUTPUT_FOLLOW = 1 << 1,
+ OUTPUT_WARN_CUTOFF = 1 << 2,
+ OUTPUT_FULL_WIDTH = 1 << 3,
+ OUTPUT_COLOR = 1 << 4,
+ OUTPUT_CATALOG = 1 << 5
+} OutputFlags;
diff --git a/src/shared/pager.c b/src/shared/pager.c
new file mode 100644
index 0000000000..8dddf24f4c
--- /dev/null
+++ b/src/shared/pager.c
@@ -0,0 +1,146 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/types.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <string.h>
+#include <sys/prctl.h>
+
+#include "pager.h"
+#include "util.h"
+#include "macro.h"
+
+static pid_t pager_pid = 0;
+
+_noreturn_ static void pager_fallback(void) {
+ ssize_t n;
+ do {
+ n = splice(STDIN_FILENO, NULL, STDOUT_FILENO, NULL, 64*1024, 0);
+ } while (n > 0);
+ if (n < 0) {
+ log_error("Internal pager failed: %m");
+ _exit(EXIT_FAILURE);
+ }
+ _exit(EXIT_SUCCESS);
+}
+
+int pager_open(bool jump_to_end) {
+ int fd[2];
+ const char *pager;
+ pid_t parent_pid;
+ int r;
+
+ if (pager_pid > 0)
+ return 1;
+
+ if ((pager = getenv("SYSTEMD_PAGER")) || (pager = getenv("PAGER")))
+ if (!*pager || streq(pager, "cat"))
+ return 0;
+
+ if (!on_tty())
+ return 0;
+
+ /* Determine and cache number of columns before we spawn the
+ * pager so that we get the value from the actual tty */
+ columns();
+
+ if (pipe(fd) < 0) {
+ log_error("Failed to create pager pipe: %m");
+ return -errno;
+ }
+
+ parent_pid = getpid();
+
+ pager_pid = fork();
+ if (pager_pid < 0) {
+ r = -errno;
+ log_error("Failed to fork pager: %m");
+ close_pipe(fd);
+ return r;
+ }
+
+ /* In the child start the pager */
+ if (pager_pid == 0) {
+
+ dup2(fd[0], STDIN_FILENO);
+ close_pipe(fd);
+
+ if (jump_to_end)
+ setenv("LESS", "FRSXMK+G", 1);
+ else
+ setenv("LESS", "FRSXMK", 1);
+
+ /* Make sure the pager goes away when the parent dies */
+ if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
+ _exit(EXIT_FAILURE);
+
+ /* Check whether our parent died before we were able
+ * to set the death signal */
+ if (getppid() != parent_pid)
+ _exit(EXIT_SUCCESS);
+
+ if (pager) {
+ execlp(pager, pager, NULL);
+ execl("/bin/sh", "sh", "-c", pager, NULL);
+ }
+
+ /* Debian's alternatives command for pagers is
+ * called 'pager'. Note that we do not call
+ * sensible-pagers here, since that is just a
+ * shell script that implements a logic that
+ * is similar to this one anyway, but is
+ * Debian-specific. */
+ execlp("pager", "pager", NULL);
+
+ execlp("less", "less", NULL);
+ execlp("more", "more", NULL);
+
+ pager_fallback();
+ /* not reached */
+ }
+
+ /* Return in the parent */
+ if (dup2(fd[1], STDOUT_FILENO) < 0) {
+ log_error("Failed to duplicate pager pipe: %m");
+ return -errno;
+ }
+
+ close_pipe(fd);
+ return 1;
+}
+
+void pager_close(void) {
+
+ if (pager_pid <= 0)
+ return;
+
+ /* Inform pager that we are done */
+ fclose(stdout);
+ kill(pager_pid, SIGCONT);
+ wait_for_terminate(pager_pid, NULL);
+ pager_pid = 0;
+}
+
+bool pager_have(void) {
+ return pager_pid > 0;
+}
diff --git a/src/shared/pager.h b/src/shared/pager.h
new file mode 100644
index 0000000000..03dca8bc03
--- /dev/null
+++ b/src/shared/pager.h
@@ -0,0 +1,30 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdbool.h>
+
+#include "macro.h"
+
+int pager_open(bool jump_to_end);
+void pager_close(void);
+bool pager_have(void) _pure_;
diff --git a/src/shared/path-lookup.c b/src/shared/path-lookup.c
new file mode 100644
index 0000000000..1a47ea9ce7
--- /dev/null
+++ b/src/shared/path-lookup.c
@@ -0,0 +1,426 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+
+#include "util.h"
+#include "mkdir.h"
+#include "strv.h"
+#include "path-util.h"
+#include "path-lookup.h"
+
+static const char* const systemd_running_as_table[_SYSTEMD_RUNNING_AS_MAX] = {
+ [SYSTEMD_SYSTEM] = "system",
+ [SYSTEMD_USER] = "user"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(systemd_running_as, SystemdRunningAs);
+
+int user_config_home(char **config_home) {
+ const char *e;
+ char *r;
+
+ e = getenv("XDG_CONFIG_HOME");
+ if (e) {
+ r = strappend(e, "/systemd/user");
+ if (!r)
+ return -ENOMEM;
+
+ *config_home = r;
+ return 1;
+ } else {
+ const char *home;
+
+ home = getenv("HOME");
+ if (home) {
+ r = strappend(home, "/.config/systemd/user");
+ if (!r)
+ return -ENOMEM;
+
+ *config_home = r;
+ return 1;
+ }
+ }
+
+ return 0;
+}
+
+static char** user_dirs(
+ const char *generator,
+ const char *generator_early,
+ const char *generator_late) {
+
+ const char * const config_unit_paths[] = {
+ USER_CONFIG_UNIT_PATH,
+ "/etc/systemd/user",
+ "/run/systemd/user",
+ NULL
+ };
+
+ const char * const data_unit_paths[] = {
+ "/usr/local/lib/systemd/user",
+ "/usr/local/share/systemd/user",
+ USER_DATA_UNIT_PATH,
+ "/usr/lib/systemd/user",
+ "/usr/share/systemd/user",
+ NULL
+ };
+
+ const char *home, *e;
+ char *config_home = NULL, *data_home = NULL;
+ char **config_dirs = NULL, **data_dirs = NULL;
+ char **r = NULL, **t;
+
+ /* Implement the mechanisms defined in
+ *
+ * http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html
+ *
+ * We look in both the config and the data dirs because we
+ * want to encourage that distributors ship their unit files
+ * as data, and allow overriding as configuration.
+ */
+
+ if (user_config_home(&config_home) < 0)
+ goto fail;
+
+ home = getenv("HOME");
+
+ e = getenv("XDG_CONFIG_DIRS");
+ if (e) {
+ config_dirs = strv_split(e, ":");
+ if (!config_dirs)
+ goto fail;
+ }
+
+ /* We don't treat /etc/xdg/systemd here as the spec
+ * suggests because we assume that that is a link to
+ * /etc/systemd/ anyway. */
+
+ e = getenv("XDG_DATA_HOME");
+ if (e) {
+ if (asprintf(&data_home, "%s/systemd/user", e) < 0)
+ goto fail;
+
+ } else if (home) {
+ if (asprintf(&data_home, "%s/.local/share/systemd/user", home) < 0)
+ goto fail;
+
+ /* There is really no need for two unit dirs in $HOME,
+ * except to be fully compliant with the XDG spec. We
+ * now try to link the two dirs, so that we can
+ * minimize disk seeks a little. Further down we'll
+ * then filter out this link, if it is actually is
+ * one. */
+
+ mkdir_parents_label(data_home, 0777);
+ (void) symlink("../../../.config/systemd/user", data_home);
+ }
+
+ e = getenv("XDG_DATA_DIRS");
+ if (e)
+ data_dirs = strv_split(e, ":");
+ else
+ data_dirs = strv_new("/usr/local/share",
+ "/usr/share",
+ NULL);
+ if (!data_dirs)
+ goto fail;
+
+ /* Now merge everything we found. */
+ if (generator_early) {
+ t = strv_append(r, generator_early);
+ if (!t)
+ goto fail;
+ strv_free(r);
+ r = t;
+ }
+
+ if (config_home) {
+ t = strv_append(r, config_home);
+ if (!t)
+ goto fail;
+ strv_free(r);
+ r = t;
+ }
+
+ if (!strv_isempty(config_dirs)) {
+ t = strv_merge_concat(r, config_dirs, "/systemd/user");
+ if (!t)
+ goto finish;
+ strv_free(r);
+ r = t;
+ }
+
+ t = strv_merge(r, (char**) config_unit_paths);
+ if (!t)
+ goto fail;
+ strv_free(r);
+ r = t;
+
+ if (generator) {
+ t = strv_append(r, generator);
+ if (!t)
+ goto fail;
+ strv_free(r);
+ r = t;
+ }
+
+ if (data_home) {
+ t = strv_append(r, data_home);
+ if (!t)
+ goto fail;
+ strv_free(r);
+ r = t;
+ }
+
+ if (!strv_isempty(data_dirs)) {
+ t = strv_merge_concat(r, data_dirs, "/systemd/user");
+ if (!t)
+ goto fail;
+ strv_free(r);
+ r = t;
+ }
+
+ t = strv_merge(r, (char**) data_unit_paths);
+ if (!t)
+ goto fail;
+ strv_free(r);
+ r = t;
+
+ if (generator_late) {
+ t = strv_append(r, generator_late);
+ if (!t)
+ goto fail;
+ strv_free(r);
+ r = t;
+ }
+
+ if (!path_strv_make_absolute_cwd(r))
+ goto fail;
+
+finish:
+ free(config_home);
+ strv_free(config_dirs);
+ free(data_home);
+ strv_free(data_dirs);
+
+ return r;
+
+fail:
+ strv_free(r);
+ r = NULL;
+ goto finish;
+}
+
+int lookup_paths_init(
+ LookupPaths *p,
+ SystemdRunningAs running_as,
+ bool personal,
+ const char *generator,
+ const char *generator_early,
+ const char *generator_late) {
+
+ const char *e;
+
+ assert(p);
+
+ /* First priority is whatever has been passed to us via env
+ * vars */
+ e = getenv("SYSTEMD_UNIT_PATH");
+ if (e) {
+ p->unit_path = path_split_and_make_absolute(e);
+ if (!p->unit_path)
+ return -ENOMEM;
+ } else
+ p->unit_path = NULL;
+
+ if (strv_isempty(p->unit_path)) {
+ /* Nothing is set, so let's figure something out. */
+ strv_free(p->unit_path);
+
+ /* For the user units we include share/ in the search
+ * path in order to comply with the XDG basedir
+ * spec. For the system stuff we avoid such
+ * nonsense. OTOH we include /lib in the search path
+ * for the system stuff but avoid it for user
+ * stuff. */
+
+ if (running_as == SYSTEMD_USER) {
+
+ if (personal)
+ p->unit_path = user_dirs(generator, generator_early, generator_late);
+ else
+ p->unit_path = strv_new(
+ /* If you modify this you also want to modify
+ * systemduserunitpath= in systemd.pc.in, and
+ * the arrays in user_dirs() above! */
+ STRV_IFNOTNULL(generator_early),
+ USER_CONFIG_UNIT_PATH,
+ "/etc/systemd/user",
+ "/run/systemd/user",
+ STRV_IFNOTNULL(generator),
+ "/usr/local/lib/systemd/user",
+ "/usr/local/share/systemd/user",
+ USER_DATA_UNIT_PATH,
+ "/usr/lib/systemd/user",
+ "/usr/share/systemd/user",
+ STRV_IFNOTNULL(generator_late),
+ NULL);
+
+ if (!p->unit_path)
+ return -ENOMEM;
+
+ } else {
+ p->unit_path = strv_new(
+ /* If you modify this you also want to modify
+ * systemdsystemunitpath= in systemd.pc.in! */
+ STRV_IFNOTNULL(generator_early),
+ SYSTEM_CONFIG_UNIT_PATH,
+ "/etc/systemd/system",
+ "/run/systemd/system",
+ STRV_IFNOTNULL(generator),
+ "/usr/local/lib/systemd/system",
+ SYSTEM_DATA_UNIT_PATH,
+ "/usr/lib/systemd/system",
+#ifdef HAVE_SPLIT_USR
+ "/lib/systemd/system",
+#endif
+ STRV_IFNOTNULL(generator_late),
+ NULL);
+
+ if (!p->unit_path)
+ return -ENOMEM;
+ }
+ }
+
+ if (!path_strv_canonicalize(p->unit_path))
+ return -ENOMEM;
+
+ strv_uniq(p->unit_path);
+
+ if (!strv_isempty(p->unit_path)) {
+ _cleanup_free_ char *t = strv_join(p->unit_path, "\n\t");
+ if (!t)
+ return -ENOMEM;
+ log_debug("Looking for unit files in (higher priority first):\n\t%s", t);
+ } else {
+ log_debug("Ignoring unit files.");
+ strv_free(p->unit_path);
+ p->unit_path = NULL;
+ }
+
+ if (running_as == SYSTEMD_SYSTEM) {
+#ifdef HAVE_SYSV_COMPAT
+ /* /etc/init.d/ compatibility does not matter to users */
+
+ e = getenv("SYSTEMD_SYSVINIT_PATH");
+ if (e) {
+ p->sysvinit_path = path_split_and_make_absolute(e);
+ if (!p->sysvinit_path)
+ return -ENOMEM;
+ } else
+ p->sysvinit_path = NULL;
+
+ if (strv_isempty(p->sysvinit_path)) {
+ strv_free(p->sysvinit_path);
+
+ p->sysvinit_path = strv_new(
+ SYSTEM_SYSVINIT_PATH, /* /etc/init.d/ */
+ NULL);
+ if (!p->sysvinit_path)
+ return -ENOMEM;
+ }
+
+ e = getenv("SYSTEMD_SYSVRCND_PATH");
+ if (e) {
+ p->sysvrcnd_path = path_split_and_make_absolute(e);
+ if (!p->sysvrcnd_path)
+ return -ENOMEM;
+ } else
+ p->sysvrcnd_path = NULL;
+
+ if (strv_isempty(p->sysvrcnd_path)) {
+ strv_free(p->sysvrcnd_path);
+
+ p->sysvrcnd_path = strv_new(
+ SYSTEM_SYSVRCND_PATH, /* /etc/rcN.d/ */
+ NULL);
+ if (!p->sysvrcnd_path)
+ return -ENOMEM;
+ }
+
+ if (!path_strv_canonicalize(p->sysvinit_path))
+ return -ENOMEM;
+
+ if (!path_strv_canonicalize(p->sysvrcnd_path))
+ return -ENOMEM;
+
+ strv_uniq(p->sysvinit_path);
+ strv_uniq(p->sysvrcnd_path);
+
+ if (!strv_isempty(p->sysvinit_path)) {
+ _cleanup_free_ char *t = strv_join(p->sysvinit_path, "\n\t");
+ if (!t)
+ return -ENOMEM;
+ log_debug("Looking for SysV init scripts in:\n\t%s", t);
+ } else {
+ log_debug("Ignoring SysV init scripts.");
+ strv_free(p->sysvinit_path);
+ p->sysvinit_path = NULL;
+ }
+
+ if (!strv_isempty(p->sysvrcnd_path)) {
+ _cleanup_free_ char *t =
+ strv_join(p->sysvrcnd_path, "\n\t");
+ if (!t)
+ return -ENOMEM;
+
+ log_debug("Looking for SysV rcN.d links in:\n\t%s", t);
+ } else {
+ log_debug("Ignoring SysV rcN.d links.");
+ strv_free(p->sysvrcnd_path);
+ p->sysvrcnd_path = NULL;
+ }
+#else
+ log_debug("SysV init scripts and rcN.d links support disabled");
+#endif
+ }
+
+ return 0;
+}
+
+void lookup_paths_free(LookupPaths *p) {
+ assert(p);
+
+ strv_free(p->unit_path);
+ p->unit_path = NULL;
+
+#ifdef HAVE_SYSV_COMPAT
+ strv_free(p->sysvinit_path);
+ strv_free(p->sysvrcnd_path);
+ p->sysvinit_path = p->sysvrcnd_path = NULL;
+#endif
+}
diff --git a/src/shared/path-lookup.h b/src/shared/path-lookup.h
new file mode 100644
index 0000000000..9dee85f967
--- /dev/null
+++ b/src/shared/path-lookup.h
@@ -0,0 +1,45 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+typedef struct LookupPaths {
+ char **unit_path;
+#ifdef HAVE_SYSV_COMPAT
+ char **sysvinit_path;
+ char **sysvrcnd_path;
+#endif
+} LookupPaths;
+
+typedef enum SystemdRunningAs {
+ SYSTEMD_SYSTEM,
+ SYSTEMD_USER,
+ _SYSTEMD_RUNNING_AS_MAX,
+ _SYSTEMD_RUNNING_AS_INVALID = -1
+} SystemdRunningAs;
+
+const char* systemd_running_as_to_string(SystemdRunningAs i) _const_;
+SystemdRunningAs systemd_running_as_from_string(const char *s) _pure_;
+
+int user_config_home(char **config_home);
+
+int lookup_paths_init(LookupPaths *p, SystemdRunningAs running_as, bool personal, const char *generator, const char *generator_early, const char *generator_late);
+void lookup_paths_free(LookupPaths *p);
diff --git a/src/shared/path-util.c b/src/shared/path-util.c
new file mode 100644
index 0000000000..0c1b6a0ab0
--- /dev/null
+++ b/src/shared/path-util.c
@@ -0,0 +1,428 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010-2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <signal.h>
+#include <stdio.h>
+#include <fcntl.h>
+#include <dirent.h>
+#include <sys/statvfs.h>
+
+#include "macro.h"
+#include "util.h"
+#include "log.h"
+#include "strv.h"
+#include "path-util.h"
+#include "missing.h"
+
+bool path_is_absolute(const char *p) {
+ return p[0] == '/';
+}
+
+bool is_path(const char *p) {
+ return !!strchr(p, '/');
+}
+
+char *path_get_file_name(const char *p) {
+ char *r;
+
+ assert(p);
+
+ r = strrchr(p, '/');
+ if (r)
+ return r + 1;
+
+ return (char*) p;
+}
+
+int path_get_parent(const char *path, char **_r) {
+ const char *e, *a = NULL, *b = NULL, *p;
+ char *r;
+ bool slash = false;
+
+ assert(path);
+ assert(_r);
+
+ if (!*path)
+ return -EINVAL;
+
+ for (e = path; *e; e++) {
+
+ if (!slash && *e == '/') {
+ a = b;
+ b = e;
+ slash = true;
+ } else if (slash && *e != '/')
+ slash = false;
+ }
+
+ if (*(e-1) == '/')
+ p = a;
+ else
+ p = b;
+
+ if (!p)
+ return -EINVAL;
+
+ if (p == path)
+ r = strdup("/");
+ else
+ r = strndup(path, p-path);
+
+ if (!r)
+ return -ENOMEM;
+
+ *_r = r;
+ return 0;
+}
+
+char **path_split_and_make_absolute(const char *p) {
+ char **l;
+ assert(p);
+
+ if (!(l = strv_split(p, ":")))
+ return NULL;
+
+ if (!path_strv_make_absolute_cwd(l)) {
+ strv_free(l);
+ return NULL;
+ }
+
+ return l;
+}
+
+char *path_make_absolute(const char *p, const char *prefix) {
+ assert(p);
+
+ /* Makes every item in the list an absolute path by prepending
+ * the prefix, if specified and necessary */
+
+ if (path_is_absolute(p) || !prefix)
+ return strdup(p);
+
+ return strjoin(prefix, "/", p, NULL);
+}
+
+char *path_make_absolute_cwd(const char *p) {
+ char *cwd, *r;
+
+ assert(p);
+
+ /* Similar to path_make_absolute(), but prefixes with the
+ * current working directory. */
+
+ if (path_is_absolute(p))
+ return strdup(p);
+
+ cwd = get_current_dir_name();
+ if (!cwd)
+ return NULL;
+
+ r = path_make_absolute(p, cwd);
+ free(cwd);
+
+ return r;
+}
+
+char **path_strv_make_absolute_cwd(char **l) {
+ char **s;
+
+ /* Goes through every item in the string list and makes it
+ * absolute. This works in place and won't rollback any
+ * changes on failure. */
+
+ STRV_FOREACH(s, l) {
+ char *t;
+
+ if (!(t = path_make_absolute_cwd(*s)))
+ return NULL;
+
+ free(*s);
+ *s = t;
+ }
+
+ return l;
+}
+
+char **path_strv_canonicalize(char **l) {
+ char **s;
+ unsigned k = 0;
+ bool enomem = false;
+
+ if (strv_isempty(l))
+ return l;
+
+ /* Goes through every item in the string list and canonicalize
+ * the path. This works in place and won't rollback any
+ * changes on failure. */
+
+ STRV_FOREACH(s, l) {
+ char *t, *u;
+
+ t = path_make_absolute_cwd(*s);
+ free(*s);
+ *s = NULL;
+
+ if (!t) {
+ enomem = true;
+ continue;
+ }
+
+ errno = 0;
+ u = canonicalize_file_name(t);
+ if (!u) {
+ if (errno == ENOENT)
+ u = t;
+ else {
+ free(t);
+ if (errno == ENOMEM || !errno)
+ enomem = true;
+
+ continue;
+ }
+ } else
+ free(t);
+
+ l[k++] = u;
+ }
+
+ l[k] = NULL;
+
+ if (enomem)
+ return NULL;
+
+ return l;
+}
+
+char **path_strv_canonicalize_uniq(char **l) {
+ if (strv_isempty(l))
+ return l;
+
+ if (!path_strv_canonicalize(l))
+ return NULL;
+
+ return strv_uniq(l);
+}
+
+char *path_kill_slashes(char *path) {
+ char *f, *t;
+ bool slash = false;
+
+ /* Removes redundant inner and trailing slashes. Modifies the
+ * passed string in-place.
+ *
+ * ///foo///bar/ becomes /foo/bar
+ */
+
+ for (f = path, t = path; *f; f++) {
+
+ if (*f == '/') {
+ slash = true;
+ continue;
+ }
+
+ if (slash) {
+ slash = false;
+ *(t++) = '/';
+ }
+
+ *(t++) = *f;
+ }
+
+ /* Special rule, if we are talking of the root directory, a
+ trailing slash is good */
+
+ if (t == path && slash)
+ *(t++) = '/';
+
+ *t = 0;
+ return path;
+}
+
+char* path_startswith(const char *path, const char *prefix) {
+ assert(path);
+ assert(prefix);
+
+ if ((path[0] == '/') != (prefix[0] == '/'))
+ return NULL;
+
+ for (;;) {
+ size_t a, b;
+
+ path += strspn(path, "/");
+ prefix += strspn(prefix, "/");
+
+ if (*prefix == 0)
+ return (char*) path;
+
+ if (*path == 0)
+ return NULL;
+
+ a = strcspn(path, "/");
+ b = strcspn(prefix, "/");
+
+ if (a != b)
+ return NULL;
+
+ if (memcmp(path, prefix, a) != 0)
+ return NULL;
+
+ path += a;
+ prefix += b;
+ }
+}
+
+bool path_equal(const char *a, const char *b) {
+ assert(a);
+ assert(b);
+
+ if ((a[0] == '/') != (b[0] == '/'))
+ return false;
+
+ for (;;) {
+ size_t j, k;
+
+ a += strspn(a, "/");
+ b += strspn(b, "/");
+
+ if (*a == 0 && *b == 0)
+ return true;
+
+ if (*a == 0 || *b == 0)
+ return false;
+
+ j = strcspn(a, "/");
+ k = strcspn(b, "/");
+
+ if (j != k)
+ return false;
+
+ if (memcmp(a, b, j) != 0)
+ return false;
+
+ a += j;
+ b += k;
+ }
+}
+
+int path_is_mount_point(const char *t, bool allow_symlink) {
+ char *parent;
+ int r;
+ struct file_handle *h;
+ int mount_id, mount_id_parent;
+ struct stat a, b;
+
+ /* We are not actually interested in the file handles, but
+ * name_to_handle_at() also passes us the mount ID, hence use
+ * it but throw the handle away */
+
+ if (path_equal(t, "/"))
+ return 1;
+
+ h = alloca(MAX_HANDLE_SZ);
+ h->handle_bytes = MAX_HANDLE_SZ;
+
+ r = name_to_handle_at(AT_FDCWD, t, h, &mount_id, allow_symlink ? AT_SYMLINK_FOLLOW : 0);
+ if (r < 0) {
+ if (errno == ENOSYS || errno == ENOTSUP)
+ /* This kernel or file system does not support
+ * name_to_handle_at(), hence fallback to the
+ * traditional stat() logic */
+ goto fallback;
+
+ if (errno == ENOENT)
+ return 0;
+
+ return -errno;
+ }
+
+ r = path_get_parent(t, &parent);
+ if (r < 0)
+ return r;
+
+ h->handle_bytes = MAX_HANDLE_SZ;
+ r = name_to_handle_at(AT_FDCWD, parent, h, &mount_id_parent, 0);
+ free(parent);
+
+ if (r < 0) {
+ /* The parent can't do name_to_handle_at() but the
+ * directory we are interested in can? If so, it must
+ * be a mount point */
+ if (errno == ENOTSUP)
+ return 1;
+
+ return -errno;
+ }
+
+ return mount_id != mount_id_parent;
+
+fallback:
+ if (allow_symlink)
+ r = stat(t, &a);
+ else
+ r = lstat(t, &a);
+
+ if (r < 0) {
+ if (errno == ENOENT)
+ return 0;
+
+ return -errno;
+ }
+
+ r = path_get_parent(t, &parent);
+ if (r < 0)
+ return r;
+
+ r = lstat(parent, &b);
+ free(parent);
+
+ if (r < 0)
+ return -errno;
+
+ return a.st_dev != b.st_dev;
+}
+
+int path_is_read_only_fs(const char *path) {
+ struct statvfs st;
+
+ assert(path);
+
+ if (statvfs(path, &st) < 0)
+ return -errno;
+
+ return !!(st.f_flag & ST_RDONLY);
+}
+
+int path_is_os_tree(const char *path) {
+ char *p;
+ int r;
+
+ /* We use /etc/os-release as flag file if something is an OS */
+
+ p = strappenda(path, "/etc/os-release");
+ r = access(p, F_OK);
+
+ return r < 0 ? 0 : 1;
+}
diff --git a/src/shared/path-util.h b/src/shared/path-util.h
new file mode 100644
index 0000000000..d187743769
--- /dev/null
+++ b/src/shared/path-util.h
@@ -0,0 +1,45 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010-2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdbool.h>
+
+#include "macro.h"
+
+bool is_path(const char *p) _pure_;
+char** path_split_and_make_absolute(const char *p);
+char* path_get_file_name(const char *p) _pure_;
+int path_get_parent(const char *path, char **parent);
+bool path_is_absolute(const char *p) _pure_;
+char* path_make_absolute(const char *p, const char *prefix);
+char* path_make_absolute_cwd(const char *p);
+char* path_kill_slashes(char *path);
+char* path_startswith(const char *path, const char *prefix) _pure_;
+bool path_equal(const char *a, const char *b) _pure_;
+
+char** path_strv_make_absolute_cwd(char **l);
+char** path_strv_canonicalize(char **l);
+char** path_strv_canonicalize_uniq(char **l);
+
+int path_is_mount_point(const char *path, bool allow_symlink);
+int path_is_read_only_fs(const char *path);
+int path_is_os_tree(const char *path);
diff --git a/src/shared/polkit.c b/src/shared/polkit.c
new file mode 100644
index 0000000000..cea7074ad3
--- /dev/null
+++ b/src/shared/polkit.c
@@ -0,0 +1,174 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/types.h>
+
+#include <errno.h>
+
+#include "util.h"
+#include "dbus-common.h"
+#include "polkit.h"
+
+int verify_polkit(
+ DBusConnection *c,
+ DBusMessage *request,
+ const char *action,
+ bool interactive,
+ bool *_challenge,
+ DBusError *error) {
+
+
+#ifdef ENABLE_POLKIT
+ DBusMessage *m = NULL, *reply = NULL;
+ const char *unix_process = "unix-process", *pid = "pid", *starttime = "start-time", *cancel_id = "";
+ uint32_t flags = interactive ? 1 : 0;
+ pid_t pid_raw;
+ uint32_t pid_u32;
+ unsigned long long starttime_raw;
+ uint64_t starttime_u64;
+ DBusMessageIter iter_msg, iter_struct, iter_array, iter_dict, iter_variant;
+ int r;
+ dbus_bool_t authorized = FALSE, challenge = FALSE;
+#endif
+ const char *sender;
+ unsigned long ul;
+
+ assert(c);
+ assert(request);
+
+ sender = dbus_message_get_sender(request);
+ if (!sender)
+ return -EINVAL;
+
+ ul = dbus_bus_get_unix_user(c, sender, error);
+ if (ul == (unsigned long) -1)
+ return -EINVAL;
+
+ /* Shortcut things for root, to avoid the PK roundtrip and dependency */
+ if (ul == 0)
+ return 1;
+
+#ifdef ENABLE_POLKIT
+
+ pid_raw = bus_get_unix_process_id(c, sender, error);
+ if (pid_raw == 0)
+ return -EINVAL;
+
+ r = get_starttime_of_pid(pid_raw, &starttime_raw);
+ if (r < 0)
+ return r;
+
+ m = dbus_message_new_method_call(
+ "org.freedesktop.PolicyKit1",
+ "/org/freedesktop/PolicyKit1/Authority",
+ "org.freedesktop.PolicyKit1.Authority",
+ "CheckAuthorization");
+ if (!m)
+ return -ENOMEM;
+
+ dbus_message_iter_init_append(m, &iter_msg);
+
+ pid_u32 = (uint32_t) pid_raw;
+ starttime_u64 = (uint64_t) starttime_raw;
+
+ if (!dbus_message_iter_open_container(&iter_msg, DBUS_TYPE_STRUCT, NULL, &iter_struct) ||
+ !dbus_message_iter_append_basic(&iter_struct, DBUS_TYPE_STRING, &unix_process) ||
+ !dbus_message_iter_open_container(&iter_struct, DBUS_TYPE_ARRAY, "{sv}", &iter_array) ||
+ !dbus_message_iter_open_container(&iter_array, DBUS_TYPE_DICT_ENTRY, NULL, &iter_dict) ||
+ !dbus_message_iter_append_basic(&iter_dict, DBUS_TYPE_STRING, &pid) ||
+ !dbus_message_iter_open_container(&iter_dict, DBUS_TYPE_VARIANT, "u", &iter_variant) ||
+ !dbus_message_iter_append_basic(&iter_variant, DBUS_TYPE_UINT32, &pid_u32) ||
+ !dbus_message_iter_close_container(&iter_dict, &iter_variant) ||
+ !dbus_message_iter_close_container(&iter_array, &iter_dict) ||
+ !dbus_message_iter_open_container(&iter_array, DBUS_TYPE_DICT_ENTRY, NULL, &iter_dict) ||
+ !dbus_message_iter_append_basic(&iter_dict, DBUS_TYPE_STRING, &starttime) ||
+ !dbus_message_iter_open_container(&iter_dict, DBUS_TYPE_VARIANT, "t", &iter_variant) ||
+ !dbus_message_iter_append_basic(&iter_variant, DBUS_TYPE_UINT64, &starttime_u64) ||
+ !dbus_message_iter_close_container(&iter_dict, &iter_variant) ||
+ !dbus_message_iter_close_container(&iter_array, &iter_dict) ||
+ !dbus_message_iter_close_container(&iter_struct, &iter_array) ||
+ !dbus_message_iter_close_container(&iter_msg, &iter_struct) ||
+ !dbus_message_iter_append_basic(&iter_msg, DBUS_TYPE_STRING, &action) ||
+ !dbus_message_iter_open_container(&iter_msg, DBUS_TYPE_ARRAY, "{ss}", &iter_array) ||
+ !dbus_message_iter_close_container(&iter_msg, &iter_array) ||
+ !dbus_message_iter_append_basic(&iter_msg, DBUS_TYPE_UINT32, &flags) ||
+ !dbus_message_iter_append_basic(&iter_msg, DBUS_TYPE_STRING, &cancel_id)) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ reply = dbus_connection_send_with_reply_and_block(c, m, -1, error);
+ if (!reply) {
+
+ /* Treat no PK available as access denied */
+ if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN)) {
+ r = -EACCES;
+ dbus_error_free(error);
+ goto finish;
+ }
+
+ r = -EIO;
+ goto finish;
+ }
+
+ if (!dbus_message_iter_init(reply, &iter_msg) ||
+ dbus_message_iter_get_arg_type(&iter_msg) != DBUS_TYPE_STRUCT) {
+ r = -EIO;
+ goto finish;
+ }
+
+ dbus_message_iter_recurse(&iter_msg, &iter_struct);
+
+ if (dbus_message_iter_get_arg_type(&iter_struct) != DBUS_TYPE_BOOLEAN) {
+ r = -EIO;
+ goto finish;
+ }
+
+ dbus_message_iter_get_basic(&iter_struct, &authorized);
+
+ if (!dbus_message_iter_next(&iter_struct) ||
+ dbus_message_iter_get_arg_type(&iter_struct) != DBUS_TYPE_BOOLEAN) {
+ r = -EIO;
+ goto finish;
+ }
+
+ dbus_message_iter_get_basic(&iter_struct, &challenge);
+
+ if (authorized)
+ r = 1;
+ else if (_challenge) {
+ *_challenge = !!challenge;
+ r = 0;
+ } else
+ r = -EPERM;
+
+finish:
+ if (m)
+ dbus_message_unref(m);
+
+ if (reply)
+ dbus_message_unref(reply);
+
+ return r;
+#else
+ return -EPERM;
+#endif
+}
diff --git a/src/shared/polkit.h b/src/shared/polkit.h
new file mode 100644
index 0000000000..6255d1f617
--- /dev/null
+++ b/src/shared/polkit.h
@@ -0,0 +1,33 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdbool.h>
+#include <dbus/dbus.h>
+
+int verify_polkit(
+ DBusConnection *c,
+ DBusMessage *request,
+ const char *action,
+ bool interactive,
+ bool *challenge,
+ DBusError *error);
diff --git a/src/shared/prioq.c b/src/shared/prioq.c
new file mode 100644
index 0000000000..2d166360aa
--- /dev/null
+++ b/src/shared/prioq.c
@@ -0,0 +1,305 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "util.h"
+#include "prioq.h"
+
+struct prioq_item {
+ void *data;
+ unsigned *idx;
+};
+
+struct Prioq {
+ compare_func_t compare_func;
+ unsigned n_items, n_allocated;
+
+ struct prioq_item *items;
+};
+
+Prioq *prioq_new(compare_func_t compare_func) {
+ Prioq *q;
+
+ q = new0(Prioq, 1);
+ if (!q)
+ return q;
+
+ q->compare_func = compare_func;
+ return q;
+}
+
+void prioq_free(Prioq *q) {
+ if (!q)
+ return;
+
+ free(q->items);
+ free(q);
+}
+
+int prioq_ensure_allocated(Prioq **q, compare_func_t compare_func) {
+ assert(q);
+
+ if (*q)
+ return 0;
+
+ *q = prioq_new(compare_func);
+ if (!*q)
+ return -ENOMEM;
+
+ return 0;
+}
+
+static void swap(Prioq *q, unsigned j, unsigned k) {
+ void *saved_data;
+ unsigned *saved_idx;
+
+ assert(q);
+ assert(j < q->n_items);
+ assert(k < q->n_items);
+
+ assert(!q->items[j].idx || *(q->items[j].idx) == j);
+ assert(!q->items[k].idx || *(q->items[k].idx) == k);
+
+ saved_data = q->items[j].data;
+ saved_idx = q->items[j].idx;
+ q->items[j].data = q->items[k].data;
+ q->items[j].idx = q->items[k].idx;
+ q->items[k].data = saved_data;
+ q->items[k].idx = saved_idx;
+
+ if (q->items[j].idx)
+ *q->items[j].idx = j;
+
+ if (q->items[k].idx)
+ *q->items[k].idx = k;
+}
+
+static unsigned shuffle_up(Prioq *q, unsigned idx) {
+ assert(q);
+
+ while (idx > 0) {
+ unsigned k;
+
+ k = (idx-1)/2;
+
+ if (q->compare_func(q->items[k].data, q->items[idx].data) < 0)
+ break;
+
+ swap(q, idx, k);
+ idx = k;
+ }
+
+ return idx;
+}
+
+static unsigned shuffle_down(Prioq *q, unsigned idx) {
+ assert(q);
+
+ for (;;) {
+ unsigned j, k, s;
+
+ k = (idx+1)*2; /* right child */
+ j = k-1; /* left child */
+
+ if (j >= q->n_items)
+ break;
+
+ if (q->compare_func(q->items[j].data, q->items[idx].data) < 0)
+
+ /* So our left child is smaller than we are, let's
+ * remember this fact */
+ s = j;
+ else
+ s = idx;
+
+ if (k < q->n_items &&
+ q->compare_func(q->items[k].data, q->items[s].data) < 0)
+
+ /* So our right child is smaller than we are, let's
+ * remember this fact */
+ s = k;
+
+ /* s now points to the smallest of the three items */
+
+ if (s == idx)
+ /* No swap necessary, we're done */
+ break;
+
+ swap(q, idx, s);
+ idx = s;
+ }
+
+ return idx;
+}
+
+int prioq_put(Prioq *q, void *data, unsigned *idx) {
+ struct prioq_item *i;
+ unsigned k;
+
+ assert(q);
+
+ if (q->n_items >= q->n_allocated) {
+ unsigned n;
+ struct prioq_item *j;
+
+ n = MAX((q->n_items+1) * 2, 16u);
+ j = realloc(q->items, sizeof(struct prioq_item) * n);
+ if (!j)
+ return -ENOMEM;
+
+ q->items = j;
+ q->n_allocated = n;
+ }
+
+ k = q->n_items++;
+ i = q->items + k;
+ i->data = data;
+ i->idx = idx;
+
+ if (idx)
+ *idx = k;
+
+ shuffle_up(q, k);
+
+ return 0;
+}
+
+static void remove_item(Prioq *q, struct prioq_item *i) {
+ struct prioq_item *l;
+
+ assert(q);
+ assert(i);
+
+ l = q->items + q->n_items - 1;
+
+ if (i == l)
+ /* Last entry, let's just remove it */
+ q->n_items--;
+ else {
+ unsigned k;
+
+ /* Not last entry, let's replace the last entry with
+ * this one, and reshuffle */
+
+ k = i - q->items;
+
+ i->data = l->data;
+ i->idx = l->idx;
+ if (i->idx)
+ *i->idx = k;
+ q->n_items--;
+
+ k = shuffle_down(q, k);
+ shuffle_up(q, k);
+ }
+}
+
+_pure_ static struct prioq_item* find_item(Prioq *q, void *data, unsigned *idx) {
+ struct prioq_item *i;
+
+ assert(q);
+
+ if (idx) {
+ if (*idx > q->n_items)
+ return NULL;
+
+ i = q->items + *idx;
+ if (i->data != data)
+ return NULL;
+
+ return i;
+ } else {
+ for (i = q->items; i < q->items + q->n_items; i++)
+ if (i->data == data)
+ return i;
+ return NULL;
+ }
+}
+
+int prioq_remove(Prioq *q, void *data, unsigned *idx) {
+ struct prioq_item *i;
+
+ if (!q)
+ return 0;
+
+ i = find_item(q, data, idx);
+ if (!i)
+ return 0;
+
+ remove_item(q, i);
+ return 1;
+}
+
+int prioq_reshuffle(Prioq *q, void *data, unsigned *idx) {
+ struct prioq_item *i;
+ unsigned k;
+
+ assert(q);
+
+ i = find_item(q, data, idx);
+ if (!i)
+ return 0;
+
+ k = i - q->items;
+ k = shuffle_down(q, k);
+ shuffle_up(q, k);
+ return 1;
+}
+
+void *prioq_peek(Prioq *q) {
+
+ if (!q)
+ return NULL;
+
+ if (q->n_items <= 0)
+ return NULL;
+
+ return q->items[0].data;
+}
+
+void *prioq_pop(Prioq *q) {
+ void *data;
+
+ if (!q)
+ return NULL;
+
+ if (q->n_items <= 0)
+ return NULL;
+
+ data = q->items[0].data;
+ remove_item(q, q->items);
+ return data;
+}
+
+unsigned prioq_size(Prioq *q) {
+
+ if (!q)
+ return 0;
+
+ return q->n_items;
+
+}
+bool prioq_isempty(Prioq *q) {
+
+ if (!q)
+ return true;
+
+ return q->n_items <= 0;
+}
diff --git a/src/shared/prioq.h b/src/shared/prioq.h
new file mode 100644
index 0000000000..4a206a3e59
--- /dev/null
+++ b/src/shared/prioq.h
@@ -0,0 +1,40 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "hashmap.h"
+
+typedef struct Prioq Prioq;
+
+Prioq *prioq_new(compare_func_t compare);
+void prioq_free(Prioq *q);
+int prioq_ensure_allocated(Prioq **q, compare_func_t compare_func);
+
+int prioq_put(Prioq *q, void *data, unsigned *idx);
+int prioq_remove(Prioq *q, void *data, unsigned *idx);
+int prioq_reshuffle(Prioq *q, void *data, unsigned *idx);
+
+void *prioq_peek(Prioq *q) _pure_;
+void *prioq_pop(Prioq *q);
+
+unsigned prioq_size(Prioq *q) _pure_;
+bool prioq_isempty(Prioq *q) _pure_;
diff --git a/src/shared/ratelimit.c b/src/shared/ratelimit.c
new file mode 100644
index 0000000000..01b62b7b38
--- /dev/null
+++ b/src/shared/ratelimit.c
@@ -0,0 +1,57 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+
+#include "ratelimit.h"
+#include "log.h"
+
+/* Modelled after Linux' lib/ratelimit.c by Dave Young
+ * <hidave.darkstar@gmail.com>, which is licensed GPLv2. */
+
+bool ratelimit_test(RateLimit *r) {
+ usec_t ts;
+
+ assert(r);
+
+ if (r->interval <= 0 || r->burst <= 0)
+ return true;
+
+ ts = now(CLOCK_MONOTONIC);
+
+ if (r->begin <= 0 ||
+ r->begin + r->interval < ts) {
+ r->begin = ts;
+
+ /* Reset counter */
+ r->num = 0;
+ goto good;
+ }
+
+ if (r->num < r->burst)
+ goto good;
+
+ return false;
+
+good:
+ r->num++;
+ return true;
+}
diff --git a/src/shared/ratelimit.h b/src/shared/ratelimit.h
new file mode 100644
index 0000000000..58efca7df1
--- /dev/null
+++ b/src/shared/ratelimit.h
@@ -0,0 +1,57 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "util.h"
+
+typedef struct RateLimit {
+ usec_t interval;
+ usec_t begin;
+ unsigned burst;
+ unsigned num;
+} RateLimit;
+
+#define RATELIMIT_DEFINE(_name, _interval, _burst) \
+ RateLimit _name = { \
+ .interval = (_interval), \
+ .burst = (_burst), \
+ .num = 0, \
+ .begin = 0 \
+ }
+
+#define RATELIMIT_INIT(v, _interval, _burst) \
+ do { \
+ RateLimit *_r = &(v); \
+ _r->interval = (_interval); \
+ _r->burst = (_burst); \
+ _r->num = 0; \
+ _r->begin = 0; \
+ } while (false)
+
+#define RATELIMIT_RESET(v) \
+ do { \
+ RateLimit *_r = &(v); \
+ _r->num = 0; \
+ _r->begin = 0; \
+ } while (false)
+
+bool ratelimit_test(RateLimit *r);
diff --git a/src/shared/replace-var.c b/src/shared/replace-var.c
new file mode 100644
index 0000000000..e11c57a43d
--- /dev/null
+++ b/src/shared/replace-var.c
@@ -0,0 +1,110 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <string.h>
+
+#include "macro.h"
+#include "util.h"
+#include "replace-var.h"
+
+/*
+ * Generic infrastructure for replacing @FOO@ style variables in
+ * strings. Will call a callback for each replacement.
+ */
+
+static int get_variable(const char *b, char **r) {
+ size_t k;
+ char *t;
+
+ assert(b);
+ assert(r);
+
+ if (*b != '@')
+ return 0;
+
+ k = strspn(b + 1, "ABCDEFGHIJKLMNOPQRSTUVWXYZ_");
+ if (k <= 0 || b[k+1] != '@')
+ return 0;
+
+ t = strndup(b + 1, k);
+ if (!t)
+ return -ENOMEM;
+
+ *r = t;
+ return 1;
+}
+
+char *replace_var(const char *text, char *(*lookup)(const char *variable, void*userdata), void *userdata) {
+ char *r, *t;
+ const char *f;
+ size_t l;
+
+ assert(text);
+ assert(lookup);
+
+ l = strlen(text);
+ r = new(char, l+1);
+ if (!r)
+ return NULL;
+
+ f = text;
+ t = r;
+ while (*f) {
+ _cleanup_free_ char *v = NULL, *n = NULL;
+ char *a;
+ int k;
+ size_t skip, d, nl;
+
+ k = get_variable(f, &v);
+ if (k < 0)
+ goto oom;
+ if (k == 0) {
+ *(t++) = *(f++);
+ continue;
+ }
+
+ n = lookup(v, userdata);
+ if (!n)
+ goto oom;
+
+ skip = strlen(v) + 2;
+
+ d = t - r;
+ nl = l - skip + strlen(n);
+ a = realloc(r, nl + 1);
+ if (!a)
+ goto oom;
+
+ l = nl;
+ r = a;
+ t = r + d;
+
+ t = stpcpy(t, n);
+ f += skip;
+ }
+
+ *t = 0;
+ return r;
+
+oom:
+ free(r);
+ return NULL;
+}
diff --git a/src/shared/replace-var.h b/src/shared/replace-var.h
new file mode 100644
index 0000000000..7eaee93a3e
--- /dev/null
+++ b/src/shared/replace-var.h
@@ -0,0 +1,24 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+char *replace_var(const char *text, char *(*lookup)(const char *variable, void*userdata), void *userdata);
diff --git a/src/shared/selinux-util.c b/src/shared/selinux-util.c
new file mode 100644
index 0000000000..ff3375607f
--- /dev/null
+++ b/src/shared/selinux-util.c
@@ -0,0 +1,42 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "selinux-util.h"
+
+#ifdef HAVE_SELINUX
+
+#include <selinux/selinux.h>
+
+static int use_selinux_cached = -1;
+
+bool use_selinux(void) {
+
+ if (use_selinux_cached < 0)
+ use_selinux_cached = is_selinux_enabled() > 0;
+
+ return use_selinux_cached;
+}
+
+void retest_selinux(void) {
+ use_selinux_cached = -1;
+}
+
+#endif
diff --git a/src/shared/selinux-util.h b/src/shared/selinux-util.h
new file mode 100644
index 0000000000..4b81202741
--- /dev/null
+++ b/src/shared/selinux-util.h
@@ -0,0 +1,27 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdbool.h>
+
+bool use_selinux(void);
+void retest_selinux(void);
diff --git a/src/shared/set.c b/src/shared/set.c
new file mode 100644
index 0000000000..c338dc3a44
--- /dev/null
+++ b/src/shared/set.c
@@ -0,0 +1,137 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdlib.h>
+
+#include "set.h"
+#include "hashmap.h"
+
+#define MAKE_SET(h) ((Set*) (h))
+#define MAKE_HASHMAP(s) ((Hashmap*) (s))
+
+/* For now this is not much more than a wrapper around a hashmap */
+
+Set *set_new(hash_func_t hash_func, compare_func_t compare_func) {
+ return MAKE_SET(hashmap_new(hash_func, compare_func));
+}
+
+void set_free(Set* s) {
+ hashmap_free(MAKE_HASHMAP(s));
+}
+
+void set_free_free(Set *s) {
+ hashmap_free_free(MAKE_HASHMAP(s));
+}
+
+int set_ensure_allocated(Set **s, hash_func_t hash_func, compare_func_t compare_func) {
+ return hashmap_ensure_allocated((Hashmap**) s, hash_func, compare_func);
+}
+
+int set_put(Set *s, void *value) {
+ return hashmap_put(MAKE_HASHMAP(s), value, value);
+}
+
+int set_consume(Set *s, void *value) {
+ int r = set_put(s, value);
+ if (r < 0)
+ free(value);
+ return r;
+}
+
+int set_replace(Set *s, void *value) {
+ return hashmap_replace(MAKE_HASHMAP(s), value, value);
+}
+
+void *set_get(Set *s, void *value) {
+ return hashmap_get(MAKE_HASHMAP(s), value);
+}
+
+bool set_contains(Set *s, void *value) {
+ return hashmap_contains(MAKE_HASHMAP(s), value);
+}
+
+void *set_remove(Set *s, void *value) {
+ return hashmap_remove(MAKE_HASHMAP(s), value);
+}
+
+int set_remove_and_put(Set *s, void *old_value, void *new_value) {
+ return hashmap_remove_and_put(MAKE_HASHMAP(s), old_value, new_value, new_value);
+}
+
+unsigned set_size(Set *s) {
+ return hashmap_size(MAKE_HASHMAP(s));
+}
+
+bool set_isempty(Set *s) {
+ return hashmap_isempty(MAKE_HASHMAP(s));
+}
+
+void *set_iterate(Set *s, Iterator *i) {
+ return hashmap_iterate(MAKE_HASHMAP(s), i, NULL);
+}
+
+void *set_iterate_backwards(Set *s, Iterator *i) {
+ return hashmap_iterate_backwards(MAKE_HASHMAP(s), i, NULL);
+}
+
+void *set_iterate_skip(Set *s, void *value, Iterator *i) {
+ return hashmap_iterate_skip(MAKE_HASHMAP(s), value, i);
+}
+
+void *set_steal_first(Set *s) {
+ return hashmap_steal_first(MAKE_HASHMAP(s));
+}
+
+void* set_first(Set *s) {
+ return hashmap_first(MAKE_HASHMAP(s));
+}
+
+void* set_last(Set *s) {
+ return hashmap_last(MAKE_HASHMAP(s));
+}
+
+int set_merge(Set *s, Set *other) {
+ return hashmap_merge(MAKE_HASHMAP(s), MAKE_HASHMAP(other));
+}
+
+void set_move(Set *s, Set *other) {
+ return hashmap_move(MAKE_HASHMAP(s), MAKE_HASHMAP(other));
+}
+
+int set_move_one(Set *s, Set *other, void *value) {
+ return hashmap_move_one(MAKE_HASHMAP(s), MAKE_HASHMAP(other), value);
+}
+
+Set* set_copy(Set *s) {
+ return MAKE_SET(hashmap_copy(MAKE_HASHMAP(s)));
+}
+
+void set_clear(Set *s) {
+ hashmap_clear(MAKE_HASHMAP(s));
+}
+
+void set_clear_free(Set *s) {
+ hashmap_clear_free(MAKE_HASHMAP(s));
+}
+
+char **set_get_strv(Set *s) {
+ return hashmap_get_strv(MAKE_HASHMAP(s));
+}
diff --git a/src/shared/set.h b/src/shared/set.h
new file mode 100644
index 0000000000..e5d46e9a8f
--- /dev/null
+++ b/src/shared/set.h
@@ -0,0 +1,83 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+/* Pretty straightforward set implementation. Internally based on the
+ * hashmap. That means that as a minor optimization a NULL set
+ * object will be treated as empty set for all read
+ * operations. That way it is not necessary to instantiate an object
+ * for each set use. */
+
+#include "hashmap.h"
+
+typedef struct Set Set;
+
+Set *set_new(hash_func_t hash_func, compare_func_t compare_func);
+void set_free(Set* s);
+static inline void set_freep(Set **s) {
+ set_free(*s);
+}
+
+void set_free_free(Set *s);
+static inline void set_free_freep(Set **s) {
+ set_free_free(*s);
+}
+
+Set* set_copy(Set *s);
+int set_ensure_allocated(Set **s, hash_func_t hash_func, compare_func_t compare_func);
+
+int set_put(Set *s, void *value);
+int set_consume(Set *s, void *value);
+int set_replace(Set *s, void *value);
+void *set_get(Set *s, void *value);
+bool set_contains(Set *s, void *value);
+void *set_remove(Set *s, void *value);
+int set_remove_and_put(Set *s, void *old_value, void *new_value);
+
+int set_merge(Set *s, Set *other);
+void set_move(Set *s, Set *other);
+int set_move_one(Set *s, Set *other, void *value);
+
+unsigned set_size(Set *s);
+bool set_isempty(Set *s);
+
+void *set_iterate(Set *s, Iterator *i);
+void *set_iterate_backwards(Set *s, Iterator *i);
+void *set_iterate_skip(Set *s, void *value, Iterator *i);
+
+void set_clear(Set *s);
+void set_clear_free(Set *s);
+
+void *set_steal_first(Set *s);
+void* set_first(Set *s);
+void* set_last(Set *s);
+
+char **set_get_strv(Set *s);
+
+#define SET_FOREACH(e, s, i) \
+ for ((i) = ITERATOR_FIRST, (e) = set_iterate((s), &(i)); (e); (e) = set_iterate((s), &(i)))
+
+#define SET_FOREACH_BACKWARDS(e, s, i) \
+ for ((i) = ITERATOR_LAST, (e) = set_iterate_backwards((s), &(i)); (e); (e) = set_iterate_backwards((s), &(i)))
+
+#define _cleanup_set_free_ _cleanup_(set_freep)
+#define _cleanup_set_free_free_ _cleanup_(set_free_freep)
diff --git a/src/shared/sleep-config.c b/src/shared/sleep-config.c
new file mode 100644
index 0000000000..cd3238b405
--- /dev/null
+++ b/src/shared/sleep-config.c
@@ -0,0 +1,179 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Zbigniew Jędrzejewski-Szmek
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+
+#include "conf-parser.h"
+#include "sleep-config.h"
+#include "fileio.h"
+#include "log.h"
+#include "strv.h"
+#include "util.h"
+
+int parse_sleep_config(const char *verb, char ***modes, char ***states) {
+ _cleanup_strv_free_ char
+ **suspend_mode = NULL, **suspend_state = NULL,
+ **hibernate_mode = NULL, **hibernate_state = NULL,
+ **hybrid_mode = NULL, **hybrid_state = NULL;
+
+ const ConfigTableItem items[] = {
+ { "Sleep", "SuspendMode", config_parse_strv, 0, &suspend_mode },
+ { "Sleep", "SuspendState", config_parse_strv, 0, &suspend_state },
+ { "Sleep", "HibernateMode", config_parse_strv, 0, &hibernate_mode },
+ { "Sleep", "HibernateState", config_parse_strv, 0, &hibernate_state },
+ { "Sleep", "HybridSleepMode", config_parse_strv, 0, &hybrid_mode },
+ { "Sleep", "HybridSleepState", config_parse_strv, 0, &hybrid_state },
+ {}};
+
+ int r;
+ FILE _cleanup_fclose_ *f;
+
+ f = fopen(PKGSYSCONFDIR "/sleep.conf", "re");
+ if (!f)
+ log_full(errno == ENOENT ? LOG_DEBUG: LOG_WARNING,
+ "Failed to open configuration file " PKGSYSCONFDIR "/sleep.conf: %m");
+ else {
+ r = config_parse(NULL, PKGSYSCONFDIR "/sleep.conf", f, "Sleep\0",
+ config_item_table_lookup, (void*) items, false, false, NULL);
+ if (r < 0)
+ log_warning("Failed to parse configuration file: %s", strerror(-r));
+ }
+
+ if (streq(verb, "suspend")) {
+ /* empty by default */
+ *modes = suspend_mode;
+
+ if (suspend_state)
+ *states = suspend_state;
+ else
+ *states = strv_split_nulstr("mem\0standby\0freeze\0");
+
+ suspend_mode = suspend_state = NULL;
+ } else if (streq(verb, "hibernate")) {
+ if (hibernate_mode)
+ *modes = hibernate_mode;
+ else
+ *modes = strv_split_nulstr("platform\0shutdown\0");
+
+ if (hibernate_state)
+ *states = hibernate_state;
+ else
+ *states = strv_split_nulstr("disk\0");
+
+ hibernate_mode = hibernate_state = NULL;
+ } else if (streq(verb, "hybrid-sleep")) {
+ if (hybrid_mode)
+ *modes = hybrid_mode;
+ else
+ *modes = strv_split_nulstr("suspend\0platform\0shutdown\0");
+
+ if (hybrid_state)
+ *states = hybrid_state;
+ else
+ *states = strv_split_nulstr("disk\0");
+
+ hybrid_mode = hybrid_state = NULL;
+ } else
+ assert_not_reached("what verb");
+
+ if (!modes || !states) {
+ strv_free(*modes);
+ strv_free(*states);
+ return log_oom();
+ }
+
+ return 0;
+}
+
+int can_sleep_state(char **types) {
+ char *w, *state, **type;
+ int r;
+ _cleanup_free_ char *p = NULL;
+
+ if (strv_isempty(types))
+ return true;
+
+ /* If /sys is read-only we cannot sleep */
+ if (access("/sys/power/state", W_OK) < 0)
+ return false;
+
+ r = read_one_line_file("/sys/power/state", &p);
+ if (r < 0)
+ return false;
+
+ STRV_FOREACH(type, types) {
+ size_t l, k;
+
+ k = strlen(*type);
+ FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
+ if (l == k && memcmp(w, *type, l) == 0)
+ return true;
+ }
+
+ return false;
+}
+
+int can_sleep_disk(char **types) {
+ char *w, *state, **type;
+ int r;
+ _cleanup_free_ char *p = NULL;
+
+ if (strv_isempty(types))
+ return true;
+
+ /* If /sys is read-only we cannot sleep */
+ if (access("/sys/power/disk", W_OK) < 0)
+ return false;
+
+ r = read_one_line_file("/sys/power/disk", &p);
+ if (r < 0)
+ return false;
+
+ STRV_FOREACH(type, types) {
+ size_t l, k;
+
+ k = strlen(*type);
+ FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
+ if (l == k && memcmp(w, *type, l) == 0)
+ return true;
+
+ if (l == k + 2 && w[0] == '[' && memcmp(w + 1, *type, l - 2) == 0 && w[l-1] == ']')
+ return true;
+ }
+ }
+
+ return false;
+}
+
+int can_sleep(const char *verb) {
+ _cleanup_strv_free_ char **modes = NULL, **states = NULL;
+ int r;
+
+ assert(streq(verb, "suspend") ||
+ streq(verb, "hibernate") ||
+ streq(verb, "hybrid-sleep"));
+
+ r = parse_sleep_config(verb, &modes, &states);
+ if (r < 0)
+ return false;
+
+ return can_sleep_state(states) && can_sleep_disk(modes);
+}
diff --git a/src/shared/sleep-config.h b/src/shared/sleep-config.h
new file mode 100644
index 0000000000..51d2dec7b4
--- /dev/null
+++ b/src/shared/sleep-config.h
@@ -0,0 +1,26 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Zbigniew Jędrzejewski-Szmek
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+int parse_sleep_config(const char *verb, char ***modes, char ***states);
+
+int can_sleep(const char *verb);
+int can_sleep_disk(char **types);
+int can_sleep_state(char **types);
diff --git a/src/shared/socket-label.c b/src/shared/socket-label.c
new file mode 100644
index 0000000000..ff212de825
--- /dev/null
+++ b/src/shared/socket-label.c
@@ -0,0 +1,143 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <arpa/inet.h>
+#include <stdio.h>
+#include <net/if.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <stddef.h>
+#include <sys/ioctl.h>
+
+#include "macro.h"
+#include "util.h"
+#include "mkdir.h"
+#include "socket-util.h"
+#include "missing.h"
+#include "label.h"
+
+int socket_address_listen(
+ const SocketAddress *a,
+ int backlog,
+ SocketAddressBindIPv6Only only,
+ const char *bind_to_device,
+ bool free_bind,
+ bool transparent,
+ mode_t directory_mode,
+ mode_t socket_mode,
+ const char *label,
+ int *ret) {
+
+ int r, fd, one;
+ assert(a);
+ assert(ret);
+
+ if ((r = socket_address_verify(a)) < 0)
+ return r;
+
+ if (socket_address_family(a) == AF_INET6 && !socket_ipv6_is_supported())
+ return -EAFNOSUPPORT;
+
+ r = label_socket_set(label);
+ if (r < 0)
+ return r;
+
+ fd = socket(socket_address_family(a), a->type | SOCK_NONBLOCK | SOCK_CLOEXEC, a->protocol);
+ r = fd < 0 ? -errno : 0;
+
+ label_socket_clear();
+
+ if (r < 0)
+ return r;
+
+ if (socket_address_family(a) == AF_INET6 && only != SOCKET_ADDRESS_DEFAULT) {
+ int flag = only == SOCKET_ADDRESS_IPV6_ONLY;
+
+ if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &flag, sizeof(flag)) < 0)
+ goto fail;
+ }
+
+ if (socket_address_family(a) == AF_INET || socket_address_family(a) == AF_INET6) {
+ if (bind_to_device)
+ if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, bind_to_device, strlen(bind_to_device)+1) < 0)
+ goto fail;
+
+ if (free_bind) {
+ one = 1;
+ if (setsockopt(fd, IPPROTO_IP, IP_FREEBIND, &one, sizeof(one)) < 0)
+ log_warning("IP_FREEBIND failed: %m");
+ }
+
+ if (transparent) {
+ one = 1;
+ if (setsockopt(fd, IPPROTO_IP, IP_TRANSPARENT, &one, sizeof(one)) < 0)
+ log_warning("IP_TRANSPARENT failed: %m");
+ }
+ }
+
+ one = 1;
+ if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0)
+ goto fail;
+
+ if (socket_address_family(a) == AF_UNIX && a->sockaddr.un.sun_path[0] != 0) {
+ mode_t old_mask;
+
+ /* Create parents */
+ mkdir_parents_label(a->sockaddr.un.sun_path, directory_mode);
+
+ /* Enforce the right access mode for the socket*/
+ old_mask = umask(~ socket_mode);
+
+ /* Include the original umask in our mask */
+ umask(~socket_mode | old_mask);
+
+ r = label_bind(fd, &a->sockaddr.sa, a->size);
+
+ if (r < 0 && errno == EADDRINUSE) {
+ /* Unlink and try again */
+ unlink(a->sockaddr.un.sun_path);
+ r = bind(fd, &a->sockaddr.sa, a->size);
+ }
+
+ umask(old_mask);
+ } else
+ r = bind(fd, &a->sockaddr.sa, a->size);
+
+ if (r < 0)
+ goto fail;
+
+ if (socket_address_can_accept(a))
+ if (listen(fd, backlog) < 0)
+ goto fail;
+
+ *ret = fd;
+ return 0;
+
+fail:
+ r = -errno;
+ close_nointr_nofail(fd);
+ return r;
+}
diff --git a/src/shared/socket-util.c b/src/shared/socket-util.c
new file mode 100644
index 0000000000..c583d3dfea
--- /dev/null
+++ b/src/shared/socket-util.c
@@ -0,0 +1,635 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <arpa/inet.h>
+#include <stdio.h>
+#include <net/if.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <stddef.h>
+#include <sys/ioctl.h>
+
+#include "macro.h"
+#include "util.h"
+#include "mkdir.h"
+#include "path-util.h"
+#include "socket-util.h"
+#include "missing.h"
+#include "fileio.h"
+
+int socket_address_parse(SocketAddress *a, const char *s) {
+ int r;
+ char *e, *n;
+ unsigned u;
+
+ assert(a);
+ assert(s);
+
+ zero(*a);
+ a->type = SOCK_STREAM;
+
+ if (*s == '[') {
+ /* IPv6 in [x:.....:z]:p notation */
+
+ if (!socket_ipv6_is_supported()) {
+ log_warning("Binding to IPv6 address not available since kernel does not support IPv6.");
+ return -EAFNOSUPPORT;
+ }
+
+ if (!(e = strchr(s+1, ']')))
+ return -EINVAL;
+
+ if (!(n = strndup(s+1, e-s-1)))
+ return -ENOMEM;
+
+ errno = 0;
+ if (inet_pton(AF_INET6, n, &a->sockaddr.in6.sin6_addr) <= 0) {
+ free(n);
+ return errno > 0 ? -errno : -EINVAL;
+ }
+
+ free(n);
+
+ e++;
+ if (*e != ':')
+ return -EINVAL;
+
+ e++;
+ if ((r = safe_atou(e, &u)) < 0)
+ return r;
+
+ if (u <= 0 || u > 0xFFFF)
+ return -EINVAL;
+
+ a->sockaddr.in6.sin6_family = AF_INET6;
+ a->sockaddr.in6.sin6_port = htons((uint16_t) u);
+ a->size = sizeof(struct sockaddr_in6);
+
+ } else if (*s == '/') {
+ /* AF_UNIX socket */
+
+ size_t l;
+
+ l = strlen(s);
+ if (l >= sizeof(a->sockaddr.un.sun_path))
+ return -EINVAL;
+
+ a->sockaddr.un.sun_family = AF_UNIX;
+ memcpy(a->sockaddr.un.sun_path, s, l);
+ a->size = offsetof(struct sockaddr_un, sun_path) + l + 1;
+
+ } else if (*s == '@') {
+ /* Abstract AF_UNIX socket */
+ size_t l;
+
+ l = strlen(s+1);
+ if (l >= sizeof(a->sockaddr.un.sun_path) - 1)
+ return -EINVAL;
+
+ a->sockaddr.un.sun_family = AF_UNIX;
+ memcpy(a->sockaddr.un.sun_path+1, s+1, l);
+ a->size = offsetof(struct sockaddr_un, sun_path) + 1 + l;
+
+ } else {
+
+ if ((e = strchr(s, ':'))) {
+
+ if ((r = safe_atou(e+1, &u)) < 0)
+ return r;
+
+ if (u <= 0 || u > 0xFFFF)
+ return -EINVAL;
+
+ if (!(n = strndup(s, e-s)))
+ return -ENOMEM;
+
+ /* IPv4 in w.x.y.z:p notation? */
+ if ((r = inet_pton(AF_INET, n, &a->sockaddr.in4.sin_addr)) < 0) {
+ free(n);
+ return -errno;
+ }
+
+ if (r > 0) {
+ /* Gotcha, it's a traditional IPv4 address */
+ free(n);
+
+ a->sockaddr.in4.sin_family = AF_INET;
+ a->sockaddr.in4.sin_port = htons((uint16_t) u);
+ a->size = sizeof(struct sockaddr_in);
+ } else {
+ unsigned idx;
+
+ if (strlen(n) > IF_NAMESIZE-1) {
+ free(n);
+ return -EINVAL;
+ }
+
+ /* Uh, our last resort, an interface name */
+ idx = if_nametoindex(n);
+ free(n);
+
+ if (idx == 0)
+ return -EINVAL;
+
+ if (!socket_ipv6_is_supported()) {
+ log_warning("Binding to interface is not available since kernel does not support IPv6.");
+ return -EAFNOSUPPORT;
+ }
+
+ a->sockaddr.in6.sin6_family = AF_INET6;
+ a->sockaddr.in6.sin6_port = htons((uint16_t) u);
+ a->sockaddr.in6.sin6_scope_id = idx;
+ a->sockaddr.in6.sin6_addr = in6addr_any;
+ a->size = sizeof(struct sockaddr_in6);
+ }
+ } else {
+
+ /* Just a port */
+ r = safe_atou(s, &u);
+ if (r < 0)
+ return r;
+
+ if (u <= 0 || u > 0xFFFF)
+ return -EINVAL;
+
+ if (socket_ipv6_is_supported()) {
+ a->sockaddr.in6.sin6_family = AF_INET6;
+ a->sockaddr.in6.sin6_port = htons((uint16_t) u);
+ a->sockaddr.in6.sin6_addr = in6addr_any;
+ a->size = sizeof(struct sockaddr_in6);
+ } else {
+ a->sockaddr.in4.sin_family = AF_INET;
+ a->sockaddr.in4.sin_port = htons((uint16_t) u);
+ a->sockaddr.in4.sin_addr.s_addr = INADDR_ANY;
+ a->size = sizeof(struct sockaddr_in);
+ }
+ }
+ }
+
+ return 0;
+}
+
+int socket_address_parse_netlink(SocketAddress *a, const char *s) {
+ int family;
+ unsigned group = 0;
+ _cleanup_free_ char *sfamily = NULL;
+ assert(a);
+ assert(s);
+
+ zero(*a);
+ a->type = SOCK_RAW;
+
+ errno = 0;
+ if (sscanf(s, "%ms %u", &sfamily, &group) < 1)
+ return errno > 0 ? -errno : -EINVAL;
+
+ family = netlink_family_from_string(sfamily);
+ if (family < 0)
+ return -EINVAL;
+
+ a->sockaddr.nl.nl_family = AF_NETLINK;
+ a->sockaddr.nl.nl_groups = group;
+
+ a->type = SOCK_RAW;
+ a->size = sizeof(struct sockaddr_nl);
+ a->protocol = family;
+
+ return 0;
+}
+
+int socket_address_verify(const SocketAddress *a) {
+ assert(a);
+
+ switch (socket_address_family(a)) {
+
+ case AF_INET:
+ if (a->size != sizeof(struct sockaddr_in))
+ return -EINVAL;
+
+ if (a->sockaddr.in4.sin_port == 0)
+ return -EINVAL;
+
+ if (a->type != SOCK_STREAM && a->type != SOCK_DGRAM)
+ return -EINVAL;
+
+ return 0;
+
+ case AF_INET6:
+ if (a->size != sizeof(struct sockaddr_in6))
+ return -EINVAL;
+
+ if (a->sockaddr.in6.sin6_port == 0)
+ return -EINVAL;
+
+ if (a->type != SOCK_STREAM && a->type != SOCK_DGRAM)
+ return -EINVAL;
+
+ return 0;
+
+ case AF_UNIX:
+ if (a->size < offsetof(struct sockaddr_un, sun_path))
+ return -EINVAL;
+
+ if (a->size > offsetof(struct sockaddr_un, sun_path)) {
+
+ if (a->sockaddr.un.sun_path[0] != 0) {
+ char *e;
+
+ /* path */
+ if (!(e = memchr(a->sockaddr.un.sun_path, 0, sizeof(a->sockaddr.un.sun_path))))
+ return -EINVAL;
+
+ if (a->size != offsetof(struct sockaddr_un, sun_path) + (e - a->sockaddr.un.sun_path) + 1)
+ return -EINVAL;
+ }
+ }
+
+ if (a->type != SOCK_STREAM && a->type != SOCK_DGRAM && a->type != SOCK_SEQPACKET)
+ return -EINVAL;
+
+ return 0;
+
+ case AF_NETLINK:
+
+ if (a->size != sizeof(struct sockaddr_nl))
+ return -EINVAL;
+
+ if (a->type != SOCK_RAW && a->type != SOCK_DGRAM)
+ return -EINVAL;
+
+ return 0;
+
+ default:
+ return -EAFNOSUPPORT;
+ }
+}
+
+int socket_address_print(const SocketAddress *a, char **p) {
+ int r;
+ assert(a);
+ assert(p);
+
+ if ((r = socket_address_verify(a)) < 0)
+ return r;
+
+ switch (socket_address_family(a)) {
+
+ case AF_INET: {
+ char *ret;
+
+ if (!(ret = new(char, INET_ADDRSTRLEN+1+5+1)))
+ return -ENOMEM;
+
+ if (!inet_ntop(AF_INET, &a->sockaddr.in4.sin_addr, ret, INET_ADDRSTRLEN)) {
+ free(ret);
+ return -errno;
+ }
+
+ sprintf(strchr(ret, 0), ":%u", ntohs(a->sockaddr.in4.sin_port));
+ *p = ret;
+ return 0;
+ }
+
+ case AF_INET6: {
+ char *ret;
+
+ if (!(ret = new(char, 1+INET6_ADDRSTRLEN+2+5+1)))
+ return -ENOMEM;
+
+ ret[0] = '[';
+ if (!inet_ntop(AF_INET6, &a->sockaddr.in6.sin6_addr, ret+1, INET6_ADDRSTRLEN)) {
+ free(ret);
+ return -errno;
+ }
+
+ sprintf(strchr(ret, 0), "]:%u", ntohs(a->sockaddr.in6.sin6_port));
+ *p = ret;
+ return 0;
+ }
+
+ case AF_UNIX: {
+ char *ret;
+
+ if (a->size <= offsetof(struct sockaddr_un, sun_path)) {
+
+ if (!(ret = strdup("<unnamed>")))
+ return -ENOMEM;
+
+ } else if (a->sockaddr.un.sun_path[0] == 0) {
+ /* abstract */
+
+ /* FIXME: We assume we can print the
+ * socket path here and that it hasn't
+ * more than one NUL byte. That is
+ * actually an invalid assumption */
+
+ if (!(ret = new(char, sizeof(a->sockaddr.un.sun_path)+1)))
+ return -ENOMEM;
+
+ ret[0] = '@';
+ memcpy(ret+1, a->sockaddr.un.sun_path+1, sizeof(a->sockaddr.un.sun_path)-1);
+ ret[sizeof(a->sockaddr.un.sun_path)] = 0;
+
+ } else {
+
+ if (!(ret = strdup(a->sockaddr.un.sun_path)))
+ return -ENOMEM;
+ }
+
+ *p = ret;
+ return 0;
+ }
+
+ case AF_NETLINK: {
+ _cleanup_free_ char *sfamily = NULL;
+
+ r = netlink_family_to_string_alloc(a->protocol, &sfamily);
+ if (r < 0)
+ return r;
+ r = asprintf(p, "%s %u", sfamily, a->sockaddr.nl.nl_groups);
+ if (r < 0)
+ return -ENOMEM;
+
+ return 0;
+ }
+
+ default:
+ return -EINVAL;
+ }
+}
+
+bool socket_address_can_accept(const SocketAddress *a) {
+ assert(a);
+
+ return
+ a->type == SOCK_STREAM ||
+ a->type == SOCK_SEQPACKET;
+}
+
+bool socket_address_equal(const SocketAddress *a, const SocketAddress *b) {
+ assert(a);
+ assert(b);
+
+ /* Invalid addresses are unequal to all */
+ if (socket_address_verify(a) < 0 ||
+ socket_address_verify(b) < 0)
+ return false;
+
+ if (a->type != b->type)
+ return false;
+
+ if (a->size != b->size)
+ return false;
+
+ if (socket_address_family(a) != socket_address_family(b))
+ return false;
+
+ switch (socket_address_family(a)) {
+
+ case AF_INET:
+ if (a->sockaddr.in4.sin_addr.s_addr != b->sockaddr.in4.sin_addr.s_addr)
+ return false;
+
+ if (a->sockaddr.in4.sin_port != b->sockaddr.in4.sin_port)
+ return false;
+
+ break;
+
+ case AF_INET6:
+ if (memcmp(&a->sockaddr.in6.sin6_addr, &b->sockaddr.in6.sin6_addr, sizeof(a->sockaddr.in6.sin6_addr)) != 0)
+ return false;
+
+ if (a->sockaddr.in6.sin6_port != b->sockaddr.in6.sin6_port)
+ return false;
+
+ break;
+
+ case AF_UNIX:
+
+ if ((a->sockaddr.un.sun_path[0] == 0) != (b->sockaddr.un.sun_path[0] == 0))
+ return false;
+
+ if (a->sockaddr.un.sun_path[0]) {
+ if (!strneq(a->sockaddr.un.sun_path, b->sockaddr.un.sun_path, sizeof(a->sockaddr.un.sun_path)))
+ return false;
+ } else {
+ if (memcmp(a->sockaddr.un.sun_path, b->sockaddr.un.sun_path, a->size) != 0)
+ return false;
+ }
+
+ break;
+
+ case AF_NETLINK:
+
+ if (a->protocol != b->protocol)
+ return false;
+
+ if (a->sockaddr.nl.nl_groups != b->sockaddr.nl.nl_groups)
+ return false;
+
+ break;
+
+ default:
+ /* Cannot compare, so we assume the addresses are different */
+ return false;
+ }
+
+ return true;
+}
+
+bool socket_address_is(const SocketAddress *a, const char *s, int type) {
+ struct SocketAddress b;
+
+ assert(a);
+ assert(s);
+
+ if (socket_address_parse(&b, s) < 0)
+ return false;
+
+ b.type = type;
+
+ return socket_address_equal(a, &b);
+}
+
+bool socket_address_is_netlink(const SocketAddress *a, const char *s) {
+ struct SocketAddress b;
+
+ assert(a);
+ assert(s);
+
+ if (socket_address_parse_netlink(&b, s) < 0)
+ return false;
+
+ return socket_address_equal(a, &b);
+}
+
+bool socket_address_needs_mount(const SocketAddress *a, const char *prefix) {
+ assert(a);
+
+ if (socket_address_family(a) != AF_UNIX)
+ return false;
+
+ if (a->sockaddr.un.sun_path[0] == 0)
+ return false;
+
+ return path_startswith(a->sockaddr.un.sun_path, prefix);
+}
+
+bool socket_ipv6_is_supported(void) {
+ char *l = 0;
+ bool enabled;
+
+ if (access("/sys/module/ipv6", F_OK) != 0)
+ return 0;
+
+ /* If we can't check "disable" parameter, assume enabled */
+ if (read_one_line_file("/sys/module/ipv6/parameters/disable", &l) < 0)
+ return 1;
+
+ /* If module was loaded with disable=1 no IPv6 available */
+ enabled = l[0] == '0';
+ free(l);
+
+ return enabled;
+}
+
+bool socket_address_matches_fd(const SocketAddress *a, int fd) {
+ union sockaddr_union sa;
+ socklen_t salen = sizeof(sa), solen;
+ int protocol, type;
+
+ assert(a);
+ assert(fd >= 0);
+
+ if (getsockname(fd, &sa.sa, &salen) < 0)
+ return false;
+
+ if (sa.sa.sa_family != a->sockaddr.sa.sa_family)
+ return false;
+
+ solen = sizeof(type);
+ if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &type, &solen) < 0)
+ return false;
+
+ if (type != a->type)
+ return false;
+
+ if (a->protocol != 0) {
+ solen = sizeof(protocol);
+ if (getsockopt(fd, SOL_SOCKET, SO_PROTOCOL, &protocol, &solen) < 0)
+ return false;
+
+ if (protocol != a->protocol)
+ return false;
+ }
+
+ switch (sa.sa.sa_family) {
+
+ case AF_INET:
+ return sa.in4.sin_port == a->sockaddr.in4.sin_port &&
+ sa.in4.sin_addr.s_addr == a->sockaddr.in4.sin_addr.s_addr;
+
+ case AF_INET6:
+ return sa.in6.sin6_port == a->sockaddr.in6.sin6_port &&
+ memcmp(&sa.in6.sin6_addr, &a->sockaddr.in6.sin6_addr, sizeof(struct in6_addr)) == 0;
+
+ case AF_UNIX:
+ return salen == a->size &&
+ memcmp(sa.un.sun_path, a->sockaddr.un.sun_path, salen - offsetof(struct sockaddr_un, sun_path)) == 0;
+
+ }
+
+ return false;
+}
+
+int make_socket_fd(const char* address, int flags) {
+ SocketAddress a;
+ int fd, r;
+ _cleanup_free_ char *p = NULL;
+
+ r = socket_address_parse(&a, address);
+ if (r < 0) {
+ log_error("failed to parse socket: %s", strerror(-r));
+ return r;
+ }
+
+ fd = socket(socket_address_family(&a), flags, 0);
+ if (fd < 0) {
+ log_error("socket(): %m");
+ return -errno;
+ }
+
+ r = socket_address_print(&a, &p);
+ if (r < 0) {
+ log_error("socket_address_print(): %s", strerror(-r));
+ return r;
+ }
+ log_info("Listening on %s", p);
+
+ r = bind(fd, &a.sockaddr.sa, a.size);
+ if (r < 0) {
+ log_error("bind to %s: %m", address);
+ return -errno;
+ }
+
+ r = listen(fd, SOMAXCONN);
+ if (r < 0) {
+ log_error("listen on %s: %m", address);
+ return -errno;
+ }
+
+ return fd;
+}
+
+static const char* const netlink_family_table[] = {
+ [NETLINK_ROUTE] = "route",
+ [NETLINK_FIREWALL] = "firewall",
+ [NETLINK_INET_DIAG] = "inet-diag",
+ [NETLINK_NFLOG] = "nflog",
+ [NETLINK_XFRM] = "xfrm",
+ [NETLINK_SELINUX] = "selinux",
+ [NETLINK_ISCSI] = "iscsi",
+ [NETLINK_AUDIT] = "audit",
+ [NETLINK_FIB_LOOKUP] = "fib-lookup",
+ [NETLINK_CONNECTOR] = "connector",
+ [NETLINK_NETFILTER] = "netfilter",
+ [NETLINK_IP6_FW] = "ip6-fw",
+ [NETLINK_DNRTMSG] = "dnrtmsg",
+ [NETLINK_KOBJECT_UEVENT] = "kobject-uevent",
+ [NETLINK_GENERIC] = "generic",
+ [NETLINK_SCSITRANSPORT] = "scsitransport",
+ [NETLINK_ECRYPTFS] = "ecryptfs"
+};
+
+DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(netlink_family, int, INT_MAX);
+
+static const char* const socket_address_bind_ipv6_only_table[_SOCKET_ADDRESS_BIND_IPV6_ONLY_MAX] = {
+ [SOCKET_ADDRESS_DEFAULT] = "default",
+ [SOCKET_ADDRESS_BOTH] = "both",
+ [SOCKET_ADDRESS_IPV6_ONLY] = "ipv6-only"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(socket_address_bind_ipv6_only, SocketAddressBindIPv6Only);
diff --git a/src/shared/socket-util.h b/src/shared/socket-util.h
new file mode 100644
index 0000000000..7829a337fc
--- /dev/null
+++ b/src/shared/socket-util.h
@@ -0,0 +1,103 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <sys/un.h>
+#include <net/if.h>
+#include <asm/types.h>
+#include <linux/netlink.h>
+
+#include "macro.h"
+#include "util.h"
+
+union sockaddr_union {
+ struct sockaddr sa;
+ struct sockaddr_in in4;
+ struct sockaddr_in6 in6;
+ struct sockaddr_un un;
+ struct sockaddr_nl nl;
+ struct sockaddr_storage storage;
+};
+
+typedef struct SocketAddress {
+ union sockaddr_union sockaddr;
+
+ /* We store the size here explicitly due to the weird
+ * sockaddr_un semantics for abstract sockets */
+ socklen_t size;
+
+ /* Socket type, i.e. SOCK_STREAM, SOCK_DGRAM, ... */
+ int type;
+
+ /* Socket protocol, IPPROTO_xxx, usually 0, except for netlink */
+ int protocol;
+} SocketAddress;
+
+typedef enum SocketAddressBindIPv6Only {
+ SOCKET_ADDRESS_DEFAULT,
+ SOCKET_ADDRESS_BOTH,
+ SOCKET_ADDRESS_IPV6_ONLY,
+ _SOCKET_ADDRESS_BIND_IPV6_ONLY_MAX,
+ _SOCKET_ADDRESS_BIND_IPV6_ONLY_INVALID = -1
+} SocketAddressBindIPv6Only;
+
+#define socket_address_family(a) ((a)->sockaddr.sa.sa_family)
+
+int socket_address_parse(SocketAddress *a, const char *s);
+int socket_address_parse_netlink(SocketAddress *a, const char *s);
+int socket_address_print(const SocketAddress *a, char **p);
+int socket_address_verify(const SocketAddress *a) _pure_;
+
+bool socket_address_can_accept(const SocketAddress *a) _pure_;
+
+int socket_address_listen(
+ const SocketAddress *a,
+ int backlog,
+ SocketAddressBindIPv6Only only,
+ const char *bind_to_device,
+ bool free_bind,
+ bool transparent,
+ mode_t directory_mode,
+ mode_t socket_mode,
+ const char *label,
+ int *ret);
+
+bool socket_address_is(const SocketAddress *a, const char *s, int type);
+bool socket_address_is_netlink(const SocketAddress *a, const char *s);
+
+bool socket_address_matches_fd(const SocketAddress *a, int fd);
+
+int make_socket_fd(const char* address, int flags);
+
+bool socket_address_equal(const SocketAddress *a, const SocketAddress *b) _pure_;
+
+bool socket_address_needs_mount(const SocketAddress *a, const char *prefix);
+
+const char* socket_address_bind_ipv6_only_to_string(SocketAddressBindIPv6Only b) _const_;
+SocketAddressBindIPv6Only socket_address_bind_ipv6_only_from_string(const char *s) _pure_;
+
+int netlink_family_to_string_alloc(int b, char **s);
+int netlink_family_from_string(const char *s);
+
+bool socket_ipv6_is_supported(void);
diff --git a/src/shared/sparse-endian.h b/src/shared/sparse-endian.h
new file mode 100644
index 0000000000..eb4dbf3615
--- /dev/null
+++ b/src/shared/sparse-endian.h
@@ -0,0 +1,87 @@
+/* Copyright (c) 2012 Josh Triplett <josh@joshtriplett.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+#ifndef SPARSE_ENDIAN_H
+#define SPARSE_ENDIAN_H
+
+#include <endian.h>
+#include <stdint.h>
+
+#ifdef __CHECKER__
+#define __bitwise __attribute__((bitwise))
+#define __force __attribute__((force))
+#else
+#define __bitwise
+#define __force
+#endif
+
+typedef uint16_t __bitwise le16_t;
+typedef uint16_t __bitwise be16_t;
+typedef uint32_t __bitwise le32_t;
+typedef uint32_t __bitwise be32_t;
+typedef uint64_t __bitwise le64_t;
+typedef uint64_t __bitwise be64_t;
+
+#undef htobe16
+#undef htole16
+#undef be16toh
+#undef le16toh
+#undef htobe32
+#undef htole32
+#undef be32toh
+#undef le32toh
+#undef htobe64
+#undef htole64
+#undef be64toh
+#undef le64toh
+
+#if __BYTE_ORDER == __LITTLE_ENDIAN
+#define bswap_16_on_le(x) __bswap_16(x)
+#define bswap_32_on_le(x) __bswap_32(x)
+#define bswap_64_on_le(x) __bswap_64(x)
+#define bswap_16_on_be(x) (x)
+#define bswap_32_on_be(x) (x)
+#define bswap_64_on_be(x) (x)
+#elif __BYTE_ORDER == __BIG_ENDIAN
+#define bswap_16_on_le(x) (x)
+#define bswap_32_on_le(x) (x)
+#define bswap_64_on_le(x) (x)
+#define bswap_16_on_be(x) __bswap_16(x)
+#define bswap_32_on_be(x) __bswap_32(x)
+#define bswap_64_on_be(x) __bswap_64(x)
+#endif
+
+static inline le16_t htole16(uint16_t value) { return (le16_t __force) bswap_16_on_be(value); }
+static inline le32_t htole32(uint32_t value) { return (le32_t __force) bswap_32_on_be(value); }
+static inline le64_t htole64(uint64_t value) { return (le64_t __force) bswap_64_on_be(value); }
+
+static inline be16_t htobe16(uint16_t value) { return (be16_t __force) bswap_16_on_le(value); }
+static inline be32_t htobe32(uint32_t value) { return (be32_t __force) bswap_32_on_le(value); }
+static inline be64_t htobe64(uint64_t value) { return (be64_t __force) bswap_64_on_le(value); }
+
+static inline uint16_t le16toh(le16_t value) { return bswap_16_on_be((uint16_t __force)value); }
+static inline uint32_t le32toh(le32_t value) { return bswap_32_on_be((uint32_t __force)value); }
+static inline uint64_t le64toh(le64_t value) { return bswap_64_on_be((uint64_t __force)value); }
+
+static inline uint16_t be16toh(be16_t value) { return bswap_16_on_le((uint16_t __force)value); }
+static inline uint32_t be32toh(be32_t value) { return bswap_32_on_le((uint32_t __force)value); }
+static inline uint64_t be64toh(be64_t value) { return bswap_64_on_le((uint64_t __force)value); }
+
+#endif /* SPARSE_ENDIAN_H */
diff --git a/src/shared/spawn-ask-password-agent.c b/src/shared/spawn-ask-password-agent.c
new file mode 100644
index 0000000000..c1a9c58681
--- /dev/null
+++ b/src/shared/spawn-ask-password-agent.c
@@ -0,0 +1,67 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/types.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <string.h>
+#include <sys/prctl.h>
+#include <signal.h>
+#include <fcntl.h>
+
+#include "log.h"
+#include "util.h"
+#include "spawn-ask-password-agent.h"
+
+static pid_t agent_pid = 0;
+
+int ask_password_agent_open(void) {
+ int r;
+
+ if (agent_pid > 0)
+ return 0;
+
+ /* We check STDIN here, not STDOUT, since this is about input,
+ * not output */
+ if (!isatty(STDIN_FILENO))
+ return 0;
+
+ r = fork_agent(&agent_pid,
+ NULL, 0,
+ SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH,
+ SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH, "--watch", NULL);
+ if (r < 0)
+ log_error("Failed to fork TTY ask password agent: %s", strerror(-r));
+
+ return r;
+}
+
+void ask_password_agent_close(void) {
+
+ if (agent_pid <= 0)
+ return;
+
+ /* Inform agent that we are done */
+ kill(agent_pid, SIGTERM);
+ kill(agent_pid, SIGCONT);
+ wait_for_terminate(agent_pid, NULL);
+ agent_pid = 0;
+}
diff --git a/src/shared/spawn-ask-password-agent.h b/src/shared/spawn-ask-password-agent.h
new file mode 100644
index 0000000000..31b4beab58
--- /dev/null
+++ b/src/shared/spawn-ask-password-agent.h
@@ -0,0 +1,25 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+int ask_password_agent_open(void);
+void ask_password_agent_close(void);
diff --git a/src/shared/spawn-polkit-agent.c b/src/shared/spawn-polkit-agent.c
new file mode 100644
index 0000000000..f9e52cdcbd
--- /dev/null
+++ b/src/shared/spawn-polkit-agent.c
@@ -0,0 +1,98 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/types.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <string.h>
+#include <sys/prctl.h>
+#include <signal.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <sys/poll.h>
+
+#include "log.h"
+#include "util.h"
+#include "spawn-polkit-agent.h"
+
+#ifdef ENABLE_POLKIT
+static pid_t agent_pid = 0;
+
+int polkit_agent_open(void) {
+ int r;
+ int pipe_fd[2];
+ char notify_fd[10 + 1];
+
+ if (agent_pid > 0)
+ return 0;
+
+ /* We check STDIN here, not STDOUT, since this is about input,
+ * not output */
+ if (!isatty(STDIN_FILENO))
+ return 0;
+
+ if (pipe2(pipe_fd, 0) < 0)
+ return -errno;
+
+ snprintf(notify_fd, sizeof(notify_fd), "%i", pipe_fd[1]);
+ char_array_0(notify_fd);
+
+ r = fork_agent(&agent_pid,
+ &pipe_fd[1], 1,
+ POLKIT_AGENT_BINARY_PATH,
+ POLKIT_AGENT_BINARY_PATH, "--notify-fd", notify_fd, "--fallback", NULL);
+
+ /* Close the writing side, because that's the one for the agent */
+ close_nointr_nofail(pipe_fd[1]);
+
+ if (r < 0)
+ log_error("Failed to fork TTY ask password agent: %s", strerror(-r));
+ else
+ /* Wait until the agent closes the fd */
+ fd_wait_for_event(pipe_fd[0], POLLHUP, (usec_t) -1);
+
+ close_nointr_nofail(pipe_fd[0]);
+
+ return r;
+}
+
+void polkit_agent_close(void) {
+
+ if (agent_pid <= 0)
+ return;
+
+ /* Inform agent that we are done */
+ kill(agent_pid, SIGTERM);
+ kill(agent_pid, SIGCONT);
+ wait_for_terminate(agent_pid, NULL);
+ agent_pid = 0;
+}
+
+#else
+
+int polkit_agent_open(void) {
+ return 0;
+}
+
+void polkit_agent_close(void) {
+}
+
+#endif
diff --git a/src/shared/spawn-polkit-agent.h b/src/shared/spawn-polkit-agent.h
new file mode 100644
index 0000000000..b91d20f120
--- /dev/null
+++ b/src/shared/spawn-polkit-agent.h
@@ -0,0 +1,28 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef foospawnpolkitagenthfoo
+#define foospawnpolkitagenthfoo
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+int polkit_agent_open(void);
+void polkit_agent_close(void);
+
+#endif
diff --git a/src/shared/specifier.c b/src/shared/specifier.c
new file mode 100644
index 0000000000..7577c91052
--- /dev/null
+++ b/src/shared/specifier.c
@@ -0,0 +1,147 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <string.h>
+
+#include "macro.h"
+#include "util.h"
+#include "specifier.h"
+
+/*
+ * Generic infrastructure for replacing %x style specifiers in
+ * strings. Will call a callback for each replacement.
+ *
+ */
+
+char *specifier_printf(const char *text, const Specifier table[], void *userdata) {
+ char *r, *t;
+ const char *f;
+ bool percent = false;
+ size_t l;
+
+ assert(text);
+ assert(table);
+
+ l = strlen(text);
+ r = new(char, l+1);
+ if (!r)
+ return NULL;
+
+ t = r;
+
+ for (f = text; *f; f++, l--) {
+
+ if (percent) {
+ if (*f == '%')
+ *(t++) = '%';
+ else {
+ const Specifier *i;
+
+ for (i = table; i->specifier; i++)
+ if (i->specifier == *f)
+ break;
+
+ if (i->lookup) {
+ char *n, *w;
+ size_t k, j;
+
+ w = i->lookup(i->specifier, i->data, userdata);
+ if (!w) {
+ free(r);
+ return NULL;
+ }
+
+ j = t - r;
+ k = strlen(w);
+
+ n = new(char, j + k + l + 1);
+ if (!n) {
+ free(r);
+ free(w);
+ return NULL;
+ }
+
+ memcpy(n, r, j);
+ memcpy(n + j, w, k);
+
+ free(r);
+ free(w);
+
+ r = n;
+ t = n + j + k;
+ } else {
+ *(t++) = '%';
+ *(t++) = *f;
+ }
+ }
+
+ percent = false;
+ } else if (*f == '%')
+ percent = true;
+ else
+ *(t++) = *f;
+ }
+
+ *t = 0;
+ return r;
+}
+
+/* Generic handler for simple string replacements */
+
+char* specifier_string(char specifier, void *data, void *userdata) {
+ return strdup(strempty(data));
+}
+
+char *specifier_machine_id(char specifier, void *data, void *userdata) {
+ sd_id128_t id;
+ char *buf;
+ int r;
+
+ r = sd_id128_get_machine(&id);
+ if (r < 0)
+ return NULL;
+
+ buf = new(char, 33);
+ if (!buf)
+ return NULL;
+
+ return sd_id128_to_string(id, buf);
+}
+
+char *specifier_boot_id(char specifier, void *data, void *userdata) {
+ sd_id128_t id;
+ char *buf;
+ int r;
+
+ r = sd_id128_get_boot(&id);
+ if (r < 0)
+ return NULL;
+
+ buf = new(char, 33);
+ if (!buf)
+ return NULL;
+
+ return sd_id128_to_string(id, buf);
+}
+
+char *specifier_host_name(char specifier, void *data, void *userdata) {
+ return gethostname_malloc();
+}
diff --git a/src/shared/specifier.h b/src/shared/specifier.h
new file mode 100644
index 0000000000..0440dcac48
--- /dev/null
+++ b/src/shared/specifier.h
@@ -0,0 +1,38 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+typedef char* (*SpecifierCallback)(char specifier, void *data, void *userdata);
+
+typedef struct Specifier {
+ const char specifier;
+ const SpecifierCallback lookup;
+ void *data;
+} Specifier;
+
+char *specifier_printf(const char *text, const Specifier table[], void *userdata);
+
+char *specifier_string(char specifier, void *data, void *userdata);
+
+char *specifier_machine_id(char specifier, void *data, void *userdata);
+char *specifier_boot_id(char specifier, void *data, void *userdata);
+char *specifier_host_name(char specifier, void *data, void *userdata);
diff --git a/src/shared/strbuf.c b/src/shared/strbuf.c
new file mode 100644
index 0000000000..01a076c2ba
--- /dev/null
+++ b/src/shared/strbuf.c
@@ -0,0 +1,201 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Kay Sievers <kay@vrfy.org>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdlib.h>
+#include <string.h>
+
+#include "util.h"
+#include "strbuf.h"
+
+/*
+ * Strbuf stores given strings in a single continuous allocated memory
+ * area. Identical strings are de-duplicated and return the same offset
+ * as the first string stored. If the tail of a string already exists
+ * in the buffer, the tail is returned.
+ *
+ * A trie (http://en.wikipedia.org/wiki/Trie) is used to maintain the
+ * information about the stored strings.
+ *
+ * Example of udev rules:
+ * $ ./udevadm test .
+ * ...
+ * read rules file: /usr/lib/udev/rules.d/99-systemd.rules
+ * rules contain 196608 bytes tokens (16384 * 12 bytes), 39742 bytes strings
+ * 23939 strings (207859 bytes), 20404 de-duplicated (171653 bytes), 3536 trie nodes used
+ * ...
+ */
+
+struct strbuf *strbuf_new(void) {
+ struct strbuf *str;
+
+ str = new0(struct strbuf, 1);
+ if (!str)
+ return NULL;
+
+ str->buf = new0(char, 1);
+ if (!str->buf)
+ goto err;
+ str->len = 1;
+
+ str->root = new0(struct strbuf_node, 1);
+ if (!str->root)
+ goto err;
+ str->nodes_count = 1;
+ return str;
+err:
+ free(str->buf);
+ free(str->root);
+ free(str);
+ return NULL;
+}
+
+static void strbuf_node_cleanup(struct strbuf_node *node) {
+ size_t i;
+
+ for (i = 0; i < node->children_count; i++)
+ strbuf_node_cleanup(node->children[i].child);
+ free(node->children);
+ free(node);
+}
+
+/* clean up trie data, leave only the string buffer */
+void strbuf_complete(struct strbuf *str) {
+ if (!str)
+ return;
+ if (str->root)
+ strbuf_node_cleanup(str->root);
+ str->root = NULL;
+}
+
+/* clean up everything */
+void strbuf_cleanup(struct strbuf *str) {
+ if (!str)
+ return;
+ if (str->root)
+ strbuf_node_cleanup(str->root);
+ free(str->buf);
+ free(str);
+}
+
+static int strbuf_children_cmp(const struct strbuf_child_entry *n1,
+ const struct strbuf_child_entry *n2) {
+ return n1->c - n2->c;
+}
+
+static void bubbleinsert(struct strbuf_node *node,
+ uint8_t c,
+ struct strbuf_node *node_child) {
+
+ struct strbuf_child_entry new = {
+ .c = c,
+ .child = node_child,
+ };
+ int left = 0, right = node->children_count;
+
+ while (right > left) {
+ int middle = (right + left) / 2 ;
+ if (strbuf_children_cmp(&node->children[middle], &new) <= 0)
+ left = middle + 1;
+ else
+ right = middle;
+ }
+
+ memmove(node->children + left + 1, node->children + left,
+ sizeof(struct strbuf_child_entry) * (node->children_count - left));
+ node->children[left] = new;
+
+ node->children_count ++;
+}
+
+/* add string, return the index/offset into the buffer */
+ssize_t strbuf_add_string(struct strbuf *str, const char *s, size_t len) {
+ uint8_t c;
+ struct strbuf_node *node;
+ size_t depth;
+ char *buf_new;
+ struct strbuf_child_entry *child;
+ struct strbuf_node *node_child;
+ ssize_t off;
+
+ if (!str->root)
+ return -EINVAL;
+
+ /* search string; start from last character to find possibly matching tails */
+ if (len == 0)
+ return 0;
+ str->in_count++;
+ str->in_len += len;
+
+ node = str->root;
+ c = s[len-1];
+ for (depth = 0; depth <= len; depth++) {
+ struct strbuf_child_entry search;
+
+ /* match against current node */
+ off = node->value_off + node->value_len - len;
+ if (depth == len || (node->value_len >= len && memcmp(str->buf + off, s, len) == 0)) {
+ str->dedup_len += len;
+ str->dedup_count++;
+ return off;
+ }
+
+ /* lookup child node */
+ c = s[len - 1 - depth];
+ search.c = c;
+ child = bsearch(&search, node->children, node->children_count,
+ sizeof(struct strbuf_child_entry),
+ (__compar_fn_t) strbuf_children_cmp);
+ if (!child)
+ break;
+ node = child->child;
+ }
+
+ /* add new string */
+ buf_new = realloc(str->buf, str->len + len+1);
+ if (!buf_new)
+ return -ENOMEM;
+ str->buf = buf_new;
+ off = str->len;
+ memcpy(str->buf + off, s, len);
+ str->len += len;
+ str->buf[str->len++] = '\0';
+
+ /* new node */
+ node_child = new0(struct strbuf_node, 1);
+ if (!node_child)
+ return -ENOMEM;
+ node_child->value_off = off;
+ node_child->value_len = len;
+
+ /* extend array, add new entry, sort for bisection */
+ child = realloc(node->children, (node->children_count + 1) * sizeof(struct strbuf_child_entry));
+ if (!child) {
+ free(node_child);
+ return -ENOMEM;
+ }
+
+ str->nodes_count++;
+
+ node->children = child;
+ bubbleinsert(node, c, node_child);
+
+ return off;
+}
diff --git a/src/shared/strbuf.h b/src/shared/strbuf.h
new file mode 100644
index 0000000000..2347fd4328
--- /dev/null
+++ b/src/shared/strbuf.h
@@ -0,0 +1,56 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Kay Sievers <kay@vrfy.org>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdarg.h>
+#include <stdint.h>
+#include <stdbool.h>
+
+struct strbuf {
+ char *buf;
+ size_t len;
+ struct strbuf_node *root;
+
+ size_t nodes_count;
+ size_t in_count;
+ size_t in_len;
+ size_t dedup_len;
+ size_t dedup_count;
+};
+
+struct strbuf_node {
+ size_t value_off;
+ size_t value_len;
+
+ struct strbuf_child_entry *children;
+ uint8_t children_count;
+};
+
+struct strbuf_child_entry {
+ uint8_t c;
+ struct strbuf_node *child;
+};
+
+struct strbuf *strbuf_new(void);
+ssize_t strbuf_add_string(struct strbuf *str, const char *s, size_t len);
+void strbuf_complete(struct strbuf *str);
+void strbuf_cleanup(struct strbuf *str);
diff --git a/src/shared/strv.c b/src/shared/strv.c
new file mode 100644
index 0000000000..a5ce7e9593
--- /dev/null
+++ b/src/shared/strv.c
@@ -0,0 +1,587 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <errno.h>
+
+#include "util.h"
+#include "strv.h"
+
+char *strv_find(char **l, const char *name) {
+ char **i;
+
+ assert(name);
+
+ STRV_FOREACH(i, l)
+ if (streq(*i, name))
+ return *i;
+
+ return NULL;
+}
+
+char *strv_find_prefix(char **l, const char *name) {
+ char **i;
+
+ assert(name);
+
+ STRV_FOREACH(i, l)
+ if (startswith(*i, name))
+ return *i;
+
+ return NULL;
+}
+
+void strv_free(char **l) {
+ char **k;
+
+ if (!l)
+ return;
+
+ for (k = l; *k; k++)
+ free(*k);
+
+ free(l);
+}
+
+char **strv_copy(char * const *l) {
+ char **r, **k;
+
+ k = r = new(char*, strv_length(l) + 1);
+ if (!r)
+ return NULL;
+
+ if (l)
+ for (; *l; k++, l++) {
+ *k = strdup(*l);
+ if (!*k) {
+ strv_free(r);
+ return NULL;
+ }
+ }
+
+ *k = NULL;
+ return r;
+}
+
+unsigned strv_length(char * const *l) {
+ unsigned n = 0;
+
+ if (!l)
+ return 0;
+
+ for (; *l; l++)
+ n++;
+
+ return n;
+}
+
+char **strv_new_ap(const char *x, va_list ap) {
+ const char *s;
+ char **a;
+ unsigned n = 0, i = 0;
+ va_list aq;
+
+ /* As a special trick we ignore all listed strings that equal
+ * (const char*) -1. This is supposed to be used with the
+ * STRV_IFNOTNULL() macro to include possibly NULL strings in
+ * the string list. */
+
+ if (x) {
+ n = x == (const char*) -1 ? 0 : 1;
+
+ va_copy(aq, ap);
+ while ((s = va_arg(aq, const char*))) {
+ if (s == (const char*) -1)
+ continue;
+
+ n++;
+ }
+
+ va_end(aq);
+ }
+
+ a = new(char*, n+1);
+ if (!a)
+ return NULL;
+
+ if (x) {
+ if (x != (const char*) -1) {
+ a[i] = strdup(x);
+ if (!a[i])
+ goto fail;
+ i++;
+ }
+
+ while ((s = va_arg(ap, const char*))) {
+
+ if (s == (const char*) -1)
+ continue;
+
+ a[i] = strdup(s);
+ if (!a[i])
+ goto fail;
+
+ i++;
+ }
+ }
+
+ a[i] = NULL;
+
+ return a;
+
+fail:
+ strv_free(a);
+ return NULL;
+}
+
+char **strv_new(const char *x, ...) {
+ char **r;
+ va_list ap;
+
+ va_start(ap, x);
+ r = strv_new_ap(x, ap);
+ va_end(ap);
+
+ return r;
+}
+
+char **strv_merge(char **a, char **b) {
+ char **r, **k;
+
+ if (!a)
+ return strv_copy(b);
+
+ if (!b)
+ return strv_copy(a);
+
+ r = new(char*, strv_length(a) + strv_length(b) + 1);
+ if (!r)
+ return NULL;
+
+ for (k = r; *a; k++, a++) {
+ *k = strdup(*a);
+ if (!*k)
+ goto fail;
+ }
+
+ for (; *b; k++, b++) {
+ *k = strdup(*b);
+ if (!*k)
+ goto fail;
+ }
+
+ *k = NULL;
+ return r;
+
+fail:
+ strv_free(r);
+ return NULL;
+}
+
+char **strv_merge_concat(char **a, char **b, const char *suffix) {
+ char **r, **k;
+
+ /* Like strv_merge(), but appends suffix to all strings in b, before adding */
+
+ if (!b)
+ return strv_copy(a);
+
+ r = new(char*, strv_length(a) + strv_length(b) + 1);
+ if (!r)
+ return NULL;
+
+ k = r;
+ if (a)
+ for (; *a; k++, a++) {
+ *k = strdup(*a);
+ if (!*k)
+ goto fail;
+ }
+
+ for (; *b; k++, b++) {
+ *k = strappend(*b, suffix);
+ if (!*k)
+ goto fail;
+ }
+
+ *k = NULL;
+ return r;
+
+fail:
+ strv_free(r);
+ return NULL;
+
+}
+
+char **strv_split(const char *s, const char *separator) {
+ char *state;
+ char *w;
+ size_t l;
+ unsigned n, i;
+ char **r;
+
+ assert(s);
+
+ n = 0;
+ FOREACH_WORD_SEPARATOR(w, l, s, separator, state)
+ n++;
+
+ r = new(char*, n+1);
+ if (!r)
+ return NULL;
+
+ i = 0;
+ FOREACH_WORD_SEPARATOR(w, l, s, separator, state) {
+ r[i] = strndup(w, l);
+ if (!r[i]) {
+ strv_free(r);
+ return NULL;
+ }
+
+ i++;
+ }
+
+ r[i] = NULL;
+ return r;
+}
+
+char **strv_split_quoted(const char *s) {
+ char *state;
+ char *w;
+ size_t l;
+ unsigned n, i;
+ char **r;
+
+ assert(s);
+
+ n = 0;
+ FOREACH_WORD_QUOTED(w, l, s, state)
+ n++;
+
+ r = new(char*, n+1);
+ if (!r)
+ return NULL;
+
+ i = 0;
+ FOREACH_WORD_QUOTED(w, l, s, state) {
+ r[i] = cunescape_length(w, l);
+ if (!r[i]) {
+ strv_free(r);
+ return NULL;
+ }
+ i++;
+ }
+
+ r[i] = NULL;
+ return r;
+}
+
+char **strv_split_newlines(const char *s) {
+ char **l;
+ unsigned n;
+
+ assert(s);
+
+ /* Special version of strv_split() that splits on newlines and
+ * suppresses an empty string at the end */
+
+ l = strv_split(s, NEWLINE);
+ if (!l)
+ return NULL;
+
+ n = strv_length(l);
+ if (n <= 0)
+ return l;
+
+ if (isempty(l[n-1])) {
+ free(l[n-1]);
+ l[n-1] = NULL;
+ }
+
+ return l;
+}
+
+char *strv_join(char **l, const char *separator) {
+ char *r, *e;
+ char **s;
+ size_t n, k;
+
+ if (!separator)
+ separator = " ";
+
+ k = strlen(separator);
+
+ n = 0;
+ STRV_FOREACH(s, l) {
+ if (n != 0)
+ n += k;
+ n += strlen(*s);
+ }
+
+ r = new(char, n+1);
+ if (!r)
+ return NULL;
+
+ e = r;
+ STRV_FOREACH(s, l) {
+ if (e != r)
+ e = stpcpy(e, separator);
+
+ e = stpcpy(e, *s);
+ }
+
+ *e = 0;
+
+ return r;
+}
+
+char **strv_append(char **l, const char *s) {
+ char **r, **k;
+
+ if (!l)
+ return strv_new(s, NULL);
+
+ if (!s)
+ return strv_copy(l);
+
+ r = new(char*, strv_length(l)+2);
+ if (!r)
+ return NULL;
+
+ for (k = r; *l; k++, l++) {
+ *k = strdup(*l);
+ if (!*k)
+ goto fail;
+ }
+
+ k[0] = strdup(s);
+ if (!k[0])
+ goto fail;
+
+ k[1] = NULL;
+ return r;
+
+fail:
+ strv_free(r);
+ return NULL;
+}
+
+int strv_push(char ***l, char *value) {
+ char **c;
+ unsigned n;
+
+ if (!value)
+ return 0;
+
+ n = strv_length(*l);
+ c = realloc(*l, sizeof(char*) * (n + 2));
+ if (!c)
+ return -ENOMEM;
+
+ c[n] = value;
+ c[n+1] = NULL;
+
+ *l = c;
+ return 0;
+}
+
+int strv_extend(char ***l, const char *value) {
+ char *v;
+ int r;
+
+ if (!value)
+ return 0;
+
+ v = strdup(value);
+ if (!v)
+ return -ENOMEM;
+
+ r = strv_push(l, v);
+ if (r < 0)
+ free(v);
+
+ return r;
+}
+
+char **strv_uniq(char **l) {
+ char **i;
+
+ /* Drops duplicate entries. The first identical string will be
+ * kept, the others dropped */
+
+ STRV_FOREACH(i, l)
+ strv_remove(i+1, *i);
+
+ return l;
+}
+
+char **strv_remove(char **l, const char *s) {
+ char **f, **t;
+
+ if (!l)
+ return NULL;
+
+ assert(s);
+
+ /* Drops every occurrence of s in the string list, edits
+ * in-place. */
+
+ for (f = t = l; *f; f++) {
+
+ if (streq(*f, s)) {
+ free(*f);
+ continue;
+ }
+
+ *(t++) = *f;
+ }
+
+ *t = NULL;
+ return l;
+}
+
+char **strv_remove_prefix(char **l, const char *s) {
+ char **f, **t;
+
+ if (!l)
+ return NULL;
+
+ assert(s);
+
+ /* Drops every occurrence of a string prefixed with s in the
+ * string list, edits in-place. */
+
+ for (f = t = l; *f; f++) {
+
+ if (startswith(*f, s)) {
+ free(*f);
+ continue;
+ }
+
+ *(t++) = *f;
+ }
+
+ *t = NULL;
+ return l;
+}
+
+char **strv_parse_nulstr(const char *s, size_t l) {
+ const char *p;
+ unsigned c = 0, i = 0;
+ char **v;
+
+ assert(s || l <= 0);
+
+ if (l <= 0)
+ return strv_new(NULL, NULL);
+
+ for (p = s; p < s + l; p++)
+ if (*p == 0)
+ c++;
+
+ if (s[l-1] != 0)
+ c++;
+
+ v = new0(char*, c+1);
+ if (!v)
+ return NULL;
+
+ p = s;
+ while (p < s + l) {
+ const char *e;
+
+ e = memchr(p, 0, s + l - p);
+
+ v[i] = strndup(p, e ? e - p : s + l - p);
+ if (!v[i]) {
+ strv_free(v);
+ return NULL;
+ }
+
+ i++;
+
+ if (!e)
+ break;
+
+ p = e + 1;
+ }
+
+ assert(i == c);
+
+ return v;
+}
+
+char **strv_split_nulstr(const char *s) {
+ const char *i;
+ char **r = NULL;
+
+ NULSTR_FOREACH(i, s)
+ if (strv_extend(&r, i) < 0) {
+ strv_free(r);
+ return NULL;
+ }
+
+ if (!r)
+ return strv_new(NULL, NULL);
+
+ return r;
+}
+
+bool strv_overlap(char **a, char **b) {
+ char **i, **j;
+
+ STRV_FOREACH(i, a) {
+ STRV_FOREACH(j, b) {
+ if (streq(*i, *j))
+ return true;
+ }
+ }
+
+ return false;
+}
+
+static int str_compare(const void *_a, const void *_b) {
+ const char **a = (const char**) _a, **b = (const char**) _b;
+
+ return strcmp(*a, *b);
+}
+
+char **strv_sort(char **l) {
+
+ if (strv_isempty(l))
+ return l;
+
+ qsort(l, strv_length(l), sizeof(char*), str_compare);
+ return l;
+}
+
+void strv_print(char **l) {
+ char **s;
+
+ if (!l)
+ return;
+
+ STRV_FOREACH(s, l)
+ puts(*s);
+}
diff --git a/src/shared/strv.h b/src/shared/strv.h
new file mode 100644
index 0000000000..e35118752f
--- /dev/null
+++ b/src/shared/strv.h
@@ -0,0 +1,87 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdarg.h>
+#include <stdbool.h>
+
+#include "macro.h"
+
+char *strv_find(char **l, const char *name) _pure_;
+char *strv_find_prefix(char **l, const char *name) _pure_;
+
+void strv_free(char **l);
+static inline void strv_freep(char ***l) {
+ strv_free(*l);
+}
+
+#define _cleanup_strv_free_ _cleanup_(strv_freep)
+
+char **strv_copy(char * const *l);
+unsigned strv_length(char * const *l) _pure_;
+
+char **strv_merge(char **a, char **b);
+char **strv_merge_concat(char **a, char **b, const char *suffix);
+char **strv_append(char **l, const char *s);
+int strv_extend(char ***l, const char *value);
+int strv_push(char ***l, char *value);
+
+char **strv_remove(char **l, const char *s);
+char **strv_remove_prefix(char **l, const char *s);
+char **strv_uniq(char **l);
+
+#define strv_contains(l, s) (!!strv_find((l), (s)))
+
+char **strv_new(const char *x, ...) _sentinel_;
+char **strv_new_ap(const char *x, va_list ap);
+
+static inline const char* STRV_IFNOTNULL(const char *x) {
+ return x ? x : (const char *) -1;
+}
+
+static inline bool strv_isempty(char * const *l) {
+ return !l || !*l;
+}
+
+char **strv_split(const char *s, const char *separator);
+char **strv_split_quoted(const char *s);
+char **strv_split_newlines(const char *s);
+
+char *strv_join(char **l, const char *separator);
+
+char **strv_parse_nulstr(const char *s, size_t l);
+char **strv_split_nulstr(const char *s);
+
+bool strv_overlap(char **a, char **b) _pure_;
+
+#define STRV_FOREACH(s, l) \
+ for ((s) = (l); (s) && *(s); (s)++)
+
+#define STRV_FOREACH_BACKWARDS(s, l) \
+ for (; (l) && ((s) >= (l)); (s)--)
+
+#define STRV_FOREACH_PAIR(x, y, l) \
+ for ((x) = (l), (y) = (x+1); (x) && *(x) && *(y); (x) += 2, (y) = (x + 1))
+
+
+char **strv_sort(char **l);
+void strv_print(char **l);
diff --git a/src/shared/strxcpyx.c b/src/shared/strxcpyx.c
new file mode 100644
index 0000000000..3cb04b25cd
--- /dev/null
+++ b/src/shared/strxcpyx.c
@@ -0,0 +1,104 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Kay Sievers
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+/*
+ * Concatenates/copies strings. In any case, terminates in all cases
+ * with '\0' * and moves the @dest pointer forward to the added '\0'.
+ * Returns the * remaining size, and 0 if the string was truncated.
+ */
+
+#include <stdio.h>
+#include <string.h>
+#include "strxcpyx.h"
+
+size_t strpcpy(char **dest, size_t size, const char *src)
+{
+ size_t len;
+
+ len = strlen(src);
+ if (len >= size) {
+ if (size > 1)
+ *dest = mempcpy(*dest, src, size-1);
+ size = 0;
+ } else {
+ if (len > 0) {
+ *dest = mempcpy(*dest, src, len);
+ size -= len;
+ }
+ }
+ *dest[0] = '\0';
+ return size;
+}
+
+size_t strpcpyf(char **dest, size_t size, const char *src, ...)
+{
+ va_list va;
+ int i;
+
+ va_start(va, src);
+ i = vsnprintf(*dest, size, src, va);
+ if (i < (int)size) {
+ *dest += i;
+ size -= i;
+ } else {
+ *dest += size;
+ size = 0;
+ }
+ va_end(va);
+ *dest[0] = '\0';
+ return size;
+}
+
+size_t strpcpyl(char **dest, size_t size, const char *src, ...)
+{
+ va_list va;
+
+ va_start(va, src);
+ do {
+ size = strpcpy(dest, size, src);
+ src = va_arg(va, char *);
+ } while (src != NULL);
+ va_end(va);
+ return size;
+}
+
+size_t strscpy(char *dest, size_t size, const char *src)
+{
+ char *s;
+
+ s = dest;
+ return strpcpy(&s, size, src);
+}
+
+size_t strscpyl(char *dest, size_t size, const char *src, ...) {
+ va_list va;
+ char *s;
+
+ va_start(va, src);
+ s = dest;
+ do {
+ size = strpcpy(&s, size, src);
+ src = va_arg(va, char *);
+ } while (src != NULL);
+ va_end(va);
+
+ return size;
+}
diff --git a/src/shared/strxcpyx.h b/src/shared/strxcpyx.h
new file mode 100644
index 0000000000..1229a4821d
--- /dev/null
+++ b/src/shared/strxcpyx.h
@@ -0,0 +1,31 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Kay Sievers
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdarg.h>
+#include <stdbool.h>
+
+size_t strpcpy(char **dest, size_t size, const char *src);
+size_t strpcpyf(char **dest, size_t size, const char *src, ...) __attribute__((format(printf, 3, 4)));
+size_t strpcpyl(char **dest, size_t size, const char *src, ...) __attribute__((sentinel));
+size_t strscpy(char *dest, size_t size, const char *src);
+size_t strscpyl(char *dest, size_t size, const char *src, ...) __attribute__((sentinel));
diff --git a/src/shared/time-dst.c b/src/shared/time-dst.c
new file mode 100644
index 0000000000..3950a882bf
--- /dev/null
+++ b/src/shared/time-dst.c
@@ -0,0 +1,332 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Timezone file reading code from glibc 2.16.
+
+ Copyright (C) 1991-2012 Free Software Foundation, Inc.
+ Copyright 2012 Kay Sievers
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+#include <ctype.h>
+#include <errno.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <endian.h>
+#include <byteswap.h>
+#include <assert.h>
+#include <limits.h>
+#include <unistd.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include <sys/stat.h>
+
+#include "time-dst.h"
+#include "util.h"
+
+/*
+ * If tzh_version is '2' or greater, the above is followed by a second instance
+ * of tzhead and a second instance of the data in which each coded transition
+ * time uses 8 rather than 4 chars, then a POSIX-TZ-environment-variable-style
+ * string for use in handling instants after the last transition time stored in
+ * the file * (with nothing between the newlines if there is no POSIX
+ * representation for such instants).
+ */
+#define TZ_MAGIC "TZif"
+struct tzhead {
+ char tzh_magic[4]; /* TZ_MAGIC */
+ char tzh_version[1]; /* '\0' or '2' as of 2005 */
+ char tzh_reserved[15]; /* reserved--must be zero */
+ char tzh_ttisgmtcnt[4]; /* coded number of trans. time flags */
+ char tzh_ttisstdcnt[4]; /* coded number of trans. time flags */
+ char tzh_leapcnt[4]; /* coded number of leap seconds */
+ char tzh_timecnt[4]; /* coded number of transition times */
+ char tzh_typecnt[4]; /* coded number of local time types */
+ char tzh_charcnt[4]; /* coded number of abbr. chars */
+};
+
+struct ttinfo {
+ long int offset; /* Seconds east of GMT. */
+ unsigned char isdst; /* Used to set tm_isdst. */
+ unsigned char idx; /* Index into `zone_names'. */
+ unsigned char isstd; /* Transition times are in standard time. */
+ unsigned char isgmt; /* Transition times are in GMT. */
+};
+
+struct leap {
+ time_t transition; /* Time the transition takes effect. */
+ long int change; /* Seconds of correction to apply. */
+};
+
+static inline int decode(const void *ptr) {
+ return be32toh(*(int *)ptr);
+}
+
+static inline int64_t decode64(const void *ptr) {
+ return be64toh(*(int64_t *)ptr);
+}
+
+int time_get_dst(time_t date, const char *tzfile,
+ time_t *switch_cur, char **zone_cur, bool *dst_cur,
+ time_t *switch_next, int *delta_next, char **zone_next, bool *dst_next) {
+ unsigned char *type_idxs = 0;
+ size_t num_types = 0;
+ struct ttinfo *types = NULL;
+ char *zone_names = NULL;
+ struct stat st;
+ size_t num_isstd, num_isgmt;
+ struct tzhead tzhead;
+ size_t chars;
+ size_t i;
+ size_t total_size;
+ size_t types_idx;
+ int trans_width = 4;
+ size_t tzspec_len;
+ size_t num_leaps;
+ size_t lo, hi;
+ size_t num_transitions = 0;
+ _cleanup_free_ time_t *transitions = NULL;
+ _cleanup_fclose_ FILE *f;
+
+ f = fopen(tzfile, "re");
+ if (f == NULL)
+ return -errno;
+
+ if (fstat(fileno(f), &st) < 0)
+ return -errno;
+
+read_again:
+ if (fread((void *)&tzhead, sizeof(tzhead), 1, f) != 1 ||
+ memcmp(tzhead.tzh_magic, TZ_MAGIC, sizeof(tzhead.tzh_magic)) != 0)
+ return -EINVAL;
+
+ num_transitions = (size_t)decode(tzhead.tzh_timecnt);
+ num_types = (size_t)decode(tzhead.tzh_typecnt);
+ chars = (size_t)decode(tzhead.tzh_charcnt);
+ num_leaps = (size_t)decode(tzhead.tzh_leapcnt);
+ num_isstd = (size_t)decode(tzhead.tzh_ttisstdcnt);
+ num_isgmt = (size_t)decode(tzhead.tzh_ttisgmtcnt);
+
+ /* For platforms with 64-bit time_t we use the new format if available. */
+ if (sizeof(time_t) == 8 && trans_width == 4 && tzhead.tzh_version[0] != '\0') {
+ size_t to_skip;
+
+ /* We use the 8-byte format. */
+ trans_width = 8;
+
+ /* Position the stream before the second header. */
+ to_skip = (num_transitions * (4 + 1)
+ + num_types * 6
+ + chars
+ + num_leaps * 8 + num_isstd + num_isgmt);
+ if (fseek(f, to_skip, SEEK_CUR) != 0)
+ return -EINVAL;
+
+ goto read_again;
+ }
+
+ if (num_transitions > ((SIZE_MAX - (__alignof__(struct ttinfo) - 1)) / (sizeof(time_t) + 1)))
+ return -EINVAL;
+
+ total_size = num_transitions * (sizeof(time_t) + 1);
+ total_size = ((total_size + __alignof__(struct ttinfo) - 1) & ~(__alignof__(struct ttinfo) - 1));
+ types_idx = total_size;
+ if (num_leaps > (SIZE_MAX - total_size) / sizeof(struct ttinfo))
+ return -EINVAL;
+
+ total_size += num_types * sizeof(struct ttinfo);
+ if (chars > SIZE_MAX - total_size)
+ return -EINVAL;
+
+ total_size += chars;
+ if (__alignof__(struct leap) - 1 > SIZE_MAX - total_size)
+ return -EINVAL;
+
+ total_size = ((total_size + __alignof__(struct leap) - 1) & ~(__alignof__(struct leap) - 1));
+ if (num_leaps > (SIZE_MAX - total_size) / sizeof(struct leap))
+ return -EINVAL;
+
+ total_size += num_leaps * sizeof(struct leap);
+ tzspec_len = 0;
+ if (sizeof(time_t) == 8 && trans_width == 8) {
+ off_t rem = st.st_size - ftello(f);
+
+ if (rem < 0 || (size_t) rem < (num_transitions * (8 + 1) + num_types * 6 + chars))
+ return -EINVAL;
+ tzspec_len = (size_t) rem - (num_transitions * (8 + 1) + num_types * 6 + chars);
+ if (num_leaps > SIZE_MAX / 12 || tzspec_len < num_leaps * 12)
+ return -EINVAL;
+ tzspec_len -= num_leaps * 12;
+ if (tzspec_len < num_isstd)
+ return -EINVAL;
+ tzspec_len -= num_isstd;
+ if (tzspec_len == 0 || tzspec_len - 1 < num_isgmt)
+ return -EINVAL;
+ tzspec_len -= num_isgmt + 1;
+ if (SIZE_MAX - total_size < tzspec_len)
+ return -EINVAL;
+ }
+
+ transitions = (time_t *)calloc(total_size + tzspec_len, 1);
+ if (transitions == NULL)
+ return -EINVAL;
+
+ type_idxs = (unsigned char *)transitions + (num_transitions
+ * sizeof(time_t));
+ types = (struct ttinfo *)((char *)transitions + types_idx);
+ zone_names = (char *)types + num_types * sizeof(struct ttinfo);
+
+ if (sizeof(time_t) == 4 || trans_width == 8) {
+ if (fread(transitions, trans_width + 1, num_transitions, f) != num_transitions)
+ return -EINVAL;
+ } else {
+ if (fread(transitions, 4, num_transitions, f) != num_transitions ||
+ fread(type_idxs, 1, num_transitions, f) != num_transitions)
+ return -EINVAL;
+ }
+
+ /* Check for bogus indices in the data file, so we can hereafter
+ safely use type_idxs[T] as indices into `types' and never crash. */
+ for (i = 0; i < num_transitions; ++i)
+ if (type_idxs[i] >= num_types)
+ return -EINVAL;
+
+ if ((BYTE_ORDER != BIG_ENDIAN && (sizeof(time_t) == 4 || trans_width == 4)) ||
+ (BYTE_ORDER == BIG_ENDIAN && sizeof(time_t) == 8 && trans_width == 4)) {
+ /* Decode the transition times, stored as 4-byte integers in
+ network (big-endian) byte order. We work from the end of
+ the array so as not to clobber the next element to be
+ processed when sizeof (time_t) > 4. */
+ i = num_transitions;
+ while (i-- > 0)
+ transitions[i] = decode((char *)transitions + i * 4);
+ } else if (BYTE_ORDER != BIG_ENDIAN && sizeof(time_t) == 8) {
+ /* Decode the transition times, stored as 8-byte integers in
+ network (big-endian) byte order. */
+ for (i = 0; i < num_transitions; ++i)
+ transitions[i] = decode64((char *)transitions + i * 8);
+ }
+
+ for (i = 0; i < num_types; ++i) {
+ unsigned char x[4];
+ int c;
+
+ if (fread(x, 1, sizeof(x), f) != sizeof(x))
+ return -EINVAL;
+ c = getc(f);
+ if ((unsigned int)c > 1u)
+ return -EINVAL;
+ types[i].isdst = c;
+ c = getc(f);
+ if ((size_t) c > chars)
+ /* Bogus index in data file. */
+ return -EINVAL;
+ types[i].idx = c;
+ types[i].offset = (long int)decode(x);
+ }
+
+ if (fread(zone_names, 1, chars, f) != chars)
+ return -EINVAL;
+
+ for (i = 0; i < num_isstd; ++i) {
+ int c = getc(f);
+ if (c == EOF)
+ return -EINVAL;
+ types[i].isstd = c != 0;
+ }
+
+ while (i < num_types)
+ types[i++].isstd = 0;
+
+ for (i = 0; i < num_isgmt; ++i) {
+ int c = getc(f);
+ if (c == EOF)
+ return -EINVAL;
+ types[i].isgmt = c != 0;
+ }
+
+ while (i < num_types)
+ types[i++].isgmt = 0;
+
+ if (num_transitions == 0)
+ return -EINVAL;
+
+ if (date < transitions[0] || date >= transitions[num_transitions - 1])
+ return -EINVAL;
+
+ /* Find the first transition after TIMER, and
+ then pick the type of the transition before it. */
+ lo = 0;
+ hi = num_transitions - 1;
+
+ /* Assume that DST is changing twice a year and guess initial
+ search spot from it.
+ Half of a gregorian year has on average 365.2425 * 86400 / 2
+ = 15778476 seconds. */
+ i = (transitions[num_transitions - 1] - date) / 15778476;
+ if (i < num_transitions) {
+ i = num_transitions - 1 - i;
+ if (date < transitions[i]) {
+ if (i < 10 || date >= transitions[i - 10]) {
+ /* Linear search. */
+ while (date < transitions[i - 1])
+ i--;
+ goto found;
+ }
+ hi = i - 10;
+ } else {
+ if (i + 10 >= num_transitions || date < transitions[i + 10]) {
+ /* Linear search. */
+ while (date >= transitions[i])
+ i++;
+ goto found;
+ }
+ lo = i + 10;
+ }
+ }
+
+ /* Binary search. */
+ while (lo + 1 < hi) {
+ i = (lo + hi) / 2;
+ if (date < transitions[i])
+ hi = i;
+ else
+ lo = i;
+ }
+ i = hi;
+
+found:
+ if (switch_cur)
+ *switch_cur = transitions[i-1];
+ if (zone_cur)
+ *zone_cur = strdup(&zone_names[types[type_idxs[i - 1]].idx]);
+ if (dst_cur)
+ *dst_cur = types[type_idxs[i-1]].isdst;
+
+ if (switch_next)
+ *switch_next = transitions[i];
+ if (delta_next)
+ *delta_next = (types[type_idxs[i]].offset - types[type_idxs[i-1]].offset) / 60;
+ if (zone_next)
+ *zone_next = strdup(&zone_names[types[type_idxs[i]].idx]);
+ if (dst_next)
+ *dst_next = types[type_idxs[i]].isdst;
+
+ return 0;
+}
diff --git a/src/shared/time-dst.h b/src/shared/time-dst.h
new file mode 100644
index 0000000000..536b6bbdfb
--- /dev/null
+++ b/src/shared/time-dst.h
@@ -0,0 +1,26 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Kay Sievers
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+int time_get_dst(time_t date, const char *tzfile,
+ time_t *switch_cur, char **zone_cur, bool *dst_cur,
+ time_t *switch_next, int *delta_next, char **zone_next, bool *dst_next);
diff --git a/src/shared/time-util.c b/src/shared/time-util.c
new file mode 100644
index 0000000000..9ee711a49e
--- /dev/null
+++ b/src/shared/time-util.c
@@ -0,0 +1,772 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <time.h>
+#include <string.h>
+
+#include "util.h"
+#include "time-util.h"
+
+usec_t now(clockid_t clock_id) {
+ struct timespec ts;
+
+ assert_se(clock_gettime(clock_id, &ts) == 0);
+
+ return timespec_load(&ts);
+}
+
+dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
+ assert(ts);
+
+ ts->realtime = now(CLOCK_REALTIME);
+ ts->monotonic = now(CLOCK_MONOTONIC);
+
+ return ts;
+}
+
+dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
+ int64_t delta;
+ assert(ts);
+
+ if (u == (usec_t) -1) {
+ ts->realtime = ts->monotonic = (usec_t) -1;
+ return ts;
+ }
+
+ ts->realtime = u;
+
+ if (u == 0)
+ ts->monotonic = 0;
+ else {
+ delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
+
+ ts->monotonic = now(CLOCK_MONOTONIC);
+
+ if ((int64_t) ts->monotonic > delta)
+ ts->monotonic -= delta;
+ else
+ ts->monotonic = 0;
+ }
+
+ return ts;
+}
+
+dual_timestamp* dual_timestamp_from_monotonic(dual_timestamp *ts, usec_t u) {
+ int64_t delta;
+ assert(ts);
+
+ if (u == (usec_t) -1) {
+ ts->realtime = ts->monotonic = (usec_t) -1;
+ return ts;
+ }
+
+ ts->monotonic = u;
+ delta = (int64_t) now(CLOCK_MONOTONIC) - (int64_t) u;
+
+ ts->realtime = now(CLOCK_REALTIME);
+ if ((int64_t) ts->realtime > delta)
+ ts->realtime -= delta;
+ else
+ ts->realtime = 0;
+
+ return ts;
+}
+
+usec_t timespec_load(const struct timespec *ts) {
+ assert(ts);
+
+ if (ts->tv_sec == (time_t) -1 &&
+ ts->tv_nsec == (long) -1)
+ return (usec_t) -1;
+
+ if ((usec_t) ts->tv_sec > (UINT64_MAX - (ts->tv_nsec / NSEC_PER_USEC)) / USEC_PER_SEC)
+ return (usec_t) -1;
+
+ return
+ (usec_t) ts->tv_sec * USEC_PER_SEC +
+ (usec_t) ts->tv_nsec / NSEC_PER_USEC;
+}
+
+struct timespec *timespec_store(struct timespec *ts, usec_t u) {
+ assert(ts);
+
+ if (u == (usec_t) -1) {
+ ts->tv_sec = (time_t) -1;
+ ts->tv_nsec = (long) -1;
+ return ts;
+ }
+
+ ts->tv_sec = (time_t) (u / USEC_PER_SEC);
+ ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
+
+ return ts;
+}
+
+usec_t timeval_load(const struct timeval *tv) {
+ assert(tv);
+
+ if (tv->tv_sec == (time_t) -1 &&
+ tv->tv_usec == (suseconds_t) -1)
+ return (usec_t) -1;
+
+ if ((usec_t) tv->tv_sec > (UINT64_MAX - tv->tv_usec) / USEC_PER_SEC)
+ return (usec_t) -1;
+
+ return
+ (usec_t) tv->tv_sec * USEC_PER_SEC +
+ (usec_t) tv->tv_usec;
+}
+
+struct timeval *timeval_store(struct timeval *tv, usec_t u) {
+ assert(tv);
+
+ if (u == (usec_t) -1) {
+ tv->tv_sec = (time_t) -1;
+ tv->tv_usec = (suseconds_t) -1;
+ return tv;
+ }
+
+ tv->tv_sec = (time_t) (u / USEC_PER_SEC);
+ tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
+
+ return tv;
+}
+
+char *format_timestamp(char *buf, size_t l, usec_t t) {
+ struct tm tm;
+ time_t sec;
+
+ assert(buf);
+ assert(l > 0);
+
+ if (t <= 0)
+ return NULL;
+
+ sec = (time_t) (t / USEC_PER_SEC);
+
+ if (strftime(buf, l, "%a %Y-%m-%d %H:%M:%S %Z", localtime_r(&sec, &tm)) <= 0)
+ return NULL;
+
+ return buf;
+}
+
+char *format_timestamp_relative(char *buf, size_t l, usec_t t) {
+ usec_t n, d;
+
+ n = now(CLOCK_REALTIME);
+
+ if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
+ return NULL;
+
+ d = n - t;
+
+ if (d >= USEC_PER_YEAR)
+ snprintf(buf, l, "%llu years %llu months ago",
+ (unsigned long long) (d / USEC_PER_YEAR),
+ (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
+ else if (d >= USEC_PER_MONTH)
+ snprintf(buf, l, "%llu months %llu days ago",
+ (unsigned long long) (d / USEC_PER_MONTH),
+ (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
+ else if (d >= USEC_PER_WEEK)
+ snprintf(buf, l, "%llu weeks %llu days ago",
+ (unsigned long long) (d / USEC_PER_WEEK),
+ (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
+ else if (d >= 2*USEC_PER_DAY)
+ snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
+ else if (d >= 25*USEC_PER_HOUR)
+ snprintf(buf, l, "1 day %lluh ago",
+ (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
+ else if (d >= 6*USEC_PER_HOUR)
+ snprintf(buf, l, "%lluh ago",
+ (unsigned long long) (d / USEC_PER_HOUR));
+ else if (d >= USEC_PER_HOUR)
+ snprintf(buf, l, "%lluh %llumin ago",
+ (unsigned long long) (d / USEC_PER_HOUR),
+ (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
+ else if (d >= 5*USEC_PER_MINUTE)
+ snprintf(buf, l, "%llumin ago",
+ (unsigned long long) (d / USEC_PER_MINUTE));
+ else if (d >= USEC_PER_MINUTE)
+ snprintf(buf, l, "%llumin %llus ago",
+ (unsigned long long) (d / USEC_PER_MINUTE),
+ (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
+ else if (d >= USEC_PER_SEC)
+ snprintf(buf, l, "%llus ago",
+ (unsigned long long) (d / USEC_PER_SEC));
+ else if (d >= USEC_PER_MSEC)
+ snprintf(buf, l, "%llums ago",
+ (unsigned long long) (d / USEC_PER_MSEC));
+ else if (d > 0)
+ snprintf(buf, l, "%lluus ago",
+ (unsigned long long) d);
+ else
+ snprintf(buf, l, "now");
+
+ buf[l-1] = 0;
+ return buf;
+}
+
+char *format_timespan(char *buf, size_t l, usec_t t, usec_t accuracy) {
+ static const struct {
+ const char *suffix;
+ usec_t usec;
+ } table[] = {
+ { "y", USEC_PER_YEAR },
+ { "month", USEC_PER_MONTH },
+ { "w", USEC_PER_WEEK },
+ { "d", USEC_PER_DAY },
+ { "h", USEC_PER_HOUR },
+ { "min", USEC_PER_MINUTE },
+ { "s", USEC_PER_SEC },
+ { "ms", USEC_PER_MSEC },
+ { "us", 1 },
+ };
+
+ unsigned i;
+ char *p = buf;
+ bool something = false;
+
+ assert(buf);
+ assert(l > 0);
+
+ if (t == (usec_t) -1)
+ return NULL;
+
+ if (t <= 0) {
+ snprintf(p, l, "0");
+ p[l-1] = 0;
+ return p;
+ }
+
+ /* The result of this function can be parsed with parse_sec */
+
+ for (i = 0; i < ELEMENTSOF(table); i++) {
+ int k;
+ size_t n;
+ bool done = false;
+ usec_t a, b;
+
+ if (t <= 0)
+ break;
+
+ if (t < accuracy && something)
+ break;
+
+ if (t < table[i].usec)
+ continue;
+
+ if (l <= 1)
+ break;
+
+ a = t / table[i].usec;
+ b = t % table[i].usec;
+
+ /* Let's see if we should shows this in dot notation */
+ if (t < USEC_PER_MINUTE && b > 0) {
+ usec_t cc;
+ int j;
+
+ j = 0;
+ for (cc = table[i].usec; cc > 1; cc /= 10)
+ j++;
+
+ for (cc = accuracy; cc > 1; cc /= 10) {
+ b /= 10;
+ j--;
+ }
+
+ if (j > 0) {
+ k = snprintf(p, l,
+ "%s%llu.%0*llu%s",
+ p > buf ? " " : "",
+ (unsigned long long) a,
+ j,
+ (unsigned long long) b,
+ table[i].suffix);
+
+ t = 0;
+ done = true;
+ }
+ }
+
+ /* No? Then let's show it normally */
+ if (!done) {
+ k = snprintf(p, l,
+ "%s%llu%s",
+ p > buf ? " " : "",
+ (unsigned long long) a,
+ table[i].suffix);
+
+ t = b;
+ }
+
+ n = MIN((size_t) k, l);
+
+ l -= n;
+ p += n;
+
+ something = true;
+ }
+
+ *p = 0;
+
+ return buf;
+}
+
+void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
+
+ assert(f);
+ assert(name);
+ assert(t);
+
+ if (!dual_timestamp_is_set(t))
+ return;
+
+ fprintf(f, "%s=%llu %llu\n",
+ name,
+ (unsigned long long) t->realtime,
+ (unsigned long long) t->monotonic);
+}
+
+void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
+ unsigned long long a, b;
+
+ assert(value);
+ assert(t);
+
+ if (sscanf(value, "%lli %llu", &a, &b) != 2)
+ log_debug("Failed to parse finish timestamp value %s", value);
+ else {
+ t->realtime = a;
+ t->monotonic = b;
+ }
+}
+
+int parse_timestamp(const char *t, usec_t *usec) {
+ static const struct {
+ const char *name;
+ const int nr;
+ } day_nr[] = {
+ { "Sunday", 0 },
+ { "Sun", 0 },
+ { "Monday", 1 },
+ { "Mon", 1 },
+ { "Tuesday", 2 },
+ { "Tue", 2 },
+ { "Wednesday", 3 },
+ { "Wed", 3 },
+ { "Thursday", 4 },
+ { "Thu", 4 },
+ { "Friday", 5 },
+ { "Fri", 5 },
+ { "Saturday", 6 },
+ { "Sat", 6 },
+ };
+
+ const char *k;
+ struct tm tm, copy;
+ time_t x;
+ usec_t plus = 0, minus = 0, ret;
+ int r, weekday = -1;
+ unsigned i;
+
+ /*
+ * Allowed syntaxes:
+ *
+ * 2012-09-22 16:34:22
+ * 2012-09-22 16:34 (seconds will be set to 0)
+ * 2012-09-22 (time will be set to 00:00:00)
+ * 16:34:22 (date will be set to today)
+ * 16:34 (date will be set to today, seconds to 0)
+ * now
+ * yesterday (time is set to 00:00:00)
+ * today (time is set to 00:00:00)
+ * tomorrow (time is set to 00:00:00)
+ * +5min
+ * -5days
+ *
+ */
+
+ assert(t);
+ assert(usec);
+
+ x = time(NULL);
+ assert_se(localtime_r(&x, &tm));
+ tm.tm_isdst = -1;
+
+ if (streq(t, "now"))
+ goto finish;
+
+ else if (streq(t, "today")) {
+ tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
+ goto finish;
+
+ } else if (streq(t, "yesterday")) {
+ tm.tm_mday --;
+ tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
+ goto finish;
+
+ } else if (streq(t, "tomorrow")) {
+ tm.tm_mday ++;
+ tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
+ goto finish;
+
+ } else if (t[0] == '+') {
+
+ r = parse_sec(t+1, &plus);
+ if (r < 0)
+ return r;
+
+ goto finish;
+ } else if (t[0] == '-') {
+
+ r = parse_sec(t+1, &minus);
+ if (r < 0)
+ return r;
+
+ goto finish;
+
+ } else if (endswith(t, " ago")) {
+ _cleanup_free_ char *z;
+
+ z = strndup(t, strlen(t) - 4);
+ if (!z)
+ return -ENOMEM;
+
+ r = parse_sec(z, &minus);
+ if (r < 0)
+ return r;
+
+ goto finish;
+ }
+
+ for (i = 0; i < ELEMENTSOF(day_nr); i++) {
+ size_t skip;
+
+ if (!startswith_no_case(t, day_nr[i].name))
+ continue;
+
+ skip = strlen(day_nr[i].name);
+ if (t[skip] != ' ')
+ continue;
+
+ weekday = day_nr[i].nr;
+ t += skip + 1;
+ break;
+ }
+
+ copy = tm;
+ k = strptime(t, "%y-%m-%d %H:%M:%S", &tm);
+ if (k && *k == 0)
+ goto finish;
+
+ tm = copy;
+ k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm);
+ if (k && *k == 0)
+ goto finish;
+
+ tm = copy;
+ k = strptime(t, "%y-%m-%d %H:%M", &tm);
+ if (k && *k == 0) {
+ tm.tm_sec = 0;
+ goto finish;
+ }
+
+ tm = copy;
+ k = strptime(t, "%Y-%m-%d %H:%M", &tm);
+ if (k && *k == 0) {
+ tm.tm_sec = 0;
+ goto finish;
+ }
+
+ tm = copy;
+ k = strptime(t, "%y-%m-%d", &tm);
+ if (k && *k == 0) {
+ tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
+ goto finish;
+ }
+
+ tm = copy;
+ k = strptime(t, "%Y-%m-%d", &tm);
+ if (k && *k == 0) {
+ tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
+ goto finish;
+ }
+
+ tm = copy;
+ k = strptime(t, "%H:%M:%S", &tm);
+ if (k && *k == 0)
+ goto finish;
+
+ tm = copy;
+ k = strptime(t, "%H:%M", &tm);
+ if (k && *k == 0) {
+ tm.tm_sec = 0;
+ goto finish;
+ }
+
+ return -EINVAL;
+
+finish:
+ x = mktime(&tm);
+ if (x == (time_t) -1)
+ return -EINVAL;
+
+ if (weekday >= 0 && tm.tm_wday != weekday)
+ return -EINVAL;
+
+ ret = (usec_t) x * USEC_PER_SEC;
+
+ ret += plus;
+ if (ret > minus)
+ ret -= minus;
+ else
+ ret = 0;
+
+ *usec = ret;
+
+ return 0;
+}
+
+int parse_sec(const char *t, usec_t *usec) {
+ static const struct {
+ const char *suffix;
+ usec_t usec;
+ } table[] = {
+ { "seconds", USEC_PER_SEC },
+ { "second", USEC_PER_SEC },
+ { "sec", USEC_PER_SEC },
+ { "s", USEC_PER_SEC },
+ { "minutes", USEC_PER_MINUTE },
+ { "minute", USEC_PER_MINUTE },
+ { "min", USEC_PER_MINUTE },
+ { "months", USEC_PER_MONTH },
+ { "month", USEC_PER_MONTH },
+ { "msec", USEC_PER_MSEC },
+ { "ms", USEC_PER_MSEC },
+ { "m", USEC_PER_MINUTE },
+ { "hours", USEC_PER_HOUR },
+ { "hour", USEC_PER_HOUR },
+ { "hr", USEC_PER_HOUR },
+ { "h", USEC_PER_HOUR },
+ { "days", USEC_PER_DAY },
+ { "day", USEC_PER_DAY },
+ { "d", USEC_PER_DAY },
+ { "weeks", USEC_PER_WEEK },
+ { "week", USEC_PER_WEEK },
+ { "w", USEC_PER_WEEK },
+ { "years", USEC_PER_YEAR },
+ { "year", USEC_PER_YEAR },
+ { "y", USEC_PER_YEAR },
+ { "usec", 1ULL },
+ { "us", 1ULL },
+ { "", USEC_PER_SEC }, /* default is sec */
+ };
+
+ const char *p;
+ usec_t r = 0;
+ bool something = false;
+
+ assert(t);
+ assert(usec);
+
+ p = t;
+ for (;;) {
+ long long l, z = 0;
+ char *e;
+ unsigned i, n = 0;
+
+ p += strspn(p, WHITESPACE);
+
+ if (*p == 0) {
+ if (!something)
+ return -EINVAL;
+
+ break;
+ }
+
+ errno = 0;
+ l = strtoll(p, &e, 10);
+
+ if (errno > 0)
+ return -errno;
+
+ if (l < 0)
+ return -ERANGE;
+
+ if (*e == '.') {
+ char *b = e + 1;
+
+ errno = 0;
+ z = strtoll(b, &e, 10);
+ if (errno > 0)
+ return -errno;
+
+ if (z < 0)
+ return -ERANGE;
+
+ if (e == b)
+ return -EINVAL;
+
+ n = e - b;
+
+ } else if (e == p)
+ return -EINVAL;
+
+ e += strspn(e, WHITESPACE);
+
+ for (i = 0; i < ELEMENTSOF(table); i++)
+ if (startswith(e, table[i].suffix)) {
+ usec_t k = (usec_t) z * table[i].usec;
+
+ for (; n > 0; n--)
+ k /= 10;
+
+ r += (usec_t) l * table[i].usec + k;
+ p = e + strlen(table[i].suffix);
+
+ something = true;
+ break;
+ }
+
+ if (i >= ELEMENTSOF(table))
+ return -EINVAL;
+
+ }
+
+ *usec = r;
+
+ return 0;
+}
+
+int parse_nsec(const char *t, nsec_t *nsec) {
+ static const struct {
+ const char *suffix;
+ nsec_t nsec;
+ } table[] = {
+ { "seconds", NSEC_PER_SEC },
+ { "second", NSEC_PER_SEC },
+ { "sec", NSEC_PER_SEC },
+ { "s", NSEC_PER_SEC },
+ { "minutes", NSEC_PER_MINUTE },
+ { "minute", NSEC_PER_MINUTE },
+ { "min", NSEC_PER_MINUTE },
+ { "months", NSEC_PER_MONTH },
+ { "month", NSEC_PER_MONTH },
+ { "msec", NSEC_PER_MSEC },
+ { "ms", NSEC_PER_MSEC },
+ { "m", NSEC_PER_MINUTE },
+ { "hours", NSEC_PER_HOUR },
+ { "hour", NSEC_PER_HOUR },
+ { "hr", NSEC_PER_HOUR },
+ { "h", NSEC_PER_HOUR },
+ { "days", NSEC_PER_DAY },
+ { "day", NSEC_PER_DAY },
+ { "d", NSEC_PER_DAY },
+ { "weeks", NSEC_PER_WEEK },
+ { "week", NSEC_PER_WEEK },
+ { "w", NSEC_PER_WEEK },
+ { "years", NSEC_PER_YEAR },
+ { "year", NSEC_PER_YEAR },
+ { "y", NSEC_PER_YEAR },
+ { "usec", NSEC_PER_USEC },
+ { "us", NSEC_PER_USEC },
+ { "nsec", 1ULL },
+ { "ns", 1ULL },
+ { "", 1ULL }, /* default is nsec */
+ };
+
+ const char *p;
+ nsec_t r = 0;
+ bool something = false;
+
+ assert(t);
+ assert(nsec);
+
+ p = t;
+ for (;;) {
+ long long l, z = 0;
+ char *e;
+ unsigned i, n = 0;
+
+ p += strspn(p, WHITESPACE);
+
+ if (*p == 0) {
+ if (!something)
+ return -EINVAL;
+
+ break;
+ }
+
+ errno = 0;
+ l = strtoll(p, &e, 10);
+
+ if (errno > 0)
+ return -errno;
+
+ if (l < 0)
+ return -ERANGE;
+
+ if (*e == '.') {
+ char *b = e + 1;
+
+ errno = 0;
+ z = strtoll(b, &e, 10);
+ if (errno > 0)
+ return -errno;
+
+ if (z < 0)
+ return -ERANGE;
+
+ if (e == b)
+ return -EINVAL;
+
+ n = e - b;
+
+ } else if (e == p)
+ return -EINVAL;
+
+ e += strspn(e, WHITESPACE);
+
+ for (i = 0; i < ELEMENTSOF(table); i++)
+ if (startswith(e, table[i].suffix)) {
+ nsec_t k = (nsec_t) z * table[i].nsec;
+
+ for (; n > 0; n--)
+ k /= 10;
+
+ r += (nsec_t) l * table[i].nsec + k;
+ p = e + strlen(table[i].suffix);
+
+ something = true;
+ break;
+ }
+
+ if (i >= ELEMENTSOF(table))
+ return -EINVAL;
+
+ }
+
+ *nsec = r;
+
+ return 0;
+}
diff --git a/src/shared/time-util.h b/src/shared/time-util.h
new file mode 100644
index 0000000000..f27a006891
--- /dev/null
+++ b/src/shared/time-util.h
@@ -0,0 +1,85 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include <inttypes.h>
+
+typedef uint64_t usec_t;
+typedef uint64_t nsec_t;
+
+#include "macro.h"
+
+typedef struct dual_timestamp {
+ usec_t realtime;
+ usec_t monotonic;
+} dual_timestamp;
+
+#define MSEC_PER_SEC 1000ULL
+#define USEC_PER_SEC 1000000ULL
+#define USEC_PER_MSEC 1000ULL
+#define NSEC_PER_SEC 1000000000ULL
+#define NSEC_PER_MSEC 1000000ULL
+#define NSEC_PER_USEC 1000ULL
+
+#define USEC_PER_MINUTE (60ULL*USEC_PER_SEC)
+#define NSEC_PER_MINUTE (60ULL*NSEC_PER_SEC)
+#define USEC_PER_HOUR (60ULL*USEC_PER_MINUTE)
+#define NSEC_PER_HOUR (60ULL*NSEC_PER_MINUTE)
+#define USEC_PER_DAY (24ULL*USEC_PER_HOUR)
+#define NSEC_PER_DAY (24ULL*NSEC_PER_HOUR)
+#define USEC_PER_WEEK (7ULL*USEC_PER_DAY)
+#define NSEC_PER_WEEK (7ULL*NSEC_PER_DAY)
+#define USEC_PER_MONTH (2629800ULL*USEC_PER_SEC)
+#define NSEC_PER_MONTH (2629800ULL*NSEC_PER_SEC)
+#define USEC_PER_YEAR (31557600ULL*USEC_PER_SEC)
+#define NSEC_PER_YEAR (31557600ULL*NSEC_PER_SEC)
+
+#define FORMAT_TIMESTAMP_MAX ((4*4+1)+11+9+4+1) /* weekdays can be unicode */
+#define FORMAT_TIMESTAMP_RELATIVE_MAX 256
+#define FORMAT_TIMESPAN_MAX 64
+
+usec_t now(clockid_t clock);
+
+dual_timestamp* dual_timestamp_get(dual_timestamp *ts);
+dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u);
+dual_timestamp* dual_timestamp_from_monotonic(dual_timestamp *ts, usec_t u);
+
+#define dual_timestamp_is_set(ts) ((ts)->realtime > 0)
+
+usec_t timespec_load(const struct timespec *ts) _pure_;
+struct timespec *timespec_store(struct timespec *ts, usec_t u);
+
+usec_t timeval_load(const struct timeval *tv) _pure_;
+struct timeval *timeval_store(struct timeval *tv, usec_t u);
+
+char *format_timestamp(char *buf, size_t l, usec_t t);
+char *format_timestamp_relative(char *buf, size_t l, usec_t t);
+char *format_timespan(char *buf, size_t l, usec_t t, usec_t accuracy);
+
+void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t);
+void dual_timestamp_deserialize(const char *value, dual_timestamp *t);
+
+int parse_timestamp(const char *t, usec_t *usec);
+
+int parse_sec(const char *t, usec_t *usec);
+int parse_nsec(const char *t, nsec_t *nsec);
diff --git a/src/shared/unit-name.c b/src/shared/unit-name.c
new file mode 100644
index 0000000000..a809713595
--- /dev/null
+++ b/src/shared/unit-name.c
@@ -0,0 +1,549 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <string.h>
+#include <assert.h>
+
+#include "path-util.h"
+#include "util.h"
+#include "unit-name.h"
+
+#define VALID_CHARS \
+ "0123456789" \
+ "abcdefghijklmnopqrstuvwxyz" \
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
+ ":-_.\\"
+
+static const char* const unit_type_table[_UNIT_TYPE_MAX] = {
+ [UNIT_SERVICE] = "service",
+ [UNIT_SOCKET] = "socket",
+ [UNIT_TARGET] = "target",
+ [UNIT_DEVICE] = "device",
+ [UNIT_MOUNT] = "mount",
+ [UNIT_AUTOMOUNT] = "automount",
+ [UNIT_SNAPSHOT] = "snapshot",
+ [UNIT_TIMER] = "timer",
+ [UNIT_SWAP] = "swap",
+ [UNIT_PATH] = "path",
+};
+
+DEFINE_STRING_TABLE_LOOKUP(unit_type, UnitType);
+
+static const char* const unit_load_state_table[_UNIT_LOAD_STATE_MAX] = {
+ [UNIT_STUB] = "stub",
+ [UNIT_LOADED] = "loaded",
+ [UNIT_ERROR] = "error",
+ [UNIT_MERGED] = "merged",
+ [UNIT_MASKED] = "masked"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(unit_load_state, UnitLoadState);
+
+bool unit_name_is_valid(const char *n, bool template_ok) {
+ const char *e, *i, *at;
+
+ /* Valid formats:
+ *
+ * string@instance.suffix
+ * string.suffix
+ */
+
+ assert(n);
+
+ if (strlen(n) >= UNIT_NAME_MAX)
+ return false;
+
+ e = strrchr(n, '.');
+ if (!e || e == n)
+ return false;
+
+ if (unit_type_from_string(e + 1) < 0)
+ return false;
+
+ for (i = n, at = NULL; i < e; i++) {
+
+ if (*i == '@' && !at)
+ at = i;
+
+ if (!strchr("@" VALID_CHARS, *i))
+ return false;
+ }
+
+ if (at) {
+ if (at == n)
+ return false;
+
+ if (!template_ok && at+1 == e)
+ return false;
+ }
+
+ return true;
+}
+
+bool unit_instance_is_valid(const char *i) {
+ assert(i);
+
+ /* The max length depends on the length of the string, so we
+ * don't really check this here. */
+
+ if (i[0] == 0)
+ return false;
+
+ /* We allow additional @ in the instance string, we do not
+ * allow them in the prefix! */
+
+ for (; *i; i++)
+ if (!strchr("@" VALID_CHARS, *i))
+ return false;
+
+ return true;
+}
+
+bool unit_prefix_is_valid(const char *p) {
+
+ /* We don't allow additional @ in the instance string */
+
+ if (p[0] == 0)
+ return false;
+
+ for (; *p; p++)
+ if (!strchr(VALID_CHARS, *p))
+ return false;
+
+ return true;
+}
+
+int unit_name_to_instance(const char *n, char **instance) {
+ const char *p, *d;
+ char *i;
+
+ assert(n);
+ assert(instance);
+
+ /* Everything past the first @ and before the last . is the instance */
+ p = strchr(n, '@');
+ if (!p) {
+ *instance = NULL;
+ return 0;
+ }
+
+ assert_se(d = strrchr(n, '.'));
+ assert(p < d);
+
+ i = strndup(p+1, d-p-1);
+ if (!i)
+ return -ENOMEM;
+
+ *instance = i;
+ return 0;
+}
+
+char *unit_name_to_prefix_and_instance(const char *n) {
+ const char *d;
+
+ assert(n);
+
+ assert_se(d = strrchr(n, '.'));
+
+ return strndup(n, d - n);
+}
+
+char *unit_name_to_prefix(const char *n) {
+ const char *p;
+
+ p = strchr(n, '@');
+ if (p)
+ return strndup(n, p - n);
+
+ return unit_name_to_prefix_and_instance(n);
+}
+
+char *unit_name_change_suffix(const char *n, const char *suffix) {
+ char *e, *r;
+ size_t a, b;
+
+ assert(n);
+ assert(unit_name_is_valid(n, true));
+ assert(suffix);
+
+ assert_se(e = strrchr(n, '.'));
+ a = e - n;
+ b = strlen(suffix);
+
+ r = new(char, a + b + 1);
+ if (!r)
+ return NULL;
+
+ memcpy(r, n, a);
+ memcpy(r+a, suffix, b+1);
+
+ return r;
+}
+
+char *unit_name_build(const char *prefix, const char *instance, const char *suffix) {
+ assert(prefix);
+ assert(unit_prefix_is_valid(prefix));
+ assert(!instance || unit_instance_is_valid(instance));
+ assert(suffix);
+
+ if (!instance)
+ return strappend(prefix, suffix);
+
+ return strjoin(prefix, "@", instance, suffix, NULL);
+}
+
+static char *do_escape_char(char c, char *t) {
+ *(t++) = '\\';
+ *(t++) = 'x';
+ *(t++) = hexchar(c >> 4);
+ *(t++) = hexchar(c);
+ return t;
+}
+
+static char *do_escape(const char *f, char *t) {
+ assert(f);
+ assert(t);
+
+ /* do not create units with a leading '.', like for "/.dotdir" mount points */
+ if (*f == '.') {
+ t = do_escape_char(*f, t);
+ f++;
+ }
+
+ for (; *f; f++) {
+ if (*f == '/')
+ *(t++) = '-';
+ else if (*f == '-' || *f == '\\' || !strchr(VALID_CHARS, *f))
+ t = do_escape_char(*f, t);
+ else
+ *(t++) = *f;
+ }
+
+ return t;
+}
+
+char *unit_name_escape(const char *f) {
+ char *r, *t;
+
+ r = new(char, strlen(f)*4+1);
+ if (!r)
+ return NULL;
+
+ t = do_escape(f, r);
+ *t = 0;
+
+ return r;
+}
+
+char *unit_name_unescape(const char *f) {
+ char *r, *t;
+
+ assert(f);
+
+ r = strdup(f);
+ if (!r)
+ return NULL;
+
+ for (t = r; *f; f++) {
+ if (*f == '-')
+ *(t++) = '/';
+ else if (*f == '\\') {
+ int a, b;
+
+ if (f[1] != 'x' ||
+ (a = unhexchar(f[2])) < 0 ||
+ (b = unhexchar(f[3])) < 0) {
+ /* Invalid escape code, let's take it literal then */
+ *(t++) = '\\';
+ } else {
+ *(t++) = (char) ((a << 4) | b);
+ f += 3;
+ }
+ } else
+ *(t++) = *f;
+ }
+
+ *t = 0;
+
+ return r;
+}
+
+char *unit_name_path_escape(const char *f) {
+ char *p, *e;
+
+ assert(f);
+
+ p = strdup(f);
+ if (!p)
+ return NULL;
+
+ path_kill_slashes(p);
+
+ if (streq(p, "/")) {
+ free(p);
+ return strdup("-");
+ }
+
+ e = unit_name_escape(p[0] == '/' ? p + 1 : p);
+ free(p);
+
+ return e;
+}
+
+char *unit_name_path_unescape(const char *f) {
+ char *e;
+
+ assert(f);
+
+ e = unit_name_unescape(f);
+ if (!e)
+ return NULL;
+
+ if (e[0] != '/') {
+ char *w;
+
+ w = strappend("/", e);
+ free(e);
+
+ return w;
+ }
+
+ return e;
+}
+
+bool unit_name_is_template(const char *n) {
+ const char *p;
+
+ assert(n);
+
+ p = strchr(n, '@');
+ if (!p)
+ return false;
+
+ return p[1] == '.';
+}
+
+bool unit_name_is_instance(const char *n) {
+ const char *p;
+
+ assert(n);
+
+ p = strchr(n, '@');
+ if (!p)
+ return false;
+
+ return p[1] != '.';
+}
+
+char *unit_name_replace_instance(const char *f, const char *i) {
+ const char *p, *e;
+ char *r, *k;
+ size_t a, b;
+
+ assert(f);
+
+ p = strchr(f, '@');
+ if (!p)
+ return strdup(f);
+
+ e = strrchr(f, '.');
+ if (!e)
+ assert_se(e = strchr(f, 0));
+
+ a = p - f;
+ b = strlen(i);
+
+ r = new(char, a + 1 + b + strlen(e) + 1);
+ if (!r)
+ return NULL;
+
+ k = mempcpy(r, f, a + 1);
+ k = mempcpy(k, i, b);
+ strcpy(k, e);
+
+ return r;
+}
+
+char *unit_name_template(const char *f) {
+ const char *p, *e;
+ char *r;
+ size_t a;
+
+ p = strchr(f, '@');
+ if (!p)
+ return strdup(f);
+
+ assert_se(e = strrchr(f, '.'));
+ a = p - f + 1;
+
+ r = new(char, a + strlen(e) + 1);
+ if (!r)
+ return NULL;
+
+ strcpy(mempcpy(r, f, a), e);
+ return r;
+
+}
+
+char *unit_name_from_path(const char *path, const char *suffix) {
+ char *p, *r;
+
+ assert(path);
+ assert(suffix);
+
+ p = unit_name_path_escape(path);
+ if (!p)
+ return NULL;
+
+ r = strappend(p, suffix);
+ free(p);
+
+ return r;
+}
+
+char *unit_name_from_path_instance(const char *prefix, const char *path, const char *suffix) {
+ char *p, *r;
+
+ assert(prefix);
+ assert(path);
+ assert(suffix);
+
+ p = unit_name_path_escape(path);
+ if (!p)
+ return NULL;
+
+ r = strjoin(prefix, "@", p, suffix, NULL);
+ free(p);
+
+ return r;
+}
+
+char *unit_name_to_path(const char *name) {
+ char *w, *e;
+
+ assert(name);
+
+ w = unit_name_to_prefix(name);
+ if (!w)
+ return NULL;
+
+ e = unit_name_path_unescape(w);
+ free(w);
+
+ return e;
+}
+
+char *unit_dbus_path_from_name(const char *name) {
+ char *e, *p;
+
+ assert(name);
+
+ e = bus_path_escape(name);
+ if (!e)
+ return NULL;
+
+ p = strappend("/org/freedesktop/systemd1/unit/", e);
+ free(e);
+
+ return p;
+}
+
+char *unit_name_mangle(const char *name) {
+ char *r, *t;
+ const char *f;
+
+ assert(name);
+
+ /* Try to turn a string that might not be a unit name into a
+ * sensible unit name. */
+
+ if (is_device_path(name))
+ return unit_name_from_path(name, ".device");
+
+ if (path_is_absolute(name))
+ return unit_name_from_path(name, ".mount");
+
+ /* We'll only escape the obvious characters here, to play
+ * safe. */
+
+ r = new(char, strlen(name) * 4 + 1 + sizeof(".service")-1);
+ if (!r)
+ return NULL;
+
+ for (f = name, t = r; *f; f++) {
+ if (*f == '/')
+ *(t++) = '-';
+ else if (!strchr("@" VALID_CHARS, *f))
+ t = do_escape_char(*f, t);
+ else
+ *(t++) = *f;
+ }
+
+ if (unit_name_to_type(name) < 0)
+ strcpy(t, ".service");
+ else
+ *t = 0;
+
+ return r;
+}
+
+char *snapshot_name_mangle(const char *name) {
+ char *r, *t;
+ const char *f;
+
+ assert(name);
+
+ /* Similar to unit_name_mangle(), but is called when we know
+ * that this is about snapshot units. */
+
+ r = new(char, strlen(name) * 4 + 1 + sizeof(".snapshot")-1);
+ if (!r)
+ return NULL;
+
+ for (f = name, t = r; *f; f++) {
+ if (*f == '/')
+ *(t++) = '-';
+ else if (!strchr(VALID_CHARS, *f))
+ t = do_escape_char(*f, t);
+ else
+ *(t++) = *f;
+ }
+
+ if (!endswith(name, ".snapshot"))
+ strcpy(t, ".snapshot");
+ else
+ *t = 0;
+
+ return r;
+}
+
+UnitType unit_name_to_type(const char *n) {
+ const char *e;
+
+ assert(n);
+
+ e = strrchr(n, '.');
+ if (!e)
+ return _UNIT_TYPE_INVALID;
+
+ return unit_type_from_string(e + 1);
+}
diff --git a/src/shared/unit-name.h b/src/shared/unit-name.h
new file mode 100644
index 0000000000..9eca8eb3c1
--- /dev/null
+++ b/src/shared/unit-name.h
@@ -0,0 +1,97 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdbool.h>
+
+#include "macro.h"
+
+#define UNIT_NAME_MAX 256
+
+typedef enum UnitType UnitType;
+typedef enum UnitLoadState UnitLoadState;
+
+enum UnitType {
+ UNIT_SERVICE = 0,
+ UNIT_SOCKET,
+ UNIT_TARGET,
+ UNIT_DEVICE,
+ UNIT_MOUNT,
+ UNIT_AUTOMOUNT,
+ UNIT_SNAPSHOT,
+ UNIT_TIMER,
+ UNIT_SWAP,
+ UNIT_PATH,
+ _UNIT_TYPE_MAX,
+ _UNIT_TYPE_INVALID = -1
+};
+
+enum UnitLoadState {
+ UNIT_STUB = 0,
+ UNIT_LOADED,
+ UNIT_ERROR,
+ UNIT_MERGED,
+ UNIT_MASKED,
+ _UNIT_LOAD_STATE_MAX,
+ _UNIT_LOAD_STATE_INVALID = -1
+};
+
+const char *unit_type_to_string(UnitType i) _const_;
+UnitType unit_type_from_string(const char *s) _pure_;
+
+const char *unit_load_state_to_string(UnitLoadState i) _const_;
+UnitLoadState unit_load_state_from_string(const char *s) _pure_;
+
+int unit_name_to_instance(const char *n, char **instance);
+char* unit_name_to_prefix(const char *n);
+char* unit_name_to_prefix_and_instance(const char *n);
+
+bool unit_name_is_valid(const char *n, bool template_ok) _pure_;
+bool unit_prefix_is_valid(const char *p) _pure_;
+bool unit_instance_is_valid(const char *i) _pure_;
+
+UnitType unit_name_to_type(const char *n) _pure_;
+
+char *unit_name_change_suffix(const char *n, const char *suffix);
+
+char *unit_name_build(const char *prefix, const char *instance, const char *suffix);
+
+char *unit_name_escape(const char *f);
+char *unit_name_unescape(const char *f);
+char *unit_name_path_escape(const char *f);
+char *unit_name_path_unescape(const char *f);
+
+bool unit_name_is_template(const char *n) _pure_;
+bool unit_name_is_instance(const char *n) _pure_;
+
+char *unit_name_replace_instance(const char *f, const char *i);
+
+char *unit_name_template(const char *f);
+
+char *unit_name_from_path(const char *path, const char *suffix);
+char *unit_name_from_path_instance(const char *prefix, const char *path, const char *suffix);
+char *unit_name_to_path(const char *name);
+
+char *unit_dbus_path_from_name(const char *name);
+
+char *unit_name_mangle(const char *name);
+char *snapshot_name_mangle(const char *name);
diff --git a/src/shared/utf8.c b/src/shared/utf8.c
new file mode 100644
index 0000000000..3964e8b1ce
--- /dev/null
+++ b/src/shared/utf8.c
@@ -0,0 +1,322 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+/* This file is based on the GLIB utf8 validation functions. The
+ * original license text follows. */
+
+/* gutf8.c - Operations on UTF-8 strings.
+ *
+ * Copyright (C) 1999 Tom Tromey
+ * Copyright (C) 2000 Red Hat, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <errno.h>
+#include <stdlib.h>
+#include <inttypes.h>
+#include <string.h>
+#include <stdbool.h>
+
+#include "utf8.h"
+#include "util.h"
+
+#define FILTER_CHAR '_'
+
+static inline bool is_unicode_valid(uint32_t ch) {
+
+ if (ch >= 0x110000) /* End of unicode space */
+ return false;
+ if ((ch & 0xFFFFF800) == 0xD800) /* Reserved area for UTF-16 */
+ return false;
+ if ((ch >= 0xFDD0) && (ch <= 0xFDEF)) /* Reserved */
+ return false;
+ if ((ch & 0xFFFE) == 0xFFFE) /* BOM (Byte Order Mark) */
+ return false;
+
+ return true;
+}
+
+static inline bool is_continuation_char(uint8_t ch) {
+ if ((ch & 0xc0) != 0x80) /* 10xxxxxx */
+ return false;
+ return true;
+}
+
+static inline void merge_continuation_char(uint32_t *u_ch, uint8_t ch) {
+ *u_ch <<= 6;
+ *u_ch |= ch & 0x3f;
+}
+
+static bool is_unicode_control(uint32_t ch) {
+
+ /*
+ 0 to ' '-1 is the C0 range.
+ DEL=0x7F, and DEL+1 to 0x9F is C1 range.
+ '\t' is in C0 range, but more or less harmless and commonly used.
+ */
+
+ return (ch < ' ' && ch != '\t') ||
+ (0x7F <= ch && ch <= 0x9F);
+}
+
+char* utf8_is_printable_n(const char* str, size_t length) {
+ uint32_t val = 0;
+ uint32_t min = 0;
+ const uint8_t *p;
+
+ assert(str);
+
+ for (p = (const uint8_t*) str; length; p++, length--) {
+ if (*p < 128) {
+ val = *p;
+ } else {
+ if ((*p & 0xe0) == 0xc0) { /* 110xxxxx two-char seq. */
+ min = 128;
+ val = (uint32_t) (*p & 0x1e);
+ goto ONE_REMAINING;
+ } else if ((*p & 0xf0) == 0xe0) { /* 1110xxxx three-char seq.*/
+ min = (1 << 11);
+ val = (uint32_t) (*p & 0x0f);
+ goto TWO_REMAINING;
+ } else if ((*p & 0xf8) == 0xf0) { /* 11110xxx four-char seq */
+ min = (1 << 16);
+ val = (uint32_t) (*p & 0x07);
+ } else
+ goto error;
+
+ p++;
+ length--;
+ if (!length || !is_continuation_char(*p))
+ goto error;
+ merge_continuation_char(&val, *p);
+
+ TWO_REMAINING:
+ p++;
+ length--;
+ if (!is_continuation_char(*p))
+ goto error;
+ merge_continuation_char(&val, *p);
+
+ ONE_REMAINING:
+ p++;
+ length--;
+ if (!is_continuation_char(*p))
+ goto error;
+ merge_continuation_char(&val, *p);
+
+ if (val < min)
+ goto error;
+ }
+
+ if (is_unicode_control(val))
+ goto error;
+ }
+
+ return (char*) str;
+
+error:
+ return NULL;
+}
+
+static char* utf8_validate(const char *str, char *output) {
+ uint32_t val = 0;
+ uint32_t min = 0;
+ const uint8_t *p, *last;
+ int size;
+ uint8_t *o;
+
+ assert(str);
+
+ o = (uint8_t*) output;
+ for (p = (const uint8_t*) str; *p; p++) {
+ if (*p < 128) {
+ if (o)
+ *o = *p;
+ } else {
+ last = p;
+
+ if ((*p & 0xe0) == 0xc0) { /* 110xxxxx two-char seq. */
+ size = 2;
+ min = 128;
+ val = (uint32_t) (*p & 0x1e);
+ goto ONE_REMAINING;
+ } else if ((*p & 0xf0) == 0xe0) { /* 1110xxxx three-char seq.*/
+ size = 3;
+ min = (1 << 11);
+ val = (uint32_t) (*p & 0x0f);
+ goto TWO_REMAINING;
+ } else if ((*p & 0xf8) == 0xf0) { /* 11110xxx four-char seq */
+ size = 4;
+ min = (1 << 16);
+ val = (uint32_t) (*p & 0x07);
+ } else
+ goto error;
+
+ p++;
+ if (!is_continuation_char(*p))
+ goto error;
+ merge_continuation_char(&val, *p);
+
+ TWO_REMAINING:
+ p++;
+ if (!is_continuation_char(*p))
+ goto error;
+ merge_continuation_char(&val, *p);
+
+ ONE_REMAINING:
+ p++;
+ if (!is_continuation_char(*p))
+ goto error;
+ merge_continuation_char(&val, *p);
+
+ if (val < min)
+ goto error;
+
+ if (!is_unicode_valid(val))
+ goto error;
+
+ if (o) {
+ memcpy(o, last, (size_t) size);
+ o += size;
+ }
+
+ continue;
+
+ error:
+ if (o) {
+ *o = FILTER_CHAR;
+ p = last; /* We retry at the next character */
+ } else
+ goto failure;
+ }
+
+ if (o)
+ o++;
+ }
+
+ if (o) {
+ *o = '\0';
+ return output;
+ }
+
+ return (char*) str;
+
+failure:
+ return NULL;
+}
+
+char* utf8_is_valid (const char *str) {
+ return utf8_validate(str, NULL);
+}
+
+char* utf8_filter (const char *str) {
+ char *new_str;
+
+ assert(str);
+
+ new_str = malloc(strlen(str) + 1);
+ if (!new_str)
+ return NULL;
+
+ return utf8_validate(str, new_str);
+}
+
+char *ascii_is_valid(const char *str) {
+ const char *p;
+
+ assert(str);
+
+ for (p = str; *p; p++)
+ if ((unsigned char) *p >= 128)
+ return NULL;
+
+ return (char*) str;
+}
+
+char *ascii_filter(const char *str) {
+ const char *s;
+ char *r, *d;
+ size_t l;
+
+ assert(str);
+
+ l = strlen(str);
+ r = malloc(l + 1);
+ if (!r)
+ return NULL;
+
+ for (s = str, d = r; *s; s++)
+ if ((unsigned char) *s < 128)
+ *(d++) = *s;
+
+ *d = 0;
+
+ return r;
+}
+
+char *utf16_to_utf8(const void *s, size_t length) {
+ char *r;
+ const uint8_t *f;
+ uint8_t *t;
+
+ r = new(char, (length*3+1)/2 + 1);
+ if (!r)
+ return NULL;
+
+ t = (uint8_t*) r;
+
+ for (f = s; f < (const uint8_t*) s + length; f += 2) {
+ uint16_t c;
+
+ c = (f[1] << 8) | f[0];
+
+ if (c == 0) {
+ *t = 0;
+ return r;
+ } else if (c < 0x80) {
+ *(t++) = (uint8_t) c;
+ } else if (c < 0x800) {
+ *(t++) = (uint8_t) (0xc0 | (c >> 6));
+ *(t++) = (uint8_t) (0x80 | (c & 0x3f));
+ } else {
+ *(t++) = (uint8_t) (0xe0 | (c >> 12));
+ *(t++) = (uint8_t) (0x80 | ((c >> 6) & 0x3f));
+ *(t++) = (uint8_t) (0x80 | (c & 0x3f));
+ }
+ }
+
+ *t = 0;
+
+ return r;
+}
diff --git a/src/shared/utf8.h b/src/shared/utf8.h
new file mode 100644
index 0000000000..794ae15ab9
--- /dev/null
+++ b/src/shared/utf8.h
@@ -0,0 +1,34 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "macro.h"
+
+char *utf8_is_valid(const char *s) _pure_;
+char *ascii_is_valid(const char *s) _pure_;
+
+char *utf8_is_printable_n(const char* str, size_t length) _pure_;
+
+char *utf8_filter(const char *s);
+char *ascii_filter(const char *s);
+
+char *utf16_to_utf8(const void *s, size_t length);
diff --git a/src/shared/util.c b/src/shared/util.c
new file mode 100644
index 0000000000..673e0da6b6
--- /dev/null
+++ b/src/shared/util.c
@@ -0,0 +1,5849 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <signal.h>
+#include <stdio.h>
+#include <syslog.h>
+#include <sched.h>
+#include <sys/resource.h>
+#include <linux/sched.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <dirent.h>
+#include <sys/ioctl.h>
+#include <linux/vt.h>
+#include <linux/tiocl.h>
+#include <termios.h>
+#include <stdarg.h>
+#include <sys/inotify.h>
+#include <sys/poll.h>
+#include <libgen.h>
+#include <ctype.h>
+#include <sys/prctl.h>
+#include <sys/utsname.h>
+#include <pwd.h>
+#include <netinet/ip.h>
+#include <linux/kd.h>
+#include <dlfcn.h>
+#include <sys/wait.h>
+#include <sys/time.h>
+#include <glob.h>
+#include <grp.h>
+#include <sys/mman.h>
+#include <sys/vfs.h>
+#include <linux/magic.h>
+#include <limits.h>
+#include <langinfo.h>
+#include <locale.h>
+#include <libgen.h>
+
+#include "macro.h"
+#include "util.h"
+#include "ioprio.h"
+#include "missing.h"
+#include "log.h"
+#include "strv.h"
+#include "label.h"
+#include "path-util.h"
+#include "exit-status.h"
+#include "hashmap.h"
+#include "env-util.h"
+#include "fileio.h"
+
+int saved_argc = 0;
+char **saved_argv = NULL;
+
+static volatile unsigned cached_columns = 0;
+static volatile unsigned cached_lines = 0;
+
+size_t page_size(void) {
+ static __thread size_t pgsz = 0;
+ long r;
+
+ if (_likely_(pgsz > 0))
+ return pgsz;
+
+ r = sysconf(_SC_PAGESIZE);
+ assert(r > 0);
+
+ pgsz = (size_t) r;
+ return pgsz;
+}
+
+bool streq_ptr(const char *a, const char *b) {
+
+ /* Like streq(), but tries to make sense of NULL pointers */
+
+ if (a && b)
+ return streq(a, b);
+
+ if (!a && !b)
+ return true;
+
+ return false;
+}
+
+char* endswith(const char *s, const char *postfix) {
+ size_t sl, pl;
+
+ assert(s);
+ assert(postfix);
+
+ sl = strlen(s);
+ pl = strlen(postfix);
+
+ if (pl == 0)
+ return (char*) s + sl;
+
+ if (sl < pl)
+ return NULL;
+
+ if (memcmp(s + sl - pl, postfix, pl) != 0)
+ return NULL;
+
+ return (char*) s + sl - pl;
+}
+
+char* startswith(const char *s, const char *prefix) {
+ const char *a, *b;
+
+ assert(s);
+ assert(prefix);
+
+ a = s, b = prefix;
+ for (;;) {
+ if (*b == 0)
+ return (char*) a;
+ if (*a != *b)
+ return NULL;
+
+ a++, b++;
+ }
+}
+
+char* startswith_no_case(const char *s, const char *prefix) {
+ const char *a, *b;
+
+ assert(s);
+ assert(prefix);
+
+ a = s, b = prefix;
+ for (;;) {
+ if (*b == 0)
+ return (char*) a;
+ if (tolower(*a) != tolower(*b))
+ return NULL;
+
+ a++, b++;
+ }
+}
+
+bool first_word(const char *s, const char *word) {
+ size_t sl, wl;
+
+ assert(s);
+ assert(word);
+
+ sl = strlen(s);
+ wl = strlen(word);
+
+ if (sl < wl)
+ return false;
+
+ if (wl == 0)
+ return true;
+
+ if (memcmp(s, word, wl) != 0)
+ return false;
+
+ return s[wl] == 0 ||
+ strchr(WHITESPACE, s[wl]);
+}
+
+int close_nointr(int fd) {
+ int r;
+
+ assert(fd >= 0);
+ r = close(fd);
+
+ /* Just ignore EINTR; a retry loop is the wrong
+ * thing to do on Linux.
+ *
+ * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
+ * https://bugzilla.gnome.org/show_bug.cgi?id=682819
+ * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
+ * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
+ */
+ if (_unlikely_(r < 0 && errno == EINTR))
+ return 0;
+ else if (r >= 0)
+ return r;
+ else
+ return -errno;
+}
+
+void close_nointr_nofail(int fd) {
+ PROTECT_ERRNO;
+
+ /* like close_nointr() but cannot fail, and guarantees errno
+ * is unchanged */
+
+ assert_se(close_nointr(fd) == 0);
+}
+
+void close_many(const int fds[], unsigned n_fd) {
+ unsigned i;
+
+ assert(fds || n_fd <= 0);
+
+ for (i = 0; i < n_fd; i++)
+ close_nointr_nofail(fds[i]);
+}
+
+int unlink_noerrno(const char *path) {
+ PROTECT_ERRNO;
+ int r;
+
+ r = unlink(path);
+ if (r < 0)
+ return -errno;
+
+ return 0;
+}
+
+int parse_boolean(const char *v) {
+ assert(v);
+
+ if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || strcaseeq(v, "on"))
+ return 1;
+ else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || strcaseeq(v, "off"))
+ return 0;
+
+ return -EINVAL;
+}
+
+int parse_pid(const char *s, pid_t* ret_pid) {
+ unsigned long ul = 0;
+ pid_t pid;
+ int r;
+
+ assert(s);
+ assert(ret_pid);
+
+ r = safe_atolu(s, &ul);
+ if (r < 0)
+ return r;
+
+ pid = (pid_t) ul;
+
+ if ((unsigned long) pid != ul)
+ return -ERANGE;
+
+ if (pid <= 0)
+ return -ERANGE;
+
+ *ret_pid = pid;
+ return 0;
+}
+
+int parse_uid(const char *s, uid_t* ret_uid) {
+ unsigned long ul = 0;
+ uid_t uid;
+ int r;
+
+ assert(s);
+ assert(ret_uid);
+
+ r = safe_atolu(s, &ul);
+ if (r < 0)
+ return r;
+
+ uid = (uid_t) ul;
+
+ if ((unsigned long) uid != ul)
+ return -ERANGE;
+
+ *ret_uid = uid;
+ return 0;
+}
+
+int safe_atou(const char *s, unsigned *ret_u) {
+ char *x = NULL;
+ unsigned long l;
+
+ assert(s);
+ assert(ret_u);
+
+ errno = 0;
+ l = strtoul(s, &x, 0);
+
+ if (!x || x == s || *x || errno)
+ return errno > 0 ? -errno : -EINVAL;
+
+ if ((unsigned long) (unsigned) l != l)
+ return -ERANGE;
+
+ *ret_u = (unsigned) l;
+ return 0;
+}
+
+int safe_atoi(const char *s, int *ret_i) {
+ char *x = NULL;
+ long l;
+
+ assert(s);
+ assert(ret_i);
+
+ errno = 0;
+ l = strtol(s, &x, 0);
+
+ if (!x || x == s || *x || errno)
+ return errno > 0 ? -errno : -EINVAL;
+
+ if ((long) (int) l != l)
+ return -ERANGE;
+
+ *ret_i = (int) l;
+ return 0;
+}
+
+int safe_atollu(const char *s, long long unsigned *ret_llu) {
+ char *x = NULL;
+ unsigned long long l;
+
+ assert(s);
+ assert(ret_llu);
+
+ errno = 0;
+ l = strtoull(s, &x, 0);
+
+ if (!x || x == s || *x || errno)
+ return errno ? -errno : -EINVAL;
+
+ *ret_llu = l;
+ return 0;
+}
+
+int safe_atolli(const char *s, long long int *ret_lli) {
+ char *x = NULL;
+ long long l;
+
+ assert(s);
+ assert(ret_lli);
+
+ errno = 0;
+ l = strtoll(s, &x, 0);
+
+ if (!x || x == s || *x || errno)
+ return errno ? -errno : -EINVAL;
+
+ *ret_lli = l;
+ return 0;
+}
+
+int safe_atod(const char *s, double *ret_d) {
+ char *x = NULL;
+ double d;
+
+ assert(s);
+ assert(ret_d);
+
+ RUN_WITH_LOCALE(LC_NUMERIC_MASK, "C") {
+ errno = 0;
+ d = strtod(s, &x);
+ }
+
+ if (!x || x == s || *x || errno)
+ return errno ? -errno : -EINVAL;
+
+ *ret_d = (double) d;
+ return 0;
+}
+
+/* Split a string into words. */
+char *split(const char *c, size_t *l, const char *separator, char **state) {
+ char *current;
+
+ current = *state ? *state : (char*) c;
+
+ if (!*current || *c == 0)
+ return NULL;
+
+ current += strspn(current, separator);
+ *l = strcspn(current, separator);
+ *state = current+*l;
+
+ return (char*) current;
+}
+
+/* Split a string into words, but consider strings enclosed in '' and
+ * "" as words even if they include spaces. */
+char *split_quoted(const char *c, size_t *l, char **state) {
+ char *current, *e;
+ bool escaped = false;
+
+ current = *state ? *state : (char*) c;
+
+ if (!*current || *c == 0)
+ return NULL;
+
+ current += strspn(current, WHITESPACE);
+
+ if (*current == '\'') {
+ current ++;
+
+ for (e = current; *e; e++) {
+ if (escaped)
+ escaped = false;
+ else if (*e == '\\')
+ escaped = true;
+ else if (*e == '\'')
+ break;
+ }
+
+ *l = e-current;
+ *state = *e == 0 ? e : e+1;
+ } else if (*current == '\"') {
+ current ++;
+
+ for (e = current; *e; e++) {
+ if (escaped)
+ escaped = false;
+ else if (*e == '\\')
+ escaped = true;
+ else if (*e == '\"')
+ break;
+ }
+
+ *l = e-current;
+ *state = *e == 0 ? e : e+1;
+ } else {
+ for (e = current; *e; e++) {
+ if (escaped)
+ escaped = false;
+ else if (*e == '\\')
+ escaped = true;
+ else if (strchr(WHITESPACE, *e))
+ break;
+ }
+ *l = e-current;
+ *state = e;
+ }
+
+ return (char*) current;
+}
+
+int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
+ int r;
+ _cleanup_fclose_ FILE *f = NULL;
+ char line[LINE_MAX];
+ long unsigned ppid;
+ const char *p;
+
+ assert(pid >= 0);
+ assert(_ppid);
+
+ if (pid == 0) {
+ *_ppid = getppid();
+ return 0;
+ }
+
+ p = procfs_file_alloca(pid, "stat");
+ f = fopen(p, "re");
+ if (!f)
+ return -errno;
+
+ if (!fgets(line, sizeof(line), f)) {
+ r = feof(f) ? -EIO : -errno;
+ return r;
+ }
+
+ /* Let's skip the pid and comm fields. The latter is enclosed
+ * in () but does not escape any () in its value, so let's
+ * skip over it manually */
+
+ p = strrchr(line, ')');
+ if (!p)
+ return -EIO;
+
+ p++;
+
+ if (sscanf(p, " "
+ "%*c " /* state */
+ "%lu ", /* ppid */
+ &ppid) != 1)
+ return -EIO;
+
+ if ((long unsigned) (pid_t) ppid != ppid)
+ return -ERANGE;
+
+ *_ppid = (pid_t) ppid;
+
+ return 0;
+}
+
+int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
+ _cleanup_fclose_ FILE *f = NULL;
+ char line[LINE_MAX];
+ const char *p;
+
+ assert(pid >= 0);
+ assert(st);
+
+ if (pid == 0)
+ p = "/proc/self/stat";
+ else
+ p = procfs_file_alloca(pid, "stat");
+
+ f = fopen(p, "re");
+ if (!f)
+ return -errno;
+
+ if (!fgets(line, sizeof(line), f)) {
+ if (ferror(f))
+ return -errno;
+
+ return -EIO;
+ }
+
+ /* Let's skip the pid and comm fields. The latter is enclosed
+ * in () but does not escape any () in its value, so let's
+ * skip over it manually */
+
+ p = strrchr(line, ')');
+ if (!p)
+ return -EIO;
+
+ p++;
+
+ if (sscanf(p, " "
+ "%*c " /* state */
+ "%*d " /* ppid */
+ "%*d " /* pgrp */
+ "%*d " /* session */
+ "%*d " /* tty_nr */
+ "%*d " /* tpgid */
+ "%*u " /* flags */
+ "%*u " /* minflt */
+ "%*u " /* cminflt */
+ "%*u " /* majflt */
+ "%*u " /* cmajflt */
+ "%*u " /* utime */
+ "%*u " /* stime */
+ "%*d " /* cutime */
+ "%*d " /* cstime */
+ "%*d " /* priority */
+ "%*d " /* nice */
+ "%*d " /* num_threads */
+ "%*d " /* itrealvalue */
+ "%llu " /* starttime */,
+ st) != 1)
+ return -EIO;
+
+ return 0;
+}
+
+int fchmod_umask(int fd, mode_t m) {
+ mode_t u;
+ int r;
+
+ u = umask(0777);
+ r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
+ umask(u);
+
+ return r;
+}
+
+char *truncate_nl(char *s) {
+ assert(s);
+
+ s[strcspn(s, NEWLINE)] = 0;
+ return s;
+}
+
+int get_process_comm(pid_t pid, char **name) {
+ const char *p;
+
+ assert(name);
+ assert(pid >= 0);
+
+ if (pid == 0)
+ p = "/proc/self/comm";
+ else
+ p = procfs_file_alloca(pid, "comm");
+
+ return read_one_line_file(p, name);
+}
+
+int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
+ _cleanup_fclose_ FILE *f = NULL;
+ char *r = NULL, *k;
+ const char *p;
+ int c;
+
+ assert(line);
+ assert(pid >= 0);
+
+ if (pid == 0)
+ p = "/proc/self/cmdline";
+ else
+ p = procfs_file_alloca(pid, "cmdline");
+
+ f = fopen(p, "re");
+ if (!f)
+ return -errno;
+
+ if (max_length == 0) {
+ size_t len = 0, allocated = 0;
+
+ while ((c = getc(f)) != EOF) {
+
+ if (!GREEDY_REALLOC(r, allocated, len+2)) {
+ free(r);
+ return -ENOMEM;
+ }
+
+ r[len++] = isprint(c) ? c : ' ';
+ }
+
+ if (len > 0)
+ r[len-1] = 0;
+
+ } else {
+ bool space = false;
+ size_t left;
+
+ r = new(char, max_length);
+ if (!r)
+ return -ENOMEM;
+
+ k = r;
+ left = max_length;
+ while ((c = getc(f)) != EOF) {
+
+ if (isprint(c)) {
+ if (space) {
+ if (left <= 4)
+ break;
+
+ *(k++) = ' ';
+ left--;
+ space = false;
+ }
+
+ if (left <= 4)
+ break;
+
+ *(k++) = (char) c;
+ left--;
+ } else
+ space = true;
+ }
+
+ if (left <= 4) {
+ size_t n = MIN(left-1, 3U);
+ memcpy(k, "...", n);
+ k[n] = 0;
+ } else
+ *k = 0;
+ }
+
+ /* Kernel threads have no argv[] */
+ if (r == NULL || r[0] == 0) {
+ char *t;
+ int h;
+
+ free(r);
+
+ if (!comm_fallback)
+ return -ENOENT;
+
+ h = get_process_comm(pid, &t);
+ if (h < 0)
+ return h;
+
+ r = strjoin("[", t, "]", NULL);
+ free(t);
+
+ if (!r)
+ return -ENOMEM;
+ }
+
+ *line = r;
+ return 0;
+}
+
+int is_kernel_thread(pid_t pid) {
+ const char *p;
+ size_t count;
+ char c;
+ bool eof;
+ FILE *f;
+
+ if (pid == 0)
+ return 0;
+
+ assert(pid > 0);
+
+ p = procfs_file_alloca(pid, "cmdline");
+ f = fopen(p, "re");
+ if (!f)
+ return -errno;
+
+ count = fread(&c, 1, 1, f);
+ eof = feof(f);
+ fclose(f);
+
+ /* Kernel threads have an empty cmdline */
+
+ if (count <= 0)
+ return eof ? 1 : -errno;
+
+ return 0;
+}
+
+
+int get_process_exe(pid_t pid, char **name) {
+ const char *p;
+
+ assert(pid >= 0);
+ assert(name);
+
+ if (pid == 0)
+ p = "/proc/self/exe";
+ else
+ p = procfs_file_alloca(pid, "exe");
+
+ return readlink_malloc(p, name);
+}
+
+static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
+ _cleanup_fclose_ FILE *f = NULL;
+ char line[LINE_MAX];
+ const char *p;
+
+ assert(field);
+ assert(uid);
+
+ if (pid == 0)
+ return getuid();
+
+ p = procfs_file_alloca(pid, "status");
+ f = fopen(p, "re");
+ if (!f)
+ return -errno;
+
+ FOREACH_LINE(line, f, return -errno) {
+ char *l;
+
+ l = strstrip(line);
+
+ if (startswith(l, field)) {
+ l += strlen(field);
+ l += strspn(l, WHITESPACE);
+
+ l[strcspn(l, WHITESPACE)] = 0;
+
+ return parse_uid(l, uid);
+ }
+ }
+
+ return -EIO;
+}
+
+int get_process_uid(pid_t pid, uid_t *uid) {
+ return get_process_id(pid, "Uid:", uid);
+}
+
+int get_process_gid(pid_t pid, gid_t *gid) {
+ assert_cc(sizeof(uid_t) == sizeof(gid_t));
+ return get_process_id(pid, "Gid:", gid);
+}
+
+char *strnappend(const char *s, const char *suffix, size_t b) {
+ size_t a;
+ char *r;
+
+ if (!s && !suffix)
+ return strdup("");
+
+ if (!s)
+ return strndup(suffix, b);
+
+ if (!suffix)
+ return strdup(s);
+
+ assert(s);
+ assert(suffix);
+
+ a = strlen(s);
+ if (b > ((size_t) -1) - a)
+ return NULL;
+
+ r = new(char, a+b+1);
+ if (!r)
+ return NULL;
+
+ memcpy(r, s, a);
+ memcpy(r+a, suffix, b);
+ r[a+b] = 0;
+
+ return r;
+}
+
+char *strappend(const char *s, const char *suffix) {
+ return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
+}
+
+int readlink_malloc(const char *p, char **r) {
+ size_t l = 100;
+
+ assert(p);
+ assert(r);
+
+ for (;;) {
+ char *c;
+ ssize_t n;
+
+ if (!(c = new(char, l)))
+ return -ENOMEM;
+
+ if ((n = readlink(p, c, l-1)) < 0) {
+ int ret = -errno;
+ free(c);
+ return ret;
+ }
+
+ if ((size_t) n < l-1) {
+ c[n] = 0;
+ *r = c;
+ return 0;
+ }
+
+ free(c);
+ l *= 2;
+ }
+}
+
+int readlink_and_make_absolute(const char *p, char **r) {
+ char *target, *k;
+ int j;
+
+ assert(p);
+ assert(r);
+
+ if ((j = readlink_malloc(p, &target)) < 0)
+ return j;
+
+ k = file_in_same_dir(p, target);
+ free(target);
+
+ if (!k)
+ return -ENOMEM;
+
+ *r = k;
+ return 0;
+}
+
+int readlink_and_canonicalize(const char *p, char **r) {
+ char *t, *s;
+ int j;
+
+ assert(p);
+ assert(r);
+
+ j = readlink_and_make_absolute(p, &t);
+ if (j < 0)
+ return j;
+
+ s = canonicalize_file_name(t);
+ if (s) {
+ free(t);
+ *r = s;
+ } else
+ *r = t;
+
+ path_kill_slashes(*r);
+
+ return 0;
+}
+
+int reset_all_signal_handlers(void) {
+ int sig;
+
+ for (sig = 1; sig < _NSIG; sig++) {
+ struct sigaction sa = {
+ .sa_handler = SIG_DFL,
+ .sa_flags = SA_RESTART,
+ };
+
+ if (sig == SIGKILL || sig == SIGSTOP)
+ continue;
+
+ /* On Linux the first two RT signals are reserved by
+ * glibc, and sigaction() will return EINVAL for them. */
+ if ((sigaction(sig, &sa, NULL) < 0))
+ if (errno != EINVAL)
+ return -errno;
+ }
+
+ return 0;
+}
+
+char *strstrip(char *s) {
+ char *e;
+
+ /* Drops trailing whitespace. Modifies the string in
+ * place. Returns pointer to first non-space character */
+
+ s += strspn(s, WHITESPACE);
+
+ for (e = strchr(s, 0); e > s; e --)
+ if (!strchr(WHITESPACE, e[-1]))
+ break;
+
+ *e = 0;
+
+ return s;
+}
+
+char *delete_chars(char *s, const char *bad) {
+ char *f, *t;
+
+ /* Drops all whitespace, regardless where in the string */
+
+ for (f = s, t = s; *f; f++) {
+ if (strchr(bad, *f))
+ continue;
+
+ *(t++) = *f;
+ }
+
+ *t = 0;
+
+ return s;
+}
+
+bool in_charset(const char *s, const char* charset) {
+ const char *i;
+
+ assert(s);
+ assert(charset);
+
+ for (i = s; *i; i++)
+ if (!strchr(charset, *i))
+ return false;
+
+ return true;
+}
+
+char *file_in_same_dir(const char *path, const char *filename) {
+ char *e, *r;
+ size_t k;
+
+ assert(path);
+ assert(filename);
+
+ /* This removes the last component of path and appends
+ * filename, unless the latter is absolute anyway or the
+ * former isn't */
+
+ if (path_is_absolute(filename))
+ return strdup(filename);
+
+ if (!(e = strrchr(path, '/')))
+ return strdup(filename);
+
+ k = strlen(filename);
+ if (!(r = new(char, e-path+1+k+1)))
+ return NULL;
+
+ memcpy(r, path, e-path+1);
+ memcpy(r+(e-path)+1, filename, k+1);
+
+ return r;
+}
+
+int rmdir_parents(const char *path, const char *stop) {
+ size_t l;
+ int r = 0;
+
+ assert(path);
+ assert(stop);
+
+ l = strlen(path);
+
+ /* Skip trailing slashes */
+ while (l > 0 && path[l-1] == '/')
+ l--;
+
+ while (l > 0) {
+ char *t;
+
+ /* Skip last component */
+ while (l > 0 && path[l-1] != '/')
+ l--;
+
+ /* Skip trailing slashes */
+ while (l > 0 && path[l-1] == '/')
+ l--;
+
+ if (l <= 0)
+ break;
+
+ if (!(t = strndup(path, l)))
+ return -ENOMEM;
+
+ if (path_startswith(stop, t)) {
+ free(t);
+ return 0;
+ }
+
+ r = rmdir(t);
+ free(t);
+
+ if (r < 0)
+ if (errno != ENOENT)
+ return -errno;
+ }
+
+ return 0;
+}
+
+char hexchar(int x) {
+ static const char table[16] = "0123456789abcdef";
+
+ return table[x & 15];
+}
+
+int unhexchar(char c) {
+
+ if (c >= '0' && c <= '9')
+ return c - '0';
+
+ if (c >= 'a' && c <= 'f')
+ return c - 'a' + 10;
+
+ if (c >= 'A' && c <= 'F')
+ return c - 'A' + 10;
+
+ return -1;
+}
+
+char *hexmem(const void *p, size_t l) {
+ char *r, *z;
+ const uint8_t *x;
+
+ z = r = malloc(l * 2 + 1);
+ if (!r)
+ return NULL;
+
+ for (x = p; x < (const uint8_t*) p + l; x++) {
+ *(z++) = hexchar(*x >> 4);
+ *(z++) = hexchar(*x & 15);
+ }
+
+ *z = 0;
+ return r;
+}
+
+void *unhexmem(const char *p, size_t l) {
+ uint8_t *r, *z;
+ const char *x;
+
+ assert(p);
+
+ z = r = malloc((l + 1) / 2 + 1);
+ if (!r)
+ return NULL;
+
+ for (x = p; x < p + l; x += 2) {
+ int a, b;
+
+ a = unhexchar(x[0]);
+ if (x+1 < p + l)
+ b = unhexchar(x[1]);
+ else
+ b = 0;
+
+ *(z++) = (uint8_t) a << 4 | (uint8_t) b;
+ }
+
+ *z = 0;
+ return r;
+}
+
+char octchar(int x) {
+ return '0' + (x & 7);
+}
+
+int unoctchar(char c) {
+
+ if (c >= '0' && c <= '7')
+ return c - '0';
+
+ return -1;
+}
+
+char decchar(int x) {
+ return '0' + (x % 10);
+}
+
+int undecchar(char c) {
+
+ if (c >= '0' && c <= '9')
+ return c - '0';
+
+ return -1;
+}
+
+char *cescape(const char *s) {
+ char *r, *t;
+ const char *f;
+
+ assert(s);
+
+ /* Does C style string escaping. */
+
+ r = new(char, strlen(s)*4 + 1);
+ if (!r)
+ return NULL;
+
+ for (f = s, t = r; *f; f++)
+
+ switch (*f) {
+
+ case '\a':
+ *(t++) = '\\';
+ *(t++) = 'a';
+ break;
+ case '\b':
+ *(t++) = '\\';
+ *(t++) = 'b';
+ break;
+ case '\f':
+ *(t++) = '\\';
+ *(t++) = 'f';
+ break;
+ case '\n':
+ *(t++) = '\\';
+ *(t++) = 'n';
+ break;
+ case '\r':
+ *(t++) = '\\';
+ *(t++) = 'r';
+ break;
+ case '\t':
+ *(t++) = '\\';
+ *(t++) = 't';
+ break;
+ case '\v':
+ *(t++) = '\\';
+ *(t++) = 'v';
+ break;
+ case '\\':
+ *(t++) = '\\';
+ *(t++) = '\\';
+ break;
+ case '"':
+ *(t++) = '\\';
+ *(t++) = '"';
+ break;
+ case '\'':
+ *(t++) = '\\';
+ *(t++) = '\'';
+ break;
+
+ default:
+ /* For special chars we prefer octal over
+ * hexadecimal encoding, simply because glib's
+ * g_strescape() does the same */
+ if ((*f < ' ') || (*f >= 127)) {
+ *(t++) = '\\';
+ *(t++) = octchar((unsigned char) *f >> 6);
+ *(t++) = octchar((unsigned char) *f >> 3);
+ *(t++) = octchar((unsigned char) *f);
+ } else
+ *(t++) = *f;
+ break;
+ }
+
+ *t = 0;
+
+ return r;
+}
+
+char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
+ char *r, *t;
+ const char *f;
+ size_t pl;
+
+ assert(s);
+
+ /* Undoes C style string escaping, and optionally prefixes it. */
+
+ pl = prefix ? strlen(prefix) : 0;
+
+ r = new(char, pl+length+1);
+ if (!r)
+ return r;
+
+ if (prefix)
+ memcpy(r, prefix, pl);
+
+ for (f = s, t = r + pl; f < s + length; f++) {
+
+ if (*f != '\\') {
+ *(t++) = *f;
+ continue;
+ }
+
+ f++;
+
+ switch (*f) {
+
+ case 'a':
+ *(t++) = '\a';
+ break;
+ case 'b':
+ *(t++) = '\b';
+ break;
+ case 'f':
+ *(t++) = '\f';
+ break;
+ case 'n':
+ *(t++) = '\n';
+ break;
+ case 'r':
+ *(t++) = '\r';
+ break;
+ case 't':
+ *(t++) = '\t';
+ break;
+ case 'v':
+ *(t++) = '\v';
+ break;
+ case '\\':
+ *(t++) = '\\';
+ break;
+ case '"':
+ *(t++) = '"';
+ break;
+ case '\'':
+ *(t++) = '\'';
+ break;
+
+ case 's':
+ /* This is an extension of the XDG syntax files */
+ *(t++) = ' ';
+ break;
+
+ case 'x': {
+ /* hexadecimal encoding */
+ int a, b;
+
+ a = unhexchar(f[1]);
+ b = unhexchar(f[2]);
+
+ if (a < 0 || b < 0) {
+ /* Invalid escape code, let's take it literal then */
+ *(t++) = '\\';
+ *(t++) = 'x';
+ } else {
+ *(t++) = (char) ((a << 4) | b);
+ f += 2;
+ }
+
+ break;
+ }
+
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7': {
+ /* octal encoding */
+ int a, b, c;
+
+ a = unoctchar(f[0]);
+ b = unoctchar(f[1]);
+ c = unoctchar(f[2]);
+
+ if (a < 0 || b < 0 || c < 0) {
+ /* Invalid escape code, let's take it literal then */
+ *(t++) = '\\';
+ *(t++) = f[0];
+ } else {
+ *(t++) = (char) ((a << 6) | (b << 3) | c);
+ f += 2;
+ }
+
+ break;
+ }
+
+ case 0:
+ /* premature end of string.*/
+ *(t++) = '\\';
+ goto finish;
+
+ default:
+ /* Invalid escape code, let's take it literal then */
+ *(t++) = '\\';
+ *(t++) = *f;
+ break;
+ }
+ }
+
+finish:
+ *t = 0;
+ return r;
+}
+
+char *cunescape_length(const char *s, size_t length) {
+ return cunescape_length_with_prefix(s, length, NULL);
+}
+
+char *cunescape(const char *s) {
+ assert(s);
+
+ return cunescape_length(s, strlen(s));
+}
+
+char *xescape(const char *s, const char *bad) {
+ char *r, *t;
+ const char *f;
+
+ /* Escapes all chars in bad, in addition to \ and all special
+ * chars, in \xFF style escaping. May be reversed with
+ * cunescape. */
+
+ r = new(char, strlen(s) * 4 + 1);
+ if (!r)
+ return NULL;
+
+ for (f = s, t = r; *f; f++) {
+
+ if ((*f < ' ') || (*f >= 127) ||
+ (*f == '\\') || strchr(bad, *f)) {
+ *(t++) = '\\';
+ *(t++) = 'x';
+ *(t++) = hexchar(*f >> 4);
+ *(t++) = hexchar(*f);
+ } else
+ *(t++) = *f;
+ }
+
+ *t = 0;
+
+ return r;
+}
+
+char *bus_path_escape(const char *s) {
+ char *r, *t;
+ const char *f;
+
+ assert(s);
+
+ /* Escapes all chars that D-Bus' object path cannot deal
+ * with. Can be reverse with bus_path_unescape(). We special
+ * case the empty string. */
+
+ if (*s == 0)
+ return strdup("_");
+
+ r = new(char, strlen(s)*3 + 1);
+ if (!r)
+ return NULL;
+
+ for (f = s, t = r; *f; f++) {
+
+ /* Escape everything that is not a-zA-Z0-9. We also
+ * escape 0-9 if it's the first character */
+
+ if (!(*f >= 'A' && *f <= 'Z') &&
+ !(*f >= 'a' && *f <= 'z') &&
+ !(f > s && *f >= '0' && *f <= '9')) {
+ *(t++) = '_';
+ *(t++) = hexchar(*f >> 4);
+ *(t++) = hexchar(*f);
+ } else
+ *(t++) = *f;
+ }
+
+ *t = 0;
+
+ return r;
+}
+
+char *bus_path_unescape(const char *f) {
+ char *r, *t;
+
+ assert(f);
+
+ /* Special case for the empty string */
+ if (streq(f, "_"))
+ return strdup("");
+
+ r = new(char, strlen(f) + 1);
+ if (!r)
+ return NULL;
+
+ for (t = r; *f; f++) {
+
+ if (*f == '_') {
+ int a, b;
+
+ if ((a = unhexchar(f[1])) < 0 ||
+ (b = unhexchar(f[2])) < 0) {
+ /* Invalid escape code, let's take it literal then */
+ *(t++) = '_';
+ } else {
+ *(t++) = (char) ((a << 4) | b);
+ f += 2;
+ }
+ } else
+ *(t++) = *f;
+ }
+
+ *t = 0;
+
+ return r;
+}
+
+char *ascii_strlower(char *t) {
+ char *p;
+
+ assert(t);
+
+ for (p = t; *p; p++)
+ if (*p >= 'A' && *p <= 'Z')
+ *p = *p - 'A' + 'a';
+
+ return t;
+}
+
+_pure_ static bool ignore_file_allow_backup(const char *filename) {
+ assert(filename);
+
+ return
+ filename[0] == '.' ||
+ streq(filename, "lost+found") ||
+ streq(filename, "aquota.user") ||
+ streq(filename, "aquota.group") ||
+ endswith(filename, ".rpmnew") ||
+ endswith(filename, ".rpmsave") ||
+ endswith(filename, ".rpmorig") ||
+ endswith(filename, ".dpkg-old") ||
+ endswith(filename, ".dpkg-new") ||
+ endswith(filename, ".swp");
+}
+
+bool ignore_file(const char *filename) {
+ assert(filename);
+
+ if (endswith(filename, "~"))
+ return false;
+
+ return ignore_file_allow_backup(filename);
+}
+
+int fd_nonblock(int fd, bool nonblock) {
+ int flags;
+
+ assert(fd >= 0);
+
+ if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
+ return -errno;
+
+ if (nonblock)
+ flags |= O_NONBLOCK;
+ else
+ flags &= ~O_NONBLOCK;
+
+ if (fcntl(fd, F_SETFL, flags) < 0)
+ return -errno;
+
+ return 0;
+}
+
+int fd_cloexec(int fd, bool cloexec) {
+ int flags;
+
+ assert(fd >= 0);
+
+ if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
+ return -errno;
+
+ if (cloexec)
+ flags |= FD_CLOEXEC;
+ else
+ flags &= ~FD_CLOEXEC;
+
+ if (fcntl(fd, F_SETFD, flags) < 0)
+ return -errno;
+
+ return 0;
+}
+
+_pure_ static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
+ unsigned i;
+
+ assert(n_fdset == 0 || fdset);
+
+ for (i = 0; i < n_fdset; i++)
+ if (fdset[i] == fd)
+ return true;
+
+ return false;
+}
+
+int close_all_fds(const int except[], unsigned n_except) {
+ DIR *d;
+ struct dirent *de;
+ int r = 0;
+
+ assert(n_except == 0 || except);
+
+ d = opendir("/proc/self/fd");
+ if (!d) {
+ int fd;
+ struct rlimit rl;
+
+ /* When /proc isn't available (for example in chroots)
+ * the fallback is brute forcing through the fd
+ * table */
+
+ assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
+ for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
+
+ if (fd_in_set(fd, except, n_except))
+ continue;
+
+ if (close_nointr(fd) < 0)
+ if (errno != EBADF && r == 0)
+ r = -errno;
+ }
+
+ return r;
+ }
+
+ while ((de = readdir(d))) {
+ int fd = -1;
+
+ if (ignore_file(de->d_name))
+ continue;
+
+ if (safe_atoi(de->d_name, &fd) < 0)
+ /* Let's better ignore this, just in case */
+ continue;
+
+ if (fd < 3)
+ continue;
+
+ if (fd == dirfd(d))
+ continue;
+
+ if (fd_in_set(fd, except, n_except))
+ continue;
+
+ if (close_nointr(fd) < 0) {
+ /* Valgrind has its own FD and doesn't want to have it closed */
+ if (errno != EBADF && r == 0)
+ r = -errno;
+ }
+ }
+
+ closedir(d);
+ return r;
+}
+
+bool chars_intersect(const char *a, const char *b) {
+ const char *p;
+
+ /* Returns true if any of the chars in a are in b. */
+ for (p = a; *p; p++)
+ if (strchr(b, *p))
+ return true;
+
+ return false;
+}
+
+bool fstype_is_network(const char *fstype) {
+ static const char table[] =
+ "cifs\0"
+ "smbfs\0"
+ "ncpfs\0"
+ "nfs\0"
+ "nfs4\0"
+ "gfs\0"
+ "gfs2\0";
+
+ return nulstr_contains(table, fstype);
+}
+
+int chvt(int vt) {
+ _cleanup_close_ int fd;
+
+ fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
+ if (fd < 0)
+ return -errno;
+
+ if (vt < 0) {
+ int tiocl[2] = {
+ TIOCL_GETKMSGREDIRECT,
+ 0
+ };
+
+ if (ioctl(fd, TIOCLINUX, tiocl) < 0)
+ return -errno;
+
+ vt = tiocl[0] <= 0 ? 1 : tiocl[0];
+ }
+
+ if (ioctl(fd, VT_ACTIVATE, vt) < 0)
+ return -errno;
+
+ return 0;
+}
+
+int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
+ struct termios old_termios, new_termios;
+ char c;
+ char line[LINE_MAX];
+
+ assert(f);
+ assert(ret);
+
+ if (tcgetattr(fileno(f), &old_termios) >= 0) {
+ new_termios = old_termios;
+
+ new_termios.c_lflag &= ~ICANON;
+ new_termios.c_cc[VMIN] = 1;
+ new_termios.c_cc[VTIME] = 0;
+
+ if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
+ size_t k;
+
+ if (t != (usec_t) -1) {
+ if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
+ tcsetattr(fileno(f), TCSADRAIN, &old_termios);
+ return -ETIMEDOUT;
+ }
+ }
+
+ k = fread(&c, 1, 1, f);
+
+ tcsetattr(fileno(f), TCSADRAIN, &old_termios);
+
+ if (k <= 0)
+ return -EIO;
+
+ if (need_nl)
+ *need_nl = c != '\n';
+
+ *ret = c;
+ return 0;
+ }
+ }
+
+ if (t != (usec_t) -1)
+ if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
+ return -ETIMEDOUT;
+
+ if (!fgets(line, sizeof(line), f))
+ return -EIO;
+
+ truncate_nl(line);
+
+ if (strlen(line) != 1)
+ return -EBADMSG;
+
+ if (need_nl)
+ *need_nl = false;
+
+ *ret = line[0];
+ return 0;
+}
+
+int ask(char *ret, const char *replies, const char *text, ...) {
+
+ assert(ret);
+ assert(replies);
+ assert(text);
+
+ for (;;) {
+ va_list ap;
+ char c;
+ int r;
+ bool need_nl = true;
+
+ if (on_tty())
+ fputs(ANSI_HIGHLIGHT_ON, stdout);
+
+ va_start(ap, text);
+ vprintf(text, ap);
+ va_end(ap);
+
+ if (on_tty())
+ fputs(ANSI_HIGHLIGHT_OFF, stdout);
+
+ fflush(stdout);
+
+ r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
+ if (r < 0) {
+
+ if (r == -EBADMSG) {
+ puts("Bad input, please try again.");
+ continue;
+ }
+
+ putchar('\n');
+ return r;
+ }
+
+ if (need_nl)
+ putchar('\n');
+
+ if (strchr(replies, c)) {
+ *ret = c;
+ return 0;
+ }
+
+ puts("Read unexpected character, please try again.");
+ }
+}
+
+int reset_terminal_fd(int fd, bool switch_to_text) {
+ struct termios termios;
+ int r = 0;
+
+ /* Set terminal to some sane defaults */
+
+ assert(fd >= 0);
+
+ /* We leave locked terminal attributes untouched, so that
+ * Plymouth may set whatever it wants to set, and we don't
+ * interfere with that. */
+
+ /* Disable exclusive mode, just in case */
+ ioctl(fd, TIOCNXCL);
+
+ /* Switch to text mode */
+ if (switch_to_text)
+ ioctl(fd, KDSETMODE, KD_TEXT);
+
+ /* Enable console unicode mode */
+ ioctl(fd, KDSKBMODE, K_UNICODE);
+
+ if (tcgetattr(fd, &termios) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ /* We only reset the stuff that matters to the software. How
+ * hardware is set up we don't touch assuming that somebody
+ * else will do that for us */
+
+ termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
+ termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
+ termios.c_oflag |= ONLCR;
+ termios.c_cflag |= CREAD;
+ termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
+
+ termios.c_cc[VINTR] = 03; /* ^C */
+ termios.c_cc[VQUIT] = 034; /* ^\ */
+ termios.c_cc[VERASE] = 0177;
+ termios.c_cc[VKILL] = 025; /* ^X */
+ termios.c_cc[VEOF] = 04; /* ^D */
+ termios.c_cc[VSTART] = 021; /* ^Q */
+ termios.c_cc[VSTOP] = 023; /* ^S */
+ termios.c_cc[VSUSP] = 032; /* ^Z */
+ termios.c_cc[VLNEXT] = 026; /* ^V */
+ termios.c_cc[VWERASE] = 027; /* ^W */
+ termios.c_cc[VREPRINT] = 022; /* ^R */
+ termios.c_cc[VEOL] = 0;
+ termios.c_cc[VEOL2] = 0;
+
+ termios.c_cc[VTIME] = 0;
+ termios.c_cc[VMIN] = 1;
+
+ if (tcsetattr(fd, TCSANOW, &termios) < 0)
+ r = -errno;
+
+finish:
+ /* Just in case, flush all crap out */
+ tcflush(fd, TCIOFLUSH);
+
+ return r;
+}
+
+int reset_terminal(const char *name) {
+ int fd, r;
+
+ fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
+ if (fd < 0)
+ return fd;
+
+ r = reset_terminal_fd(fd, true);
+ close_nointr_nofail(fd);
+
+ return r;
+}
+
+int open_terminal(const char *name, int mode) {
+ int fd, r;
+ unsigned c = 0;
+
+ /*
+ * If a TTY is in the process of being closed opening it might
+ * cause EIO. This is horribly awful, but unlikely to be
+ * changed in the kernel. Hence we work around this problem by
+ * retrying a couple of times.
+ *
+ * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
+ */
+
+ for (;;) {
+ fd = open(name, mode);
+ if (fd >= 0)
+ break;
+
+ if (errno != EIO)
+ return -errno;
+
+ /* Max 1s in total */
+ if (c >= 20)
+ return -errno;
+
+ usleep(50 * USEC_PER_MSEC);
+ c++;
+ }
+
+ if (fd < 0)
+ return -errno;
+
+ r = isatty(fd);
+ if (r < 0) {
+ close_nointr_nofail(fd);
+ return -errno;
+ }
+
+ if (!r) {
+ close_nointr_nofail(fd);
+ return -ENOTTY;
+ }
+
+ return fd;
+}
+
+int flush_fd(int fd) {
+ struct pollfd pollfd = {
+ .fd = fd,
+ .events = POLLIN,
+ };
+
+ for (;;) {
+ char buf[LINE_MAX];
+ ssize_t l;
+ int r;
+
+ r = poll(&pollfd, 1, 0);
+ if (r < 0) {
+ if (errno == EINTR)
+ continue;
+
+ return -errno;
+
+ } else if (r == 0)
+ return 0;
+
+ l = read(fd, buf, sizeof(buf));
+ if (l < 0) {
+
+ if (errno == EINTR)
+ continue;
+
+ if (errno == EAGAIN)
+ return 0;
+
+ return -errno;
+ } else if (l == 0)
+ return 0;
+ }
+}
+
+int acquire_terminal(
+ const char *name,
+ bool fail,
+ bool force,
+ bool ignore_tiocstty_eperm,
+ usec_t timeout) {
+
+ int fd = -1, notify = -1, r = 0, wd = -1;
+ usec_t ts = 0;
+
+ assert(name);
+
+ /* We use inotify to be notified when the tty is closed. We
+ * create the watch before checking if we can actually acquire
+ * it, so that we don't lose any event.
+ *
+ * Note: strictly speaking this actually watches for the
+ * device being closed, it does *not* really watch whether a
+ * tty loses its controlling process. However, unless some
+ * rogue process uses TIOCNOTTY on /dev/tty *after* closing
+ * its tty otherwise this will not become a problem. As long
+ * as the administrator makes sure not configure any service
+ * on the same tty as an untrusted user this should not be a
+ * problem. (Which he probably should not do anyway.) */
+
+ if (timeout != (usec_t) -1)
+ ts = now(CLOCK_MONOTONIC);
+
+ if (!fail && !force) {
+ notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
+ if (notify < 0) {
+ r = -errno;
+ goto fail;
+ }
+
+ wd = inotify_add_watch(notify, name, IN_CLOSE);
+ if (wd < 0) {
+ r = -errno;
+ goto fail;
+ }
+ }
+
+ for (;;) {
+ struct sigaction sa_old, sa_new = {
+ .sa_handler = SIG_IGN,
+ .sa_flags = SA_RESTART,
+ };
+
+ if (notify >= 0) {
+ r = flush_fd(notify);
+ if (r < 0)
+ goto fail;
+ }
+
+ /* We pass here O_NOCTTY only so that we can check the return
+ * value TIOCSCTTY and have a reliable way to figure out if we
+ * successfully became the controlling process of the tty */
+ fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
+ if (fd < 0)
+ return fd;
+
+ /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
+ * if we already own the tty. */
+ assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
+
+ /* First, try to get the tty */
+ if (ioctl(fd, TIOCSCTTY, force) < 0)
+ r = -errno;
+
+ assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
+
+ /* Sometimes it makes sense to ignore TIOCSCTTY
+ * returning EPERM, i.e. when very likely we already
+ * are have this controlling terminal. */
+ if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
+ r = 0;
+
+ if (r < 0 && (force || fail || r != -EPERM)) {
+ goto fail;
+ }
+
+ if (r >= 0)
+ break;
+
+ assert(!fail);
+ assert(!force);
+ assert(notify >= 0);
+
+ for (;;) {
+ uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
+ ssize_t l;
+ struct inotify_event *e;
+
+ if (timeout != (usec_t) -1) {
+ usec_t n;
+
+ n = now(CLOCK_MONOTONIC);
+ if (ts + timeout < n) {
+ r = -ETIMEDOUT;
+ goto fail;
+ }
+
+ r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
+ if (r < 0)
+ goto fail;
+
+ if (r == 0) {
+ r = -ETIMEDOUT;
+ goto fail;
+ }
+ }
+
+ l = read(notify, inotify_buffer, sizeof(inotify_buffer));
+ if (l < 0) {
+
+ if (errno == EINTR || errno == EAGAIN)
+ continue;
+
+ r = -errno;
+ goto fail;
+ }
+
+ e = (struct inotify_event*) inotify_buffer;
+
+ while (l > 0) {
+ size_t step;
+
+ if (e->wd != wd || !(e->mask & IN_CLOSE)) {
+ r = -EIO;
+ goto fail;
+ }
+
+ step = sizeof(struct inotify_event) + e->len;
+ assert(step <= (size_t) l);
+
+ e = (struct inotify_event*) ((uint8_t*) e + step);
+ l -= step;
+ }
+
+ break;
+ }
+
+ /* We close the tty fd here since if the old session
+ * ended our handle will be dead. It's important that
+ * we do this after sleeping, so that we don't enter
+ * an endless loop. */
+ close_nointr_nofail(fd);
+ }
+
+ if (notify >= 0)
+ close_nointr_nofail(notify);
+
+ r = reset_terminal_fd(fd, true);
+ if (r < 0)
+ log_warning("Failed to reset terminal: %s", strerror(-r));
+
+ return fd;
+
+fail:
+ if (fd >= 0)
+ close_nointr_nofail(fd);
+
+ if (notify >= 0)
+ close_nointr_nofail(notify);
+
+ return r;
+}
+
+int release_terminal(void) {
+ int r = 0;
+ struct sigaction sa_old, sa_new = {
+ .sa_handler = SIG_IGN,
+ .sa_flags = SA_RESTART,
+ };
+ _cleanup_close_ int fd;
+
+ fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC);
+ if (fd < 0)
+ return -errno;
+
+ /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
+ * by our own TIOCNOTTY */
+ assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
+
+ if (ioctl(fd, TIOCNOTTY) < 0)
+ r = -errno;
+
+ assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
+
+ return r;
+}
+
+int sigaction_many(const struct sigaction *sa, ...) {
+ va_list ap;
+ int r = 0, sig;
+
+ va_start(ap, sa);
+ while ((sig = va_arg(ap, int)) > 0)
+ if (sigaction(sig, sa, NULL) < 0)
+ r = -errno;
+ va_end(ap);
+
+ return r;
+}
+
+int ignore_signals(int sig, ...) {
+ struct sigaction sa = {
+ .sa_handler = SIG_IGN,
+ .sa_flags = SA_RESTART,
+ };
+ va_list ap;
+ int r = 0;
+
+
+ if (sigaction(sig, &sa, NULL) < 0)
+ r = -errno;
+
+ va_start(ap, sig);
+ while ((sig = va_arg(ap, int)) > 0)
+ if (sigaction(sig, &sa, NULL) < 0)
+ r = -errno;
+ va_end(ap);
+
+ return r;
+}
+
+int default_signals(int sig, ...) {
+ struct sigaction sa = {
+ .sa_handler = SIG_DFL,
+ .sa_flags = SA_RESTART,
+ };
+ va_list ap;
+ int r = 0;
+
+ if (sigaction(sig, &sa, NULL) < 0)
+ r = -errno;
+
+ va_start(ap, sig);
+ while ((sig = va_arg(ap, int)) > 0)
+ if (sigaction(sig, &sa, NULL) < 0)
+ r = -errno;
+ va_end(ap);
+
+ return r;
+}
+
+int close_pipe(int p[]) {
+ int a = 0, b = 0;
+
+ assert(p);
+
+ if (p[0] >= 0) {
+ a = close_nointr(p[0]);
+ p[0] = -1;
+ }
+
+ if (p[1] >= 0) {
+ b = close_nointr(p[1]);
+ p[1] = -1;
+ }
+
+ return a < 0 ? a : b;
+}
+
+ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
+ uint8_t *p;
+ ssize_t n = 0;
+
+ assert(fd >= 0);
+ assert(buf);
+
+ p = buf;
+
+ while (nbytes > 0) {
+ ssize_t k;
+
+ if ((k = read(fd, p, nbytes)) <= 0) {
+
+ if (k < 0 && errno == EINTR)
+ continue;
+
+ if (k < 0 && errno == EAGAIN && do_poll) {
+ struct pollfd pollfd = {
+ .fd = fd,
+ .events = POLLIN,
+ };
+
+ if (poll(&pollfd, 1, -1) < 0) {
+ if (errno == EINTR)
+ continue;
+
+ return n > 0 ? n : -errno;
+ }
+
+ if (pollfd.revents != POLLIN)
+ return n > 0 ? n : -EIO;
+
+ continue;
+ }
+
+ return n > 0 ? n : (k < 0 ? -errno : 0);
+ }
+
+ p += k;
+ nbytes -= k;
+ n += k;
+ }
+
+ return n;
+}
+
+ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
+ const uint8_t *p;
+ ssize_t n = 0;
+
+ assert(fd >= 0);
+ assert(buf);
+
+ p = buf;
+
+ while (nbytes > 0) {
+ ssize_t k;
+
+ k = write(fd, p, nbytes);
+ if (k <= 0) {
+
+ if (k < 0 && errno == EINTR)
+ continue;
+
+ if (k < 0 && errno == EAGAIN && do_poll) {
+ struct pollfd pollfd = {
+ .fd = fd,
+ .events = POLLOUT,
+ };
+
+ if (poll(&pollfd, 1, -1) < 0) {
+ if (errno == EINTR)
+ continue;
+
+ return n > 0 ? n : -errno;
+ }
+
+ if (pollfd.revents != POLLOUT)
+ return n > 0 ? n : -EIO;
+
+ continue;
+ }
+
+ return n > 0 ? n : (k < 0 ? -errno : 0);
+ }
+
+ p += k;
+ nbytes -= k;
+ n += k;
+ }
+
+ return n;
+}
+
+int parse_bytes(const char *t, off_t *bytes) {
+ static const struct {
+ const char *suffix;
+ off_t factor;
+ } table[] = {
+ { "B", 1 },
+ { "K", 1024ULL },
+ { "M", 1024ULL*1024ULL },
+ { "G", 1024ULL*1024ULL*1024ULL },
+ { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
+ { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
+ { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
+ { "", 1 },
+ };
+
+ const char *p;
+ off_t r = 0;
+
+ assert(t);
+ assert(bytes);
+
+ p = t;
+ do {
+ long long l;
+ char *e;
+ unsigned i;
+
+ errno = 0;
+ l = strtoll(p, &e, 10);
+
+ if (errno > 0)
+ return -errno;
+
+ if (l < 0)
+ return -ERANGE;
+
+ if (e == p)
+ return -EINVAL;
+
+ e += strspn(e, WHITESPACE);
+
+ for (i = 0; i < ELEMENTSOF(table); i++)
+ if (startswith(e, table[i].suffix)) {
+ r += (off_t) l * table[i].factor;
+ p = e + strlen(table[i].suffix);
+ break;
+ }
+
+ if (i >= ELEMENTSOF(table))
+ return -EINVAL;
+
+ } while (*p != 0);
+
+ *bytes = r;
+
+ return 0;
+}
+
+int make_stdio(int fd) {
+ int r, s, t;
+
+ assert(fd >= 0);
+
+ r = dup3(fd, STDIN_FILENO, 0);
+ s = dup3(fd, STDOUT_FILENO, 0);
+ t = dup3(fd, STDERR_FILENO, 0);
+
+ if (fd >= 3)
+ close_nointr_nofail(fd);
+
+ if (r < 0 || s < 0 || t < 0)
+ return -errno;
+
+ /* We rely here that the new fd has O_CLOEXEC not set */
+
+ return 0;
+}
+
+int make_null_stdio(void) {
+ int null_fd;
+
+ null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
+ if (null_fd < 0)
+ return -errno;
+
+ return make_stdio(null_fd);
+}
+
+bool is_device_path(const char *path) {
+
+ /* Returns true on paths that refer to a device, either in
+ * sysfs or in /dev */
+
+ return
+ path_startswith(path, "/dev/") ||
+ path_startswith(path, "/sys/");
+}
+
+int dir_is_empty(const char *path) {
+ _cleanup_closedir_ DIR *d;
+ int r;
+
+ d = opendir(path);
+ if (!d)
+ return -errno;
+
+ for (;;) {
+ struct dirent *de;
+ union dirent_storage buf;
+
+ r = readdir_r(d, &buf.de, &de);
+ if (r > 0)
+ return -r;
+
+ if (!de)
+ return 1;
+
+ if (!ignore_file(de->d_name))
+ return 0;
+ }
+}
+
+char* dirname_malloc(const char *path) {
+ char *d, *dir, *dir2;
+
+ d = strdup(path);
+ if (!d)
+ return NULL;
+ dir = dirname(d);
+ assert(dir);
+
+ if (dir != d) {
+ dir2 = strdup(dir);
+ free(d);
+ return dir2;
+ }
+
+ return dir;
+}
+
+unsigned long long random_ull(void) {
+ _cleanup_close_ int fd;
+ uint64_t ull;
+ ssize_t r;
+
+ fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
+ if (fd < 0)
+ goto fallback;
+
+ r = loop_read(fd, &ull, sizeof(ull), true);
+ if (r != sizeof(ull))
+ goto fallback;
+
+ return ull;
+
+fallback:
+ return random() * RAND_MAX + random();
+}
+
+void rename_process(const char name[8]) {
+ assert(name);
+
+ /* This is a like a poor man's setproctitle(). It changes the
+ * comm field, argv[0], and also the glibc's internally used
+ * name of the process. For the first one a limit of 16 chars
+ * applies, to the second one usually one of 10 (i.e. length
+ * of "/sbin/init"), to the third one one of 7 (i.e. length of
+ * "systemd"). If you pass a longer string it will be
+ * truncated */
+
+ prctl(PR_SET_NAME, name);
+
+ if (program_invocation_name)
+ strncpy(program_invocation_name, name, strlen(program_invocation_name));
+
+ if (saved_argc > 0) {
+ int i;
+
+ if (saved_argv[0])
+ strncpy(saved_argv[0], name, strlen(saved_argv[0]));
+
+ for (i = 1; i < saved_argc; i++) {
+ if (!saved_argv[i])
+ break;
+
+ memset(saved_argv[i], 0, strlen(saved_argv[i]));
+ }
+ }
+}
+
+void sigset_add_many(sigset_t *ss, ...) {
+ va_list ap;
+ int sig;
+
+ assert(ss);
+
+ va_start(ap, ss);
+ while ((sig = va_arg(ap, int)) > 0)
+ assert_se(sigaddset(ss, sig) == 0);
+ va_end(ap);
+}
+
+char* gethostname_malloc(void) {
+ struct utsname u;
+
+ assert_se(uname(&u) >= 0);
+
+ if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
+ return strdup(u.nodename);
+
+ return strdup(u.sysname);
+}
+
+bool hostname_is_set(void) {
+ struct utsname u;
+
+ assert_se(uname(&u) >= 0);
+
+ return !isempty(u.nodename) && !streq(u.nodename, "(none)");
+}
+
+static char *lookup_uid(uid_t uid) {
+ long bufsize;
+ char *name;
+ _cleanup_free_ char *buf = NULL;
+ struct passwd pwbuf, *pw = NULL;
+
+ /* Shortcut things to avoid NSS lookups */
+ if (uid == 0)
+ return strdup("root");
+
+ bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
+ if (bufsize <= 0)
+ bufsize = 4096;
+
+ buf = malloc(bufsize);
+ if (!buf)
+ return NULL;
+
+ if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
+ return strdup(pw->pw_name);
+
+ if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
+ return NULL;
+
+ return name;
+}
+
+char* getlogname_malloc(void) {
+ uid_t uid;
+ struct stat st;
+
+ if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
+ uid = st.st_uid;
+ else
+ uid = getuid();
+
+ return lookup_uid(uid);
+}
+
+char *getusername_malloc(void) {
+ const char *e;
+
+ e = getenv("USER");
+ if (e)
+ return strdup(e);
+
+ return lookup_uid(getuid());
+}
+
+int getttyname_malloc(int fd, char **r) {
+ char path[PATH_MAX], *c;
+ int k;
+
+ assert(r);
+
+ k = ttyname_r(fd, path, sizeof(path));
+ if (k != 0)
+ return -k;
+
+ char_array_0(path);
+
+ c = strdup(startswith(path, "/dev/") ? path + 5 : path);
+ if (!c)
+ return -ENOMEM;
+
+ *r = c;
+ return 0;
+}
+
+int getttyname_harder(int fd, char **r) {
+ int k;
+ char *s;
+
+ k = getttyname_malloc(fd, &s);
+ if (k < 0)
+ return k;
+
+ if (streq(s, "tty")) {
+ free(s);
+ return get_ctty(0, NULL, r);
+ }
+
+ *r = s;
+ return 0;
+}
+
+int get_ctty_devnr(pid_t pid, dev_t *d) {
+ _cleanup_fclose_ FILE *f = NULL;
+ char line[LINE_MAX], *p;
+ unsigned long ttynr;
+ const char *fn;
+ int k;
+
+ assert(pid >= 0);
+ assert(d);
+
+ if (pid == 0)
+ fn = "/proc/self/stat";
+ else
+ fn = procfs_file_alloca(pid, "stat");
+
+ f = fopen(fn, "re");
+ if (!f)
+ return -errno;
+
+ if (!fgets(line, sizeof(line), f)) {
+ k = feof(f) ? -EIO : -errno;
+ return k;
+ }
+
+ p = strrchr(line, ')');
+ if (!p)
+ return -EIO;
+
+ p++;
+
+ if (sscanf(p, " "
+ "%*c " /* state */
+ "%*d " /* ppid */
+ "%*d " /* pgrp */
+ "%*d " /* session */
+ "%lu ", /* ttynr */
+ &ttynr) != 1)
+ return -EIO;
+
+ if (major(ttynr) == 0 && minor(ttynr) == 0)
+ return -ENOENT;
+
+ *d = (dev_t) ttynr;
+ return 0;
+}
+
+int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
+ int k;
+ char fn[sizeof("/dev/char/")-1 + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *s, *b, *p;
+ dev_t devnr;
+
+ assert(r);
+
+ k = get_ctty_devnr(pid, &devnr);
+ if (k < 0)
+ return k;
+
+ snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
+
+ k = readlink_malloc(fn, &s);
+ if (k < 0) {
+
+ if (k != -ENOENT)
+ return k;
+
+ /* This is an ugly hack */
+ if (major(devnr) == 136) {
+ if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
+ return -ENOMEM;
+
+ *r = b;
+ if (_devnr)
+ *_devnr = devnr;
+
+ return 0;
+ }
+
+ /* Probably something like the ptys which have no
+ * symlink in /dev/char. Let's return something
+ * vaguely useful. */
+
+ b = strdup(fn + 5);
+ if (!b)
+ return -ENOMEM;
+
+ *r = b;
+ if (_devnr)
+ *_devnr = devnr;
+
+ return 0;
+ }
+
+ if (startswith(s, "/dev/"))
+ p = s + 5;
+ else if (startswith(s, "../"))
+ p = s + 3;
+ else
+ p = s;
+
+ b = strdup(p);
+ free(s);
+
+ if (!b)
+ return -ENOMEM;
+
+ *r = b;
+ if (_devnr)
+ *_devnr = devnr;
+
+ return 0;
+}
+
+int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
+ DIR *d;
+ int ret = 0;
+
+ assert(fd >= 0);
+
+ /* This returns the first error we run into, but nevertheless
+ * tries to go on. This closes the passed fd. */
+
+ d = fdopendir(fd);
+ if (!d) {
+ close_nointr_nofail(fd);
+
+ return errno == ENOENT ? 0 : -errno;
+ }
+
+ for (;;) {
+ struct dirent *de;
+ union dirent_storage buf;
+ bool is_dir, keep_around;
+ struct stat st;
+ int r;
+
+ r = readdir_r(d, &buf.de, &de);
+ if (r != 0 && ret == 0) {
+ ret = -r;
+ break;
+ }
+
+ if (!de)
+ break;
+
+ if (streq(de->d_name, ".") || streq(de->d_name, ".."))
+ continue;
+
+ if (de->d_type == DT_UNKNOWN ||
+ honour_sticky ||
+ (de->d_type == DT_DIR && root_dev)) {
+ if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
+ if (ret == 0 && errno != ENOENT)
+ ret = -errno;
+ continue;
+ }
+
+ is_dir = S_ISDIR(st.st_mode);
+ keep_around =
+ honour_sticky &&
+ (st.st_uid == 0 || st.st_uid == getuid()) &&
+ (st.st_mode & S_ISVTX);
+ } else {
+ is_dir = de->d_type == DT_DIR;
+ keep_around = false;
+ }
+
+ if (is_dir) {
+ int subdir_fd;
+
+ /* if root_dev is set, remove subdirectories only, if device is same as dir */
+ if (root_dev && st.st_dev != root_dev->st_dev)
+ continue;
+
+ subdir_fd = openat(fd, de->d_name,
+ O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
+ if (subdir_fd < 0) {
+ if (ret == 0 && errno != ENOENT)
+ ret = -errno;
+ continue;
+ }
+
+ r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
+ if (r < 0 && ret == 0)
+ ret = r;
+
+ if (!keep_around)
+ if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
+ if (ret == 0 && errno != ENOENT)
+ ret = -errno;
+ }
+
+ } else if (!only_dirs && !keep_around) {
+
+ if (unlinkat(fd, de->d_name, 0) < 0) {
+ if (ret == 0 && errno != ENOENT)
+ ret = -errno;
+ }
+ }
+ }
+
+ closedir(d);
+
+ return ret;
+}
+
+_pure_ static int is_temporary_fs(struct statfs *s) {
+ assert(s);
+ return
+ F_TYPE_CMP(s->f_type, TMPFS_MAGIC) ||
+ F_TYPE_CMP(s->f_type, RAMFS_MAGIC);
+}
+
+int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
+ struct statfs s;
+
+ assert(fd >= 0);
+
+ if (fstatfs(fd, &s) < 0) {
+ close_nointr_nofail(fd);
+ return -errno;
+ }
+
+ /* We refuse to clean disk file systems with this call. This
+ * is extra paranoia just to be sure we never ever remove
+ * non-state data */
+ if (!is_temporary_fs(&s)) {
+ log_error("Attempted to remove disk file system, and we can't allow that.");
+ close_nointr_nofail(fd);
+ return -EPERM;
+ }
+
+ return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
+}
+
+static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
+ int fd, r;
+ struct statfs s;
+
+ assert(path);
+
+ /* We refuse to clean the root file system with this
+ * call. This is extra paranoia to never cause a really
+ * seriously broken system. */
+ if (path_equal(path, "/")) {
+ log_error("Attempted to remove entire root file system, and we can't allow that.");
+ return -EPERM;
+ }
+
+ fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
+ if (fd < 0) {
+
+ if (errno != ENOTDIR)
+ return -errno;
+
+ if (!dangerous) {
+ if (statfs(path, &s) < 0)
+ return -errno;
+
+ if (!is_temporary_fs(&s)) {
+ log_error("Attempted to remove disk file system, and we can't allow that.");
+ return -EPERM;
+ }
+ }
+
+ if (delete_root && !only_dirs)
+ if (unlink(path) < 0 && errno != ENOENT)
+ return -errno;
+
+ return 0;
+ }
+
+ if (!dangerous) {
+ if (fstatfs(fd, &s) < 0) {
+ close_nointr_nofail(fd);
+ return -errno;
+ }
+
+ if (!is_temporary_fs(&s)) {
+ log_error("Attempted to remove disk file system, and we can't allow that.");
+ close_nointr_nofail(fd);
+ return -EPERM;
+ }
+ }
+
+ r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
+ if (delete_root) {
+
+ if (honour_sticky && file_is_priv_sticky(path) > 0)
+ return r;
+
+ if (rmdir(path) < 0 && errno != ENOENT) {
+ if (r == 0)
+ r = -errno;
+ }
+ }
+
+ return r;
+}
+
+int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
+ return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
+}
+
+int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
+ return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
+}
+
+int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
+ assert(path);
+
+ /* Under the assumption that we are running privileged we
+ * first change the access mode and only then hand out
+ * ownership to avoid a window where access is too open. */
+
+ if (mode != (mode_t) -1)
+ if (chmod(path, mode) < 0)
+ return -errno;
+
+ if (uid != (uid_t) -1 || gid != (gid_t) -1)
+ if (chown(path, uid, gid) < 0)
+ return -errno;
+
+ return 0;
+}
+
+int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
+ assert(fd >= 0);
+
+ /* Under the assumption that we are running privileged we
+ * first change the access mode and only then hand out
+ * ownership to avoid a window where access is too open. */
+
+ if (fchmod(fd, mode) < 0)
+ return -errno;
+
+ if (fchown(fd, uid, gid) < 0)
+ return -errno;
+
+ return 0;
+}
+
+cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
+ cpu_set_t *r;
+ unsigned n = 1024;
+
+ /* Allocates the cpuset in the right size */
+
+ for (;;) {
+ if (!(r = CPU_ALLOC(n)))
+ return NULL;
+
+ if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
+ CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
+
+ if (ncpus)
+ *ncpus = n;
+
+ return r;
+ }
+
+ CPU_FREE(r);
+
+ if (errno != EINVAL)
+ return NULL;
+
+ n *= 2;
+ }
+}
+
+int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
+ static const char status_indent[] = " "; /* "[" STATUS "] " */
+ _cleanup_free_ char *s = NULL;
+ _cleanup_close_ int fd = -1;
+ struct iovec iovec[6] = {};
+ int n = 0;
+ static bool prev_ephemeral;
+
+ assert(format);
+
+ /* This is independent of logging, as status messages are
+ * optional and go exclusively to the console. */
+
+ if (vasprintf(&s, format, ap) < 0)
+ return log_oom();
+
+ fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
+ if (fd < 0)
+ return fd;
+
+ if (ellipse) {
+ char *e;
+ size_t emax, sl;
+ int c;
+
+ c = fd_columns(fd);
+ if (c <= 0)
+ c = 80;
+
+ sl = status ? sizeof(status_indent)-1 : 0;
+
+ emax = c - sl - 1;
+ if (emax < 3)
+ emax = 3;
+
+ e = ellipsize(s, emax, 75);
+ if (e) {
+ free(s);
+ s = e;
+ }
+ }
+
+ if (prev_ephemeral)
+ IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
+ prev_ephemeral = ephemeral;
+
+ if (status) {
+ if (!isempty(status)) {
+ IOVEC_SET_STRING(iovec[n++], "[");
+ IOVEC_SET_STRING(iovec[n++], status);
+ IOVEC_SET_STRING(iovec[n++], "] ");
+ } else
+ IOVEC_SET_STRING(iovec[n++], status_indent);
+ }
+
+ IOVEC_SET_STRING(iovec[n++], s);
+ if (!ephemeral)
+ IOVEC_SET_STRING(iovec[n++], "\n");
+
+ if (writev(fd, iovec, n) < 0)
+ return -errno;
+
+ return 0;
+}
+
+int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
+ va_list ap;
+ int r;
+
+ assert(format);
+
+ va_start(ap, format);
+ r = status_vprintf(status, ellipse, ephemeral, format, ap);
+ va_end(ap);
+
+ return r;
+}
+
+int status_welcome(void) {
+ int r;
+ _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
+
+ r = parse_env_file("/etc/os-release", NEWLINE,
+ "PRETTY_NAME", &pretty_name,
+ "ANSI_COLOR", &ansi_color,
+ NULL);
+ if (r < 0 && r != -ENOENT)
+ log_warning("Failed to read /etc/os-release: %s", strerror(-r));
+
+ return status_printf(NULL, false, false,
+ "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
+ isempty(ansi_color) ? "1" : ansi_color,
+ isempty(pretty_name) ? "Linux" : pretty_name);
+}
+
+char *replace_env(const char *format, char **env) {
+ enum {
+ WORD,
+ CURLY,
+ VARIABLE
+ } state = WORD;
+
+ const char *e, *word = format;
+ char *r = NULL, *k;
+
+ assert(format);
+
+ for (e = format; *e; e ++) {
+
+ switch (state) {
+
+ case WORD:
+ if (*e == '$')
+ state = CURLY;
+ break;
+
+ case CURLY:
+ if (*e == '{') {
+ if (!(k = strnappend(r, word, e-word-1)))
+ goto fail;
+
+ free(r);
+ r = k;
+
+ word = e-1;
+ state = VARIABLE;
+
+ } else if (*e == '$') {
+ if (!(k = strnappend(r, word, e-word)))
+ goto fail;
+
+ free(r);
+ r = k;
+
+ word = e+1;
+ state = WORD;
+ } else
+ state = WORD;
+ break;
+
+ case VARIABLE:
+ if (*e == '}') {
+ const char *t;
+
+ t = strempty(strv_env_get_n(env, word+2, e-word-2));
+
+ k = strappend(r, t);
+ if (!k)
+ goto fail;
+
+ free(r);
+ r = k;
+
+ word = e+1;
+ state = WORD;
+ }
+ break;
+ }
+ }
+
+ if (!(k = strnappend(r, word, e-word)))
+ goto fail;
+
+ free(r);
+ return k;
+
+fail:
+ free(r);
+ return NULL;
+}
+
+char **replace_env_argv(char **argv, char **env) {
+ char **r, **i;
+ unsigned k = 0, l = 0;
+
+ l = strv_length(argv);
+
+ if (!(r = new(char*, l+1)))
+ return NULL;
+
+ STRV_FOREACH(i, argv) {
+
+ /* If $FOO appears as single word, replace it by the split up variable */
+ if ((*i)[0] == '$' && (*i)[1] != '{') {
+ char *e;
+ char **w, **m;
+ unsigned q;
+
+ e = strv_env_get(env, *i+1);
+ if (e) {
+
+ if (!(m = strv_split_quoted(e))) {
+ r[k] = NULL;
+ strv_free(r);
+ return NULL;
+ }
+ } else
+ m = NULL;
+
+ q = strv_length(m);
+ l = l + q - 1;
+
+ if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
+ r[k] = NULL;
+ strv_free(r);
+ strv_free(m);
+ return NULL;
+ }
+
+ r = w;
+ if (m) {
+ memcpy(r + k, m, q * sizeof(char*));
+ free(m);
+ }
+
+ k += q;
+ continue;
+ }
+
+ /* If ${FOO} appears as part of a word, replace it by the variable as-is */
+ if (!(r[k++] = replace_env(*i, env))) {
+ strv_free(r);
+ return NULL;
+ }
+ }
+
+ r[k] = NULL;
+ return r;
+}
+
+int fd_columns(int fd) {
+ struct winsize ws = {};
+
+ if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
+ return -errno;
+
+ if (ws.ws_col <= 0)
+ return -EIO;
+
+ return ws.ws_col;
+}
+
+unsigned columns(void) {
+ const char *e;
+ int c;
+
+ if (_likely_(cached_columns > 0))
+ return cached_columns;
+
+ c = 0;
+ e = getenv("COLUMNS");
+ if (e)
+ safe_atoi(e, &c);
+
+ if (c <= 0)
+ c = fd_columns(STDOUT_FILENO);
+
+ if (c <= 0)
+ c = 80;
+
+ cached_columns = c;
+ return c;
+}
+
+int fd_lines(int fd) {
+ struct winsize ws = {};
+
+ if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
+ return -errno;
+
+ if (ws.ws_row <= 0)
+ return -EIO;
+
+ return ws.ws_row;
+}
+
+unsigned lines(void) {
+ const char *e;
+ unsigned l;
+
+ if (_likely_(cached_lines > 0))
+ return cached_lines;
+
+ l = 0;
+ e = getenv("LINES");
+ if (e)
+ safe_atou(e, &l);
+
+ if (l <= 0)
+ l = fd_lines(STDOUT_FILENO);
+
+ if (l <= 0)
+ l = 24;
+
+ cached_lines = l;
+ return cached_lines;
+}
+
+/* intended to be used as a SIGWINCH sighandler */
+void columns_lines_cache_reset(int signum) {
+ cached_columns = 0;
+ cached_lines = 0;
+}
+
+bool on_tty(void) {
+ static int cached_on_tty = -1;
+
+ if (_unlikely_(cached_on_tty < 0))
+ cached_on_tty = isatty(STDOUT_FILENO) > 0;
+
+ return cached_on_tty;
+}
+
+int running_in_chroot(void) {
+ struct stat a = {}, b = {};
+
+ /* Only works as root */
+ if (stat("/proc/1/root", &a) < 0)
+ return -errno;
+
+ if (stat("/", &b) < 0)
+ return -errno;
+
+ return
+ a.st_dev != b.st_dev ||
+ a.st_ino != b.st_ino;
+}
+
+char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
+ size_t x;
+ char *r;
+
+ assert(s);
+ assert(percent <= 100);
+ assert(new_length >= 3);
+
+ if (old_length <= 3 || old_length <= new_length)
+ return strndup(s, old_length);
+
+ r = new0(char, new_length+1);
+ if (!r)
+ return r;
+
+ x = (new_length * percent) / 100;
+
+ if (x > new_length - 3)
+ x = new_length - 3;
+
+ memcpy(r, s, x);
+ r[x] = '.';
+ r[x+1] = '.';
+ r[x+2] = '.';
+ memcpy(r + x + 3,
+ s + old_length - (new_length - x - 3),
+ new_length - x - 3);
+
+ return r;
+}
+
+char *ellipsize(const char *s, size_t length, unsigned percent) {
+ return ellipsize_mem(s, strlen(s), length, percent);
+}
+
+int touch(const char *path) {
+ int fd;
+
+ assert(path);
+
+ /* This just opens the file for writing, ensuring it
+ * exists. It doesn't call utimensat() the way /usr/bin/touch
+ * does it. */
+
+ fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
+ if (fd < 0)
+ return -errno;
+
+ close_nointr_nofail(fd);
+ return 0;
+}
+
+char *unquote(const char *s, const char* quotes) {
+ size_t l;
+ assert(s);
+
+ /* This is rather stupid, simply removes the heading and
+ * trailing quotes if there is one. Doesn't care about
+ * escaping or anything. We should make this smarter one
+ * day...*/
+
+ l = strlen(s);
+ if (l < 2)
+ return strdup(s);
+
+ if (strchr(quotes, s[0]) && s[l-1] == s[0])
+ return strndup(s+1, l-2);
+
+ return strdup(s);
+}
+
+char *normalize_env_assignment(const char *s) {
+ _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
+ char *eq, *r;
+
+ eq = strchr(s, '=');
+ if (!eq) {
+ char *t;
+
+ r = strdup(s);
+ if (!r)
+ return NULL;
+
+ t = strstrip(r);
+ if (t == r)
+ return r;
+
+ memmove(r, t, strlen(t) + 1);
+ return r;
+ }
+
+ name = strndup(s, eq - s);
+ if (!name)
+ return NULL;
+
+ p = strdup(eq + 1);
+ if (!p)
+ return NULL;
+
+ value = unquote(strstrip(p), QUOTES);
+ if (!value)
+ return NULL;
+
+ if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
+ r = NULL;
+
+ return r;
+}
+
+int wait_for_terminate(pid_t pid, siginfo_t *status) {
+ siginfo_t dummy;
+
+ assert(pid >= 1);
+
+ if (!status)
+ status = &dummy;
+
+ for (;;) {
+ zero(*status);
+
+ if (waitid(P_PID, pid, status, WEXITED) < 0) {
+
+ if (errno == EINTR)
+ continue;
+
+ return -errno;
+ }
+
+ return 0;
+ }
+}
+
+int wait_for_terminate_and_warn(const char *name, pid_t pid) {
+ int r;
+ siginfo_t status;
+
+ assert(name);
+ assert(pid > 1);
+
+ r = wait_for_terminate(pid, &status);
+ if (r < 0) {
+ log_warning("Failed to wait for %s: %s", name, strerror(-r));
+ return r;
+ }
+
+ if (status.si_code == CLD_EXITED) {
+ if (status.si_status != 0) {
+ log_warning("%s failed with error code %i.", name, status.si_status);
+ return status.si_status;
+ }
+
+ log_debug("%s succeeded.", name);
+ return 0;
+
+ } else if (status.si_code == CLD_KILLED ||
+ status.si_code == CLD_DUMPED) {
+
+ log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
+ return -EPROTO;
+ }
+
+ log_warning("%s failed due to unknown reason.", name);
+ return -EPROTO;
+}
+
+_noreturn_ void freeze(void) {
+
+ /* Make sure nobody waits for us on a socket anymore */
+ close_all_fds(NULL, 0);
+
+ sync();
+
+ for (;;)
+ pause();
+}
+
+bool null_or_empty(struct stat *st) {
+ assert(st);
+
+ if (S_ISREG(st->st_mode) && st->st_size <= 0)
+ return true;
+
+ if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
+ return true;
+
+ return false;
+}
+
+int null_or_empty_path(const char *fn) {
+ struct stat st;
+
+ assert(fn);
+
+ if (stat(fn, &st) < 0)
+ return -errno;
+
+ return null_or_empty(&st);
+}
+
+DIR *xopendirat(int fd, const char *name, int flags) {
+ int nfd;
+ DIR *d;
+
+ nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
+ if (nfd < 0)
+ return NULL;
+
+ d = fdopendir(nfd);
+ if (!d) {
+ close_nointr_nofail(nfd);
+ return NULL;
+ }
+
+ return d;
+}
+
+int signal_from_string_try_harder(const char *s) {
+ int signo;
+ assert(s);
+
+ signo = signal_from_string(s);
+ if (signo <= 0)
+ if (startswith(s, "SIG"))
+ return signal_from_string(s+3);
+
+ return signo;
+}
+
+static char *tag_to_udev_node(const char *tagvalue, const char *by) {
+ char *dn, *t, *u;
+ int r;
+
+ /* FIXME: to follow udev's logic 100% we need to leave valid
+ * UTF8 chars unescaped */
+
+ u = unquote(tagvalue, "\"\'");
+ if (u == NULL)
+ return NULL;
+
+ t = xescape(u, "/ ");
+ free(u);
+
+ if (t == NULL)
+ return NULL;
+
+ r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
+ free(t);
+
+ if (r < 0)
+ return NULL;
+
+ return dn;
+}
+
+char *fstab_node_to_udev_node(const char *p) {
+ assert(p);
+
+ if (startswith(p, "LABEL="))
+ return tag_to_udev_node(p+6, "label");
+
+ if (startswith(p, "UUID="))
+ return tag_to_udev_node(p+5, "uuid");
+
+ if (startswith(p, "PARTUUID="))
+ return tag_to_udev_node(p+9, "partuuid");
+
+ if (startswith(p, "PARTLABEL="))
+ return tag_to_udev_node(p+10, "partlabel");
+
+ return strdup(p);
+}
+
+bool tty_is_vc(const char *tty) {
+ assert(tty);
+
+ if (startswith(tty, "/dev/"))
+ tty += 5;
+
+ return vtnr_from_tty(tty) >= 0;
+}
+
+bool tty_is_console(const char *tty) {
+ assert(tty);
+
+ if (startswith(tty, "/dev/"))
+ tty += 5;
+
+ return streq(tty, "console");
+}
+
+int vtnr_from_tty(const char *tty) {
+ int i, r;
+
+ assert(tty);
+
+ if (startswith(tty, "/dev/"))
+ tty += 5;
+
+ if (!startswith(tty, "tty") )
+ return -EINVAL;
+
+ if (tty[3] < '0' || tty[3] > '9')
+ return -EINVAL;
+
+ r = safe_atoi(tty+3, &i);
+ if (r < 0)
+ return r;
+
+ if (i < 0 || i > 63)
+ return -EINVAL;
+
+ return i;
+}
+
+char *resolve_dev_console(char **active) {
+ char *tty;
+
+ /* Resolve where /dev/console is pointing to, if /sys is actually ours
+ * (i.e. not read-only-mounted which is a sign for container setups) */
+
+ if (path_is_read_only_fs("/sys") > 0)
+ return NULL;
+
+ if (read_one_line_file("/sys/class/tty/console/active", active) < 0)
+ return NULL;
+
+ /* If multiple log outputs are configured the last one is what
+ * /dev/console points to */
+ tty = strrchr(*active, ' ');
+ if (tty)
+ tty++;
+ else
+ tty = *active;
+
+ return tty;
+}
+
+bool tty_is_vc_resolve(const char *tty) {
+ char *active = NULL;
+ bool b;
+
+ assert(tty);
+
+ if (startswith(tty, "/dev/"))
+ tty += 5;
+
+ if (streq(tty, "console")) {
+ tty = resolve_dev_console(&active);
+ if (!tty)
+ return false;
+ }
+
+ b = tty_is_vc(tty);
+ free(active);
+
+ return b;
+}
+
+const char *default_term_for_tty(const char *tty) {
+ assert(tty);
+
+ return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
+}
+
+bool dirent_is_file(const struct dirent *de) {
+ assert(de);
+
+ if (ignore_file(de->d_name))
+ return false;
+
+ if (de->d_type != DT_REG &&
+ de->d_type != DT_LNK &&
+ de->d_type != DT_UNKNOWN)
+ return false;
+
+ return true;
+}
+
+bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
+ assert(de);
+
+ if (de->d_type != DT_REG &&
+ de->d_type != DT_LNK &&
+ de->d_type != DT_UNKNOWN)
+ return false;
+
+ if (ignore_file_allow_backup(de->d_name))
+ return false;
+
+ return endswith(de->d_name, suffix);
+}
+
+void execute_directory(const char *directory, DIR *d, char *argv[]) {
+ DIR *_d = NULL;
+ struct dirent *de;
+ Hashmap *pids = NULL;
+
+ assert(directory);
+
+ /* Executes all binaries in a directory in parallel and
+ * waits for them to finish. */
+
+ if (!d) {
+ if (!(_d = opendir(directory))) {
+
+ if (errno == ENOENT)
+ return;
+
+ log_error("Failed to enumerate directory %s: %m", directory);
+ return;
+ }
+
+ d = _d;
+ }
+
+ if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
+ log_error("Failed to allocate set.");
+ goto finish;
+ }
+
+ while ((de = readdir(d))) {
+ char *path;
+ pid_t pid;
+ int k;
+
+ if (!dirent_is_file(de))
+ continue;
+
+ if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
+ log_oom();
+ continue;
+ }
+
+ if ((pid = fork()) < 0) {
+ log_error("Failed to fork: %m");
+ free(path);
+ continue;
+ }
+
+ if (pid == 0) {
+ char *_argv[2];
+ /* Child */
+
+ if (!argv) {
+ _argv[0] = path;
+ _argv[1] = NULL;
+ argv = _argv;
+ } else
+ argv[0] = path;
+
+ execv(path, argv);
+
+ log_error("Failed to execute %s: %m", path);
+ _exit(EXIT_FAILURE);
+ }
+
+ log_debug("Spawned %s as %lu", path, (unsigned long) pid);
+
+ if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
+ log_error("Failed to add PID to set: %s", strerror(-k));
+ free(path);
+ }
+ }
+
+ while (!hashmap_isempty(pids)) {
+ pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
+ siginfo_t si = {};
+ char *path;
+
+ if (waitid(P_PID, pid, &si, WEXITED) < 0) {
+
+ if (errno == EINTR)
+ continue;
+
+ log_error("waitid() failed: %m");
+ goto finish;
+ }
+
+ if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
+ if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
+ if (si.si_code == CLD_EXITED)
+ log_error("%s exited with exit status %i.", path, si.si_status);
+ else
+ log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
+ } else
+ log_debug("%s exited successfully.", path);
+
+ free(path);
+ }
+ }
+
+finish:
+ if (_d)
+ closedir(_d);
+
+ if (pids)
+ hashmap_free_free(pids);
+}
+
+int kill_and_sigcont(pid_t pid, int sig) {
+ int r;
+
+ r = kill(pid, sig) < 0 ? -errno : 0;
+
+ if (r >= 0)
+ kill(pid, SIGCONT);
+
+ return r;
+}
+
+bool nulstr_contains(const char*nulstr, const char *needle) {
+ const char *i;
+
+ if (!nulstr)
+ return false;
+
+ NULSTR_FOREACH(i, nulstr)
+ if (streq(i, needle))
+ return true;
+
+ return false;
+}
+
+bool plymouth_running(void) {
+ return access("/run/plymouth/pid", F_OK) >= 0;
+}
+
+char* strshorten(char *s, size_t l) {
+ assert(s);
+
+ if (l < strlen(s))
+ s[l] = 0;
+
+ return s;
+}
+
+static bool hostname_valid_char(char c) {
+ return
+ (c >= 'a' && c <= 'z') ||
+ (c >= 'A' && c <= 'Z') ||
+ (c >= '0' && c <= '9') ||
+ c == '-' ||
+ c == '_' ||
+ c == '.';
+}
+
+bool hostname_is_valid(const char *s) {
+ const char *p;
+ bool dot;
+
+ if (isempty(s))
+ return false;
+
+ for (p = s, dot = true; *p; p++) {
+ if (*p == '.') {
+ if (dot)
+ return false;
+
+ dot = true;
+ } else {
+ if (!hostname_valid_char(*p))
+ return false;
+
+ dot = false;
+ }
+ }
+
+ if (dot)
+ return false;
+
+ if (p-s > HOST_NAME_MAX)
+ return false;
+
+ return true;
+}
+
+char* hostname_cleanup(char *s, bool lowercase) {
+ char *p, *d;
+ bool dot;
+
+ for (p = s, d = s, dot = true; *p; p++) {
+ if (*p == '.') {
+ if (dot)
+ continue;
+
+ *(d++) = '.';
+ dot = true;
+ } else if (hostname_valid_char(*p)) {
+ *(d++) = lowercase ? tolower(*p) : *p;
+ dot = false;
+ }
+
+ }
+
+ if (dot && d > s)
+ d[-1] = 0;
+ else
+ *d = 0;
+
+ strshorten(s, HOST_NAME_MAX);
+
+ return s;
+}
+
+int pipe_eof(int fd) {
+ int r;
+ struct pollfd pollfd = {
+ .fd = fd,
+ .events = POLLIN|POLLHUP,
+ };
+
+ r = poll(&pollfd, 1, 0);
+ if (r < 0)
+ return -errno;
+
+ if (r == 0)
+ return 0;
+
+ return pollfd.revents & POLLHUP;
+}
+
+int fd_wait_for_event(int fd, int event, usec_t t) {
+ int r;
+ struct pollfd pollfd = {
+ .fd = fd,
+ .events = event,
+ };
+
+ r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
+ if (r < 0)
+ return -errno;
+
+ if (r == 0)
+ return 0;
+
+ return pollfd.revents;
+}
+
+int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
+ FILE *f;
+ char *t;
+ const char *fn;
+ size_t k;
+ int fd;
+
+ assert(path);
+ assert(_f);
+ assert(_temp_path);
+
+ t = new(char, strlen(path) + 1 + 6 + 1);
+ if (!t)
+ return -ENOMEM;
+
+ fn = path_get_file_name(path);
+ k = fn-path;
+ memcpy(t, path, k);
+ t[k] = '.';
+ stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
+
+ fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
+ if (fd < 0) {
+ free(t);
+ return -errno;
+ }
+
+ f = fdopen(fd, "we");
+ if (!f) {
+ unlink(t);
+ free(t);
+ return -errno;
+ }
+
+ *_f = f;
+ *_temp_path = t;
+
+ return 0;
+}
+
+int terminal_vhangup_fd(int fd) {
+ assert(fd >= 0);
+
+ if (ioctl(fd, TIOCVHANGUP) < 0)
+ return -errno;
+
+ return 0;
+}
+
+int terminal_vhangup(const char *name) {
+ int fd, r;
+
+ fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
+ if (fd < 0)
+ return fd;
+
+ r = terminal_vhangup_fd(fd);
+ close_nointr_nofail(fd);
+
+ return r;
+}
+
+int vt_disallocate(const char *name) {
+ int fd, r;
+ unsigned u;
+
+ /* Deallocate the VT if possible. If not possible
+ * (i.e. because it is the active one), at least clear it
+ * entirely (including the scrollback buffer) */
+
+ if (!startswith(name, "/dev/"))
+ return -EINVAL;
+
+ if (!tty_is_vc(name)) {
+ /* So this is not a VT. I guess we cannot deallocate
+ * it then. But let's at least clear the screen */
+
+ fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
+ if (fd < 0)
+ return fd;
+
+ loop_write(fd,
+ "\033[r" /* clear scrolling region */
+ "\033[H" /* move home */
+ "\033[2J", /* clear screen */
+ 10, false);
+ close_nointr_nofail(fd);
+
+ return 0;
+ }
+
+ if (!startswith(name, "/dev/tty"))
+ return -EINVAL;
+
+ r = safe_atou(name+8, &u);
+ if (r < 0)
+ return r;
+
+ if (u <= 0)
+ return -EINVAL;
+
+ /* Try to deallocate */
+ fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
+ if (fd < 0)
+ return fd;
+
+ r = ioctl(fd, VT_DISALLOCATE, u);
+ close_nointr_nofail(fd);
+
+ if (r >= 0)
+ return 0;
+
+ if (errno != EBUSY)
+ return -errno;
+
+ /* Couldn't deallocate, so let's clear it fully with
+ * scrollback */
+ fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
+ if (fd < 0)
+ return fd;
+
+ loop_write(fd,
+ "\033[r" /* clear scrolling region */
+ "\033[H" /* move home */
+ "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
+ 10, false);
+ close_nointr_nofail(fd);
+
+ return 0;
+}
+
+int copy_file(const char *from, const char *to) {
+ int r, fdf, fdt;
+
+ assert(from);
+ assert(to);
+
+ fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
+ if (fdf < 0)
+ return -errno;
+
+ fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
+ if (fdt < 0) {
+ close_nointr_nofail(fdf);
+ return -errno;
+ }
+
+ for (;;) {
+ char buf[PIPE_BUF];
+ ssize_t n, k;
+
+ n = read(fdf, buf, sizeof(buf));
+ if (n < 0) {
+ r = -errno;
+
+ close_nointr_nofail(fdf);
+ close_nointr(fdt);
+ unlink(to);
+
+ return r;
+ }
+
+ if (n == 0)
+ break;
+
+ errno = 0;
+ k = loop_write(fdt, buf, n, false);
+ if (n != k) {
+ r = k < 0 ? k : (errno ? -errno : -EIO);
+
+ close_nointr_nofail(fdf);
+ close_nointr(fdt);
+
+ unlink(to);
+ return r;
+ }
+ }
+
+ close_nointr_nofail(fdf);
+ r = close_nointr(fdt);
+
+ if (r < 0) {
+ unlink(to);
+ return r;
+ }
+
+ return 0;
+}
+
+int symlink_atomic(const char *from, const char *to) {
+ char *x;
+ _cleanup_free_ char *t;
+ const char *fn;
+ size_t k;
+ unsigned long long ull;
+ unsigned i;
+ int r;
+
+ assert(from);
+ assert(to);
+
+ t = new(char, strlen(to) + 1 + 16 + 1);
+ if (!t)
+ return -ENOMEM;
+
+ fn = path_get_file_name(to);
+ k = fn-to;
+ memcpy(t, to, k);
+ t[k] = '.';
+ x = stpcpy(t+k+1, fn);
+
+ ull = random_ull();
+ for (i = 0; i < 16; i++) {
+ *(x++) = hexchar(ull & 0xF);
+ ull >>= 4;
+ }
+
+ *x = 0;
+
+ if (symlink(from, t) < 0)
+ return -errno;
+
+ if (rename(t, to) < 0) {
+ r = -errno;
+ unlink(t);
+ return r;
+ }
+
+ return 0;
+}
+
+bool display_is_local(const char *display) {
+ assert(display);
+
+ return
+ display[0] == ':' &&
+ display[1] >= '0' &&
+ display[1] <= '9';
+}
+
+int socket_from_display(const char *display, char **path) {
+ size_t k;
+ char *f, *c;
+
+ assert(display);
+ assert(path);
+
+ if (!display_is_local(display))
+ return -EINVAL;
+
+ k = strspn(display+1, "0123456789");
+
+ f = new(char, sizeof("/tmp/.X11-unix/X") + k);
+ if (!f)
+ return -ENOMEM;
+
+ c = stpcpy(f, "/tmp/.X11-unix/X");
+ memcpy(c, display+1, k);
+ c[k] = 0;
+
+ *path = f;
+
+ return 0;
+}
+
+int get_user_creds(
+ const char **username,
+ uid_t *uid, gid_t *gid,
+ const char **home,
+ const char **shell) {
+
+ struct passwd *p;
+ uid_t u;
+
+ assert(username);
+ assert(*username);
+
+ /* We enforce some special rules for uid=0: in order to avoid
+ * NSS lookups for root we hardcode its data. */
+
+ if (streq(*username, "root") || streq(*username, "0")) {
+ *username = "root";
+
+ if (uid)
+ *uid = 0;
+
+ if (gid)
+ *gid = 0;
+
+ if (home)
+ *home = "/root";
+
+ if (shell)
+ *shell = "/bin/sh";
+
+ return 0;
+ }
+
+ if (parse_uid(*username, &u) >= 0) {
+ errno = 0;
+ p = getpwuid(u);
+
+ /* If there are multiple users with the same id, make
+ * sure to leave $USER to the configured value instead
+ * of the first occurrence in the database. However if
+ * the uid was configured by a numeric uid, then let's
+ * pick the real username from /etc/passwd. */
+ if (p)
+ *username = p->pw_name;
+ } else {
+ errno = 0;
+ p = getpwnam(*username);
+ }
+
+ if (!p)
+ return errno > 0 ? -errno : -ESRCH;
+
+ if (uid)
+ *uid = p->pw_uid;
+
+ if (gid)
+ *gid = p->pw_gid;
+
+ if (home)
+ *home = p->pw_dir;
+
+ if (shell)
+ *shell = p->pw_shell;
+
+ return 0;
+}
+
+char* uid_to_name(uid_t uid) {
+ struct passwd *p;
+ char *r;
+
+ if (uid == 0)
+ return strdup("root");
+
+ p = getpwuid(uid);
+ if (p)
+ return strdup(p->pw_name);
+
+ if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
+ return NULL;
+
+ return r;
+}
+
+char* gid_to_name(gid_t gid) {
+ struct group *p;
+ char *r;
+
+ if (gid == 0)
+ return strdup("root");
+
+ p = getgrgid(gid);
+ if (p)
+ return strdup(p->gr_name);
+
+ if (asprintf(&r, "%lu", (unsigned long) gid) < 0)
+ return NULL;
+
+ return r;
+}
+
+int get_group_creds(const char **groupname, gid_t *gid) {
+ struct group *g;
+ gid_t id;
+
+ assert(groupname);
+
+ /* We enforce some special rules for gid=0: in order to avoid
+ * NSS lookups for root we hardcode its data. */
+
+ if (streq(*groupname, "root") || streq(*groupname, "0")) {
+ *groupname = "root";
+
+ if (gid)
+ *gid = 0;
+
+ return 0;
+ }
+
+ if (parse_gid(*groupname, &id) >= 0) {
+ errno = 0;
+ g = getgrgid(id);
+
+ if (g)
+ *groupname = g->gr_name;
+ } else {
+ errno = 0;
+ g = getgrnam(*groupname);
+ }
+
+ if (!g)
+ return errno > 0 ? -errno : -ESRCH;
+
+ if (gid)
+ *gid = g->gr_gid;
+
+ return 0;
+}
+
+int in_gid(gid_t gid) {
+ gid_t *gids;
+ int ngroups_max, r, i;
+
+ if (getgid() == gid)
+ return 1;
+
+ if (getegid() == gid)
+ return 1;
+
+ ngroups_max = sysconf(_SC_NGROUPS_MAX);
+ assert(ngroups_max > 0);
+
+ gids = alloca(sizeof(gid_t) * ngroups_max);
+
+ r = getgroups(ngroups_max, gids);
+ if (r < 0)
+ return -errno;
+
+ for (i = 0; i < r; i++)
+ if (gids[i] == gid)
+ return 1;
+
+ return 0;
+}
+
+int in_group(const char *name) {
+ int r;
+ gid_t gid;
+
+ r = get_group_creds(&name, &gid);
+ if (r < 0)
+ return r;
+
+ return in_gid(gid);
+}
+
+int glob_exists(const char *path) {
+ _cleanup_globfree_ glob_t g = {};
+ int r, k;
+
+ assert(path);
+
+ errno = 0;
+ k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
+
+ if (k == GLOB_NOMATCH)
+ r = 0;
+ else if (k == GLOB_NOSPACE)
+ r = -ENOMEM;
+ else if (k == 0)
+ r = !strv_isempty(g.gl_pathv);
+ else
+ r = errno ? -errno : -EIO;
+
+ return r;
+}
+
+int dirent_ensure_type(DIR *d, struct dirent *de) {
+ struct stat st;
+
+ assert(d);
+ assert(de);
+
+ if (de->d_type != DT_UNKNOWN)
+ return 0;
+
+ if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
+ return -errno;
+
+ de->d_type =
+ S_ISREG(st.st_mode) ? DT_REG :
+ S_ISDIR(st.st_mode) ? DT_DIR :
+ S_ISLNK(st.st_mode) ? DT_LNK :
+ S_ISFIFO(st.st_mode) ? DT_FIFO :
+ S_ISSOCK(st.st_mode) ? DT_SOCK :
+ S_ISCHR(st.st_mode) ? DT_CHR :
+ S_ISBLK(st.st_mode) ? DT_BLK :
+ DT_UNKNOWN;
+
+ return 0;
+}
+
+int in_search_path(const char *path, char **search) {
+ char **i, *parent;
+ int r;
+
+ r = path_get_parent(path, &parent);
+ if (r < 0)
+ return r;
+
+ r = 0;
+
+ STRV_FOREACH(i, search) {
+ if (path_equal(parent, *i)) {
+ r = 1;
+ break;
+ }
+ }
+
+ free(parent);
+
+ return r;
+}
+
+int get_files_in_directory(const char *path, char ***list) {
+ DIR *d;
+ int r = 0;
+ unsigned n = 0;
+ char **l = NULL;
+
+ assert(path);
+
+ /* Returns all files in a directory in *list, and the number
+ * of files as return value. If list is NULL returns only the
+ * number */
+
+ d = opendir(path);
+ if (!d)
+ return -errno;
+
+ for (;;) {
+ struct dirent *de;
+ union dirent_storage buf;
+ int k;
+
+ k = readdir_r(d, &buf.de, &de);
+ if (k != 0) {
+ r = -k;
+ goto finish;
+ }
+
+ if (!de)
+ break;
+
+ dirent_ensure_type(d, de);
+
+ if (!dirent_is_file(de))
+ continue;
+
+ if (list) {
+ if ((unsigned) r >= n) {
+ char **t;
+
+ n = MAX(16, 2*r);
+ t = realloc(l, sizeof(char*) * n);
+ if (!t) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ l = t;
+ }
+
+ assert((unsigned) r < n);
+
+ l[r] = strdup(de->d_name);
+ if (!l[r]) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ l[++r] = NULL;
+ } else
+ r++;
+ }
+
+finish:
+ if (d)
+ closedir(d);
+
+ if (r >= 0) {
+ if (list)
+ *list = l;
+ } else
+ strv_free(l);
+
+ return r;
+}
+
+char *strjoin(const char *x, ...) {
+ va_list ap;
+ size_t l;
+ char *r, *p;
+
+ va_start(ap, x);
+
+ if (x) {
+ l = strlen(x);
+
+ for (;;) {
+ const char *t;
+ size_t n;
+
+ t = va_arg(ap, const char *);
+ if (!t)
+ break;
+
+ n = strlen(t);
+ if (n > ((size_t) -1) - l) {
+ va_end(ap);
+ return NULL;
+ }
+
+ l += n;
+ }
+ } else
+ l = 0;
+
+ va_end(ap);
+
+ r = new(char, l+1);
+ if (!r)
+ return NULL;
+
+ if (x) {
+ p = stpcpy(r, x);
+
+ va_start(ap, x);
+
+ for (;;) {
+ const char *t;
+
+ t = va_arg(ap, const char *);
+ if (!t)
+ break;
+
+ p = stpcpy(p, t);
+ }
+
+ va_end(ap);
+ } else
+ r[0] = 0;
+
+ return r;
+}
+
+bool is_main_thread(void) {
+ static __thread int cached = 0;
+
+ if (_unlikely_(cached == 0))
+ cached = getpid() == gettid() ? 1 : -1;
+
+ return cached > 0;
+}
+
+int block_get_whole_disk(dev_t d, dev_t *ret) {
+ char *p, *s;
+ int r;
+ unsigned n, m;
+
+ assert(ret);
+
+ /* If it has a queue this is good enough for us */
+ if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
+ return -ENOMEM;
+
+ r = access(p, F_OK);
+ free(p);
+
+ if (r >= 0) {
+ *ret = d;
+ return 0;
+ }
+
+ /* If it is a partition find the originating device */
+ if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
+ return -ENOMEM;
+
+ r = access(p, F_OK);
+ free(p);
+
+ if (r < 0)
+ return -ENOENT;
+
+ /* Get parent dev_t */
+ if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
+ return -ENOMEM;
+
+ r = read_one_line_file(p, &s);
+ free(p);
+
+ if (r < 0)
+ return r;
+
+ r = sscanf(s, "%u:%u", &m, &n);
+ free(s);
+
+ if (r != 2)
+ return -EINVAL;
+
+ /* Only return this if it is really good enough for us. */
+ if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
+ return -ENOMEM;
+
+ r = access(p, F_OK);
+ free(p);
+
+ if (r >= 0) {
+ *ret = makedev(m, n);
+ return 0;
+ }
+
+ return -ENOENT;
+}
+
+int file_is_priv_sticky(const char *p) {
+ struct stat st;
+
+ assert(p);
+
+ if (lstat(p, &st) < 0)
+ return -errno;
+
+ return
+ (st.st_uid == 0 || st.st_uid == getuid()) &&
+ (st.st_mode & S_ISVTX);
+}
+
+static const char *const ioprio_class_table[] = {
+ [IOPRIO_CLASS_NONE] = "none",
+ [IOPRIO_CLASS_RT] = "realtime",
+ [IOPRIO_CLASS_BE] = "best-effort",
+ [IOPRIO_CLASS_IDLE] = "idle"
+};
+
+DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
+
+static const char *const sigchld_code_table[] = {
+ [CLD_EXITED] = "exited",
+ [CLD_KILLED] = "killed",
+ [CLD_DUMPED] = "dumped",
+ [CLD_TRAPPED] = "trapped",
+ [CLD_STOPPED] = "stopped",
+ [CLD_CONTINUED] = "continued",
+};
+
+DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
+
+static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
+ [LOG_FAC(LOG_KERN)] = "kern",
+ [LOG_FAC(LOG_USER)] = "user",
+ [LOG_FAC(LOG_MAIL)] = "mail",
+ [LOG_FAC(LOG_DAEMON)] = "daemon",
+ [LOG_FAC(LOG_AUTH)] = "auth",
+ [LOG_FAC(LOG_SYSLOG)] = "syslog",
+ [LOG_FAC(LOG_LPR)] = "lpr",
+ [LOG_FAC(LOG_NEWS)] = "news",
+ [LOG_FAC(LOG_UUCP)] = "uucp",
+ [LOG_FAC(LOG_CRON)] = "cron",
+ [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
+ [LOG_FAC(LOG_FTP)] = "ftp",
+ [LOG_FAC(LOG_LOCAL0)] = "local0",
+ [LOG_FAC(LOG_LOCAL1)] = "local1",
+ [LOG_FAC(LOG_LOCAL2)] = "local2",
+ [LOG_FAC(LOG_LOCAL3)] = "local3",
+ [LOG_FAC(LOG_LOCAL4)] = "local4",
+ [LOG_FAC(LOG_LOCAL5)] = "local5",
+ [LOG_FAC(LOG_LOCAL6)] = "local6",
+ [LOG_FAC(LOG_LOCAL7)] = "local7"
+};
+
+DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
+
+static const char *const log_level_table[] = {
+ [LOG_EMERG] = "emerg",
+ [LOG_ALERT] = "alert",
+ [LOG_CRIT] = "crit",
+ [LOG_ERR] = "err",
+ [LOG_WARNING] = "warning",
+ [LOG_NOTICE] = "notice",
+ [LOG_INFO] = "info",
+ [LOG_DEBUG] = "debug"
+};
+
+DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
+
+static const char* const sched_policy_table[] = {
+ [SCHED_OTHER] = "other",
+ [SCHED_BATCH] = "batch",
+ [SCHED_IDLE] = "idle",
+ [SCHED_FIFO] = "fifo",
+ [SCHED_RR] = "rr"
+};
+
+DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
+
+static const char* const rlimit_table[] = {
+ [RLIMIT_CPU] = "LimitCPU",
+ [RLIMIT_FSIZE] = "LimitFSIZE",
+ [RLIMIT_DATA] = "LimitDATA",
+ [RLIMIT_STACK] = "LimitSTACK",
+ [RLIMIT_CORE] = "LimitCORE",
+ [RLIMIT_RSS] = "LimitRSS",
+ [RLIMIT_NOFILE] = "LimitNOFILE",
+ [RLIMIT_AS] = "LimitAS",
+ [RLIMIT_NPROC] = "LimitNPROC",
+ [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
+ [RLIMIT_LOCKS] = "LimitLOCKS",
+ [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
+ [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
+ [RLIMIT_NICE] = "LimitNICE",
+ [RLIMIT_RTPRIO] = "LimitRTPRIO",
+ [RLIMIT_RTTIME] = "LimitRTTIME"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
+
+static const char* const ip_tos_table[] = {
+ [IPTOS_LOWDELAY] = "low-delay",
+ [IPTOS_THROUGHPUT] = "throughput",
+ [IPTOS_RELIABILITY] = "reliability",
+ [IPTOS_LOWCOST] = "low-cost",
+};
+
+DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
+
+static const char *const __signal_table[] = {
+ [SIGHUP] = "HUP",
+ [SIGINT] = "INT",
+ [SIGQUIT] = "QUIT",
+ [SIGILL] = "ILL",
+ [SIGTRAP] = "TRAP",
+ [SIGABRT] = "ABRT",
+ [SIGBUS] = "BUS",
+ [SIGFPE] = "FPE",
+ [SIGKILL] = "KILL",
+ [SIGUSR1] = "USR1",
+ [SIGSEGV] = "SEGV",
+ [SIGUSR2] = "USR2",
+ [SIGPIPE] = "PIPE",
+ [SIGALRM] = "ALRM",
+ [SIGTERM] = "TERM",
+#ifdef SIGSTKFLT
+ [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
+#endif
+ [SIGCHLD] = "CHLD",
+ [SIGCONT] = "CONT",
+ [SIGSTOP] = "STOP",
+ [SIGTSTP] = "TSTP",
+ [SIGTTIN] = "TTIN",
+ [SIGTTOU] = "TTOU",
+ [SIGURG] = "URG",
+ [SIGXCPU] = "XCPU",
+ [SIGXFSZ] = "XFSZ",
+ [SIGVTALRM] = "VTALRM",
+ [SIGPROF] = "PROF",
+ [SIGWINCH] = "WINCH",
+ [SIGIO] = "IO",
+ [SIGPWR] = "PWR",
+ [SIGSYS] = "SYS"
+};
+
+DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
+
+const char *signal_to_string(int signo) {
+ static __thread char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
+ const char *name;
+
+ name = __signal_to_string(signo);
+ if (name)
+ return name;
+
+ if (signo >= SIGRTMIN && signo <= SIGRTMAX)
+ snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
+ else
+ snprintf(buf, sizeof(buf), "%d", signo);
+
+ return buf;
+}
+
+int signal_from_string(const char *s) {
+ int signo;
+ int offset = 0;
+ unsigned u;
+
+ signo = __signal_from_string(s);
+ if (signo > 0)
+ return signo;
+
+ if (startswith(s, "RTMIN+")) {
+ s += 6;
+ offset = SIGRTMIN;
+ }
+ if (safe_atou(s, &u) >= 0) {
+ signo = (int) u + offset;
+ if (signo > 0 && signo < _NSIG)
+ return signo;
+ }
+ return -1;
+}
+
+bool kexec_loaded(void) {
+ bool loaded = false;
+ char *s;
+
+ if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
+ if (s[0] == '1')
+ loaded = true;
+ free(s);
+ }
+ return loaded;
+}
+
+int strdup_or_null(const char *a, char **b) {
+ char *c;
+
+ assert(b);
+
+ if (!a) {
+ *b = NULL;
+ return 0;
+ }
+
+ c = strdup(a);
+ if (!c)
+ return -ENOMEM;
+
+ *b = c;
+ return 0;
+}
+
+int prot_from_flags(int flags) {
+
+ switch (flags & O_ACCMODE) {
+
+ case O_RDONLY:
+ return PROT_READ;
+
+ case O_WRONLY:
+ return PROT_WRITE;
+
+ case O_RDWR:
+ return PROT_READ|PROT_WRITE;
+
+ default:
+ return -EINVAL;
+ }
+}
+
+char *format_bytes(char *buf, size_t l, off_t t) {
+ unsigned i;
+
+ static const struct {
+ const char *suffix;
+ off_t factor;
+ } table[] = {
+ { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
+ { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
+ { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
+ { "G", 1024ULL*1024ULL*1024ULL },
+ { "M", 1024ULL*1024ULL },
+ { "K", 1024ULL },
+ };
+
+ for (i = 0; i < ELEMENTSOF(table); i++) {
+
+ if (t >= table[i].factor) {
+ snprintf(buf, l,
+ "%llu.%llu%s",
+ (unsigned long long) (t / table[i].factor),
+ (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
+ table[i].suffix);
+
+ goto finish;
+ }
+ }
+
+ snprintf(buf, l, "%lluB", (unsigned long long) t);
+
+finish:
+ buf[l-1] = 0;
+ return buf;
+
+}
+
+void* memdup(const void *p, size_t l) {
+ void *r;
+
+ assert(p);
+
+ r = malloc(l);
+ if (!r)
+ return NULL;
+
+ memcpy(r, p, l);
+ return r;
+}
+
+int fd_inc_sndbuf(int fd, size_t n) {
+ int r, value;
+ socklen_t l = sizeof(value);
+
+ r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
+ if (r >= 0 &&
+ l == sizeof(value) &&
+ (size_t) value >= n*2)
+ return 0;
+
+ value = (int) n;
+ r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
+ if (r < 0)
+ return -errno;
+
+ return 1;
+}
+
+int fd_inc_rcvbuf(int fd, size_t n) {
+ int r, value;
+ socklen_t l = sizeof(value);
+
+ r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
+ if (r >= 0 &&
+ l == sizeof(value) &&
+ (size_t) value >= n*2)
+ return 0;
+
+ value = (int) n;
+ r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
+ if (r < 0)
+ return -errno;
+
+ return 1;
+}
+
+int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
+ pid_t parent_pid, agent_pid;
+ int fd;
+ bool stdout_is_tty, stderr_is_tty;
+ unsigned n, i;
+ va_list ap;
+ char **l;
+
+ assert(pid);
+ assert(path);
+
+ parent_pid = getpid();
+
+ /* Spawns a temporary TTY agent, making sure it goes away when
+ * we go away */
+
+ agent_pid = fork();
+ if (agent_pid < 0)
+ return -errno;
+
+ if (agent_pid != 0) {
+ *pid = agent_pid;
+ return 0;
+ }
+
+ /* In the child:
+ *
+ * Make sure the agent goes away when the parent dies */
+ if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
+ _exit(EXIT_FAILURE);
+
+ /* Check whether our parent died before we were able
+ * to set the death signal */
+ if (getppid() != parent_pid)
+ _exit(EXIT_SUCCESS);
+
+ /* Don't leak fds to the agent */
+ close_all_fds(except, n_except);
+
+ stdout_is_tty = isatty(STDOUT_FILENO);
+ stderr_is_tty = isatty(STDERR_FILENO);
+
+ if (!stdout_is_tty || !stderr_is_tty) {
+ /* Detach from stdout/stderr. and reopen
+ * /dev/tty for them. This is important to
+ * ensure that when systemctl is started via
+ * popen() or a similar call that expects to
+ * read EOF we actually do generate EOF and
+ * not delay this indefinitely by because we
+ * keep an unused copy of stdin around. */
+ fd = open("/dev/tty", O_WRONLY);
+ if (fd < 0) {
+ log_error("Failed to open /dev/tty: %m");
+ _exit(EXIT_FAILURE);
+ }
+
+ if (!stdout_is_tty)
+ dup2(fd, STDOUT_FILENO);
+
+ if (!stderr_is_tty)
+ dup2(fd, STDERR_FILENO);
+
+ if (fd > 2)
+ close(fd);
+ }
+
+ /* Count arguments */
+ va_start(ap, path);
+ for (n = 0; va_arg(ap, char*); n++)
+ ;
+ va_end(ap);
+
+ /* Allocate strv */
+ l = alloca(sizeof(char *) * (n + 1));
+
+ /* Fill in arguments */
+ va_start(ap, path);
+ for (i = 0; i <= n; i++)
+ l[i] = va_arg(ap, char*);
+ va_end(ap);
+
+ execv(path, l);
+ _exit(EXIT_FAILURE);
+}
+
+int setrlimit_closest(int resource, const struct rlimit *rlim) {
+ struct rlimit highest, fixed;
+
+ assert(rlim);
+
+ if (setrlimit(resource, rlim) >= 0)
+ return 0;
+
+ if (errno != EPERM)
+ return -errno;
+
+ /* So we failed to set the desired setrlimit, then let's try
+ * to get as close as we can */
+ assert_se(getrlimit(resource, &highest) == 0);
+
+ fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
+ fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
+
+ if (setrlimit(resource, &fixed) < 0)
+ return -errno;
+
+ return 0;
+}
+
+int getenv_for_pid(pid_t pid, const char *field, char **_value) {
+ _cleanup_fclose_ FILE *f = NULL;
+ char *value = NULL;
+ int r;
+ bool done = false;
+ size_t l;
+ const char *path;
+
+ assert(pid >= 0);
+ assert(field);
+ assert(_value);
+
+ if (pid == 0)
+ path = "/proc/self/environ";
+ else
+ path = procfs_file_alloca(pid, "environ");
+
+ f = fopen(path, "re");
+ if (!f)
+ return -errno;
+
+ l = strlen(field);
+ r = 0;
+
+ do {
+ char line[LINE_MAX];
+ unsigned i;
+
+ for (i = 0; i < sizeof(line)-1; i++) {
+ int c;
+
+ c = getc(f);
+ if (_unlikely_(c == EOF)) {
+ done = true;
+ break;
+ } else if (c == 0)
+ break;
+
+ line[i] = c;
+ }
+ line[i] = 0;
+
+ if (memcmp(line, field, l) == 0 && line[l] == '=') {
+ value = strdup(line + l + 1);
+ if (!value)
+ return -ENOMEM;
+
+ r = 1;
+ break;
+ }
+
+ } while (!done);
+
+ *_value = value;
+ return r;
+}
+
+bool is_valid_documentation_url(const char *url) {
+ assert(url);
+
+ if (startswith(url, "http://") && url[7])
+ return true;
+
+ if (startswith(url, "https://") && url[8])
+ return true;
+
+ if (startswith(url, "file:") && url[5])
+ return true;
+
+ if (startswith(url, "info:") && url[5])
+ return true;
+
+ if (startswith(url, "man:") && url[4])
+ return true;
+
+ return false;
+}
+
+bool in_initrd(void) {
+ static __thread int saved = -1;
+ struct statfs s;
+
+ if (saved >= 0)
+ return saved;
+
+ /* We make two checks here:
+ *
+ * 1. the flag file /etc/initrd-release must exist
+ * 2. the root file system must be a memory file system
+ *
+ * The second check is extra paranoia, since misdetecting an
+ * initrd can have bad bad consequences due the initrd
+ * emptying when transititioning to the main systemd.
+ */
+
+ saved = access("/etc/initrd-release", F_OK) >= 0 &&
+ statfs("/", &s) >= 0 &&
+ is_temporary_fs(&s);
+
+ return saved;
+}
+
+void warn_melody(void) {
+ _cleanup_close_ int fd = -1;
+
+ fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
+ if (fd < 0)
+ return;
+
+ /* Yeah, this is synchronous. Kinda sucks. But well... */
+
+ ioctl(fd, KIOCSOUND, (int)(1193180/440));
+ usleep(125*USEC_PER_MSEC);
+
+ ioctl(fd, KIOCSOUND, (int)(1193180/220));
+ usleep(125*USEC_PER_MSEC);
+
+ ioctl(fd, KIOCSOUND, (int)(1193180/220));
+ usleep(125*USEC_PER_MSEC);
+
+ ioctl(fd, KIOCSOUND, 0);
+}
+
+int make_console_stdio(void) {
+ int fd, r;
+
+ /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
+
+ fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
+ if (fd < 0) {
+ log_error("Failed to acquire terminal: %s", strerror(-fd));
+ return fd;
+ }
+
+ r = make_stdio(fd);
+ if (r < 0) {
+ log_error("Failed to duplicate terminal fd: %s", strerror(-r));
+ return r;
+ }
+
+ return 0;
+}
+
+int get_home_dir(char **_h) {
+ char *h;
+ const char *e;
+ uid_t u;
+ struct passwd *p;
+
+ assert(_h);
+
+ /* Take the user specified one */
+ e = getenv("HOME");
+ if (e) {
+ h = strdup(e);
+ if (!h)
+ return -ENOMEM;
+
+ *_h = h;
+ return 0;
+ }
+
+ /* Hardcode home directory for root to avoid NSS */
+ u = getuid();
+ if (u == 0) {
+ h = strdup("/root");
+ if (!h)
+ return -ENOMEM;
+
+ *_h = h;
+ return 0;
+ }
+
+ /* Check the database... */
+ errno = 0;
+ p = getpwuid(u);
+ if (!p)
+ return errno > 0 ? -errno : -ESRCH;
+
+ if (!path_is_absolute(p->pw_dir))
+ return -EINVAL;
+
+ h = strdup(p->pw_dir);
+ if (!h)
+ return -ENOMEM;
+
+ *_h = h;
+ return 0;
+}
+
+bool filename_is_safe(const char *p) {
+
+ if (isempty(p))
+ return false;
+
+ if (strchr(p, '/'))
+ return false;
+
+ if (streq(p, "."))
+ return false;
+
+ if (streq(p, ".."))
+ return false;
+
+ if (strlen(p) > FILENAME_MAX)
+ return false;
+
+ return true;
+}
+
+bool string_is_safe(const char *p) {
+ const char *t;
+
+ assert(p);
+
+ for (t = p; *t; t++) {
+ if (*t > 0 && *t < ' ')
+ return false;
+
+ if (strchr("\\\"\'", *t))
+ return false;
+ }
+
+ return true;
+}
+
+bool string_has_cc(const char *p) {
+ const char *t;
+
+ assert(p);
+
+ for (t = p; *t; t++)
+ if (*t > 0 && *t < ' ')
+ return true;
+
+ return false;
+}
+
+bool path_is_safe(const char *p) {
+
+ if (isempty(p))
+ return false;
+
+ if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
+ return false;
+
+ if (strlen(p) > PATH_MAX)
+ return false;
+
+ /* The following two checks are not really dangerous, but hey, they still are confusing */
+ if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
+ return false;
+
+ if (strstr(p, "//"))
+ return false;
+
+ return true;
+}
+
+/* hey glibc, APIs with callbacks without a user pointer are so useless */
+void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
+ int (*compar) (const void *, const void *, void *), void *arg) {
+ size_t l, u, idx;
+ const void *p;
+ int comparison;
+
+ l = 0;
+ u = nmemb;
+ while (l < u) {
+ idx = (l + u) / 2;
+ p = (void *)(((const char *) base) + (idx * size));
+ comparison = compar(key, p, arg);
+ if (comparison < 0)
+ u = idx;
+ else if (comparison > 0)
+ l = idx + 1;
+ else
+ return (void *)p;
+ }
+ return NULL;
+}
+
+bool is_locale_utf8(void) {
+ const char *set;
+ static int cached_answer = -1;
+
+ if (cached_answer >= 0)
+ goto out;
+
+ if (!setlocale(LC_ALL, "")) {
+ cached_answer = true;
+ goto out;
+ }
+
+ set = nl_langinfo(CODESET);
+ if (!set) {
+ cached_answer = true;
+ goto out;
+ }
+
+ if(streq(set, "UTF-8")) {
+ cached_answer = true;
+ goto out;
+ }
+
+ /* For LC_CTYPE=="C" return true,
+ * because CTYPE is effectly unset and
+ * everything defaults to UTF-8 nowadays. */
+
+ set = setlocale(LC_CTYPE, NULL);
+ if (!set) {
+ cached_answer = true;
+ goto out;
+ }
+
+ cached_answer = streq(set, "C");
+
+out:
+ return (bool)cached_answer;
+}
+
+const char *draw_special_char(DrawSpecialChar ch) {
+ static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
+ /* UTF-8 */ {
+ [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
+ [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
+ [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
+ [DRAW_TREE_SPACE] = " ", /* */
+ [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
+ },
+ /* ASCII fallback */ {
+ [DRAW_TREE_VERT] = "| ",
+ [DRAW_TREE_BRANCH] = "|-",
+ [DRAW_TREE_RIGHT] = "`-",
+ [DRAW_TREE_SPACE] = " ",
+ [DRAW_TRIANGULAR_BULLET] = "> ",
+ }
+ };
+
+ return draw_table[!is_locale_utf8()][ch];
+}
+
+char *strreplace(const char *text, const char *old_string, const char *new_string) {
+ const char *f;
+ char *t, *r;
+ size_t l, old_len, new_len;
+
+ assert(text);
+ assert(old_string);
+ assert(new_string);
+
+ old_len = strlen(old_string);
+ new_len = strlen(new_string);
+
+ l = strlen(text);
+ r = new(char, l+1);
+ if (!r)
+ return NULL;
+
+ f = text;
+ t = r;
+ while (*f) {
+ char *a;
+ size_t d, nl;
+
+ if (!startswith(f, old_string)) {
+ *(t++) = *(f++);
+ continue;
+ }
+
+ d = t - r;
+ nl = l - old_len + new_len;
+ a = realloc(r, nl + 1);
+ if (!a)
+ goto oom;
+
+ l = nl;
+ r = a;
+ t = r + d;
+
+ t = stpcpy(t, new_string);
+ f += old_len;
+ }
+
+ *t = 0;
+ return r;
+
+oom:
+ free(r);
+ return NULL;
+}
+
+char *strip_tab_ansi(char **ibuf, size_t *_isz) {
+ const char *i, *begin = NULL;
+ enum {
+ STATE_OTHER,
+ STATE_ESCAPE,
+ STATE_BRACKET
+ } state = STATE_OTHER;
+ char *obuf = NULL;
+ size_t osz = 0, isz;
+ FILE *f;
+
+ assert(ibuf);
+ assert(*ibuf);
+
+ /* Strips ANSI color and replaces TABs by 8 spaces */
+
+ isz = _isz ? *_isz : strlen(*ibuf);
+
+ f = open_memstream(&obuf, &osz);
+ if (!f)
+ return NULL;
+
+ for (i = *ibuf; i < *ibuf + isz + 1; i++) {
+
+ switch (state) {
+
+ case STATE_OTHER:
+ if (i >= *ibuf + isz) /* EOT */
+ break;
+ else if (*i == '\x1B')
+ state = STATE_ESCAPE;
+ else if (*i == '\t')
+ fputs(" ", f);
+ else
+ fputc(*i, f);
+ break;
+
+ case STATE_ESCAPE:
+ if (i >= *ibuf + isz) { /* EOT */
+ fputc('\x1B', f);
+ break;
+ } else if (*i == '[') {
+ state = STATE_BRACKET;
+ begin = i + 1;
+ } else {
+ fputc('\x1B', f);
+ fputc(*i, f);
+ state = STATE_OTHER;
+ }
+
+ break;
+
+ case STATE_BRACKET:
+
+ if (i >= *ibuf + isz || /* EOT */
+ (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
+ fputc('\x1B', f);
+ fputc('[', f);
+ state = STATE_OTHER;
+ i = begin-1;
+ } else if (*i == 'm')
+ state = STATE_OTHER;
+ break;
+ }
+ }
+
+ if (ferror(f)) {
+ fclose(f);
+ free(obuf);
+ return NULL;
+ }
+
+ fclose(f);
+
+ free(*ibuf);
+ *ibuf = obuf;
+
+ if (_isz)
+ *_isz = osz;
+
+ return obuf;
+}
+
+int on_ac_power(void) {
+ bool found_offline = false, found_online = false;
+ _cleanup_closedir_ DIR *d = NULL;
+
+ d = opendir("/sys/class/power_supply");
+ if (!d)
+ return -errno;
+
+ for (;;) {
+ struct dirent *de;
+ union dirent_storage buf;
+ _cleanup_close_ int fd = -1, device = -1;
+ char contents[6];
+ ssize_t n;
+ int k;
+
+ k = readdir_r(d, &buf.de, &de);
+ if (k != 0)
+ return -k;
+
+ if (!de)
+ break;
+
+ if (ignore_file(de->d_name))
+ continue;
+
+ device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
+ if (device < 0) {
+ if (errno == ENOENT || errno == ENOTDIR)
+ continue;
+
+ return -errno;
+ }
+
+ fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
+ if (fd < 0) {
+ if (errno == ENOENT)
+ continue;
+
+ return -errno;
+ }
+
+ n = read(fd, contents, sizeof(contents));
+ if (n < 0)
+ return -errno;
+
+ if (n != 6 || memcmp(contents, "Mains\n", 6))
+ continue;
+
+ close_nointr_nofail(fd);
+ fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
+ if (fd < 0) {
+ if (errno == ENOENT)
+ continue;
+
+ return -errno;
+ }
+
+ n = read(fd, contents, sizeof(contents));
+ if (n < 0)
+ return -errno;
+
+ if (n != 2 || contents[1] != '\n')
+ return -EIO;
+
+ if (contents[0] == '1') {
+ found_online = true;
+ break;
+ } else if (contents[0] == '0')
+ found_offline = true;
+ else
+ return -EIO;
+ }
+
+ return found_online || !found_offline;
+}
+
+static int search_and_fopen_internal(const char *path, const char *mode, char **search, FILE **_f) {
+ char **i;
+
+ assert(path);
+ assert(mode);
+ assert(_f);
+
+ if (!path_strv_canonicalize_uniq(search))
+ return -ENOMEM;
+
+ STRV_FOREACH(i, search) {
+ _cleanup_free_ char *p = NULL;
+ FILE *f;
+
+ p = strjoin(*i, "/", path, NULL);
+ if (!p)
+ return -ENOMEM;
+
+ f = fopen(p, mode);
+ if (f) {
+ *_f = f;
+ return 0;
+ }
+
+ if (errno != ENOENT)
+ return -errno;
+ }
+
+ return -ENOENT;
+}
+
+int search_and_fopen(const char *path, const char *mode, const char **search, FILE **_f) {
+ _cleanup_strv_free_ char **copy = NULL;
+
+ assert(path);
+ assert(mode);
+ assert(_f);
+
+ if (path_is_absolute(path)) {
+ FILE *f;
+
+ f = fopen(path, mode);
+ if (f) {
+ *_f = f;
+ return 0;
+ }
+
+ return -errno;
+ }
+
+ copy = strv_copy((char**) search);
+ if (!copy)
+ return -ENOMEM;
+
+ return search_and_fopen_internal(path, mode, copy, _f);
+}
+
+int search_and_fopen_nulstr(const char *path, const char *mode, const char *search, FILE **_f) {
+ _cleanup_strv_free_ char **s = NULL;
+
+ if (path_is_absolute(path)) {
+ FILE *f;
+
+ f = fopen(path, mode);
+ if (f) {
+ *_f = f;
+ return 0;
+ }
+
+ return -errno;
+ }
+
+ s = strv_split_nulstr(search);
+ if (!s)
+ return -ENOMEM;
+
+ return search_and_fopen_internal(path, mode, s, _f);
+}
+
+int create_tmp_dir(char template[], char** dir_name) {
+ int r = 0;
+ char *d, *dt;
+
+ assert(dir_name);
+
+ RUN_WITH_UMASK(0077) {
+ d = mkdtemp(template);
+ }
+ if (!d) {
+ log_error("Can't create directory %s: %m", template);
+ return -errno;
+ }
+
+ dt = strjoin(d, "/tmp", NULL);
+ if (!dt) {
+ r = log_oom();
+ goto fail3;
+ }
+
+ RUN_WITH_UMASK(0000) {
+ r = mkdir(dt, 0777);
+ }
+ if (r < 0) {
+ log_error("Can't create directory %s: %m", dt);
+ r = -errno;
+ goto fail2;
+ }
+ log_debug("Created temporary directory %s", dt);
+
+ r = chmod(dt, 0777 | S_ISVTX);
+ if (r < 0) {
+ log_error("Failed to chmod %s: %m", dt);
+ r = -errno;
+ goto fail1;
+ }
+ log_debug("Set sticky bit on %s", dt);
+
+ *dir_name = dt;
+
+ return 0;
+fail1:
+ rmdir(dt);
+fail2:
+ free(dt);
+fail3:
+ rmdir(template);
+ return r;
+}
+
+char *strextend(char **x, ...) {
+ va_list ap;
+ size_t f, l;
+ char *r, *p;
+
+ assert(x);
+
+ l = f = *x ? strlen(*x) : 0;
+
+ va_start(ap, x);
+ for (;;) {
+ const char *t;
+ size_t n;
+
+ t = va_arg(ap, const char *);
+ if (!t)
+ break;
+
+ n = strlen(t);
+ if (n > ((size_t) -1) - l) {
+ va_end(ap);
+ return NULL;
+ }
+
+ l += n;
+ }
+ va_end(ap);
+
+ r = realloc(*x, l+1);
+ if (!r)
+ return NULL;
+
+ p = r + f;
+
+ va_start(ap, x);
+ for (;;) {
+ const char *t;
+
+ t = va_arg(ap, const char *);
+ if (!t)
+ break;
+
+ p = stpcpy(p, t);
+ }
+ va_end(ap);
+
+ *p = 0;
+ *x = r;
+
+ return r + l;
+}
+
+char *strrep(const char *s, unsigned n) {
+ size_t l;
+ char *r, *p;
+ unsigned i;
+
+ assert(s);
+
+ l = strlen(s);
+ p = r = malloc(l * n + 1);
+ if (!r)
+ return NULL;
+
+ for (i = 0; i < n; i++)
+ p = stpcpy(p, s);
+
+ *p = 0;
+ return r;
+}
+
+void* greedy_realloc(void **p, size_t *allocated, size_t need) {
+ size_t a;
+ void *q;
+
+ if (*allocated >= need)
+ return *p;
+
+ a = MAX(64u, need * 2);
+ q = realloc(*p, a);
+ if (!q)
+ return NULL;
+
+ *p = q;
+ *allocated = a;
+ return q;
+}
+
+bool id128_is_valid(const char *s) {
+ size_t i, l;
+
+ l = strlen(s);
+ if (l == 32) {
+
+ /* Simple formatted 128bit hex string */
+
+ for (i = 0; i < l; i++) {
+ char c = s[i];
+
+ if (!(c >= '0' && c <= '9') &&
+ !(c >= 'a' && c <= 'z') &&
+ !(c >= 'A' && c <= 'Z'))
+ return false;
+ }
+
+ } else if (l == 36) {
+
+ /* Formatted UUID */
+
+ for (i = 0; i < l; i++) {
+ char c = s[i];
+
+ if ((i == 8 || i == 13 || i == 18 || i == 23)) {
+ if (c != '-')
+ return false;
+ } else {
+ if (!(c >= '0' && c <= '9') &&
+ !(c >= 'a' && c <= 'z') &&
+ !(c >= 'A' && c <= 'Z'))
+ return false;
+ }
+ }
+
+ } else
+ return false;
+
+ return true;
+}
diff --git a/src/shared/util.h b/src/shared/util.h
new file mode 100644
index 0000000000..64e63b8c07
--- /dev/null
+++ b/src/shared/util.h
@@ -0,0 +1,734 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <alloca.h>
+#include <inttypes.h>
+#include <time.h>
+#include <sys/time.h>
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <signal.h>
+#include <sched.h>
+#include <limits.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <dirent.h>
+#include <sys/resource.h>
+#include <stddef.h>
+#include <unistd.h>
+#include <locale.h>
+
+#include "macro.h"
+#include "time-util.h"
+
+union dirent_storage {
+ struct dirent de;
+ uint8_t storage[offsetof(struct dirent, d_name) +
+ ((NAME_MAX + 1 + sizeof(long)) & ~(sizeof(long) - 1))];
+};
+
+/* What is interpreted as whitespace? */
+#define WHITESPACE " \t\n\r"
+#define NEWLINE "\n\r"
+#define QUOTES "\"\'"
+#define COMMENTS "#;"
+
+#define FORMAT_BYTES_MAX 8
+
+#define ANSI_HIGHLIGHT_ON "\x1B[1;39m"
+#define ANSI_RED_ON "\x1B[31m"
+#define ANSI_HIGHLIGHT_RED_ON "\x1B[1;31m"
+#define ANSI_GREEN_ON "\x1B[32m"
+#define ANSI_HIGHLIGHT_GREEN_ON "\x1B[1;32m"
+#define ANSI_HIGHLIGHT_YELLOW_ON "\x1B[1;33m"
+#define ANSI_HIGHLIGHT_OFF "\x1B[0m"
+#define ANSI_ERASE_TO_END_OF_LINE "\x1B[K"
+
+size_t page_size(void);
+#define PAGE_ALIGN(l) ALIGN_TO((l), page_size())
+
+#define streq(a,b) (strcmp((a),(b)) == 0)
+#define strneq(a, b, n) (strncmp((a), (b), (n)) == 0)
+#define strcaseeq(a,b) (strcasecmp((a),(b)) == 0)
+#define strncaseeq(a, b, n) (strncasecmp((a), (b), (n)) == 0)
+
+bool streq_ptr(const char *a, const char *b) _pure_;
+
+#define new(t, n) ((t*) malloc_multiply(sizeof(t), (n)))
+
+#define new0(t, n) ((t*) calloc((n), sizeof(t)))
+
+#define newa(t, n) ((t*) alloca(sizeof(t)*(n)))
+
+#define newdup(t, p, n) ((t*) memdup_multiply(p, sizeof(t), (n)))
+
+#define malloc0(n) (calloc((n), 1))
+
+static inline const char* yes_no(bool b) {
+ return b ? "yes" : "no";
+}
+
+static inline const char* strempty(const char *s) {
+ return s ? s : "";
+}
+
+static inline const char* strnull(const char *s) {
+ return s ? s : "(null)";
+}
+
+static inline const char *strna(const char *s) {
+ return s ? s : "n/a";
+}
+
+static inline bool isempty(const char *p) {
+ return !p || !p[0];
+}
+
+char *endswith(const char *s, const char *postfix) _pure_;
+char *startswith(const char *s, const char *prefix) _pure_;
+char *startswith_no_case(const char *s, const char *prefix) _pure_;
+
+bool first_word(const char *s, const char *word) _pure_;
+
+int close_nointr(int fd);
+void close_nointr_nofail(int fd);
+void close_many(const int fds[], unsigned n_fd);
+
+int parse_boolean(const char *v) _pure_;
+int parse_bytes(const char *t, off_t *bytes);
+int parse_pid(const char *s, pid_t* ret_pid);
+int parse_uid(const char *s, uid_t* ret_uid);
+#define parse_gid(s, ret_uid) parse_uid(s, ret_uid)
+
+int safe_atou(const char *s, unsigned *ret_u);
+int safe_atoi(const char *s, int *ret_i);
+
+int safe_atollu(const char *s, unsigned long long *ret_u);
+int safe_atolli(const char *s, long long int *ret_i);
+
+int safe_atod(const char *s, double *ret_d);
+
+#if __WORDSIZE == 32
+static inline int safe_atolu(const char *s, unsigned long *ret_u) {
+ assert_cc(sizeof(unsigned long) == sizeof(unsigned));
+ return safe_atou(s, (unsigned*) ret_u);
+}
+static inline int safe_atoli(const char *s, long int *ret_u) {
+ assert_cc(sizeof(long int) == sizeof(int));
+ return safe_atoi(s, (int*) ret_u);
+}
+#else
+static inline int safe_atolu(const char *s, unsigned long *ret_u) {
+ assert_cc(sizeof(unsigned long) == sizeof(unsigned long long));
+ return safe_atollu(s, (unsigned long long*) ret_u);
+}
+static inline int safe_atoli(const char *s, long int *ret_u) {
+ assert_cc(sizeof(long int) == sizeof(long long int));
+ return safe_atolli(s, (long long int*) ret_u);
+}
+#endif
+
+static inline int safe_atou32(const char *s, uint32_t *ret_u) {
+ assert_cc(sizeof(uint32_t) == sizeof(unsigned));
+ return safe_atou(s, (unsigned*) ret_u);
+}
+
+static inline int safe_atoi32(const char *s, int32_t *ret_i) {
+ assert_cc(sizeof(int32_t) == sizeof(int));
+ return safe_atoi(s, (int*) ret_i);
+}
+
+static inline int safe_atou64(const char *s, uint64_t *ret_u) {
+ assert_cc(sizeof(uint64_t) == sizeof(unsigned long long));
+ return safe_atollu(s, (unsigned long long*) ret_u);
+}
+
+static inline int safe_atoi64(const char *s, int64_t *ret_i) {
+ assert_cc(sizeof(int64_t) == sizeof(long long int));
+ return safe_atolli(s, (long long int*) ret_i);
+}
+
+char *split(const char *c, size_t *l, const char *separator, char **state);
+char *split_quoted(const char *c, size_t *l, char **state);
+
+#define FOREACH_WORD(word, length, s, state) \
+ for ((state) = NULL, (word) = split((s), &(length), WHITESPACE, &(state)); (word); (word) = split((s), &(length), WHITESPACE, &(state)))
+
+#define FOREACH_WORD_SEPARATOR(word, length, s, separator, state) \
+ for ((state) = NULL, (word) = split((s), &(length), (separator), &(state)); (word); (word) = split((s), &(length), (separator), &(state)))
+
+#define FOREACH_WORD_QUOTED(word, length, s, state) \
+ for ((state) = NULL, (word) = split_quoted((s), &(length), &(state)); (word); (word) = split_quoted((s), &(length), &(state)))
+
+pid_t get_parent_of_pid(pid_t pid, pid_t *ppid);
+int get_starttime_of_pid(pid_t pid, unsigned long long *st);
+
+char *strappend(const char *s, const char *suffix);
+char *strnappend(const char *s, const char *suffix, size_t length);
+
+char *replace_env(const char *format, char **env);
+char **replace_env_argv(char **argv, char **env);
+
+int readlink_malloc(const char *p, char **r);
+int readlink_and_make_absolute(const char *p, char **r);
+int readlink_and_canonicalize(const char *p, char **r);
+
+int reset_all_signal_handlers(void);
+
+char *strstrip(char *s);
+char *delete_chars(char *s, const char *bad);
+char *truncate_nl(char *s);
+
+char *file_in_same_dir(const char *path, const char *filename);
+
+int rmdir_parents(const char *path, const char *stop);
+
+int get_process_comm(pid_t pid, char **name);
+int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line);
+int get_process_exe(pid_t pid, char **name);
+int get_process_uid(pid_t pid, uid_t *uid);
+int get_process_gid(pid_t pid, gid_t *gid);
+
+char hexchar(int x) _const_;
+int unhexchar(char c) _const_;
+char octchar(int x) _const_;
+int unoctchar(char c) _const_;
+char decchar(int x) _const_;
+int undecchar(char c) _const_;
+
+char *cescape(const char *s);
+char *cunescape(const char *s);
+char *cunescape_length(const char *s, size_t length);
+char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix);
+
+char *xescape(const char *s, const char *bad);
+
+char *bus_path_escape(const char *s);
+char *bus_path_unescape(const char *s);
+
+char *ascii_strlower(char *path);
+
+bool dirent_is_file(const struct dirent *de) _pure_;
+bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) _pure_;
+
+bool ignore_file(const char *filename) _pure_;
+
+bool chars_intersect(const char *a, const char *b) _pure_;
+
+int make_stdio(int fd);
+int make_null_stdio(void);
+int make_console_stdio(void);
+
+unsigned long long random_ull(void);
+
+/* For basic lookup tables with strictly enumerated entries */
+#define __DEFINE_STRING_TABLE_LOOKUP(name,type,scope) \
+ scope const char *name##_to_string(type i) { \
+ if (i < 0 || i >= (type) ELEMENTSOF(name##_table)) \
+ return NULL; \
+ return name##_table[i]; \
+ } \
+ scope type name##_from_string(const char *s) { \
+ type i; \
+ assert(s); \
+ for (i = 0; i < (type)ELEMENTSOF(name##_table); i++) \
+ if (name##_table[i] && \
+ streq(name##_table[i], s)) \
+ return i; \
+ return (type) -1; \
+ } \
+ struct __useless_struct_to_allow_trailing_semicolon__
+
+#define DEFINE_STRING_TABLE_LOOKUP(name,type) __DEFINE_STRING_TABLE_LOOKUP(name,type,)
+#define DEFINE_PRIVATE_STRING_TABLE_LOOKUP(name,type) __DEFINE_STRING_TABLE_LOOKUP(name,type,static)
+
+/* For string conversions where numbers are also acceptable */
+#define DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(name,type,max) \
+ int name##_to_string_alloc(type i, char **str) { \
+ char *s; \
+ int r; \
+ if (i < 0 || i > max) \
+ return -ERANGE; \
+ if (i < (type) ELEMENTSOF(name##_table)) { \
+ s = strdup(name##_table[i]); \
+ if (!s) \
+ return log_oom(); \
+ } else { \
+ r = asprintf(&s, "%u", i); \
+ if (r < 0) \
+ return log_oom(); \
+ } \
+ *str = s; \
+ return 0; \
+ } \
+ type name##_from_string(const char *s) { \
+ type i; \
+ unsigned u = 0; \
+ assert(s); \
+ for (i = 0; i < (type)ELEMENTSOF(name##_table); i++) \
+ if (name##_table[i] && \
+ streq(name##_table[i], s)) \
+ return i; \
+ if (safe_atou(s, &u) >= 0 && u <= max) \
+ return (type) u; \
+ return (type) -1; \
+ } \
+ struct __useless_struct_to_allow_trailing_semicolon__
+
+int fd_nonblock(int fd, bool nonblock);
+int fd_cloexec(int fd, bool cloexec);
+
+int close_all_fds(const int except[], unsigned n_except);
+
+bool fstype_is_network(const char *fstype);
+
+int chvt(int vt);
+
+int read_one_char(FILE *f, char *ret, usec_t timeout, bool *need_nl);
+int ask(char *ret, const char *replies, const char *text, ...) _printf_attr_(3, 4);
+
+int reset_terminal_fd(int fd, bool switch_to_text);
+int reset_terminal(const char *name);
+
+int open_terminal(const char *name, int mode);
+int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm, usec_t timeout);
+int release_terminal(void);
+
+int flush_fd(int fd);
+
+int ignore_signals(int sig, ...);
+int default_signals(int sig, ...);
+int sigaction_many(const struct sigaction *sa, ...);
+
+int close_pipe(int p[]);
+int fopen_temporary(const char *path, FILE **_f, char **_temp_path);
+
+ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll);
+ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll);
+
+bool is_device_path(const char *path);
+
+int dir_is_empty(const char *path);
+char* dirname_malloc(const char *path);
+
+void rename_process(const char name[8]);
+
+void sigset_add_many(sigset_t *ss, ...);
+
+bool hostname_is_set(void);
+
+char* gethostname_malloc(void);
+char* getlogname_malloc(void);
+char* getusername_malloc(void);
+
+int getttyname_malloc(int fd, char **r);
+int getttyname_harder(int fd, char **r);
+
+int get_ctty_devnr(pid_t pid, dev_t *d);
+int get_ctty(pid_t, dev_t *_devnr, char **r);
+
+int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid);
+int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid);
+
+int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev);
+int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev);
+int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky);
+int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky);
+
+int pipe_eof(int fd);
+
+cpu_set_t* cpu_set_malloc(unsigned *ncpus);
+
+int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) _printf_attr_(4,0);
+int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) _printf_attr_(4,5);
+int status_welcome(void);
+
+int fd_columns(int fd);
+unsigned columns(void);
+int fd_lines(int fd);
+unsigned lines(void);
+void columns_lines_cache_reset(int _unused_ signum);
+
+bool on_tty(void);
+
+int running_in_chroot(void);
+
+char *ellipsize(const char *s, size_t length, unsigned percent);
+char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent);
+
+int touch(const char *path);
+
+char *unquote(const char *s, const char *quotes);
+char *normalize_env_assignment(const char *s);
+
+int wait_for_terminate(pid_t pid, siginfo_t *status);
+int wait_for_terminate_and_warn(const char *name, pid_t pid);
+
+_noreturn_ void freeze(void);
+
+bool null_or_empty(struct stat *st) _pure_;
+int null_or_empty_path(const char *fn);
+
+DIR *xopendirat(int dirfd, const char *name, int flags);
+
+char *fstab_node_to_udev_node(const char *p);
+
+char *resolve_dev_console(char **active);
+bool tty_is_vc(const char *tty);
+bool tty_is_vc_resolve(const char *tty);
+bool tty_is_console(const char *tty) _pure_;
+int vtnr_from_tty(const char *tty);
+const char *default_term_for_tty(const char *tty);
+
+void execute_directory(const char *directory, DIR *_d, char *argv[]);
+
+int kill_and_sigcont(pid_t pid, int sig);
+
+bool nulstr_contains(const char*nulstr, const char *needle);
+
+bool plymouth_running(void);
+
+bool hostname_is_valid(const char *s) _pure_;
+char* hostname_cleanup(char *s, bool lowercase);
+
+char* strshorten(char *s, size_t l);
+
+int terminal_vhangup_fd(int fd);
+int terminal_vhangup(const char *name);
+
+int vt_disallocate(const char *name);
+
+int copy_file(const char *from, const char *to);
+
+int symlink_atomic(const char *from, const char *to);
+
+int fchmod_umask(int fd, mode_t mode);
+
+bool display_is_local(const char *display) _pure_;
+int socket_from_display(const char *display, char **path);
+
+int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home, const char **shell);
+int get_group_creds(const char **groupname, gid_t *gid);
+
+int in_gid(gid_t gid);
+int in_group(const char *name);
+
+char* uid_to_name(uid_t uid);
+char* gid_to_name(gid_t gid);
+
+int glob_exists(const char *path);
+
+int dirent_ensure_type(DIR *d, struct dirent *de);
+
+int in_search_path(const char *path, char **search);
+int get_files_in_directory(const char *path, char ***list);
+
+char *strjoin(const char *x, ...) _sentinel_;
+
+bool is_main_thread(void);
+
+bool in_charset(const char *s, const char* charset) _pure_;
+
+int block_get_whole_disk(dev_t d, dev_t *ret);
+
+int file_is_priv_sticky(const char *p);
+
+int strdup_or_null(const char *a, char **b);
+
+#define NULSTR_FOREACH(i, l) \
+ for ((i) = (l); (i) && *(i); (i) = strchr((i), 0)+1)
+
+#define NULSTR_FOREACH_PAIR(i, j, l) \
+ for ((i) = (l), (j) = strchr((i), 0)+1; (i) && *(i); (i) = strchr((j), 0)+1, (j) = *(i) ? strchr((i), 0)+1 : (i))
+
+int ioprio_class_to_string_alloc(int i, char **s);
+int ioprio_class_from_string(const char *s);
+
+const char *sigchld_code_to_string(int i) _const_;
+int sigchld_code_from_string(const char *s) _pure_;
+
+int log_facility_unshifted_to_string_alloc(int i, char **s);
+int log_facility_unshifted_from_string(const char *s);
+
+int log_level_to_string_alloc(int i, char **s);
+int log_level_from_string(const char *s);
+
+int sched_policy_to_string_alloc(int i, char **s);
+int sched_policy_from_string(const char *s);
+
+const char *rlimit_to_string(int i) _const_;
+int rlimit_from_string(const char *s) _pure_;
+
+int ip_tos_to_string_alloc(int i, char **s);
+int ip_tos_from_string(const char *s);
+
+const char *signal_to_string(int i) _const_;
+int signal_from_string(const char *s) _pure_;
+
+int signal_from_string_try_harder(const char *s);
+
+extern int saved_argc;
+extern char **saved_argv;
+
+bool kexec_loaded(void);
+
+int prot_from_flags(int flags) _const_;
+
+char *format_bytes(char *buf, size_t l, off_t t);
+
+int fd_wait_for_event(int fd, int event, usec_t timeout);
+
+void* memdup(const void *p, size_t l) _alloc_(2);
+
+int is_kernel_thread(pid_t pid);
+
+int fd_inc_sndbuf(int fd, size_t n);
+int fd_inc_rcvbuf(int fd, size_t n);
+
+int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...);
+
+int setrlimit_closest(int resource, const struct rlimit *rlim);
+
+int getenv_for_pid(pid_t pid, const char *field, char **_value);
+
+bool is_valid_documentation_url(const char *url) _pure_;
+
+bool in_initrd(void);
+
+void warn_melody(void);
+
+int get_home_dir(char **ret);
+
+static inline void freep(void *p) {
+ free(*(void**) p);
+}
+
+static inline void fclosep(FILE **f) {
+ if (*f)
+ fclose(*f);
+}
+
+static inline void pclosep(FILE **f) {
+ if (*f)
+ pclose(*f);
+}
+
+static inline void closep(int *fd) {
+ if (*fd >= 0)
+ close_nointr_nofail(*fd);
+}
+
+static inline void closedirp(DIR **d) {
+ if (*d)
+ closedir(*d);
+}
+
+static inline void umaskp(mode_t *u) {
+ umask(*u);
+}
+
+#define _cleanup_free_ _cleanup_(freep)
+#define _cleanup_fclose_ _cleanup_(fclosep)
+#define _cleanup_pclose_ _cleanup_(pclosep)
+#define _cleanup_close_ _cleanup_(closep)
+#define _cleanup_closedir_ _cleanup_(closedirp)
+#define _cleanup_umask_ _cleanup_(umaskp)
+#define _cleanup_globfree_ _cleanup_(globfree)
+
+_malloc_ _alloc_(1, 2) static inline void *malloc_multiply(size_t a, size_t b) {
+ if (_unlikely_(b == 0 || a > ((size_t) -1) / b))
+ return NULL;
+
+ return malloc(a * b);
+}
+
+_alloc_(2, 3) static inline void *memdup_multiply(const void *p, size_t a, size_t b) {
+ if (_unlikely_(b == 0 || a > ((size_t) -1) / b))
+ return NULL;
+
+ return memdup(p, a * b);
+}
+
+bool filename_is_safe(const char *p) _pure_;
+bool path_is_safe(const char *p) _pure_;
+bool string_is_safe(const char *p) _pure_;
+bool string_has_cc(const char *p) _pure_;
+
+void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
+ int (*compar) (const void *, const void *, void *),
+ void *arg);
+
+bool is_locale_utf8(void);
+
+typedef enum DrawSpecialChar {
+ DRAW_TREE_VERT,
+ DRAW_TREE_BRANCH,
+ DRAW_TREE_RIGHT,
+ DRAW_TREE_SPACE,
+ DRAW_TRIANGULAR_BULLET,
+ _DRAW_SPECIAL_CHAR_MAX
+} DrawSpecialChar;
+const char *draw_special_char(DrawSpecialChar ch);
+
+char *strreplace(const char *text, const char *old_string, const char *new_string);
+
+char *strip_tab_ansi(char **p, size_t *l);
+
+int on_ac_power(void);
+
+int search_and_fopen(const char *path, const char *mode, const char **search, FILE **_f);
+int search_and_fopen_nulstr(const char *path, const char *mode, const char *search, FILE **_f);
+int create_tmp_dir(char template[], char** dir_name);
+
+#define FOREACH_LINE(line, f, on_error) \
+ for (;;) \
+ if (!fgets(line, sizeof(line), f)) { \
+ if (ferror(f)) { \
+ on_error; \
+ } \
+ break; \
+ } else
+
+#define FOREACH_DIRENT(de, d, on_error) \
+ for (errno = 0, de = readdir(d);; errno = 0, de = readdir(d)) \
+ if (!de) { \
+ if (errno > 0) { \
+ on_error; \
+ } \
+ break; \
+ } else if (ignore_file((de)->d_name)) \
+ continue; \
+ else
+
+static inline void *mempset(void *s, int c, size_t n) {
+ memset(s, c, n);
+ return (uint8_t*)s + n;
+}
+
+char *hexmem(const void *p, size_t l);
+void *unhexmem(const char *p, size_t l);
+
+char *strextend(char **x, ...) _sentinel_;
+char *strrep(const char *s, unsigned n);
+
+void* greedy_realloc(void **p, size_t *allocated, size_t need);
+#define GREEDY_REALLOC(array, allocated, need) \
+ greedy_realloc((void**) &(array), &(allocated), sizeof((array)[0]) * (need))
+
+static inline void _reset_errno_(int *saved_errno) {
+ errno = *saved_errno;
+}
+
+#define PROTECT_ERRNO _cleanup_(_reset_errno_) __attribute__((unused)) int _saved_errno_ = errno
+
+struct _umask_struct_ {
+ mode_t mask;
+ bool quit;
+};
+
+static inline void _reset_umask_(struct _umask_struct_ *s) {
+ umask(s->mask);
+};
+
+#define RUN_WITH_UMASK(mask) \
+ for (_cleanup_(_reset_umask_) struct _umask_struct_ _saved_umask_ = { umask(mask), false }; \
+ !_saved_umask_.quit ; \
+ _saved_umask_.quit = true)
+
+static inline unsigned u64log2(uint64_t n) {
+ return (n > 1) ? __builtin_clzll(n) ^ 63U : 0;
+}
+
+static inline bool logind_running(void) {
+ return access("/run/systemd/seats/", F_OK) >= 0;
+}
+
+#define DECIMAL_STR_WIDTH(x) \
+ ({ \
+ typeof(x) _x_ = (x); \
+ unsigned ans = 1; \
+ while (_x_ /= 10) \
+ ans++; \
+ ans; \
+ })
+
+int unlink_noerrno(const char *path);
+
+#define alloca0(n) \
+ ({ \
+ char *_new_; \
+ size_t _len_ = n; \
+ _new_ = alloca(_len_); \
+ (void *) memset(_new_, 0, _len_); \
+ })
+
+#define strappenda(a, b) \
+ ({ \
+ const char *_a_ = (a), *_b_ = (b); \
+ char *_c_; \
+ size_t _x_, _y_; \
+ _x_ = strlen(_a_); \
+ _y_ = strlen(_b_); \
+ _c_ = alloca(_x_ + _y_ + 1); \
+ strcpy(stpcpy(_c_, _a_), _b_); \
+ _c_; \
+ })
+
+#define procfs_file_alloca(pid, field) \
+ ({ \
+ pid_t _pid_ = (pid); \
+ char *_r_; \
+ _r_ = alloca(sizeof("/proc/") -1 + DECIMAL_STR_MAX(pid_t) + 1 + sizeof(field)); \
+ sprintf(_r_, "/proc/%lu/" field, (unsigned long) _pid_); \
+ _r_; \
+ })
+
+struct _locale_struct_ {
+ locale_t saved_locale;
+ locale_t new_locale;
+ bool quit;
+};
+
+static inline void _reset_locale_(struct _locale_struct_ *s) {
+ PROTECT_ERRNO;
+ if (s->saved_locale != (locale_t) 0)
+ uselocale(s->saved_locale);
+ if (s->new_locale != (locale_t) 0)
+ freelocale(s->new_locale);
+}
+
+#define RUN_WITH_LOCALE(mask, loc) \
+ for (_cleanup_(_reset_locale_) struct _locale_struct_ _saved_locale_ = { (locale_t) 0, (locale_t) 0, false }; \
+ ({ \
+ if (!_saved_locale_.quit) { \
+ PROTECT_ERRNO; \
+ _saved_locale_.new_locale = newlocale((mask), (loc), (locale_t) 0); \
+ if (_saved_locale_.new_locale != (locale_t) 0) \
+ _saved_locale_.saved_locale = uselocale(_saved_locale_.new_locale); \
+ } \
+ !_saved_locale_.quit; }) ; \
+ _saved_locale_.quit = true)
+
+bool id128_is_valid(const char *s) _pure_;
diff --git a/src/shared/utmp-wtmp.c b/src/shared/utmp-wtmp.c
new file mode 100644
index 0000000000..5d88405e13
--- /dev/null
+++ b/src/shared/utmp-wtmp.c
@@ -0,0 +1,410 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <utmpx.h>
+#include <errno.h>
+#include <assert.h>
+#include <string.h>
+#include <sys/utsname.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <sys/poll.h>
+
+#include "macro.h"
+#include "path-util.h"
+#include "utmp-wtmp.h"
+
+int utmp_get_runlevel(int *runlevel, int *previous) {
+ struct utmpx *found, lookup = { .ut_type = RUN_LVL };
+ int r;
+ const char *e;
+
+ assert(runlevel);
+
+ /* If these values are set in the environment this takes
+ * precedence. Presumably, sysvinit does this to work around a
+ * race condition that would otherwise exist where we'd always
+ * go to disk and hence might read runlevel data that might be
+ * very new and does not apply to the current script being
+ * executed. */
+
+ if ((e = getenv("RUNLEVEL")) && e[0] > 0) {
+ *runlevel = e[0];
+
+ if (previous) {
+ /* $PREVLEVEL seems to be an Upstart thing */
+
+ if ((e = getenv("PREVLEVEL")) && e[0] > 0)
+ *previous = e[0];
+ else
+ *previous = 0;
+ }
+
+ return 0;
+ }
+
+ if (utmpxname(_PATH_UTMPX) < 0)
+ return -errno;
+
+ setutxent();
+
+ if (!(found = getutxid(&lookup)))
+ r = -errno;
+ else {
+ int a, b;
+
+ a = found->ut_pid & 0xFF;
+ b = (found->ut_pid >> 8) & 0xFF;
+
+ *runlevel = a;
+ if (previous)
+ *previous = b;
+
+ r = 0;
+ }
+
+ endutxent();
+
+ return r;
+}
+
+static void init_timestamp(struct utmpx *store, usec_t t) {
+ assert(store);
+
+ zero(*store);
+
+ if (t <= 0)
+ t = now(CLOCK_REALTIME);
+
+ store->ut_tv.tv_sec = t / USEC_PER_SEC;
+ store->ut_tv.tv_usec = t % USEC_PER_SEC;
+}
+
+static void init_entry(struct utmpx *store, usec_t t) {
+ struct utsname uts = {};
+
+ assert(store);
+
+ init_timestamp(store, t);
+
+ if (uname(&uts) >= 0)
+ strncpy(store->ut_host, uts.release, sizeof(store->ut_host));
+
+ strncpy(store->ut_line, "~", sizeof(store->ut_line)); /* or ~~ ? */
+ strncpy(store->ut_id, "~~", sizeof(store->ut_id));
+}
+
+static int write_entry_utmp(const struct utmpx *store) {
+ int r;
+
+ assert(store);
+
+ /* utmp is similar to wtmp, but there is only one entry for
+ * each entry type resp. user; i.e. basically a key/value
+ * table. */
+
+ if (utmpxname(_PATH_UTMPX) < 0)
+ return -errno;
+
+ setutxent();
+
+ if (!pututxline(store))
+ r = -errno;
+ else
+ r = 0;
+
+ endutxent();
+
+ return r;
+}
+
+static int write_entry_wtmp(const struct utmpx *store) {
+ assert(store);
+
+ /* wtmp is a simple append-only file where each entry is
+ simply appended to * the end; i.e. basically a log. */
+
+ errno = 0;
+ updwtmpx(_PATH_WTMPX, store);
+ return -errno;
+}
+
+static int write_utmp_wtmp(const struct utmpx *store_utmp, const struct utmpx *store_wtmp) {
+ int r, s;
+
+ r = write_entry_utmp(store_utmp);
+ s = write_entry_wtmp(store_wtmp);
+
+ if (r >= 0)
+ r = s;
+
+ /* If utmp/wtmp have been disabled, that's a good thing, hence
+ * ignore the errors */
+ if (r == -ENOENT)
+ r = 0;
+
+ return r;
+}
+
+static int write_entry_both(const struct utmpx *store) {
+ return write_utmp_wtmp(store, store);
+}
+
+int utmp_put_shutdown(void) {
+ struct utmpx store;
+
+ init_entry(&store, 0);
+
+ store.ut_type = RUN_LVL;
+ strncpy(store.ut_user, "shutdown", sizeof(store.ut_user));
+
+ return write_entry_both(&store);
+}
+
+int utmp_put_reboot(usec_t t) {
+ struct utmpx store;
+
+ init_entry(&store, t);
+
+ store.ut_type = BOOT_TIME;
+ strncpy(store.ut_user, "reboot", sizeof(store.ut_user));
+
+ return write_entry_both(&store);
+}
+
+_pure_ static const char *sanitize_id(const char *id) {
+ size_t l;
+
+ assert(id);
+ l = strlen(id);
+
+ if (l <= sizeof(((struct utmpx*) NULL)->ut_id))
+ return id;
+
+ return id + l - sizeof(((struct utmpx*) NULL)->ut_id);
+}
+
+int utmp_put_init_process(const char *id, pid_t pid, pid_t sid, const char *line) {
+ struct utmpx store;
+
+ assert(id);
+
+ init_timestamp(&store, 0);
+
+ store.ut_type = INIT_PROCESS;
+ store.ut_pid = pid;
+ store.ut_session = sid;
+
+ strncpy(store.ut_id, sanitize_id(id), sizeof(store.ut_id));
+
+ if (line)
+ strncpy(store.ut_line, path_get_file_name(line), sizeof(store.ut_line));
+
+ return write_entry_both(&store);
+}
+
+int utmp_put_dead_process(const char *id, pid_t pid, int code, int status) {
+ struct utmpx lookup, store, store_wtmp, *found;
+
+ assert(id);
+
+ setutxent();
+
+ zero(lookup);
+ lookup.ut_type = INIT_PROCESS; /* looks for DEAD_PROCESS, LOGIN_PROCESS, USER_PROCESS, too */
+ strncpy(lookup.ut_id, sanitize_id(id), sizeof(lookup.ut_id));
+
+ if (!(found = getutxid(&lookup)))
+ return 0;
+
+ if (found->ut_pid != pid)
+ return 0;
+
+ memcpy(&store, found, sizeof(store));
+ store.ut_type = DEAD_PROCESS;
+ store.ut_exit.e_termination = code;
+ store.ut_exit.e_exit = status;
+
+ zero(store.ut_user);
+ zero(store.ut_host);
+ zero(store.ut_tv);
+
+ memcpy(&store_wtmp, &store, sizeof(store_wtmp));
+ /* wtmp wants the current time */
+ init_timestamp(&store_wtmp, 0);
+
+ return write_utmp_wtmp(&store, &store_wtmp);
+}
+
+
+int utmp_put_runlevel(int runlevel, int previous) {
+ struct utmpx store;
+ int r;
+
+ assert(runlevel > 0);
+
+ if (previous <= 0) {
+ /* Find the old runlevel automatically */
+
+ if ((r = utmp_get_runlevel(&previous, NULL)) < 0) {
+ if (r != -ESRCH)
+ return r;
+
+ previous = 0;
+ }
+ }
+
+ if (previous == runlevel)
+ return 0;
+
+ init_entry(&store, 0);
+
+ store.ut_type = RUN_LVL;
+ store.ut_pid = (runlevel & 0xFF) | ((previous & 0xFF) << 8);
+ strncpy(store.ut_user, "runlevel", sizeof(store.ut_user));
+
+ return write_entry_both(&store);
+}
+
+#define TIMEOUT_MSEC 50
+
+static int write_to_terminal(const char *tty, const char *message) {
+ _cleanup_close_ int fd = -1;
+ const char *p;
+ size_t left;
+ usec_t end;
+
+ assert(tty);
+ assert(message);
+
+ fd = open(tty, O_WRONLY|O_NDELAY|O_NOCTTY|O_CLOEXEC);
+ if (fd < 0 || !isatty(fd))
+ return -errno;
+
+ p = message;
+ left = strlen(message);
+
+ end = now(CLOCK_MONOTONIC) + TIMEOUT_MSEC*USEC_PER_MSEC;
+
+ while (left > 0) {
+ ssize_t n;
+ struct pollfd pollfd = {
+ .fd = fd,
+ .events = POLLOUT,
+ };
+ usec_t t;
+ int k;
+
+ t = now(CLOCK_MONOTONIC);
+
+ if (t >= end)
+ return -ETIME;
+
+ k = poll(&pollfd, 1, (end - t) / USEC_PER_MSEC);
+ if (k < 0)
+ return -errno;
+
+ if (k == 0)
+ return -ETIME;
+
+ n = write(fd, p, left);
+ if (n < 0) {
+ if (errno == EAGAIN)
+ continue;
+
+ return -errno;
+ }
+
+ assert((size_t) n <= left);
+
+ p += n;
+ left -= n;
+ }
+
+ return 0;
+}
+
+int utmp_wall(const char *message, bool (*match_tty)(const char *tty)) {
+ struct utmpx *u;
+ char date[FORMAT_TIMESTAMP_MAX];
+ char *text = NULL, *hn = NULL, *un = NULL, *tty = NULL;
+ int r;
+
+ if (!(hn = gethostname_malloc()) ||
+ !(un = getlogname_malloc())) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ getttyname_harder(STDIN_FILENO, &tty);
+
+ if (asprintf(&text,
+ "\a\r\n"
+ "Broadcast message from %s@%s%s%s (%s):\r\n\r\n"
+ "%s\r\n\r\n",
+ un, hn,
+ tty ? " on " : "", strempty(tty),
+ format_timestamp(date, sizeof(date), now(CLOCK_REALTIME)),
+ message) < 0) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ setutxent();
+
+ r = 0;
+
+ while ((u = getutxent())) {
+ int q;
+ const char *path;
+ char *buf = NULL;
+
+ if (u->ut_type != USER_PROCESS || u->ut_user[0] == 0)
+ continue;
+
+ /* this access is fine, because strlen("/dev/") << 32 (UT_LINESIZE) */
+ if (path_startswith(u->ut_line, "/dev/"))
+ path = u->ut_line;
+ else {
+ if (asprintf(&buf, "/dev/%.*s",
+ (int) sizeof(u->ut_line), u->ut_line) < 0) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ path = buf;
+ }
+
+ if (!match_tty || match_tty(path))
+ if ((q = write_to_terminal(path, text)) < 0)
+ r = q;
+
+ free(buf);
+ }
+
+finish:
+ free(hn);
+ free(un);
+ free(tty);
+ free(text);
+
+ return r;
+}
diff --git a/src/shared/utmp-wtmp.h b/src/shared/utmp-wtmp.h
new file mode 100644
index 0000000000..5924023203
--- /dev/null
+++ b/src/shared/utmp-wtmp.h
@@ -0,0 +1,35 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "util.h"
+
+int utmp_get_runlevel(int *runlevel, int *previous);
+
+int utmp_put_shutdown(void);
+int utmp_put_reboot(usec_t timestamp);
+int utmp_put_runlevel(int runlevel, int previous);
+
+int utmp_put_dead_process(const char *id, pid_t pid, int code, int status);
+int utmp_put_init_process(const char *id, pid_t pid, pid_t sid, const char *line);
+
+int utmp_wall(const char *message, bool (*match_tty)(const char *tty));
diff --git a/src/shared/virt.c b/src/shared/virt.c
new file mode 100644
index 0000000000..1c86a3dd1e
--- /dev/null
+++ b/src/shared/virt.c
@@ -0,0 +1,272 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <string.h>
+#include <errno.h>
+#include <unistd.h>
+
+#include "util.h"
+#include "virt.h"
+#include "fileio.h"
+
+/* Returns a short identifier for the various VM implementations */
+int detect_vm(const char **id) {
+
+#if defined(__i386__) || defined(__x86_64__)
+
+ /* Both CPUID and DMI are x86 specific interfaces... */
+
+ static const char *const dmi_vendors[] = {
+ "/sys/class/dmi/id/sys_vendor",
+ "/sys/class/dmi/id/board_vendor",
+ "/sys/class/dmi/id/bios_vendor"
+ };
+
+ static const char dmi_vendor_table[] =
+ "QEMU\0" "qemu\0"
+ /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
+ "VMware\0" "vmware\0"
+ "VMW\0" "vmware\0"
+ "Microsoft Corporation\0" "microsoft\0"
+ "innotek GmbH\0" "oracle\0"
+ "Xen\0" "xen\0"
+ "Bochs\0" "bochs\0";
+
+ static const char cpuid_vendor_table[] =
+ "XenVMMXenVMM\0" "xen\0"
+ "KVMKVMKVM\0" "kvm\0"
+ /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
+ "VMwareVMware\0" "vmware\0"
+ /* http://msdn.microsoft.com/en-us/library/ff542428.aspx */
+ "Microsoft Hv\0" "microsoft\0";
+
+ uint32_t eax, ecx;
+ union {
+ uint32_t sig32[3];
+ char text[13];
+ } sig = {};
+ unsigned i;
+ const char *j, *k;
+ bool hypervisor;
+ _cleanup_free_ char *hvtype = NULL;
+ int r;
+
+ /* Try high-level hypervisor sysfs file first:
+ *
+ * https://bugs.freedesktop.org/show_bug.cgi?id=61491 */
+ r = read_one_line_file("/sys/hypervisor/type", &hvtype);
+ if (r >= 0) {
+ if (streq(hvtype, "xen")) {
+ if (id)
+ *id = "xen";
+
+ return 1;
+ }
+ } else if (r != -ENOENT)
+ return r;
+
+ /* http://lwn.net/Articles/301888/ */
+
+#if defined (__i386__)
+#define REG_a "eax"
+#define REG_b "ebx"
+#elif defined (__amd64__)
+#define REG_a "rax"
+#define REG_b "rbx"
+#endif
+
+ /* First detect whether there is a hypervisor */
+ eax = 1;
+ __asm__ __volatile__ (
+ /* ebx/rbx is being used for PIC! */
+ " push %%"REG_b" \n\t"
+ " cpuid \n\t"
+ " pop %%"REG_b" \n\t"
+
+ : "=a" (eax), "=c" (ecx)
+ : "0" (eax)
+ );
+
+ hypervisor = !!(ecx & 0x80000000U);
+
+ if (hypervisor) {
+
+ /* There is a hypervisor, see what it is */
+ eax = 0x40000000U;
+ __asm__ __volatile__ (
+ /* ebx/rbx is being used for PIC! */
+ " push %%"REG_b" \n\t"
+ " cpuid \n\t"
+ " mov %%ebx, %1 \n\t"
+ " pop %%"REG_b" \n\t"
+
+ : "=a" (eax), "=r" (sig.sig32[0]), "=c" (sig.sig32[1]), "=d" (sig.sig32[2])
+ : "0" (eax)
+ );
+
+ NULSTR_FOREACH_PAIR(j, k, cpuid_vendor_table)
+ if (streq(sig.text, j)) {
+
+ if (id)
+ *id = k;
+
+ return 1;
+ }
+ }
+
+ for (i = 0; i < ELEMENTSOF(dmi_vendors); i++) {
+ _cleanup_free_ char *s = NULL;
+ const char *found = NULL;
+
+ r = read_one_line_file(dmi_vendors[i], &s);
+ if (r < 0) {
+ if (r != -ENOENT)
+ return r;
+
+ continue;
+ }
+
+ NULSTR_FOREACH_PAIR(j, k, dmi_vendor_table)
+ if (startswith(s, j))
+ found = k;
+
+ if (found) {
+ if (id)
+ *id = found;
+
+ return 1;
+ }
+ }
+
+ if (hypervisor || hvtype) {
+ if (id)
+ *id = "other";
+
+ return 1;
+ }
+
+#endif
+ return 0;
+}
+
+int detect_container(const char **id) {
+ _cleanup_free_ char *e = NULL;
+ int r;
+
+ /* Unfortunately many of these operations require root access
+ * in one way or another */
+
+ r = running_in_chroot();
+ if (r < 0)
+ return r;
+ if (r > 0) {
+
+ if (id)
+ *id = "chroot";
+
+ return 1;
+ }
+
+ /* /proc/vz exists in container and outside of the container,
+ * /proc/bc only outside of the container. */
+ if (access("/proc/vz", F_OK) >= 0 &&
+ access("/proc/bc", F_OK) < 0) {
+
+ if (id)
+ *id = "openvz";
+
+ return 1;
+ }
+
+ r = getenv_for_pid(1, "container", &e);
+ if (r <= 0)
+ return r;
+
+ /* We only recognize a selected few here, since we want to
+ * enforce a redacted namespace */
+ if (streq(e, "lxc")) {
+ if (id)
+ *id = "lxc";
+ } else if (streq(e, "lxc-libvirt")) {
+ if (id)
+ *id = "lxc-libvirt";
+ } else if (streq(e, "systemd-nspawn")) {
+ if (id)
+ *id = "systemd-nspawn";
+ } else {
+ if (id)
+ *id = "other";
+ }
+
+ return r;
+}
+
+/* Returns a short identifier for the various VM/container implementations */
+Virtualization detect_virtualization(const char **id) {
+
+ static __thread Virtualization cached_virt = _VIRTUALIZATION_INVALID;
+ static __thread const char *cached_id = NULL;
+
+ const char *_id;
+ int r;
+ Virtualization v;
+
+ if (_likely_(cached_virt >= 0)) {
+
+ if (id && cached_virt > 0)
+ *id = cached_id;
+
+ return cached_virt;
+ }
+
+ r = detect_container(&_id);
+ if (r < 0) {
+ v = r;
+ goto finish;
+ } else if (r > 0) {
+ v = VIRTUALIZATION_CONTAINER;
+ goto finish;
+ }
+
+ r = detect_vm(&_id);
+ if (r < 0) {
+ v = r;
+ goto finish;
+ } else if (r > 0) {
+ v = VIRTUALIZATION_VM;
+ goto finish;
+ }
+
+ v = VIRTUALIZATION_NONE;
+
+finish:
+ if (v > 0) {
+ cached_id = _id;
+
+ if (id)
+ *id = _id;
+ }
+
+ if (v >= 0)
+ cached_virt = v;
+
+ return v;
+}
diff --git a/src/shared/virt.h b/src/shared/virt.h
new file mode 100644
index 0000000000..aa6ad35ba9
--- /dev/null
+++ b/src/shared/virt.h
@@ -0,0 +1,35 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+int detect_vm(const char **id);
+int detect_container(const char **id);
+
+typedef enum Virtualization {
+ VIRTUALIZATION_NONE = 0,
+ VIRTUALIZATION_VM,
+ VIRTUALIZATION_CONTAINER,
+ _VIRTUALIZATION_MAX,
+ _VIRTUALIZATION_INVALID = -1
+} Virtualization;
+
+Virtualization detect_virtualization(const char **id);
diff --git a/src/shared/watchdog.c b/src/shared/watchdog.c
new file mode 100644
index 0000000000..ddbe7afd3c
--- /dev/null
+++ b/src/shared/watchdog.c
@@ -0,0 +1,169 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/ioctl.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <linux/watchdog.h>
+
+#include "watchdog.h"
+#include "log.h"
+
+static int watchdog_fd = -1;
+static usec_t watchdog_timeout = (usec_t) -1;
+
+static int update_timeout(void) {
+ int r;
+
+ if (watchdog_fd < 0)
+ return 0;
+
+ if (watchdog_timeout == (usec_t) -1)
+ return 0;
+ else if (watchdog_timeout == 0) {
+ int flags;
+
+ flags = WDIOS_DISABLECARD;
+ r = ioctl(watchdog_fd, WDIOC_SETOPTIONS, &flags);
+ if (r < 0) {
+ log_warning("Failed to disable hardware watchdog: %m");
+ return -errno;
+ }
+ } else {
+ int sec, flags;
+ char buf[FORMAT_TIMESPAN_MAX];
+
+ sec = (int) ((watchdog_timeout + USEC_PER_SEC - 1) / USEC_PER_SEC);
+ r = ioctl(watchdog_fd, WDIOC_SETTIMEOUT, &sec);
+ if (r < 0) {
+ log_warning("Failed to set timeout to %is: %m", sec);
+ return -errno;
+ }
+
+ watchdog_timeout = (usec_t) sec * USEC_PER_SEC;
+ log_info("Set hardware watchdog to %s.", format_timespan(buf, sizeof(buf), watchdog_timeout, 0));
+
+ flags = WDIOS_ENABLECARD;
+ r = ioctl(watchdog_fd, WDIOC_SETOPTIONS, &flags);
+ if (r < 0) {
+ log_warning("Failed to enable hardware watchdog: %m");
+ return -errno;
+ }
+
+ r = ioctl(watchdog_fd, WDIOC_KEEPALIVE, 0);
+ if (r < 0) {
+ log_warning("Failed to ping hardware watchdog: %m");
+ return -errno;
+ }
+ }
+
+ return 0;
+}
+
+static int open_watchdog(void) {
+ struct watchdog_info ident;
+
+ if (watchdog_fd >= 0)
+ return 0;
+
+ watchdog_fd = open("/dev/watchdog", O_WRONLY|O_CLOEXEC);
+ if (watchdog_fd < 0)
+ return -errno;
+
+ if (ioctl(watchdog_fd, WDIOC_GETSUPPORT, &ident) >= 0)
+ log_info("Hardware watchdog '%s', version %x",
+ ident.identity,
+ ident.firmware_version);
+
+ return update_timeout();
+}
+
+int watchdog_set_timeout(usec_t *usec) {
+ int r;
+
+ watchdog_timeout = *usec;
+
+ /* If we didn't open the watchdog yet and didn't get any
+ * explicit timeout value set, don't do anything */
+ if (watchdog_fd < 0 && watchdog_timeout == (usec_t) -1)
+ return 0;
+
+ if (watchdog_fd < 0)
+ r = open_watchdog();
+ else
+ r = update_timeout();
+
+ *usec = watchdog_timeout;
+
+ return r;
+}
+
+int watchdog_ping(void) {
+ int r;
+
+ if (watchdog_fd < 0) {
+ r = open_watchdog();
+ if (r < 0)
+ return r;
+ }
+
+ r = ioctl(watchdog_fd, WDIOC_KEEPALIVE, 0);
+ if (r < 0) {
+ log_warning("Failed to ping hardware watchdog: %m");
+ return -errno;
+ }
+
+ return 0;
+}
+
+void watchdog_close(bool disarm) {
+ int r;
+
+ if (watchdog_fd < 0)
+ return;
+
+ if (disarm) {
+ int flags;
+
+ /* Explicitly disarm it */
+ flags = WDIOS_DISABLECARD;
+ r = ioctl(watchdog_fd, WDIOC_SETOPTIONS, &flags);
+ if (r < 0)
+ log_warning("Failed to disable hardware watchdog: %m");
+
+ /* To be sure, use magic close logic, too */
+ for (;;) {
+ static const char v = 'V';
+
+ if (write(watchdog_fd, &v, 1) > 0)
+ break;
+
+ if (errno != EINTR) {
+ log_error("Failed to disarm watchdog timer: %m");
+ break;
+ }
+ }
+ }
+
+ close_nointr_nofail(watchdog_fd);
+ watchdog_fd = -1;
+}
diff --git a/src/shared/watchdog.h b/src/shared/watchdog.h
new file mode 100644
index 0000000000..b748b15857
--- /dev/null
+++ b/src/shared/watchdog.h
@@ -0,0 +1,28 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "util.h"
+
+int watchdog_set_timeout(usec_t *usec);
+int watchdog_ping(void);
+void watchdog_close(bool disarm);
diff --git a/src/shutdownd/shutdownd.c b/src/shutdownd/shutdownd.c
new file mode 100644
index 0000000000..461a7261f4
--- /dev/null
+++ b/src/shutdownd/shutdownd.c
@@ -0,0 +1,471 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/socket.h>
+#include <sys/poll.h>
+#include <sys/types.h>
+#include <sys/timerfd.h>
+#include <assert.h>
+#include <string.h>
+#include <errno.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <stddef.h>
+
+#include <systemd/sd-daemon.h>
+#include <systemd/sd-shutdown.h>
+
+#include "log.h"
+#include "macro.h"
+#include "util.h"
+#include "utmp-wtmp.h"
+#include "mkdir.h"
+#include "fileio.h"
+
+union shutdown_buffer {
+ struct sd_shutdown_command command;
+ char space[offsetof(struct sd_shutdown_command, wall_message) + LINE_MAX];
+};
+
+static int read_packet(int fd, union shutdown_buffer *_b) {
+ struct ucred *ucred;
+ ssize_t n;
+
+ union shutdown_buffer b; /* We maintain our own copy here, in
+ * order not to corrupt the last message */
+ struct iovec iovec = {
+ iovec.iov_base = &b,
+ iovec.iov_len = sizeof(b) - 1,
+ };
+ union {
+ struct cmsghdr cmsghdr;
+ uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
+ } control = {};
+ struct msghdr msghdr = {
+ .msg_iov = &iovec,
+ msghdr.msg_iovlen = 1,
+ msghdr.msg_control = &control,
+ msghdr.msg_controllen = sizeof(control),
+ };
+
+ assert(fd >= 0);
+ assert(_b);
+
+ n = recvmsg(fd, &msghdr, MSG_DONTWAIT);
+ if (n <= 0) {
+ if (n == 0) {
+ log_error("Short read");
+ return -EIO;
+ }
+
+ if (errno == EAGAIN || errno == EINTR)
+ return 0;
+
+ log_error("recvmsg(): %m");
+ return -errno;
+ }
+
+ if (msghdr.msg_controllen < CMSG_LEN(sizeof(struct ucred)) ||
+ control.cmsghdr.cmsg_level != SOL_SOCKET ||
+ control.cmsghdr.cmsg_type != SCM_CREDENTIALS ||
+ control.cmsghdr.cmsg_len != CMSG_LEN(sizeof(struct ucred))) {
+ log_warning("Received message without credentials. Ignoring.");
+ return 0;
+ }
+
+ ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
+ if (ucred->uid != 0) {
+ log_warning("Got request from unprivileged user. Ignoring.");
+ return 0;
+ }
+
+ if ((size_t) n < offsetof(struct sd_shutdown_command, wall_message)) {
+ log_warning("Message has invalid size. Ignoring.");
+ return 0;
+ }
+
+ if (b.command.mode != SD_SHUTDOWN_NONE &&
+ b.command.mode != SD_SHUTDOWN_REBOOT &&
+ b.command.mode != SD_SHUTDOWN_POWEROFF &&
+ b.command.mode != SD_SHUTDOWN_HALT &&
+ b.command.mode != SD_SHUTDOWN_KEXEC) {
+ log_warning("Message has invalid mode. Ignoring.");
+ return 0;
+ }
+
+ b.space[n] = 0;
+
+ *_b = b;
+ return 1;
+}
+
+static void warn_wall(usec_t n, struct sd_shutdown_command *c) {
+ char date[FORMAT_TIMESTAMP_MAX];
+ const char *prefix;
+ char *l = NULL;
+
+ assert(c);
+ assert(c->warn_wall);
+
+ if (n >= c->usec)
+ return;
+
+ if (c->mode == SD_SHUTDOWN_HALT)
+ prefix = "The system is going down for system halt at ";
+ else if (c->mode == SD_SHUTDOWN_POWEROFF)
+ prefix = "The system is going down for power-off at ";
+ else if (c->mode == SD_SHUTDOWN_REBOOT)
+ prefix = "The system is going down for reboot at ";
+ else if (c->mode == SD_SHUTDOWN_KEXEC)
+ prefix = "The system is going down for kexec reboot at ";
+ else if (c->mode == SD_SHUTDOWN_NONE)
+ prefix = "The system shutdown has been cancelled at ";
+ else
+ assert_not_reached("Unknown mode!");
+
+ if (asprintf(&l, "%s%s%s%s!", c->wall_message, c->wall_message[0] ? "\n" : "",
+ prefix, format_timestamp(date, sizeof(date), c->usec)) < 0)
+ log_error("Failed to allocate wall message");
+ else {
+ utmp_wall(l, NULL);
+ free(l);
+ }
+}
+
+_const_ static usec_t when_wall(usec_t n, usec_t elapse) {
+
+ static const struct {
+ usec_t delay;
+ usec_t interval;
+ } table[] = {
+ { 0, USEC_PER_MINUTE },
+ { 10 * USEC_PER_MINUTE, 15 * USEC_PER_MINUTE },
+ { USEC_PER_HOUR, 30 * USEC_PER_MINUTE },
+ { 3 * USEC_PER_HOUR, USEC_PER_HOUR },
+ };
+
+ usec_t left, sub;
+ unsigned i = ELEMENTSOF(table) - 1;
+
+ /* If the time is already passed, then don't announce */
+ if (n >= elapse)
+ return 0;
+
+ left = elapse - n;
+ while (left < table[i].delay)
+ i--;
+ sub = (left / table[i].interval) * table[i].interval;
+
+ assert(sub < elapse);
+ return elapse - sub;
+}
+
+static usec_t when_nologin(usec_t elapse) {
+ return elapse > 5*USEC_PER_MINUTE ? elapse - 5*USEC_PER_MINUTE : 1;
+}
+
+static const char *mode_to_string(enum sd_shutdown_mode m) {
+ switch (m) {
+ case SD_SHUTDOWN_REBOOT:
+ return "reboot";
+ case SD_SHUTDOWN_POWEROFF:
+ return "poweroff";
+ case SD_SHUTDOWN_HALT:
+ return "halt";
+ case SD_SHUTDOWN_KEXEC:
+ return "kexec";
+ default:
+ return NULL;
+ }
+}
+
+static int update_schedule_file(struct sd_shutdown_command *c) {
+ int r;
+ FILE *f;
+ char *temp_path, *t;
+
+ assert(c);
+
+ r = mkdir_safe_label("/run/systemd/shutdown", 0755, 0, 0);
+ if (r < 0) {
+ log_error("Failed to create shutdown subdirectory: %s", strerror(-r));
+ return r;
+ }
+
+ t = cescape(c->wall_message);
+ if (!t)
+ return log_oom();
+
+ r = fopen_temporary("/run/systemd/shutdown/scheduled", &f, &temp_path);
+ if (r < 0) {
+ log_error("Failed to save information about scheduled shutdowns: %s", strerror(-r));
+ free(t);
+ return r;
+ }
+
+ fchmod(fileno(f), 0644);
+
+ fprintf(f,
+ "USEC=%llu\n"
+ "WARN_WALL=%i\n"
+ "MODE=%s\n",
+ (unsigned long long) c->usec,
+ c->warn_wall,
+ mode_to_string(c->mode));
+
+ if (c->dry_run)
+ fputs("DRY_RUN=1\n", f);
+
+ if (!isempty(t))
+ fprintf(f, "WALL_MESSAGE=%s\n", t);
+
+ free(t);
+
+ fflush(f);
+
+ if (ferror(f) || rename(temp_path, "/run/systemd/shutdown/scheduled") < 0) {
+ log_error("Failed to write information about scheduled shutdowns: %m");
+ r = -errno;
+
+ unlink(temp_path);
+ unlink("/run/systemd/shutdown/scheduled");
+ }
+
+ fclose(f);
+ free(temp_path);
+
+ return r;
+}
+
+static bool scheduled(struct sd_shutdown_command *c) {
+ return c->usec > 0 && c->mode != SD_SHUTDOWN_NONE;
+}
+
+int main(int argc, char *argv[]) {
+ enum {
+ FD_SOCKET,
+ FD_WALL_TIMER,
+ FD_NOLOGIN_TIMER,
+ FD_SHUTDOWN_TIMER,
+ _FD_MAX
+ };
+
+ int r = EXIT_FAILURE, n_fds;
+ union shutdown_buffer b = {};
+ struct pollfd pollfd[_FD_MAX] = {};
+ bool exec_shutdown = false, unlink_nologin = false;
+ unsigned i;
+
+ if (getppid() != 1) {
+ log_error("This program should be invoked by init only.");
+ return EXIT_FAILURE;
+ }
+
+ if (argc > 1) {
+ log_error("This program does not take arguments.");
+ return EXIT_FAILURE;
+ }
+
+ log_set_target(LOG_TARGET_AUTO);
+ log_parse_environment();
+ log_open();
+
+ umask(0022);
+
+ n_fds = sd_listen_fds(true);
+ if (n_fds < 0) {
+ log_error("Failed to read listening file descriptors from environment: %s", strerror(-r));
+ return EXIT_FAILURE;
+ }
+
+ if (n_fds != 1) {
+ log_error("Need exactly one file descriptor.");
+ return EXIT_FAILURE;
+ }
+
+ pollfd[FD_SOCKET].fd = SD_LISTEN_FDS_START;
+ pollfd[FD_SOCKET].events = POLLIN;
+
+ for (i = FD_WALL_TIMER; i < _FD_MAX; i++) {
+ pollfd[i].events = POLLIN;
+ pollfd[i].fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK|TFD_CLOEXEC);
+ if (pollfd[i].fd < 0) {
+ log_error("timerfd_create(): %m");
+ goto finish;
+ }
+ }
+
+ log_debug("systemd-shutdownd running as pid %lu", (unsigned long) getpid());
+
+ sd_notify(false,
+ "READY=1\n"
+ "STATUS=Processing requests...");
+
+ for (;;) {
+ int k;
+ usec_t n;
+
+ k = poll(pollfd, _FD_MAX, scheduled(&b.command) ? -1 : 0);
+ if (k < 0) {
+
+ if (errno == EAGAIN || errno == EINTR)
+ continue;
+
+ log_error("poll(): %m");
+ goto finish;
+ }
+
+ /* Exit on idle */
+ if (k == 0)
+ break;
+
+ n = now(CLOCK_REALTIME);
+
+ if (pollfd[FD_SOCKET].revents) {
+
+ k = read_packet(pollfd[FD_SOCKET].fd, &b);
+ if (k < 0)
+ goto finish;
+ else if (k > 0) {
+ struct itimerspec its;
+ char date[FORMAT_TIMESTAMP_MAX];
+
+ if (!scheduled(&b.command)) {
+ log_info("Shutdown canceled.");
+ if (b.command.warn_wall)
+ warn_wall(0, &b.command);
+ break;
+ }
+
+ zero(its);
+ if (b.command.warn_wall) {
+ /* Send wall messages every so often */
+ timespec_store(&its.it_value, when_wall(n, b.command.usec));
+
+ /* Warn immediately if less than 15 minutes are left */
+ if (n < b.command.usec &&
+ n + 15*USEC_PER_MINUTE >= b.command.usec)
+ warn_wall(n, &b.command);
+ }
+ if (timerfd_settime(pollfd[FD_WALL_TIMER].fd, TFD_TIMER_ABSTIME, &its, NULL) < 0) {
+ log_error("timerfd_settime(): %m");
+ goto finish;
+ }
+
+ /* Disallow logins 5 minutes prior to shutdown */
+ zero(its);
+ timespec_store(&its.it_value, when_nologin(b.command.usec));
+ if (timerfd_settime(pollfd[FD_NOLOGIN_TIMER].fd, TFD_TIMER_ABSTIME, &its, NULL) < 0) {
+ log_error("timerfd_settime(): %m");
+ goto finish;
+ }
+
+ /* Shutdown after the specified time is reached */
+ zero(its);
+ timespec_store(&its.it_value, b.command.usec);
+ if (timerfd_settime(pollfd[FD_SHUTDOWN_TIMER].fd, TFD_TIMER_ABSTIME, &its, NULL) < 0) {
+ log_error("timerfd_settime(): %m");
+ goto finish;
+ }
+
+ update_schedule_file(&b.command);
+
+ sd_notifyf(false,
+ "STATUS=Shutting down at %s (%s)...",
+ format_timestamp(date, sizeof(date), b.command.usec),
+ mode_to_string(b.command.mode));
+
+ log_info("Shutting down at %s (%s)...", date, mode_to_string(b.command.mode));
+ }
+ }
+
+ if (pollfd[FD_WALL_TIMER].revents) {
+ struct itimerspec its = {};
+
+ warn_wall(n, &b.command);
+ flush_fd(pollfd[FD_WALL_TIMER].fd);
+
+ /* Restart timer */
+ timespec_store(&its.it_value, when_wall(n, b.command.usec));
+ if (timerfd_settime(pollfd[FD_WALL_TIMER].fd, TFD_TIMER_ABSTIME, &its, NULL) < 0) {
+ log_error("timerfd_settime(): %m");
+ goto finish;
+ }
+ }
+
+ if (pollfd[FD_NOLOGIN_TIMER].revents) {
+ int e;
+
+ log_info("Creating /run/nologin, blocking further logins...");
+
+ e = write_string_file_atomic("/run/nologin", "System is going down.");
+ if (e < 0)
+ log_error("Failed to create /run/nologin: %s", strerror(-e));
+ else
+ unlink_nologin = true;
+
+ flush_fd(pollfd[FD_NOLOGIN_TIMER].fd);
+ }
+
+ if (pollfd[FD_SHUTDOWN_TIMER].revents) {
+ exec_shutdown = true;
+ goto finish;
+ }
+ }
+
+ r = EXIT_SUCCESS;
+
+ log_debug("systemd-shutdownd stopped as pid %lu", (unsigned long) getpid());
+
+finish:
+
+ for (i = 0; i < _FD_MAX; i++)
+ if (pollfd[i].fd >= 0)
+ close_nointr_nofail(pollfd[i].fd);
+
+ if (unlink_nologin)
+ unlink("/run/nologin");
+
+ unlink("/run/systemd/shutdown/scheduled");
+
+ if (exec_shutdown && !b.command.dry_run) {
+ char sw[3];
+
+ sw[0] = '-';
+ sw[1] = b.command.mode;
+ sw[2] = 0;
+
+ execl(SYSTEMCTL_BINARY_PATH,
+ "shutdown",
+ sw,
+ "now",
+ (b.command.warn_wall && b.command.wall_message[0]) ? b.command.wall_message :
+ (b.command.warn_wall ? NULL : "--no-wall"),
+ NULL);
+
+ log_error("Failed to execute /sbin/shutdown: %m");
+ }
+
+ sd_notify(false,
+ "STATUS=Exiting...");
+
+ return r;
+}
diff --git a/src/sleep/sleep.c b/src/sleep/sleep.c
new file mode 100644
index 0000000000..a56ab89e54
--- /dev/null
+++ b/src/sleep/sleep.c
@@ -0,0 +1,222 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+ Copyright 2013 Zbigniew Jędrzejewski-Szmek
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include <errno.h>
+#include <string.h>
+#include <getopt.h>
+
+#include "systemd/sd-id128.h"
+#include "systemd/sd-messages.h"
+#include "log.h"
+#include "util.h"
+#include "strv.h"
+#include "fileio.h"
+#include "build.h"
+#include "sleep-config.h"
+
+static char* arg_verb = NULL;
+
+static int write_mode(char **modes) {
+ int r = 0;
+ char **mode;
+
+ STRV_FOREACH(mode, modes) {
+ int k = write_string_file("/sys/power/disk", *mode);
+ if (k == 0)
+ return 0;
+ log_debug("Failed to write '%s' to /sys/power/disk: %s",
+ *mode, strerror(-k));
+ if (r == 0)
+ r = k;
+ }
+
+ if (r < 0)
+ log_error("Failed to write mode to /sys/power/disk: %s",
+ strerror(-r));
+
+ return r;
+}
+
+static int write_state(FILE *f0, char **states) {
+ FILE _cleanup_fclose_ *f = f0;
+ char **state;
+ int r = 0;
+
+ STRV_FOREACH(state, states) {
+ int k;
+
+ k = write_string_to_file(f, *state);
+ if (k == 0)
+ return 0;
+ log_debug("Failed to write '%s' to /sys/power/state: %s",
+ *state, strerror(-k));
+ if (r == 0)
+ r = k;
+
+ fclose(f);
+ f = fopen("/sys/power/state", "we");
+ if (!f) {
+ log_error("Failed to open /sys/power/state: %m");
+ return -errno;
+ }
+ }
+
+ return r;
+}
+
+static int execute(char **modes, char **states) {
+ char* arguments[4];
+ int r;
+ FILE *f;
+ const char* note = strappenda("SLEEP=", arg_verb);
+
+ /* This file is opened first, so that if we hit an error,
+ * we can abort before modyfing any state. */
+ f = fopen("/sys/power/state", "we");
+ if (!f) {
+ log_error("Failed to open /sys/power/state: %m");
+ return -errno;
+ }
+
+ /* Configure the hibernation mode */
+ r = write_mode(modes);
+ if (r < 0)
+ return r;
+
+ arguments[0] = NULL;
+ arguments[1] = (char*) "pre";
+ arguments[2] = arg_verb;
+ arguments[3] = NULL;
+ execute_directory(SYSTEM_SLEEP_PATH, NULL, arguments);
+
+ log_struct(LOG_INFO,
+ MESSAGE_ID(SD_MESSAGE_SLEEP_START),
+ "MESSAGE=Suspending system...",
+ note,
+ NULL);
+
+ r = write_state(f, states);
+ if (r < 0)
+ return r;
+
+ log_struct(LOG_INFO,
+ MESSAGE_ID(SD_MESSAGE_SLEEP_STOP),
+ "MESSAGE=System resumed.",
+ note,
+ NULL);
+
+ arguments[1] = (char*) "post";
+ execute_directory(SYSTEM_SLEEP_PATH, NULL, arguments);
+
+ return r;
+}
+
+static int help(void) {
+ printf("%s COMMAND\n\n"
+ "Suspend the system, hibernate the system, or both.\n\n"
+ "Commands:\n"
+ " -h --help Show this help and exit\n"
+ " --version Print version string and exit\n"
+ " suspend Suspend the system\n"
+ " hibernate Hibernate the system\n"
+ " hybrid-sleep Both hibernate and suspend the system\n"
+ , program_invocation_short_name
+ );
+
+ return 0;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+ enum {
+ ARG_VERSION = 0x100,
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "version", no_argument, NULL, ARG_VERSION },
+ { NULL, 0, NULL, 0 }
+ };
+
+ int c;
+
+ assert(argc >= 0);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "+h", options, NULL)) >= 0)
+ switch(c) {
+ case 'h':
+ help();
+ return 0 /* done */;
+
+ case ARG_VERSION:
+ puts(PACKAGE_STRING);
+ puts(SYSTEMD_FEATURES);
+ return 0 /* done */;
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ log_error("Unknown option code %c", c);
+ return -EINVAL;
+ }
+
+ if (argc - optind != 1) {
+ log_error("Usage: %s COMMAND",
+ program_invocation_short_name);
+ return -EINVAL;
+ }
+
+ arg_verb = argv[optind];
+
+ if (!streq(arg_verb, "suspend") &&
+ !streq(arg_verb, "hibernate") &&
+ !streq(arg_verb, "hybrid-sleep")) {
+ log_error("Unknown command '%s'.", arg_verb);
+ return -EINVAL;
+ }
+
+ return 1 /* work to do */;
+}
+
+int main(int argc, char *argv[]) {
+ _cleanup_strv_free_ char **modes = NULL, **states = NULL;
+ int r;
+
+ log_set_target(LOG_TARGET_AUTO);
+ log_parse_environment();
+ log_open();
+
+ r = parse_argv(argc, argv);
+ if (r <= 0)
+ goto finish;
+
+ r = parse_sleep_config(arg_verb, &modes, &states);
+ if (r < 0)
+ goto finish;
+
+ r = execute(modes, states);
+
+finish:
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/src/stdio-bridge/stdio-bridge.c b/src/stdio-bridge/stdio-bridge.c
new file mode 100644
index 0000000000..a5bdb03416
--- /dev/null
+++ b/src/stdio-bridge/stdio-bridge.c
@@ -0,0 +1,231 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <sys/types.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <string.h>
+#include <errno.h>
+#include <sys/poll.h>
+#include <stddef.h>
+
+#include "log.h"
+#include "util.h"
+#include "socket-util.h"
+#include "sd-daemon.h"
+#include "sd-bus.h"
+#include "bus-internal.h"
+#include "bus-message.h"
+
+int main(int argc, char *argv[]) {
+ _cleanup_bus_unref_ sd_bus *a = NULL, *b = NULL;
+ sd_id128_t server_id;
+ bool is_unix;
+ int r;
+
+ if (argc > 1) {
+ log_error("This program takes no argument.");
+ return EXIT_FAILURE;
+ }
+
+ log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
+ log_parse_environment();
+ log_open();
+
+ is_unix =
+ sd_is_socket(STDIN_FILENO, AF_UNIX, 0, 0) > 0 &&
+ sd_is_socket(STDOUT_FILENO, AF_UNIX, 0, 0) > 0;
+
+ r = sd_bus_new(&a);
+ if (r < 0) {
+ log_error("Failed to allocate bus: %s", strerror(-r));
+ goto finish;
+ }
+
+ r = sd_bus_set_address(a, "unix:path=/run/dbus/system_bus_socket");
+ if (r < 0) {
+ log_error("Failed to set address to connect to: %s", strerror(-r));
+ goto finish;
+ }
+
+ r = sd_bus_set_negotiate_fds(a, is_unix);
+ if (r < 0) {
+ log_error("Failed to set FD negotiation: %s", strerror(-r));
+ goto finish;
+ }
+
+ r = sd_bus_start(a);
+ if (r < 0) {
+ log_error("Failed to start bus client: %s", strerror(-r));
+ goto finish;
+ }
+
+ r = sd_bus_get_server_id(a, &server_id);
+ if (r < 0) {
+ log_error("Failed to get server ID: %s", strerror(-r));
+ goto finish;
+ }
+
+ r = sd_bus_new(&b);
+ if (r < 0) {
+ log_error("Failed to allocate bus: %s", strerror(-r));
+ goto finish;
+ }
+
+ r = sd_bus_set_fd(b, STDIN_FILENO, STDOUT_FILENO);
+ if (r < 0) {
+ log_error("Failed to set fds: %s", strerror(-r));
+ goto finish;
+ }
+
+ r = sd_bus_set_server(b, 1, server_id);
+ if (r < 0) {
+ log_error("Failed to set server mode: %s", strerror(-r));
+ goto finish;
+ }
+
+ r = sd_bus_set_negotiate_fds(b, is_unix);
+ if (r < 0) {
+ log_error("Failed to set FD negotiation: %s", strerror(-r));
+ goto finish;
+ }
+
+ r = sd_bus_set_anonymous(b, true);
+ if (r < 0) {
+ log_error("Failed to set anonymous authentication: %s", strerror(-r));
+ goto finish;
+ }
+
+ r = sd_bus_start(b);
+ if (r < 0) {
+ log_error("Failed to start bus client: %s", strerror(-r));
+ goto finish;
+ }
+
+ for (;;) {
+ _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
+ int events_a, events_b, fd;
+ uint64_t timeout_a, timeout_b, t;
+ struct timespec _ts, *ts;
+
+ r = sd_bus_process(a, &m);
+ if (r < 0) {
+ log_error("Failed to process bus: %s", strerror(-r));
+ goto finish;
+ }
+
+ if (m) {
+ r = sd_bus_send(b, m, NULL);
+ if (r < 0) {
+ log_error("Failed to send message: %s", strerror(-r));
+ goto finish;
+ }
+ }
+
+ if (r > 0)
+ continue;
+
+ r = sd_bus_process(b, &m);
+ if (r < 0) {
+ log_error("Failed to process bus: %s", strerror(-r));
+ goto finish;
+ }
+
+ if (m) {
+ r = sd_bus_send(a, m, NULL);
+ if (r < 0) {
+ log_error("Failed to send message: %s", strerror(-r));
+ goto finish;
+ }
+ }
+
+ if (r > 0)
+ continue;
+
+ fd = sd_bus_get_fd(a);
+ if (fd < 0) {
+ log_error("Failed to get fd: %s", strerror(-r));
+ goto finish;
+ }
+
+ events_a = sd_bus_get_events(a);
+ if (events_a < 0) {
+ log_error("Failed to get events mask: %s", strerror(-r));
+ goto finish;
+ }
+
+ r = sd_bus_get_timeout(a, &timeout_a);
+ if (r < 0) {
+ log_error("Failed to get timeout: %s", strerror(-r));
+ goto finish;
+ }
+
+ events_b = sd_bus_get_events(b);
+ if (events_b < 0) {
+ log_error("Failed to get events mask: %s", strerror(-r));
+ goto finish;
+ }
+
+ r = sd_bus_get_timeout(b, &timeout_b);
+ if (r < 0) {
+ log_error("Failed to get timeout: %s", strerror(-r));
+ goto finish;
+ }
+
+ t = timeout_a;
+ if (t == (uint64_t) -1 || (timeout_b != (uint64_t) -1 && timeout_b < timeout_a))
+ t = timeout_b;
+
+ if (t == (uint64_t) -1)
+ ts = NULL;
+ else {
+ usec_t nw;
+
+ nw = now(CLOCK_MONOTONIC);
+ if (t > nw)
+ t -= nw;
+ else
+ t = 0;
+
+ ts = timespec_store(&_ts, t);
+ }
+
+ {
+ struct pollfd p[3] = {
+ {.fd = fd, .events = events_a, },
+ {.fd = STDIN_FILENO, .events = events_b & POLLIN, },
+ {.fd = STDOUT_FILENO, .events = events_b & POLLOUT, }};
+
+ r = ppoll(p, ELEMENTSOF(p), ts, NULL);
+ }
+ if (r < 0) {
+ log_error("ppoll() failed: %m");
+ goto finish;
+ }
+ }
+
+ r = 0;
+
+finish:
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/src/sysctl/sysctl.c b/src/sysctl/sysctl.c
new file mode 100644
index 0000000000..db18dd9f6e
--- /dev/null
+++ b/src/sysctl/sysctl.c
@@ -0,0 +1,325 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdlib.h>
+#include <stdbool.h>
+#include <errno.h>
+#include <string.h>
+#include <stdio.h>
+#include <limits.h>
+#include <getopt.h>
+
+#include "log.h"
+#include "strv.h"
+#include "util.h"
+#include "strv.h"
+#include "hashmap.h"
+#include "path-util.h"
+#include "conf-files.h"
+#include "fileio.h"
+
+static char **arg_prefixes = NULL;
+
+static const char conf_file_dirs[] =
+ "/etc/sysctl.d\0"
+ "/run/sysctl.d\0"
+ "/usr/local/lib/sysctl.d\0"
+ "/usr/lib/sysctl.d\0"
+#ifdef HAVE_SPLIT_USR
+ "/lib/sysctl.d\0"
+#endif
+ ;
+
+static char *normalize_sysctl(char *s) {
+ char *n;
+
+ for (n = s; *n; n++)
+ if (*n == '.')
+ *n = '/';
+
+ return s;
+}
+
+static int apply_sysctl(const char *property, const char *value) {
+ _cleanup_free_ char *p = NULL;
+ char *n;
+ int r = 0, k;
+
+ log_debug("Setting '%s' to '%s'", property, value);
+
+ p = new(char, sizeof("/proc/sys/") + strlen(property));
+ if (!p)
+ return log_oom();
+
+ n = stpcpy(p, "/proc/sys/");
+ strcpy(n, property);
+
+ if (!strv_isempty(arg_prefixes)) {
+ char **i;
+ bool good = false;
+
+ STRV_FOREACH(i, arg_prefixes)
+ if (path_startswith(p, *i)) {
+ good = true;
+ break;
+ }
+
+ if (!good) {
+ log_debug("Skipping %s", p);
+ return 0;
+ }
+ }
+
+ k = write_string_file(p, value);
+ if (k < 0) {
+ log_full(k == -ENOENT ? LOG_DEBUG : LOG_WARNING,
+ "Failed to write '%s' to '%s': %s", value, p, strerror(-k));
+
+ if (k != -ENOENT && r == 0)
+ r = k;
+ }
+
+ return r;
+}
+
+static int apply_all(Hashmap *sysctl_options) {
+ int r = 0;
+ char *property, *value;
+ Iterator i;
+
+ assert(sysctl_options);
+
+ HASHMAP_FOREACH_KEY(value, property, sysctl_options, i) {
+ int k;
+
+ k = apply_sysctl(property, value);
+ if (k < 0 && r == 0)
+ r = k;
+ }
+ return r;
+}
+
+static int parse_file(Hashmap *sysctl_options, const char *path, bool ignore_enoent) {
+ _cleanup_fclose_ FILE *f = NULL;
+ int r;
+
+ assert(path);
+
+ r = search_and_fopen_nulstr(path, "re", conf_file_dirs, &f);
+ if (r < 0) {
+ if (ignore_enoent && r == -ENOENT)
+ return 0;
+
+ log_error("Failed to open file '%s', ignoring: %s", path, strerror(-r));
+ return r;
+ }
+
+ log_debug("parse: %s\n", path);
+ while (!feof(f)) {
+ char l[LINE_MAX], *p, *value, *new_value, *property, *existing;
+ int k;
+
+ if (!fgets(l, sizeof(l), f)) {
+ if (feof(f))
+ break;
+
+ log_error("Failed to read file '%s', ignoring: %m", path);
+ return -errno;
+ }
+
+ p = strstrip(l);
+ if (!*p)
+ continue;
+
+ if (strchr(COMMENTS "\n", *p))
+ continue;
+
+ value = strchr(p, '=');
+ if (!value) {
+ log_error("Line is not an assignment in file '%s': %s", path, value);
+
+ if (r == 0)
+ r = -EINVAL;
+ continue;
+ }
+
+ *value = 0;
+ value++;
+
+ p = normalize_sysctl(strstrip(p));
+ value = strstrip(value);
+
+ existing = hashmap_get(sysctl_options, p);
+ if (existing) {
+ if (!streq(value, existing))
+ log_warning("Duplicate assignment of %s in file '%s', ignoring.",
+ p, path);
+
+ continue;
+ }
+
+ property = strdup(p);
+ if (!property)
+ return log_oom();
+
+ new_value = strdup(value);
+ if (!new_value) {
+ free(property);
+ return log_oom();
+ }
+
+ k = hashmap_put(sysctl_options, property, new_value);
+ if (k < 0) {
+ log_error("Failed to add sysctl variable %s to hashmap: %s", property, strerror(-r));
+ free(property);
+ free(new_value);
+ return k;
+ }
+ }
+
+ return r;
+}
+
+static int help(void) {
+
+ printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
+ "Applies kernel sysctl settings.\n\n"
+ " -h --help Show this help\n"
+ " --prefix=PATH Only apply rules that apply to paths with the specified prefix\n",
+ program_invocation_short_name);
+
+ return 0;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+
+ enum {
+ ARG_PREFIX
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "prefix", required_argument, NULL, ARG_PREFIX },
+ { NULL, 0, NULL, 0 }
+ };
+
+ int c;
+
+ assert(argc >= 0);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
+
+ switch (c) {
+
+ case 'h':
+ help();
+ return 0;
+
+ case ARG_PREFIX: {
+ char *p;
+ char **l;
+
+ for (p = optarg; *p; p++)
+ if (*p == '.')
+ *p = '/';
+
+ l = strv_append(arg_prefixes, optarg);
+ if (!l)
+ return log_oom();
+
+ strv_free(arg_prefixes);
+ arg_prefixes = l;
+
+ break;
+ }
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ log_error("Unknown option code %c", c);
+ return -EINVAL;
+ }
+ }
+
+ return 1;
+}
+
+int main(int argc, char *argv[]) {
+ int r = 0, k;
+ Hashmap *sysctl_options;
+
+ r = parse_argv(argc, argv);
+ if (r <= 0)
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+
+ log_set_target(LOG_TARGET_AUTO);
+ log_parse_environment();
+ log_open();
+
+ umask(0022);
+
+ sysctl_options = hashmap_new(string_hash_func, string_compare_func);
+ if (!sysctl_options) {
+ r = log_oom();
+ goto finish;
+ }
+
+ r = 0;
+
+ if (argc > optind) {
+ int i;
+
+ for (i = optind; i < argc; i++) {
+ k = parse_file(sysctl_options, argv[i], false);
+ if (k < 0 && r == 0)
+ r = k;
+ }
+ } else {
+ _cleanup_strv_free_ char **files = NULL;
+ char **f;
+
+ r = conf_files_list_nulstr(&files, ".conf", NULL, conf_file_dirs);
+ if (r < 0) {
+ log_error("Failed to enumerate sysctl.d files: %s", strerror(-r));
+ goto finish;
+ }
+
+ r = parse_file(sysctl_options, "/etc/sysctl.conf", true);
+
+ STRV_FOREACH(f, files) {
+ k = parse_file(sysctl_options, *f, true);
+ if (k < 0 && r == 0)
+ r = k;
+ }
+ }
+
+ k = apply_all(sysctl_options);
+ if (k < 0 && r == 0)
+ r = k;
+
+finish:
+ hashmap_free_free_free(sysctl_options);
+ strv_free(arg_prefixes);
+
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/src/system-update-generator/system-update-generator.c b/src/system-update-generator/system-update-generator.c
new file mode 100644
index 0000000000..13b8a0c426
--- /dev/null
+++ b/src/system-update-generator/system-update-generator.c
@@ -0,0 +1,81 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <unistd.h>
+
+#include "log.h"
+#include "util.h"
+#include "unit-name.h"
+#include "path-util.h"
+
+/*
+ * Implements the logic described in
+ * http://freedesktop.org/wiki/Software/systemd/SystemUpdates
+ */
+
+static const char *arg_dest = "/tmp";
+
+static int generate_symlink(void) {
+ struct stat st;
+ char _cleanup_free_ *p = NULL;
+
+ if (lstat("/system-update", &st) < 0) {
+ if (errno == ENOENT)
+ return 0;
+
+ log_error("Failed to check for system update: %m");
+ return -EINVAL;
+ }
+
+ p = strappend(arg_dest, "/default.target");
+ if (!p)
+ return log_oom();
+
+ if (symlink(SYSTEM_DATA_UNIT_PATH "/system-update.target", p) < 0) {
+ log_error("Failed to create symlink %s: %m", p);
+ return -errno;
+ }
+
+ return 0;
+}
+
+int main(int argc, char *argv[]) {
+ int r;
+
+ if (argc > 1 && argc != 4) {
+ log_error("This program takes three or no arguments.");
+ return EXIT_FAILURE;
+ }
+
+ if (argc > 1)
+ arg_dest = argv[2];
+
+ log_set_target(LOG_TARGET_SAFE);
+ log_parse_environment();
+ log_open();
+
+ umask(0022);
+
+ r = generate_symlink();
+
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/src/systemctl/systemctl.c b/src/systemctl/systemctl.c
new file mode 100644
index 0000000000..3cca861cf6
--- /dev/null
+++ b/src/systemctl/systemctl.c
@@ -0,0 +1,6063 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/reboot.h>
+#include <stdio.h>
+#include <getopt.h>
+#include <locale.h>
+#include <stdbool.h>
+#include <string.h>
+#include <errno.h>
+#include <sys/ioctl.h>
+#include <termios.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <stddef.h>
+#include <sys/prctl.h>
+#include <dbus/dbus.h>
+
+#include <systemd/sd-daemon.h>
+#include <systemd/sd-shutdown.h>
+#include <systemd/sd-login.h>
+
+#include "log.h"
+#include "util.h"
+#include "macro.h"
+#include "set.h"
+#include "utmp-wtmp.h"
+#include "special.h"
+#include "initreq.h"
+#include "path-util.h"
+#include "strv.h"
+#include "dbus-common.h"
+#include "cgroup-show.h"
+#include "cgroup-util.h"
+#include "list.h"
+#include "path-lookup.h"
+#include "conf-parser.h"
+#include "exit-status.h"
+#include "bus-errors.h"
+#include "build.h"
+#include "unit-name.h"
+#include "pager.h"
+#include "spawn-ask-password-agent.h"
+#include "spawn-polkit-agent.h"
+#include "install.h"
+#include "logs-show.h"
+#include "path-util.h"
+#include "socket-util.h"
+#include "fileio.h"
+
+static char **arg_types = NULL;
+static char **arg_load_states = NULL;
+static char **arg_properties = NULL;
+static bool arg_all = false;
+static enum dependency {
+ DEPENDENCY_FORWARD,
+ DEPENDENCY_REVERSE,
+ DEPENDENCY_AFTER,
+ DEPENDENCY_BEFORE,
+} arg_dependency = DEPENDENCY_FORWARD;
+static const char *arg_job_mode = "replace";
+static UnitFileScope arg_scope = UNIT_FILE_SYSTEM;
+static bool arg_no_block = false;
+static bool arg_no_legend = false;
+static bool arg_no_pager = false;
+static bool arg_no_wtmp = false;
+static bool arg_no_wall = false;
+static bool arg_no_reload = false;
+static bool arg_show_types = false;
+static bool arg_ignore_inhibitors = false;
+static bool arg_dry = false;
+static bool arg_quiet = false;
+static bool arg_full = false;
+static int arg_force = 0;
+static bool arg_ask_password = true;
+static bool arg_failed = false;
+static bool arg_runtime = false;
+static char **arg_wall = NULL;
+static const char *arg_kill_who = NULL;
+static int arg_signal = SIGTERM;
+static const char *arg_root = NULL;
+static usec_t arg_when = 0;
+static enum action {
+ ACTION_INVALID,
+ ACTION_SYSTEMCTL,
+ ACTION_HALT,
+ ACTION_POWEROFF,
+ ACTION_REBOOT,
+ ACTION_KEXEC,
+ ACTION_EXIT,
+ ACTION_SUSPEND,
+ ACTION_HIBERNATE,
+ ACTION_HYBRID_SLEEP,
+ ACTION_RUNLEVEL2,
+ ACTION_RUNLEVEL3,
+ ACTION_RUNLEVEL4,
+ ACTION_RUNLEVEL5,
+ ACTION_RESCUE,
+ ACTION_EMERGENCY,
+ ACTION_DEFAULT,
+ ACTION_RELOAD,
+ ACTION_REEXEC,
+ ACTION_RUNLEVEL,
+ ACTION_CANCEL_SHUTDOWN,
+ _ACTION_MAX
+} arg_action = ACTION_SYSTEMCTL;
+static enum transport {
+ TRANSPORT_NORMAL,
+ TRANSPORT_SSH,
+ TRANSPORT_POLKIT
+} arg_transport = TRANSPORT_NORMAL;
+static const char *arg_host = NULL;
+static unsigned arg_lines = 10;
+static OutputMode arg_output = OUTPUT_SHORT;
+static bool arg_plain = false;
+
+static bool private_bus = false;
+
+static int daemon_reload(DBusConnection *bus, char **args);
+static void halt_now(enum action a);
+
+static void pager_open_if_enabled(void) {
+
+ if (arg_no_pager)
+ return;
+
+ pager_open(false);
+}
+
+static void ask_password_agent_open_if_enabled(void) {
+
+ /* Open the password agent as a child process if necessary */
+
+ if (!arg_ask_password)
+ return;
+
+ if (arg_scope != UNIT_FILE_SYSTEM)
+ return;
+
+ ask_password_agent_open();
+}
+
+#ifdef HAVE_LOGIND
+static void polkit_agent_open_if_enabled(void) {
+
+ /* Open the polkit agent as a child process if necessary */
+
+ if (!arg_ask_password)
+ return;
+
+ if (arg_scope != UNIT_FILE_SYSTEM)
+ return;
+
+ polkit_agent_open();
+}
+#endif
+
+static const char *ansi_highlight(bool b) {
+
+ if (!on_tty())
+ return "";
+
+ return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
+}
+
+static const char *ansi_highlight_red(bool b) {
+
+ if (!on_tty())
+ return "";
+
+ return b ? ANSI_HIGHLIGHT_RED_ON : ANSI_HIGHLIGHT_OFF;
+}
+
+static const char *ansi_highlight_green(bool b) {
+
+ if (!on_tty())
+ return "";
+
+ return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
+}
+
+static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
+ assert(error);
+
+ if (!dbus_error_is_set(error))
+ return r;
+
+ if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
+ dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
+ dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
+ dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
+ return EXIT_NOPERMISSION;
+
+ if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
+ return EXIT_NOTINSTALLED;
+
+ if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
+ dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
+ return EXIT_NOTIMPLEMENTED;
+
+ if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
+ return EXIT_NOTCONFIGURED;
+
+ if (r != 0)
+ return r;
+
+ return EXIT_FAILURE;
+}
+
+static void warn_wall(enum action a) {
+ static const char *table[_ACTION_MAX] = {
+ [ACTION_HALT] = "The system is going down for system halt NOW!",
+ [ACTION_REBOOT] = "The system is going down for reboot NOW!",
+ [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
+ [ACTION_KEXEC] = "The system is going down for kexec reboot NOW!",
+ [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
+ [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!",
+ [ACTION_CANCEL_SHUTDOWN] = "The system shutdown has been cancelled NOW!"
+ };
+
+ if (arg_no_wall)
+ return;
+
+ if (arg_wall) {
+ _cleanup_free_ char *p;
+
+ p = strv_join(arg_wall, " ");
+ if (!p) {
+ log_oom();
+ return;
+ }
+
+ if (*p) {
+ utmp_wall(p, NULL);
+ return;
+ }
+ }
+
+ if (!table[a])
+ return;
+
+ utmp_wall(table[a], NULL);
+}
+
+static bool avoid_bus(void) {
+
+ if (running_in_chroot() > 0)
+ return true;
+
+ if (sd_booted() <= 0)
+ return true;
+
+ if (!isempty(arg_root))
+ return true;
+
+ if (arg_scope == UNIT_FILE_GLOBAL)
+ return true;
+
+ return false;
+}
+
+static int compare_unit_info(const void *a, const void *b) {
+ const char *d1, *d2;
+ const struct unit_info *u = a, *v = b;
+
+ d1 = strrchr(u->id, '.');
+ d2 = strrchr(v->id, '.');
+
+ if (d1 && d2) {
+ int r;
+
+ r = strcasecmp(d1, d2);
+ if (r != 0)
+ return r;
+ }
+
+ return strcasecmp(u->id, v->id);
+}
+
+static bool output_show_unit(const struct unit_info *u) {
+ const char *dot;
+
+ if (arg_failed)
+ return streq(u->active_state, "failed");
+
+ return (!arg_types || ((dot = strrchr(u->id, '.')) &&
+ strv_find(arg_types, dot+1))) &&
+ (!arg_load_states || strv_find(arg_load_states, u->load_state)) &&
+ (arg_all || !(streq(u->active_state, "inactive")
+ || u->following[0]) || u->job_id > 0);
+}
+
+static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
+ unsigned id_len, max_id_len, active_len, sub_len, job_len, desc_len, n_shown = 0;
+ const struct unit_info *u;
+ int job_count = 0;
+
+ max_id_len = sizeof("UNIT")-1;
+ active_len = sizeof("ACTIVE")-1;
+ sub_len = sizeof("SUB")-1;
+ job_len = sizeof("JOB")-1;
+ desc_len = 0;
+
+ for (u = unit_infos; u < unit_infos + c; u++) {
+ if (!output_show_unit(u))
+ continue;
+
+ max_id_len = MAX(max_id_len, strlen(u->id));
+ active_len = MAX(active_len, strlen(u->active_state));
+ sub_len = MAX(sub_len, strlen(u->sub_state));
+ if (u->job_id != 0) {
+ job_len = MAX(job_len, strlen(u->job_type));
+ job_count++;
+ }
+ }
+
+ if (!arg_full) {
+ unsigned basic_len;
+ id_len = MIN(max_id_len, 25u);
+ basic_len = 5 + id_len + 5 + active_len + sub_len;
+ if (job_count)
+ basic_len += job_len + 1;
+ if (basic_len < (unsigned) columns()) {
+ unsigned extra_len, incr;
+ extra_len = columns() - basic_len;
+ /* Either UNIT already got 25, or is fully satisfied.
+ * Grant up to 25 to DESC now. */
+ incr = MIN(extra_len, 25u);
+ desc_len += incr;
+ extra_len -= incr;
+ /* split the remaining space between UNIT and DESC,
+ * but do not give UNIT more than it needs. */
+ if (extra_len > 0) {
+ incr = MIN(extra_len / 2, max_id_len - id_len);
+ id_len += incr;
+ desc_len += extra_len - incr;
+ }
+ }
+ } else
+ id_len = max_id_len;
+
+ for (u = unit_infos; u < unit_infos + c; u++) {
+ _cleanup_free_ char *e = NULL;
+ const char *on_loaded, *off_loaded, *on = "";
+ const char *on_active, *off_active, *off = "";
+
+ if (!output_show_unit(u))
+ continue;
+
+ if (!n_shown && !arg_no_legend) {
+ printf("%-*s %-6s %-*s %-*s ", id_len, "UNIT", "LOAD",
+ active_len, "ACTIVE", sub_len, "SUB");
+ if (job_count)
+ printf("%-*s ", job_len, "JOB");
+ if (!arg_full && arg_no_pager)
+ printf("%.*s\n", desc_len, "DESCRIPTION");
+ else
+ printf("%s\n", "DESCRIPTION");
+ }
+
+ n_shown++;
+
+ if (streq(u->load_state, "error")) {
+ on_loaded = on = ansi_highlight_red(true);
+ off_loaded = off = ansi_highlight_red(false);
+ } else
+ on_loaded = off_loaded = "";
+
+ if (streq(u->active_state, "failed")) {
+ on_active = on = ansi_highlight_red(true);
+ off_active = off = ansi_highlight_red(false);
+ } else
+ on_active = off_active = "";
+
+ e = arg_full ? NULL : ellipsize(u->id, id_len, 33);
+
+ printf("%s%-*s%s %s%-6s%s %s%-*s %-*s%s %-*s",
+ on, id_len, e ? e : u->id, off,
+ on_loaded, u->load_state, off_loaded,
+ on_active, active_len, u->active_state,
+ sub_len, u->sub_state, off_active,
+ job_count ? job_len + 1 : 0, u->job_id ? u->job_type : "");
+ if (!arg_full && arg_no_pager)
+ printf("%.*s\n", desc_len, u->description);
+ else
+ printf("%s\n", u->description);
+ }
+
+ if (!arg_no_legend) {
+ const char *on, *off;
+
+ if (n_shown) {
+ printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
+ "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
+ "SUB = The low-level unit activation state, values depend on unit type.\n");
+ if (job_count)
+ printf("JOB = Pending job for the unit.\n");
+ puts("");
+ on = ansi_highlight(true);
+ off = ansi_highlight(false);
+ } else {
+ on = ansi_highlight_red(true);
+ off = ansi_highlight_red(false);
+ }
+
+ if (arg_all)
+ printf("%s%u loaded units listed.%s\n"
+ "To show all installed unit files use 'systemctl list-unit-files'.\n",
+ on, n_shown, off);
+ else
+ printf("%s%u loaded units listed.%s Pass --all to see loaded but inactive units, too.\n"
+ "To show all installed unit files use 'systemctl list-unit-files'.\n",
+ on, n_shown, off);
+ }
+}
+
+static int get_unit_list(DBusConnection *bus, DBusMessage **reply,
+ struct unit_info **unit_infos, unsigned *c) {
+ DBusMessageIter iter, sub;
+ size_t size = 0;
+ int r;
+
+ assert(bus);
+ assert(unit_infos);
+ assert(c);
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "ListUnits",
+ reply,
+ NULL,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+
+ if (!dbus_message_iter_init(*reply, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
+ dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_recurse(&iter, &sub);
+
+ while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ if (!GREEDY_REALLOC(*unit_infos, size, *c + 1))
+ return log_oom();
+
+ bus_parse_unit_info(&sub, *unit_infos + *c);
+ (*c)++;
+
+ dbus_message_iter_next(&sub);
+ }
+
+ return 0;
+}
+
+static int list_units(DBusConnection *bus, char **args) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ _cleanup_free_ struct unit_info *unit_infos = NULL;
+ unsigned c = 0;
+ int r;
+
+ pager_open_if_enabled();
+
+ r = get_unit_list(bus, &reply, &unit_infos, &c);
+ if (r < 0)
+ return r;
+
+ qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
+
+ output_units_list(unit_infos, c);
+
+ return 0;
+}
+
+static int get_triggered_units(DBusConnection *bus, const char* unit_path,
+ char*** triggered)
+{
+ const char *interface = "org.freedesktop.systemd1.Unit",
+ *triggers_property = "Triggers";
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ DBusMessageIter iter, sub;
+ int r;
+
+ r = bus_method_call_with_reply(bus,
+ "org.freedesktop.systemd1",
+ unit_path,
+ "org.freedesktop.DBus.Properties",
+ "Get",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &interface,
+ DBUS_TYPE_STRING, &triggers_property,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+
+ if (!dbus_message_iter_init(reply, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
+ log_error("Failed to parse reply.");
+ return -EBADMSG;
+ }
+
+ dbus_message_iter_recurse(&iter, &sub);
+ dbus_message_iter_recurse(&sub, &iter);
+ sub = iter;
+
+ while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ const char *unit;
+
+ if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
+ log_error("Failed to parse reply.");
+ return -EBADMSG;
+ }
+
+ dbus_message_iter_get_basic(&sub, &unit);
+ r = strv_extend(triggered, unit);
+ if (r < 0)
+ return r;
+
+ dbus_message_iter_next(&sub);
+ }
+
+ return 0;
+}
+
+static int get_listening(DBusConnection *bus, const char* unit_path,
+ char*** listen, unsigned *c)
+{
+ const char *interface = "org.freedesktop.systemd1.Socket",
+ *listen_property = "Listen";
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ DBusMessageIter iter, sub;
+ int r;
+
+ r = bus_method_call_with_reply(bus,
+ "org.freedesktop.systemd1",
+ unit_path,
+ "org.freedesktop.DBus.Properties",
+ "Get",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &interface,
+ DBUS_TYPE_STRING, &listen_property,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+
+ if (!dbus_message_iter_init(reply, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
+ log_error("Failed to parse reply.");
+ return -EBADMSG;
+ }
+
+ dbus_message_iter_recurse(&iter, &sub);
+ dbus_message_iter_recurse(&sub, &iter);
+ sub = iter;
+
+ while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ DBusMessageIter sub2;
+ const char *type, *path;
+
+ if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
+ log_error("Failed to parse reply.");
+ return -EBADMSG;
+ }
+
+ dbus_message_iter_recurse(&sub, &sub2);
+
+ if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0) {
+ r = strv_extend(listen, type);
+ if (r < 0)
+ return r;
+
+ r = strv_extend(listen, path);
+ if (r < 0)
+ return r;
+
+ (*c) ++;
+ }
+
+ dbus_message_iter_next(&sub);
+ }
+
+ return 0;
+}
+
+struct socket_info {
+ const char* id;
+
+ char* type;
+ char* path;
+
+ /* Note: triggered is a list here, although it almost certainly
+ * will always be one unit. Nevertheless, dbus API allows for multiple
+ * values, so let's follow that.*/
+ char** triggered;
+
+ /* The strv above is shared. free is set only in the first one. */
+ bool own_triggered;
+};
+
+static int socket_info_compare(struct socket_info *a, struct socket_info *b) {
+ int o = strcmp(a->path, b->path);
+ if (o == 0)
+ o = strcmp(a->type, b->type);
+ return o;
+}
+
+static int output_sockets_list(struct socket_info *socket_infos, unsigned cs) {
+ struct socket_info *s;
+ unsigned pathlen = sizeof("LISTEN") - 1,
+ typelen = (sizeof("TYPE") - 1) * arg_show_types,
+ socklen = sizeof("UNIT") - 1,
+ servlen = sizeof("ACTIVATES") - 1;
+ const char *on, *off;
+
+ for (s = socket_infos; s < socket_infos + cs; s++) {
+ char **a;
+ unsigned tmp = 0;
+
+ socklen = MAX(socklen, strlen(s->id));
+ if (arg_show_types)
+ typelen = MAX(typelen, strlen(s->type));
+ pathlen = MAX(pathlen, strlen(s->path));
+
+ STRV_FOREACH(a, s->triggered)
+ tmp += strlen(*a) + 2*(a != s->triggered);
+ servlen = MAX(servlen, tmp);
+ }
+
+ if (cs) {
+ printf("%-*s %-*.*s%-*s %s\n",
+ pathlen, "LISTEN",
+ typelen + arg_show_types, typelen + arg_show_types, "TYPE ",
+ socklen, "UNIT",
+ "ACTIVATES");
+
+ for (s = socket_infos; s < socket_infos + cs; s++) {
+ char **a;
+
+ if (arg_show_types)
+ printf("%-*s %-*s %-*s",
+ pathlen, s->path, typelen, s->type, socklen, s->id);
+ else
+ printf("%-*s %-*s",
+ pathlen, s->path, socklen, s->id);
+ STRV_FOREACH(a, s->triggered)
+ printf("%s %s",
+ a == s->triggered ? "" : ",", *a);
+ printf("\n");
+ }
+
+ on = ansi_highlight(true);
+ off = ansi_highlight(false);
+ printf("\n");
+ } else {
+ on = ansi_highlight_red(true);
+ off = ansi_highlight_red(false);
+ }
+
+ printf("%s%u sockets listed.%s\n", on, cs, off);
+ if (!arg_all)
+ printf("Pass --all to see loaded but inactive sockets, too.\n");
+
+ return 0;
+}
+
+static int list_sockets(DBusConnection *bus, char **args) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ _cleanup_free_ struct unit_info *unit_infos = NULL;
+ struct socket_info *socket_infos = NULL;
+ const struct unit_info *u;
+ struct socket_info *s;
+ unsigned cu = 0, cs = 0;
+ size_t size = 0;
+ int r;
+
+ pager_open_if_enabled();
+
+ r = get_unit_list(bus, &reply, &unit_infos, &cu);
+ if (r < 0)
+ return r;
+
+ for (u = unit_infos; u < unit_infos + cu; u++) {
+ const char *dot;
+ _cleanup_strv_free_ char **listen = NULL, **triggered = NULL;
+ unsigned c = 0, i;
+
+ if (!output_show_unit(u))
+ continue;
+
+ if ((dot = strrchr(u->id, '.')) && !streq(dot+1, "socket"))
+ continue;
+
+ r = get_triggered_units(bus, u->unit_path, &triggered);
+ if (r < 0)
+ goto cleanup;
+
+ r = get_listening(bus, u->unit_path, &listen, &c);
+ if (r < 0)
+ goto cleanup;
+
+ if (!GREEDY_REALLOC(socket_infos, size, cs + c)) {
+ r = log_oom();
+ goto cleanup;
+ }
+
+ for (i = 0; i < c; i++)
+ socket_infos[cs + i] = (struct socket_info) {
+ .id = u->id,
+ .type = listen[i*2],
+ .path = listen[i*2 + 1],
+ .triggered = triggered,
+ .own_triggered = i==0,
+ };
+
+ /* from this point on we will cleanup those socket_infos */
+ cs += c;
+ free(listen);
+ listen = triggered = NULL; /* avoid cleanup */
+ }
+
+ qsort(socket_infos, cs, sizeof(struct socket_info),
+ (__compar_fn_t) socket_info_compare);
+
+ output_sockets_list(socket_infos, cs);
+
+ cleanup:
+ assert(cs == 0 || socket_infos);
+ for (s = socket_infos; s < socket_infos + cs; s++) {
+ free(s->type);
+ free(s->path);
+ if (s->own_triggered)
+ strv_free(s->triggered);
+ }
+ free(socket_infos);
+
+ return 0;
+}
+
+static int compare_unit_file_list(const void *a, const void *b) {
+ const char *d1, *d2;
+ const UnitFileList *u = a, *v = b;
+
+ d1 = strrchr(u->path, '.');
+ d2 = strrchr(v->path, '.');
+
+ if (d1 && d2) {
+ int r;
+
+ r = strcasecmp(d1, d2);
+ if (r != 0)
+ return r;
+ }
+
+ return strcasecmp(path_get_file_name(u->path), path_get_file_name(v->path));
+}
+
+static bool output_show_unit_file(const UnitFileList *u) {
+ const char *dot;
+
+ return !arg_types || ((dot = strrchr(u->path, '.')) && strv_find(arg_types, dot+1));
+}
+
+static void output_unit_file_list(const UnitFileList *units, unsigned c) {
+ unsigned max_id_len, id_cols, state_cols, n_shown = 0;
+ const UnitFileList *u;
+
+ max_id_len = sizeof("UNIT FILE")-1;
+ state_cols = sizeof("STATE")-1;
+ for (u = units; u < units + c; u++) {
+ if (!output_show_unit_file(u))
+ continue;
+
+ max_id_len = MAX(max_id_len, strlen(path_get_file_name(u->path)));
+ state_cols = MAX(state_cols, strlen(unit_file_state_to_string(u->state)));
+ }
+
+ if (!arg_full) {
+ unsigned basic_cols;
+ id_cols = MIN(max_id_len, 25u);
+ basic_cols = 1 + id_cols + state_cols;
+ if (basic_cols < (unsigned) columns())
+ id_cols += MIN(columns() - basic_cols, max_id_len - id_cols);
+ } else
+ id_cols = max_id_len;
+
+ if (!arg_no_legend)
+ printf("%-*s %-*s\n", id_cols, "UNIT FILE", state_cols, "STATE");
+
+ for (u = units; u < units + c; u++) {
+ _cleanup_free_ char *e = NULL;
+ const char *on, *off;
+ const char *id;
+
+ if (!output_show_unit_file(u))
+ continue;
+
+ n_shown++;
+
+ if (u->state == UNIT_FILE_MASKED ||
+ u->state == UNIT_FILE_MASKED_RUNTIME ||
+ u->state == UNIT_FILE_DISABLED ||
+ u->state == UNIT_FILE_INVALID) {
+ on = ansi_highlight_red(true);
+ off = ansi_highlight_red(false);
+ } else if (u->state == UNIT_FILE_ENABLED) {
+ on = ansi_highlight_green(true);
+ off = ansi_highlight_green(false);
+ } else
+ on = off = "";
+
+ id = path_get_file_name(u->path);
+
+ e = arg_full ? NULL : ellipsize(id, id_cols, 33);
+
+ printf("%-*s %s%-*s%s\n",
+ id_cols, e ? e : id,
+ on, state_cols, unit_file_state_to_string(u->state), off);
+ }
+
+ if (!arg_no_legend)
+ printf("\n%u unit files listed.\n", n_shown);
+}
+
+static int list_unit_files(DBusConnection *bus, char **args) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ _cleanup_free_ UnitFileList *units = NULL;
+ DBusMessageIter iter, sub, sub2;
+ unsigned c = 0, n_units = 0;
+ int r;
+
+ pager_open_if_enabled();
+
+ if (avoid_bus()) {
+ Hashmap *h;
+ UnitFileList *u;
+ Iterator i;
+
+ h = hashmap_new(string_hash_func, string_compare_func);
+ if (!h)
+ return log_oom();
+
+ r = unit_file_get_list(arg_scope, arg_root, h);
+ if (r < 0) {
+ unit_file_list_free(h);
+ log_error("Failed to get unit file list: %s", strerror(-r));
+ return r;
+ }
+
+ n_units = hashmap_size(h);
+ units = new(UnitFileList, n_units);
+ if (!units) {
+ unit_file_list_free(h);
+ return log_oom();
+ }
+
+ HASHMAP_FOREACH(u, h, i) {
+ memcpy(units + c++, u, sizeof(UnitFileList));
+ free(u);
+ }
+
+ hashmap_free(h);
+ } else {
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "ListUnitFiles",
+ &reply,
+ NULL,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+
+ if (!dbus_message_iter_init(reply, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
+ dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_recurse(&iter, &sub);
+
+ while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ UnitFileList *u;
+ const char *state;
+
+ assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT);
+
+ if (c >= n_units) {
+ UnitFileList *w;
+
+ n_units = MAX(2*c, 16u);
+ w = realloc(units, sizeof(struct UnitFileList) * n_units);
+ if (!w)
+ return log_oom();
+
+ units = w;
+ }
+
+ u = units + c;
+
+ dbus_message_iter_recurse(&sub, &sub2);
+
+ if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->path, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, false) < 0) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ u->state = unit_file_state_from_string(state);
+
+ dbus_message_iter_next(&sub);
+ c++;
+ }
+ }
+
+ if (c > 0) {
+ qsort(units, c, sizeof(UnitFileList), compare_unit_file_list);
+ output_unit_file_list(units, c);
+ }
+
+ return 0;
+}
+
+static int list_dependencies_print(const char *name, int level, unsigned int branches, bool last) {
+ int i;
+ _cleanup_free_ char *n = NULL;
+ size_t len = 0;
+ size_t max_len = MAX(columns(),20u);
+
+ if (!arg_plain) {
+ for (i = level - 1; i >= 0; i--) {
+ len += 2;
+ if(len > max_len - 3 && !arg_full) {
+ printf("%s...\n",max_len % 2 ? "" : " ");
+ return 0;
+ }
+ printf("%s", draw_special_char(branches & (1 << i) ? DRAW_TREE_VERT : DRAW_TREE_SPACE));
+ }
+ len += 2;
+ if(len > max_len - 3 && !arg_full) {
+ printf("%s...\n",max_len % 2 ? "" : " ");
+ return 0;
+ }
+ printf("%s", draw_special_char(last ? DRAW_TREE_RIGHT : DRAW_TREE_BRANCH));
+ }
+
+ if(arg_full){
+ printf("%s\n", name);
+ return 0;
+ }
+
+ n = ellipsize(name, max_len-len, 100);
+ if(!n)
+ return log_oom();
+
+ printf("%s\n", n);
+ return 0;
+}
+
+static int list_dependencies_get_dependencies(DBusConnection *bus, const char *name, char ***deps) {
+ static const char *dependencies[] = {
+ [DEPENDENCY_FORWARD] = "Requires\0"
+ "RequiresOverridable\0"
+ "Requisite\0"
+ "RequisiteOverridable\0"
+ "Wants\0",
+ [DEPENDENCY_REVERSE] = "RequiredBy\0"
+ "RequiredByOverridable\0"
+ "WantedBy\0"
+ "PartOf\0",
+ [DEPENDENCY_AFTER] = "After\0",
+ [DEPENDENCY_BEFORE] = "Before\0",
+ };
+
+ _cleanup_free_ char *path;
+ const char *interface = "org.freedesktop.systemd1.Unit";
+
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ DBusMessageIter iter, sub, sub2, sub3;
+
+ int r = 0;
+ char **ret = NULL;
+
+ assert(bus);
+ assert(name);
+ assert(deps);
+
+ path = unit_dbus_path_from_name(name);
+ if (path == NULL) {
+ r = -EINVAL;
+ goto finish;
+ }
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.systemd1",
+ path,
+ "org.freedesktop.DBus.Properties",
+ "GetAll",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &interface,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ goto finish;
+
+ if (!dbus_message_iter_init(reply, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
+ dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
+ log_error("Failed to parse reply.");
+ r = -EIO;
+ goto finish;
+ }
+
+ dbus_message_iter_recurse(&iter, &sub);
+
+ while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ const char *prop;
+
+ assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_DICT_ENTRY);
+ dbus_message_iter_recurse(&sub, &sub2);
+
+ if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
+ log_error("Failed to parse reply.");
+ r = -EIO;
+ goto finish;
+ }
+
+ if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
+ log_error("Failed to parse reply.");
+ r = -EIO;
+ goto finish;
+ }
+
+ dbus_message_iter_recurse(&sub2, &sub3);
+ dbus_message_iter_next(&sub);
+
+ assert(arg_dependency < ELEMENTSOF(dependencies));
+ if (!nulstr_contains(dependencies[arg_dependency], prop))
+ continue;
+
+ if (dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_ARRAY) {
+ if (dbus_message_iter_get_element_type(&sub3) == DBUS_TYPE_STRING) {
+ DBusMessageIter sub4;
+ dbus_message_iter_recurse(&sub3, &sub4);
+
+ while (dbus_message_iter_get_arg_type(&sub4) != DBUS_TYPE_INVALID) {
+ const char *s;
+
+ assert(dbus_message_iter_get_arg_type(&sub4) == DBUS_TYPE_STRING);
+ dbus_message_iter_get_basic(&sub4, &s);
+
+ r = strv_extend(&ret, s);
+ if (r < 0) {
+ log_oom();
+ goto finish;
+ }
+
+ dbus_message_iter_next(&sub4);
+ }
+ }
+ }
+ }
+finish:
+ if (r < 0)
+ strv_free(ret);
+ else
+ *deps = ret;
+ return r;
+}
+
+static int list_dependencies_compare(const void *_a, const void *_b) {
+ const char **a = (const char**) _a, **b = (const char**) _b;
+ if (unit_name_to_type(*a) == UNIT_TARGET && unit_name_to_type(*b) != UNIT_TARGET)
+ return 1;
+ if (unit_name_to_type(*a) != UNIT_TARGET && unit_name_to_type(*b) == UNIT_TARGET)
+ return -1;
+ return strcasecmp(*a, *b);
+}
+
+static int list_dependencies_one(DBusConnection *bus, const char *name, int level, char ***units, unsigned int branches) {
+ _cleanup_strv_free_ char **deps = NULL, **u;
+ char **c;
+ int r = 0;
+
+ u = strv_append(*units, name);
+ if (!u)
+ return log_oom();
+
+ r = list_dependencies_get_dependencies(bus, name, &deps);
+ if (r < 0)
+ return r;
+
+ qsort(deps, strv_length(deps), sizeof (char*), list_dependencies_compare);
+
+ STRV_FOREACH(c, deps) {
+ if (strv_contains(u, *c)) {
+ if (!arg_plain) {
+ r = list_dependencies_print("...", level + 1, (branches << 1) | (c[1] == NULL ? 0 : 1), 1);
+ if (r < 0)
+ return r;
+ }
+ continue;
+ }
+
+ r = list_dependencies_print(*c, level, branches, c[1] == NULL);
+ if (r < 0)
+ return r;
+
+ if (arg_all || unit_name_to_type(*c) == UNIT_TARGET) {
+ r = list_dependencies_one(bus, *c, level + 1, &u, (branches << 1) | (c[1] == NULL ? 0 : 1));
+ if(r < 0)
+ return r;
+ }
+ }
+ if (arg_plain) {
+ strv_free(*units);
+ *units = u;
+ u = NULL;
+ }
+ return 0;
+}
+
+static int list_dependencies(DBusConnection *bus, char **args) {
+ _cleanup_free_ char *unit = NULL;
+ _cleanup_strv_free_ char **units = NULL;
+ const char *u;
+
+ assert(bus);
+
+ if (args[1]) {
+ unit = unit_name_mangle(args[1]);
+ if (!unit)
+ return log_oom();
+ u = unit;
+ } else
+ u = SPECIAL_DEFAULT_TARGET;
+
+ pager_open_if_enabled();
+
+ puts(u);
+
+ return list_dependencies_one(bus, u, 0, &units, 0);
+}
+
+struct job_info {
+ uint32_t id;
+ char *name, *type, *state;
+};
+
+static void list_jobs_print(struct job_info* jobs, size_t n) {
+ size_t i;
+ struct job_info *j;
+ const char *on, *off;
+ bool shorten = false;
+
+ assert(n == 0 || jobs);
+
+ if (n == 0) {
+ on = ansi_highlight_green(true);
+ off = ansi_highlight_green(false);
+
+ printf("%sNo jobs running.%s\n", on, off);
+ return;
+ }
+
+ pager_open_if_enabled();
+
+ {
+ /* JOB UNIT TYPE STATE */
+ unsigned l0 = 3, l1 = 4, l2 = 4, l3 = 5;
+
+ for (i = 0, j = jobs; i < n; i++, j++) {
+ assert(j->name && j->type && j->state);
+ l0 = MAX(l0, DECIMAL_STR_WIDTH(j->id));
+ l1 = MAX(l1, strlen(j->name));
+ l2 = MAX(l2, strlen(j->type));
+ l3 = MAX(l3, strlen(j->state));
+ }
+
+ if (!arg_full && l0 + 1 + l1 + l2 + 1 + l3 > columns()) {
+ l1 = MAX(33u, columns() - l0 - l2 - l3 - 3);
+ shorten = true;
+ }
+
+ if (on_tty())
+ printf("%*s %-*s %-*s %-*s\n",
+ l0, "JOB",
+ l1, "UNIT",
+ l2, "TYPE",
+ l3, "STATE");
+
+ for (i = 0, j = jobs; i < n; i++, j++) {
+ _cleanup_free_ char *e = NULL;
+
+ if (streq(j->state, "running")) {
+ on = ansi_highlight(true);
+ off = ansi_highlight(false);
+ } else
+ on = off = "";
+
+ e = shorten ? ellipsize(j->name, l1, 33) : NULL;
+ printf("%*u %s%-*s%s %-*s %s%-*s%s\n",
+ l0, j->id,
+ on, l1, e ? e : j->name, off,
+ l2, j->type,
+ on, l3, j->state, off);
+ }
+ }
+
+ on = ansi_highlight(true);
+ off = ansi_highlight(false);
+
+ if (on_tty())
+ printf("\n%s%zu jobs listed%s.\n", on, n, off);
+}
+
+static int list_jobs(DBusConnection *bus, char **args) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ DBusMessageIter iter, sub, sub2;
+ int r;
+ struct job_info *jobs = NULL;
+ size_t size = 0, used = 0;
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "ListJobs",
+ &reply,
+ NULL,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+
+ if (!dbus_message_iter_init(reply, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
+ dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_recurse(&iter, &sub);
+
+ while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ const char *name, *type, *state, *job_path, *unit_path;
+ uint32_t id;
+
+ if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_recurse(&sub, &sub2);
+
+ if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
+ log_error("Failed to parse reply.");
+ r = -EIO;
+ goto finish;
+ }
+
+ if (!GREEDY_REALLOC(jobs, size, used + 1)) {
+ r = log_oom();
+ goto finish;
+ }
+
+ jobs[used++] = (struct job_info) { id,
+ strdup(name),
+ strdup(type),
+ strdup(state) };
+ if (!jobs[used-1].name || !jobs[used-1].type || !jobs[used-1].state) {
+ r = log_oom();
+ goto finish;
+ }
+
+ dbus_message_iter_next(&sub);
+ }
+
+ list_jobs_print(jobs, used);
+
+ finish:
+ while (used--) {
+ free(jobs[used].name);
+ free(jobs[used].type);
+ free(jobs[used].state);
+ }
+ free(jobs);
+
+ return 0;
+}
+
+static int load_unit(DBusConnection *bus, char **args) {
+ char **name;
+
+ assert(args);
+
+ STRV_FOREACH(name, args+1) {
+ _cleanup_free_ char *n = NULL;
+ int r;
+
+ n = unit_name_mangle(*name);
+ if (!n)
+ return log_oom();
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "LoadUnit",
+ NULL,
+ NULL,
+ DBUS_TYPE_STRING, &n,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static int cancel_job(DBusConnection *bus, char **args) {
+ char **name;
+
+ assert(args);
+
+ if (strv_length(args) <= 1)
+ return daemon_reload(bus, args);
+
+ STRV_FOREACH(name, args+1) {
+ uint32_t id;
+ int r;
+
+ r = safe_atou32(*name, &id);
+ if (r < 0) {
+ log_error("Failed to parse job id: %s", strerror(-r));
+ return r;
+ }
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "CancelJob",
+ NULL,
+ NULL,
+ DBUS_TYPE_UINT32, &id,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ dbus_bool_t b = FALSE;
+ DBusMessageIter iter, sub;
+ const char
+ *interface = "org.freedesktop.systemd1.Unit",
+ *property = "NeedDaemonReload",
+ *path;
+ _cleanup_free_ char *n = NULL;
+ int r;
+
+ /* We ignore all errors here, since this is used to show a warning only */
+
+ n = unit_name_mangle(unit);
+ if (!n)
+ return log_oom();
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "GetUnit",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &n,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+
+ if (!dbus_message_get_args(reply, NULL,
+ DBUS_TYPE_OBJECT_PATH, &path,
+ DBUS_TYPE_INVALID))
+ return -EIO;
+
+ dbus_message_unref(reply);
+ reply = NULL;
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.systemd1",
+ path,
+ "org.freedesktop.DBus.Properties",
+ "Get",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &interface,
+ DBUS_TYPE_STRING, &property,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+
+ if (!dbus_message_iter_init(reply, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
+ return -EIO;
+
+ dbus_message_iter_recurse(&iter, &sub);
+ if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
+ return -EIO;
+
+ dbus_message_iter_get_basic(&sub, &b);
+ return b;
+}
+
+typedef struct WaitData {
+ Set *set;
+
+ char *name;
+ char *result;
+} WaitData;
+
+static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
+ _cleanup_dbus_error_free_ DBusError error;
+ WaitData *d = data;
+
+ dbus_error_init(&error);
+
+ assert(connection);
+ assert(message);
+ assert(d);
+
+ log_debug("Got D-Bus request: %s.%s() on %s",
+ dbus_message_get_interface(message),
+ dbus_message_get_member(message),
+ dbus_message_get_path(message));
+
+ if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
+ log_error("Warning! D-Bus connection terminated.");
+ dbus_connection_close(connection);
+
+ } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
+ uint32_t id;
+ const char *path, *result, *unit;
+
+ if (dbus_message_get_args(message, &error,
+ DBUS_TYPE_UINT32, &id,
+ DBUS_TYPE_OBJECT_PATH, &path,
+ DBUS_TYPE_STRING, &unit,
+ DBUS_TYPE_STRING, &result,
+ DBUS_TYPE_INVALID)) {
+
+ free(set_remove(d->set, (char*) path));
+
+ if (!isempty(result))
+ d->result = strdup(result);
+
+ if (!isempty(unit))
+ d->name = strdup(unit);
+
+ return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
+ }
+#ifndef LEGACY
+ dbus_error_free(&error);
+ if (dbus_message_get_args(message, &error,
+ DBUS_TYPE_UINT32, &id,
+ DBUS_TYPE_OBJECT_PATH, &path,
+ DBUS_TYPE_STRING, &result,
+ DBUS_TYPE_INVALID)) {
+ /* Compatibility with older systemd versions <
+ * 183 during upgrades. This should be dropped
+ * one day. */
+ free(set_remove(d->set, (char*) path));
+
+ if (*result)
+ d->result = strdup(result);
+
+ return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
+ }
+#endif
+
+ log_error("Failed to parse message: %s", bus_error_message(&error));
+ }
+
+ return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
+}
+
+static int enable_wait_for_jobs(DBusConnection *bus) {
+ DBusError error;
+
+ assert(bus);
+
+ if (private_bus)
+ return 0;
+
+ dbus_error_init(&error);
+ dbus_bus_add_match(bus,
+ "type='signal',"
+ "sender='org.freedesktop.systemd1',"
+ "interface='org.freedesktop.systemd1.Manager',"
+ "member='JobRemoved',"
+ "path='/org/freedesktop/systemd1'",
+ &error);
+
+ if (dbus_error_is_set(&error)) {
+ log_error("Failed to add match: %s", bus_error_message(&error));
+ dbus_error_free(&error);
+ return -EIO;
+ }
+
+ /* This is slightly dirty, since we don't undo the match registrations. */
+ return 0;
+}
+
+static int wait_for_jobs(DBusConnection *bus, Set *s) {
+ int r = 0;
+ WaitData d = { .set = s };
+
+ assert(bus);
+ assert(s);
+
+ if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL))
+ return log_oom();
+
+ while (!set_isempty(s)) {
+
+ if (!dbus_connection_read_write_dispatch(bus, -1)) {
+ log_error("Disconnected from bus.");
+ return -ECONNREFUSED;
+ }
+
+ if (!d.result)
+ goto free_name;
+
+ if (!arg_quiet) {
+ if (streq(d.result, "timeout"))
+ log_error("Job for %s timed out.", strna(d.name));
+ else if (streq(d.result, "canceled"))
+ log_error("Job for %s canceled.", strna(d.name));
+ else if (streq(d.result, "dependency"))
+ log_error("A dependency job for %s failed. See 'journalctl -xn' for details.", strna(d.name));
+ else if (!streq(d.result, "done") && !streq(d.result, "skipped"))
+ log_error("Job for %s failed. See 'systemctl status %s' and 'journalctl -xn' for details.", strna(d.name), strna(d.name));
+ }
+
+ if (streq_ptr(d.result, "timeout"))
+ r = -ETIME;
+ else if (streq_ptr(d.result, "canceled"))
+ r = -ECANCELED;
+ else if (!streq_ptr(d.result, "done") && !streq_ptr(d.result, "skipped"))
+ r = -EIO;
+
+ free(d.result);
+ d.result = NULL;
+
+ free_name:
+ free(d.name);
+ d.name = NULL;
+ }
+
+ dbus_connection_remove_filter(bus, wait_filter, &d);
+ return r;
+}
+
+static int check_one_unit(DBusConnection *bus, const char *name, char **check_states, bool quiet) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ _cleanup_free_ char *n = NULL;
+ DBusMessageIter iter, sub;
+ const char
+ *interface = "org.freedesktop.systemd1.Unit",
+ *property = "ActiveState";
+ const char *state, *path;
+ DBusError error;
+ int r;
+
+ assert(name);
+
+ dbus_error_init(&error);
+
+ n = unit_name_mangle(name);
+ if (!n)
+ return log_oom();
+
+ r = bus_method_call_with_reply (
+ bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "GetUnit",
+ &reply,
+ &error,
+ DBUS_TYPE_STRING, &n,
+ DBUS_TYPE_INVALID);
+ if (r < 0) {
+ dbus_error_free(&error);
+
+ if (!quiet)
+ puts("unknown");
+ return 0;
+ }
+
+ if (!dbus_message_get_args(reply, NULL,
+ DBUS_TYPE_OBJECT_PATH, &path,
+ DBUS_TYPE_INVALID)) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_unref(reply);
+ reply = NULL;
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.systemd1",
+ path,
+ "org.freedesktop.DBus.Properties",
+ "Get",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &interface,
+ DBUS_TYPE_STRING, &property,
+ DBUS_TYPE_INVALID);
+ if (r < 0) {
+ if (!quiet)
+ puts("unknown");
+ return 0;
+ }
+
+ if (!dbus_message_iter_init(reply, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
+ log_error("Failed to parse reply.");
+ return r;
+ }
+
+ dbus_message_iter_recurse(&iter, &sub);
+
+ if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
+ log_error("Failed to parse reply.");
+ return r;
+ }
+
+ dbus_message_iter_get_basic(&sub, &state);
+
+ if (!quiet)
+ puts(state);
+
+ return strv_find(check_states, state) ? 1 : 0;
+}
+
+static void check_triggering_units(
+ DBusConnection *bus,
+ const char *unit_name) {
+
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ DBusMessageIter iter, sub;
+ const char *interface = "org.freedesktop.systemd1.Unit",
+ *load_state_property = "LoadState",
+ *triggered_by_property = "TriggeredBy",
+ *state;
+ _cleanup_free_ char *unit_path = NULL, *n = NULL;
+ bool print_warning_label = true;
+ int r;
+
+ n = unit_name_mangle(unit_name);
+ if (!n) {
+ log_oom();
+ return;
+ }
+
+ unit_path = unit_dbus_path_from_name(n);
+ if (!unit_path) {
+ log_oom();
+ return;
+ }
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.systemd1",
+ unit_path,
+ "org.freedesktop.DBus.Properties",
+ "Get",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &interface,
+ DBUS_TYPE_STRING, &load_state_property,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return;
+
+ if (!dbus_message_iter_init(reply, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
+ log_error("Failed to parse reply.");
+ return;
+ }
+
+ dbus_message_iter_recurse(&iter, &sub);
+
+ if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
+ log_error("Failed to parse reply.");
+ return;
+ }
+
+ dbus_message_iter_get_basic(&sub, &state);
+
+ if (streq(state, "masked"))
+ return;
+
+ dbus_message_unref(reply);
+ reply = NULL;
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.systemd1",
+ unit_path,
+ "org.freedesktop.DBus.Properties",
+ "Get",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &interface,
+ DBUS_TYPE_STRING, &triggered_by_property,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return;
+
+ if (!dbus_message_iter_init(reply, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
+ log_error("Failed to parse reply.");
+ return;
+ }
+
+ dbus_message_iter_recurse(&iter, &sub);
+ dbus_message_iter_recurse(&sub, &iter);
+ sub = iter;
+
+ while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ const char * const check_states[] = {
+ "active",
+ "reloading",
+ NULL
+ };
+ const char *service_trigger;
+
+ if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
+ log_error("Failed to parse reply.");
+ return;
+ }
+
+ dbus_message_iter_get_basic(&sub, &service_trigger);
+
+ r = check_one_unit(bus, service_trigger, (char**) check_states, true);
+ if (r < 0)
+ return;
+ if (r > 0) {
+ if (print_warning_label) {
+ log_warning("Warning: Stopping %s, but it can still be activated by:", unit_name);
+ print_warning_label = false;
+ }
+
+ log_warning(" %s", service_trigger);
+ }
+
+ dbus_message_iter_next(&sub);
+ }
+}
+
+static int start_unit_one(
+ DBusConnection *bus,
+ const char *method,
+ const char *name,
+ const char *mode,
+ DBusError *error,
+ Set *s) {
+
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ _cleanup_free_ char *n;
+ const char *path;
+ int r;
+
+ assert(method);
+ assert(name);
+ assert(mode);
+ assert(error);
+
+ n = unit_name_mangle(name);
+ if (!n)
+ return log_oom();
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ method,
+ &reply,
+ error,
+ DBUS_TYPE_STRING, &n,
+ DBUS_TYPE_STRING, &mode,
+ DBUS_TYPE_INVALID);
+ if (r) {
+ if (r == -ENOENT && arg_action != ACTION_SYSTEMCTL)
+ /* There's always a fallback possible for
+ * legacy actions. */
+ r = -EADDRNOTAVAIL;
+ else
+ log_error("Failed to issue method call: %s", bus_error_message(error));
+
+ return r;
+ }
+
+ if (!dbus_message_get_args(reply, error,
+ DBUS_TYPE_OBJECT_PATH, &path,
+ DBUS_TYPE_INVALID)) {
+ log_error("Failed to parse reply: %s", bus_error_message(error));
+ return -EIO;
+ }
+
+ if (need_daemon_reload(bus, n))
+ log_warning("Warning: Unit file of %s changed on disk, 'systemctl %s daemon-reload' recommended.",
+ n, arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
+
+ if (s) {
+ char *p;
+
+ p = strdup(path);
+ if (!p)
+ return log_oom();
+
+ r = set_consume(s, p);
+ if (r < 0) {
+ log_error("Failed to add path to set.");
+ return r;
+ }
+ }
+
+ return 0;
+}
+
+static const struct {
+ const char *target;
+ const char *verb;
+ const char *mode;
+} action_table[_ACTION_MAX] = {
+ [ACTION_HALT] = { SPECIAL_HALT_TARGET, "halt", "replace-irreversibly" },
+ [ACTION_POWEROFF] = { SPECIAL_POWEROFF_TARGET, "poweroff", "replace-irreversibly" },
+ [ACTION_REBOOT] = { SPECIAL_REBOOT_TARGET, "reboot", "replace-irreversibly" },
+ [ACTION_KEXEC] = { SPECIAL_KEXEC_TARGET, "kexec", "replace-irreversibly" },
+ [ACTION_RUNLEVEL2] = { SPECIAL_RUNLEVEL2_TARGET, NULL, "isolate" },
+ [ACTION_RUNLEVEL3] = { SPECIAL_RUNLEVEL3_TARGET, NULL, "isolate" },
+ [ACTION_RUNLEVEL4] = { SPECIAL_RUNLEVEL4_TARGET, NULL, "isolate" },
+ [ACTION_RUNLEVEL5] = { SPECIAL_RUNLEVEL5_TARGET, NULL, "isolate" },
+ [ACTION_RESCUE] = { SPECIAL_RESCUE_TARGET, "rescue", "isolate" },
+ [ACTION_EMERGENCY] = { SPECIAL_EMERGENCY_TARGET, "emergency", "isolate" },
+ [ACTION_DEFAULT] = { SPECIAL_DEFAULT_TARGET, "default", "isolate" },
+ [ACTION_EXIT] = { SPECIAL_EXIT_TARGET, "exit", "replace-irreversibly" },
+ [ACTION_SUSPEND] = { SPECIAL_SUSPEND_TARGET, "suspend", "replace-irreversibly" },
+ [ACTION_HIBERNATE] = { SPECIAL_HIBERNATE_TARGET, "hibernate", "replace-irreversibly" },
+ [ACTION_HYBRID_SLEEP] = { SPECIAL_HYBRID_SLEEP_TARGET, "hybrid-sleep", "replace-irreversibly" },
+};
+
+static enum action verb_to_action(const char *verb) {
+ enum action i;
+
+ for (i = ACTION_INVALID; i < _ACTION_MAX; i++)
+ if (action_table[i].verb && streq(verb, action_table[i].verb))
+ return i;
+ return ACTION_INVALID;
+}
+
+static int start_unit(DBusConnection *bus, char **args) {
+
+ int r, ret = 0;
+ const char *method, *mode, *one_name;
+ _cleanup_set_free_free_ Set *s = NULL;
+ _cleanup_dbus_error_free_ DBusError error;
+ char **name;
+
+ dbus_error_init(&error);
+
+ assert(bus);
+
+ ask_password_agent_open_if_enabled();
+
+ if (arg_action == ACTION_SYSTEMCTL) {
+ enum action action;
+ method =
+ streq(args[0], "stop") ||
+ streq(args[0], "condstop") ? "StopUnit" :
+ streq(args[0], "reload") ? "ReloadUnit" :
+ streq(args[0], "restart") ? "RestartUnit" :
+
+ streq(args[0], "try-restart") ||
+ streq(args[0], "condrestart") ? "TryRestartUnit" :
+
+ streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
+
+ streq(args[0], "reload-or-try-restart") ||
+ streq(args[0], "condreload") ||
+
+ streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
+ "StartUnit";
+ action = verb_to_action(args[0]);
+
+ mode = streq(args[0], "isolate") ? "isolate" :
+ action_table[action].mode ?: arg_job_mode;
+
+ one_name = action_table[action].target;
+
+ } else {
+ assert(arg_action < ELEMENTSOF(action_table));
+ assert(action_table[arg_action].target);
+
+ method = "StartUnit";
+
+ mode = action_table[arg_action].mode;
+ one_name = action_table[arg_action].target;
+ }
+
+ if (!arg_no_block) {
+ ret = enable_wait_for_jobs(bus);
+ if (ret < 0) {
+ log_error("Could not watch jobs: %s", strerror(-ret));
+ return ret;
+ }
+
+ s = set_new(string_hash_func, string_compare_func);
+ if (!s)
+ return log_oom();
+ }
+
+ if (one_name) {
+ ret = start_unit_one(bus, method, one_name, mode, &error, s);
+ if (ret < 0)
+ ret = translate_bus_error_to_exit_status(ret, &error);
+ } else {
+ STRV_FOREACH(name, args+1) {
+ r = start_unit_one(bus, method, *name, mode, &error, s);
+ if (r < 0) {
+ ret = translate_bus_error_to_exit_status(r, &error);
+ dbus_error_free(&error);
+ }
+ }
+ }
+
+ if (!arg_no_block) {
+ r = wait_for_jobs(bus, s);
+ if (r < 0)
+ return r;
+
+ /* When stopping units, warn if they can still be triggered by
+ * another active unit (socket, path, timer) */
+ if (!arg_quiet && streq(method, "StopUnit")) {
+ if (one_name)
+ check_triggering_units(bus, one_name);
+ else
+ STRV_FOREACH(name, args+1)
+ check_triggering_units(bus, *name);
+ }
+ }
+
+ return ret;
+}
+
+/* Ask systemd-logind, which might grant access to unprivileged users
+ * through PolicyKit */
+static int reboot_with_logind(DBusConnection *bus, enum action a) {
+#ifdef HAVE_LOGIND
+ const char *method;
+ dbus_bool_t interactive = true;
+
+ if (!bus)
+ return -EIO;
+
+ polkit_agent_open_if_enabled();
+
+ switch (a) {
+
+ case ACTION_REBOOT:
+ method = "Reboot";
+ break;
+
+ case ACTION_POWEROFF:
+ method = "PowerOff";
+ break;
+
+ case ACTION_SUSPEND:
+ method = "Suspend";
+ break;
+
+ case ACTION_HIBERNATE:
+ method = "Hibernate";
+ break;
+
+ case ACTION_HYBRID_SLEEP:
+ method = "HybridSleep";
+ break;
+
+ default:
+ return -EINVAL;
+ }
+
+ return bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ method,
+ NULL,
+ NULL,
+ DBUS_TYPE_BOOLEAN, &interactive,
+ DBUS_TYPE_INVALID);
+#else
+ return -ENOSYS;
+#endif
+}
+
+static int check_inhibitors(DBusConnection *bus, enum action a) {
+#ifdef HAVE_LOGIND
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ DBusMessageIter iter, sub, sub2;
+ int r;
+ unsigned c = 0;
+ _cleanup_strv_free_ char **sessions = NULL;
+ char **s;
+
+ if (!bus)
+ return 0;
+
+ if (arg_ignore_inhibitors || arg_force > 0)
+ return 0;
+
+ if (arg_when > 0)
+ return 0;
+
+ if (geteuid() == 0)
+ return 0;
+
+ if (!on_tty())
+ return 0;
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "ListInhibitors",
+ &reply,
+ NULL,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ /* If logind is not around, then there are no inhibitors... */
+ return 0;
+
+ if (!dbus_message_iter_init(reply, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
+ dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_recurse(&iter, &sub);
+ while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ const char *what, *who, *why, *mode;
+ uint32_t uid, pid;
+ _cleanup_strv_free_ char **sv = NULL;
+ _cleanup_free_ char *comm = NULL, *user = NULL;
+
+ if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_recurse(&sub, &sub2);
+
+ if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &what, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &who, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &why, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &mode, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &uid, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, false) < 0) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ if (!streq(mode, "block"))
+ goto next;
+
+ sv = strv_split(what, ":");
+ if (!sv)
+ return log_oom();
+
+ if (!strv_contains(sv,
+ a == ACTION_HALT ||
+ a == ACTION_POWEROFF ||
+ a == ACTION_REBOOT ||
+ a == ACTION_KEXEC ? "shutdown" : "sleep"))
+ goto next;
+
+ get_process_comm(pid, &comm);
+ user = uid_to_name(uid);
+ log_warning("Operation inhibited by \"%s\" (PID %lu \"%s\", user %s), reason is \"%s\".",
+ who, (unsigned long) pid, strna(comm), strna(user), why);
+ c++;
+
+ next:
+ dbus_message_iter_next(&sub);
+ }
+
+ dbus_message_iter_recurse(&iter, &sub);
+
+ /* Check for current sessions */
+ sd_get_sessions(&sessions);
+ STRV_FOREACH(s, sessions) {
+ uid_t uid;
+ _cleanup_free_ char *type = NULL, *tty = NULL, *seat = NULL, *user = NULL, *service = NULL, *class = NULL;
+
+ if (sd_session_get_uid(*s, &uid) < 0 || uid == getuid())
+ continue;
+
+ if (sd_session_get_class(*s, &class) < 0 || !streq(class, "user"))
+ continue;
+
+ if (sd_session_get_type(*s, &type) < 0 || (!streq(type, "x11") && !streq(type, "tty")))
+ continue;
+
+ sd_session_get_tty(*s, &tty);
+ sd_session_get_seat(*s, &seat);
+ sd_session_get_service(*s, &service);
+ user = uid_to_name(uid);
+
+ log_warning("User %s is logged in on %s.", strna(user), isempty(tty) ? (isempty(seat) ? strna(service) : seat) : tty);
+ c++;
+ }
+
+ if (c <= 0)
+ return 0;
+
+ log_error("Please retry operation after closing inhibitors and logging out other users.\nAlternatively, ignore inhibitors and users with 'systemctl %s -i'.",
+ action_table[a].verb);
+
+ return -EPERM;
+#else
+ return 0;
+#endif
+}
+
+static int start_special(DBusConnection *bus, char **args) {
+ enum action a;
+ int r;
+
+ assert(args);
+
+ a = verb_to_action(args[0]);
+
+ r = check_inhibitors(bus, a);
+ if (r < 0)
+ return r;
+
+ if (arg_force >= 2 && geteuid() != 0) {
+ log_error("Must be root.");
+ return -EPERM;
+ }
+
+ if (arg_force >= 2 &&
+ (a == ACTION_HALT ||
+ a == ACTION_POWEROFF ||
+ a == ACTION_REBOOT))
+ halt_now(a);
+
+ if (arg_force >= 1 &&
+ (a == ACTION_HALT ||
+ a == ACTION_POWEROFF ||
+ a == ACTION_REBOOT ||
+ a == ACTION_KEXEC ||
+ a == ACTION_EXIT))
+ return daemon_reload(bus, args);
+
+ /* first try logind, to allow authentication with polkit */
+ if (geteuid() != 0 &&
+ (a == ACTION_POWEROFF ||
+ a == ACTION_REBOOT ||
+ a == ACTION_SUSPEND ||
+ a == ACTION_HIBERNATE ||
+ a == ACTION_HYBRID_SLEEP)) {
+ r = reboot_with_logind(bus, a);
+ if (r >= 0)
+ return r;
+ }
+
+ r = start_unit(bus, args);
+ if (r == EXIT_SUCCESS)
+ warn_wall(a);
+
+ return r;
+}
+
+static int check_unit_active(DBusConnection *bus, char **args) {
+ const char * const check_states[] = {
+ "active",
+ "reloading",
+ NULL
+ };
+
+ char **name;
+ int r = 3; /* According to LSB: "program is not running" */
+
+ assert(bus);
+ assert(args);
+
+ STRV_FOREACH(name, args+1) {
+ int state;
+
+ state = check_one_unit(bus, *name, (char**) check_states, arg_quiet);
+ if (state < 0)
+ return state;
+ if (state > 0)
+ r = 0;
+ }
+
+ return r;
+}
+
+static int check_unit_failed(DBusConnection *bus, char **args) {
+ const char * const check_states[] = {
+ "failed",
+ NULL
+ };
+
+ char **name;
+ int r = 1;
+
+ assert(bus);
+ assert(args);
+
+ STRV_FOREACH(name, args+1) {
+ int state;
+
+ state = check_one_unit(bus, *name, (char**) check_states, arg_quiet);
+ if (state < 0)
+ return state;
+ if (state > 0)
+ r = 0;
+ }
+
+ return r;
+}
+
+static int kill_unit(DBusConnection *bus, char **args) {
+ char **name;
+ int r = 0;
+
+ assert(bus);
+ assert(args);
+
+ if (!arg_kill_who)
+ arg_kill_who = "all";
+
+ STRV_FOREACH(name, args+1) {
+ _cleanup_free_ char *n = NULL;
+
+ n = unit_name_mangle(*name);
+ if (!n)
+ return log_oom();
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "KillUnit",
+ NULL,
+ NULL,
+ DBUS_TYPE_STRING, &n,
+ DBUS_TYPE_STRING, &arg_kill_who,
+ DBUS_TYPE_INT32, &arg_signal,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+ }
+ return 0;
+}
+
+static int set_cgroup(DBusConnection *bus, char **args) {
+ _cleanup_free_ char *n = NULL;
+ const char *method, *runtime;
+ char **argument;
+ int r;
+
+ assert(bus);
+ assert(args);
+
+ method =
+ streq(args[0], "set-cgroup") ? "SetUnitControlGroup" :
+ streq(args[0], "unset-cgroup") ? "UnsetUnitControlGroup"
+ : "UnsetUnitControlGroupAttribute";
+
+ runtime = arg_runtime ? "runtime" : "persistent";
+
+ n = unit_name_mangle(args[1]);
+ if (!n)
+ return log_oom();
+
+ STRV_FOREACH(argument, args + 2) {
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ method,
+ NULL,
+ NULL,
+ DBUS_TYPE_STRING, &n,
+ DBUS_TYPE_STRING, argument,
+ DBUS_TYPE_STRING, &runtime,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static int set_cgroup_attr(DBusConnection *bus, char **args) {
+ _cleanup_dbus_message_unref_ DBusMessage *m = NULL, *reply = NULL;
+ DBusError error;
+ DBusMessageIter iter;
+ _cleanup_free_ char *n = NULL;
+ const char *runtime;
+ int r;
+
+ assert(bus);
+ assert(args);
+
+ dbus_error_init(&error);
+
+ runtime = arg_runtime ? "runtime" : "persistent";
+
+ n = unit_name_mangle(args[1]);
+ if (!n)
+ return log_oom();
+
+ m = dbus_message_new_method_call(
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "SetUnitControlGroupAttribute");
+ if (!m)
+ return log_oom();
+
+ dbus_message_iter_init_append(m, &iter);
+ if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &n) ||
+ !dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &args[2]))
+ return log_oom();
+
+ r = bus_append_strv_iter(&iter, args + 3);
+ if (r < 0)
+ return log_oom();
+
+ if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &runtime))
+ return log_oom();
+
+ reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
+ if (!reply) {
+ log_error("Failed to issue method call: %s", bus_error_message(&error));
+ dbus_error_free(&error);
+ return -EIO;
+ }
+
+ return 0;
+}
+
+static int get_cgroup_attr(DBusConnection *bus, char **args) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ _cleanup_free_ char *n = NULL;
+ char **argument;
+ int r;
+
+ assert(bus);
+ assert(args);
+
+ n = unit_name_mangle(args[1]);
+ if (!n)
+ return log_oom();
+
+ STRV_FOREACH(argument, args + 2) {
+ _cleanup_strv_free_ char **list = NULL;
+ DBusMessageIter iter;
+ char **a;
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "GetUnitControlGroupAttribute",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &n,
+ DBUS_TYPE_STRING, argument,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+
+ if (!dbus_message_iter_init(reply, &iter)) {
+ log_error("Failed to initialize iterator.");
+ return -EIO;
+ }
+
+ r = bus_parse_strv_iter(&iter, &list);
+ if (r < 0) {
+ log_error("Failed to parse value list.");
+ return r;
+ }
+
+ STRV_FOREACH(a, list) {
+ if (endswith(*a, "\n"))
+ fputs(*a, stdout);
+ else
+ puts(*a);
+ }
+ }
+
+ return 0;
+}
+
+typedef struct ExecStatusInfo {
+ char *name;
+
+ char *path;
+ char **argv;
+
+ bool ignore;
+
+ usec_t start_timestamp;
+ usec_t exit_timestamp;
+ pid_t pid;
+ int code;
+ int status;
+
+ LIST_FIELDS(struct ExecStatusInfo, exec);
+} ExecStatusInfo;
+
+static void exec_status_info_free(ExecStatusInfo *i) {
+ assert(i);
+
+ free(i->name);
+ free(i->path);
+ strv_free(i->argv);
+ free(i);
+}
+
+static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
+ uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
+ DBusMessageIter sub2, sub3;
+ const char*path;
+ unsigned n;
+ uint32_t pid;
+ int32_t code, status;
+ dbus_bool_t ignore;
+
+ assert(i);
+ assert(i);
+
+ if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
+ return -EIO;
+
+ dbus_message_iter_recurse(sub, &sub2);
+
+ if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
+ return -EIO;
+
+ i->path = strdup(path);
+ if (!i->path)
+ return -ENOMEM;
+
+ if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
+ dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
+ return -EIO;
+
+ n = 0;
+ dbus_message_iter_recurse(&sub2, &sub3);
+ while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
+ assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
+ dbus_message_iter_next(&sub3);
+ n++;
+ }
+
+ i->argv = new0(char*, n+1);
+ if (!i->argv)
+ return -ENOMEM;
+
+ n = 0;
+ dbus_message_iter_recurse(&sub2, &sub3);
+ while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
+ const char *s;
+
+ assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
+ dbus_message_iter_get_basic(&sub3, &s);
+ dbus_message_iter_next(&sub3);
+
+ i->argv[n] = strdup(s);
+ if (!i->argv[n])
+ return -ENOMEM;
+
+ n++;
+ }
+
+ if (!dbus_message_iter_next(&sub2) ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp_monotonic, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp_monotonic, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
+ return -EIO;
+
+ i->ignore = ignore;
+ i->start_timestamp = (usec_t) start_timestamp;
+ i->exit_timestamp = (usec_t) exit_timestamp;
+ i->pid = (pid_t) pid;
+ i->code = code;
+ i->status = status;
+
+ return 0;
+}
+
+typedef struct UnitStatusInfo {
+ const char *id;
+ const char *load_state;
+ const char *active_state;
+ const char *sub_state;
+ const char *unit_file_state;
+
+ const char *description;
+ const char *following;
+
+ char **documentation;
+
+ const char *fragment_path;
+ const char *source_path;
+ const char *default_control_group;
+
+ char **dropin_paths;
+
+ const char *load_error;
+ const char *result;
+
+ usec_t inactive_exit_timestamp;
+ usec_t inactive_exit_timestamp_monotonic;
+ usec_t active_enter_timestamp;
+ usec_t active_exit_timestamp;
+ usec_t inactive_enter_timestamp;
+
+ bool need_daemon_reload;
+
+ /* Service */
+ pid_t main_pid;
+ pid_t control_pid;
+ const char *status_text;
+ bool running:1;
+
+ usec_t start_timestamp;
+ usec_t exit_timestamp;
+
+ int exit_code, exit_status;
+
+ usec_t condition_timestamp;
+ bool condition_result;
+
+ /* Socket */
+ unsigned n_accepted;
+ unsigned n_connections;
+ bool accept;
+
+ /* Pairs of type, path */
+ char **listen;
+
+ /* Device */
+ const char *sysfs_path;
+
+ /* Mount, Automount */
+ const char *where;
+
+ /* Swap */
+ const char *what;
+
+ LIST_HEAD(ExecStatusInfo, exec);
+} UnitStatusInfo;
+
+static void print_status_info(UnitStatusInfo *i) {
+ ExecStatusInfo *p;
+ const char *on, *off, *ss;
+ usec_t timestamp;
+ char since1[FORMAT_TIMESTAMP_RELATIVE_MAX], *s1;
+ char since2[FORMAT_TIMESTAMP_MAX], *s2;
+ const char *path;
+ int flags =
+ arg_all * OUTPUT_SHOW_ALL |
+ (!on_tty() || pager_have()) * OUTPUT_FULL_WIDTH |
+ on_tty() * OUTPUT_COLOR |
+ !arg_quiet * OUTPUT_WARN_CUTOFF |
+ arg_full * OUTPUT_FULL_WIDTH;
+ int maxlen = 8; /* a value that'll suffice most of the time */
+ char **t, **t2;
+
+ assert(i);
+
+ STRV_FOREACH_PAIR(t, t2, i->listen)
+ maxlen = MAX(maxlen, (int)(sizeof("Listen") - 1 + strlen(*t)));
+ if (i->accept)
+ maxlen = MAX(maxlen, (int)sizeof("Accept") - 1);
+ if (i->main_pid > 0)
+ maxlen = MAX(maxlen, (int)sizeof("Main PID") - 1);
+ else if (i->control_pid > 0)
+ maxlen = MAX(maxlen, (int)sizeof("Control") - 1);
+
+ /* This shows pretty information about a unit. See
+ * print_property() for a low-level property printer */
+
+ printf("%s", strna(i->id));
+
+ if (i->description && !streq_ptr(i->id, i->description))
+ printf(" - %s", i->description);
+
+ printf("\n");
+
+ if (i->following)
+ printf(" %*s: unit currently follows state of %s\n", maxlen, "Follow", i->following);
+
+ if (streq_ptr(i->load_state, "error")) {
+ on = ansi_highlight_red(true);
+ off = ansi_highlight_red(false);
+ } else
+ on = off = "";
+
+ path = i->source_path ? i->source_path : i->fragment_path;
+
+ if (i->load_error)
+ printf(" %*s: %s%s%s (Reason: %s)\n",
+ maxlen, "Loaded", on, strna(i->load_state), off, i->load_error);
+ else if (path && i->unit_file_state)
+ printf(" %*s: %s%s%s (%s; %s)\n",
+ maxlen, "Loaded", on, strna(i->load_state), off, path, i->unit_file_state);
+ else if (path)
+ printf(" %*s: %s%s%s (%s)\n",
+ maxlen, "Loaded", on, strna(i->load_state), off, path);
+ else
+ printf(" %*s: %s%s%s\n",
+ maxlen, "Loaded", on, strna(i->load_state), off);
+
+ if (!strv_isempty(i->dropin_paths)) {
+ char ** dropin;
+ char * dir = NULL;
+ bool last = false;
+
+ STRV_FOREACH(dropin, i->dropin_paths) {
+ if (! dir || last) {
+ printf(" %*s ", maxlen, dir ? "" : "Drop-In:");
+
+ free(dir);
+
+ if (path_get_parent(*dropin, &dir) < 0) {
+ log_oom();
+ return;
+ }
+
+ printf("%s\n %*s %s", dir, maxlen, "",
+ draw_special_char(DRAW_TREE_RIGHT));
+ }
+
+ last = ! (*(dropin + 1) && startswith(*(dropin + 1), dir));
+
+ printf("%s%s", path_get_file_name(*dropin), last ? "\n" : ", ");
+ }
+
+ free(dir);
+ }
+
+ ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
+
+ if (streq_ptr(i->active_state, "failed")) {
+ on = ansi_highlight_red(true);
+ off = ansi_highlight_red(false);
+ } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
+ on = ansi_highlight_green(true);
+ off = ansi_highlight_green(false);
+ } else
+ on = off = "";
+
+ if (ss)
+ printf(" %*s: %s%s (%s)%s",
+ maxlen, "Active", on, strna(i->active_state), ss, off);
+ else
+ printf(" %*s: %s%s%s",
+ maxlen, "Active", on, strna(i->active_state), off);
+
+ if (!isempty(i->result) && !streq(i->result, "success"))
+ printf(" (Result: %s)", i->result);
+
+ timestamp = (streq_ptr(i->active_state, "active") ||
+ streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
+ (streq_ptr(i->active_state, "inactive") ||
+ streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
+ streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
+ i->active_exit_timestamp;
+
+ s1 = format_timestamp_relative(since1, sizeof(since1), timestamp);
+ s2 = format_timestamp(since2, sizeof(since2), timestamp);
+
+ if (s1)
+ printf(" since %s; %s\n", s2, s1);
+ else if (s2)
+ printf(" since %s\n", s2);
+ else
+ printf("\n");
+
+ if (!i->condition_result && i->condition_timestamp > 0) {
+ s1 = format_timestamp_relative(since1, sizeof(since1), i->condition_timestamp);
+ s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
+
+ if (s1)
+ printf(" %*s start condition failed at %s; %s\n", maxlen, "", s2, s1);
+ else if (s2)
+ printf(" %*s start condition failed at %s\n", maxlen, "", s2);
+ }
+
+ if (i->sysfs_path)
+ printf(" %*s: %s\n", maxlen, "Device", i->sysfs_path);
+ if (i->where)
+ printf(" %*s: %s\n", maxlen, "Where", i->where);
+ if (i->what)
+ printf(" %*s: %s\n", maxlen, "What", i->what);
+
+ STRV_FOREACH(t, i->documentation)
+ printf(" %*s %s\n", maxlen+1, t == i->documentation ? "Docs:" : "", *t);
+
+ STRV_FOREACH_PAIR(t, t2, i->listen)
+ printf(" %*s %s (%s)\n", maxlen+1, t == i->listen ? "Listen:" : "", *t2, *t);
+
+ if (i->accept)
+ printf(" %*s: %u; Connected: %u\n", maxlen, "Accepted", i->n_accepted, i->n_connections);
+
+ LIST_FOREACH(exec, p, i->exec) {
+ _cleanup_free_ char *argv = NULL;
+ bool good;
+
+ /* Only show exited processes here */
+ if (p->code == 0)
+ continue;
+
+ argv = strv_join(p->argv, " ");
+ printf(" %*s: %u %s=%s ", maxlen, "Process", p->pid, p->name, strna(argv));
+
+ good = is_clean_exit_lsb(p->code, p->status, NULL);
+ if (!good) {
+ on = ansi_highlight_red(true);
+ off = ansi_highlight_red(false);
+ } else
+ on = off = "";
+
+ printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
+
+ if (p->code == CLD_EXITED) {
+ const char *c;
+
+ printf("status=%i", p->status);
+
+ c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD);
+ if (c)
+ printf("/%s", c);
+
+ } else
+ printf("signal=%s", signal_to_string(p->status));
+
+ printf(")%s\n", off);
+
+ if (i->main_pid == p->pid &&
+ i->start_timestamp == p->start_timestamp &&
+ i->exit_timestamp == p->start_timestamp)
+ /* Let's not show this twice */
+ i->main_pid = 0;
+
+ if (p->pid == i->control_pid)
+ i->control_pid = 0;
+ }
+
+ if (i->main_pid > 0 || i->control_pid > 0) {
+ if (i->main_pid > 0) {
+ printf(" %*s: %u", maxlen, "Main PID", (unsigned) i->main_pid);
+
+ if (i->running) {
+ _cleanup_free_ char *comm = NULL;
+ get_process_comm(i->main_pid, &comm);
+ if (comm)
+ printf(" (%s)", comm);
+ } else if (i->exit_code > 0) {
+ printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
+
+ if (i->exit_code == CLD_EXITED) {
+ const char *c;
+
+ printf("status=%i", i->exit_status);
+
+ c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD);
+ if (c)
+ printf("/%s", c);
+
+ } else
+ printf("signal=%s", signal_to_string(i->exit_status));
+ printf(")");
+ }
+
+ if (i->control_pid > 0)
+ printf(";");
+ }
+
+ if (i->control_pid > 0) {
+ _cleanup_free_ char *c = NULL;
+
+ printf(" %*s: %u", i->main_pid ? 0 : maxlen, "Control", (unsigned) i->control_pid);
+
+ get_process_comm(i->control_pid, &c);
+ if (c)
+ printf(" (%s)", c);
+ }
+
+ printf("\n");
+ }
+
+ if (i->status_text)
+ printf(" %*s: \"%s\"\n", maxlen, "Status", i->status_text);
+
+ if (i->default_control_group &&
+ (i->main_pid > 0 || i->control_pid > 0 || cg_is_empty_by_spec(i->default_control_group, false) == 0)) {
+ unsigned c;
+
+ printf(" %*s: %s\n", maxlen, "CGroup", i->default_control_group);
+
+ if (arg_transport != TRANSPORT_SSH) {
+ unsigned k = 0;
+ pid_t extra[2];
+ char prefix[maxlen + 4];
+ memset(prefix, ' ', sizeof(prefix) - 1);
+ prefix[sizeof(prefix) - 1] = '\0';
+
+ c = columns();
+ if (c > sizeof(prefix) - 1)
+ c -= sizeof(prefix) - 1;
+ else
+ c = 0;
+
+ if (i->main_pid > 0)
+ extra[k++] = i->main_pid;
+
+ if (i->control_pid > 0)
+ extra[k++] = i->control_pid;
+
+ show_cgroup_and_extra_by_spec(i->default_control_group, prefix,
+ c, false, extra, k, flags);
+ }
+ }
+
+ if (i->id && arg_transport != TRANSPORT_SSH) {
+ printf("\n");
+ show_journal_by_unit(stdout,
+ i->id,
+ arg_output,
+ 0,
+ i->inactive_exit_timestamp_monotonic,
+ arg_lines,
+ getuid(),
+ flags,
+ arg_scope == UNIT_FILE_SYSTEM);
+ }
+
+ if (i->need_daemon_reload)
+ printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
+ ansi_highlight_red(true),
+ ansi_highlight_red(false),
+ arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
+}
+
+static void show_unit_help(UnitStatusInfo *i) {
+ char **p;
+
+ assert(i);
+
+ if (!i->documentation) {
+ log_info("Documentation for %s not known.", i->id);
+ return;
+ }
+
+ STRV_FOREACH(p, i->documentation) {
+
+ if (startswith(*p, "man:")) {
+ size_t k;
+ char *e = NULL;
+ _cleanup_free_ char *page = NULL, *section = NULL;
+ const char *args[4] = { "man", NULL, NULL, NULL };
+ pid_t pid;
+
+ k = strlen(*p);
+
+ if ((*p)[k-1] == ')')
+ e = strrchr(*p, '(');
+
+ if (e) {
+ page = strndup((*p) + 4, e - *p - 4);
+ section = strndup(e + 1, *p + k - e - 2);
+ if (!page || !section) {
+ log_oom();
+ return;
+ }
+
+ args[1] = section;
+ args[2] = page;
+ } else
+ args[1] = *p + 4;
+
+ pid = fork();
+ if (pid < 0) {
+ log_error("Failed to fork: %m");
+ continue;
+ }
+
+ if (pid == 0) {
+ /* Child */
+ execvp(args[0], (char**) args);
+ log_error("Failed to execute man: %m");
+ _exit(EXIT_FAILURE);
+ }
+
+ wait_for_terminate(pid, NULL);
+ } else
+ log_info("Can't show: %s", *p);
+ }
+}
+
+static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
+
+ assert(name);
+ assert(iter);
+ assert(i);
+
+ switch (dbus_message_iter_get_arg_type(iter)) {
+
+ case DBUS_TYPE_STRING: {
+ const char *s;
+
+ dbus_message_iter_get_basic(iter, &s);
+
+ if (!isempty(s)) {
+ if (streq(name, "Id"))
+ i->id = s;
+ else if (streq(name, "LoadState"))
+ i->load_state = s;
+ else if (streq(name, "ActiveState"))
+ i->active_state = s;
+ else if (streq(name, "SubState"))
+ i->sub_state = s;
+ else if (streq(name, "Description"))
+ i->description = s;
+ else if (streq(name, "FragmentPath"))
+ i->fragment_path = s;
+ else if (streq(name, "SourcePath"))
+ i->source_path = s;
+ else if (streq(name, "DefaultControlGroup"))
+ i->default_control_group = s;
+ else if (streq(name, "StatusText"))
+ i->status_text = s;
+ else if (streq(name, "SysFSPath"))
+ i->sysfs_path = s;
+ else if (streq(name, "Where"))
+ i->where = s;
+ else if (streq(name, "What"))
+ i->what = s;
+ else if (streq(name, "Following"))
+ i->following = s;
+ else if (streq(name, "UnitFileState"))
+ i->unit_file_state = s;
+ else if (streq(name, "Result"))
+ i->result = s;
+ }
+
+ break;
+ }
+
+ case DBUS_TYPE_BOOLEAN: {
+ dbus_bool_t b;
+
+ dbus_message_iter_get_basic(iter, &b);
+
+ if (streq(name, "Accept"))
+ i->accept = b;
+ else if (streq(name, "NeedDaemonReload"))
+ i->need_daemon_reload = b;
+ else if (streq(name, "ConditionResult"))
+ i->condition_result = b;
+
+ break;
+ }
+
+ case DBUS_TYPE_UINT32: {
+ uint32_t u;
+
+ dbus_message_iter_get_basic(iter, &u);
+
+ if (streq(name, "MainPID")) {
+ if (u > 0) {
+ i->main_pid = (pid_t) u;
+ i->running = true;
+ }
+ } else if (streq(name, "ControlPID"))
+ i->control_pid = (pid_t) u;
+ else if (streq(name, "ExecMainPID")) {
+ if (u > 0)
+ i->main_pid = (pid_t) u;
+ } else if (streq(name, "NAccepted"))
+ i->n_accepted = u;
+ else if (streq(name, "NConnections"))
+ i->n_connections = u;
+
+ break;
+ }
+
+ case DBUS_TYPE_INT32: {
+ int32_t j;
+
+ dbus_message_iter_get_basic(iter, &j);
+
+ if (streq(name, "ExecMainCode"))
+ i->exit_code = (int) j;
+ else if (streq(name, "ExecMainStatus"))
+ i->exit_status = (int) j;
+
+ break;
+ }
+
+ case DBUS_TYPE_UINT64: {
+ uint64_t u;
+
+ dbus_message_iter_get_basic(iter, &u);
+
+ if (streq(name, "ExecMainStartTimestamp"))
+ i->start_timestamp = (usec_t) u;
+ else if (streq(name, "ExecMainExitTimestamp"))
+ i->exit_timestamp = (usec_t) u;
+ else if (streq(name, "ActiveEnterTimestamp"))
+ i->active_enter_timestamp = (usec_t) u;
+ else if (streq(name, "InactiveEnterTimestamp"))
+ i->inactive_enter_timestamp = (usec_t) u;
+ else if (streq(name, "InactiveExitTimestamp"))
+ i->inactive_exit_timestamp = (usec_t) u;
+ else if (streq(name, "InactiveExitTimestampMonotonic"))
+ i->inactive_exit_timestamp_monotonic = (usec_t) u;
+ else if (streq(name, "ActiveExitTimestamp"))
+ i->active_exit_timestamp = (usec_t) u;
+ else if (streq(name, "ConditionTimestamp"))
+ i->condition_timestamp = (usec_t) u;
+
+ break;
+ }
+
+ case DBUS_TYPE_ARRAY: {
+
+ if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
+ startswith(name, "Exec")) {
+ DBusMessageIter sub;
+
+ dbus_message_iter_recurse(iter, &sub);
+ while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
+ ExecStatusInfo *info;
+ int r;
+
+ if (!(info = new0(ExecStatusInfo, 1)))
+ return -ENOMEM;
+
+ if (!(info->name = strdup(name))) {
+ free(info);
+ return -ENOMEM;
+ }
+
+ if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
+ free(info);
+ return r;
+ }
+
+ LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
+
+ dbus_message_iter_next(&sub);
+ }
+
+ } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Listen")) {
+ DBusMessageIter sub, sub2;
+
+ dbus_message_iter_recurse(iter, &sub);
+ while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
+ const char *type, *path;
+
+ dbus_message_iter_recurse(&sub, &sub2);
+
+ if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0) {
+ int r;
+
+ r = strv_extend(&i->listen, type);
+ if (r < 0)
+ return r;
+ r = strv_extend(&i->listen, path);
+ if (r < 0)
+ return r;
+ }
+
+ dbus_message_iter_next(&sub);
+ }
+
+ return 0;
+
+ } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING && streq(name, "DropInPaths")) {
+ int r = bus_parse_strv_iter(iter, &i->dropin_paths);
+ if (r < 0)
+ return r;
+
+ } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING &&
+ streq(name, "Documentation")) {
+
+ DBusMessageIter sub;
+
+ dbus_message_iter_recurse(iter, &sub);
+ while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING) {
+ const char *s;
+ int r;
+
+ dbus_message_iter_get_basic(&sub, &s);
+
+ r = strv_extend(&i->documentation, s);
+ if (r < 0)
+ return r;
+
+ dbus_message_iter_next(&sub);
+ }
+ }
+
+ break;
+ }
+
+ case DBUS_TYPE_STRUCT: {
+
+ if (streq(name, "LoadError")) {
+ DBusMessageIter sub;
+ const char *n, *message;
+ int r;
+
+ dbus_message_iter_recurse(iter, &sub);
+
+ r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &n, true);
+ if (r < 0)
+ return r;
+
+ r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &message, false);
+ if (r < 0)
+ return r;
+
+ if (!isempty(message))
+ i->load_error = message;
+ }
+
+ break;
+ }
+ }
+
+ return 0;
+}
+
+static int print_property(const char *name, DBusMessageIter *iter) {
+ assert(name);
+ assert(iter);
+
+ /* This is a low-level property printer, see
+ * print_status_info() for the nicer output */
+
+ if (arg_properties && !strv_find(arg_properties, name))
+ return 0;
+
+ switch (dbus_message_iter_get_arg_type(iter)) {
+
+ case DBUS_TYPE_STRUCT: {
+ DBusMessageIter sub;
+ dbus_message_iter_recurse(iter, &sub);
+
+ if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
+ uint32_t u;
+
+ dbus_message_iter_get_basic(&sub, &u);
+
+ if (u)
+ printf("%s=%u\n", name, (unsigned) u);
+ else if (arg_all)
+ printf("%s=\n", name);
+
+ return 0;
+ } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
+ const char *s;
+
+ dbus_message_iter_get_basic(&sub, &s);
+
+ if (arg_all || s[0])
+ printf("%s=%s\n", name, s);
+
+ return 0;
+ } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "LoadError")) {
+ const char *a = NULL, *b = NULL;
+
+ if (bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &a, true) >= 0)
+ bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &b, false);
+
+ if (arg_all || !isempty(a) || !isempty(b))
+ printf("%s=%s \"%s\"\n", name, strempty(a), strempty(b));
+
+ return 0;
+ }
+
+ break;
+ }
+
+ case DBUS_TYPE_ARRAY:
+
+ if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "EnvironmentFiles")) {
+ DBusMessageIter sub, sub2;
+
+ dbus_message_iter_recurse(iter, &sub);
+ while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
+ const char *path;
+ dbus_bool_t ignore;
+
+ dbus_message_iter_recurse(&sub, &sub2);
+
+ if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, false) >= 0)
+ printf("EnvironmentFile=%s (ignore_errors=%s)\n", path, yes_no(ignore));
+
+ dbus_message_iter_next(&sub);
+ }
+
+ return 0;
+
+ } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
+ DBusMessageIter sub, sub2;
+
+ dbus_message_iter_recurse(iter, &sub);
+
+ while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
+ const char *type, *path;
+
+ dbus_message_iter_recurse(&sub, &sub2);
+
+ if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
+ printf("%s=%s\n", type, path);
+
+ dbus_message_iter_next(&sub);
+ }
+
+ return 0;
+
+ } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Listen")) {
+ DBusMessageIter sub, sub2;
+
+ dbus_message_iter_recurse(iter, &sub);
+ while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
+ const char *type, *path;
+
+ dbus_message_iter_recurse(&sub, &sub2);
+
+ if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
+ printf("Listen%s=%s\n", type, path);
+
+ dbus_message_iter_next(&sub);
+ }
+
+ return 0;
+
+ } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
+ DBusMessageIter sub, sub2;
+
+ dbus_message_iter_recurse(iter, &sub);
+ while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
+ const char *base;
+ uint64_t value, next_elapse;
+
+ dbus_message_iter_recurse(&sub, &sub2);
+
+ if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
+ char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
+
+ printf("%s={ value=%s ; next_elapse=%s }\n",
+ base,
+ format_timespan(timespan1, sizeof(timespan1), value, 0),
+ format_timespan(timespan2, sizeof(timespan2), next_elapse, 0));
+ }
+
+ dbus_message_iter_next(&sub);
+ }
+
+ return 0;
+
+ } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "ControlGroupAttributes")) {
+ DBusMessageIter sub, sub2;
+
+ dbus_message_iter_recurse(iter, &sub);
+ while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
+ const char *controller, *attr, *value;
+
+ dbus_message_iter_recurse(&sub, &sub2);
+
+ if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &controller, true) >= 0 &&
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &attr, true) >= 0 &&
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &value, false) >= 0) {
+
+ printf("ControlGroupAttributes={ controller=%s ; attribute=%s ; value=\"%s\" }\n",
+ controller,
+ attr,
+ value);
+ }
+
+ dbus_message_iter_next(&sub);
+ }
+
+ return 0;
+
+ } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
+ DBusMessageIter sub;
+
+ dbus_message_iter_recurse(iter, &sub);
+ while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
+ ExecStatusInfo info = {};
+
+ if (exec_status_info_deserialize(&sub, &info) >= 0) {
+ char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
+ _cleanup_free_ char *t;
+
+ t = strv_join(info.argv, " ");
+
+ printf("%s={ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
+ name,
+ strna(info.path),
+ strna(t),
+ yes_no(info.ignore),
+ strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
+ strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
+ (unsigned) info. pid,
+ sigchld_code_to_string(info.code),
+ info.status,
+ info.code == CLD_EXITED ? "" : "/",
+ strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
+ }
+
+ free(info.path);
+ strv_free(info.argv);
+
+ dbus_message_iter_next(&sub);
+ }
+
+ return 0;
+ }
+
+ break;
+ }
+
+ if (generic_print_property(name, iter, arg_all) > 0)
+ return 0;
+
+ if (arg_all)
+ printf("%s=[unprintable]\n", name);
+
+ return 0;
+}
+
+static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
+ _cleanup_free_ DBusMessage *reply = NULL;
+ const char *interface = "";
+ int r;
+ DBusMessageIter iter, sub, sub2, sub3;
+ UnitStatusInfo info = {};
+ ExecStatusInfo *p;
+
+ assert(path);
+ assert(new_line);
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.systemd1",
+ path,
+ "org.freedesktop.DBus.Properties",
+ "GetAll",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &interface,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+
+ if (!dbus_message_iter_init(reply, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
+ dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_recurse(&iter, &sub);
+
+ if (*new_line)
+ printf("\n");
+
+ *new_line = true;
+
+ while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ const char *name;
+
+ assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_DICT_ENTRY);
+ dbus_message_iter_recurse(&sub, &sub2);
+
+ if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
+ dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_recurse(&sub2, &sub3);
+
+ if (show_properties)
+ r = print_property(name, &sub3);
+ else
+ r = status_property(name, &sub3, &info);
+ if (r < 0) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_next(&sub);
+ }
+
+ r = 0;
+
+ if (!show_properties) {
+ if (streq(verb, "help"))
+ show_unit_help(&info);
+ else
+ print_status_info(&info);
+ }
+
+ strv_free(info.documentation);
+ strv_free(info.dropin_paths);
+ strv_free(info.listen);
+
+ if (!streq_ptr(info.active_state, "active") &&
+ !streq_ptr(info.active_state, "reloading") &&
+ streq(verb, "status"))
+ /* According to LSB: "program not running" */
+ r = 3;
+
+ while ((p = info.exec)) {
+ LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
+ exec_status_info_free(p);
+ }
+
+ return r;
+}
+
+static int show_one_by_pid(const char *verb, DBusConnection *bus, uint32_t pid, bool *new_line) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ const char *path = NULL;
+ _cleanup_dbus_error_free_ DBusError error;
+ int r;
+
+ dbus_error_init(&error);
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "GetUnitByPID",
+ &reply,
+ NULL,
+ DBUS_TYPE_UINT32, &pid,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+
+ if (!dbus_message_get_args(reply, &error,
+ DBUS_TYPE_OBJECT_PATH, &path,
+ DBUS_TYPE_INVALID)) {
+ log_error("Failed to parse reply: %s", bus_error_message(&error));
+ return -EIO;
+ }
+
+ r = show_one(verb, bus, path, false, new_line);
+ return r;
+}
+
+static int show_all(const char* verb, DBusConnection *bus, bool show_properties, bool *new_line) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ _cleanup_free_ struct unit_info *unit_infos = NULL;
+ unsigned c = 0;
+ const struct unit_info *u;
+ int r;
+
+ r = get_unit_list(bus, &reply, &unit_infos, &c);
+ if (r < 0)
+ return r;
+
+ qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
+
+ for (u = unit_infos; u < unit_infos + c; u++) {
+ _cleanup_free_ char *p = NULL;
+
+ if (!output_show_unit(u))
+ continue;
+
+ p = unit_dbus_path_from_name(u->id);
+ if (!p)
+ return log_oom();
+
+ printf("%s -> '%s'\n", u->id, p);
+
+ r = show_one(verb, bus, p, show_properties, new_line);
+ if (r != 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static int show(DBusConnection *bus, char **args) {
+ int r, ret = 0;
+ bool show_properties, show_status, new_line = false;
+ char **name;
+
+ assert(bus);
+ assert(args);
+
+ show_properties = streq(args[0], "show");
+ show_status = streq(args[0], "status");
+
+ if (show_properties)
+ pager_open_if_enabled();
+
+ /* If no argument is specified inspect the manager itself */
+
+ if (show_properties && strv_length(args) <= 1)
+ return show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
+
+ if (show_status && strv_length(args) <= 1)
+ return show_all(args[0], bus, false, &new_line);
+
+ STRV_FOREACH(name, args+1) {
+ uint32_t id;
+
+ if (safe_atou32(*name, &id) < 0) {
+ _cleanup_free_ char *p = NULL, *n = NULL;
+ /* Interpret as unit name */
+
+ n = unit_name_mangle(*name);
+ if (!n)
+ return log_oom();
+
+ p = unit_dbus_path_from_name(n);
+ if (!p)
+ return log_oom();
+
+ r = show_one(args[0], bus, p, show_properties, &new_line);
+ if (r != 0)
+ ret = r;
+
+ } else if (show_properties) {
+ _cleanup_free_ char *p = NULL;
+
+ /* Interpret as job id */
+ if (asprintf(&p, "/org/freedesktop/systemd1/job/%u", id) < 0)
+ return log_oom();
+
+ r = show_one(args[0], bus, p, show_properties, &new_line);
+ if (r != 0)
+ ret = r;
+
+ } else {
+ /* Interpret as PID */
+ r = show_one_by_pid(args[0], bus, id, &new_line);
+ if (r != 0)
+ ret = r;
+ }
+ }
+
+ return ret;
+}
+
+static int dump(DBusConnection *bus, char **args) {
+ _cleanup_free_ DBusMessage *reply = NULL;
+ DBusError error;
+ int r;
+ const char *text;
+
+ dbus_error_init(&error);
+
+ pager_open_if_enabled();
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "Dump",
+ &reply,
+ NULL,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+
+ if (!dbus_message_get_args(reply, &error,
+ DBUS_TYPE_STRING, &text,
+ DBUS_TYPE_INVALID)) {
+ log_error("Failed to parse reply: %s", bus_error_message(&error));
+ dbus_error_free(&error);
+ return -EIO;
+ }
+
+ fputs(text, stdout);
+ return 0;
+}
+
+static int snapshot(DBusConnection *bus, char **args) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ DBusError error;
+ int r;
+ dbus_bool_t cleanup = FALSE;
+ DBusMessageIter iter, sub;
+ const char
+ *path, *id,
+ *interface = "org.freedesktop.systemd1.Unit",
+ *property = "Id";
+ _cleanup_free_ char *n = NULL;
+
+ dbus_error_init(&error);
+
+ if (strv_length(args) > 1)
+ n = snapshot_name_mangle(args[1]);
+ else
+ n = strdup("");
+ if (!n)
+ return log_oom();
+
+ r = bus_method_call_with_reply (
+ bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "CreateSnapshot",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &n,
+ DBUS_TYPE_BOOLEAN, &cleanup,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+
+ if (!dbus_message_get_args(reply, &error,
+ DBUS_TYPE_OBJECT_PATH, &path,
+ DBUS_TYPE_INVALID)) {
+ log_error("Failed to parse reply: %s", bus_error_message(&error));
+ dbus_error_free(&error);
+ return -EIO;
+ }
+
+ dbus_message_unref(reply);
+ reply = NULL;
+
+ r = bus_method_call_with_reply (
+ bus,
+ "org.freedesktop.systemd1",
+ path,
+ "org.freedesktop.DBus.Properties",
+ "Get",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &interface,
+ DBUS_TYPE_STRING, &property,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+
+ if (!dbus_message_iter_init(reply, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_recurse(&iter, &sub);
+
+ if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_get_basic(&sub, &id);
+
+ if (!arg_quiet)
+ puts(id);
+
+ return 0;
+}
+
+static int delete_snapshot(DBusConnection *bus, char **args) {
+ char **name;
+
+ assert(args);
+
+ STRV_FOREACH(name, args+1) {
+ _cleanup_free_ char *n = NULL;
+ int r;
+
+ n = snapshot_name_mangle(*name);
+ if (!n)
+ return log_oom();
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "RemoveSnapshot",
+ NULL,
+ NULL,
+ DBUS_TYPE_STRING, &n,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static int daemon_reload(DBusConnection *bus, char **args) {
+ int r;
+ const char *method;
+ DBusError error;
+
+ if (arg_action == ACTION_RELOAD)
+ method = "Reload";
+ else if (arg_action == ACTION_REEXEC)
+ method = "Reexecute";
+ else {
+ assert(arg_action == ACTION_SYSTEMCTL);
+
+ method =
+ streq(args[0], "clear-jobs") ||
+ streq(args[0], "cancel") ? "ClearJobs" :
+ streq(args[0], "daemon-reexec") ? "Reexecute" :
+ streq(args[0], "reset-failed") ? "ResetFailed" :
+ streq(args[0], "halt") ? "Halt" :
+ streq(args[0], "poweroff") ? "PowerOff" :
+ streq(args[0], "reboot") ? "Reboot" :
+ streq(args[0], "kexec") ? "KExec" :
+ streq(args[0], "exit") ? "Exit" :
+ /* "daemon-reload" */ "Reload";
+ }
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ method,
+ NULL,
+ &error,
+ DBUS_TYPE_INVALID);
+
+ if (r == -ENOENT && arg_action != ACTION_SYSTEMCTL)
+ /* There's always a fallback possible for
+ * legacy actions. */
+ r = -EADDRNOTAVAIL;
+ else if (r == -ETIMEDOUT && streq(method, "Reexecute"))
+ /* On reexecution, we expect a disconnect, not
+ * a reply */
+ r = 0;
+ else if (r < 0)
+ log_error("Failed to issue method call: %s", bus_error_message(&error));
+
+ dbus_error_free(&error);
+ return r;
+}
+
+static int reset_failed(DBusConnection *bus, char **args) {
+ int r = 0;
+ char **name;
+
+ if (strv_length(args) <= 1)
+ return daemon_reload(bus, args);
+
+ STRV_FOREACH(name, args+1) {
+ _cleanup_free_ char *n;
+
+ n = unit_name_mangle(*name);
+ if (!n)
+ return log_oom();
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "ResetFailedUnit",
+ NULL,
+ NULL,
+ DBUS_TYPE_STRING, &n,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static int show_enviroment(DBusConnection *bus, char **args) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ DBusMessageIter iter, sub, sub2;
+ int r;
+ const char
+ *interface = "org.freedesktop.systemd1.Manager",
+ *property = "Environment";
+
+ pager_open_if_enabled();
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.DBus.Properties",
+ "Get",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &interface,
+ DBUS_TYPE_STRING, &property,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+
+ if (!dbus_message_iter_init(reply, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_recurse(&iter, &sub);
+
+ if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
+ dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_recurse(&sub, &sub2);
+
+ while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
+ const char *text;
+
+ if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_get_basic(&sub2, &text);
+ puts(text);
+
+ dbus_message_iter_next(&sub2);
+ }
+
+ return 0;
+}
+
+static int switch_root(DBusConnection *bus, char **args) {
+ unsigned l;
+ const char *root;
+ _cleanup_free_ char *init = NULL;
+
+ l = strv_length(args);
+ if (l < 2 || l > 3) {
+ log_error("Wrong number of arguments.");
+ return -EINVAL;
+ }
+
+ root = args[1];
+
+ if (l >= 3)
+ init = strdup(args[2]);
+ else {
+ parse_env_file("/proc/cmdline", WHITESPACE,
+ "init", &init,
+ NULL);
+
+ if (!init)
+ init = strdup("");
+ }
+ if (!init)
+ return log_oom();
+
+ log_debug("switching root - root: %s; init: %s", root, init);
+
+ return bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "SwitchRoot",
+ NULL,
+ NULL,
+ DBUS_TYPE_STRING, &root,
+ DBUS_TYPE_STRING, &init,
+ DBUS_TYPE_INVALID);
+}
+
+static int set_environment(DBusConnection *bus, char **args) {
+ _cleanup_dbus_message_unref_ DBusMessage *m = NULL, *reply = NULL;
+ DBusError error;
+ const char *method;
+ DBusMessageIter iter;
+ int r;
+
+ assert(bus);
+ assert(args);
+
+ dbus_error_init(&error);
+
+ method = streq(args[0], "set-environment")
+ ? "SetEnvironment"
+ : "UnsetEnvironment";
+
+ m = dbus_message_new_method_call(
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ method);
+ if (!m)
+ return log_oom();
+
+ dbus_message_iter_init_append(m, &iter);
+
+ r = bus_append_strv_iter(&iter, args + 1);
+ if (r < 0)
+ return log_oom();
+
+ reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
+ if (!reply) {
+ log_error("Failed to issue method call: %s", bus_error_message(&error));
+ dbus_error_free(&error);
+ return -EIO;
+ }
+
+ return 0;
+}
+
+static int enable_sysv_units(char **args) {
+ int r = 0;
+
+#if defined(HAVE_SYSV_COMPAT) && defined(HAVE_CHKCONFIG)
+ const char *verb = args[0];
+ unsigned f = 1, t = 1;
+ LookupPaths paths = {};
+
+ if (arg_scope != UNIT_FILE_SYSTEM)
+ return 0;
+
+ if (!streq(verb, "enable") &&
+ !streq(verb, "disable") &&
+ !streq(verb, "is-enabled"))
+ return 0;
+
+ /* Processes all SysV units, and reshuffles the array so that
+ * afterwards only the native units remain */
+
+ r = lookup_paths_init(&paths, SYSTEMD_SYSTEM, false, NULL, NULL, NULL);
+ if (r < 0)
+ return r;
+
+ r = 0;
+ for (f = 1; args[f]; f++) {
+ const char *name;
+ _cleanup_free_ char *p = NULL, *q = NULL;
+ bool found_native = false, found_sysv;
+ unsigned c = 1;
+ const char *argv[6] = { "/sbin/chkconfig", NULL, NULL, NULL, NULL };
+ char **k, *l;
+ int j;
+ pid_t pid;
+ siginfo_t status;
+
+ name = args[f];
+
+ if (!endswith(name, ".service"))
+ continue;
+
+ if (path_is_absolute(name))
+ continue;
+
+ STRV_FOREACH(k, paths.unit_path) {
+ if (!isempty(arg_root))
+ asprintf(&p, "%s/%s/%s", arg_root, *k, name);
+ else
+ asprintf(&p, "%s/%s", *k, name);
+
+ if (!p) {
+ r = log_oom();
+ goto finish;
+ }
+
+ found_native = access(p, F_OK) >= 0;
+ free(p);
+ p = NULL;
+
+ if (found_native)
+ break;
+ }
+
+ if (found_native)
+ continue;
+
+ if (!isempty(arg_root))
+ asprintf(&p, "%s/" SYSTEM_SYSVINIT_PATH "/%s", arg_root, name);
+ else
+ asprintf(&p, SYSTEM_SYSVINIT_PATH "/%s", name);
+ if (!p) {
+ r = log_oom();
+ goto finish;
+ }
+
+ p[strlen(p) - sizeof(".service") + 1] = 0;
+ found_sysv = access(p, F_OK) >= 0;
+
+ if (!found_sysv)
+ continue;
+
+ /* Mark this entry, so that we don't try enabling it as native unit */
+ args[f] = (char*) "";
+
+ log_info("%s is not a native service, redirecting to /sbin/chkconfig.", name);
+
+ if (!isempty(arg_root))
+ argv[c++] = q = strappend("--root=", arg_root);
+
+ argv[c++] = path_get_file_name(p);
+ argv[c++] =
+ streq(verb, "enable") ? "on" :
+ streq(verb, "disable") ? "off" : "--level=5";
+ argv[c] = NULL;
+
+ l = strv_join((char**)argv, " ");
+ if (!l) {
+ r = log_oom();
+ goto finish;
+ }
+
+ log_info("Executing %s", l);
+ free(l);
+
+ pid = fork();
+ if (pid < 0) {
+ log_error("Failed to fork: %m");
+ r = -errno;
+ goto finish;
+ } else if (pid == 0) {
+ /* Child */
+
+ execv(argv[0], (char**) argv);
+ _exit(EXIT_FAILURE);
+ }
+
+ j = wait_for_terminate(pid, &status);
+ if (j < 0) {
+ log_error("Failed to wait for child: %s", strerror(-r));
+ r = j;
+ goto finish;
+ }
+
+ if (status.si_code == CLD_EXITED) {
+ if (streq(verb, "is-enabled")) {
+ if (status.si_status == 0) {
+ if (!arg_quiet)
+ puts("enabled");
+ r = 1;
+ } else {
+ if (!arg_quiet)
+ puts("disabled");
+ }
+
+ } else if (status.si_status != 0) {
+ r = -EINVAL;
+ goto finish;
+ }
+ } else {
+ r = -EPROTO;
+ goto finish;
+ }
+ }
+
+finish:
+ lookup_paths_free(&paths);
+
+ /* Drop all SysV units */
+ for (f = 1, t = 1; args[f]; f++) {
+
+ if (isempty(args[f]))
+ continue;
+
+ args[t++] = args[f];
+ }
+
+ args[t] = NULL;
+
+#endif
+ return r;
+}
+
+static int mangle_names(char **original_names, char ***mangled_names) {
+ char **i, **l, **name;
+
+ l = new(char*, strv_length(original_names) + 1);
+ if (!l)
+ return log_oom();
+
+ i = l;
+ STRV_FOREACH(name, original_names) {
+
+ /* When enabling units qualified path names are OK,
+ * too, hence allow them explicitly. */
+
+ if (is_path(*name))
+ *i = strdup(*name);
+ else
+ *i = unit_name_mangle(*name);
+
+ if (!*i) {
+ strv_free(l);
+ return log_oom();
+ }
+
+ i++;
+ }
+
+ *i = NULL;
+ *mangled_names = l;
+
+ return 0;
+}
+
+static int enable_unit(DBusConnection *bus, char **args) {
+ const char *verb = args[0];
+ UnitFileChange *changes = NULL;
+ unsigned n_changes = 0, i;
+ int carries_install_info = -1;
+ _cleanup_dbus_message_unref_ DBusMessage *m = NULL, *reply = NULL;
+ int r;
+ _cleanup_dbus_error_free_ DBusError error;
+ _cleanup_strv_free_ char **mangled_names = NULL;
+
+ dbus_error_init(&error);
+
+ r = enable_sysv_units(args);
+ if (r < 0)
+ return r;
+
+ if (!args[1])
+ return 0;
+
+ if (!bus || avoid_bus()) {
+ if (streq(verb, "enable")) {
+ r = unit_file_enable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
+ carries_install_info = r;
+ } else if (streq(verb, "disable"))
+ r = unit_file_disable(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
+ else if (streq(verb, "reenable")) {
+ r = unit_file_reenable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
+ carries_install_info = r;
+ } else if (streq(verb, "link"))
+ r = unit_file_link(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
+ else if (streq(verb, "preset")) {
+ r = unit_file_preset(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
+ carries_install_info = r;
+ } else if (streq(verb, "mask"))
+ r = unit_file_mask(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
+ else if (streq(verb, "unmask"))
+ r = unit_file_unmask(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
+ else
+ assert_not_reached("Unknown verb");
+
+ if (r < 0) {
+ log_error("Operation failed: %s", strerror(-r));
+ goto finish;
+ }
+
+ if (!arg_quiet) {
+ for (i = 0; i < n_changes; i++) {
+ if (changes[i].type == UNIT_FILE_SYMLINK)
+ log_info("ln -s '%s' '%s'", changes[i].source, changes[i].path);
+ else
+ log_info("rm '%s'", changes[i].path);
+ }
+ }
+
+ r = 0;
+ } else {
+ const char *method;
+ bool send_force = true, expect_carries_install_info = false;
+ dbus_bool_t a, b;
+ DBusMessageIter iter, sub, sub2;
+
+ if (streq(verb, "enable")) {
+ method = "EnableUnitFiles";
+ expect_carries_install_info = true;
+ } else if (streq(verb, "disable")) {
+ method = "DisableUnitFiles";
+ send_force = false;
+ } else if (streq(verb, "reenable")) {
+ method = "ReenableUnitFiles";
+ expect_carries_install_info = true;
+ } else if (streq(verb, "link"))
+ method = "LinkUnitFiles";
+ else if (streq(verb, "preset")) {
+ method = "PresetUnitFiles";
+ expect_carries_install_info = true;
+ } else if (streq(verb, "mask"))
+ method = "MaskUnitFiles";
+ else if (streq(verb, "unmask")) {
+ method = "UnmaskUnitFiles";
+ send_force = false;
+ } else
+ assert_not_reached("Unknown verb");
+
+ m = dbus_message_new_method_call(
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ method);
+ if (!m) {
+ r = log_oom();
+ goto finish;
+ }
+
+ dbus_message_iter_init_append(m, &iter);
+
+ r = mangle_names(args+1, &mangled_names);
+ if(r < 0)
+ goto finish;
+
+ r = bus_append_strv_iter(&iter, mangled_names);
+ if (r < 0) {
+ log_error("Failed to append unit files.");
+ goto finish;
+ }
+
+ a = arg_runtime;
+ if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &a)) {
+ log_error("Failed to append runtime boolean.");
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ if (send_force) {
+ b = arg_force;
+
+ if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b)) {
+ log_error("Failed to append force boolean.");
+ r = -ENOMEM;
+ goto finish;
+ }
+ }
+
+ reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
+ if (!reply) {
+ log_error("Failed to issue method call: %s", bus_error_message(&error));
+ r = -EIO;
+ goto finish;
+ }
+
+ if (!dbus_message_iter_init(reply, &iter)) {
+ log_error("Failed to initialize iterator.");
+ goto finish;
+ }
+
+ if (expect_carries_install_info) {
+ r = bus_iter_get_basic_and_next(&iter, DBUS_TYPE_BOOLEAN, &b, true);
+ if (r < 0) {
+ log_error("Failed to parse reply.");
+ goto finish;
+ }
+
+ carries_install_info = b;
+ }
+
+ if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
+ dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
+ log_error("Failed to parse reply.");
+ r = -EIO;
+ goto finish;
+ }
+
+ dbus_message_iter_recurse(&iter, &sub);
+ while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ const char *type, *path, *source;
+
+ if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
+ log_error("Failed to parse reply.");
+ r = -EIO;
+ goto finish;
+ }
+
+ dbus_message_iter_recurse(&sub, &sub2);
+
+ if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0 ||
+ bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &source, false) < 0) {
+ log_error("Failed to parse reply.");
+ r = -EIO;
+ goto finish;
+ }
+
+ if (!arg_quiet) {
+ if (streq(type, "symlink"))
+ log_info("ln -s '%s' '%s'", source, path);
+ else
+ log_info("rm '%s'", path);
+ }
+
+ dbus_message_iter_next(&sub);
+ }
+
+ /* Try to reload if enabeld */
+ if (!arg_no_reload)
+ r = daemon_reload(bus, args);
+ }
+
+ if (carries_install_info == 0)
+ log_warning("The unit files have no [Install] section. They are not meant to be enabled\n"
+ "using systemctl.\n"
+ "Possible reasons for having this kind of units are:\n"
+ "1) A unit may be statically enabled by being symlinked from another unit's\n"
+ " .wants/ or .requires/ directory.\n"
+ "2) A unit's purpose may be to act as a helper for some other unit which has\n"
+ " a requirement dependency on it.\n"
+ "3) A unit may be started when needed via activation (socket, path, timer,\n"
+ " D-Bus, udev, scripted systemctl call, ...).\n");
+
+finish:
+ unit_file_changes_free(changes, n_changes);
+
+ return r;
+}
+
+static int unit_is_enabled(DBusConnection *bus, char **args) {
+ _cleanup_dbus_error_free_ DBusError error;
+ int r;
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ bool enabled;
+ char **name;
+ char *n;
+
+ dbus_error_init(&error);
+
+ r = enable_sysv_units(args);
+ if (r < 0)
+ return r;
+
+ enabled = r > 0;
+
+ if (!bus || avoid_bus()) {
+
+ STRV_FOREACH(name, args+1) {
+ UnitFileState state;
+
+ n = unit_name_mangle(*name);
+ if (!n)
+ return log_oom();
+
+ state = unit_file_get_state(arg_scope, arg_root, n);
+
+ free(n);
+
+ if (state < 0)
+ return state;
+
+ if (state == UNIT_FILE_ENABLED ||
+ state == UNIT_FILE_ENABLED_RUNTIME ||
+ state == UNIT_FILE_STATIC)
+ enabled = true;
+
+ if (!arg_quiet)
+ puts(unit_file_state_to_string(state));
+ }
+
+ } else {
+ STRV_FOREACH(name, args+1) {
+ const char *s;
+
+ n = unit_name_mangle(*name);
+ if (!n)
+ return log_oom();
+
+ r = bus_method_call_with_reply (
+ bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "GetUnitFileState",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &n,
+ DBUS_TYPE_INVALID);
+
+ free(n);
+
+ if (r)
+ return r;
+
+ if (!dbus_message_get_args(reply, &error,
+ DBUS_TYPE_STRING, &s,
+ DBUS_TYPE_INVALID)) {
+ log_error("Failed to parse reply: %s", bus_error_message(&error));
+ return -EIO;
+ }
+
+ dbus_message_unref(reply);
+ reply = NULL;
+
+ if (streq(s, "enabled") ||
+ streq(s, "enabled-runtime") ||
+ streq(s, "static"))
+ enabled = true;
+
+ if (!arg_quiet)
+ puts(s);
+ }
+ }
+
+ return enabled ? 0 : 1;
+}
+
+static int systemctl_help(void) {
+
+ pager_open_if_enabled();
+
+ printf("%s [OPTIONS...] {COMMAND} ...\n\n"
+ "Query or send control commands to the systemd manager.\n\n"
+ " -h --help Show this help\n"
+ " --version Show package version\n"
+ " -t --type=TYPE List only units of a particular type\n"
+ " -p --property=NAME Show only properties by this name\n"
+ " -a --all Show all loaded units/properties, including dead/empty\n"
+ " ones. To list all units installed on the system, use\n"
+ " the 'list-unit-files' command instead.\n"
+ " --reverse Show reverse dependencies with 'list-dependencies'\n"
+ " --failed Show only failed units\n"
+ " --full Don't ellipsize unit names on output\n"
+ " --fail When queueing a new job, fail if conflicting jobs are\n"
+ " pending\n"
+ " --irreversible Create jobs which cannot be implicitly cancelled\n"
+ " --show-types When showing sockets, explicitly show their type\n"
+ " --ignore-dependencies\n"
+ " When queueing a new job, ignore all its dependencies\n"
+ " -i --ignore-inhibitors\n"
+ " When shutting down or sleeping, ignore inhibitors\n"
+ " --kill-who=WHO Who to send signal to\n"
+ " -s --signal=SIGNAL Which signal to send\n"
+ " -H --host=[USER@]HOST\n"
+ " Show information for remote host\n"
+ " -P --privileged Acquire privileges before execution\n"
+ " -q --quiet Suppress output\n"
+ " --no-block Do not wait until operation finished\n"
+ " --no-wall Don't send wall message before halt/power-off/reboot\n"
+ " --no-reload When enabling/disabling unit files, don't reload daemon\n"
+ " configuration\n"
+ " --no-legend Do not print a legend (column headers and hints)\n"
+ " --no-pager Do not pipe output into a pager\n"
+ " --no-ask-password\n"
+ " Do not ask for system passwords\n"
+ " --system Connect to system manager\n"
+ " --user Connect to user service manager\n"
+ " --global Enable/disable unit files globally\n"
+ " -f --force When enabling unit files, override existing symlinks\n"
+ " When shutting down, execute action immediately\n"
+ " --root=PATH Enable unit files in the specified root directory\n"
+ " --runtime Enable unit files only temporarily until next reboot\n"
+ " -n --lines=INTEGER Journal entries to show\n"
+ " -o --output=STRING Change journal output mode (short, short-monotonic,\n"
+ " verbose, export, json, json-pretty, json-sse, cat)\n\n"
+ "Unit Commands:\n"
+ " list-units List loaded units\n"
+ " start [NAME...] Start (activate) one or more units\n"
+ " stop [NAME...] Stop (deactivate) one or more units\n"
+ " reload [NAME...] Reload one or more units\n"
+ " restart [NAME...] Start or restart one or more units\n"
+ " try-restart [NAME...] Restart one or more units if active\n"
+ " reload-or-restart [NAME...] Reload one or more units if possible,\n"
+ " otherwise start or restart\n"
+ " reload-or-try-restart [NAME...] Reload one or more units if possible,\n"
+ " otherwise restart if active\n"
+ " isolate [NAME] Start one unit and stop all others\n"
+ " kill [NAME...] Send signal to processes of a unit\n"
+ " is-active [NAME...] Check whether units are active\n"
+ " is-failed [NAME...] Check whether units are failed\n"
+ " status [NAME...|PID...] Show runtime status of one or more units\n"
+ " show [NAME...|JOB...] Show properties of one or more\n"
+ " units/jobs or the manager\n"
+ " help [NAME...|PID...] Show manual for one or more units\n"
+ " reset-failed [NAME...] Reset failed state for all, one, or more\n"
+ " units\n"
+ " get-cgroup-attr [NAME] [ATTR] ...\n"
+ " Get control group attrubute\n"
+ " set-cgroup-attr [NAME] [ATTR] [VALUE] ...\n"
+ " Set control group attribute\n"
+ " unset-cgroup-attr [NAME] [ATTR...]\n"
+ " Unset control group attribute\n"
+ " set-cgroup [NAME] [CGROUP...] Add unit to a control group\n"
+ " unset-cgroup [NAME] [CGROUP...] Remove unit from a control group\n"
+ " load [NAME...] Load one or more units\n"
+ " list-dependencies [NAME] Recursively show units which are required\n"
+ " or wanted by this unit or by which this\n"
+ " unit is required or wanted\n\n"
+ "Unit File Commands:\n"
+ " list-unit-files List installed unit files\n"
+ " enable [NAME...] Enable one or more unit files\n"
+ " disable [NAME...] Disable one or more unit files\n"
+ " reenable [NAME...] Reenable one or more unit files\n"
+ " preset [NAME...] Enable/disable one or more unit files\n"
+ " based on preset configuration\n"
+ " mask [NAME...] Mask one or more units\n"
+ " unmask [NAME...] Unmask one or more units\n"
+ " link [PATH...] Link one or more units files into\n"
+ " the search path\n"
+ " is-enabled [NAME...] Check whether unit files are enabled\n\n"
+ "Job Commands:\n"
+ " list-jobs List jobs\n"
+ " cancel [JOB...] Cancel all, one, or more jobs\n\n"
+ "Status Commands:\n"
+ " dump Dump server status\n"
+ "Snapshot Commands:\n"
+ " snapshot [NAME] Create a snapshot\n"
+ " delete [NAME...] Remove one or more snapshots\n\n"
+ "Environment Commands:\n"
+ " show-environment Dump environment\n"
+ " set-environment [NAME=VALUE...] Set one or more environment variables\n"
+ " unset-environment [NAME...] Unset one or more environment variables\n\n"
+ "Manager Lifecycle Commands:\n"
+ " daemon-reload Reload systemd manager configuration\n"
+ " daemon-reexec Reexecute systemd manager\n\n"
+ "System Commands:\n"
+ " default Enter system default mode\n"
+ " rescue Enter system rescue mode\n"
+ " emergency Enter system emergency mode\n"
+ " halt Shut down and halt the system\n"
+ " poweroff Shut down and power-off the system\n"
+ " reboot Shut down and reboot the system\n"
+ " kexec Shut down and reboot the system with kexec\n"
+ " exit Request user instance exit\n"
+ " switch-root [ROOT] [INIT] Change to a different root file system\n"
+ " suspend Suspend the system\n"
+ " hibernate Hibernate the system\n"
+ " hybrid-sleep Hibernate and suspend the system\n",
+ program_invocation_short_name);
+
+ return 0;
+}
+
+static int halt_help(void) {
+
+ printf("%s [OPTIONS...]\n\n"
+ "%s the system.\n\n"
+ " --help Show this help\n"
+ " --halt Halt the machine\n"
+ " -p --poweroff Switch off the machine\n"
+ " --reboot Reboot the machine\n"
+ " -f --force Force immediate halt/power-off/reboot\n"
+ " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
+ " -d --no-wtmp Don't write wtmp record\n"
+ " --no-wall Don't send wall message before halt/power-off/reboot\n",
+ program_invocation_short_name,
+ arg_action == ACTION_REBOOT ? "Reboot" :
+ arg_action == ACTION_POWEROFF ? "Power off" :
+ "Halt");
+
+ return 0;
+}
+
+static int shutdown_help(void) {
+
+ printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
+ "Shut down the system.\n\n"
+ " --help Show this help\n"
+ " -H --halt Halt the machine\n"
+ " -P --poweroff Power-off the machine\n"
+ " -r --reboot Reboot the machine\n"
+ " -h Equivalent to --poweroff, overridden by --halt\n"
+ " -k Don't halt/power-off/reboot, just send warnings\n"
+ " --no-wall Don't send wall message before halt/power-off/reboot\n"
+ " -c Cancel a pending shutdown\n",
+ program_invocation_short_name);
+
+ return 0;
+}
+
+static int telinit_help(void) {
+
+ printf("%s [OPTIONS...] {COMMAND}\n\n"
+ "Send control commands to the init daemon.\n\n"
+ " --help Show this help\n"
+ " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
+ "Commands:\n"
+ " 0 Power-off the machine\n"
+ " 6 Reboot the machine\n"
+ " 2, 3, 4, 5 Start runlevelX.target unit\n"
+ " 1, s, S Enter rescue mode\n"
+ " q, Q Reload init daemon configuration\n"
+ " u, U Reexecute init daemon\n",
+ program_invocation_short_name);
+
+ return 0;
+}
+
+static int runlevel_help(void) {
+
+ printf("%s [OPTIONS...]\n\n"
+ "Prints the previous and current runlevel of the init system.\n\n"
+ " --help Show this help\n",
+ program_invocation_short_name);
+
+ return 0;
+}
+
+static int help_types(void) {
+ int i;
+ const char *t;
+
+ puts("Available unit types:");
+ for(i = 0; i < _UNIT_TYPE_MAX; i++) {
+ t = unit_type_to_string(i);
+ if (t)
+ puts(t);
+ }
+
+ puts("\nAvailable unit load states: ");
+ for(i = 0; i < _UNIT_LOAD_STATE_MAX; i++) {
+ t = unit_load_state_to_string(i);
+ if (t)
+ puts(t);
+ }
+
+ return 0;
+}
+
+static int systemctl_parse_argv(int argc, char *argv[]) {
+
+ enum {
+ ARG_FAIL = 0x100,
+ ARG_REVERSE,
+ ARG_AFTER,
+ ARG_BEFORE,
+ ARG_SHOW_TYPES,
+ ARG_IRREVERSIBLE,
+ ARG_IGNORE_DEPENDENCIES,
+ ARG_VERSION,
+ ARG_USER,
+ ARG_SYSTEM,
+ ARG_GLOBAL,
+ ARG_NO_BLOCK,
+ ARG_NO_LEGEND,
+ ARG_NO_PAGER,
+ ARG_NO_WALL,
+ ARG_ROOT,
+ ARG_FULL,
+ ARG_NO_RELOAD,
+ ARG_KILL_WHO,
+ ARG_NO_ASK_PASSWORD,
+ ARG_FAILED,
+ ARG_RUNTIME,
+ ARG_FORCE,
+ ARG_PLAIN
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "version", no_argument, NULL, ARG_VERSION },
+ { "type", required_argument, NULL, 't' },
+ { "property", required_argument, NULL, 'p' },
+ { "all", no_argument, NULL, 'a' },
+ { "reverse", no_argument, NULL, ARG_REVERSE },
+ { "after", no_argument, NULL, ARG_AFTER },
+ { "before", no_argument, NULL, ARG_BEFORE },
+ { "show-types", no_argument, NULL, ARG_SHOW_TYPES },
+ { "failed", no_argument, NULL, ARG_FAILED },
+ { "full", no_argument, NULL, ARG_FULL },
+ { "fail", no_argument, NULL, ARG_FAIL },
+ { "irreversible", no_argument, NULL, ARG_IRREVERSIBLE },
+ { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
+ { "ignore-inhibitors", no_argument, NULL, 'i' },
+ { "user", no_argument, NULL, ARG_USER },
+ { "system", no_argument, NULL, ARG_SYSTEM },
+ { "global", no_argument, NULL, ARG_GLOBAL },
+ { "no-block", no_argument, NULL, ARG_NO_BLOCK },
+ { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
+ { "no-pager", no_argument, NULL, ARG_NO_PAGER },
+ { "no-wall", no_argument, NULL, ARG_NO_WALL },
+ { "quiet", no_argument, NULL, 'q' },
+ { "root", required_argument, NULL, ARG_ROOT },
+ { "force", no_argument, NULL, ARG_FORCE },
+ { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
+ { "kill-who", required_argument, NULL, ARG_KILL_WHO },
+ { "signal", required_argument, NULL, 's' },
+ { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
+ { "host", required_argument, NULL, 'H' },
+ { "privileged",no_argument, NULL, 'P' },
+ { "runtime", no_argument, NULL, ARG_RUNTIME },
+ { "lines", required_argument, NULL, 'n' },
+ { "output", required_argument, NULL, 'o' },
+ { "plain", no_argument, NULL, ARG_PLAIN },
+ { NULL, 0, NULL, 0 }
+ };
+
+ int c;
+
+ assert(argc >= 0);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "ht:p:aqfs:H:Pn:o:i", options, NULL)) >= 0) {
+
+ switch (c) {
+
+ case 'h':
+ systemctl_help();
+ return 0;
+
+ case ARG_VERSION:
+ puts(PACKAGE_STRING);
+ puts(SYSTEMD_FEATURES);
+ return 0;
+
+ case 't': {
+ char *word, *state;
+ size_t size;
+
+ FOREACH_WORD_SEPARATOR(word, size, optarg, ",", state) {
+ _cleanup_free_ char *type;
+
+ type = strndup(word, size);
+ if (!type)
+ return -ENOMEM;
+
+ if (streq(type, "help")) {
+ help_types();
+ return 0;
+ }
+
+ if (unit_type_from_string(type) >= 0) {
+ if (strv_push(&arg_types, type))
+ return log_oom();
+ type = NULL;
+ continue;
+ }
+
+ if (unit_load_state_from_string(optarg) >= 0) {
+ if (strv_push(&arg_load_states, type))
+ return log_oom();
+ type = NULL;
+ continue;
+ }
+
+ log_error("Unknown unit type or load state '%s'.", type);
+ log_info("Use -t help to see a list of allowed values.");
+ return -EINVAL;
+ }
+
+ break;
+ }
+
+ case 'p': {
+ /* Make sure that if the empty property list
+ was specified, we won't show any properties. */
+ if (isempty(optarg) && !arg_properties) {
+ arg_properties = strv_new(NULL, NULL);
+ if (!arg_properties)
+ return log_oom();
+ } else {
+ char *word, *state;
+ size_t size;
+
+ FOREACH_WORD_SEPARATOR(word, size, optarg, ",", state) {
+ char *prop;
+
+ prop = strndup(word, size);
+ if (!prop)
+ return log_oom();
+
+ if (strv_push(&arg_properties, prop)) {
+ free(prop);
+ return log_oom();
+ }
+ }
+ }
+
+ /* If the user asked for a particular
+ * property, show it to him, even if it is
+ * empty. */
+ arg_all = true;
+
+ break;
+ }
+
+ case 'a':
+ arg_all = true;
+ break;
+
+ case ARG_REVERSE:
+ arg_dependency = DEPENDENCY_REVERSE;
+ break;
+
+ case ARG_AFTER:
+ arg_dependency = DEPENDENCY_AFTER;
+ break;
+
+ case ARG_BEFORE:
+ arg_dependency = DEPENDENCY_BEFORE;
+ break;
+
+ case ARG_SHOW_TYPES:
+ arg_show_types = true;
+ break;
+
+ case ARG_FAIL:
+ arg_job_mode = "fail";
+ break;
+
+ case ARG_IRREVERSIBLE:
+ arg_job_mode = "replace-irreversibly";
+ break;
+
+ case ARG_IGNORE_DEPENDENCIES:
+ arg_job_mode = "ignore-dependencies";
+ break;
+
+ case ARG_USER:
+ arg_scope = UNIT_FILE_USER;
+ break;
+
+ case ARG_SYSTEM:
+ arg_scope = UNIT_FILE_SYSTEM;
+ break;
+
+ case ARG_GLOBAL:
+ arg_scope = UNIT_FILE_GLOBAL;
+ break;
+
+ case ARG_NO_BLOCK:
+ arg_no_block = true;
+ break;
+
+ case ARG_NO_LEGEND:
+ arg_no_legend = true;
+ break;
+
+ case ARG_NO_PAGER:
+ arg_no_pager = true;
+ break;
+
+ case ARG_NO_WALL:
+ arg_no_wall = true;
+ break;
+
+ case ARG_ROOT:
+ arg_root = optarg;
+ break;
+
+ case ARG_FULL:
+ arg_full = true;
+ break;
+
+ case ARG_FAILED:
+ arg_failed = true;
+ break;
+
+ case 'q':
+ arg_quiet = true;
+ break;
+
+ case ARG_FORCE:
+ arg_force ++;
+ break;
+
+ case 'f':
+ arg_force ++;
+ break;
+
+ case ARG_NO_RELOAD:
+ arg_no_reload = true;
+ break;
+
+ case ARG_KILL_WHO:
+ arg_kill_who = optarg;
+ break;
+
+ case 's':
+ if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
+ log_error("Failed to parse signal string %s.", optarg);
+ return -EINVAL;
+ }
+ break;
+
+ case ARG_NO_ASK_PASSWORD:
+ arg_ask_password = false;
+ break;
+
+ case 'P':
+ arg_transport = TRANSPORT_POLKIT;
+ break;
+
+ case 'H':
+ arg_transport = TRANSPORT_SSH;
+ arg_host = optarg;
+ break;
+
+ case ARG_RUNTIME:
+ arg_runtime = true;
+ break;
+
+ case 'n':
+ if (safe_atou(optarg, &arg_lines) < 0) {
+ log_error("Failed to parse lines '%s'", optarg);
+ return -EINVAL;
+ }
+ break;
+
+ case 'o':
+ arg_output = output_mode_from_string(optarg);
+ if (arg_output < 0) {
+ log_error("Unknown output '%s'.", optarg);
+ return -EINVAL;
+ }
+ break;
+
+ case 'i':
+ arg_ignore_inhibitors = true;
+ break;
+
+ case ARG_PLAIN:
+ arg_plain = true;
+ break;
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ log_error("Unknown option code '%c'.", c);
+ return -EINVAL;
+ }
+ }
+
+ if (arg_transport != TRANSPORT_NORMAL && arg_scope != UNIT_FILE_SYSTEM) {
+ log_error("Cannot access user instance remotely.");
+ return -EINVAL;
+ }
+
+ return 1;
+}
+
+static int halt_parse_argv(int argc, char *argv[]) {
+
+ enum {
+ ARG_HELP = 0x100,
+ ARG_HALT,
+ ARG_REBOOT,
+ ARG_NO_WALL
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, ARG_HELP },
+ { "halt", no_argument, NULL, ARG_HALT },
+ { "poweroff", no_argument, NULL, 'p' },
+ { "reboot", no_argument, NULL, ARG_REBOOT },
+ { "force", no_argument, NULL, 'f' },
+ { "wtmp-only", no_argument, NULL, 'w' },
+ { "no-wtmp", no_argument, NULL, 'd' },
+ { "no-wall", no_argument, NULL, ARG_NO_WALL },
+ { NULL, 0, NULL, 0 }
+ };
+
+ int c, runlevel;
+
+ assert(argc >= 0);
+ assert(argv);
+
+ if (utmp_get_runlevel(&runlevel, NULL) >= 0)
+ if (runlevel == '0' || runlevel == '6')
+ arg_force = 2;
+
+ while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
+ switch (c) {
+
+ case ARG_HELP:
+ halt_help();
+ return 0;
+
+ case ARG_HALT:
+ arg_action = ACTION_HALT;
+ break;
+
+ case 'p':
+ if (arg_action != ACTION_REBOOT)
+ arg_action = ACTION_POWEROFF;
+ break;
+
+ case ARG_REBOOT:
+ arg_action = ACTION_REBOOT;
+ break;
+
+ case 'f':
+ arg_force = 2;
+ break;
+
+ case 'w':
+ arg_dry = true;
+ break;
+
+ case 'd':
+ arg_no_wtmp = true;
+ break;
+
+ case ARG_NO_WALL:
+ arg_no_wall = true;
+ break;
+
+ case 'i':
+ case 'h':
+ case 'n':
+ /* Compatibility nops */
+ break;
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ log_error("Unknown option code '%c'.", c);
+ return -EINVAL;
+ }
+ }
+
+ if (optind < argc) {
+ log_error("Too many arguments.");
+ return -EINVAL;
+ }
+
+ return 1;
+}
+
+static int parse_time_spec(const char *t, usec_t *_u) {
+ assert(t);
+ assert(_u);
+
+ if (streq(t, "now"))
+ *_u = 0;
+ else if (!strchr(t, ':')) {
+ uint64_t u;
+
+ if (safe_atou64(t, &u) < 0)
+ return -EINVAL;
+
+ *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
+ } else {
+ char *e = NULL;
+ long hour, minute;
+ struct tm tm = {};
+ time_t s;
+ usec_t n;
+
+ errno = 0;
+ hour = strtol(t, &e, 10);
+ if (errno > 0 || *e != ':' || hour < 0 || hour > 23)
+ return -EINVAL;
+
+ minute = strtol(e+1, &e, 10);
+ if (errno > 0 || *e != 0 || minute < 0 || minute > 59)
+ return -EINVAL;
+
+ n = now(CLOCK_REALTIME);
+ s = (time_t) (n / USEC_PER_SEC);
+
+ assert_se(localtime_r(&s, &tm));
+
+ tm.tm_hour = (int) hour;
+ tm.tm_min = (int) minute;
+ tm.tm_sec = 0;
+
+ assert_se(s = mktime(&tm));
+
+ *_u = (usec_t) s * USEC_PER_SEC;
+
+ while (*_u <= n)
+ *_u += USEC_PER_DAY;
+ }
+
+ return 0;
+}
+
+static int shutdown_parse_argv(int argc, char *argv[]) {
+
+ enum {
+ ARG_HELP = 0x100,
+ ARG_NO_WALL
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, ARG_HELP },
+ { "halt", no_argument, NULL, 'H' },
+ { "poweroff", no_argument, NULL, 'P' },
+ { "reboot", no_argument, NULL, 'r' },
+ { "kexec", no_argument, NULL, 'K' }, /* not documented extension */
+ { "no-wall", no_argument, NULL, ARG_NO_WALL },
+ { NULL, 0, NULL, 0 }
+ };
+
+ int c, r;
+
+ assert(argc >= 0);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
+ switch (c) {
+
+ case ARG_HELP:
+ shutdown_help();
+ return 0;
+
+ case 'H':
+ arg_action = ACTION_HALT;
+ break;
+
+ case 'P':
+ arg_action = ACTION_POWEROFF;
+ break;
+
+ case 'r':
+ if (kexec_loaded())
+ arg_action = ACTION_KEXEC;
+ else
+ arg_action = ACTION_REBOOT;
+ break;
+
+ case 'K':
+ arg_action = ACTION_KEXEC;
+ break;
+
+ case 'h':
+ if (arg_action != ACTION_HALT)
+ arg_action = ACTION_POWEROFF;
+ break;
+
+ case 'k':
+ arg_dry = true;
+ break;
+
+ case ARG_NO_WALL:
+ arg_no_wall = true;
+ break;
+
+ case 't':
+ case 'a':
+ /* Compatibility nops */
+ break;
+
+ case 'c':
+ arg_action = ACTION_CANCEL_SHUTDOWN;
+ break;
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ log_error("Unknown option code '%c'.", c);
+ return -EINVAL;
+ }
+ }
+
+ if (argc > optind && arg_action != ACTION_CANCEL_SHUTDOWN) {
+ r = parse_time_spec(argv[optind], &arg_when);
+ if (r < 0) {
+ log_error("Failed to parse time specification: %s", argv[optind]);
+ return r;
+ }
+ } else
+ arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
+
+ if (argc > optind && arg_action == ACTION_CANCEL_SHUTDOWN)
+ /* No time argument for shutdown cancel */
+ arg_wall = argv + optind;
+ else if (argc > optind + 1)
+ /* We skip the time argument */
+ arg_wall = argv + optind + 1;
+
+ optind = argc;
+
+ return 1;
+}
+
+static int telinit_parse_argv(int argc, char *argv[]) {
+
+ enum {
+ ARG_HELP = 0x100,
+ ARG_NO_WALL
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, ARG_HELP },
+ { "no-wall", no_argument, NULL, ARG_NO_WALL },
+ { NULL, 0, NULL, 0 }
+ };
+
+ static const struct {
+ char from;
+ enum action to;
+ } table[] = {
+ { '0', ACTION_POWEROFF },
+ { '6', ACTION_REBOOT },
+ { '1', ACTION_RESCUE },
+ { '2', ACTION_RUNLEVEL2 },
+ { '3', ACTION_RUNLEVEL3 },
+ { '4', ACTION_RUNLEVEL4 },
+ { '5', ACTION_RUNLEVEL5 },
+ { 's', ACTION_RESCUE },
+ { 'S', ACTION_RESCUE },
+ { 'q', ACTION_RELOAD },
+ { 'Q', ACTION_RELOAD },
+ { 'u', ACTION_REEXEC },
+ { 'U', ACTION_REEXEC }
+ };
+
+ unsigned i;
+ int c;
+
+ assert(argc >= 0);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
+ switch (c) {
+
+ case ARG_HELP:
+ telinit_help();
+ return 0;
+
+ case ARG_NO_WALL:
+ arg_no_wall = true;
+ break;
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ log_error("Unknown option code '%c'.", c);
+ return -EINVAL;
+ }
+ }
+
+ if (optind >= argc) {
+ telinit_help();
+ return -EINVAL;
+ }
+
+ if (optind + 1 < argc) {
+ log_error("Too many arguments.");
+ return -EINVAL;
+ }
+
+ if (strlen(argv[optind]) != 1) {
+ log_error("Expected single character argument.");
+ return -EINVAL;
+ }
+
+ for (i = 0; i < ELEMENTSOF(table); i++)
+ if (table[i].from == argv[optind][0])
+ break;
+
+ if (i >= ELEMENTSOF(table)) {
+ log_error("Unknown command '%s'.", argv[optind]);
+ return -EINVAL;
+ }
+
+ arg_action = table[i].to;
+
+ optind ++;
+
+ return 1;
+}
+
+static int runlevel_parse_argv(int argc, char *argv[]) {
+
+ enum {
+ ARG_HELP = 0x100,
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, ARG_HELP },
+ { NULL, 0, NULL, 0 }
+ };
+
+ int c;
+
+ assert(argc >= 0);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
+ switch (c) {
+
+ case ARG_HELP:
+ runlevel_help();
+ return 0;
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ log_error("Unknown option code '%c'.", c);
+ return -EINVAL;
+ }
+ }
+
+ if (optind < argc) {
+ log_error("Too many arguments.");
+ return -EINVAL;
+ }
+
+ return 1;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+ assert(argc >= 0);
+ assert(argv);
+
+ if (program_invocation_short_name) {
+
+ if (strstr(program_invocation_short_name, "halt")) {
+ arg_action = ACTION_HALT;
+ return halt_parse_argv(argc, argv);
+ } else if (strstr(program_invocation_short_name, "poweroff")) {
+ arg_action = ACTION_POWEROFF;
+ return halt_parse_argv(argc, argv);
+ } else if (strstr(program_invocation_short_name, "reboot")) {
+ if (kexec_loaded())
+ arg_action = ACTION_KEXEC;
+ else
+ arg_action = ACTION_REBOOT;
+ return halt_parse_argv(argc, argv);
+ } else if (strstr(program_invocation_short_name, "shutdown")) {
+ arg_action = ACTION_POWEROFF;
+ return shutdown_parse_argv(argc, argv);
+ } else if (strstr(program_invocation_short_name, "init")) {
+
+ if (sd_booted() > 0) {
+ arg_action = ACTION_INVALID;
+ return telinit_parse_argv(argc, argv);
+ } else {
+ /* Hmm, so some other init system is
+ * running, we need to forward this
+ * request to it. For now we simply
+ * guess that it is Upstart. */
+
+ execv(TELINIT, argv);
+
+ log_error("Couldn't find an alternative telinit implementation to spawn.");
+ return -EIO;
+ }
+
+ } else if (strstr(program_invocation_short_name, "runlevel")) {
+ arg_action = ACTION_RUNLEVEL;
+ return runlevel_parse_argv(argc, argv);
+ }
+ }
+
+ arg_action = ACTION_SYSTEMCTL;
+ return systemctl_parse_argv(argc, argv);
+}
+
+_pure_ static int action_to_runlevel(void) {
+
+ static const char table[_ACTION_MAX] = {
+ [ACTION_HALT] = '0',
+ [ACTION_POWEROFF] = '0',
+ [ACTION_REBOOT] = '6',
+ [ACTION_RUNLEVEL2] = '2',
+ [ACTION_RUNLEVEL3] = '3',
+ [ACTION_RUNLEVEL4] = '4',
+ [ACTION_RUNLEVEL5] = '5',
+ [ACTION_RESCUE] = '1'
+ };
+
+ assert(arg_action < _ACTION_MAX);
+
+ return table[arg_action];
+}
+
+static int talk_upstart(void) {
+ _cleanup_dbus_message_unref_ DBusMessage *m = NULL, *reply = NULL;
+ _cleanup_dbus_error_free_ DBusError error;
+ int previous, rl, r;
+ char
+ env1_buf[] = "RUNLEVEL=X",
+ env2_buf[] = "PREVLEVEL=X";
+ char *env1 = env1_buf, *env2 = env2_buf;
+ const char *emit = "runlevel";
+ dbus_bool_t b_false = FALSE;
+ DBusMessageIter iter, sub;
+ DBusConnection *bus;
+
+ dbus_error_init(&error);
+
+ if (!(rl = action_to_runlevel()))
+ return 0;
+
+ if (utmp_get_runlevel(&previous, NULL) < 0)
+ previous = 'N';
+
+ if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
+ if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
+ r = 0;
+ goto finish;
+ }
+
+ log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
+ r = -EIO;
+ goto finish;
+ }
+
+ if ((r = bus_check_peercred(bus)) < 0) {
+ log_error("Failed to verify owner of bus.");
+ goto finish;
+ }
+
+ if (!(m = dbus_message_new_method_call(
+ "com.ubuntu.Upstart",
+ "/com/ubuntu/Upstart",
+ "com.ubuntu.Upstart0_6",
+ "EmitEvent"))) {
+
+ log_error("Could not allocate message.");
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ dbus_message_iter_init_append(m, &iter);
+
+ env1_buf[sizeof(env1_buf)-2] = rl;
+ env2_buf[sizeof(env2_buf)-2] = previous;
+
+ if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
+ !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
+ !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
+ !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
+ !dbus_message_iter_close_container(&iter, &sub) ||
+ !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
+ log_error("Could not append arguments to message.");
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
+
+ if (bus_error_is_no_service(&error)) {
+ r = -EADDRNOTAVAIL;
+ goto finish;
+ }
+
+ log_error("Failed to issue method call: %s", bus_error_message(&error));
+ r = -EIO;
+ goto finish;
+ }
+
+ r = 1;
+
+finish:
+ if (bus) {
+ dbus_connection_flush(bus);
+ dbus_connection_close(bus);
+ dbus_connection_unref(bus);
+ }
+
+ return r;
+}
+
+static int talk_initctl(void) {
+ struct init_request request = {};
+ int r;
+ _cleanup_close_ int fd = -1;
+ char rl;
+
+ rl = action_to_runlevel();
+ if (!rl)
+ return 0;
+
+ request.magic = INIT_MAGIC;
+ request.sleeptime = 0;
+ request.cmd = INIT_CMD_RUNLVL;
+ request.runlevel = rl;
+
+ fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY);
+ if (fd < 0) {
+ if (errno == ENOENT)
+ return 0;
+
+ log_error("Failed to open "INIT_FIFO": %m");
+ return -errno;
+ }
+
+ errno = 0;
+ r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
+ if (r) {
+ log_error("Failed to write to "INIT_FIFO": %m");
+ return errno > 0 ? -errno : -EIO;
+ }
+
+ return 1;
+}
+
+static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
+
+ static const struct {
+ const char* verb;
+ const enum {
+ MORE,
+ LESS,
+ EQUAL
+ } argc_cmp;
+ const int argc;
+ int (* const dispatch)(DBusConnection *bus, char **args);
+ } verbs[] = {
+ { "list-units", LESS, 1, list_units },
+ { "list-unit-files", EQUAL, 1, list_unit_files },
+ { "list-sockets", LESS, 1, list_sockets },
+ { "list-jobs", EQUAL, 1, list_jobs },
+ { "clear-jobs", EQUAL, 1, daemon_reload },
+ { "load", MORE, 2, load_unit },
+ { "cancel", MORE, 2, cancel_job },
+ { "start", MORE, 2, start_unit },
+ { "stop", MORE, 2, start_unit },
+ { "condstop", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
+ { "reload", MORE, 2, start_unit },
+ { "restart", MORE, 2, start_unit },
+ { "try-restart", MORE, 2, start_unit },
+ { "reload-or-restart", MORE, 2, start_unit },
+ { "reload-or-try-restart", MORE, 2, start_unit },
+ { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
+ { "condreload", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
+ { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
+ { "isolate", EQUAL, 2, start_unit },
+ { "set-cgroup", MORE, 3, set_cgroup },
+ { "unset-cgroup", MORE, 3, set_cgroup },
+ { "get-cgroup-attr", MORE, 3, get_cgroup_attr },
+ { "set-cgroup-attr", MORE, 4, set_cgroup_attr },
+ { "unset-cgroup-attr", MORE, 3, set_cgroup },
+ { "kill", MORE, 2, kill_unit },
+ { "is-active", MORE, 2, check_unit_active },
+ { "check", MORE, 2, check_unit_active },
+ { "is-failed", MORE, 2, check_unit_failed },
+ { "show", MORE, 1, show },
+ { "status", MORE, 1, show },
+ { "help", MORE, 2, show },
+ { "dump", EQUAL, 1, dump },
+ { "snapshot", LESS, 2, snapshot },
+ { "delete", MORE, 2, delete_snapshot },
+ { "daemon-reload", EQUAL, 1, daemon_reload },
+ { "daemon-reexec", EQUAL, 1, daemon_reload },
+ { "show-environment", EQUAL, 1, show_enviroment },
+ { "set-environment", MORE, 2, set_environment },
+ { "unset-environment", MORE, 2, set_environment },
+ { "halt", EQUAL, 1, start_special },
+ { "poweroff", EQUAL, 1, start_special },
+ { "reboot", EQUAL, 1, start_special },
+ { "kexec", EQUAL, 1, start_special },
+ { "suspend", EQUAL, 1, start_special },
+ { "hibernate", EQUAL, 1, start_special },
+ { "hybrid-sleep", EQUAL, 1, start_special },
+ { "default", EQUAL, 1, start_special },
+ { "rescue", EQUAL, 1, start_special },
+ { "emergency", EQUAL, 1, start_special },
+ { "exit", EQUAL, 1, start_special },
+ { "reset-failed", MORE, 1, reset_failed },
+ { "enable", MORE, 2, enable_unit },
+ { "disable", MORE, 2, enable_unit },
+ { "is-enabled", MORE, 2, unit_is_enabled },
+ { "reenable", MORE, 2, enable_unit },
+ { "preset", MORE, 2, enable_unit },
+ { "mask", MORE, 2, enable_unit },
+ { "unmask", MORE, 2, enable_unit },
+ { "link", MORE, 2, enable_unit },
+ { "switch-root", MORE, 2, switch_root },
+ { "list-dependencies", LESS, 2, list_dependencies },
+ };
+
+ int left;
+ unsigned i;
+
+ assert(argc >= 0);
+ assert(argv);
+ assert(error);
+
+ left = argc - optind;
+
+ if (left <= 0)
+ /* Special rule: no arguments means "list-units" */
+ i = 0;
+ else {
+ if (streq(argv[optind], "help") && !argv[optind+1]) {
+ log_error("This command expects one or more "
+ "unit names. Did you mean --help?");
+ return -EINVAL;
+ }
+
+ for (i = 0; i < ELEMENTSOF(verbs); i++)
+ if (streq(argv[optind], verbs[i].verb))
+ break;
+
+ if (i >= ELEMENTSOF(verbs)) {
+ log_error("Unknown operation '%s'.", argv[optind]);
+ return -EINVAL;
+ }
+ }
+
+ switch (verbs[i].argc_cmp) {
+
+ case EQUAL:
+ if (left != verbs[i].argc) {
+ log_error("Invalid number of arguments.");
+ return -EINVAL;
+ }
+
+ break;
+
+ case MORE:
+ if (left < verbs[i].argc) {
+ log_error("Too few arguments.");
+ return -EINVAL;
+ }
+
+ break;
+
+ case LESS:
+ if (left > verbs[i].argc) {
+ log_error("Too many arguments.");
+ return -EINVAL;
+ }
+
+ break;
+
+ default:
+ assert_not_reached("Unknown comparison operator.");
+ }
+
+ /* Require a bus connection for all operations but
+ * enable/disable */
+ if (!streq(verbs[i].verb, "enable") &&
+ !streq(verbs[i].verb, "disable") &&
+ !streq(verbs[i].verb, "is-enabled") &&
+ !streq(verbs[i].verb, "list-unit-files") &&
+ !streq(verbs[i].verb, "reenable") &&
+ !streq(verbs[i].verb, "preset") &&
+ !streq(verbs[i].verb, "mask") &&
+ !streq(verbs[i].verb, "unmask") &&
+ !streq(verbs[i].verb, "link")) {
+
+ if (running_in_chroot() > 0) {
+ log_info("Running in chroot, ignoring request.");
+ return 0;
+ }
+
+ if (((!streq(verbs[i].verb, "reboot") &&
+ !streq(verbs[i].verb, "halt") &&
+ !streq(verbs[i].verb, "poweroff")) || arg_force <= 0) && !bus) {
+ log_error("Failed to get D-Bus connection: %s",
+ dbus_error_is_set(error) ? error->message : "No connection to service manager.");
+ return -EIO;
+ }
+
+ } else {
+
+ if (!bus && !avoid_bus()) {
+ log_error("Failed to get D-Bus connection: %s",
+ dbus_error_is_set(error) ? error->message : "No connection to service manager.");
+ return -EIO;
+ }
+ }
+
+ return verbs[i].dispatch(bus, argv + optind);
+}
+
+static int send_shutdownd(usec_t t, char mode, bool dry_run, bool warn, const char *message) {
+ _cleanup_close_ int fd;
+ struct sd_shutdown_command c = {
+ .usec = t,
+ .mode = mode,
+ .dry_run = dry_run,
+ .warn_wall = warn,
+ };
+ union sockaddr_union sockaddr = {
+ .un.sun_family = AF_UNIX,
+ .un.sun_path = "/run/systemd/shutdownd",
+ };
+ struct iovec iovec[2] = {
+ {.iov_base = (char*) &c,
+ .iov_len = offsetof(struct sd_shutdown_command, wall_message),
+ }
+ };
+ struct msghdr msghdr = {
+ .msg_name = &sockaddr,
+ .msg_namelen = offsetof(struct sockaddr_un, sun_path)
+ + sizeof("/run/systemd/shutdownd") - 1,
+ .msg_iov = iovec,
+ .msg_iovlen = 1,
+ };
+
+ fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
+ if (fd < 0)
+ return -errno;
+
+ if (!isempty(message)) {
+ iovec[1].iov_base = (char*) message;
+ iovec[1].iov_len = strlen(message);
+ msghdr.msg_iovlen++;
+ }
+
+ if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0)
+ return -errno;
+
+ return 0;
+}
+
+static int reload_with_fallback(DBusConnection *bus) {
+
+ if (bus) {
+ /* First, try systemd via D-Bus. */
+ if (daemon_reload(bus, NULL) >= 0)
+ return 0;
+ }
+
+ /* Nothing else worked, so let's try signals */
+ assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
+
+ if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
+ log_error("kill() failed: %m");
+ return -errno;
+ }
+
+ return 0;
+}
+
+static int start_with_fallback(DBusConnection *bus) {
+
+ if (bus) {
+ /* First, try systemd via D-Bus. */
+ if (start_unit(bus, NULL) >= 0)
+ goto done;
+ }
+
+ /* Hmm, talking to systemd via D-Bus didn't work. Then
+ * let's try to talk to Upstart via D-Bus. */
+ if (talk_upstart() > 0)
+ goto done;
+
+ /* Nothing else worked, so let's try
+ * /dev/initctl */
+ if (talk_initctl() > 0)
+ goto done;
+
+ log_error("Failed to talk to init daemon.");
+ return -EIO;
+
+done:
+ warn_wall(arg_action);
+ return 0;
+}
+
+static _noreturn_ void halt_now(enum action a) {
+
+ /* Make sure C-A-D is handled by the kernel from this
+ * point on... */
+ reboot(RB_ENABLE_CAD);
+
+ switch (a) {
+
+ case ACTION_HALT:
+ log_info("Halting.");
+ reboot(RB_HALT_SYSTEM);
+ break;
+
+ case ACTION_POWEROFF:
+ log_info("Powering off.");
+ reboot(RB_POWER_OFF);
+ break;
+
+ case ACTION_REBOOT:
+ log_info("Rebooting.");
+ reboot(RB_AUTOBOOT);
+ break;
+
+ default:
+ assert_not_reached("Unknown halt action.");
+ }
+
+ assert_not_reached("Uh? This shouldn't happen.");
+}
+
+static int halt_main(DBusConnection *bus) {
+ int r;
+
+ r = check_inhibitors(bus, arg_action);
+ if (r < 0)
+ return r;
+
+ if (geteuid() != 0) {
+ /* Try logind if we are a normal user and no special
+ * mode applies. Maybe PolicyKit allows us to shutdown
+ * the machine. */
+
+ if (arg_when <= 0 &&
+ !arg_dry &&
+ arg_force <= 0 &&
+ (arg_action == ACTION_POWEROFF ||
+ arg_action == ACTION_REBOOT)) {
+ r = reboot_with_logind(bus, arg_action);
+ if (r >= 0)
+ return r;
+ }
+
+ log_error("Must be root.");
+ return -EPERM;
+ }
+
+ if (arg_when > 0) {
+ _cleanup_free_ char *m;
+
+ m = strv_join(arg_wall, " ");
+ r = send_shutdownd(arg_when,
+ arg_action == ACTION_HALT ? 'H' :
+ arg_action == ACTION_POWEROFF ? 'P' :
+ arg_action == ACTION_KEXEC ? 'K' :
+ 'r',
+ arg_dry,
+ !arg_no_wall,
+ m);
+
+ if (r < 0)
+ log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
+ else {
+ char date[FORMAT_TIMESTAMP_MAX];
+
+ log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
+ format_timestamp(date, sizeof(date), arg_when));
+ return 0;
+ }
+ }
+
+ if (!arg_dry && !arg_force)
+ return start_with_fallback(bus);
+
+ if (!arg_no_wtmp) {
+ if (sd_booted() > 0)
+ log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
+ else {
+ r = utmp_put_shutdown();
+ if (r < 0)
+ log_warning("Failed to write utmp record: %s", strerror(-r));
+ }
+ }
+
+ if (arg_dry)
+ return 0;
+
+ halt_now(arg_action);
+ /* We should never reach this. */
+ return -ENOSYS;
+}
+
+static int runlevel_main(void) {
+ int r, runlevel, previous;
+
+ r = utmp_get_runlevel(&runlevel, &previous);
+ if (r < 0) {
+ puts("unknown");
+ return r;
+ }
+
+ printf("%c %c\n",
+ previous <= 0 ? 'N' : previous,
+ runlevel <= 0 ? 'N' : runlevel);
+
+ return 0;
+}
+
+int main(int argc, char*argv[]) {
+ int r, retval = EXIT_FAILURE;
+ DBusConnection *bus = NULL;
+ _cleanup_dbus_error_free_ DBusError error;
+
+ dbus_error_init(&error);
+
+ setlocale(LC_ALL, "");
+ log_parse_environment();
+ log_open();
+
+ r = parse_argv(argc, argv);
+ if (r < 0)
+ goto finish;
+ else if (r == 0) {
+ retval = EXIT_SUCCESS;
+ goto finish;
+ }
+
+ /* /sbin/runlevel doesn't need to communicate via D-Bus, so
+ * let's shortcut this */
+ if (arg_action == ACTION_RUNLEVEL) {
+ r = runlevel_main();
+ retval = r < 0 ? EXIT_FAILURE : r;
+ goto finish;
+ }
+
+ if (running_in_chroot() > 0 && arg_action != ACTION_SYSTEMCTL) {
+ log_info("Running in chroot, ignoring request.");
+ retval = 0;
+ goto finish;
+ }
+
+ if (!avoid_bus()) {
+ if (arg_transport == TRANSPORT_NORMAL)
+ bus_connect(arg_scope == UNIT_FILE_SYSTEM ? DBUS_BUS_SYSTEM : DBUS_BUS_SESSION, &bus, &private_bus, &error);
+ else if (arg_transport == TRANSPORT_POLKIT) {
+ bus_connect_system_polkit(&bus, &error);
+ private_bus = false;
+ } else if (arg_transport == TRANSPORT_SSH) {
+ bus_connect_system_ssh(NULL, arg_host, &bus, &error);
+ private_bus = false;
+ } else
+ assert_not_reached("Uh, invalid transport...");
+ }
+
+ switch (arg_action) {
+
+ case ACTION_SYSTEMCTL:
+ r = systemctl_main(bus, argc, argv, &error);
+ break;
+
+ case ACTION_HALT:
+ case ACTION_POWEROFF:
+ case ACTION_REBOOT:
+ case ACTION_KEXEC:
+ r = halt_main(bus);
+ break;
+
+ case ACTION_RUNLEVEL2:
+ case ACTION_RUNLEVEL3:
+ case ACTION_RUNLEVEL4:
+ case ACTION_RUNLEVEL5:
+ case ACTION_RESCUE:
+ case ACTION_EMERGENCY:
+ case ACTION_DEFAULT:
+ r = start_with_fallback(bus);
+ break;
+
+ case ACTION_RELOAD:
+ case ACTION_REEXEC:
+ r = reload_with_fallback(bus);
+ break;
+
+ case ACTION_CANCEL_SHUTDOWN: {
+ char *m = NULL;
+
+ if (arg_wall) {
+ m = strv_join(arg_wall, " ");
+ if (!m) {
+ retval = EXIT_FAILURE;
+ goto finish;
+ }
+ }
+ r = send_shutdownd(arg_when, SD_SHUTDOWN_NONE, false, !arg_no_wall, m);
+ if (r < 0)
+ log_warning("Failed to talk to shutdownd, shutdown hasn't been cancelled: %s", strerror(-r));
+ free(m);
+ break;
+ }
+
+ case ACTION_INVALID:
+ case ACTION_RUNLEVEL:
+ default:
+ assert_not_reached("Unknown action");
+ }
+
+ retval = r < 0 ? EXIT_FAILURE : r;
+
+finish:
+ if (bus) {
+ dbus_connection_flush(bus);
+ dbus_connection_close(bus);
+ dbus_connection_unref(bus);
+ }
+
+ dbus_shutdown();
+
+ strv_free(arg_types);
+ strv_free(arg_load_states);
+ strv_free(arg_properties);
+
+ pager_close();
+ ask_password_agent_close();
+ polkit_agent_close();
+
+ return retval;
+}
diff --git a/src/systemd/sd-bus-protocol.h b/src/systemd/sd-bus-protocol.h
new file mode 100644
index 0000000000..a26d27c31a
--- /dev/null
+++ b/src/systemd/sd-bus-protocol.h
@@ -0,0 +1,153 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef foosdbusprotocolhfoo
+#define foosdbusprotocolhfoo
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <endian.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Types of message */
+
+enum {
+ _SD_BUS_MESSAGE_TYPE_INVALID = 0,
+ SD_BUS_MESSAGE_TYPE_METHOD_CALL,
+ SD_BUS_MESSAGE_TYPE_METHOD_RETURN,
+ SD_BUS_MESSAGE_TYPE_METHOD_ERROR,
+ SD_BUS_MESSAGE_TYPE_SIGNAL,
+ _SD_BUS_MESSAGE_TYPE_MAX
+};
+
+/* Primitive types */
+
+enum {
+ _SD_BUS_TYPE_INVALID = 0,
+ SD_BUS_TYPE_BYTE = 'y',
+ SD_BUS_TYPE_BOOLEAN = 'b',
+ SD_BUS_TYPE_INT16 = 'n',
+ SD_BUS_TYPE_UINT16 = 'q',
+ SD_BUS_TYPE_INT32 = 'i',
+ SD_BUS_TYPE_UINT32 = 'u',
+ SD_BUS_TYPE_INT64 = 'x',
+ SD_BUS_TYPE_UINT64 = 't',
+ SD_BUS_TYPE_DOUBLE = 'd',
+ SD_BUS_TYPE_STRING = 's',
+ SD_BUS_TYPE_OBJECT_PATH = 'o',
+ SD_BUS_TYPE_SIGNATURE = 'g',
+ SD_BUS_TYPE_UNIX_FD = 'h',
+ SD_BUS_TYPE_ARRAY = 'a',
+ SD_BUS_TYPE_VARIANT = 'v',
+ SD_BUS_TYPE_STRUCT = 'r', /* not actually used in signatures */
+ SD_BUS_TYPE_STRUCT_BEGIN = '(',
+ SD_BUS_TYPE_STRUCT_END = ')',
+ SD_BUS_TYPE_DICT_ENTRY = 'e', /* not actually used in signatures */
+ SD_BUS_TYPE_DICT_ENTRY_BEGIN = '{',
+ SD_BUS_TYPE_DICT_ENTRY_END = '}',
+};
+
+/* Endianness */
+
+enum {
+ _SD_BUS_INVALID_ENDIAN = 0,
+ SD_BUS_LITTLE_ENDIAN = 'l',
+ SD_BUS_BIG_ENDIAN = 'B',
+#if __BYTE_ORDER == __BIG_ENDIAN
+ SD_BUS_NATIVE_ENDIAN = SD_BUS_BIG_ENDIAN,
+ SD_BUS_REVERSE_ENDIAN = SD_BUS_LITTLE_ENDIAN
+#else
+ SD_BUS_NATIVE_ENDIAN = SD_BUS_LITTLE_ENDIAN,
+ SD_BUS_REVERSE_ENDIAN = SD_BUS_BIG_ENDIAN
+#endif
+};
+
+/* Flags */
+
+enum {
+ SD_BUS_MESSAGE_NO_REPLY_EXPECTED = 1,
+ SD_BUS_MESSAGE_NO_AUTO_START = 2
+};
+
+/* Header fields */
+
+enum {
+ _SD_BUS_MESSAGE_HEADER_INVALID = 0,
+ SD_BUS_MESSAGE_HEADER_PATH,
+ SD_BUS_MESSAGE_HEADER_INTERFACE,
+ SD_BUS_MESSAGE_HEADER_MEMBER,
+ SD_BUS_MESSAGE_HEADER_ERROR_NAME,
+ SD_BUS_MESSAGE_HEADER_REPLY_SERIAL,
+ SD_BUS_MESSAGE_HEADER_DESTINATION,
+ SD_BUS_MESSAGE_HEADER_SENDER,
+ SD_BUS_MESSAGE_HEADER_SIGNATURE,
+ SD_BUS_MESSAGE_HEADER_UNIX_FDS,
+ _SD_BUS_MESSAGE_HEADER_MAX
+};
+
+#define SD_BUS_INTROSPECT_DOCTYPE \
+ "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n" \
+ "\"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
+
+#define SD_BUS_INTROSPECT_INTERFACE_PROPERTIES \
+ " <interface name=\"org.freedesktop.DBus.Properties\">\n" \
+ " <method name=\"Get\">\n" \
+ " <arg name=\"interface\" direction=\"in\" type=\"s\"/>\n" \
+ " <arg name=\"property\" direction=\"in\" type=\"s\"/>\n" \
+ " <arg name=\"value\" direction=\"out\" type=\"v\"/>\n" \
+ " </method>\n" \
+ " <method name=\"GetAll\">\n" \
+ " <arg name=\"interface\" direction=\"in\" type=\"s\"/>\n" \
+ " <arg name=\"properties\" direction=\"out\" type=\"a{sv}\"/>\n" \
+ " </method>\n" \
+ " <method name=\"Set\">\n" \
+ " <arg name=\"interface\" direction=\"in\" type=\"s\"/>\n" \
+ " <arg name=\"property\" direction=\"in\" type=\"s\"/>\n" \
+ " <arg name=\"value\" direction=\"in\" type=\"v\"/>\n" \
+ " </method>\n" \
+ " <signal name=\"PropertiesChanged\">\n" \
+ " <arg type=\"s\" name=\"interface\"/>\n" \
+ " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n" \
+ " <arg type=\"as\" name=\"invalidated_properties\"/>\n" \
+ " </signal>\n" \
+ " </interface>\n"
+
+#define SD_BUS_INTROSPECT_INTERFACE_INTROSPECTABLE \
+ " <interface name=\"org.freedesktop.DBus.Introspectable\">\n" \
+ " <method name=\"Introspect\">\n" \
+ " <arg name=\"data\" type=\"s\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ " </interface>\n"
+
+#define SD_BUS_INTROSPECT_INTERFACE_PEER \
+ "<interface name=\"org.freedesktop.DBus.Peer\">\n" \
+ " <method name=\"Ping\"/>\n" \
+ " <method name=\"GetMachineId\">\n" \
+ " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n" \
+ " </method>\n" \
+ "</interface>\n"
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/src/systemd/sd-bus.h b/src/systemd/sd-bus.h
new file mode 100644
index 0000000000..c1ec50871f
--- /dev/null
+++ b/src/systemd/sd-bus.h
@@ -0,0 +1,210 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef foosdbushfoo
+#define foosdbushfoo
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <inttypes.h>
+#include <sys/types.h>
+
+#include <sd-id128.h>
+#include "sd-bus-protocol.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef _sd_printf_attr_
+# if __GNUC__ >= 4
+# define _sd_printf_attr_(a,b) __attribute__ ((format (printf, a, b)))
+# else
+# define _sd_printf_attr_(a,b)
+# endif
+#endif
+
+/* TODO:
+ * - add page donation logic
+ * - api for appending/reading fixed arrays
+ * - merge busctl into systemctl or so?
+ * - default policy (allow uid == 0 and our own uid)
+ *
+ * - enforce alignment of pointers passed in
+ * - negotiation for attach attributes
+ *
+ * - for kernel and unix transports allow setting the unix user/access mode for the node
+ */
+
+typedef struct sd_bus sd_bus;
+typedef struct sd_bus_message sd_bus_message;
+
+typedef struct {
+ const char *name;
+ const char *message;
+ int need_free;
+} sd_bus_error;
+
+typedef int (*sd_bus_message_handler_t)(sd_bus *bus, int ret, sd_bus_message *m, void *userdata);
+
+/* Connections */
+
+int sd_bus_open_system(sd_bus **ret);
+int sd_bus_open_user(sd_bus **ret);
+
+int sd_bus_new(sd_bus **ret);
+int sd_bus_set_address(sd_bus *bus, const char *address);
+int sd_bus_set_fd(sd_bus *bus, int input_fd, int output_fd);
+int sd_bus_set_exec(sd_bus *bus, const char *path, char *const argv[]);
+int sd_bus_set_bus_client(sd_bus *bus, int b);
+int sd_bus_set_server(sd_bus *bus, int b, sd_id128_t server_id);
+int sd_bus_set_anonymous(sd_bus *bus, int b);
+int sd_bus_set_negotiate_fds(sd_bus *bus, int b);
+int sd_bus_start(sd_bus *ret);
+
+void sd_bus_close(sd_bus *bus);
+
+sd_bus *sd_bus_ref(sd_bus *bus);
+sd_bus *sd_bus_unref(sd_bus *bus);
+
+int sd_bus_is_open(sd_bus *bus);
+int sd_bus_can_send(sd_bus *bus, char type);
+int sd_bus_get_server_id(sd_bus *bus, sd_id128_t *peer);
+
+int sd_bus_send(sd_bus *bus, sd_bus_message *m, uint64_t *serial);
+int sd_bus_send_with_reply(sd_bus *bus, sd_bus_message *m, sd_bus_message_handler_t callback, void *userdata, uint64_t usec, uint64_t *serial);
+int sd_bus_send_with_reply_cancel(sd_bus *bus, uint64_t serial);
+int sd_bus_send_with_reply_and_block(sd_bus *bus, sd_bus_message *m, uint64_t usec, sd_bus_error *error, sd_bus_message **r);
+
+int sd_bus_get_fd(sd_bus *bus);
+int sd_bus_get_events(sd_bus *bus);
+int sd_bus_get_timeout(sd_bus *bus, uint64_t *timeout_usec);
+int sd_bus_process(sd_bus *bus, sd_bus_message **r);
+int sd_bus_wait(sd_bus *bus, uint64_t timeout_usec);
+int sd_bus_flush(sd_bus *bus);
+
+int sd_bus_add_filter(sd_bus *bus, sd_bus_message_handler_t callback, void *userdata);
+int sd_bus_remove_filter(sd_bus *bus, sd_bus_message_handler_t callback, void *userdata);
+
+int sd_bus_add_object(sd_bus *bus, const char *path, sd_bus_message_handler_t callback, void *userdata);
+int sd_bus_remove_object(sd_bus *bus, const char *path, sd_bus_message_handler_t callback, void *userdata);
+
+int sd_bus_add_fallback(sd_bus *bus, const char *prefix, sd_bus_message_handler_t callback, void *userdata);
+int sd_bus_remove_fallback(sd_bus *bus, const char *prefix, sd_bus_message_handler_t callback, void *userdata);
+
+int sd_bus_add_match(sd_bus *bus, const char *match, sd_bus_message_handler_t callback, void *userdata);
+int sd_bus_remove_match(sd_bus *bus, const char *match, sd_bus_message_handler_t callback, void *userdata);
+
+/* Message object */
+
+int sd_bus_message_new_signal(sd_bus *bus, const char *path, const char *interface, const char *member, sd_bus_message **m);
+int sd_bus_message_new_method_call(sd_bus *bus, const char *destination, const char *path, const char *interface, const char *member, sd_bus_message **m);
+int sd_bus_message_new_method_return(sd_bus *bus, sd_bus_message *call, sd_bus_message **m);
+int sd_bus_message_new_method_error(sd_bus *bus, sd_bus_message *call, const sd_bus_error *e, sd_bus_message **m);
+
+sd_bus_message* sd_bus_message_ref(sd_bus_message *m);
+sd_bus_message* sd_bus_message_unref(sd_bus_message *m);
+
+int sd_bus_message_get_type(sd_bus_message *m, uint8_t *type);
+int sd_bus_message_get_serial(sd_bus_message *m, uint64_t *serial);
+int sd_bus_message_get_reply_serial(sd_bus_message *m, uint64_t *serial);
+int sd_bus_message_get_no_reply(sd_bus_message *m);
+
+const char *sd_bus_message_get_path(sd_bus_message *m);
+const char *sd_bus_message_get_interface(sd_bus_message *m);
+const char *sd_bus_message_get_member(sd_bus_message *m);
+const char *sd_bus_message_get_destination(sd_bus_message *m);
+const char *sd_bus_message_get_sender(sd_bus_message *m);
+const sd_bus_error *sd_bus_message_get_error(sd_bus_message *m);
+
+int sd_bus_message_get_monotonic_timestamp(sd_bus_message *m, uint64_t *usec);
+int sd_bus_message_get_realtime_timestamp(sd_bus_message *m, uint64_t *usec);
+int sd_bus_message_get_uid(sd_bus_message *m, uid_t *uid);
+int sd_bus_message_get_gid(sd_bus_message *m, gid_t *gid);
+int sd_bus_message_get_pid(sd_bus_message *m, pid_t *pid);
+int sd_bus_message_get_tid(sd_bus_message *m, pid_t *tid);
+int sd_bus_message_get_pid_starttime(sd_bus_message *m, uint64_t *usec);
+int sd_bus_message_get_selinux_context(sd_bus_message *m, const char **r);
+int sd_bus_message_get_comm(sd_bus_message *m, const char **r);
+int sd_bus_message_get_tid_comm(sd_bus_message *m, const char **r);
+int sd_bus_message_get_exe(sd_bus_message *m, const char **r);
+int sd_bus_message_get_cgroup(sd_bus_message *m, const char **r);
+int sd_bus_message_get_cmdline(sd_bus_message *m, char ***cmdline);
+int sd_bus_message_get_unit(sd_bus_message *m, const char **unit);
+int sd_bus_message_get_user_unit(sd_bus_message *m, const char **unit);
+int sd_bus_message_get_session(sd_bus_message *m, const char **session);
+int sd_bus_message_get_owner_uid(sd_bus_message *m, uid_t *uid);
+int sd_bus_message_get_audit_sessionid(sd_bus_message *m, uint32_t *sessionid);
+int sd_bus_message_get_audit_loginuid(sd_bus_message *m, uid_t *loginuid);
+int sd_bus_message_has_effective_cap(sd_bus_message *m, int capability);
+
+int sd_bus_message_is_signal(sd_bus_message *m, const char *interface, const char *member);
+int sd_bus_message_is_method_call(sd_bus_message *m, const char *interface, const char *member);
+int sd_bus_message_is_method_error(sd_bus_message *m, const char *name);
+
+int sd_bus_message_set_no_reply(sd_bus_message *m, int b);
+int sd_bus_message_set_destination(sd_bus_message *m, const char *destination);
+
+int sd_bus_message_append(sd_bus_message *m, const char *types, ...);
+int sd_bus_message_append_basic(sd_bus_message *m, char type, const void *p);
+int sd_bus_message_open_container(sd_bus_message *m, char type, const char *contents);
+int sd_bus_message_close_container(sd_bus_message *m);
+
+int sd_bus_message_read(sd_bus_message *m, const char *types, ...);
+int sd_bus_message_read_basic(sd_bus_message *m, char type, void *p);
+int sd_bus_message_enter_container(sd_bus_message *m, char type, const char *contents);
+int sd_bus_message_exit_container(sd_bus_message *m);
+int sd_bus_message_peek_type(sd_bus_message *m, char *type, const char **contents);
+int sd_bus_message_rewind(sd_bus_message *m, int complete);
+
+/* Convenience calls */
+
+int sd_bus_emit_signal(sd_bus *bus, const char *path, const char *interface, const char *member, const char *types, ...);
+int sd_bus_call_method(sd_bus *bus, const char *destination, const char *path, const char *interface, const char *member, sd_bus_error *error, sd_bus_message **reply, const char *types, ...);
+int sd_bus_reply_method_return(sd_bus *bus, sd_bus_message *call, const char *types, ...);
+int sd_bus_reply_method_error(sd_bus *bus, sd_bus_message *call, const sd_bus_error *e);
+
+/* Bus management */
+
+int sd_bus_get_unique_name(sd_bus *bus, const char **unique);
+int sd_bus_request_name(sd_bus *bus, const char *name, int flags);
+int sd_bus_release_name(sd_bus *bus, const char *name);
+int sd_bus_list_names(sd_bus *bus, char ***l);
+int sd_bus_get_owner(sd_bus *bus, const char *name, char **owner);
+int sd_bus_get_owner_uid(sd_bus *bus, const char *name, uid_t *uid);
+int sd_bus_get_owner_pid(sd_bus *bus, const char *name, pid_t *pid);
+int sd_bus_get_owner_machine_id(sd_bus *bus, const char *name, sd_id128_t *machine);
+
+/* Error structures */
+
+#define SD_BUS_ERROR_NULL ((sd_bus_error) {NULL, NULL, 0})
+#define SD_BUS_ERROR_MAKE(name, message) ((sd_bus_error) {(name), (message), 0})
+
+void sd_bus_error_free(sd_bus_error *e);
+int sd_bus_error_set(sd_bus_error *e, const char *name, const char *format, ...) _sd_printf_attr_(3, 0);
+void sd_bus_error_set_const(sd_bus_error *e, const char *name, const char *message);
+int sd_bus_error_copy(sd_bus_error *dest, const sd_bus_error *e);
+int sd_bus_error_is_set(const sd_bus_error *e);
+int sd_bus_error_has_name(const sd_bus_error *e, const char *name);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/src/systemd/sd-daemon.h b/src/systemd/sd-daemon.h
new file mode 100644
index 0000000000..daa3f4c857
--- /dev/null
+++ b/src/systemd/sd-daemon.h
@@ -0,0 +1,282 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef foosddaemonhfoo
+#define foosddaemonhfoo
+
+/***
+ Copyright 2010 Lennart Poettering
+
+ Permission is hereby granted, free of charge, to any person
+ obtaining a copy of this software and associated documentation files
+ (the "Software"), to deal in the Software without restriction,
+ including without limitation the rights to use, copy, modify, merge,
+ publish, distribute, sublicense, and/or sell copies of the Software,
+ and to permit persons to whom the Software is furnished to do so,
+ subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+***/
+
+#include <sys/types.h>
+#include <inttypes.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ Reference implementation of a few systemd related interfaces for
+ writing daemons. These interfaces are trivial to implement. To
+ simplify porting we provide this reference implementation.
+ Applications are welcome to reimplement the algorithms described
+ here if they do not want to include these two source files.
+
+ The following functionality is provided:
+
+ - Support for logging with log levels on stderr
+ - File descriptor passing for socket-based activation
+ - Daemon startup and status notification
+ - Detection of systemd boots
+
+ You may compile this with -DDISABLE_SYSTEMD to disable systemd
+ support. This makes all those calls NOPs that are directly related to
+ systemd (i.e. only sd_is_xxx() will stay useful).
+
+ Since this is drop-in code we don't want any of our symbols to be
+ exported in any case. Hence we declare hidden visibility for all of
+ them.
+
+ You may find an up-to-date version of these source files online:
+
+ http://cgit.freedesktop.org/systemd/systemd/plain/src/systemd/sd-daemon.h
+ http://cgit.freedesktop.org/systemd/systemd/plain/src/libsystemd-daemon/sd-daemon.c
+
+ This should compile on non-Linux systems, too, but with the
+ exception of the sd_is_xxx() calls all functions will become NOPs.
+
+ See sd-daemon(3) for more information.
+*/
+
+#ifndef _sd_printf_attr_
+# if __GNUC__ >= 4
+# define _sd_printf_attr_(a,b) __attribute__ ((format (printf, a, b)))
+# else
+# define _sd_printf_attr_(a,b)
+# endif
+#endif
+
+/*
+ Log levels for usage on stderr:
+
+ fprintf(stderr, SD_NOTICE "Hello World!\n");
+
+ This is similar to printk() usage in the kernel.
+*/
+#define SD_EMERG "<0>" /* system is unusable */
+#define SD_ALERT "<1>" /* action must be taken immediately */
+#define SD_CRIT "<2>" /* critical conditions */
+#define SD_ERR "<3>" /* error conditions */
+#define SD_WARNING "<4>" /* warning conditions */
+#define SD_NOTICE "<5>" /* normal but significant condition */
+#define SD_INFO "<6>" /* informational */
+#define SD_DEBUG "<7>" /* debug-level messages */
+
+/* The first passed file descriptor is fd 3 */
+#define SD_LISTEN_FDS_START 3
+
+/*
+ Returns how many file descriptors have been passed, or a negative
+ errno code on failure. Optionally, removes the $LISTEN_FDS and
+ $LISTEN_PID file descriptors from the environment (recommended, but
+ problematic in threaded environments). If r is the return value of
+ this function you'll find the file descriptors passed as fds
+ SD_LISTEN_FDS_START to SD_LISTEN_FDS_START+r-1. Returns a negative
+ errno style error code on failure. This function call ensures that
+ the FD_CLOEXEC flag is set for the passed file descriptors, to make
+ sure they are not passed on to child processes. If FD_CLOEXEC shall
+ not be set, the caller needs to unset it after this call for all file
+ descriptors that are used.
+
+ See sd_listen_fds(3) for more information.
+*/
+int sd_listen_fds(int unset_environment);
+
+/*
+ Helper call for identifying a passed file descriptor. Returns 1 if
+ the file descriptor is a FIFO in the file system stored under the
+ specified path, 0 otherwise. If path is NULL a path name check will
+ not be done and the call only verifies if the file descriptor
+ refers to a FIFO. Returns a negative errno style error code on
+ failure.
+
+ See sd_is_fifo(3) for more information.
+*/
+int sd_is_fifo(int fd, const char *path);
+
+/*
+ Helper call for identifying a passed file descriptor. Returns 1 if
+ the file descriptor is a special character device on the file
+ system stored under the specified path, 0 otherwise.
+ If path is NULL a path name check will not be done and the call
+ only verifies if the file descriptor refers to a special character.
+ Returns a negative errno style error code on failure.
+
+ See sd_is_special(3) for more information.
+*/
+int sd_is_special(int fd, const char *path);
+
+/*
+ Helper call for identifying a passed file descriptor. Returns 1 if
+ the file descriptor is a socket of the specified family (AF_INET,
+ ...) and type (SOCK_DGRAM, SOCK_STREAM, ...), 0 otherwise. If
+ family is 0 a socket family check will not be done. If type is 0 a
+ socket type check will not be done and the call only verifies if
+ the file descriptor refers to a socket. If listening is > 0 it is
+ verified that the socket is in listening mode. (i.e. listen() has
+ been called) If listening is == 0 it is verified that the socket is
+ not in listening mode. If listening is < 0 no listening mode check
+ is done. Returns a negative errno style error code on failure.
+
+ See sd_is_socket(3) for more information.
+*/
+int sd_is_socket(int fd, int family, int type, int listening);
+
+/*
+ Helper call for identifying a passed file descriptor. Returns 1 if
+ the file descriptor is an Internet socket, of the specified family
+ (either AF_INET or AF_INET6) and the specified type (SOCK_DGRAM,
+ SOCK_STREAM, ...), 0 otherwise. If version is 0 a protocol version
+ check is not done. If type is 0 a socket type check will not be
+ done. If port is 0 a socket port check will not be done. The
+ listening flag is used the same way as in sd_is_socket(). Returns a
+ negative errno style error code on failure.
+
+ See sd_is_socket_inet(3) for more information.
+*/
+int sd_is_socket_inet(int fd, int family, int type, int listening, uint16_t port);
+
+/*
+ Helper call for identifying a passed file descriptor. Returns 1 if
+ the file descriptor is an AF_UNIX socket of the specified type
+ (SOCK_DGRAM, SOCK_STREAM, ...) and path, 0 otherwise. If type is 0
+ a socket type check will not be done. If path is NULL a socket path
+ check will not be done. For normal AF_UNIX sockets set length to
+ 0. For abstract namespace sockets set length to the length of the
+ socket name (including the initial 0 byte), and pass the full
+ socket path in path (including the initial 0 byte). The listening
+ flag is used the same way as in sd_is_socket(). Returns a negative
+ errno style error code on failure.
+
+ See sd_is_socket_unix(3) for more information.
+*/
+int sd_is_socket_unix(int fd, int type, int listening, const char *path, size_t length);
+
+/*
+ Helper call for identifying a passed file descriptor. Returns 1 if
+ the file descriptor is a POSIX Message Queue of the specified name,
+ 0 otherwise. If path is NULL a message queue name check is not
+ done. Returns a negative errno style error code on failure.
+*/
+int sd_is_mq(int fd, const char *path);
+
+/*
+ Informs systemd about changed daemon state. This takes a number of
+ newline separated environment-style variable assignments in a
+ string. The following variables are known:
+
+ READY=1 Tells systemd that daemon startup is finished (only
+ relevant for services of Type=notify). The passed
+ argument is a boolean "1" or "0". Since there is
+ little value in signaling non-readiness the only
+ value daemons should send is "READY=1".
+
+ STATUS=... Passes a single-line status string back to systemd
+ that describes the daemon state. This is free-from
+ and can be used for various purposes: general state
+ feedback, fsck-like programs could pass completion
+ percentages and failing programs could pass a human
+ readable error message. Example: "STATUS=Completed
+ 66% of file system check..."
+
+ ERRNO=... If a daemon fails, the errno-style error code,
+ formatted as string. Example: "ERRNO=2" for ENOENT.
+
+ BUSERROR=... If a daemon fails, the D-Bus error-style error
+ code. Example: "BUSERROR=org.freedesktop.DBus.Error.TimedOut"
+
+ MAINPID=... The main pid of a daemon, in case systemd did not
+ fork off the process itself. Example: "MAINPID=4711"
+
+ WATCHDOG=1 Tells systemd to update the watchdog timestamp.
+ Services using this feature should do this in
+ regular intervals. A watchdog framework can use the
+ timestamps to detect failed services.
+
+ Daemons can choose to send additional variables. However, it is
+ recommended to prefix variable names not listed above with X_.
+
+ Returns a negative errno-style error code on failure. Returns > 0
+ if systemd could be notified, 0 if it couldn't possibly because
+ systemd is not running.
+
+ Example: When a daemon finished starting up, it could issue this
+ call to notify systemd about it:
+
+ sd_notify(0, "READY=1");
+
+ See sd_notifyf() for more complete examples.
+
+ See sd_notify(3) for more information.
+*/
+int sd_notify(int unset_environment, const char *state);
+
+/*
+ Similar to sd_notify() but takes a format string.
+
+ Example 1: A daemon could send the following after initialization:
+
+ sd_notifyf(0, "READY=1\n"
+ "STATUS=Processing requests...\n"
+ "MAINPID=%lu",
+ (unsigned long) getpid());
+
+ Example 2: A daemon could send the following shortly before
+ exiting, on failure:
+
+ sd_notifyf(0, "STATUS=Failed to start up: %s\n"
+ "ERRNO=%i",
+ strerror(errno),
+ errno);
+
+ See sd_notifyf(3) for more information.
+*/
+int sd_notifyf(int unset_environment, const char *format, ...) _sd_printf_attr_(2,3);
+
+/*
+ Returns > 0 if the system was booted with systemd. Returns < 0 on
+ error. Returns 0 if the system was not booted with systemd. Note
+ that all of the functions above handle non-systemd boots just
+ fine. You should NOT protect them with a call to this function. Also
+ note that this function checks whether the system, not the user
+ session is controlled by systemd. However the functions above work
+ for both user and system services.
+
+ See sd_booted(3) for more information.
+*/
+int sd_booted(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/src/systemd/sd-id128.h b/src/systemd/sd-id128.h
new file mode 100644
index 0000000000..3a83932093
--- /dev/null
+++ b/src/systemd/sd-id128.h
@@ -0,0 +1,109 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef fooid128hfoo
+#define fooid128hfoo
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <inttypes.h>
+#include <string.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* 128 Bit ID APIs. See sd-id128(3) for more information. */
+
+typedef union sd_id128 sd_id128_t;
+
+union sd_id128 {
+ uint8_t bytes[16];
+ uint64_t qwords[2];
+};
+
+char *sd_id128_to_string(sd_id128_t id, char s[33]);
+
+int sd_id128_from_string(const char *s, sd_id128_t *ret);
+
+int sd_id128_randomize(sd_id128_t *ret);
+
+int sd_id128_get_machine(sd_id128_t *ret);
+
+int sd_id128_get_boot(sd_id128_t *ret);
+
+#define SD_ID128_MAKE(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) \
+ ((sd_id128_t) { .bytes = { 0x##v0, 0x##v1, 0x##v2, 0x##v3, 0x##v4, 0x##v5, 0x##v6, 0x##v7, \
+ 0x##v8, 0x##v9, 0x##v10, 0x##v11, 0x##v12, 0x##v13, 0x##v14, 0x##v15 }})
+
+/* Note that SD_ID128_FORMAT_VAL will evaluate the passed argument 16
+ * times. It is hence not a good idea to call this macro with an
+ * expensive function as paramater or an expression with side
+ * effects */
+
+#define SD_ID128_FORMAT_STR "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x"
+#define SD_ID128_FORMAT_VAL(x) (x).bytes[0], (x).bytes[1], (x).bytes[2], (x).bytes[3], (x).bytes[4], (x).bytes[5], (x).bytes[6], (x).bytes[7], (x).bytes[8], (x).bytes[9], (x).bytes[10], (x).bytes[11], (x).bytes[12], (x).bytes[13], (x).bytes[14], (x).bytes[15]
+
+#define SD_ID128_CONST_STR(x) \
+ ((char[33]) { \
+ ((x).bytes[0] >> 4) >= 10 ? 'a' + ((x).bytes[0] >> 4) - 10 : '0' + ((x).bytes[0] >> 4), \
+ ((x).bytes[0] & 15) >= 10 ? 'a' + ((x).bytes[0] & 15) - 10 : '0' + ((x).bytes[0] & 15), \
+ ((x).bytes[1] >> 4) >= 10 ? 'a' + ((x).bytes[1] >> 4) - 10 : '0' + ((x).bytes[1] >> 4), \
+ ((x).bytes[1] & 15) >= 10 ? 'a' + ((x).bytes[1] & 15) - 10 : '0' + ((x).bytes[1] & 15), \
+ ((x).bytes[2] >> 4) >= 10 ? 'a' + ((x).bytes[2] >> 4) - 10 : '0' + ((x).bytes[2] >> 4), \
+ ((x).bytes[2] & 15) >= 10 ? 'a' + ((x).bytes[2] & 15) - 10 : '0' + ((x).bytes[2] & 15), \
+ ((x).bytes[3] >> 4) >= 10 ? 'a' + ((x).bytes[3] >> 4) - 10 : '0' + ((x).bytes[3] >> 4), \
+ ((x).bytes[3] & 15) >= 10 ? 'a' + ((x).bytes[3] & 15) - 10 : '0' + ((x).bytes[3] & 15), \
+ ((x).bytes[4] >> 4) >= 10 ? 'a' + ((x).bytes[4] >> 4) - 10 : '0' + ((x).bytes[4] >> 4), \
+ ((x).bytes[4] & 15) >= 10 ? 'a' + ((x).bytes[4] & 15) - 10 : '0' + ((x).bytes[4] & 15), \
+ ((x).bytes[5] >> 4) >= 10 ? 'a' + ((x).bytes[5] >> 4) - 10 : '0' + ((x).bytes[5] >> 4), \
+ ((x).bytes[5] & 15) >= 10 ? 'a' + ((x).bytes[5] & 15) - 10 : '0' + ((x).bytes[5] & 15), \
+ ((x).bytes[6] >> 4) >= 10 ? 'a' + ((x).bytes[6] >> 4) - 10 : '0' + ((x).bytes[6] >> 4), \
+ ((x).bytes[6] & 15) >= 10 ? 'a' + ((x).bytes[6] & 15) - 10 : '0' + ((x).bytes[6] & 15), \
+ ((x).bytes[7] >> 4) >= 10 ? 'a' + ((x).bytes[7] >> 4) - 10 : '0' + ((x).bytes[7] >> 4), \
+ ((x).bytes[7] & 15) >= 10 ? 'a' + ((x).bytes[7] & 15) - 10 : '0' + ((x).bytes[7] & 15), \
+ ((x).bytes[8] >> 4) >= 10 ? 'a' + ((x).bytes[8] >> 4) - 10 : '0' + ((x).bytes[8] >> 4), \
+ ((x).bytes[8] & 15) >= 10 ? 'a' + ((x).bytes[8] & 15) - 10 : '0' + ((x).bytes[8] & 15), \
+ ((x).bytes[9] >> 4) >= 10 ? 'a' + ((x).bytes[9] >> 4) - 10 : '0' + ((x).bytes[9] >> 4), \
+ ((x).bytes[9] & 15) >= 10 ? 'a' + ((x).bytes[9] & 15) - 10 : '0' + ((x).bytes[9] & 15), \
+ ((x).bytes[10] >> 4) >= 10 ? 'a' + ((x).bytes[10] >> 4) - 10 : '0' + ((x).bytes[10] >> 4), \
+ ((x).bytes[10] & 15) >= 10 ? 'a' + ((x).bytes[10] & 15) - 10 : '0' + ((x).bytes[10] & 15), \
+ ((x).bytes[11] >> 4) >= 10 ? 'a' + ((x).bytes[11] >> 4) - 10 : '0' + ((x).bytes[11] >> 4), \
+ ((x).bytes[11] & 15) >= 10 ? 'a' + ((x).bytes[11] & 15) - 10 : '0' + ((x).bytes[11] & 15), \
+ ((x).bytes[12] >> 4) >= 10 ? 'a' + ((x).bytes[12] >> 4) - 10 : '0' + ((x).bytes[12] >> 4), \
+ ((x).bytes[12] & 15) >= 10 ? 'a' + ((x).bytes[12] & 15) - 10 : '0' + ((x).bytes[12] & 15), \
+ ((x).bytes[13] >> 4) >= 10 ? 'a' + ((x).bytes[13] >> 4) - 10 : '0' + ((x).bytes[13] >> 4), \
+ ((x).bytes[13] & 15) >= 10 ? 'a' + ((x).bytes[13] & 15) - 10 : '0' + ((x).bytes[13] & 15), \
+ ((x).bytes[14] >> 4) >= 10 ? 'a' + ((x).bytes[14] >> 4) - 10 : '0' + ((x).bytes[14] >> 4), \
+ ((x).bytes[14] & 15) >= 10 ? 'a' + ((x).bytes[14] & 15) - 10 : '0' + ((x).bytes[14] & 15), \
+ ((x).bytes[15] >> 4) >= 10 ? 'a' + ((x).bytes[15] >> 4) - 10 : '0' + ((x).bytes[15] >> 4), \
+ ((x).bytes[15] & 15) >= 10 ? 'a' + ((x).bytes[15] & 15) - 10 : '0' + ((x).bytes[15] & 15), \
+ 0 })
+
+static inline int sd_id128_equal(sd_id128_t a, sd_id128_t b) {
+ return memcmp(&a, &b, 16) == 0;
+}
+
+#define SD_ID128_NULL ((sd_id128_t) { .qwords = { 0, 0 }})
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/src/systemd/sd-journal.h b/src/systemd/sd-journal.h
new file mode 100644
index 0000000000..5375d49963
--- /dev/null
+++ b/src/systemd/sd-journal.h
@@ -0,0 +1,170 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef foojournalhfoo
+#define foojournalhfoo
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <inttypes.h>
+#include <sys/types.h>
+#include <stdarg.h>
+#include <sys/uio.h>
+#include <syslog.h>
+
+#include <systemd/sd-id128.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef _sd_printf_attr_
+# if __GNUC__ >= 4
+# define _sd_printf_attr_(a,b) __attribute__ ((format (printf, a, b)))
+# else
+# define _sd_printf_attr_(a,b)
+# endif
+#endif
+
+#ifndef _sd_sentinel_attr_
+# define _sd_sentinel_attr_ __attribute__((sentinel))
+#endif
+
+/* Journal APIs. See sd-journal(3) for more information. */
+
+/* Write to daemon */
+int sd_journal_print(int priority, const char *format, ...) _sd_printf_attr_(2, 3);
+int sd_journal_printv(int priority, const char *format, va_list ap) _sd_printf_attr_(2, 0);
+int sd_journal_send(const char *format, ...) _sd_printf_attr_(1, 0) _sd_sentinel_attr_;
+int sd_journal_sendv(const struct iovec *iov, int n);
+int sd_journal_perror(const char *message);
+
+/* Used by the macros below. Don't call this directly. */
+int sd_journal_print_with_location(int priority, const char *file, const char *line, const char *func, const char *format, ...) _sd_printf_attr_(5, 6);
+int sd_journal_printv_with_location(int priority, const char *file, const char *line, const char *func, const char *format, va_list ap) _sd_printf_attr_(5, 0);
+int sd_journal_send_with_location(const char *file, const char *line, const char *func, const char *format, ...) _sd_printf_attr_(4, 0) _sd_sentinel_attr_;
+int sd_journal_sendv_with_location(const char *file, const char *line, const char *func, const struct iovec *iov, int n);
+int sd_journal_perror_with_location(const char *file, const char *line, const char *func, const char *message);
+
+/* implicitly add code location to messages sent, if this is enabled */
+#ifndef SD_JOURNAL_SUPPRESS_LOCATION
+
+#define _sd_XSTRINGIFY(x) #x
+#define _sd_STRINGIFY(x) _sd_XSTRINGIFY(x)
+
+#define sd_journal_print(priority, ...) sd_journal_print_with_location(priority, "CODE_FILE=" __FILE__, "CODE_LINE=" _sd_STRINGIFY(__LINE__), __func__, __VA_ARGS__)
+#define sd_journal_printv(priority, format, ap) sd_journal_printv_with_location(priority, "CODE_FILE=" __FILE__, "CODE_LINE=" _sd_STRINGIFY(__LINE__), __func__, format, ap)
+#define sd_journal_send(...) sd_journal_send_with_location("CODE_FILE=" __FILE__, "CODE_LINE=" _sd_STRINGIFY(__LINE__), __func__, __VA_ARGS__)
+#define sd_journal_sendv(iovec, n) sd_journal_sendv_with_location("CODE_FILE=" __FILE__, "CODE_LINE=" _sd_STRINGIFY(__LINE__), __func__, iovec, n)
+#define sd_journal_perror(message) sd_journal_perror_with_location("CODE_FILE=" __FILE__, "CODE_LINE=" _sd_STRINGIFY(__LINE__), __func__, message)
+
+#endif
+
+int sd_journal_stream_fd(const char *identifier, int priority, int level_prefix);
+
+/* Browse journal stream */
+
+typedef struct sd_journal sd_journal;
+
+/* Open flags */
+enum {
+ SD_JOURNAL_LOCAL_ONLY = 1,
+ SD_JOURNAL_RUNTIME_ONLY = 2,
+ SD_JOURNAL_SYSTEM_ONLY = 4
+};
+
+/* Wakeup event types */
+enum {
+ SD_JOURNAL_NOP,
+ SD_JOURNAL_APPEND,
+ SD_JOURNAL_INVALIDATE
+};
+
+int sd_journal_open(sd_journal **ret, int flags);
+int sd_journal_open_directory(sd_journal **ret, const char *path, int flags);
+void sd_journal_close(sd_journal *j);
+
+int sd_journal_previous(sd_journal *j);
+int sd_journal_next(sd_journal *j);
+
+int sd_journal_previous_skip(sd_journal *j, uint64_t skip);
+int sd_journal_next_skip(sd_journal *j, uint64_t skip);
+
+int sd_journal_get_realtime_usec(sd_journal *j, uint64_t *ret);
+int sd_journal_get_monotonic_usec(sd_journal *j, uint64_t *ret, sd_id128_t *ret_boot_id);
+
+int sd_journal_set_data_threshold(sd_journal *j, size_t sz);
+int sd_journal_get_data_threshold(sd_journal *j, size_t *sz);
+
+int sd_journal_get_data(sd_journal *j, const char *field, const void **data, size_t *l);
+int sd_journal_enumerate_data(sd_journal *j, const void **data, size_t *l);
+void sd_journal_restart_data(sd_journal *j);
+
+int sd_journal_add_match(sd_journal *j, const void *data, size_t size);
+int sd_journal_add_disjunction(sd_journal *j);
+int sd_journal_add_conjunction(sd_journal *j);
+void sd_journal_flush_matches(sd_journal *j);
+
+int sd_journal_seek_head(sd_journal *j);
+int sd_journal_seek_tail(sd_journal *j);
+int sd_journal_seek_monotonic_usec(sd_journal *j, sd_id128_t boot_id, uint64_t usec);
+int sd_journal_seek_realtime_usec(sd_journal *j, uint64_t usec);
+int sd_journal_seek_cursor(sd_journal *j, const char *cursor);
+
+int sd_journal_get_cursor(sd_journal *j, char **cursor);
+int sd_journal_test_cursor(sd_journal *j, const char *cursor);
+
+int sd_journal_get_cutoff_realtime_usec(sd_journal *j, uint64_t *from, uint64_t *to);
+int sd_journal_get_cutoff_monotonic_usec(sd_journal *j, const sd_id128_t boot_id, uint64_t *from, uint64_t *to);
+
+int sd_journal_get_usage(sd_journal *j, uint64_t *bytes);
+
+int sd_journal_query_unique(sd_journal *j, const char *field);
+int sd_journal_enumerate_unique(sd_journal *j, const void **data, size_t *l);
+void sd_journal_restart_unique(sd_journal *j);
+
+int sd_journal_get_fd(sd_journal *j);
+int sd_journal_get_events(sd_journal *j);
+int sd_journal_get_timeout(sd_journal *j, uint64_t *timeout_usec);
+int sd_journal_process(sd_journal *j);
+int sd_journal_wait(sd_journal *j, uint64_t timeout_usec);
+int sd_journal_reliable_fd(sd_journal *j);
+
+int sd_journal_get_catalog(sd_journal *j, char **text);
+int sd_journal_get_catalog_for_message_id(sd_id128_t id, char **ret);
+
+#define SD_JOURNAL_FOREACH(j) \
+ if (sd_journal_seek_head(j) >= 0) \
+ while (sd_journal_next(j) > 0)
+
+#define SD_JOURNAL_FOREACH_BACKWARDS(j) \
+ if (sd_journal_seek_tail(j) >= 0) \
+ while (sd_journal_previous(j) > 0)
+
+#define SD_JOURNAL_FOREACH_DATA(j, data, l) \
+ for (sd_journal_restart_data(j); sd_journal_enumerate_data((j), &(data), &(l)) > 0; )
+
+#define SD_JOURNAL_FOREACH_UNIQUE(j, data, l) \
+ for (sd_journal_restart_unique(j); sd_journal_enumerate_unique((j), &(data), &(l)) > 0; )
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/src/systemd/sd-login.h b/src/systemd/sd-login.h
new file mode 100644
index 0000000000..4855e327a1
--- /dev/null
+++ b/src/systemd/sd-login.h
@@ -0,0 +1,183 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef foosdloginhfoo
+#define foosdloginhfoo
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/types.h>
+#include <inttypes.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * A few points:
+ *
+ * Instead of returning an empty string array or empty uid array, we
+ * may return NULL.
+ *
+ * Free the data the library returns with libc free(). String arrays
+ * are NULL terminated and you need to free the array itself in
+ * addition to the strings contained.
+ *
+ * We return error codes as negative errno, kernel-style. 0 or
+ * positive on success.
+ *
+ * These functions access data in /proc, /sys/fs/cgroup and /run. All
+ * of these are virtual file systems, hence the accesses are
+ * relatively cheap.
+ *
+ * See sd-login(3) for more information.
+ */
+
+/* Get session from PID. Note that 'shared' processes of a user are
+ * not attached to a session, but only attached to a user. This will
+ * return an error for system processes and 'shared' processes of a
+ * user. */
+int sd_pid_get_session(pid_t pid, char **session);
+
+/* Get UID of the owner of the session of the PID (or in case the
+ * process is a 'shared' user process the UID of that user is
+ * returned). This will not return the UID of the process, but rather
+ * the UID of the owner of the cgroup the process is in. This will
+ * return an error for system processes. */
+int sd_pid_get_owner_uid(pid_t pid, uid_t *uid);
+
+/* Get systemd unit (i.e. service) name from PID, for system
+ * services. This will return an error for non-service processes. */
+int sd_pid_get_unit(pid_t pid, char **unit);
+
+/* Get systemd unit (i.e. service) name from PID, for user
+ * services. This will return an error for non-user-service
+ * processes. */
+int sd_pid_get_user_unit(pid_t pid, char **unit);
+
+/* Get machine name from PID, for processes assigned to VM or
+ * container. This will return an error for non-service processes. */
+int sd_pid_get_machine_name(pid_t pid, char **name);
+
+/* Get state from uid. Possible states: offline, lingering, online, active, closing */
+int sd_uid_get_state(uid_t uid, char**state);
+
+/* Return 1 if uid has session on seat. If require_active is true will
+ * look for active sessions only. */
+int sd_uid_is_on_seat(uid_t uid, int require_active, const char *seat);
+
+/* Return sessions of user. If require_active is true will look for
+ * active sessions only. Returns number of sessions as return
+ * value. If sessions is NULL will just return number of sessions. */
+int sd_uid_get_sessions(uid_t uid, int require_active, char ***sessions);
+
+/* Return seats of user is on. If require_active is true will look for
+ * active seats only. Returns number of seats. If seats is NULL will
+ * just return number of seats.*/
+int sd_uid_get_seats(uid_t uid, int require_active, char ***seats);
+
+/* Return 1 if the session is a active. */
+int sd_session_is_active(const char *session);
+
+/* Get state from session. Possible states: online, active, closing
+ * (This function is a more generic version of
+ * sd_session_is_active().) */
+int sd_session_get_state(const char *sessio, char **state);
+
+/* Determine user id of session */
+int sd_session_get_uid(const char *session, uid_t *uid);
+
+/* Determine seat of session */
+int sd_session_get_seat(const char *session, char **seat);
+
+/* Determine the (PAM) service name this session was registered by. */
+int sd_session_get_service(const char *session, char **service);
+
+/* Determine the type of this session, i.e. one of "tty", "x11" or "unspecified". */
+int sd_session_get_type(const char *session, char **type);
+
+/* Determine the class of this session, i.e. one of "user", "greeter" or "lock-screen". */
+int sd_session_get_class(const char *session, char **clazz);
+
+/* Determine the X11 display of this session. */
+int sd_session_get_display(const char *session, char **display);
+
+/* Determine the TTY of this session. */
+int sd_session_get_tty(const char *session, char **display);
+
+/* Return active session and user of seat */
+int sd_seat_get_active(const char *seat, char **session, uid_t *uid);
+
+/* Return sessions and users on seat. Returns number of sessions as
+ * return value. If sessions is NULL returns only the number of
+ * sessions. */
+int sd_seat_get_sessions(const char *seat, char ***sessions, uid_t **uid, unsigned *n_uids);
+
+/* Return whether the seat is multi-session capable */
+int sd_seat_can_multi_session(const char *seat);
+
+/* Return whether the seat is TTY capable, i.e. suitable for showing console UIs */
+int sd_seat_can_tty(const char *seat);
+
+/* Return whether the seat is graphics capable, i.e. suitable for showing graphical UIs */
+int sd_seat_can_graphical(const char *seat);
+
+/* Get all seats, store in *seats. Returns the number of seats. If
+ * seats is NULL only returns number of seats. */
+int sd_get_seats(char ***seats);
+
+/* Get all sessions, store in *sessions. Returns the number of
+ * sessions. If sessions is NULL only returns number of sessions. */
+int sd_get_sessions(char ***sessions);
+
+/* Get all logged in users, store in *users. Returns the number of
+ * users. If users is NULL only returns the number of users. */
+int sd_get_uids(uid_t **users);
+
+/* Get all running virtual machines/containers */
+int sd_get_machine_names(char ***machines);
+
+/* Monitor object */
+typedef struct sd_login_monitor sd_login_monitor;
+
+/* Create a new monitor. Category must be NULL, "seat", "session",
+ * "uid", "machine" to get monitor events for the specific category
+ * (or all). */
+int sd_login_monitor_new(const char *category, sd_login_monitor** ret);
+
+/* Destroys the passed monitor. Returns NULL. */
+sd_login_monitor* sd_login_monitor_unref(sd_login_monitor *m);
+
+/* Flushes the monitor */
+int sd_login_monitor_flush(sd_login_monitor *m);
+
+/* Get FD from monitor */
+int sd_login_monitor_get_fd(sd_login_monitor *m);
+
+/* Get poll() mask to monitor */
+int sd_login_monitor_get_events(sd_login_monitor *m);
+
+/* Get timeout for poll(), as usec value relative to CLOCK_MONOTONIC's epoch */
+int sd_login_monitor_get_timeout(sd_login_monitor *m, uint64_t *timeout_usec);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/src/systemd/sd-messages.h b/src/systemd/sd-messages.h
new file mode 100644
index 0000000000..c8de331691
--- /dev/null
+++ b/src/systemd/sd-messages.h
@@ -0,0 +1,84 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef foosdmessageshfoo
+#define foosdmessageshfoo
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <systemd/sd-id128.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Hey! If you add a new message here, you *must* also update the
+ * message catalog with an appropriate explanation */
+
+#define SD_MESSAGE_JOURNAL_START SD_ID128_MAKE(f7,73,79,a8,49,0b,40,8b,be,5f,69,40,50,5a,77,7b)
+#define SD_MESSAGE_JOURNAL_STOP SD_ID128_MAKE(d9,3f,b3,c9,c2,4d,45,1a,97,ce,a6,15,ce,59,c0,0b)
+#define SD_MESSAGE_JOURNAL_DROPPED SD_ID128_MAKE(a5,96,d6,fe,7b,fa,49,94,82,8e,72,30,9e,95,d6,1e)
+#define SD_MESSAGE_JOURNAL_MISSED SD_ID128_MAKE(e9,bf,28,e6,e8,34,48,1b,b6,f4,8f,54,8a,d1,36,06)
+
+#define SD_MESSAGE_COREDUMP SD_ID128_MAKE(fc,2e,22,bc,6e,e6,47,b6,b9,07,29,ab,34,a2,50,b1)
+
+#define SD_MESSAGE_SESSION_START SD_ID128_MAKE(8d,45,62,0c,1a,43,48,db,b1,74,10,da,57,c6,0c,66)
+#define SD_MESSAGE_SESSION_STOP SD_ID128_MAKE(33,54,93,94,24,b4,45,6d,98,02,ca,83,33,ed,42,4a)
+#define SD_MESSAGE_SEAT_START SD_ID128_MAKE(fc,be,fc,5d,a2,3d,42,80,93,f9,7c,82,a9,29,0f,7b)
+#define SD_MESSAGE_SEAT_STOP SD_ID128_MAKE(e7,85,2b,fe,46,78,4e,d0,ac,cd,e0,4b,c8,64,c2,d5)
+
+#define SD_MESSAGE_TIME_CHANGE SD_ID128_MAKE(c7,a7,87,07,9b,35,4e,aa,a9,e7,7b,37,18,93,cd,27)
+#define SD_MESSAGE_TIMEZONE_CHANGE SD_ID128_MAKE(45,f8,2f,4a,ef,7a,4b,bf,94,2c,e8,61,d1,f2,09,90)
+
+#define SD_MESSAGE_STARTUP_FINISHED SD_ID128_MAKE(b0,7a,24,9c,d0,24,41,4a,82,dd,00,cd,18,13,78,ff)
+
+#define SD_MESSAGE_SLEEP_START SD_ID128_MAKE(6b,bd,95,ee,97,79,41,e4,97,c4,8b,e2,7c,25,41,28)
+#define SD_MESSAGE_SLEEP_STOP SD_ID128_MAKE(88,11,e6,df,2a,8e,40,f5,8a,94,ce,a2,6f,8e,bf,14)
+
+#define SD_MESSAGE_SHUTDOWN SD_ID128_MAKE(98,26,88,66,d1,d5,4a,49,9c,4e,98,92,1d,93,bc,40)
+
+#define SD_MESSAGE_UNIT_STARTING SD_ID128_MAKE(7d,49,58,e8,42,da,4a,75,8f,6c,1c,dc,7b,36,dc,c5)
+#define SD_MESSAGE_UNIT_STARTED SD_ID128_MAKE(39,f5,34,79,d3,a0,45,ac,8e,11,78,62,48,23,1f,bf)
+#define SD_MESSAGE_UNIT_STOPPING SD_ID128_MAKE(de,5b,42,6a,63,be,47,a7,b6,ac,3e,aa,c8,2e,2f,6f)
+#define SD_MESSAGE_UNIT_STOPPED SD_ID128_MAKE(9d,1a,aa,27,d6,01,40,bd,96,36,54,38,aa,d2,02,86)
+#define SD_MESSAGE_UNIT_FAILED SD_ID128_MAKE(be,02,cf,68,55,d2,42,8b,a4,0d,f7,e9,d0,22,f0,3d)
+#define SD_MESSAGE_UNIT_RELOADING SD_ID128_MAKE(d3,4d,03,7f,ff,18,47,e6,ae,66,9a,37,0e,69,47,25)
+#define SD_MESSAGE_UNIT_RELOADED SD_ID128_MAKE(7b,05,eb,c6,68,38,42,22,ba,a8,88,11,79,cf,da,54)
+
+#define SD_MESSAGE_SPAWN_FAILED SD_ID128_MAKE(64,12,57,65,1c,1b,4e,c9,a8,62,4d,7a,40,a9,e1,e7)
+
+#define SD_MESSAGE_FORWARD_SYSLOG_MISSED SD_ID128_MAKE(00,27,22,9c,a0,64,41,81,a7,6c,4e,92,45,8a,fa,2e)
+
+#define SD_MESSAGE_OVERMOUNTING SD_ID128_MAKE(1d,ee,03,69,c7,fc,47,36,b7,09,9b,38,ec,b4,6e,e7)
+
+#define SD_MESSAGE_LID_OPENED SD_ID128_MAKE(b7,2e,a4,a2,88,15,45,a0,b5,0e,20,0e,55,b9,b0,6f)
+#define SD_MESSAGE_LID_CLOSED SD_ID128_MAKE(b7,2e,a4,a2,88,15,45,a0,b5,0e,20,0e,55,b9,b0,70)
+#define SD_MESSAGE_POWER_KEY SD_ID128_MAKE(b7,2e,a4,a2,88,15,45,a0,b5,0e,20,0e,55,b9,b0,71)
+#define SD_MESSAGE_SUSPEND_KEY SD_ID128_MAKE(b7,2e,a4,a2,88,15,45,a0,b5,0e,20,0e,55,b9,b0,72)
+#define SD_MESSAGE_HIBERNATE_KEY SD_ID128_MAKE(b7,2e,a4,a2,88,15,45,a0,b5,0e,20,0e,55,b9,b0,73)
+
+#define SD_MESSAGE_CONFIG_ERROR SD_ID128_MAKE(c7,72,d2,4e,9a,88,4c,be,b9,ea,12,62,5c,30,6c,01)
+
+#define SD_MESSAGE_BOOTCHART SD_ID128_MAKE(9f,26,aa,56,2c,f4,40,c2,b1,6c,77,3d,04,79,b5,18)
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/src/systemd/sd-readahead.h b/src/systemd/sd-readahead.h
new file mode 100644
index 0000000000..2dac104f7a
--- /dev/null
+++ b/src/systemd/sd-readahead.h
@@ -0,0 +1,73 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef foosdreadaheadhfoo
+#define foosdreadaheadhfoo
+
+/***
+ Copyright 2010 Lennart Poettering
+
+ Permission is hereby granted, free of charge, to any person
+ obtaining a copy of this software and associated documentation files
+ (the "Software"), to deal in the Software without restriction,
+ including without limitation the rights to use, copy, modify, merge,
+ publish, distribute, sublicense, and/or sell copies of the Software,
+ and to permit persons to whom the Software is furnished to do so,
+ subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+***/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ Reference implementation of a few boot readahead related
+ interfaces. These interfaces are trivial to implement. To simplify
+ porting we provide this reference implementation. Applications are
+ welcome to reimplement the algorithms described here if they do not
+ want to include these two source files.
+
+ You may compile this with -DDISABLE_SYSTEMD to disable systemd
+ support. This makes all calls NOPs.
+
+ Since this is drop-in code we don't want any of our symbols to be
+ exported in any case. Hence we declare hidden visibility for all of
+ them.
+
+ You may find an up-to-date version of these source files online:
+
+ http://cgit.freedesktop.org/systemd/systemd/plain/src/systemd/sd-readahead.h
+ http://cgit.freedesktop.org/systemd/systemd/plain/src/readahead/sd-readahead.c
+
+ This should compile on non-Linux systems, too, but all functions
+ will become NOPs.
+
+ See sd-readahead(3) for more information.
+*/
+
+/*
+ Controls ongoing disk read-ahead operations during boot-up. The argument
+ must be a string, and either "cancel", "done" or "noreplay".
+
+ cancel = terminate read-ahead data collection, drop collected information
+ done = terminate read-ahead data collection, keep collected information
+ noreplay = terminate read-ahead replay
+*/
+int sd_readahead(const char *action);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/src/systemd/sd-shutdown.h b/src/systemd/sd-shutdown.h
new file mode 100644
index 0000000000..b8f6a487ec
--- /dev/null
+++ b/src/systemd/sd-shutdown.h
@@ -0,0 +1,108 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef foosdshutdownhfoo
+#define foosdshutdownhfoo
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+/* Interface for scheduling and cancelling timed shutdowns. */
+
+#include <inttypes.h>
+
+typedef enum sd_shutdown_mode {
+ SD_SHUTDOWN_NONE = 0,
+ SD_SHUTDOWN_REBOOT = 'r',
+ SD_SHUTDOWN_POWEROFF = 'P',
+ SD_SHUTDOWN_HALT = 'H',
+ SD_SHUTDOWN_KEXEC = 'K'
+} sd_shutdown_mode_t;
+
+/* Calculate the size of the message as "offsetof(struct
+ * sd_shutdown_command, wall_message) +
+ * strlen(command.wall_message)" */
+struct sd_shutdown_command {
+ /* Microseconds after the epoch 1970 UTC */
+ uint64_t usec;
+
+ /* H, P, r, i.e. the switches usually passed to
+ * /usr/bin/shutdown to select whether to halt, power-off or
+ * reboot the machine */
+ sd_shutdown_mode_t mode:8;
+
+ /* If non-zero, don't actually shut down, just pretend */
+ unsigned dry_run:1;
+
+ /* If non-zero, send our wall message */
+ unsigned warn_wall:1;
+
+ /* The wall message to send around. Leave empty for the
+ * default wall message */
+ char wall_message[];
+} __attribute__((packed));
+
+/* The scheme is very simple:
+ *
+ * To schedule a shutdown, simply fill in and send a single
+ * AF_UNIX/SOCK_DGRAM datagram with the structure above suffixed with
+ * the wall message to the socket /run/systemd/shutdownd (leave an
+ * empty wall message for the default shutdown message). To calculate
+ * the size of the message use "offsetof(struct sd_shutdown_command,
+ * wall_message) + strlen(command.wall_message)".
+ *
+ * To cancel a shutdown, do the same, but send an fully zeroed out
+ * structure.
+ *
+ * To be notified about scheduled shutdowns, create an inotify watch
+ * on /run/shutdown/. Whenever a file called "scheduled" appears a
+ * shutdown is scheduled. If it is removed it is canceled. It is
+ * replaced the scheduled shutdown has been changed. The file contains
+ * a simple environment-like block, that contains information about
+ * the scheduled shutdown:
+ *
+ * USEC=
+ * encodes the time for the shutdown in usecs since the epoch UTC,
+ * formatted as numeric string.
+ *
+ * WARN_WALL=
+ * is 1 if a wall message shall be sent
+ *
+ * DRY_RUN=
+ * is 1 if a dry run shutdown is scheduled
+ *
+ * MODE=
+ * is the shutdown mode, one of "poweroff", "reboot", "halt", "kexec"
+ *
+ * WALL_MESSAGE=
+ * is the wall message to use, with all special characters escape in C style.
+ *
+ * Note that some fields might be missing if they do not apply.
+ *
+ * Note that the file is first written to a temporary file and then
+ * renamed, in order to provide atomic properties for readers: if the
+ * file exists under the name "scheduled" it is guaranteed to be fully
+ * written. A reader should ignore all files in that directory by any
+ * other name.
+ *
+ * Scheduled shutdowns are only accepted from privileged processes,
+ * but the directory may be watched and the file in it read by
+ * anybody.
+ */
+
+#endif
diff --git a/src/test/test-calendarspec.c b/src/test/test-calendarspec.c
new file mode 100644
index 0000000000..21b0024388
--- /dev/null
+++ b/src/test/test-calendarspec.c
@@ -0,0 +1,88 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <string.h>
+
+#include "calendarspec.h"
+#include "util.h"
+
+static void test_one(const char *input, const char *output) {
+ CalendarSpec *c;
+ _cleanup_free_ char *p = NULL, *q = NULL;
+ usec_t u;
+ char buf[FORMAT_TIMESTAMP_MAX];
+ int r;
+
+ assert_se(calendar_spec_from_string(input, &c) >= 0);
+
+ assert_se(calendar_spec_to_string(c, &p) >= 0);
+ printf("\"%s\" → \"%s\"\n", input, p);
+
+ assert_se(streq(p, output));
+
+ u = now(CLOCK_REALTIME);
+ r = calendar_spec_next_usec(c, u, &u);
+ printf("Next: %s\n", r < 0 ? strerror(-r) : format_timestamp(buf, sizeof(buf), u));
+ calendar_spec_free(c);
+
+ assert_se(calendar_spec_from_string(p, &c) >= 0);
+ assert_se(calendar_spec_to_string(c, &q) >= 0);
+ calendar_spec_free(c);
+
+ assert_se(streq(q, p));
+}
+
+int main(int argc, char* argv[]) {
+ CalendarSpec *c;
+
+ test_one("Sat,Thu,Mon-Wed,Sat-Sun", "Mon-Thu,Sat,Sun *-*-* 00:00:00");
+ test_one("Mon,Sun 12-*-* 2,1:23", "Mon,Sun 2012-*-* 01,02:23:00");
+ test_one("Wed *-1", "Wed *-*-01 00:00:00");
+ test_one("Wed-Wed,Wed *-1", "Wed *-*-01 00:00:00");
+ test_one("Wed, 17:48", "Wed *-*-* 17:48:00");
+ test_one("Wed-Sat,Tue 12-10-15 1:2:3", "Tue-Sat 2012-10-15 01:02:03");
+ test_one("*-*-7 0:0:0", "*-*-07 00:00:00");
+ test_one("10-15", "*-10-15 00:00:00");
+ test_one("monday *-12-* 17:00", "Mon *-12-* 17:00:00");
+ test_one("Mon,Fri *-*-3,1,2 *:30:45", "Mon,Fri *-*-01,02,03 *:30:45");
+ test_one("12,14,13,12:20,10,30", "*-*-* 12,13,14:10,20,30:00");
+ test_one("mon,fri *-1/2-1,3 *:30:45", "Mon,Fri *-01/2-01,03 *:30:45");
+ test_one("03-05 08:05:40", "*-03-05 08:05:40");
+ test_one("08:05:40", "*-*-* 08:05:40");
+ test_one("05:40", "*-*-* 05:40:00");
+ test_one("Sat,Sun 12-05 08:05:40", "Sat,Sun *-12-05 08:05:40");
+ test_one("Sat,Sun 08:05:40", "Sat,Sun *-*-* 08:05:40");
+ test_one("2003-03-05 05:40", "2003-03-05 05:40:00");
+ test_one("2003-03-05", "2003-03-05 00:00:00");
+ test_one("03-05", "*-03-05 00:00:00");
+ test_one("hourly", "*-*-* *:00:00");
+ test_one("daily", "*-*-* 00:00:00");
+ test_one("monthly", "*-*-01 00:00:00");
+ test_one("weekly", "Mon *-*-* 00:00:00");
+ test_one("*:2/3", "*-*-* *:02/3:00");
+
+ assert_se(calendar_spec_from_string("test", &c) < 0);
+ assert_se(calendar_spec_from_string("", &c) < 0);
+ assert_se(calendar_spec_from_string("7", &c) < 0);
+ assert_se(calendar_spec_from_string("121212:1:2", &c) < 0);
+
+ return 0;
+}
diff --git a/src/test/test-cgroup-util.c b/src/test/test-cgroup-util.c
new file mode 100644
index 0000000000..c9634d42b0
--- /dev/null
+++ b/src/test/test-cgroup-util.c
@@ -0,0 +1,183 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Zbigniew Jędrzejewski-Szmek
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+
+#include "util.h"
+#include "cgroup-util.h"
+
+static void check_p_d_u(const char *path, int code, const char *result) {
+ _cleanup_free_ char *unit = NULL;
+
+ assert_se(cg_path_decode_unit(path, &unit) == code);
+ assert_se(streq_ptr(unit, result));
+}
+
+static void test_path_decode_unit(void) {
+ check_p_d_u("getty@.service/getty@tty2.service", 0, "getty@tty2.service");
+ check_p_d_u("getty@.service/getty@tty2.service/xxx", 0, "getty@tty2.service");
+ check_p_d_u("getty@.service/", -EINVAL, NULL);
+ check_p_d_u("getty@.service", -EINVAL, NULL);
+ check_p_d_u("getty.service", 0, "getty.service");
+ check_p_d_u("getty", -EINVAL, NULL);
+}
+
+static void check_p_g_u(const char *path, int code, const char *result) {
+ _cleanup_free_ char *unit = NULL;
+
+ assert_se(cg_path_get_unit(path, &unit) == code);
+ assert_se(streq_ptr(unit, result));
+}
+
+static void check_p_g_u_u(const char *path, int code, const char *result) {
+ _cleanup_free_ char *unit = NULL;
+
+ assert_se(cg_path_get_user_unit(path, &unit) == code);
+ assert_se(streq_ptr(unit, result));
+}
+
+static void test_path_get_unit(void) {
+ check_p_g_u("/system/foobar.service/sdfdsaf", 0, "foobar.service");
+ check_p_g_u("/system/getty@.service/getty@tty5.service", 0, "getty@tty5.service");
+ check_p_g_u("/system/getty@.service/getty@tty5.service/aaa/bbb", 0, "getty@tty5.service");
+ check_p_g_u("/system/getty@.service/getty@tty5.service/", 0, "getty@tty5.service");
+ check_p_g_u("/system/getty@tty6.service/tty5", 0, "getty@tty6.service");
+ check_p_g_u("sadfdsafsda", -ENOENT, NULL);
+ check_p_g_u("/system/getty####@tty6.service/tty5", -EINVAL, NULL);
+}
+
+static void test_path_get_user_unit(void) {
+ check_p_g_u_u("/user/lennart/2/systemd-21548/foobar.service", 0, "foobar.service");
+ check_p_g_u_u("/user/lennart/2/systemd-21548/foobar.service/waldo", 0, "foobar.service");
+ check_p_g_u_u("/user/lennart/2/systemd-21548/foobar.service/waldo/uuuux", 0, "foobar.service");
+ check_p_g_u_u("/user/lennart/2/systemd-21548/waldo/waldo/uuuux", -EINVAL, NULL);
+ check_p_g_u_u("/user/lennart/2/foobar.service", -ENOENT, NULL);
+ check_p_g_u_u("/user/lennart/2/systemd-21548/foobar@.service/foobar@pie.service/pa/po", 0, "foobar@pie.service");
+}
+
+static void test_get_paths(void) {
+ _cleanup_free_ char *a = NULL, *b = NULL, *c = NULL, *d = NULL;
+
+ assert_se(cg_get_root_path(&a) >= 0);
+ log_info("Root = %s", a);
+
+ assert_se(cg_get_system_path(&b) >= 0);
+ log_info("System = %s", b);
+
+ assert_se(cg_get_user_path(&c) >= 0);
+ log_info("User = %s", c);
+
+ assert_se(cg_get_machine_path("harley", &d) >= 0);
+ log_info("Machine = %s", d);
+}
+
+static void test_proc(void) {
+ _cleanup_closedir_ DIR *d = NULL;
+ struct dirent *de;
+ int r;
+
+ d = opendir("/proc");
+ assert_se(d);
+
+ FOREACH_DIRENT(de, d, break) {
+ _cleanup_free_ char *path = NULL, *path_shifted = NULL, *session = NULL, *unit = NULL, *user_unit = NULL, *machine = NULL, *prefix = NULL;
+ pid_t pid;
+ uid_t uid = (uid_t) -1;
+
+ if (de->d_type != DT_DIR &&
+ de->d_type != DT_UNKNOWN)
+ continue;
+
+ r = parse_pid(de->d_name, &pid);
+ if (r < 0)
+ continue;
+
+ if (is_kernel_thread(pid))
+ continue;
+
+ cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &path);
+ cg_pid_get_path_shifted(pid, &prefix, &path_shifted);
+ cg_pid_get_owner_uid(pid, &uid);
+ cg_pid_get_session(pid, &session);
+ cg_pid_get_unit(pid, &unit);
+ cg_pid_get_user_unit(pid, &user_unit);
+ cg_pid_get_machine_name(pid, &machine);
+
+ printf("%lu\t%s\t%s\t%s\t%lu\t%s\t%s\t%s\t%s\n",
+ (unsigned long) pid,
+ path,
+ prefix,
+ path_shifted,
+ (unsigned long) uid,
+ session,
+ unit,
+ user_unit,
+ machine);
+ }
+}
+
+static void test_escape_one(const char *s, const char *r) {
+ _cleanup_free_ char *b;
+
+ b = cg_escape(s);
+ assert_se(b);
+ assert_se(streq(b, r));
+
+ assert_se(streq(cg_unescape(b), s));
+}
+
+static void test_escape(void) {
+ test_escape_one("foobar", "foobar");
+ test_escape_one(".foobar", "_.foobar");
+ test_escape_one("foobar.service", "foobar.service");
+ test_escape_one("cgroup.service", "_cgroup.service");
+ test_escape_one("cpu.service", "_cpu.service");
+ test_escape_one("tasks", "_tasks");
+ test_escape_one("_foobar", "__foobar");
+ test_escape_one("", "_");
+ test_escape_one("_", "__");
+ test_escape_one(".", "_.");
+}
+
+static void test_controller_is_valid(void) {
+ assert_se(cg_controller_is_valid("foobar", false));
+ assert_se(cg_controller_is_valid("foo_bar", false));
+ assert_se(cg_controller_is_valid("name=foo", true));
+ assert_se(!cg_controller_is_valid("", false));
+ assert_se(!cg_controller_is_valid("name=", true));
+ assert_se(!cg_controller_is_valid("=", false));
+ assert_se(!cg_controller_is_valid("cpu,cpuacct", false));
+ assert_se(!cg_controller_is_valid("_", false));
+ assert_se(!cg_controller_is_valid("_foobar", false));
+ assert_se(!cg_controller_is_valid("tatü", false));
+}
+
+int main(void) {
+ test_path_decode_unit();
+ test_path_get_unit();
+ test_path_get_user_unit();
+ test_get_paths();
+ test_proc();
+ test_escape();
+ test_controller_is_valid();
+
+ return 0;
+}
diff --git a/src/test/test-cgroup.c b/src/test/test-cgroup.c
new file mode 100644
index 0000000000..3a3489d6a2
--- /dev/null
+++ b/src/test/test-cgroup.c
@@ -0,0 +1,105 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <unistd.h>
+#include <string.h>
+
+#include "cgroup-util.h"
+#include "path-util.h"
+#include "util.h"
+#include "log.h"
+
+int main(int argc, char*argv[]) {
+ char *path;
+ char *c, *p;
+
+ assert_se(cg_create(SYSTEMD_CGROUP_CONTROLLER, "/test-a", NULL) == 0);
+ assert_se(cg_create(SYSTEMD_CGROUP_CONTROLLER, "/test-a", NULL) == 0);
+ assert_se(cg_create(SYSTEMD_CGROUP_CONTROLLER, "/test-b", NULL) == 0);
+ assert_se(cg_create(SYSTEMD_CGROUP_CONTROLLER, "/test-b/test-c", NULL) == 0);
+ assert_se(cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, "/test-b", 0) == 0);
+
+ assert_se(cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, getpid(), &path) == 0);
+ assert_se(streq(path, "/test-b"));
+ free(path);
+
+ assert_se(cg_attach(SYSTEMD_CGROUP_CONTROLLER, "/test-a", 0) == 0);
+
+ assert_se(cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, getpid(), &path) == 0);
+ assert_se(path_equal(path, "/test-a"));
+ free(path);
+
+ assert_se(cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, "/test-b/test-d", 0) == 0);
+
+ assert_se(cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, getpid(), &path) == 0);
+ assert_se(path_equal(path, "/test-b/test-d"));
+ free(path);
+
+ assert_se(cg_get_path(SYSTEMD_CGROUP_CONTROLLER, "/test-b/test-d", NULL, &path) == 0);
+ assert_se(path_equal(path, "/sys/fs/cgroup/systemd/test-b/test-d"));
+ free(path);
+
+ assert_se(cg_is_empty(SYSTEMD_CGROUP_CONTROLLER, "/test-a", false) > 0);
+ assert_se(cg_is_empty(SYSTEMD_CGROUP_CONTROLLER, "/test-b", false) > 0);
+ assert_se(cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, "/test-a", false) > 0);
+ assert_se(cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, "/test-b", false) == 0);
+
+ assert_se(cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, "/test-a", 0, false, false, false, NULL) == 0);
+ assert_se(cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, "/test-b", 0, false, false, false, NULL) > 0);
+
+ assert_se(cg_migrate_recursive(SYSTEMD_CGROUP_CONTROLLER, "/test-b", SYSTEMD_CGROUP_CONTROLLER, "/test-a", false, false) > 0);
+
+ assert_se(cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, "/test-a", false) == 0);
+ assert_se(cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, "/test-b", false) > 0);
+
+ assert_se(cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, "/test-a", 0, false, false, false, NULL) > 0);
+ assert_se(cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, "/test-b", 0, false, false, false, NULL) == 0);
+
+ cg_trim(SYSTEMD_CGROUP_CONTROLLER, "/", false);
+
+ assert_se(cg_delete(SYSTEMD_CGROUP_CONTROLLER, "/test-b") < 0);
+ assert_se(cg_delete(SYSTEMD_CGROUP_CONTROLLER, "/test-a") >= 0);
+
+ assert_se(cg_split_spec("foobar:/", &c, &p) == 0);
+ assert(streq(c, "foobar"));
+ assert(streq(p, "/"));
+ free(c);
+ free(p);
+
+ assert_se(cg_split_spec("foobar:", &c, &p) < 0);
+ assert_se(cg_split_spec("foobar:asdfd", &c, &p) < 0);
+ assert_se(cg_split_spec(":///", &c, &p) < 0);
+ assert_se(cg_split_spec(":", &c, &p) < 0);
+ assert_se(cg_split_spec("", &c, &p) < 0);
+ assert_se(cg_split_spec("fo/obar:/", &c, &p) < 0);
+
+ assert_se(cg_split_spec("/", &c, &p) >= 0);
+ assert(c == NULL);
+ assert(streq(p, "/"));
+ free(p);
+
+ assert_se(cg_split_spec("foo", &c, &p) >= 0);
+ assert(streq(c, "foo"));
+ assert(p == NULL);
+ free(c);
+
+ return 0;
+}
diff --git a/src/test/test-daemon.c b/src/test/test-daemon.c
new file mode 100644
index 0000000000..3215f0c560
--- /dev/null
+++ b/src/test/test-daemon.c
@@ -0,0 +1,37 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <unistd.h>
+
+#include <systemd/sd-daemon.h>
+
+int main(int argc, char*argv[]) {
+
+ sd_notify(0, "STATUS=Starting up");
+ sleep(5);
+ sd_notify(0,
+ "STATUS=Running\n"
+ "READY=1");
+ sleep(10);
+ sd_notify(0, "STATUS=Quitting");
+
+ return 0;
+}
diff --git a/src/test/test-date.c b/src/test/test-date.c
new file mode 100644
index 0000000000..40ffc17b2f
--- /dev/null
+++ b/src/test/test-date.c
@@ -0,0 +1,61 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <string.h>
+
+#include "util.h"
+
+static void test_one(const char *p) {
+ usec_t t, q;
+ char buf[FORMAT_TIMESTAMP_MAX], buf_relative[FORMAT_TIMESTAMP_RELATIVE_MAX];
+
+ assert_se(parse_timestamp(p, &t) >= 0);
+ log_info("%s", format_timestamp(buf, sizeof(buf), t));
+
+ /* Chop off timezone */
+ *strrchr(buf, ' ') = 0;
+
+ assert_se(parse_timestamp(buf, &q) >= 0);
+ assert_se(q == t);
+
+ log_info("%s", strna(format_timestamp_relative(buf_relative, sizeof(buf_relative), t)));
+ assert_se(parse_timestamp(buf, &q) >= 0);
+}
+
+int main(int argc, char *argv[]) {
+ test_one("17:41");
+ test_one("18:42:44");
+ test_one("12-10-02 12:13:14");
+ test_one("12-10-2 12:13:14");
+ test_one("12-10-03 12:13");
+ test_one("2012-12-30 18:42");
+ test_one("2012-10-02");
+ test_one("Tue 2012-10-02");
+ test_one("now");
+ test_one("yesterday");
+ test_one("today");
+ test_one("tomorrow");
+ test_one("+2d");
+ test_one("+2y 4d");
+ test_one("5months ago");
+
+ return 0;
+}
diff --git a/src/test/test-efivars.c b/src/test/test-efivars.c
new file mode 100644
index 0000000000..43ea5917b6
--- /dev/null
+++ b/src/test/test-efivars.c
@@ -0,0 +1,47 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "util.h"
+#include "log.h"
+#include "efivars.h"
+
+int main(int argc, char* argv[]) {
+ char s[MAX(FORMAT_TIMESPAN_MAX, FORMAT_TIMESTAMP_MAX)];
+ int r;
+ dual_timestamp fw, l, k;
+
+ dual_timestamp_from_monotonic(&k, 0);
+
+ r = efi_get_boot_timestamps(NULL, &fw, &l);
+ if (r < 0) {
+ log_error("Failed to read variables: %s", strerror(-r));
+ return 1;
+ }
+
+ log_info("Firmware began %s before kernel.", format_timespan(s, sizeof(s), fw.monotonic, 0));
+ log_info("Loader began %s before kernel.", format_timespan(s, sizeof(s), l.monotonic, 0));
+
+ log_info("Firmware began %s.", format_timestamp(s, sizeof(s), fw.realtime));
+ log_info("Loader began %s.", format_timestamp(s, sizeof(s), l.realtime));
+ log_info("Kernel began %s.", format_timestamp(s, sizeof(s), k.realtime));
+
+ return 0;
+}
diff --git a/src/test/test-engine.c b/src/test/test-engine.c
new file mode 100644
index 0000000000..0f3862226a
--- /dev/null
+++ b/src/test/test-engine.c
@@ -0,0 +1,99 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include <errno.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "manager.h"
+
+int main(int argc, char *argv[]) {
+ Manager *m = NULL;
+ Unit *a = NULL, *b = NULL, *c = NULL, *d = NULL, *e = NULL, *g = NULL, *h = NULL;
+ Job *j;
+
+ assert_se(set_unit_path("test") >= 0);
+
+ assert_se(manager_new(SYSTEMD_SYSTEM, &m) >= 0);
+
+ printf("Load1:\n");
+ assert_se(manager_load_unit(m, "a.service", NULL, NULL, &a) >= 0);
+ assert_se(manager_load_unit(m, "b.service", NULL, NULL, &b) >= 0);
+ assert_se(manager_load_unit(m, "c.service", NULL, NULL, &c) >= 0);
+ manager_dump_units(m, stdout, "\t");
+
+ printf("Test1: (Trivial)\n");
+ assert_se(manager_add_job(m, JOB_START, c, JOB_REPLACE, false, NULL, &j) == 0);
+ manager_dump_jobs(m, stdout, "\t");
+
+ printf("Load2:\n");
+ manager_clear_jobs(m);
+ assert_se(manager_load_unit(m, "d.service", NULL, NULL, &d) >= 0);
+ assert_se(manager_load_unit(m, "e.service", NULL, NULL, &e) >= 0);
+ manager_dump_units(m, stdout, "\t");
+
+ printf("Test2: (Cyclic Order, Unfixable)\n");
+ assert_se(manager_add_job(m, JOB_START, d, JOB_REPLACE, false, NULL, &j) == -ENOEXEC);
+ manager_dump_jobs(m, stdout, "\t");
+
+ printf("Test3: (Cyclic Order, Fixable, Garbage Collector)\n");
+ assert_se(manager_add_job(m, JOB_START, e, JOB_REPLACE, false, NULL, &j) == 0);
+ manager_dump_jobs(m, stdout, "\t");
+
+ printf("Test4: (Identical transaction)\n");
+ assert_se(manager_add_job(m, JOB_START, e, JOB_FAIL, false, NULL, &j) == 0);
+ manager_dump_jobs(m, stdout, "\t");
+
+ printf("Load3:\n");
+ assert_se(manager_load_unit(m, "g.service", NULL, NULL, &g) >= 0);
+ manager_dump_units(m, stdout, "\t");
+
+ printf("Test5: (Colliding transaction, fail)\n");
+ assert_se(manager_add_job(m, JOB_START, g, JOB_FAIL, false, NULL, &j) == -EEXIST);
+
+ printf("Test6: (Colliding transaction, replace)\n");
+ assert_se(manager_add_job(m, JOB_START, g, JOB_REPLACE, false, NULL, &j) == 0);
+ manager_dump_jobs(m, stdout, "\t");
+
+ printf("Test7: (Unmergeable job type, fail)\n");
+ assert_se(manager_add_job(m, JOB_STOP, g, JOB_FAIL, false, NULL, &j) == -EEXIST);
+
+ printf("Test8: (Mergeable job type, fail)\n");
+ assert_se(manager_add_job(m, JOB_RESTART, g, JOB_FAIL, false, NULL, &j) == 0);
+ manager_dump_jobs(m, stdout, "\t");
+
+ printf("Test9: (Unmergeable job type, replace)\n");
+ assert_se(manager_add_job(m, JOB_STOP, g, JOB_REPLACE, false, NULL, &j) == 0);
+ manager_dump_jobs(m, stdout, "\t");
+
+ printf("Load4:\n");
+ assert_se(manager_load_unit(m, "h.service", NULL, NULL, &h) >= 0);
+ manager_dump_units(m, stdout, "\t");
+
+ printf("Test10: (Unmergeable job type of auxiliary job, fail)\n");
+ assert_se(manager_add_job(m, JOB_START, h, JOB_FAIL, false, NULL, &j) == 0);
+ manager_dump_jobs(m, stdout, "\t");
+
+ manager_free(m);
+
+ return 0;
+}
diff --git a/src/test/test-env-replace.c b/src/test/test-env-replace.c
new file mode 100644
index 0000000000..0274e97618
--- /dev/null
+++ b/src/test/test-env-replace.c
@@ -0,0 +1,218 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <unistd.h>
+#include <string.h>
+
+#include "util.h"
+#include "strv.h"
+#include "env-util.h"
+
+static void test_strv_env_delete(void) {
+ _cleanup_strv_free_ char **a = NULL, **b = NULL, **c = NULL, **d = NULL;
+
+ a = strv_new("FOO=BAR", "WALDO=WALDO", "WALDO=", "PIEP", "SCHLUMPF=SMURF", NULL);
+ assert_se(a);
+
+ b = strv_new("PIEP", "FOO", NULL);
+ assert_se(b);
+
+ c = strv_new("SCHLUMPF", NULL);
+ assert_se(c);
+
+ d = strv_env_delete(a, 2, b, c);
+ assert_se(d);
+
+ assert_se(streq(d[0], "WALDO=WALDO"));
+ assert_se(streq(d[1], "WALDO="));
+ assert_se(strv_length(d) == 2);
+}
+
+static void test_strv_env_unset(void) {
+ _cleanup_strv_free_ char **l = NULL;
+
+ l = strv_new("PIEP", "SCHLUMPF=SMURFF", "NANANANA=YES", NULL);
+ assert_se(l);
+
+ assert_se(strv_env_unset(l, "SCHLUMPF") == l);
+
+ assert_se(streq(l[0], "PIEP"));
+ assert_se(streq(l[1], "NANANANA=YES"));
+ assert_se(strv_length(l) == 2);
+}
+
+static void test_strv_env_set(void) {
+ _cleanup_strv_free_ char **l = NULL, **r = NULL;
+
+ l = strv_new("PIEP", "SCHLUMPF=SMURFF", "NANANANA=YES", NULL);
+ assert_se(l);
+
+ r = strv_env_set(l, "WALDO=WALDO");
+ assert_se(r);
+
+ assert_se(streq(r[0], "PIEP"));
+ assert_se(streq(r[1], "SCHLUMPF=SMURFF"));
+ assert_se(streq(r[2], "NANANANA=YES"));
+ assert_se(streq(r[3], "WALDO=WALDO"));
+ assert_se(strv_length(r) == 4);
+}
+
+static void test_strv_env_merge(void) {
+ _cleanup_strv_free_ char **a = NULL, **b = NULL, **r = NULL;
+
+ a = strv_new("FOO=BAR", "WALDO=WALDO", "WALDO=", "PIEP", "SCHLUMPF=SMURF", NULL);
+ assert_se(a);
+
+ b = strv_new("FOO=KKK", "FOO=", "PIEP=", "SCHLUMPF=SMURFF", "NANANANA=YES", NULL);
+ assert_se(b);
+
+ r = strv_env_merge(2, a, b);
+ assert_se(r);
+ assert_se(streq(r[0], "FOO="));
+ assert_se(streq(r[1], "WALDO="));
+ assert_se(streq(r[2], "PIEP"));
+ assert_se(streq(r[3], "SCHLUMPF=SMURFF"));
+ assert_se(streq(r[4], "PIEP="));
+ assert_se(streq(r[5], "NANANANA=YES"));
+ assert_se(strv_length(r) == 6);
+
+ assert_se(strv_env_clean(r) == r);
+ assert_se(streq(r[0], "FOO="));
+ assert_se(streq(r[1], "WALDO="));
+ assert_se(streq(r[2], "SCHLUMPF=SMURFF"));
+ assert_se(streq(r[3], "PIEP="));
+ assert_se(streq(r[4], "NANANANA=YES"));
+ assert_se(strv_length(r) == 5);
+}
+
+static void test_replace_env_arg(void) {
+ const char *env[] = {
+ "FOO=BAR BAR",
+ "BAR=waldo",
+ NULL
+ };
+ const char *line[] = {
+ "FOO$FOO",
+ "FOO$FOOFOO",
+ "FOO${FOO}$FOO",
+ "FOO${FOO}",
+ "${FOO}",
+ "$FOO",
+ "$FOO$FOO",
+ "${FOO}${BAR}",
+ "${FOO",
+ NULL
+ };
+ _cleanup_strv_free_ char **r = NULL;
+
+ r = replace_env_argv((char**) line, (char**) env);
+ assert_se(r);
+ assert_se(streq(r[0], "FOO$FOO"));
+ assert_se(streq(r[1], "FOO$FOOFOO"));
+ assert_se(streq(r[2], "FOOBAR BAR$FOO"));
+ assert_se(streq(r[3], "FOOBAR BAR"));
+ assert_se(streq(r[4], "BAR BAR"));
+ assert_se(streq(r[5], "BAR"));
+ assert_se(streq(r[6], "BAR"));
+ assert_se(streq(r[7], "BAR BARwaldo"));
+ assert_se(streq(r[8], "${FOO"));
+ assert_se(strv_length(r) == 9);
+}
+
+static void test_one_normalize(const char *input, const char *output) {
+ _cleanup_free_ char *t;
+
+ t = normalize_env_assignment(input);
+ assert_se(t);
+ assert_se(streq(t, output));
+}
+
+static void test_normalize_env_assignment(void) {
+ test_one_normalize("foo=bar", "foo=bar");
+ test_one_normalize("=bar", "=bar");
+ test_one_normalize("foo=", "foo=");
+ test_one_normalize("=", "=");
+ test_one_normalize("", "");
+ test_one_normalize("a=\"waldo\"", "a=waldo");
+ test_one_normalize("a=\"waldo", "a=\"waldo");
+ test_one_normalize("a=waldo\"", "a=waldo\"");
+ test_one_normalize("a=\'", "a='");
+ test_one_normalize("a=\'\'", "a=");
+ test_one_normalize(" xyz ", "xyz");
+ test_one_normalize(" xyz = bar ", "xyz=bar");
+ test_one_normalize(" xyz = 'bar ' ", "xyz=bar ");
+ test_one_normalize(" ' xyz' = 'bar ' ", "' xyz'=bar ");
+}
+
+static void test_env_clean(void) {
+ _cleanup_strv_free_ char **e;
+
+ e = strv_new("FOOBAR=WALDO",
+ "FOOBAR=WALDO",
+ "FOOBAR",
+ "F",
+ "X=",
+ "F=F",
+ "=",
+ "=F",
+ "",
+ "0000=000",
+ "äöüß=abcd",
+ "abcd=äöüß",
+ "xyz\n=xyz",
+ "xyz=xyz\n",
+ "another=one",
+ "another=final one",
+ NULL);
+ assert_se(e);
+ assert_se(!strv_env_is_valid(e));
+ assert_se(strv_env_clean(e) == e);
+ assert_se(strv_env_is_valid(e));
+
+ assert_se(streq(e[0], "FOOBAR=WALDO"));
+ assert_se(streq(e[1], "X="));
+ assert_se(streq(e[2], "F=F"));
+ assert_se(streq(e[3], "abcd=äöüß"));
+ assert_se(streq(e[4], "another=final one"));
+ assert_se(e[5] == NULL);
+}
+
+static void test_env_name_is_valid(void) {
+ assert_se(env_name_is_valid("test"));
+
+ assert_se(!env_name_is_valid(NULL));
+ assert_se(!env_name_is_valid(""));
+ assert_se(!env_name_is_valid("5_starting_with_a_number_is_wrong"));
+ assert_se(!env_name_is_valid("#¤%&?_only_numbers_letters_and_underscore_allowed"));
+}
+
+int main(int argc, char *argv[]) {
+ test_strv_env_delete();
+ test_strv_env_unset();
+ test_strv_env_set();
+ test_strv_env_merge();
+ test_replace_env_arg();
+ test_normalize_env_assignment();
+ test_env_clean();
+ test_env_name_is_valid();
+
+ return 0;
+}
diff --git a/src/test/test-fileio.c b/src/test/test-fileio.c
new file mode 100644
index 0000000000..d56f7cc856
--- /dev/null
+++ b/src/test/test-fileio.c
@@ -0,0 +1,145 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include <fcntl.h>
+#include <unistd.h>
+
+#include "util.h"
+#include "fileio.h"
+#include "strv.h"
+#include "env-util.h"
+
+static void test_parse_env_file(void) {
+ char t[] = "/tmp/test-parse-env-file-XXXXXX";
+ int fd, r;
+ FILE *f;
+ _cleanup_free_ char *one = NULL, *two = NULL, *three = NULL, *four = NULL, *five = NULL,
+ *six = NULL, *seven = NULL, *eight = NULL, *nine = NULL, *ten = NULL;
+ _cleanup_strv_free_ char **a = NULL, **b = NULL;
+ char **i;
+ unsigned k;
+
+ fd = mkostemp(t, O_CLOEXEC);
+ assert_se(fd >= 0);
+
+ f = fdopen(fd, "w");
+ assert_se(f);
+
+ fputs("one=BAR \n"
+ "# comment\n"
+ " # comment \n"
+ " ; comment \n"
+ " two = bar \n"
+ "invalid line\n"
+ "invalid line #comment\n"
+ "three = \"333\n"
+ "xxxx\"\n"
+ "four = \'44\\\"44\'\n"
+ "five = \'55\\\'55\' \"FIVE\" cinco \n"
+ "six = seis sechs\\\n"
+ " sis\n"
+ "seven=\"sevenval\" #nocomment\n"
+ "eight=eightval #nocomment\n"
+ "export nine=nineval\n"
+ "ten=", f);
+
+ fflush(f);
+ fclose(f);
+
+ r = load_env_file(t, NULL, &a);
+ assert_se(r >= 0);
+
+ STRV_FOREACH(i, a)
+ log_info("Got: <%s>", *i);
+
+ assert_se(streq(a[0], "one=BAR"));
+ assert_se(streq(a[1], "two=bar"));
+ assert_se(streq(a[2], "three=333\nxxxx"));
+ assert_se(streq(a[3], "four=44\"44"));
+ assert_se(streq(a[4], "five=55\'55FIVEcinco"));
+ assert_se(streq(a[5], "six=seis sechs sis"));
+ assert_se(streq(a[6], "seven=sevenval#nocomment"));
+ assert_se(streq(a[7], "eight=eightval #nocomment"));
+ assert_se(streq(a[8], "export nine=nineval"));
+ assert_se(streq(a[9], "ten="));
+ assert_se(a[10] == NULL);
+
+ strv_env_clean_log(a, "/tmp/test-fileio");
+
+ k = 0;
+ STRV_FOREACH(i, b) {
+ log_info("Got2: <%s>", *i);
+ assert_se(streq(*i, a[k++]));
+ }
+
+ r = parse_env_file(
+ t, NULL,
+ "one", &one,
+ "two", &two,
+ "three", &three,
+ "four", &four,
+ "five", &five,
+ "six", &six,
+ "seven", &seven,
+ "eight", &eight,
+ "export nine", &nine,
+ "ten", &ten,
+ NULL);
+
+ assert_se(r >= 0);
+
+ log_info("one=[%s]", strna(one));
+ log_info("two=[%s]", strna(two));
+ log_info("three=[%s]", strna(three));
+ log_info("four=[%s]", strna(four));
+ log_info("five=[%s]", strna(five));
+ log_info("six=[%s]", strna(six));
+ log_info("seven=[%s]", strna(seven));
+ log_info("eight=[%s]", strna(eight));
+ log_info("export nine=[%s]", strna(nine));
+ log_info("ten=[%s]", strna(nine));
+
+ assert_se(streq(one, "BAR"));
+ assert_se(streq(two, "bar"));
+ assert_se(streq(three, "333\nxxxx"));
+ assert_se(streq(four, "44\"44"));
+ assert_se(streq(five, "55\'55FIVEcinco"));
+ assert_se(streq(six, "seis sechs sis"));
+ assert_se(streq(seven, "sevenval#nocomment"));
+ assert_se(streq(eight, "eightval #nocomment"));
+ assert_se(streq(nine, "nineval"));
+ assert_se(ten == NULL);
+
+ r = write_env_file("/tmp/test-fileio", a);
+ assert_se(r >= 0);
+
+ r = load_env_file("/tmp/test-fileio", NULL, &b);
+ assert_se(r >= 0);
+
+ unlink(t);
+ unlink("/tmp/test-fileio");
+}
+
+int main(int argc, char *argv[]) {
+ test_parse_env_file();
+ return 0;
+}
diff --git a/src/test/test-hashmap.c b/src/test/test-hashmap.c
new file mode 100644
index 0000000000..2aead79bb1
--- /dev/null
+++ b/src/test/test-hashmap.c
@@ -0,0 +1,508 @@
+/***
+ This file is part of systemd
+
+ Copyright 2013 Daniel Buch
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <inttypes.h>
+#include "strv.h"
+#include "util.h"
+#include "hashmap.h"
+
+static void test_hashmap_replace(void) {
+ Hashmap *m;
+ char *val1, *val2, *val3, *val4, *val5, *r;
+
+ m = hashmap_new(string_hash_func, string_compare_func);
+
+ val1 = strdup("val1");
+ assert_se(val1);
+ val2 = strdup("val2");
+ assert_se(val2);
+ val3 = strdup("val3");
+ assert_se(val3);
+ val4 = strdup("val4");
+ assert_se(val4);
+ val5 = strdup("val5");
+ assert_se(val5);
+
+ hashmap_put(m, "key 1", val1);
+ hashmap_put(m, "key 2", val2);
+ hashmap_put(m, "key 3", val3);
+ hashmap_put(m, "key 4", val4);
+
+ hashmap_replace(m, "key 3", val1);
+ r = hashmap_get(m, "key 3");
+ assert_se(streq(r, "val1"));
+
+ hashmap_replace(m, "key 5", val5);
+ r = hashmap_get(m, "key 5");
+ assert_se(streq(r, "val5"));
+
+ free(val1);
+ free(val2);
+ free(val3);
+ free(val4);
+ free(val5);
+ hashmap_free(m);
+}
+
+static void test_hashmap_copy(void) {
+ Hashmap *m, *copy;
+ char *val1, *val2, *val3, *val4, *r;
+
+ val1 = strdup("val1");
+ assert_se(val1);
+ val2 = strdup("val2");
+ assert_se(val2);
+ val3 = strdup("val3");
+ assert_se(val3);
+ val4 = strdup("val4");
+ assert_se(val4);
+
+ m = hashmap_new(string_hash_func, string_compare_func);
+
+ hashmap_put(m, "key 1", val1);
+ hashmap_put(m, "key 2", val2);
+ hashmap_put(m, "key 3", val3);
+ hashmap_put(m, "key 4", val4);
+
+ copy = hashmap_copy(m);
+
+ r = hashmap_get(copy, "key 1");
+ assert_se(streq(r, "val1"));
+ r = hashmap_get(copy, "key 2");
+ assert_se(streq(r, "val2"));
+ r = hashmap_get(copy, "key 3");
+ assert_se(streq(r, "val3"));
+ r = hashmap_get(copy, "key 4");
+ assert_se(streq(r, "val4"));
+
+ hashmap_free_free(copy);
+ hashmap_free(m);
+}
+
+static void test_hashmap_get_strv(void) {
+ Hashmap *m;
+ char **strv;
+ char *val1, *val2, *val3, *val4;
+
+ val1 = strdup("val1");
+ assert_se(val1);
+ val2 = strdup("val2");
+ assert_se(val2);
+ val3 = strdup("val3");
+ assert_se(val3);
+ val4 = strdup("val4");
+ assert_se(val4);
+
+ m = hashmap_new(string_hash_func, string_compare_func);
+
+ hashmap_put(m, "key 1", val1);
+ hashmap_put(m, "key 2", val2);
+ hashmap_put(m, "key 3", val3);
+ hashmap_put(m, "key 4", val4);
+
+ strv = hashmap_get_strv(m);
+
+ assert_se(streq(strv[0], "val1"));
+ assert_se(streq(strv[1], "val2"));
+ assert_se(streq(strv[2], "val3"));
+ assert_se(streq(strv[3], "val4"));
+
+ strv_free(strv);
+
+ hashmap_free(m);
+}
+
+static void test_hashmap_move_one(void) {
+ Hashmap *m, *n;
+ char *val1, *val2, *val3, *val4, *r;
+
+ val1 = strdup("val1");
+ assert_se(val1);
+ val2 = strdup("val2");
+ assert_se(val2);
+ val3 = strdup("val3");
+ assert_se(val3);
+ val4 = strdup("val4");
+ assert_se(val4);
+
+ m = hashmap_new(string_hash_func, string_compare_func);
+ n = hashmap_new(string_hash_func, string_compare_func);
+
+ hashmap_put(m, "key 1", val1);
+ hashmap_put(m, "key 2", val2);
+ hashmap_put(m, "key 3", val3);
+ hashmap_put(m, "key 4", val4);
+
+ hashmap_move_one(n, m, "key 3");
+ hashmap_move_one(n, m, "key 4");
+
+ r = hashmap_get(n, "key 3");
+ assert_se(r && streq(r, "val3"));
+ r = hashmap_get(n, "key 4");
+ assert_se(r && streq(r, "val4"));
+ r = hashmap_get(m, "key 3");
+ assert_se(!r);
+
+
+ hashmap_free_free(m);
+ hashmap_free_free(n);
+}
+
+static void test_hashmap_next(void) {
+ Hashmap *m;
+ char *val1, *val2, *val3, *val4, *r;
+
+ m = hashmap_new(string_hash_func, string_compare_func);
+ val1 = strdup("val1");
+ assert_se(val1);
+ val2 = strdup("val2");
+ assert_se(val2);
+ val3 = strdup("val3");
+ assert_se(val3);
+ val4 = strdup("val4");
+ assert_se(val4);
+
+ hashmap_put(m, "key 1", val1);
+ hashmap_put(m, "key 2", val2);
+ hashmap_put(m, "key 3", val3);
+ hashmap_put(m, "key 4", val4);
+
+ r = hashmap_next(m, "key 1");
+ assert_se(streq(r, val2));
+ r = hashmap_next(m, "key 2");
+ assert_se(streq(r, val3));
+ r = hashmap_next(m, "key 3");
+ assert_se(streq(r, val4));
+ r = hashmap_next(m, "key 4");
+ assert_se(!r);
+
+ hashmap_free_free(m);
+}
+
+static void test_hashmap_update(void) {
+ Hashmap *m;
+ char *val1, *val2, *r;
+
+ m = hashmap_new(string_hash_func, string_compare_func);
+ val1 = strdup("old_value");
+ assert_se(val1);
+ val2 = strdup("new_value");
+ assert_se(val2);
+
+ hashmap_put(m, "key 1", val1);
+ r = hashmap_get(m, "key 1");
+ assert_se(streq(r, "old_value"));
+
+ hashmap_update(m, "key 1", val2);
+ r = hashmap_get(m, "key 1");
+ assert_se(streq(r, "new_value"));
+
+ free(val1);
+ free(val2);
+ hashmap_free(m);
+}
+
+static void test_hashmap_put(void) {
+ Hashmap *m;
+ int valid_hashmap_put;
+
+ m = hashmap_new(string_hash_func, string_compare_func);
+
+ valid_hashmap_put = hashmap_put(m, "key 1", (void*) (const char *) "val 1");
+ assert_se(valid_hashmap_put == 1);
+
+ assert_se(m);
+ hashmap_free(m);
+}
+
+static void test_hashmap_ensure_allocated(void) {
+ Hashmap *m;
+ int valid_hashmap;
+
+ m = hashmap_new(string_hash_func, string_compare_func);
+
+ valid_hashmap = hashmap_ensure_allocated(&m, string_hash_func, string_compare_func);
+ assert_se(valid_hashmap == 0);
+
+ assert_se(m);
+ hashmap_free(m);
+}
+
+static void test_hashmap_foreach_key(void) {
+ Hashmap *m;
+ Iterator i;
+ bool key_found[] = { false, false, false, false };
+ const char *s;
+ const char *key;
+ static const char key_table[] =
+ "key 1\0"
+ "key 2\0"
+ "key 3\0"
+ "key 4\0";
+
+ m = hashmap_new(string_hash_func, string_compare_func);
+
+ NULSTR_FOREACH(key, key_table)
+ hashmap_put(m, key, (void*) (const char*) "my dummy val");
+
+ HASHMAP_FOREACH_KEY(s, key, m, i) {
+ if (!key_found[0] && streq(key, "key 1"))
+ key_found[0] = true;
+ else if (!key_found[1] && streq(key, "key 2"))
+ key_found[1] = true;
+ else if (!key_found[2] && streq(key, "key 3"))
+ key_found[2] = true;
+ else if (!key_found[3] && streq(key, "fail"))
+ key_found[3] = true;
+ }
+
+ assert_se(m);
+ assert_se(key_found[0] && key_found[1] && key_found[2] && !key_found[3]);
+
+ hashmap_free(m);
+}
+
+static void test_hashmap_foreach(void) {
+ Hashmap *m;
+ Iterator i;
+ bool value_found[] = { false, false, false, false };
+ char *val1, *val2, *val3, *val4, *s;
+
+ val1 = strdup("my val1");
+ assert_se(val1);
+ val2 = strdup("my val2");
+ assert_se(val2);
+ val3 = strdup("my val3");
+ assert_se(val3);
+ val4 = strdup("my val4");
+ assert_se(val4);
+
+ m = hashmap_new(string_hash_func, string_compare_func);
+
+ hashmap_put(m, "Key 1", val1);
+ hashmap_put(m, "Key 2", val2);
+ hashmap_put(m, "Key 3", val3);
+ hashmap_put(m, "Key 4", val4);
+
+ HASHMAP_FOREACH(s, m, i) {
+ if (!value_found[0] && streq(s, val1))
+ value_found[0] = true;
+ else if (!value_found[1] && streq(s, val2))
+ value_found[1] = true;
+ else if (!value_found[2] && streq(s, val3))
+ value_found[2] = true;
+ else if (!value_found[3] && streq(s, val4))
+ value_found[3] = true;
+ }
+
+ assert_se(m);
+ assert_se(value_found[0] && value_found[1] && value_found[2] && value_found[3]);
+
+ hashmap_free_free(m);
+}
+
+static void test_hashmap_foreach_backwards(void) {
+ Hashmap *m;
+ Iterator i;
+ char *val1, *val2, *val3, *val4, *s;
+ bool value_found[] = { false, false, false, false };
+
+ val1 = strdup("my val1");
+ assert_se(val1);
+ val2 = strdup("my val2");
+ assert_se(val2);
+ val3 = strdup("my val3");
+ assert_se(val3);
+ val4 = strdup("my val4");
+ assert_se(val4);
+
+ m = hashmap_new(string_hash_func, string_compare_func);
+ hashmap_put(m, "Key 1", val1);
+ hashmap_put(m, "Key 2", val2);
+ hashmap_put(m, "Key 3", val3);
+ hashmap_put(m, "Key 4", val4);
+
+ HASHMAP_FOREACH_BACKWARDS(s, m, i) {
+ if (!value_found[0] && streq(s, val1))
+ value_found[0] = true;
+ else if (!value_found[1] && streq(s, val2))
+ value_found[1] = true;
+ else if (!value_found[2] && streq(s, val3))
+ value_found[2] = true;
+ else if (!value_found[3] && streq(s, val4))
+ value_found[3] = true;
+ }
+
+ assert_se(m);
+ assert_se(value_found[0] && value_found[1] && value_found[2] && value_found[3]);
+
+ hashmap_free_free(m);
+}
+
+static void test_hashmap_merge(void) {
+ Hashmap *m;
+ Hashmap *n;
+ char *val1, *val2, *val3, *val4, *r;
+
+ val1 = strdup("my val1");
+ assert_se(val1);
+ val2 = strdup("my val2");
+ assert_se(val2);
+ val3 = strdup("my val3");
+ assert_se(val3);
+ val4 = strdup("my val4");
+ assert_se(val4);
+
+ n = hashmap_new(string_hash_func, string_compare_func);
+ m = hashmap_new(string_hash_func, string_compare_func);
+
+ hashmap_put(m, "Key 1", val1);
+ hashmap_put(m, "Key 2", val2);
+ hashmap_put(n, "Key 3", val3);
+ hashmap_put(n, "Key 4", val4);
+
+ assert_se(hashmap_merge(m, n) == 0);
+ r = hashmap_get(m, "Key 3");
+ assert_se(r && streq(r, "my val3"));
+ r = hashmap_get(m, "Key 4");
+ assert_se(r && streq(r, "my val4"));
+
+ assert_se(n);
+ assert_se(m);
+ hashmap_free(n);
+ hashmap_free_free(m);
+}
+
+static void test_hashmap_contains(void) {
+ Hashmap *m;
+ char *val1;
+
+ val1 = strdup("my val");
+ assert_se(val1);
+
+ m = hashmap_new(string_hash_func, string_compare_func);
+
+ assert_se(!hashmap_contains(m, "Key 1"));
+ hashmap_put(m, "Key 1", val1);
+ assert_se(hashmap_contains(m, "Key 1"));
+
+ assert_se(m);
+ hashmap_free_free(m);
+}
+
+static void test_hashmap_isempty(void) {
+ Hashmap *m;
+ char *val1;
+
+ val1 = strdup("my val");
+ assert_se(val1);
+
+ m = hashmap_new(string_hash_func, string_compare_func);
+
+ assert_se(hashmap_isempty(m));
+ hashmap_put(m, "Key 1", val1);
+ assert_se(!hashmap_isempty(m));
+
+ assert_se(m);
+ hashmap_free_free(m);
+}
+
+static void test_hashmap_size(void) {
+ Hashmap *m;
+ char *val1, *val2, *val3, *val4;
+
+ val1 = strdup("my val");
+ assert_se(val1);
+ val2 = strdup("my val");
+ assert_se(val2);
+ val3 = strdup("my val");
+ assert_se(val3);
+ val4 = strdup("my val");
+ assert_se(val4);
+
+ m = hashmap_new(string_hash_func, string_compare_func);
+
+ hashmap_put(m, "Key 1", val1);
+ hashmap_put(m, "Key 2", val2);
+ hashmap_put(m, "Key 3", val3);
+ hashmap_put(m, "Key 4", val4);
+
+ assert_se(m);
+ assert_se(hashmap_size(m) == 4);
+ hashmap_free_free(m);
+}
+
+static void test_hashmap_get(void) {
+ Hashmap *m;
+ char *r;
+ char *val;
+
+ val = strdup("my val");
+ assert_se(val);
+
+ m = hashmap_new(string_hash_func, string_compare_func);
+
+ hashmap_put(m, "Key 1", val);
+
+ r = hashmap_get(m, "Key 1");
+ assert_se(streq(r, val));
+
+ assert_se(m);
+ hashmap_free_free(m);
+}
+
+static void test_uint64_compare_func(void) {
+ assert_se(uint64_compare_func("a", "a") == 0);
+ assert_se(uint64_compare_func("a", "b") == -1);
+ assert_se(uint64_compare_func("b", "a") == 1);
+}
+
+static void test_trivial_compare_func(void) {
+ assert_se(trivial_compare_func(INT_TO_PTR('a'), INT_TO_PTR('a')) == 0);
+ assert_se(trivial_compare_func(INT_TO_PTR('a'), INT_TO_PTR('b')) == -1);
+ assert_se(trivial_compare_func(INT_TO_PTR('b'), INT_TO_PTR('a')) == 1);
+}
+
+static void test_string_compare_func(void) {
+ assert_se(!string_compare_func("fred", "wilma") == 0);
+ assert_se(string_compare_func("fred", "fred") == 0);
+}
+
+int main(int argc, const char *argv[])
+{
+ test_hashmap_copy();
+ test_hashmap_get_strv();
+ test_hashmap_move_one();
+ test_hashmap_next();
+ test_hashmap_replace();
+ test_hashmap_update();
+ test_hashmap_put();
+ test_hashmap_ensure_allocated();
+ test_hashmap_foreach();
+ test_hashmap_foreach_backwards();
+ test_hashmap_foreach_key();
+ test_hashmap_contains();
+ test_hashmap_merge();
+ test_hashmap_isempty();
+ test_hashmap_get();
+ test_hashmap_size();
+ test_uint64_compare_func();
+ test_trivial_compare_func();
+ test_string_compare_func();
+}
diff --git a/src/test/test-hostname.c b/src/test/test-hostname.c
new file mode 100644
index 0000000000..ad4f285619
--- /dev/null
+++ b/src/test/test-hostname.c
@@ -0,0 +1,38 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <string.h>
+#include <stdio.h>
+#include <fcntl.h>
+
+#include "hostname-setup.h"
+#include "util.h"
+
+int main(int argc, char* argv[]) {
+ int r;
+
+ r = hostname_setup();
+ if (r < 0)
+ fprintf(stderr, "hostname: %s\n", strerror(-r));
+
+ return 0;
+}
diff --git a/src/test/test-id128.c b/src/test/test-id128.c
new file mode 100644
index 0000000000..2ed8e292e6
--- /dev/null
+++ b/src/test/test-id128.c
@@ -0,0 +1,75 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <string.h>
+
+#include <systemd/sd-id128.h>
+
+#include "util.h"
+#include "macro.h"
+
+#define ID128_WALDI SD_ID128_MAKE(01, 02, 03, 04, 05, 06, 07, 08, 09, 0a, 0b, 0c, 0d, 0e, 0f, 10)
+#define STR_WALDI "0102030405060708090a0b0c0d0e0f10"
+#define UUID_WALDI "01020304-0506-0708-090a-0b0c0d0e0f10"
+
+int main(int argc, char *argv[]) {
+ sd_id128_t id, id2;
+ char t[33];
+ _cleanup_free_ char *b = NULL;
+
+ assert_se(sd_id128_randomize(&id) == 0);
+ printf("random: %s\n", sd_id128_to_string(id, t));
+
+ assert_se(sd_id128_from_string(t, &id2) == 0);
+ assert_se(sd_id128_equal(id, id2));
+
+ assert_se(sd_id128_get_machine(&id) == 0);
+ printf("machine: %s\n", sd_id128_to_string(id, t));
+
+ assert_se(sd_id128_get_boot(&id) == 0);
+ printf("boot: %s\n", sd_id128_to_string(id, t));
+
+ printf("waldi: %s\n", sd_id128_to_string(ID128_WALDI, t));
+ assert_se(streq(t, STR_WALDI));
+
+ assert_se(asprintf(&b, SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(ID128_WALDI)) == 32);
+ printf("waldi2: %s\n", b);
+ assert_se(streq(t, b));
+
+ assert_se(sd_id128_from_string(UUID_WALDI, &id) >= 0);
+ assert_se(sd_id128_equal(id, ID128_WALDI));
+
+ assert_se(sd_id128_from_string("", &id) < 0);
+ assert_se(sd_id128_from_string("01020304-0506-0708-090a-0b0c0d0e0f101", &id) < 0);
+ assert_se(sd_id128_from_string("01020304-0506-0708-090a-0b0c0d0e0f10-", &id) < 0);
+ assert_se(sd_id128_from_string("01020304-0506-0708-090a0b0c0d0e0f10", &id) < 0);
+ assert_se(sd_id128_from_string("010203040506-0708-090a-0b0c0d0e0f10", &id) < 0);
+
+ assert_se(id128_is_valid(STR_WALDI));
+ assert_se(id128_is_valid(UUID_WALDI));
+ assert_se(!id128_is_valid(""));
+ assert_se(!id128_is_valid("01020304-0506-0708-090a-0b0c0d0e0f101"));
+ assert_se(!id128_is_valid("01020304-0506-0708-090a-0b0c0d0e0f10-"));
+ assert_se(!id128_is_valid("01020304-0506-0708-090a0b0c0d0e0f10"));
+ assert_se(!id128_is_valid("010203040506-0708-090a-0b0c0d0e0f10"));
+
+ return 0;
+}
diff --git a/src/test/test-install.c b/src/test/test-install.c
new file mode 100644
index 0000000000..2c1b9efcb8
--- /dev/null
+++ b/src/test/test-install.c
@@ -0,0 +1,265 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <string.h>
+#include <stdio.h>
+#include <fcntl.h>
+
+#include "util.h"
+#include "path-util.h"
+#include "install.h"
+
+static void dump_changes(UnitFileChange *c, unsigned n) {
+ unsigned i;
+
+ assert(n == 0 || c);
+
+ for (i = 0; i < n; i++) {
+ if (c[i].type == UNIT_FILE_UNLINK)
+ printf("rm '%s'\n", c[i].path);
+ else if (c[i].type == UNIT_FILE_SYMLINK)
+ printf("ln -s '%s' '%s'\n", c[i].source, c[i].path);
+ }
+}
+
+int main(int argc, char* argv[]) {
+ Hashmap *h;
+ UnitFileList *p;
+ Iterator i;
+ int r;
+ const char *const files[] = { "avahi-daemon.service", NULL };
+ const char *const files2[] = { "/home/lennart/test.service", NULL };
+ UnitFileChange *changes = NULL;
+ unsigned n_changes = 0;
+
+ h = hashmap_new(string_hash_func, string_compare_func);
+ r = unit_file_get_list(UNIT_FILE_SYSTEM, NULL, h);
+ assert_se(r == 0);
+
+ HASHMAP_FOREACH(p, h, i) {
+ UnitFileState s;
+
+ s = unit_file_get_state(UNIT_FILE_SYSTEM, NULL, path_get_file_name(p->path));
+
+ assert_se(p->state == s);
+
+ fprintf(stderr, "%s (%s)\n",
+ p->path,
+ unit_file_state_to_string(p->state));
+ }
+
+ unit_file_list_free(h);
+
+ log_error("enable");
+
+ r = unit_file_enable(UNIT_FILE_SYSTEM, false, NULL, (char**) files, false, &changes, &n_changes);
+ assert_se(r >= 0);
+
+ log_error("enable2");
+
+ r = unit_file_enable(UNIT_FILE_SYSTEM, false, NULL, (char**) files, false, &changes, &n_changes);
+ assert_se(r >= 0);
+
+ dump_changes(changes, n_changes);
+ unit_file_changes_free(changes, n_changes);
+
+ assert_se(unit_file_get_state(UNIT_FILE_SYSTEM, NULL, files[0]) == UNIT_FILE_ENABLED);
+
+ log_error("disable");
+
+ changes = NULL;
+ n_changes = 0;
+
+ r = unit_file_disable(UNIT_FILE_SYSTEM, false, NULL, (char**) files, &changes, &n_changes);
+ assert_se(r >= 0);
+
+ dump_changes(changes, n_changes);
+ unit_file_changes_free(changes, n_changes);
+
+ assert_se(unit_file_get_state(UNIT_FILE_SYSTEM, NULL, files[0]) == UNIT_FILE_DISABLED);
+
+ log_error("mask");
+ changes = NULL;
+ n_changes = 0;
+
+ r = unit_file_mask(UNIT_FILE_SYSTEM, false, NULL, (char**) files, false, &changes, &n_changes);
+ assert_se(r >= 0);
+ log_error("mask2");
+ r = unit_file_mask(UNIT_FILE_SYSTEM, false, NULL, (char**) files, false, &changes, &n_changes);
+ assert_se(r >= 0);
+
+ dump_changes(changes, n_changes);
+ unit_file_changes_free(changes, n_changes);
+
+ assert_se(unit_file_get_state(UNIT_FILE_SYSTEM, NULL, files[0]) == UNIT_FILE_MASKED);
+
+ log_error("unmask");
+ changes = NULL;
+ n_changes = 0;
+
+ r = unit_file_unmask(UNIT_FILE_SYSTEM, false, NULL, (char**) files, &changes, &n_changes);
+ assert_se(r >= 0);
+ log_error("unmask2");
+ r = unit_file_unmask(UNIT_FILE_SYSTEM, false, NULL, (char**) files, &changes, &n_changes);
+ assert_se(r >= 0);
+
+ dump_changes(changes, n_changes);
+ unit_file_changes_free(changes, n_changes);
+
+ assert_se(unit_file_get_state(UNIT_FILE_SYSTEM, NULL, files[0]) == UNIT_FILE_DISABLED);
+
+ log_error("mask");
+ changes = NULL;
+ n_changes = 0;
+
+ r = unit_file_mask(UNIT_FILE_SYSTEM, false, NULL, (char**) files, false, &changes, &n_changes);
+ assert_se(r >= 0);
+
+ dump_changes(changes, n_changes);
+ unit_file_changes_free(changes, n_changes);
+
+ assert_se(unit_file_get_state(UNIT_FILE_SYSTEM, NULL, files[0]) == UNIT_FILE_MASKED);
+
+ log_error("disable");
+ changes = NULL;
+ n_changes = 0;
+
+ r = unit_file_disable(UNIT_FILE_SYSTEM, false, NULL, (char**) files, &changes, &n_changes);
+ assert_se(r >= 0);
+ log_error("disable2");
+ r = unit_file_disable(UNIT_FILE_SYSTEM, false, NULL, (char**) files, &changes, &n_changes);
+ assert_se(r >= 0);
+
+ dump_changes(changes, n_changes);
+ unit_file_changes_free(changes, n_changes);
+
+ assert_se(unit_file_get_state(UNIT_FILE_SYSTEM, NULL, files[0]) == UNIT_FILE_MASKED);
+
+ log_error("umask");
+ changes = NULL;
+ n_changes = 0;
+
+ r = unit_file_unmask(UNIT_FILE_SYSTEM, false, NULL, (char**) files, &changes, &n_changes);
+ assert_se(r >= 0);
+
+ dump_changes(changes, n_changes);
+ unit_file_changes_free(changes, n_changes);
+
+ assert_se(unit_file_get_state(UNIT_FILE_SYSTEM, NULL, files[0]) == UNIT_FILE_DISABLED);
+
+ log_error("enable files2");
+ changes = NULL;
+ n_changes = 0;
+
+ r = unit_file_enable(UNIT_FILE_SYSTEM, false, NULL, (char**) files2, false, &changes, &n_changes);
+ assert_se(r >= 0);
+
+ dump_changes(changes, n_changes);
+ unit_file_changes_free(changes, n_changes);
+
+ assert_se(unit_file_get_state(UNIT_FILE_SYSTEM, NULL, path_get_file_name(files2[0])) == UNIT_FILE_ENABLED);
+
+ log_error("disable files2");
+ changes = NULL;
+ n_changes = 0;
+
+ r = unit_file_disable(UNIT_FILE_SYSTEM, false, NULL, (char**) files2, &changes, &n_changes);
+ assert_se(r >= 0);
+
+ dump_changes(changes, n_changes);
+ unit_file_changes_free(changes, n_changes);
+
+ assert_se(unit_file_get_state(UNIT_FILE_SYSTEM, NULL, path_get_file_name(files2[0])) == _UNIT_FILE_STATE_INVALID);
+
+ log_error("link files2");
+ changes = NULL;
+ n_changes = 0;
+
+ r = unit_file_link(UNIT_FILE_SYSTEM, false, NULL, (char**) files2, false, &changes, &n_changes);
+ assert_se(r >= 0);
+
+ dump_changes(changes, n_changes);
+ unit_file_changes_free(changes, n_changes);
+
+ assert_se(unit_file_get_state(UNIT_FILE_SYSTEM, NULL, path_get_file_name(files2[0])) == UNIT_FILE_LINKED);
+
+ log_error("disable files2");
+ changes = NULL;
+ n_changes = 0;
+
+ r = unit_file_disable(UNIT_FILE_SYSTEM, false, NULL, (char**) files2, &changes, &n_changes);
+ assert_se(r >= 0);
+
+ dump_changes(changes, n_changes);
+ unit_file_changes_free(changes, n_changes);
+
+ assert_se(unit_file_get_state(UNIT_FILE_SYSTEM, NULL, path_get_file_name(files2[0])) == _UNIT_FILE_STATE_INVALID);
+
+ log_error("link files2");
+ changes = NULL;
+ n_changes = 0;
+
+ r = unit_file_link(UNIT_FILE_SYSTEM, false, NULL, (char**) files2, false, &changes, &n_changes);
+ assert_se(r >= 0);
+
+ dump_changes(changes, n_changes);
+ unit_file_changes_free(changes, n_changes);
+
+ assert_se(unit_file_get_state(UNIT_FILE_SYSTEM, NULL, path_get_file_name(files2[0])) == UNIT_FILE_LINKED);
+
+ log_error("reenable files2");
+ changes = NULL;
+ n_changes = 0;
+
+ r = unit_file_reenable(UNIT_FILE_SYSTEM, false, NULL, (char**) files2, false, &changes, &n_changes);
+ assert_se(r >= 0);
+
+ dump_changes(changes, n_changes);
+ unit_file_changes_free(changes, n_changes);
+
+ assert_se(unit_file_get_state(UNIT_FILE_SYSTEM, NULL, path_get_file_name(files2[0])) == UNIT_FILE_ENABLED);
+
+ log_error("disable files2");
+ changes = NULL;
+ n_changes = 0;
+
+ r = unit_file_disable(UNIT_FILE_SYSTEM, false, NULL, (char**) files2, &changes, &n_changes);
+ assert_se(r >= 0);
+
+ dump_changes(changes, n_changes);
+ unit_file_changes_free(changes, n_changes);
+
+ assert_se(unit_file_get_state(UNIT_FILE_SYSTEM, NULL, path_get_file_name(files2[0])) == _UNIT_FILE_STATE_INVALID);
+ log_error("preset files");
+ changes = NULL;
+ n_changes = 0;
+
+ r = unit_file_preset(UNIT_FILE_SYSTEM, false, NULL, (char**) files, false, &changes, &n_changes);
+ assert_se(r >= 0);
+
+ dump_changes(changes, n_changes);
+ unit_file_changes_free(changes, n_changes);
+
+ assert_se(unit_file_get_state(UNIT_FILE_SYSTEM, NULL, path_get_file_name(files[0])) == UNIT_FILE_ENABLED);
+
+ return 0;
+}
diff --git a/src/test/test-job-type.c b/src/test/test-job-type.c
new file mode 100644
index 0000000000..1066374436
--- /dev/null
+++ b/src/test/test-job-type.c
@@ -0,0 +1,105 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include <errno.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "job.h"
+#include "unit.h"
+#include "service.h"
+
+int main(int argc, char*argv[]) {
+ JobType a, b, c, ab, bc, ab_c, bc_a, a_bc;
+ const ServiceState test_states[] = { SERVICE_DEAD, SERVICE_RUNNING };
+ unsigned i;
+ bool merged_ab;
+
+ /* fake a unit */
+ static Service s = {
+ .meta.load_state = UNIT_LOADED,
+ .type = SERVICE_SIMPLE,
+ };
+ Unit *u = UNIT(&s);
+
+ for (i = 0; i < ELEMENTSOF(test_states); i++) {
+ s.state = test_states[i];
+ printf("\nWith collapsing for service state %s\n"
+ "=========================================\n", service_state_to_string(s.state));
+ for (a = 0; a < _JOB_TYPE_MAX_MERGING; a++) {
+ for (b = 0; b < _JOB_TYPE_MAX_MERGING; b++) {
+
+ ab = a;
+ merged_ab = (job_type_merge_and_collapse(&ab, b, u) >= 0);
+
+ if (!job_type_is_mergeable(a, b)) {
+ assert(!merged_ab);
+ printf("Not mergeable: %s + %s\n", job_type_to_string(a), job_type_to_string(b));
+ continue;
+ }
+
+ assert(merged_ab);
+ printf("%s + %s = %s\n", job_type_to_string(a), job_type_to_string(b), job_type_to_string(ab));
+
+ for (c = 0; c < _JOB_TYPE_MAX_MERGING; c++) {
+
+ /* Verify transitivity of mergeability of job types */
+ assert(!job_type_is_mergeable(a, b) ||
+ !job_type_is_mergeable(b, c) ||
+ job_type_is_mergeable(a, c));
+
+ /* Verify that merged entries can be merged with the same entries
+ * they can be merged with separately */
+ assert(!job_type_is_mergeable(a, c) || job_type_is_mergeable(ab, c));
+ assert(!job_type_is_mergeable(b, c) || job_type_is_mergeable(ab, c));
+
+ /* Verify that if a merged with b is not mergeable with c, then
+ * either a or b is not mergeable with c either. */
+ assert(job_type_is_mergeable(ab, c) || !job_type_is_mergeable(a, c) || !job_type_is_mergeable(b, c));
+
+ bc = b;
+ if (job_type_merge_and_collapse(&bc, c, u) >= 0) {
+
+ /* Verify associativity */
+
+ ab_c = ab;
+ assert(job_type_merge_and_collapse(&ab_c, c, u) == 0);
+
+ bc_a = bc;
+ assert(job_type_merge_and_collapse(&bc_a, a, u) == 0);
+
+ a_bc = a;
+ assert(job_type_merge_and_collapse(&a_bc, bc, u) == 0);
+
+ assert(ab_c == bc_a);
+ assert(ab_c == a_bc);
+
+ printf("%s + %s + %s = %s\n", job_type_to_string(a), job_type_to_string(b), job_type_to_string(c), job_type_to_string(ab_c));
+ }
+ }
+ }
+ }
+ }
+
+
+ return 0;
+}
diff --git a/src/test/test-libudev.c b/src/test/test-libudev.c
new file mode 100644
index 0000000000..caa3b4d14c
--- /dev/null
+++ b/src/test/test-libudev.c
@@ -0,0 +1,520 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2008-2012 Kay Sievers <kay@vrfy.org>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include <stdarg.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <errno.h>
+#include <string.h>
+#include <getopt.h>
+#include <syslog.h>
+#include <fcntl.h>
+#include <sys/epoll.h>
+
+#include "libudev.h"
+#include "util.h"
+
+#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
+
+static void log_fn(struct udev *udev,
+ int priority, const char *file, int line, const char *fn,
+ const char *format, va_list args)
+{
+ printf("test-libudev: %s %s:%d ", fn, file, line);
+ vprintf(format, args);
+}
+
+static void print_device(struct udev_device *device)
+{
+ const char *str;
+ dev_t devnum;
+ int count;
+ struct udev_list_entry *list_entry;
+
+ printf("*** device: %p ***\n", device);
+ str = udev_device_get_action(device);
+ if (str != NULL)
+ printf("action: '%s'\n", str);
+
+ str = udev_device_get_syspath(device);
+ printf("syspath: '%s'\n", str);
+
+ str = udev_device_get_sysname(device);
+ printf("sysname: '%s'\n", str);
+
+ str = udev_device_get_sysnum(device);
+ if (str != NULL)
+ printf("sysnum: '%s'\n", str);
+
+ str = udev_device_get_devpath(device);
+ printf("devpath: '%s'\n", str);
+
+ str = udev_device_get_subsystem(device);
+ if (str != NULL)
+ printf("subsystem: '%s'\n", str);
+
+ str = udev_device_get_devtype(device);
+ if (str != NULL)
+ printf("devtype: '%s'\n", str);
+
+ str = udev_device_get_driver(device);
+ if (str != NULL)
+ printf("driver: '%s'\n", str);
+
+ str = udev_device_get_devnode(device);
+ if (str != NULL)
+ printf("devname: '%s'\n", str);
+
+ devnum = udev_device_get_devnum(device);
+ if (major(devnum) > 0)
+ printf("devnum: %u:%u\n", major(devnum), minor(devnum));
+
+ count = 0;
+ udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(device)) {
+ printf("link: '%s'\n", udev_list_entry_get_name(list_entry));
+ count++;
+ }
+ if (count > 0)
+ printf("found %i links\n", count);
+
+ count = 0;
+ udev_list_entry_foreach(list_entry, udev_device_get_properties_list_entry(device)) {
+ printf("property: '%s=%s'\n",
+ udev_list_entry_get_name(list_entry),
+ udev_list_entry_get_value(list_entry));
+ count++;
+ }
+ if (count > 0)
+ printf("found %i properties\n", count);
+
+ str = udev_device_get_property_value(device, "MAJOR");
+ if (str != NULL)
+ printf("MAJOR: '%s'\n", str);
+
+ str = udev_device_get_sysattr_value(device, "dev");
+ if (str != NULL)
+ printf("attr{dev}: '%s'\n", str);
+
+ printf("\n");
+}
+
+static int test_device(struct udev *udev, const char *syspath)
+{
+ struct udev_device *device;
+
+ printf("looking at device: %s\n", syspath);
+ device = udev_device_new_from_syspath(udev, syspath);
+ if (device == NULL) {
+ printf("no device found\n");
+ return -1;
+ }
+ print_device(device);
+ udev_device_unref(device);
+ return 0;
+}
+
+static int test_device_parents(struct udev *udev, const char *syspath)
+{
+ struct udev_device *device;
+ struct udev_device *device_parent;
+
+ printf("looking at device: %s\n", syspath);
+ device = udev_device_new_from_syspath(udev, syspath);
+ if (device == NULL)
+ return -1;
+
+ printf("looking at parents\n");
+ device_parent = device;
+ do {
+ print_device(device_parent);
+ device_parent = udev_device_get_parent(device_parent);
+ } while (device_parent != NULL);
+
+ printf("looking at parents again\n");
+ device_parent = device;
+ do {
+ print_device(device_parent);
+ device_parent = udev_device_get_parent(device_parent);
+ } while (device_parent != NULL);
+ udev_device_unref(device);
+
+ return 0;
+}
+
+static int test_device_devnum(struct udev *udev)
+{
+ dev_t devnum = makedev(1, 3);
+ struct udev_device *device;
+
+ printf("looking up device: %u:%u\n", major(devnum), minor(devnum));
+ device = udev_device_new_from_devnum(udev, 'c', devnum);
+ if (device == NULL)
+ return -1;
+ print_device(device);
+ udev_device_unref(device);
+ return 0;
+}
+
+static int test_device_subsys_name(struct udev *udev)
+{
+ struct udev_device *device;
+
+ printf("looking up device: 'block':'sda'\n");
+ device = udev_device_new_from_subsystem_sysname(udev, "block", "sda");
+ if (device == NULL)
+ return -1;
+ print_device(device);
+ udev_device_unref(device);
+
+ printf("looking up device: 'subsystem':'pci'\n");
+ device = udev_device_new_from_subsystem_sysname(udev, "subsystem", "pci");
+ if (device == NULL)
+ return -1;
+ print_device(device);
+ udev_device_unref(device);
+
+ printf("looking up device: 'drivers':'scsi:sd'\n");
+ device = udev_device_new_from_subsystem_sysname(udev, "drivers", "scsi:sd");
+ if (device == NULL)
+ return -1;
+ print_device(device);
+ udev_device_unref(device);
+
+ printf("looking up device: 'module':'printk'\n");
+ device = udev_device_new_from_subsystem_sysname(udev, "module", "printk");
+ if (device == NULL)
+ return -1;
+ print_device(device);
+ udev_device_unref(device);
+ return 0;
+}
+
+static int test_enumerate_print_list(struct udev_enumerate *enumerate)
+{
+ struct udev_list_entry *list_entry;
+ int count = 0;
+
+ udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(enumerate)) {
+ struct udev_device *device;
+
+ device = udev_device_new_from_syspath(udev_enumerate_get_udev(enumerate),
+ udev_list_entry_get_name(list_entry));
+ if (device != NULL) {
+ printf("device: '%s' (%s)\n",
+ udev_device_get_syspath(device),
+ udev_device_get_subsystem(device));
+ udev_device_unref(device);
+ count++;
+ }
+ }
+ printf("found %i devices\n\n", count);
+ return count;
+}
+
+static int test_monitor(struct udev *udev)
+{
+ struct udev_monitor *udev_monitor = NULL;
+ int fd_ep;
+ int fd_udev = -1;
+ struct epoll_event ep_udev, ep_stdin;
+
+ fd_ep = epoll_create1(EPOLL_CLOEXEC);
+ if (fd_ep < 0) {
+ printf("error creating epoll fd: %m\n");
+ goto out;
+ }
+
+ udev_monitor = udev_monitor_new_from_netlink(udev, "udev");
+ if (udev_monitor == NULL) {
+ printf("no socket\n");
+ goto out;
+ }
+ fd_udev = udev_monitor_get_fd(udev_monitor);
+
+ if (udev_monitor_filter_add_match_subsystem_devtype(udev_monitor, "block", NULL) < 0 ||
+ udev_monitor_filter_add_match_subsystem_devtype(udev_monitor, "tty", NULL) < 0 ||
+ udev_monitor_filter_add_match_subsystem_devtype(udev_monitor, "usb", "usb_device") < 0) {
+ printf("filter failed\n");
+ goto out;
+ }
+
+ if (udev_monitor_enable_receiving(udev_monitor) < 0) {
+ printf("bind failed\n");
+ goto out;
+ }
+
+ memset(&ep_udev, 0, sizeof(struct epoll_event));
+ ep_udev.events = EPOLLIN;
+ ep_udev.data.fd = fd_udev;
+ if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_udev, &ep_udev) < 0) {
+ printf("fail to add fd to epoll: %m\n");
+ goto out;
+ }
+
+ memset(&ep_stdin, 0, sizeof(struct epoll_event));
+ ep_stdin.events = EPOLLIN;
+ ep_stdin.data.fd = STDIN_FILENO;
+ if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, STDIN_FILENO, &ep_stdin) < 0) {
+ printf("fail to add fd to epoll: %m\n");
+ goto out;
+ }
+
+ for (;;) {
+ int fdcount;
+ struct epoll_event ev[4];
+ struct udev_device *device;
+ int i;
+
+ printf("waiting for events from udev, press ENTER to exit\n");
+ fdcount = epoll_wait(fd_ep, ev, ARRAY_SIZE(ev), -1);
+ printf("epoll fd count: %i\n", fdcount);
+
+ for (i = 0; i < fdcount; i++) {
+ if (ev[i].data.fd == fd_udev && ev[i].events & EPOLLIN) {
+ device = udev_monitor_receive_device(udev_monitor);
+ if (device == NULL) {
+ printf("no device from socket\n");
+ continue;
+ }
+ print_device(device);
+ udev_device_unref(device);
+ } else if (ev[i].data.fd == STDIN_FILENO && ev[i].events & EPOLLIN) {
+ printf("exiting loop\n");
+ goto out;
+ }
+ }
+ }
+out:
+ if (fd_ep >= 0)
+ close(fd_ep);
+ udev_monitor_unref(udev_monitor);
+ return 0;
+}
+
+static int test_queue(struct udev *udev)
+{
+ struct udev_queue *udev_queue;
+ unsigned long long int seqnum;
+ struct udev_list_entry *list_entry;
+
+ udev_queue = udev_queue_new(udev);
+ if (udev_queue == NULL)
+ return -1;
+ seqnum = udev_queue_get_kernel_seqnum(udev_queue);
+ printf("seqnum kernel: %llu\n", seqnum);
+ seqnum = udev_queue_get_udev_seqnum(udev_queue);
+ printf("seqnum udev : %llu\n", seqnum);
+
+ if (udev_queue_get_queue_is_empty(udev_queue))
+ printf("queue is empty\n");
+ printf("get queue list\n");
+ udev_list_entry_foreach(list_entry, udev_queue_get_queued_list_entry(udev_queue))
+ printf("queued: '%s' [%s]\n", udev_list_entry_get_name(list_entry), udev_list_entry_get_value(list_entry));
+ printf("\n");
+ printf("get queue list again\n");
+ udev_list_entry_foreach(list_entry, udev_queue_get_queued_list_entry(udev_queue))
+ printf("queued: '%s' [%s]\n", udev_list_entry_get_name(list_entry), udev_list_entry_get_value(list_entry));
+ printf("\n");
+
+ list_entry = udev_queue_get_queued_list_entry(udev_queue);
+ if (list_entry != NULL) {
+ printf("event [%llu] is queued\n", seqnum);
+ seqnum = strtoull(udev_list_entry_get_value(list_entry), NULL, 10);
+ if (udev_queue_get_seqnum_is_finished(udev_queue, seqnum))
+ printf("event [%llu] is not finished\n", seqnum);
+ else
+ printf("event [%llu] is finished\n", seqnum);
+ }
+ printf("\n");
+ udev_queue_unref(udev_queue);
+ return 0;
+}
+
+static int test_enumerate(struct udev *udev, const char *subsystem)
+{
+ struct udev_enumerate *udev_enumerate;
+
+ printf("enumerate '%s'\n", subsystem == NULL ? "<all>" : subsystem);
+ udev_enumerate = udev_enumerate_new(udev);
+ if (udev_enumerate == NULL)
+ return -1;
+ udev_enumerate_add_match_subsystem(udev_enumerate, subsystem);
+ udev_enumerate_scan_devices(udev_enumerate);
+ test_enumerate_print_list(udev_enumerate);
+ udev_enumerate_unref(udev_enumerate);
+
+ printf("enumerate 'net' + duplicated scan + null + zero\n");
+ udev_enumerate = udev_enumerate_new(udev);
+ if (udev_enumerate == NULL)
+ return -1;
+ udev_enumerate_add_match_subsystem(udev_enumerate, "net");
+ udev_enumerate_scan_devices(udev_enumerate);
+ udev_enumerate_scan_devices(udev_enumerate);
+ udev_enumerate_add_syspath(udev_enumerate, "/sys/class/mem/zero");
+ udev_enumerate_add_syspath(udev_enumerate, "/sys/class/mem/null");
+ udev_enumerate_add_syspath(udev_enumerate, "/sys/class/mem/zero");
+ udev_enumerate_add_syspath(udev_enumerate, "/sys/class/mem/null");
+ udev_enumerate_add_syspath(udev_enumerate, "/sys/class/mem/zero");
+ udev_enumerate_add_syspath(udev_enumerate, "/sys/class/mem/null");
+ udev_enumerate_add_syspath(udev_enumerate, "/sys/class/mem/null");
+ udev_enumerate_add_syspath(udev_enumerate, "/sys/class/mem/zero");
+ udev_enumerate_add_syspath(udev_enumerate, "/sys/class/mem/zero");
+ udev_enumerate_scan_devices(udev_enumerate);
+ test_enumerate_print_list(udev_enumerate);
+ udev_enumerate_unref(udev_enumerate);
+
+ printf("enumerate 'block'\n");
+ udev_enumerate = udev_enumerate_new(udev);
+ if (udev_enumerate == NULL)
+ return -1;
+ udev_enumerate_add_match_subsystem(udev_enumerate,"block");
+ udev_enumerate_add_match_is_initialized(udev_enumerate);
+ udev_enumerate_scan_devices(udev_enumerate);
+ test_enumerate_print_list(udev_enumerate);
+ udev_enumerate_unref(udev_enumerate);
+
+ printf("enumerate 'not block'\n");
+ udev_enumerate = udev_enumerate_new(udev);
+ if (udev_enumerate == NULL)
+ return -1;
+ udev_enumerate_add_nomatch_subsystem(udev_enumerate, "block");
+ udev_enumerate_scan_devices(udev_enumerate);
+ test_enumerate_print_list(udev_enumerate);
+ udev_enumerate_unref(udev_enumerate);
+
+ printf("enumerate 'pci, mem, vc'\n");
+ udev_enumerate = udev_enumerate_new(udev);
+ if (udev_enumerate == NULL)
+ return -1;
+ udev_enumerate_add_match_subsystem(udev_enumerate, "pci");
+ udev_enumerate_add_match_subsystem(udev_enumerate, "mem");
+ udev_enumerate_add_match_subsystem(udev_enumerate, "vc");
+ udev_enumerate_scan_devices(udev_enumerate);
+ test_enumerate_print_list(udev_enumerate);
+ udev_enumerate_unref(udev_enumerate);
+
+ printf("enumerate 'subsystem'\n");
+ udev_enumerate = udev_enumerate_new(udev);
+ if (udev_enumerate == NULL)
+ return -1;
+ udev_enumerate_scan_subsystems(udev_enumerate);
+ test_enumerate_print_list(udev_enumerate);
+ udev_enumerate_unref(udev_enumerate);
+
+ printf("enumerate 'property IF_FS_*=filesystem'\n");
+ udev_enumerate = udev_enumerate_new(udev);
+ if (udev_enumerate == NULL)
+ return -1;
+ udev_enumerate_add_match_property(udev_enumerate, "ID_FS*", "filesystem");
+ udev_enumerate_scan_devices(udev_enumerate);
+ test_enumerate_print_list(udev_enumerate);
+ udev_enumerate_unref(udev_enumerate);
+ return 0;
+}
+
+static int test_hwdb(struct udev *udev, const char *modalias) {
+ struct udev_hwdb * hwdb;
+ struct udev_list_entry *entry;
+
+ hwdb = udev_hwdb_new(udev);
+
+ udev_list_entry_foreach(entry, udev_hwdb_get_properties_list_entry(hwdb, modalias, 0))
+ printf("'%s'='%s'\n", udev_list_entry_get_name(entry), udev_list_entry_get_value(entry));
+ printf("\n");
+
+ hwdb = udev_hwdb_unref(hwdb);
+ return 0;
+}
+
+int main(int argc, char *argv[])
+{
+ struct udev *udev = NULL;
+ static const struct option options[] = {
+ { "syspath", required_argument, NULL, 'p' },
+ { "subsystem", required_argument, NULL, 's' },
+ { "debug", no_argument, NULL, 'd' },
+ { "help", no_argument, NULL, 'h' },
+ { "version", no_argument, NULL, 'V' },
+ {}
+ };
+ const char *syspath = "/devices/virtual/mem/null";
+ const char *subsystem = NULL;
+ char path[1024];
+
+ udev = udev_new();
+ printf("context: %p\n", udev);
+ if (udev == NULL) {
+ printf("no context\n");
+ return 1;
+ }
+ udev_set_log_fn(udev, log_fn);
+ printf("set log: %p\n", log_fn);
+
+ for (;;) {
+ int option;
+
+ option = getopt_long(argc, argv, "+p:s:dhV", options, NULL);
+ if (option == -1)
+ break;
+
+ switch (option) {
+ case 'p':
+ syspath = optarg;
+ break;
+ case 's':
+ subsystem = optarg;
+ break;
+ case 'd':
+ if (udev_get_log_priority(udev) < LOG_INFO)
+ udev_set_log_priority(udev, LOG_INFO);
+ break;
+ case 'h':
+ printf("--debug --syspath= --subsystem= --help\n");
+ goto out;
+ case 'V':
+ printf("%s\n", VERSION);
+ goto out;
+ default:
+ goto out;
+ }
+ }
+
+ /* add sys path if needed */
+ if (!startswith(syspath, "/sys")) {
+ snprintf(path, sizeof(path), "/sys/%s", syspath);
+ syspath = path;
+ }
+
+ test_device(udev, syspath);
+ test_device_devnum(udev);
+ test_device_subsys_name(udev);
+ test_device_parents(udev, syspath);
+
+ test_enumerate(udev, subsystem);
+
+ test_queue(udev);
+
+ test_hwdb(udev, "usb:v0D50p0011*");
+
+ test_monitor(udev);
+out:
+ udev_unref(udev);
+ return 0;
+}
diff --git a/src/test/test-log.c b/src/test/test-log.c
new file mode 100644
index 0000000000..8dc3d5383f
--- /dev/null
+++ b/src/test/test-log.c
@@ -0,0 +1,53 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stddef.h>
+#include <unistd.h>
+
+#include "log.h"
+
+int main(int argc, char* argv[]) {
+
+ log_set_target(LOG_TARGET_CONSOLE);
+ log_open();
+
+ log_struct(LOG_INFO,
+ "MESSAGE=Waldo PID=%lu", (unsigned long) getpid(),
+ "SERVICE=piepapo",
+ NULL);
+
+ log_set_target(LOG_TARGET_JOURNAL);
+ log_open();
+
+ log_struct(LOG_INFO,
+ "MESSAGE=Foobar PID=%lu", (unsigned long) getpid(),
+ "SERVICE=foobar",
+ NULL);
+
+ log_struct(LOG_INFO,
+ "MESSAGE=Foobar PID=%lu", (unsigned long) getpid(),
+ "FORMAT_STR_TEST=1=%i A=%c 2=%hi 3=%li 4=%lli 1=%p foo=%s 2.5=%g 3.5=%g 4.5=%Lg",
+ (int) 1, 'A', (short) 2, (long int) 3, (long long int) 4, (void*) 1, "foo", (float) 2.5f, (double) 3.5, (long double) 4.5,
+ "SUFFIX=GOT IT",
+ NULL);
+
+ return 0;
+}
diff --git a/src/test/test-loopback.c b/src/test/test-loopback.c
new file mode 100644
index 0000000000..ab330ac840
--- /dev/null
+++ b/src/test/test-loopback.c
@@ -0,0 +1,37 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <string.h>
+#include <stdio.h>
+#include <fcntl.h>
+
+#include "loopback-setup.h"
+#include "util.h"
+
+int main(int argc, char* argv[]) {
+ int r;
+
+ if ((r = loopback_setup()) < 0)
+ fprintf(stderr, "loopback: %s\n", strerror(-r));
+
+ return 0;
+}
diff --git a/src/test/test-ns.c b/src/test/test-ns.c
new file mode 100644
index 0000000000..ad0d0419c4
--- /dev/null
+++ b/src/test/test-ns.c
@@ -0,0 +1,73 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/mount.h>
+#include <linux/fs.h>
+
+#include "namespace.h"
+#include "execute.h"
+#include "log.h"
+
+int main(int argc, char *argv[]) {
+ const char * const writable[] = {
+ "/home",
+ NULL
+ };
+
+ const char * const readonly[] = {
+ "/",
+ "/usr",
+ "/boot",
+ NULL
+ };
+
+ const char * const inaccessible[] = {
+ "/home/lennart/projects",
+ NULL
+ };
+
+ int r;
+ char tmp_dir[] = "/tmp/systemd-private-XXXXXX",
+ var_tmp_dir[] = "/var/tmp/systemd-private-XXXXXX";
+
+ assert_se(mkdtemp(tmp_dir));
+ assert_se(mkdtemp(var_tmp_dir));
+
+ r = setup_namespace((char **) writable,
+ (char **) readonly,
+ (char **) inaccessible,
+ tmp_dir,
+ var_tmp_dir,
+ true,
+ 0);
+ if (r < 0) {
+ log_error("Failed to setup namespace: %s", strerror(-r));
+ return 1;
+ }
+
+ execl("/bin/sh", "/bin/sh", NULL);
+ log_error("execl(): %m");
+
+ return 1;
+}
diff --git a/src/test/test-path-util.c b/src/test/test-path-util.c
new file mode 100644
index 0000000000..127e17803f
--- /dev/null
+++ b/src/test/test-path-util.c
@@ -0,0 +1,89 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Zbigniew Jędrzejewski-Szmek
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+
+#include "path-util.h"
+#include "util.h"
+#include "macro.h"
+
+
+static void test_path(void) {
+ assert_se(path_equal("/goo", "/goo"));
+ assert_se(path_equal("//goo", "/goo"));
+ assert_se(path_equal("//goo/////", "/goo"));
+ assert_se(path_equal("goo/////", "goo"));
+
+ assert_se(path_equal("/goo/boo", "/goo//boo"));
+ assert_se(path_equal("//goo/boo", "/goo/boo//"));
+
+ assert_se(path_equal("/", "///"));
+
+ assert_se(!path_equal("/x", "x/"));
+ assert_se(!path_equal("x/", "/"));
+
+ assert_se(!path_equal("/x/./y", "x/y"));
+ assert_se(!path_equal("x/.y", "x/y"));
+
+ assert_se(path_is_absolute("/"));
+ assert_se(!path_is_absolute("./"));
+
+ assert_se(is_path("/dir"));
+ assert_se(is_path("a/b"));
+ assert_se(!is_path("."));
+
+ assert_se(streq(path_get_file_name("./aa/bb/../file.da."), "file.da."));
+ assert_se(streq(path_get_file_name("/aa///.file"), ".file"));
+ assert_se(streq(path_get_file_name("/aa///file..."), "file..."));
+ assert_se(streq(path_get_file_name("file.../"), ""));
+
+#define test_parent(x, y) { \
+ char *z; \
+ int r = path_get_parent(x, &z); \
+ printf("expected: %s\n", y ? y : "error"); \
+ printf("actual: %s\n", r<0 ? "error" : z); \
+ assert_se((y==NULL) ^ (r==0)); \
+ assert_se(y==NULL || path_equal(z, y)); \
+ }
+
+ test_parent("./aa/bb/../file.da.", "./aa/bb/..");
+ test_parent("/aa///.file", "/aa///");
+ test_parent("/aa///file...", "/aa///");
+ test_parent("file.../", NULL);
+
+ assert_se(path_is_mount_point("/", true));
+ assert_se(path_is_mount_point("/", false));
+
+ {
+ char p1[] = "aaa/bbb////ccc";
+ char p2[] = "//aaa/.////ccc";
+ char p3[] = "/./";
+
+ assert(path_equal(path_kill_slashes(p1), "aaa/bbb/ccc"));
+ assert(path_equal(path_kill_slashes(p2), "/aaa/./ccc"));
+ assert(path_equal(path_kill_slashes(p3), "/./"));
+ }
+}
+
+int main(void) {
+ test_path();
+ return 0;
+}
diff --git a/src/test/test-prioq.c b/src/test/test-prioq.c
new file mode 100644
index 0000000000..aeac73973b
--- /dev/null
+++ b/src/test/test-prioq.c
@@ -0,0 +1,166 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdlib.h>
+
+#include "util.h"
+#include "set.h"
+#include "prioq.h"
+
+#define SET_SIZE 1024*4
+
+static int unsigned_compare(const void *a, const void *b) {
+ const unsigned *x = a, *y = b;
+
+ if (*x < *y)
+ return -1;
+
+ if (*x > *y)
+ return 1;
+
+ return 0;
+}
+
+static void test_unsigned(void) {
+ unsigned buffer[SET_SIZE], i;
+ Prioq *q;
+
+ srand(0);
+
+ q = prioq_new(trivial_compare_func);
+ assert_se(q);
+
+ for (i = 0; i < ELEMENTSOF(buffer); i++) {
+ unsigned u;
+
+ u = (unsigned) rand();
+ buffer[i] = u;
+ assert_se(prioq_put(q, UINT_TO_PTR(u), NULL) >= 0);
+ }
+
+ qsort(buffer, ELEMENTSOF(buffer), sizeof(buffer[0]), unsigned_compare);
+
+ for (i = 0; i < ELEMENTSOF(buffer); i++) {
+ unsigned u;
+
+ assert_se(prioq_size(q) == ELEMENTSOF(buffer) - i);
+
+ u = PTR_TO_UINT(prioq_pop(q));
+ assert_se(buffer[i] == u);
+ }
+
+ assert_se(prioq_isempty(q));
+ prioq_free(q);
+}
+
+struct test {
+ unsigned value;
+ unsigned idx;
+};
+
+static int test_compare(const void *a, const void *b) {
+ const struct test *x = a, *y = b;
+
+ if (x->value < y->value)
+ return -1;
+
+ if (x->value > y->value)
+ return 1;
+
+ return 0;
+}
+
+static unsigned test_hash(const void *a) {
+ const struct test *x = a;
+
+ return x->value;
+}
+
+static void test_struct(void) {
+ Prioq *q;
+ Set *s;
+ unsigned previous = 0, i;
+ int r;
+
+ srand(0);
+
+ q = prioq_new(test_compare);
+ assert_se(q);
+
+ s = set_new(test_hash, test_compare);
+ assert_se(s);
+
+ for (i = 0; i < SET_SIZE; i++) {
+ struct test *t;
+
+ t = new0(struct test, 1);
+ assert_se(t);
+ t->value = (unsigned) rand();
+
+ r = prioq_put(q, t, &t->idx);
+ assert_se(r >= 0);
+
+ if (i % 4 == 0) {
+ r = set_consume(s, t);
+ assert_se(r >= 0);
+ }
+ }
+
+ for (;;) {
+ struct test *t;
+
+ t = set_steal_first(s);
+ if (!t)
+ break;
+
+ r = prioq_remove(q, t, &t->idx);
+ assert_se(r > 0);
+
+ free(t);
+ }
+
+ for (i = 0; i < SET_SIZE * 3 / 4; i++) {
+ struct test *t;
+
+ assert_se(prioq_size(q) == (SET_SIZE * 3 / 4) - i);
+
+ t = prioq_pop(q);
+ assert_se(t);
+
+ assert_se(previous <= t->value);
+ previous = t->value;
+ free(t);
+ }
+
+ assert_se(prioq_isempty(q));
+ prioq_free(q);
+
+ assert_se(set_isempty(s));
+ set_free(s);
+}
+
+int main(int argc, char* argv[]) {
+
+ test_unsigned();
+ test_struct();
+
+ return 0;
+}
diff --git a/src/test/test-replace-var.c b/src/test/test-replace-var.c
new file mode 100644
index 0000000000..b1d42d77fd
--- /dev/null
+++ b/src/test/test-replace-var.c
@@ -0,0 +1,46 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <string.h>
+
+#include "util.h"
+#include "macro.h"
+#include "replace-var.h"
+
+static char *lookup(const char *variable, void *userdata) {
+ return strjoin("<<<", variable, ">>>", NULL);
+}
+
+int main(int argc, char *argv[]) {
+ char *r;
+
+ assert_se(r = replace_var("@@@foobar@xyz@HALLO@foobar@test@@testtest@TEST@...@@@", lookup, NULL));
+ puts(r);
+ assert_se(streq(r, "@@@foobar@xyz<<<HALLO>>>foobar@test@@testtest<<<TEST>>>...@@@"));
+ free(r);
+
+ assert_se(r = strreplace("XYZFFFFXYZFFFFXYZ", "XYZ", "ABC"));
+ puts(r);
+ assert_se(streq(r, "ABCFFFFABCFFFFABC"));
+ free(r);
+
+ return 0;
+}
diff --git a/src/test/test-sched-prio.c b/src/test/test-sched-prio.c
new file mode 100644
index 0000000000..ba0aacf79d
--- /dev/null
+++ b/src/test/test-sched-prio.c
@@ -0,0 +1,92 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Holger Hans Peter Freyther
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sched.h>
+
+#include "manager.h"
+#include "macro.h"
+
+int main(int argc, char *argv[]) {
+ Manager *m;
+ Unit *idle_ok, *idle_bad, *rr_ok, *rr_bad, *rr_sched;
+ Service *ser;
+ FILE *serial = NULL;
+ FDSet *fdset = NULL;
+ int r;
+
+ /* prepare the test */
+ assert_se(set_unit_path(TEST_DIR) >= 0);
+ r = manager_new(SYSTEMD_USER, &m);
+ if (r == -EPERM) {
+ puts("manager_new: Permission denied. Skipping test.");
+ return EXIT_TEST_SKIP;
+ }
+ assert(r >= 0);
+ assert_se(manager_startup(m, serial, fdset) >= 0);
+
+ /* load idle ok */
+ assert_se(manager_load_unit(m, "sched_idle_ok.service", NULL, NULL, &idle_ok) >= 0);
+ assert_se(idle_ok->load_state == UNIT_LOADED);
+ ser = SERVICE(idle_ok);
+ assert_se(ser->exec_context.cpu_sched_policy == SCHED_OTHER);
+ assert_se(ser->exec_context.cpu_sched_priority == 0);
+
+ /*
+ * load idle bad. This should print a warning but we have no way to look at it.
+ */
+ assert_se(manager_load_unit(m, "sched_idle_bad.service", NULL, NULL, &idle_bad) >= 0);
+ assert_se(idle_bad->load_state == UNIT_LOADED);
+ ser = SERVICE(idle_ok);
+ assert_se(ser->exec_context.cpu_sched_policy == SCHED_OTHER);
+ assert_se(ser->exec_context.cpu_sched_priority == 0);
+
+ /*
+ * load rr ok.
+ * Test that the default priority is moving from 0 to 1.
+ */
+ assert_se(manager_load_unit(m, "sched_rr_ok.service", NULL, NULL, &rr_ok) >= 0);
+ assert_se(rr_ok->load_state == UNIT_LOADED);
+ ser = SERVICE(rr_ok);
+ assert_se(ser->exec_context.cpu_sched_policy == SCHED_RR);
+ assert_se(ser->exec_context.cpu_sched_priority == 1);
+
+ /*
+ * load rr bad.
+ * Test that the value of 0 and 100 is ignored.
+ */
+ assert_se(manager_load_unit(m, "sched_rr_bad.service", NULL, NULL, &rr_bad) >= 0);
+ assert_se(rr_bad->load_state == UNIT_LOADED);
+ ser = SERVICE(rr_bad);
+ assert_se(ser->exec_context.cpu_sched_policy == SCHED_RR);
+ assert_se(ser->exec_context.cpu_sched_priority == 1);
+
+ /*
+ * load rr change.
+ * Test that anything between 1 and 99 can be set.
+ */
+ assert_se(manager_load_unit(m, "sched_rr_change.service", NULL, NULL, &rr_sched) >= 0);
+ assert_se(rr_sched->load_state == UNIT_LOADED);
+ ser = SERVICE(rr_sched);
+ assert_se(ser->exec_context.cpu_sched_policy == SCHED_RR);
+ assert_se(ser->exec_context.cpu_sched_priority == 99);
+
+ return EXIT_SUCCESS;
+}
diff --git a/src/test/test-sleep.c b/src/test/test-sleep.c
new file mode 100644
index 0000000000..c3cb9c531d
--- /dev/null
+++ b/src/test/test-sleep.c
@@ -0,0 +1,57 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <string.h>
+#include <stdio.h>
+#include <fcntl.h>
+
+#include "util.h"
+#include "log.h"
+#include "sleep-config.h"
+#include "strv.h"
+
+int main(int argc, char* argv[]) {
+ _cleanup_strv_free_ char
+ **standby = strv_new("standby", NULL),
+ **mem = strv_new("mem", NULL),
+ **disk = strv_new("disk", NULL),
+ **suspend = strv_new("suspend", NULL),
+ **reboot = strv_new("reboot", NULL),
+ **platform = strv_new("platform", NULL),
+ **shutdown = strv_new("shutdown", NULL),
+ **freez = strv_new("freeze", NULL);
+
+ log_info("Can Standby: %s", yes_no(can_sleep_state(standby) > 0));
+ log_info("Can Suspend: %s", yes_no(can_sleep_state(mem) > 0));
+ log_info("Can Hibernate: %s", yes_no(can_sleep_state(disk) > 0));
+ log_info("Can Hibernate+Suspend (Hybrid-Sleep): %s", yes_no(can_sleep_disk(suspend) > 0));
+ log_info("Can Hibernate+Reboot: %s", yes_no(can_sleep_disk(reboot) > 0));
+ log_info("Can Hibernate+Platform: %s", yes_no(can_sleep_disk(platform) > 0));
+ log_info("Can Hibernate+Shutdown: %s", yes_no(can_sleep_disk(shutdown) > 0));
+ log_info("Can Freeze: %s", yes_no(can_sleep_disk(freez) > 0));
+
+ log_info("Suspend configured and possible: %s", yes_no(can_sleep("suspend") > 0));
+ log_info("Hibernation configured and possible: %s", yes_no(can_sleep("hibernate") > 0));
+ log_info("Hybrid-sleep configured and possible: %s", yes_no(can_sleep("hybrid-sleep") > 0));
+
+ return 0;
+}
diff --git a/src/test/test-strbuf.c b/src/test/test-strbuf.c
new file mode 100644
index 0000000000..e9b6c033fd
--- /dev/null
+++ b/src/test/test-strbuf.c
@@ -0,0 +1,93 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Thomas H.P. Andersen
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdlib.h>
+#include <string.h>
+
+#include "strbuf.h"
+#include "strv.h"
+#include "util.h"
+
+static ssize_t add_string(struct strbuf *sb, const char *s) {
+ return strbuf_add_string(sb, s, strlen(s));
+}
+
+static void test_strbuf(void) {
+ struct strbuf *sb;
+ _cleanup_strv_free_ char **l;
+ ssize_t a, b, c, d, e, f, g;
+
+ sb = strbuf_new();
+
+ a = add_string(sb, "waldo");
+ b = add_string(sb, "foo");
+ c = add_string(sb, "bar");
+ d = add_string(sb, "waldo"); /* duplicate */
+ e = add_string(sb, "aldo"); /* duplicate */
+ f = add_string(sb, "do"); /* duplicate */
+ g = add_string(sb, "waldorf"); /* not a duplicate: matches from tail */
+
+ /* check the content of the buffer directly */
+ l = strv_parse_nulstr(sb->buf, sb->len);
+
+ assert(streq(l[0], "")); /* root*/
+ assert(streq(l[1], "waldo"));
+ assert(streq(l[2], "foo"));
+ assert(streq(l[3], "bar"));
+ assert(streq(l[4], "waldorf"));
+
+ assert(sb->nodes_count == 5); /* root + 4 non-duplicates */
+ assert(sb->dedup_count == 3);
+ assert(sb->in_count == 7);
+
+ assert(sb->in_len == 29); /* length of all strings added */
+ assert(sb->dedup_len == 11); /* length of all strings duplicated */
+ assert(sb->len == 23); /* buffer length: in - dedup + \0 for each node */
+
+ /* check the returned offsets and the respective content in the buffer */
+ assert(a == 1);
+ assert(b == 7);
+ assert(c == 11);
+ assert(d == 1);
+ assert(e == 2);
+ assert(f == 4);
+ assert(g == 15);
+
+ assert(streq(sb->buf + a, "waldo"));
+ assert(streq(sb->buf + b, "foo"));
+ assert(streq(sb->buf + c, "bar"));
+ assert(streq(sb->buf + d, "waldo"));
+ assert(streq(sb->buf + e, "aldo"));
+ assert(streq(sb->buf + f, "do"));
+ assert(streq(sb->buf + g, "waldorf"));
+
+ strbuf_complete(sb);
+ assert(sb->root == NULL);
+
+ strbuf_cleanup(sb);
+}
+
+int main(int argc, const char *argv[])
+{
+ test_strbuf();
+
+ return 0;
+}
diff --git a/src/test/test-strip-tab-ansi.c b/src/test/test-strip-tab-ansi.c
new file mode 100644
index 0000000000..5016906ad0
--- /dev/null
+++ b/src/test/test-strip-tab-ansi.c
@@ -0,0 +1,52 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+
+#include "util.h"
+
+int main(int argc, char *argv[]) {
+ char *p;
+
+ assert_se(p = strdup("\tFoobar\tbar\twaldo\t"));
+ assert_se(strip_tab_ansi(&p, NULL));
+ fprintf(stdout, "<%s>\n", p);
+ assert_se(streq(p, " Foobar bar waldo "));
+ free(p);
+
+ assert_se(p = strdup(ANSI_HIGHLIGHT_ON "Hello" ANSI_HIGHLIGHT_OFF ANSI_HIGHLIGHT_RED_ON " world!" ANSI_HIGHLIGHT_OFF));
+ assert_se(strip_tab_ansi(&p, NULL));
+ fprintf(stdout, "<%s>\n", p);
+ assert_se(streq(p, "Hello world!"));
+ free(p);
+
+ assert_se(p = strdup("\x1B[\x1B[\t\x1B[" ANSI_HIGHLIGHT_ON "\x1B[" "Hello" ANSI_HIGHLIGHT_OFF ANSI_HIGHLIGHT_RED_ON " world!" ANSI_HIGHLIGHT_OFF));
+ assert_se(strip_tab_ansi(&p, NULL));
+ assert_se(streq(p, "\x1B[\x1B[ \x1B[\x1B[Hello world!"));
+ free(p);
+
+ assert_se(p = strdup("\x1B[waldo"));
+ assert_se(strip_tab_ansi(&p, NULL));
+ assert_se(streq(p, "\x1B[waldo"));
+ free(p);
+
+ return 0;
+}
diff --git a/src/test/test-strv.c b/src/test/test-strv.c
new file mode 100644
index 0000000000..074e1bb3d4
--- /dev/null
+++ b/src/test/test-strv.c
@@ -0,0 +1,265 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+ Copyright 2013 Thomas H.P. Andersen
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <string.h>
+
+#include "util.h"
+#include "specifier.h"
+#include "strv.h"
+
+static void test_specifier_printf(void) {
+ _cleanup_free_ char *w = NULL;
+
+ const Specifier table[] = {
+ { 'a', specifier_string, (char*) "AAAA" },
+ { 'b', specifier_string, (char*) "BBBB" },
+ { 0, NULL, NULL }
+ };
+
+ w = specifier_printf("xxx a=%a b=%b yyy", table, NULL);
+ puts(w);
+
+ assert_se(w);
+ assert_se(streq(w, "xxx a=AAAA b=BBBB yyy"));
+}
+
+static void test_strv_find(void) {
+ const char * const input_table[] = {
+ "one",
+ "two",
+ "three",
+ NULL
+ };
+
+ assert_se(strv_find((char **)input_table, "three"));
+ assert_se(!strv_find((char **)input_table, "four"));
+}
+
+static void test_strv_find_prefix(void) {
+ const char * const input_table[] = {
+ "one",
+ "two",
+ "three",
+ NULL
+ };
+
+ assert_se(strv_find_prefix((char **)input_table, "o"));
+ assert_se(strv_find_prefix((char **)input_table, "one"));
+ assert_se(strv_find_prefix((char **)input_table, ""));
+ assert_se(!strv_find_prefix((char **)input_table, "xxx"));
+ assert_se(!strv_find_prefix((char **)input_table, "onee"));
+}
+
+static void test_strv_join(void) {
+ _cleanup_free_ char *p = NULL, *q = NULL, *r = NULL, *s = NULL, *t = NULL;
+
+ const char * const input_table_multiple[] = {
+ "one",
+ "two",
+ "three",
+ NULL
+ };
+ const char * const input_table_one[] = {
+ "one",
+ NULL
+ };
+ const char * const input_table_none[] = {
+ NULL
+ };
+
+ p = strv_join((char **)input_table_multiple, ", ");
+ assert_se(p);
+ assert_se(streq(p, "one, two, three"));
+
+ q = strv_join((char **)input_table_multiple, ";");
+ assert_se(q);
+ assert_se(streq(q, "one;two;three"));
+
+ r = strv_join((char **)input_table_multiple, NULL);
+ assert_se(r);
+ assert_se(streq(r, "one two three"));
+
+ s = strv_join((char **)input_table_one, ", ");
+ assert_se(s);
+ assert_se(streq(s, "one"));
+
+ t = strv_join((char **)input_table_none, ", ");
+ assert_se(t);
+ assert_se(streq(t, ""));
+}
+
+static void test_strv_split_nulstr(void) {
+ _cleanup_strv_free_ char **l = NULL;
+ const char nulstr[] = "str0\0str1\0str2\0str3\0";
+
+ l = strv_split_nulstr (nulstr);
+ assert_se(l);
+
+ assert_se(streq(l[0], "str0"));
+ assert_se(streq(l[1], "str1"));
+ assert_se(streq(l[2], "str2"));
+ assert_se(streq(l[3], "str3"));
+}
+
+static void test_strv_parse_nulstr(void) {
+ _cleanup_strv_free_ char **l = NULL;
+ const char nulstr[] = "fuck\0fuck2\0fuck3\0\0fuck5\0\0xxx";
+
+ l = strv_parse_nulstr(nulstr, sizeof(nulstr)-1);
+ assert_se(l);
+ puts("Parse nulstr:");
+ strv_print(l);
+
+ assert_se(streq(l[0], "fuck"));
+ assert_se(streq(l[1], "fuck2"));
+ assert_se(streq(l[2], "fuck3"));
+ assert_se(streq(l[3], ""));
+ assert_se(streq(l[4], "fuck5"));
+ assert_se(streq(l[5], ""));
+ assert_se(streq(l[6], "xxx"));
+}
+
+static void test_strv_overlap(void) {
+ const char * const input_table[] = {
+ "one",
+ "two",
+ "three",
+ NULL
+ };
+ const char * const input_table_overlap[] = {
+ "two",
+ NULL
+ };
+ const char * const input_table_unique[] = {
+ "four",
+ "five",
+ "six",
+ NULL
+ };
+
+ assert_se(strv_overlap((char **)input_table, (char**)input_table_overlap));
+ assert_se(!strv_overlap((char **)input_table, (char**)input_table_unique));
+}
+
+static void test_strv_sort(void) {
+ const char* input_table[] = {
+ "durian",
+ "apple",
+ "citrus",
+ "CAPITAL LETTERS FIRST",
+ "banana",
+ NULL
+ };
+
+ strv_sort((char **)input_table);
+
+ assert_se(streq(input_table[0], "CAPITAL LETTERS FIRST"));
+ assert_se(streq(input_table[1], "apple"));
+ assert_se(streq(input_table[2], "banana"));
+ assert_se(streq(input_table[3], "citrus"));
+ assert_se(streq(input_table[4], "durian"));
+}
+
+static void test_strv_merge_concat(void) {
+ _cleanup_strv_free_ char **a = NULL, **b = NULL, **c = NULL;
+
+ a = strv_new("without", "suffix", NULL);
+ b = strv_new("with", "suffix", NULL);
+ assert_se(a);
+ assert_se(b);
+
+ c = strv_merge_concat(a, b, "_suffix");
+ assert_se(c);
+
+ assert_se(streq(c[0], "without"));
+ assert_se(streq(c[1], "suffix"));
+ assert_se(streq(c[2], "with_suffix"));
+ assert_se(streq(c[3], "suffix_suffix"));
+}
+
+static void test_strv_merge(void) {
+ _cleanup_strv_free_ char **a = NULL, **b = NULL, **c = NULL;
+
+ a = strv_new("abc", "def", "ghi", NULL);
+ b = strv_new("jkl", "mno", "pqr", NULL);
+ assert_se(a);
+ assert_se(b);
+
+ c = strv_merge(a, b);
+ assert_se(c);
+
+ assert_se(streq(c[0], "abc"));
+ assert_se(streq(c[1], "def"));
+ assert_se(streq(c[2], "ghi"));
+ assert_se(streq(c[3], "jkl"));
+ assert_se(streq(c[4], "mno"));
+ assert_se(streq(c[5], "pqr"));
+
+ assert_se(strv_length(c) == 6);
+}
+
+static void test_strv_append(void) {
+ _cleanup_strv_free_ char **a = NULL, **b = NULL, **c = NULL;
+
+ a = strv_new("test", "test1", NULL);
+ assert_se(a);
+ b = strv_append(a, "test2");
+ c = strv_append(NULL, "test3");
+ assert_se(b);
+ assert_se(c);
+
+ assert_se(streq(b[0], "test"));
+ assert_se(streq(b[1], "test1"));
+ assert_se(streq(b[2], "test2"));
+ assert_se(streq(c[0], "test3"));
+}
+
+static void test_strv_foreach_pair(void) {
+ _cleanup_strv_free_ char **a = NULL;
+ char **x, **y;
+
+ a = strv_new("pair_one", "pair_one",
+ "pair_two", "pair_two",
+ "pair_three", "pair_three",
+ NULL);
+
+ STRV_FOREACH_PAIR(x, y, a) {
+ assert_se(streq(*x, *y));
+ }
+}
+
+int main(int argc, char *argv[]) {
+ test_specifier_printf();
+ test_strv_foreach_pair();
+ test_strv_find();
+ test_strv_find_prefix();
+ test_strv_join();
+ test_strv_split_nulstr();
+ test_strv_parse_nulstr();
+ test_strv_overlap();
+ test_strv_sort();
+ test_strv_merge();
+ test_strv_merge_concat();
+ test_strv_append();
+
+ return 0;
+}
diff --git a/src/test/test-strxcpyx.c b/src/test/test-strxcpyx.c
new file mode 100644
index 0000000000..b7b70d4c15
--- /dev/null
+++ b/src/test/test-strxcpyx.c
@@ -0,0 +1,101 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Thomas H.P. Andersen
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <string.h>
+
+#include "util.h"
+#include "strv.h"
+#include "strxcpyx.h"
+
+static void test_strpcpy(void) {
+ char target[25];
+ char *s = target;
+ size_t space_left;
+
+ space_left = sizeof(target);
+ space_left = strpcpy(&s, space_left, "12345");
+ space_left = strpcpy(&s, space_left, "hey hey hey");
+ space_left = strpcpy(&s, space_left, "waldo");
+ space_left = strpcpy(&s, space_left, "ba");
+ space_left = strpcpy(&s, space_left, "r");
+ space_left = strpcpy(&s, space_left, "foo");
+
+ assert(streq(target, "12345hey hey heywaldobar"));
+ assert(space_left == 0);
+}
+
+static void test_strpcpyf(void) {
+ char target[25];
+ char *s = target;
+ size_t space_left;
+
+ space_left = sizeof(target);
+ space_left = strpcpyf(&s, space_left, "space left: %zd. ", space_left);
+ space_left = strpcpyf(&s, space_left, "foo%s", "bar");
+
+ assert(streq(target, "space left: 25. foobar"));
+ assert(space_left == 3);
+}
+
+static void test_strpcpyl(void) {
+ char target[25];
+ char *s = target;
+ size_t space_left;
+
+ space_left = sizeof(target);
+ space_left = strpcpyl(&s, space_left, "waldo", " test", " waldo. ", NULL);
+ space_left = strpcpyl(&s, space_left, "Banana", NULL);
+
+ assert(streq(target, "waldo test waldo. Banana"));
+ assert(space_left == 1);
+}
+
+static void test_strscpy(void) {
+ char target[25];
+ size_t space_left;
+
+ space_left = sizeof(target);
+ space_left = strscpy(target, space_left, "12345");
+
+ assert(streq(target, "12345"));
+ assert(space_left == 20);
+}
+
+static void test_strscpyl(void) {
+ char target[25];
+ size_t space_left;
+
+ space_left = sizeof(target);
+ space_left = strscpyl(target, space_left, "12345", "waldo", "waldo", NULL);
+
+ assert(streq(target, "12345waldowaldo"));
+ assert(space_left == 10);
+}
+
+int main(int argc, char *argv[]) {
+ test_strpcpy();
+ test_strpcpyf();
+ test_strpcpyl();
+ test_strscpy();
+ test_strscpyl();
+
+ return 0;
+}
diff --git a/src/test/test-time.c b/src/test/test-time.c
new file mode 100644
index 0000000000..36a33046a2
--- /dev/null
+++ b/src/test/test-time.c
@@ -0,0 +1,136 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "time-util.h"
+
+static void test_parse_sec(void) {
+ usec_t u;
+
+ assert_se(parse_sec("5s", &u) >= 0);
+ assert_se(u == 5 * USEC_PER_SEC);
+ assert_se(parse_sec("5s500ms", &u) >= 0);
+ assert_se(u == 5 * USEC_PER_SEC + 500 * USEC_PER_MSEC);
+ assert_se(parse_sec(" 5s 500ms ", &u) >= 0);
+ assert_se(u == 5 * USEC_PER_SEC + 500 * USEC_PER_MSEC);
+ assert_se(parse_sec(" 5.5s ", &u) >= 0);
+ assert_se(u == 5 * USEC_PER_SEC + 500 * USEC_PER_MSEC);
+ assert_se(parse_sec(" 5.5s 0.5ms ", &u) >= 0);
+ assert_se(u == 5 * USEC_PER_SEC + 500 * USEC_PER_MSEC + 500);
+ assert_se(parse_sec(" .22s ", &u) >= 0);
+ assert_se(u == 220 * USEC_PER_MSEC);
+ assert_se(parse_sec(" .50y ", &u) >= 0);
+ assert_se(u == USEC_PER_YEAR / 2);
+ assert_se(parse_sec("2.5", &u) >= 0);
+ assert_se(u == 2500 * USEC_PER_MSEC);
+ assert_se(parse_sec(".7", &u) >= 0);
+ assert_se(u == 700 * USEC_PER_MSEC);
+
+ assert_se(parse_sec(" xyz ", &u) < 0);
+ assert_se(parse_sec("", &u) < 0);
+ assert_se(parse_sec(" . ", &u) < 0);
+ assert_se(parse_sec(" 5. ", &u) < 0);
+ assert_se(parse_sec(".s ", &u) < 0);
+}
+
+static void test_parse_nsec(void) {
+ nsec_t u;
+
+ assert_se(parse_nsec("5s", &u) >= 0);
+ assert_se(u == 5 * NSEC_PER_SEC);
+ assert_se(parse_nsec("5s500ms", &u) >= 0);
+ assert_se(u == 5 * NSEC_PER_SEC + 500 * NSEC_PER_MSEC);
+ assert_se(parse_nsec(" 5s 500ms ", &u) >= 0);
+ assert_se(u == 5 * NSEC_PER_SEC + 500 * NSEC_PER_MSEC);
+ assert_se(parse_nsec(" 5.5s ", &u) >= 0);
+ assert_se(u == 5 * NSEC_PER_SEC + 500 * NSEC_PER_MSEC);
+ assert_se(parse_nsec(" 5.5s 0.5ms ", &u) >= 0);
+ assert_se(u == 5 * NSEC_PER_SEC + 500 * NSEC_PER_MSEC + 500 * NSEC_PER_USEC);
+ assert_se(parse_nsec(" .22s ", &u) >= 0);
+ assert_se(u == 220 * NSEC_PER_MSEC);
+ assert_se(parse_nsec(" .50y ", &u) >= 0);
+ assert_se(u == NSEC_PER_YEAR / 2);
+ assert_se(parse_nsec("2.5", &u) >= 0);
+ assert_se(u == 2);
+ assert_se(parse_nsec(".7", &u) >= 0);
+ assert_se(u == 0);
+
+ assert_se(parse_nsec(" xyz ", &u) < 0);
+ assert_se(parse_nsec("", &u) < 0);
+ assert_se(parse_nsec(" . ", &u) < 0);
+ assert_se(parse_nsec(" 5. ", &u) < 0);
+ assert_se(parse_nsec(".s ", &u) < 0);
+}
+
+static void test_format_timespan_one(usec_t x, usec_t accuracy) {
+ char *r;
+ char l[FORMAT_TIMESPAN_MAX];
+ usec_t y;
+
+ log_info("%llu (at accuracy %llu)", (unsigned long long) x, (unsigned long long) accuracy);
+
+ r = format_timespan(l, sizeof(l), x, accuracy);
+ assert_se(r);
+
+ log_info(" = <%s>", l);
+
+ assert_se(parse_sec(l, &y) >= 0);
+
+ log_info(" = %llu", (unsigned long long) y);
+
+ if (accuracy <= 0)
+ accuracy = 1;
+
+ assert_se(x / accuracy == y / accuracy);
+}
+
+static void test_format_timespan(usec_t accuracy) {
+ test_format_timespan_one(0, accuracy);
+ test_format_timespan_one(1, accuracy);
+ test_format_timespan_one(1*USEC_PER_SEC, accuracy);
+ test_format_timespan_one(999*USEC_PER_MSEC, accuracy);
+ test_format_timespan_one(1234567, accuracy);
+ test_format_timespan_one(12, accuracy);
+ test_format_timespan_one(123, accuracy);
+ test_format_timespan_one(1234, accuracy);
+ test_format_timespan_one(12345, accuracy);
+ test_format_timespan_one(123456, accuracy);
+ test_format_timespan_one(1234567, accuracy);
+ test_format_timespan_one(12345678, accuracy);
+ test_format_timespan_one(1200000, accuracy);
+ test_format_timespan_one(1230000, accuracy);
+ test_format_timespan_one(1230000, accuracy);
+ test_format_timespan_one(1234000, accuracy);
+ test_format_timespan_one(1234500, accuracy);
+ test_format_timespan_one(1234560, accuracy);
+ test_format_timespan_one(1234567, accuracy);
+ test_format_timespan_one(986087, accuracy);
+ test_format_timespan_one(500 * USEC_PER_MSEC, accuracy);
+ test_format_timespan_one(9*USEC_PER_YEAR/5 - 23, accuracy);
+}
+
+int main(int argc, char *argv[]) {
+ test_parse_sec();
+ test_parse_nsec();
+ test_format_timespan(1);
+ test_format_timespan(USEC_PER_MSEC);
+ test_format_timespan(USEC_PER_SEC);
+ return 0;
+}
diff --git a/src/test/test-udev.c b/src/test/test-udev.c
new file mode 100644
index 0000000000..52b61b4206
--- /dev/null
+++ b/src/test/test-udev.c
@@ -0,0 +1,171 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2003-2004 Greg Kroah-Hartman <greg@kroah.com>
+ Copyright 2004-2012 Kay Sievers <kay@vrfy.org>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include <stddef.h>
+#include <stdlib.h>
+#include <string.h>
+#include <fcntl.h>
+#include <ctype.h>
+#include <errno.h>
+#include <unistd.h>
+#include <syslog.h>
+#include <grp.h>
+#include <sched.h>
+#include <sys/mount.h>
+#include <sys/signalfd.h>
+
+#include "missing.h"
+#include "udev.h"
+
+void udev_main_log(struct udev *udev, int priority,
+ const char *file, int line, const char *fn,
+ const char *format, va_list args) {}
+
+static int fake_filesystems(void) {
+ static const struct fakefs {
+ const char *src;
+ const char *target;
+ const char *error;
+ } fakefss[] = {
+ { "test/sys", "/sys", "failed to mount test /sys" },
+ { "test/dev", "/dev", "failed to mount test /dev" },
+ { "test/run", "/run", "failed to mount test /run" },
+ { "test/run", "/etc/udev/rules.d", "failed to mount empty /etc/udev/rules.d" },
+ { "test/run", "/usr/lib/udev/rules.d", "failed to mount empty /usr/lib/udev/rules.d" },
+ };
+ unsigned int i;
+ int err;
+
+ err = unshare(CLONE_NEWNS);
+ if (err < 0) {
+ err = -errno;
+ fprintf(stderr, "failed to call unshare(): %m\n");
+ goto out;
+ }
+
+ if (mount(NULL, "/", NULL, MS_PRIVATE|MS_REC, NULL) < 0) {
+ err = -errno;
+ fprintf(stderr, "failed to mount / as private: %m\n");
+ goto out;
+ }
+
+ for (i = 0; i < ELEMENTSOF(fakefss); i++) {
+ err = mount(fakefss[i].src, fakefss[i].target, NULL, MS_BIND, NULL);
+ if (err < 0) {
+ err = -errno;
+ fprintf(stderr, "%s %m", fakefss[i].error);
+ return err;
+ }
+ }
+out:
+ return err;
+}
+
+
+int main(int argc, char *argv[])
+{
+ struct udev *udev;
+ struct udev_event *event = NULL;
+ struct udev_device *dev = NULL;
+ struct udev_rules *rules = NULL;
+ char syspath[UTIL_PATH_SIZE];
+ const char *devpath;
+ const char *action;
+ sigset_t mask, sigmask_orig;
+ int err;
+
+ err = fake_filesystems();
+ if (err < 0)
+ return EXIT_FAILURE;
+
+ udev = udev_new();
+ if (udev == NULL)
+ exit(EXIT_FAILURE);
+ log_debug("version %s\n", VERSION);
+ label_init("/dev");
+
+ sigprocmask(SIG_SETMASK, NULL, &sigmask_orig);
+
+ action = argv[1];
+ if (action == NULL) {
+ log_error("action missing\n");
+ goto out;
+ }
+
+ devpath = argv[2];
+ if (devpath == NULL) {
+ log_error("devpath missing\n");
+ goto out;
+ }
+
+ rules = udev_rules_new(udev, 1);
+
+ strscpyl(syspath, sizeof(syspath), "/sys", devpath, NULL);
+ dev = udev_device_new_from_syspath(udev, syspath);
+ if (dev == NULL) {
+ log_debug("unknown device '%s'\n", devpath);
+ goto out;
+ }
+
+ udev_device_set_action(dev, action);
+ event = udev_event_new(dev);
+
+ sigfillset(&mask);
+ sigprocmask(SIG_SETMASK, &mask, &sigmask_orig);
+ event->fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
+ if (event->fd_signal < 0) {
+ fprintf(stderr, "error creating signalfd\n");
+ goto out;
+ }
+
+ /* do what devtmpfs usually provides us */
+ if (udev_device_get_devnode(dev) != NULL) {
+ mode_t mode = 0600;
+
+ if (streq(udev_device_get_subsystem(dev), "block"))
+ mode |= S_IFBLK;
+ else
+ mode |= S_IFCHR;
+
+ if (!streq(action, "remove")) {
+ mkdir_parents_label(udev_device_get_devnode(dev), 0755);
+ mknod(udev_device_get_devnode(dev), mode, udev_device_get_devnum(dev));
+ } else {
+ unlink(udev_device_get_devnode(dev));
+ util_delete_path(udev, udev_device_get_devnode(dev));
+ }
+ }
+
+ err = udev_event_execute_rules(event, rules, &sigmask_orig);
+ if (err == 0)
+ udev_event_execute_run(event, NULL);
+out:
+ if (event != NULL && event->fd_signal >= 0)
+ close(event->fd_signal);
+ udev_event_unref(event);
+ udev_device_unref(dev);
+ udev_rules_unref(rules);
+ label_finish();
+ udev_unref(udev);
+ if (err != 0)
+ return EXIT_FAILURE;
+ return EXIT_SUCCESS;
+}
diff --git a/src/test/test-unit-file.c b/src/test/test-unit-file.c
new file mode 100644
index 0000000000..a7fe77af24
--- /dev/null
+++ b/src/test/test-unit-file.c
@@ -0,0 +1,367 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+ Copyright 2013 Zbigniew Jędrzejewski-Szmek
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <stdio.h>
+#include <stddef.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "install.h"
+#include "install-printf.h"
+#include "specifier.h"
+#include "util.h"
+#include "macro.h"
+#include "hashmap.h"
+#include "load-fragment.h"
+#include "strv.h"
+#include "fileio.h"
+
+static void test_unit_file_get_set(void) {
+ int r;
+ Hashmap *h;
+ Iterator i;
+ UnitFileList *p;
+
+ h = hashmap_new(string_hash_func, string_compare_func);
+ assert(h);
+
+ r = unit_file_get_list(UNIT_FILE_SYSTEM, NULL, h);
+ log_info("unit_file_get_list: %s", strerror(-r));
+ assert(r >= 0);
+
+ HASHMAP_FOREACH(p, h, i)
+ printf("%s = %s\n", p->path, unit_file_state_to_string(p->state));
+
+ unit_file_list_free(h);
+}
+
+static void check_execcommand(ExecCommand *c,
+ const char* path,
+ const char* argv0,
+ const char* argv1,
+ bool ignore) {
+ assert_se(c);
+ log_info("%s %s %s %s",
+ c->path, c->argv[0], c->argv[1], c->argv[2]);
+ assert_se(streq(c->path, path));
+ assert_se(streq(c->argv[0], argv0));
+ assert_se(streq(c->argv[1], argv1));
+ assert_se(c->argv[2] == NULL);
+ assert_se(c->ignore == ignore);
+}
+
+static void test_config_parse_exec(void) {
+ /* int config_parse_exec( */
+ /* const char *filename, */
+ /* unsigned line, */
+ /* const char *section, */
+ /* const char *lvalue, */
+ /* int ltype, */
+ /* const char *rvalue, */
+ /* void *data, */
+ /* void *userdata) */
+ int r;
+
+ ExecCommand *c = NULL, *c1;
+
+ /* basic test */
+ r = config_parse_exec(NULL, "fake", 1, "section",
+ "LValue", 0, "/RValue r1",
+ &c, NULL);
+ assert_se(r >= 0);
+ check_execcommand(c, "/RValue", "/RValue", "r1", false);
+
+ r = config_parse_exec(NULL, "fake", 2, "section",
+ "LValue", 0, "/RValue///slashes/// r1",
+ &c, NULL);
+ /* test slashes */
+ assert_se(r >= 0);
+ c1 = c->command_next;
+ check_execcommand(c1, "/RValue/slashes", "/RValue///slashes///",
+ "r1", false);
+
+ /* honour_argv0 */
+ r = config_parse_exec(NULL, "fake", 3, "section",
+ "LValue", 0, "@/RValue///slashes2/// argv0 r1",
+ &c, NULL);
+ assert_se(r >= 0);
+ c1 = c1->command_next;
+ check_execcommand(c1, "/RValue/slashes2", "argv0", "r1", false);
+
+ /* ignore && honour_argv0 */
+ r = config_parse_exec(NULL, "fake", 4, "section",
+ "LValue", 0, "-@/RValue///slashes3/// argv0a r1",
+ &c, NULL);
+ assert_se(r >= 0);
+ c1 = c1->command_next;
+ check_execcommand(c1,
+ "/RValue/slashes3", "argv0a", "r1", true);
+
+ /* ignore && honour_argv0 */
+ r = config_parse_exec(NULL, "fake", 4, "section",
+ "LValue", 0, "@-/RValue///slashes4/// argv0b r1",
+ &c, NULL);
+ assert_se(r >= 0);
+ c1 = c1->command_next;
+ check_execcommand(c1,
+ "/RValue/slashes4", "argv0b", "r1", true);
+
+ /* ignore && ignore */
+ r = config_parse_exec(NULL, "fake", 4, "section",
+ "LValue", 0, "--/RValue argv0 r1",
+ &c, NULL);
+ assert_se(r == 0);
+ assert_se(c1->command_next == NULL);
+
+ /* ignore && ignore */
+ r = config_parse_exec(NULL, "fake", 4, "section",
+ "LValue", 0, "-@-/RValue argv0 r1",
+ &c, NULL);
+ assert_se(r == 0);
+ assert_se(c1->command_next == NULL);
+
+ /* semicolon */
+ r = config_parse_exec(NULL, "fake", 5, "section",
+ "LValue", 0,
+ "-@/RValue argv0 r1 ; "
+ "/goo/goo boo",
+ &c, NULL);
+ assert_se(r >= 0);
+ c1 = c1->command_next;
+ check_execcommand(c1,
+ "/RValue", "argv0", "r1", true);
+
+ c1 = c1->command_next;
+ check_execcommand(c1,
+ "/goo/goo", "/goo/goo", "boo", false);
+
+ /* trailing semicolon */
+ r = config_parse_exec(NULL, "fake", 5, "section",
+ "LValue", 0,
+ "-@/RValue argv0 r1 ; ",
+ &c, NULL);
+ assert_se(r >= 0);
+ c1 = c1->command_next;
+ check_execcommand(c1,
+ "/RValue", "argv0", "r1", true);
+
+ assert_se(c1->command_next == NULL);
+
+ /* escaped semicolon */
+ r = config_parse_exec(NULL, "fake", 5, "section",
+ "LValue", 0,
+ "/usr/bin/find \\;",
+ &c, NULL);
+ assert_se(r >= 0);
+ c1 = c1->command_next;
+ check_execcommand(c1,
+ "/usr/bin/find", "/usr/bin/find", ";", false);
+
+ exec_command_free_list(c);
+}
+
+#define env_file_1 \
+ "a=a\n" \
+ "b=b\\\n" \
+ "c\n" \
+ "d=d\\\n" \
+ "e\\\n" \
+ "f\n" \
+ "g=g\\ \n" \
+ "h=h\n" \
+ "i=i\\"
+
+#define env_file_2 \
+ "a=a\\\n"
+
+#define env_file_3 \
+ "#SPAMD_ARGS=\"-d --socketpath=/var/lib/bulwark/spamd \\\n" \
+ "#--nouser-config \\\n" \
+ "normal=line"
+
+#define env_file_4 \
+ "# Generated\n" \
+ "\n" \
+ "HWMON_MODULES=\"coretemp f71882fg\"\n" \
+ "\n" \
+ "# For compatibility reasons\n" \
+ "\n" \
+ "MODULE_0=coretemp\n" \
+ "MODULE_1=f71882fg"
+
+
+static void test_load_env_file_1(void) {
+ _cleanup_strv_free_ char **data = NULL;
+ int r;
+
+ char name[] = "/tmp/test-load-env-file.XXXXXX";
+ _cleanup_close_ int fd = mkstemp(name);
+ assert(fd >= 0);
+ assert_se(write(fd, env_file_1, sizeof(env_file_1)) == sizeof(env_file_1));
+
+ r = load_env_file(name, NULL, &data);
+ assert(r == 0);
+ assert(streq(data[0], "a=a"));
+ assert(streq(data[1], "b=bc"));
+ assert(streq(data[2], "d=def"));
+ assert(streq(data[3], "g=g "));
+ assert(streq(data[4], "h=h"));
+ assert(streq(data[5], "i=i"));
+ assert(data[6] == NULL);
+ unlink(name);
+}
+
+static void test_load_env_file_2(void) {
+ _cleanup_strv_free_ char **data = NULL;
+ int r;
+
+ char name[] = "/tmp/test-load-env-file.XXXXXX";
+ _cleanup_close_ int fd = mkstemp(name);
+ assert(fd >= 0);
+ assert_se(write(fd, env_file_2, sizeof(env_file_2)) == sizeof(env_file_2));
+
+ r = load_env_file(name, NULL, &data);
+ assert(r == 0);
+ assert(streq(data[0], "a=a"));
+ assert(data[1] == NULL);
+ unlink(name);
+}
+
+static void test_load_env_file_3(void) {
+ _cleanup_strv_free_ char **data = NULL;
+ int r;
+
+ char name[] = "/tmp/test-load-env-file.XXXXXX";
+ _cleanup_close_ int fd = mkstemp(name);
+ assert(fd >= 0);
+ assert_se(write(fd, env_file_3, sizeof(env_file_3)) == sizeof(env_file_3));
+
+ r = load_env_file(name, NULL, &data);
+ assert(r == 0);
+ assert(data == NULL);
+ unlink(name);
+}
+
+static void test_load_env_file_4(void) {
+ _cleanup_strv_free_ char **data = NULL;
+ int r;
+
+ char name[] = "/tmp/test-load-env-file.XXXXXX";
+ _cleanup_close_ int fd = mkstemp(name);
+ assert(fd >= 0);
+ assert_se(write(fd, env_file_4, sizeof(env_file_4)) == sizeof(env_file_4));
+
+ r = load_env_file(name, NULL, &data);
+ assert(r == 0);
+ assert(streq(data[0], "HWMON_MODULES=coretemp f71882fg"));
+ assert(streq(data[1], "MODULE_0=coretemp"));
+ assert(streq(data[2], "MODULE_1=f71882fg"));
+ assert(data[3] == NULL);
+ unlink(name);
+}
+
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wnonnull"
+
+static void test_install_printf(void) {
+ char name[] = "name.service",
+ path[] = "/run/systemd/system/name.service",
+ user[] = "xxxx-no-such-user";
+ InstallInfo i = {name, path, user};
+ InstallInfo i2 = {name, path, NULL};
+ char name3[] = "name@inst.service",
+ path3[] = "/run/systemd/system/name.service";
+ InstallInfo i3 = {name3, path3, user};
+ InstallInfo i4 = {name3, path3, NULL};
+
+ _cleanup_free_ char *mid, *bid, *host;
+
+ assert_se((mid = specifier_machine_id('m', NULL, NULL)));
+ assert_se((bid = specifier_boot_id('b', NULL, NULL)));
+ assert_se((host = gethostname_malloc()));
+
+#define expect(src, pattern, result) \
+ do { \
+ _cleanup_free_ char *t = install_full_printf(&src, pattern); \
+ _cleanup_free_ char \
+ *d1 = strdup(i.name), \
+ *d2 = strdup(i.path), \
+ *d3 = strdup(i.user); \
+ memzero(i.name, strlen(i.name)); \
+ memzero(i.path, strlen(i.path)); \
+ memzero(i.user, strlen(i.user)); \
+ assert(d1 && d2 && d3); \
+ if (result) { \
+ printf("%s\n", t); \
+ assert(streq(t, result)); \
+ } else assert(t == NULL); \
+ strcpy(i.name, d1); \
+ strcpy(i.path, d2); \
+ strcpy(i.user, d3); \
+ } while(false)
+
+ assert_se(setenv("USER", "root", 1) == 0);
+
+ expect(i, "%n", "name.service");
+ expect(i, "%N", "name");
+ expect(i, "%p", "name");
+ expect(i, "%i", "");
+ expect(i, "%u", "xxxx-no-such-user");
+ expect(i, "%U", NULL);
+ expect(i, "%m", mid);
+ expect(i, "%b", bid);
+ expect(i, "%H", host);
+
+ expect(i2, "%u", "root");
+ expect(i2, "%U", "0");
+
+ expect(i3, "%n", "name@inst.service");
+ expect(i3, "%N", "name@inst");
+ expect(i3, "%p", "name");
+ expect(i3, "%u", "xxxx-no-such-user");
+ expect(i3, "%U", NULL);
+ expect(i3, "%m", mid);
+ expect(i3, "%b", bid);
+ expect(i3, "%H", host);
+
+ expect(i4, "%u", "root");
+ expect(i4, "%U", "0");
+}
+#pragma GCC diagnostic pop
+
+int main(int argc, char *argv[]) {
+
+ log_parse_environment();
+ log_open();
+
+ test_unit_file_get_set();
+ test_config_parse_exec();
+ test_load_env_file_1();
+ test_load_env_file_2();
+ test_load_env_file_3();
+ test_load_env_file_4();
+ test_install_printf();
+
+ return 0;
+}
diff --git a/src/test/test-unit-name.c b/src/test/test-unit-name.c
new file mode 100644
index 0000000000..86cb2b8da6
--- /dev/null
+++ b/src/test/test-unit-name.c
@@ -0,0 +1,199 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+ Copyright 2013 Zbigniew Jędrzejewski-Szmek
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <pwd.h>
+
+#include "manager.h"
+#include "unit.h"
+#include "unit-name.h"
+#include "unit-printf.h"
+#include "install.h"
+#include "specifier.h"
+#include "util.h"
+#include "macro.h"
+
+static void test_replacements(void) {
+#define expect(pattern, repl, expected) \
+ { \
+ _cleanup_free_ char *t = \
+ unit_name_replace_instance(pattern, repl); \
+ puts(t); \
+ assert(streq(t, expected)); \
+ }
+
+ expect("foo@.service", "waldo", "foo@waldo.service");
+ expect("foo@xyz.service", "waldo", "foo@waldo.service");
+ expect("xyz", "waldo", "xyz");
+ expect("", "waldo", "");
+ expect("foo.service", "waldo", "foo.service");
+ expect(".service", "waldo", ".service");
+ expect("foo@", "waldo", "foo@waldo");
+ expect("@bar", "waldo", "@waldo");
+
+ puts("-------------------------------------------------");
+#undef expect
+#define expect(path, suffix, expected) \
+ { \
+ _cleanup_free_ char *k, *t = \
+ unit_name_from_path(path, suffix); \
+ puts(t); \
+ k = unit_name_to_path(t); \
+ puts(k); \
+ assert(streq(k, expected ? expected : path)); \
+ }
+
+ expect("/waldo", ".mount", NULL);
+ expect("/waldo/quuix", ".mount", NULL);
+ expect("/waldo/quuix/", ".mount", "/waldo/quuix");
+ expect("/", ".mount", NULL);
+ expect("///", ".mount", "/");
+
+ puts("-------------------------------------------------");
+#undef expect
+#define expect(pattern, path, suffix, expected) \
+ { \
+ _cleanup_free_ char *t = \
+ unit_name_from_path_instance(pattern, path, suffix); \
+ puts(t); \
+ assert(streq(t, expected)); \
+ }
+
+ expect("waldo", "/waldo", ".mount", "waldo@waldo.mount");
+ expect("waldo", "/waldo////quuix////", ".mount", "waldo@waldo-quuix.mount");
+ expect("waldo", "/", ".mount", "waldo@-.mount");
+ expect("wa--ldo", "/--", ".mount", "wa--ldo@\\x2d\\x2d.mount");
+
+ puts("-------------------------------------------------");
+#undef expect
+#define expect(pattern) \
+ { \
+ _cleanup_free_ char *k, *t; \
+ assert_se(t = unit_name_mangle(pattern)); \
+ assert_se(k = unit_name_mangle(t)); \
+ puts(t); \
+ assert_se(streq(t, k)); \
+ }
+
+ expect("/home");
+ expect("/dev/sda");
+ expect("üxknürz.service");
+ expect("foobar-meh...waldi.service");
+ expect("_____####----.....service");
+ expect("_____##@;;;,,,##----.....service");
+ expect("xxx@@@@/////\\\\\\\\\\yyy.service");
+
+#undef expect
+}
+
+static int test_unit_printf(void) {
+ Manager *m;
+ Unit *u, *u2;
+ int r;
+
+ _cleanup_free_ char *mid, *bid, *host, *root_uid;
+ struct passwd *root;
+
+ assert_se((mid = specifier_machine_id('m', NULL, NULL)));
+ assert_se((bid = specifier_boot_id('b', NULL, NULL)));
+ assert_se((host = gethostname_malloc()));
+
+ assert_se((root = getpwnam("root")));
+ assert_se(asprintf(&root_uid, "%d", (int) root->pw_uid) > 0);
+
+ r = manager_new(SYSTEMD_USER, &m);
+ if (r == -EPERM) {
+ puts("manager_new: Permission denied. Skipping test.");
+ return EXIT_TEST_SKIP;
+ }
+ assert(r == 0);
+
+#define expect(unit, pattern, expected) \
+ { \
+ char *e; \
+ _cleanup_free_ char *t = \
+ unit_full_printf(unit, pattern); \
+ printf("result: %s\nexpect: %s\n", t, expected); \
+ if ((e = endswith(expected, "*"))) \
+ assert(strncmp(t, e, e-expected)); \
+ else \
+ assert(streq(t, expected)); \
+ }
+
+ assert_se(setenv("USER", "root", 1) == 0);
+ assert_se(setenv("HOME", "/root", 1) == 0);
+
+ assert_se(u = unit_new(m, sizeof(Service)));
+ assert_se(unit_add_name(u, "blah.service") == 0);
+ assert_se(unit_add_name(u, "blah.service") == 0);
+
+ /* general tests */
+ expect(u, "%%", "%");
+ expect(u, "%%s", "%s");
+ expect(u, "%", ""); // REALLY?
+
+ /* normal unit */
+ expect(u, "%n", "blah.service");
+ expect(u, "%N", "blah");
+ expect(u, "%p", "blah");
+ expect(u, "%P", "blah");
+ expect(u, "%i", "");
+ expect(u, "%I", "");
+ expect(u, "%u", root->pw_name);
+ expect(u, "%U", root_uid);
+ expect(u, "%h", root->pw_dir);
+ expect(u, "%s", "/bin/sh");
+ expect(u, "%m", mid);
+ expect(u, "%b", bid);
+ expect(u, "%H", host);
+ expect(u, "%t", "/run/user/*");
+
+ /* templated */
+ assert_se(u2 = unit_new(m, sizeof(Service)));
+ assert_se(unit_add_name(u2, "blah@foo-foo.service") == 0);
+ assert_se(unit_add_name(u2, "blah@foo-foo.service") == 0);
+
+ expect(u2, "%n", "blah@foo-foo.service");
+ expect(u2, "%N", "blah@foo-foo");
+ expect(u2, "%p", "blah");
+ expect(u2, "%P", "blah");
+ expect(u2, "%i", "foo-foo");
+ expect(u2, "%I", "foo/foo");
+ expect(u2, "%u", root->pw_name);
+ expect(u2, "%U", root_uid);
+ expect(u2, "%h", root->pw_dir);
+ expect(u2, "%s", "/bin/sh");
+ expect(u2, "%m", mid);
+ expect(u2, "%b", bid);
+ expect(u2, "%H", host);
+ expect(u2, "%t", "/run/user/*");
+
+ return 0;
+}
+
+int main(int argc, char* argv[]) {
+ test_replacements();
+ return test_unit_printf();
+}
diff --git a/src/test/test-util.c b/src/test/test-util.c
new file mode 100644
index 0000000000..4c3a8a6b88
--- /dev/null
+++ b/src/test/test-util.c
@@ -0,0 +1,472 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+ Copyright 2013 Thomas H.P. Andersen
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <string.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <locale.h>
+#include <errno.h>
+
+#include "util.h"
+
+static void test_streq_ptr(void) {
+ assert_se(streq_ptr(NULL, NULL));
+ assert_se(!streq_ptr("abc", "cdef"));
+}
+
+static void test_first_word(void) {
+ assert_se(first_word("Hello", ""));
+ assert_se(first_word("Hello", "Hello"));
+ assert_se(first_word("Hello world", "Hello"));
+ assert_se(first_word("Hello\tworld", "Hello"));
+ assert_se(first_word("Hello\nworld", "Hello"));
+ assert_se(first_word("Hello\rworld", "Hello"));
+ assert_se(first_word("Hello ", "Hello"));
+
+ assert_se(!first_word("Hello", "Hellooo"));
+ assert_se(!first_word("Hello", "xxxxx"));
+ assert_se(!first_word("Hellooo", "Hello"));
+}
+
+static void test_close_many(void) {
+ int fds[3];
+ char name0[] = "/tmp/test-close-many.XXXXXX";
+ char name1[] = "/tmp/test-close-many.XXXXXX";
+ char name2[] = "/tmp/test-close-many.XXXXXX";
+
+ fds[0] = mkstemp(name0);
+ fds[1] = mkstemp(name1);
+ fds[2] = mkstemp(name2);
+
+ close_many(fds, 2);
+
+ assert_se(fcntl(fds[0], F_GETFD) == -1);
+ assert_se(fcntl(fds[1], F_GETFD) == -1);
+ assert_se(fcntl(fds[2], F_GETFD) >= 0);
+
+ close_nointr_nofail(fds[2]);
+
+ unlink(name0);
+ unlink(name1);
+ unlink(name2);
+}
+
+static void test_parse_boolean(void) {
+ assert_se(parse_boolean("1") == 1);
+ assert_se(parse_boolean("y") == 1);
+ assert_se(parse_boolean("Y") == 1);
+ assert_se(parse_boolean("yes") == 1);
+ assert_se(parse_boolean("YES") == 1);
+ assert_se(parse_boolean("true") == 1);
+ assert_se(parse_boolean("TRUE") == 1);
+ assert_se(parse_boolean("on") == 1);
+ assert_se(parse_boolean("ON") == 1);
+
+ assert_se(parse_boolean("0") == 0);
+ assert_se(parse_boolean("n") == 0);
+ assert_se(parse_boolean("N") == 0);
+ assert_se(parse_boolean("no") == 0);
+ assert_se(parse_boolean("NO") == 0);
+ assert_se(parse_boolean("false") == 0);
+ assert_se(parse_boolean("FALSE") == 0);
+ assert_se(parse_boolean("off") == 0);
+ assert_se(parse_boolean("OFF") == 0);
+
+ assert_se(parse_boolean("garbage") < 0);
+ assert_se(parse_boolean("") < 0);
+}
+
+static void test_parse_pid(void) {
+ int r;
+ pid_t pid;
+
+ r = parse_pid("100", &pid);
+ assert_se(r == 0);
+ assert_se(pid == 100);
+
+ r = parse_pid("0x7FFFFFFF", &pid);
+ assert_se(r == 0);
+ assert_se(pid == 2147483647);
+
+ pid = 65; /* pid is left unchanged on ERANGE. Set to known arbitrary value. */
+ r = parse_pid("0", &pid);
+ assert_se(r == -ERANGE);
+ assert_se(pid == 65);
+
+ pid = 65; /* pid is left unchanged on ERANGE. Set to known arbitrary value. */
+ r = parse_pid("-100", &pid);
+ assert_se(r == -ERANGE);
+ assert_se(pid == 65);
+
+ pid = 65; /* pid is left unchanged on ERANGE. Set to known arbitrary value. */
+ r = parse_pid("0xFFFFFFFFFFFFFFFFF", &pid);
+ assert(r == -ERANGE);
+ assert_se(pid == 65);
+}
+
+static void test_parse_uid(void) {
+ int r;
+ uid_t uid;
+
+ r = parse_uid("100", &uid);
+ assert_se(r == 0);
+ assert_se(uid == 100);
+}
+
+static void test_safe_atolli(void) {
+ int r;
+ long long l;
+
+ r = safe_atolli("12345", &l);
+ assert_se(r == 0);
+ assert_se(l == 12345);
+
+ r = safe_atolli("junk", &l);
+ assert_se(r == -EINVAL);
+}
+
+static void test_safe_atod(void) {
+ int r;
+ double d;
+ char *e;
+
+ r = safe_atod("junk", &d);
+ assert_se(r == -EINVAL);
+
+ r = safe_atod("0.2244", &d);
+ assert_se(r == 0);
+ assert_se(abs(d - 0.2244) < 0.000001);
+
+ r = safe_atod("0,5", &d);
+ assert_se(r == -EINVAL);
+
+ errno = 0;
+ strtod("0,5", &e);
+ assert_se(*e == ',');
+
+ /* Check if this really is locale independent */
+ setlocale(LC_NUMERIC, "de_DE.utf8");
+
+ r = safe_atod("0.2244", &d);
+ assert_se(r == 0);
+ assert_se(abs(d - 0.2244) < 0.000001);
+
+ r = safe_atod("0,5", &d);
+ assert_se(r == -EINVAL);
+
+ errno = 0;
+ assert_se(abs(strtod("0,5", &e) - 0.5) < 0.00001);
+
+ /* And check again, reset */
+ setlocale(LC_NUMERIC, "C");
+
+ r = safe_atod("0.2244", &d);
+ assert_se(r == 0);
+ assert_se(abs(d - 0.2244) < 0.000001);
+
+ r = safe_atod("0,5", &d);
+ assert_se(r == -EINVAL);
+
+ errno = 0;
+ strtod("0,5", &e);
+ assert_se(*e == ',');
+}
+
+static void test_strappend(void) {
+ _cleanup_free_ char *t1, *t2, *t3, *t4;
+
+ t1 = strappend(NULL, NULL);
+ assert_se(streq(t1, ""));
+
+ t2 = strappend(NULL, "suf");
+ assert_se(streq(t2, "suf"));
+
+ t3 = strappend("pre", NULL);
+ assert_se(streq(t3, "pre"));
+
+ t4 = strappend("pre", "suf");
+ assert_se(streq(t4, "presuf"));
+}
+
+static void test_strstrip(void) {
+ char *r;
+ char input[] = " hello, waldo. ";
+
+ r = strstrip(input);
+ assert_se(streq(r, "hello, waldo."));
+
+}
+
+static void test_delete_chars(void) {
+ char *r;
+ char input[] = " hello, waldo. abc";
+
+ r = delete_chars(input, WHITESPACE);
+ assert_se(streq(r, "hello,waldo.abc"));
+}
+
+static void test_in_charset(void) {
+ assert_se(in_charset("dddaaabbbcccc", "abcd"));
+ assert_se(!in_charset("dddaaabbbcccc", "abc f"));
+}
+
+static void test_hexchar(void) {
+ assert_se(hexchar(0xa) == 'a');
+ assert_se(hexchar(0x0) == '0');
+}
+
+static void test_unhexchar(void) {
+ assert_se(unhexchar('a') == 0xA);
+ assert_se(unhexchar('A') == 0xA);
+ assert_se(unhexchar('0') == 0x0);
+}
+
+static void test_octchar(void) {
+ assert_se(octchar(00) == '0');
+ assert_se(octchar(07) == '7');
+}
+
+static void test_unoctchar(void) {
+ assert_se(unoctchar('0') == 00);
+ assert_se(unoctchar('7') == 07);
+}
+
+static void test_decchar(void) {
+ assert_se(decchar(0) == '0');
+ assert_se(decchar(9) == '9');
+}
+
+static void test_undecchar(void) {
+ assert_se(undecchar('0') == 0);
+ assert_se(undecchar('9') == 9);
+}
+
+static void test_foreach_word(void) {
+ char *w, *state;
+ size_t l;
+ int i = 0;
+ const char test[] = "test abc d\te f ";
+ const char * const expected[] = {
+ "test",
+ "abc",
+ "d",
+ "e",
+ "f",
+ "",
+ NULL
+ };
+
+ FOREACH_WORD(w, l, test, state) {
+ assert_se(strneq(expected[i++], w, l));
+ }
+}
+
+static void test_foreach_word_quoted(void) {
+ char *w, *state;
+ size_t l;
+ int i = 0;
+ const char test[] = "test a b c 'd' e '' '' hhh '' '' \"a b c\"";
+ const char * const expected[] = {
+ "test",
+ "a",
+ "b",
+ "c",
+ "d",
+ "e",
+ "",
+ "",
+ "hhh",
+ "",
+ "",
+ "a b c",
+ NULL
+ };
+
+ printf("<%s>\n", test);
+ FOREACH_WORD_QUOTED(w, l, test, state) {
+ _cleanup_free_ char *t = NULL;
+
+ assert_se(t = strndup(w, l));
+ assert_se(strneq(expected[i++], w, l));
+ printf("<%s>\n", t);
+ }
+}
+
+static void test_default_term_for_tty(void) {
+ puts(default_term_for_tty("/dev/tty23"));
+ puts(default_term_for_tty("/dev/ttyS23"));
+ puts(default_term_for_tty("/dev/tty0"));
+ puts(default_term_for_tty("/dev/pty0"));
+ puts(default_term_for_tty("/dev/pts/0"));
+ puts(default_term_for_tty("/dev/console"));
+ puts(default_term_for_tty("tty23"));
+ puts(default_term_for_tty("ttyS23"));
+ puts(default_term_for_tty("tty0"));
+ puts(default_term_for_tty("pty0"));
+ puts(default_term_for_tty("pts/0"));
+ puts(default_term_for_tty("console"));
+}
+
+static void test_memdup_multiply(void) {
+ int org[] = {1, 2, 3};
+ int *dup;
+
+ dup = (int*)memdup_multiply(org, sizeof(int), 3);
+
+ assert_se(dup);
+ assert_se(dup[0] == 1);
+ assert_se(dup[1] == 2);
+ assert_se(dup[2] == 3);
+ free(dup);
+}
+
+static void test_bus_path_escape_one(const char *a, const char *b) {
+ _cleanup_free_ char *t = NULL, *x = NULL, *y = NULL;
+
+ assert_se(t = bus_path_escape(a));
+ assert_se(streq(t, b));
+
+ assert_se(x = bus_path_unescape(t));
+ assert_se(streq(a, x));
+
+ assert_se(y = bus_path_unescape(b));
+ assert_se(streq(a, y));
+}
+
+static void test_bus_path_escape(void) {
+ test_bus_path_escape_one("foo123bar", "foo123bar");
+ test_bus_path_escape_one("foo.bar", "foo_2ebar");
+ test_bus_path_escape_one("foo_2ebar", "foo_5f2ebar");
+ test_bus_path_escape_one("", "_");
+ test_bus_path_escape_one("_", "_5f");
+ test_bus_path_escape_one("1", "_31");
+ test_bus_path_escape_one(":1", "_3a1");
+}
+
+static void test_hostname_is_valid(void) {
+ assert(hostname_is_valid("foobar"));
+ assert(hostname_is_valid("foobar.com"));
+ assert(!hostname_is_valid("fööbar"));
+ assert(!hostname_is_valid(""));
+ assert(!hostname_is_valid("."));
+ assert(!hostname_is_valid(".."));
+ assert(!hostname_is_valid("foobar."));
+ assert(!hostname_is_valid(".foobar"));
+ assert(!hostname_is_valid("foo..bar"));
+ assert(!hostname_is_valid("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"));
+}
+
+static void test_u64log2(void) {
+ assert(u64log2(0) == 0);
+ assert(u64log2(8) == 3);
+ assert(u64log2(9) == 3);
+ assert(u64log2(15) == 3);
+ assert(u64log2(16) == 4);
+ assert(u64log2(1024*1024) == 20);
+ assert(u64log2(1024*1024+5) == 20);
+}
+
+static void test_get_process_comm(void) {
+ _cleanup_free_ char *a = NULL, *c = NULL, *d = NULL, *f = NULL, *i = NULL;
+ unsigned long long b;
+ pid_t e;
+ uid_t u;
+ gid_t g;
+ dev_t h;
+ int r;
+
+ assert_se(get_process_comm(1, &a) >= 0);
+ log_info("pid1 comm: '%s'", a);
+
+ assert_se(get_starttime_of_pid(1, &b) >= 0);
+ log_info("pid1 starttime: '%llu'", b);
+
+ assert_se(get_process_cmdline(1, 0, true, &c) >= 0);
+ log_info("pid1 cmdline: '%s'", c);
+
+ assert_se(get_process_cmdline(1, 8, false, &d) >= 0);
+ log_info("pid1 cmdline truncated: '%s'", d);
+
+ assert_se(get_parent_of_pid(1, &e) >= 0);
+ log_info("pid1 ppid: '%llu'", (unsigned long long) e);
+ assert_se(e == 0);
+
+ assert_se(is_kernel_thread(1) == 0);
+
+ r = get_process_exe(1, &f);
+ assert_se(r >= 0 || r == -EACCES);
+ log_info("pid1 exe: '%s'", strna(f));
+
+ assert_se(get_process_uid(1, &u) == 0);
+ log_info("pid1 uid: '%llu'", (unsigned long long) u);
+ assert_se(u == 0);
+
+ assert_se(get_process_gid(1, &g) == 0);
+ log_info("pid1 gid: '%llu'", (unsigned long long) g);
+ assert_se(g == 0);
+
+ assert(get_ctty_devnr(1, &h) == -ENOENT);
+
+ getenv_for_pid(1, "PATH", &i);
+ log_info("pid1 $PATH: '%s'", strna(i));
+}
+
+static void test_protect_errno(void) {
+ errno = 12;
+ {
+ PROTECT_ERRNO;
+ errno = 11;
+ }
+ assert(errno == 12);
+}
+
+int main(int argc, char *argv[]) {
+ test_streq_ptr();
+ test_first_word();
+ test_close_many();
+ test_parse_boolean();
+ test_parse_pid();
+ test_parse_uid();
+ test_safe_atolli();
+ test_safe_atod();
+ test_strappend();
+ test_strstrip();
+ test_delete_chars();
+ test_in_charset();
+ test_hexchar();
+ test_unhexchar();
+ test_octchar();
+ test_unoctchar();
+ test_decchar();
+ test_undecchar();
+ test_foreach_word();
+ test_foreach_word_quoted();
+ test_default_term_for_tty();
+ test_memdup_multiply();
+ test_bus_path_escape();
+ test_hostname_is_valid();
+ test_u64log2();
+ test_get_process_comm();
+ test_protect_errno();
+
+ return 0;
+}
diff --git a/src/test/test-watchdog.c b/src/test/test-watchdog.c
new file mode 100644
index 0000000000..ccb1854708
--- /dev/null
+++ b/src/test/test-watchdog.c
@@ -0,0 +1,51 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <unistd.h>
+#include <string.h>
+
+#include "watchdog.h"
+#include "log.h"
+
+int main(int argc, char *argv[]) {
+ usec_t t = 10 * USEC_PER_SEC;
+ unsigned i;
+ int r;
+
+ log_set_max_level(LOG_DEBUG);
+ log_parse_environment();
+
+ r = watchdog_set_timeout(&t);
+ if (r < 0)
+ log_warning("Failed to open watchdog: %s", strerror(-r));
+
+ for (i = 0; i < 5; i++) {
+ log_info("Pinging...");
+ r = watchdog_ping();
+ if (r < 0)
+ log_warning("Failed to ping watchdog: %s", strerror(-r));
+
+ usleep(t/2);
+ }
+
+ watchdog_close(true);
+ return 0;
+}
diff --git a/src/timedate/org.freedesktop.timedate1.conf b/src/timedate/org.freedesktop.timedate1.conf
new file mode 100644
index 0000000000..36557d5841
--- /dev/null
+++ b/src/timedate/org.freedesktop.timedate1.conf
@@ -0,0 +1,27 @@
+<?xml version="1.0"?> <!--*-nxml-*-->
+<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
+ "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
+
+<!--
+ This file is part of systemd.
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+-->
+
+<busconfig>
+
+ <policy user="root">
+ <allow own="org.freedesktop.timedate1"/>
+ <allow send_destination="org.freedesktop.timedate1"/>
+ <allow receive_sender="org.freedesktop.timedate1"/>
+ </policy>
+
+ <policy context="default">
+ <allow send_destination="org.freedesktop.timedate1"/>
+ <allow receive_sender="org.freedesktop.timedate1"/>
+ </policy>
+
+</busconfig>
diff --git a/src/timedate/org.freedesktop.timedate1.policy.in b/src/timedate/org.freedesktop.timedate1.policy.in
new file mode 100644
index 0000000000..aa30b70831
--- /dev/null
+++ b/src/timedate/org.freedesktop.timedate1.policy.in
@@ -0,0 +1,62 @@
+<?xml version="1.0" encoding="UTF-8"?> <!--*-nxml-*-->
+<!DOCTYPE policyconfig PUBLIC "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
+ "http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd">
+
+<!--
+ This file is part of systemd.
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+-->
+
+<policyconfig>
+
+ <vendor>The systemd Project</vendor>
+ <vendor_url>http://www.freedesktop.org/wiki/Software/systemd</vendor_url>
+
+ <action id="org.freedesktop.timedate1.set-time">
+ <_description>Set system time</_description>
+ <_message>Authentication is required to set the system time.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.timedate1.set-timezone org.freedesktop.timedate1.set-ntp</annotate>
+ </action>
+
+ <action id="org.freedesktop.timedate1.set-timezone">
+ <_description>Set system timezone</_description>
+ <_message>Authentication is required to set the system timezone.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ </action>
+
+ <action id="org.freedesktop.timedate1.set-local-rtc">
+ <_description>Set RTC to local timezone or UTC</_description>
+ <_message>Authentication is required to control whether
+ the RTC stores the local or UTC time.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ </action>
+
+ <action id="org.freedesktop.timedate1.set-ntp">
+ <_description>Turn network time synchronization on or off</_description>
+ <_message>Authentication is required to control whether
+ network time synchronization shall be enabled.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ </action>
+
+</policyconfig>
diff --git a/src/timedate/org.freedesktop.timedate1.service b/src/timedate/org.freedesktop.timedate1.service
new file mode 100644
index 0000000000..875f4bec78
--- /dev/null
+++ b/src/timedate/org.freedesktop.timedate1.service
@@ -0,0 +1,12 @@
+# This file is part of systemd.
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 of the License, or
+# (at your option) any later version.
+
+[D-BUS Service]
+Name=org.freedesktop.timedate1
+Exec=/bin/false
+User=root
+SystemdService=dbus-org.freedesktop.timedate1.service
diff --git a/src/timedate/timedatectl.c b/src/timedate/timedatectl.c
new file mode 100644
index 0000000000..8d4e560b93
--- /dev/null
+++ b/src/timedate/timedatectl.c
@@ -0,0 +1,715 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdlib.h>
+#include <stdbool.h>
+#include <unistd.h>
+#include <getopt.h>
+#include <locale.h>
+#include <string.h>
+#include <sys/timex.h>
+
+#include "dbus-common.h"
+#include "util.h"
+#include "spawn-polkit-agent.h"
+#include "build.h"
+#include "hwclock.h"
+#include "strv.h"
+#include "pager.h"
+#include "time-dst.h"
+
+static bool arg_adjust_system_clock = false;
+static bool arg_no_pager = false;
+static enum transport {
+ TRANSPORT_NORMAL,
+ TRANSPORT_SSH,
+ TRANSPORT_POLKIT
+} arg_transport = TRANSPORT_NORMAL;
+static bool arg_ask_password = true;
+static const char *arg_host = NULL;
+
+static void pager_open_if_enabled(void) {
+
+ if (arg_no_pager)
+ return;
+
+ pager_open(false);
+}
+
+static void polkit_agent_open_if_enabled(void) {
+
+ /* Open the polkit agent as a child process if necessary */
+
+ if (!arg_ask_password)
+ return;
+
+ polkit_agent_open();
+}
+
+typedef struct StatusInfo {
+ const char *timezone;
+ bool local_rtc;
+ bool ntp;
+ bool can_ntp;
+} StatusInfo;
+
+static bool ntp_synced(void) {
+ struct timex txc = {};
+
+ if (adjtimex(&txc) < 0)
+ return false;
+
+ if (txc.status & STA_UNSYNC)
+ return false;
+
+ return true;
+}
+
+static const char *jump_str(int delta_minutes, char *s, size_t size) {
+ if (delta_minutes == 60)
+ return "one hour forward";
+ if (delta_minutes == -60)
+ return "one hour backwards";
+ if (delta_minutes < 0) {
+ snprintf(s, size, "%i minutes backwards", -delta_minutes);
+ return s;
+ }
+ if (delta_minutes > 0) {
+ snprintf(s, size, "%i minutes forward", delta_minutes);
+ return s;
+ }
+ return "";
+}
+
+static void print_status_info(StatusInfo *i) {
+ usec_t n;
+ char a[FORMAT_TIMESTAMP_MAX];
+ char b[FORMAT_TIMESTAMP_MAX];
+ char s[32];
+ struct tm tm;
+ time_t sec;
+ char *zc, *zn;
+ time_t t, tc, tn;
+ int dn;
+ bool is_dstc, is_dstn;
+ int r;
+
+ assert(i);
+
+ /* enforce the values of /etc/localtime */
+ if (getenv("TZ")) {
+ fprintf(stderr, "Warning: ignoring the TZ variable, reading the system's timezone setting only.\n\n");
+ unsetenv("TZ");
+ }
+
+ n = now(CLOCK_REALTIME);
+ sec = (time_t) (n / USEC_PER_SEC);
+
+ zero(tm);
+ assert_se(strftime(a, sizeof(a), "%a %Y-%m-%d %H:%M:%S %Z", localtime_r(&sec, &tm)) > 0);
+ char_array_0(a);
+ printf(" Local time: %s\n", a);
+
+ zero(tm);
+ assert_se(strftime(a, sizeof(a), "%a %Y-%m-%d %H:%M:%S UTC", gmtime_r(&sec, &tm)) > 0);
+ char_array_0(a);
+ printf(" Universal time: %s\n", a);
+
+ zero(tm);
+ r = hwclock_get_time(&tm);
+ if (r >= 0) {
+ /* Calculcate the week-day */
+ mktime(&tm);
+
+ assert_se(strftime(a, sizeof(a), "%a %Y-%m-%d %H:%M:%S", &tm) > 0);
+ char_array_0(a);
+ printf(" RTC time: %s\n", a);
+ }
+
+ zero(tm);
+ assert_se(strftime(a, sizeof(a), "%Z, %z", localtime_r(&sec, &tm)) > 0);
+ char_array_0(a);
+ printf(" Timezone: %s (%s)\n"
+ " NTP enabled: %s\n"
+ "NTP synchronized: %s\n"
+ " RTC in local TZ: %s\n",
+ strna(i->timezone),
+ a,
+ i->can_ntp ? yes_no(i->ntp) : "n/a",
+ yes_no(ntp_synced()),
+ yes_no(i->local_rtc));
+
+ r = time_get_dst(sec, "/etc/localtime",
+ &tc, &zc, &is_dstc,
+ &tn, &dn, &zn, &is_dstn);
+ if (r < 0)
+ printf(" DST active: n/a\n");
+ else {
+ printf(" DST active: %s\n", yes_no(is_dstc));
+
+ t = tc - 1;
+ zero(tm);
+ assert_se(strftime(a, sizeof(a), "%a %Y-%m-%d %H:%M:%S %Z", localtime_r(&t, &tm)) > 0);
+ char_array_0(a);
+
+ zero(tm);
+ assert_se(strftime(b, sizeof(b), "%a %Y-%m-%d %H:%M:%S %Z", localtime_r(&tc, &tm)) > 0);
+ char_array_0(b);
+ printf(" Last DST change: DST %s at\n"
+ " %s\n"
+ " %s\n",
+ is_dstc ? "began" : "ended", a, b);
+
+ t = tn - 1;
+ zero(tm);
+ assert_se(strftime(a, sizeof(a), "%a %Y-%m-%d %H:%M:%S %Z", localtime_r(&t, &tm)) > 0);
+ char_array_0(a);
+
+ zero(tm);
+ assert_se(strftime(b, sizeof(b), "%a %Y-%m-%d %H:%M:%S %Z", localtime_r(&tn, &tm)) > 0);
+ char_array_0(b);
+ printf(" Next DST change: DST %s (the clock jumps %s) at\n"
+ " %s\n"
+ " %s\n",
+ is_dstn ? "begins" : "ends", jump_str(dn, s, sizeof(s)), a, b);
+
+ free(zc);
+ free(zn);
+ }
+
+ if (i->local_rtc)
+ fputs("\n" ANSI_HIGHLIGHT_ON
+ "Warning: The RTC is configured to maintain time in the local time zone. This\n"
+ " mode is not fully supported and will create various problems with time\n"
+ " zone changes and daylight saving adjustments. If at all possible use\n"
+ " RTC in UTC, by calling 'timedatectl set-local-rtc 0'" ANSI_HIGHLIGHT_OFF ".\n", stdout);
+}
+
+static int status_property(const char *name, DBusMessageIter *iter, StatusInfo *i) {
+ assert(name);
+ assert(iter);
+
+ switch (dbus_message_iter_get_arg_type(iter)) {
+
+ case DBUS_TYPE_STRING: {
+ const char *s;
+
+ dbus_message_iter_get_basic(iter, &s);
+ if (!isempty(s)) {
+ if (streq(name, "Timezone"))
+ i->timezone = s;
+ }
+ break;
+ }
+
+ case DBUS_TYPE_BOOLEAN: {
+ dbus_bool_t b;
+
+ dbus_message_iter_get_basic(iter, &b);
+ if (streq(name, "LocalRTC"))
+ i->local_rtc = b;
+ else if (streq(name, "NTP"))
+ i->ntp = b;
+ else if (streq(name, "CanNTP"))
+ i->can_ntp = b;
+ }
+ }
+
+ return 0;
+}
+
+static int show_status(DBusConnection *bus, char **args, unsigned n) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ const char *interface = "";
+ int r;
+ DBusMessageIter iter, sub, sub2, sub3;
+ StatusInfo info = {};
+
+ assert(args);
+
+ r = bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.timedate1",
+ "/org/freedesktop/timedate1",
+ "org.freedesktop.DBus.Properties",
+ "GetAll",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &interface,
+ DBUS_TYPE_INVALID);
+ if (r < 0)
+ return r;
+
+ if (!dbus_message_iter_init(reply, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
+ dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_recurse(&iter, &sub);
+
+ while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+ const char *name;
+
+ if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_recurse(&sub, &sub2);
+
+ if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
+ log_error("Failed to parse reply.");
+ return -EIO;
+ }
+
+ dbus_message_iter_recurse(&sub2, &sub3);
+
+ r = status_property(name, &sub3, &info);
+ if (r < 0) {
+ log_error("Failed to parse reply.");
+ return r;
+ }
+
+ dbus_message_iter_next(&sub);
+ }
+
+ print_status_info(&info);
+ return 0;
+}
+
+static int set_time(DBusConnection *bus, char **args, unsigned n) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ dbus_bool_t relative = false, interactive = true;
+ usec_t t;
+ dbus_int64_t u;
+ int r;
+
+ assert(args);
+ assert(n == 2);
+
+ polkit_agent_open_if_enabled();
+
+ r = parse_timestamp(args[1], &t);
+ if (r < 0) {
+ log_error("Failed to parse time specification: %s", args[1]);
+ return r;
+ }
+
+ u = (dbus_uint64_t) t;
+
+ return bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.timedate1",
+ "/org/freedesktop/timedate1",
+ "org.freedesktop.timedate1",
+ "SetTime",
+ &reply,
+ NULL,
+ DBUS_TYPE_INT64, &u,
+ DBUS_TYPE_BOOLEAN, &relative,
+ DBUS_TYPE_BOOLEAN, &interactive,
+ DBUS_TYPE_INVALID);
+}
+
+static int set_timezone(DBusConnection *bus, char **args, unsigned n) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ dbus_bool_t interactive = true;
+
+ assert(args);
+ assert(n == 2);
+
+ polkit_agent_open_if_enabled();
+
+ return bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.timedate1",
+ "/org/freedesktop/timedate1",
+ "org.freedesktop.timedate1",
+ "SetTimezone",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &args[1],
+ DBUS_TYPE_BOOLEAN, &interactive,
+ DBUS_TYPE_INVALID);
+}
+
+static int set_local_rtc(DBusConnection *bus, char **args, unsigned n) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ dbus_bool_t interactive = true, b, q;
+ int r;
+
+ assert(args);
+ assert(n == 2);
+
+ polkit_agent_open_if_enabled();
+
+ r = parse_boolean(args[1]);
+ if (r < 0) {
+ log_error("Failed to parse local RTC setting: %s", args[1]);
+ return r;
+ }
+
+ b = r;
+ q = arg_adjust_system_clock;
+
+ return bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.timedate1",
+ "/org/freedesktop/timedate1",
+ "org.freedesktop.timedate1",
+ "SetLocalRTC",
+ &reply,
+ NULL,
+ DBUS_TYPE_BOOLEAN, &b,
+ DBUS_TYPE_BOOLEAN, &q,
+ DBUS_TYPE_BOOLEAN, &interactive,
+ DBUS_TYPE_INVALID);
+}
+
+static int set_ntp(DBusConnection *bus, char **args, unsigned n) {
+ _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+ dbus_bool_t interactive = true, b;
+ int r;
+
+ assert(args);
+ assert(n == 2);
+
+ polkit_agent_open_if_enabled();
+
+ r = parse_boolean(args[1]);
+ if (r < 0) {
+ log_error("Failed to parse NTP setting: %s", args[1]);
+ return r;
+ }
+
+ b = r;
+
+ return bus_method_call_with_reply(
+ bus,
+ "org.freedesktop.timedate1",
+ "/org/freedesktop/timedate1",
+ "org.freedesktop.timedate1",
+ "SetNTP",
+ &reply,
+ NULL,
+ DBUS_TYPE_BOOLEAN, &b,
+ DBUS_TYPE_BOOLEAN, &interactive,
+ DBUS_TYPE_INVALID);
+}
+
+static int list_timezones(DBusConnection *bus, char **args, unsigned n) {
+ _cleanup_fclose_ FILE *f = NULL;
+ _cleanup_strv_free_ char **zones = NULL;
+ size_t n_zones = 0;
+
+ assert(args);
+ assert(n == 1);
+
+ f = fopen("/usr/share/zoneinfo/zone.tab", "re");
+ if (!f) {
+ log_error("Failed to open timezone database: %m");
+ return -errno;
+ }
+
+ for (;;) {
+ char l[LINE_MAX], *p, **z, *w;
+ size_t k;
+
+ if (!fgets(l, sizeof(l), f)) {
+ if (feof(f))
+ break;
+
+ log_error("Failed to read timezone database: %m");
+ return -errno;
+ }
+
+ p = strstrip(l);
+
+ if (isempty(p) || *p == '#')
+ continue;
+
+
+ /* Skip over country code */
+ p += strcspn(p, WHITESPACE);
+ p += strspn(p, WHITESPACE);
+
+ /* Skip over coordinates */
+ p += strcspn(p, WHITESPACE);
+ p += strspn(p, WHITESPACE);
+
+ /* Found timezone name */
+ k = strcspn(p, WHITESPACE);
+ if (k <= 0)
+ continue;
+
+ w = strndup(p, k);
+ if (!w)
+ return log_oom();
+
+ z = realloc(zones, sizeof(char*) * (n_zones + 2));
+ if (!z) {
+ free(w);
+ return log_oom();
+ }
+
+ zones = z;
+ zones[n_zones++] = w;
+ }
+
+ if (zones)
+ zones[n_zones] = NULL;
+
+ pager_open_if_enabled();
+
+ strv_sort(zones);
+ strv_print(zones);
+
+ return 0;
+}
+
+static int help(void) {
+
+ printf("%s [OPTIONS...] COMMAND ...\n\n"
+ "Query or change system time and date settings.\n\n"
+ " -h --help Show this help\n"
+ " --version Show package version\n"
+ " --adjust-system-clock\n"
+ " Adjust system clock when changing local RTC mode\n"
+ " --no-pager Do not pipe output into a pager\n"
+ " --no-ask-password Do not prompt for password\n"
+ " -H --host=[USER@]HOST Operate on remote host\n\n"
+ "Commands:\n"
+ " status Show current time settings\n"
+ " set-time TIME Set system time\n"
+ " set-timezone ZONE Set system timezone\n"
+ " list-timezones Show known timezones\n"
+ " set-local-rtc BOOL Control whether RTC is in local time\n"
+ " set-ntp BOOL Control whether NTP is enabled\n",
+ program_invocation_short_name);
+
+ return 0;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+
+ enum {
+ ARG_VERSION = 0x100,
+ ARG_NO_PAGER,
+ ARG_ADJUST_SYSTEM_CLOCK,
+ ARG_NO_ASK_PASSWORD
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "version", no_argument, NULL, ARG_VERSION },
+ { "no-pager", no_argument, NULL, ARG_NO_PAGER },
+ { "host", required_argument, NULL, 'H' },
+ { "privileged", no_argument, NULL, 'P' },
+ { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
+ { "adjust-system-clock", no_argument, NULL, ARG_ADJUST_SYSTEM_CLOCK },
+ { NULL, 0, NULL, 0 }
+ };
+
+ int c;
+
+ assert(argc >= 0);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "+hH:P", options, NULL)) >= 0) {
+
+ switch (c) {
+
+ case 'h':
+ help();
+ return 0;
+
+ case ARG_VERSION:
+ puts(PACKAGE_STRING);
+ puts(SYSTEMD_FEATURES);
+ return 0;
+
+ case 'P':
+ arg_transport = TRANSPORT_POLKIT;
+ break;
+
+ case 'H':
+ arg_transport = TRANSPORT_SSH;
+ arg_host = optarg;
+ break;
+
+ case ARG_ADJUST_SYSTEM_CLOCK:
+ arg_adjust_system_clock = true;
+ break;
+
+ case ARG_NO_PAGER:
+ arg_no_pager = true;
+ break;
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ log_error("Unknown option code %c", c);
+ return -EINVAL;
+ }
+ }
+
+ return 1;
+}
+
+static int timedatectl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
+
+ static const struct {
+ const char* verb;
+ const enum {
+ MORE,
+ LESS,
+ EQUAL
+ } argc_cmp;
+ const int argc;
+ int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
+ } verbs[] = {
+ { "status", LESS, 1, show_status },
+ { "set-time", EQUAL, 2, set_time },
+ { "set-timezone", EQUAL, 2, set_timezone },
+ { "list-timezones", EQUAL, 1, list_timezones },
+ { "set-local-rtc", EQUAL, 2, set_local_rtc },
+ { "set-ntp", EQUAL, 2, set_ntp, },
+ };
+
+ int left;
+ unsigned i;
+
+ assert(argc >= 0);
+ assert(argv);
+ assert(error);
+
+ left = argc - optind;
+
+ if (left <= 0)
+ /* Special rule: no arguments means "status" */
+ i = 0;
+ else {
+ if (streq(argv[optind], "help")) {
+ help();
+ return 0;
+ }
+
+ for (i = 0; i < ELEMENTSOF(verbs); i++)
+ if (streq(argv[optind], verbs[i].verb))
+ break;
+
+ if (i >= ELEMENTSOF(verbs)) {
+ log_error("Unknown operation %s", argv[optind]);
+ return -EINVAL;
+ }
+ }
+
+ switch (verbs[i].argc_cmp) {
+
+ case EQUAL:
+ if (left != verbs[i].argc) {
+ log_error("Invalid number of arguments.");
+ return -EINVAL;
+ }
+
+ break;
+
+ case MORE:
+ if (left < verbs[i].argc) {
+ log_error("Too few arguments.");
+ return -EINVAL;
+ }
+
+ break;
+
+ case LESS:
+ if (left > verbs[i].argc) {
+ log_error("Too many arguments.");
+ return -EINVAL;
+ }
+
+ break;
+
+ default:
+ assert_not_reached("Unknown comparison operator.");
+ }
+
+ if (!bus) {
+ log_error("Failed to get D-Bus connection: %s", error->message);
+ return -EIO;
+ }
+
+ return verbs[i].dispatch(bus, argv + optind, left);
+}
+
+int main(int argc, char *argv[]) {
+ int r, retval = EXIT_FAILURE;
+ DBusConnection *bus = NULL;
+ DBusError error;
+
+ dbus_error_init(&error);
+
+ setlocale(LC_ALL, "");
+ log_parse_environment();
+ log_open();
+
+ r = parse_argv(argc, argv);
+ if (r < 0)
+ goto finish;
+ else if (r == 0) {
+ retval = EXIT_SUCCESS;
+ goto finish;
+ }
+
+ if (arg_transport == TRANSPORT_NORMAL)
+ bus = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error);
+ else if (arg_transport == TRANSPORT_POLKIT)
+ bus_connect_system_polkit(&bus, &error);
+ else if (arg_transport == TRANSPORT_SSH)
+ bus_connect_system_ssh(NULL, arg_host, &bus, &error);
+ else
+ assert_not_reached("Uh, invalid transport...");
+
+ r = timedatectl_main(bus, argc, argv, &error);
+ retval = r < 0 ? EXIT_FAILURE : r;
+
+finish:
+ if (bus) {
+ dbus_connection_flush(bus);
+ dbus_connection_close(bus);
+ dbus_connection_unref(bus);
+ }
+
+ dbus_error_free(&error);
+ dbus_shutdown();
+
+ pager_close();
+
+ return retval;
+}
diff --git a/src/timedate/timedated.c b/src/timedate/timedated.c
new file mode 100644
index 0000000000..cdb6e5b16c
--- /dev/null
+++ b/src/timedate/timedated.c
@@ -0,0 +1,1026 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <dbus/dbus.h>
+
+#include <errno.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "systemd/sd-id128.h"
+#include "systemd/sd-messages.h"
+#include "util.h"
+#include "strv.h"
+#include "dbus-common.h"
+#include "polkit.h"
+#include "def.h"
+#include "hwclock.h"
+#include "conf-files.h"
+#include "path-util.h"
+#include "fileio-label.h"
+#include "label.h"
+
+#define NULL_ADJTIME_UTC "0.0 0 0\n0\nUTC\n"
+#define NULL_ADJTIME_LOCAL "0.0 0 0\n0\nLOCAL\n"
+
+#define INTERFACE \
+ " <interface name=\"org.freedesktop.timedate1\">\n" \
+ " <property name=\"Timezone\" type=\"s\" access=\"read\"/>\n" \
+ " <property name=\"LocalRTC\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"CanNTP\" type=\"b\" access=\"read\"/>\n" \
+ " <property name=\"NTP\" type=\"b\" access=\"read\"/>\n" \
+ " <method name=\"SetTime\">\n" \
+ " <arg name=\"usec_utc\" type=\"x\" direction=\"in\"/>\n" \
+ " <arg name=\"relative\" type=\"b\" direction=\"in\"/>\n" \
+ " <arg name=\"user_interaction\" type=\"b\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"SetTimezone\">\n" \
+ " <arg name=\"timezone\" type=\"s\" direction=\"in\"/>\n" \
+ " <arg name=\"user_interaction\" type=\"b\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"SetLocalRTC\">\n" \
+ " <arg name=\"local_rtc\" type=\"b\" direction=\"in\"/>\n" \
+ " <arg name=\"fix_system\" type=\"b\" direction=\"in\"/>\n" \
+ " <arg name=\"user_interaction\" type=\"b\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " <method name=\"SetNTP\">\n" \
+ " <arg name=\"use_ntp\" type=\"b\" direction=\"in\"/>\n" \
+ " <arg name=\"user_interaction\" type=\"b\" direction=\"in\"/>\n" \
+ " </method>\n" \
+ " </interface>\n"
+
+#define INTROSPECTION \
+ DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE \
+ "<node>\n" \
+ INTERFACE \
+ BUS_PROPERTIES_INTERFACE \
+ BUS_INTROSPECTABLE_INTERFACE \
+ BUS_PEER_INTERFACE \
+ "</node>\n"
+
+#define INTERFACES_LIST \
+ BUS_GENERIC_INTERFACES_LIST \
+ "org.freedesktop.timedate1\0"
+
+const char timedate_interface[] _introspect_("timedate1") = INTERFACE;
+
+typedef struct TZ {
+ char *zone;
+ bool local_rtc;
+ int can_ntp;
+ int use_ntp;
+} TZ;
+
+static TZ tz = {
+ .zone = NULL,
+ .local_rtc = false,
+ .can_ntp = -1,
+ .use_ntp = -1,
+};
+
+static usec_t remain_until;
+
+static void free_data(void) {
+ free(tz.zone);
+ tz.zone = NULL;
+
+ tz.local_rtc = false;
+}
+
+static bool valid_timezone(const char *name) {
+ const char *p;
+ char *t;
+ bool slash = false;
+ int r;
+ struct stat st;
+
+ assert(name);
+
+ if (*name == '/' || *name == 0)
+ return false;
+
+ for (p = name; *p; p++) {
+ if (!(*p >= '0' && *p <= '9') &&
+ !(*p >= 'a' && *p <= 'z') &&
+ !(*p >= 'A' && *p <= 'Z') &&
+ !(*p == '-' || *p == '_' || *p == '+' || *p == '/'))
+ return false;
+
+ if (*p == '/') {
+
+ if (slash)
+ return false;
+
+ slash = true;
+ } else
+ slash = false;
+ }
+
+ if (slash)
+ return false;
+
+ t = strappend("/usr/share/zoneinfo/", name);
+ if (!t)
+ return false;
+
+ r = stat(t, &st);
+ free(t);
+
+ if (r < 0)
+ return false;
+
+ if (!S_ISREG(st.st_mode))
+ return false;
+
+ return true;
+}
+
+static int read_data(void) {
+ int r;
+ _cleanup_free_ char *t = NULL;
+
+ free_data();
+
+ r = readlink_malloc("/etc/localtime", &t);
+ if (r < 0) {
+ if (r == -EINVAL)
+ log_warning("/etc/localtime should be a symbolic link to a timezone data file in /usr/share/zoneinfo/.");
+ else
+ log_warning("Failed to get target of /etc/localtime: %s", strerror(-r));
+ } else {
+ const char *e;
+
+ e = path_startswith(t, "/usr/share/zoneinfo/");
+ if (!e)
+ e = path_startswith(t, "../usr/share/zoneinfo/");
+
+ if (!e)
+ log_warning("/etc/localtime should be a symbolic link to a timezone data file in /usr/share/zoneinfo/.");
+ else {
+ tz.zone = strdup(e);
+ if (!tz.zone)
+ return log_oom();
+
+ goto have_timezone;
+ }
+ }
+
+have_timezone:
+ if (isempty(tz.zone)) {
+ free(tz.zone);
+ tz.zone = NULL;
+ }
+
+ tz.local_rtc = hwclock_is_localtime() > 0;
+
+ return 0;
+}
+
+static int write_data_timezone(void) {
+ int r = 0;
+ _cleanup_free_ char *p = NULL;
+
+ if (!tz.zone) {
+ if (unlink("/etc/localtime") < 0 && errno != ENOENT)
+ r = -errno;
+
+ return r;
+ }
+
+ p = strappend("../usr/share/zoneinfo/", tz.zone);
+ if (!p)
+ return log_oom();
+
+ r = symlink_atomic(p, "/etc/localtime");
+ if (r < 0)
+ return r;
+
+ return 0;
+}
+
+static int write_data_local_rtc(void) {
+ int r;
+ _cleanup_free_ char *s = NULL, *w = NULL;
+
+ r = read_full_file("/etc/adjtime", &s, NULL);
+ if (r < 0) {
+ if (r != -ENOENT)
+ return r;
+
+ if (!tz.local_rtc)
+ return 0;
+
+ w = strdup(NULL_ADJTIME_LOCAL);
+ if (!w)
+ return -ENOMEM;
+ } else {
+ char *p, *e;
+ size_t a, b;
+
+ p = strchr(s, '\n');
+ if (!p)
+ return -EIO;
+
+ p = strchr(p+1, '\n');
+ if (!p)
+ return -EIO;
+
+ p++;
+ e = strchr(p, '\n');
+ if (!e)
+ return -EIO;
+
+ a = p - s;
+ b = strlen(e);
+
+ w = new(char, a + (tz.local_rtc ? 5 : 3) + b + 1);
+ if (!w)
+ return -ENOMEM;
+
+ *(char*) mempcpy(stpcpy(mempcpy(w, s, a), tz.local_rtc ? "LOCAL" : "UTC"), e, b) = 0;
+
+ if (streq(w, NULL_ADJTIME_UTC)) {
+ if (unlink("/etc/adjtime") < 0)
+ if (errno != ENOENT)
+ return -errno;
+
+ return 0;
+ }
+ }
+ label_init("/etc");
+ return write_string_file_atomic_label("/etc/adjtime", w);
+}
+
+static char** get_ntp_services(void) {
+ _cleanup_strv_free_ char **r = NULL, **files;
+ char **i;
+ int k;
+
+ k = conf_files_list(&files, ".list", NULL,
+ "/etc/systemd/ntp-units.d",
+ "/run/systemd/ntp-units.d",
+ "/usr/local/lib/systemd/ntp-units.d",
+ "/usr/lib/systemd/ntp-units.d",
+ NULL);
+ if (k < 0)
+ return NULL;
+
+ STRV_FOREACH(i, files) {
+ _cleanup_fclose_ FILE *f;
+
+ f = fopen(*i, "re");
+ if (!f)
+ continue;
+
+ for (;;) {
+ char line[PATH_MAX], *l;
+
+ if (!fgets(line, sizeof(line), f)) {
+
+ if (ferror(f))
+ log_error("Failed to read NTP units file: %m");
+
+ break;
+ }
+
+ l = strstrip(line);
+ if (l[0] == 0 || l[0] == '#')
+ continue;
+
+ if (strv_extend(&r, l) < 0) {
+ log_oom();
+ return NULL;
+ }
+ }
+ }
+
+ i = r;
+ r = NULL; /* avoid cleanup */
+
+ return strv_uniq(i);
+}
+
+static int read_ntp(DBusConnection *bus) {
+ DBusMessage *m = NULL, *reply = NULL;
+ DBusError error;
+ int r;
+ char **i, **l;
+
+ assert(bus);
+
+ dbus_error_init(&error);
+
+ l = get_ntp_services();
+ STRV_FOREACH(i, l) {
+ const char *s;
+
+ if (m)
+ dbus_message_unref(m);
+ m = dbus_message_new_method_call(
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "GetUnitFileState");
+ if (!m) {
+ r = log_oom();
+ goto finish;
+ }
+
+ if (!dbus_message_append_args(m,
+ DBUS_TYPE_STRING, i,
+ DBUS_TYPE_INVALID)) {
+ r = log_oom();
+ goto finish;
+ }
+
+ reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
+ if (!reply) {
+ if (streq(error.name, "org.freedesktop.DBus.Error.FileNotFound")) {
+ /* This implementation does not exist, try next one */
+ dbus_error_free(&error);
+ continue;
+ }
+
+ log_error("Failed to issue method call: %s", bus_error_message(&error));
+ r = -EIO;
+ goto finish;
+ }
+
+ if (!dbus_message_get_args(reply, &error,
+ DBUS_TYPE_STRING, &s,
+ DBUS_TYPE_INVALID)) {
+ log_error("Failed to parse reply: %s", bus_error_message(&error));
+ r = -EIO;
+ goto finish;
+ }
+
+ tz.can_ntp = 1;
+ tz.use_ntp =
+ streq(s, "enabled") ||
+ streq(s, "enabled-runtime");
+ r = 0;
+ goto finish;
+ }
+
+ /* NTP is not installed. */
+ tz.can_ntp = 0;
+ tz.use_ntp = 0;
+ r = 0;
+
+finish:
+ if (m)
+ dbus_message_unref(m);
+
+ if (reply)
+ dbus_message_unref(reply);
+
+ strv_free(l);
+
+ dbus_error_free(&error);
+
+ return r;
+}
+
+static int start_ntp(DBusConnection *bus, DBusError *error) {
+ DBusMessage *m = NULL, *reply = NULL;
+ const char *mode = "replace";
+ char **i, **l;
+ int r;
+
+ assert(bus);
+ assert(error);
+
+ l = get_ntp_services();
+ STRV_FOREACH(i, l) {
+ if (m)
+ dbus_message_unref(m);
+ m = dbus_message_new_method_call(
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ tz.use_ntp ? "StartUnit" : "StopUnit");
+ if (!m) {
+ log_error("Could not allocate message.");
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ if (!dbus_message_append_args(m,
+ DBUS_TYPE_STRING, i,
+ DBUS_TYPE_STRING, &mode,
+ DBUS_TYPE_INVALID)) {
+ log_error("Could not append arguments to message.");
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error);
+ if (!reply) {
+ if (streq(error->name, "org.freedesktop.DBus.Error.FileNotFound") ||
+ streq(error->name, "org.freedesktop.systemd1.LoadFailed") ||
+ streq(error->name, "org.freedesktop.systemd1.NoSuchUnit")) {
+ /* This implementation does not exist, try next one */
+ dbus_error_free(error);
+ continue;
+ }
+
+ log_error("Failed to issue method call: %s", bus_error_message(error));
+ r = -EIO;
+ goto finish;
+ }
+
+ r = 0;
+ goto finish;
+ }
+
+ /* No implementaiton available... */
+ r = -ENOENT;
+
+finish:
+ if (m)
+ dbus_message_unref(m);
+
+ if (reply)
+ dbus_message_unref(reply);
+
+ strv_free(l);
+
+ return r;
+}
+
+static int enable_ntp(DBusConnection *bus, DBusError *error) {
+ DBusMessage *m = NULL, *reply = NULL;
+ int r;
+ DBusMessageIter iter;
+ dbus_bool_t f = FALSE, t = TRUE;
+ char **i, **l;
+
+ assert(bus);
+ assert(error);
+
+ l = get_ntp_services();
+ STRV_FOREACH(i, l) {
+ char* k[2];
+
+ if (m)
+ dbus_message_unref(m);
+ m = dbus_message_new_method_call(
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ tz.use_ntp ? "EnableUnitFiles" : "DisableUnitFiles");
+ if (!m) {
+ log_error("Could not allocate message.");
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ dbus_message_iter_init_append(m, &iter);
+
+ k[0] = *i;
+ k[1] = NULL;
+
+ r = bus_append_strv_iter(&iter, k);
+ if (r < 0) {
+ log_error("Failed to append unit files.");
+ goto finish;
+ }
+
+ /* send runtime bool */
+ if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &f)) {
+ log_error("Failed to append runtime boolean.");
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ if (tz.use_ntp) {
+ /* send force bool */
+ if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &t)) {
+ log_error("Failed to append force boolean.");
+ r = -ENOMEM;
+ goto finish;
+ }
+ }
+
+ reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error);
+ if (!reply) {
+ if (streq(error->name, "org.freedesktop.DBus.Error.FileNotFound")) {
+ /* This implementation does not exist, try next one */
+ dbus_error_free(error);
+ continue;
+ }
+
+ log_error("Failed to issue method call: %s", bus_error_message(error));
+ r = -EIO;
+ goto finish;
+ }
+
+ dbus_message_unref(m);
+ m = dbus_message_new_method_call(
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "Reload");
+ if (!m) {
+ log_error("Could not allocate message.");
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ dbus_message_unref(reply);
+ reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error);
+ if (!reply) {
+ log_error("Failed to issue method call: %s", bus_error_message(error));
+ r = -EIO;
+ goto finish;
+ }
+
+ r = 0;
+ goto finish;
+ }
+
+ r = -ENOENT;
+
+finish:
+ if (m)
+ dbus_message_unref(m);
+
+ if (reply)
+ dbus_message_unref(reply);
+
+ strv_free(l);
+
+ return r;
+}
+
+static int property_append_can_ntp(DBusMessageIter *i, const char *property, void *data) {
+ dbus_bool_t db;
+
+ assert(i);
+ assert(property);
+
+ db = tz.can_ntp > 0;
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_BOOLEAN, &db))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static int property_append_ntp(DBusMessageIter *i, const char *property, void *data) {
+ dbus_bool_t db;
+
+ assert(i);
+ assert(property);
+
+ db = tz.use_ntp > 0;
+
+ if (!dbus_message_iter_append_basic(i, DBUS_TYPE_BOOLEAN, &db))
+ return -ENOMEM;
+
+ return 0;
+}
+
+static const BusProperty bus_timedate_properties[] = {
+ { "Timezone", bus_property_append_string, "s", offsetof(TZ, zone), true },
+ { "LocalRTC", bus_property_append_bool, "b", offsetof(TZ, local_rtc) },
+ { "CanNTP", property_append_can_ntp, "b", offsetof(TZ, can_ntp) },
+ { "NTP", property_append_ntp, "b", offsetof(TZ, use_ntp) },
+ { NULL, }
+};
+
+static const BusBoundProperties bps[] = {
+ { "org.freedesktop.timedate1", bus_timedate_properties, &tz },
+ { NULL, }
+};
+
+static DBusHandlerResult timedate_message_handler(
+ DBusConnection *connection,
+ DBusMessage *message,
+ void *userdata) {
+
+ DBusMessage *reply = NULL, *changed = NULL;
+ DBusError error;
+ int r;
+
+ assert(connection);
+ assert(message);
+
+ dbus_error_init(&error);
+
+ if (dbus_message_is_method_call(message, "org.freedesktop.timedate1", "SetTimezone")) {
+ const char *z;
+ dbus_bool_t interactive;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_STRING, &z,
+ DBUS_TYPE_BOOLEAN, &interactive,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ if (!valid_timezone(z))
+ return bus_send_error_reply(connection, message, NULL, -EINVAL);
+
+ if (!streq_ptr(z, tz.zone)) {
+ char *t;
+
+ r = verify_polkit(connection, message, "org.freedesktop.timedate1.set-timezone", interactive, NULL, &error);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ t = strdup(z);
+ if (!t)
+ goto oom;
+
+ free(tz.zone);
+ tz.zone = t;
+
+ /* 1. Write new configuration file */
+ r = write_data_timezone();
+ if (r < 0) {
+ log_error("Failed to set timezone: %s", strerror(-r));
+ return bus_send_error_reply(connection, message, NULL, r);
+ }
+
+ /* 2. Tell the kernel our time zone */
+ hwclock_set_timezone(NULL);
+
+ if (tz.local_rtc) {
+ struct timespec ts;
+ struct tm *tm;
+
+ /* 3. Sync RTC from system clock, with the new delta */
+ assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
+ assert_se(tm = localtime(&ts.tv_sec));
+ hwclock_set_time(tm);
+ }
+
+ log_struct(LOG_INFO,
+ MESSAGE_ID(SD_MESSAGE_TIMEZONE_CHANGE),
+ "TIMEZONE=%s", tz.zone,
+ "MESSAGE=Changed timezone to '%s'.", tz.zone,
+ NULL);
+
+ changed = bus_properties_changed_new(
+ "/org/freedesktop/timedate1",
+ "org.freedesktop.timedate1",
+ "Timezone\0");
+ if (!changed)
+ goto oom;
+ }
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.timedate1", "SetLocalRTC")) {
+ dbus_bool_t lrtc;
+ dbus_bool_t fix_system;
+ dbus_bool_t interactive;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_BOOLEAN, &lrtc,
+ DBUS_TYPE_BOOLEAN, &fix_system,
+ DBUS_TYPE_BOOLEAN, &interactive,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ if (lrtc != tz.local_rtc) {
+ struct timespec ts;
+
+ r = verify_polkit(connection, message, "org.freedesktop.timedate1.set-local-rtc", interactive, NULL, &error);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ tz.local_rtc = lrtc;
+
+ /* 1. Write new configuration file */
+ r = write_data_local_rtc();
+ if (r < 0) {
+ log_error("Failed to set RTC to local/UTC: %s", strerror(-r));
+ return bus_send_error_reply(connection, message, NULL, r);
+ }
+
+ /* 2. Tell the kernel our time zone */
+ hwclock_set_timezone(NULL);
+
+ /* 3. Synchronize clocks */
+ assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
+
+ if (fix_system) {
+ struct tm tm;
+
+ /* Sync system clock from RTC; first,
+ * initialize the timezone fields of
+ * struct tm. */
+ if (tz.local_rtc)
+ tm = *localtime(&ts.tv_sec);
+ else
+ tm = *gmtime(&ts.tv_sec);
+
+ /* Override the main fields of
+ * struct tm, but not the timezone
+ * fields */
+ if (hwclock_get_time(&tm) >= 0) {
+
+ /* And set the system clock
+ * with this */
+ if (tz.local_rtc)
+ ts.tv_sec = mktime(&tm);
+ else
+ ts.tv_sec = timegm(&tm);
+
+ clock_settime(CLOCK_REALTIME, &ts);
+ }
+
+ } else {
+ struct tm *tm;
+
+ /* Sync RTC from system clock */
+ if (tz.local_rtc)
+ tm = localtime(&ts.tv_sec);
+ else
+ tm = gmtime(&ts.tv_sec);
+
+ hwclock_set_time(tm);
+ }
+
+ log_info("RTC configured to %s time.", tz.local_rtc ? "local" : "UTC");
+
+ changed = bus_properties_changed_new(
+ "/org/freedesktop/timedate1",
+ "org.freedesktop.timedate1",
+ "LocalRTC\0");
+ if (!changed)
+ goto oom;
+ }
+
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.timedate1", "SetTime")) {
+ int64_t utc;
+ dbus_bool_t relative;
+ dbus_bool_t interactive;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_INT64, &utc,
+ DBUS_TYPE_BOOLEAN, &relative,
+ DBUS_TYPE_BOOLEAN, &interactive,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ if (!relative && utc <= 0)
+ return bus_send_error_reply(connection, message, NULL, -EINVAL);
+
+ if (!relative || utc != 0) {
+ struct timespec ts;
+ struct tm* tm;
+
+ if (relative) {
+ usec_t n, x;
+
+ n = now(CLOCK_REALTIME);
+ x = n + utc;
+
+ if ((utc > 0 && x < n) ||
+ (utc < 0 && x > n))
+ return bus_send_error_reply(connection, message, NULL, -EOVERFLOW);
+
+ timespec_store(&ts, x);
+ } else
+ timespec_store(&ts, (usec_t) utc);
+
+ r = verify_polkit(connection, message, "org.freedesktop.timedate1.set-time", interactive, NULL, &error);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ /* Set system clock */
+ if (clock_settime(CLOCK_REALTIME, &ts) < 0) {
+ log_error("Failed to set local time: %m");
+ return bus_send_error_reply(connection, message, NULL, -errno);
+ }
+
+ /* Sync down to RTC */
+ if (tz.local_rtc)
+ tm = localtime(&ts.tv_sec);
+ else
+ tm = gmtime(&ts.tv_sec);
+
+ hwclock_set_time(tm);
+
+ log_struct(LOG_INFO,
+ MESSAGE_ID(SD_MESSAGE_TIME_CHANGE),
+ "REALTIME=%llu", (unsigned long long) timespec_load(&ts),
+ "MESSAGE=Changed local time to %s", ctime(&ts.tv_sec),
+ NULL);
+ }
+ } else if (dbus_message_is_method_call(message, "org.freedesktop.timedate1", "SetNTP")) {
+ dbus_bool_t ntp;
+ dbus_bool_t interactive;
+
+ if (!dbus_message_get_args(
+ message,
+ &error,
+ DBUS_TYPE_BOOLEAN, &ntp,
+ DBUS_TYPE_BOOLEAN, &interactive,
+ DBUS_TYPE_INVALID))
+ return bus_send_error_reply(connection, message, &error, -EINVAL);
+
+ if (ntp != !!tz.use_ntp) {
+
+ r = verify_polkit(connection, message, "org.freedesktop.timedate1.set-ntp", interactive, NULL, &error);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ tz.use_ntp = !!ntp;
+
+ r = enable_ntp(connection, &error);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ r = start_ntp(connection, &error);
+ if (r < 0)
+ return bus_send_error_reply(connection, message, &error, r);
+
+ log_info("Set NTP to %s", tz.use_ntp ? "enabled" : "disabled");
+
+ changed = bus_properties_changed_new(
+ "/org/freedesktop/timedate1",
+ "org.freedesktop.timedate1",
+ "NTP\0");
+ if (!changed)
+ goto oom;
+ }
+
+ } else
+ return bus_default_message_handler(connection, message, INTROSPECTION, INTERFACES_LIST, bps);
+
+ if (!(reply = dbus_message_new_method_return(message)))
+ goto oom;
+
+ if (!bus_maybe_send_reply(connection, message, reply))
+ goto oom;
+
+ dbus_message_unref(reply);
+ reply = NULL;
+
+ if (changed) {
+
+ if (!dbus_connection_send(connection, changed, NULL))
+ goto oom;
+
+ dbus_message_unref(changed);
+ }
+
+ return DBUS_HANDLER_RESULT_HANDLED;
+
+oom:
+ if (reply)
+ dbus_message_unref(reply);
+
+ if (changed)
+ dbus_message_unref(changed);
+
+ dbus_error_free(&error);
+
+ return DBUS_HANDLER_RESULT_NEED_MEMORY;
+}
+
+static int connect_bus(DBusConnection **_bus) {
+ static const DBusObjectPathVTable timedate_vtable = {
+ .message_function = timedate_message_handler
+ };
+ DBusError error;
+ DBusConnection *bus = NULL;
+ int r;
+
+ assert(_bus);
+
+ dbus_error_init(&error);
+
+ bus = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error);
+ if (!bus) {
+ log_error("Failed to get system D-Bus connection: %s", bus_error_message(&error));
+ r = -ECONNREFUSED;
+ goto fail2;
+ }
+
+ dbus_connection_set_exit_on_disconnect(bus, FALSE);
+
+ if (!dbus_connection_register_object_path(bus, "/org/freedesktop/timedate1", &timedate_vtable, NULL) ||
+ !dbus_connection_add_filter(bus, bus_exit_idle_filter, &remain_until, NULL)) {
+ r = log_oom();
+ goto fail;
+ }
+
+ r = dbus_bus_request_name(bus, "org.freedesktop.timedate1", DBUS_NAME_FLAG_DO_NOT_QUEUE, &error);
+ if (dbus_error_is_set(&error)) {
+ log_error("Failed to register name on bus: %s", bus_error_message(&error));
+ r = -EEXIST;
+ goto fail;
+ }
+
+ if (r != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) {
+ log_error("Failed to acquire name.");
+ r = -EEXIST;
+ goto fail;
+ }
+
+ if (_bus)
+ *_bus = bus;
+
+ return 0;
+
+fail:
+ dbus_connection_close(bus);
+ dbus_connection_unref(bus);
+fail2:
+ dbus_error_free(&error);
+
+ return r;
+}
+
+int main(int argc, char *argv[]) {
+ int r;
+ DBusConnection *bus = NULL;
+ bool exiting = false;
+
+ log_set_target(LOG_TARGET_AUTO);
+ log_parse_environment();
+ log_open();
+
+ umask(0022);
+
+ if (argc == 2 && streq(argv[1], "--introspect")) {
+ fputs(DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE
+ "<node>\n", stdout);
+ fputs(timedate_interface, stdout);
+ fputs("</node>\n", stdout);
+ return 0;
+ }
+
+ if (argc != 1) {
+ log_error("This program takes no arguments.");
+ r = -EINVAL;
+ goto finish;
+ }
+
+ r = read_data();
+ if (r < 0) {
+ log_error("Failed to read timezone data: %s", strerror(-r));
+ goto finish;
+ }
+
+ r = connect_bus(&bus);
+ if (r < 0)
+ goto finish;
+
+ r = read_ntp(bus);
+ if (r < 0) {
+ log_error("Failed to determine whether NTP is enabled: %s", strerror(-r));
+ goto finish;
+ }
+
+ remain_until = now(CLOCK_MONOTONIC) + DEFAULT_EXIT_USEC;
+ for (;;) {
+
+ if (!dbus_connection_read_write_dispatch(bus, exiting ? -1 : (int) (DEFAULT_EXIT_USEC/USEC_PER_MSEC)))
+ break;
+
+ if (!exiting && remain_until < now(CLOCK_MONOTONIC)) {
+ exiting = true;
+ bus_async_unregister_and_exit(bus, "org.freedesktop.timedated1");
+ }
+ }
+
+ r = 0;
+
+finish:
+ free_data();
+
+ if (bus) {
+ dbus_connection_flush(bus);
+ dbus_connection_close(bus);
+ dbus_connection_unref(bus);
+ }
+
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/src/timestamp/timestamp.c b/src/timestamp/timestamp.c
new file mode 100644
index 0000000000..1152f1b52e
--- /dev/null
+++ b/src/timestamp/timestamp.c
@@ -0,0 +1,39 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+
+#include "util.h"
+
+int main(int argc, char *argv[]) {
+ struct dual_timestamp t;
+
+ /* This is mostly useful for stuff like init ram disk scripts
+ * which want to take a proper timestamp to do minimal bootup
+ * profiling. */
+
+ dual_timestamp_get(&t);
+ printf("%llu %llu\n",
+ (unsigned long long) t.realtime,
+ (unsigned long long) t.monotonic);
+
+ return 0;
+}
diff --git a/src/tmpfiles/tmpfiles.c b/src/tmpfiles/tmpfiles.c
new file mode 100644
index 0000000000..f4885ec942
--- /dev/null
+++ b/src/tmpfiles/tmpfiles.c
@@ -0,0 +1,1425 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering, Kay Sievers
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <unistd.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <limits.h>
+#include <dirent.h>
+#include <grp.h>
+#include <pwd.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <getopt.h>
+#include <stdbool.h>
+#include <time.h>
+#include <sys/types.h>
+#include <sys/param.h>
+#include <glob.h>
+#include <fnmatch.h>
+#include <sys/capability.h>
+
+#include "log.h"
+#include "util.h"
+#include "macro.h"
+#include "missing.h"
+#include "mkdir.h"
+#include "path-util.h"
+#include "strv.h"
+#include "label.h"
+#include "set.h"
+#include "conf-files.h"
+#include "capability.h"
+
+/* This reads all files listed in /etc/tmpfiles.d/?*.conf and creates
+ * them in the file system. This is intended to be used to create
+ * properly owned directories beneath /tmp, /var/tmp, /run, which are
+ * volatile and hence need to be recreated on bootup. */
+
+typedef enum ItemType {
+ /* These ones take file names */
+ CREATE_FILE = 'f',
+ TRUNCATE_FILE = 'F',
+ WRITE_FILE = 'w',
+ CREATE_DIRECTORY = 'd',
+ TRUNCATE_DIRECTORY = 'D',
+ CREATE_FIFO = 'p',
+ CREATE_SYMLINK = 'L',
+ CREATE_CHAR_DEVICE = 'c',
+ CREATE_BLOCK_DEVICE = 'b',
+
+ /* These ones take globs */
+ IGNORE_PATH = 'x',
+ IGNORE_DIRECTORY_PATH = 'X',
+ REMOVE_PATH = 'r',
+ RECURSIVE_REMOVE_PATH = 'R',
+ RELABEL_PATH = 'z',
+ RECURSIVE_RELABEL_PATH = 'Z'
+} ItemType;
+
+typedef struct Item {
+ ItemType type;
+
+ char *path;
+ char *argument;
+ uid_t uid;
+ gid_t gid;
+ mode_t mode;
+ usec_t age;
+
+ dev_t major_minor;
+
+ bool uid_set:1;
+ bool gid_set:1;
+ bool mode_set:1;
+ bool age_set:1;
+
+ bool keep_first_level:1;
+} Item;
+
+static Hashmap *items = NULL, *globs = NULL;
+static Set *unix_sockets = NULL;
+
+static bool arg_create = false;
+static bool arg_clean = false;
+static bool arg_remove = false;
+
+static const char *arg_prefix = NULL;
+
+static const char conf_file_dirs[] =
+ "/etc/tmpfiles.d\0"
+ "/run/tmpfiles.d\0"
+ "/usr/local/lib/tmpfiles.d\0"
+ "/usr/lib/tmpfiles.d\0"
+#ifdef HAVE_SPLIT_USR
+ "/lib/tmpfiles.d\0"
+#endif
+ ;
+
+#define MAX_DEPTH 256
+
+static bool needs_glob(ItemType t) {
+ return t == IGNORE_PATH || t == IGNORE_DIRECTORY_PATH || t == REMOVE_PATH || t == RECURSIVE_REMOVE_PATH || t == RELABEL_PATH || t == RECURSIVE_RELABEL_PATH;
+}
+
+static struct Item* find_glob(Hashmap *h, const char *match) {
+ Item *j;
+ Iterator i;
+
+ HASHMAP_FOREACH(j, h, i)
+ if (fnmatch(j->path, match, FNM_PATHNAME|FNM_PERIOD) == 0)
+ return j;
+
+ return NULL;
+}
+
+static void load_unix_sockets(void) {
+ _cleanup_fclose_ FILE *f = NULL;
+ char line[LINE_MAX];
+
+ if (unix_sockets)
+ return;
+
+ /* We maintain a cache of the sockets we found in
+ * /proc/net/unix to speed things up a little. */
+
+ unix_sockets = set_new(string_hash_func, string_compare_func);
+ if (!unix_sockets)
+ return;
+
+ f = fopen("/proc/net/unix", "re");
+ if (!f)
+ return;
+
+ /* Skip header */
+ if (!fgets(line, sizeof(line), f))
+ goto fail;
+
+ for (;;) {
+ char *p, *s;
+ int k;
+
+ if (!fgets(line, sizeof(line), f))
+ break;
+
+ truncate_nl(line);
+
+ p = strchr(line, ':');
+ if (!p)
+ continue;
+
+ if (strlen(p) < 37)
+ continue;
+
+ p += 37;
+ p += strspn(p, WHITESPACE);
+ p += strcspn(p, WHITESPACE); /* skip one more word */
+ p += strspn(p, WHITESPACE);
+
+ if (*p != '/')
+ continue;
+
+ s = strdup(p);
+ if (!s)
+ goto fail;
+
+ path_kill_slashes(s);
+
+ k = set_consume(unix_sockets, s);
+ if (k < 0 && k != -EEXIST)
+ goto fail;
+ }
+
+ return;
+
+fail:
+ set_free_free(unix_sockets);
+ unix_sockets = NULL;
+}
+
+static bool unix_socket_alive(const char *fn) {
+ assert(fn);
+
+ load_unix_sockets();
+
+ if (unix_sockets)
+ return !!set_get(unix_sockets, (char*) fn);
+
+ /* We don't know, so assume yes */
+ return true;
+}
+
+static int dir_is_mount_point(DIR *d, const char *subdir) {
+ struct file_handle *h;
+ int mount_id_parent, mount_id;
+ int r_p, r;
+
+ h = alloca(MAX_HANDLE_SZ);
+
+ h->handle_bytes = MAX_HANDLE_SZ;
+ r_p = name_to_handle_at(dirfd(d), ".", h, &mount_id_parent, 0);
+ if (r_p < 0)
+ r_p = -errno;
+
+ h->handle_bytes = MAX_HANDLE_SZ;
+ r = name_to_handle_at(dirfd(d), subdir, h, &mount_id, 0);
+ if (r < 0)
+ r = -errno;
+
+ /* got no handle; make no assumptions, return error */
+ if (r_p < 0 && r < 0)
+ return r_p;
+
+ /* got both handles; if they differ, it is a mount point */
+ if (r_p >= 0 && r >= 0)
+ return mount_id_parent != mount_id;
+
+ /* got only one handle; assume different mount points if one
+ * of both queries was not supported by the filesystem */
+ if (r_p == -ENOSYS || r_p == -ENOTSUP || r == -ENOSYS || r == -ENOTSUP)
+ return true;
+
+ /* return error */
+ if (r_p < 0)
+ return r_p;
+ return r;
+}
+
+static int dir_cleanup(
+ Item *i,
+ const char *p,
+ DIR *d,
+ const struct stat *ds,
+ usec_t cutoff,
+ dev_t rootdev,
+ bool mountpoint,
+ int maxdepth,
+ bool keep_this_level)
+{
+ struct dirent *dent;
+ struct timespec times[2];
+ bool deleted = false;
+ int r = 0;
+
+ while ((dent = readdir(d))) {
+ struct stat s;
+ usec_t age;
+ _cleanup_free_ char *sub_path = NULL;
+
+ if (streq(dent->d_name, ".") ||
+ streq(dent->d_name, ".."))
+ continue;
+
+ if (fstatat(dirfd(d), dent->d_name, &s, AT_SYMLINK_NOFOLLOW) < 0) {
+
+ if (errno != ENOENT) {
+ log_error("stat(%s/%s) failed: %m", p, dent->d_name);
+ r = -errno;
+ }
+
+ continue;
+ }
+
+ /* Stay on the same filesystem */
+ if (s.st_dev != rootdev)
+ continue;
+
+ /* Try to detect bind mounts of the same filesystem instance; they
+ * do not differ in device major/minors. This type of query is not
+ * supported on all kernels or filesystem types though. */
+ if (S_ISDIR(s.st_mode) && dir_is_mount_point(d, dent->d_name) > 0)
+ continue;
+
+ /* Do not delete read-only files owned by root */
+ if (s.st_uid == 0 && !(s.st_mode & S_IWUSR))
+ continue;
+
+ if (asprintf(&sub_path, "%s/%s", p, dent->d_name) < 0) {
+ r = log_oom();
+ goto finish;
+ }
+
+ /* Is there an item configured for this path? */
+ if (hashmap_get(items, sub_path))
+ continue;
+
+ if (find_glob(globs, sub_path))
+ continue;
+
+ if (S_ISDIR(s.st_mode)) {
+
+ if (mountpoint &&
+ streq(dent->d_name, "lost+found") &&
+ s.st_uid == 0)
+ continue;
+
+ if (maxdepth <= 0)
+ log_warning("Reached max depth on %s.", sub_path);
+ else {
+ _cleanup_closedir_ DIR *sub_dir;
+ int q;
+
+ sub_dir = xopendirat(dirfd(d), dent->d_name, O_NOFOLLOW|O_NOATIME);
+ if (sub_dir == NULL) {
+ if (errno != ENOENT) {
+ log_error("opendir(%s/%s) failed: %m", p, dent->d_name);
+ r = -errno;
+ }
+
+ continue;
+ }
+
+ q = dir_cleanup(i, sub_path, sub_dir, &s, cutoff, rootdev, false, maxdepth-1, false);
+
+ if (q < 0)
+ r = q;
+ }
+
+ /* Note: if you are wondering why we don't
+ * support the sticky bit for excluding
+ * directories from cleaning like we do it for
+ * other file system objects: well, the sticky
+ * bit already has a meaning for directories,
+ * so we don't want to overload that. */
+
+ if (keep_this_level)
+ continue;
+
+ /* Ignore ctime, we change it when deleting */
+ age = MAX(timespec_load(&s.st_mtim),
+ timespec_load(&s.st_atim));
+ if (age >= cutoff)
+ continue;
+
+ if (i->type != IGNORE_DIRECTORY_PATH || !streq(dent->d_name, p)) {
+ log_debug("rmdir '%s'\n", sub_path);
+
+ if (unlinkat(dirfd(d), dent->d_name, AT_REMOVEDIR) < 0) {
+ if (errno != ENOENT && errno != ENOTEMPTY) {
+ log_error("rmdir(%s): %m", sub_path);
+ r = -errno;
+ }
+ }
+ }
+
+ } else {
+ /* Skip files for which the sticky bit is
+ * set. These are semantics we define, and are
+ * unknown elsewhere. See XDG_RUNTIME_DIR
+ * specification for details. */
+ if (s.st_mode & S_ISVTX)
+ continue;
+
+ if (mountpoint && S_ISREG(s.st_mode)) {
+ if (streq(dent->d_name, ".journal") &&
+ s.st_uid == 0)
+ continue;
+
+ if (streq(dent->d_name, "aquota.user") ||
+ streq(dent->d_name, "aquota.group"))
+ continue;
+ }
+
+ /* Ignore sockets that are listed in /proc/net/unix */
+ if (S_ISSOCK(s.st_mode) && unix_socket_alive(sub_path))
+ continue;
+
+ /* Ignore device nodes */
+ if (S_ISCHR(s.st_mode) || S_ISBLK(s.st_mode))
+ continue;
+
+ /* Keep files on this level around if this is
+ * requested */
+ if (keep_this_level)
+ continue;
+
+ age = MAX3(timespec_load(&s.st_mtim),
+ timespec_load(&s.st_atim),
+ timespec_load(&s.st_ctim));
+
+ if (age >= cutoff)
+ continue;
+
+ log_debug("unlink '%s'\n", sub_path);
+
+ if (unlinkat(dirfd(d), dent->d_name, 0) < 0) {
+ if (errno != ENOENT) {
+ log_error("unlink(%s): %m", sub_path);
+ r = -errno;
+ }
+ }
+
+ deleted = true;
+ }
+ }
+
+finish:
+ if (deleted) {
+ /* Restore original directory timestamps */
+ times[0] = ds->st_atim;
+ times[1] = ds->st_mtim;
+
+ if (futimens(dirfd(d), times) < 0)
+ log_error("utimensat(%s): %m", p);
+ }
+
+ return r;
+}
+
+static int item_set_perms(Item *i, const char *path) {
+ /* not using i->path directly because it may be a glob */
+ if (i->mode_set)
+ if (chmod(path, i->mode) < 0) {
+ log_error("chmod(%s) failed: %m", path);
+ return -errno;
+ }
+
+ if (i->uid_set || i->gid_set)
+ if (chown(path,
+ i->uid_set ? i->uid : (uid_t) -1,
+ i->gid_set ? i->gid : (gid_t) -1) < 0) {
+
+ log_error("chown(%s) failed: %m", path);
+ return -errno;
+ }
+
+ return label_fix(path, false, false);
+}
+
+static int write_one_file(Item *i, const char *path) {
+ int r, e, fd, flags;
+ struct stat st;
+
+ flags = i->type == CREATE_FILE ? O_CREAT|O_APPEND :
+ i->type == TRUNCATE_FILE ? O_CREAT|O_TRUNC : 0;
+
+ RUN_WITH_UMASK(0) {
+ label_context_set(path, S_IFREG);
+ fd = open(path, flags|O_NDELAY|O_CLOEXEC|O_WRONLY|O_NOCTTY|O_NOFOLLOW, i->mode);
+ e = errno;
+ label_context_clear();
+ errno = e;
+ }
+
+ if (fd < 0) {
+ if (i->type == WRITE_FILE && errno == ENOENT)
+ return 0;
+
+ log_error("Failed to create file %s: %m", path);
+ return -errno;
+ }
+
+ if (i->argument) {
+ ssize_t n;
+ size_t l;
+ _cleanup_free_ char *unescaped;
+
+ unescaped = cunescape(i->argument);
+ if (unescaped == NULL) {
+ close_nointr_nofail(fd);
+ return log_oom();
+ }
+
+ l = strlen(unescaped);
+ n = write(fd, unescaped, l);
+
+ if (n < 0 || (size_t) n < l) {
+ log_error("Failed to write file %s: %s", path, n < 0 ? strerror(-n) : "Short write");
+ close_nointr_nofail(fd);
+ return n < 0 ? n : -EIO;
+ }
+ }
+
+ close_nointr_nofail(fd);
+
+ if (stat(path, &st) < 0) {
+ log_error("stat(%s) failed: %m", path);
+ return -errno;
+ }
+
+ if (!S_ISREG(st.st_mode)) {
+ log_error("%s is not a file.", path);
+ return -EEXIST;
+ }
+
+ r = item_set_perms(i, path);
+ if (r < 0)
+ return r;
+
+ return 0;
+}
+
+static int recursive_relabel_children(Item *i, const char *path) {
+ _cleanup_closedir_ DIR *d;
+ int ret = 0;
+
+ /* This returns the first error we run into, but nevertheless
+ * tries to go on */
+
+ d = opendir(path);
+ if (!d)
+ return errno == ENOENT ? 0 : -errno;
+
+ for (;;) {
+ struct dirent *de;
+ union dirent_storage buf;
+ bool is_dir;
+ int r;
+ _cleanup_free_ char *entry_path = NULL;
+
+ r = readdir_r(d, &buf.de, &de);
+ if (r != 0) {
+ if (ret == 0)
+ ret = -r;
+ break;
+ }
+
+ if (!de)
+ break;
+
+ if (streq(de->d_name, ".") || streq(de->d_name, ".."))
+ continue;
+
+ if (asprintf(&entry_path, "%s/%s", path, de->d_name) < 0) {
+ if (ret == 0)
+ ret = -ENOMEM;
+ continue;
+ }
+
+ if (de->d_type == DT_UNKNOWN) {
+ struct stat st;
+
+ if (lstat(entry_path, &st) < 0) {
+ if (ret == 0 && errno != ENOENT)
+ ret = -errno;
+ continue;
+ }
+
+ is_dir = S_ISDIR(st.st_mode);
+
+ } else
+ is_dir = de->d_type == DT_DIR;
+
+ r = item_set_perms(i, entry_path);
+ if (r < 0) {
+ if (ret == 0 && r != -ENOENT)
+ ret = r;
+ continue;
+ }
+
+ if (is_dir) {
+ r = recursive_relabel_children(i, entry_path);
+ if (r < 0 && ret == 0)
+ ret = r;
+ }
+ }
+
+ return ret;
+}
+
+static int recursive_relabel(Item *i, const char *path) {
+ int r;
+ struct stat st;
+
+ r = item_set_perms(i, path);
+ if (r < 0)
+ return r;
+
+ if (lstat(path, &st) < 0)
+ return -errno;
+
+ if (S_ISDIR(st.st_mode))
+ r = recursive_relabel_children(i, path);
+
+ return r;
+}
+
+static int glob_item(Item *i, int (*action)(Item *, const char *)) {
+ int r = 0, k;
+ _cleanup_globfree_ glob_t g = {};
+ char **fn;
+
+ errno = 0;
+ k = glob(i->path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
+ if (k != 0)
+ if (k != GLOB_NOMATCH) {
+ if (errno > 0)
+ errno = EIO;
+
+ log_error("glob(%s) failed: %m", i->path);
+ return -errno;
+ }
+
+ STRV_FOREACH(fn, g.gl_pathv) {
+ k = action(i, *fn);
+ if (k < 0)
+ r = k;
+ }
+
+ return r;
+}
+
+static int create_item(Item *i) {
+ int r, e;
+ struct stat st;
+
+ assert(i);
+
+ switch (i->type) {
+
+ case IGNORE_PATH:
+ case IGNORE_DIRECTORY_PATH:
+ case REMOVE_PATH:
+ case RECURSIVE_REMOVE_PATH:
+ return 0;
+
+ case CREATE_FILE:
+ case TRUNCATE_FILE:
+ r = write_one_file(i, i->path);
+ if (r < 0)
+ return r;
+ break;
+ case WRITE_FILE:
+ r = glob_item(i, write_one_file);
+ if (r < 0)
+ return r;
+
+ break;
+
+ case TRUNCATE_DIRECTORY:
+ case CREATE_DIRECTORY:
+
+ RUN_WITH_UMASK(0000) {
+ mkdir_parents_label(i->path, 0755);
+ r = mkdir(i->path, i->mode);
+ }
+
+ if (r < 0 && errno != EEXIST) {
+ log_error("Failed to create directory %s: %m", i->path);
+ return -errno;
+ }
+
+ if (stat(i->path, &st) < 0) {
+ log_error("stat(%s) failed: %m", i->path);
+ return -errno;
+ }
+
+ if (!S_ISDIR(st.st_mode)) {
+ log_error("%s is not a directory.", i->path);
+ return -EEXIST;
+ }
+
+ r = item_set_perms(i, i->path);
+ if (r < 0)
+ return r;
+
+ break;
+
+ case CREATE_FIFO:
+
+ RUN_WITH_UMASK(0000) {
+ r = mkfifo(i->path, i->mode);
+ }
+
+ if (r < 0 && errno != EEXIST) {
+ log_error("Failed to create fifo %s: %m", i->path);
+ return -errno;
+ }
+
+ if (stat(i->path, &st) < 0) {
+ log_error("stat(%s) failed: %m", i->path);
+ return -errno;
+ }
+
+ if (!S_ISFIFO(st.st_mode)) {
+ log_error("%s is not a fifo.", i->path);
+ return -EEXIST;
+ }
+
+ r = item_set_perms(i, i->path);
+ if (r < 0)
+ return r;
+
+ break;
+
+ case CREATE_SYMLINK: {
+ char *x;
+
+ label_context_set(i->path, S_IFLNK);
+ r = symlink(i->argument, i->path);
+ e = errno;
+ label_context_clear();
+ errno = e;
+
+ if (r < 0 && errno != EEXIST) {
+ log_error("symlink(%s, %s) failed: %m", i->argument, i->path);
+ return -errno;
+ }
+
+ r = readlink_malloc(i->path, &x);
+ if (r < 0) {
+ log_error("readlink(%s) failed: %s", i->path, strerror(-r));
+ return -errno;
+ }
+
+ if (!streq(i->argument, x)) {
+ free(x);
+ log_error("%s is not the right symlinks.", i->path);
+ return -EEXIST;
+ }
+
+ free(x);
+ break;
+ }
+
+ case CREATE_BLOCK_DEVICE:
+ case CREATE_CHAR_DEVICE: {
+ mode_t file_type;
+
+ if (have_effective_cap(CAP_MKNOD) == 0) {
+ /* In a container we lack CAP_MKNOD. We
+ shouldn't attempt to create the device node in
+ that case to avoid noise, and we don't support
+ virtualized devices in containers anyway. */
+
+ log_debug("We lack CAP_MKNOD, skipping creation of device node %s.", i->path);
+ return 0;
+ }
+
+ file_type = (i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
+
+ RUN_WITH_UMASK(0000) {
+ label_context_set(i->path, file_type);
+ r = mknod(i->path, i->mode | file_type, i->major_minor);
+ e = errno;
+ label_context_clear();
+ errno = e;
+ }
+
+ if (r < 0 && errno != EEXIST) {
+ log_error("Failed to create device node %s: %m", i->path);
+ return -errno;
+ }
+
+ if (stat(i->path, &st) < 0) {
+ log_error("stat(%s) failed: %m", i->path);
+ return -errno;
+ }
+
+ if ((st.st_mode & S_IFMT) != file_type) {
+ log_error("%s is not a device node.", i->path);
+ return -EEXIST;
+ }
+
+ r = item_set_perms(i, i->path);
+ if (r < 0)
+ return r;
+
+ break;
+ }
+
+ case RELABEL_PATH:
+
+ r = glob_item(i, item_set_perms);
+ if (r < 0)
+ return 0;
+ break;
+
+ case RECURSIVE_RELABEL_PATH:
+
+ r = glob_item(i, recursive_relabel);
+ if (r < 0)
+ return r;
+ }
+
+ log_debug("%s created successfully.", i->path);
+
+ return 0;
+}
+
+static int remove_item_instance(Item *i, const char *instance) {
+ int r;
+
+ assert(i);
+
+ switch (i->type) {
+
+ case CREATE_FILE:
+ case TRUNCATE_FILE:
+ case CREATE_DIRECTORY:
+ case CREATE_FIFO:
+ case CREATE_SYMLINK:
+ case CREATE_BLOCK_DEVICE:
+ case CREATE_CHAR_DEVICE:
+ case IGNORE_PATH:
+ case IGNORE_DIRECTORY_PATH:
+ case RELABEL_PATH:
+ case RECURSIVE_RELABEL_PATH:
+ case WRITE_FILE:
+ break;
+
+ case REMOVE_PATH:
+ if (remove(instance) < 0 && errno != ENOENT) {
+ log_error("remove(%s): %m", instance);
+ return -errno;
+ }
+
+ break;
+
+ case TRUNCATE_DIRECTORY:
+ case RECURSIVE_REMOVE_PATH:
+ /* FIXME: we probably should use dir_cleanup() here
+ * instead of rm_rf() so that 'x' is honoured. */
+ r = rm_rf_dangerous(instance, false, i->type == RECURSIVE_REMOVE_PATH, false);
+ if (r < 0 && r != -ENOENT) {
+ log_error("rm_rf(%s): %s", instance, strerror(-r));
+ return r;
+ }
+
+ break;
+ }
+
+ return 0;
+}
+
+static int remove_item(Item *i) {
+ int r = 0;
+
+ assert(i);
+
+ switch (i->type) {
+
+ case CREATE_FILE:
+ case TRUNCATE_FILE:
+ case CREATE_DIRECTORY:
+ case CREATE_FIFO:
+ case CREATE_SYMLINK:
+ case CREATE_CHAR_DEVICE:
+ case CREATE_BLOCK_DEVICE:
+ case IGNORE_PATH:
+ case IGNORE_DIRECTORY_PATH:
+ case RELABEL_PATH:
+ case RECURSIVE_RELABEL_PATH:
+ case WRITE_FILE:
+ break;
+
+ case REMOVE_PATH:
+ case TRUNCATE_DIRECTORY:
+ case RECURSIVE_REMOVE_PATH:
+ r = glob_item(i, remove_item_instance);
+ break;
+ }
+
+ return r;
+}
+
+static int clean_item_instance(Item *i, const char* instance) {
+ _cleanup_closedir_ DIR *d = NULL;
+ struct stat s, ps;
+ bool mountpoint;
+ int r;
+ usec_t cutoff, n;
+
+ assert(i);
+
+ if (!i->age_set)
+ return 0;
+
+ n = now(CLOCK_REALTIME);
+ if (n < i->age)
+ return 0;
+
+ cutoff = n - i->age;
+
+ d = opendir(instance);
+ if (!d) {
+ if (errno == ENOENT || errno == ENOTDIR)
+ return 0;
+
+ log_error("Failed to open directory %s: %m", i->path);
+ return -errno;
+ }
+
+ if (fstat(dirfd(d), &s) < 0) {
+ log_error("stat(%s) failed: %m", i->path);
+ return -errno;
+ }
+
+ if (!S_ISDIR(s.st_mode)) {
+ log_error("%s is not a directory.", i->path);
+ return -ENOTDIR;
+ }
+
+ if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0) {
+ log_error("stat(%s/..) failed: %m", i->path);
+ return -errno;
+ }
+
+ mountpoint = s.st_dev != ps.st_dev ||
+ (s.st_dev == ps.st_dev && s.st_ino == ps.st_ino);
+
+ r = dir_cleanup(i, instance, d, &s, cutoff, s.st_dev, mountpoint,
+ MAX_DEPTH, i->keep_first_level);
+ return r;
+}
+
+static int clean_item(Item *i) {
+ int r = 0;
+
+ assert(i);
+
+ switch (i->type) {
+ case CREATE_DIRECTORY:
+ case TRUNCATE_DIRECTORY:
+ case IGNORE_PATH:
+ clean_item_instance(i, i->path);
+ break;
+ case IGNORE_DIRECTORY_PATH:
+ r = glob_item(i, clean_item_instance);
+ break;
+ default:
+ break;
+ }
+
+ return r;
+}
+
+static int process_item(Item *i) {
+ int r, q, p;
+
+ assert(i);
+
+ r = arg_create ? create_item(i) : 0;
+ q = arg_remove ? remove_item(i) : 0;
+ p = arg_clean ? clean_item(i) : 0;
+
+ if (r < 0)
+ return r;
+
+ if (q < 0)
+ return q;
+
+ return p;
+}
+
+static void item_free(Item *i) {
+ assert(i);
+
+ free(i->path);
+ free(i->argument);
+ free(i);
+}
+
+static bool item_equal(Item *a, Item *b) {
+ assert(a);
+ assert(b);
+
+ if (!streq_ptr(a->path, b->path))
+ return false;
+
+ if (a->type != b->type)
+ return false;
+
+ if (a->uid_set != b->uid_set ||
+ (a->uid_set && a->uid != b->uid))
+ return false;
+
+ if (a->gid_set != b->gid_set ||
+ (a->gid_set && a->gid != b->gid))
+ return false;
+
+ if (a->mode_set != b->mode_set ||
+ (a->mode_set && a->mode != b->mode))
+ return false;
+
+ if (a->age_set != b->age_set ||
+ (a->age_set && a->age != b->age))
+ return false;
+
+ if ((a->type == CREATE_FILE ||
+ a->type == TRUNCATE_FILE ||
+ a->type == WRITE_FILE ||
+ a->type == CREATE_SYMLINK) &&
+ !streq_ptr(a->argument, b->argument))
+ return false;
+
+ if ((a->type == CREATE_CHAR_DEVICE ||
+ a->type == CREATE_BLOCK_DEVICE) &&
+ a->major_minor != b->major_minor)
+ return false;
+
+ return true;
+}
+
+static int parse_line(const char *fname, unsigned line, const char *buffer) {
+ _cleanup_free_ Item *i = NULL;
+ Item *existing;
+ _cleanup_free_ char
+ *mode = NULL, *user = NULL, *group = NULL, *age = NULL;
+ char type;
+ Hashmap *h;
+ int r, n = -1;
+
+ assert(fname);
+ assert(line >= 1);
+ assert(buffer);
+
+ i = new0(Item, 1);
+ if (!i)
+ return log_oom();
+
+ r = sscanf(buffer,
+ "%c %ms %ms %ms %ms %ms %n",
+ &type,
+ &i->path,
+ &mode,
+ &user,
+ &group,
+ &age,
+ &n);
+ if (r < 2) {
+ log_error("[%s:%u] Syntax error.", fname, line);
+ return -EIO;
+ }
+
+ if (n >= 0) {
+ n += strspn(buffer+n, WHITESPACE);
+ if (buffer[n] != 0 && (buffer[n] != '-' || buffer[n+1] != 0)) {
+ i->argument = unquote(buffer+n, "\"");
+ if (!i->argument)
+ return log_oom();
+ }
+ }
+
+ switch(type) {
+
+ case CREATE_FILE:
+ case TRUNCATE_FILE:
+ case CREATE_DIRECTORY:
+ case TRUNCATE_DIRECTORY:
+ case CREATE_FIFO:
+ case IGNORE_PATH:
+ case IGNORE_DIRECTORY_PATH:
+ case REMOVE_PATH:
+ case RECURSIVE_REMOVE_PATH:
+ case RELABEL_PATH:
+ case RECURSIVE_RELABEL_PATH:
+ break;
+
+ case CREATE_SYMLINK:
+ if (!i->argument) {
+ log_error("[%s:%u] Symlink file requires argument.", fname, line);
+ return -EBADMSG;
+ }
+ break;
+
+ case WRITE_FILE:
+ if (!i->argument) {
+ log_error("[%s:%u] Write file requires argument.", fname, line);
+ return -EBADMSG;
+ }
+ break;
+
+ case CREATE_CHAR_DEVICE:
+ case CREATE_BLOCK_DEVICE: {
+ unsigned major, minor;
+
+ if (!i->argument) {
+ log_error("[%s:%u] Device file requires argument.", fname, line);
+ return -EBADMSG;
+ }
+
+ if (sscanf(i->argument, "%u:%u", &major, &minor) != 2) {
+ log_error("[%s:%u] Can't parse device file major/minor '%s'.", fname, line, i->argument);
+ return -EBADMSG;
+ }
+
+ i->major_minor = makedev(major, minor);
+ break;
+ }
+
+ default:
+ log_error("[%s:%u] Unknown file type '%c'.", fname, line, type);
+ return -EBADMSG;
+ }
+
+ i->type = type;
+
+ if (!path_is_absolute(i->path)) {
+ log_error("[%s:%u] Path '%s' not absolute.", fname, line, i->path);
+ return -EBADMSG;
+ }
+
+ path_kill_slashes(i->path);
+
+ if (arg_prefix && !path_startswith(i->path, arg_prefix))
+ return 0;
+
+ if (user && !streq(user, "-")) {
+ const char *u = user;
+
+ r = get_user_creds(&u, &i->uid, NULL, NULL, NULL);
+ if (r < 0) {
+ log_error("[%s:%u] Unknown user '%s'.", fname, line, user);
+ return r;
+ }
+
+ i->uid_set = true;
+ }
+
+ if (group && !streq(group, "-")) {
+ const char *g = group;
+
+ r = get_group_creds(&g, &i->gid);
+ if (r < 0) {
+ log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
+ return r;
+ }
+
+ i->gid_set = true;
+ }
+
+ if (mode && !streq(mode, "-")) {
+ unsigned m;
+
+ if (sscanf(mode, "%o", &m) != 1) {
+ log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
+ return -ENOENT;
+ }
+
+ i->mode = m;
+ i->mode_set = true;
+ } else
+ i->mode =
+ i->type == CREATE_DIRECTORY ||
+ i->type == TRUNCATE_DIRECTORY ? 0755 : 0644;
+
+ if (age && !streq(age, "-")) {
+ const char *a = age;
+
+ if (*a == '~') {
+ i->keep_first_level = true;
+ a++;
+ }
+
+ if (parse_sec(a, &i->age) < 0) {
+ log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
+ return -EBADMSG;
+ }
+
+ i->age_set = true;
+ }
+
+ h = needs_glob(i->type) ? globs : items;
+
+ existing = hashmap_get(h, i->path);
+ if (existing) {
+
+ /* Two identical items are fine */
+ if (!item_equal(existing, i))
+ log_warning("Two or more conflicting lines for %s configured, ignoring.", i->path);
+
+ return 0;
+ }
+
+ r = hashmap_put(h, i->path, i);
+ if (r < 0) {
+ log_error("Failed to insert item %s: %s", i->path, strerror(-r));
+ return r;
+ }
+
+ i = NULL; /* avoid cleanup */
+
+ return 0;
+}
+
+static int help(void) {
+
+ printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
+ "Creates, deletes and cleans up volatile and temporary files and directories.\n\n"
+ " -h --help Show this help\n"
+ " --create Create marked files/directories\n"
+ " --clean Clean up marked directories\n"
+ " --remove Remove marked files/directories\n"
+ " --prefix=PATH Only apply rules that apply to paths with the specified prefix\n",
+ program_invocation_short_name);
+
+ return 0;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+
+ enum {
+ ARG_CREATE,
+ ARG_CLEAN,
+ ARG_REMOVE,
+ ARG_PREFIX
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "create", no_argument, NULL, ARG_CREATE },
+ { "clean", no_argument, NULL, ARG_CLEAN },
+ { "remove", no_argument, NULL, ARG_REMOVE },
+ { "prefix", required_argument, NULL, ARG_PREFIX },
+ { NULL, 0, NULL, 0 }
+ };
+
+ int c;
+
+ assert(argc >= 0);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
+
+ switch (c) {
+
+ case 'h':
+ help();
+ return 0;
+
+ case ARG_CREATE:
+ arg_create = true;
+ break;
+
+ case ARG_CLEAN:
+ arg_clean = true;
+ break;
+
+ case ARG_REMOVE:
+ arg_remove = true;
+ break;
+
+ case ARG_PREFIX:
+ arg_prefix = optarg;
+ break;
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ log_error("Unknown option code %c", c);
+ return -EINVAL;
+ }
+ }
+
+ if (!arg_clean && !arg_create && !arg_remove) {
+ log_error("You need to specify at least one of --clean, --create or --remove.");
+ return -EINVAL;
+ }
+
+ return 1;
+}
+
+static int read_config_file(const char *fn, bool ignore_enoent) {
+ FILE *f;
+ unsigned v = 0;
+ int r;
+ Iterator iterator;
+ Item *i;
+
+ assert(fn);
+
+ r = search_and_fopen_nulstr(fn, "re", conf_file_dirs, &f);
+ if (r < 0) {
+ if (ignore_enoent && r == -ENOENT)
+ return 0;
+
+ log_error("Failed to open '%s', ignoring: %s", fn, strerror(-r));
+ return r;
+ }
+
+ log_debug("apply: %s\n", fn);
+ for (;;) {
+ char line[LINE_MAX], *l;
+ int k;
+
+ if (!(fgets(line, sizeof(line), f)))
+ break;
+
+ v++;
+
+ l = strstrip(line);
+ if (*l == '#' || *l == 0)
+ continue;
+
+ if ((k = parse_line(fn, v, l)) < 0)
+ if (r == 0)
+ r = k;
+ }
+
+ /* we have to determine age parameter for each entry of type X */
+ HASHMAP_FOREACH(i, globs, iterator) {
+ Iterator iter;
+ Item *j, *candidate_item = NULL;
+
+ if (i->type != IGNORE_DIRECTORY_PATH)
+ continue;
+
+ HASHMAP_FOREACH(j, items, iter) {
+ if (j->type != CREATE_DIRECTORY && j->type != TRUNCATE_DIRECTORY)
+ continue;
+
+ if (path_equal(j->path, i->path)) {
+ candidate_item = j;
+ break;
+ }
+
+ if ((!candidate_item && path_startswith(i->path, j->path)) ||
+ (candidate_item && path_startswith(j->path, candidate_item->path) && (fnmatch(i->path, j->path, FNM_PATHNAME | FNM_PERIOD) == 0)))
+ candidate_item = j;
+ }
+
+ if (candidate_item) {
+ i->age = candidate_item->age;
+ i->age_set = true;
+ }
+ }
+
+ if (ferror(f)) {
+ log_error("Failed to read from file %s: %m", fn);
+ if (r == 0)
+ r = -EIO;
+ }
+
+ fclose(f);
+
+ return r;
+}
+
+int main(int argc, char *argv[]) {
+ int r, k;
+ Item *i;
+ Iterator iterator;
+
+ r = parse_argv(argc, argv);
+ if (r <= 0)
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+
+ log_set_target(LOG_TARGET_AUTO);
+ log_parse_environment();
+ log_open();
+
+ umask(0022);
+
+ label_init(NULL);
+
+ items = hashmap_new(string_hash_func, string_compare_func);
+ globs = hashmap_new(string_hash_func, string_compare_func);
+
+ if (!items || !globs) {
+ r = log_oom();
+ goto finish;
+ }
+
+ r = 0;
+
+ if (optind < argc) {
+ int j;
+
+ for (j = optind; j < argc; j++) {
+ k = read_config_file(argv[j], false);
+ if (k < 0 && r == 0)
+ r = k;
+ }
+
+ } else {
+ _cleanup_strv_free_ char **files = NULL;
+ char **f;
+
+ r = conf_files_list_nulstr(&files, ".conf", NULL, conf_file_dirs);
+ if (r < 0) {
+ log_error("Failed to enumerate tmpfiles.d files: %s", strerror(-r));
+ goto finish;
+ }
+
+ STRV_FOREACH(f, files) {
+ k = read_config_file(*f, true);
+ if (k < 0 && r == 0)
+ r = k;
+ }
+ }
+
+ HASHMAP_FOREACH(i, globs, iterator)
+ process_item(i);
+
+ HASHMAP_FOREACH(i, items, iterator)
+ process_item(i);
+
+finish:
+ while ((i = hashmap_steal_first(items)))
+ item_free(i);
+
+ while ((i = hashmap_steal_first(globs)))
+ item_free(i);
+
+ hashmap_free(items);
+ hashmap_free(globs);
+
+ set_free_free(unix_sockets);
+
+ label_finish();
+
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/src/tty-ask-password-agent/tty-ask-password-agent.c b/src/tty-ask-password-agent/tty-ask-password-agent.c
new file mode 100644
index 0000000000..f463662d6b
--- /dev/null
+++ b/src/tty-ask-password-agent/tty-ask-password-agent.c
@@ -0,0 +1,759 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdbool.h>
+#include <errno.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <stddef.h>
+#include <sys/poll.h>
+#include <sys/inotify.h>
+#include <unistd.h>
+#include <getopt.h>
+#include <sys/signalfd.h>
+#include <fcntl.h>
+
+#include "util.h"
+#include "mkdir.h"
+#include "path-util.h"
+#include "conf-parser.h"
+#include "utmp-wtmp.h"
+#include "socket-util.h"
+#include "ask-password-api.h"
+#include "strv.h"
+#include "build.h"
+
+static enum {
+ ACTION_LIST,
+ ACTION_QUERY,
+ ACTION_WATCH,
+ ACTION_WALL
+} arg_action = ACTION_QUERY;
+
+static bool arg_plymouth = false;
+static bool arg_console = false;
+
+static int ask_password_plymouth(
+ const char *message,
+ usec_t until,
+ const char *flag_file,
+ bool accept_cached,
+ char ***_passphrases) {
+
+ int fd = -1, notify = -1;
+ union sockaddr_union sa = {};
+ char *packet = NULL;
+ ssize_t k;
+ int r, n;
+ struct pollfd pollfd[2] = {};
+ char buffer[LINE_MAX];
+ size_t p = 0;
+ enum {
+ POLL_SOCKET,
+ POLL_INOTIFY
+ };
+
+ assert(_passphrases);
+
+ if (flag_file) {
+ if ((notify = inotify_init1(IN_CLOEXEC|IN_NONBLOCK)) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ if (inotify_add_watch(notify, flag_file, IN_ATTRIB /* for the link count */) < 0) {
+ r = -errno;
+ goto finish;
+ }
+ }
+
+ if ((fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0)) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ sa.sa.sa_family = AF_UNIX;
+ strncpy(sa.un.sun_path+1, "/org/freedesktop/plymouthd", sizeof(sa.un.sun_path)-1);
+ if (connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + 1 + strlen(sa.un.sun_path+1)) < 0) {
+ log_error("Failed to connect to Plymouth: %m");
+ r = -errno;
+ goto finish;
+ }
+
+ if (accept_cached) {
+ packet = strdup("c");
+ n = 1;
+ } else
+ asprintf(&packet, "*\002%c%s%n", (int) (strlen(message) + 1), message, &n);
+
+ if (!packet) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ if ((k = loop_write(fd, packet, n+1, true)) != n+1) {
+ r = k < 0 ? (int) k : -EIO;
+ goto finish;
+ }
+
+ pollfd[POLL_SOCKET].fd = fd;
+ pollfd[POLL_SOCKET].events = POLLIN;
+ pollfd[POLL_INOTIFY].fd = notify;
+ pollfd[POLL_INOTIFY].events = POLLIN;
+
+ for (;;) {
+ int sleep_for = -1, j;
+
+ if (until > 0) {
+ usec_t y;
+
+ y = now(CLOCK_MONOTONIC);
+
+ if (y > until) {
+ r = -ETIME;
+ goto finish;
+ }
+
+ sleep_for = (int) ((until - y) / USEC_PER_MSEC);
+ }
+
+ if (flag_file)
+ if (access(flag_file, F_OK) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ if ((j = poll(pollfd, notify > 0 ? 2 : 1, sleep_for)) < 0) {
+
+ if (errno == EINTR)
+ continue;
+
+ r = -errno;
+ goto finish;
+ } else if (j == 0) {
+ r = -ETIME;
+ goto finish;
+ }
+
+ if (notify > 0 && pollfd[POLL_INOTIFY].revents != 0)
+ flush_fd(notify);
+
+ if (pollfd[POLL_SOCKET].revents == 0)
+ continue;
+
+ if ((k = read(fd, buffer + p, sizeof(buffer) - p)) <= 0) {
+ r = k < 0 ? -errno : -EIO;
+ goto finish;
+ }
+
+ p += k;
+
+ if (p < 1)
+ continue;
+
+ if (buffer[0] == 5) {
+
+ if (accept_cached) {
+ /* Hmm, first try with cached
+ * passwords failed, so let's retry
+ * with a normal password request */
+ free(packet);
+ packet = NULL;
+
+ if (asprintf(&packet, "*\002%c%s%n", (int) (strlen(message) + 1), message, &n) < 0) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ if ((k = loop_write(fd, packet, n+1, true)) != n+1) {
+ r = k < 0 ? (int) k : -EIO;
+ goto finish;
+ }
+
+ accept_cached = false;
+ p = 0;
+ continue;
+ }
+
+ /* No password, because UI not shown */
+ r = -ENOENT;
+ goto finish;
+
+ } else if (buffer[0] == 2 || buffer[0] == 9) {
+ uint32_t size;
+ char **l;
+
+ /* One ore more answers */
+ if (p < 5)
+ continue;
+
+ memcpy(&size, buffer+1, sizeof(size));
+ size = le32toh(size);
+ if (size+5 > sizeof(buffer)) {
+ r = -EIO;
+ goto finish;
+ }
+
+ if (p-5 < size)
+ continue;
+
+ if (!(l = strv_parse_nulstr(buffer + 5, size))) {
+ r = -ENOMEM;
+ goto finish;
+ }
+
+ *_passphrases = l;
+ break;
+
+ } else {
+ /* Unknown packet */
+ r = -EIO;
+ goto finish;
+ }
+ }
+
+ r = 0;
+
+finish:
+ if (notify >= 0)
+ close_nointr_nofail(notify);
+
+ if (fd >= 0)
+ close_nointr_nofail(fd);
+
+ free(packet);
+
+ return r;
+}
+
+static int parse_password(const char *filename, char **wall) {
+ char *socket_name = NULL, *message = NULL, *packet = NULL;
+ uint64_t not_after = 0;
+ unsigned pid = 0;
+ int socket_fd = -1;
+ bool accept_cached = false;
+
+ const ConfigTableItem items[] = {
+ { "Ask", "Socket", config_parse_string, 0, &socket_name },
+ { "Ask", "NotAfter", config_parse_uint64, 0, &not_after },
+ { "Ask", "Message", config_parse_string, 0, &message },
+ { "Ask", "PID", config_parse_unsigned, 0, &pid },
+ { "Ask", "AcceptCached", config_parse_bool, 0, &accept_cached },
+ { NULL, NULL, NULL, 0, NULL }
+ };
+
+ FILE *f;
+ int r;
+
+ assert(filename);
+
+ f = fopen(filename, "re");
+ if (!f) {
+ if (errno == ENOENT)
+ return 0;
+
+ log_error("open(%s): %m", filename);
+ return -errno;
+ }
+
+ r = config_parse(NULL, filename, f, NULL, config_item_table_lookup, (void*) items, true, false, NULL);
+ if (r < 0) {
+ log_error("Failed to parse password file %s: %s", filename, strerror(-r));
+ goto finish;
+ }
+
+ if (!socket_name) {
+ log_error("Invalid password file %s", filename);
+ r = -EBADMSG;
+ goto finish;
+ }
+
+ if (not_after > 0) {
+ if (now(CLOCK_MONOTONIC) > not_after) {
+ r = 0;
+ goto finish;
+ }
+ }
+
+ if (pid > 0 &&
+ kill(pid, 0) < 0 &&
+ errno == ESRCH) {
+ r = 0;
+ goto finish;
+ }
+
+ if (arg_action == ACTION_LIST)
+ printf("'%s' (PID %u)\n", message, pid);
+ else if (arg_action == ACTION_WALL) {
+ char *_wall;
+
+ if (asprintf(&_wall,
+ "%s%sPassword entry required for \'%s\' (PID %u).\r\n"
+ "Please enter password with the systemd-tty-ask-password-agent tool!",
+ *wall ? *wall : "",
+ *wall ? "\r\n\r\n" : "",
+ message,
+ pid) < 0) {
+ r = log_oom();
+ goto finish;
+ }
+
+ free(*wall);
+ *wall = _wall;
+ } else {
+ union {
+ struct sockaddr sa;
+ struct sockaddr_un un;
+ } sa = {};
+ size_t packet_length = 0;
+
+ assert(arg_action == ACTION_QUERY ||
+ arg_action == ACTION_WATCH);
+
+ if (access(socket_name, W_OK) < 0) {
+
+ if (arg_action == ACTION_QUERY)
+ log_info("Not querying '%s' (PID %u), lacking privileges.", message, pid);
+
+ r = 0;
+ goto finish;
+ }
+
+ if (arg_plymouth) {
+ _cleanup_strv_free_ char **passwords = NULL;
+
+ if ((r = ask_password_plymouth(message, not_after, filename, accept_cached, &passwords)) >= 0) {
+ char **p;
+
+ packet_length = 1;
+ STRV_FOREACH(p, passwords)
+ packet_length += strlen(*p) + 1;
+
+ if (!(packet = new(char, packet_length)))
+ r = -ENOMEM;
+ else {
+ char *d;
+
+ packet[0] = '+';
+ d = packet+1;
+
+ STRV_FOREACH(p, passwords)
+ d = stpcpy(d, *p) + 1;
+ }
+ }
+
+ } else {
+ int tty_fd = -1;
+ char *password;
+
+ if (arg_console)
+ if ((tty_fd = acquire_terminal("/dev/console", false, false, false, (usec_t) -1)) < 0) {
+ r = tty_fd;
+ goto finish;
+ }
+
+ r = ask_password_tty(message, not_after, filename, &password);
+
+ if (arg_console) {
+ close_nointr_nofail(tty_fd);
+ release_terminal();
+ }
+
+ if (r >= 0) {
+ packet_length = 1+strlen(password)+1;
+ if (!(packet = new(char, packet_length)))
+ r = -ENOMEM;
+ else {
+ packet[0] = '+';
+ strcpy(packet+1, password);
+ }
+
+ free(password);
+ }
+ }
+
+ if (r == -ETIME || r == -ENOENT) {
+ /* If the query went away, that's OK */
+ r = 0;
+ goto finish;
+ }
+
+ if (r < 0) {
+ log_error("Failed to query password: %s", strerror(-r));
+ goto finish;
+ }
+
+ if ((socket_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0) {
+ log_error("socket(): %m");
+ r = -errno;
+ goto finish;
+ }
+
+ sa.un.sun_family = AF_UNIX;
+ strncpy(sa.un.sun_path, socket_name, sizeof(sa.un.sun_path));
+
+ if (sendto(socket_fd, packet, packet_length, MSG_NOSIGNAL, &sa.sa, offsetof(struct sockaddr_un, sun_path) + strlen(socket_name)) < 0) {
+ log_error("Failed to send: %m");
+ r = -errno;
+ goto finish;
+ }
+ }
+
+finish:
+ fclose(f);
+
+ if (socket_fd >= 0)
+ close_nointr_nofail(socket_fd);
+
+ free(packet);
+ free(socket_name);
+ free(message);
+
+ return r;
+}
+
+static int wall_tty_block(void) {
+ char *p;
+ int fd, r;
+ dev_t devnr;
+
+ r = get_ctty_devnr(0, &devnr);
+ if (r < 0)
+ return -r;
+
+ if (asprintf(&p, "/run/systemd/ask-password-block/%u:%u", major(devnr), minor(devnr)) < 0)
+ return -ENOMEM;
+
+ mkdir_parents_label(p, 0700);
+ mkfifo(p, 0600);
+
+ fd = open(p, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
+ free(p);
+
+ if (fd < 0)
+ return -errno;
+
+ return fd;
+}
+
+static bool wall_tty_match(const char *path) {
+ int fd, k;
+ char *p;
+ struct stat st;
+
+ if (path_is_absolute(path))
+ k = lstat(path, &st);
+ else {
+ if (asprintf(&p, "/dev/%s", path) < 0)
+ return true;
+
+ k = lstat(p, &st);
+ free(p);
+ }
+
+ if (k < 0)
+ return true;
+
+ if (!S_ISCHR(st.st_mode))
+ return true;
+
+ /* We use named pipes to ensure that wall messages suggesting
+ * password entry are not printed over password prompts
+ * already shown. We use the fact here that opening a pipe in
+ * non-blocking mode for write-only will succeed only if
+ * there's some writer behind it. Using pipes has the
+ * advantage that the block will automatically go away if the
+ * process dies. */
+
+ if (asprintf(&p, "/run/systemd/ask-password-block/%u:%u", major(st.st_rdev), minor(st.st_rdev)) < 0)
+ return true;
+
+ fd = open(p, O_WRONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
+ free(p);
+
+ if (fd < 0)
+ return true;
+
+ /* What, we managed to open the pipe? Then this tty is filtered. */
+ close_nointr_nofail(fd);
+ return false;
+}
+
+static int show_passwords(void) {
+ DIR *d;
+ struct dirent *de;
+ int r = 0;
+
+ if (!(d = opendir("/run/systemd/ask-password"))) {
+ if (errno == ENOENT)
+ return 0;
+
+ log_error("opendir(): %m");
+ return -errno;
+ }
+
+ while ((de = readdir(d))) {
+ char *p;
+ int q;
+ char *wall;
+
+ /* We only support /dev on tmpfs, hence we can rely on
+ * d_type to be reliable */
+
+ if (de->d_type != DT_REG)
+ continue;
+
+ if (ignore_file(de->d_name))
+ continue;
+
+ if (!startswith(de->d_name, "ask."))
+ continue;
+
+ if (!(p = strappend("/run/systemd/ask-password/", de->d_name))) {
+ r = log_oom();
+ goto finish;
+ }
+
+ wall = NULL;
+ if ((q = parse_password(p, &wall)) < 0)
+ r = q;
+
+ free(p);
+
+ if (wall) {
+ utmp_wall(wall, wall_tty_match);
+ free(wall);
+ }
+ }
+
+finish:
+ if (d)
+ closedir(d);
+
+ return r;
+}
+
+static int watch_passwords(void) {
+ enum {
+ FD_INOTIFY,
+ FD_SIGNAL,
+ _FD_MAX
+ };
+
+ int notify = -1, signal_fd = -1, tty_block_fd = -1;
+ struct pollfd pollfd[_FD_MAX] = {};
+ sigset_t mask;
+ int r;
+
+ tty_block_fd = wall_tty_block();
+
+ mkdir_p_label("/run/systemd/ask-password", 0755);
+
+ if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ if (inotify_add_watch(notify, "/run/systemd/ask-password", IN_CLOSE_WRITE|IN_MOVED_TO) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ assert_se(sigemptyset(&mask) == 0);
+ sigset_add_many(&mask, SIGINT, SIGTERM, -1);
+ assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
+
+ if ((signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0) {
+ log_error("signalfd(): %m");
+ r = -errno;
+ goto finish;
+ }
+
+ pollfd[FD_INOTIFY].fd = notify;
+ pollfd[FD_INOTIFY].events = POLLIN;
+ pollfd[FD_SIGNAL].fd = signal_fd;
+ pollfd[FD_SIGNAL].events = POLLIN;
+
+ for (;;) {
+ if ((r = show_passwords()) < 0)
+ log_error("Failed to show password: %s", strerror(-r));
+
+ if (poll(pollfd, _FD_MAX, -1) < 0) {
+
+ if (errno == EINTR)
+ continue;
+
+ r = -errno;
+ goto finish;
+ }
+
+ if (pollfd[FD_INOTIFY].revents != 0)
+ flush_fd(notify);
+
+ if (pollfd[FD_SIGNAL].revents != 0)
+ break;
+ }
+
+ r = 0;
+
+finish:
+ if (notify >= 0)
+ close_nointr_nofail(notify);
+
+ if (signal_fd >= 0)
+ close_nointr_nofail(signal_fd);
+
+ if (tty_block_fd >= 0)
+ close_nointr_nofail(tty_block_fd);
+
+ return r;
+}
+
+static int help(void) {
+
+ printf("%s [OPTIONS...]\n\n"
+ "Process system password requests.\n\n"
+ " -h --help Show this help\n"
+ " --version Show package version\n"
+ " --list Show pending password requests\n"
+ " --query Process pending password requests\n"
+ " --watch Continuously process password requests\n"
+ " --wall Continuously forward password requests to wall\n"
+ " --plymouth Ask question with Plymouth instead of on TTY\n"
+ " --console Ask question on /dev/console instead of current TTY\n",
+ program_invocation_short_name);
+
+ return 0;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+
+ enum {
+ ARG_LIST = 0x100,
+ ARG_QUERY,
+ ARG_WATCH,
+ ARG_WALL,
+ ARG_PLYMOUTH,
+ ARG_CONSOLE,
+ ARG_VERSION
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "version", no_argument, NULL, ARG_VERSION },
+ { "list", no_argument, NULL, ARG_LIST },
+ { "query", no_argument, NULL, ARG_QUERY },
+ { "watch", no_argument, NULL, ARG_WATCH },
+ { "wall", no_argument, NULL, ARG_WALL },
+ { "plymouth", no_argument, NULL, ARG_PLYMOUTH },
+ { "console", no_argument, NULL, ARG_CONSOLE },
+ { NULL, 0, NULL, 0 }
+ };
+
+ int c;
+
+ assert(argc >= 0);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
+
+ switch (c) {
+
+ case 'h':
+ help();
+ return 0;
+
+ case ARG_VERSION:
+ puts(PACKAGE_STRING);
+ puts(SYSTEMD_FEATURES);
+ return 0;
+
+ case ARG_LIST:
+ arg_action = ACTION_LIST;
+ break;
+
+ case ARG_QUERY:
+ arg_action = ACTION_QUERY;
+ break;
+
+ case ARG_WATCH:
+ arg_action = ACTION_WATCH;
+ break;
+
+ case ARG_WALL:
+ arg_action = ACTION_WALL;
+ break;
+
+ case ARG_PLYMOUTH:
+ arg_plymouth = true;
+ break;
+
+ case ARG_CONSOLE:
+ arg_console = true;
+ break;
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ log_error("Unknown option code %c", c);
+ return -EINVAL;
+ }
+ }
+
+ if (optind != argc) {
+ help();
+ return -EINVAL;
+ }
+
+ return 1;
+}
+
+int main(int argc, char *argv[]) {
+ int r;
+
+ log_set_target(LOG_TARGET_AUTO);
+ log_parse_environment();
+ log_open();
+
+ umask(0022);
+
+ if ((r = parse_argv(argc, argv)) <= 0)
+ goto finish;
+
+ if (arg_console) {
+ setsid();
+ release_terminal();
+ }
+
+ if (arg_action == ACTION_WATCH ||
+ arg_action == ACTION_WALL)
+ r = watch_passwords();
+ else
+ r = show_passwords();
+
+ if (r < 0)
+ log_error("Error: %s", strerror(-r));
+
+finish:
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/src/udev/accelerometer/accelerometer.c b/src/udev/accelerometer/accelerometer.c
new file mode 100644
index 0000000000..e611b48a42
--- /dev/null
+++ b/src/udev/accelerometer/accelerometer.c
@@ -0,0 +1,342 @@
+/*
+ * accelerometer - exports device orientation through property
+ *
+ * When an "change" event is received on an accelerometer,
+ * open its device node, and from the value, as well as the previous
+ * value of the property, calculate the device's new orientation,
+ * and export it as ID_INPUT_ACCELEROMETER_ORIENTATION.
+ *
+ * Possible values are:
+ * undefined
+ * * normal
+ * * bottom-up
+ * * left-up
+ * * right-up
+ *
+ * The property will be persistent across sessions, and the new
+ * orientations can be deducted from the previous one (it allows
+ * for a threshold for switching between opposite ends of the
+ * orientation).
+ *
+ * Copyright (C) 2011 Red Hat, Inc.
+ * Author:
+ * Bastien Nocera <hadess@hadess.net>
+ *
+ * orientation_calc() from the sensorfw package
+ * Copyright (C) 2009-2010 Nokia Corporation
+ * Authors:
+ * Üstün Ergenoglu <ext-ustun.ergenoglu@nokia.com>
+ * Timo Rongas <ext-timo.2.rongas@nokia.com>
+ * Lihan Guo <lihan.guo@digia.com>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+#include <stdio.h>
+#include <string.h>
+#include <stdbool.h>
+#include <math.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <getopt.h>
+#include <limits.h>
+#include <linux/limits.h>
+#include <linux/input.h>
+
+#include "libudev.h"
+#include "libudev-private.h"
+
+/* we must use this kernel-compatible implementation */
+#define BITS_PER_LONG (sizeof(unsigned long) * 8)
+#define NBITS(x) ((((x)-1)/BITS_PER_LONG)+1)
+#define OFF(x) ((x)%BITS_PER_LONG)
+#define BIT(x) (1UL<<OFF(x))
+#define LONG(x) ((x)/BITS_PER_LONG)
+#define test_bit(bit, array) ((array[LONG(bit)] >> OFF(bit)) & 1)
+
+static int debug = 0;
+
+static void log_fn(struct udev *udev, int priority,
+ const char *file, int line, const char *fn,
+ const char *format, va_list args)
+{
+ if (debug) {
+ fprintf(stderr, "%s: ", fn);
+ vfprintf(stderr, format, args);
+ } else {
+ vsyslog(priority, format, args);
+ }
+}
+
+typedef enum {
+ ORIENTATION_UNDEFINED,
+ ORIENTATION_NORMAL,
+ ORIENTATION_BOTTOM_UP,
+ ORIENTATION_LEFT_UP,
+ ORIENTATION_RIGHT_UP
+} OrientationUp;
+
+static const char *orientations[] = {
+ "undefined",
+ "normal",
+ "bottom-up",
+ "left-up",
+ "right-up",
+ NULL
+};
+
+#define ORIENTATION_UP_UP ORIENTATION_NORMAL
+
+#define DEFAULT_THRESHOLD 250
+#define RADIANS_TO_DEGREES 180.0/M_PI
+#define SAME_AXIS_LIMIT 5
+
+#define THRESHOLD_LANDSCAPE 25
+#define THRESHOLD_PORTRAIT 20
+
+static const char *
+orientation_to_string (OrientationUp o)
+{
+ return orientations[o];
+}
+
+static OrientationUp
+string_to_orientation (const char *orientation)
+{
+ int i;
+
+ if (orientation == NULL)
+ return ORIENTATION_UNDEFINED;
+ for (i = 0; orientations[i] != NULL; i++) {
+ if (streq (orientation, orientations[i]))
+ return i;
+ }
+ return ORIENTATION_UNDEFINED;
+}
+
+static OrientationUp
+orientation_calc (OrientationUp prev,
+ int x, int y, int z)
+{
+ int rotation;
+ OrientationUp ret = prev;
+
+ /* Portrait check */
+ rotation = round(atan((double) x / sqrt(y * y + z * z)) * RADIANS_TO_DEGREES);
+
+ if (abs(rotation) > THRESHOLD_PORTRAIT) {
+ ret = (rotation < 0) ? ORIENTATION_LEFT_UP : ORIENTATION_RIGHT_UP;
+
+ /* Some threshold to switching between portrait modes */
+ if (prev == ORIENTATION_LEFT_UP || prev == ORIENTATION_RIGHT_UP) {
+ if (abs(rotation) < SAME_AXIS_LIMIT) {
+ ret = prev;
+ }
+ }
+
+ } else {
+ /* Landscape check */
+ rotation = round(atan((double) y / sqrt(x * x + z * z)) * RADIANS_TO_DEGREES);
+
+ if (abs(rotation) > THRESHOLD_LANDSCAPE) {
+ ret = (rotation < 0) ? ORIENTATION_BOTTOM_UP : ORIENTATION_NORMAL;
+
+ /* Some threshold to switching between landscape modes */
+ if (prev == ORIENTATION_BOTTOM_UP || prev == ORIENTATION_NORMAL) {
+ if (abs(rotation) < SAME_AXIS_LIMIT) {
+ ret = prev;
+ }
+ }
+ }
+ }
+
+ return ret;
+}
+
+static OrientationUp
+get_prev_orientation(struct udev_device *dev)
+{
+ const char *value;
+
+ value = udev_device_get_property_value(dev, "ID_INPUT_ACCELEROMETER_ORIENTATION");
+ if (value == NULL)
+ return ORIENTATION_UNDEFINED;
+ return string_to_orientation(value);
+}
+
+#define SET_AXIS(axis, code_) if (ev[i].code == code_) { if (got_##axis == 0) { axis = ev[i].value; got_##axis = true; } }
+
+/* accelerometers */
+static void test_orientation(struct udev *udev,
+ struct udev_device *dev,
+ const char *devpath)
+{
+ OrientationUp old, new;
+ _cleanup_close_ int fd = -1;
+ struct input_event ev[64];
+ bool got_syn = false;
+ bool got_x = false, got_y = false, got_z = false;
+ int x = 0, y = 0, z = 0;
+ char text[64];
+
+ old = get_prev_orientation(dev);
+
+ fd = open(devpath, O_RDONLY);
+ if (fd < 0)
+ return;
+
+ while (1) {
+ int i, r;
+
+ r = read(fd, ev, sizeof(struct input_event) * 64);
+
+ if (r < (int) sizeof(struct input_event))
+ return;
+
+ for (i = 0; i < r / (int) sizeof(struct input_event); i++) {
+ if (got_syn) {
+ if (ev[i].type == EV_ABS) {
+ SET_AXIS(x, ABS_X);
+ SET_AXIS(y, ABS_Y);
+ SET_AXIS(z, ABS_Z);
+ }
+ }
+ if (ev[i].type == EV_SYN && ev[i].code == SYN_REPORT)
+ got_syn = true;
+ if (got_x && got_y && got_z)
+ goto read_dev;
+ }
+ }
+
+read_dev:
+ new = orientation_calc(old, x, y, z);
+ snprintf(text, sizeof(text),
+ "ID_INPUT_ACCELEROMETER_ORIENTATION=%s", orientation_to_string(new));
+ puts(text);
+}
+
+static void help(void)
+{
+ printf("Usage: accelerometer [options] <device path>\n"
+ " --debug debug to stderr\n"
+ " --help print this help text\n\n");
+}
+
+int main (int argc, char** argv)
+{
+ struct udev *udev;
+ struct udev_device *dev;
+
+ static const struct option options[] = {
+ { "debug", no_argument, NULL, 'd' },
+ { "help", no_argument, NULL, 'h' },
+ {}
+ };
+
+ char devpath[PATH_MAX];
+ char *devnode;
+ struct udev_enumerate *enumerate;
+ struct udev_list_entry *list_entry;
+
+ udev = udev_new();
+ if (udev == NULL)
+ return 1;
+
+ log_open();
+ udev_set_log_fn(udev, log_fn);
+
+ /* CLI argument parsing */
+ while (1) {
+ int option;
+
+ option = getopt_long(argc, argv, "dxh", options, NULL);
+ if (option == -1)
+ break;
+
+ switch (option) {
+ case 'd':
+ debug = 1;
+ log_set_max_level(LOG_DEBUG);
+ udev_set_log_priority(udev, LOG_DEBUG);
+ break;
+ case 'h':
+ help();
+ exit(0);
+ default:
+ exit(1);
+ }
+ }
+
+ if (argv[optind] == NULL) {
+ help();
+ exit(1);
+ }
+
+ /* get the device */
+ snprintf(devpath, sizeof(devpath), "/sys/%s", argv[optind]);
+ dev = udev_device_new_from_syspath(udev, devpath);
+ if (dev == NULL) {
+ fprintf(stderr, "unable to access '%s'\n", devpath);
+ return 1;
+ }
+
+ /* Get the children devices and find the devnode */
+ devnode = NULL;
+ enumerate = udev_enumerate_new(udev);
+ udev_enumerate_add_match_parent(enumerate, dev);
+ udev_enumerate_scan_devices(enumerate);
+ udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(enumerate)) {
+ struct udev_device *device;
+ const char *node;
+
+ device = udev_device_new_from_syspath(udev_enumerate_get_udev(enumerate),
+ udev_list_entry_get_name(list_entry));
+ if (device == NULL)
+ continue;
+ /* Already found it */
+ if (devnode != NULL) {
+ udev_device_unref(device);
+ continue;
+ }
+
+ node = udev_device_get_devnode(device);
+ if (node == NULL) {
+ udev_device_unref(device);
+ continue;
+ }
+ /* Use the event sub-device */
+ if (strstr(node, "/event") == NULL) {
+ udev_device_unref(device);
+ continue;
+ }
+
+ devnode = strdup(node);
+ udev_device_unref(device);
+ }
+
+ if (devnode == NULL) {
+ fprintf(stderr, "unable to get device node for '%s'\n", devpath);
+ return 0;
+ }
+
+ log_debug("opening accelerometer device %s\n", devnode);
+ test_orientation(udev, dev, devnode);
+ free(devnode);
+ log_close();
+ return 0;
+}
diff --git a/src/udev/ata_id/ata_id.c b/src/udev/ata_id/ata_id.c
new file mode 100644
index 0000000000..68a06b93b8
--- /dev/null
+++ b/src/udev/ata_id/ata_id.c
@@ -0,0 +1,690 @@
+/*
+ * ata_id - reads product/serial number from ATA drives
+ *
+ * Copyright (C) 2005-2008 Kay Sievers <kay@vrfy.org>
+ * Copyright (C) 2009 Lennart Poettering <lennart@poettering.net>
+ * Copyright (C) 2009-2010 David Zeuthen <zeuthen@gmail.com>
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <ctype.h>
+#include <string.h>
+#include <errno.h>
+#include <getopt.h>
+#include <scsi/scsi.h>
+#include <scsi/sg.h>
+#include <scsi/scsi_ioctl.h>
+#include <sys/ioctl.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <linux/types.h>
+#include <linux/hdreg.h>
+#include <linux/fs.h>
+#include <linux/cdrom.h>
+#include <linux/bsg.h>
+#include <arpa/inet.h>
+
+#include "libudev.h"
+#include "libudev-private.h"
+#include "log.h"
+
+#define COMMAND_TIMEOUT_MSEC (30 * 1000)
+
+static int disk_scsi_inquiry_command(int fd,
+ void *buf,
+ size_t buf_len)
+{
+ uint8_t cdb[6] = {
+ /*
+ * INQUIRY, see SPC-4 section 6.4
+ */
+ [0] = 0x12, /* OPERATION CODE: INQUIRY */
+ [3] = (buf_len >> 8), /* ALLOCATION LENGTH */
+ [4] = (buf_len & 0xff),
+ };
+ uint8_t sense[32] = {};
+ struct sg_io_v4 io_v4 = {
+ .guard = 'Q',
+ .protocol = BSG_PROTOCOL_SCSI,
+ .subprotocol = BSG_SUB_PROTOCOL_SCSI_CMD,
+ .request_len = sizeof(cdb),
+ .request = (uintptr_t) cdb,
+ .max_response_len = sizeof(sense),
+ .response = (uintptr_t) sense,
+ .din_xfer_len = buf_len,
+ .din_xferp = (uintptr_t) buf,
+ .timeout = COMMAND_TIMEOUT_MSEC,
+ };
+ int ret;
+
+ ret = ioctl(fd, SG_IO, &io_v4);
+ if (ret != 0) {
+ /* could be that the driver doesn't do version 4, try version 3 */
+ if (errno == EINVAL) {
+ struct sg_io_hdr io_hdr = {
+ .interface_id = 'S',
+ .cmdp = (unsigned char*) cdb,
+ .cmd_len = sizeof (cdb),
+ .dxferp = buf,
+ .dxfer_len = buf_len,
+ .sbp = sense,
+ .mx_sb_len = sizeof(sense),
+ .dxfer_direction = SG_DXFER_FROM_DEV,
+ .timeout = COMMAND_TIMEOUT_MSEC,
+ };
+
+ ret = ioctl(fd, SG_IO, &io_hdr);
+ if (ret != 0)
+ return ret;
+
+ /* even if the ioctl succeeds, we need to check the return value */
+ if (!(io_hdr.status == 0 &&
+ io_hdr.host_status == 0 &&
+ io_hdr.driver_status == 0)) {
+ errno = EIO;
+ return -1;
+ }
+ } else
+ return ret;
+ }
+
+ /* even if the ioctl succeeds, we need to check the return value */
+ if (!(io_v4.device_status == 0 &&
+ io_v4.transport_status == 0 &&
+ io_v4.driver_status == 0)) {
+ errno = EIO;
+ return -1;
+ }
+
+ return 0;
+}
+
+static int disk_identify_command(int fd,
+ void *buf,
+ size_t buf_len)
+{
+ uint8_t cdb[12] = {
+ /*
+ * ATA Pass-Through 12 byte command, as described in
+ *
+ * T10 04-262r8 ATA Command Pass-Through
+ *
+ * from http://www.t10.org/ftp/t10/document.04/04-262r8.pdf
+ */
+ [0] = 0xa1, /* OPERATION CODE: 12 byte pass through */
+ [1] = 4 << 1, /* PROTOCOL: PIO Data-in */
+ [2] = 0x2e, /* OFF_LINE=0, CK_COND=1, T_DIR=1, BYT_BLOK=1, T_LENGTH=2 */
+ [3] = 0, /* FEATURES */
+ [4] = 1, /* SECTORS */
+ [5] = 0, /* LBA LOW */
+ [6] = 0, /* LBA MID */
+ [7] = 0, /* LBA HIGH */
+ [8] = 0 & 0x4F, /* SELECT */
+ [9] = 0xEC, /* Command: ATA IDENTIFY DEVICE */
+ };
+ uint8_t sense[32] = {};
+ uint8_t *desc = sense + 8;
+ struct sg_io_v4 io_v4 = {
+ .guard = 'Q',
+ .protocol = BSG_PROTOCOL_SCSI,
+ .subprotocol = BSG_SUB_PROTOCOL_SCSI_CMD,
+ .request_len = sizeof(cdb),
+ .request = (uintptr_t) cdb,
+ .max_response_len = sizeof(sense),
+ .response = (uintptr_t) sense,
+ .din_xfer_len = buf_len,
+ .din_xferp = (uintptr_t) buf,
+ .timeout = COMMAND_TIMEOUT_MSEC,
+ };
+ int ret;
+
+ ret = ioctl(fd, SG_IO, &io_v4);
+ if (ret != 0) {
+ /* could be that the driver doesn't do version 4, try version 3 */
+ if (errno == EINVAL) {
+ struct sg_io_hdr io_hdr = {
+ .interface_id = 'S',
+ .cmdp = (unsigned char*) cdb,
+ .cmd_len = sizeof (cdb),
+ .dxferp = buf,
+ .dxfer_len = buf_len,
+ .sbp = sense,
+ .mx_sb_len = sizeof (sense),
+ .dxfer_direction = SG_DXFER_FROM_DEV,
+ .timeout = COMMAND_TIMEOUT_MSEC,
+ };
+
+ ret = ioctl(fd, SG_IO, &io_hdr);
+ if (ret != 0)
+ return ret;
+ } else
+ return ret;
+ }
+
+ if (!(sense[0] == 0x72 && desc[0] == 0x9 && desc[1] == 0x0c)) {
+ errno = EIO;
+ return -1;
+ }
+
+ return 0;
+}
+
+static int disk_identify_packet_device_command(int fd,
+ void *buf,
+ size_t buf_len)
+{
+ uint8_t cdb[16] = {
+ /*
+ * ATA Pass-Through 16 byte command, as described in
+ *
+ * T10 04-262r8 ATA Command Pass-Through
+ *
+ * from http://www.t10.org/ftp/t10/document.04/04-262r8.pdf
+ */
+ [0] = 0x85, /* OPERATION CODE: 16 byte pass through */
+ [1] = 4 << 1, /* PROTOCOL: PIO Data-in */
+ [2] = 0x2e, /* OFF_LINE=0, CK_COND=1, T_DIR=1, BYT_BLOK=1, T_LENGTH=2 */
+ [3] = 0, /* FEATURES */
+ [4] = 0, /* FEATURES */
+ [5] = 0, /* SECTORS */
+ [6] = 1, /* SECTORS */
+ [7] = 0, /* LBA LOW */
+ [8] = 0, /* LBA LOW */
+ [9] = 0, /* LBA MID */
+ [10] = 0, /* LBA MID */
+ [11] = 0, /* LBA HIGH */
+ [12] = 0, /* LBA HIGH */
+ [13] = 0, /* DEVICE */
+ [14] = 0xA1, /* Command: ATA IDENTIFY PACKET DEVICE */
+ [15] = 0, /* CONTROL */
+ };
+ uint8_t sense[32] = {};
+ uint8_t *desc = sense + 8;
+ struct sg_io_v4 io_v4 = {
+ .guard = 'Q',
+ .protocol = BSG_PROTOCOL_SCSI,
+ .subprotocol = BSG_SUB_PROTOCOL_SCSI_CMD,
+ .request_len = sizeof (cdb),
+ .request = (uintptr_t) cdb,
+ .max_response_len = sizeof (sense),
+ .response = (uintptr_t) sense,
+ .din_xfer_len = buf_len,
+ .din_xferp = (uintptr_t) buf,
+ .timeout = COMMAND_TIMEOUT_MSEC,
+ };
+ int ret;
+
+ ret = ioctl(fd, SG_IO, &io_v4);
+ if (ret != 0) {
+ /* could be that the driver doesn't do version 4, try version 3 */
+ if (errno == EINVAL) {
+ struct sg_io_hdr io_hdr = {
+ .interface_id = 'S',
+ .cmdp = (unsigned char*) cdb,
+ .cmd_len = sizeof (cdb),
+ .dxferp = buf,
+ .dxfer_len = buf_len,
+ .sbp = sense,
+ .mx_sb_len = sizeof (sense),
+ .dxfer_direction = SG_DXFER_FROM_DEV,
+ .timeout = COMMAND_TIMEOUT_MSEC,
+ };
+
+ ret = ioctl(fd, SG_IO, &io_hdr);
+ if (ret != 0)
+ return ret;
+ } else
+ return ret;
+ }
+
+ if (!(sense[0] == 0x72 && desc[0] == 0x9 && desc[1] == 0x0c)) {
+ errno = EIO;
+ return -1;
+ }
+
+ return 0;
+}
+
+/**
+ * disk_identify_get_string:
+ * @identify: A block of IDENTIFY data
+ * @offset_words: Offset of the string to get, in words.
+ * @dest: Destination buffer for the string.
+ * @dest_len: Length of destination buffer, in bytes.
+ *
+ * Copies the ATA string from @identify located at @offset_words into @dest.
+ */
+static void disk_identify_get_string(uint8_t identify[512],
+ unsigned int offset_words,
+ char *dest,
+ size_t dest_len)
+{
+ unsigned int c1;
+ unsigned int c2;
+
+ while (dest_len > 0) {
+ c1 = identify[offset_words * 2 + 1];
+ c2 = identify[offset_words * 2];
+ *dest = c1;
+ dest++;
+ *dest = c2;
+ dest++;
+ offset_words++;
+ dest_len -= 2;
+ }
+}
+
+static void disk_identify_fixup_string(uint8_t identify[512],
+ unsigned int offset_words,
+ size_t len)
+{
+ disk_identify_get_string(identify, offset_words,
+ (char *) identify + offset_words * 2, len);
+}
+
+static void disk_identify_fixup_uint16 (uint8_t identify[512], unsigned int offset_words)
+{
+ uint16_t *p;
+
+ p = (uint16_t *) identify;
+ p[offset_words] = le16toh (p[offset_words]);
+}
+
+/**
+ * disk_identify:
+ * @udev: The libudev context.
+ * @fd: File descriptor for the block device.
+ * @out_identify: Return location for IDENTIFY data.
+ * @out_is_packet_device: Return location for whether returned data is from a IDENTIFY PACKET DEVICE.
+ *
+ * Sends the IDENTIFY DEVICE or IDENTIFY PACKET DEVICE command to the
+ * device represented by @fd. If successful, then the result will be
+ * copied into @out_identify and @out_is_packet_device.
+ *
+ * This routine is based on code from libatasmart, Copyright 2008
+ * Lennart Poettering, LGPL v2.1.
+ *
+ * Returns: 0 if the data was successfully obtained, otherwise
+ * non-zero with errno set.
+ */
+static int disk_identify(struct udev *udev,
+ int fd,
+ uint8_t out_identify[512],
+ int *out_is_packet_device)
+{
+ int ret;
+ uint8_t inquiry_buf[36];
+ int peripheral_device_type;
+ int all_nul_bytes;
+ int n;
+ int is_packet_device = 0;
+
+ /* init results */
+ memzero(out_identify, 512);
+
+ /* If we were to use ATA PASS_THROUGH (12) on an ATAPI device
+ * we could accidentally blank media. This is because MMC's BLANK
+ * command has the same op-code (0x61).
+ *
+ * To prevent this from happening we bail out if the device
+ * isn't a Direct Access Block Device, e.g. SCSI type 0x00
+ * (CD/DVD devices are type 0x05). So we send a SCSI INQUIRY
+ * command first... libata is handling this via its SCSI
+ * emulation layer.
+ *
+ * This also ensures that we're actually dealing with a device
+ * that understands SCSI commands.
+ *
+ * (Yes, it is a bit perverse that we're tunneling the ATA
+ * command through SCSI and relying on the ATA driver
+ * emulating SCSI well-enough...)
+ *
+ * (See commit 160b069c25690bfb0c785994c7c3710289179107 for
+ * the original bug-fix and see http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=556635
+ * for the original bug-report.)
+ */
+ ret = disk_scsi_inquiry_command (fd, inquiry_buf, sizeof (inquiry_buf));
+ if (ret != 0)
+ goto out;
+
+ /* SPC-4, section 6.4.2: Standard INQUIRY data */
+ peripheral_device_type = inquiry_buf[0] & 0x1f;
+ if (peripheral_device_type == 0x05)
+ {
+ is_packet_device = 1;
+ ret = disk_identify_packet_device_command(fd, out_identify, 512);
+ goto check_nul_bytes;
+ }
+ if (peripheral_device_type != 0x00) {
+ ret = -1;
+ errno = EIO;
+ goto out;
+ }
+
+ /* OK, now issue the IDENTIFY DEVICE command */
+ ret = disk_identify_command(fd, out_identify, 512);
+ if (ret != 0)
+ goto out;
+
+ check_nul_bytes:
+ /* Check if IDENTIFY data is all NUL bytes - if so, bail */
+ all_nul_bytes = 1;
+ for (n = 0; n < 512; n++) {
+ if (out_identify[n] != '\0') {
+ all_nul_bytes = 0;
+ break;
+ }
+ }
+
+ if (all_nul_bytes) {
+ ret = -1;
+ errno = EIO;
+ goto out;
+ }
+
+out:
+ if (out_is_packet_device != NULL)
+ *out_is_packet_device = is_packet_device;
+ return ret;
+}
+
+static void log_fn(struct udev *udev, int priority,
+ const char *file, int line, const char *fn,
+ const char *format, va_list args)
+{
+ vsyslog(priority, format, args);
+}
+
+int main(int argc, char *argv[])
+{
+ struct udev *udev;
+ struct hd_driveid id;
+ uint8_t identify[512];
+ uint16_t *identify_words;
+ char model[41];
+ char model_enc[256];
+ char serial[21];
+ char revision[9];
+ const char *node = NULL;
+ int export = 0;
+ int fd;
+ uint16_t word;
+ int rc = 0;
+ int is_packet_device = 0;
+ static const struct option options[] = {
+ { "export", no_argument, NULL, 'x' },
+ { "help", no_argument, NULL, 'h' },
+ {}
+ };
+
+ udev = udev_new();
+ if (udev == NULL)
+ goto exit;
+
+ log_open();
+ udev_set_log_fn(udev, log_fn);
+
+ while (1) {
+ int option;
+
+ option = getopt_long(argc, argv, "xh", options, NULL);
+ if (option == -1)
+ break;
+
+ switch (option) {
+ case 'x':
+ export = 1;
+ break;
+ case 'h':
+ printf("Usage: ata_id [--export] [--help] <device>\n"
+ " --export print values as environment keys\n"
+ " --help print this help text\n\n");
+ goto exit;
+ }
+ }
+
+ node = argv[optind];
+ if (node == NULL) {
+ log_error("no node specified\n");
+ rc = 1;
+ goto exit;
+ }
+
+ fd = open(node, O_RDONLY|O_NONBLOCK);
+ if (fd < 0) {
+ log_error("unable to open '%s'\n", node);
+ rc = 1;
+ goto exit;
+ }
+
+ if (disk_identify(udev, fd, identify, &is_packet_device) == 0) {
+ /*
+ * fix up only the fields from the IDENTIFY data that we are going to
+ * use and copy it into the hd_driveid struct for convenience
+ */
+ disk_identify_fixup_string(identify, 10, 20); /* serial */
+ disk_identify_fixup_string(identify, 23, 8); /* fwrev */
+ disk_identify_fixup_string(identify, 27, 40); /* model */
+ disk_identify_fixup_uint16(identify, 0); /* configuration */
+ disk_identify_fixup_uint16(identify, 75); /* queue depth */
+ disk_identify_fixup_uint16(identify, 75); /* SATA capabilities */
+ disk_identify_fixup_uint16(identify, 82); /* command set supported */
+ disk_identify_fixup_uint16(identify, 83); /* command set supported */
+ disk_identify_fixup_uint16(identify, 84); /* command set supported */
+ disk_identify_fixup_uint16(identify, 85); /* command set supported */
+ disk_identify_fixup_uint16(identify, 86); /* command set supported */
+ disk_identify_fixup_uint16(identify, 87); /* command set supported */
+ disk_identify_fixup_uint16(identify, 89); /* time required for SECURITY ERASE UNIT */
+ disk_identify_fixup_uint16(identify, 90); /* time required for enhanced SECURITY ERASE UNIT */
+ disk_identify_fixup_uint16(identify, 91); /* current APM values */
+ disk_identify_fixup_uint16(identify, 94); /* current AAM value */
+ disk_identify_fixup_uint16(identify, 128); /* device lock function */
+ disk_identify_fixup_uint16(identify, 217); /* nominal media rotation rate */
+ memcpy(&id, identify, sizeof id);
+ } else {
+ /* If this fails, then try HDIO_GET_IDENTITY */
+ if (ioctl(fd, HDIO_GET_IDENTITY, &id) != 0) {
+ log_info("HDIO_GET_IDENTITY failed for '%s': %m\n", node);
+ rc = 2;
+ goto close;
+ }
+ }
+ identify_words = (uint16_t *) identify;
+
+ memcpy (model, id.model, 40);
+ model[40] = '\0';
+ udev_util_encode_string(model, model_enc, sizeof(model_enc));
+ util_replace_whitespace((char *) id.model, model, 40);
+ util_replace_chars(model, NULL);
+ util_replace_whitespace((char *) id.serial_no, serial, 20);
+ util_replace_chars(serial, NULL);
+ util_replace_whitespace((char *) id.fw_rev, revision, 8);
+ util_replace_chars(revision, NULL);
+
+ if (export) {
+ /* Set this to convey the disk speaks the ATA protocol */
+ printf("ID_ATA=1\n");
+
+ if ((id.config >> 8) & 0x80) {
+ /* This is an ATAPI device */
+ switch ((id.config >> 8) & 0x1f) {
+ case 0:
+ printf("ID_TYPE=cd\n");
+ break;
+ case 1:
+ printf("ID_TYPE=tape\n");
+ break;
+ case 5:
+ printf("ID_TYPE=cd\n");
+ break;
+ case 7:
+ printf("ID_TYPE=optical\n");
+ break;
+ default:
+ printf("ID_TYPE=generic\n");
+ break;
+ }
+ } else {
+ printf("ID_TYPE=disk\n");
+ }
+ printf("ID_BUS=ata\n");
+ printf("ID_MODEL=%s\n", model);
+ printf("ID_MODEL_ENC=%s\n", model_enc);
+ printf("ID_REVISION=%s\n", revision);
+ if (serial[0] != '\0') {
+ printf("ID_SERIAL=%s_%s\n", model, serial);
+ printf("ID_SERIAL_SHORT=%s\n", serial);
+ } else {
+ printf("ID_SERIAL=%s\n", model);
+ }
+
+ if (id.command_set_1 & (1<<5)) {
+ printf ("ID_ATA_WRITE_CACHE=1\n");
+ printf ("ID_ATA_WRITE_CACHE_ENABLED=%d\n", (id.cfs_enable_1 & (1<<5)) ? 1 : 0);
+ }
+ if (id.command_set_1 & (1<<10)) {
+ printf("ID_ATA_FEATURE_SET_HPA=1\n");
+ printf("ID_ATA_FEATURE_SET_HPA_ENABLED=%d\n", (id.cfs_enable_1 & (1<<10)) ? 1 : 0);
+
+ /*
+ * TODO: use the READ NATIVE MAX ADDRESS command to get the native max address
+ * so it is easy to check whether the protected area is in use.
+ */
+ }
+ if (id.command_set_1 & (1<<3)) {
+ printf("ID_ATA_FEATURE_SET_PM=1\n");
+ printf("ID_ATA_FEATURE_SET_PM_ENABLED=%d\n", (id.cfs_enable_1 & (1<<3)) ? 1 : 0);
+ }
+ if (id.command_set_1 & (1<<1)) {
+ printf("ID_ATA_FEATURE_SET_SECURITY=1\n");
+ printf("ID_ATA_FEATURE_SET_SECURITY_ENABLED=%d\n", (id.cfs_enable_1 & (1<<1)) ? 1 : 0);
+ printf("ID_ATA_FEATURE_SET_SECURITY_ERASE_UNIT_MIN=%d\n", id.trseuc * 2);
+ if ((id.cfs_enable_1 & (1<<1))) /* enabled */ {
+ if (id.dlf & (1<<8))
+ printf("ID_ATA_FEATURE_SET_SECURITY_LEVEL=maximum\n");
+ else
+ printf("ID_ATA_FEATURE_SET_SECURITY_LEVEL=high\n");
+ }
+ if (id.dlf & (1<<5))
+ printf("ID_ATA_FEATURE_SET_SECURITY_ENHANCED_ERASE_UNIT_MIN=%d\n", id.trsEuc * 2);
+ if (id.dlf & (1<<4))
+ printf("ID_ATA_FEATURE_SET_SECURITY_EXPIRE=1\n");
+ if (id.dlf & (1<<3))
+ printf("ID_ATA_FEATURE_SET_SECURITY_FROZEN=1\n");
+ if (id.dlf & (1<<2))
+ printf("ID_ATA_FEATURE_SET_SECURITY_LOCKED=1\n");
+ }
+ if (id.command_set_1 & (1<<0)) {
+ printf("ID_ATA_FEATURE_SET_SMART=1\n");
+ printf("ID_ATA_FEATURE_SET_SMART_ENABLED=%d\n", (id.cfs_enable_1 & (1<<0)) ? 1 : 0);
+ }
+ if (id.command_set_2 & (1<<9)) {
+ printf("ID_ATA_FEATURE_SET_AAM=1\n");
+ printf("ID_ATA_FEATURE_SET_AAM_ENABLED=%d\n", (id.cfs_enable_2 & (1<<9)) ? 1 : 0);
+ printf("ID_ATA_FEATURE_SET_AAM_VENDOR_RECOMMENDED_VALUE=%d\n", id.acoustic >> 8);
+ printf("ID_ATA_FEATURE_SET_AAM_CURRENT_VALUE=%d\n", id.acoustic & 0xff);
+ }
+ if (id.command_set_2 & (1<<5)) {
+ printf("ID_ATA_FEATURE_SET_PUIS=1\n");
+ printf("ID_ATA_FEATURE_SET_PUIS_ENABLED=%d\n", (id.cfs_enable_2 & (1<<5)) ? 1 : 0);
+ }
+ if (id.command_set_2 & (1<<3)) {
+ printf("ID_ATA_FEATURE_SET_APM=1\n");
+ printf("ID_ATA_FEATURE_SET_APM_ENABLED=%d\n", (id.cfs_enable_2 & (1<<3)) ? 1 : 0);
+ if ((id.cfs_enable_2 & (1<<3)))
+ printf("ID_ATA_FEATURE_SET_APM_CURRENT_VALUE=%d\n", id.CurAPMvalues & 0xff);
+ }
+ if (id.command_set_2 & (1<<0))
+ printf("ID_ATA_DOWNLOAD_MICROCODE=1\n");
+
+ /*
+ * Word 76 indicates the capabilities of a SATA device. A PATA device shall set
+ * word 76 to 0000h or FFFFh. If word 76 is set to 0000h or FFFFh, then
+ * the device does not claim compliance with the Serial ATA specification and words
+ * 76 through 79 are not valid and shall be ignored.
+ */
+ word = *((uint16_t *) identify + 76);
+ if (word != 0x0000 && word != 0xffff) {
+ printf("ID_ATA_SATA=1\n");
+ /*
+ * If bit 2 of word 76 is set to one, then the device supports the Gen2
+ * signaling rate of 3.0 Gb/s (see SATA 2.6).
+ *
+ * If bit 1 of word 76 is set to one, then the device supports the Gen1
+ * signaling rate of 1.5 Gb/s (see SATA 2.6).
+ */
+ if (word & (1<<2))
+ printf("ID_ATA_SATA_SIGNAL_RATE_GEN2=1\n");
+ if (word & (1<<1))
+ printf("ID_ATA_SATA_SIGNAL_RATE_GEN1=1\n");
+ }
+
+ /* Word 217 indicates the nominal media rotation rate of the device */
+ word = *((uint16_t *) identify + 217);
+ if (word != 0x0000) {
+ if (word == 0x0001) {
+ printf ("ID_ATA_ROTATION_RATE_RPM=0\n"); /* non-rotating e.g. SSD */
+ } else if (word >= 0x0401 && word <= 0xfffe) {
+ printf ("ID_ATA_ROTATION_RATE_RPM=%d\n", word);
+ }
+ }
+
+ /*
+ * Words 108-111 contain a mandatory World Wide Name (WWN) in the NAA IEEE Registered identifier
+ * format. Word 108 bits (15:12) shall contain 5h, indicating that the naming authority is IEEE.
+ * All other values are reserved.
+ */
+ word = *((uint16_t *) identify + 108);
+ if ((word & 0xf000) == 0x5000) {
+ uint64_t wwwn;
+
+ wwwn = *((uint16_t *) identify + 108);
+ wwwn <<= 16;
+ wwwn |= *((uint16_t *) identify + 109);
+ wwwn <<= 16;
+ wwwn |= *((uint16_t *) identify + 110);
+ wwwn <<= 16;
+ wwwn |= *((uint16_t *) identify + 111);
+ printf("ID_WWN=0x%llx\n", (unsigned long long int) wwwn);
+ /* ATA devices have no vendor extension */
+ printf("ID_WWN_WITH_EXTENSION=0x%llx\n", (unsigned long long int) wwwn);
+ }
+
+ /* from Linux's include/linux/ata.h */
+ if (identify_words[0] == 0x848a || identify_words[0] == 0x844a) {
+ printf("ID_ATA_CFA=1\n");
+ } else {
+ if ((identify_words[83] & 0xc004) == 0x4004) {
+ printf("ID_ATA_CFA=1\n");
+ }
+ }
+ } else {
+ if (serial[0] != '\0')
+ printf("%s_%s\n", model, serial);
+ else
+ printf("%s\n", model);
+ }
+close:
+ close(fd);
+exit:
+ udev_unref(udev);
+ log_close();
+ return rc;
+}
diff --git a/src/udev/cdrom_id/cdrom_id.c b/src/udev/cdrom_id/cdrom_id.c
new file mode 100644
index 0000000000..1ad0459236
--- /dev/null
+++ b/src/udev/cdrom_id/cdrom_id.c
@@ -0,0 +1,1097 @@
+/*
+ * cdrom_id - optical drive and media information prober
+ *
+ * Copyright (C) 2008-2010 Kay Sievers <kay@vrfy.org>
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <stdio.h>
+#include <stddef.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <string.h>
+#include <limits.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <getopt.h>
+#include <time.h>
+#include <scsi/sg.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/ioctl.h>
+#include <linux/cdrom.h>
+
+#include "libudev.h"
+#include "libudev-private.h"
+
+static bool debug;
+
+static void log_fn(struct udev *udev, int priority,
+ const char *file, int line, const char *fn,
+ const char *format, va_list args)
+{
+ if (debug) {
+ fprintf(stderr, "%s: ", fn);
+ vfprintf(stderr, format, args);
+ } else {
+ vsyslog(priority, format, args);
+ }
+}
+
+/* device info */
+static unsigned int cd_cd_rom;
+static unsigned int cd_cd_r;
+static unsigned int cd_cd_rw;
+static unsigned int cd_dvd_rom;
+static unsigned int cd_dvd_r;
+static unsigned int cd_dvd_rw;
+static unsigned int cd_dvd_ram;
+static unsigned int cd_dvd_plus_r;
+static unsigned int cd_dvd_plus_rw;
+static unsigned int cd_dvd_plus_r_dl;
+static unsigned int cd_dvd_plus_rw_dl;
+static unsigned int cd_bd;
+static unsigned int cd_bd_r;
+static unsigned int cd_bd_re;
+static unsigned int cd_hddvd;
+static unsigned int cd_hddvd_r;
+static unsigned int cd_hddvd_rw;
+static unsigned int cd_mo;
+static unsigned int cd_mrw;
+static unsigned int cd_mrw_w;
+
+/* media info */
+static unsigned int cd_media;
+static unsigned int cd_media_cd_rom;
+static unsigned int cd_media_cd_r;
+static unsigned int cd_media_cd_rw;
+static unsigned int cd_media_dvd_rom;
+static unsigned int cd_media_dvd_r;
+static unsigned int cd_media_dvd_rw;
+static unsigned int cd_media_dvd_rw_ro; /* restricted overwrite mode */
+static unsigned int cd_media_dvd_rw_seq; /* sequential mode */
+static unsigned int cd_media_dvd_ram;
+static unsigned int cd_media_dvd_plus_r;
+static unsigned int cd_media_dvd_plus_rw;
+static unsigned int cd_media_dvd_plus_r_dl;
+static unsigned int cd_media_dvd_plus_rw_dl;
+static unsigned int cd_media_bd;
+static unsigned int cd_media_bd_r;
+static unsigned int cd_media_bd_re;
+static unsigned int cd_media_hddvd;
+static unsigned int cd_media_hddvd_r;
+static unsigned int cd_media_hddvd_rw;
+static unsigned int cd_media_mo;
+static unsigned int cd_media_mrw;
+static unsigned int cd_media_mrw_w;
+
+static const char *cd_media_state = NULL;
+static unsigned int cd_media_session_next;
+static unsigned int cd_media_session_count;
+static unsigned int cd_media_track_count;
+static unsigned int cd_media_track_count_data;
+static unsigned int cd_media_track_count_audio;
+static unsigned long long int cd_media_session_last_offset;
+
+#define ERRCODE(s) ((((s)[2] & 0x0F) << 16) | ((s)[12] << 8) | ((s)[13]))
+#define SK(errcode) (((errcode) >> 16) & 0xF)
+#define ASC(errcode) (((errcode) >> 8) & 0xFF)
+#define ASCQ(errcode) ((errcode) & 0xFF)
+
+static bool is_mounted(const char *device)
+{
+ struct stat statbuf;
+ FILE *fp;
+ int maj, min;
+ bool mounted = false;
+
+ if (stat(device, &statbuf) < 0)
+ return -ENODEV;
+
+ fp = fopen("/proc/self/mountinfo", "re");
+ if (fp == NULL)
+ return -ENOSYS;
+ while (fscanf(fp, "%*s %*s %i:%i %*[^\n]", &maj, &min) == 2) {
+ if (makedev(maj, min) == statbuf.st_rdev) {
+ mounted = true;
+ break;
+ }
+ }
+ fclose(fp);
+ return mounted;
+}
+
+static void info_scsi_cmd_err(struct udev *udev, const char *cmd, int err)
+{
+ if (err == -1) {
+ log_debug("%s failed\n", cmd);
+ return;
+ }
+ log_debug("%s failed with SK=%Xh/ASC=%02Xh/ACQ=%02Xh\n", cmd, SK(err), ASC(err), ASCQ(err));
+}
+
+struct scsi_cmd {
+ struct cdrom_generic_command cgc;
+ union {
+ struct request_sense s;
+ unsigned char u[18];
+ } _sense;
+ struct sg_io_hdr sg_io;
+};
+
+static void scsi_cmd_init(struct udev *udev, struct scsi_cmd *cmd)
+{
+ memset(cmd, 0x00, sizeof(struct scsi_cmd));
+ cmd->cgc.quiet = 1;
+ cmd->cgc.sense = &cmd->_sense.s;
+ cmd->sg_io.interface_id = 'S';
+ cmd->sg_io.mx_sb_len = sizeof(cmd->_sense);
+ cmd->sg_io.cmdp = cmd->cgc.cmd;
+ cmd->sg_io.sbp = cmd->_sense.u;
+ cmd->sg_io.flags = SG_FLAG_LUN_INHIBIT | SG_FLAG_DIRECT_IO;
+}
+
+static void scsi_cmd_set(struct udev *udev, struct scsi_cmd *cmd, size_t i, unsigned char arg)
+{
+ cmd->sg_io.cmd_len = i + 1;
+ cmd->cgc.cmd[i] = arg;
+}
+
+#define CHECK_CONDITION 0x01
+
+static int scsi_cmd_run(struct udev *udev, struct scsi_cmd *cmd, int fd, unsigned char *buf, size_t bufsize)
+{
+ int ret = 0;
+
+ if (bufsize > 0) {
+ cmd->sg_io.dxferp = buf;
+ cmd->sg_io.dxfer_len = bufsize;
+ cmd->sg_io.dxfer_direction = SG_DXFER_FROM_DEV;
+ } else {
+ cmd->sg_io.dxfer_direction = SG_DXFER_NONE;
+ }
+ if (ioctl(fd, SG_IO, &cmd->sg_io))
+ return -1;
+
+ if ((cmd->sg_io.info & SG_INFO_OK_MASK) != SG_INFO_OK) {
+ errno = EIO;
+ ret = -1;
+ if (cmd->sg_io.masked_status & CHECK_CONDITION) {
+ ret = ERRCODE(cmd->_sense.u);
+ if (ret == 0)
+ ret = -1;
+ }
+ }
+ return ret;
+}
+
+static int media_lock(struct udev *udev, int fd, bool lock)
+{
+ int err;
+
+ /* disable the kernel's lock logic */
+ err = ioctl(fd, CDROM_CLEAR_OPTIONS, CDO_LOCK);
+ if (err < 0)
+ log_debug("CDROM_CLEAR_OPTIONS, CDO_LOCK failed\n");
+
+ err = ioctl(fd, CDROM_LOCKDOOR, lock ? 1 : 0);
+ if (err < 0)
+ log_debug("CDROM_LOCKDOOR failed\n");
+
+ return err;
+}
+
+static int media_eject(struct udev *udev, int fd)
+{
+ struct scsi_cmd sc;
+ int err;
+
+ scsi_cmd_init(udev, &sc);
+ scsi_cmd_set(udev, &sc, 0, 0x1b);
+ scsi_cmd_set(udev, &sc, 4, 0x02);
+ scsi_cmd_set(udev, &sc, 5, 0);
+ err = scsi_cmd_run(udev, &sc, fd, NULL, 0);
+ if ((err != 0)) {
+ info_scsi_cmd_err(udev, "START_STOP_UNIT", err);
+ return -1;
+ }
+ return 0;
+}
+
+static int cd_capability_compat(struct udev *udev, int fd)
+{
+ int capability;
+
+ capability = ioctl(fd, CDROM_GET_CAPABILITY, NULL);
+ if (capability < 0) {
+ log_debug("CDROM_GET_CAPABILITY failed\n");
+ return -1;
+ }
+
+ if (capability & CDC_CD_R)
+ cd_cd_r = 1;
+ if (capability & CDC_CD_RW)
+ cd_cd_rw = 1;
+ if (capability & CDC_DVD)
+ cd_dvd_rom = 1;
+ if (capability & CDC_DVD_R)
+ cd_dvd_r = 1;
+ if (capability & CDC_DVD_RAM)
+ cd_dvd_ram = 1;
+ if (capability & CDC_MRW)
+ cd_mrw = 1;
+ if (capability & CDC_MRW_W)
+ cd_mrw_w = 1;
+ return 0;
+}
+
+static int cd_media_compat(struct udev *udev, int fd)
+{
+ if (ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT) != CDS_DISC_OK) {
+ log_debug("CDROM_DRIVE_STATUS != CDS_DISC_OK\n");
+ return -1;
+ }
+ cd_media = 1;
+ return 0;
+}
+
+static int cd_inquiry(struct udev *udev, int fd)
+{
+ struct scsi_cmd sc;
+ unsigned char inq[128];
+ int err;
+
+ scsi_cmd_init(udev, &sc);
+ scsi_cmd_set(udev, &sc, 0, 0x12);
+ scsi_cmd_set(udev, &sc, 4, 36);
+ scsi_cmd_set(udev, &sc, 5, 0);
+ err = scsi_cmd_run(udev, &sc, fd, inq, 36);
+ if ((err != 0)) {
+ info_scsi_cmd_err(udev, "INQUIRY", err);
+ return -1;
+ }
+
+ if ((inq[0] & 0x1F) != 5) {
+ log_debug("not an MMC unit\n");
+ return -1;
+ }
+
+ log_debug("INQUIRY: [%.8s][%.16s][%.4s]\n", inq + 8, inq + 16, inq + 32);
+ return 0;
+}
+
+static void feature_profile_media(struct udev *udev, int cur_profile)
+{
+ switch (cur_profile) {
+ case 0x03:
+ case 0x04:
+ case 0x05:
+ log_debug("profile 0x%02x \n", cur_profile);
+ cd_media = 1;
+ cd_media_mo = 1;
+ break;
+ case 0x08:
+ log_debug("profile 0x%02x media_cd_rom\n", cur_profile);
+ cd_media = 1;
+ cd_media_cd_rom = 1;
+ break;
+ case 0x09:
+ log_debug("profile 0x%02x media_cd_r\n", cur_profile);
+ cd_media = 1;
+ cd_media_cd_r = 1;
+ break;
+ case 0x0a:
+ log_debug("profile 0x%02x media_cd_rw\n", cur_profile);
+ cd_media = 1;
+ cd_media_cd_rw = 1;
+ break;
+ case 0x10:
+ log_debug("profile 0x%02x media_dvd_ro\n", cur_profile);
+ cd_media = 1;
+ cd_media_dvd_rom = 1;
+ break;
+ case 0x11:
+ log_debug("profile 0x%02x media_dvd_r\n", cur_profile);
+ cd_media = 1;
+ cd_media_dvd_r = 1;
+ break;
+ case 0x12:
+ log_debug("profile 0x%02x media_dvd_ram\n", cur_profile);
+ cd_media = 1;
+ cd_media_dvd_ram = 1;
+ break;
+ case 0x13:
+ log_debug("profile 0x%02x media_dvd_rw_ro\n", cur_profile);
+ cd_media = 1;
+ cd_media_dvd_rw = 1;
+ cd_media_dvd_rw_ro = 1;
+ break;
+ case 0x14:
+ log_debug("profile 0x%02x media_dvd_rw_seq\n", cur_profile);
+ cd_media = 1;
+ cd_media_dvd_rw = 1;
+ cd_media_dvd_rw_seq = 1;
+ break;
+ case 0x1B:
+ log_debug("profile 0x%02x media_dvd_plus_r\n", cur_profile);
+ cd_media = 1;
+ cd_media_dvd_plus_r = 1;
+ break;
+ case 0x1A:
+ log_debug("profile 0x%02x media_dvd_plus_rw\n", cur_profile);
+ cd_media = 1;
+ cd_media_dvd_plus_rw = 1;
+ break;
+ case 0x2A:
+ log_debug("profile 0x%02x media_dvd_plus_rw_dl\n", cur_profile);
+ cd_media = 1;
+ cd_media_dvd_plus_rw_dl = 1;
+ break;
+ case 0x2B:
+ log_debug("profile 0x%02x media_dvd_plus_r_dl\n", cur_profile);
+ cd_media = 1;
+ cd_media_dvd_plus_r_dl = 1;
+ break;
+ case 0x40:
+ log_debug("profile 0x%02x media_bd\n", cur_profile);
+ cd_media = 1;
+ cd_media_bd = 1;
+ break;
+ case 0x41:
+ case 0x42:
+ log_debug("profile 0x%02x media_bd_r\n", cur_profile);
+ cd_media = 1;
+ cd_media_bd_r = 1;
+ break;
+ case 0x43:
+ log_debug("profile 0x%02x media_bd_re\n", cur_profile);
+ cd_media = 1;
+ cd_media_bd_re = 1;
+ break;
+ case 0x50:
+ log_debug("profile 0x%02x media_hddvd\n", cur_profile);
+ cd_media = 1;
+ cd_media_hddvd = 1;
+ break;
+ case 0x51:
+ log_debug("profile 0x%02x media_hddvd_r\n", cur_profile);
+ cd_media = 1;
+ cd_media_hddvd_r = 1;
+ break;
+ case 0x52:
+ log_debug("profile 0x%02x media_hddvd_rw\n", cur_profile);
+ cd_media = 1;
+ cd_media_hddvd_rw = 1;
+ break;
+ default:
+ log_debug("profile 0x%02x <ignored>\n", cur_profile);
+ break;
+ }
+}
+
+static int feature_profiles(struct udev *udev, const unsigned char *profiles, size_t size)
+{
+ unsigned int i;
+
+ for (i = 0; i+4 <= size; i += 4) {
+ int profile;
+
+ profile = profiles[i] << 8 | profiles[i+1];
+ switch (profile) {
+ case 0x03:
+ case 0x04:
+ case 0x05:
+ log_debug("profile 0x%02x mo\n", profile);
+ cd_mo = 1;
+ break;
+ case 0x08:
+ log_debug("profile 0x%02x cd_rom\n", profile);
+ cd_cd_rom = 1;
+ break;
+ case 0x09:
+ log_debug("profile 0x%02x cd_r\n", profile);
+ cd_cd_r = 1;
+ break;
+ case 0x0A:
+ log_debug("profile 0x%02x cd_rw\n", profile);
+ cd_cd_rw = 1;
+ break;
+ case 0x10:
+ log_debug("profile 0x%02x dvd_rom\n", profile);
+ cd_dvd_rom = 1;
+ break;
+ case 0x12:
+ log_debug("profile 0x%02x dvd_ram\n", profile);
+ cd_dvd_ram = 1;
+ break;
+ case 0x13:
+ case 0x14:
+ log_debug("profile 0x%02x dvd_rw\n", profile);
+ cd_dvd_rw = 1;
+ break;
+ case 0x1B:
+ log_debug("profile 0x%02x dvd_plus_r\n", profile);
+ cd_dvd_plus_r = 1;
+ break;
+ case 0x1A:
+ log_debug("profile 0x%02x dvd_plus_rw\n", profile);
+ cd_dvd_plus_rw = 1;
+ break;
+ case 0x2A:
+ log_debug("profile 0x%02x dvd_plus_rw_dl\n", profile);
+ cd_dvd_plus_rw_dl = 1;
+ break;
+ case 0x2B:
+ log_debug("profile 0x%02x dvd_plus_r_dl\n", profile);
+ cd_dvd_plus_r_dl = 1;
+ break;
+ case 0x40:
+ cd_bd = 1;
+ log_debug("profile 0x%02x bd\n", profile);
+ break;
+ case 0x41:
+ case 0x42:
+ cd_bd_r = 1;
+ log_debug("profile 0x%02x bd_r\n", profile);
+ break;
+ case 0x43:
+ cd_bd_re = 1;
+ log_debug("profile 0x%02x bd_re\n", profile);
+ break;
+ case 0x50:
+ cd_hddvd = 1;
+ log_debug("profile 0x%02x hddvd\n", profile);
+ break;
+ case 0x51:
+ cd_hddvd_r = 1;
+ log_debug("profile 0x%02x hddvd_r\n", profile);
+ break;
+ case 0x52:
+ cd_hddvd_rw = 1;
+ log_debug("profile 0x%02x hddvd_rw\n", profile);
+ break;
+ default:
+ log_debug("profile 0x%02x <ignored>\n", profile);
+ break;
+ }
+ }
+ return 0;
+}
+
+/* returns 0 if media was detected */
+static int cd_profiles_old_mmc(struct udev *udev, int fd)
+{
+ struct scsi_cmd sc;
+ int err;
+
+ unsigned char header[32];
+
+ scsi_cmd_init(udev, &sc);
+ scsi_cmd_set(udev, &sc, 0, 0x51);
+ scsi_cmd_set(udev, &sc, 8, sizeof(header));
+ scsi_cmd_set(udev, &sc, 9, 0);
+ err = scsi_cmd_run(udev, &sc, fd, header, sizeof(header));
+ if ((err != 0)) {
+ info_scsi_cmd_err(udev, "READ DISC INFORMATION", err);
+ if (cd_media == 1) {
+ log_debug("no current profile, but disc is present; assuming CD-ROM\n");
+ cd_media_cd_rom = 1;
+ cd_media_track_count = 1;
+ cd_media_track_count_data = 1;
+ return 0;
+ } else {
+ log_debug("no current profile, assuming no media\n");
+ return -1;
+ }
+ };
+
+ cd_media = 1;
+
+ if (header[2] & 16) {
+ cd_media_cd_rw = 1;
+ log_debug("profile 0x0a media_cd_rw\n");
+ } else if ((header[2] & 3) < 2 && cd_cd_r) {
+ cd_media_cd_r = 1;
+ log_debug("profile 0x09 media_cd_r\n");
+ } else {
+ cd_media_cd_rom = 1;
+ log_debug("profile 0x08 media_cd_rom\n");
+ }
+ return 0;
+}
+
+/* returns 0 if media was detected */
+static int cd_profiles(struct udev *udev, int fd)
+{
+ struct scsi_cmd sc;
+ unsigned char features[65530];
+ unsigned int cur_profile = 0;
+ unsigned int len;
+ unsigned int i;
+ int err;
+ int ret;
+
+ ret = -1;
+
+ /* First query the current profile */
+ scsi_cmd_init(udev, &sc);
+ scsi_cmd_set(udev, &sc, 0, 0x46);
+ scsi_cmd_set(udev, &sc, 8, 8);
+ scsi_cmd_set(udev, &sc, 9, 0);
+ err = scsi_cmd_run(udev, &sc, fd, features, 8);
+ if ((err != 0)) {
+ info_scsi_cmd_err(udev, "GET CONFIGURATION", err);
+ /* handle pre-MMC2 drives which do not support GET CONFIGURATION */
+ if (SK(err) == 0x5 && ASC(err) == 0x20) {
+ log_debug("drive is pre-MMC2 and does not support 46h get configuration command\n");
+ log_debug("trying to work around the problem\n");
+ ret = cd_profiles_old_mmc(udev, fd);
+ }
+ goto out;
+ }
+
+ cur_profile = features[6] << 8 | features[7];
+ if (cur_profile > 0) {
+ log_debug("current profile 0x%02x\n", cur_profile);
+ feature_profile_media (udev, cur_profile);
+ ret = 0; /* we have media */
+ } else {
+ log_debug("no current profile, assuming no media\n");
+ }
+
+ len = features[0] << 24 | features[1] << 16 | features[2] << 8 | features[3];
+ log_debug("GET CONFIGURATION: size of features buffer 0x%04x\n", len);
+
+ if (len > sizeof(features)) {
+ log_debug("can not get features in a single query, truncating\n");
+ len = sizeof(features);
+ } else if (len <= 8) {
+ len = sizeof(features);
+ }
+
+ /* Now get the full feature buffer */
+ scsi_cmd_init(udev, &sc);
+ scsi_cmd_set(udev, &sc, 0, 0x46);
+ scsi_cmd_set(udev, &sc, 7, ( len >> 8 ) & 0xff);
+ scsi_cmd_set(udev, &sc, 8, len & 0xff);
+ scsi_cmd_set(udev, &sc, 9, 0);
+ err = scsi_cmd_run(udev, &sc, fd, features, len);
+ if ((err != 0)) {
+ info_scsi_cmd_err(udev, "GET CONFIGURATION", err);
+ return -1;
+ }
+
+ /* parse the length once more, in case the drive decided to have other features suddenly :) */
+ len = features[0] << 24 | features[1] << 16 | features[2] << 8 | features[3];
+ log_debug("GET CONFIGURATION: size of features buffer 0x%04x\n", len);
+
+ if (len > sizeof(features)) {
+ log_debug("can not get features in a single query, truncating\n");
+ len = sizeof(features);
+ }
+
+ /* device features */
+ for (i = 8; i+4 < len; i += (4 + features[i+3])) {
+ unsigned int feature;
+
+ feature = features[i] << 8 | features[i+1];
+
+ switch (feature) {
+ case 0x00:
+ log_debug("GET CONFIGURATION: feature 'profiles', with %i entries\n", features[i+3] / 4);
+ feature_profiles(udev, &features[i]+4, features[i+3]);
+ break;
+ default:
+ log_debug("GET CONFIGURATION: feature 0x%04x <ignored>, with 0x%02x bytes\n", feature, features[i+3]);
+ break;
+ }
+ }
+out:
+ return ret;
+}
+
+static int cd_media_info(struct udev *udev, int fd)
+{
+ struct scsi_cmd sc;
+ unsigned char header[32];
+ static const char *media_status[] = {
+ "blank",
+ "appendable",
+ "complete",
+ "other"
+ };
+ int err;
+
+ scsi_cmd_init(udev, &sc);
+ scsi_cmd_set(udev, &sc, 0, 0x51);
+ scsi_cmd_set(udev, &sc, 8, sizeof(header) & 0xff);
+ scsi_cmd_set(udev, &sc, 9, 0);
+ err = scsi_cmd_run(udev, &sc, fd, header, sizeof(header));
+ if ((err != 0)) {
+ info_scsi_cmd_err(udev, "READ DISC INFORMATION", err);
+ return -1;
+ };
+
+ cd_media = 1;
+ log_debug("disk type %02x\n", header[8]);
+ log_debug("hardware reported media status: %s\n", media_status[header[2] & 3]);
+
+ /* exclude plain CDROM, some fake cdroms return 0 for "blank" media here */
+ if (!cd_media_cd_rom)
+ cd_media_state = media_status[header[2] & 3];
+
+ /* fresh DVD-RW in restricted overwite mode reports itself as
+ * "appendable"; change it to "blank" to make it consistent with what
+ * gets reported after blanking, and what userspace expects */
+ if (cd_media_dvd_rw_ro && (header[2] & 3) == 1)
+ cd_media_state = media_status[0];
+
+ /* DVD+RW discs (and DVD-RW in restricted mode) once formatted are
+ * always "complete", DVD-RAM are "other" or "complete" if the disc is
+ * write protected; we need to check the contents if it is blank */
+ if ((cd_media_dvd_rw_ro || cd_media_dvd_plus_rw || cd_media_dvd_plus_rw_dl || cd_media_dvd_ram) && (header[2] & 3) > 1) {
+ unsigned char buffer[32 * 2048];
+ unsigned char result, len;
+ int block, offset;
+
+ if (cd_media_dvd_ram) {
+ /* a write protected dvd-ram may report "complete" status */
+
+ unsigned char dvdstruct[8];
+ unsigned char format[12];
+
+ scsi_cmd_init(udev, &sc);
+ scsi_cmd_set(udev, &sc, 0, 0xAD);
+ scsi_cmd_set(udev, &sc, 7, 0xC0);
+ scsi_cmd_set(udev, &sc, 9, sizeof(dvdstruct));
+ scsi_cmd_set(udev, &sc, 11, 0);
+ err = scsi_cmd_run(udev, &sc, fd, dvdstruct, sizeof(dvdstruct));
+ if ((err != 0)) {
+ info_scsi_cmd_err(udev, "READ DVD STRUCTURE", err);
+ return -1;
+ }
+ if (dvdstruct[4] & 0x02) {
+ cd_media_state = media_status[2];
+ log_debug("write-protected DVD-RAM media inserted\n");
+ goto determined;
+ }
+
+ /* let's make sure we don't try to read unformatted media */
+ scsi_cmd_init(udev, &sc);
+ scsi_cmd_set(udev, &sc, 0, 0x23);
+ scsi_cmd_set(udev, &sc, 8, sizeof(format));
+ scsi_cmd_set(udev, &sc, 9, 0);
+ err = scsi_cmd_run(udev, &sc, fd, format, sizeof(format));
+ if ((err != 0)) {
+ info_scsi_cmd_err(udev, "READ DVD FORMAT CAPACITIES", err);
+ return -1;
+ }
+
+ len = format[3];
+ if (len & 7 || len < 16) {
+ log_debug("invalid format capacities length\n");
+ return -1;
+ }
+
+ switch(format[8] & 3) {
+ case 1:
+ log_debug("unformatted DVD-RAM media inserted\n");
+ /* This means that last format was interrupted
+ * or failed, blank dvd-ram discs are factory
+ * formatted. Take no action here as it takes
+ * quite a while to reformat a dvd-ram and it's
+ * not automatically started */
+ goto determined;
+
+ case 2:
+ log_debug("formatted DVD-RAM media inserted\n");
+ break;
+
+ case 3:
+ cd_media = 0; //return no media
+ log_debug("format capacities returned no media\n");
+ return -1;
+ }
+ }
+
+ /* Take a closer look at formatted media (unformatted DVD+RW
+ * has "blank" status", DVD-RAM was examined earlier) and check
+ * for ISO and UDF PVDs or a fs superblock presence and do it
+ * in one ioctl (we need just sectors 0 and 16) */
+ scsi_cmd_init(udev, &sc);
+ scsi_cmd_set(udev, &sc, 0, 0x28);
+ scsi_cmd_set(udev, &sc, 5, 0);
+ scsi_cmd_set(udev, &sc, 8, 32);
+ scsi_cmd_set(udev, &sc, 9, 0);
+ err = scsi_cmd_run(udev, &sc, fd, buffer, sizeof(buffer));
+ if ((err != 0)) {
+ cd_media = 0;
+ info_scsi_cmd_err(udev, "READ FIRST 32 BLOCKS", err);
+ return -1;
+ }
+
+ /* if any non-zero data is found in sector 16 (iso and udf) or
+ * eventually 0 (fat32 boot sector, ext2 superblock, etc), disc
+ * is assumed non-blank */
+ result = 0;
+
+ for (block = 32768; block >= 0 && !result; block -= 32768) {
+ offset = block;
+ while (offset < (block + 2048) && !result) {
+ result = buffer [offset];
+ offset++;
+ }
+ }
+
+ if (!result) {
+ cd_media_state = media_status[0];
+ log_debug("no data in blocks 0 or 16, assuming blank\n");
+ } else {
+ log_debug("data in blocks 0 or 16, assuming complete\n");
+ }
+ }
+
+determined:
+ /* "other" is e. g. DVD-RAM, can't append sessions there; DVDs in
+ * restricted overwrite mode can never append, only in sequential mode */
+ if ((header[2] & 3) < 2 && !cd_media_dvd_rw_ro)
+ cd_media_session_next = header[10] << 8 | header[5];
+ cd_media_session_count = header[9] << 8 | header[4];
+ cd_media_track_count = header[11] << 8 | header[6];
+
+ return 0;
+}
+
+static int cd_media_toc(struct udev *udev, int fd)
+{
+ struct scsi_cmd sc;
+ unsigned char header[12];
+ unsigned char toc[65536];
+ unsigned int len, i, num_tracks;
+ unsigned char *p;
+ int err;
+
+ scsi_cmd_init(udev, &sc);
+ scsi_cmd_set(udev, &sc, 0, 0x43);
+ scsi_cmd_set(udev, &sc, 6, 1);
+ scsi_cmd_set(udev, &sc, 8, sizeof(header) & 0xff);
+ scsi_cmd_set(udev, &sc, 9, 0);
+ err = scsi_cmd_run(udev, &sc, fd, header, sizeof(header));
+ if ((err != 0)) {
+ info_scsi_cmd_err(udev, "READ TOC", err);
+ return -1;
+ }
+
+ len = (header[0] << 8 | header[1]) + 2;
+ log_debug("READ TOC: len: %d, start track: %d, end track: %d\n", len, header[2], header[3]);
+ if (len > sizeof(toc))
+ return -1;
+ if (len < 2)
+ return -1;
+ /* 2: first track, 3: last track */
+ num_tracks = header[3] - header[2] + 1;
+
+ /* empty media has no tracks */
+ if (len < 8)
+ return 0;
+
+ scsi_cmd_init(udev, &sc);
+ scsi_cmd_set(udev, &sc, 0, 0x43);
+ scsi_cmd_set(udev, &sc, 6, header[2]); /* First Track/Session Number */
+ scsi_cmd_set(udev, &sc, 7, (len >> 8) & 0xff);
+ scsi_cmd_set(udev, &sc, 8, len & 0xff);
+ scsi_cmd_set(udev, &sc, 9, 0);
+ err = scsi_cmd_run(udev, &sc, fd, toc, len);
+ if ((err != 0)) {
+ info_scsi_cmd_err(udev, "READ TOC (tracks)", err);
+ return -1;
+ }
+
+ /* Take care to not iterate beyond the last valid track as specified in
+ * the TOC, but also avoid going beyond the TOC length, just in case
+ * the last track number is invalidly large */
+ for (p = toc+4, i = 4; i < len-8 && num_tracks > 0; i += 8, p += 8, --num_tracks) {
+ unsigned int block;
+ unsigned int is_data_track;
+
+ is_data_track = (p[1] & 0x04) != 0;
+
+ block = p[4] << 24 | p[5] << 16 | p[6] << 8 | p[7];
+ log_debug("track=%u info=0x%x(%s) start_block=%u\n",
+ p[2], p[1] & 0x0f, is_data_track ? "data":"audio", block);
+
+ if (is_data_track)
+ cd_media_track_count_data++;
+ else
+ cd_media_track_count_audio++;
+ }
+
+ scsi_cmd_init(udev, &sc);
+ scsi_cmd_set(udev, &sc, 0, 0x43);
+ scsi_cmd_set(udev, &sc, 2, 1); /* Session Info */
+ scsi_cmd_set(udev, &sc, 8, sizeof(header));
+ scsi_cmd_set(udev, &sc, 9, 0);
+ err = scsi_cmd_run(udev, &sc, fd, header, sizeof(header));
+ if ((err != 0)) {
+ info_scsi_cmd_err(udev, "READ TOC (multi session)", err);
+ return -1;
+ }
+ len = header[4+4] << 24 | header[4+5] << 16 | header[4+6] << 8 | header[4+7];
+ log_debug("last track %u starts at block %u\n", header[4+2], len);
+ cd_media_session_last_offset = (unsigned long long int)len * 2048;
+ return 0;
+}
+
+int main(int argc, char *argv[])
+{
+ struct udev *udev;
+ static const struct option options[] = {
+ { "lock-media", no_argument, NULL, 'l' },
+ { "unlock-media", no_argument, NULL, 'u' },
+ { "eject-media", no_argument, NULL, 'e' },
+ { "debug", no_argument, NULL, 'd' },
+ { "help", no_argument, NULL, 'h' },
+ {}
+ };
+ bool eject = false;
+ bool lock = false;
+ bool unlock = false;
+ const char *node = NULL;
+ int fd = -1;
+ int cnt;
+ int rc = 0;
+
+ udev = udev_new();
+ if (udev == NULL)
+ goto exit;
+
+ log_open();
+ udev_set_log_fn(udev, log_fn);
+
+ while (1) {
+ int option;
+
+ option = getopt_long(argc, argv, "deluh", options, NULL);
+ if (option == -1)
+ break;
+
+ switch (option) {
+ case 'l':
+ lock = true;
+ break;
+ case 'u':
+ unlock = true;
+ break;
+ case 'e':
+ eject = true;
+ break;
+ case 'd':
+ debug = true;
+ log_set_max_level(LOG_DEBUG);
+ udev_set_log_priority(udev, LOG_DEBUG);
+ break;
+ case 'h':
+ printf("Usage: cdrom_id [options] <device>\n"
+ " --lock-media lock the media (to enable eject request events)\n"
+ " --unlock-media unlock the media\n"
+ " --eject-media eject the media\n"
+ " --debug debug to stderr\n"
+ " --help print this help text\n\n");
+ goto exit;
+ default:
+ rc = 1;
+ goto exit;
+ }
+ }
+
+ node = argv[optind];
+ if (!node) {
+ log_error("no device\n");
+ fprintf(stderr, "no device\n");
+ rc = 1;
+ goto exit;
+ }
+
+ srand((unsigned int)getpid());
+ for (cnt = 20; cnt > 0; cnt--) {
+ struct timespec duration;
+
+ fd = open(node, O_RDONLY|O_NONBLOCK|(is_mounted(node) ? 0 : O_EXCL));
+ if (fd >= 0 || errno != EBUSY)
+ break;
+ duration.tv_sec = 0;
+ duration.tv_nsec = (100 * 1000 * 1000) + (rand() % 100 * 1000 * 1000);
+ nanosleep(&duration, NULL);
+ }
+ if (fd < 0) {
+ log_debug("unable to open '%s'\n", node);
+ fprintf(stderr, "unable to open '%s'\n", node);
+ rc = 1;
+ goto exit;
+ }
+ log_debug("probing: '%s'\n", node);
+
+ /* same data as original cdrom_id */
+ if (cd_capability_compat(udev, fd) < 0) {
+ rc = 1;
+ goto exit;
+ }
+
+ /* check for media - don't bail if there's no media as we still need to
+ * to read profiles */
+ cd_media_compat(udev, fd);
+
+ /* check if drive talks MMC */
+ if (cd_inquiry(udev, fd) < 0)
+ goto work;
+
+ /* read drive and possibly current profile */
+ if (cd_profiles(udev, fd) != 0)
+ goto work;
+
+ /* at this point we are guaranteed to have media in the drive - find out more about it */
+
+ /* get session/track info */
+ cd_media_toc(udev, fd);
+
+ /* get writable media state */
+ cd_media_info(udev, fd);
+
+work:
+ /* lock the media, so we enable eject button events */
+ if (lock && cd_media) {
+ log_debug("PREVENT_ALLOW_MEDIUM_REMOVAL (lock)\n");
+ media_lock(udev, fd, true);
+ }
+
+ if (unlock && cd_media) {
+ log_debug("PREVENT_ALLOW_MEDIUM_REMOVAL (unlock)\n");
+ media_lock(udev, fd, false);
+ }
+
+ if (eject) {
+ log_debug("PREVENT_ALLOW_MEDIUM_REMOVAL (unlock)\n");
+ media_lock(udev, fd, false);
+ log_debug("START_STOP_UNIT (eject)\n");
+ media_eject(udev, fd);
+ }
+
+ printf("ID_CDROM=1\n");
+ if (cd_cd_rom)
+ printf("ID_CDROM_CD=1\n");
+ if (cd_cd_r)
+ printf("ID_CDROM_CD_R=1\n");
+ if (cd_cd_rw)
+ printf("ID_CDROM_CD_RW=1\n");
+ if (cd_dvd_rom)
+ printf("ID_CDROM_DVD=1\n");
+ if (cd_dvd_r)
+ printf("ID_CDROM_DVD_R=1\n");
+ if (cd_dvd_rw)
+ printf("ID_CDROM_DVD_RW=1\n");
+ if (cd_dvd_ram)
+ printf("ID_CDROM_DVD_RAM=1\n");
+ if (cd_dvd_plus_r)
+ printf("ID_CDROM_DVD_PLUS_R=1\n");
+ if (cd_dvd_plus_rw)
+ printf("ID_CDROM_DVD_PLUS_RW=1\n");
+ if (cd_dvd_plus_r_dl)
+ printf("ID_CDROM_DVD_PLUS_R_DL=1\n");
+ if (cd_dvd_plus_rw_dl)
+ printf("ID_CDROM_DVD_PLUS_RW_DL=1\n");
+ if (cd_bd)
+ printf("ID_CDROM_BD=1\n");
+ if (cd_bd_r)
+ printf("ID_CDROM_BD_R=1\n");
+ if (cd_bd_re)
+ printf("ID_CDROM_BD_RE=1\n");
+ if (cd_hddvd)
+ printf("ID_CDROM_HDDVD=1\n");
+ if (cd_hddvd_r)
+ printf("ID_CDROM_HDDVD_R=1\n");
+ if (cd_hddvd_rw)
+ printf("ID_CDROM_HDDVD_RW=1\n");
+ if (cd_mo)
+ printf("ID_CDROM_MO=1\n");
+ if (cd_mrw)
+ printf("ID_CDROM_MRW=1\n");
+ if (cd_mrw_w)
+ printf("ID_CDROM_MRW_W=1\n");
+
+ if (cd_media)
+ printf("ID_CDROM_MEDIA=1\n");
+ if (cd_media_mo)
+ printf("ID_CDROM_MEDIA_MO=1\n");
+ if (cd_media_mrw)
+ printf("ID_CDROM_MEDIA_MRW=1\n");
+ if (cd_media_mrw_w)
+ printf("ID_CDROM_MEDIA_MRW_W=1\n");
+ if (cd_media_cd_rom)
+ printf("ID_CDROM_MEDIA_CD=1\n");
+ if (cd_media_cd_r)
+ printf("ID_CDROM_MEDIA_CD_R=1\n");
+ if (cd_media_cd_rw)
+ printf("ID_CDROM_MEDIA_CD_RW=1\n");
+ if (cd_media_dvd_rom)
+ printf("ID_CDROM_MEDIA_DVD=1\n");
+ if (cd_media_dvd_r)
+ printf("ID_CDROM_MEDIA_DVD_R=1\n");
+ if (cd_media_dvd_ram)
+ printf("ID_CDROM_MEDIA_DVD_RAM=1\n");
+ if (cd_media_dvd_rw)
+ printf("ID_CDROM_MEDIA_DVD_RW=1\n");
+ if (cd_media_dvd_plus_r)
+ printf("ID_CDROM_MEDIA_DVD_PLUS_R=1\n");
+ if (cd_media_dvd_plus_rw)
+ printf("ID_CDROM_MEDIA_DVD_PLUS_RW=1\n");
+ if (cd_media_dvd_plus_rw_dl)
+ printf("ID_CDROM_MEDIA_DVD_PLUS_RW_DL=1\n");
+ if (cd_media_dvd_plus_r_dl)
+ printf("ID_CDROM_MEDIA_DVD_PLUS_R_DL=1\n");
+ if (cd_media_bd)
+ printf("ID_CDROM_MEDIA_BD=1\n");
+ if (cd_media_bd_r)
+ printf("ID_CDROM_MEDIA_BD_R=1\n");
+ if (cd_media_bd_re)
+ printf("ID_CDROM_MEDIA_BD_RE=1\n");
+ if (cd_media_hddvd)
+ printf("ID_CDROM_MEDIA_HDDVD=1\n");
+ if (cd_media_hddvd_r)
+ printf("ID_CDROM_MEDIA_HDDVD_R=1\n");
+ if (cd_media_hddvd_rw)
+ printf("ID_CDROM_MEDIA_HDDVD_RW=1\n");
+
+ if (cd_media_state != NULL)
+ printf("ID_CDROM_MEDIA_STATE=%s\n", cd_media_state);
+ if (cd_media_session_next > 0)
+ printf("ID_CDROM_MEDIA_SESSION_NEXT=%d\n", cd_media_session_next);
+ if (cd_media_session_count > 0)
+ printf("ID_CDROM_MEDIA_SESSION_COUNT=%d\n", cd_media_session_count);
+ if (cd_media_session_count > 1 && cd_media_session_last_offset > 0)
+ printf("ID_CDROM_MEDIA_SESSION_LAST_OFFSET=%llu\n", cd_media_session_last_offset);
+ if (cd_media_track_count > 0)
+ printf("ID_CDROM_MEDIA_TRACK_COUNT=%d\n", cd_media_track_count);
+ if (cd_media_track_count_audio > 0)
+ printf("ID_CDROM_MEDIA_TRACK_COUNT_AUDIO=%d\n", cd_media_track_count_audio);
+ if (cd_media_track_count_data > 0)
+ printf("ID_CDROM_MEDIA_TRACK_COUNT_DATA=%d\n", cd_media_track_count_data);
+exit:
+ if (fd >= 0)
+ close(fd);
+ udev_unref(udev);
+ log_close();
+ return rc;
+}
diff --git a/src/udev/collect/collect.c b/src/udev/collect/collect.c
new file mode 100644
index 0000000000..f95ee23b75
--- /dev/null
+++ b/src/udev/collect/collect.c
@@ -0,0 +1,492 @@
+/*
+ * Collect variables across events.
+ *
+ * usage: collect [--add|--remove] <checkpoint> <id> <idlist>
+ *
+ * Adds ID <id> to the list governed by <checkpoint>.
+ * <id> must be part of the ID list <idlist>.
+ * If all IDs given by <idlist> are listed (ie collect has been
+ * invoked for each ID in <idlist>) collect returns 0, the
+ * number of missing IDs otherwise.
+ * A negative number is returned on error.
+ *
+ * Copyright(C) 2007, Hannes Reinecke <hare@suse.de>
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <unistd.h>
+#include <signal.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <string.h>
+#include <getopt.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#include "libudev.h"
+#include "libudev-private.h"
+#include "macro.h"
+
+#define BUFSIZE 16
+#define UDEV_ALARM_TIMEOUT 180
+
+enum collect_state {
+ STATE_NONE,
+ STATE_OLD,
+ STATE_CONFIRMED,
+};
+
+struct _mate {
+ struct udev_list_node node;
+ char *name;
+ enum collect_state state;
+};
+
+static struct udev_list_node bunch;
+static int debug;
+
+/* This can increase dynamically */
+static size_t bufsize = BUFSIZE;
+
+static inline struct _mate *node_to_mate(struct udev_list_node *node)
+{
+ return container_of(node, struct _mate, node);
+}
+
+_noreturn_ static void sig_alrm(int signo)
+{
+ exit(4);
+}
+
+static void usage(void)
+{
+ printf("usage: collect [--add|--remove] [--debug] <checkpoint> <id> <idlist>\n"
+ "\n"
+ " Adds ID <id> to the list governed by <checkpoint>.\n"
+ " <id> must be part of the list <idlist>.\n"
+ " If all IDs given by <idlist> are listed (ie collect has been\n"
+ " invoked for each ID in <idlist>) collect returns 0, the\n"
+ " number of missing IDs otherwise.\n"
+ " On error a negative number is returned.\n"
+ "\n");
+}
+
+/*
+ * prepare
+ *
+ * Prepares the database file
+ */
+static int prepare(char *dir, char *filename)
+{
+ struct stat statbuf;
+ char buf[512];
+ int fd;
+
+ if (stat(dir, &statbuf) < 0)
+ mkdir(dir, 0700);
+
+ snprintf(buf, sizeof(buf), "%s/%s", dir, filename);
+
+ fd = open(buf,O_RDWR|O_CREAT, S_IRUSR|S_IWUSR);
+ if (fd < 0)
+ fprintf(stderr, "Cannot open %s: %s\n", buf, strerror(errno));
+
+ if (lockf(fd,F_TLOCK,0) < 0) {
+ if (debug)
+ fprintf(stderr, "Lock taken, wait for %d seconds\n", UDEV_ALARM_TIMEOUT);
+ if (errno == EAGAIN || errno == EACCES) {
+ alarm(UDEV_ALARM_TIMEOUT);
+ lockf(fd, F_LOCK, 0);
+ if (debug)
+ fprintf(stderr, "Acquired lock on %s\n", buf);
+ } else {
+ if (debug)
+ fprintf(stderr, "Could not get lock on %s: %s\n", buf, strerror(errno));
+ }
+ }
+
+ return fd;
+}
+
+/*
+ * Read checkpoint file
+ *
+ * Tricky reading this. We allocate a buffer twice as large
+ * as we're going to read. Then we read into the upper half
+ * of that buffer and start parsing.
+ * Once we do _not_ find end-of-work terminator (whitespace
+ * character) we move the upper half to the lower half,
+ * adjust the read pointer and read the next bit.
+ * Quite clever methinks :-)
+ * I should become a programmer ...
+ *
+ * Yes, one could have used fgets() for this. But then we'd
+ * have to use freopen etc which I found quite tedious.
+ */
+static int checkout(int fd)
+{
+ int len;
+ char *buf, *ptr, *word = NULL;
+ struct _mate *him;
+
+ restart:
+ len = bufsize >> 1;
+ buf = malloc(bufsize + 1);
+ if (!buf)
+ return log_oom();
+ memset(buf, ' ', bufsize);
+ buf[bufsize] = '\0';
+
+ ptr = buf + len;
+ while ((read(fd, buf + len, len)) > 0) {
+ while (ptr && *ptr) {
+ word = ptr;
+ ptr = strpbrk(word," \n\t\r");
+ if (!ptr && word < (buf + len)) {
+ bufsize = bufsize << 1;
+ if (debug)
+ fprintf(stderr, "ID overflow, restarting with size %zi\n", bufsize);
+ free(buf);
+ lseek(fd, 0, SEEK_SET);
+ goto restart;
+ }
+ if (ptr) {
+ *ptr = '\0';
+ ptr++;
+ if (!strlen(word))
+ continue;
+
+ if (debug)
+ fprintf(stderr, "Found word %s\n", word);
+ him = malloc(sizeof (struct _mate));
+ if (!him) {
+ free(buf);
+ return log_oom();
+ }
+ him->name = strdup(word);
+ if (!him->name) {
+ free(buf);
+ free(him);
+ return log_oom();
+ }
+ him->state = STATE_OLD;
+ udev_list_node_append(&him->node, &bunch);
+ word = NULL;
+ }
+ }
+ memcpy(buf, buf + len, len);
+ memset(buf + len, ' ', len);
+
+ if (!ptr)
+ ptr = word;
+ if (!ptr)
+ break;
+ ptr -= len;
+ }
+
+ free(buf);
+ return 0;
+}
+
+/*
+ * invite
+ *
+ * Adds a new ID 'us' to the internal list,
+ * marks it as confirmed.
+ */
+static void invite(char *us)
+{
+ struct udev_list_node *him_node;
+ struct _mate *who = NULL;
+
+ if (debug)
+ fprintf(stderr, "Adding ID '%s'\n", us);
+
+ udev_list_node_foreach(him_node, &bunch) {
+ struct _mate *him = node_to_mate(him_node);
+
+ if (streq(him->name, us)) {
+ him->state = STATE_CONFIRMED;
+ who = him;
+ }
+ }
+ if (debug && !who)
+ fprintf(stderr, "ID '%s' not in database\n", us);
+
+}
+
+/*
+ * reject
+ *
+ * Marks the ID 'us' as invalid,
+ * causing it to be removed when the
+ * list is written out.
+ */
+static void reject(char *us)
+{
+ struct udev_list_node *him_node;
+ struct _mate *who = NULL;
+
+ if (debug)
+ fprintf(stderr, "Removing ID '%s'\n", us);
+
+ udev_list_node_foreach(him_node, &bunch) {
+ struct _mate *him = node_to_mate(him_node);
+
+ if (streq(him->name, us)) {
+ him->state = STATE_NONE;
+ who = him;
+ }
+ }
+ if (debug && !who)
+ fprintf(stderr, "ID '%s' not in database\n", us);
+}
+
+/*
+ * kickout
+ *
+ * Remove all IDs in the internal list which are not part
+ * of the list passed via the commandline.
+ */
+static void kickout(void)
+{
+ struct udev_list_node *him_node;
+ struct udev_list_node *tmp;
+
+ udev_list_node_foreach_safe(him_node, tmp, &bunch) {
+ struct _mate *him = node_to_mate(him_node);
+
+ if (him->state == STATE_OLD) {
+ udev_list_node_remove(&him->node);
+ free(him->name);
+ free(him);
+ }
+ }
+}
+
+/*
+ * missing
+ *
+ * Counts all missing IDs in the internal list.
+ */
+static int missing(int fd)
+{
+ char *buf;
+ int ret = 0;
+ struct udev_list_node *him_node;
+
+ buf = malloc(bufsize);
+ if (!buf)
+ return log_oom();
+
+ udev_list_node_foreach(him_node, &bunch) {
+ struct _mate *him = node_to_mate(him_node);
+
+ if (him->state == STATE_NONE) {
+ ret++;
+ } else {
+ while (strlen(him->name)+1 >= bufsize) {
+ char *tmpbuf;
+
+ bufsize = bufsize << 1;
+ tmpbuf = realloc(buf, bufsize);
+ if (!tmpbuf) {
+ free(buf);
+ return log_oom();
+ }
+ buf = tmpbuf;
+ }
+ snprintf(buf, strlen(him->name)+2, "%s ", him->name);
+ if (write(fd, buf, strlen(buf)) < 0) {
+ free(buf);
+ return -1;
+ }
+ }
+ }
+
+ free(buf);
+ return ret;
+}
+
+/*
+ * everybody
+ *
+ * Prints out the status of the internal list.
+ */
+static void everybody(void)
+{
+ struct udev_list_node *him_node;
+ const char *state = "";
+
+ udev_list_node_foreach(him_node, &bunch) {
+ struct _mate *him = node_to_mate(him_node);
+
+ switch (him->state) {
+ case STATE_NONE:
+ state = "none";
+ break;
+ case STATE_OLD:
+ state = "old";
+ break;
+ case STATE_CONFIRMED:
+ state = "confirmed";
+ break;
+ }
+ fprintf(stderr, "ID: %s=%s\n", him->name, state);
+ }
+}
+
+int main(int argc, char **argv)
+{
+ struct udev *udev;
+ static const struct option options[] = {
+ { "add", no_argument, NULL, 'a' },
+ { "remove", no_argument, NULL, 'r' },
+ { "debug", no_argument, NULL, 'd' },
+ { "help", no_argument, NULL, 'h' },
+ {}
+ };
+ int argi;
+ char *checkpoint, *us;
+ int fd;
+ int i;
+ int ret = EXIT_SUCCESS;
+ int prune = 0;
+ char tmpdir[UTIL_PATH_SIZE];
+
+ udev = udev_new();
+ if (udev == NULL) {
+ ret = EXIT_FAILURE;
+ goto exit;
+ }
+
+ while (1) {
+ int option;
+
+ option = getopt_long(argc, argv, "ardh", options, NULL);
+ if (option == -1)
+ break;
+
+ switch (option) {
+ case 'a':
+ prune = 0;
+ break;
+ case 'r':
+ prune = 1;
+ break;
+ case 'd':
+ debug = 1;
+ break;
+ case 'h':
+ usage();
+ goto exit;
+ default:
+ ret = 1;
+ goto exit;
+ }
+ }
+
+ argi = optind;
+ if (argi + 2 > argc) {
+ printf("Missing parameter(s)\n");
+ ret = 1;
+ goto exit;
+ }
+ checkpoint = argv[argi++];
+ us = argv[argi++];
+
+ if (signal(SIGALRM, sig_alrm) == SIG_ERR) {
+ fprintf(stderr, "Cannot set SIGALRM: %s\n", strerror(errno));
+ ret = 2;
+ goto exit;
+ }
+
+ udev_list_node_init(&bunch);
+
+ if (debug)
+ fprintf(stderr, "Using checkpoint '%s'\n", checkpoint);
+
+ strscpyl(tmpdir, sizeof(tmpdir), "/run/udev/collect", NULL);
+ fd = prepare(tmpdir, checkpoint);
+ if (fd < 0) {
+ ret = 3;
+ goto out;
+ }
+
+ if (checkout(fd) < 0) {
+ ret = 2;
+ goto out;
+ }
+
+ for (i = argi; i < argc; i++) {
+ struct udev_list_node *him_node;
+ struct _mate *who;
+
+ who = NULL;
+ udev_list_node_foreach(him_node, &bunch) {
+ struct _mate *him = node_to_mate(him_node);
+
+ if (streq(him->name, argv[i]))
+ who = him;
+ }
+ if (!who) {
+ struct _mate *him;
+
+ if (debug)
+ fprintf(stderr, "ID %s: not in database\n", argv[i]);
+ him = malloc(sizeof (struct _mate));
+ if (!him) {
+ ret = ENOMEM;
+ goto out;
+ }
+
+ him->name = malloc(strlen(argv[i]) + 1);
+ if (!him->name) {
+ ret = ENOMEM;
+ goto out;
+ }
+
+ strcpy(him->name, argv[i]);
+ him->state = STATE_NONE;
+ udev_list_node_append(&him->node, &bunch);
+ } else {
+ if (debug)
+ fprintf(stderr, "ID %s: found in database\n", argv[i]);
+ who->state = STATE_CONFIRMED;
+ }
+ }
+
+ if (prune)
+ reject(us);
+ else
+ invite(us);
+
+ if (debug) {
+ everybody();
+ fprintf(stderr, "Prune lists\n");
+ }
+ kickout();
+
+ lseek(fd, 0, SEEK_SET);
+ ftruncate(fd, 0);
+ ret = missing(fd);
+
+ lockf(fd, F_ULOCK, 0);
+ close(fd);
+out:
+ if (debug)
+ everybody();
+ if (ret >= 0)
+ printf("COLLECT_%s=%d\n", checkpoint, ret);
+exit:
+ udev_unref(udev);
+ return ret;
+}
diff --git a/src/udev/keymap/95-keyboard-force-release.rules b/src/udev/keymap/95-keyboard-force-release.rules
new file mode 100644
index 0000000000..3e33e85535
--- /dev/null
+++ b/src/udev/keymap/95-keyboard-force-release.rules
@@ -0,0 +1,57 @@
+# Set model specific atkbd force_release quirk
+#
+# Several laptops have hotkeys which don't generate release events,
+# which can cause problems with software key repeat.
+# The atkbd driver has a quirk handler for generating synthetic
+# release events, which can be configured via sysfs since 2.6.32.
+# Simply add a file with a list of scancodes for your laptop model
+# in /usr/lib/udev/keymaps, and add a rule here.
+# If the hotkeys also need a keymap assignment you can copy the
+# scancodes from the keymap file, otherwise you can run
+# /usr/lib/udev/keymap -i /dev/input/eventX
+# on a Linux vt to find out.
+
+ACTION=="remove", GOTO="force_release_end"
+SUBSYSTEM!="serio", GOTO="force_release_end"
+KERNEL!="serio*", GOTO="force_release_end"
+DRIVER!="atkbd", GOTO="force_release_end"
+
+ENV{DMI_VENDOR}="$attr{[dmi/id]sys_vendor}"
+
+ENV{DMI_VENDOR}=="[sS][aA][mM][sS][uU][nN][gG]*", RUN+="keyboard-force-release.sh $devpath samsung-other"
+ENV{DMI_VENDOR}=="[sS][aA][mM][sS][uU][nN][gG]*", ATTR{[dmi/id]product_name}=="*90X3A*|*900X3*|*900X4*", RUN+="keyboard-force-release.sh $devpath samsung-series-9"
+
+ENV{DMI_VENDOR}=="Dell Inc.", ATTR{[dmi/id]product_name}=="Studio 1557|Studio 1558", RUN+="keyboard-force-release.sh $devpath common-volume-keys"
+ENV{DMI_VENDOR}=="Dell Inc.", ATTR{[dmi/id]product_name}=="Latitude E*|Latitude *U|Precision M*", RUN+="keyboard-force-release.sh $devpath dell-touchpad"
+ENV{DMI_VENDOR}=="Dell Inc.", ATTR{[dmi/id]product_name}=="XPS*", RUN+="keyboard-force-release.sh $devpath dell-xps"
+
+ENV{DMI_VENDOR}=="FUJITSU SIEMENS", ATTR{[dmi/id]product_name}=="AMILO*", RUN+="keyboard-force-release.sh $devpath common-volume-keys"
+
+ENV{DMI_VENDOR}=="FOXCONN", ATTR{[dmi/id]product_name}=="QBOOK", RUN+="keyboard-force-release.sh $devpath common-volume-keys"
+
+ENV{DMI_VENDOR}=="MTC", ATTR{[dmi/id]product_version}=="A0", RUN+="keyboard-force-release.sh $devpath common-volume-keys"
+
+ENV{DMI_VENDOR}=="Mio Technology", ATTR{[dmi/id]product_name}=="N890", RUN+="keyboard-force-release.sh $devpath common-volume-keys"
+
+ENV{DMI_VENDOR}=="PEGATRON CORP.", ATTR{[dmi/id]product_name}=="Spring Peak", RUN+="keyboard-force-release.sh $devpath common-volume-keys"
+
+ENV{DMI_VENDOR}=="TOSHIBA", ATTR{[dmi/id]product_name}=="Satellite [uU]300*|Satellite Pro [uU]300*|Satellite [uU]305*|SATELLITE [uU]500*", RUN+="keyboard-force-release.sh $devpath common-volume-keys"
+
+ENV{DMI_VENDOR}=="Viooo Corporation", ATTR{[dmi/id]product_name}=="PT17", RUN+="keyboard-force-release.sh $devpath common-volume-keys"
+
+# These are all the HP laptops that setup a touchpad toggle key
+ENV{DMI_VENDOR}=="Hewlett-Packard*", ATTR{[dmi/id]product_name}=="*[pP][aA][vV][iI][lL][iI][oO][nN]*", RUN+="keyboard-force-release.sh $devpath hp-other"
+ENV{DMI_VENDOR}=="Hewlett-Packard*", ATTR{[dmi/id]product_name}=="*[tT][xX]2*", RUN+="keyboard-force-release.sh $devpath hp-other"
+ENV{DMI_VENDOR}=="Hewlett-Packard*", ATTR{[dmi/id]product_name}=="*2510p*|*2530p*|HP G60 Notebook PC|HDX9494NR", RUN+="keyboard-force-release.sh $devpath hp-other"
+
+ENV{DMI_VENDOR}=="Zepto", ATTR{[dmi/id]product_name}=="Znote 6615WD", RUN+="keyboard-force-release.sh $devpath common-volume-keys"
+
+ENV{DMI_VENDOR}=="Zepto", ATTR{[dmi/id]product_name}=="Znote", ATTR{[dmi/id]product_version}=="6625WD", RUN+="keyboard-force-release.sh $devpath common-volume-keys"
+
+ENV{DMI_VENDOR}=="HANNspree", ATTR{[dmi/id]product_name}=="SN10E100", RUN+="keyboard-force-release.sh $devpath common-volume-keys"
+
+ENV{DMI_VENDOR}=="GIGABYTE", ATTR{[dmi/id]product_name}=="i1520M", RUN+="keyboard-force-release.sh $devpath common-volume-keys"
+
+ENV{DMI_VENDOR}=="BenQ", ATTR{[dmi/id]product_name}=="*nScreen*", RUN+="keyboard-force-release.sh $devpath common-volume-keys"
+
+LABEL="force_release_end"
diff --git a/src/udev/keymap/95-keymap.rules b/src/udev/keymap/95-keymap.rules
new file mode 100644
index 0000000000..7956092030
--- /dev/null
+++ b/src/udev/keymap/95-keymap.rules
@@ -0,0 +1,183 @@
+# Set model specific hotkey keycodes.
+#
+# Key map overrides can be specified by either giving scancode/keyname pairs
+# directly as keymap arguments (if there are just one or two to change), or as
+# a file name (in /usr/lib/udev/keymaps), which has to contain scancode/keyname
+# pairs.
+
+ACTION=="remove", GOTO="keyboard_end"
+KERNEL!="event*", GOTO="keyboard_end"
+ENV{ID_INPUT_KEY}=="", GOTO="keyboard_end"
+SUBSYSTEMS=="bluetooth", GOTO="keyboard_end"
+
+SUBSYSTEMS=="usb", IMPORT{builtin}="usb_id"
+SUBSYSTEMS=="usb", GOTO="keyboard_usbcheck"
+GOTO="keyboard_modulecheck"
+
+#
+# The following are external USB keyboards
+#
+
+LABEL="keyboard_usbcheck"
+
+ENV{ID_VENDOR}=="Genius", ENV{ID_MODEL_ID}=="0708", ENV{ID_USB_INTERFACE_NUM}=="01", RUN+="keymap $name genius-slimstar-320"
+ENV{ID_VENDOR}=="Logitech*", ATTRS{name}=="Logitech USB Multimedia Keyboard", RUN+="keymap $name logitech-wave"
+ENV{ID_VENDOR}=="Logitech*", ATTRS{name}=="Logitech USB Receiver", RUN+="keymap $name logitech-wave-cordless"
+# Logitech Cordless Wave Pro looks slightly weird; some hotkeys are coming through the mouse interface
+ENV{ID_VENDOR_ID}=="046d", ENV{ID_MODEL_ID}=="c52[9b]", ATTRS{name}=="Logitech USB Receiver", RUN+="keymap $name logitech-wave-pro-cordless"
+
+ENV{ID_VENDOR}=="Lite-On_Technology_Corp*", ATTRS{name}=="Lite-On Technology Corp. ThinkPad USB Keyboard with TrackPoint", RUN+="keymap $name lenovo-thinkpad-usb-keyboard-trackpoint"
+ENV{ID_VENDOR_ID}=="04b3", ENV{ID_MODEL_ID}=="301[89]", RUN+="keymap $name ibm-thinkpad-usb-keyboard-trackpoint"
+
+ENV{ID_VENDOR}=="Microsoft", ENV{ID_MODEL_ID}=="00db", RUN+="keymap $name 0xc022d zoomin 0xc022e zoomout"
+
+GOTO="keyboard_end"
+
+#
+# The following are exposed as separate input devices with low key codes, thus
+# we need to check their input device product name
+#
+
+LABEL="keyboard_modulecheck"
+
+ENV{DMI_VENDOR}="$attr{[dmi/id]sys_vendor}"
+ENV{DMI_VENDOR}=="", GOTO="keyboard_end"
+
+ENV{DMI_VENDOR}=="LENOVO*", KERNELS=="input*", ATTRS{name}=="ThinkPad Extra Buttons", RUN+="keymap $name module-lenovo"
+ENV{DMI_VENDOR}=="LENOVO*", KERNELS=="input*", ATTRS{name}=="Lenovo ThinkPad SL Series extra buttons", RUN+="keymap $name 0x0E bluetooth"
+ENV{DMI_VENDOR}=="LENOVO*", KERNELS=="input*", ATTRS{name}=="Ideapad extra buttons", RUN+="keymap $name 0x42 f23 0x43 f22"
+
+ENV{DMI_VENDOR}=="ASUS*", KERNELS=="input*", ATTRS{name}=="Asus Extra Buttons", ATTR{[dmi/id]product_name}=="W3J", RUN+="keymap $name module-asus-w3j"
+ENV{DMI_VENDOR}=="ASUS*", KERNELS=="input*", ATTRS{name}=="Eee PC WMI hotkeys|Asus Laptop Support|Asus*WMI*", RUN+="keymap $name 0x6B f21"
+ENV{DMI_VENDOR}=="ASUS*", KERNELS=="input*", ATTRS{name}=="Eee PC Hotkey Driver", RUN+="keymap $name 0x37 f21"
+
+ENV{DMI_VENDOR}=="IBM*", KERNELS=="input*", ATTRS{name}=="ThinkPad Extra Buttons", RUN+="keymap $name module-ibm"
+ENV{DMI_VENDOR}=="Sony*", KERNELS=="input*", ATTRS{name}=="Sony Vaio Keys", RUN+="keymap $name module-sony"
+ENV{DMI_VENDOR}=="Acer*", KERNELS=="input*", ATTRS{name}=="Acer WMI hotkeys", RUN+="keymap $name 0x82 f21"
+ENV{DMI_VENDOR}=="MICRO-STAR*|Micro-Star*", KERNELS=="input*", ATTRS{name}=="MSI Laptop hotkeys", RUN+="keymap $name 0x213 f22 0x214 f23"
+
+# Older Vaios have some different keys
+ENV{DMI_VENDOR}=="Sony*", ATTR{[dmi/id]product_name}=="*PCG-C1*|*PCG-K25*|*PCG-F1*|*PCG-F2*|*PCG-F3*|*PCG-F4*|*PCG-F5*|*PCG-F6*|*PCG-FX*|*PCG-FRV*|*PCG-GR*|*PCG-TR*|*PCG-NV*|*PCG-Z*|*VGN-S360*", ATTRS{name}=="Sony Vaio Keys", RUN+="keymap $name module-sony-old"
+
+# Some Sony VGN/VPC models have yet another one
+ENV{DMI_VENDOR}=="Sony*", ATTR{[dmi/id]product_name}=="VGN-AR71*|VGN-FW*|VGN-Z21*", ATTRS{name}=="Sony Vaio Keys", RUN+="keymap $name module-sony-vgn"
+ENV{DMI_VENDOR}=="Sony*", ATTR{[dmi/id]product_name}=="VPC*", ATTRS{name}=="Sony Vaio Keys", RUN+="keymap $name module-sony-vpc"
+
+
+#
+# The following rules belong to standard i8042 AT keyboard with high key codes.
+#
+
+DRIVERS=="atkbd", GOTO="keyboard_vendorcheck"
+GOTO="keyboard_end"
+
+LABEL="keyboard_vendorcheck"
+
+ENV{DMI_VENDOR}=="Dell*", RUN+="keymap $name dell"
+ENV{DMI_VENDOR}=="Dell*", ATTR{[dmi/id]product_name}=="Inspiron 910|Inspiron 1010|Inspiron 1011|Inspiron 1012|Inspiron 1110|Inspiron 1210", RUN+="keymap $name 0x84 wlan"
+ENV{DMI_VENDOR}=="Dell*", ATTR{[dmi/id]product_name}=="Latitude XT2", RUN+="keymap $name dell-latitude-xt2"
+
+ENV{DMI_VENDOR}=="Compaq*", ATTR{[dmi/id]product_name}=="*E500*|*Evo N*", RUN+="keymap $name compaq-e_evo"
+
+ENV{DMI_VENDOR}=="LENOVO*", ATTR{[dmi/id]product_version}=="*3000*", RUN+="keymap $name lenovo-3000"
+ENV{DMI_VENDOR}=="LENOVO*", ATTR{[dmi/id]product_version}=="ThinkPad X6*", ATTR{[dmi/id]product_version}=="* Tablet", RUN+="keymap $name lenovo-thinkpad_x6_tablet"
+ENV{DMI_VENDOR}=="LENOVO*", ATTR{[dmi/id]product_version}=="ThinkPad X2* Tablet*", ATTR{[dmi/id]product_version}=="* Tablet", RUN+="keymap $name lenovo-thinkpad_x200_tablet"
+ENV{DMI_VENDOR}=="LENOVO*", ATTR{[dmi/id]product_version}=="*IdeaPad*", RUN+="keymap $name lenovo-ideapad"
+ENV{DMI_VENDOR}=="LENOVO*", ATTR{[dmi/id]product_name}=="S10-*", RUN+="keymap $name lenovo-ideapad"
+ENV{DMI_VENDOR}=="LENOVO", ATTR{[dmi/id]product_version}=="*IdeaPad Y550*", RUN+="keymap $name 0x95 media 0xA3 play"
+ENV{DMI_VENDOR}=="LENOVO", ATTR{[dmi/id]product_version}=="*Lenovo V480*", RUN+="keymap $name 0xf1 f21"
+# 0xf1 is touchpad toggle, 0xCE is microphone mute in Lenovo U300s
+ENV{DMI_VENDOR}=="LENOVO", ATTR{[dmi/id]product_version}=="*IdeaPad U300s*", RUN+="keymap $name 0xf1 f21 0xCE f20"
+
+ENV{DMI_VENDOR}=="Hewlett-Packard*", RUN+="keymap $name hewlett-packard"
+ENV{DMI_VENDOR}=="Hewlett-Packard*", ATTR{[dmi/id]product_name}=="*[tT][aA][bB][lL][eE][tT]*", RUN+="keymap $name hewlett-packard-tablet"
+ENV{DMI_VENDOR}=="Hewlett-Packard*", ATTR{[dmi/id]product_name}=="*[pP][aA][vV][iI][lL][iI][oO][nN]*", RUN+="keymap $name hewlett-packard-pavilion"
+ENV{DMI_VENDOR}=="Hewlett-Packard*", ATTR{[dmi/id]product_name}=="*Compaq*|*EliteBook*|*2230s*", RUN+="keymap $name hewlett-packard-compaq_elitebook"
+ENV{DMI_VENDOR}=="Hewlett-Packard*", ATTR{[dmi/id]product_name}=="*Presario*CQ*", RUN+="keymap $name 0xD8 f21 0xD9 f21"
+ENV{DMI_VENDOR}=="Hewlett-Packard*", ATTR{[dmi/id]product_name}=="*2510p*|*2530p*|HP G60 Notebook PC", RUN+="keymap $name hewlett-packard-2510p_2530p"
+ENV{DMI_VENDOR}=="Hewlett-Packard*", ATTR{[dmi/id]product_name}=="*[tT][xX]2*", RUN+="keymap $name hewlett-packard-tx2"
+ENV{DMI_VENDOR}=="Hewlett-Packard", ATTR{[dmi/id]product_name}=="Presario 2100*", RUN+="keymap $name hewlett-packard-presario-2100"
+ENV{DMI_VENDOR}=="Hewlett-Packard", ATTR{[dmi/id]product_name}=="HP G62 Notebook PC", RUN+="keymap $name 0xB2 www"
+ENV{DMI_VENDOR}=="Hewlett-Packard", ATTR{[dmi/id]product_name}=="HP ProBook*", RUN+="keymap $name 0xF8 rfkill 0xB2 www"
+ENV{DMI_VENDOR}=="Hewlett-Packard", ATTR{[dmi/id]product_name}=="HP EliteBook 8440p", RUN+="keymap $name hewlett-packard_elitebook-8440p"
+ENV{DMI_VENDOR}=="Hewlett-Packard", ATTR{[dmi/id]product_name}=="HP EliteBook 8460p", RUN+="keymap $name hewlett-packard_elitebook-8460p"
+ENV{DMI_VENDOR}=="Hewlett-Packard", ATTR{[dmi/id]product_name}=="HDX9494NR", RUN+="keymap $name hewlett-packard-hdx9494nr"
+# HP Pavilion dv6315ea has empty DMI_VENDOR
+ATTR{[dmi/id]board_vendor}=="Quanta", ATTR{[dmi/id]board_name}=="30B7", ATTR{[dmi/id]board_version}=="65.2B", RUN+="keymap $name 0x88 media" # "quick play
+
+# Gateway clone of Acer Aspire One AOA110/AOA150
+ENV{DMI_VENDOR}=="Gateway*", ATTR{[dmi/id]product_name}=="*AOA1*", RUN+="keymap $name acer"
+
+ENV{DMI_VENDOR}=="Acer*", RUN+="keymap $name acer"
+ENV{DMI_VENDOR}=="Acer*", ATTR{[dmi/id]product_name}=="Extensa*", ATTR{[dmi/id]product_name}=="*5210*|*5220*|*5610*|*5620*|*5720*", RUN+="keymap $name 0xEE screenlock"
+ENV{DMI_VENDOR}=="Acer*", ATTR{[dmi/id]product_name}=="TravelMate*C3[01]0*", RUN+="keymap $name acer-travelmate_c300"
+ENV{DMI_VENDOR}=="Acer*", ATTR{[dmi/id]product_name}=="TravelMate*6292*|TravelMate*8471*|TravelMate*4720*|TravelMate*7720*|Aspire 1810T*|AO751h|AO531h", RUN+="keymap $name 0xD9 bluetooth"
+ENV{DMI_VENDOR}=="Acer*", ATTR{[dmi/id]product_name}=="TravelMate*4720*", RUN+="keymap $name 0xB2 www 0xEE screenlock"
+ENV{DMI_VENDOR}=="Acer*", ATTR{[dmi/id]product_name}=="TravelMate 6593|Aspire 1640", RUN+="keymap $name 0xB2 www 0xEE screenlock"
+ENV{DMI_VENDOR}=="Acer*", ATTR{[dmi/id]product_name}=="Aspire 6920", RUN+="keymap $name acer-aspire_6920"
+ENV{DMI_VENDOR}=="Acer*", ATTR{[dmi/id]product_name}=="Aspire 5920G", RUN+="keymap $name acer-aspire_5920g"
+ENV{DMI_VENDOR}=="Acer*", ATTR{[dmi/id]product_name}=="Aspire 5720*", RUN+="keymap $name acer-aspire_5720"
+ENV{DMI_VENDOR}=="Acer*", ATTR{[dmi/id]product_name}=="Aspire 8930", RUN+="keymap $name acer-aspire_8930"
+ENV{DMI_VENDOR}=="Acer*", ATTR{[dmi/id]product_serial}=="ZG8*", RUN+="keymap $name acer-aspire_5720"
+
+ENV{DMI_VENDOR}=="*BenQ*", ATTR{[dmi/id]product_name}=="*Joybook R22*", RUN+="keymap $name 0x6E wlan"
+
+ENV{DMI_VENDOR}=="FUJITSU*", ATTR{[dmi/id]product_name}=="*AMILO Pro V3205*", RUN+="keymap $name fujitsu-amilo_pro_v3205"
+ENV{DMI_VENDOR}=="FUJITSU*", ATTR{[dmi/id]product_name}=="*AMILO Pa 2548*", RUN+="keymap $name fujitsu-amilo_pa_2548"
+ENV{DMI_VENDOR}=="FUJITSU*", ATTR{[dmi/id]product_name}=="*ESPRIMO Mobile V5*", RUN+="keymap $name fujitsu-esprimo_mobile_v5"
+ENV{DMI_VENDOR}=="FUJITSU*", ATTR{[dmi/id]product_name}=="*ESPRIMO Mobile V6*", RUN+="keymap $name fujitsu-esprimo_mobile_v6"
+ENV{DMI_VENDOR}=="FUJITSU*", ATTR{[dmi/id]product_name}=="*AMILO Pro Edition V3505*", RUN+="keymap $name fujitsu-amilo_pro_edition_v3505"
+ENV{DMI_VENDOR}=="FUJITSU*", ATTR{[dmi/id]product_name}=="*Amilo Si 1520*", RUN+="keymap $name fujitsu-amilo_si_1520"
+ENV{DMI_VENDOR}=="FUJITSU*", ATTR{[dmi/id]product_name}=="AMILO*M*", RUN+="keymap $name 0x97 prog2 0x9F prog1"
+ENV{DMI_VENDOR}=="FUJITSU*", ATTR{[dmi/id]product_name}=="Amilo Li 1718", RUN+="keymap $name 0xD6 wlan"
+ENV{DMI_VENDOR}=="FUJITSU*", ATTR{[dmi/id]product_name}=="AMILO Li 2732", RUN+="keymap $name fujitsu-amilo_li_2732"
+
+ENV{DMI_VENDOR}=="LG*", ATTR{[dmi/id]product_name}=="*X110*", RUN+="keymap $name lg-x110"
+
+ENV{DMI_VENDOR}=="MEDION*", ATTR{[dmi/id]product_name}=="*FID2060*", RUN+="keymap $name medion-fid2060"
+ENV{DMI_VENDOR}=="MEDIONNB", ATTR{[dmi/id]product_name}=="A555*", RUN+="keymap $name medionnb-a555"
+
+ENV{DMI_VENDOR}=="MICRO-STAR*|Micro-Star*", RUN+="keymap $name micro-star"
+
+# some MSI models generate ACPI/input events on the LNXVIDEO input devices,
+# plus some extra synthesized ones on atkbd as an echo of actually changing the
+# brightness; so ignore those atkbd ones, to avoid loops
+ENV{DMI_VENDOR}=="MICRO-STAR*", ATTR{[dmi/id]product_name}=="*U-100*|*U100*|*N033", RUN+="keymap $name 0xF7 reserved 0xF8 reserved"
+
+# MSI Wind U90/U100 generates separate touchpad on/off keycodes so ignore touchpad toggle keycode
+ENV{DMI_VENDOR}=="MICRO-STAR*", ATTR{[dmi/id]product_name}=="U90/U100", RUN+="keymap $name 0xE4 reserved"
+
+ENV{DMI_VENDOR}=="INVENTEC", ATTR{[dmi/id]product_name}=="SYMPHONY 6.0/7.0", RUN+="keymap $name inventec-symphony_6.0_7.0"
+
+ENV{DMI_VENDOR}=="MAXDATA", ATTR{[dmi/id]product_name}=="Pro 7000*", RUN+="keymap $name maxdata-pro_7000"
+
+ENV{DMI_VENDOR}=="[sS][aA][mM][sS][uU][nN][gG]*", RUN+="keymap $name samsung-other"
+ENV{DMI_VENDOR}=="[sS][aA][mM][sS][uU][nN][gG]*", ATTR{[dmi/id]product_name}=="*SX20S*", RUN+="keymap $name samsung-sx20s"
+ENV{DMI_VENDOR}=="[sS][aA][mM][sS][uU][nN][gG]*", ATTR{[dmi/id]product_name}=="SQ1US", RUN+="keymap $name samsung-sq1us"
+ENV{DMI_VENDOR}=="[sS][aA][mM][sS][uU][nN][gG]*", ATTR{[dmi/id]product_name}=="*700Z*", RUN+="keymap $name 0xBA ejectcd 0x96 keyboardbrightnessup 0x97 keyboardbrightnessdown"
+ENV{DMI_VENDOR}=="[sS][aA][mM][sS][uU][nN][gG]*", ATTR{[dmi/id]product_name}=="*700T*", RUN+="keymap $name 0xAD leftmeta"
+ENV{DMI_VENDOR}=="[sS][aA][mM][sS][uU][nN][gG]*", ATTR{[dmi/id]product_name}=="*90X3A*|*900X3*|*900X4*", RUN+="keymap $name samsung-series-9"
+
+ENV{DMI_VENDOR}=="TOSHIBA", ATTR{[dmi/id]product_name}=="SATELLITE A100", RUN+="keymap $name toshiba-satellite_a100"
+ENV{DMI_VENDOR}=="TOSHIBA", ATTR{[dmi/id]product_name}=="Satellite A110", RUN+="keymap $name toshiba-satellite_a110"
+ENV{DMI_VENDOR}=="TOSHIBA", ATTR{[dmi/id]product_name}=="Satellite M30X", RUN+="keymap $name toshiba-satellite_m30x"
+
+ENV{DMI_VENDOR}=="OQO Inc.*", ATTR{[dmi/id]product_name}=="OQO Model 2*", RUN+="keymap $name oqo-model2"
+
+ENV{DMI_VENDOR}=="ONKYO CORPORATION", ATTR{[dmi/id]product_name}=="ONKYOPC", RUN+="keymap $name onkyo"
+
+ENV{DMI_VENDOR}=="ASUS", RUN+="keymap $name asus"
+
+ENV{DMI_VENDOR}=="VIA", ATTR{[dmi/id]product_name}=="K8N800", ATTR{[dmi/id]product_version}=="VT8204B", RUN+="keymap $name 0x81 prog1"
+
+ENV{DMI_VENDOR}=="Zepto", ATTR{[dmi/id]product_name}=="Znote", ATTR{[dmi/id]product_version}=="62*|63*", RUN+="keymap $name zepto-znote"
+
+ENV{DMI_VENDOR}=="Everex", ATTR{[dmi/id]product_name}=="XT5000*", RUN+="keymap $name everex-xt5000"
+
+ENV{DMI_VENDOR}=="COMPAL", ATTR{[dmi/id]product_name}=="HEL80I", RUN+="keymap $name 0x84 wlan"
+
+ENV{DMI_VENDOR}=="OLPC", ATTR{[dmi/id]product_name}=="XO", RUN+="keymap $name olpc-xo"
+
+ENV{DMI_VENDOR}=="Alienware*", ATTR{[dmi/id]product_name}=="M14xR1", RUN+="keymap $name 0x8A ejectcd"
+
+LABEL="keyboard_end"
diff --git a/src/udev/keymap/README.keymap.txt b/src/udev/keymap/README.keymap.txt
new file mode 100644
index 0000000000..2cf2a4e88c
--- /dev/null
+++ b/src/udev/keymap/README.keymap.txt
@@ -0,0 +1,97 @@
+= The udev keymap tool =
+
+== Introduction ==
+
+This udev extension configures computer model specific key mappings. This is
+particularly necessary for the non-standard extra keys found on many laptops,
+such as "brightness up", "next song", "www browser", or "suspend". Often these
+are accessed with the Fn key.
+
+Every key produces a "scan code", which is highly vendor/model specific for the
+nonstandard keys. This tool maintains mappings for these scan codes to standard
+"key codes", which denote the "meaning" of the key. The key codes are defined
+in /usr/include/linux/input.h.
+
+If some of your keys on your keyboard are not working at all, or produce the
+wrong effect, then a very likely cause of this is that the scan code -> key
+code mapping is incorrect on your computer.
+
+== Structure ==
+
+udev-keymap consists of the following parts:
+
+ keymaps/*:: mappings of scan codes to key code names
+
+ 95-keymap.rules:: udev rules for mapping system vendor/product names and
+ input module names to one of the keymaps above
+
+ keymap:: manipulate an evdev input device:
+ * write a key map file into a device (used by udev rules)
+ * dump current scan → key code mapping
+ * interactively display scan and key codes of pressed keys
+
+ findkeyboards:: display evdev input devices which belong to actual keyboards,
+ i. e. those suitable for the keymap program
+
+== Fixing broken keys ==
+
+In order to make a broken key work on your system and send it back to upstream
+for inclusion you need to do the following steps:
+
+ 1. Find the keyboard device.
+
+ Run /usr/lib/udev/findkeyboards. This should always give you an "AT
+ keyboard" and possibly a "module". Some laptops (notably Thinkpads, Sonys, and
+ Acers) have multimedia/function keys on a separate input device instead of the
+ primary keyboard. The keyboard device should have a name like "input/event3".
+ In the following commands, the name will be written as "input/eventX" (replace
+ X with the appropriate number).
+
+ 2. Find broken scan codes:
+
+ sudo /usr/lib/udev/keymap -i input/eventX
+
+ Press all multimedia/function keys and check if the key name that gets printed
+ out is plausible. If it is unknown or wrong, write down the scan code (looks
+ like "0x1E") and the intended functionality of this key. Look in
+ /usr/include/linux/input.h for an available KEY_XXXXX constant which most
+ closely approximates this functionality and write it down as the new key code.
+
+ For example, you might press a key labeled "web browser" which currently
+ produces "unknown". Note down this:
+
+ 0x1E www # Fn+F2 web browser
+
+ Repeat that for all other keys. Write the resulting list into a file. Look at
+ /usr/lib/udev/keymaps/ for existing key map files and make sure that you use the
+ same structure.
+
+ If the key only ever works once and then your keyboard (or the entire desktop)
+ gets stuck for a long time, then it is likely that the BIOS fails to send a
+ corresponding "key release" event after the key press event. Please note down
+ this case as well, as it can be worked around in
+ /usr/lib/udev/keymaps/95-keyboard-force-release.rules .
+
+ 3. Find out your system vendor and product:
+
+ cat /sys/class/dmi/id/sys_vendor
+ cat /sys/class/dmi/id/product_name
+
+ 4. Generate a device dump with "udevadm info --export-db > /tmp/udev-db.txt".
+
+ 6. Send the system vendor/product names, the key mapping from step 2,
+ and /tmp/udev-db.txt from step 4 to the linux-hotplug@vger.kernel.org mailing
+ list, so that they can be included in the next release.
+
+For local testing, copy your map file to /usr/lib/udev/keymaps/ with an appropriate
+name, and add an appropriate udev rule to /usr/lib/udev/rules.d/95-keymap.rules:
+
+ * If you selected an "AT keyboard", add the rule to the section after
+ 'LABEL="keyboard_vendorcheck"'.
+
+ * If you selected a "module", add the rule to the top section where the
+ "ThinkPad Extra Buttons" are.
+
+== Author ==
+
+keymap is written and maintained by Martin Pitt <martin.pitt@ubuntu.com>.
diff --git a/src/udev/keymap/check-keymaps.sh b/src/udev/keymap/check-keymaps.sh
new file mode 100755
index 0000000000..c4572745e0
--- /dev/null
+++ b/src/udev/keymap/check-keymaps.sh
@@ -0,0 +1,38 @@
+#!/bin/bash
+
+# check that all key names in keymaps/* are known in <linux/input.h>
+# and that all key maps listed in the rules are valid and present in
+# Makefile.am
+SRCDIR=${1:-.}
+KEYLIST=${2:-src/udev/keymap/keys.txt}
+KEYMAPS_DIR=$SRCDIR/keymaps
+RULES=$SRCDIR/src/udev/keymap/95-keymap.rules
+
+[ -e "$KEYLIST" ] || {
+ echo "need $KEYLIST please build first" >&2
+ exit 1
+}
+
+missing=$(join -v 2 <(awk '{print tolower(substr($1,5))}' $KEYLIST | sort -u) \
+ <(grep -hv '^#' ${KEYMAPS_DIR}/*| awk '{print $2}' | sort -u))
+[ -z "$missing" ] || {
+ echo "ERROR: unknown key names in keymaps/*:" >&2
+ echo "$missing" >&2
+ exit 1
+}
+
+# check that all maps referred to in $RULES exist
+maps=$(sed -rn '/keymap \$name/ { s/^.*\$name ([^"[:space:]]+).*$/\1/; p }' $RULES)
+for m in $maps; do
+ # ignore inline mappings
+ [ "$m" = "${m#0x}" ] || continue
+
+ [ -e ${KEYMAPS_DIR}/$m ] || {
+ echo "ERROR: unknown map name in $RULES: $m" >&2
+ exit 1
+ }
+ grep -q "keymaps/$m\>" $SRCDIR/Makefile.am || {
+ echo "ERROR: map file $m is not added to Makefile.am" >&2
+ exit 1
+ }
+done
diff --git a/src/udev/keymap/findkeyboards b/src/udev/keymap/findkeyboards
new file mode 100755
index 0000000000..c6b50d12d0
--- /dev/null
+++ b/src/udev/keymap/findkeyboards
@@ -0,0 +1,68 @@
+#!/bin/sh -e
+# Find "real" keyboard devices and print their device path.
+# Author: Martin Pitt <martin.pitt@ubuntu.com>
+#
+# Copyright (C) 2009, Canonical Ltd.
+#
+# This program is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+
+# returns OK if $1 contains $2
+strstr() {
+ [ "${1#*$2*}" != "$1" ]
+}
+
+# returns OK if $1 contains $2 at the beginning
+str_starts() {
+ [ "${1#$2*}" != "$1" ]
+}
+
+str_line_starts() {
+ while read a; do str_starts "$a" "$1" && return 0;done
+ return 1;
+}
+
+# print a list of input devices which are keyboard-like
+keyboard_devices() {
+ # standard AT keyboard
+ for dev in `udevadm trigger --dry-run --verbose --property-match=ID_INPUT_KEYBOARD=1`; do
+ env=`udevadm info --query=env --path=$dev`
+ # filter out non-event devices, such as the parent input devices which have no devnode
+ if ! echo "$env" | str_line_starts 'DEVNAME='; then
+ continue
+ fi
+ walk=`udevadm info --attribute-walk --path=$dev`
+ if strstr "$walk" 'DRIVERS=="atkbd"'; then
+ echo -n 'AT keyboard: '
+ elif echo "$env" | str_line_starts 'ID_USB_DRIVER=usbhid'; then
+ echo -n 'USB keyboard: '
+ else
+ echo -n 'Unknown type: '
+ fi
+ udevadm info --query=name --path=$dev
+ done
+
+ # modules
+ module=$(udevadm trigger --verbose --dry-run --subsystem-match=input --attr-match=name='*Extra Buttons')
+ module="$module
+ $(udevadm trigger --verbose --dry-run --subsystem-match=input --attr-match=name='*extra buttons')"
+ module="$module
+ $(udevadm trigger --verbose --dry-run --subsystem-match=input --attr-match=name='Sony Vaio Keys')"
+ for m in $module; do
+ for evdev in $m/event*/dev; do
+ if [ -e "$evdev" ]; then
+ echo -n 'module: '
+ udevadm info --query=name --path=${evdev%%/dev}
+ fi
+ done
+ done
+}
+
+keyboard_devices
diff --git a/src/udev/keymap/keyboard-force-release.sh b/src/udev/keymap/keyboard-force-release.sh
new file mode 100755
index 0000000000..858caabf9f
--- /dev/null
+++ b/src/udev/keymap/keyboard-force-release.sh
@@ -0,0 +1,22 @@
+#!/bin/sh -e
+# read list of scancodes, convert hex to decimal and
+# append to the atkbd force_release sysfs attribute
+# $1 sysfs devpath for serioX
+# $2 file with scancode list (hex or dec)
+
+case "$2" in
+ /*) scf="$2" ;;
+ *) scf="/usr/lib/udev/keymaps/force-release/$2" ;;
+esac
+
+read attr <"/sys/$1/force_release"
+while read scancode dummy; do
+ case "$scancode" in
+ \#*) ;;
+ *)
+ scancode=$(($scancode))
+ attr="$attr${attr:+,}$scancode"
+ ;;
+ esac
+done <"$scf"
+echo "$attr" >"/sys/$1/force_release"
diff --git a/src/udev/keymap/keyboard-force-release.sh.in b/src/udev/keymap/keyboard-force-release.sh.in
new file mode 100755
index 0000000000..b82674840f
--- /dev/null
+++ b/src/udev/keymap/keyboard-force-release.sh.in
@@ -0,0 +1,22 @@
+#!/bin/sh -e
+# read list of scancodes, convert hex to decimal and
+# append to the atkbd force_release sysfs attribute
+# $1 sysfs devpath for serioX
+# $2 file with scancode list (hex or dec)
+
+case "$2" in
+ /*) scf="$2" ;;
+ *) scf="@udevlibexecdir@/keymaps/force-release/$2" ;;
+esac
+
+read attr <"/sys/$1/force_release"
+while read scancode dummy; do
+ case "$scancode" in
+ \#*) ;;
+ *)
+ scancode=$(($scancode))
+ attr="$attr${attr:+,}$scancode"
+ ;;
+ esac
+done <"$scf"
+echo "$attr" >"/sys/$1/force_release"
diff --git a/src/udev/keymap/keymap.c b/src/udev/keymap/keymap.c
new file mode 100644
index 0000000000..ae0a19d3a3
--- /dev/null
+++ b/src/udev/keymap/keymap.c
@@ -0,0 +1,453 @@
+/*
+ * keymap - dump keymap of an evdev device or set a new keymap from a file
+ *
+ * Based on keyfuzz by Lennart Poettering <mzqrovna@0pointer.net>
+ * Adapted for udev-extras by Martin Pitt <martin.pitt@ubuntu.com>
+ *
+ * Copyright (C) 2006, Lennart Poettering
+ * Copyright (C) 2009, Canonical Ltd.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdint.h>
+#include <ctype.h>
+#include <unistd.h>
+#include <errno.h>
+#include <limits.h>
+#include <fcntl.h>
+#include <getopt.h>
+#include <sys/ioctl.h>
+#include <linux/limits.h>
+#include <linux/input.h>
+
+static const struct key* lookup_key (const char *str, unsigned int len);
+
+#include "keys-from-name.h"
+#include "keys-to-name.h"
+#include "macro.h"
+#include "util.h"
+
+#define MAX_SCANCODES 1024
+
+static int evdev_open(const char *dev)
+{
+ int fd;
+ char fn[PATH_MAX];
+
+ if (!startswith(dev, "/dev")) {
+ snprintf(fn, sizeof(fn), "/dev/%s", dev);
+ dev = fn;
+ }
+
+ if ((fd = open(dev, O_RDWR)) < 0) {
+ fprintf(stderr, "error open('%s'): %m\n", dev);
+ return -1;
+ }
+ return fd;
+}
+
+static int evdev_get_keycode(int fd, unsigned scancode, int e)
+{
+ unsigned codes[2];
+
+ codes[0] = scancode;
+ if (ioctl(fd, EVIOCGKEYCODE, codes) < 0) {
+ if (e && errno == EINVAL) {
+ return -2;
+ } else {
+ fprintf(stderr, "EVIOCGKEYCODE for scan code 0x%x: %m\n", scancode);
+ return -1;
+ }
+ }
+ return codes[1];
+}
+
+static int evdev_set_keycode(int fd, unsigned scancode, int keycode)
+{
+ unsigned codes[2];
+
+ codes[0] = scancode;
+ codes[1] = (unsigned) keycode;
+
+ if (ioctl(fd, EVIOCSKEYCODE, codes) < 0) {
+ fprintf(stderr, "EVIOCSKEYCODE: %m\n");
+ return -1;
+ }
+ return 0;
+}
+
+static int evdev_driver_version(int fd, char *v, size_t l)
+{
+ int version;
+
+ if (ioctl(fd, EVIOCGVERSION, &version)) {
+ fprintf(stderr, "EVIOCGVERSION: %m\n");
+ return -1;
+ }
+
+ snprintf(v, l, "%i.%i.%i.", version >> 16, (version >> 8) & 0xff, version & 0xff);
+ return 0;
+}
+
+static int evdev_device_name(int fd, char *n, size_t l)
+{
+ if (ioctl(fd, EVIOCGNAME(l), n) < 0) {
+ fprintf(stderr, "EVIOCGNAME: %m\n");
+ return -1;
+ }
+ return 0;
+}
+
+/* Return a lower-case string with KEY_ prefix removed */
+static const char* format_keyname(const char* key) {
+ static char result[101];
+ const char* s;
+ int len;
+
+ for (s = key+4, len = 0; *s && len < 100; ++len, ++s)
+ result[len] = tolower(*s);
+ result[len] = '\0';
+ return result;
+}
+
+static int dump_table(int fd) {
+ char version[256], name[256];
+ unsigned scancode;
+ int r = -1;
+
+ if (evdev_driver_version(fd, version, sizeof(version)) < 0)
+ goto fail;
+
+ if (evdev_device_name(fd, name, sizeof(name)) < 0)
+ goto fail;
+
+ printf("### evdev %s, driver '%s'\n", version, name);
+
+ r = 0;
+ for (scancode = 0; scancode < MAX_SCANCODES; scancode++) {
+ int keycode;
+
+ if ((keycode = evdev_get_keycode(fd, scancode, 1)) < 0) {
+ if (keycode == -2)
+ continue;
+ r = -1;
+ break;
+ }
+
+ if (keycode < KEY_MAX && key_names[keycode])
+ printf("0x%03x %s\n", scancode, format_keyname(key_names[keycode]));
+ else
+ printf("0x%03x 0x%03x\n", scancode, keycode);
+ }
+fail:
+ return r;
+}
+
+static void set_key(int fd, const char* scancode_str, const char* keyname)
+{
+ unsigned scancode;
+ char *endptr;
+ char t[105] = "KEY_UNKNOWN";
+ const struct key *k;
+
+ scancode = (unsigned) strtol(scancode_str, &endptr, 0);
+ if (*endptr != '\0') {
+ fprintf(stderr, "ERROR: Invalid scancode\n");
+ exit(1);
+ }
+
+ snprintf(t, sizeof(t), "KEY_%s", keyname);
+
+ if (!(k = lookup_key(t, strlen(t)))) {
+ fprintf(stderr, "ERROR: Unknown key name '%s'\n", keyname);
+ exit(1);
+ }
+
+ if (evdev_set_keycode(fd, scancode, k->id) < 0)
+ fprintf(stderr, "setting scancode 0x%2X to key code %i failed\n",
+ scancode, k->id);
+ else
+ printf("setting scancode 0x%2X to key code %i\n",
+ scancode, k->id);
+}
+
+static int merge_table(int fd, FILE *f) {
+ int r = 0;
+ int line = 0;
+
+ while (!feof(f)) {
+ char s[256], *p;
+ unsigned scancode;
+ int new_keycode, old_keycode;
+
+ if (!fgets(s, sizeof(s), f))
+ break;
+
+ line++;
+ p = s+strspn(s, "\t ");
+ if (*p == '#' || *p == '\n')
+ continue;
+
+ if (sscanf(p, "%i %i", &scancode, &new_keycode) != 2) {
+ char t[105] = "KEY_UNKNOWN";
+ const struct key *k;
+
+ if (sscanf(p, "%i %100s", &scancode, t+4) != 2) {
+ fprintf(stderr, "WARNING: Parse failure at line %i, ignoring.\n", line);
+ r = -1;
+ continue;
+ }
+
+ if (!(k = lookup_key(t, strlen(t)))) {
+ fprintf(stderr, "WARNING: Unknown key '%s' at line %i, ignoring.\n", t, line);
+ r = -1;
+ continue;
+ }
+
+ new_keycode = k->id;
+ }
+
+
+ if ((old_keycode = evdev_get_keycode(fd, scancode, 0)) < 0) {
+ r = -1;
+ continue;
+ }
+
+ if (evdev_set_keycode(fd, scancode, new_keycode) < 0) {
+ r = -1;
+ continue;
+ }
+
+ if (new_keycode != old_keycode)
+ fprintf(stderr, "Remapped scancode 0x%02x to 0x%02x (prior: 0x%02x)\n",
+ scancode, new_keycode, old_keycode);
+ }
+
+ fclose(f);
+ return r;
+}
+
+
+/* read one event; return 1 if valid */
+static int read_event(int fd, struct input_event* ev)
+{
+ int ret;
+ ret = read(fd, ev, sizeof(struct input_event));
+
+ if (ret < 0) {
+ perror("read");
+ return 0;
+ }
+ if (ret != sizeof(struct input_event)) {
+ fprintf(stderr, "did not get enough data for event struct, aborting\n");
+ return 0;
+ }
+
+ return 1;
+}
+
+static void print_key(unsigned scancode, uint16_t keycode, int has_scan, int has_key)
+{
+ const char *keyname;
+
+ /* ignore key release events */
+ if (has_key == 1)
+ return;
+
+ if (has_key == 0 && has_scan != 0) {
+ fprintf(stderr, "got scan code event 0x%02X without a key code event\n",
+ scancode);
+ return;
+ }
+
+ if (has_scan != 0)
+ printf("scan code: 0x%02X ", scancode);
+ else
+ printf("(no scan code received) ");
+
+ keyname = key_names[keycode];
+ if (keyname != NULL)
+ printf("key code: %s\n", format_keyname(keyname));
+ else
+ printf("key code: %03X\n", keycode);
+}
+
+static void interactive(int fd)
+{
+ struct input_event ev;
+ unsigned last_scan = 0;
+ uint16_t last_key = 0;
+ int has_scan; /* boolean */
+ int has_key; /* 0: none, 1: release, 2: press */
+
+ /* grab input device */
+ ioctl(fd, EVIOCGRAB, 1);
+ puts("Press ESC to finish, or Control-C if this device is not your primary keyboard");
+
+ has_scan = has_key = 0;
+ while (read_event(fd, &ev)) {
+ /* Drivers usually send the scan code first, then the key code,
+ * then a SYN. Some drivers (like thinkpad_acpi) send the key
+ * code first, and some drivers might not send SYN events, so
+ * keep a robust state machine which can deal with any of those
+ */
+
+ if (ev.type == EV_MSC && ev.code == MSC_SCAN) {
+ if (has_scan) {
+ fputs("driver did not send SYN event in between key events; previous event:\n",
+ stderr);
+ print_key(last_scan, last_key, has_scan, has_key);
+ has_key = 0;
+ }
+
+ last_scan = ev.value;
+ has_scan = 1;
+ /*printf("--- got scan %u; has scan %i key %i\n", last_scan, has_scan, has_key); */
+ }
+ else if (ev.type == EV_KEY) {
+ if (has_key) {
+ fputs("driver did not send SYN event in between key events; previous event:\n",
+ stderr);
+ print_key(last_scan, last_key, has_scan, has_key);
+ has_scan = 0;
+ }
+
+ last_key = ev.code;
+ has_key = 1 + ev.value;
+ /*printf("--- got key %hu; has scan %i key %i\n", last_key, has_scan, has_key);*/
+
+ /* Stop on ESC */
+ if (ev.code == KEY_ESC && ev.value == 0)
+ break;
+ }
+ else if (ev.type == EV_SYN) {
+ /*printf("--- got SYN; has scan %i key %i\n", has_scan, has_key);*/
+ print_key(last_scan, last_key, has_scan, has_key);
+
+ has_scan = has_key = 0;
+ }
+
+ }
+
+ /* release input device */
+ ioctl(fd, EVIOCGRAB, 0);
+}
+
+_noreturn_ static void help(int error)
+{
+ const char* h = "Usage: keymap <event device> [<map file>]\n"
+ " keymap <event device> scancode keyname [...]\n"
+ " keymap -i <event device>\n";
+ if (error) {
+ fputs(h, stderr);
+ exit(2);
+ } else {
+ fputs(h, stdout);
+ exit(0);
+ }
+}
+
+int main(int argc, char **argv)
+{
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "interactive", no_argument, NULL, 'i' },
+ {}
+ };
+ int fd = -1;
+ int opt_interactive = 0;
+ int i;
+
+ while (1) {
+ int option;
+
+ option = getopt_long(argc, argv, "hi", options, NULL);
+ if (option == -1)
+ break;
+
+ switch (option) {
+ case 'h':
+ help(0);
+
+ case 'i':
+ opt_interactive = 1;
+ break;
+ default:
+ return 1;
+ }
+ }
+
+ if (argc < optind+1)
+ help (1);
+
+ if ((fd = evdev_open(argv[optind])) < 0)
+ return 3;
+
+ /* one argument (device): dump or interactive */
+ if (argc == optind+1) {
+ if (opt_interactive)
+ interactive(fd);
+ else
+ dump_table(fd);
+ return 0;
+ }
+
+ /* two arguments (device, mapfile): set map file */
+ if (argc == optind+2) {
+ const char *filearg = argv[optind+1];
+ if (strchr(filearg, '/')) {
+ /* Keymap file argument is a path */
+ FILE *f = fopen(filearg, "re");
+ if (f)
+ merge_table(fd, f);
+ else
+ perror(filearg);
+ } else {
+ /* Keymap file argument is a filename */
+ /* Open override file if present, otherwise default file */
+ char keymap_path[PATH_MAX];
+ FILE *f;
+
+ snprintf(keymap_path, sizeof(keymap_path), "/etc/udev/keymaps/%s", filearg);
+ f = fopen(keymap_path, "re");
+ if (f) {
+ merge_table(fd, f);
+ } else {
+ snprintf(keymap_path, sizeof(keymap_path), UDEVLIBEXECDIR "/keymaps/%s", filearg);
+ f = fopen(keymap_path, "re");
+ if (f)
+ merge_table(fd, f);
+ else
+ perror(keymap_path);
+ }
+ }
+ return 0;
+ }
+
+ /* more arguments (device, scancode/keyname pairs): set keys directly */
+ if ((argc - optind - 1) % 2 == 0) {
+ for (i = optind+1; i < argc; i += 2)
+ set_key(fd, argv[i], argv[i+1]);
+ return 0;
+ }
+
+ /* invalid number of arguments */
+ help(1);
+ return 1; /* not reached */
+}
diff --git a/src/udev/mtd_probe/mtd_probe.c b/src/udev/mtd_probe/mtd_probe.c
new file mode 100644
index 0000000000..70c04db40b
--- /dev/null
+++ b/src/udev/mtd_probe/mtd_probe.c
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2010 - Maxim Levitsky
+ *
+ * mtd_probe is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * mtd_probe is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with mtd_probe; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301 USA
+ */
+#include "mtd_probe.h"
+#include <stdio.h>
+#include <sys/ioctl.h>
+#include <mtd/mtd-user.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <stdlib.h>
+
+int main(int argc, char** argv)
+{
+ int mtd_fd;
+ int error;
+ mtd_info_t mtd_info;
+
+ if (argc != 2) {
+ printf("usage: mtd_probe /dev/mtd[n]\n");
+ return 1;
+ }
+
+ mtd_fd = open(argv[1], O_RDONLY);
+ if (mtd_fd == -1) {
+ perror("open");
+ exit(-1);
+ }
+
+ error = ioctl(mtd_fd, MEMGETINFO, &mtd_info);
+ if (error == -1) {
+ perror("ioctl");
+ exit(-1);
+ }
+
+ probe_smart_media(mtd_fd, &mtd_info);
+ return -1;
+}
diff --git a/src/udev/mtd_probe/mtd_probe.h b/src/udev/mtd_probe/mtd_probe.h
new file mode 100644
index 0000000000..2a37ede578
--- /dev/null
+++ b/src/udev/mtd_probe/mtd_probe.h
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2010 - Maxim Levitsky
+ *
+ * mtd_probe is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * mtd_probe is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with mtd_probe; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301 USA
+ */
+
+#include <mtd/mtd-user.h>
+
+/* Full oob structure as written on the flash */
+struct sm_oob {
+ uint32_t reserved;
+ uint8_t data_status;
+ uint8_t block_status;
+ uint8_t lba_copy1[2];
+ uint8_t ecc2[3];
+ uint8_t lba_copy2[2];
+ uint8_t ecc1[3];
+} __attribute__((packed));
+
+
+/* one sector is always 512 bytes, but it can consist of two nand pages */
+#define SM_SECTOR_SIZE 512
+
+/* oob area is also 16 bytes, but might be from two pages */
+#define SM_OOB_SIZE 16
+
+/* This is maximum zone size, and all devices that have more that one zone
+ have this size */
+#define SM_MAX_ZONE_SIZE 1024
+
+/* support for small page nand */
+#define SM_SMALL_PAGE 256
+#define SM_SMALL_OOB_SIZE 8
+
+
+void probe_smart_media(int mtd_fd, mtd_info_t *info);
diff --git a/src/udev/mtd_probe/probe_smartmedia.c b/src/udev/mtd_probe/probe_smartmedia.c
new file mode 100644
index 0000000000..feadb5076c
--- /dev/null
+++ b/src/udev/mtd_probe/probe_smartmedia.c
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2010 - Maxim Levitsky
+ *
+ * mtd_probe is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * mtd_probe is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with mtd_probe; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301 USA
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <mtd/mtd-user.h>
+#include <string.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include "mtd_probe.h"
+
+static const uint8_t cis_signature[] = {
+ 0x01, 0x03, 0xD9, 0x01, 0xFF, 0x18, 0x02, 0xDF, 0x01, 0x20
+};
+
+
+void probe_smart_media(int mtd_fd, mtd_info_t* info)
+{
+ int sector_size;
+ int block_size;
+ int size_in_megs;
+ int spare_count;
+ char* cis_buffer = malloc(SM_SECTOR_SIZE);
+ int offset;
+ int cis_found = 0;
+
+ if (!cis_buffer)
+ return;
+
+ if (info->type != MTD_NANDFLASH)
+ goto exit;
+
+ sector_size = info->writesize;
+ block_size = info->erasesize;
+ size_in_megs = info->size / (1024 * 1024);
+
+ if (sector_size != SM_SECTOR_SIZE && sector_size != SM_SMALL_PAGE)
+ goto exit;
+
+ switch(size_in_megs) {
+ case 1:
+ case 2:
+ spare_count = 6;
+ break;
+ case 4:
+ spare_count = 12;
+ break;
+ default:
+ spare_count = 24;
+ break;
+ }
+
+ for (offset = 0 ; offset < block_size * spare_count ;
+ offset += sector_size) {
+ lseek(mtd_fd, SEEK_SET, offset);
+ if (read(mtd_fd, cis_buffer, SM_SECTOR_SIZE) == SM_SECTOR_SIZE){
+ cis_found = 1;
+ break;
+ }
+ }
+
+ if (!cis_found)
+ goto exit;
+
+ if (memcmp(cis_buffer, cis_signature, sizeof(cis_signature)) != 0 &&
+ (memcmp(cis_buffer + SM_SMALL_PAGE, cis_signature,
+ sizeof(cis_signature)) != 0))
+ goto exit;
+
+ printf("MTD_FTL=smartmedia\n");
+ free(cis_buffer);
+ exit(0);
+exit:
+ free(cis_buffer);
+ return;
+}
diff --git a/src/udev/scsi_id/README b/src/udev/scsi_id/README
new file mode 100644
index 0000000000..9cfe73991c
--- /dev/null
+++ b/src/udev/scsi_id/README
@@ -0,0 +1,4 @@
+scsi_id - generate a SCSI unique identifier for a given SCSI device
+
+Please send questions, comments or patches to <patmans@us.ibm.com> or
+<linux-hotplug-devel@lists.sourceforge.net>.
diff --git a/src/udev/scsi_id/scsi.h b/src/udev/scsi_id/scsi.h
new file mode 100644
index 0000000000..c423cac574
--- /dev/null
+++ b/src/udev/scsi_id/scsi.h
@@ -0,0 +1,97 @@
+/*
+ * scsi.h
+ *
+ * General scsi and linux scsi specific defines and structs.
+ *
+ * Copyright (C) IBM Corp. 2003
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the
+ * Free Software Foundation version 2 of the License.
+ */
+
+#include <scsi/scsi.h>
+
+struct scsi_ioctl_command {
+ unsigned int inlen; /* excluding scsi command length */
+ unsigned int outlen;
+ unsigned char data[1];
+ /* on input, scsi command starts here then opt. data */
+};
+
+/*
+ * Default 5 second timeout
+ */
+#define DEF_TIMEOUT 5000
+
+#define SENSE_BUFF_LEN 32
+
+/*
+ * The request buffer size passed to the SCSI INQUIRY commands, use 254,
+ * as this is a nice value for some devices, especially some of the usb
+ * mass storage devices.
+ */
+#define SCSI_INQ_BUFF_LEN 254
+
+/*
+ * SCSI INQUIRY vendor and model (really product) lengths.
+ */
+#define VENDOR_LENGTH 8
+#define MODEL_LENGTH 16
+
+#define INQUIRY_CMD 0x12
+#define INQUIRY_CMDLEN 6
+
+/*
+ * INQUIRY VPD page 0x83 identifier descriptor related values. Reference the
+ * SCSI Primary Commands specification for details.
+ */
+
+/*
+ * id type values of id descriptors. These are assumed to fit in 4 bits.
+ */
+#define SCSI_ID_VENDOR_SPECIFIC 0
+#define SCSI_ID_T10_VENDOR 1
+#define SCSI_ID_EUI_64 2
+#define SCSI_ID_NAA 3
+#define SCSI_ID_RELPORT 4
+#define SCSI_ID_TGTGROUP 5
+#define SCSI_ID_LUNGROUP 6
+#define SCSI_ID_MD5 7
+#define SCSI_ID_NAME 8
+
+/*
+ * Supported NAA values. These fit in 4 bits, so the "don't care" value
+ * cannot conflict with real values.
+ */
+#define SCSI_ID_NAA_DONT_CARE 0xff
+#define SCSI_ID_NAA_IEEE_REG 5
+#define SCSI_ID_NAA_IEEE_REG_EXTENDED 6
+
+/*
+ * Supported Code Set values.
+ */
+#define SCSI_ID_BINARY 1
+#define SCSI_ID_ASCII 2
+
+struct scsi_id_search_values {
+ u_char id_type;
+ u_char naa_type;
+ u_char code_set;
+};
+
+/*
+ * Following are the "true" SCSI status codes. Linux has traditionally
+ * used a 1 bit right and masked version of these. So now CHECK_CONDITION
+ * and friends (in <scsi/scsi.h>) are deprecated.
+ */
+#define SCSI_CHECK_CONDITION 0x2
+#define SCSI_CONDITION_MET 0x4
+#define SCSI_BUSY 0x8
+#define SCSI_IMMEDIATE 0x10
+#define SCSI_IMMEDIATE_CONDITION_MET 0x14
+#define SCSI_RESERVATION_CONFLICT 0x18
+#define SCSI_COMMAND_TERMINATED 0x22
+#define SCSI_TASK_SET_FULL 0x28
+#define SCSI_ACA_ACTIVE 0x30
+#define SCSI_TASK_ABORTED 0x40
diff --git a/src/udev/scsi_id/scsi_id.c b/src/udev/scsi_id/scsi_id.c
new file mode 100644
index 0000000000..ab7c54c3f2
--- /dev/null
+++ b/src/udev/scsi_id/scsi_id.c
@@ -0,0 +1,634 @@
+/*
+ * Copyright (C) IBM Corp. 2003
+ * Copyright (C) SUSE Linux Products GmbH, 2006
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <signal.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <string.h>
+#include <syslog.h>
+#include <stdarg.h>
+#include <ctype.h>
+#include <getopt.h>
+#include <sys/stat.h>
+
+#include "libudev.h"
+#include "libudev-private.h"
+#include "scsi_id.h"
+
+static const struct option options[] = {
+ { "device", required_argument, NULL, 'd' },
+ { "config", required_argument, NULL, 'f' },
+ { "page", required_argument, NULL, 'p' },
+ { "blacklisted", no_argument, NULL, 'b' },
+ { "whitelisted", no_argument, NULL, 'g' },
+ { "replace-whitespace", no_argument, NULL, 'u' },
+ { "sg-version", required_argument, NULL, 's' },
+ { "verbose", no_argument, NULL, 'v' },
+ { "version", no_argument, NULL, 'V' },
+ { "export", no_argument, NULL, 'x' },
+ { "help", no_argument, NULL, 'h' },
+ {}
+};
+
+static const char short_options[] = "d:f:ghip:uvVx";
+static const char dev_short_options[] = "bgp:";
+
+static int all_good;
+static int dev_specified;
+static char config_file[MAX_PATH_LEN] = "/etc/scsi_id.config";
+static enum page_code default_page_code;
+static int sg_version = 4;
+static int use_stderr;
+static int debug;
+static int reformat_serial;
+static int export;
+static char vendor_str[64];
+static char model_str[64];
+static char vendor_enc_str[256];
+static char model_enc_str[256];
+static char revision_str[16];
+static char type_str[16];
+
+static void log_fn(struct udev *udev, int priority,
+ const char *file, int line, const char *fn,
+ const char *format, va_list args)
+{
+ vsyslog(priority, format, args);
+}
+
+static void set_type(const char *from, char *to, size_t len)
+{
+ int type_num;
+ char *eptr;
+ const char *type = "generic";
+
+ type_num = strtoul(from, &eptr, 0);
+ if (eptr != from) {
+ switch (type_num) {
+ case 0:
+ type = "disk";
+ break;
+ case 1:
+ type = "tape";
+ break;
+ case 4:
+ type = "optical";
+ break;
+ case 5:
+ type = "cd";
+ break;
+ case 7:
+ type = "optical";
+ break;
+ case 0xe:
+ type = "disk";
+ break;
+ case 0xf:
+ type = "optical";
+ break;
+ default:
+ break;
+ }
+ }
+ strscpy(to, len, type);
+}
+
+/*
+ * get_value:
+ *
+ * buf points to an '=' followed by a quoted string ("foo") or a string ending
+ * with a space or ','.
+ *
+ * Return a pointer to the NUL terminated string, returns NULL if no
+ * matches.
+ */
+static char *get_value(char **buffer)
+{
+ static const char *quote_string = "\"\n";
+ static const char *comma_string = ",\n";
+ char *val;
+ const char *end;
+
+ if (**buffer == '"') {
+ /*
+ * skip leading quote, terminate when quote seen
+ */
+ (*buffer)++;
+ end = quote_string;
+ } else {
+ end = comma_string;
+ }
+ val = strsep(buffer, end);
+ if (val && end == quote_string)
+ /*
+ * skip trailing quote
+ */
+ (*buffer)++;
+
+ while (isspace(**buffer))
+ (*buffer)++;
+
+ return val;
+}
+
+static int argc_count(char *opts)
+{
+ int i = 0;
+ while (*opts != '\0')
+ if (*opts++ == ' ')
+ i++;
+ return i;
+}
+
+/*
+ * get_file_options:
+ *
+ * If vendor == NULL, find a line in the config file with only "OPTIONS=";
+ * if vendor and model are set find the first OPTIONS line in the config
+ * file that matches. Set argc and argv to match the OPTIONS string.
+ *
+ * vendor and model can end in '\n'.
+ */
+static int get_file_options(struct udev *udev,
+ const char *vendor, const char *model,
+ int *argc, char ***newargv)
+{
+ char *buffer;
+ FILE *fd;
+ char *buf;
+ char *str1;
+ char *vendor_in, *model_in, *options_in; /* read in from file */
+ int lineno;
+ int c;
+ int retval = 0;
+
+ fd = fopen(config_file, "re");
+ if (fd == NULL) {
+ if (errno == ENOENT) {
+ return 1;
+ } else {
+ log_error("can't open %s: %s\n", config_file, strerror(errno));
+ return -1;
+ }
+ }
+
+ /*
+ * Allocate a buffer rather than put it on the stack so we can
+ * keep it around to parse any options (any allocated newargv
+ * points into this buffer for its strings).
+ */
+ buffer = malloc(MAX_BUFFER_LEN);
+ if (!buffer) {
+ fclose(fd);
+ return log_oom();
+ }
+
+ *newargv = NULL;
+ lineno = 0;
+ while (1) {
+ vendor_in = model_in = options_in = NULL;
+
+ buf = fgets(buffer, MAX_BUFFER_LEN, fd);
+ if (buf == NULL)
+ break;
+ lineno++;
+ if (buf[strlen(buffer) - 1] != '\n') {
+ log_error("Config file line %d too long\n", lineno);
+ break;
+ }
+
+ while (isspace(*buf))
+ buf++;
+
+ /* blank or all whitespace line */
+ if (*buf == '\0')
+ continue;
+
+ /* comment line */
+ if (*buf == '#')
+ continue;
+
+ str1 = strsep(&buf, "=");
+ if (str1 && strcaseeq(str1, "VENDOR")) {
+ str1 = get_value(&buf);
+ if (!str1) {
+ retval = log_oom();
+ break;
+ }
+ vendor_in = str1;
+
+ str1 = strsep(&buf, "=");
+ if (str1 && strcaseeq(str1, "MODEL")) {
+ str1 = get_value(&buf);
+ if (!str1) {
+ retval = log_oom();
+ break;
+ }
+ model_in = str1;
+ str1 = strsep(&buf, "=");
+ }
+ }
+
+ if (str1 && strcaseeq(str1, "OPTIONS")) {
+ str1 = get_value(&buf);
+ if (!str1) {
+ retval = log_oom();
+ break;
+ }
+ options_in = str1;
+ }
+
+ /*
+ * Only allow: [vendor=foo[,model=bar]]options=stuff
+ */
+ if (!options_in || (!vendor_in && model_in)) {
+ log_error("Error parsing config file line %d '%s'\n", lineno, buffer);
+ retval = -1;
+ break;
+ }
+ if (vendor == NULL) {
+ if (vendor_in == NULL)
+ break;
+ } else if ((vendor_in && strneq(vendor, vendor_in,
+ strlen(vendor_in))) &&
+ (!model_in || (strneq(model, model_in,
+ strlen(model_in))))) {
+ /*
+ * Matched vendor and optionally model.
+ *
+ * Note: a short vendor_in or model_in can
+ * give a partial match (that is FOO
+ * matches FOOBAR).
+ */
+ break;
+ }
+ }
+
+ if (retval == 0) {
+ if (vendor_in != NULL || model_in != NULL ||
+ options_in != NULL) {
+ /*
+ * Something matched. Allocate newargv, and store
+ * values found in options_in.
+ */
+ strcpy(buffer, options_in);
+ c = argc_count(buffer) + 2;
+ *newargv = calloc(c, sizeof(**newargv));
+ if (!*newargv) {
+ retval = log_oom();
+ } else {
+ *argc = c;
+ c = 0;
+ /*
+ * argv[0] at 0 is skipped by getopt, but
+ * store the buffer address there for
+ * later freeing
+ */
+ (*newargv)[c] = buffer;
+ for (c = 1; c < *argc; c++)
+ (*newargv)[c] = strsep(&buffer, " \t");
+ }
+ } else {
+ /* No matches */
+ retval = 1;
+ }
+ }
+ if (retval != 0)
+ free(buffer);
+ fclose(fd);
+ return retval;
+}
+
+static int set_options(struct udev *udev,
+ int argc, char **argv, const char *short_opts,
+ char *maj_min_dev)
+{
+ int option;
+
+ /*
+ * optind is a global extern used by getopt. Since we can call
+ * set_options twice (once for command line, and once for config
+ * file) we have to reset this back to 1.
+ */
+ optind = 1;
+ while (1) {
+ option = getopt_long(argc, argv, short_opts, options, NULL);
+ if (option == -1)
+ break;
+
+ switch (option) {
+ case 'b':
+ all_good = 0;
+ break;
+
+ case 'd':
+ dev_specified = 1;
+ strscpy(maj_min_dev, MAX_PATH_LEN, optarg);
+ break;
+
+ case 'e':
+ use_stderr = 1;
+ break;
+
+ case 'f':
+ strscpy(config_file, MAX_PATH_LEN, optarg);
+ break;
+
+ case 'g':
+ all_good = 1;
+ break;
+
+ case 'h':
+ printf("Usage: scsi_id OPTIONS <device>\n"
+ " --device= device node for SG_IO commands\n"
+ " --config= location of config file\n"
+ " --page=0x80|0x83|pre-spc3-83 SCSI page (0x80, 0x83, pre-spc3-83)\n"
+ " --sg-version=3|4 use SGv3 or SGv4\n"
+ " --blacklisted threat device as blacklisted\n"
+ " --whitelisted threat device as whitelisted\n"
+ " --replace-whitespace replace all whitespaces by underscores\n"
+ " --verbose verbose logging\n"
+ " --version print version\n"
+ " --export print values as environment keys\n"
+ " --help print this help text\n\n");
+ exit(0);
+
+ case 'p':
+ if (streq(optarg, "0x80")) {
+ default_page_code = PAGE_80;
+ } else if (streq(optarg, "0x83")) {
+ default_page_code = PAGE_83;
+ } else if (streq(optarg, "pre-spc3-83")) {
+ default_page_code = PAGE_83_PRE_SPC3;
+ } else {
+ log_error("Unknown page code '%s'\n", optarg);
+ return -1;
+ }
+ break;
+
+ case 's':
+ sg_version = atoi(optarg);
+ if (sg_version < 3 || sg_version > 4) {
+ log_error("Unknown SG version '%s'\n", optarg);
+ return -1;
+ }
+ break;
+
+ case 'u':
+ reformat_serial = 1;
+ break;
+
+ case 'x':
+ export = 1;
+ break;
+
+ case 'v':
+ debug++;
+ break;
+
+ case 'V':
+ printf("%s\n", VERSION);
+ exit(0);
+ break;
+
+ default:
+ exit(1);
+ }
+ }
+ if (optind < argc && !dev_specified) {
+ dev_specified = 1;
+ strscpy(maj_min_dev, MAX_PATH_LEN, argv[optind]);
+ }
+ return 0;
+}
+
+static int per_dev_options(struct udev *udev,
+ struct scsi_id_device *dev_scsi, int *good_bad, int *page_code)
+{
+ int retval;
+ int newargc;
+ char **newargv = NULL;
+ int option;
+
+ *good_bad = all_good;
+ *page_code = default_page_code;
+
+ retval = get_file_options(udev, vendor_str, model_str, &newargc, &newargv);
+
+ optind = 1; /* reset this global extern */
+ while (retval == 0) {
+ option = getopt_long(newargc, newargv, dev_short_options, options, NULL);
+ if (option == -1)
+ break;
+
+ switch (option) {
+ case 'b':
+ *good_bad = 0;
+ break;
+
+ case 'g':
+ *good_bad = 1;
+ break;
+
+ case 'p':
+ if (streq(optarg, "0x80")) {
+ *page_code = PAGE_80;
+ } else if (streq(optarg, "0x83")) {
+ *page_code = PAGE_83;
+ } else if (streq(optarg, "pre-spc3-83")) {
+ *page_code = PAGE_83_PRE_SPC3;
+ } else {
+ log_error("Unknown page code '%s'\n", optarg);
+ retval = -1;
+ }
+ break;
+
+ default:
+ log_error("Unknown or bad option '%c' (0x%x)\n", option, option);
+ retval = -1;
+ break;
+ }
+ }
+
+ if (newargv) {
+ free(newargv[0]);
+ free(newargv);
+ }
+ return retval;
+}
+
+static int set_inq_values(struct udev *udev, struct scsi_id_device *dev_scsi, const char *path)
+{
+ int retval;
+
+ dev_scsi->use_sg = sg_version;
+
+ retval = scsi_std_inquiry(udev, dev_scsi, path);
+ if (retval)
+ return retval;
+
+ udev_util_encode_string(dev_scsi->vendor, vendor_enc_str, sizeof(vendor_enc_str));
+ udev_util_encode_string(dev_scsi->model, model_enc_str, sizeof(model_enc_str));
+
+ util_replace_whitespace(dev_scsi->vendor, vendor_str, sizeof(vendor_str));
+ util_replace_chars(vendor_str, NULL);
+ util_replace_whitespace(dev_scsi->model, model_str, sizeof(model_str));
+ util_replace_chars(model_str, NULL);
+ set_type(dev_scsi->type, type_str, sizeof(type_str));
+ util_replace_whitespace(dev_scsi->revision, revision_str, sizeof(revision_str));
+ util_replace_chars(revision_str, NULL);
+ return 0;
+}
+
+/*
+ * scsi_id: try to get an id, if one is found, printf it to stdout.
+ * returns a value passed to exit() - 0 if printed an id, else 1.
+ */
+static int scsi_id(struct udev *udev, char *maj_min_dev)
+{
+ struct scsi_id_device dev_scsi;
+ int good_dev;
+ int page_code;
+ int retval = 0;
+
+ memset(&dev_scsi, 0x00, sizeof(struct scsi_id_device));
+
+ if (set_inq_values(udev, &dev_scsi, maj_min_dev) < 0) {
+ retval = 1;
+ goto out;
+ }
+
+ /* get per device (vendor + model) options from the config file */
+ per_dev_options(udev, &dev_scsi, &good_dev, &page_code);
+ if (!good_dev) {
+ retval = 1;
+ goto out;
+ }
+
+ /* read serial number from mode pages (no values for optical drives) */
+ scsi_get_serial(udev, &dev_scsi, maj_min_dev, page_code, MAX_SERIAL_LEN);
+
+ if (export) {
+ char serial_str[MAX_SERIAL_LEN];
+
+ printf("ID_SCSI=1\n");
+ printf("ID_VENDOR=%s\n", vendor_str);
+ printf("ID_VENDOR_ENC=%s\n", vendor_enc_str);
+ printf("ID_MODEL=%s\n", model_str);
+ printf("ID_MODEL_ENC=%s\n", model_enc_str);
+ printf("ID_REVISION=%s\n", revision_str);
+ printf("ID_TYPE=%s\n", type_str);
+ if (dev_scsi.serial[0] != '\0') {
+ util_replace_whitespace(dev_scsi.serial, serial_str, sizeof(serial_str));
+ util_replace_chars(serial_str, NULL);
+ printf("ID_SERIAL=%s\n", serial_str);
+ util_replace_whitespace(dev_scsi.serial_short, serial_str, sizeof(serial_str));
+ util_replace_chars(serial_str, NULL);
+ printf("ID_SERIAL_SHORT=%s\n", serial_str);
+ }
+ if (dev_scsi.wwn[0] != '\0') {
+ printf("ID_WWN=0x%s\n", dev_scsi.wwn);
+ if (dev_scsi.wwn_vendor_extension[0] != '\0') {
+ printf("ID_WWN_VENDOR_EXTENSION=0x%s\n", dev_scsi.wwn_vendor_extension);
+ printf("ID_WWN_WITH_EXTENSION=0x%s%s\n", dev_scsi.wwn, dev_scsi.wwn_vendor_extension);
+ } else {
+ printf("ID_WWN_WITH_EXTENSION=0x%s\n", dev_scsi.wwn);
+ }
+ }
+ if (dev_scsi.tgpt_group[0] != '\0') {
+ printf("ID_TARGET_PORT=%s\n", dev_scsi.tgpt_group);
+ }
+ if (dev_scsi.unit_serial_number[0] != '\0') {
+ printf("ID_SCSI_SERIAL=%s\n", dev_scsi.unit_serial_number);
+ }
+ goto out;
+ }
+
+ if (dev_scsi.serial[0] == '\0') {
+ retval = 1;
+ goto out;
+ }
+
+ if (reformat_serial) {
+ char serial_str[MAX_SERIAL_LEN];
+
+ util_replace_whitespace(dev_scsi.serial, serial_str, sizeof(serial_str));
+ util_replace_chars(serial_str, NULL);
+ printf("%s\n", serial_str);
+ goto out;
+ }
+
+ printf("%s\n", dev_scsi.serial);
+out:
+ return retval;
+}
+
+int main(int argc, char **argv)
+{
+ struct udev *udev;
+ int retval = 0;
+ char maj_min_dev[MAX_PATH_LEN];
+ int newargc;
+ char **newargv;
+
+ udev = udev_new();
+ if (udev == NULL)
+ goto exit;
+
+ log_open();
+ udev_set_log_fn(udev, log_fn);
+
+ /*
+ * Get config file options.
+ */
+ newargv = NULL;
+ retval = get_file_options(udev, NULL, NULL, &newargc, &newargv);
+ if (retval < 0) {
+ retval = 1;
+ goto exit;
+ }
+ if (newargv && (retval == 0)) {
+ if (set_options(udev, newargc, newargv, short_options, maj_min_dev) < 0) {
+ retval = 2;
+ goto exit;
+ }
+ free(newargv);
+ }
+
+ /*
+ * Get command line options (overriding any config file settings).
+ */
+ if (set_options(udev, argc, argv, short_options, maj_min_dev) < 0)
+ exit(1);
+
+ if (!dev_specified) {
+ log_error("no device specified\n");
+ retval = 1;
+ goto exit;
+ }
+
+ retval = scsi_id(udev, maj_min_dev);
+
+exit:
+ udev_unref(udev);
+ log_close();
+ return retval;
+}
diff --git a/src/udev/scsi_id/scsi_id.h b/src/udev/scsi_id/scsi_id.h
new file mode 100644
index 0000000000..103e443d07
--- /dev/null
+++ b/src/udev/scsi_id/scsi_id.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) IBM Corp. 2003
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#define MAX_PATH_LEN 512
+
+/*
+ * MAX_ATTR_LEN: maximum length of the result of reading a sysfs
+ * attribute.
+ */
+#define MAX_ATTR_LEN 256
+
+/*
+ * MAX_SERIAL_LEN: the maximum length of the serial number, including
+ * added prefixes such as vendor and product (model) strings.
+ */
+#define MAX_SERIAL_LEN 256
+
+/*
+ * MAX_BUFFER_LEN: maximum buffer size and line length used while reading
+ * the config file.
+ */
+#define MAX_BUFFER_LEN 256
+
+struct scsi_id_device {
+ char vendor[9];
+ char model[17];
+ char revision[5];
+ char type[33];
+ char kernel[64];
+ char serial[MAX_SERIAL_LEN];
+ char serial_short[MAX_SERIAL_LEN];
+ int use_sg;
+
+ /* Always from page 0x80 e.g. 'B3G1P8500RWT' - may not be unique */
+ char unit_serial_number[MAX_SERIAL_LEN];
+
+ /* NULs if not set - otherwise hex encoding using lower-case e.g. '50014ee0016eb572' */
+ char wwn[17];
+
+ /* NULs if not set - otherwise hex encoding using lower-case e.g. '0xe00000d80000' */
+ char wwn_vendor_extension[17];
+
+ /* NULs if not set - otherwise decimal number */
+ char tgpt_group[8];
+};
+
+int scsi_std_inquiry(struct udev *udev, struct scsi_id_device *dev_scsi, const char *devname);
+int scsi_get_serial(struct udev *udev, struct scsi_id_device *dev_scsi, const char *devname,
+ int page_code, int len);
+
+/*
+ * Page code values.
+ */
+enum page_code {
+ PAGE_83_PRE_SPC3 = -0x83,
+ PAGE_UNSPECIFIED = 0x00,
+ PAGE_80 = 0x80,
+ PAGE_83 = 0x83,
+};
diff --git a/src/udev/scsi_id/scsi_serial.c b/src/udev/scsi_id/scsi_serial.c
new file mode 100644
index 0000000000..d522a23a08
--- /dev/null
+++ b/src/udev/scsi_id/scsi_serial.c
@@ -0,0 +1,968 @@
+/*
+ * Copyright (C) IBM Corp. 2003
+ *
+ * Author: Patrick Mansfield<patmans@us.ibm.com>
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <sys/types.h>
+#include <sys/ioctl.h>
+#include <sys/stat.h>
+#include <stdio.h>
+#include <errno.h>
+#include <string.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <syslog.h>
+#include <time.h>
+#include <inttypes.h>
+#include <scsi/scsi.h>
+#include <scsi/sg.h>
+#include <linux/types.h>
+#include <linux/bsg.h>
+
+#include "libudev.h"
+#include "libudev-private.h"
+#include "scsi.h"
+#include "scsi_id.h"
+
+/*
+ * A priority based list of id, naa, and binary/ascii for the identifier
+ * descriptor in VPD page 0x83.
+ *
+ * Brute force search for a match starting with the first value in the
+ * following id_search_list. This is not a performance issue, since there
+ * is normally one or some small number of descriptors.
+ */
+static const struct scsi_id_search_values id_search_list[] = {
+ { SCSI_ID_TGTGROUP, SCSI_ID_NAA_DONT_CARE, SCSI_ID_BINARY },
+ { SCSI_ID_NAA, SCSI_ID_NAA_IEEE_REG_EXTENDED, SCSI_ID_BINARY },
+ { SCSI_ID_NAA, SCSI_ID_NAA_IEEE_REG_EXTENDED, SCSI_ID_ASCII },
+ { SCSI_ID_NAA, SCSI_ID_NAA_IEEE_REG, SCSI_ID_BINARY },
+ { SCSI_ID_NAA, SCSI_ID_NAA_IEEE_REG, SCSI_ID_ASCII },
+ /*
+ * Devices already exist using NAA values that are now marked
+ * reserved. These should not conflict with other values, or it is
+ * a bug in the device. As long as we find the IEEE extended one
+ * first, we really don't care what other ones are used. Using
+ * don't care here means that a device that returns multiple
+ * non-IEEE descriptors in a random order will get different
+ * names.
+ */
+ { SCSI_ID_NAA, SCSI_ID_NAA_DONT_CARE, SCSI_ID_BINARY },
+ { SCSI_ID_NAA, SCSI_ID_NAA_DONT_CARE, SCSI_ID_ASCII },
+ { SCSI_ID_EUI_64, SCSI_ID_NAA_DONT_CARE, SCSI_ID_BINARY },
+ { SCSI_ID_EUI_64, SCSI_ID_NAA_DONT_CARE, SCSI_ID_ASCII },
+ { SCSI_ID_T10_VENDOR, SCSI_ID_NAA_DONT_CARE, SCSI_ID_BINARY },
+ { SCSI_ID_T10_VENDOR, SCSI_ID_NAA_DONT_CARE, SCSI_ID_ASCII },
+ { SCSI_ID_VENDOR_SPECIFIC, SCSI_ID_NAA_DONT_CARE, SCSI_ID_BINARY },
+ { SCSI_ID_VENDOR_SPECIFIC, SCSI_ID_NAA_DONT_CARE, SCSI_ID_ASCII },
+};
+
+static const char hex_str[]="0123456789abcdef";
+
+/*
+ * Values returned in the result/status, only the ones used by the code
+ * are used here.
+ */
+
+#define DID_NO_CONNECT 0x01 /* Unable to connect before timeout */
+#define DID_BUS_BUSY 0x02 /* Bus remain busy until timeout */
+#define DID_TIME_OUT 0x03 /* Timed out for some other reason */
+#define DRIVER_TIMEOUT 0x06
+#define DRIVER_SENSE 0x08 /* Sense_buffer has been set */
+
+/* The following "category" function returns one of the following */
+#define SG_ERR_CAT_CLEAN 0 /* No errors or other information */
+#define SG_ERR_CAT_MEDIA_CHANGED 1 /* interpreted from sense buffer */
+#define SG_ERR_CAT_RESET 2 /* interpreted from sense buffer */
+#define SG_ERR_CAT_TIMEOUT 3
+#define SG_ERR_CAT_RECOVERED 4 /* Successful command after recovered err */
+#define SG_ERR_CAT_NOTSUPPORTED 5 /* Illegal / unsupported command */
+#define SG_ERR_CAT_SENSE 98 /* Something else in the sense buffer */
+#define SG_ERR_CAT_OTHER 99 /* Some other error/warning */
+
+static int do_scsi_page80_inquiry(struct udev *udev,
+ struct scsi_id_device *dev_scsi, int fd,
+ char *serial, char *serial_short, int max_len);
+
+static int sg_err_category_new(struct udev *udev,
+ int scsi_status, int msg_status, int
+ host_status, int driver_status, const
+ unsigned char *sense_buffer, int sb_len)
+{
+ scsi_status &= 0x7e;
+
+ /*
+ * XXX change to return only two values - failed or OK.
+ */
+
+ if (!scsi_status && !host_status && !driver_status)
+ return SG_ERR_CAT_CLEAN;
+
+ if ((scsi_status == SCSI_CHECK_CONDITION) ||
+ (scsi_status == SCSI_COMMAND_TERMINATED) ||
+ ((driver_status & 0xf) == DRIVER_SENSE)) {
+ if (sense_buffer && (sb_len > 2)) {
+ int sense_key;
+ unsigned char asc;
+
+ if (sense_buffer[0] & 0x2) {
+ sense_key = sense_buffer[1] & 0xf;
+ asc = sense_buffer[2];
+ } else {
+ sense_key = sense_buffer[2] & 0xf;
+ asc = (sb_len > 12) ? sense_buffer[12] : 0;
+ }
+
+ if (sense_key == RECOVERED_ERROR)
+ return SG_ERR_CAT_RECOVERED;
+ else if (sense_key == UNIT_ATTENTION) {
+ if (0x28 == asc)
+ return SG_ERR_CAT_MEDIA_CHANGED;
+ if (0x29 == asc)
+ return SG_ERR_CAT_RESET;
+ } else if (sense_key == ILLEGAL_REQUEST) {
+ return SG_ERR_CAT_NOTSUPPORTED;
+ }
+ }
+ return SG_ERR_CAT_SENSE;
+ }
+ if (host_status) {
+ if ((host_status == DID_NO_CONNECT) ||
+ (host_status == DID_BUS_BUSY) ||
+ (host_status == DID_TIME_OUT))
+ return SG_ERR_CAT_TIMEOUT;
+ }
+ if (driver_status) {
+ if (driver_status == DRIVER_TIMEOUT)
+ return SG_ERR_CAT_TIMEOUT;
+ }
+ return SG_ERR_CAT_OTHER;
+}
+
+static int sg_err_category3(struct udev *udev, struct sg_io_hdr *hp)
+{
+ return sg_err_category_new(udev,
+ hp->status, hp->msg_status,
+ hp->host_status, hp->driver_status,
+ hp->sbp, hp->sb_len_wr);
+}
+
+static int sg_err_category4(struct udev *udev, struct sg_io_v4 *hp)
+{
+ return sg_err_category_new(udev, hp->device_status, 0,
+ hp->transport_status, hp->driver_status,
+ (unsigned char *)(uintptr_t)hp->response,
+ hp->response_len);
+}
+
+static int scsi_dump_sense(struct udev *udev,
+ struct scsi_id_device *dev_scsi,
+ unsigned char *sense_buffer, int sb_len)
+{
+ int s;
+ int code;
+ int sense_class;
+ int sense_key;
+ int asc, ascq;
+#ifdef DUMP_SENSE
+ char out_buffer[256];
+ int i, j;
+#endif
+
+ /*
+ * Figure out and print the sense key, asc and ascq.
+ *
+ * If you want to suppress these for a particular drive model, add
+ * a black list entry in the scsi_id config file.
+ *
+ * XXX We probably need to: lookup the sense/asc/ascq in a retry
+ * table, and if found return 1 (after dumping the sense, asc, and
+ * ascq). So, if/when we get something like a power on/reset,
+ * we'll retry the command.
+ */
+
+ if (sb_len < 1) {
+ log_debug("%s: sense buffer empty\n", dev_scsi->kernel);
+ return -1;
+ }
+
+ sense_class = (sense_buffer[0] >> 4) & 0x07;
+ code = sense_buffer[0] & 0xf;
+
+ if (sense_class == 7) {
+ /*
+ * extended sense data.
+ */
+ s = sense_buffer[7] + 8;
+ if (sb_len < s) {
+ log_debug("%s: sense buffer too small %d bytes, %d bytes too short\n",
+ dev_scsi->kernel, sb_len, s - sb_len);
+ return -1;
+ }
+ if ((code == 0x0) || (code == 0x1)) {
+ sense_key = sense_buffer[2] & 0xf;
+ if (s < 14) {
+ /*
+ * Possible?
+ */
+ log_debug("%s: sense result too" " small %d bytes\n",
+ dev_scsi->kernel, s);
+ return -1;
+ }
+ asc = sense_buffer[12];
+ ascq = sense_buffer[13];
+ } else if ((code == 0x2) || (code == 0x3)) {
+ sense_key = sense_buffer[1] & 0xf;
+ asc = sense_buffer[2];
+ ascq = sense_buffer[3];
+ } else {
+ log_debug("%s: invalid sense code 0x%x\n",
+ dev_scsi->kernel, code);
+ return -1;
+ }
+ log_debug("%s: sense key 0x%x ASC 0x%x ASCQ 0x%x\n",
+ dev_scsi->kernel, sense_key, asc, ascq);
+ } else {
+ if (sb_len < 4) {
+ log_debug("%s: sense buffer too small %d bytes, %d bytes too short\n",
+ dev_scsi->kernel, sb_len, 4 - sb_len);
+ return -1;
+ }
+
+ if (sense_buffer[0] < 15)
+ log_debug("%s: old sense key: 0x%x\n", dev_scsi->kernel, sense_buffer[0] & 0x0f);
+ else
+ log_debug("%s: sense = %2x %2x\n",
+ dev_scsi->kernel, sense_buffer[0], sense_buffer[2]);
+ log_debug("%s: non-extended sense class %d code 0x%0x\n",
+ dev_scsi->kernel, sense_class, code);
+
+ }
+
+#ifdef DUMP_SENSE
+ for (i = 0, j = 0; (i < s) && (j < 254); i++) {
+ out_buffer[j++] = hex_str[(sense_buffer[i] & 0xf0) >> 4];
+ out_buffer[j++] = hex_str[sense_buffer[i] & 0x0f];
+ out_buffer[j++] = ' ';
+ }
+ out_buffer[j] = '\0';
+ log_debug("%s: sense dump:\n", dev_scsi->kernel);
+ log_debug("%s: %s\n", dev_scsi->kernel, out_buffer);
+
+#endif
+ return -1;
+}
+
+static int scsi_dump(struct udev *udev,
+ struct scsi_id_device *dev_scsi, struct sg_io_hdr *io)
+{
+ if (!io->status && !io->host_status && !io->msg_status &&
+ !io->driver_status) {
+ /*
+ * Impossible, should not be called.
+ */
+ log_debug("%s: called with no error\n", __FUNCTION__);
+ return -1;
+ }
+
+ log_debug("%s: sg_io failed status 0x%x 0x%x 0x%x 0x%x\n",
+ dev_scsi->kernel, io->driver_status, io->host_status, io->msg_status, io->status);
+ if (io->status == SCSI_CHECK_CONDITION)
+ return scsi_dump_sense(udev, dev_scsi, io->sbp, io->sb_len_wr);
+ else
+ return -1;
+}
+
+static int scsi_dump_v4(struct udev *udev,
+ struct scsi_id_device *dev_scsi, struct sg_io_v4 *io)
+{
+ if (!io->device_status && !io->transport_status &&
+ !io->driver_status) {
+ /*
+ * Impossible, should not be called.
+ */
+ log_debug("%s: called with no error\n", __FUNCTION__);
+ return -1;
+ }
+
+ log_debug("%s: sg_io failed status 0x%x 0x%x 0x%x\n",
+ dev_scsi->kernel, io->driver_status, io->transport_status,
+ io->device_status);
+ if (io->device_status == SCSI_CHECK_CONDITION)
+ return scsi_dump_sense(udev, dev_scsi, (unsigned char *)(uintptr_t)io->response,
+ io->response_len);
+ else
+ return -1;
+}
+
+static int scsi_inquiry(struct udev *udev,
+ struct scsi_id_device *dev_scsi, int fd,
+ unsigned char evpd, unsigned char page,
+ unsigned char *buf, unsigned int buflen)
+{
+ unsigned char inq_cmd[INQUIRY_CMDLEN] =
+ { INQUIRY_CMD, evpd, page, 0, buflen, 0 };
+ unsigned char sense[SENSE_BUFF_LEN];
+ void *io_buf;
+ struct sg_io_v4 io_v4;
+ struct sg_io_hdr io_hdr;
+ int retry = 3; /* rather random */
+ int retval;
+
+ if (buflen > SCSI_INQ_BUFF_LEN) {
+ log_debug("buflen %d too long\n", buflen);
+ return -1;
+ }
+
+resend:
+ if (dev_scsi->use_sg == 4) {
+ memset(&io_v4, 0, sizeof(struct sg_io_v4));
+ io_v4.guard = 'Q';
+ io_v4.protocol = BSG_PROTOCOL_SCSI;
+ io_v4.subprotocol = BSG_SUB_PROTOCOL_SCSI_CMD;
+ io_v4.request_len = sizeof(inq_cmd);
+ io_v4.request = (uintptr_t)inq_cmd;
+ io_v4.max_response_len = sizeof(sense);
+ io_v4.response = (uintptr_t)sense;
+ io_v4.din_xfer_len = buflen;
+ io_v4.din_xferp = (uintptr_t)buf;
+ io_buf = (void *)&io_v4;
+ } else {
+ memset(&io_hdr, 0, sizeof(struct sg_io_hdr));
+ io_hdr.interface_id = 'S';
+ io_hdr.cmd_len = sizeof(inq_cmd);
+ io_hdr.mx_sb_len = sizeof(sense);
+ io_hdr.dxfer_direction = SG_DXFER_FROM_DEV;
+ io_hdr.dxfer_len = buflen;
+ io_hdr.dxferp = buf;
+ io_hdr.cmdp = inq_cmd;
+ io_hdr.sbp = sense;
+ io_hdr.timeout = DEF_TIMEOUT;
+ io_buf = (void *)&io_hdr;
+ }
+
+ retval = ioctl(fd, SG_IO, io_buf);
+ if (retval < 0) {
+ if ((errno == EINVAL || errno == ENOSYS) && dev_scsi->use_sg == 4) {
+ dev_scsi->use_sg = 3;
+ goto resend;
+ }
+ log_debug("%s: ioctl failed: %s\n", dev_scsi->kernel, strerror(errno));
+ goto error;
+ }
+
+ if (dev_scsi->use_sg == 4)
+ retval = sg_err_category4(udev, io_buf);
+ else
+ retval = sg_err_category3(udev, io_buf);
+
+ switch (retval) {
+ case SG_ERR_CAT_NOTSUPPORTED:
+ buf[1] = 0;
+ /* Fallthrough */
+ case SG_ERR_CAT_CLEAN:
+ case SG_ERR_CAT_RECOVERED:
+ retval = 0;
+ break;
+
+ default:
+ if (dev_scsi->use_sg == 4)
+ retval = scsi_dump_v4(udev, dev_scsi, io_buf);
+ else
+ retval = scsi_dump(udev, dev_scsi, io_buf);
+ }
+
+ if (!retval) {
+ retval = buflen;
+ } else if (retval > 0) {
+ if (--retry > 0)
+ goto resend;
+ retval = -1;
+ }
+
+error:
+ if (retval < 0)
+ log_debug("%s: Unable to get INQUIRY vpd %d page 0x%x.\n",
+ dev_scsi->kernel, evpd, page);
+
+ return retval;
+}
+
+/* Get list of supported EVPD pages */
+static int do_scsi_page0_inquiry(struct udev *udev,
+ struct scsi_id_device *dev_scsi, int fd,
+ unsigned char *buffer, unsigned int len)
+{
+ int retval;
+
+ memset(buffer, 0, len);
+ retval = scsi_inquiry(udev, dev_scsi, fd, 1, 0x0, buffer, len);
+ if (retval < 0)
+ return 1;
+
+ if (buffer[1] != 0) {
+ log_debug("%s: page 0 not available.\n", dev_scsi->kernel);
+ return 1;
+ }
+ if (buffer[3] > len) {
+ log_debug("%s: page 0 buffer too long %d\n", dev_scsi->kernel, buffer[3]);
+ return 1;
+ }
+
+ /*
+ * Following check is based on code once included in the 2.5.x
+ * kernel.
+ *
+ * Some ill behaved devices return the standard inquiry here
+ * rather than the evpd data, snoop the data to verify.
+ */
+ if (buffer[3] > MODEL_LENGTH) {
+ /*
+ * If the vendor id appears in the page assume the page is
+ * invalid.
+ */
+ if (strneq((char *)&buffer[VENDOR_LENGTH], dev_scsi->vendor, VENDOR_LENGTH)) {
+ log_debug("%s: invalid page0 data\n", dev_scsi->kernel);
+ return 1;
+ }
+ }
+ return 0;
+}
+
+/*
+ * The caller checks that serial is long enough to include the vendor +
+ * model.
+ */
+static int prepend_vendor_model(struct udev *udev,
+ struct scsi_id_device *dev_scsi, char *serial)
+{
+ int ind;
+
+ strncpy(serial, dev_scsi->vendor, VENDOR_LENGTH);
+ strncat(serial, dev_scsi->model, MODEL_LENGTH);
+ ind = strlen(serial);
+
+ /*
+ * This is not a complete check, since we are using strncat/cpy
+ * above, ind will never be too large.
+ */
+ if (ind != (VENDOR_LENGTH + MODEL_LENGTH)) {
+ log_debug("%s: expected length %d, got length %d\n",
+ dev_scsi->kernel, (VENDOR_LENGTH + MODEL_LENGTH), ind);
+ return -1;
+ }
+ return ind;
+}
+
+/*
+ * check_fill_0x83_id - check the page 0x83 id, if OK allocate and fill
+ * serial number.
+ */
+static int check_fill_0x83_id(struct udev *udev,
+ struct scsi_id_device *dev_scsi,
+ unsigned char *page_83,
+ const struct scsi_id_search_values
+ *id_search, char *serial, char *serial_short,
+ int max_len, char *wwn,
+ char *wwn_vendor_extension, char *tgpt_group)
+{
+ int i, j, s, len;
+
+ /*
+ * ASSOCIATION must be with the device (value 0)
+ * or with the target port for SCSI_ID_TGTPORT
+ */
+ if ((page_83[1] & 0x30) == 0x10) {
+ if (id_search->id_type != SCSI_ID_TGTGROUP)
+ return 1;
+ } else if ((page_83[1] & 0x30) != 0) {
+ return 1;
+ }
+
+ if ((page_83[1] & 0x0f) != id_search->id_type)
+ return 1;
+
+ /*
+ * Possibly check NAA sub-type.
+ */
+ if ((id_search->naa_type != SCSI_ID_NAA_DONT_CARE) &&
+ (id_search->naa_type != (page_83[4] & 0xf0) >> 4))
+ return 1;
+
+ /*
+ * Check for matching code set - ASCII or BINARY.
+ */
+ if ((page_83[0] & 0x0f) != id_search->code_set)
+ return 1;
+
+ /*
+ * page_83[3]: identifier length
+ */
+ len = page_83[3];
+ if ((page_83[0] & 0x0f) != SCSI_ID_ASCII)
+ /*
+ * If not ASCII, use two bytes for each binary value.
+ */
+ len *= 2;
+
+ /*
+ * Add one byte for the NUL termination, and one for the id_type.
+ */
+ len += 2;
+ if (id_search->id_type == SCSI_ID_VENDOR_SPECIFIC)
+ len += VENDOR_LENGTH + MODEL_LENGTH;
+
+ if (max_len < len) {
+ log_debug("%s: length %d too short - need %d\n",
+ dev_scsi->kernel, max_len, len);
+ return 1;
+ }
+
+ if (id_search->id_type == SCSI_ID_TGTGROUP && tgpt_group != NULL) {
+ unsigned int group;
+
+ group = ((unsigned int)page_83[6] << 8) | page_83[7];
+ sprintf(tgpt_group,"%x", group);
+ return 1;
+ }
+
+ serial[0] = hex_str[id_search->id_type];
+
+ /*
+ * For SCSI_ID_VENDOR_SPECIFIC prepend the vendor and model before
+ * the id since it is not unique across all vendors and models,
+ * this differs from SCSI_ID_T10_VENDOR, where the vendor is
+ * included in the identifier.
+ */
+ if (id_search->id_type == SCSI_ID_VENDOR_SPECIFIC)
+ if (prepend_vendor_model(udev, dev_scsi, &serial[1]) < 0)
+ return 1;
+
+ i = 4; /* offset to the start of the identifier */
+ s = j = strlen(serial);
+ if ((page_83[0] & 0x0f) == SCSI_ID_ASCII) {
+ /*
+ * ASCII descriptor.
+ */
+ while (i < (4 + page_83[3]))
+ serial[j++] = page_83[i++];
+ } else {
+ /*
+ * Binary descriptor, convert to ASCII, using two bytes of
+ * ASCII for each byte in the page_83.
+ */
+ while (i < (4 + page_83[3])) {
+ serial[j++] = hex_str[(page_83[i] & 0xf0) >> 4];
+ serial[j++] = hex_str[page_83[i] & 0x0f];
+ i++;
+ }
+ }
+
+ strcpy(serial_short, &serial[s]);
+
+ if (id_search->id_type == SCSI_ID_NAA && wwn != NULL) {
+ strncpy(wwn, &serial[s], 16);
+ if (wwn_vendor_extension != NULL) {
+ strncpy(wwn_vendor_extension, &serial[s + 16], 16);
+ }
+ }
+
+ return 0;
+}
+
+/* Extract the raw binary from VPD 0x83 pre-SPC devices */
+static int check_fill_0x83_prespc3(struct udev *udev,
+ struct scsi_id_device *dev_scsi,
+ unsigned char *page_83,
+ const struct scsi_id_search_values
+ *id_search, char *serial, char *serial_short, int max_len)
+{
+ int i, j;
+
+ serial[0] = hex_str[id_search->id_type];
+ /* serial has been memset to zero before */
+ j = strlen(serial); /* j = 1; */
+
+ for (i = 0; (i < page_83[3]) && (j < max_len-3); ++i) {
+ serial[j++] = hex_str[(page_83[4+i] & 0xf0) >> 4];
+ serial[j++] = hex_str[ page_83[4+i] & 0x0f];
+ }
+ serial[max_len-1] = 0;
+ strncpy(serial_short, serial, max_len-1);
+ return 0;
+}
+
+
+/* Get device identification VPD page */
+static int do_scsi_page83_inquiry(struct udev *udev,
+ struct scsi_id_device *dev_scsi, int fd,
+ char *serial, char *serial_short, int len,
+ char *unit_serial_number, char *wwn,
+ char *wwn_vendor_extension, char *tgpt_group)
+{
+ int retval;
+ unsigned int id_ind, j;
+ unsigned char page_83[SCSI_INQ_BUFF_LEN];
+
+ /* also pick up the page 80 serial number */
+ do_scsi_page80_inquiry(udev, dev_scsi, fd, NULL, unit_serial_number, MAX_SERIAL_LEN);
+
+ memset(page_83, 0, SCSI_INQ_BUFF_LEN);
+ retval = scsi_inquiry(udev, dev_scsi, fd, 1, PAGE_83, page_83,
+ SCSI_INQ_BUFF_LEN);
+ if (retval < 0)
+ return 1;
+
+ if (page_83[1] != PAGE_83) {
+ log_debug("%s: Invalid page 0x83\n", dev_scsi->kernel);
+ return 1;
+ }
+
+ /*
+ * XXX Some devices (IBM 3542) return all spaces for an identifier if
+ * the LUN is not actually configured. This leads to identifiers of
+ * the form: "1 ".
+ */
+
+ /*
+ * Model 4, 5, and (some) model 6 EMC Symmetrix devices return
+ * a page 83 reply according to SCSI-2 format instead of SPC-2/3.
+ *
+ * The SCSI-2 page 83 format returns an IEEE WWN in binary
+ * encoded hexi-decimal in the 16 bytes following the initial
+ * 4-byte page 83 reply header.
+ *
+ * Both the SPC-2 and SPC-3 formats return an IEEE WWN as part
+ * of an Identification descriptor. The 3rd byte of the first
+ * Identification descriptor is a reserved (BSZ) byte field.
+ *
+ * Reference the 7th byte of the page 83 reply to determine
+ * whether the reply is compliant with SCSI-2 or SPC-2/3
+ * specifications. A zero value in the 7th byte indicates
+ * an SPC-2/3 conformant reply, (i.e., the reserved field of the
+ * first Identification descriptor). This byte will be non-zero
+ * for a SCSI-2 conformant page 83 reply from these EMC
+ * Symmetrix models since the 7th byte of the reply corresponds
+ * to the 4th and 5th nibbles of the 6-byte OUI for EMC, that is,
+ * 0x006048.
+ */
+
+ if (page_83[6] != 0)
+ return check_fill_0x83_prespc3(udev,
+ dev_scsi, page_83, id_search_list,
+ serial, serial_short, len);
+
+ /*
+ * Search for a match in the prioritized id_search_list - since WWN ids
+ * come first we can pick up the WWN in check_fill_0x83_id().
+ */
+ for (id_ind = 0;
+ id_ind < sizeof(id_search_list)/sizeof(id_search_list[0]);
+ id_ind++) {
+ /*
+ * Examine each descriptor returned. There is normally only
+ * one or a small number of descriptors.
+ */
+ for (j = 4; j <= (unsigned int)page_83[3] + 3; j += page_83[j + 3] + 4) {
+ retval = check_fill_0x83_id(udev,
+ dev_scsi, &page_83[j],
+ &id_search_list[id_ind],
+ serial, serial_short, len,
+ wwn, wwn_vendor_extension,
+ tgpt_group);
+ if (!retval)
+ return retval;
+ else if (retval < 0)
+ return retval;
+ }
+ }
+ return 1;
+}
+
+/*
+ * Get device identification VPD page for older SCSI-2 device which is not
+ * compliant with either SPC-2 or SPC-3 format.
+ *
+ * Return the hard coded error code value 2 if the page 83 reply is not
+ * conformant to the SCSI-2 format.
+ */
+static int do_scsi_page83_prespc3_inquiry(struct udev *udev,
+ struct scsi_id_device *dev_scsi, int fd,
+ char *serial, char *serial_short, int len)
+{
+ int retval;
+ int i, j;
+ unsigned char page_83[SCSI_INQ_BUFF_LEN];
+
+ memset(page_83, 0, SCSI_INQ_BUFF_LEN);
+ retval = scsi_inquiry(udev, dev_scsi, fd, 1, PAGE_83, page_83, SCSI_INQ_BUFF_LEN);
+ if (retval < 0)
+ return 1;
+
+ if (page_83[1] != PAGE_83) {
+ log_debug("%s: Invalid page 0x83\n", dev_scsi->kernel);
+ return 1;
+ }
+ /*
+ * Model 4, 5, and (some) model 6 EMC Symmetrix devices return
+ * a page 83 reply according to SCSI-2 format instead of SPC-2/3.
+ *
+ * The SCSI-2 page 83 format returns an IEEE WWN in binary
+ * encoded hexi-decimal in the 16 bytes following the initial
+ * 4-byte page 83 reply header.
+ *
+ * Both the SPC-2 and SPC-3 formats return an IEEE WWN as part
+ * of an Identification descriptor. The 3rd byte of the first
+ * Identification descriptor is a reserved (BSZ) byte field.
+ *
+ * Reference the 7th byte of the page 83 reply to determine
+ * whether the reply is compliant with SCSI-2 or SPC-2/3
+ * specifications. A zero value in the 7th byte indicates
+ * an SPC-2/3 conformant reply, (i.e., the reserved field of the
+ * first Identification descriptor). This byte will be non-zero
+ * for a SCSI-2 conformant page 83 reply from these EMC
+ * Symmetrix models since the 7th byte of the reply corresponds
+ * to the 4th and 5th nibbles of the 6-byte OUI for EMC, that is,
+ * 0x006048.
+ */
+ if (page_83[6] == 0)
+ return 2;
+
+ serial[0] = hex_str[id_search_list[0].id_type];
+ /*
+ * The first four bytes contain data, not a descriptor.
+ */
+ i = 4;
+ j = strlen(serial);
+ /*
+ * Binary descriptor, convert to ASCII,
+ * using two bytes of ASCII for each byte
+ * in the page_83.
+ */
+ while (i < (page_83[3]+4)) {
+ serial[j++] = hex_str[(page_83[i] & 0xf0) >> 4];
+ serial[j++] = hex_str[page_83[i] & 0x0f];
+ i++;
+ }
+ return 0;
+}
+
+/* Get unit serial number VPD page */
+static int do_scsi_page80_inquiry(struct udev *udev,
+ struct scsi_id_device *dev_scsi, int fd,
+ char *serial, char *serial_short, int max_len)
+{
+ int retval;
+ int ser_ind;
+ int i;
+ int len;
+ unsigned char buf[SCSI_INQ_BUFF_LEN];
+
+ memset(buf, 0, SCSI_INQ_BUFF_LEN);
+ retval = scsi_inquiry(udev, dev_scsi, fd, 1, PAGE_80, buf, SCSI_INQ_BUFF_LEN);
+ if (retval < 0)
+ return retval;
+
+ if (buf[1] != PAGE_80) {
+ log_debug("%s: Invalid page 0x80\n", dev_scsi->kernel);
+ return 1;
+ }
+
+ len = 1 + VENDOR_LENGTH + MODEL_LENGTH + buf[3];
+ if (max_len < len) {
+ log_debug("%s: length %d too short - need %d\n",
+ dev_scsi->kernel, max_len, len);
+ return 1;
+ }
+ /*
+ * Prepend 'S' to avoid unlikely collision with page 0x83 vendor
+ * specific type where we prepend '0' + vendor + model.
+ */
+ len = buf[3];
+ if (serial != NULL) {
+ serial[0] = 'S';
+ ser_ind = prepend_vendor_model(udev, dev_scsi, &serial[1]);
+ if (ser_ind < 0)
+ return 1;
+ ser_ind++; /* for the leading 'S' */
+ for (i = 4; i < len + 4; i++, ser_ind++)
+ serial[ser_ind] = buf[i];
+ }
+ if (serial_short != NULL) {
+ memcpy(serial_short, &buf[4], len);
+ serial_short[len] = '\0';
+ }
+ return 0;
+}
+
+int scsi_std_inquiry(struct udev *udev,
+ struct scsi_id_device *dev_scsi, const char *devname)
+{
+ int fd;
+ unsigned char buf[SCSI_INQ_BUFF_LEN];
+ struct stat statbuf;
+ int err = 0;
+
+ fd = open(devname, O_RDONLY | O_NONBLOCK);
+ if (fd < 0) {
+ log_debug("scsi_id: cannot open %s: %s\n",
+ devname, strerror(errno));
+ return 1;
+ }
+
+ if (fstat(fd, &statbuf) < 0) {
+ log_debug("scsi_id: cannot stat %s: %s\n",
+ devname, strerror(errno));
+ err = 2;
+ goto out;
+ }
+ sprintf(dev_scsi->kernel,"%d:%d", major(statbuf.st_rdev),
+ minor(statbuf.st_rdev));
+
+ memset(buf, 0, SCSI_INQ_BUFF_LEN);
+ err = scsi_inquiry(udev, dev_scsi, fd, 0, 0, buf, SCSI_INQ_BUFF_LEN);
+ if (err < 0)
+ goto out;
+
+ err = 0;
+ memcpy(dev_scsi->vendor, buf + 8, 8);
+ dev_scsi->vendor[8] = '\0';
+ memcpy(dev_scsi->model, buf + 16, 16);
+ dev_scsi->model[16] = '\0';
+ memcpy(dev_scsi->revision, buf + 32, 4);
+ dev_scsi->revision[4] = '\0';
+ sprintf(dev_scsi->type,"%x", buf[0] & 0x1f);
+
+out:
+ close(fd);
+ return err;
+}
+
+int scsi_get_serial(struct udev *udev,
+ struct scsi_id_device *dev_scsi, const char *devname,
+ int page_code, int len)
+{
+ unsigned char page0[SCSI_INQ_BUFF_LEN];
+ int fd = -1;
+ int cnt;
+ int ind;
+ int retval;
+
+ memset(dev_scsi->serial, 0, len);
+ srand((unsigned int)getpid());
+ for (cnt = 20; cnt > 0; cnt--) {
+ struct timespec duration;
+
+ fd = open(devname, O_RDONLY | O_NONBLOCK);
+ if (fd >= 0 || errno != EBUSY)
+ break;
+ duration.tv_sec = 0;
+ duration.tv_nsec = (200 * 1000 * 1000) + (rand() % 100 * 1000 * 1000);
+ nanosleep(&duration, NULL);
+ }
+ if (fd < 0)
+ return 1;
+
+ if (page_code == PAGE_80) {
+ if (do_scsi_page80_inquiry(udev, dev_scsi, fd, dev_scsi->serial, dev_scsi->serial_short, len)) {
+ retval = 1;
+ goto completed;
+ } else {
+ retval = 0;
+ goto completed;
+ }
+ } else if (page_code == PAGE_83) {
+ if (do_scsi_page83_inquiry(udev, dev_scsi, fd, dev_scsi->serial, dev_scsi->serial_short, len, dev_scsi->unit_serial_number, dev_scsi->wwn, dev_scsi->wwn_vendor_extension, dev_scsi->tgpt_group)) {
+ retval = 1;
+ goto completed;
+ } else {
+ retval = 0;
+ goto completed;
+ }
+ } else if (page_code == PAGE_83_PRE_SPC3) {
+ retval = do_scsi_page83_prespc3_inquiry(udev, dev_scsi, fd, dev_scsi->serial, dev_scsi->serial_short, len);
+ if (retval) {
+ /*
+ * Fallback to servicing a SPC-2/3 compliant page 83
+ * inquiry if the page 83 reply format does not
+ * conform to pre-SPC3 expectations.
+ */
+ if (retval == 2) {
+ if (do_scsi_page83_inquiry(udev, dev_scsi, fd, dev_scsi->serial, dev_scsi->serial_short, len, dev_scsi->unit_serial_number, dev_scsi->wwn, dev_scsi->wwn_vendor_extension, dev_scsi->tgpt_group)) {
+ retval = 1;
+ goto completed;
+ } else {
+ retval = 0;
+ goto completed;
+ }
+ }
+ else {
+ retval = 1;
+ goto completed;
+ }
+ } else {
+ retval = 0;
+ goto completed;
+ }
+ } else if (page_code != 0x00) {
+ log_debug("%s: unsupported page code 0x%d\n", dev_scsi->kernel, page_code);
+ retval = 1;
+ goto completed;
+ }
+
+ /*
+ * Get page 0, the page of the pages. By default, try from best to
+ * worst of supported pages: 0x83 then 0x80.
+ */
+ if (do_scsi_page0_inquiry(udev, dev_scsi, fd, page0, SCSI_INQ_BUFF_LEN)) {
+ /*
+ * Don't try anything else. Black list if a specific page
+ * should be used for this vendor+model, or maybe have an
+ * optional fall-back to page 0x80 or page 0x83.
+ */
+ retval = 1;
+ goto completed;
+ }
+
+ for (ind = 4; ind <= page0[3] + 3; ind++)
+ if (page0[ind] == PAGE_83)
+ if (!do_scsi_page83_inquiry(udev, dev_scsi, fd,
+ dev_scsi->serial, dev_scsi->serial_short, len, dev_scsi->unit_serial_number, dev_scsi->wwn, dev_scsi->wwn_vendor_extension, dev_scsi->tgpt_group)) {
+ /*
+ * Success
+ */
+ retval = 0;
+ goto completed;
+ }
+
+ for (ind = 4; ind <= page0[3] + 3; ind++)
+ if (page0[ind] == PAGE_80)
+ if (!do_scsi_page80_inquiry(udev, dev_scsi, fd,
+ dev_scsi->serial, dev_scsi->serial_short, len)) {
+ /*
+ * Success
+ */
+ retval = 0;
+ goto completed;
+ }
+ retval = 1;
+
+completed:
+ close(fd);
+ return retval;
+}
diff --git a/src/udev/udev-builtin-blkid.c b/src/udev/udev-builtin-blkid.c
new file mode 100644
index 0000000000..bae429344f
--- /dev/null
+++ b/src/udev/udev-builtin-blkid.c
@@ -0,0 +1,220 @@
+/*
+ * probe disks for filesystems and partitions
+ *
+ * Copyright (C) 2011 Kay Sievers <kay@vrfy.org>
+ * Copyright (C) 2011 Karel Zak <kzak@redhat.com>
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <unistd.h>
+#include <string.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <getopt.h>
+#include <sys/stat.h>
+#include <blkid/blkid.h>
+
+#include "udev.h"
+
+static void print_property(struct udev_device *dev, bool test, const char *name, const char *value)
+{
+ char s[265];
+
+ s[0] = '\0';
+
+ if (streq(name, "TYPE")) {
+ udev_builtin_add_property(dev, test, "ID_FS_TYPE", value);
+
+ } else if (streq(name, "USAGE")) {
+ udev_builtin_add_property(dev, test, "ID_FS_USAGE", value);
+
+ } else if (streq(name, "VERSION")) {
+ udev_builtin_add_property(dev, test, "ID_FS_VERSION", value);
+
+ } else if (streq(name, "UUID")) {
+ blkid_safe_string(value, s, sizeof(s));
+ udev_builtin_add_property(dev, test, "ID_FS_UUID", s);
+ blkid_encode_string(value, s, sizeof(s));
+ udev_builtin_add_property(dev, test, "ID_FS_UUID_ENC", s);
+
+ } else if (streq(name, "UUID_SUB")) {
+ blkid_safe_string(value, s, sizeof(s));
+ udev_builtin_add_property(dev, test, "ID_FS_UUID_SUB", s);
+ blkid_encode_string(value, s, sizeof(s));
+ udev_builtin_add_property(dev, test, "ID_FS_UUID_SUB_ENC", s);
+
+ } else if (streq(name, "LABEL")) {
+ blkid_safe_string(value, s, sizeof(s));
+ udev_builtin_add_property(dev, test, "ID_FS_LABEL", s);
+ blkid_encode_string(value, s, sizeof(s));
+ udev_builtin_add_property(dev, test, "ID_FS_LABEL_ENC", s);
+
+ } else if (streq(name, "PTTYPE")) {
+ udev_builtin_add_property(dev, test, "ID_PART_TABLE_TYPE", value);
+
+ } else if (streq(name, "PART_ENTRY_NAME")) {
+ blkid_encode_string(value, s, sizeof(s));
+ udev_builtin_add_property(dev, test, "ID_PART_ENTRY_NAME", s);
+
+ } else if (streq(name, "PART_ENTRY_TYPE")) {
+ blkid_encode_string(value, s, sizeof(s));
+ udev_builtin_add_property(dev, test, "ID_PART_ENTRY_TYPE", s);
+
+ } else if (startswith(name, "PART_ENTRY_")) {
+ strscpyl(s, sizeof(s), "ID_", name, NULL);
+ udev_builtin_add_property(dev, test, s, value);
+
+ } else if (streq(name, "SYSTEM_ID")) {
+ blkid_encode_string(value, s, sizeof(s));
+ udev_builtin_add_property(dev, test, "ID_FS_SYSTEM_ID", s);
+
+ } else if (streq(name, "PUBLISHER_ID")) {
+ blkid_encode_string(value, s, sizeof(s));
+ udev_builtin_add_property(dev, test, "ID_FS_PUBLISHER_ID", s);
+
+ } else if (streq(name, "APPLICATION_ID")) {
+ blkid_encode_string(value, s, sizeof(s));
+ udev_builtin_add_property(dev, test, "ID_FS_APPLICATION_ID", s);
+
+ } else if (streq(name, "BOOT_SYSTEM_ID")) {
+ blkid_encode_string(value, s, sizeof(s));
+ udev_builtin_add_property(dev, test, "ID_FS_BOOT_SYSTEM_ID", s);
+ }
+}
+
+static int probe_superblocks(blkid_probe pr)
+{
+ struct stat st;
+ int rc;
+
+ if (fstat(blkid_probe_get_fd(pr), &st))
+ return -1;
+
+ blkid_probe_enable_partitions(pr, 1);
+
+ if (!S_ISCHR(st.st_mode) && blkid_probe_get_size(pr) <= 1024 * 1440 &&
+ blkid_probe_is_wholedisk(pr)) {
+ /*
+ * check if the small disk is partitioned, if yes then
+ * don't probe for filesystems.
+ */
+ blkid_probe_enable_superblocks(pr, 0);
+
+ rc = blkid_do_fullprobe(pr);
+ if (rc < 0)
+ return rc; /* -1 = error, 1 = nothing, 0 = succes */
+
+ if (blkid_probe_lookup_value(pr, "PTTYPE", NULL, NULL) == 0)
+ return 0; /* partition table detected */
+ }
+
+ blkid_probe_set_partitions_flags(pr, BLKID_PARTS_ENTRY_DETAILS);
+ blkid_probe_enable_superblocks(pr, 1);
+
+ return blkid_do_safeprobe(pr);
+}
+
+static int builtin_blkid(struct udev_device *dev, int argc, char *argv[], bool test)
+{
+ int64_t offset = 0;
+ bool noraid = false;
+ int fd = -1;
+ blkid_probe pr;
+ const char *data;
+ const char *name;
+ int nvals;
+ int i;
+ size_t len;
+ int err = 0;
+
+ static const struct option options[] = {
+ { "offset", optional_argument, NULL, 'o' },
+ { "noraid", no_argument, NULL, 'R' },
+ {}
+ };
+
+ for (;;) {
+ int option;
+
+ option = getopt_long(argc, argv, "oR", options, NULL);
+ if (option == -1)
+ break;
+
+ switch (option) {
+ case 'o':
+ offset = strtoull(optarg, NULL, 0);
+ break;
+ case 'R':
+ noraid = true;
+ break;
+ }
+ }
+
+ pr = blkid_new_probe();
+ if (!pr)
+ return EXIT_FAILURE;
+
+ blkid_probe_set_superblocks_flags(pr,
+ BLKID_SUBLKS_LABEL | BLKID_SUBLKS_UUID |
+ BLKID_SUBLKS_TYPE | BLKID_SUBLKS_SECTYPE |
+ BLKID_SUBLKS_USAGE | BLKID_SUBLKS_VERSION);
+
+ if (noraid)
+ blkid_probe_filter_superblocks_usage(pr, BLKID_FLTR_NOTIN, BLKID_USAGE_RAID);
+
+ fd = open(udev_device_get_devnode(dev), O_RDONLY|O_CLOEXEC);
+ if (fd < 0) {
+ fprintf(stderr, "error: %s: %m\n", udev_device_get_devnode(dev));
+ goto out;
+ }
+
+ err = blkid_probe_set_device(pr, fd, offset, 0);
+ if (err < 0)
+ goto out;
+
+ log_debug("probe %s %sraid offset=%llu\n",
+ udev_device_get_devnode(dev),
+ noraid ? "no" : "", (unsigned long long) offset);
+
+ err = probe_superblocks(pr);
+ if (err < 0)
+ goto out;
+
+ nvals = blkid_probe_numof_values(pr);
+ for (i = 0; i < nvals; i++) {
+ if (blkid_probe_get_value(pr, i, &name, &data, &len))
+ continue;
+ len = strnlen((char *) data, len);
+ print_property(dev, test, name, (char *) data);
+ }
+
+ blkid_free_probe(pr);
+out:
+ if (fd > 0)
+ close(fd);
+ if (err < 0)
+ return EXIT_FAILURE;
+ return EXIT_SUCCESS;
+}
+
+const struct udev_builtin udev_builtin_blkid = {
+ .name = "blkid",
+ .cmd = builtin_blkid,
+ .help = "filesystem and partition probing",
+ .run_once = true,
+};
diff --git a/src/udev/udev-builtin-btrfs.c b/src/udev/udev-builtin-btrfs.c
new file mode 100644
index 0000000000..f7bea69b26
--- /dev/null
+++ b/src/udev/udev-builtin-btrfs.c
@@ -0,0 +1,65 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Kay Sievers <kay@vrfy.org>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <unistd.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <sys/ioctl.h>
+
+#include "udev.h"
+
+#define BTRFS_PATH_NAME_MAX 4087
+struct btrfs_ioctl_vol_args {
+ int64_t fd;
+ char name[BTRFS_PATH_NAME_MAX + 1];
+};
+#define BTRFS_IOCTL_MAGIC 0x94
+#define BTRFS_IOC_DEVICES_READY _IOR(BTRFS_IOCTL_MAGIC, 39, struct btrfs_ioctl_vol_args)
+
+static int builtin_btrfs(struct udev_device *dev, int argc, char *argv[], bool test)
+{
+ struct btrfs_ioctl_vol_args args;
+ int fd;
+ int err;
+
+ if (argc != 3 || !streq(argv[1], "ready"))
+ return EXIT_FAILURE;
+
+ fd = open("/dev/btrfs-control", O_RDWR);
+ if (fd < 0)
+ return EXIT_FAILURE;
+
+ strscpy(args.name, sizeof(args.name), argv[2]);
+ err = ioctl(fd, BTRFS_IOC_DEVICES_READY, &args);
+ close(fd);
+ if (err < 0)
+ return EXIT_FAILURE;
+
+ udev_builtin_add_property(dev, test, "ID_BTRFS_READY", err == 0 ? "1" : "0");
+ return EXIT_SUCCESS;
+}
+
+const struct udev_builtin udev_builtin_btrfs = {
+ .name = "btrfs",
+ .cmd = builtin_btrfs,
+ .help = "btrfs volume management",
+};
diff --git a/src/udev/udev-builtin-firmware.c b/src/udev/udev-builtin-firmware.c
new file mode 100644
index 0000000000..b80940b6ef
--- /dev/null
+++ b/src/udev/udev-builtin-firmware.c
@@ -0,0 +1,157 @@
+/*
+ * firmware - Kernel firmware loader
+ *
+ * Copyright (C) 2009 Piter Punk <piterpunk@slackware.com>
+ * Copyright (C) 2009-2011 Kay Sievers <kay@vrfy.org>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; either version 2 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details:*
+ */
+
+#include <unistd.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <getopt.h>
+#include <errno.h>
+#include <stdbool.h>
+#include <sys/utsname.h>
+#include <sys/stat.h>
+
+#include "udev.h"
+
+static bool set_loading(struct udev *udev, char *loadpath, const char *state)
+{
+ FILE *ldfile;
+
+ ldfile = fopen(loadpath, "we");
+ if (ldfile == NULL) {
+ log_error("error: can not open '%s'\n", loadpath);
+ return false;
+ };
+ fprintf(ldfile, "%s\n", state);
+ fclose(ldfile);
+ return true;
+}
+
+static bool copy_firmware(struct udev *udev, const char *source, const char *target, size_t size)
+{
+ char *buf;
+ FILE *fsource = NULL, *ftarget = NULL;
+ bool ret = false;
+
+ buf = malloc(size);
+ if (buf == NULL) {
+ log_error("No memory available to load firmware file");
+ return false;
+ }
+
+ log_debug("writing '%s' (%zi) to '%s'\n", source, size, target);
+
+ fsource = fopen(source, "re");
+ if (fsource == NULL)
+ goto exit;
+ ftarget = fopen(target, "we");
+ if (ftarget == NULL)
+ goto exit;
+ if (fread(buf, size, 1, fsource) != 1)
+ goto exit;
+ if (fwrite(buf, size, 1, ftarget) == 1)
+ ret = true;
+exit:
+ if (ftarget != NULL)
+ fclose(ftarget);
+ if (fsource != NULL)
+ fclose(fsource);
+ free(buf);
+ return ret;
+}
+
+static int builtin_firmware(struct udev_device *dev, int argc, char *argv[], bool test)
+{
+ struct udev *udev = udev_device_get_udev(dev);
+ static const char *searchpath[] = { FIRMWARE_PATH };
+ char loadpath[UTIL_PATH_SIZE];
+ char datapath[UTIL_PATH_SIZE];
+ char fwpath[UTIL_PATH_SIZE];
+ const char *firmware;
+ FILE *fwfile = NULL;
+ struct utsname kernel;
+ struct stat statbuf;
+ unsigned int i;
+ int rc = EXIT_SUCCESS;
+
+ firmware = udev_device_get_property_value(dev, "FIRMWARE");
+ if (firmware == NULL) {
+ log_error("firmware parameter missing\n\n");
+ rc = EXIT_FAILURE;
+ goto exit;
+ }
+
+ /* lookup firmware file */
+ uname(&kernel);
+ for (i = 0; i < ELEMENTSOF(searchpath); i++) {
+ strscpyl(fwpath, sizeof(fwpath), searchpath[i], kernel.release, "/", firmware, NULL);
+ fwfile = fopen(fwpath, "re");
+ if (fwfile != NULL)
+ break;
+
+ strscpyl(fwpath, sizeof(fwpath), searchpath[i], firmware, NULL);
+ fwfile = fopen(fwpath, "re");
+ if (fwfile != NULL)
+ break;
+ }
+
+ strscpyl(loadpath, sizeof(loadpath), udev_device_get_syspath(dev), "/loading", NULL);
+
+ if (fwfile == NULL) {
+ log_debug("did not find firmware file '%s'\n", firmware);
+ rc = EXIT_FAILURE;
+ /*
+ * Do not cancel the request in the initrd, the real root might have
+ * the firmware file and the 'coldplug' run in the real root will find
+ * this pending request and fulfill or cancel it.
+ * */
+ if (!in_initrd())
+ set_loading(udev, loadpath, "-1");
+ goto exit;
+ }
+
+ if (stat(fwpath, &statbuf) < 0 || statbuf.st_size == 0) {
+ if (!in_initrd())
+ set_loading(udev, loadpath, "-1");
+ rc = EXIT_FAILURE;
+ goto exit;
+ }
+
+ if (!set_loading(udev, loadpath, "1"))
+ goto exit;
+
+ strscpyl(datapath, sizeof(datapath), udev_device_get_syspath(dev), "/data", NULL);
+ if (!copy_firmware(udev, fwpath, datapath, statbuf.st_size)) {
+ log_error("error sending firmware '%s' to device\n", firmware);
+ set_loading(udev, loadpath, "-1");
+ rc = EXIT_FAILURE;
+ goto exit;
+ };
+
+ set_loading(udev, loadpath, "0");
+exit:
+ if (fwfile)
+ fclose(fwfile);
+ return rc;
+}
+
+const struct udev_builtin udev_builtin_firmware = {
+ .name = "firmware",
+ .cmd = builtin_firmware,
+ .help = "kernel firmware loader",
+ .run_once = true,
+};
diff --git a/src/udev/udev-builtin-hwdb.c b/src/udev/udev-builtin-hwdb.c
new file mode 100644
index 0000000000..0b35d799fe
--- /dev/null
+++ b/src/udev/udev-builtin-hwdb.c
@@ -0,0 +1,162 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Kay Sievers <kay@vrfy.org>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include <errno.h>
+#include <string.h>
+#include <inttypes.h>
+#include <ctype.h>
+#include <stdlib.h>
+#include <getopt.h>
+
+#include "udev.h"
+
+static struct udev_hwdb *hwdb;
+
+int udev_builtin_hwdb_lookup(struct udev_device *dev, const char *modalias, bool test) {
+ struct udev_list_entry *entry;
+ int n = 0;
+
+ if (!hwdb)
+ return -ENOENT;
+
+ udev_list_entry_foreach(entry, udev_hwdb_get_properties_list_entry(hwdb, modalias, 0)) {
+ if (udev_builtin_add_property(dev, test,
+ udev_list_entry_get_name(entry),
+ udev_list_entry_get_value(entry)) < 0)
+ return -ENOMEM;
+ n++;
+ }
+ return n;
+}
+
+static const char *modalias_usb(struct udev_device *dev, char *s, size_t size) {
+ const char *v, *p;
+ int vn, pn;
+
+ v = udev_device_get_sysattr_value(dev, "idVendor");
+ if (!v)
+ return NULL;
+ p = udev_device_get_sysattr_value(dev, "idProduct");
+ if (!p)
+ return NULL;
+ vn = strtol(v, NULL, 16);
+ if (vn <= 0)
+ return NULL;
+ pn = strtol(p, NULL, 16);
+ if (pn <= 0)
+ return NULL;
+ snprintf(s, size, "usb:v%04Xp%04X*", vn, pn);
+ return s;
+}
+
+static int udev_builtin_hwdb_search(struct udev_device *dev, const char *subsystem, bool test) {
+ struct udev_device *d;
+ char s[16];
+ int n = 0;
+
+ for (d = dev; d; d = udev_device_get_parent(d)) {
+ const char *dsubsys;
+ const char *modalias = NULL;
+
+ dsubsys = udev_device_get_subsystem(d);
+ if (!dsubsys)
+ continue;
+
+ /* look only at devices of a specific subsystem */
+ if (subsystem && !streq(dsubsys, subsystem))
+ continue;
+
+ /* the usb_device does not have a modalias, compose one */
+ if (streq(dsubsys, "usb"))
+ modalias = modalias_usb(dev, s, sizeof(s));
+
+ if (!modalias)
+ modalias = udev_device_get_property_value(d, "MODALIAS");
+
+ if (!modalias)
+ continue;
+ n = udev_builtin_hwdb_lookup(dev, modalias, test);
+ if (n > 0)
+ break;
+ }
+
+ return n;
+}
+
+static int builtin_hwdb(struct udev_device *dev, int argc, char *argv[], bool test) {
+ static const struct option options[] = {
+ { "subsystem", required_argument, NULL, 's' },
+ {}
+ };
+ const char *subsystem = NULL;
+
+ if (!hwdb)
+ return EXIT_FAILURE;
+
+ for (;;) {
+ int option;
+
+ option = getopt_long(argc, argv, "s", options, NULL);
+ if (option == -1)
+ break;
+
+ switch (option) {
+ case 's':
+ subsystem = optarg;
+ break;
+ }
+ }
+
+ if (udev_builtin_hwdb_search(dev, subsystem, test) < 0)
+ return EXIT_FAILURE;
+ return EXIT_SUCCESS;
+}
+
+/* called at udev startup and reload */
+static int builtin_hwdb_init(struct udev *udev)
+{
+ if (hwdb)
+ return 0;
+ hwdb = udev_hwdb_new(udev);
+ if (!hwdb)
+ return -ENOMEM;
+ return 0;
+}
+
+/* called on udev shutdown and reload request */
+static void builtin_hwdb_exit(struct udev *udev)
+{
+ hwdb = udev_hwdb_unref(hwdb);
+}
+
+/* called every couple of seconds during event activity; 'true' if config has changed */
+static bool builtin_hwdb_validate(struct udev *udev)
+{
+ return udev_hwdb_validate(hwdb);
+}
+
+const struct udev_builtin udev_builtin_hwdb = {
+ .name = "hwdb",
+ .cmd = builtin_hwdb,
+ .init = builtin_hwdb_init,
+ .exit = builtin_hwdb_exit,
+ .validate = builtin_hwdb_validate,
+ .help = "hardware database",
+};
diff --git a/src/udev/udev-builtin-input_id.c b/src/udev/udev-builtin-input_id.c
new file mode 100644
index 0000000000..445b602f9c
--- /dev/null
+++ b/src/udev/udev-builtin-input_id.c
@@ -0,0 +1,219 @@
+/*
+ * compose persistent device path
+ *
+ * Copyright (C) 2009 Martin Pitt <martin.pitt@ubuntu.com>
+ * Portions Copyright (C) 2004 David Zeuthen, <david@fubar.dk>
+ * Copyright (C) 2011 Kay Sievers <kay@vrfy.org>
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <unistd.h>
+#include <string.h>
+#include <errno.h>
+#include <linux/limits.h>
+#include <linux/input.h>
+
+#include "udev.h"
+
+/* we must use this kernel-compatible implementation */
+#define BITS_PER_LONG (sizeof(unsigned long) * 8)
+#define NBITS(x) ((((x)-1)/BITS_PER_LONG)+1)
+#define OFF(x) ((x)%BITS_PER_LONG)
+#define BIT(x) (1UL<<OFF(x))
+#define LONG(x) ((x)/BITS_PER_LONG)
+#define test_bit(bit, array) ((array[LONG(bit)] >> OFF(bit)) & 1)
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wformat-nonliteral"
+/*
+ * Read a capability attribute and return bitmask.
+ * @param dev udev_device
+ * @param attr sysfs attribute name (e. g. "capabilities/key")
+ * @param bitmask: Output array which has a sizeof of bitmask_size
+ */
+static void get_cap_mask(struct udev_device *dev,
+ struct udev_device *pdev, const char* attr,
+ unsigned long *bitmask, size_t bitmask_size,
+ bool test)
+{
+ char text[4096];
+ unsigned i;
+ char* word;
+ unsigned long val;
+
+ snprintf(text, sizeof(text), "%s", udev_device_get_sysattr_value(pdev, attr));
+ log_debug("%s raw kernel attribute: %s\n", attr, text);
+
+ memset (bitmask, 0, bitmask_size);
+ i = 0;
+ while ((word = strrchr(text, ' ')) != NULL) {
+ val = strtoul (word+1, NULL, 16);
+ if (i < bitmask_size/sizeof(unsigned long))
+ bitmask[i] = val;
+ else
+ log_debug("ignoring %s block %lX which is larger than maximum size\n", attr, val);
+ *word = '\0';
+ ++i;
+ }
+ val = strtoul (text, NULL, 16);
+ if (i < bitmask_size / sizeof(unsigned long))
+ bitmask[i] = val;
+ else
+ log_debug("ignoring %s block %lX which is larger than maximum size\n", attr, val);
+
+ if (test) {
+ /* printf pattern with the right unsigned long number of hex chars */
+ snprintf(text, sizeof(text), " bit %%4u: %%0%zilX\n", 2 * sizeof(unsigned long));
+ log_debug("%s decoded bit map:\n", attr);
+ val = bitmask_size / sizeof (unsigned long);
+ /* skip over leading zeros */
+ while (bitmask[val-1] == 0 && val > 0)
+ --val;
+ for (i = 0; i < val; ++i)
+ log_debug(text, i * BITS_PER_LONG, bitmask[i]);
+ }
+}
+#pragma GCC diagnostic pop
+
+/* pointer devices */
+static void test_pointers (struct udev_device *dev,
+ const unsigned long* bitmask_ev,
+ const unsigned long* bitmask_abs,
+ const unsigned long* bitmask_key,
+ const unsigned long* bitmask_rel,
+ bool test)
+{
+ int is_mouse = 0;
+ int is_touchpad = 0;
+
+ if (!test_bit (EV_KEY, bitmask_ev)) {
+ if (test_bit (EV_ABS, bitmask_ev) &&
+ test_bit (ABS_X, bitmask_abs) &&
+ test_bit (ABS_Y, bitmask_abs) &&
+ test_bit (ABS_Z, bitmask_abs))
+ udev_builtin_add_property(dev, test, "ID_INPUT_ACCELEROMETER", "1");
+ return;
+ }
+
+ if (test_bit (EV_ABS, bitmask_ev) &&
+ test_bit (ABS_X, bitmask_abs) && test_bit (ABS_Y, bitmask_abs)) {
+ if (test_bit (BTN_STYLUS, bitmask_key) || test_bit (BTN_TOOL_PEN, bitmask_key))
+ udev_builtin_add_property(dev, test, "ID_INPUT_TABLET", "1");
+ else if (test_bit (BTN_TOOL_FINGER, bitmask_key) && !test_bit (BTN_TOOL_PEN, bitmask_key))
+ is_touchpad = 1;
+ else if (test_bit (BTN_TRIGGER, bitmask_key) ||
+ test_bit (BTN_A, bitmask_key) ||
+ test_bit (BTN_1, bitmask_key))
+ udev_builtin_add_property(dev, test, "ID_INPUT_JOYSTICK", "1");
+ else if (test_bit (BTN_MOUSE, bitmask_key))
+ /* This path is taken by VMware's USB mouse, which has
+ * absolute axes, but no touch/pressure button. */
+ is_mouse = 1;
+ else if (test_bit (BTN_TOUCH, bitmask_key))
+ udev_builtin_add_property(dev, test, "ID_INPUT_TOUCHSCREEN", "1");
+ }
+
+ if (test_bit (EV_REL, bitmask_ev) &&
+ test_bit (REL_X, bitmask_rel) && test_bit (REL_Y, bitmask_rel) &&
+ test_bit (BTN_MOUSE, bitmask_key))
+ is_mouse = 1;
+
+ if (is_mouse)
+ udev_builtin_add_property(dev, test, "ID_INPUT_MOUSE", "1");
+ if (is_touchpad)
+ udev_builtin_add_property(dev, test, "ID_INPUT_TOUCHPAD", "1");
+}
+
+/* key like devices */
+static void test_key (struct udev_device *dev,
+ const unsigned long* bitmask_ev,
+ const unsigned long* bitmask_key,
+ bool test)
+{
+ unsigned i;
+ unsigned long found;
+ unsigned long mask;
+
+ /* do we have any KEY_* capability? */
+ if (!test_bit (EV_KEY, bitmask_ev)) {
+ log_debug("test_key: no EV_KEY capability\n");
+ return;
+ }
+
+ /* only consider KEY_* here, not BTN_* */
+ found = 0;
+ for (i = 0; i < BTN_MISC/BITS_PER_LONG; ++i) {
+ found |= bitmask_key[i];
+ log_debug("test_key: checking bit block %lu for any keys; found=%i\n", (unsigned long)i*BITS_PER_LONG, found > 0);
+ }
+ /* If there are no keys in the lower block, check the higher block */
+ if (!found) {
+ for (i = KEY_OK; i < BTN_TRIGGER_HAPPY; ++i) {
+ if (test_bit (i, bitmask_key)) {
+ log_debug("test_key: Found key %x in high block\n", i);
+ found = 1;
+ break;
+ }
+ }
+ }
+
+ if (found > 0)
+ udev_builtin_add_property(dev, test, "ID_INPUT_KEY", "1");
+
+ /* the first 32 bits are ESC, numbers, and Q to D; if we have all of
+ * those, consider it a full keyboard; do not test KEY_RESERVED, though */
+ mask = 0xFFFFFFFE;
+ if ((bitmask_key[0] & mask) == mask)
+ udev_builtin_add_property(dev, test, "ID_INPUT_KEYBOARD", "1");
+}
+
+static int builtin_input_id(struct udev_device *dev, int argc, char *argv[], bool test)
+{
+ struct udev_device *pdev;
+ unsigned long bitmask_ev[NBITS(EV_MAX)];
+ unsigned long bitmask_abs[NBITS(ABS_MAX)];
+ unsigned long bitmask_key[NBITS(KEY_MAX)];
+ unsigned long bitmask_rel[NBITS(REL_MAX)];
+
+ /* walk up the parental chain until we find the real input device; the
+ * argument is very likely a subdevice of this, like eventN */
+ pdev = dev;
+ while (pdev != NULL && udev_device_get_sysattr_value(pdev, "capabilities/ev") == NULL)
+ pdev = udev_device_get_parent_with_subsystem_devtype(pdev, "input", NULL);
+
+ /* not an "input" class device */
+ if (pdev == NULL)
+ return EXIT_SUCCESS;
+
+ /* Use this as a flag that input devices were detected, so that this
+ * program doesn't need to be called more than once per device */
+ udev_builtin_add_property(dev, test, "ID_INPUT", "1");
+ get_cap_mask(dev, pdev, "capabilities/ev", bitmask_ev, sizeof(bitmask_ev), test);
+ get_cap_mask(dev, pdev, "capabilities/abs", bitmask_abs, sizeof(bitmask_abs), test);
+ get_cap_mask(dev, pdev, "capabilities/rel", bitmask_rel, sizeof(bitmask_rel), test);
+ get_cap_mask(dev, pdev, "capabilities/key", bitmask_key, sizeof(bitmask_key), test);
+ test_pointers(dev, bitmask_ev, bitmask_abs, bitmask_key, bitmask_rel, test);
+ test_key(dev, bitmask_ev, bitmask_key, test);
+ return EXIT_SUCCESS;
+}
+
+const struct udev_builtin udev_builtin_input_id = {
+ .name = "input_id",
+ .cmd = builtin_input_id,
+ .help = "input device properties",
+};
diff --git a/src/udev/udev-builtin-kmod.c b/src/udev/udev-builtin-kmod.c
new file mode 100644
index 0000000000..fc28121267
--- /dev/null
+++ b/src/udev/udev-builtin-kmod.c
@@ -0,0 +1,134 @@
+/*
+ * load kernel modules
+ *
+ * Copyright (C) 2011-2012 Kay Sievers <kay@vrfy.org>
+ * Copyright (C) 2011 ProFUSION embedded systems
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <unistd.h>
+#include <string.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <sys/wait.h>
+#include <libkmod.h>
+
+#include "udev.h"
+
+static struct kmod_ctx *ctx;
+
+static int load_module(struct udev *udev, const char *alias)
+{
+ struct kmod_list *list = NULL;
+ struct kmod_list *l;
+ int err;
+
+ err = kmod_module_new_from_lookup(ctx, alias, &list);
+ if (err < 0)
+ return err;
+
+ if (list == NULL)
+ log_debug("no module matches '%s'\n", alias);
+
+ kmod_list_foreach(l, list) {
+ struct kmod_module *mod = kmod_module_get_module(l);
+
+ err = kmod_module_probe_insert_module(mod, KMOD_PROBE_APPLY_BLACKLIST, NULL, NULL, NULL, NULL);
+ if (err == KMOD_PROBE_APPLY_BLACKLIST)
+ log_debug("module '%s' is blacklisted\n", kmod_module_get_name(mod));
+ else if (err == 0)
+ log_debug("inserted '%s'\n", kmod_module_get_name(mod));
+ else
+ log_debug("failed to insert '%s'\n", kmod_module_get_name(mod));
+
+ kmod_module_unref(mod);
+ }
+
+ kmod_module_unref_list(list);
+ return err;
+}
+
+static void udev_kmod_log(void *data, int priority, const char *file, int line,
+ const char *fn, const char *format, va_list args)
+{
+ udev_main_log(data, priority, file, line, fn, format, args);
+}
+
+static int builtin_kmod(struct udev_device *dev, int argc, char *argv[], bool test)
+{
+ struct udev *udev = udev_device_get_udev(dev);
+ int i;
+
+ if (!ctx)
+ return 0;
+
+ if (argc < 3 || !streq(argv[1], "load")) {
+ log_error("expect: %s load <module>\n", argv[0]);
+ return EXIT_FAILURE;
+ }
+
+ for (i = 2; argv[i]; i++) {
+ log_debug("execute '%s' '%s'\n", argv[1], argv[i]);
+ load_module(udev, argv[i]);
+ }
+
+ return EXIT_SUCCESS;
+}
+
+/* called at udev startup and reload */
+static int builtin_kmod_init(struct udev *udev)
+{
+ if (ctx)
+ return 0;
+
+ ctx = kmod_new(NULL, NULL);
+ if (!ctx)
+ return -ENOMEM;
+
+ log_debug("load module index\n");
+ kmod_set_log_fn(ctx, udev_kmod_log, udev);
+ kmod_load_resources(ctx);
+ return 0;
+}
+
+/* called on udev shutdown and reload request */
+static void builtin_kmod_exit(struct udev *udev)
+{
+ log_debug("unload module index\n");
+ ctx = kmod_unref(ctx);
+}
+
+/* called every couple of seconds during event activity; 'true' if config has changed */
+static bool builtin_kmod_validate(struct udev *udev)
+{
+ log_debug("validate module index\n");
+ if (!ctx)
+ return false;
+ return (kmod_validate_resources(ctx) != KMOD_RESOURCES_OK);
+}
+
+const struct udev_builtin udev_builtin_kmod = {
+ .name = "kmod",
+ .cmd = builtin_kmod,
+ .init = builtin_kmod_init,
+ .exit = builtin_kmod_exit,
+ .validate = builtin_kmod_validate,
+ .help = "kernel module loader",
+ .run_once = false,
+};
diff --git a/src/udev/udev-builtin-net_id.c b/src/udev/udev-builtin-net_id.c
new file mode 100644
index 0000000000..5719021e93
--- /dev/null
+++ b/src/udev/udev-builtin-net_id.c
@@ -0,0 +1,505 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Kay Sievers <kay@vrfy.org>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+/*
+ * Predictable network interface device names based on:
+ * - firmware/bios-provided index numbers for on-board devices
+ * - firmware-provided pci-express hotplug slot index number
+ * - physical/geographical location of the hardware
+ * - the interface's MAC address
+ *
+ * http://www.freedesktop.org/wiki/Software/systemd/PredictableNetworkInterfaceNames
+ *
+ * Two character prefixes based on the type of interface:
+ * en -- ethernet
+ * wl -- wlan
+ * ww -- wwan
+ *
+ * Type of names:
+ * o<index> -- on-board device index number
+ * s<slot>[f<function>][d<dev_id>] -- hotplug slot index number
+ * x<MAC> -- MAC address
+ * p<bus>s<slot>[f<function>][d<dev_id>] -- PCI geographical location
+ * p<bus>s<slot>[f<function>][u<port>][..][c<config>][i<interface>]
+ * -- USB port number chain
+ *
+ * All multi-function PCI devices will carry the [f<function>] number in the
+ * device name, including the function 0 device.
+ *
+ * For USB devices the full chain of port numbers of hubs is composed. If the
+ * name gets longer than the maximum number of 15 characters, the name is not
+ * exported.
+ * The usual USB configuration == 1 and interface == 0 values are suppressed.
+ *
+ * PCI ethernet card with firmware index "1":
+ * ID_NET_NAME_ONBOARD=eno1
+ * ID_NET_NAME_ONBOARD_LABEL=Ethernet Port 1
+ *
+ * PCI ethernet card in hotplug slot with firmware index number:
+ * /sys/devices/pci0000:00/0000:00:1c.3/0000:05:00.0/net/ens1
+ * ID_NET_NAME_MAC=enx000000000466
+ * ID_NET_NAME_PATH=enp5s0
+ * ID_NET_NAME_SLOT=ens1
+ *
+ * PCI ethernet multi-function card with 2 ports:
+ * /sys/devices/pci0000:00/0000:00:1c.0/0000:02:00.0/net/enp2s0f0
+ * ID_NET_NAME_MAC=enx78e7d1ea46da
+ * ID_NET_NAME_PATH=enp2s0f0
+ * /sys/devices/pci0000:00/0000:00:1c.0/0000:02:00.1/net/enp2s0f1
+ * ID_NET_NAME_MAC=enx78e7d1ea46dc
+ * ID_NET_NAME_PATH=enp2s0f1
+ *
+ * PCI wlan card:
+ * /sys/devices/pci0000:00/0000:00:1c.1/0000:03:00.0/net/wlp3s0
+ * ID_NET_NAME_MAC=wlx0024d7e31130
+ * ID_NET_NAME_PATH=wlp3s0
+ *
+ * USB built-in 3G modem:
+ * /sys/devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.4/2-1.4:1.6/net/wwp0s29u1u4i6
+ * ID_NET_NAME_MAC=wwx028037ec0200
+ * ID_NET_NAME_PATH=wwp0s29u1u4i6
+ *
+ * USB Android phone:
+ * /sys/devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2/2-1.2:1.0/net/enp0s29u1u2
+ * ID_NET_NAME_MAC=enxd626b3450fb5
+ * ID_NET_NAME_PATH=enp0s29u1u2
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <unistd.h>
+#include <string.h>
+#include <errno.h>
+#include <net/if.h>
+#include <linux/pci_regs.h>
+
+#include "udev.h"
+#include "fileio.h"
+
+enum netname_type{
+ NET_UNDEF,
+ NET_PCI,
+ NET_USB,
+ NET_BCMA,
+};
+
+struct netnames {
+ enum netname_type type;
+
+ uint8_t mac[6];
+ bool mac_valid;
+
+ struct udev_device *pcidev;
+ char pci_slot[IFNAMSIZ];
+ char pci_path[IFNAMSIZ];
+ char pci_onboard[IFNAMSIZ];
+ const char *pci_onboard_label;
+
+ char usb_ports[IFNAMSIZ];
+
+ char bcma_core[IFNAMSIZ];
+};
+
+/* retrieve on-board index number and label from firmware */
+static int dev_pci_onboard(struct udev_device *dev, struct netnames *names) {
+ const char *index;
+ int idx;
+
+ /* ACPI _DSM -- device specific method for naming a PCI or PCI Express device */
+ index = udev_device_get_sysattr_value(names->pcidev, "acpi_index");
+ /* SMBIOS type 41 -- Onboard Devices Extended Information */
+ if (!index)
+ index = udev_device_get_sysattr_value(names->pcidev, "index");
+ if (!index)
+ return -ENOENT;
+ idx = strtoul(index, NULL, 0);
+ if (idx <= 0)
+ return -EINVAL;
+ snprintf(names->pci_onboard, sizeof(names->pci_onboard), "o%d", idx);
+
+ names->pci_onboard_label = udev_device_get_sysattr_value(names->pcidev, "label");
+ return 0;
+}
+
+/* read the 256 bytes PCI configuration space to check the multi-function bit */
+static bool is_pci_multifunction(struct udev_device *dev) {
+ char filename[256];
+ FILE *f = NULL;
+ char config[64];
+ bool multi = false;
+
+ snprintf(filename, sizeof(filename), "%s/config", udev_device_get_syspath(dev));
+ f = fopen(filename, "re");
+ if (!f)
+ goto out;
+ if (fread(&config, sizeof(config), 1, f) != 1)
+ goto out;
+
+ /* bit 0-6 header type, bit 7 multi/single function device */
+ if ((config[PCI_HEADER_TYPE] & 0x80) != 0)
+ multi = true;
+out:
+ if(f)
+ fclose(f);
+ return multi;
+}
+
+static int dev_pci_slot(struct udev_device *dev, struct netnames *names) {
+ struct udev *udev = udev_device_get_udev(names->pcidev);
+ unsigned int bus;
+ unsigned int slot;
+ unsigned int func;
+ unsigned int dev_id = 0;
+ size_t l;
+ char *s;
+ const char *attr;
+ struct udev_device *pci = NULL;
+ char slots[256];
+ DIR *dir;
+ struct dirent *dent;
+ char str[256];
+ int hotplug_slot = 0;
+ int err = 0;
+
+ if (sscanf(udev_device_get_sysname(names->pcidev), "0000:%x:%x.%d", &bus, &slot, &func) != 3)
+ return -ENOENT;
+
+ /* kernel provided multi-device index */
+ attr = udev_device_get_sysattr_value(dev, "dev_id");
+ if (attr)
+ dev_id = strtol(attr, NULL, 16);
+
+ /* compose a name based on the raw kernel's PCI bus, slot numbers */
+ s = names->pci_path;
+ l = strpcpyf(&s, sizeof(names->pci_path), "p%ds%d", bus, slot);
+ if (func > 0 || is_pci_multifunction(names->pcidev))
+ l = strpcpyf(&s, l, "f%d", func);
+ if (dev_id > 0)
+ l = strpcpyf(&s, l, "d%d", dev_id);
+ if (l == 0)
+ names->pci_path[0] = '\0';
+
+ /* ACPI _SUN -- slot user number */
+ pci = udev_device_new_from_subsystem_sysname(udev, "subsystem", "pci");
+ if (!pci) {
+ err = -ENOENT;
+ goto out;
+ }
+ snprintf(slots, sizeof(slots), "%s/slots", udev_device_get_syspath(pci));
+ dir = opendir(slots);
+ if (!dir) {
+ err = -errno;
+ goto out;
+ }
+
+ for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
+ int i;
+ char *rest;
+ char *address;
+
+ if (dent->d_name[0] == '.')
+ continue;
+ i = strtol(dent->d_name, &rest, 10);
+ if (rest[0] != '\0')
+ continue;
+ if (i < 1)
+ continue;
+ snprintf(str, sizeof(str), "%s/%s/address", slots, dent->d_name);
+ if (read_one_line_file(str, &address) >= 0) {
+ /* match slot address with device by stripping the function */
+ if (strneq(address, udev_device_get_sysname(names->pcidev), strlen(address)))
+ hotplug_slot = i;
+ free(address);
+ }
+
+ if (hotplug_slot > 0)
+ break;
+ }
+ closedir(dir);
+
+ if (hotplug_slot > 0) {
+ s = names->pci_slot;
+ l = strpcpyf(&s, sizeof(names->pci_slot), "s%d", hotplug_slot);
+ if (func > 0 || is_pci_multifunction(names->pcidev))
+ l = strpcpyf(&s, l, "f%d", func);
+ if (dev_id > 0)
+ l = strpcpyf(&s, l, "d%d", dev_id);
+ if (l == 0)
+ names->pci_path[0] = '\0';
+ }
+out:
+ udev_device_unref(pci);
+ return err;
+}
+
+static int names_pci(struct udev_device *dev, struct netnames *names) {
+ struct udev_device *parent;
+
+ parent = udev_device_get_parent(dev);
+ if (!parent)
+ return -ENOENT;
+ /* check if our direct parent is a PCI device with no other bus in-between */
+ if (streq_ptr("pci", udev_device_get_subsystem(parent))) {
+ names->type = NET_PCI;
+ names->pcidev = parent;
+ } else {
+ names->pcidev = udev_device_get_parent_with_subsystem_devtype(dev, "pci", NULL);
+ if (!names->pcidev)
+ return -ENOENT;
+ }
+ dev_pci_onboard(dev, names);
+ dev_pci_slot(dev, names);
+ return 0;
+}
+
+static int names_usb(struct udev_device *dev, struct netnames *names) {
+ struct udev_device *usbdev;
+ char name[256];
+ char *ports;
+ char *config;
+ char *interf;
+ size_t l;
+ char *s;
+
+ usbdev = udev_device_get_parent_with_subsystem_devtype(dev, "usb", "usb_interface");
+ if (!usbdev)
+ return -ENOENT;
+
+ /* get USB port number chain, configuration, interface */
+ strscpy(name, sizeof(name), udev_device_get_sysname(usbdev));
+ s = strchr(name, '-');
+ if (!s)
+ return -EINVAL;
+ ports = s+1;
+
+ s = strchr(ports, ':');
+ if (!s)
+ return -EINVAL;
+ s[0] = '\0';
+ config = s+1;
+
+ s = strchr(config, '.');
+ if (!s)
+ return -EINVAL;
+ s[0] = '\0';
+ interf = s+1;
+
+ /* prefix every port number in the chain with "u"*/
+ s = ports;
+ while ((s = strchr(s, '.')))
+ s[0] = 'u';
+ s = names->usb_ports;
+ l = strpcpyl(&s, sizeof(names->usb_ports), "u", ports, NULL);
+
+ /* append USB config number, suppress the common config == 1 */
+ if (!streq(config, "1"))
+ l = strpcpyl(&s, sizeof(names->usb_ports), "c", config, NULL);
+
+ /* append USB interface number, suppress the interface == 0 */
+ if (!streq(interf, "0"))
+ l = strpcpyl(&s, sizeof(names->usb_ports), "i", interf, NULL);
+ if (l == 0)
+ return -ENAMETOOLONG;
+
+ names->type = NET_USB;
+ return 0;
+}
+
+static int names_bcma(struct udev_device *dev, struct netnames *names) {
+ struct udev_device *bcmadev;
+ unsigned int core;
+
+ bcmadev = udev_device_get_parent_with_subsystem_devtype(dev, "bcma", NULL);
+ if (!bcmadev)
+ return -ENOENT;
+
+ /* bus num:core num */
+ if (sscanf(udev_device_get_sysname(bcmadev), "bcma%*d:%d", &core) != 1)
+ return -EINVAL;
+ /* suppress the common core == 0 */
+ if (core > 0)
+ snprintf(names->bcma_core, sizeof(names->bcma_core), "b%d", core);
+
+ names->type = NET_BCMA;
+ return 0;
+}
+
+static int names_mac(struct udev_device *dev, struct netnames *names) {
+ const char *s;
+ unsigned int i;
+ unsigned int a1, a2, a3, a4, a5, a6;
+
+ /* check for NET_ADDR_PERM, skip random MAC addresses */
+ s = udev_device_get_sysattr_value(dev, "addr_assign_type");
+ if (!s)
+ return EXIT_FAILURE;
+ i = strtoul(s, NULL, 0);
+ if (i != 0)
+ return 0;
+
+ s = udev_device_get_sysattr_value(dev, "address");
+ if (!s)
+ return -ENOENT;
+ if (sscanf(s, "%x:%x:%x:%x:%x:%x", &a1, &a2, &a3, &a4, &a5, &a6) != 6)
+ return -EINVAL;
+
+ /* skip empty MAC addresses */
+ if (a1 + a2 + a3 + a4 + a5 + a6 == 0)
+ return -EINVAL;
+
+ names->mac[0] = a1;
+ names->mac[1] = a2;
+ names->mac[2] = a3;
+ names->mac[3] = a4;
+ names->mac[4] = a5;
+ names->mac[5] = a6;
+ names->mac_valid = true;
+ return 0;
+}
+
+/* IEEE Organizationally Unique Identifier vendor string */
+static int ieee_oui(struct udev_device *dev, struct netnames *names, bool test) {
+ char str[32];
+
+ if (!names->mac_valid)
+ return -ENOENT;
+ /* skip commonly misused 00:00:00 (Xerox) prefix */
+ if (memcmp(names->mac, "\0\0\0", 3) == 0)
+ return -EINVAL;
+ snprintf(str, sizeof(str), "OUI:%02X%02X%02X%02X%02X%02X",
+ names->mac[0], names->mac[1], names->mac[2],
+ names->mac[3], names->mac[4], names->mac[5]);
+ udev_builtin_hwdb_lookup(dev, str, test);
+ return 0;
+}
+
+static int builtin_net_id(struct udev_device *dev, int argc, char *argv[], bool test) {
+ const char *s;
+ const char *p;
+ unsigned int i;
+ const char *devtype;
+ const char *prefix = "en";
+ struct netnames names = {};
+ int err;
+
+ /* handle only ARPHRD_ETHER devices */
+ s = udev_device_get_sysattr_value(dev, "type");
+ if (!s)
+ return EXIT_FAILURE;
+ i = strtoul(s, NULL, 0);
+ if (i != 1)
+ return 0;
+
+ /* skip stacked devices, like VLANs, ... */
+ s = udev_device_get_sysattr_value(dev, "ifindex");
+ if (!s)
+ return EXIT_FAILURE;
+ p = udev_device_get_sysattr_value(dev, "iflink");
+ if (!p)
+ return EXIT_FAILURE;
+ if (!streq(s, p))
+ return 0;
+
+ devtype = udev_device_get_devtype(dev);
+ if (devtype) {
+ if (streq("wlan", devtype))
+ prefix = "wl";
+ else if (streq("wwan", devtype))
+ prefix = "ww";
+ }
+
+ err = names_mac(dev, &names);
+ if (err >= 0 && names.mac_valid) {
+ char str[IFNAMSIZ];
+
+ snprintf(str, sizeof(str), "%sx%02x%02x%02x%02x%02x%02x", prefix,
+ names.mac[0], names.mac[1], names.mac[2],
+ names.mac[3], names.mac[4], names.mac[5]);
+ udev_builtin_add_property(dev, test, "ID_NET_NAME_MAC", str);
+
+ ieee_oui(dev, &names, test);
+ }
+
+ /* get PCI based path names, we compose only PCI based paths */
+ err = names_pci(dev, &names);
+ if (err < 0)
+ goto out;
+
+ /* plain PCI device */
+ if (names.type == NET_PCI) {
+ char str[IFNAMSIZ];
+
+ if (names.pci_onboard[0])
+ if (snprintf(str, sizeof(str), "%s%s", prefix, names.pci_onboard) < (int)sizeof(str))
+ udev_builtin_add_property(dev, test, "ID_NET_NAME_ONBOARD", str);
+
+ if (names.pci_onboard_label)
+ if (snprintf(str, sizeof(str), "%s%s", prefix, names.pci_onboard_label) < (int)sizeof(str))
+ udev_builtin_add_property(dev, test, "ID_NET_LABEL_ONBOARD", str);
+
+ if (names.pci_path[0])
+ if (snprintf(str, sizeof(str), "%s%s", prefix, names.pci_path) < (int)sizeof(str))
+ udev_builtin_add_property(dev, test, "ID_NET_NAME_PATH", str);
+
+ if (names.pci_slot[0])
+ if (snprintf(str, sizeof(str), "%s%s", prefix, names.pci_slot) < (int)sizeof(str))
+ udev_builtin_add_property(dev, test, "ID_NET_NAME_SLOT", str);
+ goto out;
+ }
+
+ /* USB device */
+ err = names_usb(dev, &names);
+ if (err >= 0 && names.type == NET_USB) {
+ char str[IFNAMSIZ];
+
+ if (names.pci_path[0])
+ if (snprintf(str, sizeof(str), "%s%s%s", prefix, names.pci_path, names.usb_ports) < (int)sizeof(str))
+ udev_builtin_add_property(dev, test, "ID_NET_NAME_PATH", str);
+
+ if (names.pci_slot[0])
+ if (snprintf(str, sizeof(str), "%s%s%s", prefix, names.pci_slot, names.usb_ports) < (int)sizeof(str))
+ udev_builtin_add_property(dev, test, "ID_NET_NAME_SLOT", str);
+ goto out;
+ }
+
+ /* Broadcom bus */
+ err = names_bcma(dev, &names);
+ if (err >= 0 && names.type == NET_BCMA) {
+ char str[IFNAMSIZ];
+
+ if (names.pci_path[0])
+ if (snprintf(str, sizeof(str), "%s%s%s", prefix, names.pci_path, names.bcma_core) < (int)sizeof(str))
+ udev_builtin_add_property(dev, test, "ID_NET_NAME_PATH", str);
+
+ if (names.pci_slot[0])
+ if (snprintf(str, sizeof(str), "%s%s%s", prefix, names.pci_slot, names.bcma_core) < (int)sizeof(str))
+ udev_builtin_add_property(dev, test, "ID_NET_NAME_SLOT", str);
+ goto out;
+ }
+
+out:
+ return EXIT_SUCCESS;
+}
+
+const struct udev_builtin udev_builtin_net_id = {
+ .name = "net_id",
+ .cmd = builtin_net_id,
+ .help = "network device properties",
+};
diff --git a/src/udev/udev-builtin-path_id.c b/src/udev/udev-builtin-path_id.c
new file mode 100644
index 0000000000..da0273197b
--- /dev/null
+++ b/src/udev/udev-builtin-path_id.c
@@ -0,0 +1,593 @@
+/*
+ * compose persistent device path
+ *
+ * Copyright (C) 2009-2011 Kay Sievers <kay@vrfy.org>
+ *
+ * Logic based on Hannes Reinecke's shell script.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <unistd.h>
+#include <string.h>
+#include <ctype.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <dirent.h>
+#include <getopt.h>
+
+#include "udev.h"
+
+static int path_prepend(char **path, const char *fmt, ...)
+{
+ va_list va;
+ char *pre;
+ int err = 0;
+
+ va_start(va, fmt);
+ err = vasprintf(&pre, fmt, va);
+ va_end(va);
+ if (err < 0)
+ goto out;
+
+ if (*path != NULL) {
+ char *new;
+
+ err = asprintf(&new, "%s-%s", pre, *path);
+ free(pre);
+ if (err < 0)
+ goto out;
+ free(*path);
+ *path = new;
+ } else {
+ *path = pre;
+ }
+out:
+ return err;
+}
+
+/*
+** Linux only supports 32 bit luns.
+** See drivers/scsi/scsi_scan.c::scsilun_to_int() for more details.
+*/
+static int format_lun_number(struct udev_device *dev, char **path)
+{
+ unsigned long lun = strtoul(udev_device_get_sysnum(dev), NULL, 10);
+
+ /* address method 0, peripheral device addressing with bus id of zero */
+ if (lun < 256)
+ return path_prepend(path, "lun-%d", lun);
+ /* handle all other lun addressing methods by using a variant of the original lun format */
+ return path_prepend(path, "lun-0x%04x%04x00000000", (lun & 0xffff), (lun >> 16) & 0xffff);
+}
+
+static struct udev_device *skip_subsystem(struct udev_device *dev, const char *subsys)
+{
+ struct udev_device *parent = dev;
+
+ while (parent != NULL) {
+ const char *subsystem;
+
+ subsystem = udev_device_get_subsystem(parent);
+ if (subsystem == NULL || !streq(subsystem, subsys))
+ break;
+ dev = parent;
+ parent = udev_device_get_parent(parent);
+ }
+ return dev;
+}
+
+static struct udev_device *handle_scsi_fibre_channel(struct udev_device *parent, char **path)
+{
+ struct udev *udev = udev_device_get_udev(parent);
+ struct udev_device *targetdev;
+ struct udev_device *fcdev = NULL;
+ const char *port;
+ char *lun = NULL;
+
+ targetdev = udev_device_get_parent_with_subsystem_devtype(parent, "scsi", "scsi_target");
+ if (targetdev == NULL)
+ return NULL;
+
+ fcdev = udev_device_new_from_subsystem_sysname(udev, "fc_transport", udev_device_get_sysname(targetdev));
+ if (fcdev == NULL)
+ return NULL;
+ port = udev_device_get_sysattr_value(fcdev, "port_name");
+ if (port == NULL) {
+ parent = NULL;
+ goto out;
+ }
+
+ format_lun_number(parent, &lun);
+ path_prepend(path, "fc-%s-%s", port, lun);
+ if (lun)
+ free(lun);
+out:
+ udev_device_unref(fcdev);
+ return parent;
+}
+
+static struct udev_device *handle_scsi_sas(struct udev_device *parent, char **path)
+{
+ struct udev *udev = udev_device_get_udev(parent);
+ struct udev_device *targetdev;
+ struct udev_device *target_parent;
+ struct udev_device *sasdev;
+ const char *sas_address;
+ char *lun = NULL;
+
+ targetdev = udev_device_get_parent_with_subsystem_devtype(parent, "scsi", "scsi_target");
+ if (targetdev == NULL)
+ return NULL;
+
+ target_parent = udev_device_get_parent(targetdev);
+ if (target_parent == NULL)
+ return NULL;
+
+ sasdev = udev_device_new_from_subsystem_sysname(udev, "sas_device",
+ udev_device_get_sysname(target_parent));
+ if (sasdev == NULL)
+ return NULL;
+
+ sas_address = udev_device_get_sysattr_value(sasdev, "sas_address");
+ if (sas_address == NULL) {
+ parent = NULL;
+ goto out;
+ }
+
+ format_lun_number(parent, &lun);
+ path_prepend(path, "sas-%s-%s", sas_address, lun);
+ if (lun)
+ free(lun);
+out:
+ udev_device_unref(sasdev);
+ return parent;
+}
+
+static struct udev_device *handle_scsi_iscsi(struct udev_device *parent, char **path)
+{
+ struct udev *udev = udev_device_get_udev(parent);
+ struct udev_device *transportdev;
+ struct udev_device *sessiondev = NULL;
+ const char *target;
+ char *connname;
+ struct udev_device *conndev = NULL;
+ const char *addr;
+ const char *port;
+ char *lun = NULL;
+
+ /* find iscsi session */
+ transportdev = parent;
+ for (;;) {
+ transportdev = udev_device_get_parent(transportdev);
+ if (transportdev == NULL)
+ return NULL;
+ if (startswith(udev_device_get_sysname(transportdev), "session"))
+ break;
+ }
+
+ /* find iscsi session device */
+ sessiondev = udev_device_new_from_subsystem_sysname(udev, "iscsi_session", udev_device_get_sysname(transportdev));
+ if (sessiondev == NULL)
+ return NULL;
+ target = udev_device_get_sysattr_value(sessiondev, "targetname");
+ if (target == NULL) {
+ parent = NULL;
+ goto out;
+ }
+
+ if (asprintf(&connname, "connection%s:0", udev_device_get_sysnum(transportdev)) < 0) {
+ parent = NULL;
+ goto out;
+ }
+ conndev = udev_device_new_from_subsystem_sysname(udev, "iscsi_connection", connname);
+ free(connname);
+ if (conndev == NULL) {
+ parent = NULL;
+ goto out;
+ }
+ addr = udev_device_get_sysattr_value(conndev, "persistent_address");
+ port = udev_device_get_sysattr_value(conndev, "persistent_port");
+ if (addr == NULL || port == NULL) {
+ parent = NULL;
+ goto out;
+ }
+
+ format_lun_number(parent, &lun);
+ path_prepend(path, "ip-%s:%s-iscsi-%s-%s", addr, port, target, lun);
+ if (lun)
+ free(lun);
+out:
+ udev_device_unref(sessiondev);
+ udev_device_unref(conndev);
+ return parent;
+}
+
+static struct udev_device *handle_scsi_default(struct udev_device *parent, char **path)
+{
+ struct udev_device *hostdev;
+ int host, bus, target, lun;
+ const char *name;
+ char *base;
+ char *pos;
+ DIR *dir;
+ struct dirent *dent;
+ int basenum;
+
+ hostdev = udev_device_get_parent_with_subsystem_devtype(parent, "scsi", "scsi_host");
+ if (hostdev == NULL)
+ return NULL;
+
+ name = udev_device_get_sysname(parent);
+ if (sscanf(name, "%d:%d:%d:%d", &host, &bus, &target, &lun) != 4)
+ return NULL;
+
+ /*
+ * Rebase host offset to get the local relative number
+ *
+ * Note: This is by definition racy, unreliable and too simple.
+ * Please do not copy this model anywhere. It's just a left-over
+ * from the time we had no idea how things should look like in
+ * the end.
+ *
+ * Making assumptions about a global in-kernel counter and use
+ * that to calculate a local offset is a very broken concept. It
+ * can only work as long as things are in strict order.
+ *
+ * The kernel needs to export the instance/port number of a
+ * controller directly, without the need for rebase magic like
+ * this. Manual driver unbind/bind, parallel hotplug/unplug will
+ * get into the way of this "I hope it works" logic.
+ */
+ basenum = -1;
+ base = strdup(udev_device_get_syspath(hostdev));
+ if (base == NULL)
+ return NULL;
+ pos = strrchr(base, '/');
+ if (pos == NULL) {
+ parent = NULL;
+ goto out;
+ }
+ pos[0] = '\0';
+ dir = opendir(base);
+ if (dir == NULL) {
+ parent = NULL;
+ goto out;
+ }
+ for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
+ char *rest;
+ int i;
+
+ if (dent->d_name[0] == '.')
+ continue;
+ if (dent->d_type != DT_DIR && dent->d_type != DT_LNK)
+ continue;
+ if (!startswith(dent->d_name, "host"))
+ continue;
+ i = strtoul(&dent->d_name[4], &rest, 10);
+ if (rest[0] != '\0')
+ continue;
+ /*
+ * find the smallest number; the host really needs to export its
+ * own instance number per parent device; relying on the global host
+ * enumeration and plainly rebasing the numbers sounds unreliable
+ */
+ if (basenum == -1 || i < basenum)
+ basenum = i;
+ }
+ closedir(dir);
+ if (basenum == -1) {
+ parent = NULL;
+ goto out;
+ }
+ host -= basenum;
+
+ path_prepend(path, "scsi-%u:%u:%u:%u", host, bus, target, lun);
+out:
+ free(base);
+ return hostdev;
+}
+
+static struct udev_device *handle_scsi_hyperv(struct udev_device *parent, char **path) {
+ struct udev_device *hostdev;
+ struct udev_device *vmbusdev;
+ const char *guid_str;
+ char *lun = NULL;
+ char guid[38];
+ size_t i, k;
+
+ hostdev = udev_device_get_parent_with_subsystem_devtype(parent, "scsi", "scsi_host");
+ if (!hostdev)
+ return NULL;
+
+ vmbusdev = udev_device_get_parent(hostdev);
+ if (!vmbusdev)
+ return NULL;
+
+ guid_str = udev_device_get_sysattr_value(vmbusdev, "device_id");
+ if (!guid_str)
+ return NULL;
+
+ if (strlen(guid_str) < 37 || guid_str[0] != '{' || guid_str[36] != '}')
+ return NULL;
+
+ for (i = 1, k = 0; i < 36; i++) {
+ if (guid_str[i] == '-')
+ continue;
+ guid[k++] = guid_str[i];
+ }
+ guid[k] = '\0';
+
+ format_lun_number(parent, &lun);
+ path_prepend(path, "vmbus-%s-%s", guid, lun);
+ free(lun);
+ return parent;
+}
+
+static struct udev_device *handle_scsi(struct udev_device *parent, char **path)
+{
+ const char *devtype;
+ const char *name;
+ const char *id;
+
+ devtype = udev_device_get_devtype(parent);
+ if (devtype == NULL || !streq(devtype, "scsi_device"))
+ return parent;
+
+ /* firewire */
+ id = udev_device_get_sysattr_value(parent, "ieee1394_id");
+ if (id != NULL) {
+ parent = skip_subsystem(parent, "scsi");
+ path_prepend(path, "ieee1394-0x%s", id);
+ goto out;
+ }
+
+ /* scsi sysfs does not have a "subsystem" for the transport */
+ name = udev_device_get_syspath(parent);
+
+ if (strstr(name, "/rport-") != NULL) {
+ parent = handle_scsi_fibre_channel(parent, path);
+ goto out;
+ }
+
+ if (strstr(name, "/end_device-") != NULL) {
+ parent = handle_scsi_sas(parent, path);
+ goto out;
+ }
+
+ if (strstr(name, "/session") != NULL) {
+ parent = handle_scsi_iscsi(parent, path);
+ goto out;
+ }
+
+ /*
+ * We do not support the ATA transport class, it uses global counters
+ * to name the ata devices which numbers spread across multiple
+ * controllers.
+ *
+ * The real link numbers are not exported. Also, possible chains of ports
+ * behind port multipliers cannot be composed that way.
+ *
+ * Until all that is solved at the kernel level, there are no by-path/
+ * links for ATA devices.
+ */
+ if (strstr(name, "/ata") != NULL) {
+ parent = NULL;
+ goto out;
+ }
+
+ if (strstr(name, "/vmbus_") != NULL) {
+ parent = handle_scsi_hyperv(parent, path);
+ goto out;
+ }
+
+ parent = handle_scsi_default(parent, path);
+out:
+ return parent;
+}
+
+static struct udev_device *handle_cciss(struct udev_device *parent, char **path)
+{
+ const char *str;
+ unsigned int controller, disk;
+
+ str = udev_device_get_sysname(parent);
+ if (sscanf(str, "c%ud%u%*s", &controller, &disk) != 2)
+ return NULL;
+
+ path_prepend(path, "cciss-disk%u", disk);
+ parent = skip_subsystem(parent, "cciss");
+ return parent;
+}
+
+static void handle_scsi_tape(struct udev_device *dev, char **path)
+{
+ const char *name;
+
+ /* must be the last device in the syspath */
+ if (*path != NULL)
+ return;
+
+ name = udev_device_get_sysname(dev);
+ if (startswith(name, "nst") && strchr("lma", name[3]) != NULL)
+ path_prepend(path, "nst%c", name[3]);
+ else if (startswith(name, "st") && strchr("lma", name[2]) != NULL)
+ path_prepend(path, "st%c", name[2]);
+}
+
+static struct udev_device *handle_usb(struct udev_device *parent, char **path)
+{
+ const char *devtype;
+ const char *str;
+ const char *port;
+
+ devtype = udev_device_get_devtype(parent);
+ if (devtype == NULL)
+ return parent;
+ if (!streq(devtype, "usb_interface") && !streq(devtype, "usb_device"))
+ return parent;
+
+ str = udev_device_get_sysname(parent);
+ port = strchr(str, '-');
+ if (port == NULL)
+ return parent;
+ port++;
+
+ parent = skip_subsystem(parent, "usb");
+ path_prepend(path, "usb-0:%s", port);
+ return parent;
+}
+
+static struct udev_device *handle_ccw(struct udev_device *parent, struct udev_device *dev, char **path)
+{
+ struct udev_device *scsi_dev;
+
+ scsi_dev = udev_device_get_parent_with_subsystem_devtype(dev, "scsi", "scsi_device");
+ if (scsi_dev != NULL) {
+ const char *wwpn;
+ const char *lun;
+ const char *hba_id;
+
+ hba_id = udev_device_get_sysattr_value(scsi_dev, "hba_id");
+ wwpn = udev_device_get_sysattr_value(scsi_dev, "wwpn");
+ lun = udev_device_get_sysattr_value(scsi_dev, "fcp_lun");
+ if (hba_id != NULL && lun != NULL && wwpn != NULL) {
+ path_prepend(path, "ccw-%s-zfcp-%s:%s", hba_id, wwpn, lun);
+ goto out;
+ }
+ }
+
+ path_prepend(path, "ccw-%s", udev_device_get_sysname(parent));
+out:
+ parent = skip_subsystem(parent, "ccw");
+ return parent;
+}
+
+static int builtin_path_id(struct udev_device *dev, int argc, char *argv[], bool test)
+{
+ struct udev_device *parent;
+ char *path = NULL;
+ bool some_transport = false;
+
+ /* S390 ccw bus */
+ parent = udev_device_get_parent_with_subsystem_devtype(dev, "ccw", NULL);
+ if (parent != NULL) {
+ handle_ccw(parent, dev, &path);
+ goto out;
+ }
+
+ /* walk up the chain of devices and compose path */
+ parent = dev;
+ while (parent != NULL) {
+ const char *subsys;
+
+ subsys = udev_device_get_subsystem(parent);
+ if (subsys == NULL) {
+ ;
+ } else if (streq(subsys, "scsi_tape")) {
+ handle_scsi_tape(parent, &path);
+ } else if (streq(subsys, "scsi")) {
+ parent = handle_scsi(parent, &path);
+ some_transport = true;
+ } else if (streq(subsys, "cciss")) {
+ parent = handle_cciss(parent, &path);
+ some_transport = true;
+ } else if (streq(subsys, "usb")) {
+ parent = handle_usb(parent, &path);
+ some_transport = true;
+ } else if (streq(subsys, "serio")) {
+ path_prepend(&path, "serio-%s", udev_device_get_sysnum(parent));
+ parent = skip_subsystem(parent, "serio");
+ } else if (streq(subsys, "pci")) {
+ path_prepend(&path, "pci-%s", udev_device_get_sysname(parent));
+ parent = skip_subsystem(parent, "pci");
+ } else if (streq(subsys, "platform")) {
+ path_prepend(&path, "platform-%s", udev_device_get_sysname(parent));
+ parent = skip_subsystem(parent, "platform");
+ some_transport = true;
+ } else if (streq(subsys, "acpi")) {
+ path_prepend(&path, "acpi-%s", udev_device_get_sysname(parent));
+ parent = skip_subsystem(parent, "acpi");
+ } else if (streq(subsys, "xen")) {
+ path_prepend(&path, "xen-%s", udev_device_get_sysname(parent));
+ parent = skip_subsystem(parent, "xen");
+ } else if (streq(subsys, "virtio")) {
+ path_prepend(&path, "virtio-pci-%s", udev_device_get_sysname(parent));
+ parent = skip_subsystem(parent, "virtio");
+ } else if (streq(subsys, "scm")) {
+ path_prepend(&path, "scm-%s", udev_device_get_sysname(parent));
+ parent = skip_subsystem(parent, "scm");
+ }
+
+ parent = udev_device_get_parent(parent);
+ }
+
+ /*
+ * Do not return a single-parent-device-only for block
+ * devices, they might have entire buses behind it which
+ * do not get unique IDs only by using the parent device.
+ */
+ if (!some_transport && streq(udev_device_get_subsystem(dev), "block")) {
+ free(path);
+ path = NULL;
+ }
+
+out:
+ if (path != NULL) {
+ char tag[UTIL_NAME_SIZE];
+ size_t i;
+ const char *p;
+
+ /* compose valid udev tag name */
+ for (p = path, i = 0; *p; p++) {
+ if ((*p >= '0' && *p <= '9') ||
+ (*p >= 'A' && *p <= 'Z') ||
+ (*p >= 'a' && *p <= 'z') ||
+ *p == '-') {
+ tag[i++] = *p;
+ continue;
+ }
+
+ /* skip all leading '_' */
+ if (i == 0)
+ continue;
+
+ /* avoid second '_' */
+ if (tag[i-1] == '_')
+ continue;
+
+ tag[i++] = '_';
+ }
+ /* strip trailing '_' */
+ while (i > 0 && tag[i-1] == '_')
+ i--;
+ tag[i] = '\0';
+
+ udev_builtin_add_property(dev, test, "ID_PATH", path);
+ udev_builtin_add_property(dev, test, "ID_PATH_TAG", tag);
+ free(path);
+ return EXIT_SUCCESS;
+ }
+ return EXIT_FAILURE;
+}
+
+const struct udev_builtin udev_builtin_path_id = {
+ .name = "path_id",
+ .cmd = builtin_path_id,
+ .help = "compose persistent device path",
+ .run_once = true,
+};
diff --git a/src/udev/udev-builtin-uaccess.c b/src/udev/udev-builtin-uaccess.c
new file mode 100644
index 0000000000..354ee08f28
--- /dev/null
+++ b/src/udev/udev-builtin-uaccess.c
@@ -0,0 +1,98 @@
+/*
+ * manage device node user ACL
+ *
+ * Copyright 2010-2012 Kay Sievers <kay@vrfy.org>
+ * Copyright 2010 Lennart Poettering
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <unistd.h>
+#include <string.h>
+#include <ctype.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <dirent.h>
+#include <getopt.h>
+
+#include <systemd/sd-login.h>
+#include "logind-acl.h"
+#include "udev.h"
+#include "util.h"
+
+static int builtin_uaccess(struct udev_device *dev, int argc, char *argv[], bool test)
+{
+ int r;
+ const char *path = NULL, *seat;
+ bool changed_acl = false;
+ uid_t uid;
+
+ log_set_target(LOG_TARGET_AUTO);
+ log_parse_environment();
+ log_open();
+
+ umask(0022);
+
+ /* don't muck around with ACLs when the system is not running systemd */
+ if (!logind_running())
+ return 0;
+
+ path = udev_device_get_devnode(dev);
+ seat = udev_device_get_property_value(dev, "ID_SEAT");
+ if (!seat)
+ seat = "seat0";
+
+ r = sd_seat_get_active(seat, NULL, &uid);
+ if (r == -ENOENT) {
+ /* No active session on this seat */
+ r = 0;
+ goto finish;
+ } else if (r < 0) {
+ log_error("Failed to determine active user on seat %s.", seat);
+ goto finish;
+ }
+
+ r = devnode_acl(path, true, false, 0, true, uid);
+ if (r < 0) {
+ log_error("Failed to apply ACL on %s: %s", path, strerror(-r));
+ goto finish;
+ }
+
+ changed_acl = true;
+ r = 0;
+
+finish:
+ if (path && !changed_acl) {
+ int k;
+
+ /* Better be safe than sorry and reset ACL */
+ k = devnode_acl(path, true, false, 0, false, 0);
+ if (k < 0) {
+ log_error("Failed to apply ACL on %s: %s", path, strerror(-k));
+ if (r >= 0)
+ r = k;
+ }
+ }
+
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+}
+
+const struct udev_builtin udev_builtin_uaccess = {
+ .name = "uaccess",
+ .cmd = builtin_uaccess,
+ .help = "manage device node user ACL",
+};
diff --git a/src/udev/udev-builtin-usb_id.c b/src/udev/udev-builtin-usb_id.c
new file mode 100644
index 0000000000..e3bbd05e4b
--- /dev/null
+++ b/src/udev/udev-builtin-usb_id.c
@@ -0,0 +1,482 @@
+/*
+ * USB device properties and persistent device path
+ *
+ * Copyright (c) 2005 SUSE Linux Products GmbH, Germany
+ * Author: Hannes Reinecke <hare@suse.de>
+ *
+ * Copyright (C) 2005-2011 Kay Sievers <kay@vrfy.org>
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <unistd.h>
+#include <string.h>
+#include <ctype.h>
+#include <fcntl.h>
+#include <errno.h>
+
+#include "udev.h"
+
+static void set_usb_iftype(char *to, int if_class_num, size_t len)
+{
+ const char *type = "generic";
+
+ switch (if_class_num) {
+ case 1:
+ type = "audio";
+ break;
+ case 2: /* CDC-Control */
+ break;
+ case 3:
+ type = "hid";
+ break;
+ case 5: /* Physical */
+ break;
+ case 6:
+ type = "media";
+ break;
+ case 7:
+ type = "printer";
+ break;
+ case 8:
+ type = "storage";
+ break;
+ case 9:
+ type = "hub";
+ break;
+ case 0x0a: /* CDC-Data */
+ break;
+ case 0x0b: /* Chip/Smart Card */
+ break;
+ case 0x0d: /* Content Security */
+ break;
+ case 0x0e:
+ type = "video";
+ break;
+ case 0xdc: /* Diagnostic Device */
+ break;
+ case 0xe0: /* Wireless Controller */
+ break;
+ case 0xfe: /* Application-specific */
+ break;
+ case 0xff: /* Vendor-specific */
+ break;
+ default:
+ break;
+ }
+ strncpy(to, type, len);
+ to[len-1] = '\0';
+}
+
+static int set_usb_mass_storage_ifsubtype(char *to, const char *from, size_t len)
+{
+ int type_num = 0;
+ char *eptr;
+ const char *type = "generic";
+
+ type_num = strtoul(from, &eptr, 0);
+ if (eptr != from) {
+ switch (type_num) {
+ case 2:
+ type = "atapi";
+ break;
+ case 3:
+ type = "tape";
+ break;
+ case 4: /* UFI */
+ case 5: /* SFF-8070i */
+ type = "floppy";
+ break;
+ case 1: /* RBC devices */
+ type = "rbc";
+ break;
+ case 6: /* Transparent SPC-2 devices */
+ type = "scsi";
+ break;
+ default:
+ break;
+ }
+ }
+ strscpy(to, len, type);
+ return type_num;
+}
+
+static void set_scsi_type(char *to, const char *from, size_t len)
+{
+ int type_num;
+ char *eptr;
+ const char *type = "generic";
+
+ type_num = strtoul(from, &eptr, 0);
+ if (eptr != from) {
+ switch (type_num) {
+ case 0:
+ case 0xe:
+ type = "disk";
+ break;
+ case 1:
+ type = "tape";
+ break;
+ case 4:
+ case 7:
+ case 0xf:
+ type = "optical";
+ break;
+ case 5:
+ type = "cd";
+ break;
+ default:
+ break;
+ }
+ }
+ strscpy(to, len, type);
+}
+
+#define USB_DT_DEVICE 0x01
+#define USB_DT_INTERFACE 0x04
+
+static int dev_if_packed_info(struct udev_device *dev, char *ifs_str, size_t len)
+{
+ _cleanup_free_ char *filename = NULL;
+ _cleanup_close_ int fd = -1;
+ ssize_t size;
+ unsigned char buf[18 + 65535];
+ int pos = 0;
+ unsigned strpos = 0;
+ struct usb_interface_descriptor {
+ u_int8_t bLength;
+ u_int8_t bDescriptorType;
+ u_int8_t bInterfaceNumber;
+ u_int8_t bAlternateSetting;
+ u_int8_t bNumEndpoints;
+ u_int8_t bInterfaceClass;
+ u_int8_t bInterfaceSubClass;
+ u_int8_t bInterfaceProtocol;
+ u_int8_t iInterface;
+ } __attribute__((packed));
+
+ if (asprintf(&filename, "%s/descriptors", udev_device_get_syspath(dev)) < 0)
+ return log_oom();
+
+ fd = open(filename, O_RDONLY|O_CLOEXEC);
+ if (fd < 0) {
+ fprintf(stderr, "error opening USB device 'descriptors' file\n");
+ return -errno;
+ }
+
+ size = read(fd, buf, sizeof(buf));
+ if (size < 18 || size == sizeof(buf))
+ return -EIO;
+
+ ifs_str[0] = '\0';
+ while (pos < size && strpos+7 < len-2) {
+ struct usb_interface_descriptor *desc;
+ char if_str[8];
+
+ desc = (struct usb_interface_descriptor *) &buf[pos];
+ if (desc->bLength < 3)
+ break;
+ pos += desc->bLength;
+
+ if (desc->bDescriptorType != USB_DT_INTERFACE)
+ continue;
+
+ if (snprintf(if_str, 8, ":%02x%02x%02x",
+ desc->bInterfaceClass,
+ desc->bInterfaceSubClass,
+ desc->bInterfaceProtocol) != 7)
+ continue;
+
+ if (strstr(ifs_str, if_str) != NULL)
+ continue;
+
+ memcpy(&ifs_str[strpos], if_str, 8),
+ strpos += 7;
+ }
+
+ if (strpos > 0) {
+ ifs_str[strpos++] = ':';
+ ifs_str[strpos++] = '\0';
+ }
+
+ return 0;
+}
+
+/*
+ * A unique USB identification is generated like this:
+ *
+ * 1.) Get the USB device type from InterfaceClass and InterfaceSubClass
+ * 2.) If the device type is 'Mass-Storage/SPC-2' or 'Mass-Storage/RBC'
+ * use the SCSI vendor and model as USB-Vendor and USB-model.
+ * 3.) Otherwise use the USB manufacturer and product as
+ * USB-Vendor and USB-model. Any non-printable characters
+ * in those strings will be skipped; a slash '/' will be converted
+ * into a full stop '.'.
+ * 4.) If that fails, too, we will use idVendor and idProduct
+ * as USB-Vendor and USB-model.
+ * 5.) The USB identification is the USB-vendor and USB-model
+ * string concatenated with an underscore '_'.
+ * 6.) If the device supplies a serial number, this number
+ * is concatenated with the identification with an underscore '_'.
+ */
+static int builtin_usb_id(struct udev_device *dev, int argc, char *argv[], bool test)
+{
+ char vendor_str[64];
+ char vendor_str_enc[256];
+ const char *vendor_id;
+ char model_str[64];
+ char model_str_enc[256];
+ const char *product_id;
+ char serial_str[UTIL_NAME_SIZE];
+ char packed_if_str[UTIL_NAME_SIZE];
+ char revision_str[64];
+ char type_str[64];
+ char instance_str[64];
+ const char *ifnum = NULL;
+ const char *driver = NULL;
+ char serial[256];
+
+ struct udev_device *dev_interface = NULL;
+ struct udev_device *dev_usb = NULL;
+ const char *if_class, *if_subclass;
+ int if_class_num;
+ int protocol = 0;
+ size_t l;
+ char *s;
+
+ vendor_str[0] = '\0';
+ model_str[0] = '\0';
+ serial_str[0] = '\0';
+ packed_if_str[0] = '\0';
+ revision_str[0] = '\0';
+ type_str[0] = '\0';
+ instance_str[0] = '\0';
+
+ /* shortcut, if we are called directly for a "usb_device" type */
+ if (udev_device_get_devtype(dev) != NULL && streq(udev_device_get_devtype(dev), "usb_device")) {
+ dev_if_packed_info(dev, packed_if_str, sizeof(packed_if_str));
+ dev_usb = dev;
+ goto fallback;
+ }
+
+ /* usb interface directory */
+ dev_interface = udev_device_get_parent_with_subsystem_devtype(dev, "usb", "usb_interface");
+ if (dev_interface == NULL) {
+ log_debug("unable to access usb_interface device of '%s'\n",
+ udev_device_get_syspath(dev));
+ return EXIT_FAILURE;
+ }
+
+ ifnum = udev_device_get_sysattr_value(dev_interface, "bInterfaceNumber");
+ driver = udev_device_get_sysattr_value(dev_interface, "driver");
+
+ if_class = udev_device_get_sysattr_value(dev_interface, "bInterfaceClass");
+ if (!if_class) {
+ log_debug("%s: cannot get bInterfaceClass attribute\n",
+ udev_device_get_sysname(dev));
+ return EXIT_FAILURE;
+ }
+
+ if_class_num = strtoul(if_class, NULL, 16);
+ if (if_class_num == 8) {
+ /* mass storage */
+ if_subclass = udev_device_get_sysattr_value(dev_interface, "bInterfaceSubClass");
+ if (if_subclass != NULL)
+ protocol = set_usb_mass_storage_ifsubtype(type_str, if_subclass, sizeof(type_str)-1);
+ } else {
+ set_usb_iftype(type_str, if_class_num, sizeof(type_str)-1);
+ }
+
+ log_debug("%s: if_class %d protocol %d\n",
+ udev_device_get_syspath(dev_interface), if_class_num, protocol);
+
+ /* usb device directory */
+ dev_usb = udev_device_get_parent_with_subsystem_devtype(dev_interface, "usb", "usb_device");
+ if (!dev_usb) {
+ log_debug("unable to find parent 'usb' device of '%s'\n",
+ udev_device_get_syspath(dev));
+ return EXIT_FAILURE;
+ }
+
+ /* all interfaces of the device in a single string */
+ dev_if_packed_info(dev_usb, packed_if_str, sizeof(packed_if_str));
+
+ /* mass storage : SCSI or ATAPI */
+ if ((protocol == 6 || protocol == 2)) {
+ struct udev_device *dev_scsi;
+ const char *scsi_model, *scsi_vendor, *scsi_type, *scsi_rev;
+ int host, bus, target, lun;
+
+ /* get scsi device */
+ dev_scsi = udev_device_get_parent_with_subsystem_devtype(dev, "scsi", "scsi_device");
+ if (dev_scsi == NULL) {
+ log_debug("unable to find parent 'scsi' device of '%s'\n",
+ udev_device_get_syspath(dev));
+ goto fallback;
+ }
+ if (sscanf(udev_device_get_sysname(dev_scsi), "%d:%d:%d:%d", &host, &bus, &target, &lun) != 4) {
+ log_debug("invalid scsi device '%s'\n", udev_device_get_sysname(dev_scsi));
+ goto fallback;
+ }
+
+ /* Generic SPC-2 device */
+ scsi_vendor = udev_device_get_sysattr_value(dev_scsi, "vendor");
+ if (!scsi_vendor) {
+ log_debug("%s: cannot get SCSI vendor attribute\n",
+ udev_device_get_sysname(dev_scsi));
+ goto fallback;
+ }
+ udev_util_encode_string(scsi_vendor, vendor_str_enc, sizeof(vendor_str_enc));
+ util_replace_whitespace(scsi_vendor, vendor_str, sizeof(vendor_str)-1);
+ util_replace_chars(vendor_str, NULL);
+
+ scsi_model = udev_device_get_sysattr_value(dev_scsi, "model");
+ if (!scsi_model) {
+ log_debug("%s: cannot get SCSI model attribute\n",
+ udev_device_get_sysname(dev_scsi));
+ goto fallback;
+ }
+ udev_util_encode_string(scsi_model, model_str_enc, sizeof(model_str_enc));
+ util_replace_whitespace(scsi_model, model_str, sizeof(model_str)-1);
+ util_replace_chars(model_str, NULL);
+
+ scsi_type = udev_device_get_sysattr_value(dev_scsi, "type");
+ if (!scsi_type) {
+ log_debug("%s: cannot get SCSI type attribute\n",
+ udev_device_get_sysname(dev_scsi));
+ goto fallback;
+ }
+ set_scsi_type(type_str, scsi_type, sizeof(type_str)-1);
+
+ scsi_rev = udev_device_get_sysattr_value(dev_scsi, "rev");
+ if (!scsi_rev) {
+ log_debug("%s: cannot get SCSI revision attribute\n",
+ udev_device_get_sysname(dev_scsi));
+ goto fallback;
+ }
+ util_replace_whitespace(scsi_rev, revision_str, sizeof(revision_str)-1);
+ util_replace_chars(revision_str, NULL);
+
+ /*
+ * some broken devices have the same identifiers
+ * for all luns, export the target:lun number
+ */
+ sprintf(instance_str, "%d:%d", target, lun);
+ }
+
+fallback:
+ vendor_id = udev_device_get_sysattr_value(dev_usb, "idVendor");
+ product_id = udev_device_get_sysattr_value(dev_usb, "idProduct");
+
+ /* fallback to USB vendor & device */
+ if (vendor_str[0] == '\0') {
+ const char *usb_vendor = NULL;
+
+ usb_vendor = udev_device_get_sysattr_value(dev_usb, "manufacturer");
+ if (!usb_vendor)
+ usb_vendor = vendor_id;
+ if (!usb_vendor) {
+ log_debug("No USB vendor information available\n");
+ return EXIT_FAILURE;
+ }
+ udev_util_encode_string(usb_vendor, vendor_str_enc, sizeof(vendor_str_enc));
+ util_replace_whitespace(usb_vendor, vendor_str, sizeof(vendor_str)-1);
+ util_replace_chars(vendor_str, NULL);
+ }
+
+ if (model_str[0] == '\0') {
+ const char *usb_model = NULL;
+
+ usb_model = udev_device_get_sysattr_value(dev_usb, "product");
+ if (!usb_model)
+ usb_model = product_id;
+ if (!usb_model)
+ return EXIT_FAILURE;
+ udev_util_encode_string(usb_model, model_str_enc, sizeof(model_str_enc));
+ util_replace_whitespace(usb_model, model_str, sizeof(model_str)-1);
+ util_replace_chars(model_str, NULL);
+ }
+
+ if (revision_str[0] == '\0') {
+ const char *usb_rev;
+
+ usb_rev = udev_device_get_sysattr_value(dev_usb, "bcdDevice");
+ if (usb_rev) {
+ util_replace_whitespace(usb_rev, revision_str, sizeof(revision_str)-1);
+ util_replace_chars(revision_str, NULL);
+ }
+ }
+
+ if (serial_str[0] == '\0') {
+ const char *usb_serial;
+
+ usb_serial = udev_device_get_sysattr_value(dev_usb, "serial");
+ if (usb_serial) {
+ const unsigned char *p;
+
+ /* http://msdn.microsoft.com/en-us/library/windows/hardware/gg487321.aspx */
+ for (p = (unsigned char *)usb_serial; *p != '\0'; p++)
+ if (*p < 0x20 || *p > 0x7f || *p == ',') {
+ usb_serial = NULL;
+ break;
+ }
+ }
+
+ if (usb_serial) {
+ util_replace_whitespace(usb_serial, serial_str, sizeof(serial_str)-1);
+ util_replace_chars(serial_str, NULL);
+ }
+ }
+
+ s = serial;
+ l = strpcpyl(&s, sizeof(serial), vendor_str, "_", model_str, NULL);
+ if (serial_str[0] != '\0')
+ l = strpcpyl(&s, l, "_", serial_str, NULL);
+
+ if (instance_str[0] != '\0')
+ strpcpyl(&s, l, "-", instance_str, NULL);
+
+ udev_builtin_add_property(dev, test, "ID_VENDOR", vendor_str);
+ udev_builtin_add_property(dev, test, "ID_VENDOR_ENC", vendor_str_enc);
+ udev_builtin_add_property(dev, test, "ID_VENDOR_ID", vendor_id);
+ udev_builtin_add_property(dev, test, "ID_MODEL", model_str);
+ udev_builtin_add_property(dev, test, "ID_MODEL_ENC", model_str_enc);
+ udev_builtin_add_property(dev, test, "ID_MODEL_ID", product_id);
+ udev_builtin_add_property(dev, test, "ID_REVISION", revision_str);
+ udev_builtin_add_property(dev, test, "ID_SERIAL", serial);
+ if (serial_str[0] != '\0')
+ udev_builtin_add_property(dev, test, "ID_SERIAL_SHORT", serial_str);
+ if (type_str[0] != '\0')
+ udev_builtin_add_property(dev, test, "ID_TYPE", type_str);
+ if (instance_str[0] != '\0')
+ udev_builtin_add_property(dev, test, "ID_INSTANCE", instance_str);
+ udev_builtin_add_property(dev, test, "ID_BUS", "usb");
+ if (packed_if_str[0] != '\0')
+ udev_builtin_add_property(dev, test, "ID_USB_INTERFACES", packed_if_str);
+ if (ifnum != NULL)
+ udev_builtin_add_property(dev, test, "ID_USB_INTERFACE_NUM", ifnum);
+ if (driver != NULL)
+ udev_builtin_add_property(dev, test, "ID_USB_DRIVER", driver);
+ return EXIT_SUCCESS;
+}
+
+const struct udev_builtin udev_builtin_usb_id = {
+ .name = "usb_id",
+ .cmd = builtin_usb_id,
+ .help = "usb device properties",
+ .run_once = true,
+};
diff --git a/src/udev/udev-builtin.c b/src/udev/udev-builtin.c
new file mode 100644
index 0000000000..c7d431988d
--- /dev/null
+++ b/src/udev/udev-builtin.c
@@ -0,0 +1,150 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2007-2012 Kay Sievers <kay@vrfy.org>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <unistd.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <string.h>
+#include <errno.h>
+#include <getopt.h>
+
+#include "udev.h"
+
+static bool initialized;
+
+static const struct udev_builtin *builtins[] = {
+#ifdef HAVE_BLKID
+ [UDEV_BUILTIN_BLKID] = &udev_builtin_blkid,
+#endif
+ [UDEV_BUILTIN_BTRFS] = &udev_builtin_btrfs,
+#ifdef HAVE_FIRMWARE
+ [UDEV_BUILTIN_FIRMWARE] = &udev_builtin_firmware,
+#endif
+ [UDEV_BUILTIN_HWDB] = &udev_builtin_hwdb,
+ [UDEV_BUILTIN_INPUT_ID] = &udev_builtin_input_id,
+#ifdef HAVE_KMOD
+ [UDEV_BUILTIN_KMOD] = &udev_builtin_kmod,
+#endif
+ [UDEV_BUILTIN_NET_ID] = &udev_builtin_net_id,
+ [UDEV_BUILTIN_PATH_ID] = &udev_builtin_path_id,
+ [UDEV_BUILTIN_USB_ID] = &udev_builtin_usb_id,
+#ifdef HAVE_ACL
+ [UDEV_BUILTIN_UACCESS] = &udev_builtin_uaccess,
+#endif
+};
+
+void udev_builtin_init(struct udev *udev)
+{
+ unsigned int i;
+
+ if (initialized)
+ return;
+
+ for (i = 0; i < ELEMENTSOF(builtins); i++)
+ if (builtins[i]->init)
+ builtins[i]->init(udev);
+
+ initialized = true;
+}
+
+void udev_builtin_exit(struct udev *udev)
+{
+ unsigned int i;
+
+ if (!initialized)
+ return;
+
+ for (i = 0; i < ELEMENTSOF(builtins); i++)
+ if (builtins[i]->exit)
+ builtins[i]->exit(udev);
+
+ initialized = false;
+}
+
+bool udev_builtin_validate(struct udev *udev)
+{
+ unsigned int i;
+
+ for (i = 0; i < ELEMENTSOF(builtins); i++)
+ if (builtins[i]->validate && builtins[i]->validate(udev))
+ return true;
+ return false;
+}
+
+void udev_builtin_list(struct udev *udev)
+{
+ unsigned int i;
+
+ for (i = 0; i < ELEMENTSOF(builtins); i++)
+ fprintf(stderr, " %-12s %s\n", builtins[i]->name, builtins[i]->help);
+}
+
+const char *udev_builtin_name(enum udev_builtin_cmd cmd)
+{
+ return builtins[cmd]->name;
+}
+
+bool udev_builtin_run_once(enum udev_builtin_cmd cmd)
+{
+ return builtins[cmd]->run_once;
+}
+
+enum udev_builtin_cmd udev_builtin_lookup(const char *command)
+{
+ char name[UTIL_PATH_SIZE];
+ enum udev_builtin_cmd i;
+ char *pos;
+
+ strscpy(name, sizeof(name), command);
+ pos = strchr(name, ' ');
+ if (pos)
+ pos[0] = '\0';
+ for (i = 0; i < ELEMENTSOF(builtins); i++)
+ if (streq(builtins[i]->name, name))
+ return i;
+ return UDEV_BUILTIN_MAX;
+}
+
+int udev_builtin_run(struct udev_device *dev, enum udev_builtin_cmd cmd, const char *command, bool test)
+{
+ char arg[UTIL_PATH_SIZE];
+ int argc;
+ char *argv[128];
+
+ /* we need '0' here to reset the internal state */
+ optind = 0;
+ strscpy(arg, sizeof(arg), command);
+ udev_build_argv(udev_device_get_udev(dev), arg, &argc, argv);
+ return builtins[cmd]->cmd(dev, argc, argv, test);
+}
+
+int udev_builtin_add_property(struct udev_device *dev, bool test, const char *key, const char *val)
+{
+ struct udev_list_entry *entry;
+
+ entry = udev_device_add_property(dev, key, val);
+ /* store in db, skip private keys */
+ if (key[0] != '.')
+ udev_list_entry_set_num(entry, true);
+
+ if (test)
+ printf("%s=%s\n", key, val);
+ return 0;
+}
diff --git a/src/udev/udev-ctrl.c b/src/udev/udev-ctrl.c
new file mode 100644
index 0000000000..e60da906c5
--- /dev/null
+++ b/src/udev/udev-ctrl.c
@@ -0,0 +1,492 @@
+/*
+ * libudev - interface to udev device information
+ *
+ * Copyright (C) 2008 Kay Sievers <kay@vrfy.org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/poll.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+
+#include "udev.h"
+
+/* wire protocol magic must match */
+#define UDEV_CTRL_MAGIC 0xdead1dea
+
+enum udev_ctrl_msg_type {
+ UDEV_CTRL_UNKNOWN,
+ UDEV_CTRL_SET_LOG_LEVEL,
+ UDEV_CTRL_STOP_EXEC_QUEUE,
+ UDEV_CTRL_START_EXEC_QUEUE,
+ UDEV_CTRL_RELOAD,
+ UDEV_CTRL_SET_ENV,
+ UDEV_CTRL_SET_CHILDREN_MAX,
+ UDEV_CTRL_PING,
+ UDEV_CTRL_EXIT,
+};
+
+struct udev_ctrl_msg_wire {
+ char version[16];
+ unsigned int magic;
+ enum udev_ctrl_msg_type type;
+ union {
+ int intval;
+ char buf[256];
+ };
+};
+
+struct udev_ctrl_msg {
+ int refcount;
+ struct udev_ctrl_connection *conn;
+ struct udev_ctrl_msg_wire ctrl_msg_wire;
+};
+
+struct udev_ctrl {
+ int refcount;
+ struct udev *udev;
+ int sock;
+ struct sockaddr_un saddr;
+ socklen_t addrlen;
+ bool bound;
+ bool cleanup_socket;
+ bool connected;
+};
+
+struct udev_ctrl_connection {
+ int refcount;
+ struct udev_ctrl *uctrl;
+ int sock;
+};
+
+struct udev_ctrl *udev_ctrl_new_from_fd(struct udev *udev, int fd)
+{
+ struct udev_ctrl *uctrl;
+ const int on = 1;
+
+ uctrl = calloc(1, sizeof(struct udev_ctrl));
+ if (uctrl == NULL)
+ return NULL;
+ uctrl->refcount = 1;
+ uctrl->udev = udev;
+
+ if (fd < 0) {
+ uctrl->sock = socket(AF_LOCAL, SOCK_SEQPACKET|SOCK_NONBLOCK|SOCK_CLOEXEC, 0);
+ if (uctrl->sock < 0) {
+ log_error("error getting socket: %m\n");
+ udev_ctrl_unref(uctrl);
+ return NULL;
+ }
+ } else {
+ uctrl->bound = true;
+ uctrl->sock = fd;
+ }
+ setsockopt(uctrl->sock, SOL_SOCKET, SO_PASSCRED, &on, sizeof(on));
+
+ uctrl->saddr.sun_family = AF_LOCAL;
+ strscpy(uctrl->saddr.sun_path, sizeof(uctrl->saddr.sun_path), "/run/udev/control");
+ uctrl->addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(uctrl->saddr.sun_path);
+ return uctrl;
+}
+
+struct udev_ctrl *udev_ctrl_new(struct udev *udev)
+{
+ return udev_ctrl_new_from_fd(udev, -1);
+}
+
+int udev_ctrl_enable_receiving(struct udev_ctrl *uctrl)
+{
+ int err;
+
+ if (!uctrl->bound) {
+ err = bind(uctrl->sock, (struct sockaddr *)&uctrl->saddr, uctrl->addrlen);
+ if (err < 0 && errno == EADDRINUSE) {
+ unlink(uctrl->saddr.sun_path);
+ err = bind(uctrl->sock, (struct sockaddr *)&uctrl->saddr, uctrl->addrlen);
+ }
+
+ if (err < 0) {
+ err = -errno;
+ log_error("bind failed: %m\n");
+ return err;
+ }
+
+ err = listen(uctrl->sock, 0);
+ if (err < 0) {
+ err = -errno;
+ log_error("listen failed: %m\n");
+ return err;
+ }
+
+ uctrl->bound = true;
+ uctrl->cleanup_socket = true;
+ }
+ return 0;
+}
+
+struct udev *udev_ctrl_get_udev(struct udev_ctrl *uctrl)
+{
+ return uctrl->udev;
+}
+
+struct udev_ctrl *udev_ctrl_ref(struct udev_ctrl *uctrl)
+{
+ if (uctrl == NULL)
+ return NULL;
+ uctrl->refcount++;
+ return uctrl;
+}
+
+struct udev_ctrl *udev_ctrl_unref(struct udev_ctrl *uctrl)
+{
+ if (uctrl == NULL)
+ return NULL;
+ uctrl->refcount--;
+ if (uctrl->refcount > 0)
+ return uctrl;
+ if (uctrl->sock >= 0)
+ close(uctrl->sock);
+ free(uctrl);
+ return NULL;
+}
+
+int udev_ctrl_cleanup(struct udev_ctrl *uctrl)
+{
+ if (uctrl == NULL)
+ return 0;
+ if (uctrl->cleanup_socket)
+ unlink(uctrl->saddr.sun_path);
+ return 0;
+}
+
+int udev_ctrl_get_fd(struct udev_ctrl *uctrl)
+{
+ if (uctrl == NULL)
+ return -EINVAL;
+ return uctrl->sock;
+}
+
+struct udev_ctrl_connection *udev_ctrl_get_connection(struct udev_ctrl *uctrl)
+{
+ struct udev_ctrl_connection *conn;
+ struct ucred ucred;
+ socklen_t slen;
+ const int on = 1;
+
+ conn = calloc(1, sizeof(struct udev_ctrl_connection));
+ if (conn == NULL)
+ return NULL;
+ conn->refcount = 1;
+ conn->uctrl = uctrl;
+
+ conn->sock = accept4(uctrl->sock, NULL, NULL, SOCK_CLOEXEC|SOCK_NONBLOCK);
+ if (conn->sock < 0) {
+ if (errno != EINTR)
+ log_error("unable to receive ctrl connection: %m\n");
+ goto err;
+ }
+
+ /* check peer credential of connection */
+ slen = sizeof(ucred);
+ if (getsockopt(conn->sock, SOL_SOCKET, SO_PEERCRED, &ucred, &slen) < 0) {
+ log_error("unable to receive credentials of ctrl connection: %m\n");
+ goto err;
+ }
+ if (ucred.uid > 0) {
+ log_error("sender uid=%i, message ignored\n", ucred.uid);
+ goto err;
+ }
+
+ /* enable receiving of the sender credentials in the messages */
+ setsockopt(conn->sock, SOL_SOCKET, SO_PASSCRED, &on, sizeof(on));
+ udev_ctrl_ref(uctrl);
+ return conn;
+err:
+ if (conn->sock >= 0)
+ close(conn->sock);
+ free(conn);
+ return NULL;
+}
+
+struct udev_ctrl_connection *udev_ctrl_connection_ref(struct udev_ctrl_connection *conn)
+{
+ if (conn == NULL)
+ return NULL;
+ conn->refcount++;
+ return conn;
+}
+
+struct udev_ctrl_connection *udev_ctrl_connection_unref(struct udev_ctrl_connection *conn)
+{
+ if (conn == NULL)
+ return NULL;
+ conn->refcount--;
+ if (conn->refcount > 0)
+ return conn;
+ if (conn->sock >= 0)
+ close(conn->sock);
+ udev_ctrl_unref(conn->uctrl);
+ free(conn);
+ return NULL;
+}
+
+static int ctrl_send(struct udev_ctrl *uctrl, enum udev_ctrl_msg_type type, int intval, const char *buf, int timeout)
+{
+ struct udev_ctrl_msg_wire ctrl_msg_wire;
+ int err = 0;
+
+ memset(&ctrl_msg_wire, 0x00, sizeof(struct udev_ctrl_msg_wire));
+ strcpy(ctrl_msg_wire.version, "udev-" VERSION);
+ ctrl_msg_wire.magic = UDEV_CTRL_MAGIC;
+ ctrl_msg_wire.type = type;
+
+ if (buf != NULL)
+ strscpy(ctrl_msg_wire.buf, sizeof(ctrl_msg_wire.buf), buf);
+ else
+ ctrl_msg_wire.intval = intval;
+
+ if (!uctrl->connected) {
+ if (connect(uctrl->sock, (struct sockaddr *)&uctrl->saddr, uctrl->addrlen) < 0) {
+ err = -errno;
+ goto out;
+ }
+ uctrl->connected = true;
+ }
+ if (send(uctrl->sock, &ctrl_msg_wire, sizeof(ctrl_msg_wire), 0) < 0) {
+ err = -errno;
+ goto out;
+ }
+
+ /* wait for peer message handling or disconnect */
+ for (;;) {
+ struct pollfd pfd[1];
+ int r;
+
+ pfd[0].fd = uctrl->sock;
+ pfd[0].events = POLLIN;
+ r = poll(pfd, 1, timeout * 1000);
+ if (r < 0) {
+ if (errno == EINTR)
+ continue;
+ err = -errno;
+ break;
+ }
+
+ if (r > 0 && pfd[0].revents & POLLERR) {
+ err = -EIO;
+ break;
+ }
+
+ if (r == 0)
+ err = -ETIMEDOUT;
+ break;
+ }
+out:
+ return err;
+}
+
+int udev_ctrl_send_set_log_level(struct udev_ctrl *uctrl, int priority, int timeout)
+{
+ return ctrl_send(uctrl, UDEV_CTRL_SET_LOG_LEVEL, priority, NULL, timeout);
+}
+
+int udev_ctrl_send_stop_exec_queue(struct udev_ctrl *uctrl, int timeout)
+{
+ return ctrl_send(uctrl, UDEV_CTRL_STOP_EXEC_QUEUE, 0, NULL, timeout);
+}
+
+int udev_ctrl_send_start_exec_queue(struct udev_ctrl *uctrl, int timeout)
+{
+ return ctrl_send(uctrl, UDEV_CTRL_START_EXEC_QUEUE, 0, NULL, timeout);
+}
+
+int udev_ctrl_send_reload(struct udev_ctrl *uctrl, int timeout)
+{
+ return ctrl_send(uctrl, UDEV_CTRL_RELOAD, 0, NULL, timeout);
+}
+
+int udev_ctrl_send_set_env(struct udev_ctrl *uctrl, const char *key, int timeout)
+{
+ return ctrl_send(uctrl, UDEV_CTRL_SET_ENV, 0, key, timeout);
+}
+
+int udev_ctrl_send_set_children_max(struct udev_ctrl *uctrl, int count, int timeout)
+{
+ return ctrl_send(uctrl, UDEV_CTRL_SET_CHILDREN_MAX, count, NULL, timeout);
+}
+
+int udev_ctrl_send_ping(struct udev_ctrl *uctrl, int timeout)
+{
+ return ctrl_send(uctrl, UDEV_CTRL_PING, 0, NULL, timeout);
+}
+
+int udev_ctrl_send_exit(struct udev_ctrl *uctrl, int timeout)
+{
+ return ctrl_send(uctrl, UDEV_CTRL_EXIT, 0, NULL, timeout);
+}
+
+struct udev_ctrl_msg *udev_ctrl_receive_msg(struct udev_ctrl_connection *conn)
+{
+ struct udev_ctrl_msg *uctrl_msg;
+ ssize_t size;
+ struct msghdr smsg;
+ struct cmsghdr *cmsg;
+ struct iovec iov;
+ struct ucred *cred;
+ char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
+
+ uctrl_msg = calloc(1, sizeof(struct udev_ctrl_msg));
+ if (uctrl_msg == NULL)
+ return NULL;
+ uctrl_msg->refcount = 1;
+ uctrl_msg->conn = conn;
+ udev_ctrl_connection_ref(conn);
+
+ /* wait for the incoming message */
+ for(;;) {
+ struct pollfd pfd[1];
+ int r;
+
+ pfd[0].fd = conn->sock;
+ pfd[0].events = POLLIN;
+
+ r = poll(pfd, 1, 10000);
+ if (r < 0) {
+ if (errno == EINTR)
+ continue;
+ goto err;
+ } else if (r == 0) {
+ log_error("timeout waiting for ctrl message\n");
+ goto err;
+ } else {
+ if (!(pfd[0].revents & POLLIN)) {
+ log_error("ctrl connection error: %m\n");
+ goto err;
+ }
+ }
+
+ break;
+ }
+
+ iov.iov_base = &uctrl_msg->ctrl_msg_wire;
+ iov.iov_len = sizeof(struct udev_ctrl_msg_wire);
+ memset(&smsg, 0x00, sizeof(struct msghdr));
+ smsg.msg_iov = &iov;
+ smsg.msg_iovlen = 1;
+ smsg.msg_control = cred_msg;
+ smsg.msg_controllen = sizeof(cred_msg);
+ size = recvmsg(conn->sock, &smsg, 0);
+ if (size < 0) {
+ log_error("unable to receive ctrl message: %m\n");
+ goto err;
+ }
+ cmsg = CMSG_FIRSTHDR(&smsg);
+ cred = (struct ucred *) CMSG_DATA(cmsg);
+
+ if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
+ log_error("no sender credentials received, message ignored\n");
+ goto err;
+ }
+
+ if (cred->uid != 0) {
+ log_error("sender uid=%i, message ignored\n", cred->uid);
+ goto err;
+ }
+
+ if (uctrl_msg->ctrl_msg_wire.magic != UDEV_CTRL_MAGIC) {
+ log_error("message magic 0x%08x doesn't match, ignore it\n", uctrl_msg->ctrl_msg_wire.magic);
+ goto err;
+ }
+
+ return uctrl_msg;
+err:
+ udev_ctrl_msg_unref(uctrl_msg);
+ return NULL;
+}
+
+struct udev_ctrl_msg *udev_ctrl_msg_ref(struct udev_ctrl_msg *ctrl_msg)
+{
+ if (ctrl_msg == NULL)
+ return NULL;
+ ctrl_msg->refcount++;
+ return ctrl_msg;
+}
+
+struct udev_ctrl_msg *udev_ctrl_msg_unref(struct udev_ctrl_msg *ctrl_msg)
+{
+ if (ctrl_msg == NULL)
+ return NULL;
+ ctrl_msg->refcount--;
+ if (ctrl_msg->refcount > 0)
+ return ctrl_msg;
+ udev_ctrl_connection_unref(ctrl_msg->conn);
+ free(ctrl_msg);
+ return NULL;
+}
+
+int udev_ctrl_get_set_log_level(struct udev_ctrl_msg *ctrl_msg)
+{
+ if (ctrl_msg->ctrl_msg_wire.type == UDEV_CTRL_SET_LOG_LEVEL)
+ return ctrl_msg->ctrl_msg_wire.intval;
+ return -1;
+}
+
+int udev_ctrl_get_stop_exec_queue(struct udev_ctrl_msg *ctrl_msg)
+{
+ if (ctrl_msg->ctrl_msg_wire.type == UDEV_CTRL_STOP_EXEC_QUEUE)
+ return 1;
+ return -1;
+}
+
+int udev_ctrl_get_start_exec_queue(struct udev_ctrl_msg *ctrl_msg)
+{
+ if (ctrl_msg->ctrl_msg_wire.type == UDEV_CTRL_START_EXEC_QUEUE)
+ return 1;
+ return -1;
+}
+
+int udev_ctrl_get_reload(struct udev_ctrl_msg *ctrl_msg)
+{
+ if (ctrl_msg->ctrl_msg_wire.type == UDEV_CTRL_RELOAD)
+ return 1;
+ return -1;
+}
+
+const char *udev_ctrl_get_set_env(struct udev_ctrl_msg *ctrl_msg)
+{
+ if (ctrl_msg->ctrl_msg_wire.type == UDEV_CTRL_SET_ENV)
+ return ctrl_msg->ctrl_msg_wire.buf;
+ return NULL;
+}
+
+int udev_ctrl_get_set_children_max(struct udev_ctrl_msg *ctrl_msg)
+{
+ if (ctrl_msg->ctrl_msg_wire.type == UDEV_CTRL_SET_CHILDREN_MAX)
+ return ctrl_msg->ctrl_msg_wire.intval;
+ return -1;
+}
+
+int udev_ctrl_get_ping(struct udev_ctrl_msg *ctrl_msg)
+{
+ if (ctrl_msg->ctrl_msg_wire.type == UDEV_CTRL_PING)
+ return 1;
+ return -1;
+}
+
+int udev_ctrl_get_exit(struct udev_ctrl_msg *ctrl_msg)
+{
+ if (ctrl_msg->ctrl_msg_wire.type == UDEV_CTRL_EXIT)
+ return 1;
+ return -1;
+}
diff --git a/src/udev/udev-event.c b/src/udev/udev-event.c
new file mode 100644
index 0000000000..3db2cb7165
--- /dev/null
+++ b/src/udev/udev-event.c
@@ -0,0 +1,914 @@
+/*
+ * Copyright (C) 2003-2013 Kay Sievers <kay@vrfy.org>
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <stddef.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <ctype.h>
+#include <string.h>
+#include <time.h>
+#include <net/if.h>
+#include <sys/ioctl.h>
+#include <sys/prctl.h>
+#include <sys/poll.h>
+#include <sys/epoll.h>
+#include <sys/wait.h>
+#include <sys/socket.h>
+#include <sys/signalfd.h>
+#include <linux/sockios.h>
+
+#include "udev.h"
+
+struct udev_event *udev_event_new(struct udev_device *dev)
+{
+ struct udev *udev = udev_device_get_udev(dev);
+ struct udev_event *event;
+
+ event = calloc(1, sizeof(struct udev_event));
+ if (event == NULL)
+ return NULL;
+ event->dev = dev;
+ event->udev = udev;
+ udev_list_init(udev, &event->run_list, false);
+ event->fd_signal = -1;
+ event->birth_usec = now(CLOCK_MONOTONIC);
+ event->timeout_usec = 30 * 1000 * 1000;
+ return event;
+}
+
+void udev_event_unref(struct udev_event *event)
+{
+ if (event == NULL)
+ return;
+ udev_list_cleanup(&event->run_list);
+ free(event->program_result);
+ free(event->name);
+ free(event);
+}
+
+size_t udev_event_apply_format(struct udev_event *event, const char *src, char *dest, size_t size)
+{
+ struct udev_device *dev = event->dev;
+ enum subst_type {
+ SUBST_UNKNOWN,
+ SUBST_DEVNODE,
+ SUBST_ATTR,
+ SUBST_ENV,
+ SUBST_KERNEL,
+ SUBST_KERNEL_NUMBER,
+ SUBST_DRIVER,
+ SUBST_DEVPATH,
+ SUBST_ID,
+ SUBST_MAJOR,
+ SUBST_MINOR,
+ SUBST_RESULT,
+ SUBST_PARENT,
+ SUBST_NAME,
+ SUBST_LINKS,
+ SUBST_ROOT,
+ SUBST_SYS,
+ };
+ static const struct subst_map {
+ const char *name;
+ const char fmt;
+ enum subst_type type;
+ } map[] = {
+ { .name = "devnode", .fmt = 'N', .type = SUBST_DEVNODE },
+ { .name = "tempnode", .fmt = 'N', .type = SUBST_DEVNODE },
+ { .name = "attr", .fmt = 's', .type = SUBST_ATTR },
+ { .name = "sysfs", .fmt = 's', .type = SUBST_ATTR },
+ { .name = "env", .fmt = 'E', .type = SUBST_ENV },
+ { .name = "kernel", .fmt = 'k', .type = SUBST_KERNEL },
+ { .name = "number", .fmt = 'n', .type = SUBST_KERNEL_NUMBER },
+ { .name = "driver", .fmt = 'd', .type = SUBST_DRIVER },
+ { .name = "devpath", .fmt = 'p', .type = SUBST_DEVPATH },
+ { .name = "id", .fmt = 'b', .type = SUBST_ID },
+ { .name = "major", .fmt = 'M', .type = SUBST_MAJOR },
+ { .name = "minor", .fmt = 'm', .type = SUBST_MINOR },
+ { .name = "result", .fmt = 'c', .type = SUBST_RESULT },
+ { .name = "parent", .fmt = 'P', .type = SUBST_PARENT },
+ { .name = "name", .fmt = 'D', .type = SUBST_NAME },
+ { .name = "links", .fmt = 'L', .type = SUBST_LINKS },
+ { .name = "root", .fmt = 'r', .type = SUBST_ROOT },
+ { .name = "sys", .fmt = 'S', .type = SUBST_SYS },
+ };
+ const char *from;
+ char *s;
+ size_t l;
+
+ from = src;
+ s = dest;
+ l = size;
+
+ for (;;) {
+ enum subst_type type = SUBST_UNKNOWN;
+ char attrbuf[UTIL_PATH_SIZE];
+ char *attr = NULL;
+
+ while (from[0] != '\0') {
+ if (from[0] == '$') {
+ /* substitute named variable */
+ unsigned int i;
+
+ if (from[1] == '$') {
+ from++;
+ goto copy;
+ }
+
+ for (i = 0; i < ELEMENTSOF(map); i++) {
+ if (startswith(&from[1], map[i].name)) {
+ type = map[i].type;
+ from += strlen(map[i].name)+1;
+ goto subst;
+ }
+ }
+ } else if (from[0] == '%') {
+ /* substitute format char */
+ unsigned int i;
+
+ if (from[1] == '%') {
+ from++;
+ goto copy;
+ }
+
+ for (i = 0; i < ELEMENTSOF(map); i++) {
+ if (from[1] == map[i].fmt) {
+ type = map[i].type;
+ from += 2;
+ goto subst;
+ }
+ }
+ }
+copy:
+ /* copy char */
+ if (l == 0)
+ goto out;
+ s[0] = from[0];
+ from++;
+ s++;
+ l--;
+ }
+
+ goto out;
+subst:
+ /* extract possible $format{attr} */
+ if (from[0] == '{') {
+ unsigned int i;
+
+ from++;
+ for (i = 0; from[i] != '}'; i++) {
+ if (from[i] == '\0') {
+ log_error("missing closing brace for format '%s'\n", src);
+ goto out;
+ }
+ }
+ if (i >= sizeof(attrbuf))
+ goto out;
+ memcpy(attrbuf, from, i);
+ attrbuf[i] = '\0';
+ from += i+1;
+ attr = attrbuf;
+ } else {
+ attr = NULL;
+ }
+
+ switch (type) {
+ case SUBST_DEVPATH:
+ l = strpcpy(&s, l, udev_device_get_devpath(dev));
+ break;
+ case SUBST_KERNEL:
+ l = strpcpy(&s, l, udev_device_get_sysname(dev));
+ break;
+ case SUBST_KERNEL_NUMBER:
+ if (udev_device_get_sysnum(dev) == NULL)
+ break;
+ l = strpcpy(&s, l, udev_device_get_sysnum(dev));
+ break;
+ case SUBST_ID:
+ if (event->dev_parent == NULL)
+ break;
+ l = strpcpy(&s, l, udev_device_get_sysname(event->dev_parent));
+ break;
+ case SUBST_DRIVER: {
+ const char *driver;
+
+ if (event->dev_parent == NULL)
+ break;
+
+ driver = udev_device_get_driver(event->dev_parent);
+ if (driver == NULL)
+ break;
+ l = strpcpy(&s, l, driver);
+ break;
+ }
+ case SUBST_MAJOR: {
+ char num[UTIL_PATH_SIZE];
+
+ sprintf(num, "%d", major(udev_device_get_devnum(dev)));
+ l = strpcpy(&s, l, num);
+ break;
+ }
+ case SUBST_MINOR: {
+ char num[UTIL_PATH_SIZE];
+
+ sprintf(num, "%d", minor(udev_device_get_devnum(dev)));
+ l = strpcpy(&s, l, num);
+ break;
+ }
+ case SUBST_RESULT: {
+ char *rest;
+ int i;
+
+ if (event->program_result == NULL)
+ break;
+ /* get part part of the result string */
+ i = 0;
+ if (attr != NULL)
+ i = strtoul(attr, &rest, 10);
+ if (i > 0) {
+ char result[UTIL_PATH_SIZE];
+ char tmp[UTIL_PATH_SIZE];
+ char *cpos;
+
+ strscpy(result, sizeof(result), event->program_result);
+ cpos = result;
+ while (--i) {
+ while (cpos[0] != '\0' && !isspace(cpos[0]))
+ cpos++;
+ while (isspace(cpos[0]))
+ cpos++;
+ }
+ if (i > 0) {
+ log_error("requested part of result string not found\n");
+ break;
+ }
+ strscpy(tmp, sizeof(tmp), cpos);
+ /* %{2+}c copies the whole string from the second part on */
+ if (rest[0] != '+') {
+ cpos = strchr(tmp, ' ');
+ if (cpos)
+ cpos[0] = '\0';
+ }
+ l = strpcpy(&s, l, tmp);
+ } else {
+ l = strpcpy(&s, l, event->program_result);
+ }
+ break;
+ }
+ case SUBST_ATTR: {
+ const char *value = NULL;
+ char vbuf[UTIL_NAME_SIZE];
+ size_t len;
+ int count;
+
+ if (attr == NULL) {
+ log_error("missing file parameter for attr\n");
+ break;
+ }
+
+ /* try to read the value specified by "[dmi/id]product_name" */
+ if (util_resolve_subsys_kernel(event->udev, attr, vbuf, sizeof(vbuf), 1) == 0)
+ value = vbuf;
+
+ /* try to read the attribute the device */
+ if (value == NULL)
+ value = udev_device_get_sysattr_value(event->dev, attr);
+
+ /* try to read the attribute of the parent device, other matches have selected */
+ if (value == NULL && event->dev_parent != NULL && event->dev_parent != event->dev)
+ value = udev_device_get_sysattr_value(event->dev_parent, attr);
+
+ if (value == NULL)
+ break;
+
+ /* strip trailing whitespace, and replace unwanted characters */
+ if (value != vbuf)
+ strscpy(vbuf, sizeof(vbuf), value);
+ len = strlen(vbuf);
+ while (len > 0 && isspace(vbuf[--len]))
+ vbuf[len] = '\0';
+ count = util_replace_chars(vbuf, UDEV_ALLOWED_CHARS_INPUT);
+ if (count > 0)
+ log_debug("%i character(s) replaced\n" , count);
+ l = strpcpy(&s, l, vbuf);
+ break;
+ }
+ case SUBST_PARENT: {
+ struct udev_device *dev_parent;
+ const char *devnode;
+
+ dev_parent = udev_device_get_parent(event->dev);
+ if (dev_parent == NULL)
+ break;
+ devnode = udev_device_get_devnode(dev_parent);
+ if (devnode != NULL)
+ l = strpcpy(&s, l, devnode + strlen("/dev/"));
+ break;
+ }
+ case SUBST_DEVNODE:
+ if (udev_device_get_devnode(dev) != NULL)
+ l = strpcpy(&s, l, udev_device_get_devnode(dev));
+ break;
+ case SUBST_NAME:
+ if (event->name != NULL)
+ l = strpcpy(&s, l, event->name);
+ else if (udev_device_get_devnode(dev) != NULL)
+ l = strpcpy(&s, l, udev_device_get_devnode(dev) + strlen("/dev/"));
+ else
+ l = strpcpy(&s, l, udev_device_get_sysname(dev));
+ break;
+ case SUBST_LINKS: {
+ struct udev_list_entry *list_entry;
+
+ list_entry = udev_device_get_devlinks_list_entry(dev);
+ if (list_entry == NULL)
+ break;
+ l = strpcpy(&s, l, udev_list_entry_get_name(list_entry) + strlen("/dev/"));
+ udev_list_entry_foreach(list_entry, udev_list_entry_get_next(list_entry))
+ l = strpcpyl(&s, l, " ", udev_list_entry_get_name(list_entry) + strlen("/dev/"), NULL);
+ break;
+ }
+ case SUBST_ROOT:
+ l = strpcpy(&s, l, "/dev");
+ break;
+ case SUBST_SYS:
+ l = strpcpy(&s, l, "/sys");
+ break;
+ case SUBST_ENV:
+ if (attr == NULL) {
+ break;
+ } else {
+ const char *value;
+
+ value = udev_device_get_property_value(event->dev, attr);
+ if (value == NULL)
+ break;
+ l = strpcpy(&s, l, value);
+ break;
+ }
+ default:
+ log_error("unknown substitution type=%i\n", type);
+ break;
+ }
+ }
+
+out:
+ s[0] = '\0';
+ return l;
+}
+
+static int spawn_exec(struct udev_event *event,
+ const char *cmd, char *const argv[], char **envp, const sigset_t *sigmask,
+ int fd_stdout, int fd_stderr)
+{
+ int err;
+ int fd;
+
+ /* discard child output or connect to pipe */
+ fd = open("/dev/null", O_RDWR);
+ if (fd >= 0) {
+ dup2(fd, STDIN_FILENO);
+ if (fd_stdout < 0)
+ dup2(fd, STDOUT_FILENO);
+ if (fd_stderr < 0)
+ dup2(fd, STDERR_FILENO);
+ close(fd);
+ } else {
+ log_error("open /dev/null failed: %m\n");
+ }
+
+ /* connect pipes to std{out,err} */
+ if (fd_stdout >= 0) {
+ dup2(fd_stdout, STDOUT_FILENO);
+ close(fd_stdout);
+ }
+ if (fd_stderr >= 0) {
+ dup2(fd_stderr, STDERR_FILENO);
+ close(fd_stderr);
+ }
+
+ /* terminate child in case parent goes away */
+ prctl(PR_SET_PDEATHSIG, SIGTERM);
+
+ /* restore original udev sigmask before exec */
+ if (sigmask)
+ sigprocmask(SIG_SETMASK, sigmask, NULL);
+
+ execve(argv[0], argv, envp);
+
+ /* exec failed */
+ err = -errno;
+ log_error("failed to execute '%s' '%s': %m\n", argv[0], cmd);
+ return err;
+}
+
+static void spawn_read(struct udev_event *event,
+ const char *cmd,
+ int fd_stdout, int fd_stderr,
+ char *result, size_t ressize)
+{
+ size_t respos = 0;
+ int fd_ep = -1;
+ struct epoll_event ep_outpipe, ep_errpipe;
+
+ /* read from child if requested */
+ if (fd_stdout < 0 && fd_stderr < 0)
+ return;
+
+ fd_ep = epoll_create1(EPOLL_CLOEXEC);
+ if (fd_ep < 0) {
+ log_error("error creating epoll fd: %m\n");
+ goto out;
+ }
+
+ if (fd_stdout >= 0) {
+ memset(&ep_outpipe, 0, sizeof(struct epoll_event));
+ ep_outpipe.events = EPOLLIN;
+ ep_outpipe.data.ptr = &fd_stdout;
+ if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_stdout, &ep_outpipe) < 0) {
+ log_error("fail to add fd to epoll: %m\n");
+ goto out;
+ }
+ }
+
+ if (fd_stderr >= 0) {
+ memset(&ep_errpipe, 0, sizeof(struct epoll_event));
+ ep_errpipe.events = EPOLLIN;
+ ep_errpipe.data.ptr = &fd_stderr;
+ if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_stderr, &ep_errpipe) < 0) {
+ log_error("fail to add fd to epoll: %m\n");
+ goto out;
+ }
+ }
+
+ /* read child output */
+ while (fd_stdout >= 0 || fd_stderr >= 0) {
+ int timeout;
+ int fdcount;
+ struct epoll_event ev[4];
+ int i;
+
+ if (event->timeout_usec > 0) {
+ usec_t age_usec;
+
+ age_usec = now(CLOCK_MONOTONIC) - event->birth_usec;
+ if (age_usec >= event->timeout_usec) {
+ log_error("timeout '%s'\n", cmd);
+ goto out;
+ }
+ timeout = ((event->timeout_usec - age_usec) / 1000) + 1000;
+ } else {
+ timeout = -1;
+ }
+
+ fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), timeout);
+ if (fdcount < 0) {
+ if (errno == EINTR)
+ continue;
+ log_error("failed to poll: %m\n");
+ goto out;
+ }
+ if (fdcount == 0) {
+ log_error("timeout '%s'\n", cmd);
+ goto out;
+ }
+
+ for (i = 0; i < fdcount; i++) {
+ int *fd = (int *)ev[i].data.ptr;
+
+ if (ev[i].events & EPOLLIN) {
+ ssize_t count;
+ char buf[4096];
+
+ count = read(*fd, buf, sizeof(buf)-1);
+ if (count <= 0)
+ continue;
+ buf[count] = '\0';
+
+ /* store stdout result */
+ if (result != NULL && *fd == fd_stdout) {
+ if (respos + count < ressize) {
+ memcpy(&result[respos], buf, count);
+ respos += count;
+ } else {
+ log_error("'%s' ressize %zd too short\n", cmd, ressize);
+ }
+ }
+
+ /* log debug output only if we watch stderr */
+ if (fd_stderr >= 0) {
+ char *pos;
+ char *line;
+
+ pos = buf;
+ while ((line = strsep(&pos, "\n"))) {
+ if (pos != NULL || line[0] != '\0')
+ log_debug("'%s'(%s) '%s'\n", cmd, *fd == fd_stdout ? "out" : "err" , line);
+ }
+ }
+ } else if (ev[i].events & EPOLLHUP) {
+ if (epoll_ctl(fd_ep, EPOLL_CTL_DEL, *fd, NULL) < 0) {
+ log_error("failed to remove fd from epoll: %m\n");
+ goto out;
+ }
+ *fd = -1;
+ }
+ }
+ }
+
+ /* return the child's stdout string */
+ if (result != NULL)
+ result[respos] = '\0';
+out:
+ if (fd_ep >= 0)
+ close(fd_ep);
+}
+
+static int spawn_wait(struct udev_event *event, const char *cmd, pid_t pid)
+{
+ struct pollfd pfd[1];
+ int err = 0;
+
+ pfd[0].events = POLLIN;
+ pfd[0].fd = event->fd_signal;
+
+ while (pid > 0) {
+ int timeout;
+ int fdcount;
+
+ if (event->timeout_usec > 0) {
+ usec_t age_usec;
+
+ age_usec = now(CLOCK_MONOTONIC) - event->birth_usec;
+ if (age_usec >= event->timeout_usec)
+ timeout = 1000;
+ else
+ timeout = ((event->timeout_usec - age_usec) / 1000) + 1000;
+ } else {
+ timeout = -1;
+ }
+
+ fdcount = poll(pfd, 1, timeout);
+ if (fdcount < 0) {
+ if (errno == EINTR)
+ continue;
+ err = -errno;
+ log_error("failed to poll: %m\n");
+ goto out;
+ }
+ if (fdcount == 0) {
+ log_error("timeout: killing '%s' [%u]\n", cmd, pid);
+ kill(pid, SIGKILL);
+ }
+
+ if (pfd[0].revents & POLLIN) {
+ struct signalfd_siginfo fdsi;
+ int status;
+ ssize_t size;
+
+ size = read(event->fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
+ if (size != sizeof(struct signalfd_siginfo))
+ continue;
+
+ switch (fdsi.ssi_signo) {
+ case SIGTERM:
+ event->sigterm = true;
+ break;
+ case SIGCHLD:
+ if (waitpid(pid, &status, WNOHANG) < 0)
+ break;
+ if (WIFEXITED(status)) {
+ log_debug("'%s' [%u] exit with return code %i\n", cmd, pid, WEXITSTATUS(status));
+ if (WEXITSTATUS(status) != 0)
+ err = -1;
+ } else if (WIFSIGNALED(status)) {
+ log_error("'%s' [%u] terminated by signal %i (%s)\n", cmd, pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
+ err = -1;
+ } else if (WIFSTOPPED(status)) {
+ log_error("'%s' [%u] stopped\n", cmd, pid);
+ err = -1;
+ } else if (WIFCONTINUED(status)) {
+ log_error("'%s' [%u] continued\n", cmd, pid);
+ err = -1;
+ } else {
+ log_error("'%s' [%u] exit with status 0x%04x\n", cmd, pid, status);
+ err = -1;
+ }
+ pid = 0;
+ break;
+ }
+ }
+ }
+out:
+ return err;
+}
+
+int udev_build_argv(struct udev *udev, char *cmd, int *argc, char *argv[])
+{
+ int i = 0;
+ char *pos;
+
+ if (strchr(cmd, ' ') == NULL) {
+ argv[i++] = cmd;
+ goto out;
+ }
+
+ pos = cmd;
+ while (pos != NULL && pos[0] != '\0') {
+ if (pos[0] == '\'') {
+ /* do not separate quotes */
+ pos++;
+ argv[i] = strsep(&pos, "\'");
+ if (pos != NULL)
+ while (pos[0] == ' ')
+ pos++;
+ } else {
+ argv[i] = strsep(&pos, " ");
+ if (pos != NULL)
+ while (pos[0] == ' ')
+ pos++;
+ }
+ i++;
+ }
+out:
+ argv[i] = NULL;
+ if (argc)
+ *argc = i;
+ return 0;
+}
+
+int udev_event_spawn(struct udev_event *event,
+ const char *cmd, char **envp, const sigset_t *sigmask,
+ char *result, size_t ressize)
+{
+ struct udev *udev = event->udev;
+ int outpipe[2] = {-1, -1};
+ int errpipe[2] = {-1, -1};
+ pid_t pid;
+ char arg[UTIL_PATH_SIZE];
+ char *argv[128];
+ char program[UTIL_PATH_SIZE];
+ int err = 0;
+
+ strscpy(arg, sizeof(arg), cmd);
+ udev_build_argv(event->udev, arg, NULL, argv);
+
+ /* pipes from child to parent */
+ if (result != NULL || udev_get_log_priority(udev) >= LOG_INFO) {
+ if (pipe2(outpipe, O_NONBLOCK) != 0) {
+ err = -errno;
+ log_error("pipe failed: %m\n");
+ goto out;
+ }
+ }
+ if (udev_get_log_priority(udev) >= LOG_INFO) {
+ if (pipe2(errpipe, O_NONBLOCK) != 0) {
+ err = -errno;
+ log_error("pipe failed: %m\n");
+ goto out;
+ }
+ }
+
+ /* allow programs in /usr/lib/udev/ to be called without the path */
+ if (argv[0][0] != '/') {
+ strscpyl(program, sizeof(program), UDEVLIBEXECDIR "/", argv[0], NULL);
+ argv[0] = program;
+ }
+
+ pid = fork();
+ switch(pid) {
+ case 0:
+ /* child closes parent's ends of pipes */
+ if (outpipe[READ_END] >= 0) {
+ close(outpipe[READ_END]);
+ outpipe[READ_END] = -1;
+ }
+ if (errpipe[READ_END] >= 0) {
+ close(errpipe[READ_END]);
+ errpipe[READ_END] = -1;
+ }
+
+ log_debug("starting '%s'\n", cmd);
+
+ spawn_exec(event, cmd, argv, envp, sigmask,
+ outpipe[WRITE_END], errpipe[WRITE_END]);
+
+ _exit(2 );
+ case -1:
+ log_error("fork of '%s' failed: %m\n", cmd);
+ err = -1;
+ goto out;
+ default:
+ /* parent closed child's ends of pipes */
+ if (outpipe[WRITE_END] >= 0) {
+ close(outpipe[WRITE_END]);
+ outpipe[WRITE_END] = -1;
+ }
+ if (errpipe[WRITE_END] >= 0) {
+ close(errpipe[WRITE_END]);
+ errpipe[WRITE_END] = -1;
+ }
+
+ spawn_read(event, cmd,
+ outpipe[READ_END], errpipe[READ_END],
+ result, ressize);
+
+ err = spawn_wait(event, cmd, pid);
+ }
+
+out:
+ if (outpipe[READ_END] >= 0)
+ close(outpipe[READ_END]);
+ if (outpipe[WRITE_END] >= 0)
+ close(outpipe[WRITE_END]);
+ if (errpipe[READ_END] >= 0)
+ close(errpipe[READ_END]);
+ if (errpipe[WRITE_END] >= 0)
+ close(errpipe[WRITE_END]);
+ return err;
+}
+
+static int rename_netif(struct udev_event *event)
+{
+ struct udev_device *dev = event->dev;
+ int sk;
+ struct ifreq ifr;
+ int err;
+
+ log_debug("changing net interface name from '%s' to '%s'\n",
+ udev_device_get_sysname(dev), event->name);
+
+ sk = socket(PF_INET, SOCK_DGRAM, 0);
+ if (sk < 0) {
+ err = -errno;
+ log_error("error opening socket: %m\n");
+ return err;
+ }
+
+ memset(&ifr, 0x00, sizeof(struct ifreq));
+ strscpy(ifr.ifr_name, IFNAMSIZ, udev_device_get_sysname(dev));
+ strscpy(ifr.ifr_newname, IFNAMSIZ, event->name);
+ err = ioctl(sk, SIOCSIFNAME, &ifr);
+ if (err >= 0) {
+ print_kmsg("renamed network interface %s to %s\n", ifr.ifr_name, ifr.ifr_newname);
+ } else {
+ err = -errno;
+ log_error("error changing net interface name %s to %s: %m\n", ifr.ifr_name, ifr.ifr_newname);
+ }
+ close(sk);
+ return err;
+}
+
+int udev_event_execute_rules(struct udev_event *event, struct udev_rules *rules, const sigset_t *sigmask)
+{
+ struct udev_device *dev = event->dev;
+ int err = 0;
+
+ if (udev_device_get_subsystem(dev) == NULL)
+ return -1;
+
+ if (streq(udev_device_get_action(dev), "remove")) {
+ udev_device_read_db(dev, NULL);
+ udev_device_delete_db(dev);
+ udev_device_tag_index(dev, NULL, false);
+
+ if (major(udev_device_get_devnum(dev)) != 0)
+ udev_watch_end(event->udev, dev);
+
+ udev_rules_apply_to_event(rules, event, sigmask);
+
+ if (major(udev_device_get_devnum(dev)) != 0)
+ udev_node_remove(dev);
+ } else {
+ event->dev_db = udev_device_new(event->udev);
+ if (event->dev_db != NULL) {
+ udev_device_set_syspath(event->dev_db, udev_device_get_syspath(dev));
+ udev_device_set_subsystem(event->dev_db, udev_device_get_subsystem(dev));
+ udev_device_read_db(event->dev_db, NULL);
+ udev_device_set_info_loaded(event->dev_db);
+
+ /* disable watch during event processing */
+ if (major(udev_device_get_devnum(dev)) != 0)
+ udev_watch_end(event->udev, event->dev_db);
+ }
+
+ udev_rules_apply_to_event(rules, event, sigmask);
+
+ /* rename a new network interface, if needed */
+ if (udev_device_get_ifindex(dev) > 0 && streq(udev_device_get_action(dev), "add") &&
+ event->name != NULL && !streq(event->name, udev_device_get_sysname(dev))) {
+ char syspath[UTIL_PATH_SIZE];
+ char *pos;
+
+ err = rename_netif(event);
+ if (err == 0) {
+ log_debug("renamed netif to '%s'\n", event->name);
+
+ /* remember old name */
+ udev_device_add_property(dev, "INTERFACE_OLD", udev_device_get_sysname(dev));
+
+ /* now change the devpath, because the kernel device name has changed */
+ strscpy(syspath, sizeof(syspath), udev_device_get_syspath(dev));
+ pos = strrchr(syspath, '/');
+ if (pos != NULL) {
+ pos++;
+ strscpy(pos, sizeof(syspath) - (pos - syspath), event->name);
+ udev_device_set_syspath(event->dev, syspath);
+ udev_device_add_property(dev, "INTERFACE", udev_device_get_sysname(dev));
+ log_debug("changed devpath to '%s'\n", udev_device_get_devpath(dev));
+ }
+ }
+ }
+
+ if (major(udev_device_get_devnum(dev)) > 0) {
+ bool apply;
+
+ /* remove/update possible left-over symlinks from old database entry */
+ if (event->dev_db != NULL)
+ udev_node_update_old_links(dev, event->dev_db);
+
+ if (!event->owner_set)
+ event->uid = udev_device_get_devnode_uid(dev);
+
+ if (!event->group_set)
+ event->gid = udev_device_get_devnode_gid(dev);
+
+ if (!event->mode_set) {
+ if (udev_device_get_devnode_mode(dev) > 0) {
+ /* kernel supplied value */
+ event->mode = udev_device_get_devnode_mode(dev);
+ } else if (event->gid > 0) {
+ /* default 0660 if a group is assigned */
+ event->mode = 0660;
+ } else {
+ /* default 0600 */
+ event->mode = 0600;
+ }
+ }
+
+ apply = streq(udev_device_get_action(dev), "add") || event->owner_set || event->group_set || event->mode_set;
+ udev_node_add(dev, apply, event->mode, event->uid, event->gid);
+ }
+
+ /* preserve old, or get new initialization timestamp */
+ if (event->dev_db != NULL && udev_device_get_usec_initialized(event->dev_db) > 0)
+ udev_device_set_usec_initialized(event->dev, udev_device_get_usec_initialized(event->dev_db));
+ else if (udev_device_get_usec_initialized(event->dev) == 0)
+ udev_device_set_usec_initialized(event->dev, now(CLOCK_MONOTONIC));
+
+ /* (re)write database file */
+ udev_device_update_db(dev);
+ udev_device_tag_index(dev, event->dev_db, true);
+ udev_device_set_is_initialized(dev);
+
+ udev_device_unref(event->dev_db);
+ event->dev_db = NULL;
+ }
+ return err;
+}
+
+void udev_event_execute_run(struct udev_event *event, const sigset_t *sigmask)
+{
+ struct udev_list_entry *list_entry;
+
+ udev_list_entry_foreach(list_entry, udev_list_get_entry(&event->run_list)) {
+ const char *cmd = udev_list_entry_get_name(list_entry);
+ enum udev_builtin_cmd builtin_cmd = udev_list_entry_get_num(list_entry);
+
+ if (builtin_cmd < UDEV_BUILTIN_MAX) {
+ char command[UTIL_PATH_SIZE];
+
+ udev_event_apply_format(event, cmd, command, sizeof(command));
+ udev_builtin_run(event->dev, builtin_cmd, command, false);
+ } else {
+ char program[UTIL_PATH_SIZE];
+ char **envp;
+
+ if (event->exec_delay > 0) {
+ log_debug("delay execution of '%s'\n", program);
+ sleep(event->exec_delay);
+ }
+
+ udev_event_apply_format(event, cmd, program, sizeof(program));
+ envp = udev_device_get_properties_envp(event->dev);
+ udev_event_spawn(event, program, envp, sigmask, NULL, 0);
+ }
+ }
+}
diff --git a/src/udev/udev-node.c b/src/udev/udev-node.c
new file mode 100644
index 0000000000..1148a1529c
--- /dev/null
+++ b/src/udev/udev-node.c
@@ -0,0 +1,333 @@
+/*
+ * Copyright (C) 2003-2013 Kay Sievers <kay@vrfy.org>
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <stddef.h>
+#include <stdbool.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <errno.h>
+#include <grp.h>
+#include <dirent.h>
+#include <sys/time.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+
+#include "udev.h"
+
+static int node_symlink(struct udev_device *dev, const char *node, const char *slink)
+{
+ struct stat stats;
+ char target[UTIL_PATH_SIZE];
+ char *s;
+ size_t l;
+ char slink_tmp[UTIL_PATH_SIZE + 32];
+ int i = 0;
+ int tail = 0;
+ int err = 0;
+
+ /* use relative link */
+ target[0] = '\0';
+ while (node[i] && (node[i] == slink[i])) {
+ if (node[i] == '/')
+ tail = i+1;
+ i++;
+ }
+ s = target;
+ l = sizeof(target);
+ while (slink[i] != '\0') {
+ if (slink[i] == '/')
+ l = strpcpy(&s, l, "../");
+ i++;
+ }
+ l = strscpy(s, l, &node[tail]);
+ if (l == 0) {
+ err = -EINVAL;
+ goto exit;
+ }
+
+ /* preserve link with correct target, do not replace node of other device */
+ if (lstat(slink, &stats) == 0) {
+ if (S_ISBLK(stats.st_mode) || S_ISCHR(stats.st_mode)) {
+ log_error("conflicting device node '%s' found, link to '%s' will not be created\n", slink, node);
+ goto exit;
+ } else if (S_ISLNK(stats.st_mode)) {
+ char buf[UTIL_PATH_SIZE];
+ int len;
+
+ len = readlink(slink, buf, sizeof(buf));
+ if (len > 0 && len < (int)sizeof(buf)) {
+ buf[len] = '\0';
+ if (streq(target, buf)) {
+ log_debug("preserve already existing symlink '%s' to '%s'\n", slink, target);
+ label_fix(slink, true, false);
+ utimensat(AT_FDCWD, slink, NULL, AT_SYMLINK_NOFOLLOW);
+ goto exit;
+ }
+ }
+ }
+ } else {
+ log_debug("creating symlink '%s' to '%s'\n", slink, target);
+ do {
+ err = mkdir_parents_label(slink, 0755);
+ if (err != 0 && err != -ENOENT)
+ break;
+ label_context_set(slink, S_IFLNK);
+ err = symlink(target, slink);
+ if (err != 0)
+ err = -errno;
+ label_context_clear();
+ } while (err == -ENOENT);
+ if (err == 0)
+ goto exit;
+ }
+
+ log_debug("atomically replace '%s'\n", slink);
+ strscpyl(slink_tmp, sizeof(slink_tmp), slink, ".tmp-", udev_device_get_id_filename(dev), NULL);
+ unlink(slink_tmp);
+ do {
+ err = mkdir_parents_label(slink_tmp, 0755);
+ if (err != 0 && err != -ENOENT)
+ break;
+ label_context_set(slink_tmp, S_IFLNK);
+ err = symlink(target, slink_tmp);
+ if (err != 0)
+ err = -errno;
+ label_context_clear();
+ } while (err == -ENOENT);
+ if (err != 0) {
+ log_error("symlink '%s' '%s' failed: %m\n", target, slink_tmp);
+ goto exit;
+ }
+ err = rename(slink_tmp, slink);
+ if (err != 0) {
+ log_error("rename '%s' '%s' failed: %m\n", slink_tmp, slink);
+ unlink(slink_tmp);
+ }
+exit:
+ return err;
+}
+
+/* find device node of device with highest priority */
+static const char *link_find_prioritized(struct udev_device *dev, bool add, const char *stackdir, char *buf, size_t bufsize)
+{
+ struct udev *udev = udev_device_get_udev(dev);
+ DIR *dir;
+ int priority = 0;
+ const char *target = NULL;
+
+ if (add) {
+ priority = udev_device_get_devlink_priority(dev);
+ strscpy(buf, bufsize, udev_device_get_devnode(dev));
+ target = buf;
+ }
+
+ dir = opendir(stackdir);
+ if (dir == NULL)
+ return target;
+ for (;;) {
+ struct udev_device *dev_db;
+ struct dirent *dent;
+
+ dent = readdir(dir);
+ if (dent == NULL || dent->d_name[0] == '\0')
+ break;
+ if (dent->d_name[0] == '.')
+ continue;
+
+ log_debug("found '%s' claiming '%s'\n", dent->d_name, stackdir);
+
+ /* did we find ourself? */
+ if (streq(dent->d_name, udev_device_get_id_filename(dev)))
+ continue;
+
+ dev_db = udev_device_new_from_device_id(udev, dent->d_name);
+ if (dev_db != NULL) {
+ const char *devnode;
+
+ devnode = udev_device_get_devnode(dev_db);
+ if (devnode != NULL) {
+ if (target == NULL || udev_device_get_devlink_priority(dev_db) > priority) {
+ log_debug("'%s' claims priority %i for '%s'\n",
+ udev_device_get_syspath(dev_db), udev_device_get_devlink_priority(dev_db), stackdir);
+ priority = udev_device_get_devlink_priority(dev_db);
+ strscpy(buf, bufsize, devnode);
+ target = buf;
+ }
+ }
+ udev_device_unref(dev_db);
+ }
+ }
+ closedir(dir);
+ return target;
+}
+
+/* manage "stack of names" with possibly specified device priorities */
+static void link_update(struct udev_device *dev, const char *slink, bool add)
+{
+ struct udev *udev = udev_device_get_udev(dev);
+ char name_enc[UTIL_PATH_SIZE];
+ char filename[UTIL_PATH_SIZE * 2];
+ char dirname[UTIL_PATH_SIZE];
+ const char *target;
+ char buf[UTIL_PATH_SIZE];
+
+ util_path_encode(slink + strlen("/dev"), name_enc, sizeof(name_enc));
+ strscpyl(dirname, sizeof(dirname), "/run/udev/links/", name_enc, NULL);
+ strscpyl(filename, sizeof(filename), dirname, "/", udev_device_get_id_filename(dev), NULL);
+
+ if (!add && unlink(filename) == 0)
+ rmdir(dirname);
+
+ target = link_find_prioritized(dev, add, dirname, buf, sizeof(buf));
+ if (target == NULL) {
+ log_debug("no reference left, remove '%s'\n", slink);
+ if (unlink(slink) == 0)
+ util_delete_path(udev, slink);
+ } else {
+ log_debug("creating link '%s' to '%s'\n", slink, target);
+ node_symlink(dev, target, slink);
+ }
+
+ if (add) {
+ int err;
+
+ do {
+ int fd;
+
+ err = mkdir_parents(filename, 0755);
+ if (err != 0 && err != -ENOENT)
+ break;
+ fd = open(filename, O_WRONLY|O_CREAT|O_CLOEXEC|O_TRUNC|O_NOFOLLOW, 0444);
+ if (fd >= 0)
+ close(fd);
+ else
+ err = -errno;
+ } while (err == -ENOENT);
+ }
+}
+
+void udev_node_update_old_links(struct udev_device *dev, struct udev_device *dev_old)
+{
+ struct udev_list_entry *list_entry;
+
+ /* update possible left-over symlinks */
+ udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(dev_old)) {
+ const char *name = udev_list_entry_get_name(list_entry);
+ struct udev_list_entry *list_entry_current;
+ int found;
+
+ /* check if old link name still belongs to this device */
+ found = 0;
+ udev_list_entry_foreach(list_entry_current, udev_device_get_devlinks_list_entry(dev)) {
+ const char *name_current = udev_list_entry_get_name(list_entry_current);
+
+ if (streq(name, name_current)) {
+ found = 1;
+ break;
+ }
+ }
+ if (found)
+ continue;
+
+ log_debug("update old name, '%s' no longer belonging to '%s'\n",
+ name, udev_device_get_devpath(dev));
+ link_update(dev, name, false);
+ }
+}
+
+static int node_permissions_apply(struct udev_device *dev, bool apply, mode_t mode, uid_t uid, gid_t gid)
+{
+ const char *devnode = udev_device_get_devnode(dev);
+ dev_t devnum = udev_device_get_devnum(dev);
+ struct stat stats;
+ int err = 0;
+
+ if (streq(udev_device_get_subsystem(dev), "block"))
+ mode |= S_IFBLK;
+ else
+ mode |= S_IFCHR;
+
+ if (lstat(devnode, &stats) != 0) {
+ err = -errno;
+ log_debug("can not stat() node '%s' (%m)\n", devnode);
+ goto out;
+ }
+
+ if (((stats.st_mode & S_IFMT) != (mode & S_IFMT)) || (stats.st_rdev != devnum)) {
+ err = -EEXIST;
+ log_debug("found node '%s' with non-matching devnum %s, skip handling\n",
+ udev_device_get_devnode(dev), udev_device_get_id_filename(dev));
+ goto out;
+ }
+
+ if (apply) {
+ if ((stats.st_mode & 0777) != (mode & 0777) || stats.st_uid != uid || stats.st_gid != gid) {
+ log_debug("set permissions %s, %#o, uid=%u, gid=%u\n", devnode, mode, uid, gid);
+ chmod(devnode, mode);
+ chown(devnode, uid, gid);
+ } else {
+ log_debug("preserve permissions %s, %#o, uid=%u, gid=%u\n", devnode, mode, uid, gid);
+ }
+ label_fix(devnode, true, false);
+ }
+
+ /* always update timestamp when we re-use the node, like on media change events */
+ utimensat(AT_FDCWD, devnode, NULL, 0);
+out:
+ return err;
+}
+
+void udev_node_add(struct udev_device *dev, bool apply, mode_t mode, uid_t uid, gid_t gid)
+{
+ char filename[UTIL_PATH_SIZE];
+ struct udev_list_entry *list_entry;
+
+ log_debug("handling device node '%s', devnum=%s, mode=%#o, uid=%d, gid=%d\n",
+ udev_device_get_devnode(dev), udev_device_get_id_filename(dev), mode, uid, gid);
+
+ if (node_permissions_apply(dev, apply, mode, uid, gid) < 0)
+ return;
+
+ /* always add /dev/{block,char}/$major:$minor */
+ snprintf(filename, sizeof(filename), "/dev/%s/%u:%u",
+ streq(udev_device_get_subsystem(dev), "block") ? "block" : "char",
+ major(udev_device_get_devnum(dev)), minor(udev_device_get_devnum(dev)));
+ node_symlink(dev, udev_device_get_devnode(dev), filename);
+
+ /* create/update symlinks, add symlinks to name index */
+ udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(dev))
+ link_update(dev, udev_list_entry_get_name(list_entry), true);
+}
+
+void udev_node_remove(struct udev_device *dev)
+{
+ struct udev_list_entry *list_entry;
+ char filename[UTIL_PATH_SIZE];
+
+ /* remove/update symlinks, remove symlinks from name index */
+ udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(dev))
+ link_update(dev, udev_list_entry_get_name(list_entry), false);
+
+ /* remove /dev/{block,char}/$major:$minor */
+ snprintf(filename, sizeof(filename), "/dev/%s/%u:%u",
+ streq(udev_device_get_subsystem(dev), "block") ? "block" : "char",
+ major(udev_device_get_devnum(dev)), minor(udev_device_get_devnum(dev)));
+ unlink(filename);
+}
diff --git a/src/udev/udev-rules.c b/src/udev/udev-rules.c
new file mode 100644
index 0000000000..7a4fb70258
--- /dev/null
+++ b/src/udev/udev-rules.c
@@ -0,0 +1,2577 @@
+/*
+ * Copyright (C) 2003-2012 Kay Sievers <kay@vrfy.org>
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <stddef.h>
+#include <limits.h>
+#include <stdlib.h>
+#include <stdbool.h>
+#include <string.h>
+#include <stdio.h>
+#include <fcntl.h>
+#include <ctype.h>
+#include <unistd.h>
+#include <errno.h>
+#include <dirent.h>
+#include <fnmatch.h>
+#include <time.h>
+
+#include "udev.h"
+#include "path-util.h"
+#include "conf-files.h"
+#include "strbuf.h"
+
+#define PREALLOC_TOKEN 2048
+
+struct uid_gid {
+ unsigned int name_off;
+ union {
+ uid_t uid;
+ gid_t gid;
+ };
+};
+
+struct udev_rules {
+ struct udev *udev;
+ char **dirs;
+ usec_t *dirs_ts_usec;
+ int resolve_names;
+
+ /* every key in the rules file becomes a token */
+ struct token *tokens;
+ unsigned int token_cur;
+ unsigned int token_max;
+
+ /* all key strings are copied and de-duplicated in a single continuous string buffer */
+ struct strbuf *strbuf;
+
+ /* during rule parsing, uid/gid lookup results are cached */
+ struct uid_gid *uids;
+ unsigned int uids_cur;
+ unsigned int uids_max;
+ struct uid_gid *gids;
+ unsigned int gids_cur;
+ unsigned int gids_max;
+};
+
+static char *rules_str(struct udev_rules *rules, unsigned int off) {
+ return rules->strbuf->buf + off;
+}
+
+static unsigned int rules_add_string(struct udev_rules *rules, const char *s) {
+ return strbuf_add_string(rules->strbuf, s, strlen(s));
+}
+
+/* KEY=="", KEY!="", KEY+="", KEY="", KEY:="" */
+enum operation_type {
+ OP_UNSET,
+
+ OP_MATCH,
+ OP_NOMATCH,
+ OP_MATCH_MAX,
+
+ OP_ADD,
+ OP_ASSIGN,
+ OP_ASSIGN_FINAL,
+};
+
+enum string_glob_type {
+ GL_UNSET,
+ GL_PLAIN, /* no special chars */
+ GL_GLOB, /* shell globs ?,*,[] */
+ GL_SPLIT, /* multi-value A|B */
+ GL_SPLIT_GLOB, /* multi-value with glob A*|B* */
+ GL_SOMETHING, /* commonly used "?*" */
+};
+
+enum string_subst_type {
+ SB_UNSET,
+ SB_NONE,
+ SB_FORMAT,
+ SB_SUBSYS,
+};
+
+/* tokens of a rule are sorted/handled in this order */
+enum token_type {
+ TK_UNSET,
+ TK_RULE,
+
+ TK_M_ACTION, /* val */
+ TK_M_DEVPATH, /* val */
+ TK_M_KERNEL, /* val */
+ TK_M_DEVLINK, /* val */
+ TK_M_NAME, /* val */
+ TK_M_ENV, /* val, attr */
+ TK_M_TAG, /* val */
+ TK_M_SUBSYSTEM, /* val */
+ TK_M_DRIVER, /* val */
+ TK_M_WAITFOR, /* val */
+ TK_M_ATTR, /* val, attr */
+
+ TK_M_PARENTS_MIN,
+ TK_M_KERNELS, /* val */
+ TK_M_SUBSYSTEMS, /* val */
+ TK_M_DRIVERS, /* val */
+ TK_M_ATTRS, /* val, attr */
+ TK_M_TAGS, /* val */
+ TK_M_PARENTS_MAX,
+
+ TK_M_TEST, /* val, mode_t */
+ TK_M_EVENT_TIMEOUT, /* int */
+ TK_M_PROGRAM, /* val */
+ TK_M_IMPORT_FILE, /* val */
+ TK_M_IMPORT_PROG, /* val */
+ TK_M_IMPORT_BUILTIN, /* val */
+ TK_M_IMPORT_DB, /* val */
+ TK_M_IMPORT_CMDLINE, /* val */
+ TK_M_IMPORT_PARENT, /* val */
+ TK_M_RESULT, /* val */
+ TK_M_MAX,
+
+ TK_A_STRING_ESCAPE_NONE,
+ TK_A_STRING_ESCAPE_REPLACE,
+ TK_A_DB_PERSIST,
+ TK_A_INOTIFY_WATCH, /* int */
+ TK_A_DEVLINK_PRIO, /* int */
+ TK_A_OWNER, /* val */
+ TK_A_GROUP, /* val */
+ TK_A_MODE, /* val */
+ TK_A_OWNER_ID, /* uid_t */
+ TK_A_GROUP_ID, /* gid_t */
+ TK_A_MODE_ID, /* mode_t */
+ TK_A_STATIC_NODE, /* val */
+ TK_A_ENV, /* val, attr */
+ TK_A_TAG, /* val */
+ TK_A_NAME, /* val */
+ TK_A_DEVLINK, /* val */
+ TK_A_ATTR, /* val, attr */
+ TK_A_RUN_BUILTIN, /* val, bool */
+ TK_A_RUN_PROGRAM, /* val, bool */
+ TK_A_GOTO, /* size_t */
+
+ TK_END,
+};
+
+/* we try to pack stuff in a way that we take only 12 bytes per token */
+struct token {
+ union {
+ unsigned char type; /* same in rule and key */
+ struct {
+ enum token_type type:8;
+ bool can_set_name:1;
+ bool has_static_node:1;
+ unsigned int unused:6;
+ unsigned short token_count;
+ unsigned int label_off;
+ unsigned short filename_off;
+ unsigned short filename_line;
+ } rule;
+ struct {
+ enum token_type type:8;
+ enum operation_type op:8;
+ enum string_glob_type glob:8;
+ enum string_subst_type subst:4;
+ enum string_subst_type attrsubst:4;
+ unsigned int value_off;
+ union {
+ unsigned int attr_off;
+ unsigned int rule_goto;
+ mode_t mode;
+ uid_t uid;
+ gid_t gid;
+ int devlink_prio;
+ int event_timeout;
+ int watch;
+ enum udev_builtin_cmd builtin_cmd;
+ };
+ } key;
+ };
+};
+
+#define MAX_TK 64
+struct rule_tmp {
+ struct udev_rules *rules;
+ struct token rule;
+ struct token token[MAX_TK];
+ unsigned int token_cur;
+};
+
+#ifdef DEBUG
+static const char *operation_str(enum operation_type type)
+{
+ static const char *operation_strs[] = {
+ [OP_UNSET] = "UNSET",
+ [OP_MATCH] = "match",
+ [OP_NOMATCH] = "nomatch",
+ [OP_MATCH_MAX] = "MATCH_MAX",
+
+ [OP_ADD] = "add",
+ [OP_ASSIGN] = "assign",
+ [OP_ASSIGN_FINAL] = "assign-final",
+} ;
+
+ return operation_strs[type];
+}
+
+static const char *string_glob_str(enum string_glob_type type)
+{
+ static const char *string_glob_strs[] = {
+ [GL_UNSET] = "UNSET",
+ [GL_PLAIN] = "plain",
+ [GL_GLOB] = "glob",
+ [GL_SPLIT] = "split",
+ [GL_SPLIT_GLOB] = "split-glob",
+ [GL_SOMETHING] = "split-glob",
+ };
+
+ return string_glob_strs[type];
+}
+
+static const char *token_str(enum token_type type)
+{
+ static const char *token_strs[] = {
+ [TK_UNSET] = "UNSET",
+ [TK_RULE] = "RULE",
+
+ [TK_M_ACTION] = "M ACTION",
+ [TK_M_DEVPATH] = "M DEVPATH",
+ [TK_M_KERNEL] = "M KERNEL",
+ [TK_M_DEVLINK] = "M DEVLINK",
+ [TK_M_NAME] = "M NAME",
+ [TK_M_ENV] = "M ENV",
+ [TK_M_TAG] = "M TAG",
+ [TK_M_SUBSYSTEM] = "M SUBSYSTEM",
+ [TK_M_DRIVER] = "M DRIVER",
+ [TK_M_WAITFOR] = "M WAITFOR",
+ [TK_M_ATTR] = "M ATTR",
+
+ [TK_M_PARENTS_MIN] = "M PARENTS_MIN",
+ [TK_M_KERNELS] = "M KERNELS",
+ [TK_M_SUBSYSTEMS] = "M SUBSYSTEMS",
+ [TK_M_DRIVERS] = "M DRIVERS",
+ [TK_M_ATTRS] = "M ATTRS",
+ [TK_M_TAGS] = "M TAGS",
+ [TK_M_PARENTS_MAX] = "M PARENTS_MAX",
+
+ [TK_M_TEST] = "M TEST",
+ [TK_M_EVENT_TIMEOUT] = "M EVENT_TIMEOUT",
+ [TK_M_PROGRAM] = "M PROGRAM",
+ [TK_M_IMPORT_FILE] = "M IMPORT_FILE",
+ [TK_M_IMPORT_PROG] = "M IMPORT_PROG",
+ [TK_M_IMPORT_BUILTIN] = "M IMPORT_BUILTIN",
+ [TK_M_IMPORT_DB] = "M IMPORT_DB",
+ [TK_M_IMPORT_CMDLINE] = "M IMPORT_CMDLINE",
+ [TK_M_IMPORT_PARENT] = "M IMPORT_PARENT",
+ [TK_M_RESULT] = "M RESULT",
+ [TK_M_MAX] = "M MAX",
+
+ [TK_A_STRING_ESCAPE_NONE] = "A STRING_ESCAPE_NONE",
+ [TK_A_STRING_ESCAPE_REPLACE] = "A STRING_ESCAPE_REPLACE",
+ [TK_A_DB_PERSIST] = "A DB_PERSIST",
+ [TK_A_INOTIFY_WATCH] = "A INOTIFY_WATCH",
+ [TK_A_DEVLINK_PRIO] = "A DEVLINK_PRIO",
+ [TK_A_OWNER] = "A OWNER",
+ [TK_A_GROUP] = "A GROUP",
+ [TK_A_MODE] = "A MODE",
+ [TK_A_OWNER_ID] = "A OWNER_ID",
+ [TK_A_GROUP_ID] = "A GROUP_ID",
+ [TK_A_STATIC_NODE] = "A STATIC_NODE",
+ [TK_A_MODE_ID] = "A MODE_ID",
+ [TK_A_ENV] = "A ENV",
+ [TK_A_TAG] = "A ENV",
+ [TK_A_NAME] = "A NAME",
+ [TK_A_DEVLINK] = "A DEVLINK",
+ [TK_A_ATTR] = "A ATTR",
+ [TK_A_RUN_BUILTIN] = "A RUN_BUILTIN",
+ [TK_A_RUN_PROGRAM] = "A RUN_PROGRAM",
+ [TK_A_GOTO] = "A GOTO",
+
+ [TK_END] = "END",
+ };
+
+ return token_strs[type];
+}
+
+static void dump_token(struct udev_rules *rules, struct token *token)
+{
+ enum token_type type = token->type;
+ enum operation_type op = token->key.op;
+ enum string_glob_type glob = token->key.glob;
+ const char *value = str(rules, token->key.value_off);
+ const char *attr = &rules->buf[token->key.attr_off];
+
+ switch (type) {
+ case TK_RULE:
+ {
+ const char *tks_ptr = (char *)rules->tokens;
+ const char *tk_ptr = (char *)token;
+ unsigned int idx = (tk_ptr - tks_ptr) / sizeof(struct token);
+
+ log_debug("* RULE %s:%u, token: %u, count: %u, label: '%s'\n",
+ &rules->buf[token->rule.filename_off], token->rule.filename_line,
+ idx, token->rule.token_count,
+ &rules->buf[token->rule.label_off]);
+ break;
+ }
+ case TK_M_ACTION:
+ case TK_M_DEVPATH:
+ case TK_M_KERNEL:
+ case TK_M_SUBSYSTEM:
+ case TK_M_DRIVER:
+ case TK_M_WAITFOR:
+ case TK_M_DEVLINK:
+ case TK_M_NAME:
+ case TK_M_KERNELS:
+ case TK_M_SUBSYSTEMS:
+ case TK_M_DRIVERS:
+ case TK_M_TAGS:
+ case TK_M_PROGRAM:
+ case TK_M_IMPORT_FILE:
+ case TK_M_IMPORT_PROG:
+ case TK_M_IMPORT_DB:
+ case TK_M_IMPORT_CMDLINE:
+ case TK_M_IMPORT_PARENT:
+ case TK_M_RESULT:
+ case TK_A_NAME:
+ case TK_A_DEVLINK:
+ case TK_A_OWNER:
+ case TK_A_GROUP:
+ case TK_A_MODE:
+ case TK_A_RUN_BUILTIN:
+ case TK_A_RUN_PROGRAM:
+ log_debug("%s %s '%s'(%s)\n",
+ token_str(type), operation_str(op), value, string_glob_str(glob));
+ break;
+ case TK_M_IMPORT_BUILTIN:
+ log_debug("%s %i '%s'\n", token_str(type), token->key.builtin_cmd, value);
+ break;
+ case TK_M_ATTR:
+ case TK_M_ATTRS:
+ case TK_M_ENV:
+ case TK_A_ATTR:
+ case TK_A_ENV:
+ log_debug("%s %s '%s' '%s'(%s)\n",
+ token_str(type), operation_str(op), attr, value, string_glob_str(glob));
+ break;
+ case TK_M_TAG:
+ case TK_A_TAG:
+ log_debug("%s %s '%s'\n", token_str(type), operation_str(op), value);
+ break;
+ case TK_A_STRING_ESCAPE_NONE:
+ case TK_A_STRING_ESCAPE_REPLACE:
+ case TK_A_DB_PERSIST:
+ log_debug("%s\n", token_str(type));
+ break;
+ case TK_M_TEST:
+ log_debug("%s %s '%s'(%s) %#o\n",
+ token_str(type), operation_str(op), value, string_glob_str(glob), token->key.mode);
+ break;
+ case TK_A_INOTIFY_WATCH:
+ log_debug("%s %u\n", token_str(type), token->key.watch);
+ break;
+ case TK_A_DEVLINK_PRIO:
+ log_debug("%s %u\n", token_str(type), token->key.devlink_prio);
+ break;
+ case TK_A_OWNER_ID:
+ log_debug("%s %s %u\n", token_str(type), operation_str(op), token->key.uid);
+ break;
+ case TK_A_GROUP_ID:
+ log_debug("%s %s %u\n", token_str(type), operation_str(op), token->key.gid);
+ break;
+ case TK_A_MODE_ID:
+ log_debug("%s %s %#o\n", token_str(type), operation_str(op), token->key.mode);
+ break;
+ case TK_A_STATIC_NODE:
+ log_debug("%s '%s'\n", token_str(type), value);
+ break;
+ case TK_M_EVENT_TIMEOUT:
+ log_debug("%s %u\n", token_str(type), token->key.event_timeout);
+ break;
+ case TK_A_GOTO:
+ log_debug("%s '%s' %u\n", token_str(type), value, token->key.rule_goto);
+ break;
+ case TK_END:
+ log_debug("* %s\n", token_str(type));
+ break;
+ case TK_M_PARENTS_MIN:
+ case TK_M_PARENTS_MAX:
+ case TK_M_MAX:
+ case TK_UNSET:
+ log_debug("unknown type %u\n", type);
+ break;
+ }
+}
+
+static void dump_rules(struct udev_rules *rules)
+{
+ unsigned int i;
+
+ log_debug("dumping %u (%zu bytes) tokens, %u (%zu bytes) strings\n",
+ rules->token_cur,
+ rules->token_cur * sizeof(struct token),
+ rules->buf_count,
+ rules->buf_cur);
+ for(i = 0; i < rules->token_cur; i++)
+ dump_token(rules, &rules->tokens[i]);
+}
+#else
+static inline const char *operation_str(enum operation_type type) { return NULL; }
+static inline const char *token_str(enum token_type type) { return NULL; }
+static inline void dump_token(struct udev_rules *rules, struct token *token) {}
+static inline void dump_rules(struct udev_rules *rules) {}
+#endif /* DEBUG */
+
+static int add_token(struct udev_rules *rules, struct token *token)
+{
+ /* grow buffer if needed */
+ if (rules->token_cur+1 >= rules->token_max) {
+ struct token *tokens;
+ unsigned int add;
+
+ /* double the buffer size */
+ add = rules->token_max;
+ if (add < 8)
+ add = 8;
+
+ tokens = realloc(rules->tokens, (rules->token_max + add ) * sizeof(struct token));
+ if (tokens == NULL)
+ return -1;
+ rules->tokens = tokens;
+ rules->token_max += add;
+ }
+ memcpy(&rules->tokens[rules->token_cur], token, sizeof(struct token));
+ rules->token_cur++;
+ return 0;
+}
+
+static uid_t add_uid(struct udev_rules *rules, const char *owner)
+{
+ unsigned int i;
+ uid_t uid;
+ unsigned int off;
+
+ /* lookup, if we know it already */
+ for (i = 0; i < rules->uids_cur; i++) {
+ off = rules->uids[i].name_off;
+ if (streq(rules_str(rules, off), owner)) {
+ uid = rules->uids[i].uid;
+ return uid;
+ }
+ }
+ uid = util_lookup_user(rules->udev, owner);
+
+ /* grow buffer if needed */
+ if (rules->uids_cur+1 >= rules->uids_max) {
+ struct uid_gid *uids;
+ unsigned int add;
+
+ /* double the buffer size */
+ add = rules->uids_max;
+ if (add < 1)
+ add = 8;
+
+ uids = realloc(rules->uids, (rules->uids_max + add ) * sizeof(struct uid_gid));
+ if (uids == NULL)
+ return uid;
+ rules->uids = uids;
+ rules->uids_max += add;
+ }
+ rules->uids[rules->uids_cur].uid = uid;
+ off = rules_add_string(rules, owner);
+ if (off <= 0)
+ return uid;
+ rules->uids[rules->uids_cur].name_off = off;
+ rules->uids_cur++;
+ return uid;
+}
+
+static gid_t add_gid(struct udev_rules *rules, const char *group)
+{
+ unsigned int i;
+ gid_t gid;
+ unsigned int off;
+
+ /* lookup, if we know it already */
+ for (i = 0; i < rules->gids_cur; i++) {
+ off = rules->gids[i].name_off;
+ if (streq(rules_str(rules, off), group)) {
+ gid = rules->gids[i].gid;
+ return gid;
+ }
+ }
+ gid = util_lookup_group(rules->udev, group);
+
+ /* grow buffer if needed */
+ if (rules->gids_cur+1 >= rules->gids_max) {
+ struct uid_gid *gids;
+ unsigned int add;
+
+ /* double the buffer size */
+ add = rules->gids_max;
+ if (add < 1)
+ add = 8;
+
+ gids = realloc(rules->gids, (rules->gids_max + add ) * sizeof(struct uid_gid));
+ if (gids == NULL)
+ return gid;
+ rules->gids = gids;
+ rules->gids_max += add;
+ }
+ rules->gids[rules->gids_cur].gid = gid;
+ off = rules_add_string(rules, group);
+ if (off <= 0)
+ return gid;
+ rules->gids[rules->gids_cur].name_off = off;
+ rules->gids_cur++;
+ return gid;
+}
+
+static int import_property_from_string(struct udev_device *dev, char *line)
+{
+ char *key;
+ char *val;
+ size_t len;
+
+ /* find key */
+ key = line;
+ while (isspace(key[0]))
+ key++;
+
+ /* comment or empty line */
+ if (key[0] == '#' || key[0] == '\0')
+ return -1;
+
+ /* split key/value */
+ val = strchr(key, '=');
+ if (val == NULL)
+ return -1;
+ val[0] = '\0';
+ val++;
+
+ /* find value */
+ while (isspace(val[0]))
+ val++;
+
+ /* terminate key */
+ len = strlen(key);
+ if (len == 0)
+ return -1;
+ while (isspace(key[len-1]))
+ len--;
+ key[len] = '\0';
+
+ /* terminate value */
+ len = strlen(val);
+ if (len == 0)
+ return -1;
+ while (isspace(val[len-1]))
+ len--;
+ val[len] = '\0';
+
+ if (len == 0)
+ return -1;
+
+ /* unquote */
+ if (val[0] == '"' || val[0] == '\'') {
+ if (val[len-1] != val[0]) {
+ log_debug("inconsistent quoting: '%s', skip\n", line);
+ return -1;
+ }
+ val[len-1] = '\0';
+ val++;
+ }
+
+ /* handle device, renamed by external tool, returning new path */
+ if (streq(key, "DEVPATH")) {
+ char syspath[UTIL_PATH_SIZE];
+
+ log_debug("updating devpath from '%s' to '%s'\n",
+ udev_device_get_devpath(dev), val);
+ strscpyl(syspath, sizeof(syspath), "/sys", val, NULL);
+ udev_device_set_syspath(dev, syspath);
+ } else {
+ struct udev_list_entry *entry;
+
+ entry = udev_device_add_property(dev, key, val);
+ /* store in db, skip private keys */
+ if (key[0] != '.')
+ udev_list_entry_set_num(entry, true);
+ }
+ return 0;
+}
+
+static int import_file_into_properties(struct udev_device *dev, const char *filename)
+{
+ FILE *f;
+ char line[UTIL_LINE_SIZE];
+
+ f = fopen(filename, "re");
+ if (f == NULL)
+ return -1;
+ while (fgets(line, sizeof(line), f) != NULL)
+ import_property_from_string(dev, line);
+ fclose(f);
+ return 0;
+}
+
+static int import_program_into_properties(struct udev_event *event, const char *program, const sigset_t *sigmask)
+{
+ struct udev_device *dev = event->dev;
+ char **envp;
+ char result[UTIL_LINE_SIZE];
+ char *line;
+ int err;
+
+ envp = udev_device_get_properties_envp(dev);
+ err = udev_event_spawn(event, program, envp, sigmask, result, sizeof(result));
+ if (err < 0)
+ return err;
+
+ line = result;
+ while (line != NULL) {
+ char *pos;
+
+ pos = strchr(line, '\n');
+ if (pos != NULL) {
+ pos[0] = '\0';
+ pos = &pos[1];
+ }
+ import_property_from_string(dev, line);
+ line = pos;
+ }
+ return 0;
+}
+
+static int import_parent_into_properties(struct udev_device *dev, const char *filter)
+{
+ struct udev_device *dev_parent;
+ struct udev_list_entry *list_entry;
+
+ dev_parent = udev_device_get_parent(dev);
+ if (dev_parent == NULL)
+ return -1;
+
+ udev_list_entry_foreach(list_entry, udev_device_get_properties_list_entry(dev_parent)) {
+ const char *key = udev_list_entry_get_name(list_entry);
+ const char *val = udev_list_entry_get_value(list_entry);
+
+ if (fnmatch(filter, key, 0) == 0) {
+ struct udev_list_entry *entry;
+
+ entry = udev_device_add_property(dev, key, val);
+ /* store in db, skip private keys */
+ if (key[0] != '.')
+ udev_list_entry_set_num(entry, true);
+ }
+ }
+ return 0;
+}
+
+#define WAIT_LOOP_PER_SECOND 50
+static int wait_for_file(struct udev_device *dev, const char *file, int timeout)
+{
+ char filepath[UTIL_PATH_SIZE];
+ char devicepath[UTIL_PATH_SIZE];
+ struct stat stats;
+ int loop = timeout * WAIT_LOOP_PER_SECOND;
+
+ /* a relative path is a device attribute */
+ devicepath[0] = '\0';
+ if (file[0] != '/') {
+ strscpyl(devicepath, sizeof(devicepath), udev_device_get_syspath(dev), NULL);
+ strscpyl(filepath, sizeof(filepath), devicepath, "/", file, NULL);
+ file = filepath;
+ }
+
+ while (--loop) {
+ const struct timespec duration = { 0, 1000 * 1000 * 1000 / WAIT_LOOP_PER_SECOND };
+
+ /* lookup file */
+ if (stat(file, &stats) == 0) {
+ log_debug("file '%s' appeared after %i loops\n", file, (timeout * WAIT_LOOP_PER_SECOND) - loop-1);
+ return 0;
+ }
+ /* make sure, the device did not disappear in the meantime */
+ if (devicepath[0] != '\0' && stat(devicepath, &stats) != 0) {
+ log_debug("device disappeared while waiting for '%s'\n", file);
+ return -2;
+ }
+ log_debug("wait for '%s' for %i mseconds\n", file, 1000 / WAIT_LOOP_PER_SECOND);
+ nanosleep(&duration, NULL);
+ }
+ log_debug("waiting for '%s' failed\n", file);
+ return -1;
+}
+
+static int attr_subst_subdir(char *attr, size_t len)
+{
+ bool found = false;
+
+ if (strstr(attr, "/*/")) {
+ char *pos;
+ char dirname[UTIL_PATH_SIZE];
+ const char *tail;
+ DIR *dir;
+
+ strscpy(dirname, sizeof(dirname), attr);
+ pos = strstr(dirname, "/*/");
+ if (pos == NULL)
+ return -1;
+ pos[0] = '\0';
+ tail = &pos[2];
+ dir = opendir(dirname);
+ if (dir != NULL) {
+ struct dirent *dent;
+
+ for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
+ struct stat stats;
+
+ if (dent->d_name[0] == '.')
+ continue;
+ strscpyl(attr, len, dirname, "/", dent->d_name, tail, NULL);
+ if (stat(attr, &stats) == 0) {
+ found = true;
+ break;
+ }
+ }
+ closedir(dir);
+ }
+ }
+
+ return found;
+}
+
+static int get_key(struct udev *udev, char **line, char **key, enum operation_type *op, char **value)
+{
+ char *linepos;
+ char *temp;
+
+ linepos = *line;
+ if (linepos == NULL || linepos[0] == '\0')
+ return -1;
+
+ /* skip whitespace */
+ while (isspace(linepos[0]) || linepos[0] == ',')
+ linepos++;
+
+ /* get the key */
+ if (linepos[0] == '\0')
+ return -1;
+ *key = linepos;
+
+ for (;;) {
+ linepos++;
+ if (linepos[0] == '\0')
+ return -1;
+ if (isspace(linepos[0]))
+ break;
+ if (linepos[0] == '=')
+ break;
+ if ((linepos[0] == '+') || (linepos[0] == '!') || (linepos[0] == ':'))
+ if (linepos[1] == '=')
+ break;
+ }
+
+ /* remember end of key */
+ temp = linepos;
+
+ /* skip whitespace after key */
+ while (isspace(linepos[0]))
+ linepos++;
+ if (linepos[0] == '\0')
+ return -1;
+
+ /* get operation type */
+ if (linepos[0] == '=' && linepos[1] == '=') {
+ *op = OP_MATCH;
+ linepos += 2;
+ } else if (linepos[0] == '!' && linepos[1] == '=') {
+ *op = OP_NOMATCH;
+ linepos += 2;
+ } else if (linepos[0] == '+' && linepos[1] == '=') {
+ *op = OP_ADD;
+ linepos += 2;
+ } else if (linepos[0] == '=') {
+ *op = OP_ASSIGN;
+ linepos++;
+ } else if (linepos[0] == ':' && linepos[1] == '=') {
+ *op = OP_ASSIGN_FINAL;
+ linepos += 2;
+ } else
+ return -1;
+
+ /* terminate key */
+ temp[0] = '\0';
+
+ /* skip whitespace after operator */
+ while (isspace(linepos[0]))
+ linepos++;
+ if (linepos[0] == '\0')
+ return -1;
+
+ /* get the value */
+ if (linepos[0] == '"')
+ linepos++;
+ else
+ return -1;
+ *value = linepos;
+
+ /* terminate */
+ temp = strchr(linepos, '"');
+ if (!temp)
+ return -1;
+ temp[0] = '\0';
+ temp++;
+
+ /* move line to next key */
+ *line = temp;
+ return 0;
+}
+
+/* extract possible KEY{attr} */
+static const char *get_key_attribute(struct udev *udev, char *str)
+{
+ char *pos;
+ char *attr;
+
+ attr = strchr(str, '{');
+ if (attr != NULL) {
+ attr++;
+ pos = strchr(attr, '}');
+ if (pos == NULL) {
+ log_error("missing closing brace for format\n");
+ return NULL;
+ }
+ pos[0] = '\0';
+ return attr;
+ }
+ return NULL;
+}
+
+static int rule_add_key(struct rule_tmp *rule_tmp, enum token_type type,
+ enum operation_type op,
+ const char *value, const void *data)
+{
+ struct token *token = &rule_tmp->token[rule_tmp->token_cur];
+ const char *attr = NULL;
+
+ memset(token, 0x00, sizeof(struct token));
+
+ switch (type) {
+ case TK_M_ACTION:
+ case TK_M_DEVPATH:
+ case TK_M_KERNEL:
+ case TK_M_SUBSYSTEM:
+ case TK_M_DRIVER:
+ case TK_M_WAITFOR:
+ case TK_M_DEVLINK:
+ case TK_M_NAME:
+ case TK_M_KERNELS:
+ case TK_M_SUBSYSTEMS:
+ case TK_M_DRIVERS:
+ case TK_M_TAGS:
+ case TK_M_PROGRAM:
+ case TK_M_IMPORT_FILE:
+ case TK_M_IMPORT_PROG:
+ case TK_M_IMPORT_DB:
+ case TK_M_IMPORT_CMDLINE:
+ case TK_M_IMPORT_PARENT:
+ case TK_M_RESULT:
+ case TK_A_OWNER:
+ case TK_A_GROUP:
+ case TK_A_MODE:
+ case TK_A_DEVLINK:
+ case TK_A_NAME:
+ case TK_A_GOTO:
+ case TK_M_TAG:
+ case TK_A_TAG:
+ token->key.value_off = rules_add_string(rule_tmp->rules, value);
+ break;
+ case TK_M_IMPORT_BUILTIN:
+ token->key.value_off = rules_add_string(rule_tmp->rules, value);
+ token->key.builtin_cmd = *(enum udev_builtin_cmd *)data;
+ break;
+ case TK_M_ENV:
+ case TK_M_ATTR:
+ case TK_M_ATTRS:
+ case TK_A_ATTR:
+ case TK_A_ENV:
+ attr = data;
+ token->key.value_off = rules_add_string(rule_tmp->rules, value);
+ token->key.attr_off = rules_add_string(rule_tmp->rules, attr);
+ break;
+ case TK_M_TEST:
+ token->key.value_off = rules_add_string(rule_tmp->rules, value);
+ if (data != NULL)
+ token->key.mode = *(mode_t *)data;
+ break;
+ case TK_A_STRING_ESCAPE_NONE:
+ case TK_A_STRING_ESCAPE_REPLACE:
+ case TK_A_DB_PERSIST:
+ break;
+ case TK_A_RUN_BUILTIN:
+ case TK_A_RUN_PROGRAM:
+ token->key.builtin_cmd = *(enum udev_builtin_cmd *)data;
+ token->key.value_off = rules_add_string(rule_tmp->rules, value);
+ break;
+ case TK_A_INOTIFY_WATCH:
+ case TK_A_DEVLINK_PRIO:
+ token->key.devlink_prio = *(int *)data;
+ break;
+ case TK_A_OWNER_ID:
+ token->key.uid = *(uid_t *)data;
+ break;
+ case TK_A_GROUP_ID:
+ token->key.gid = *(gid_t *)data;
+ break;
+ case TK_A_MODE_ID:
+ token->key.mode = *(mode_t *)data;
+ break;
+ case TK_A_STATIC_NODE:
+ token->key.value_off = rules_add_string(rule_tmp->rules, value);
+ break;
+ case TK_M_EVENT_TIMEOUT:
+ token->key.event_timeout = *(int *)data;
+ break;
+ case TK_RULE:
+ case TK_M_PARENTS_MIN:
+ case TK_M_PARENTS_MAX:
+ case TK_M_MAX:
+ case TK_END:
+ case TK_UNSET:
+ log_error("wrong type %u\n", type);
+ return -1;
+ }
+
+ if (value != NULL && type < TK_M_MAX) {
+ /* check if we need to split or call fnmatch() while matching rules */
+ enum string_glob_type glob;
+ int has_split;
+ int has_glob;
+
+ has_split = (strchr(value, '|') != NULL);
+ has_glob = (strchr(value, '*') != NULL || strchr(value, '?') != NULL || strchr(value, '[') != NULL);
+ if (has_split && has_glob) {
+ glob = GL_SPLIT_GLOB;
+ } else if (has_split) {
+ glob = GL_SPLIT;
+ } else if (has_glob) {
+ if (streq(value, "?*"))
+ glob = GL_SOMETHING;
+ else
+ glob = GL_GLOB;
+ } else {
+ glob = GL_PLAIN;
+ }
+ token->key.glob = glob;
+ }
+
+ if (value != NULL && type > TK_M_MAX) {
+ /* check if assigned value has substitution chars */
+ if (value[0] == '[')
+ token->key.subst = SB_SUBSYS;
+ else if (strchr(value, '%') != NULL || strchr(value, '$') != NULL)
+ token->key.subst = SB_FORMAT;
+ else
+ token->key.subst = SB_NONE;
+ }
+
+ if (attr != NULL) {
+ /* check if property/attribut name has substitution chars */
+ if (attr[0] == '[')
+ token->key.attrsubst = SB_SUBSYS;
+ else if (strchr(attr, '%') != NULL || strchr(attr, '$') != NULL)
+ token->key.attrsubst = SB_FORMAT;
+ else
+ token->key.attrsubst = SB_NONE;
+ }
+
+ token->key.type = type;
+ token->key.op = op;
+ rule_tmp->token_cur++;
+ if (rule_tmp->token_cur >= ELEMENTSOF(rule_tmp->token)) {
+ log_error("temporary rule array too small\n");
+ return -1;
+ }
+ return 0;
+}
+
+static int sort_token(struct udev_rules *rules, struct rule_tmp *rule_tmp)
+{
+ unsigned int i;
+ unsigned int start = 0;
+ unsigned int end = rule_tmp->token_cur;
+
+ for (i = 0; i < rule_tmp->token_cur; i++) {
+ enum token_type next_val = TK_UNSET;
+ unsigned int next_idx = 0;
+ unsigned int j;
+
+ /* find smallest value */
+ for (j = start; j < end; j++) {
+ if (rule_tmp->token[j].type == TK_UNSET)
+ continue;
+ if (next_val == TK_UNSET || rule_tmp->token[j].type < next_val) {
+ next_val = rule_tmp->token[j].type;
+ next_idx = j;
+ }
+ }
+
+ /* add token and mark done */
+ if (add_token(rules, &rule_tmp->token[next_idx]) != 0)
+ return -1;
+ rule_tmp->token[next_idx].type = TK_UNSET;
+
+ /* shrink range */
+ if (next_idx == start)
+ start++;
+ if (next_idx+1 == end)
+ end--;
+ }
+ return 0;
+}
+
+static int add_rule(struct udev_rules *rules, char *line,
+ const char *filename, unsigned int filename_off, unsigned int lineno)
+{
+ char *linepos;
+ const char *attr;
+ struct rule_tmp rule_tmp;
+
+ memset(&rule_tmp, 0x00, sizeof(struct rule_tmp));
+ rule_tmp.rules = rules;
+ rule_tmp.rule.type = TK_RULE;
+ /* the offset in the rule is limited to unsigned short */
+ if (filename_off < USHRT_MAX)
+ rule_tmp.rule.rule.filename_off = filename_off;
+ rule_tmp.rule.rule.filename_line = lineno;
+
+ linepos = line;
+ for (;;) {
+ char *key;
+ char *value;
+ enum operation_type op;
+
+ if (get_key(rules->udev, &linepos, &key, &op, &value) != 0)
+ break;
+
+ if (streq(key, "ACTION")) {
+ if (op > OP_MATCH_MAX) {
+ log_error("invalid ACTION operation\n");
+ goto invalid;
+ }
+ rule_add_key(&rule_tmp, TK_M_ACTION, op, value, NULL);
+ continue;
+ }
+
+ if (streq(key, "DEVPATH")) {
+ if (op > OP_MATCH_MAX) {
+ log_error("invalid DEVPATH operation\n");
+ goto invalid;
+ }
+ rule_add_key(&rule_tmp, TK_M_DEVPATH, op, value, NULL);
+ continue;
+ }
+
+ if (streq(key, "KERNEL")) {
+ if (op > OP_MATCH_MAX) {
+ log_error("invalid KERNEL operation\n");
+ goto invalid;
+ }
+ rule_add_key(&rule_tmp, TK_M_KERNEL, op, value, NULL);
+ continue;
+ }
+
+ if (streq(key, "SUBSYSTEM")) {
+ if (op > OP_MATCH_MAX) {
+ log_error("invalid SUBSYSTEM operation\n");
+ goto invalid;
+ }
+ /* bus, class, subsystem events should all be the same */
+ if (streq(value, "subsystem") ||
+ streq(value, "bus") ||
+ streq(value, "class")) {
+ if (streq(value, "bus") || streq(value, "class"))
+ log_error("'%s' must be specified as 'subsystem' \n"
+ "please fix it in %s:%u", value, filename, lineno);
+ rule_add_key(&rule_tmp, TK_M_SUBSYSTEM, op, "subsystem|class|bus", NULL);
+ } else
+ rule_add_key(&rule_tmp, TK_M_SUBSYSTEM, op, value, NULL);
+ continue;
+ }
+
+ if (streq(key, "DRIVER")) {
+ if (op > OP_MATCH_MAX) {
+ log_error("invalid DRIVER operation\n");
+ goto invalid;
+ }
+ rule_add_key(&rule_tmp, TK_M_DRIVER, op, value, NULL);
+ continue;
+ }
+
+ if (startswith(key, "ATTR{")) {
+ attr = get_key_attribute(rules->udev, key + sizeof("ATTR")-1);
+ if (attr == NULL) {
+ log_error("error parsing ATTR attribute\n");
+ goto invalid;
+ }
+ if (op < OP_MATCH_MAX) {
+ rule_add_key(&rule_tmp, TK_M_ATTR, op, value, attr);
+ } else {
+ rule_add_key(&rule_tmp, TK_A_ATTR, op, value, attr);
+ }
+ continue;
+ }
+
+ if (streq(key, "KERNELS")) {
+ if (op > OP_MATCH_MAX) {
+ log_error("invalid KERNELS operation\n");
+ goto invalid;
+ }
+ rule_add_key(&rule_tmp, TK_M_KERNELS, op, value, NULL);
+ continue;
+ }
+
+ if (streq(key, "SUBSYSTEMS")) {
+ if (op > OP_MATCH_MAX) {
+ log_error("invalid SUBSYSTEMS operation\n");
+ goto invalid;
+ }
+ rule_add_key(&rule_tmp, TK_M_SUBSYSTEMS, op, value, NULL);
+ continue;
+ }
+
+ if (streq(key, "DRIVERS")) {
+ if (op > OP_MATCH_MAX) {
+ log_error("invalid DRIVERS operation\n");
+ goto invalid;
+ }
+ rule_add_key(&rule_tmp, TK_M_DRIVERS, op, value, NULL);
+ continue;
+ }
+
+ if (startswith(key, "ATTRS{")) {
+ if (op > OP_MATCH_MAX) {
+ log_error("invalid ATTRS operation\n");
+ goto invalid;
+ }
+ attr = get_key_attribute(rules->udev, key + sizeof("ATTRS")-1);
+ if (attr == NULL) {
+ log_error("error parsing ATTRS attribute\n");
+ goto invalid;
+ }
+ if (startswith(attr, "device/"))
+ log_error("the 'device' link may not be available in a future kernel, "
+ "please fix it in %s:%u", filename, lineno);
+ else if (strstr(attr, "../") != NULL)
+ log_error("do not reference parent sysfs directories directly, "
+ "it may break with a future kernel, please fix it in %s:%u", filename, lineno);
+ rule_add_key(&rule_tmp, TK_M_ATTRS, op, value, attr);
+ continue;
+ }
+
+ if (streq(key, "TAGS")) {
+ if (op > OP_MATCH_MAX) {
+ log_error("invalid TAGS operation\n");
+ goto invalid;
+ }
+ rule_add_key(&rule_tmp, TK_M_TAGS, op, value, NULL);
+ continue;
+ }
+
+ if (startswith(key, "ENV{")) {
+ attr = get_key_attribute(rules->udev, key + sizeof("ENV")-1);
+ if (attr == NULL) {
+ log_error("error parsing ENV attribute\n");
+ goto invalid;
+ }
+ if (op < OP_MATCH_MAX) {
+ if (rule_add_key(&rule_tmp, TK_M_ENV, op, value, attr) != 0)
+ goto invalid;
+ } else {
+ static const char *blacklist[] = {
+ "ACTION",
+ "SUBSYSTEM",
+ "DEVTYPE",
+ "MAJOR",
+ "MINOR",
+ "DRIVER",
+ "IFINDEX",
+ "DEVNAME",
+ "DEVLINKS",
+ "DEVPATH",
+ "TAGS",
+ };
+ unsigned int i;
+
+ for (i = 0; i < ELEMENTSOF(blacklist); i++) {
+ if (!streq(attr, blacklist[i]))
+ continue;
+ log_error("invalid ENV attribute, '%s' can not be set %s:%u\n", attr, filename, lineno);
+ goto invalid;
+ }
+ if (rule_add_key(&rule_tmp, TK_A_ENV, op, value, attr) != 0)
+ goto invalid;
+ }
+ continue;
+ }
+
+ if (streq(key, "TAG")) {
+ if (op < OP_MATCH_MAX)
+ rule_add_key(&rule_tmp, TK_M_TAG, op, value, NULL);
+ else
+ rule_add_key(&rule_tmp, TK_A_TAG, op, value, NULL);
+ continue;
+ }
+
+ if (streq(key, "PROGRAM")) {
+ rule_add_key(&rule_tmp, TK_M_PROGRAM, op, value, NULL);
+ continue;
+ }
+
+ if (streq(key, "RESULT")) {
+ if (op > OP_MATCH_MAX) {
+ log_error("invalid RESULT operation\n");
+ goto invalid;
+ }
+ rule_add_key(&rule_tmp, TK_M_RESULT, op, value, NULL);
+ continue;
+ }
+
+ if (startswith(key, "IMPORT")) {
+ attr = get_key_attribute(rules->udev, key + sizeof("IMPORT")-1);
+ if (attr == NULL) {
+ log_error("IMPORT{} type missing, ignoring IMPORT %s:%u\n", filename, lineno);
+ continue;
+ }
+ if (streq(attr, "program")) {
+ /* find known built-in command */
+ if (value[0] != '/') {
+ enum udev_builtin_cmd cmd;
+
+ cmd = udev_builtin_lookup(value);
+ if (cmd < UDEV_BUILTIN_MAX) {
+ log_debug("IMPORT found builtin '%s', replacing %s:%u\n",
+ value, filename, lineno);
+ rule_add_key(&rule_tmp, TK_M_IMPORT_BUILTIN, op, value, &cmd);
+ continue;
+ }
+ }
+ rule_add_key(&rule_tmp, TK_M_IMPORT_PROG, op, value, NULL);
+ } else if (streq(attr, "builtin")) {
+ enum udev_builtin_cmd cmd = udev_builtin_lookup(value);
+
+ if (cmd < UDEV_BUILTIN_MAX)
+ rule_add_key(&rule_tmp, TK_M_IMPORT_BUILTIN, op, value, &cmd);
+ else
+ log_error("IMPORT{builtin}: '%s' unknown %s:%u\n", value, filename, lineno);
+ } else if (streq(attr, "file")) {
+ rule_add_key(&rule_tmp, TK_M_IMPORT_FILE, op, value, NULL);
+ } else if (streq(attr, "db")) {
+ rule_add_key(&rule_tmp, TK_M_IMPORT_DB, op, value, NULL);
+ } else if (streq(attr, "cmdline")) {
+ rule_add_key(&rule_tmp, TK_M_IMPORT_CMDLINE, op, value, NULL);
+ } else if (streq(attr, "parent")) {
+ rule_add_key(&rule_tmp, TK_M_IMPORT_PARENT, op, value, NULL);
+ } else
+ log_error("IMPORT{} unknown type, ignoring IMPORT %s:%u\n", filename, lineno);
+ continue;
+ }
+
+ if (startswith(key, "TEST")) {
+ mode_t mode = 0;
+
+ if (op > OP_MATCH_MAX) {
+ log_error("invalid TEST operation\n");
+ goto invalid;
+ }
+ attr = get_key_attribute(rules->udev, key + sizeof("TEST")-1);
+ if (attr != NULL) {
+ mode = strtol(attr, NULL, 8);
+ rule_add_key(&rule_tmp, TK_M_TEST, op, value, &mode);
+ } else {
+ rule_add_key(&rule_tmp, TK_M_TEST, op, value, NULL);
+ }
+ continue;
+ }
+
+ if (startswith(key, "RUN")) {
+ attr = get_key_attribute(rules->udev, key + sizeof("RUN")-1);
+ if (attr == NULL)
+ attr = "program";
+
+ if (streq(attr, "builtin")) {
+ enum udev_builtin_cmd cmd = udev_builtin_lookup(value);
+
+ if (cmd < UDEV_BUILTIN_MAX)
+ rule_add_key(&rule_tmp, TK_A_RUN_BUILTIN, op, value, &cmd);
+ else
+ log_error("IMPORT{builtin}: '%s' unknown %s:%u\n", value, filename, lineno);
+ } else if (streq(attr, "program")) {
+ enum udev_builtin_cmd cmd = UDEV_BUILTIN_MAX;
+
+ rule_add_key(&rule_tmp, TK_A_RUN_PROGRAM, op, value, &cmd);
+ } else {
+ log_error("RUN{} unknown type, ignoring RUN %s:%u\n", filename, lineno);
+ }
+
+ continue;
+ }
+
+ if (streq(key, "WAIT_FOR") || streq(key, "WAIT_FOR_SYSFS")) {
+ rule_add_key(&rule_tmp, TK_M_WAITFOR, 0, value, NULL);
+ continue;
+ }
+
+ if (streq(key, "LABEL")) {
+ rule_tmp.rule.rule.label_off = rules_add_string(rules, value);
+ continue;
+ }
+
+ if (streq(key, "GOTO")) {
+ rule_add_key(&rule_tmp, TK_A_GOTO, 0, value, NULL);
+ continue;
+ }
+
+ if (startswith(key, "NAME")) {
+ if (op < OP_MATCH_MAX) {
+ rule_add_key(&rule_tmp, TK_M_NAME, op, value, NULL);
+ } else {
+ if (streq(value, "%k")) {
+ log_error("NAME=\"%%k\" is ignored, because it breaks kernel supplied names, "
+ "please remove it from %s:%u\n", filename, lineno);
+ continue;
+ }
+ if (value[0] == '\0') {
+ log_debug("NAME=\"\" is ignored, because udev will not delete any device nodes, "
+ "please remove it from %s:%u\n", filename, lineno);
+ continue;
+ }
+ rule_add_key(&rule_tmp, TK_A_NAME, op, value, NULL);
+ }
+ rule_tmp.rule.rule.can_set_name = true;
+ continue;
+ }
+
+ if (streq(key, "SYMLINK")) {
+ if (op < OP_MATCH_MAX)
+ rule_add_key(&rule_tmp, TK_M_DEVLINK, op, value, NULL);
+ else
+ rule_add_key(&rule_tmp, TK_A_DEVLINK, op, value, NULL);
+ rule_tmp.rule.rule.can_set_name = true;
+ continue;
+ }
+
+ if (streq(key, "OWNER")) {
+ uid_t uid;
+ char *endptr;
+
+ uid = strtoul(value, &endptr, 10);
+ if (endptr[0] == '\0') {
+ rule_add_key(&rule_tmp, TK_A_OWNER_ID, op, NULL, &uid);
+ } else if ((rules->resolve_names > 0) && strchr("$%", value[0]) == NULL) {
+ uid = add_uid(rules, value);
+ rule_add_key(&rule_tmp, TK_A_OWNER_ID, op, NULL, &uid);
+ } else if (rules->resolve_names >= 0) {
+ rule_add_key(&rule_tmp, TK_A_OWNER, op, value, NULL);
+ }
+ rule_tmp.rule.rule.can_set_name = true;
+ continue;
+ }
+
+ if (streq(key, "GROUP")) {
+ gid_t gid;
+ char *endptr;
+
+ gid = strtoul(value, &endptr, 10);
+ if (endptr[0] == '\0') {
+ rule_add_key(&rule_tmp, TK_A_GROUP_ID, op, NULL, &gid);
+ } else if ((rules->resolve_names > 0) && strchr("$%", value[0]) == NULL) {
+ gid = add_gid(rules, value);
+ rule_add_key(&rule_tmp, TK_A_GROUP_ID, op, NULL, &gid);
+ } else if (rules->resolve_names >= 0) {
+ rule_add_key(&rule_tmp, TK_A_GROUP, op, value, NULL);
+ }
+ rule_tmp.rule.rule.can_set_name = true;
+ continue;
+ }
+
+ if (streq(key, "MODE")) {
+ mode_t mode;
+ char *endptr;
+
+ mode = strtol(value, &endptr, 8);
+ if (endptr[0] == '\0')
+ rule_add_key(&rule_tmp, TK_A_MODE_ID, op, NULL, &mode);
+ else
+ rule_add_key(&rule_tmp, TK_A_MODE, op, value, NULL);
+ rule_tmp.rule.rule.can_set_name = true;
+ continue;
+ }
+
+ if (streq(key, "OPTIONS")) {
+ const char *pos;
+
+ pos = strstr(value, "link_priority=");
+ if (pos != NULL) {
+ int prio = atoi(&pos[strlen("link_priority=")]);
+
+ rule_add_key(&rule_tmp, TK_A_DEVLINK_PRIO, op, NULL, &prio);
+ }
+
+ pos = strstr(value, "event_timeout=");
+ if (pos != NULL) {
+ int tout = atoi(&pos[strlen("event_timeout=")]);
+
+ rule_add_key(&rule_tmp, TK_M_EVENT_TIMEOUT, op, NULL, &tout);
+ }
+
+ pos = strstr(value, "string_escape=");
+ if (pos != NULL) {
+ pos = &pos[strlen("string_escape=")];
+ if (startswith(pos, "none"))
+ rule_add_key(&rule_tmp, TK_A_STRING_ESCAPE_NONE, op, NULL, NULL);
+ else if (startswith(pos, "replace"))
+ rule_add_key(&rule_tmp, TK_A_STRING_ESCAPE_REPLACE, op, NULL, NULL);
+ }
+
+ pos = strstr(value, "db_persist");
+ if (pos != NULL)
+ rule_add_key(&rule_tmp, TK_A_DB_PERSIST, op, NULL, NULL);
+
+ pos = strstr(value, "nowatch");
+ if (pos != NULL) {
+ const int off = 0;
+
+ rule_add_key(&rule_tmp, TK_A_INOTIFY_WATCH, op, NULL, &off);
+ } else {
+ pos = strstr(value, "watch");
+ if (pos != NULL) {
+ const int on = 1;
+
+ rule_add_key(&rule_tmp, TK_A_INOTIFY_WATCH, op, NULL, &on);
+ }
+ }
+
+ pos = strstr(value, "static_node=");
+ if (pos != NULL) {
+ rule_add_key(&rule_tmp, TK_A_STATIC_NODE, op, &pos[strlen("static_node=")], NULL);
+ rule_tmp.rule.rule.has_static_node = true;
+ }
+
+ continue;
+ }
+
+ log_error("unknown key '%s' in %s:%u\n", key, filename, lineno);
+ goto invalid;
+ }
+
+ /* add rule token */
+ rule_tmp.rule.rule.token_count = 1 + rule_tmp.token_cur;
+ if (add_token(rules, &rule_tmp.rule) != 0)
+ goto invalid;
+
+ /* add tokens to list, sorted by type */
+ if (sort_token(rules, &rule_tmp) != 0)
+ goto invalid;
+
+ return 0;
+invalid:
+ log_error("invalid rule '%s:%u'\n", filename, lineno);
+ return -1;
+}
+
+static int parse_file(struct udev_rules *rules, const char *filename)
+{
+ FILE *f;
+ unsigned int first_token;
+ unsigned int filename_off;
+ char line[UTIL_LINE_SIZE];
+ int line_nr = 0;
+ unsigned int i;
+
+ if (null_or_empty_path(filename)) {
+ log_debug("skip empty file: %s\n", filename);
+ return 0;
+ }
+ log_debug("read rules file: %s\n", filename);
+
+ f = fopen(filename, "re");
+ if (f == NULL)
+ return -1;
+
+ first_token = rules->token_cur;
+ filename_off = rules_add_string(rules, filename);
+
+ while (fgets(line, sizeof(line), f) != NULL) {
+ char *key;
+ size_t len;
+
+ /* skip whitespace */
+ line_nr++;
+ key = line;
+ while (isspace(key[0]))
+ key++;
+
+ /* comment */
+ if (key[0] == '#')
+ continue;
+
+ len = strlen(line);
+ if (len < 3)
+ continue;
+
+ /* continue reading if backslash+newline is found */
+ while (line[len-2] == '\\') {
+ if (fgets(&line[len-2], (sizeof(line)-len)+2, f) == NULL)
+ break;
+ if (strlen(&line[len-2]) < 2)
+ break;
+ line_nr++;
+ len = strlen(line);
+ }
+
+ if (len+1 >= sizeof(line)) {
+ log_error("line too long '%s':%u, ignored\n", filename, line_nr);
+ continue;
+ }
+ add_rule(rules, key, filename, filename_off, line_nr);
+ }
+ fclose(f);
+
+ /* link GOTOs to LABEL rules in this file to be able to fast-forward */
+ for (i = first_token+1; i < rules->token_cur; i++) {
+ if (rules->tokens[i].type == TK_A_GOTO) {
+ char *label = rules_str(rules, rules->tokens[i].key.value_off);
+ unsigned int j;
+
+ for (j = i+1; j < rules->token_cur; j++) {
+ if (rules->tokens[j].type != TK_RULE)
+ continue;
+ if (rules->tokens[j].rule.label_off == 0)
+ continue;
+ if (!streq(label, rules_str(rules, rules->tokens[j].rule.label_off)))
+ continue;
+ rules->tokens[i].key.rule_goto = j;
+ break;
+ }
+ if (rules->tokens[i].key.rule_goto == 0)
+ log_error("GOTO '%s' has no matching label in: '%s'\n", label, filename);
+ }
+ }
+ return 0;
+}
+
+struct udev_rules *udev_rules_new(struct udev *udev, int resolve_names)
+{
+ struct udev_rules *rules;
+ struct udev_list file_list;
+ struct token end_token;
+ char **files, **f;
+ int r;
+
+ rules = calloc(1, sizeof(struct udev_rules));
+ if (rules == NULL)
+ return NULL;
+ rules->udev = udev;
+ rules->resolve_names = resolve_names;
+ udev_list_init(udev, &file_list, true);
+
+ /* init token array and string buffer */
+ rules->tokens = malloc(PREALLOC_TOKEN * sizeof(struct token));
+ if (rules->tokens == NULL)
+ return udev_rules_unref(rules);
+ rules->token_max = PREALLOC_TOKEN;
+
+ rules->strbuf = strbuf_new();
+ if (!rules->strbuf)
+ return udev_rules_unref(rules);
+
+ rules->dirs = strv_new("/etc/udev/rules.d",
+ "/run/udev/rules.d",
+ UDEVLIBEXECDIR "/rules.d",
+ NULL);
+ if (!rules->dirs) {
+ log_error("failed to build config directory array");
+ return udev_rules_unref(rules);
+ }
+ if (!path_strv_canonicalize(rules->dirs)) {
+ log_error("failed to canonicalize config directories\n");
+ return udev_rules_unref(rules);
+ }
+ strv_uniq(rules->dirs);
+
+ rules->dirs_ts_usec = calloc(strv_length(rules->dirs), sizeof(long long));
+ if(!rules->dirs_ts_usec)
+ return udev_rules_unref(rules);
+ udev_rules_check_timestamp(rules);
+
+ r = conf_files_list_strv(&files, ".rules", NULL, (const char **)rules->dirs);
+ if (r < 0) {
+ log_error("failed to enumerate rules files: %s\n", strerror(-r));
+ return udev_rules_unref(rules);
+ }
+
+ /*
+ * The offset value in the rules strct is limited; add all
+ * rules file names to the beginning of the string buffer.
+ */
+ STRV_FOREACH(f, files)
+ rules_add_string(rules, *f);
+
+ STRV_FOREACH(f, files)
+ parse_file(rules, *f);
+
+ strv_free(files);
+
+ memset(&end_token, 0x00, sizeof(struct token));
+ end_token.type = TK_END;
+ add_token(rules, &end_token);
+ log_debug("rules contain %zu bytes tokens (%u * %zu bytes), %zu bytes strings\n",
+ rules->token_max * sizeof(struct token), rules->token_max, sizeof(struct token), rules->strbuf->len);
+
+ /* cleanup temporary strbuf data */
+ log_debug("%zu strings (%zu bytes), %zu de-duplicated (%zu bytes), %zu trie nodes used\n",
+ rules->strbuf->in_count, rules->strbuf->in_len,
+ rules->strbuf->dedup_count, rules->strbuf->dedup_len, rules->strbuf->nodes_count);
+ strbuf_complete(rules->strbuf);
+
+ /* cleanup uid/gid cache */
+ free(rules->uids);
+ rules->uids = NULL;
+ rules->uids_cur = 0;
+ rules->uids_max = 0;
+ free(rules->gids);
+ rules->gids = NULL;
+ rules->gids_cur = 0;
+ rules->gids_max = 0;
+
+ dump_rules(rules);
+ return rules;
+}
+
+struct udev_rules *udev_rules_unref(struct udev_rules *rules)
+{
+ if (rules == NULL)
+ return NULL;
+ free(rules->tokens);
+ strbuf_cleanup(rules->strbuf);
+ free(rules->uids);
+ free(rules->gids);
+ strv_free(rules->dirs);
+ free(rules->dirs_ts_usec);
+ free(rules);
+ return NULL;
+}
+
+bool udev_rules_check_timestamp(struct udev_rules *rules)
+{
+ unsigned int i;
+ bool changed = false;
+
+ if (rules == NULL)
+ goto out;
+
+ for (i = 0; rules->dirs[i]; i++) {
+ struct stat stats;
+
+ if (stat(rules->dirs[i], &stats) < 0)
+ continue;
+
+ if (rules->dirs_ts_usec[i] == timespec_load(&stats.st_mtim))
+ continue;
+
+ /* first check */
+ if (rules->dirs_ts_usec[i] != 0) {
+ log_debug("reload - timestamp of '%s' changed\n", rules->dirs[i]);
+ changed = true;
+ }
+
+ /* update timestamp */
+ rules->dirs_ts_usec[i] = timespec_load(&stats.st_mtim);
+ }
+out:
+ return changed;
+}
+
+static int match_key(struct udev_rules *rules, struct token *token, const char *val)
+{
+ char *key_value = rules_str(rules, token->key.value_off);
+ char *pos;
+ bool match = false;
+
+ if (val == NULL)
+ val = "";
+
+ switch (token->key.glob) {
+ case GL_PLAIN:
+ match = (streq(key_value, val));
+ break;
+ case GL_GLOB:
+ match = (fnmatch(key_value, val, 0) == 0);
+ break;
+ case GL_SPLIT:
+ {
+ const char *s;
+ size_t len;
+
+ s = rules_str(rules, token->key.value_off);
+ len = strlen(val);
+ for (;;) {
+ const char *next;
+
+ next = strchr(s, '|');
+ if (next != NULL) {
+ size_t matchlen = (size_t)(next - s);
+
+ match = (matchlen == len && strneq(s, val, matchlen));
+ if (match)
+ break;
+ } else {
+ match = (streq(s, val));
+ break;
+ }
+ s = &next[1];
+ }
+ break;
+ }
+ case GL_SPLIT_GLOB:
+ {
+ char value[UTIL_PATH_SIZE];
+
+ strscpy(value, sizeof(value), rules_str(rules, token->key.value_off));
+ key_value = value;
+ while (key_value != NULL) {
+ pos = strchr(key_value, '|');
+ if (pos != NULL) {
+ pos[0] = '\0';
+ pos = &pos[1];
+ }
+ match = (fnmatch(key_value, val, 0) == 0);
+ if (match)
+ break;
+ key_value = pos;
+ }
+ break;
+ }
+ case GL_SOMETHING:
+ match = (val[0] != '\0');
+ break;
+ case GL_UNSET:
+ return -1;
+ }
+
+ if (match && (token->key.op == OP_MATCH))
+ return 0;
+ if (!match && (token->key.op == OP_NOMATCH))
+ return 0;
+ return -1;
+}
+
+static int match_attr(struct udev_rules *rules, struct udev_device *dev, struct udev_event *event, struct token *cur)
+{
+ const char *name;
+ char nbuf[UTIL_NAME_SIZE];
+ const char *value;
+ char vbuf[UTIL_NAME_SIZE];
+ size_t len;
+
+ name = rules_str(rules, cur->key.attr_off);
+ switch (cur->key.attrsubst) {
+ case SB_FORMAT:
+ udev_event_apply_format(event, name, nbuf, sizeof(nbuf));
+ name = nbuf;
+ /* fall through */
+ case SB_NONE:
+ value = udev_device_get_sysattr_value(dev, name);
+ if (value == NULL)
+ return -1;
+ break;
+ case SB_SUBSYS:
+ if (util_resolve_subsys_kernel(event->udev, name, vbuf, sizeof(vbuf), 1) != 0)
+ return -1;
+ value = vbuf;
+ break;
+ default:
+ return -1;
+ }
+
+ /* remove trailing whitespace, if not asked to match for it */
+ len = strlen(value);
+ if (len > 0 && isspace(value[len-1])) {
+ const char *key_value;
+ size_t klen;
+
+ key_value = rules_str(rules, cur->key.value_off);
+ klen = strlen(key_value);
+ if (klen > 0 && !isspace(key_value[klen-1])) {
+ if (value != vbuf) {
+ strscpy(vbuf, sizeof(vbuf), value);
+ value = vbuf;
+ }
+ while (len > 0 && isspace(vbuf[--len]))
+ vbuf[len] = '\0';
+ }
+ }
+
+ return match_key(rules, cur, value);
+}
+
+enum escape_type {
+ ESCAPE_UNSET,
+ ESCAPE_NONE,
+ ESCAPE_REPLACE,
+};
+
+int udev_rules_apply_to_event(struct udev_rules *rules, struct udev_event *event, const sigset_t *sigmask)
+{
+ struct token *cur;
+ struct token *rule;
+ enum escape_type esc = ESCAPE_UNSET;
+ bool can_set_name;
+
+ if (rules->tokens == NULL)
+ return -1;
+
+ can_set_name = ((!streq(udev_device_get_action(event->dev), "remove")) &&
+ (major(udev_device_get_devnum(event->dev)) > 0 ||
+ udev_device_get_ifindex(event->dev) > 0));
+
+ /* loop through token list, match, run actions or forward to next rule */
+ cur = &rules->tokens[0];
+ rule = cur;
+ for (;;) {
+ dump_token(rules, cur);
+ switch (cur->type) {
+ case TK_RULE:
+ /* current rule */
+ rule = cur;
+ /* possibly skip rules which want to set NAME, SYMLINK, OWNER, GROUP, MODE */
+ if (!can_set_name && rule->rule.can_set_name)
+ goto nomatch;
+ esc = ESCAPE_UNSET;
+ break;
+ case TK_M_ACTION:
+ if (match_key(rules, cur, udev_device_get_action(event->dev)) != 0)
+ goto nomatch;
+ break;
+ case TK_M_DEVPATH:
+ if (match_key(rules, cur, udev_device_get_devpath(event->dev)) != 0)
+ goto nomatch;
+ break;
+ case TK_M_KERNEL:
+ if (match_key(rules, cur, udev_device_get_sysname(event->dev)) != 0)
+ goto nomatch;
+ break;
+ case TK_M_DEVLINK: {
+ struct udev_list_entry *list_entry;
+ bool match = false;
+
+ udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(event->dev)) {
+ const char *devlink;
+
+ devlink = udev_list_entry_get_name(list_entry) + strlen("/dev/");
+ if (match_key(rules, cur, devlink) == 0) {
+ match = true;
+ break;
+ }
+ }
+ if (!match)
+ goto nomatch;
+ break;
+ }
+ case TK_M_NAME:
+ if (match_key(rules, cur, event->name) != 0)
+ goto nomatch;
+ break;
+ case TK_M_ENV: {
+ const char *key_name = rules_str(rules, cur->key.attr_off);
+ const char *value;
+
+ value = udev_device_get_property_value(event->dev, key_name);
+ if (value == NULL)
+ value = "";
+ if (match_key(rules, cur, value))
+ goto nomatch;
+ break;
+ }
+ case TK_M_TAG: {
+ struct udev_list_entry *list_entry;
+ bool match = false;
+
+ udev_list_entry_foreach(list_entry, udev_device_get_tags_list_entry(event->dev)) {
+ if (streq(rules_str(rules, cur->key.value_off), udev_list_entry_get_name(list_entry))) {
+ match = true;
+ break;
+ }
+ }
+ if (!match && (cur->key.op != OP_NOMATCH))
+ goto nomatch;
+ break;
+ }
+ case TK_M_SUBSYSTEM:
+ if (match_key(rules, cur, udev_device_get_subsystem(event->dev)) != 0)
+ goto nomatch;
+ break;
+ case TK_M_DRIVER:
+ if (match_key(rules, cur, udev_device_get_driver(event->dev)) != 0)
+ goto nomatch;
+ break;
+ case TK_M_WAITFOR: {
+ char filename[UTIL_PATH_SIZE];
+ int found;
+
+ udev_event_apply_format(event, rules_str(rules, cur->key.value_off), filename, sizeof(filename));
+ found = (wait_for_file(event->dev, filename, 10) == 0);
+ if (!found && (cur->key.op != OP_NOMATCH))
+ goto nomatch;
+ break;
+ }
+ case TK_M_ATTR:
+ if (match_attr(rules, event->dev, event, cur) != 0)
+ goto nomatch;
+ break;
+ case TK_M_KERNELS:
+ case TK_M_SUBSYSTEMS:
+ case TK_M_DRIVERS:
+ case TK_M_ATTRS:
+ case TK_M_TAGS: {
+ struct token *next;
+
+ /* get whole sequence of parent matches */
+ next = cur;
+ while (next->type > TK_M_PARENTS_MIN && next->type < TK_M_PARENTS_MAX)
+ next++;
+
+ /* loop over parents */
+ event->dev_parent = event->dev;
+ for (;;) {
+ struct token *key;
+
+ /* loop over sequence of parent match keys */
+ for (key = cur; key < next; key++ ) {
+ dump_token(rules, key);
+ switch(key->type) {
+ case TK_M_KERNELS:
+ if (match_key(rules, key, udev_device_get_sysname(event->dev_parent)) != 0)
+ goto try_parent;
+ break;
+ case TK_M_SUBSYSTEMS:
+ if (match_key(rules, key, udev_device_get_subsystem(event->dev_parent)) != 0)
+ goto try_parent;
+ break;
+ case TK_M_DRIVERS:
+ if (match_key(rules, key, udev_device_get_driver(event->dev_parent)) != 0)
+ goto try_parent;
+ break;
+ case TK_M_ATTRS:
+ if (match_attr(rules, event->dev_parent, event, key) != 0)
+ goto try_parent;
+ break;
+ case TK_M_TAGS: {
+ bool match = udev_device_has_tag(event->dev_parent, rules_str(rules, cur->key.value_off));
+
+ if (match && key->key.op == OP_NOMATCH)
+ goto try_parent;
+ if (!match && key->key.op == OP_MATCH)
+ goto try_parent;
+ break;
+ }
+ default:
+ goto nomatch;
+ }
+ }
+ break;
+
+ try_parent:
+ event->dev_parent = udev_device_get_parent(event->dev_parent);
+ if (event->dev_parent == NULL)
+ goto nomatch;
+ }
+ /* move behind our sequence of parent match keys */
+ cur = next;
+ continue;
+ }
+ case TK_M_TEST: {
+ char filename[UTIL_PATH_SIZE];
+ struct stat statbuf;
+ int match;
+
+ udev_event_apply_format(event, rules_str(rules, cur->key.value_off), filename, sizeof(filename));
+ if (util_resolve_subsys_kernel(event->udev, filename, filename, sizeof(filename), 0) != 0) {
+ if (filename[0] != '/') {
+ char tmp[UTIL_PATH_SIZE];
+
+ strscpy(tmp, sizeof(tmp), filename);
+ strscpyl(filename, sizeof(filename),
+ udev_device_get_syspath(event->dev), "/", tmp, NULL);
+ }
+ }
+ attr_subst_subdir(filename, sizeof(filename));
+
+ match = (stat(filename, &statbuf) == 0);
+ if (match && cur->key.mode > 0)
+ match = ((statbuf.st_mode & cur->key.mode) > 0);
+ if (match && cur->key.op == OP_NOMATCH)
+ goto nomatch;
+ if (!match && cur->key.op == OP_MATCH)
+ goto nomatch;
+ break;
+ }
+ case TK_M_EVENT_TIMEOUT:
+ log_debug("OPTIONS event_timeout=%u\n", cur->key.event_timeout);
+ event->timeout_usec = cur->key.event_timeout * 1000 * 1000;
+ break;
+ case TK_M_PROGRAM: {
+ char program[UTIL_PATH_SIZE];
+ char **envp;
+ char result[UTIL_PATH_SIZE];
+
+ free(event->program_result);
+ event->program_result = NULL;
+ udev_event_apply_format(event, rules_str(rules, cur->key.value_off), program, sizeof(program));
+ envp = udev_device_get_properties_envp(event->dev);
+ log_debug("PROGRAM '%s' %s:%u\n",
+ program,
+ rules_str(rules, rule->rule.filename_off),
+ rule->rule.filename_line);
+
+ if (udev_event_spawn(event, program, envp, sigmask, result, sizeof(result)) < 0) {
+ if (cur->key.op != OP_NOMATCH)
+ goto nomatch;
+ } else {
+ int count;
+
+ util_remove_trailing_chars(result, '\n');
+ if (esc == ESCAPE_UNSET || esc == ESCAPE_REPLACE) {
+ count = util_replace_chars(result, UDEV_ALLOWED_CHARS_INPUT);
+ if (count > 0)
+ log_debug("%i character(s) replaced\n" , count);
+ }
+ event->program_result = strdup(result);
+ if (cur->key.op == OP_NOMATCH)
+ goto nomatch;
+ }
+ break;
+ }
+ case TK_M_IMPORT_FILE: {
+ char import[UTIL_PATH_SIZE];
+
+ udev_event_apply_format(event, rules_str(rules, cur->key.value_off), import, sizeof(import));
+ if (import_file_into_properties(event->dev, import) != 0)
+ if (cur->key.op != OP_NOMATCH)
+ goto nomatch;
+ break;
+ }
+ case TK_M_IMPORT_PROG: {
+ char import[UTIL_PATH_SIZE];
+
+ udev_event_apply_format(event, rules_str(rules, cur->key.value_off), import, sizeof(import));
+ log_debug("IMPORT '%s' %s:%u\n",
+ import,
+ rules_str(rules, rule->rule.filename_off),
+ rule->rule.filename_line);
+
+ if (import_program_into_properties(event, import, sigmask) != 0)
+ if (cur->key.op != OP_NOMATCH)
+ goto nomatch;
+ break;
+ }
+ case TK_M_IMPORT_BUILTIN: {
+ char command[UTIL_PATH_SIZE];
+
+ if (udev_builtin_run_once(cur->key.builtin_cmd)) {
+ /* check if we ran already */
+ if (event->builtin_run & (1 << cur->key.builtin_cmd)) {
+ log_debug("IMPORT builtin skip '%s' %s:%u\n",
+ udev_builtin_name(cur->key.builtin_cmd),
+ rules_str(rules, rule->rule.filename_off),
+ rule->rule.filename_line);
+ /* return the result from earlier run */
+ if (event->builtin_ret & (1 << cur->key.builtin_cmd))
+ if (cur->key.op != OP_NOMATCH)
+ goto nomatch;
+ break;
+ }
+ /* mark as ran */
+ event->builtin_run |= (1 << cur->key.builtin_cmd);
+ }
+
+ udev_event_apply_format(event, rules_str(rules, cur->key.value_off), command, sizeof(command));
+ log_debug("IMPORT builtin '%s' %s:%u\n",
+ udev_builtin_name(cur->key.builtin_cmd),
+ rules_str(rules, rule->rule.filename_off),
+ rule->rule.filename_line);
+
+ if (udev_builtin_run(event->dev, cur->key.builtin_cmd, command, false) != 0) {
+ /* remember failure */
+ log_debug("IMPORT builtin '%s' returned non-zero\n",
+ udev_builtin_name(cur->key.builtin_cmd));
+ event->builtin_ret |= (1 << cur->key.builtin_cmd);
+ if (cur->key.op != OP_NOMATCH)
+ goto nomatch;
+ }
+ break;
+ }
+ case TK_M_IMPORT_DB: {
+ const char *key = rules_str(rules, cur->key.value_off);
+ const char *value;
+
+ value = udev_device_get_property_value(event->dev_db, key);
+ if (value != NULL) {
+ struct udev_list_entry *entry;
+
+ entry = udev_device_add_property(event->dev, key, value);
+ udev_list_entry_set_num(entry, true);
+ } else {
+ if (cur->key.op != OP_NOMATCH)
+ goto nomatch;
+ }
+ break;
+ }
+ case TK_M_IMPORT_CMDLINE: {
+ FILE *f;
+ bool imported = false;
+
+ f = fopen("/proc/cmdline", "re");
+ if (f != NULL) {
+ char cmdline[4096];
+
+ if (fgets(cmdline, sizeof(cmdline), f) != NULL) {
+ const char *key = rules_str(rules, cur->key.value_off);
+ char *pos;
+
+ pos = strstr(cmdline, key);
+ if (pos != NULL) {
+ struct udev_list_entry *entry;
+
+ pos += strlen(key);
+ if (pos[0] == '\0' || isspace(pos[0])) {
+ /* we import simple flags as 'FLAG=1' */
+ entry = udev_device_add_property(event->dev, key, "1");
+ udev_list_entry_set_num(entry, true);
+ imported = true;
+ } else if (pos[0] == '=') {
+ const char *value;
+
+ pos++;
+ value = pos;
+ while (pos[0] != '\0' && !isspace(pos[0]))
+ pos++;
+ pos[0] = '\0';
+ entry = udev_device_add_property(event->dev, key, value);
+ udev_list_entry_set_num(entry, true);
+ imported = true;
+ }
+ }
+ }
+ fclose(f);
+ }
+ if (!imported && cur->key.op != OP_NOMATCH)
+ goto nomatch;
+ break;
+ }
+ case TK_M_IMPORT_PARENT: {
+ char import[UTIL_PATH_SIZE];
+
+ udev_event_apply_format(event, rules_str(rules, cur->key.value_off), import, sizeof(import));
+ if (import_parent_into_properties(event->dev, import) != 0)
+ if (cur->key.op != OP_NOMATCH)
+ goto nomatch;
+ break;
+ }
+ case TK_M_RESULT:
+ if (match_key(rules, cur, event->program_result) != 0)
+ goto nomatch;
+ break;
+ case TK_A_STRING_ESCAPE_NONE:
+ esc = ESCAPE_NONE;
+ break;
+ case TK_A_STRING_ESCAPE_REPLACE:
+ esc = ESCAPE_REPLACE;
+ break;
+ case TK_A_DB_PERSIST:
+ udev_device_set_db_persist(event->dev);
+ break;
+ case TK_A_INOTIFY_WATCH:
+ if (event->inotify_watch_final)
+ break;
+ if (cur->key.op == OP_ASSIGN_FINAL)
+ event->inotify_watch_final = true;
+ event->inotify_watch = cur->key.watch;
+ break;
+ case TK_A_DEVLINK_PRIO:
+ udev_device_set_devlink_priority(event->dev, cur->key.devlink_prio);
+ break;
+ case TK_A_OWNER: {
+ char owner[UTIL_NAME_SIZE];
+
+ if (event->owner_final)
+ break;
+ if (cur->key.op == OP_ASSIGN_FINAL)
+ event->owner_final = true;
+ udev_event_apply_format(event, rules_str(rules, cur->key.value_off), owner, sizeof(owner));
+ event->owner_set = true;
+ event->uid = util_lookup_user(event->udev, owner);
+ log_debug("OWNER %u %s:%u\n",
+ event->uid,
+ rules_str(rules, rule->rule.filename_off),
+ rule->rule.filename_line);
+ break;
+ }
+ case TK_A_GROUP: {
+ char group[UTIL_NAME_SIZE];
+
+ if (event->group_final)
+ break;
+ if (cur->key.op == OP_ASSIGN_FINAL)
+ event->group_final = true;
+ udev_event_apply_format(event, rules_str(rules, cur->key.value_off), group, sizeof(group));
+ event->group_set = true;
+ event->gid = util_lookup_group(event->udev, group);
+ log_debug("GROUP %u %s:%u\n",
+ event->gid,
+ rules_str(rules, rule->rule.filename_off),
+ rule->rule.filename_line);
+ break;
+ }
+ case TK_A_MODE: {
+ char mode_str[UTIL_NAME_SIZE];
+ mode_t mode;
+ char *endptr;
+
+ if (event->mode_final)
+ break;
+ udev_event_apply_format(event, rules_str(rules, cur->key.value_off), mode_str, sizeof(mode_str));
+ mode = strtol(mode_str, &endptr, 8);
+ if (endptr[0] != '\0') {
+ log_error("ignoring invalid mode '%s'\n", mode_str);
+ break;
+ }
+ if (cur->key.op == OP_ASSIGN_FINAL)
+ event->mode_final = true;
+ event->mode_set = true;
+ event->mode = mode;
+ log_debug("MODE %#o %s:%u\n",
+ event->mode,
+ rules_str(rules, rule->rule.filename_off),
+ rule->rule.filename_line);
+ break;
+ }
+ case TK_A_OWNER_ID:
+ if (event->owner_final)
+ break;
+ if (cur->key.op == OP_ASSIGN_FINAL)
+ event->owner_final = true;
+ event->owner_set = true;
+ event->uid = cur->key.uid;
+ log_debug("OWNER %u %s:%u\n",
+ event->uid,
+ rules_str(rules, rule->rule.filename_off),
+ rule->rule.filename_line);
+ break;
+ case TK_A_GROUP_ID:
+ if (event->group_final)
+ break;
+ if (cur->key.op == OP_ASSIGN_FINAL)
+ event->group_final = true;
+ event->group_set = true;
+ event->gid = cur->key.gid;
+ log_debug("GROUP %u %s:%u\n",
+ event->gid,
+ rules_str(rules, rule->rule.filename_off),
+ rule->rule.filename_line);
+ break;
+ case TK_A_MODE_ID:
+ if (event->mode_final)
+ break;
+ if (cur->key.op == OP_ASSIGN_FINAL)
+ event->mode_final = true;
+ event->mode_set = true;
+ event->mode = cur->key.mode;
+ log_debug("MODE %#o %s:%u\n",
+ event->mode,
+ rules_str(rules, rule->rule.filename_off),
+ rule->rule.filename_line);
+ break;
+ case TK_A_ENV: {
+ const char *name = rules_str(rules, cur->key.attr_off);
+ char *value = rules_str(rules, cur->key.value_off);
+ char value_new[UTIL_NAME_SIZE];
+ const char *value_old = NULL;
+ struct udev_list_entry *entry;
+
+ if (value[0] == '\0') {
+ if (cur->key.op == OP_ADD)
+ break;
+ udev_device_add_property(event->dev, name, NULL);
+ break;
+ }
+
+ if (cur->key.op == OP_ADD)
+ value_old = udev_device_get_property_value(event->dev, name);
+ if (value_old) {
+ char temp[UTIL_NAME_SIZE];
+
+ /* append value separated by space */
+ udev_event_apply_format(event, value, temp, sizeof(temp));
+ strscpyl(value_new, sizeof(value_new), value_old, " ", temp, NULL);
+ } else
+ udev_event_apply_format(event, value, value_new, sizeof(value_new));
+
+ entry = udev_device_add_property(event->dev, name, value_new);
+ /* store in db, skip private keys */
+ if (name[0] != '.')
+ udev_list_entry_set_num(entry, true);
+ break;
+ }
+ case TK_A_TAG: {
+ char tag[UTIL_PATH_SIZE];
+ const char *p;
+
+ udev_event_apply_format(event, rules_str(rules, cur->key.value_off), tag, sizeof(tag));
+ if (cur->key.op == OP_ASSIGN || cur->key.op == OP_ASSIGN_FINAL)
+ udev_device_cleanup_tags_list(event->dev);
+ for (p = tag; *p != '\0'; p++) {
+ if ((*p >= 'a' && *p <= 'z') ||
+ (*p >= 'A' && *p <= 'Z') ||
+ (*p >= '0' && *p <= '9') ||
+ *p == '-' || *p == '_')
+ continue;
+ log_error("ignoring invalid tag name '%s'\n", tag);
+ break;
+ }
+ udev_device_add_tag(event->dev, tag);
+ break;
+ }
+ case TK_A_NAME: {
+ const char *name = rules_str(rules, cur->key.value_off);
+
+ char name_str[UTIL_PATH_SIZE];
+ int count;
+
+ if (event->name_final)
+ break;
+ if (cur->key.op == OP_ASSIGN_FINAL)
+ event->name_final = true;
+ udev_event_apply_format(event, name, name_str, sizeof(name_str));
+ if (esc == ESCAPE_UNSET || esc == ESCAPE_REPLACE) {
+ count = util_replace_chars(name_str, "/");
+ if (count > 0)
+ log_debug("%i character(s) replaced\n", count);
+ }
+ if (major(udev_device_get_devnum(event->dev)) &&
+ (!streq(name_str, udev_device_get_devnode(event->dev) + strlen("/dev/")))) {
+ log_error("NAME=\"%s\" ignored, kernel device nodes "
+ "can not be renamed; please fix it in %s:%u\n", name,
+ rules_str(rules, rule->rule.filename_off), rule->rule.filename_line);
+ break;
+ }
+ free(event->name);
+ event->name = strdup(name_str);
+ log_debug("NAME '%s' %s:%u\n",
+ event->name,
+ rules_str(rules, rule->rule.filename_off),
+ rule->rule.filename_line);
+ break;
+ }
+ case TK_A_DEVLINK: {
+ char temp[UTIL_PATH_SIZE];
+ char filename[UTIL_PATH_SIZE];
+ char *pos, *next;
+ int count = 0;
+
+ if (event->devlink_final)
+ break;
+ if (major(udev_device_get_devnum(event->dev)) == 0)
+ break;
+ if (cur->key.op == OP_ASSIGN_FINAL)
+ event->devlink_final = true;
+ if (cur->key.op == OP_ASSIGN || cur->key.op == OP_ASSIGN_FINAL)
+ udev_device_cleanup_devlinks_list(event->dev);
+
+ /* allow multiple symlinks separated by spaces */
+ udev_event_apply_format(event, rules_str(rules, cur->key.value_off), temp, sizeof(temp));
+ if (esc == ESCAPE_UNSET)
+ count = util_replace_chars(temp, "/ ");
+ else if (esc == ESCAPE_REPLACE)
+ count = util_replace_chars(temp, "/");
+ if (count > 0)
+ log_debug("%i character(s) replaced\n" , count);
+ pos = temp;
+ while (isspace(pos[0]))
+ pos++;
+ next = strchr(pos, ' ');
+ while (next != NULL) {
+ next[0] = '\0';
+ log_debug("LINK '%s' %s:%u\n", pos,
+ rules_str(rules, rule->rule.filename_off), rule->rule.filename_line);
+ strscpyl(filename, sizeof(filename), "/dev/", pos, NULL);
+ udev_device_add_devlink(event->dev, filename);
+ while (isspace(next[1]))
+ next++;
+ pos = &next[1];
+ next = strchr(pos, ' ');
+ }
+ if (pos[0] != '\0') {
+ log_debug("LINK '%s' %s:%u\n", pos,
+ rules_str(rules, rule->rule.filename_off), rule->rule.filename_line);
+ strscpyl(filename, sizeof(filename), "/dev/", pos, NULL);
+ udev_device_add_devlink(event->dev, filename);
+ }
+ break;
+ }
+ case TK_A_ATTR: {
+ const char *key_name = rules_str(rules, cur->key.attr_off);
+ char attr[UTIL_PATH_SIZE];
+ char value[UTIL_NAME_SIZE];
+ FILE *f;
+
+ if (util_resolve_subsys_kernel(event->udev, key_name, attr, sizeof(attr), 0) != 0)
+ strscpyl(attr, sizeof(attr), udev_device_get_syspath(event->dev), "/", key_name, NULL);
+ attr_subst_subdir(attr, sizeof(attr));
+
+ udev_event_apply_format(event, rules_str(rules, cur->key.value_off), value, sizeof(value));
+ log_debug("ATTR '%s' writing '%s' %s:%u\n", attr, value,
+ rules_str(rules, rule->rule.filename_off),
+ rule->rule.filename_line);
+ f = fopen(attr, "we");
+ if (f != NULL) {
+ if (fprintf(f, "%s", value) <= 0)
+ log_error("error writing ATTR{%s}: %m\n", attr);
+ fclose(f);
+ } else {
+ log_error("error opening ATTR{%s} for writing: %m\n", attr);
+ }
+ break;
+ }
+ case TK_A_RUN_BUILTIN:
+ case TK_A_RUN_PROGRAM: {
+ struct udev_list_entry *entry;
+
+ if (cur->key.op == OP_ASSIGN || cur->key.op == OP_ASSIGN_FINAL)
+ udev_list_cleanup(&event->run_list);
+ log_debug("RUN '%s' %s:%u\n",
+ rules_str(rules, cur->key.value_off),
+ rules_str(rules, rule->rule.filename_off),
+ rule->rule.filename_line);
+ entry = udev_list_entry_add(&event->run_list, rules_str(rules, cur->key.value_off), NULL);
+ udev_list_entry_set_num(entry, cur->key.builtin_cmd);
+ break;
+ }
+ case TK_A_GOTO:
+ if (cur->key.rule_goto == 0)
+ break;
+ cur = &rules->tokens[cur->key.rule_goto];
+ continue;
+ case TK_END:
+ return 0;
+
+ case TK_M_PARENTS_MIN:
+ case TK_M_PARENTS_MAX:
+ case TK_M_MAX:
+ case TK_UNSET:
+ log_error("wrong type %u\n", cur->type);
+ goto nomatch;
+ }
+
+ cur++;
+ continue;
+ nomatch:
+ /* fast-forward to next rule */
+ cur = rule + rule->rule.token_count;
+ }
+}
+
+void udev_rules_apply_static_dev_perms(struct udev_rules *rules)
+{
+ struct token *cur;
+ struct token *rule;
+ uid_t uid = 0;
+ gid_t gid = 0;
+ mode_t mode = 0;
+
+ if (rules->tokens == NULL)
+ return;
+
+ cur = &rules->tokens[0];
+ rule = cur;
+ for (;;) {
+ switch (cur->type) {
+ case TK_RULE:
+ /* current rule */
+ rule = cur;
+
+ /* skip rules without a static_node tag */
+ if (!rule->rule.has_static_node)
+ goto next;
+
+ uid = 0;
+ gid = 0;
+ mode = 0;
+ break;
+ case TK_A_OWNER_ID:
+ uid = cur->key.uid;
+ break;
+ case TK_A_GROUP_ID:
+ gid = cur->key.gid;
+ break;
+ case TK_A_MODE_ID:
+ mode = cur->key.mode;
+ break;
+ case TK_A_STATIC_NODE: {
+ char filename[UTIL_PATH_SIZE];
+ struct stat stats;
+
+ /* we assure, that the permissions tokens are sorted before the static token */
+ if (mode == 0 && uid == 0 && gid == 0)
+ goto next;
+ strscpyl(filename, sizeof(filename), "/dev/", rules_str(rules, cur->key.value_off), NULL);
+ if (stat(filename, &stats) != 0)
+ goto next;
+ if (!S_ISBLK(stats.st_mode) && !S_ISCHR(stats.st_mode))
+ goto next;
+ if (mode == 0) {
+ if (gid > 0)
+ mode = 0660;
+ else
+ mode = 0600;
+ }
+ if (mode != (stats.st_mode & 01777)) {
+ chmod(filename, mode);
+ log_debug("chmod '%s' %#o\n", filename, mode);
+ }
+
+ if ((uid != 0 && uid != stats.st_uid) || (gid != 0 && gid != stats.st_gid)) {
+ chown(filename, uid, gid);
+ log_debug("chown '%s' %u %u\n", filename, uid, gid);
+ }
+
+ utimensat(AT_FDCWD, filename, NULL, 0);
+ break;
+ }
+ case TK_END:
+ return;
+ }
+
+ cur++;
+ continue;
+next:
+ /* fast-forward to next rule */
+ cur = rule + rule->rule.token_count;
+ continue;
+ }
+}
diff --git a/src/udev/udev-watch.c b/src/udev/udev-watch.c
new file mode 100644
index 0000000000..9b694c6666
--- /dev/null
+++ b/src/udev/udev-watch.c
@@ -0,0 +1,161 @@
+/*
+ * Copyright (C) 2004-2012 Kay Sievers <kay@vrfy.org>
+ * Copyright (C) 2009 Canonical Ltd.
+ * Copyright (C) 2009 Scott James Remnant <scott@netsplit.com>
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <sys/types.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <dirent.h>
+#include <stddef.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/inotify.h>
+
+#include "udev.h"
+
+static int inotify_fd = -1;
+
+/* inotify descriptor, will be shared with rules directory;
+ * set to cloexec since we need our children to be able to add
+ * watches for us
+ */
+int udev_watch_init(struct udev *udev)
+{
+ inotify_fd = inotify_init1(IN_CLOEXEC);
+ if (inotify_fd < 0)
+ log_error("inotify_init failed: %m\n");
+ return inotify_fd;
+}
+
+/* move any old watches directory out of the way, and then restore
+ * the watches
+ */
+void udev_watch_restore(struct udev *udev)
+{
+ if (inotify_fd < 0)
+ return;
+
+ if (rename("/run/udev/watch", "/run/udev/watch.old") == 0) {
+ DIR *dir;
+ struct dirent *ent;
+
+ dir = opendir("/run/udev/watch.old");
+ if (dir == NULL) {
+ log_error("unable to open old watches dir /run/udev/watch.old; old watches will not be restored: %m");
+ return;
+ }
+
+ for (ent = readdir(dir); ent != NULL; ent = readdir(dir)) {
+ char device[UTIL_PATH_SIZE];
+ ssize_t len;
+ struct udev_device *dev;
+
+ if (ent->d_name[0] == '.')
+ continue;
+
+ len = readlinkat(dirfd(dir), ent->d_name, device, sizeof(device));
+ if (len <= 0 || len == (ssize_t)sizeof(device))
+ goto unlink;
+ device[len] = '\0';
+
+ dev = udev_device_new_from_device_id(udev, device);
+ if (dev == NULL)
+ goto unlink;
+
+ log_debug("restoring old watch on '%s'\n", udev_device_get_devnode(dev));
+ udev_watch_begin(udev, dev);
+ udev_device_unref(dev);
+unlink:
+ unlinkat(dirfd(dir), ent->d_name, 0);
+ }
+
+ closedir(dir);
+ rmdir("/run/udev/watch.old");
+
+ } else if (errno != ENOENT) {
+ log_error("unable to move watches dir /run/udev/watch; old watches will not be restored: %m");
+ }
+}
+
+void udev_watch_begin(struct udev *udev, struct udev_device *dev)
+{
+ char filename[UTIL_PATH_SIZE];
+ int wd;
+ int r;
+
+ if (inotify_fd < 0)
+ return;
+
+ log_debug("adding watch on '%s'\n", udev_device_get_devnode(dev));
+ wd = inotify_add_watch(inotify_fd, udev_device_get_devnode(dev), IN_CLOSE_WRITE);
+ if (wd < 0) {
+ log_error("inotify_add_watch(%d, %s, %o) failed: %m\n",
+ inotify_fd, udev_device_get_devnode(dev), IN_CLOSE_WRITE);
+ return;
+ }
+
+ snprintf(filename, sizeof(filename), "/run/udev/watch/%d", wd);
+ mkdir_parents(filename, 0755);
+ unlink(filename);
+ r = symlink(udev_device_get_id_filename(dev), filename);
+ if (r < 0)
+ log_error("Failed to create symlink %s: %m", filename);
+
+ udev_device_set_watch_handle(dev, wd);
+}
+
+void udev_watch_end(struct udev *udev, struct udev_device *dev)
+{
+ int wd;
+ char filename[UTIL_PATH_SIZE];
+
+ if (inotify_fd < 0)
+ return;
+
+ wd = udev_device_get_watch_handle(dev);
+ if (wd < 0)
+ return;
+
+ log_debug("removing watch on '%s'\n", udev_device_get_devnode(dev));
+ inotify_rm_watch(inotify_fd, wd);
+
+ snprintf(filename, sizeof(filename), "/run/udev/watch/%d", wd);
+ unlink(filename);
+
+ udev_device_set_watch_handle(dev, -1);
+}
+
+struct udev_device *udev_watch_lookup(struct udev *udev, int wd)
+{
+ char filename[UTIL_PATH_SIZE];
+ char device[UTIL_NAME_SIZE];
+ ssize_t len;
+
+ if (inotify_fd < 0 || wd < 0)
+ return NULL;
+
+ snprintf(filename, sizeof(filename), "/run/udev/watch/%d", wd);
+ len = readlink(filename, device, sizeof(device));
+ if (len <= 0 || (size_t)len == sizeof(device))
+ return NULL;
+ device[len] = '\0';
+
+ return udev_device_new_from_device_id(udev, device);
+}
diff --git a/src/udev/udev.conf b/src/udev/udev.conf
new file mode 100644
index 0000000000..f39253eb67
--- /dev/null
+++ b/src/udev/udev.conf
@@ -0,0 +1,3 @@
+# see udev(7) for details
+
+#udev_log="info"
diff --git a/src/udev/udev.h b/src/udev/udev.h
new file mode 100644
index 0000000000..caec5f0a5d
--- /dev/null
+++ b/src/udev/udev.h
@@ -0,0 +1,214 @@
+/*
+ * Copyright (C) 2003 Greg Kroah-Hartman <greg@kroah.com>
+ * Copyright (C) 2003-2010 Kay Sievers <kay@vrfy.org>
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#pragma once
+
+#include <sys/types.h>
+#include <sys/param.h>
+#include <signal.h>
+
+#include "macro.h"
+#include "libudev.h"
+#include "libudev-private.h"
+#include "util.h"
+#include "label.h"
+#include "strv.h"
+
+struct udev_event {
+ struct udev *udev;
+ struct udev_device *dev;
+ struct udev_device *dev_parent;
+ struct udev_device *dev_db;
+ char *name;
+ char *program_result;
+ mode_t mode;
+ uid_t uid;
+ gid_t gid;
+ struct udev_list run_list;
+ int exec_delay;
+ usec_t birth_usec;
+ usec_t timeout_usec;
+ int fd_signal;
+ unsigned int builtin_run;
+ unsigned int builtin_ret;
+ bool sigterm;
+ bool inotify_watch;
+ bool inotify_watch_final;
+ bool group_set;
+ bool group_final;
+ bool owner_set;
+ bool owner_final;
+ bool mode_set;
+ bool mode_final;
+ bool name_final;
+ bool devlink_final;
+ bool run_final;
+};
+
+struct udev_watch {
+ struct udev_list_node node;
+ int handle;
+ char *name;
+};
+
+/* udev-rules.c */
+struct udev_rules;
+struct udev_rules *udev_rules_new(struct udev *udev, int resolve_names);
+struct udev_rules *udev_rules_unref(struct udev_rules *rules);
+bool udev_rules_check_timestamp(struct udev_rules *rules);
+int udev_rules_apply_to_event(struct udev_rules *rules, struct udev_event *event, const sigset_t *sigmask);
+void udev_rules_apply_static_dev_perms(struct udev_rules *rules);
+
+/* udev-event.c */
+struct udev_event *udev_event_new(struct udev_device *dev);
+void udev_event_unref(struct udev_event *event);
+size_t udev_event_apply_format(struct udev_event *event, const char *src, char *dest, size_t size);
+int udev_event_apply_subsys_kernel(struct udev_event *event, const char *string,
+ char *result, size_t maxsize, int read_value);
+int udev_event_spawn(struct udev_event *event,
+ const char *cmd, char **envp, const sigset_t *sigmask,
+ char *result, size_t ressize);
+int udev_event_execute_rules(struct udev_event *event, struct udev_rules *rules, const sigset_t *sigset);
+void udev_event_execute_run(struct udev_event *event, const sigset_t *sigset);
+int udev_build_argv(struct udev *udev, char *cmd, int *argc, char *argv[]);
+
+/* udev-watch.c */
+int udev_watch_init(struct udev *udev);
+void udev_watch_restore(struct udev *udev);
+void udev_watch_begin(struct udev *udev, struct udev_device *dev);
+void udev_watch_end(struct udev *udev, struct udev_device *dev);
+struct udev_device *udev_watch_lookup(struct udev *udev, int wd);
+
+/* udev-node.c */
+void udev_node_add(struct udev_device *dev, bool apply, mode_t mode, uid_t uid, gid_t gid);
+void udev_node_remove(struct udev_device *dev);
+void udev_node_update_old_links(struct udev_device *dev, struct udev_device *dev_old);
+
+/* udev-ctrl.c */
+struct udev_ctrl;
+struct udev_ctrl *udev_ctrl_new(struct udev *udev);
+struct udev_ctrl *udev_ctrl_new_from_fd(struct udev *udev, int fd);
+int udev_ctrl_enable_receiving(struct udev_ctrl *uctrl);
+struct udev_ctrl *udev_ctrl_ref(struct udev_ctrl *uctrl);
+struct udev_ctrl *udev_ctrl_unref(struct udev_ctrl *uctrl);
+int udev_ctrl_cleanup(struct udev_ctrl *uctrl);
+struct udev *udev_ctrl_get_udev(struct udev_ctrl *uctrl);
+int udev_ctrl_get_fd(struct udev_ctrl *uctrl);
+int udev_ctrl_send_set_log_level(struct udev_ctrl *uctrl, int priority, int timeout);
+int udev_ctrl_send_stop_exec_queue(struct udev_ctrl *uctrl, int timeout);
+int udev_ctrl_send_start_exec_queue(struct udev_ctrl *uctrl, int timeout);
+int udev_ctrl_send_reload(struct udev_ctrl *uctrl, int timeout);
+int udev_ctrl_send_ping(struct udev_ctrl *uctrl, int timeout);
+int udev_ctrl_send_exit(struct udev_ctrl *uctrl, int timeout);
+int udev_ctrl_send_set_env(struct udev_ctrl *uctrl, const char *key, int timeout);
+int udev_ctrl_send_set_children_max(struct udev_ctrl *uctrl, int count, int timeout);
+struct udev_ctrl_connection;
+struct udev_ctrl_connection *udev_ctrl_get_connection(struct udev_ctrl *uctrl);
+struct udev_ctrl_connection *udev_ctrl_connection_ref(struct udev_ctrl_connection *conn);
+struct udev_ctrl_connection *udev_ctrl_connection_unref(struct udev_ctrl_connection *conn);
+struct udev_ctrl_msg;
+struct udev_ctrl_msg *udev_ctrl_receive_msg(struct udev_ctrl_connection *conn);
+struct udev_ctrl_msg *udev_ctrl_msg_ref(struct udev_ctrl_msg *ctrl_msg);
+struct udev_ctrl_msg *udev_ctrl_msg_unref(struct udev_ctrl_msg *ctrl_msg);
+int udev_ctrl_get_set_log_level(struct udev_ctrl_msg *ctrl_msg);
+int udev_ctrl_get_stop_exec_queue(struct udev_ctrl_msg *ctrl_msg);
+int udev_ctrl_get_start_exec_queue(struct udev_ctrl_msg *ctrl_msg);
+int udev_ctrl_get_reload(struct udev_ctrl_msg *ctrl_msg);
+int udev_ctrl_get_ping(struct udev_ctrl_msg *ctrl_msg);
+int udev_ctrl_get_exit(struct udev_ctrl_msg *ctrl_msg);
+const char *udev_ctrl_get_set_env(struct udev_ctrl_msg *ctrl_msg);
+int udev_ctrl_get_set_children_max(struct udev_ctrl_msg *ctrl_msg);
+
+/* built-in commands */
+enum udev_builtin_cmd {
+#ifdef HAVE_BLKID
+ UDEV_BUILTIN_BLKID,
+#endif
+ UDEV_BUILTIN_BTRFS,
+#ifdef HAVE_FIRMWARE
+ UDEV_BUILTIN_FIRMWARE,
+#endif
+ UDEV_BUILTIN_HWDB,
+ UDEV_BUILTIN_INPUT_ID,
+#ifdef HAVE_KMOD
+ UDEV_BUILTIN_KMOD,
+#endif
+ UDEV_BUILTIN_NET_ID,
+ UDEV_BUILTIN_PATH_ID,
+ UDEV_BUILTIN_USB_ID,
+#ifdef HAVE_ACL
+ UDEV_BUILTIN_UACCESS,
+#endif
+ UDEV_BUILTIN_MAX
+};
+struct udev_builtin {
+ const char *name;
+ int (*cmd)(struct udev_device *dev, int argc, char *argv[], bool test);
+ const char *help;
+ int (*init)(struct udev *udev);
+ void (*exit)(struct udev *udev);
+ bool (*validate)(struct udev *udev);
+ bool run_once;
+};
+#ifdef HAVE_BLKID
+extern const struct udev_builtin udev_builtin_blkid;
+#endif
+extern const struct udev_builtin udev_builtin_btrfs;
+#ifdef HAVE_FIRMWARE
+extern const struct udev_builtin udev_builtin_firmware;
+#endif
+extern const struct udev_builtin udev_builtin_hwdb;
+extern const struct udev_builtin udev_builtin_input_id;
+#ifdef HAVE_KMOD
+extern const struct udev_builtin udev_builtin_kmod;
+#endif
+extern const struct udev_builtin udev_builtin_net_id;
+extern const struct udev_builtin udev_builtin_path_id;
+extern const struct udev_builtin udev_builtin_usb_id;
+extern const struct udev_builtin udev_builtin_uaccess;
+void udev_builtin_init(struct udev *udev);
+void udev_builtin_exit(struct udev *udev);
+enum udev_builtin_cmd udev_builtin_lookup(const char *command);
+const char *udev_builtin_name(enum udev_builtin_cmd cmd);
+bool udev_builtin_run_once(enum udev_builtin_cmd cmd);
+int udev_builtin_run(struct udev_device *dev, enum udev_builtin_cmd cmd, const char *command, bool test);
+void udev_builtin_list(struct udev *udev);
+bool udev_builtin_validate(struct udev *udev);
+int udev_builtin_add_property(struct udev_device *dev, bool test, const char *key, const char *val);
+int udev_builtin_hwdb_lookup(struct udev_device *dev, const char *modalias, bool test);
+
+/* udev logging */
+void udev_main_log(struct udev *udev, int priority,
+ const char *file, int line, const char *fn,
+ const char *format, va_list args) _printf_attr_(6, 0);
+
+/* udevadm commands */
+struct udevadm_cmd {
+ const char *name;
+ int (*cmd)(struct udev *udev, int argc, char *argv[]);
+ const char *help;
+ int debug;
+};
+extern const struct udevadm_cmd udevadm_info;
+extern const struct udevadm_cmd udevadm_trigger;
+extern const struct udevadm_cmd udevadm_settle;
+extern const struct udevadm_cmd udevadm_control;
+extern const struct udevadm_cmd udevadm_monitor;
+extern const struct udevadm_cmd udevadm_hwdb;
+extern const struct udevadm_cmd udevadm_test;
+extern const struct udevadm_cmd udevadm_test_builtin;
diff --git a/src/udev/udev.pc.in b/src/udev/udev.pc.in
new file mode 100644
index 0000000000..a0c2e82d47
--- /dev/null
+++ b/src/udev/udev.pc.in
@@ -0,0 +1,5 @@
+Name: udev
+Description: udev
+Version: @VERSION@
+
+udevdir=@udevlibexecdir@
diff --git a/src/udev/udevadm-control.c b/src/udev/udevadm-control.c
new file mode 100644
index 0000000000..c5a189257d
--- /dev/null
+++ b/src/udev/udevadm-control.c
@@ -0,0 +1,175 @@
+/*
+ * Copyright (C) 2005-2011 Kay Sievers <kay@vrfy.org>
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <time.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <string.h>
+#include <unistd.h>
+#include <getopt.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/wait.h>
+#include <sys/un.h>
+
+#include "udev.h"
+
+static void print_help(void)
+{
+ printf("Usage: udevadm control COMMAND\n"
+ " --exit instruct the daemon to cleanup and exit\n"
+ " --log-priority=<level> set the udev log level for the daemon\n"
+ " --stop-exec-queue do not execute events, queue only\n"
+ " --start-exec-queue execute events, flush queue\n"
+ " --reload reload rules and databases\n"
+ " --property=<KEY>=<value> set a global property for all events\n"
+ " --children-max=<N> maximum number of children\n"
+ " --timeout=<seconds> maximum time to block for a reply\n"
+ " --help print this help text\n\n");
+}
+
+static int adm_control(struct udev *udev, int argc, char *argv[])
+{
+ struct udev_ctrl *uctrl = NULL;
+ int timeout = 60;
+ int rc = 1;
+
+ static const struct option options[] = {
+ { "exit", no_argument, NULL, 'e' },
+ { "log-priority", required_argument, NULL, 'l' },
+ { "stop-exec-queue", no_argument, NULL, 's' },
+ { "start-exec-queue", no_argument, NULL, 'S' },
+ { "reload", no_argument, NULL, 'R' },
+ { "reload-rules", no_argument, NULL, 'R' },
+ { "property", required_argument, NULL, 'p' },
+ { "env", required_argument, NULL, 'p' },
+ { "children-max", required_argument, NULL, 'm' },
+ { "timeout", required_argument, NULL, 't' },
+ { "help", no_argument, NULL, 'h' },
+ {}
+ };
+
+ if (getuid() != 0) {
+ fprintf(stderr, "root privileges required\n");
+ return 1;
+ }
+
+ uctrl = udev_ctrl_new(udev);
+ if (uctrl == NULL)
+ return 2;
+
+ for (;;) {
+ int option;
+
+ option = getopt_long(argc, argv, "el:sSRp:m:h", options, NULL);
+ if (option == -1)
+ break;
+
+ switch (option) {
+ case 'e':
+ if (udev_ctrl_send_exit(uctrl, timeout) < 0)
+ rc = 2;
+ else
+ rc = 0;
+ break;
+ case 'l': {
+ int i;
+
+ i = util_log_priority(optarg);
+ if (i < 0) {
+ fprintf(stderr, "invalid number '%s'\n", optarg);
+ goto out;
+ }
+ if (udev_ctrl_send_set_log_level(uctrl, util_log_priority(optarg), timeout) < 0)
+ rc = 2;
+ else
+ rc = 0;
+ break;
+ }
+ case 's':
+ if (udev_ctrl_send_stop_exec_queue(uctrl, timeout) < 0)
+ rc = 2;
+ else
+ rc = 0;
+ break;
+ case 'S':
+ if (udev_ctrl_send_start_exec_queue(uctrl, timeout) < 0)
+ rc = 2;
+ else
+ rc = 0;
+ break;
+ case 'R':
+ if (udev_ctrl_send_reload(uctrl, timeout) < 0)
+ rc = 2;
+ else
+ rc = 0;
+ break;
+ case 'p':
+ if (strchr(optarg, '=') == NULL) {
+ fprintf(stderr, "expect <KEY>=<value> instead of '%s'\n", optarg);
+ goto out;
+ }
+ if (udev_ctrl_send_set_env(uctrl, optarg, timeout) < 0)
+ rc = 2;
+ else
+ rc = 0;
+ break;
+ case 'm': {
+ char *endp;
+ int i;
+
+ i = strtoul(optarg, &endp, 0);
+ if (endp[0] != '\0' || i < 1) {
+ fprintf(stderr, "invalid number '%s'\n", optarg);
+ goto out;
+ }
+ if (udev_ctrl_send_set_children_max(uctrl, i, timeout) < 0)
+ rc = 2;
+ else
+ rc = 0;
+ break;
+ }
+ case 't': {
+ int seconds;
+
+ seconds = atoi(optarg);
+ if (seconds >= 0)
+ timeout = seconds;
+ else
+ fprintf(stderr, "invalid timeout value\n");
+ break;
+ }
+ case 'h':
+ print_help();
+ rc = 0;
+ break;
+ }
+ }
+
+ if (argv[optind] != NULL)
+ fprintf(stderr, "unknown option\n");
+ else if (optind == 1)
+ fprintf(stderr, "missing option\n");
+out:
+ udev_ctrl_unref(uctrl);
+ return rc;
+}
+
+const struct udevadm_cmd udevadm_control = {
+ .name = "control",
+ .cmd = adm_control,
+ .help = "control the udev daemon",
+};
diff --git a/src/udev/udevadm-hwdb.c b/src/udev/udevadm-hwdb.c
new file mode 100644
index 0000000000..3e849aaed6
--- /dev/null
+++ b/src/udev/udevadm-hwdb.c
@@ -0,0 +1,609 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Kay Sievers <kay@vrfy.org>
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdlib.h>
+#include <unistd.h>
+#include <getopt.h>
+#include <string.h>
+
+#include "util.h"
+#include "strbuf.h"
+#include "conf-files.h"
+
+#include "udev.h"
+#include "libudev-hwdb-def.h"
+
+/*
+ * Generic udev properties, key/value database based on modalias strings.
+ * Uses a Patricia/radix trie to index all matches for efficient lookup.
+ */
+
+static const char * const conf_file_dirs[] = {
+ "/etc/udev/hwdb.d",
+ UDEVLIBEXECDIR "/hwdb.d",
+ NULL
+};
+
+/* in-memory trie objects */
+struct trie {
+ struct trie_node *root;
+ struct strbuf *strings;
+
+ size_t nodes_count;
+ size_t children_count;
+ size_t values_count;
+};
+
+struct trie_node {
+ /* prefix, common part for all children of this node */
+ size_t prefix_off;
+
+ /* sorted array of pointers to children nodes */
+ struct trie_child_entry *children;
+ uint8_t children_count;
+
+ /* sorted array of key/value pairs */
+ struct trie_value_entry *values;
+ size_t values_count;
+};
+
+/* children array item with char (0-255) index */
+struct trie_child_entry {
+ uint8_t c;
+ struct trie_node *child;
+};
+
+/* value array item with key/value pairs */
+struct trie_value_entry {
+ size_t key_off;
+ size_t value_off;
+};
+
+static int trie_children_cmp(const void *v1, const void *v2) {
+ const struct trie_child_entry *n1 = v1;
+ const struct trie_child_entry *n2 = v2;
+
+ return n1->c - n2->c;
+}
+
+static int node_add_child(struct trie *trie, struct trie_node *node, struct trie_node *node_child, uint8_t c) {
+ struct trie_child_entry *child;
+
+ /* extend array, add new entry, sort for bisection */
+ child = realloc(node->children, (node->children_count + 1) * sizeof(struct trie_child_entry));
+ if (!child)
+ return -ENOMEM;
+
+ node->children = child;
+ trie->children_count++;
+ node->children[node->children_count].c = c;
+ node->children[node->children_count].child = node_child;
+ node->children_count++;
+ qsort(node->children, node->children_count, sizeof(struct trie_child_entry), trie_children_cmp);
+ trie->nodes_count++;
+
+ return 0;
+}
+
+static struct trie_node *node_lookup(const struct trie_node *node, uint8_t c) {
+ struct trie_child_entry *child;
+ struct trie_child_entry search;
+
+ search.c = c;
+ child = bsearch(&search, node->children, node->children_count, sizeof(struct trie_child_entry), trie_children_cmp);
+ if (child)
+ return child->child;
+ return NULL;
+}
+
+static void trie_node_cleanup(struct trie_node *node) {
+ size_t i;
+
+ for (i = 0; i < node->children_count; i++)
+ trie_node_cleanup(node->children[i].child);
+ free(node->children);
+ free(node->values);
+ free(node);
+}
+
+static int trie_values_cmp(const void *v1, const void *v2, void *arg) {
+ const struct trie_value_entry *val1 = v1;
+ const struct trie_value_entry *val2 = v2;
+ struct trie *trie = arg;
+
+ return strcmp(trie->strings->buf + val1->key_off,
+ trie->strings->buf + val2->key_off);
+}
+
+static int trie_node_add_value(struct trie *trie, struct trie_node *node,
+ const char *key, const char *value) {
+ ssize_t k, v;
+ struct trie_value_entry *val;
+
+ k = strbuf_add_string(trie->strings, key, strlen(key));
+ if (k < 0)
+ return k;
+ v = strbuf_add_string(trie->strings, value, strlen(value));
+ if (v < 0)
+ return v;
+
+ if (node->values_count) {
+ struct trie_value_entry search = {
+ .key_off = k,
+ .value_off = v,
+ };
+
+ val = xbsearch_r(&search, node->values, node->values_count, sizeof(struct trie_value_entry), trie_values_cmp, trie);
+ if (val) {
+ /* replace existing earlier key with new value */
+ val->value_off = v;
+ return 0;
+ }
+ }
+
+ /* extend array, add new entry, sort for bisection */
+ val = realloc(node->values, (node->values_count + 1) * sizeof(struct trie_value_entry));
+ if (!val)
+ return -ENOMEM;
+ trie->values_count++;
+ node->values = val;
+ node->values[node->values_count].key_off = k;
+ node->values[node->values_count].value_off = v;
+ node->values_count++;
+ qsort_r(node->values, node->values_count, sizeof(struct trie_value_entry), trie_values_cmp, trie);
+ return 0;
+}
+
+static int trie_insert(struct trie *trie, struct trie_node *node, const char *search,
+ const char *key, const char *value) {
+ size_t i = 0;
+ int err = 0;
+
+ for (;;) {
+ size_t p;
+ uint8_t c;
+ struct trie_node *child;
+
+ for (p = 0; (c = trie->strings->buf[node->prefix_off + p]); p++) {
+ _cleanup_free_ char *s = NULL;
+ ssize_t off;
+ _cleanup_free_ struct trie_node *new_child = NULL;
+
+ if (c == search[i + p])
+ continue;
+
+ /* split node */
+ new_child = calloc(sizeof(struct trie_node), 1);
+ if (!new_child)
+ return -ENOMEM;
+
+ /* move values from parent to child */
+ new_child->prefix_off = node->prefix_off + p+1;
+ new_child->children = node->children;
+ new_child->children_count = node->children_count;
+ new_child->values = node->values;
+ new_child->values_count = node->values_count;
+
+ /* update parent; use strdup() because the source gets realloc()d */
+ s = strndup(trie->strings->buf + node->prefix_off, p);
+ if (!s)
+ return -ENOMEM;
+
+ off = strbuf_add_string(trie->strings, s, p);
+ if (off < 0)
+ return off;
+
+ node->prefix_off = off;
+ node->children = NULL;
+ node->children_count = 0;
+ node->values = NULL;
+ node->values_count = 0;
+ err = node_add_child(trie, node, new_child, c);
+ if (err)
+ return err;
+
+ new_child = NULL; /* avoid cleanup */
+ break;
+ }
+ i += p;
+
+ c = search[i];
+ if (c == '\0')
+ return trie_node_add_value(trie, node, key, value);
+
+ child = node_lookup(node, c);
+ if (!child) {
+ ssize_t off;
+
+ /* new child */
+ child = calloc(sizeof(struct trie_node), 1);
+ if (!child)
+ return -ENOMEM;
+
+ off = strbuf_add_string(trie->strings, search + i+1, strlen(search + i+1));
+ if (off < 0) {
+ free(child);
+ return off;
+ }
+
+ child->prefix_off = off;
+ err = node_add_child(trie, node, child, c);
+ if (err) {
+ free(child);
+ return err;
+ }
+
+ return trie_node_add_value(trie, child, key, value);
+ }
+
+ node = child;
+ i++;
+ }
+}
+
+struct trie_f {
+ FILE *f;
+ struct trie *trie;
+ uint64_t strings_off;
+
+ uint64_t nodes_count;
+ uint64_t children_count;
+ uint64_t values_count;
+};
+
+/* calculate the storage space for the nodes, children arrays, value arrays */
+static void trie_store_nodes_size(struct trie_f *trie, struct trie_node *node) {
+ uint64_t i;
+
+ for (i = 0; i < node->children_count; i++)
+ trie_store_nodes_size(trie, node->children[i].child);
+
+ trie->strings_off += sizeof(struct trie_node_f);
+ for (i = 0; i < node->children_count; i++)
+ trie->strings_off += sizeof(struct trie_child_entry_f);
+ for (i = 0; i < node->values_count; i++)
+ trie->strings_off += sizeof(struct trie_value_entry_f);
+}
+
+static int64_t trie_store_nodes(struct trie_f *trie, struct trie_node *node) {
+ uint64_t i;
+ struct trie_node_f n = {
+ .prefix_off = htole64(trie->strings_off + node->prefix_off),
+ .children_count = node->children_count,
+ .values_count = htole64(node->values_count),
+ };
+ struct trie_child_entry_f *children = NULL;
+ int64_t node_off;
+
+ if (node->children_count) {
+ children = new0(struct trie_child_entry_f, node->children_count);
+ if (!children)
+ return -ENOMEM;
+ }
+
+ /* post-order recursion */
+ for (i = 0; i < node->children_count; i++) {
+ int64_t child_off;
+
+ child_off = trie_store_nodes(trie, node->children[i].child);
+ if (child_off < 0)
+ return child_off;
+ children[i].c = node->children[i].c;
+ children[i].child_off = htole64(child_off);
+ }
+
+ /* write node */
+ node_off = ftello(trie->f);
+ fwrite(&n, sizeof(struct trie_node_f), 1, trie->f);
+ trie->nodes_count++;
+
+ /* append children array */
+ if (node->children_count) {
+ fwrite(children, sizeof(struct trie_child_entry_f), node->children_count, trie->f);
+ trie->children_count += node->children_count;
+ free(children);
+ }
+
+ /* append values array */
+ for (i = 0; i < node->values_count; i++) {
+ struct trie_value_entry_f v = {
+ .key_off = htole64(trie->strings_off + node->values[i].key_off),
+ .value_off = htole64(trie->strings_off + node->values[i].value_off),
+ };
+
+ fwrite(&v, sizeof(struct trie_value_entry_f), 1, trie->f);
+ trie->values_count++;
+ }
+
+ return node_off;
+}
+
+static int trie_store(struct trie *trie, const char *filename) {
+ struct trie_f t = {
+ .trie = trie,
+ };
+ char *filename_tmp;
+ int64_t pos;
+ int64_t root_off;
+ int64_t size;
+ struct trie_header_f h = {
+ .signature = HWDB_SIG,
+ .tool_version = htole64(atoi(VERSION)),
+ .header_size = htole64(sizeof(struct trie_header_f)),
+ .node_size = htole64(sizeof(struct trie_node_f)),
+ .child_entry_size = htole64(sizeof(struct trie_child_entry_f)),
+ .value_entry_size = htole64(sizeof(struct trie_value_entry_f)),
+ };
+ int err;
+
+ /* calculate size of header, nodes, children entries, value entries */
+ t.strings_off = sizeof(struct trie_header_f);
+ trie_store_nodes_size(&t, trie->root);
+
+ err = fopen_temporary(filename , &t.f, &filename_tmp);
+ if (err < 0)
+ return err;
+ fchmod(fileno(t.f), 0444);
+
+ /* write nodes */
+ fseeko(t.f, sizeof(struct trie_header_f), SEEK_SET);
+ root_off = trie_store_nodes(&t, trie->root);
+ h.nodes_root_off = htole64(root_off);
+ pos = ftello(t.f);
+ h.nodes_len = htole64(pos - sizeof(struct trie_header_f));
+
+ /* write string buffer */
+ fwrite(trie->strings->buf, trie->strings->len, 1, t.f);
+ h.strings_len = htole64(trie->strings->len);
+
+ /* write header */
+ size = ftello(t.f);
+ h.file_size = htole64(size);
+ fseeko(t.f, 0, SEEK_SET);
+ fwrite(&h, sizeof(struct trie_header_f), 1, t.f);
+ err = ferror(t.f);
+ if (err)
+ err = -errno;
+ fclose(t.f);
+ if (err < 0 || rename(filename_tmp, filename) < 0) {
+ unlink(filename_tmp);
+ goto out;
+ }
+
+ log_debug("=== trie on-disk ===\n");
+ log_debug("size: %8llu bytes\n", (unsigned long long)size);
+ log_debug("header: %8zu bytes\n", sizeof(struct trie_header_f));
+ log_debug("nodes: %8llu bytes (%8llu)\n",
+ (unsigned long long)t.nodes_count * sizeof(struct trie_node_f), (unsigned long long)t.nodes_count);
+ log_debug("child pointers: %8llu bytes (%8llu)\n",
+ (unsigned long long)t.children_count * sizeof(struct trie_child_entry_f), (unsigned long long)t.children_count);
+ log_debug("value pointers: %8llu bytes (%8llu)\n",
+ (unsigned long long)t.values_count * sizeof(struct trie_value_entry_f), (unsigned long long)t.values_count);
+ log_debug("string store: %8llu bytes\n", (unsigned long long)trie->strings->len);
+ log_debug("strings start: %8llu\n", (unsigned long long) t.strings_off);
+out:
+ free(filename_tmp);
+ return err;
+}
+
+static int import_file(struct trie *trie, const char *filename) {
+ FILE *f;
+ char line[LINE_MAX];
+ char match[LINE_MAX];
+ char cond[LINE_MAX];
+
+ f = fopen(filename, "re");
+ if (f == NULL)
+ return -errno;
+
+ match[0] = '\0';
+ cond[0] = '\0';
+ while (fgets(line, sizeof(line), f)) {
+ size_t len;
+
+ if (line[0] == '#')
+ continue;
+
+ /* new line, new record */
+ if (line[0] == '\n') {
+ match[0] = '\0';
+ cond[0] = '\0';
+ continue;
+ }
+
+ /* remove newline */
+ len = strlen(line);
+ if (len < 2)
+ continue;
+ line[len-1] = '\0';
+
+ /* start of new record */
+ if (match[0] == '\0') {
+ strcpy(match, line);
+ cond[0] = '\0';
+ continue;
+ }
+
+ if (line[0] == '+') {
+ strcpy(cond, line);
+ continue;
+ }
+
+ /* TODO: support +; skip the entire record until we support it */
+ if (cond[0] != '\0')
+ continue;
+
+ /* value lines */
+ if (line[0] == ' ') {
+ char *value;
+
+ value = strchr(line, '=');
+ if (!value)
+ continue;
+ value[0] = '\0';
+ value++;
+ trie_insert(trie, trie->root, match, line, value);
+ }
+ }
+ fclose(f);
+ return 0;
+}
+
+static void help(void) {
+ printf("Usage: udevadm hwdb OPTIONS\n"
+ " --update update the hardware database\n"
+ " --test=<modalias> query database and print result\n"
+ " --root=<path> alternative root path in the filesystem\n"
+ " --help\n\n");
+}
+
+static int adm_hwdb(struct udev *udev, int argc, char *argv[]) {
+ static const struct option options[] = {
+ { "update", no_argument, NULL, 'u' },
+ { "root", required_argument, NULL, 'r' },
+ { "test", required_argument, NULL, 't' },
+ { "help", no_argument, NULL, 'h' },
+ {}
+ };
+ const char *test = NULL;
+ const char *root = "";
+ bool update = false;
+ struct trie *trie = NULL;
+ int err;
+ int rc = EXIT_SUCCESS;
+
+ for (;;) {
+ int option;
+
+ option = getopt_long(argc, argv, "ut:r:h", options, NULL);
+ if (option == -1)
+ break;
+
+ switch (option) {
+ case 'u':
+ update = true;
+ break;
+ case 't':
+ test = optarg;
+ break;
+ case 'r':
+ root = optarg;
+ break;
+ case 'h':
+ help();
+ return EXIT_SUCCESS;
+ }
+ }
+
+ if (!update && !test) {
+ help();
+ return EXIT_SUCCESS;
+ }
+
+ if (update) {
+ char **files, **f;
+ _cleanup_free_ char *hwdb_bin = NULL;
+
+ trie = calloc(sizeof(struct trie), 1);
+ if (!trie) {
+ rc = EXIT_FAILURE;
+ goto out;
+ }
+
+ /* string store */
+ trie->strings = strbuf_new();
+ if (!trie->strings) {
+ rc = EXIT_FAILURE;
+ goto out;
+ }
+
+ /* index */
+ trie->root = calloc(sizeof(struct trie_node), 1);
+ if (!trie->root) {
+ rc = EXIT_FAILURE;
+ goto out;
+ }
+ trie->nodes_count++;
+
+ err = conf_files_list_strv(&files, ".hwdb", root, conf_file_dirs);
+ if (err < 0) {
+ log_error("failed to enumerate hwdb files: %s\n", strerror(-err));
+ rc = EXIT_FAILURE;
+ goto out;
+ }
+ STRV_FOREACH(f, files) {
+ log_debug("reading file '%s'", *f);
+ import_file(trie, *f);
+ }
+ strv_free(files);
+
+ strbuf_complete(trie->strings);
+
+ log_debug("=== trie in-memory ===\n");
+ log_debug("nodes: %8zu bytes (%8zu)\n",
+ trie->nodes_count * sizeof(struct trie_node), trie->nodes_count);
+ log_debug("children arrays: %8zu bytes (%8zu)\n",
+ trie->children_count * sizeof(struct trie_child_entry), trie->children_count);
+ log_debug("values arrays: %8zu bytes (%8zu)\n",
+ trie->values_count * sizeof(struct trie_value_entry), trie->values_count);
+ log_debug("strings: %8zu bytes\n",
+ trie->strings->len);
+ log_debug("strings incoming: %8zu bytes (%8zu)\n",
+ trie->strings->in_len, trie->strings->in_count);
+ log_debug("strings dedup'ed: %8zu bytes (%8zu)\n",
+ trie->strings->dedup_len, trie->strings->dedup_count);
+
+ if (asprintf(&hwdb_bin, "%s/etc/udev/hwdb.bin", root) < 0) {
+ rc = EXIT_FAILURE;
+ goto out;
+ }
+ mkdir_parents(hwdb_bin, 0755);
+ err = trie_store(trie, hwdb_bin);
+ if (err < 0) {
+ log_error("Failure writing database %s: %s", hwdb_bin, strerror(-err));
+ rc = EXIT_FAILURE;
+ }
+ }
+
+ if (test) {
+ struct udev_hwdb *hwdb = udev_hwdb_new(udev);
+
+ if (hwdb) {
+ struct udev_list_entry *entry;
+
+ udev_list_entry_foreach(entry, udev_hwdb_get_properties_list_entry(hwdb, test, 0))
+ printf("%s=%s\n", udev_list_entry_get_name(entry), udev_list_entry_get_value(entry));
+ hwdb = udev_hwdb_unref(hwdb);
+ }
+ }
+out:
+ if (trie) {
+ if (trie->root)
+ trie_node_cleanup(trie->root);
+ strbuf_cleanup(trie->strings);
+ free(trie);
+ }
+ return rc;
+}
+
+const struct udevadm_cmd udevadm_hwdb = {
+ .name = "hwdb",
+ .cmd = adm_hwdb,
+ .help = "maintain the hardware database index",
+};
diff --git a/src/udev/udevadm-info.c b/src/udev/udevadm-info.c
new file mode 100644
index 0000000000..002876594f
--- /dev/null
+++ b/src/udev/udevadm-info.c
@@ -0,0 +1,544 @@
+/*
+ * Copyright (C) 2004-2009 Kay Sievers <kay@vrfy.org>
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <stddef.h>
+#include <ctype.h>
+#include <stdarg.h>
+#include <unistd.h>
+#include <dirent.h>
+#include <errno.h>
+#include <getopt.h>
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+
+#include "udev.h"
+
+static bool skip_attribute(const char *name)
+{
+ static const char* const skip[] = {
+ "uevent",
+ "dev",
+ "modalias",
+ "resource",
+ "driver",
+ "subsystem",
+ "module",
+ };
+ unsigned int i;
+
+ for (i = 0; i < ELEMENTSOF(skip); i++)
+ if (streq(name, skip[i]))
+ return true;
+ return false;
+}
+
+static void print_all_attributes(struct udev_device *device, const char *key)
+{
+ struct udev_list_entry *sysattr;
+
+ udev_list_entry_foreach(sysattr, udev_device_get_sysattr_list_entry(device)) {
+ const char *name;
+ const char *value;
+ size_t len;
+
+ name = udev_list_entry_get_name(sysattr);
+ if (skip_attribute(name))
+ continue;
+
+ value = udev_device_get_sysattr_value(device, name);
+ if (value == NULL)
+ continue;
+
+ /* skip any values that look like a path */
+ if (value[0] == '/')
+ continue;
+
+ /* skip nonprintable attributes */
+ len = strlen(value);
+ while (len > 0 && isprint(value[len-1]))
+ len--;
+ if (len > 0)
+ continue;
+
+ printf(" %s{%s}==\"%s\"\n", key, name, value);
+ }
+ printf("\n");
+}
+
+static int print_device_chain(struct udev_device *device)
+{
+ struct udev_device *device_parent;
+ const char *str;
+
+ printf("\n"
+ "Udevadm info starts with the device specified by the devpath and then\n"
+ "walks up the chain of parent devices. It prints for every device\n"
+ "found, all possible attributes in the udev rules key format.\n"
+ "A rule to match, can be composed by the attributes of the device\n"
+ "and the attributes from one single parent device.\n"
+ "\n");
+
+ printf(" looking at device '%s':\n", udev_device_get_devpath(device));
+ printf(" KERNEL==\"%s\"\n", udev_device_get_sysname(device));
+ str = udev_device_get_subsystem(device);
+ if (str == NULL)
+ str = "";
+ printf(" SUBSYSTEM==\"%s\"\n", str);
+ str = udev_device_get_driver(device);
+ if (str == NULL)
+ str = "";
+ printf(" DRIVER==\"%s\"\n", str);
+ print_all_attributes(device, "ATTR");
+
+ device_parent = device;
+ do {
+ device_parent = udev_device_get_parent(device_parent);
+ if (device_parent == NULL)
+ break;
+ printf(" looking at parent device '%s':\n", udev_device_get_devpath(device_parent));
+ printf(" KERNELS==\"%s\"\n", udev_device_get_sysname(device_parent));
+ str = udev_device_get_subsystem(device_parent);
+ if (str == NULL)
+ str = "";
+ printf(" SUBSYSTEMS==\"%s\"\n", str);
+ str = udev_device_get_driver(device_parent);
+ if (str == NULL)
+ str = "";
+ printf(" DRIVERS==\"%s\"\n", str);
+ print_all_attributes(device_parent, "ATTRS");
+ } while (device_parent != NULL);
+
+ return 0;
+}
+
+static void print_record(struct udev_device *device)
+{
+ const char *str;
+ int i;
+ struct udev_list_entry *list_entry;
+
+ printf("P: %s\n", udev_device_get_devpath(device));
+
+ str = udev_device_get_devnode(device);
+ if (str != NULL)
+ printf("N: %s\n", str + strlen("/dev/"));
+
+ i = udev_device_get_devlink_priority(device);
+ if (i != 0)
+ printf("L: %i\n", i);
+
+ udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(device))
+ printf("S: %s\n", udev_list_entry_get_name(list_entry) + strlen("/dev/"));
+
+ udev_list_entry_foreach(list_entry, udev_device_get_properties_list_entry(device))
+ printf("E: %s=%s\n",
+ udev_list_entry_get_name(list_entry),
+ udev_list_entry_get_value(list_entry));
+ printf("\n");
+}
+
+static int stat_device(const char *name, bool export, const char *prefix)
+{
+ struct stat statbuf;
+
+ if (stat(name, &statbuf) != 0)
+ return -1;
+
+ if (export) {
+ if (prefix == NULL)
+ prefix = "INFO_";
+ printf("%sMAJOR=%d\n"
+ "%sMINOR=%d\n",
+ prefix, major(statbuf.st_dev),
+ prefix, minor(statbuf.st_dev));
+ } else
+ printf("%d:%d\n", major(statbuf.st_dev), minor(statbuf.st_dev));
+ return 0;
+}
+
+static int export_devices(struct udev *udev)
+{
+ struct udev_enumerate *udev_enumerate;
+ struct udev_list_entry *list_entry;
+
+ udev_enumerate = udev_enumerate_new(udev);
+ if (udev_enumerate == NULL)
+ return -1;
+ udev_enumerate_scan_devices(udev_enumerate);
+ udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(udev_enumerate)) {
+ struct udev_device *device;
+
+ device = udev_device_new_from_syspath(udev, udev_list_entry_get_name(list_entry));
+ if (device != NULL) {
+ print_record(device);
+ udev_device_unref(device);
+ }
+ }
+ udev_enumerate_unref(udev_enumerate);
+ return 0;
+}
+
+static void cleanup_dir(DIR *dir, mode_t mask, int depth)
+{
+ struct dirent *dent;
+
+ if (depth <= 0)
+ return;
+
+ for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
+ struct stat stats;
+
+ if (dent->d_name[0] == '.')
+ continue;
+ if (fstatat(dirfd(dir), dent->d_name, &stats, AT_SYMLINK_NOFOLLOW) != 0)
+ continue;
+ if ((stats.st_mode & mask) != 0)
+ continue;
+ if (S_ISDIR(stats.st_mode)) {
+ DIR *dir2;
+
+ dir2 = fdopendir(openat(dirfd(dir), dent->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC));
+ if (dir2 != NULL) {
+ cleanup_dir(dir2, mask, depth-1);
+ closedir(dir2);
+ }
+ unlinkat(dirfd(dir), dent->d_name, AT_REMOVEDIR);
+ } else {
+ unlinkat(dirfd(dir), dent->d_name, 0);
+ }
+ }
+}
+
+static void cleanup_db(struct udev *udev)
+{
+ DIR *dir;
+
+ unlink("/run/udev/queue.bin");
+
+ dir = opendir("/run/udev/data");
+ if (dir != NULL) {
+ cleanup_dir(dir, S_ISVTX, 1);
+ closedir(dir);
+ }
+
+ dir = opendir("/run/udev/links");
+ if (dir != NULL) {
+ cleanup_dir(dir, 0, 2);
+ closedir(dir);
+ }
+
+ dir = opendir("/run/udev/tags");
+ if (dir != NULL) {
+ cleanup_dir(dir, 0, 2);
+ closedir(dir);
+ }
+
+ dir = opendir("/run/udev/watch");
+ if (dir != NULL) {
+ cleanup_dir(dir, 0, 1);
+ closedir(dir);
+ }
+}
+
+static struct udev_device *find_device(struct udev *udev, const char *id, const char *prefix)
+{
+ char name[UTIL_PATH_SIZE];
+
+ if (prefix && !startswith(id, prefix)) {
+ strscpyl(name, sizeof(name), prefix, id, NULL);
+ id = name;
+ }
+
+ if (startswith(id, "/dev/")) {
+ struct stat statbuf;
+ char type;
+
+ if (stat(id, &statbuf) < 0)
+ return NULL;
+
+ if (S_ISBLK(statbuf.st_mode))
+ type = 'b';
+ else if (S_ISCHR(statbuf.st_mode))
+ type = 'c';
+ else
+ return NULL;
+
+ return udev_device_new_from_devnum(udev, type, statbuf.st_rdev);
+ } else if (startswith(id, "/sys/"))
+ return udev_device_new_from_syspath(udev, id);
+ else
+ return NULL;
+}
+
+static int uinfo(struct udev *udev, int argc, char *argv[])
+{
+ struct udev_device *device = NULL;
+ bool root = 0;
+ bool export = 0;
+ const char *export_prefix = NULL;
+ char name[UTIL_PATH_SIZE];
+ struct udev_list_entry *list_entry;
+ int rc = 0;
+
+ static const struct option options[] = {
+ { "name", required_argument, NULL, 'n' },
+ { "path", required_argument, NULL, 'p' },
+ { "query", required_argument, NULL, 'q' },
+ { "attribute-walk", no_argument, NULL, 'a' },
+ { "cleanup-db", no_argument, NULL, 'c' },
+ { "export-db", no_argument, NULL, 'e' },
+ { "root", no_argument, NULL, 'r' },
+ { "device-id-of-file", required_argument, NULL, 'd' },
+ { "export", no_argument, NULL, 'x' },
+ { "export-prefix", required_argument, NULL, 'P' },
+ { "version", no_argument, NULL, 'V' },
+ { "help", no_argument, NULL, 'h' },
+ {}
+ };
+
+ static const char *usage =
+ "Usage: udevadm info OPTIONS\n"
+ " --query=<type> query device information:\n"
+ " name name of device node\n"
+ " symlink pointing to node\n"
+ " path sys device path\n"
+ " property the device properties\n"
+ " all all values\n"
+ " --path=<syspath> sys device path used for query or attribute walk\n"
+ " --name=<name> node or symlink name used for query or attribute walk\n"
+ " --root prepend dev directory to path names\n"
+ " --attribute-walk print all key matches while walking along the chain\n"
+ " of parent devices\n"
+ " --device-id-of-file=<file> print major:minor of device containing this file\n"
+ " --export export key/value pairs\n"
+ " --export-prefix export the key name with a prefix\n"
+ " --export-db export the content of the udev database\n"
+ " --cleanup-db cleanup the udev database\n"
+ " --help\n";
+
+ enum action_type {
+ ACTION_QUERY,
+ ACTION_ATTRIBUTE_WALK,
+ ACTION_DEVICE_ID_FILE,
+ } action = ACTION_QUERY;
+
+ enum query_type {
+ QUERY_NAME,
+ QUERY_PATH,
+ QUERY_SYMLINK,
+ QUERY_PROPERTY,
+ QUERY_ALL,
+ } query = QUERY_ALL;
+
+ for (;;) {
+ int option;
+
+ option = getopt_long(argc, argv, "aced:n:p:q:rxP:RVh", options, NULL);
+ if (option == -1)
+ break;
+
+ switch (option) {
+ case 'n': {
+ if (device != NULL) {
+ fprintf(stderr, "device already specified\n");
+ rc = 2;
+ goto exit;
+ }
+
+ device = find_device(udev, optarg, "/dev/");
+ if (device == NULL) {
+ fprintf(stderr, "device node not found\n");
+ rc = 2;
+ goto exit;
+ }
+ break;
+ }
+ case 'p':
+ if (device != NULL) {
+ fprintf(stderr, "device already specified\n");
+ rc = 2;
+ goto exit;
+ }
+
+ device = find_device(udev, optarg, "/sys");
+ if (device == NULL) {
+ fprintf(stderr, "syspath not found\n");
+ rc = 2;
+ goto exit;
+ }
+ break;
+ case 'q':
+ action = ACTION_QUERY;
+ if (streq(optarg, "property") || streq(optarg, "env")) {
+ query = QUERY_PROPERTY;
+ } else if (streq(optarg, "name")) {
+ query = QUERY_NAME;
+ } else if (streq(optarg, "symlink")) {
+ query = QUERY_SYMLINK;
+ } else if (streq(optarg, "path")) {
+ query = QUERY_PATH;
+ } else if (streq(optarg, "all")) {
+ query = QUERY_ALL;
+ } else {
+ fprintf(stderr, "unknown query type\n");
+ rc = 3;
+ goto exit;
+ }
+ break;
+ case 'r':
+ root = true;
+ break;
+ case 'd':
+ action = ACTION_DEVICE_ID_FILE;
+ strscpy(name, sizeof(name), optarg);
+ break;
+ case 'a':
+ action = ACTION_ATTRIBUTE_WALK;
+ break;
+ case 'e':
+ export_devices(udev);
+ goto exit;
+ case 'c':
+ cleanup_db(udev);
+ goto exit;
+ case 'x':
+ export = true;
+ break;
+ case 'P':
+ export_prefix = optarg;
+ break;
+ case 'V':
+ printf("%s\n", VERSION);
+ goto exit;
+ case 'h':
+ printf("%s\n", usage);
+ goto exit;
+ default:
+ rc = 1;
+ goto exit;
+ }
+ }
+
+ switch (action) {
+ case ACTION_QUERY:
+ if (!device) {
+ if (!argv[optind]) {
+ fprintf(stderr, "%s\n", usage);
+ rc = 2;
+ goto exit;
+ }
+ device = find_device(udev, argv[optind], NULL);
+ if (!device) {
+ fprintf(stderr, "Unknown device, --name=, --path=, or absolute path in /dev/ or /sys expected.\n");
+ rc = 4;
+ goto exit;
+ }
+ }
+
+ switch(query) {
+ case QUERY_NAME: {
+ const char *node = udev_device_get_devnode(device);
+
+ if (node == NULL) {
+ fprintf(stderr, "no device node found\n");
+ rc = 5;
+ goto exit;
+ }
+
+ if (root)
+ printf("%s\n", udev_device_get_devnode(device));
+ else
+ printf("%s\n", udev_device_get_devnode(device) + strlen("/dev/"));
+ break;
+ }
+ case QUERY_SYMLINK:
+ list_entry = udev_device_get_devlinks_list_entry(device);
+ while (list_entry != NULL) {
+ if (root)
+ printf("%s", udev_list_entry_get_name(list_entry));
+ else
+ printf("%s", udev_list_entry_get_name(list_entry) + strlen("/dev/"));
+ list_entry = udev_list_entry_get_next(list_entry);
+ if (list_entry != NULL)
+ printf(" ");
+ }
+ printf("\n");
+ break;
+ case QUERY_PATH:
+ printf("%s\n", udev_device_get_devpath(device));
+ goto exit;
+ case QUERY_PROPERTY:
+ list_entry = udev_device_get_properties_list_entry(device);
+ while (list_entry != NULL) {
+ if (export) {
+ const char *prefix = export_prefix;
+
+ if (prefix == NULL)
+ prefix = "";
+ printf("%s%s='%s'\n", prefix,
+ udev_list_entry_get_name(list_entry),
+ udev_list_entry_get_value(list_entry));
+ } else {
+ printf("%s=%s\n", udev_list_entry_get_name(list_entry), udev_list_entry_get_value(list_entry));
+ }
+ list_entry = udev_list_entry_get_next(list_entry);
+ }
+ break;
+ case QUERY_ALL:
+ print_record(device);
+ break;
+ default:
+ fprintf(stderr, "unknown query type\n");
+ break;
+ }
+ break;
+ case ACTION_ATTRIBUTE_WALK:
+ if (!device && argv[optind]) {
+ device = find_device(udev, argv[optind], NULL);
+ if (!device) {
+ fprintf(stderr, "Unknown device, absolute path in /dev/ or /sys expected.\n");
+ rc = 4;
+ goto exit;
+ }
+ }
+ if (!device) {
+ fprintf(stderr, "Unknown device, --name=, --path=, or absolute path in /dev/ or /sys expected.\n");
+ rc = 4;
+ goto exit;
+ }
+ print_device_chain(device);
+ break;
+ case ACTION_DEVICE_ID_FILE:
+ if (stat_device(name, export, export_prefix) != 0)
+ rc = 1;
+ break;
+ }
+
+exit:
+ udev_device_unref(device);
+ return rc;
+}
+
+const struct udevadm_cmd udevadm_info = {
+ .name = "info",
+ .cmd = uinfo,
+ .help = "query sysfs or the udev database",
+};
diff --git a/src/udev/udevadm-monitor.c b/src/udev/udevadm-monitor.c
new file mode 100644
index 0000000000..a390ee6c34
--- /dev/null
+++ b/src/udev/udevadm-monitor.c
@@ -0,0 +1,297 @@
+/*
+ * Copyright (C) 2004-2010 Kay Sievers <kay@vrfy.org>
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <unistd.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <string.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <signal.h>
+#include <getopt.h>
+#include <time.h>
+#include <sys/time.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <sys/epoll.h>
+#include <linux/types.h>
+#include <linux/netlink.h>
+
+#include "udev.h"
+
+static bool udev_exit;
+
+static void sig_handler(int signum)
+{
+ if (signum == SIGINT || signum == SIGTERM)
+ udev_exit = true;
+}
+
+static void print_device(struct udev_device *device, const char *source, int prop)
+{
+ struct timespec ts;
+
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ printf("%-6s[%llu.%06u] %-8s %s (%s)\n",
+ source,
+ (unsigned long long) ts.tv_sec, (unsigned int) ts.tv_nsec/1000,
+ udev_device_get_action(device),
+ udev_device_get_devpath(device),
+ udev_device_get_subsystem(device));
+ if (prop) {
+ struct udev_list_entry *list_entry;
+
+ udev_list_entry_foreach(list_entry, udev_device_get_properties_list_entry(device))
+ printf("%s=%s\n",
+ udev_list_entry_get_name(list_entry),
+ udev_list_entry_get_value(list_entry));
+ printf("\n");
+ }
+}
+
+static int adm_monitor(struct udev *udev, int argc, char *argv[])
+{
+ struct sigaction act;
+ sigset_t mask;
+ int option;
+ bool prop = false;
+ bool print_kernel = false;
+ bool print_udev = false;
+ struct udev_list subsystem_match_list;
+ struct udev_list tag_match_list;
+ struct udev_monitor *udev_monitor = NULL;
+ struct udev_monitor *kernel_monitor = NULL;
+ int fd_ep = -1;
+ int fd_kernel = -1, fd_udev = -1;
+ struct epoll_event ep_kernel, ep_udev;
+ int rc = 0;
+
+ static const struct option options[] = {
+ { "property", no_argument, NULL, 'p' },
+ { "environment", no_argument, NULL, 'e' },
+ { "kernel", no_argument, NULL, 'k' },
+ { "udev", no_argument, NULL, 'u' },
+ { "subsystem-match", required_argument, NULL, 's' },
+ { "tag-match", required_argument, NULL, 't' },
+ { "help", no_argument, NULL, 'h' },
+ {}
+ };
+
+ udev_list_init(udev, &subsystem_match_list, true);
+ udev_list_init(udev, &tag_match_list, true);
+
+ for (;;) {
+ option = getopt_long(argc, argv, "pekus:t:h", options, NULL);
+ if (option == -1)
+ break;
+
+ switch (option) {
+ case 'p':
+ case 'e':
+ prop = true;
+ break;
+ case 'k':
+ print_kernel = true;
+ break;
+ case 'u':
+ print_udev = true;
+ break;
+ case 's':
+ {
+ char subsys[UTIL_NAME_SIZE];
+ char *devtype;
+
+ strscpy(subsys, sizeof(subsys), optarg);
+ devtype = strchr(subsys, '/');
+ if (devtype != NULL) {
+ devtype[0] = '\0';
+ devtype++;
+ }
+ udev_list_entry_add(&subsystem_match_list, subsys, devtype);
+ break;
+ }
+ case 't':
+ udev_list_entry_add(&tag_match_list, optarg, NULL);
+ break;
+ case 'h':
+ printf("Usage: udevadm monitor [--property] [--kernel] [--udev] [--help]\n"
+ " --property print the event properties\n"
+ " --kernel print kernel uevents\n"
+ " --udev print udev events\n"
+ " --subsystem-match=<subsystem[/devtype]> filter events by subsystem\n"
+ " --tag-match=<tag> filter events by tag\n"
+ " --help\n\n");
+ goto out;
+ default:
+ rc = 1;
+ goto out;
+ }
+ }
+
+ if (!print_kernel && !print_udev) {
+ print_kernel = true;
+ print_udev = true;
+ }
+
+ /* set signal handlers */
+ memset(&act, 0x00, sizeof(struct sigaction));
+ act.sa_handler = sig_handler;
+ sigemptyset(&act.sa_mask);
+ act.sa_flags = SA_RESTART;
+ sigaction(SIGINT, &act, NULL);
+ sigaction(SIGTERM, &act, NULL);
+ sigemptyset(&mask);
+ sigaddset(&mask, SIGINT);
+ sigaddset(&mask, SIGTERM);
+ sigprocmask(SIG_UNBLOCK, &mask, NULL);
+
+ fd_ep = epoll_create1(EPOLL_CLOEXEC);
+ if (fd_ep < 0) {
+ log_error("error creating epoll fd: %m\n");
+ goto out;
+ }
+
+ printf("monitor will print the received events for:\n");
+ if (print_udev) {
+ struct udev_list_entry *entry;
+
+ udev_monitor = udev_monitor_new_from_netlink(udev, "udev");
+ if (udev_monitor == NULL) {
+ fprintf(stderr, "error: unable to create netlink socket\n");
+ rc = 1;
+ goto out;
+ }
+ udev_monitor_set_receive_buffer_size(udev_monitor, 128*1024*1024);
+ fd_udev = udev_monitor_get_fd(udev_monitor);
+
+ udev_list_entry_foreach(entry, udev_list_get_entry(&subsystem_match_list)) {
+ const char *subsys = udev_list_entry_get_name(entry);
+ const char *devtype = udev_list_entry_get_value(entry);
+
+ if (udev_monitor_filter_add_match_subsystem_devtype(udev_monitor, subsys, devtype) < 0)
+ fprintf(stderr, "error: unable to apply subsystem filter '%s'\n", subsys);
+ }
+
+ udev_list_entry_foreach(entry, udev_list_get_entry(&tag_match_list)) {
+ const char *tag = udev_list_entry_get_name(entry);
+
+ if (udev_monitor_filter_add_match_tag(udev_monitor, tag) < 0)
+ fprintf(stderr, "error: unable to apply tag filter '%s'\n", tag);
+ }
+
+ if (udev_monitor_enable_receiving(udev_monitor) < 0) {
+ fprintf(stderr, "error: unable to subscribe to udev events\n");
+ rc = 2;
+ goto out;
+ }
+
+ memset(&ep_udev, 0, sizeof(struct epoll_event));
+ ep_udev.events = EPOLLIN;
+ ep_udev.data.fd = fd_udev;
+ if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_udev, &ep_udev) < 0) {
+ log_error("fail to add fd to epoll: %m\n");
+ goto out;
+ }
+
+ printf("UDEV - the event which udev sends out after rule processing\n");
+ }
+
+ if (print_kernel) {
+ struct udev_list_entry *entry;
+
+ kernel_monitor = udev_monitor_new_from_netlink(udev, "kernel");
+ if (kernel_monitor == NULL) {
+ fprintf(stderr, "error: unable to create netlink socket\n");
+ rc = 3;
+ goto out;
+ }
+ udev_monitor_set_receive_buffer_size(kernel_monitor, 128*1024*1024);
+ fd_kernel = udev_monitor_get_fd(kernel_monitor);
+
+ udev_list_entry_foreach(entry, udev_list_get_entry(&subsystem_match_list)) {
+ const char *subsys = udev_list_entry_get_name(entry);
+
+ if (udev_monitor_filter_add_match_subsystem_devtype(kernel_monitor, subsys, NULL) < 0)
+ fprintf(stderr, "error: unable to apply subsystem filter '%s'\n", subsys);
+ }
+
+ if (udev_monitor_enable_receiving(kernel_monitor) < 0) {
+ fprintf(stderr, "error: unable to subscribe to kernel events\n");
+ rc = 4;
+ goto out;
+ }
+
+ memset(&ep_kernel, 0, sizeof(struct epoll_event));
+ ep_kernel.events = EPOLLIN;
+ ep_kernel.data.fd = fd_kernel;
+ if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_kernel, &ep_kernel) < 0) {
+ log_error("fail to add fd to epoll: %m\n");
+ goto out;
+ }
+
+ printf("KERNEL - the kernel uevent\n");
+ }
+ printf("\n");
+
+ while (!udev_exit) {
+ int fdcount;
+ struct epoll_event ev[4];
+ int i;
+
+ fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), -1);
+ if (fdcount < 0) {
+ if (errno != EINTR)
+ fprintf(stderr, "error receiving uevent message: %m\n");
+ continue;
+ }
+
+ for (i = 0; i < fdcount; i++) {
+ if (ev[i].data.fd == fd_kernel && ev[i].events & EPOLLIN) {
+ struct udev_device *device;
+
+ device = udev_monitor_receive_device(kernel_monitor);
+ if (device == NULL)
+ continue;
+ print_device(device, "KERNEL", prop);
+ udev_device_unref(device);
+ } else if (ev[i].data.fd == fd_udev && ev[i].events & EPOLLIN) {
+ struct udev_device *device;
+
+ device = udev_monitor_receive_device(udev_monitor);
+ if (device == NULL)
+ continue;
+ print_device(device, "UDEV", prop);
+ udev_device_unref(device);
+ }
+ }
+ }
+out:
+ if (fd_ep >= 0)
+ close(fd_ep);
+ udev_monitor_unref(udev_monitor);
+ udev_monitor_unref(kernel_monitor);
+ udev_list_cleanup(&subsystem_match_list);
+ udev_list_cleanup(&tag_match_list);
+ return rc;
+}
+
+const struct udevadm_cmd udevadm_monitor = {
+ .name = "monitor",
+ .cmd = adm_monitor,
+ .help = "listen to kernel and udev events",
+};
diff --git a/src/udev/udevadm-settle.c b/src/udev/udevadm-settle.c
new file mode 100644
index 0000000000..c4fc4ee4e5
--- /dev/null
+++ b/src/udev/udevadm-settle.c
@@ -0,0 +1,232 @@
+/*
+ * Copyright (C) 2006-2009 Kay Sievers <kay@vrfy.org>
+ * Copyright (C) 2009 Canonical Ltd.
+ * Copyright (C) 2009 Scott James Remnant <scott@netsplit.com>
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <stdlib.h>
+#include <stddef.h>
+#include <string.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <errno.h>
+#include <dirent.h>
+#include <fcntl.h>
+#include <syslog.h>
+#include <getopt.h>
+#include <signal.h>
+#include <time.h>
+#include <sys/inotify.h>
+#include <sys/poll.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+
+#include "udev.h"
+
+static int adm_settle(struct udev *udev, int argc, char *argv[])
+{
+ static const struct option options[] = {
+ { "seq-start", required_argument, NULL, 's' },
+ { "seq-end", required_argument, NULL, 'e' },
+ { "timeout", required_argument, NULL, 't' },
+ { "exit-if-exists", required_argument, NULL, 'E' },
+ { "quiet", no_argument, NULL, 'q' },
+ { "help", no_argument, NULL, 'h' },
+ {}
+ };
+ usec_t start_usec = now(CLOCK_MONOTONIC);
+ usec_t start = 0;
+ usec_t end = 0;
+ int quiet = 0;
+ const char *exists = NULL;
+ unsigned int timeout = 120;
+ struct pollfd pfd[1] = { {.fd = -1}, };
+ struct udev_queue *udev_queue = NULL;
+ int rc = EXIT_FAILURE;
+
+ for (;;) {
+ int option;
+ int seconds;
+
+ option = getopt_long(argc, argv, "s:e:t:E:qh", options, NULL);
+ if (option == -1)
+ break;
+
+ switch (option) {
+ case 's':
+ start = strtoull(optarg, NULL, 0);
+ break;
+ case 'e':
+ end = strtoull(optarg, NULL, 0);
+ break;
+ case 't':
+ seconds = atoi(optarg);
+ if (seconds >= 0)
+ timeout = seconds;
+ else
+ fprintf(stderr, "invalid timeout value\n");
+ break;
+ case 'q':
+ quiet = 1;
+ break;
+ case 'E':
+ exists = optarg;
+ break;
+ case 'h':
+ printf("Usage: udevadm settle OPTIONS\n"
+ " --timeout=<seconds> maximum time to wait for events\n"
+ " --seq-start=<seqnum> first seqnum to wait for\n"
+ " --seq-end=<seqnum> last seqnum to wait for\n"
+ " --exit-if-exists=<file> stop waiting if file exists\n"
+ " --quiet do not print list after timeout\n"
+ " --help\n\n");
+ exit(EXIT_SUCCESS);
+ default:
+ exit(EXIT_FAILURE);
+ }
+ }
+
+ udev_queue = udev_queue_new(udev);
+ if (udev_queue == NULL)
+ exit(2);
+
+ if (start > 0) {
+ unsigned long long kernel_seq;
+
+ kernel_seq = udev_queue_get_kernel_seqnum(udev_queue);
+
+ /* unless specified, the last event is the current kernel seqnum */
+ if (end == 0)
+ end = udev_queue_get_kernel_seqnum(udev_queue);
+
+ if (start > end) {
+ log_error("seq-start larger than seq-end, ignoring\n");
+ start = 0;
+ end = 0;
+ }
+
+ if (start > kernel_seq || end > kernel_seq) {
+ log_error("seq-start or seq-end larger than current kernel value, ignoring\n");
+ start = 0;
+ end = 0;
+ }
+ log_debug("start=%llu end=%llu current=%llu\n", (unsigned long long)start, (unsigned long long)end, kernel_seq);
+ } else {
+ if (end > 0) {
+ log_error("seq-end needs seq-start parameter, ignoring\n");
+ end = 0;
+ }
+ }
+
+ /* guarantee that the udev daemon isn't pre-processing */
+ if (getuid() == 0) {
+ struct udev_ctrl *uctrl;
+
+ uctrl = udev_ctrl_new(udev);
+ if (uctrl != NULL) {
+ if (udev_ctrl_send_ping(uctrl, timeout) < 0) {
+ log_debug("no connection to daemon\n");
+ udev_ctrl_unref(uctrl);
+ rc = EXIT_SUCCESS;
+ goto out;
+ }
+ udev_ctrl_unref(uctrl);
+ }
+ }
+
+ pfd[0].events = POLLIN;
+ pfd[0].fd = inotify_init1(IN_CLOEXEC);
+ if (pfd[0].fd < 0) {
+ log_error("inotify_init failed: %m\n");
+ } else {
+ if (inotify_add_watch(pfd[0].fd, "/run/udev" , IN_MOVED_TO) < 0) {
+ log_error("watching /run/udev failed\n");
+ close(pfd[0].fd);
+ pfd[0].fd = -1;
+ }
+ }
+
+ for (;;) {
+ struct stat statbuf;
+
+ if (exists != NULL && stat(exists, &statbuf) == 0) {
+ rc = EXIT_SUCCESS;
+ break;
+ }
+
+ if (start > 0) {
+ /* if asked for, wait for a specific sequence of events */
+ if (udev_queue_get_seqnum_sequence_is_finished(udev_queue, start, end) == 1) {
+ rc = EXIT_SUCCESS;
+ break;
+ }
+ } else {
+ /* exit if queue is empty */
+ if (udev_queue_get_queue_is_empty(udev_queue)) {
+ rc = EXIT_SUCCESS;
+ break;
+ }
+ }
+
+ if (pfd[0].fd >= 0) {
+ int delay;
+
+ if (exists != NULL || start > 0)
+ delay = 100;
+ else
+ delay = 1000;
+ /* wake up after delay, or immediately after the queue is rebuilt */
+ if (poll(pfd, 1, delay) > 0 && pfd[0].revents & POLLIN) {
+ char buf[sizeof(struct inotify_event) + PATH_MAX];
+
+ read(pfd[0].fd, buf, sizeof(buf));
+ }
+ } else {
+ sleep(1);
+ }
+
+ if (timeout > 0) {
+ usec_t age_usec;
+
+ age_usec = now(CLOCK_MONOTONIC) - start_usec;
+ if (age_usec / (1000 * 1000) >= timeout) {
+ struct udev_list_entry *list_entry;
+
+ if (!quiet && udev_queue_get_queued_list_entry(udev_queue) != NULL) {
+ log_debug("timeout waiting for udev queue\n");
+ printf("\nudevadm settle - timeout of %i seconds reached, the event queue contains:\n", timeout);
+ udev_list_entry_foreach(list_entry, udev_queue_get_queued_list_entry(udev_queue))
+ printf(" %s (%s)\n",
+ udev_list_entry_get_name(list_entry),
+ udev_list_entry_get_value(list_entry));
+ }
+
+ break;
+ }
+ }
+ }
+out:
+ if (pfd[0].fd >= 0)
+ close(pfd[0].fd);
+ udev_queue_unref(udev_queue);
+ return rc;
+}
+
+const struct udevadm_cmd udevadm_settle = {
+ .name = "settle",
+ .cmd = adm_settle,
+ .help = "wait for the event queue to finish",
+};
diff --git a/src/udev/udevadm-test-builtin.c b/src/udev/udevadm-test-builtin.c
new file mode 100644
index 0000000000..f4aa21ee72
--- /dev/null
+++ b/src/udev/udevadm-test-builtin.c
@@ -0,0 +1,127 @@
+/*
+ * Copyright (C) 2011 Kay Sievers <kay@vrfy.org>
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <stdlib.h>
+#include <stddef.h>
+#include <string.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <errno.h>
+#include <dirent.h>
+#include <fcntl.h>
+#include <syslog.h>
+#include <getopt.h>
+#include <signal.h>
+#include <time.h>
+#include <sys/inotify.h>
+#include <sys/poll.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+
+#include "udev.h"
+
+static void help(struct udev *udev)
+{
+ fprintf(stderr, "\n");
+ fprintf(stderr, "Usage: udevadm builtin [--help] <command> <syspath>\n");
+ udev_builtin_list(udev);
+ fprintf(stderr, "\n");
+}
+
+static int adm_builtin(struct udev *udev, int argc, char *argv[])
+{
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ {}
+ };
+ char *command = NULL;
+ char *syspath = NULL;
+ char filename[UTIL_PATH_SIZE];
+ struct udev_device *dev = NULL;
+ enum udev_builtin_cmd cmd;
+ int rc = EXIT_SUCCESS;
+
+ for (;;) {
+ int option;
+
+ option = getopt_long(argc, argv, "h", options, NULL);
+ if (option == -1)
+ break;
+
+ switch (option) {
+ case 'h':
+ help(udev);
+ goto out;
+ }
+ }
+
+ command = argv[optind++];
+ if (command == NULL) {
+ fprintf(stderr, "command missing\n");
+ help(udev);
+ rc = 2;
+ goto out;
+ }
+
+ syspath = argv[optind++];
+ if (syspath == NULL) {
+ fprintf(stderr, "syspath missing\n\n");
+ rc = 3;
+ goto out;
+ }
+
+ udev_builtin_init(udev);
+
+ cmd = udev_builtin_lookup(command);
+ if (cmd >= UDEV_BUILTIN_MAX) {
+ fprintf(stderr, "unknown command '%s'\n", command);
+ help(udev);
+ rc = 5;
+ goto out;
+ }
+
+ /* add /sys if needed */
+ if (!startswith(syspath, "/sys"))
+ strscpyl(filename, sizeof(filename), "/sys", syspath, NULL);
+ else
+ strscpy(filename, sizeof(filename), syspath);
+ util_remove_trailing_chars(filename, '/');
+
+ dev = udev_device_new_from_syspath(udev, filename);
+ if (dev == NULL) {
+ fprintf(stderr, "unable to open device '%s'\n\n", filename);
+ rc = 4;
+ goto out;
+ }
+
+ rc = udev_builtin_run(dev, cmd, command, true);
+ if (rc < 0) {
+ fprintf(stderr, "error executing '%s', exit code %i\n\n", command, rc);
+ rc = 6;
+ }
+out:
+ udev_device_unref(dev);
+ udev_builtin_exit(udev);
+ return rc;
+}
+
+const struct udevadm_cmd udevadm_test_builtin = {
+ .name = "test-builtin",
+ .cmd = adm_builtin,
+ .help = "test a built-in command",
+ .debug = true,
+};
diff --git a/src/udev/udevadm-test.c b/src/udev/udevadm-test.c
new file mode 100644
index 0000000000..df1409bff6
--- /dev/null
+++ b/src/udev/udevadm-test.c
@@ -0,0 +1,172 @@
+/*
+ * Copyright (C) 2003-2004 Greg Kroah-Hartman <greg@kroah.com>
+ * Copyright (C) 2004-2008 Kay Sievers <kay@vrfy.org>
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <stddef.h>
+#include <unistd.h>
+#include <errno.h>
+#include <ctype.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <syslog.h>
+#include <getopt.h>
+#include <sys/signalfd.h>
+
+#include "udev.h"
+
+static int adm_test(struct udev *udev, int argc, char *argv[])
+{
+ int resolve_names = 1;
+ char filename[UTIL_PATH_SIZE];
+ const char *action = "add";
+ const char *syspath = NULL;
+ struct udev_event *event = NULL;
+ struct udev_device *dev = NULL;
+ struct udev_rules *rules = NULL;
+ struct udev_list_entry *entry;
+ sigset_t mask, sigmask_orig;
+ int err;
+ int rc = 0;
+
+ static const struct option options[] = {
+ { "action", required_argument, NULL, 'a' },
+ { "resolve-names", required_argument, NULL, 'N' },
+ { "help", no_argument, NULL, 'h' },
+ {}
+ };
+
+ log_debug("version %s\n", VERSION);
+
+ for (;;) {
+ int option;
+
+ option = getopt_long(argc, argv, "a:s:N:fh", options, NULL);
+ if (option == -1)
+ break;
+
+ switch (option) {
+ case 'a':
+ action = optarg;
+ break;
+ case 'N':
+ if (streq (optarg, "early")) {
+ resolve_names = 1;
+ } else if (streq (optarg, "late")) {
+ resolve_names = 0;
+ } else if (streq (optarg, "never")) {
+ resolve_names = -1;
+ } else {
+ fprintf(stderr, "resolve-names must be early, late or never\n");
+ log_error("resolve-names must be early, late or never\n");
+ exit(EXIT_FAILURE);
+ }
+ break;
+ case 'h':
+ printf("Usage: udevadm test OPTIONS <syspath>\n"
+ " --action=<string> set action string\n"
+ " --help\n\n");
+ exit(EXIT_SUCCESS);
+ default:
+ exit(EXIT_FAILURE);
+ }
+ }
+ syspath = argv[optind];
+
+ if (syspath == NULL) {
+ fprintf(stderr, "syspath parameter missing\n");
+ rc = 2;
+ goto out;
+ }
+
+ printf("This program is for debugging only, it does not run any program\n"
+ "specified by a RUN key. It may show incorrect results, because\n"
+ "some values may be different, or not available at a simulation run.\n"
+ "\n");
+
+ sigprocmask(SIG_SETMASK, NULL, &sigmask_orig);
+
+ udev_builtin_init(udev);
+
+ rules = udev_rules_new(udev, resolve_names);
+ if (rules == NULL) {
+ fprintf(stderr, "error reading rules\n");
+ rc = 3;
+ goto out;
+ }
+
+ /* add /sys if needed */
+ if (!startswith(syspath, "/sys"))
+ strscpyl(filename, sizeof(filename), "/sys", syspath, NULL);
+ else
+ strscpy(filename, sizeof(filename), syspath);
+ util_remove_trailing_chars(filename, '/');
+
+ dev = udev_device_new_from_syspath(udev, filename);
+ if (dev == NULL) {
+ fprintf(stderr, "unable to open device '%s'\n", filename);
+ rc = 4;
+ goto out;
+ }
+
+ /* skip reading of db, but read kernel parameters */
+ udev_device_set_info_loaded(dev);
+ udev_device_read_uevent_file(dev);
+
+ udev_device_set_action(dev, action);
+ event = udev_event_new(dev);
+
+ sigfillset(&mask);
+ sigprocmask(SIG_SETMASK, &mask, &sigmask_orig);
+ event->fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
+ if (event->fd_signal < 0) {
+ fprintf(stderr, "error creating signalfd\n");
+ rc = 5;
+ goto out;
+ }
+
+ err = udev_event_execute_rules(event, rules, &sigmask_orig);
+
+ udev_list_entry_foreach(entry, udev_device_get_properties_list_entry(dev))
+ printf("%s=%s\n", udev_list_entry_get_name(entry), udev_list_entry_get_value(entry));
+
+ if (err == 0) {
+ udev_list_entry_foreach(entry, udev_list_get_entry(&event->run_list)) {
+ char program[UTIL_PATH_SIZE];
+
+ udev_event_apply_format(event, udev_list_entry_get_name(entry), program, sizeof(program));
+ printf("run: '%s'\n", program);
+ }
+ }
+out:
+ if (event != NULL && event->fd_signal >= 0)
+ close(event->fd_signal);
+ udev_event_unref(event);
+ udev_device_unref(dev);
+ udev_rules_unref(rules);
+ udev_builtin_exit(udev);
+ return rc;
+}
+
+const struct udevadm_cmd udevadm_test = {
+ .name = "test",
+ .cmd = adm_test,
+ .help = "test an event run",
+ .debug = true,
+};
diff --git a/src/udev/udevadm-trigger.c b/src/udev/udevadm-trigger.c
new file mode 100644
index 0000000000..f472996965
--- /dev/null
+++ b/src/udev/udevadm-trigger.c
@@ -0,0 +1,228 @@
+/*
+ * Copyright (C) 2008-2009 Kay Sievers <kay@vrfy.org>
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <stdlib.h>
+#include <stddef.h>
+#include <string.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <getopt.h>
+#include <errno.h>
+#include <dirent.h>
+#include <fcntl.h>
+#include <syslog.h>
+#include <fnmatch.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+
+#include "udev.h"
+
+static int verbose;
+static int dry_run;
+
+static void exec_list(struct udev_enumerate *udev_enumerate, const char *action)
+{
+ struct udev_list_entry *entry;
+
+ udev_list_entry_foreach(entry, udev_enumerate_get_list_entry(udev_enumerate)) {
+ char filename[UTIL_PATH_SIZE];
+ int fd;
+
+ if (verbose)
+ printf("%s\n", udev_list_entry_get_name(entry));
+ if (dry_run)
+ continue;
+ strscpyl(filename, sizeof(filename), udev_list_entry_get_name(entry), "/uevent", NULL);
+ fd = open(filename, O_WRONLY);
+ if (fd < 0)
+ continue;
+ if (write(fd, action, strlen(action)) < 0)
+ log_debug("error writing '%s' to '%s': %m\n", action, filename);
+ close(fd);
+ }
+}
+
+static const char *keyval(const char *str, const char **val, char *buf, size_t size)
+{
+ char *pos;
+
+ strscpy(buf, size,str);
+ pos = strchr(buf, '=');
+ if (pos != NULL) {
+ pos[0] = 0;
+ pos++;
+ }
+ *val = pos;
+ return buf;
+}
+
+static int adm_trigger(struct udev *udev, int argc, char *argv[])
+{
+ static const struct option options[] = {
+ { "verbose", no_argument, NULL, 'v' },
+ { "dry-run", no_argument, NULL, 'n' },
+ { "type", required_argument, NULL, 't' },
+ { "action", required_argument, NULL, 'c' },
+ { "subsystem-match", required_argument, NULL, 's' },
+ { "subsystem-nomatch", required_argument, NULL, 'S' },
+ { "attr-match", required_argument, NULL, 'a' },
+ { "attr-nomatch", required_argument, NULL, 'A' },
+ { "property-match", required_argument, NULL, 'p' },
+ { "tag-match", required_argument, NULL, 'g' },
+ { "sysname-match", required_argument, NULL, 'y' },
+ { "parent-match", required_argument, NULL, 'b' },
+ { "help", no_argument, NULL, 'h' },
+ {}
+ };
+ enum {
+ TYPE_DEVICES,
+ TYPE_SUBSYSTEMS,
+ } device_type = TYPE_DEVICES;
+ const char *action = "change";
+ struct udev_enumerate *udev_enumerate;
+ int rc = 0;
+
+ udev_enumerate = udev_enumerate_new(udev);
+ if (udev_enumerate == NULL) {
+ rc = 1;
+ goto exit;
+ }
+
+ for (;;) {
+ int option;
+ const char *key;
+ const char *val;
+ char buf[UTIL_PATH_SIZE];
+
+ option = getopt_long(argc, argv, "vng:o:t:hc:p:s:S:a:A:y:b:", options, NULL);
+ if (option == -1)
+ break;
+
+ switch (option) {
+ case 'v':
+ verbose = 1;
+ break;
+ case 'n':
+ dry_run = 1;
+ break;
+ case 't':
+ if (streq(optarg, "devices")) {
+ device_type = TYPE_DEVICES;
+ } else if (streq(optarg, "subsystems")) {
+ device_type = TYPE_SUBSYSTEMS;
+ } else {
+ log_error("unknown type --type=%s\n", optarg);
+ rc = 2;
+ goto exit;
+ }
+ break;
+ case 'c':
+ action = optarg;
+ break;
+ case 's':
+ udev_enumerate_add_match_subsystem(udev_enumerate, optarg);
+ break;
+ case 'S':
+ udev_enumerate_add_nomatch_subsystem(udev_enumerate, optarg);
+ break;
+ case 'a':
+ key = keyval(optarg, &val, buf, sizeof(buf));
+ udev_enumerate_add_match_sysattr(udev_enumerate, key, val);
+ break;
+ case 'A':
+ key = keyval(optarg, &val, buf, sizeof(buf));
+ udev_enumerate_add_nomatch_sysattr(udev_enumerate, key, val);
+ break;
+ case 'p':
+ key = keyval(optarg, &val, buf, sizeof(buf));
+ udev_enumerate_add_match_property(udev_enumerate, key, val);
+ break;
+ case 'g':
+ udev_enumerate_add_match_tag(udev_enumerate, optarg);
+ break;
+ case 'y':
+ udev_enumerate_add_match_sysname(udev_enumerate, optarg);
+ break;
+ case 'b': {
+ char path[UTIL_PATH_SIZE];
+ struct udev_device *dev;
+
+ /* add sys dir if needed */
+ if (!startswith(optarg, "/sys"))
+ strscpyl(path, sizeof(path), "/sys", optarg, NULL);
+ else
+ strscpy(path, sizeof(path), optarg);
+ util_remove_trailing_chars(path, '/');
+ dev = udev_device_new_from_syspath(udev, path);
+ if (dev == NULL) {
+ log_error("unable to open the device '%s'\n", optarg);
+ rc = 2;
+ goto exit;
+ }
+ udev_enumerate_add_match_parent(udev_enumerate, dev);
+ /* drop reference immediately, enumerate pins the device as long as needed */
+ udev_device_unref(dev);
+ break;
+ }
+ case 'h':
+ printf("Usage: udevadm trigger OPTIONS\n"
+ " --verbose print the list of devices while running\n"
+ " --dry-run do not actually trigger the events\n"
+ " --type= type of events to trigger\n"
+ " devices sys devices (default)\n"
+ " subsystems sys subsystems and drivers\n"
+ " --action=<action> event action value, default is \"change\"\n"
+ " --subsystem-match=<subsystem> trigger devices from a matching subsystem\n"
+ " --subsystem-nomatch=<subsystem> exclude devices from a matching subsystem\n"
+ " --attr-match=<file[=<value>]> trigger devices with a matching attribute\n"
+ " --attr-nomatch=<file[=<value>]> exclude devices with a matching attribute\n"
+ " --property-match=<key>=<value> trigger devices with a matching property\n"
+ " --tag-match=<key>=<value> trigger devices with a matching property\n"
+ " --sysname-match=<name> trigger devices with a matching name\n"
+ " --parent-match=<name> trigger devices with that parent device\n"
+ " --help\n\n");
+ goto exit;
+ default:
+ rc = 1;
+ goto exit;
+ }
+ }
+
+ switch (device_type) {
+ case TYPE_SUBSYSTEMS:
+ udev_enumerate_scan_subsystems(udev_enumerate);
+ exec_list(udev_enumerate, action);
+ goto exit;
+ case TYPE_DEVICES:
+ udev_enumerate_scan_devices(udev_enumerate);
+ exec_list(udev_enumerate, action);
+ goto exit;
+ default:
+ assert_not_reached("device_type");
+ }
+exit:
+ udev_enumerate_unref(udev_enumerate);
+ return rc;
+}
+
+const struct udevadm_cmd udevadm_trigger = {
+ .name = "trigger",
+ .cmd = adm_trigger,
+ .help = "request events from the kernel",
+};
diff --git a/src/udev/udevadm.c b/src/udev/udevadm.c
new file mode 100644
index 0000000000..e14b3ca27c
--- /dev/null
+++ b/src/udev/udevadm.c
@@ -0,0 +1,152 @@
+/*
+ * Copyright (C) 2007-2012 Kay Sievers <kay@vrfy.org>
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <unistd.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <string.h>
+#include <errno.h>
+#include <getopt.h>
+
+#include "udev.h"
+
+void udev_main_log(struct udev *udev, int priority,
+ const char *file, int line, const char *fn,
+ const char *format, va_list args)
+{
+ log_metav(priority, file, line, fn, format, args);
+}
+
+static int adm_version(struct udev *udev, int argc, char *argv[])
+{
+ printf("%s\n", VERSION);
+ return 0;
+}
+
+static const struct udevadm_cmd udevadm_version = {
+ .name = "version",
+ .cmd = adm_version,
+};
+
+static int adm_help(struct udev *udev, int argc, char *argv[]);
+
+static const struct udevadm_cmd udevadm_help = {
+ .name = "help",
+ .cmd = adm_help,
+};
+
+static const struct udevadm_cmd *udevadm_cmds[] = {
+ &udevadm_info,
+ &udevadm_trigger,
+ &udevadm_settle,
+ &udevadm_control,
+ &udevadm_monitor,
+ &udevadm_hwdb,
+ &udevadm_test,
+ &udevadm_test_builtin,
+ &udevadm_version,
+ &udevadm_help,
+};
+
+static int adm_help(struct udev *udev, int argc, char *argv[])
+{
+ unsigned int i;
+
+ fprintf(stderr, "Usage: udevadm [--help] [--version] [--debug] COMMAND [COMMAND OPTIONS]\n");
+ for (i = 0; i < ELEMENTSOF(udevadm_cmds); i++)
+ if (udevadm_cmds[i]->help != NULL)
+ printf(" %-12s %s\n", udevadm_cmds[i]->name, udevadm_cmds[i]->help);
+ fprintf(stderr, "\n");
+ return 0;
+}
+
+static int run_command(struct udev *udev, const struct udevadm_cmd *cmd, int argc, char *argv[])
+{
+ if (cmd->debug)
+ log_set_max_level(LOG_DEBUG);
+ log_debug("calling: %s\n", cmd->name);
+ return cmd->cmd(udev, argc, argv);
+}
+
+int main(int argc, char *argv[])
+{
+ struct udev *udev;
+ static const struct option options[] = {
+ { "debug", no_argument, NULL, 'd' },
+ { "help", no_argument, NULL, 'h' },
+ { "version", no_argument, NULL, 'V' },
+ {}
+ };
+ const char *command;
+ unsigned int i;
+ int rc = 1;
+
+ udev = udev_new();
+ if (udev == NULL)
+ goto out;
+
+ log_parse_environment();
+ log_open();
+ udev_set_log_fn(udev, udev_main_log);
+ label_init("/dev");
+
+ for (;;) {
+ int option;
+
+ option = getopt_long(argc, argv, "+dhV", options, NULL);
+ if (option == -1)
+ break;
+
+ switch (option) {
+ case 'd':
+ log_set_max_level(LOG_DEBUG);
+ udev_set_log_priority(udev, LOG_DEBUG);
+ break;
+ case 'h':
+ rc = adm_help(udev, argc, argv);
+ goto out;
+ case 'V':
+ rc = adm_version(udev, argc, argv);
+ goto out;
+ default:
+ goto out;
+ }
+ }
+ command = argv[optind];
+
+ if (command != NULL)
+ for (i = 0; i < ELEMENTSOF(udevadm_cmds); i++) {
+ if (streq(udevadm_cmds[i]->name, command)) {
+ argc -= optind;
+ argv += optind;
+ /* we need '0' here to reset the internal state */
+ optind = 0;
+ rc = run_command(udev, udevadm_cmds[i], argc, argv);
+ goto out;
+ }
+ }
+
+ fprintf(stderr, "missing or unknown command\n\n");
+ adm_help(udev, argc, argv);
+ rc = 2;
+out:
+ label_finish();
+ udev_unref(udev);
+ log_close();
+ return rc;
+}
diff --git a/src/udev/udevd.c b/src/udev/udevd.c
new file mode 100644
index 0000000000..7d13b4f532
--- /dev/null
+++ b/src/udev/udevd.c
@@ -0,0 +1,1479 @@
+/*
+ * Copyright (C) 2004-2012 Kay Sievers <kay@vrfy.org>
+ * Copyright (C) 2004 Chris Friesen <chris_friesen@sympatico.ca>
+ * Copyright (C) 2009 Canonical Ltd.
+ * Copyright (C) 2009 Scott James Remnant <scott@netsplit.com>
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <stddef.h>
+#include <signal.h>
+#include <unistd.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdbool.h>
+#include <string.h>
+#include <ctype.h>
+#include <fcntl.h>
+#include <time.h>
+#include <getopt.h>
+#include <dirent.h>
+#include <sys/time.h>
+#include <sys/prctl.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <sys/signalfd.h>
+#include <sys/epoll.h>
+#include <sys/poll.h>
+#include <sys/wait.h>
+#include <sys/stat.h>
+#include <sys/ioctl.h>
+#include <sys/inotify.h>
+#include <sys/utsname.h>
+
+#include "udev.h"
+#include "sd-daemon.h"
+#include "cgroup-util.h"
+#include "dev-setup.h"
+#include "fileio.h"
+
+static bool debug;
+
+void udev_main_log(struct udev *udev, int priority,
+ const char *file, int line, const char *fn,
+ const char *format, va_list args)
+{
+ log_metav(priority, file, line, fn, format, args);
+}
+
+static struct udev_rules *rules;
+static struct udev_queue_export *udev_queue_export;
+static struct udev_ctrl *udev_ctrl;
+static struct udev_monitor *monitor;
+static int worker_watch[2] = { -1, -1 };
+static int fd_signal = -1;
+static int fd_ep = -1;
+static int fd_inotify = -1;
+static bool stop_exec_queue;
+static bool reload;
+static int children;
+static int children_max;
+static int exec_delay;
+static sigset_t sigmask_orig;
+static UDEV_LIST(event_list);
+static UDEV_LIST(worker_list);
+char *udev_cgroup;
+static bool udev_exit;
+
+enum event_state {
+ EVENT_UNDEF,
+ EVENT_QUEUED,
+ EVENT_RUNNING,
+};
+
+struct event {
+ struct udev_list_node node;
+ struct udev *udev;
+ struct udev_device *dev;
+ enum event_state state;
+ int exitcode;
+ unsigned long long int delaying_seqnum;
+ unsigned long long int seqnum;
+ const char *devpath;
+ size_t devpath_len;
+ const char *devpath_old;
+ dev_t devnum;
+ int ifindex;
+ bool is_block;
+#ifdef HAVE_FIRMWARE
+ bool nodelay;
+#endif
+};
+
+static inline struct event *node_to_event(struct udev_list_node *node)
+{
+ return container_of(node, struct event, node);
+}
+
+static void event_queue_cleanup(struct udev *udev, enum event_state type);
+
+enum worker_state {
+ WORKER_UNDEF,
+ WORKER_RUNNING,
+ WORKER_IDLE,
+ WORKER_KILLED,
+};
+
+struct worker {
+ struct udev_list_node node;
+ struct udev *udev;
+ int refcount;
+ pid_t pid;
+ struct udev_monitor *monitor;
+ enum worker_state state;
+ struct event *event;
+ usec_t event_start_usec;
+};
+
+/* passed from worker to main process */
+struct worker_message {
+ pid_t pid;
+ int exitcode;
+};
+
+static inline struct worker *node_to_worker(struct udev_list_node *node)
+{
+ return container_of(node, struct worker, node);
+}
+
+static void event_queue_delete(struct event *event, bool export)
+{
+ udev_list_node_remove(&event->node);
+
+ if (export) {
+ udev_queue_export_device_finished(udev_queue_export, event->dev);
+ log_debug("seq %llu done with %i\n", udev_device_get_seqnum(event->dev), event->exitcode);
+ }
+ udev_device_unref(event->dev);
+ free(event);
+}
+
+static struct worker *worker_ref(struct worker *worker)
+{
+ worker->refcount++;
+ return worker;
+}
+
+static void worker_cleanup(struct worker *worker)
+{
+ udev_list_node_remove(&worker->node);
+ udev_monitor_unref(worker->monitor);
+ children--;
+ free(worker);
+}
+
+static void worker_unref(struct worker *worker)
+{
+ worker->refcount--;
+ if (worker->refcount > 0)
+ return;
+ log_debug("worker [%u] cleaned up\n", worker->pid);
+ worker_cleanup(worker);
+}
+
+static void worker_list_cleanup(struct udev *udev)
+{
+ struct udev_list_node *loop, *tmp;
+
+ udev_list_node_foreach_safe(loop, tmp, &worker_list) {
+ struct worker *worker = node_to_worker(loop);
+
+ worker_cleanup(worker);
+ }
+}
+
+static void worker_new(struct event *event)
+{
+ struct udev *udev = event->udev;
+ struct worker *worker;
+ struct udev_monitor *worker_monitor;
+ pid_t pid;
+
+ /* listen for new events */
+ worker_monitor = udev_monitor_new_from_netlink(udev, NULL);
+ if (worker_monitor == NULL)
+ return;
+ /* allow the main daemon netlink address to send devices to the worker */
+ udev_monitor_allow_unicast_sender(worker_monitor, monitor);
+ udev_monitor_enable_receiving(worker_monitor);
+
+ worker = calloc(1, sizeof(struct worker));
+ if (worker == NULL) {
+ udev_monitor_unref(worker_monitor);
+ return;
+ }
+ /* worker + event reference */
+ worker->refcount = 2;
+ worker->udev = udev;
+
+ pid = fork();
+ switch (pid) {
+ case 0: {
+ struct udev_device *dev = NULL;
+ int fd_monitor;
+ struct epoll_event ep_signal, ep_monitor;
+ sigset_t mask;
+ int rc = EXIT_SUCCESS;
+
+ /* take initial device from queue */
+ dev = event->dev;
+ event->dev = NULL;
+
+ free(worker);
+ worker_list_cleanup(udev);
+ event_queue_cleanup(udev, EVENT_UNDEF);
+ udev_queue_export_unref(udev_queue_export);
+ udev_monitor_unref(monitor);
+ udev_ctrl_unref(udev_ctrl);
+ close(fd_signal);
+ close(fd_ep);
+ close(worker_watch[READ_END]);
+
+ sigfillset(&mask);
+ fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
+ if (fd_signal < 0) {
+ log_error("error creating signalfd %m\n");
+ rc = 2;
+ goto out;
+ }
+
+ fd_ep = epoll_create1(EPOLL_CLOEXEC);
+ if (fd_ep < 0) {
+ log_error("error creating epoll fd: %m\n");
+ rc = 3;
+ goto out;
+ }
+
+ memset(&ep_signal, 0, sizeof(struct epoll_event));
+ ep_signal.events = EPOLLIN;
+ ep_signal.data.fd = fd_signal;
+
+ fd_monitor = udev_monitor_get_fd(worker_monitor);
+ memset(&ep_monitor, 0, sizeof(struct epoll_event));
+ ep_monitor.events = EPOLLIN;
+ ep_monitor.data.fd = fd_monitor;
+
+ if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
+ epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_monitor, &ep_monitor) < 0) {
+ log_error("fail to add fds to epoll: %m\n");
+ rc = 4;
+ goto out;
+ }
+
+ /* request TERM signal if parent exits */
+ prctl(PR_SET_PDEATHSIG, SIGTERM);
+
+ /* reset OOM score, we only protect the main daemon */
+ write_string_file("/proc/self/oom_score_adj", "0");
+
+ for (;;) {
+ struct udev_event *udev_event;
+ struct worker_message msg;
+ int err;
+
+ log_debug("seq %llu running\n", udev_device_get_seqnum(dev));
+ udev_event = udev_event_new(dev);
+ if (udev_event == NULL) {
+ rc = 5;
+ goto out;
+ }
+
+ /* needed for SIGCHLD/SIGTERM in spawn() */
+ udev_event->fd_signal = fd_signal;
+
+ if (exec_delay > 0)
+ udev_event->exec_delay = exec_delay;
+
+ /* apply rules, create node, symlinks */
+ err = udev_event_execute_rules(udev_event, rules, &sigmask_orig);
+
+ if (err == 0)
+ udev_event_execute_run(udev_event, &sigmask_orig);
+
+ /* apply/restore inotify watch */
+ if (err == 0 && udev_event->inotify_watch) {
+ udev_watch_begin(udev, dev);
+ udev_device_update_db(dev);
+ }
+
+ /* send processed event back to libudev listeners */
+ udev_monitor_send_device(worker_monitor, NULL, dev);
+
+ /* send udevd the result of the event execution */
+ memset(&msg, 0, sizeof(struct worker_message));
+ if (err != 0)
+ msg.exitcode = err;
+ msg.pid = getpid();
+ send(worker_watch[WRITE_END], &msg, sizeof(struct worker_message), 0);
+
+ log_debug("seq %llu processed with %i\n", udev_device_get_seqnum(dev), err);
+
+ udev_device_unref(dev);
+ dev = NULL;
+
+ if (udev_event->sigterm) {
+ udev_event_unref(udev_event);
+ goto out;
+ }
+
+ udev_event_unref(udev_event);
+
+ /* wait for more device messages from main udevd, or term signal */
+ while (dev == NULL) {
+ struct epoll_event ev[4];
+ int fdcount;
+ int i;
+
+ fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), -1);
+ if (fdcount < 0) {
+ if (errno == EINTR)
+ continue;
+ log_error("failed to poll: %m\n");
+ goto out;
+ }
+
+ for (i = 0; i < fdcount; i++) {
+ if (ev[i].data.fd == fd_monitor && ev[i].events & EPOLLIN) {
+ dev = udev_monitor_receive_device(worker_monitor);
+ break;
+ } else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN) {
+ struct signalfd_siginfo fdsi;
+ ssize_t size;
+
+ size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
+ if (size != sizeof(struct signalfd_siginfo))
+ continue;
+ switch (fdsi.ssi_signo) {
+ case SIGTERM:
+ goto out;
+ }
+ }
+ }
+ }
+ }
+out:
+ udev_device_unref(dev);
+ if (fd_signal >= 0)
+ close(fd_signal);
+ if (fd_ep >= 0)
+ close(fd_ep);
+ close(fd_inotify);
+ close(worker_watch[WRITE_END]);
+ udev_rules_unref(rules);
+ udev_builtin_exit(udev);
+ udev_monitor_unref(worker_monitor);
+ udev_unref(udev);
+ log_close();
+ exit(rc);
+ }
+ case -1:
+ udev_monitor_unref(worker_monitor);
+ event->state = EVENT_QUEUED;
+ free(worker);
+ log_error("fork of child failed: %m\n");
+ break;
+ default:
+ /* close monitor, but keep address around */
+ udev_monitor_disconnect(worker_monitor);
+ worker->monitor = worker_monitor;
+ worker->pid = pid;
+ worker->state = WORKER_RUNNING;
+ worker->event_start_usec = now(CLOCK_MONOTONIC);
+ worker->event = event;
+ event->state = EVENT_RUNNING;
+ udev_list_node_append(&worker->node, &worker_list);
+ children++;
+ log_debug("seq %llu forked new worker [%u]\n", udev_device_get_seqnum(event->dev), pid);
+ break;
+ }
+}
+
+static void event_run(struct event *event)
+{
+ struct udev_list_node *loop;
+
+ udev_list_node_foreach(loop, &worker_list) {
+ struct worker *worker = node_to_worker(loop);
+ ssize_t count;
+
+ if (worker->state != WORKER_IDLE)
+ continue;
+
+ count = udev_monitor_send_device(monitor, worker->monitor, event->dev);
+ if (count < 0) {
+ log_error("worker [%u] did not accept message %zi (%m), kill it\n", worker->pid, count);
+ kill(worker->pid, SIGKILL);
+ worker->state = WORKER_KILLED;
+ continue;
+ }
+ worker_ref(worker);
+ worker->event = event;
+ worker->state = WORKER_RUNNING;
+ worker->event_start_usec = now(CLOCK_MONOTONIC);
+ event->state = EVENT_RUNNING;
+ return;
+ }
+
+ if (children >= children_max) {
+ if (children_max > 1)
+ log_debug("maximum number (%i) of children reached\n", children);
+ return;
+ }
+
+ /* start new worker and pass initial device */
+ worker_new(event);
+}
+
+static int event_queue_insert(struct udev_device *dev)
+{
+ struct event *event;
+
+ event = calloc(1, sizeof(struct event));
+ if (event == NULL)
+ return -1;
+
+ event->udev = udev_device_get_udev(dev);
+ event->dev = dev;
+ event->seqnum = udev_device_get_seqnum(dev);
+ event->devpath = udev_device_get_devpath(dev);
+ event->devpath_len = strlen(event->devpath);
+ event->devpath_old = udev_device_get_devpath_old(dev);
+ event->devnum = udev_device_get_devnum(dev);
+ event->is_block = streq("block", udev_device_get_subsystem(dev));
+ event->ifindex = udev_device_get_ifindex(dev);
+#ifdef HAVE_FIRMWARE
+ if (streq(udev_device_get_subsystem(dev), "firmware"))
+ event->nodelay = true;
+#endif
+
+ udev_queue_export_device_queued(udev_queue_export, dev);
+ log_debug("seq %llu queued, '%s' '%s'\n", udev_device_get_seqnum(dev),
+ udev_device_get_action(dev), udev_device_get_subsystem(dev));
+
+ event->state = EVENT_QUEUED;
+ udev_list_node_append(&event->node, &event_list);
+ return 0;
+}
+
+static void worker_kill(struct udev *udev)
+{
+ struct udev_list_node *loop;
+
+ udev_list_node_foreach(loop, &worker_list) {
+ struct worker *worker = node_to_worker(loop);
+
+ if (worker->state == WORKER_KILLED)
+ continue;
+
+ worker->state = WORKER_KILLED;
+ kill(worker->pid, SIGTERM);
+ }
+}
+
+/* lookup event for identical, parent, child device */
+static bool is_devpath_busy(struct event *event)
+{
+ struct udev_list_node *loop;
+ size_t common;
+
+ /* check if queue contains events we depend on */
+ udev_list_node_foreach(loop, &event_list) {
+ struct event *loop_event = node_to_event(loop);
+
+ /* we already found a later event, earlier can not block us, no need to check again */
+ if (loop_event->seqnum < event->delaying_seqnum)
+ continue;
+
+ /* event we checked earlier still exists, no need to check again */
+ if (loop_event->seqnum == event->delaying_seqnum)
+ return true;
+
+ /* found ourself, no later event can block us */
+ if (loop_event->seqnum >= event->seqnum)
+ break;
+
+ /* check major/minor */
+ if (major(event->devnum) != 0 && event->devnum == loop_event->devnum && event->is_block == loop_event->is_block)
+ return true;
+
+ /* check network device ifindex */
+ if (event->ifindex != 0 && event->ifindex == loop_event->ifindex)
+ return true;
+
+ /* check our old name */
+ if (event->devpath_old != NULL && streq(loop_event->devpath, event->devpath_old)) {
+ event->delaying_seqnum = loop_event->seqnum;
+ return true;
+ }
+
+ /* compare devpath */
+ common = MIN(loop_event->devpath_len, event->devpath_len);
+
+ /* one devpath is contained in the other? */
+ if (memcmp(loop_event->devpath, event->devpath, common) != 0)
+ continue;
+
+ /* identical device event found */
+ if (loop_event->devpath_len == event->devpath_len) {
+ /* devices names might have changed/swapped in the meantime */
+ if (major(event->devnum) != 0 && (event->devnum != loop_event->devnum || event->is_block != loop_event->is_block))
+ continue;
+ if (event->ifindex != 0 && event->ifindex != loop_event->ifindex)
+ continue;
+ event->delaying_seqnum = loop_event->seqnum;
+ return true;
+ }
+
+#ifdef HAVE_FIRMWARE
+ /* allow to bypass the dependency tracking */
+ if (event->nodelay)
+ continue;
+#endif
+
+ /* parent device event found */
+ if (event->devpath[common] == '/') {
+ event->delaying_seqnum = loop_event->seqnum;
+ return true;
+ }
+
+ /* child device event found */
+ if (loop_event->devpath[common] == '/') {
+ event->delaying_seqnum = loop_event->seqnum;
+ return true;
+ }
+
+ /* no matching device */
+ continue;
+ }
+
+ return false;
+}
+
+static void event_queue_start(struct udev *udev)
+{
+ struct udev_list_node *loop;
+
+ udev_list_node_foreach(loop, &event_list) {
+ struct event *event = node_to_event(loop);
+
+ if (event->state != EVENT_QUEUED)
+ continue;
+
+ /* do not start event if parent or child event is still running */
+ if (is_devpath_busy(event))
+ continue;
+
+ event_run(event);
+ }
+}
+
+static void event_queue_cleanup(struct udev *udev, enum event_state match_type)
+{
+ struct udev_list_node *loop, *tmp;
+
+ udev_list_node_foreach_safe(loop, tmp, &event_list) {
+ struct event *event = node_to_event(loop);
+
+ if (match_type != EVENT_UNDEF && match_type != event->state)
+ continue;
+
+ event_queue_delete(event, false);
+ }
+}
+
+static void worker_returned(int fd_worker)
+{
+ for (;;) {
+ struct worker_message msg;
+ ssize_t size;
+ struct udev_list_node *loop;
+
+ size = recv(fd_worker, &msg, sizeof(struct worker_message), MSG_DONTWAIT);
+ if (size != sizeof(struct worker_message))
+ break;
+
+ /* lookup worker who sent the signal */
+ udev_list_node_foreach(loop, &worker_list) {
+ struct worker *worker = node_to_worker(loop);
+
+ if (worker->pid != msg.pid)
+ continue;
+
+ /* worker returned */
+ if (worker->event) {
+ worker->event->exitcode = msg.exitcode;
+ event_queue_delete(worker->event, true);
+ worker->event = NULL;
+ }
+ if (worker->state != WORKER_KILLED)
+ worker->state = WORKER_IDLE;
+ worker_unref(worker);
+ break;
+ }
+ }
+}
+
+/* receive the udevd message from userspace */
+static struct udev_ctrl_connection *handle_ctrl_msg(struct udev_ctrl *uctrl)
+{
+ struct udev *udev = udev_ctrl_get_udev(uctrl);
+ struct udev_ctrl_connection *ctrl_conn;
+ struct udev_ctrl_msg *ctrl_msg = NULL;
+ const char *str;
+ int i;
+
+ ctrl_conn = udev_ctrl_get_connection(uctrl);
+ if (ctrl_conn == NULL)
+ goto out;
+
+ ctrl_msg = udev_ctrl_receive_msg(ctrl_conn);
+ if (ctrl_msg == NULL)
+ goto out;
+
+ i = udev_ctrl_get_set_log_level(ctrl_msg);
+ if (i >= 0) {
+ log_debug("udevd message (SET_LOG_PRIORITY) received, log_priority=%i\n", i);
+ log_set_max_level(i);
+ udev_set_log_priority(udev, i);
+ worker_kill(udev);
+ }
+
+ if (udev_ctrl_get_stop_exec_queue(ctrl_msg) > 0) {
+ log_debug("udevd message (STOP_EXEC_QUEUE) received\n");
+ stop_exec_queue = true;
+ }
+
+ if (udev_ctrl_get_start_exec_queue(ctrl_msg) > 0) {
+ log_debug("udevd message (START_EXEC_QUEUE) received\n");
+ stop_exec_queue = false;
+ }
+
+ if (udev_ctrl_get_reload(ctrl_msg) > 0) {
+ log_debug("udevd message (RELOAD) received\n");
+ reload = true;
+ }
+
+ str = udev_ctrl_get_set_env(ctrl_msg);
+ if (str != NULL) {
+ char *key;
+
+ key = strdup(str);
+ if (key != NULL) {
+ char *val;
+
+ val = strchr(key, '=');
+ if (val != NULL) {
+ val[0] = '\0';
+ val = &val[1];
+ if (val[0] == '\0') {
+ log_debug("udevd message (ENV) received, unset '%s'\n", key);
+ udev_add_property(udev, key, NULL);
+ } else {
+ log_debug("udevd message (ENV) received, set '%s=%s'\n", key, val);
+ udev_add_property(udev, key, val);
+ }
+ } else {
+ log_error("wrong key format '%s'\n", key);
+ }
+ free(key);
+ }
+ worker_kill(udev);
+ }
+
+ i = udev_ctrl_get_set_children_max(ctrl_msg);
+ if (i >= 0) {
+ log_debug("udevd message (SET_MAX_CHILDREN) received, children_max=%i\n", i);
+ children_max = i;
+ }
+
+ if (udev_ctrl_get_ping(ctrl_msg) > 0)
+ log_debug("udevd message (SYNC) received\n");
+
+ if (udev_ctrl_get_exit(ctrl_msg) > 0) {
+ log_debug("udevd message (EXIT) received\n");
+ udev_exit = true;
+ /* keep reference to block the client until we exit */
+ udev_ctrl_connection_ref(ctrl_conn);
+ }
+out:
+ udev_ctrl_msg_unref(ctrl_msg);
+ return udev_ctrl_connection_unref(ctrl_conn);
+}
+
+/* read inotify messages */
+static int handle_inotify(struct udev *udev)
+{
+ int nbytes, pos;
+ char *buf;
+ struct inotify_event *ev;
+
+ if ((ioctl(fd_inotify, FIONREAD, &nbytes) < 0) || (nbytes <= 0))
+ return 0;
+
+ buf = malloc(nbytes);
+ if (buf == NULL) {
+ log_error("error getting buffer for inotify\n");
+ return -1;
+ }
+
+ nbytes = read(fd_inotify, buf, nbytes);
+
+ for (pos = 0; pos < nbytes; pos += sizeof(struct inotify_event) + ev->len) {
+ struct udev_device *dev;
+
+ ev = (struct inotify_event *)(buf + pos);
+ dev = udev_watch_lookup(udev, ev->wd);
+ if (dev != NULL) {
+ log_debug("inotify event: %x for %s\n", ev->mask, udev_device_get_devnode(dev));
+ if (ev->mask & IN_CLOSE_WRITE) {
+ char filename[UTIL_PATH_SIZE];
+ int fd;
+
+ log_debug("device %s closed, synthesising 'change'\n", udev_device_get_devnode(dev));
+ strscpyl(filename, sizeof(filename), udev_device_get_syspath(dev), "/uevent", NULL);
+ fd = open(filename, O_WRONLY);
+ if (fd >= 0) {
+ if (write(fd, "change", 6) < 0)
+ log_debug("error writing uevent: %m\n");
+ close(fd);
+ }
+ }
+ if (ev->mask & IN_IGNORED)
+ udev_watch_end(udev, dev);
+
+ udev_device_unref(dev);
+ }
+
+ }
+
+ free(buf);
+ return 0;
+}
+
+static void handle_signal(struct udev *udev, int signo)
+{
+ switch (signo) {
+ case SIGINT:
+ case SIGTERM:
+ udev_exit = true;
+ break;
+ case SIGCHLD:
+ for (;;) {
+ pid_t pid;
+ int status;
+ struct udev_list_node *loop, *tmp;
+
+ pid = waitpid(-1, &status, WNOHANG);
+ if (pid <= 0)
+ break;
+
+ udev_list_node_foreach_safe(loop, tmp, &worker_list) {
+ struct worker *worker = node_to_worker(loop);
+
+ if (worker->pid != pid)
+ continue;
+ log_debug("worker [%u] exit\n", pid);
+
+ if (WIFEXITED(status)) {
+ if (WEXITSTATUS(status) != 0)
+ log_error("worker [%u] exit with return code %i\n", pid, WEXITSTATUS(status));
+ } else if (WIFSIGNALED(status)) {
+ log_error("worker [%u] terminated by signal %i (%s)\n",
+ pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
+ } else if (WIFSTOPPED(status)) {
+ log_error("worker [%u] stopped\n", pid);
+ } else if (WIFCONTINUED(status)) {
+ log_error("worker [%u] continued\n", pid);
+ } else {
+ log_error("worker [%u] exit with status 0x%04x\n", pid, status);
+ }
+
+ if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
+ if (worker->event) {
+ log_error("worker [%u] failed while handling '%s'\n",
+ pid, worker->event->devpath);
+ worker->event->exitcode = -32;
+ event_queue_delete(worker->event, true);
+ /* drop reference taken for state 'running' */
+ worker_unref(worker);
+ }
+ }
+ worker_unref(worker);
+ break;
+ }
+ }
+ break;
+ case SIGHUP:
+ reload = true;
+ break;
+ }
+}
+
+static void static_dev_create_from_modules(struct udev *udev)
+{
+ struct utsname kernel;
+ char modules[UTIL_PATH_SIZE];
+ char buf[4096];
+ FILE *f;
+
+ if (uname(&kernel) < 0) {
+ log_error("uname failed: %m");
+ return;
+ }
+
+ strscpyl(modules, sizeof(modules), ROOTPREFIX "/lib/modules/", kernel.release, "/modules.devname", NULL);
+ f = fopen(modules, "re");
+ if (f == NULL)
+ return;
+
+ while (fgets(buf, sizeof(buf), f) != NULL) {
+ char *s;
+ const char *modname;
+ const char *devname;
+ const char *devno;
+ int maj, min;
+ char type;
+ mode_t mode;
+ char filename[UTIL_PATH_SIZE];
+
+ if (buf[0] == '#')
+ continue;
+
+ modname = buf;
+ s = strchr(modname, ' ');
+ if (s == NULL)
+ continue;
+ s[0] = '\0';
+
+ devname = &s[1];
+ s = strchr(devname, ' ');
+ if (s == NULL)
+ continue;
+ s[0] = '\0';
+
+ devno = &s[1];
+ s = strchr(devno, ' ');
+ if (s == NULL)
+ s = strchr(devno, '\n');
+ if (s != NULL)
+ s[0] = '\0';
+ if (sscanf(devno, "%c%u:%u", &type, &maj, &min) != 3)
+ continue;
+
+ mode = 0600;
+ if (type == 'c')
+ mode |= S_IFCHR;
+ else if (type == 'b')
+ mode |= S_IFBLK;
+ else
+ continue;
+
+ strscpyl(filename, sizeof(filename), "/dev/", devname, NULL);
+ mkdir_parents_label(filename, 0755);
+ label_context_set(filename, mode);
+ log_debug("mknod '%s' %c%u:%u\n", filename, type, maj, min);
+ if (mknod(filename, mode, makedev(maj, min)) < 0 && errno == EEXIST)
+ utimensat(AT_FDCWD, filename, NULL, 0);
+ label_context_clear();
+ }
+
+ fclose(f);
+}
+
+static int systemd_fds(struct udev *udev, int *rctrl, int *rnetlink)
+{
+ int ctrl = -1, netlink = -1;
+ int fd, n;
+
+ n = sd_listen_fds(true);
+ if (n <= 0)
+ return -1;
+
+ for (fd = SD_LISTEN_FDS_START; fd < n + SD_LISTEN_FDS_START; fd++) {
+ if (sd_is_socket(fd, AF_LOCAL, SOCK_SEQPACKET, -1)) {
+ if (ctrl >= 0)
+ return -1;
+ ctrl = fd;
+ continue;
+ }
+
+ if (sd_is_socket(fd, AF_NETLINK, SOCK_RAW, -1)) {
+ if (netlink >= 0)
+ return -1;
+ netlink = fd;
+ continue;
+ }
+
+ return -1;
+ }
+
+ if (ctrl < 0 || netlink < 0)
+ return -1;
+
+ log_debug("ctrl=%i netlink=%i\n", ctrl, netlink);
+ *rctrl = ctrl;
+ *rnetlink = netlink;
+ return 0;
+}
+
+/*
+ * read the kernel commandline, in case we need to get into debug mode
+ * udev.log-priority=<level> syslog priority
+ * udev.children-max=<number of workers> events are fully serialized if set to 1
+ * udev.exec-delay=<number of seconds> delay execution of every executed program
+ */
+static void kernel_cmdline_options(struct udev *udev)
+{
+ char *line, *w, *state;
+ size_t l;
+
+ if (read_one_line_file("/proc/cmdline", &line) < 0)
+ return;
+
+ FOREACH_WORD_QUOTED(w, l, line, state) {
+ char *s, *opt;
+
+ s = strndup(w, l);
+ if (!s)
+ break;
+
+ /* accept the same options for the initrd, prefixed with "rd." */
+ if (in_initrd() && startswith(s, "rd."))
+ opt = s + 3;
+ else
+ opt = s;
+
+ if (startswith(opt, "udev.log-priority=")) {
+ int prio;
+
+ prio = util_log_priority(opt + 18);
+ log_set_max_level(prio);
+ udev_set_log_priority(udev, prio);
+ } else if (startswith(opt, "udev.children-max=")) {
+ children_max = strtoul(opt + 18, NULL, 0);
+ } else if (startswith(opt, "udev.exec-delay=")) {
+ exec_delay = strtoul(opt + 16, NULL, 0);
+ }
+
+ free(s);
+ }
+
+ free(line);
+}
+
+int main(int argc, char *argv[])
+{
+ struct udev *udev;
+ sigset_t mask;
+ int daemonize = false;
+ int resolve_names = 1;
+ static const struct option options[] = {
+ { "daemon", no_argument, NULL, 'd' },
+ { "debug", no_argument, NULL, 'D' },
+ { "children-max", required_argument, NULL, 'c' },
+ { "exec-delay", required_argument, NULL, 'e' },
+ { "resolve-names", required_argument, NULL, 'N' },
+ { "help", no_argument, NULL, 'h' },
+ { "version", no_argument, NULL, 'V' },
+ {}
+ };
+ int fd_ctrl = -1;
+ int fd_netlink = -1;
+ int fd_worker = -1;
+ struct epoll_event ep_ctrl, ep_inotify, ep_signal, ep_netlink, ep_worker;
+ struct udev_ctrl_connection *ctrl_conn = NULL;
+ int rc = 1;
+
+ udev = udev_new();
+ if (udev == NULL)
+ goto exit;
+
+ log_set_target(LOG_TARGET_AUTO);
+ log_parse_environment();
+ log_open();
+ udev_set_log_fn(udev, udev_main_log);
+ log_debug("version %s\n", VERSION);
+ label_init("/dev");
+
+ for (;;) {
+ int option;
+
+ option = getopt_long(argc, argv, "c:de:DtN:hV", options, NULL);
+ if (option == -1)
+ break;
+
+ switch (option) {
+ case 'd':
+ daemonize = true;
+ break;
+ case 'c':
+ children_max = strtoul(optarg, NULL, 0);
+ break;
+ case 'e':
+ exec_delay = strtoul(optarg, NULL, 0);
+ break;
+ case 'D':
+ debug = true;
+ log_set_max_level(LOG_DEBUG);
+ udev_set_log_priority(udev, LOG_DEBUG);
+ break;
+ case 'N':
+ if (streq(optarg, "early")) {
+ resolve_names = 1;
+ } else if (streq(optarg, "late")) {
+ resolve_names = 0;
+ } else if (streq(optarg, "never")) {
+ resolve_names = -1;
+ } else {
+ fprintf(stderr, "resolve-names must be early, late or never\n");
+ log_error("resolve-names must be early, late or never\n");
+ goto exit;
+ }
+ break;
+ case 'h':
+ printf("Usage: udevd OPTIONS\n"
+ " --daemon\n"
+ " --debug\n"
+ " --children-max=<maximum number of workers>\n"
+ " --exec-delay=<seconds to wait before executing RUN=>\n"
+ " --resolve-names=early|late|never\n"
+ " --version\n"
+ " --help\n"
+ "\n");
+ goto exit;
+ case 'V':
+ printf("%s\n", VERSION);
+ goto exit;
+ default:
+ goto exit;
+ }
+ }
+
+ kernel_cmdline_options(udev);
+
+ if (getuid() != 0) {
+ fprintf(stderr, "root privileges required\n");
+ log_error("root privileges required\n");
+ goto exit;
+ }
+
+ /* set umask before creating any file/directory */
+ chdir("/");
+ umask(022);
+
+ mkdir("/run/udev", 0755);
+
+ dev_setup(NULL);
+ static_dev_create_from_modules(udev);
+
+ /* before opening new files, make sure std{in,out,err} fds are in a sane state */
+ if (daemonize) {
+ int fd;
+
+ fd = open("/dev/null", O_RDWR);
+ if (fd >= 0) {
+ if (write(STDOUT_FILENO, 0, 0) < 0)
+ dup2(fd, STDOUT_FILENO);
+ if (write(STDERR_FILENO, 0, 0) < 0)
+ dup2(fd, STDERR_FILENO);
+ if (fd > STDERR_FILENO)
+ close(fd);
+ } else {
+ fprintf(stderr, "cannot open /dev/null\n");
+ log_error("cannot open /dev/null\n");
+ }
+ }
+
+ if (systemd_fds(udev, &fd_ctrl, &fd_netlink) >= 0) {
+ /* get control and netlink socket from systemd */
+ udev_ctrl = udev_ctrl_new_from_fd(udev, fd_ctrl);
+ if (udev_ctrl == NULL) {
+ log_error("error taking over udev control socket");
+ rc = 1;
+ goto exit;
+ }
+
+ monitor = udev_monitor_new_from_netlink_fd(udev, "kernel", fd_netlink);
+ if (monitor == NULL) {
+ log_error("error taking over netlink socket\n");
+ rc = 3;
+ goto exit;
+ }
+
+ /* get our own cgroup, we regularly kill everything udev has left behind */
+ if (cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &udev_cgroup) < 0)
+ udev_cgroup = NULL;
+ } else {
+ /* open control and netlink socket */
+ udev_ctrl = udev_ctrl_new(udev);
+ if (udev_ctrl == NULL) {
+ fprintf(stderr, "error initializing udev control socket");
+ log_error("error initializing udev control socket");
+ rc = 1;
+ goto exit;
+ }
+ fd_ctrl = udev_ctrl_get_fd(udev_ctrl);
+
+ monitor = udev_monitor_new_from_netlink(udev, "kernel");
+ if (monitor == NULL) {
+ fprintf(stderr, "error initializing netlink socket\n");
+ log_error("error initializing netlink socket\n");
+ rc = 3;
+ goto exit;
+ }
+ fd_netlink = udev_monitor_get_fd(monitor);
+ }
+
+ if (udev_monitor_enable_receiving(monitor) < 0) {
+ fprintf(stderr, "error binding netlink socket\n");
+ log_error("error binding netlink socket\n");
+ rc = 3;
+ goto exit;
+ }
+
+ if (udev_ctrl_enable_receiving(udev_ctrl) < 0) {
+ fprintf(stderr, "error binding udev control socket\n");
+ log_error("error binding udev control socket\n");
+ rc = 1;
+ goto exit;
+ }
+
+ udev_monitor_set_receive_buffer_size(monitor, 128*1024*1024);
+
+ /* create queue file before signalling 'ready', to make sure we block 'settle' */
+ udev_queue_export = udev_queue_export_new(udev);
+ if (udev_queue_export == NULL) {
+ log_error("error creating queue file\n");
+ goto exit;
+ }
+
+ if (daemonize) {
+ pid_t pid;
+
+ pid = fork();
+ switch (pid) {
+ case 0:
+ break;
+ case -1:
+ log_error("fork of daemon failed: %m\n");
+ rc = 4;
+ goto exit;
+ default:
+ rc = EXIT_SUCCESS;
+ goto exit_daemonize;
+ }
+
+ setsid();
+
+ write_string_file("/proc/self/oom_score_adj", "-1000");
+ } else {
+ sd_notify(1, "READY=1");
+ }
+
+ print_kmsg("starting version " VERSION "\n");
+
+ if (!debug) {
+ int fd;
+
+ fd = open("/dev/null", O_RDWR);
+ if (fd >= 0) {
+ dup2(fd, STDIN_FILENO);
+ dup2(fd, STDOUT_FILENO);
+ dup2(fd, STDERR_FILENO);
+ close(fd);
+ }
+ }
+
+ fd_inotify = udev_watch_init(udev);
+ if (fd_inotify < 0) {
+ fprintf(stderr, "error initializing inotify\n");
+ log_error("error initializing inotify\n");
+ rc = 4;
+ goto exit;
+ }
+ udev_watch_restore(udev);
+
+ /* block and listen to all signals on signalfd */
+ sigfillset(&mask);
+ sigprocmask(SIG_SETMASK, &mask, &sigmask_orig);
+ fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
+ if (fd_signal < 0) {
+ fprintf(stderr, "error creating signalfd\n");
+ log_error("error creating signalfd\n");
+ rc = 5;
+ goto exit;
+ }
+
+ /* unnamed socket from workers to the main daemon */
+ if (socketpair(AF_LOCAL, SOCK_DGRAM|SOCK_CLOEXEC, 0, worker_watch) < 0) {
+ fprintf(stderr, "error creating socketpair\n");
+ log_error("error creating socketpair\n");
+ rc = 6;
+ goto exit;
+ }
+ fd_worker = worker_watch[READ_END];
+
+ udev_builtin_init(udev);
+
+ rules = udev_rules_new(udev, resolve_names);
+ if (rules == NULL) {
+ log_error("error reading rules\n");
+ goto exit;
+ }
+
+ memset(&ep_ctrl, 0, sizeof(struct epoll_event));
+ ep_ctrl.events = EPOLLIN;
+ ep_ctrl.data.fd = fd_ctrl;
+
+ memset(&ep_inotify, 0, sizeof(struct epoll_event));
+ ep_inotify.events = EPOLLIN;
+ ep_inotify.data.fd = fd_inotify;
+
+ memset(&ep_signal, 0, sizeof(struct epoll_event));
+ ep_signal.events = EPOLLIN;
+ ep_signal.data.fd = fd_signal;
+
+ memset(&ep_netlink, 0, sizeof(struct epoll_event));
+ ep_netlink.events = EPOLLIN;
+ ep_netlink.data.fd = fd_netlink;
+
+ memset(&ep_worker, 0, sizeof(struct epoll_event));
+ ep_worker.events = EPOLLIN;
+ ep_worker.data.fd = fd_worker;
+
+ fd_ep = epoll_create1(EPOLL_CLOEXEC);
+ if (fd_ep < 0) {
+ log_error("error creating epoll fd: %m\n");
+ goto exit;
+ }
+ if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_ctrl, &ep_ctrl) < 0 ||
+ epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_inotify, &ep_inotify) < 0 ||
+ epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
+ epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_netlink, &ep_netlink) < 0 ||
+ epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_worker, &ep_worker) < 0) {
+ log_error("fail to add fds to epoll: %m\n");
+ goto exit;
+ }
+
+ if (children_max <= 0) {
+ cpu_set_t cpu_set;
+
+ children_max = 8;
+
+ if (sched_getaffinity(0, sizeof (cpu_set), &cpu_set) == 0) {
+ children_max += CPU_COUNT(&cpu_set) * 2;
+ }
+ }
+ log_debug("set children_max to %u\n", children_max);
+
+ udev_rules_apply_static_dev_perms(rules);
+
+ udev_list_node_init(&event_list);
+ udev_list_node_init(&worker_list);
+
+ for (;;) {
+ static usec_t last_usec;
+ struct epoll_event ev[8];
+ int fdcount;
+ int timeout;
+ bool is_worker, is_signal, is_inotify, is_netlink, is_ctrl;
+ int i;
+
+ if (udev_exit) {
+ /* close sources of new events and discard buffered events */
+ if (fd_ctrl >= 0) {
+ epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_ctrl, NULL);
+ fd_ctrl = -1;
+ }
+ if (monitor != NULL) {
+ epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_netlink, NULL);
+ udev_monitor_unref(monitor);
+ monitor = NULL;
+ }
+ if (fd_inotify >= 0) {
+ epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_inotify, NULL);
+ close(fd_inotify);
+ fd_inotify = -1;
+ }
+
+ /* discard queued events and kill workers */
+ event_queue_cleanup(udev, EVENT_QUEUED);
+ worker_kill(udev);
+
+ /* exit after all has cleaned up */
+ if (udev_list_node_is_empty(&event_list) && udev_list_node_is_empty(&worker_list))
+ break;
+
+ /* timeout at exit for workers to finish */
+ timeout = 30 * 1000;
+ } else if (udev_list_node_is_empty(&event_list) && !children) {
+ /* we are idle */
+ timeout = -1;
+
+ /* cleanup possible left-over processes in our cgroup */
+ if (udev_cgroup)
+ cg_kill(SYSTEMD_CGROUP_CONTROLLER, udev_cgroup, SIGKILL, false, true, NULL);
+ } else {
+ /* kill idle or hanging workers */
+ timeout = 3 * 1000;
+ }
+ fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), timeout);
+ if (fdcount < 0)
+ continue;
+
+ if (fdcount == 0) {
+ struct udev_list_node *loop;
+
+ /* timeout */
+ if (udev_exit) {
+ log_error("timeout, giving up waiting for workers to finish\n");
+ break;
+ }
+
+ /* kill idle workers */
+ if (udev_list_node_is_empty(&event_list)) {
+ log_debug("cleanup idle workers\n");
+ worker_kill(udev);
+ }
+
+ /* check for hanging events */
+ udev_list_node_foreach(loop, &worker_list) {
+ struct worker *worker = node_to_worker(loop);
+
+ if (worker->state != WORKER_RUNNING)
+ continue;
+
+ if ((now(CLOCK_MONOTONIC) - worker->event_start_usec) > 30 * 1000 * 1000) {
+ log_error("worker [%u] %s timeout; kill it\n", worker->pid,
+ worker->event ? worker->event->devpath : "<idle>");
+ kill(worker->pid, SIGKILL);
+ worker->state = WORKER_KILLED;
+ /* drop reference taken for state 'running' */
+ worker_unref(worker);
+ if (worker->event) {
+ log_error("seq %llu '%s' killed\n",
+ udev_device_get_seqnum(worker->event->dev), worker->event->devpath);
+ worker->event->exitcode = -64;
+ event_queue_delete(worker->event, true);
+ worker->event = NULL;
+ }
+ }
+ }
+
+ }
+
+ is_worker = is_signal = is_inotify = is_netlink = is_ctrl = false;
+ for (i = 0; i < fdcount; i++) {
+ if (ev[i].data.fd == fd_worker && ev[i].events & EPOLLIN)
+ is_worker = true;
+ else if (ev[i].data.fd == fd_netlink && ev[i].events & EPOLLIN)
+ is_netlink = true;
+ else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN)
+ is_signal = true;
+ else if (ev[i].data.fd == fd_inotify && ev[i].events & EPOLLIN)
+ is_inotify = true;
+ else if (ev[i].data.fd == fd_ctrl && ev[i].events & EPOLLIN)
+ is_ctrl = true;
+ }
+
+ /* check for changed config, every 3 seconds at most */
+ if ((now(CLOCK_MONOTONIC) - last_usec) > 3 * 1000 * 1000) {
+ if (udev_rules_check_timestamp(rules))
+ reload = true;
+ if (udev_builtin_validate(udev))
+ reload = true;
+
+ last_usec = now(CLOCK_MONOTONIC);
+ }
+
+ /* reload requested, HUP signal received, rules changed, builtin changed */
+ if (reload) {
+ worker_kill(udev);
+ rules = udev_rules_unref(rules);
+ udev_builtin_exit(udev);
+ reload = false;
+ }
+
+ /* event has finished */
+ if (is_worker)
+ worker_returned(fd_worker);
+
+ if (is_netlink) {
+ struct udev_device *dev;
+
+ dev = udev_monitor_receive_device(monitor);
+ if (dev != NULL) {
+ udev_device_set_usec_initialized(dev, now(CLOCK_MONOTONIC));
+ if (event_queue_insert(dev) < 0)
+ udev_device_unref(dev);
+ }
+ }
+
+ /* start new events */
+ if (!udev_list_node_is_empty(&event_list) && !udev_exit && !stop_exec_queue) {
+ udev_builtin_init(udev);
+ if (rules == NULL)
+ rules = udev_rules_new(udev, resolve_names);
+ if (rules != NULL)
+ event_queue_start(udev);
+ }
+
+ if (is_signal) {
+ struct signalfd_siginfo fdsi;
+ ssize_t size;
+
+ size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
+ if (size == sizeof(struct signalfd_siginfo))
+ handle_signal(udev, fdsi.ssi_signo);
+ }
+
+ /* we are shutting down, the events below are not handled anymore */
+ if (udev_exit)
+ continue;
+
+ /* device node watch */
+ if (is_inotify)
+ handle_inotify(udev);
+
+ /*
+ * This needs to be after the inotify handling, to make sure,
+ * that the ping is send back after the possibly generated
+ * "change" events by the inotify device node watch.
+ *
+ * A single time we may receive a client connection which we need to
+ * keep open to block the client. It will be closed right before we
+ * exit.
+ */
+ if (is_ctrl)
+ ctrl_conn = handle_ctrl_msg(udev_ctrl);
+ }
+
+ rc = EXIT_SUCCESS;
+exit:
+ udev_queue_export_cleanup(udev_queue_export);
+ udev_ctrl_cleanup(udev_ctrl);
+exit_daemonize:
+ if (fd_ep >= 0)
+ close(fd_ep);
+ worker_list_cleanup(udev);
+ event_queue_cleanup(udev, EVENT_UNDEF);
+ udev_rules_unref(rules);
+ udev_builtin_exit(udev);
+ if (fd_signal >= 0)
+ close(fd_signal);
+ if (worker_watch[READ_END] >= 0)
+ close(worker_watch[READ_END]);
+ if (worker_watch[WRITE_END] >= 0)
+ close(worker_watch[WRITE_END]);
+ udev_monitor_unref(monitor);
+ udev_queue_export_unref(udev_queue_export);
+ udev_ctrl_connection_unref(ctrl_conn);
+ udev_ctrl_unref(udev_ctrl);
+ label_finish();
+ udev_unref(udev);
+ log_close();
+ return rc;
+}
diff --git a/src/udev/v4l_id/v4l_id.c b/src/udev/v4l_id/v4l_id.c
new file mode 100644
index 0000000000..8dcb645ed9
--- /dev/null
+++ b/src/udev/v4l_id/v4l_id.c
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2009 Kay Sievers <kay@vrfy.org>
+ * Copyright (c) 2009 Filippo Argiolas <filippo.argiolas@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; either version 2 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details:
+ */
+
+#include <stdio.h>
+#include <errno.h>
+#include <string.h>
+#include <ctype.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <getopt.h>
+#include <sys/types.h>
+#include <sys/time.h>
+#include <sys/ioctl.h>
+#include <linux/videodev2.h>
+
+int main (int argc, char *argv[])
+{
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ {}
+ };
+ int fd;
+ char *device;
+ struct v4l2_capability v2cap;
+
+ while (1) {
+ int option;
+
+ option = getopt_long(argc, argv, "h", options, NULL);
+ if (option == -1)
+ break;
+
+ switch (option) {
+ case 'h':
+ printf("Usage: v4l_id [--help] <device file>\n\n");
+ return 0;
+ default:
+ return 1;
+ }
+ }
+ device = argv[optind];
+
+ if (device == NULL)
+ return 2;
+ fd = open (device, O_RDONLY);
+ if (fd < 0)
+ return 3;
+
+ if (ioctl (fd, VIDIOC_QUERYCAP, &v2cap) == 0) {
+ printf("ID_V4L_VERSION=2\n");
+ printf("ID_V4L_PRODUCT=%s\n", v2cap.card);
+ printf("ID_V4L_CAPABILITIES=:");
+ if ((v2cap.capabilities & V4L2_CAP_VIDEO_CAPTURE) > 0)
+ printf("capture:");
+ if ((v2cap.capabilities & V4L2_CAP_VIDEO_OUTPUT) > 0)
+ printf("video_output:");
+ if ((v2cap.capabilities & V4L2_CAP_VIDEO_OVERLAY) > 0)
+ printf("video_overlay:");
+ if ((v2cap.capabilities & V4L2_CAP_AUDIO) > 0)
+ printf("audio:");
+ if ((v2cap.capabilities & V4L2_CAP_TUNER) > 0)
+ printf("tuner:");
+ if ((v2cap.capabilities & V4L2_CAP_RADIO) > 0)
+ printf("radio:");
+ printf("\n");
+ }
+
+ close (fd);
+ return 0;
+}
diff --git a/src/update-utmp/update-utmp.c b/src/update-utmp/update-utmp.c
new file mode 100644
index 0000000000..9184025554
--- /dev/null
+++ b/src/update-utmp/update-utmp.c
@@ -0,0 +1,385 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <assert.h>
+#include <errno.h>
+#include <string.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <dbus/dbus.h>
+
+#ifdef HAVE_AUDIT
+#include <libaudit.h>
+#endif
+
+#include "log.h"
+#include "macro.h"
+#include "util.h"
+#include "special.h"
+#include "utmp-wtmp.h"
+#include "dbus-common.h"
+
+typedef struct Context {
+ DBusConnection *bus;
+#ifdef HAVE_AUDIT
+ int audit_fd;
+#endif
+} Context;
+
+static usec_t get_startup_time(Context *c) {
+ const char
+ *interface = "org.freedesktop.systemd1.Manager",
+ *property = "UserspaceTimestamp";
+
+ usec_t t = 0;
+ DBusMessage *reply = NULL;
+ DBusMessageIter iter, sub;
+
+ assert(c);
+
+ if (bus_method_call_with_reply (
+ c->bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.DBus.Properties",
+ "Get",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &interface,
+ DBUS_TYPE_STRING, &property,
+ DBUS_TYPE_INVALID))
+ goto finish;
+
+ if (!dbus_message_iter_init(reply, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
+ log_error("Failed to parse reply.");
+ goto finish;
+ }
+
+ dbus_message_iter_recurse(&iter, &sub);
+
+ if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT64) {
+ log_error("Failed to parse reply.");
+ goto finish;
+ }
+
+ dbus_message_iter_get_basic(&sub, &t);
+
+finish:
+ if (reply)
+ dbus_message_unref(reply);
+ return t;
+}
+
+static int get_current_runlevel(Context *c) {
+ static const struct {
+ const int runlevel;
+ const char *special;
+ } table[] = {
+ /* The first target of this list that is active or has
+ * a job scheduled wins. We prefer runlevels 5 and 3
+ * here over the others, since these are the main
+ * runlevels used on Fedora. It might make sense to
+ * change the order on some distributions. */
+ { '5', SPECIAL_RUNLEVEL5_TARGET },
+ { '3', SPECIAL_RUNLEVEL3_TARGET },
+ { '4', SPECIAL_RUNLEVEL4_TARGET },
+ { '2', SPECIAL_RUNLEVEL2_TARGET },
+ { 'S', SPECIAL_RESCUE_TARGET },
+ };
+ const char
+ *interface = "org.freedesktop.systemd1.Unit",
+ *property = "ActiveState";
+
+ DBusMessage *reply = NULL;
+ int r = 0;
+ unsigned i;
+ DBusError error;
+
+ assert(c);
+
+ dbus_error_init(&error);
+
+ for (i = 0; i < ELEMENTSOF(table); i++) {
+ const char *path = NULL, *state;
+ DBusMessageIter iter, sub;
+
+ r = bus_method_call_with_reply (
+ c->bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "GetUnit",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &table[i].special,
+ DBUS_TYPE_INVALID);
+ if (r == -ENOMEM)
+ goto finish;
+ if (r)
+ continue;
+
+ if (!dbus_message_get_args(reply, &error,
+ DBUS_TYPE_OBJECT_PATH, &path,
+ DBUS_TYPE_INVALID)) {
+ log_error("Failed to parse reply: %s", bus_error_message(&error));
+ r = -EIO;
+ goto finish;
+ }
+
+ dbus_message_unref(reply);
+ r = bus_method_call_with_reply (
+ c->bus,
+ "org.freedesktop.systemd1",
+ path,
+ "org.freedesktop.DBus.Properties",
+ "Get",
+ &reply,
+ NULL,
+ DBUS_TYPE_STRING, &interface,
+ DBUS_TYPE_STRING, &property,
+ DBUS_TYPE_INVALID);
+ if (r)
+ goto finish;
+
+ if (!dbus_message_iter_init(reply, &iter) ||
+ dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
+ log_error("Failed to parse reply.");
+ r = -EIO;
+ goto finish;
+ }
+
+ dbus_message_iter_recurse(&iter, &sub);
+
+ if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
+ log_error("Failed to parse reply.");
+ r = -EIO;
+ goto finish;
+ }
+
+ dbus_message_iter_get_basic(&sub, &state);
+
+ if (streq(state, "active") || streq(state, "reloading"))
+ r = table[i].runlevel;
+
+ dbus_message_unref(reply);
+ reply = NULL;
+
+ if (r)
+ break;
+ }
+
+finish:
+ if (reply)
+ dbus_message_unref(reply);
+
+ dbus_error_free(&error);
+
+ return r;
+}
+
+static int on_reboot(Context *c) {
+ int r = 0, q;
+ usec_t t;
+
+ assert(c);
+
+ /* We finished start-up, so let's write the utmp
+ * record and send the audit msg */
+
+#ifdef HAVE_AUDIT
+ if (c->audit_fd >= 0)
+ if (audit_log_user_message(c->audit_fd, AUDIT_SYSTEM_BOOT, "init", NULL, NULL, NULL, 1) < 0 &&
+ errno != EPERM) {
+ log_error("Failed to send audit message: %m");
+ r = -errno;
+ }
+#endif
+
+ /* If this call fails it will return 0, which
+ * utmp_put_reboot() will then fix to the current time */
+ t = get_startup_time(c);
+
+ if ((q = utmp_put_reboot(t)) < 0) {
+ log_error("Failed to write utmp record: %s", strerror(-q));
+ r = q;
+ }
+
+ return r;
+}
+
+static int on_shutdown(Context *c) {
+ int r = 0, q;
+
+ assert(c);
+
+ /* We started shut-down, so let's write the utmp
+ * record and send the audit msg */
+
+#ifdef HAVE_AUDIT
+ if (c->audit_fd >= 0)
+ if (audit_log_user_message(c->audit_fd, AUDIT_SYSTEM_SHUTDOWN, "init", NULL, NULL, NULL, 1) < 0 &&
+ errno != EPERM) {
+ log_error("Failed to send audit message: %m");
+ r = -errno;
+ }
+#endif
+
+ if ((q = utmp_put_shutdown()) < 0) {
+ log_error("Failed to write utmp record: %s", strerror(-q));
+ r = q;
+ }
+
+ return r;
+}
+
+static int on_runlevel(Context *c) {
+ int r = 0, q, previous, runlevel;
+
+ assert(c);
+
+ /* We finished changing runlevel, so let's write the
+ * utmp record and send the audit msg */
+
+ /* First, get last runlevel */
+ if ((q = utmp_get_runlevel(&previous, NULL)) < 0) {
+
+ if (q != -ESRCH && q != -ENOENT) {
+ log_error("Failed to get current runlevel: %s", strerror(-q));
+ return q;
+ }
+
+ /* Hmm, we didn't find any runlevel, that means we
+ * have been rebooted */
+ r = on_reboot(c);
+ previous = 0;
+ }
+
+ /* Secondly, get new runlevel */
+ if ((runlevel = get_current_runlevel(c)) < 0)
+ return runlevel;
+
+ if (previous == runlevel)
+ return 0;
+
+#ifdef HAVE_AUDIT
+ if (c->audit_fd >= 0) {
+ char *s = NULL;
+
+ if (asprintf(&s, "old-level=%c new-level=%c",
+ previous > 0 ? previous : 'N',
+ runlevel > 0 ? runlevel : 'N') < 0)
+ return -ENOMEM;
+
+ if (audit_log_user_message(c->audit_fd, AUDIT_SYSTEM_RUNLEVEL, s, NULL, NULL, NULL, 1) < 0 &&
+ errno != EPERM) {
+ log_error("Failed to send audit message: %m");
+ r = -errno;
+ }
+
+ free(s);
+ }
+#endif
+
+ if ((q = utmp_put_runlevel(runlevel, previous)) < 0) {
+ if (q != -ESRCH && q != -ENOENT) {
+ log_error("Failed to write utmp record: %s", strerror(-q));
+ r = q;
+ }
+ }
+
+ return r;
+}
+
+int main(int argc, char *argv[]) {
+ int r;
+ DBusError error;
+ Context c = {};
+
+ dbus_error_init(&error);
+
+#ifdef HAVE_AUDIT
+ c.audit_fd = -1;
+#endif
+
+ if (getppid() != 1) {
+ log_error("This program should be invoked by init only.");
+ return EXIT_FAILURE;
+ }
+
+ if (argc != 2) {
+ log_error("This program requires one argument.");
+ return EXIT_FAILURE;
+ }
+
+ log_set_target(LOG_TARGET_AUTO);
+ log_parse_environment();
+ log_open();
+
+ umask(0022);
+
+#ifdef HAVE_AUDIT
+ if ((c.audit_fd = audit_open()) < 0 &&
+ /* If the kernel lacks netlink or audit support,
+ * don't worry about it. */
+ errno != EAFNOSUPPORT && errno != EPROTONOSUPPORT)
+ log_error("Failed to connect to audit log: %m");
+#endif
+
+ if (bus_connect(DBUS_BUS_SYSTEM, &c.bus, NULL, &error) < 0) {
+ log_error("Failed to get D-Bus connection: %s", bus_error_message(&error));
+ r = -EIO;
+ goto finish;
+ }
+
+ log_debug("systemd-update-utmp running as pid %lu", (unsigned long) getpid());
+
+ if (streq(argv[1], "reboot"))
+ r = on_reboot(&c);
+ else if (streq(argv[1], "shutdown"))
+ r = on_shutdown(&c);
+ else if (streq(argv[1], "runlevel"))
+ r = on_runlevel(&c);
+ else {
+ log_error("Unknown command %s", argv[1]);
+ r = -EINVAL;
+ }
+
+ log_debug("systemd-update-utmp stopped as pid %lu", (unsigned long) getpid());
+
+finish:
+#ifdef HAVE_AUDIT
+ if (c.audit_fd >= 0)
+ audit_close(c.audit_fd);
+#endif
+
+ if (c.bus) {
+ dbus_connection_flush(c.bus);
+ dbus_connection_close(c.bus);
+ dbus_connection_unref(c.bus);
+ }
+
+ dbus_error_free(&error);
+ dbus_shutdown();
+
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/src/vconsole/vconsole-setup.c b/src/vconsole/vconsole-setup.c
new file mode 100644
index 0000000000..1bbf737c36
--- /dev/null
+++ b/src/vconsole/vconsole-setup.c
@@ -0,0 +1,308 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Kay Sievers
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <stdio.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <string.h>
+#include <fcntl.h>
+#include <ctype.h>
+#include <stdbool.h>
+#include <stdarg.h>
+#include <limits.h>
+#include <sys/ioctl.h>
+#include <sys/wait.h>
+#include <linux/tiocl.h>
+#include <linux/kd.h>
+#include <linux/vt.h>
+
+#include "util.h"
+#include "log.h"
+#include "macro.h"
+#include "virt.h"
+#include "fileio.h"
+
+static bool is_vconsole(int fd) {
+ unsigned char data[1];
+
+ data[0] = TIOCL_GETFGCONSOLE;
+ return ioctl(fd, TIOCLINUX, data) >= 0;
+}
+
+static int disable_utf8(int fd) {
+ int r = 0, k;
+
+ if (ioctl(fd, KDSKBMODE, K_XLATE) < 0)
+ r = -errno;
+
+ if (loop_write(fd, "\033%@", 3, false) < 0)
+ r = -errno;
+
+ k = write_string_file("/sys/module/vt/parameters/default_utf8", "0");
+ if (k < 0)
+ r = k;
+
+ if (r < 0)
+ log_warning("Failed to disable UTF-8: %s", strerror(-r));
+
+ return r;
+}
+
+static int enable_utf8(int fd) {
+ int r = 0, k;
+ long current = 0;
+
+ if (ioctl(fd, KDGKBMODE, &current) < 0 || current == K_XLATE) {
+ /*
+ * Change the current keyboard to unicode, unless it
+ * is currently in raw or off mode anyway. We
+ * shouldn't interfere with X11's processing of the
+ * key events.
+ *
+ * http://lists.freedesktop.org/archives/systemd-devel/2013-February/008573.html
+ *
+ */
+
+ if (ioctl(fd, KDSKBMODE, K_UNICODE) < 0)
+ r = -errno;
+ }
+
+ if (loop_write(fd, "\033%G", 3, false) < 0)
+ r = -errno;
+
+ k = write_string_file("/sys/module/vt/parameters/default_utf8", "1");
+ if (k < 0)
+ r = k;
+
+ if (r < 0)
+ log_warning("Failed to enable UTF-8: %s", strerror(-r));
+
+ return r;
+}
+
+static int keymap_load(const char *vc, const char *map, const char *map_toggle, bool utf8, pid_t *_pid) {
+ const char *args[8];
+ int i = 0;
+ pid_t pid;
+
+ if (isempty(map)) {
+ /* An empty map means kernel map */
+ *_pid = 0;
+ return 0;
+ }
+
+ args[i++] = KBD_LOADKEYS;
+ args[i++] = "-q";
+ args[i++] = "-C";
+ args[i++] = vc;
+ if (utf8)
+ args[i++] = "-u";
+ args[i++] = map;
+ if (map_toggle)
+ args[i++] = map_toggle;
+ args[i++] = NULL;
+
+ pid = fork();
+ if (pid < 0) {
+ log_error("Failed to fork: %m");
+ return -errno;
+ } else if (pid == 0) {
+ execv(args[0], (char **) args);
+ _exit(EXIT_FAILURE);
+ }
+
+ *_pid = pid;
+ return 0;
+}
+
+static int font_load(const char *vc, const char *font, const char *map, const char *unimap, pid_t *_pid) {
+ const char *args[9];
+ int i = 0;
+ pid_t pid;
+
+ if (isempty(font)) {
+ /* An empty font means kernel font */
+ *_pid = 0;
+ return 0;
+ }
+
+ args[i++] = KBD_SETFONT;
+ args[i++] = "-C";
+ args[i++] = vc;
+ args[i++] = font;
+ if (map) {
+ args[i++] = "-m";
+ args[i++] = map;
+ }
+ if (unimap) {
+ args[i++] = "-u";
+ args[i++] = unimap;
+ }
+ args[i++] = NULL;
+
+ pid = fork();
+ if (pid < 0) {
+ log_error("Failed to fork: %m");
+ return -errno;
+ } else if (pid == 0) {
+ execv(args[0], (char **) args);
+ _exit(EXIT_FAILURE);
+ }
+
+ *_pid = pid;
+ return 0;
+}
+
+/*
+ * A newly allocated VT uses the font from the active VT. Here
+ * we update all possibly already allocated VTs with the configured
+ * font. It also allows to restart systemd-vconsole-setup.service,
+ * to apply a new font to all VTs.
+ */
+static void font_copy_to_all_vcs(int fd) {
+ struct vt_stat vcs = {};
+ int i, r;
+
+ /* get active, and 16 bit mask of used VT numbers */
+ r = ioctl(fd, VT_GETSTATE, &vcs);
+ if (r < 0)
+ return;
+
+ for (i = 1; i <= 15; i++) {
+ char vcname[16];
+ _cleanup_close_ int vcfd = -1;
+ struct console_font_op cfo = {};
+
+ if (i == vcs.v_active)
+ continue;
+
+ /* skip non-allocated ttys */
+ snprintf(vcname, sizeof(vcname), "/dev/vcs%i", i);
+ if (access(vcname, F_OK) < 0)
+ continue;
+
+ snprintf(vcname, sizeof(vcname), "/dev/tty%i", i);
+ vcfd = open_terminal(vcname, O_RDWR|O_CLOEXEC);
+ if (vcfd < 0)
+ continue;
+
+ /* copy font from active VT, where the font was uploaded to */
+ cfo.op = KD_FONT_OP_COPY;
+ cfo.height = vcs.v_active-1; /* tty1 == index 0 */
+ ioctl(vcfd, KDFONTOP, &cfo);
+ }
+}
+
+int main(int argc, char **argv) {
+ const char *vc;
+ char *vc_keymap = NULL;
+ char *vc_keymap_toggle = NULL;
+ char *vc_font = NULL;
+ char *vc_font_map = NULL;
+ char *vc_font_unimap = NULL;
+ int fd = -1;
+ bool utf8;
+ pid_t font_pid = 0, keymap_pid = 0;
+ bool font_copy = false;
+ int r = EXIT_FAILURE;
+
+ log_set_target(LOG_TARGET_AUTO);
+ log_parse_environment();
+ log_open();
+
+ umask(0022);
+
+ if (argv[1])
+ vc = argv[1];
+ else {
+ vc = "/dev/tty0";
+ font_copy = true;
+ }
+
+ fd = open_terminal(vc, O_RDWR|O_CLOEXEC);
+ if (fd < 0) {
+ log_error("Failed to open %s: %m", vc);
+ goto finish;
+ }
+
+ if (!is_vconsole(fd)) {
+ log_error("Device %s is not a virtual console.", vc);
+ goto finish;
+ }
+
+ utf8 = is_locale_utf8();
+
+ r = parse_env_file("/etc/vconsole.conf", NEWLINE,
+ "KEYMAP", &vc_keymap,
+ "KEYMAP_TOGGLE", &vc_keymap_toggle,
+ "FONT", &vc_font,
+ "FONT_MAP", &vc_font_map,
+ "FONT_UNIMAP", &vc_font_unimap,
+ NULL);
+
+ if (r < 0 && r != -ENOENT)
+ log_warning("Failed to read /etc/vconsole.conf: %s", strerror(-r));
+
+ /* Let the kernel command line override /etc/vconsole.conf */
+ if (detect_container(NULL) <= 0) {
+ r = parse_env_file("/proc/cmdline", WHITESPACE,
+ "vconsole.keymap", &vc_keymap,
+ "vconsole.keymap.toggle", &vc_keymap_toggle,
+ "vconsole.font", &vc_font,
+ "vconsole.font.map", &vc_font_map,
+ "vconsole.font.unimap", &vc_font_unimap,
+ NULL);
+
+ if (r < 0 && r != -ENOENT)
+ log_warning("Failed to read /proc/cmdline: %s", strerror(-r));
+ }
+
+ if (utf8)
+ enable_utf8(fd);
+ else
+ disable_utf8(fd);
+
+ r = EXIT_FAILURE;
+ if (keymap_load(vc, vc_keymap, vc_keymap_toggle, utf8, &keymap_pid) >= 0 &&
+ font_load(vc, vc_font, vc_font_map, vc_font_unimap, &font_pid) >= 0)
+ r = EXIT_SUCCESS;
+
+finish:
+ if (keymap_pid > 0)
+ wait_for_terminate_and_warn(KBD_LOADKEYS, keymap_pid);
+
+ if (font_pid > 0) {
+ wait_for_terminate_and_warn(KBD_SETFONT, font_pid);
+ if (font_copy)
+ font_copy_to_all_vcs(fd);
+ }
+
+ free(vc_keymap);
+ free(vc_font);
+ free(vc_font_map);
+ free(vc_font_unimap);
+
+ if (fd >= 0)
+ close_nointr_nofail(fd);
+
+ return r;
+}