summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLennart Poettering <lennart@poettering.net>2020-05-27 18:41:01 +0200
committerGitHub <noreply@github.com>2020-05-27 18:41:01 +0200
commit6bce17455e880404984761bfe064ed8ee1dce303 (patch)
tree1904a050c5921db33e8c7e20aa16df841c6b739c
parentf978844eb62e1c47431b388ab90aafdd29f624ec (diff)
parent2ad7597e44dc1cfd82c6b5211575dc8dc10c24a5 (diff)
downloadsystemd-6bce17455e880404984761bfe064ed8ee1dce303.tar.gz
Merge pull request #15226 from benzea/benzea/xdg-autostart-generator
xdg-autostart-generator: a generator for XDG autostart files
-rw-r--r--man/rules/meson.build1
-rw-r--r--man/systemd-xdg-autostart-generator.xml57
-rw-r--r--man/systemd.generator.xml1
-rw-r--r--man/systemd.special.xml12
-rw-r--r--meson.build24
-rw-r--r--meson_options.txt2
-rw-r--r--src/fuzz/fuzz-xdg-desktop.c37
-rw-r--r--src/fuzz/meson.build6
-rw-r--r--src/sysv-generator/sysv-generator.c2
-rw-r--r--src/test/meson.build10
-rw-r--r--src/test/test-xdg-autostart.c95
-rw-r--r--src/xdg-autostart-generator/xdg-autostart-condition.c46
-rw-r--r--src/xdg-autostart-generator/xdg-autostart-generator.c116
-rw-r--r--src/xdg-autostart-generator/xdg-autostart-service.c618
-rw-r--r--src/xdg-autostart-generator/xdg-autostart-service.h36
-rw-r--r--test/fuzz/fuzz-xdg-desktop/full.desktop10
-rw-r--r--test/fuzz/fuzz-xdg-desktop/org.gnome.SettingsDaemon.Power.desktop10
-rw-r--r--test/fuzz/fuzz-xdg-desktop/valid.desktop12
-rw-r--r--units/user/meson.build4
-rw-r--r--units/user/xdg-desktop-autostart.target14
20 files changed, 1112 insertions, 1 deletions
diff --git a/man/rules/meson.build b/man/rules/meson.build
index 78440e6e91..b04ae1c67c 100644
--- a/man/rules/meson.build
+++ b/man/rules/meson.build
@@ -975,6 +975,7 @@ manpages = [
['systemd-veritysetup'],
'HAVE_LIBCRYPTSETUP'],
['systemd-volatile-root.service', '8', ['systemd-volatile-root'], ''],
+ ['systemd-xdg-autostart-generator', '8', [], 'ENABLE_XDG_AUTOSTART'],
['systemd', '1', ['init'], ''],
['systemd.automount', '5', [], ''],
['systemd.device', '5', [], ''],
diff --git a/man/systemd-xdg-autostart-generator.xml b/man/systemd-xdg-autostart-generator.xml
new file mode 100644
index 0000000000..1d50ec5cfe
--- /dev/null
+++ b/man/systemd-xdg-autostart-generator.xml
@@ -0,0 +1,57 @@
+<?xml version="1.0"?>
+<!--*-nxml-*-->
+<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
+ "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd">
+<!-- SPDX-License-Identifier: LGPL-2.1+ -->
+<refentry id="systemd-xdg-autostart-generator" conditional="ENABLE_XDG_AUTOSTART">
+
+ <refentryinfo>
+ <title>systemd-xdg-autostart-generator</title>
+ <productname>systemd</productname>
+ </refentryinfo>
+
+ <refmeta>
+ <refentrytitle>systemd-xdg-autostart-generator</refentrytitle>
+ <manvolnum>8</manvolnum>
+ </refmeta>
+
+ <refnamediv>
+ <refname>systemd-xdg-autostart-generator</refname>
+ <refpurpose>User unit generator for XDG autostart files</refpurpose>
+ </refnamediv>
+
+ <refsynopsisdiv>
+ <para><filename>/usr/lib/systemd/system-generators/systemd-xdg-autostart-generator</filename></para>
+ </refsynopsisdiv>
+
+ <refsect1>
+ <title>Description</title>
+
+ <para><filename>systemd-xdg-autostart-generator</filename> is a generator
+ that creates .service units for
+ <ulink url="https://specifications.freedesktop.org/autostart-spec/autostart-spec-latest.html">XDG autostart</ulink>
+ files.
+ This permits desktop environments to delegate startup of these applications to
+ <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>
+ .</para>
+
+ <para>Units created by <filename>systemd-xdg-autostart-generator</filename>
+ can be started by the desktop environment using <literal>xdg-desktop-autostart.target</literal>.
+ See
+ <citerefentry><refentrytitle>systemd.special</refentrytitle><manvolnum>5</manvolnum></citerefentry>
+ for more details.</para>
+
+ <para><filename>systemd-xdg-autostart-generator</filename> implements
+ <citerefentry><refentrytitle>systemd.generator</refentrytitle><manvolnum>7</manvolnum></citerefentry>.</para>
+ </refsect1>
+
+ <refsect1>
+ <title>See Also</title>
+ <para>
+ <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>,
+ <citerefentry><refentrytitle>systemd.service</refentrytitle><manvolnum>5</manvolnum></citerefentry>,
+ <citerefentry><refentrytitle>systemd.target</refentrytitle><manvolnum>5</manvolnum></citerefentry>
+ </para>
+ </refsect1>
+
+</refentry>
diff --git a/man/systemd.generator.xml b/man/systemd.generator.xml
index dd0b591996..babbe14e04 100644
--- a/man/systemd.generator.xml
+++ b/man/systemd.generator.xml
@@ -310,6 +310,7 @@ find $dir</programlisting>
<citerefentry><refentrytitle>systemd-rc-local-generator</refentrytitle><manvolnum>8</manvolnum></citerefentry>,
<citerefentry><refentrytitle>systemd-system-update-generator</refentrytitle><manvolnum>8</manvolnum></citerefentry>,
<citerefentry><refentrytitle>systemd-sysv-generator</refentrytitle><manvolnum>8</manvolnum></citerefentry>,
+ <citerefentry><refentrytitle>systemd-xdg-autostart-generator</refentrytitle><manvolnum>8</manvolnum></citerefentry>,
<citerefentry><refentrytitle>systemd.unit</refentrytitle><manvolnum>5</manvolnum></citerefentry>,
<citerefentry><refentrytitle>systemctl</refentrytitle><manvolnum>1</manvolnum></citerefentry>,
<citerefentry><refentrytitle>systemd.environment-generator</refentrytitle><manvolnum>7</manvolnum></citerefentry>
diff --git a/man/systemd.special.xml b/man/systemd.special.xml
index c37e732b5f..8cd4c15f28 100644
--- a/man/systemd.special.xml
+++ b/man/systemd.special.xml
@@ -1150,6 +1150,18 @@
<filename>gnome-session.target</filename>.</para>
</listitem>
</varlistentry>
+
+ <varlistentry>
+ <term><filename>xdg-desktop-autostart.target</filename></term>
+ <listitem>
+ <para>The XDG specification defines a way to autostart applications using XDG desktop files.
+ systemd ships
+ <citerefentry><refentrytitle>systemd-xdg-autostart-generator</refentrytitle><manvolnum>8</manvolnum></citerefentry>
+ for the XDG desktop files in autostart directories.
+ Desktop Environments can opt-in to use this service by adding a <varname>Wants=</varname>
+ dependency on <literal>xdg-desktop-autostart.target</literal></para>.
+ </listitem>
+ </varlistentry>
</variablelist>
</refsect2>
</refsect1>
diff --git a/meson.build b/meson.build
index 53c450eb01..008fd998e9 100644
--- a/meson.build
+++ b/meson.build
@@ -1417,6 +1417,7 @@ foreach term : ['utmp',
'tmpfiles',
'hwdb',
'rfkill',
+ 'xdg-autostart',
'ldconfig',
'efi',
'tpm',
@@ -1520,6 +1521,7 @@ includes = include_directories('src/basic',
'src/libudev',
'src/core',
'src/shutdown',
+ 'src/xdg-autostart-generator',
'src/libsystemd/sd-bus',
'src/libsystemd/sd-device',
'src/libsystemd/sd-event',
@@ -2301,6 +2303,27 @@ if conf.get('HAVE_SYSV_COMPAT') == 1
install_dir : systemgeneratordir)
endif
+if conf.get('ENABLE_XDG_AUTOSTART') == 1
+ executable(
+ 'systemd-xdg-autostart-generator',
+ 'src/xdg-autostart-generator/xdg-autostart-generator.c',
+ 'src/xdg-autostart-generator/xdg-autostart-service.c',
+ include_directories : includes,
+ link_with : [libshared],
+ install_rpath : rootlibexecdir,
+ install : true,
+ install_dir : usergeneratordir)
+
+ executable(
+ 'systemd-xdg-autostart-condition',
+ 'src/xdg-autostart-generator/xdg-autostart-condition.c',
+ include_directories : includes,
+ link_with : [libshared],
+ install_rpath : rootlibexecdir,
+ install : true,
+ install_dir : rootlibexecdir)
+endif
+
if conf.get('ENABLE_HOSTNAMED') == 1
executable(
'systemd-hostnamed',
@@ -3566,6 +3589,7 @@ foreach tuple : [
['randomseed'],
['backlight'],
['rfkill'],
+ ['xdg-autostart'],
['logind'],
['machined'],
['portabled'],
diff --git a/meson_options.txt b/meson_options.txt
index d5ed2a7a42..2a2597912f 100644
--- a/meson_options.txt
+++ b/meson_options.txt
@@ -142,6 +142,8 @@ option('hwdb', type : 'boolean',
description : 'support for the hardware database')
option('rfkill', type : 'boolean',
description : 'support for the rfkill tools')
+option('xdg-autostart', type : 'boolean',
+ description : 'install the xdg-autostart-generator and unit')
option('man', type : 'combo', choices : ['auto', 'true', 'false'],
value : 'false',
description : 'build and install man pages')
diff --git a/src/fuzz/fuzz-xdg-desktop.c b/src/fuzz/fuzz-xdg-desktop.c
new file mode 100644
index 0000000000..8c6472bee5
--- /dev/null
+++ b/src/fuzz/fuzz-xdg-desktop.c
@@ -0,0 +1,37 @@
+/* SPDX-License-Identifier: LGPL-2.1+ */
+
+#include "alloc-util.h"
+#include "fd-util.h"
+#include "fs-util.h"
+#include "rm-rf.h"
+#include "string-util.h"
+#include "strv.h"
+#include "tests.h"
+#include "tmpfile-util.h"
+#include "fuzz.h"
+#include "xdg-autostart-service.h"
+
+int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
+ _cleanup_(unlink_tempfilep) char name[] = "/tmp/fuzz-xdg-desktop.XXXXXX";
+ _cleanup_close_ int fd = -1;
+ _cleanup_(xdg_autostart_service_freep) XdgAutostartService *service = NULL;
+ _cleanup_(rm_rf_physical_and_freep) char *tmpdir = NULL;
+
+ /* We don't want to fill the logs with messages about parse errors.
+ * Disable most logging if not running standalone */
+ if (!getenv("SYSTEMD_LOG_LEVEL"))
+ log_set_max_level(LOG_CRIT);
+
+ assert_se(mkdtemp_malloc("/tmp/fuzz-xdg-desktop-XXXXXX", &tmpdir) >= 0);
+
+ fd = mkostemp_safe(name);
+ assert_se(fd >= 0);
+ assert_se(write(fd, data, size) == (ssize_t) size);
+
+ assert_se(service = xdg_autostart_service_parse_desktop(name));
+ assert_se(service->name = strdup("fuzz-xdg-desktop.service"));
+ if (service)
+ (void) xdg_autostart_service_generate_unit(service, tmpdir);
+
+ return 0;
+}
diff --git a/src/fuzz/meson.build b/src/fuzz/meson.build
index c88812d1de..01f119fcd0 100644
--- a/src/fuzz/meson.build
+++ b/src/fuzz/meson.build
@@ -146,4 +146,10 @@ fuzzers += [
[['src/fuzz/fuzz-time-util.c'],
[libshared],
[]],
+
+ [['src/fuzz/fuzz-xdg-desktop.c',
+ 'src/xdg-autostart-generator/xdg-autostart-service.h',
+ 'src/xdg-autostart-generator/xdg-autostart-service.c'],
+ [],
+ []],
]
diff --git a/src/sysv-generator/sysv-generator.c b/src/sysv-generator/sysv-generator.c
index 3ad139b242..eb6b2d084e 100644
--- a/src/sysv-generator/sysv-generator.c
+++ b/src/sysv-generator/sysv-generator.c
@@ -849,7 +849,7 @@ static int set_dependencies_from_rcnd(const LookupPaths *lp, Hashmap *all_servic
continue;
}
- FOREACH_DIRENT(de, d, log_error_errno(errno, "Failed to enumerate directory %s, ignoring: %m", path)) {
+ FOREACH_DIRENT(de, d, log_warning_errno(errno, "Failed to enumerate directory %s, ignoring: %m", path)) {
_cleanup_free_ char *name = NULL, *fpath = NULL;
int a, b;
diff --git a/src/test/meson.build b/src/test/meson.build
index 318dc25906..d3fc803088 100644
--- a/src/test/meson.build
+++ b/src/test/meson.build
@@ -1143,3 +1143,13 @@ tests += [
libshared],
[threads]],
]
+
+############################################################
+
+tests += [
+ [['src/test/test-xdg-autostart.c',
+ 'src/xdg-autostart-generator/xdg-autostart-service.c',
+ 'src/xdg-autostart-generator/xdg-autostart-service.h',],
+ [],
+ []],
+]
diff --git a/src/test/test-xdg-autostart.c b/src/test/test-xdg-autostart.c
new file mode 100644
index 0000000000..cc75bc6024
--- /dev/null
+++ b/src/test/test-xdg-autostart.c
@@ -0,0 +1,95 @@
+/* SPDX-License-Identifier: LGPL-2.1+ */
+
+#include "alloc-util.h"
+#include "fd-util.h"
+#include "fs-util.h"
+#include "string-util.h"
+#include "strv.h"
+#include "tests.h"
+#include "tmpfile-util.h"
+#include "xdg-autostart-service.h"
+
+static void test_translate_name(void) {
+ _cleanup_free_ char *t;
+
+ assert_se(t = xdg_autostart_service_translate_name("a-b.blub.desktop"));
+ assert_se(streq(t, "app-a\\x2db.blub-autostart.service"));
+}
+
+static void test_xdg_format_exec_start_one(const char *exec, const char *expected) {
+ _cleanup_free_ char* out = NULL;
+
+ xdg_autostart_format_exec_start(exec, &out);
+ log_info("In: '%s', out: '%s', expected: '%s'", exec, out, expected);
+ assert_se(streq(out, expected));
+}
+
+static void test_xdg_format_exec_start(void) {
+ test_xdg_format_exec_start_one("/bin/sleep 100", "/bin/sleep \"100\"");
+
+ /* All standardised % identifiers are stripped. */
+ test_xdg_format_exec_start_one("/bin/sleep %f \"%F\" %u %U %d %D\t%n %N %i %c %k %v %m", "/bin/sleep");
+
+ /* Unknown % identifier currently remain, but are escaped. */
+ test_xdg_format_exec_start_one("/bin/sleep %X \"%Y\"", "/bin/sleep \"%%X\" \"%%Y\"");
+
+ test_xdg_format_exec_start_one("/bin/sleep \";\\\"\"", "/bin/sleep \";\\\"\"");
+}
+
+static const char* const xdg_desktop_file[] = {
+ "[Desktop Entry]\n"
+ "Exec\t =\t /bin/sleep 100\n" /* Whitespace Before/After = must be ignored */
+ "OnlyShowIn = A;B;\n"
+ "NotShowIn=C;;D\\\\\\;;E\n", /* "C", "", "D\;", "E" */
+
+ "[Desktop Entry]\n"
+ "Exec=a\n"
+ "Exec=b\n",
+
+ "[Desktop Entry]\n"
+ "Hidden=\t true\n",
+};
+
+static void test_xdg_desktop_parse(unsigned i, const char *s) {
+ _cleanup_(unlink_tempfilep) char name[] = "/tmp/test-xdg-autostart-parser.XXXXXX";
+ _cleanup_fclose_ FILE *f = NULL;
+ _cleanup_(xdg_autostart_service_freep) XdgAutostartService *service = NULL;
+
+ log_info("== %s[%i] ==", __func__, i);
+
+ assert_se(fmkostemp_safe(name, "r+", &f) == 0);
+ assert_se(fwrite(s, strlen(s), 1, f) == 1);
+ rewind(f);
+
+ assert_se(service = xdg_autostart_service_parse_desktop(name));
+
+ switch (i) {
+ case 0:
+ assert_se(streq(service->exec_string, "/bin/sleep 100"));
+ assert_se(strv_equal(service->only_show_in, STRV_MAKE("A", "B")));
+ assert_se(strv_equal(service->not_show_in, STRV_MAKE("C", "", "D\\;", "E")));
+ assert_se(!service->hidden);
+ break;
+ case 1:
+ /* The second entry is not permissible and will be ignored (and error logged). */
+ assert_se(streq(service->exec_string, "a"));
+ break;
+ case 2:
+ assert_se(service->hidden);
+ break;
+ }
+}
+
+int main(int argc, char *argv[]) {
+ size_t i;
+
+ test_setup_logging(LOG_DEBUG);
+
+ test_translate_name();
+ test_xdg_format_exec_start();
+
+ for (i = 0; i < ELEMENTSOF(xdg_desktop_file); i++)
+ test_xdg_desktop_parse(i, xdg_desktop_file[i]);
+
+ return 0;
+}
diff --git a/src/xdg-autostart-generator/xdg-autostart-condition.c b/src/xdg-autostart-generator/xdg-autostart-condition.c
new file mode 100644
index 0000000000..84a3561654
--- /dev/null
+++ b/src/xdg-autostart-generator/xdg-autostart-condition.c
@@ -0,0 +1,46 @@
+/* SPDX-License-Identifier: LGPL-2.1+ */
+
+#include "main-func.h"
+#include "strv.h"
+
+/*
+ * This binary is intended to be run as an ExecCondition= in units generated
+ * by the xdg-autostart-generator. It does the appropriate checks against
+ * XDG_CURRENT_DESKTOP that are too advanced for simple ConditionEnvironment=
+ * matches.
+ */
+
+static int run(int argc, char *argv[]) {
+ _cleanup_strv_free_ char **only_show_in = NULL, **not_show_in = NULL, **desktops = NULL;
+ const char *xdg_current_desktop;
+ char **d;
+
+ if (argc != 3)
+ return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
+ "Wrong argument count. Expected the OnlyShowIn= and NotShowIn= sets, each colon separated.");
+
+ xdg_current_desktop = getenv("XDG_CURRENT_DESKTOP");
+ if (xdg_current_desktop) {
+ desktops = strv_split(xdg_current_desktop, ":");
+ if (!desktops)
+ return log_oom();
+ }
+
+ only_show_in = strv_split(argv[1], ":");
+ not_show_in = strv_split(argv[2], ":");
+ if (!only_show_in || !not_show_in)
+ return log_oom();
+
+ /* Each desktop in XDG_CURRENT_DESKTOP needs to be matched in order. */
+ STRV_FOREACH(d, desktops) {
+ if (strv_contains(only_show_in, *d))
+ return 0;
+ if (strv_contains(not_show_in, *d))
+ return 1;
+ }
+
+ /* non-zero exit code when only_show_in has a proper value */
+ return !strv_isempty(only_show_in);
+}
+
+DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);
diff --git a/src/xdg-autostart-generator/xdg-autostart-generator.c b/src/xdg-autostart-generator/xdg-autostart-generator.c
new file mode 100644
index 0000000000..53366a31ec
--- /dev/null
+++ b/src/xdg-autostart-generator/xdg-autostart-generator.c
@@ -0,0 +1,116 @@
+/* SPDX-License-Identifier: LGPL-2.1+ */
+
+#include <errno.h>
+#include <stdio.h>
+#include <unistd.h>
+
+#include "dirent-util.h"
+#include "fd-util.h"
+#include "generator.h"
+#include "hashmap.h"
+#include "log.h"
+#include "main-func.h"
+#include "nulstr-util.h"
+#include "path-lookup.h"
+#include "stat-util.h"
+#include "string-util.h"
+#include "strv.h"
+#include "xdg-autostart-service.h"
+
+DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(xdgautostartservice_hash_ops, char, string_hash_func, string_compare_func, XdgAutostartService, xdg_autostart_service_free);
+
+static int enumerate_xdg_autostart(Hashmap *all_services) {
+ _cleanup_strv_free_ char **autostart_dirs = NULL;
+ _cleanup_strv_free_ char **config_dirs = NULL;
+ _unused_ _cleanup_strv_free_ char **data_dirs = NULL;
+ _cleanup_free_ char *user_config_autostart_dir = NULL;
+ char **path;
+ int r;
+
+ r = xdg_user_config_dir(&user_config_autostart_dir, "/autostart");
+ if (r < 0)
+ return r;
+ r = strv_extend(&autostart_dirs, user_config_autostart_dir);
+ if (r < 0)
+ return r;
+
+ r = xdg_user_dirs(&config_dirs, &data_dirs);
+ if (r < 0)
+ return r;
+ r = strv_extend_strv_concat(&autostart_dirs, config_dirs, "/autostart");
+ if (r < 0)
+ return r;
+
+ STRV_FOREACH(path, autostart_dirs) {
+ _cleanup_closedir_ DIR *d = NULL;
+ struct dirent *de;
+
+ d = opendir(*path);
+ if (!d) {
+ if (errno != ENOENT)
+ log_warning_errno(errno, "Opening %s failed, ignoring: %m", *path);
+ continue;
+ }
+
+ FOREACH_DIRENT(de, d, log_warning_errno(errno, "Failed to enumerate directory %s, ignoring: %m", *path)) {
+ _cleanup_free_ char *fpath = NULL, *name = NULL;
+ _cleanup_(xdg_autostart_service_freep) XdgAutostartService *service = NULL;
+ struct stat st;
+
+ if (fstatat(dirfd(d), de->d_name, &st, 0) < 0) {
+ log_warning_errno(errno, "stat() failed on %s/%s, ignoring: %m", *path, de->d_name);
+ continue;
+ }
+
+ if (!S_ISREG(st.st_mode))
+ continue;
+
+ name = xdg_autostart_service_translate_name(de->d_name);
+ if (!name)
+ return log_oom();
+
+ if (hashmap_contains(all_services, name))
+ continue;
+
+ fpath = path_join(*path, de->d_name);
+ if (!fpath)
+ return log_oom();
+
+ service = xdg_autostart_service_parse_desktop(fpath);
+ if (!service)
+ return log_oom();
+ service->name = TAKE_PTR(name);
+
+ r = hashmap_put(all_services, service->name, service);
+ if (r < 0)
+ return log_oom();
+ TAKE_PTR(service);
+ }
+ }
+
+ return 0;
+}
+
+static int run(const char *dest, const char *dest_early, const char *dest_late) {
+ _cleanup_(hashmap_freep) Hashmap *all_services = NULL;
+ XdgAutostartService *service;
+ Iterator j;
+ int r;
+
+ assert_se(dest_late);
+
+ all_services = hashmap_new(&xdgautostartservice_hash_ops);
+ if (!all_services)
+ return log_oom();
+
+ r = enumerate_xdg_autostart(all_services);
+ if (r < 0)
+ return r;
+
+ HASHMAP_FOREACH(service, all_services, j)
+ (void) xdg_autostart_service_generate_unit(service, dest_late);
+
+ return 0;
+}
+
+DEFINE_MAIN_GENERATOR_FUNCTION(run);
diff --git a/src/xdg-autostart-generator/xdg-autostart-service.c b/src/xdg-autostart-generator/xdg-autostart-service.c
new file mode 100644
index 0000000000..9ff80c5bb0
--- /dev/null
+++ b/src/xdg-autostart-generator/xdg-autostart-service.c
@@ -0,0 +1,618 @@
+/* SPDX-License-Identifier: LGPL-2.1+ */
+
+#include <errno.h>
+#include <stdio.h>
+#include <unistd.h>
+
+#include "xdg-autostart-service.h"
+
+#include "conf-parser.h"
+#include "escape.h"
+#include "unit-name.h"
+#include "path-util.h"
+#include "fd-util.h"
+#include "generator.h"
+#include "log.h"
+#include "specifier.h"
+#include "string-util.h"
+#include "nulstr-util.h"
+#include "strv.h"
+
+XdgAutostartService* xdg_autostart_service_free(XdgAutostartService *s) {
+ if (!s)
+ return NULL;
+
+ free(s->name);
+ free(s->path);
+ free(s->description);
+
+ free(s->type);
+ free(s->exec_string);
+
+ strv_free(s->only_show_in);
+ strv_free(s->not_show_in);
+
+ free(s->try_exec);
+ free(s->autostart_condition);
+ free(s->kde_autostart_condition);
+
+ free(s->gnome_autostart_phase);
+
+ return mfree(s);
+}
+
+char *xdg_autostart_service_translate_name(const char *name) {
+ _cleanup_free_ char *c = NULL, *escaped = NULL;
+ char *res;
+
+ c = strdup(name);
+ if (!c)
+ return NULL;
+
+ res = endswith(c, ".desktop");
+ if (res)
+ *res = '\0';
+
+ escaped = unit_name_escape(c);
+ if (!escaped)
+ return NULL;
+
+ return strjoin("app-", escaped, "-autostart.service");
+}
+
+static int xdg_config_parse_bool(
+ const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ unsigned section_line,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ bool *b = data;
+ const char *value;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ if (streq(rvalue, "true"))
+ *b = true;
+ else if (streq(rvalue, "false"))
+ *b = false;
+ else
+ return log_syntax(unit, LOG_ERR, filename, line, SYNTHETIC_ERRNO(EINVAL), "Invalid value for boolean: %s", value);
+
+ return 0;
+}
+
+/* Unescapes the string in-place, returns non-zero status on error. */
+static int xdg_unescape_string(
+ const char *unit,
+ const char *filename,
+ int line,
+ char *str) {
+
+ char *in;
+ char *out;
+
+ assert(str);
+
+ in = out = str;
+
+ for (; *in; in++, out++) {
+ if (*in == '\\') {
+ /* Move forward, and ensure it is a valid escape. */
+ in++;
+
+ switch (*in) {
+ case 's':
+ *out = ' ';
+ break;
+ case 'n':
+ *out = '\n';
+ break;
+ case 't':
+ *out = '\t';
+ break;
+ case 'r':
+ *out = '\r';
+ break;
+ case '\\':
+ *out = '\\';
+ break;
+ case ';':
+ /* Technically only permitted for strv. */
+ *out = ';';
+ break;
+ default:
+ return log_syntax(unit, LOG_ERR, filename, line, SYNTHETIC_ERRNO(EINVAL), "Undefined escape sequence \\%c.", *in);
+ }
+
+ continue;
+ }
+
+ *out = *in;
+ }
+ *out = '\0';
+
+ return 0;
+}
+
+/* Note: We do not bother with unescaping the strings, hence the _raw postfix. */
+static int xdg_config_parse_string(
+ const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ unsigned section_line,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ _cleanup_free_ char *res = NULL;
+ char **out = data;
+ int r;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ /* XDG does not allow duplicate definitions. */
+ if (*out) {
+ log_syntax(unit, LOG_ERR, filename, line, 0, "Key %s was defined multiple times, ignoring.", lvalue);
+ return 0;
+ }
+
+ res = strdup(rvalue);
+ if (!res)
+ return log_oom();
+
+ r = xdg_unescape_string(unit, filename, line, res);
+ if (r < 0)
+ return r;
+
+ *out = TAKE_PTR(res);
+ return 0;
+}
+
+static int xdg_config_parse_strv(
+ const char *unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ unsigned section_line,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ char ***sv = data;
+ const char *start;
+ const char *end;
+ int r;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ /* XDG does not allow duplicate definitions. */
+ if (*sv) {
+ log_syntax(unit, LOG_ERR, filename, line, 0, "Key %s was defined multiple times, ignoring.", lvalue);
+ return 0;
+ }
+
+ *sv = strv_new(NULL);
+ if (!*sv)
+ return log_oom();
+
+ /* We cannot use strv_split because it does not handle escaping correctly. */
+ start = rvalue;
+
+ for (end = start; *end; end++) {
+ if (*end == '\\') {
+ /* Move forward, and ensure it is a valid escape. */
+ end++;
+ if (strchr("sntr\\;", *end) == NULL) {
+ log_syntax(unit, LOG_ERR, filename, line, 0, "Undefined escape sequence \\%c.", *end);
+ return 0;
+ }
+ continue;
+ }
+
+ if (*end == ';') {
+ _cleanup_free_ char *copy = NULL;
+
+ copy = strndup(start, end - start);
+ if (!copy)
+ return log_oom();
+ r = xdg_unescape_string(unit, filename, line, copy);
+ if (r < 0)
+ return r;
+ r = strv_consume(sv, TAKE_PTR(copy));
+ if (r < 0)
+ return log_oom();
+
+ start = end + 1;
+ }
+ }
+
+ /* Any trailing entry should be ignored if it is empty. */
+ if (end > start) {
+ r = strv_extend(sv, start);
+ if (r < 0)
+ return log_oom();
+ }
+
+ return 0;
+}
+
+static int xdg_config_item_table_lookup(
+ const void *table,
+ const char *section,
+ const char *lvalue,
+ ConfigParserCallback *func,
+ int *ltype,
+ void **data,
+ void *userdata) {
+
+ assert(lvalue);
+
+ /* Ignore any keys with [] as those are translations. */
+ if (strchr(lvalue, '[')) {
+ *func = NULL;
+ *ltype = 0;
+ *data = NULL;
+ return 1;
+ }
+
+ return config_item_table_lookup(table, section, lvalue, func, ltype, data, userdata);
+}
+
+XdgAutostartService *xdg_autostart_service_parse_desktop(const char *path) {
+ _cleanup_(xdg_autostart_service_freep) XdgAutostartService *service = NULL;
+ int r;
+
+ service = new0(XdgAutostartService, 1);
+ if (!service)
+ return NULL;
+
+ service->path = strdup(path);
+ if (!service->path)
+ return NULL;
+
+ const ConfigTableItem items[] = {
+ { "Desktop Entry", "Name", xdg_config_parse_string, 0, &service->description},
+ { "Desktop Entry", "Exec", xdg_config_parse_string, 0, &service->exec_string},
+ { "Desktop Entry", "TryExec", xdg_config_parse_string, 0, &service->try_exec},
+ { "Desktop Entry", "Type", xdg_config_parse_string, 0, &service->type},
+ { "Desktop Entry", "OnlyShowIn", xdg_config_parse_strv, 0, &service->only_show_in},
+ { "Desktop Entry", "NotShowIn", xdg_config_parse_strv, 0, &service->not_show_in},
+ { "Desktop Entry", "Hidden", xdg_config_parse_bool, 0, &service->hidden},
+ { "Desktop Entry", "AutostartCondition", xdg_config_parse_string, 0, &service->autostart_condition},
+ { "Desktop Entry", "X-KDE-autostart-condition", xdg_config_parse_string, 0, &service->kde_autostart_condition},
+ { "Desktop Entry", "X-GNOME-Autostart-Phase", xdg_config_parse_string, 0, &service->gnome_autostart_phase},
+ { "Desktop Entry", "X-systemd-skip", xdg_config_parse_bool, 0, &service->systemd_skip},
+
+ /* Common entries that we do not use currently. */
+ { "Desktop Entry", "Categories", NULL, 0, NULL},
+ { "Desktop Entry", "Comment", NULL, 0, NULL},
+ { "Desktop Entry", "Encoding", NULL, 0, NULL},
+ { "Desktop Entry", "GenericName", NULL, 0, NULL},
+ { "Desktop Entry", "Icon", NULL, 0, NULL},
+ { "Desktop Entry", "Keywords", NULL, 0, NULL},
+ { "Desktop Entry", "NoDisplay", NULL, 0, NULL},
+ { "Desktop Entry", "StartupNotify", NULL, 0, NULL},
+ { "Desktop Entry", "Terminal", NULL, 0, NULL},
+ { "Desktop Entry", "Version", NULL, 0, NULL},
+ {}
+ };
+
+ r = config_parse(NULL, service->path, NULL,
+ "Desktop Entry\0",
+ xdg_config_item_table_lookup, items,
+ CONFIG_PARSE_WARN, service);
+ /* If parsing failed, only hide the file so it will still mask others. */
+ if (r < 0) {
+ log_warning_errno(r, "Failed to parse %s, ignoring it", service->path);
+ service->hidden = true;
+ }
+
+ return TAKE_PTR(service);
+}
+
+int xdg_autostart_format_exec_start(
+ const char *exec,
+ char **ret_exec_start) {
+
+ _cleanup_strv_free_ char **exec_split = NULL;
+ char *res;
+ size_t n, i;
+ bool first_arg;
+ int r;
+
+ /*
+ * Unfortunately, there is a mismatch between systemd's idea of $PATH
+ * and XDGs. i.e. we need to ensure that we have an absolute path to
+ * support cases where $PATH has been modified from the default set.
+ *
+ * Note that this is only needed for development environments though;
+ * so while it is important, this should have no effect in production
+ * environments.
+ *
+ * To be compliant with the XDG specification, we also need to strip
+ * certain parameters and such. Doing so properly makes parsing the
+ * command line unavoidable.
+ *
+ * NOTE: Technically, XDG only specifies " as quotes, while this also
+ * accepts '.
+ */
+ exec_split = strv_split_full(exec, WHITESPACE, SPLIT_QUOTES | SPLIT_RELAX);
+ if (!exec_split)
+ return -ENOMEM;
+
+ if (strv_isempty(exec_split))
+ return log_warning_errno(SYNTHETIC_ERRNO(EINVAL), "Exec line is empty");
+
+ first_arg = true;
+ for (i = n = 0; exec_split[i]; i++) {
+ _cleanup_free_ char *c = NULL, *raw = NULL, *p = NULL, *escaped = NULL, *quoted = NULL;
+
+ r = cunescape(exec_split[i], 0, &c);
+ if (r < 0)
+ return log_debug_errno(r, "Failed to unescape '%s': %m", exec_split[i]);
+
+ if (first_arg) {
+ _cleanup_free_ char *executable = NULL;
+
+ /* This is the executable, find it in $PATH */
+ first_arg = false;
+ r = find_binary(c, &executable);
+ if (r < 0)
+ return log_info_errno(r, "Exec binary '%s' does not exist: %m", c);
+
+ escaped = cescape(executable);
+ if (!escaped)
+ return log_oom();
+
+ free(exec_split[n]);
+ exec_split[n++] = TAKE_PTR(escaped);
+ continue;
+ }
+
+ /*
+ * Remove any standardised XDG fields; we assume they never appear as
+ * part of another argument as that just does not make any sense as
+ * they can be empty (GLib will e.g. turn "%f" into an empty argument).
+ * Other implementations may handle this differently.
+ */
+ if (STR_IN_SET(c,
+ "%f", "%F",
+ "%u", "%U",
+ "%d", "%D",
+ "%n", "%N",
+ "%i", /* Location of icon, could be implemented. */
+ "%c", /* Translated application name, could be implemented. */
+ "%k", /* Location of desktop file, could be implemented. */
+ "%v",
+ "%m"
+ ))
+ continue;
+
+ /*
+ * %% -> % and then % -> %% means that we correctly quote any %
+ * and also quote any left over (and invalid) % specifier from
+ * the desktop file.
+ */
+ raw = strreplace(c, "%%", "%");
+ if (!raw)
+ return log_oom();
+ p = strreplace(raw, "%", "%%");
+ if (!p)
+ return log_oom();
+ escaped = cescape(p);
+ if (!escaped)
+ return log_oom();
+
+ quoted = strjoin("\"", escaped, "\"");
+ if (!quoted)
+ return log_oom();
+
+ free(exec_split[n]);
+ exec_split[n++] = TAKE_PTR(quoted);
+ }
+ for (; exec_split[n]; n++)
+ exec_split[n] = mfree(exec_split[n]);
+
+ res = strv_join(exec_split, " ");
+ if (!res)
+ return log_oom();
+
+ *ret_exec_start = res;
+ return 0;
+}
+
+static int xdg_autostart_generate_desktop_condition(
+ FILE *f,
+ const char *test_binary,
+ const char *condition) {
+
+ int r;
+
+ /* Generate an ExecCondition for GNOME autostart condition */
+ if (!isempty(condition)) {
+ _cleanup_free_ char *gnome_autostart_condition_path = NULL, *e_autostart_condition = NULL;
+
+ r = find_binary(test_binary, &gnome_autostart_condition_path);
+ if (r < 0) {
+ log_full_errno(r == -ENOENT ? LOG_INFO : LOG_WARNING, r,
+ "%s not found: %m", test_binary);
+ fprintf(f, "# ExecCondition using %s skipped due to missing binary.\n", test_binary);
+ return r;
+ }
+
+ e_autostart_condition = cescape(condition);
+ if (!e_autostart_condition)
+ return log_oom();
+
+ fprintf(f,
+ "ExecCondition=%s --condition \"%s\"\n",
+ gnome_autostart_condition_path,
+ e_autostart_condition);
+ }
+
+ return 0;
+}
+
+int xdg_autostart_service_generate_unit(
+ XdgAutostartService *service,
+ const char *dest) {
+
+ _cleanup_free_ char *path_escaped = NULL, *exec_start = NULL, *unit = NULL;
+ _cleanup_fclose_ FILE *f = NULL;
+ int r;
+
+ assert(service);
+
+ /* Nothing to do for hidden services. */
+ if (service->hidden) {
+ log_info("Not generating service for XDG autostart %s, it is hidden.", service->name);
+ return 0;
+ }
+
+ if (service->systemd_skip) {
+ log_info("Not generating service for XDG autostart %s, should be skipped by generator.", service->name);
+ return 0;
+ }
+
+ /* Nothing to do if type is not Application. */
+ if (!streq_ptr(service->type, "Application")) {
+ log_info("Not generating service for XDG autostart %s, it is hidden.", service->name);
+ return 0;
+ }
+
+ if (!service->exec_string) {
+ log_warning("Not generating service for XDG autostart %s, it is has no Exec= line.", service->name);
+ return 0;
+ }
+
+ /*
+ * The TryExec key cannot be checked properly from the systemd unit,
+ * it is trivial to check using find_binary though.
+ */
+ if (service->try_exec) {
+ r = find_binary(service->try_exec, NULL);
+ if (r < 0) {
+ log_full_errno(r == -ENOENT ? LOG_INFO : LOG_WARNING, r,
+ "Not generating service for XDG autostart %s, could not find TryExec= binary %s: %m",
+ service->name, service->try_exec);
+ return 0;
+ }
+ }
+
+ r = xdg_autostart_format_exec_start(service->exec_string, &exec_start);
+ if (r < 0) {
+ log_warning_errno(r,
+ "Not generating service for XDG autostart %s, error parsing Exec= line: %m",
+ service->name);
+ return 0;
+ }
+
+ if (streq_ptr(service->gnome_autostart_phase, "EarlyInitialization")) {
+ log_info("Not generating service for XDG autostart %s, EarlyInitialization needs to be handled separately.",
+ service->name);
+ return 0;
+ }
+
+ path_escaped = specifier_escape(service->path);
+ if (!path_escaped)
+ return log_oom();
+
+ unit = path_join(dest, service->name);
+ if (!unit)
+ return log_oom();
+
+ f = fopen(unit, "wxe");
+ if (!f)
+ return log_error_errno(errno, "Failed to create unit file %s: %m", unit);
+
+ fprintf(f,
+ "# Automatically generated by systemd-xdg-autostart-generator\n\n"
+ "[Unit]\n"
+ "Documentation=man:systemd-xdg-autostart-generator(8)\n"
+ "SourcePath=%s\n"
+ "PartOf=graphical-session.target\n\n",
+ path_escaped);
+
+ if (service->description) {
+ _cleanup_free_ char *t = NULL;
+
+ t = specifier_escape(service->description);
+ if (!t)
+ return log_oom();
+
+ fprintf(f, "Description=%s\n", t);
+ }
+
+ /* Only start after the session is ready.
+ * XXX: GNOME has an autostart order which we may want to support.
+ * It is not clear how this can be implemented reliably, which
+ * is why it is skipped for now. */
+ fprintf(f,
+ "After=graphical-session.target\n");
+
+ fprintf(f,
+ "\n[Service]\n"
+ "Type=simple\n"
+ "ExecStart=:%s\n"
+ "Restart=no\n"
+ "TimeoutSec=5s\n"
+ "Slice=app.slice\n",
+ exec_start);
+
+ /* Generate an ExecCondition to check $XDG_CURRENT_DESKTOP */
+ if (!strv_isempty(service->only_show_in) || !strv_isempty(service->not_show_in)) {
+ _cleanup_free_ char *only_show_in = NULL, *not_show_in = NULL, *e_only_show_in = NULL, *e_not_show_in = NULL;
+
+ only_show_in = strv_join(service->only_show_in, ":");
+ not_show_in = strv_join(service->not_show_in, ":");
+ if (!only_show_in || !not_show_in)
+ return log_oom();
+
+ e_only_show_in = cescape(only_show_in);
+ e_not_show_in = cescape(not_show_in);
+ if (!e_only_show_in || !e_not_show_in)
+ return log_oom();
+
+ /* Just assume the values are reasonably sane */
+ fprintf(f,
+ "ExecCondition=" ROOTLIBEXECDIR "/systemd-xdg-autostart-condition \"%s\" \"%s\"\n",
+ e_only_show_in,
+ e_not_show_in);
+ }
+
+ r = xdg_autostart_generate_desktop_condition(f,
+ "gnome-systemd-autostart-condition",
+ service->autostart_condition);
+ if (r < 0)
+ return r;
+
+ r = xdg_autostart_generate_desktop_condition(f,
+ "kde-systemd-start-condition",
+ service->kde_autostart_condition);
+ if (r < 0)
+ return r;
+
+ (void) generator_add_symlink(dest, "xdg-desktop-autostart.target", "wants", service->name);
+
+ return 0;
+}
diff --git a/src/xdg-autostart-generator/xdg-autostart-service.h b/src/xdg-autostart-generator/xdg-autostart-service.h
new file mode 100644
index 0000000000..685f97824e
--- /dev/null
+++ b/src/xdg-autostart-generator/xdg-autostart-service.h
@@ -0,0 +1,36 @@
+/* SPDX-License-Identifier: LGPL-2.1+ */
+#pragma once
+
+#include "macro.h"
+
+typedef struct XdgAutostartService {
+ char *name;
+ char *path;
+ char *description; /* Name in XDG desktop file */
+
+ char *type; /* Purely as an assertion check */
+ char *exec_string;
+
+ char **only_show_in;
+ char **not_show_in;
+
+ char *try_exec;
+ char *autostart_condition; /* This is mostly GNOME specific */
+ char *kde_autostart_condition;
+
+ char *gnome_autostart_phase;
+
+ bool hidden;
+ bool systemd_skip;
+
+} XdgAutostartService;
+
+
+XdgAutostartService * xdg_autostart_service_free(XdgAutostartService *s);
+DEFINE_TRIVIAL_CLEANUP_FUNC(XdgAutostartService*, xdg_autostart_service_free);
+
+char *xdg_autostart_service_translate_name(const char *name);
+int xdg_autostart_format_exec_start(const char *exec, char **ret_exec_start);
+
+XdgAutostartService *xdg_autostart_service_parse_desktop(const char *path);
+int xdg_autostart_service_generate_unit(XdgAutostartService *service, const char *dest);
diff --git a/test/fuzz/fuzz-xdg-desktop/full.desktop b/test/fuzz/fuzz-xdg-desktop/full.desktop
new file mode 100644
index 0000000000..e5da36bbab
--- /dev/null
+++ b/test/fuzz/fuzz-xdg-desktop/full.desktop
@@ -0,0 +1,10 @@
+[Desktop Entry]
+Type=Application
+Name=GNOME Settings Daemon's power plugin
+Exec=/usr/bin/sleep %i %f "%F" "--test" ";\\\\!?"
+OnlyShowIn=GNOME;
+NoDisplay=true
+X-GNOME-Autostart-Phase=Initialization
+X-GNOME-Autostart-Notify=true
+X-GNOME-AutoRestart=true
+X-GNOME-HiddenUnderSystemd=true
diff --git a/test/fuzz/fuzz-xdg-desktop/org.gnome.SettingsDaemon.Power.desktop b/test/fuzz/fuzz-xdg-desktop/org.gnome.SettingsDaemon.Power.desktop
new file mode 100644
index 0000000000..9d3e0c5a02
--- /dev/null
+++ b/test/fuzz/fuzz-xdg-desktop/org.gnome.SettingsDaemon.Power.desktop
@@ -0,0 +1,10 @@
+[Desktop Entry]
+Type=Application
+Name=GNOME Settings Daemon's power plugin
+Exec=/usr/libexec/gsd-power
+OnlyShowIn=GNOME;
+NoDisplay=true
+X-GNOME-Autostart-Phase=Initialization
+X-GNOME-Autostart-Notify=true
+X-GNOME-AutoRestart=true
+X-GNOME-HiddenUnderSystemd=true
diff --git a/test/fuzz/fuzz-xdg-desktop/valid.desktop b/test/fuzz/fuzz-xdg-desktop/valid.desktop
new file mode 100644
index 0000000000..20fb5fecb7
--- /dev/null
+++ b/test/fuzz/fuzz-xdg-desktop/valid.desktop
@@ -0,0 +1,12 @@
+Desktop Entry
+Name=
+Exec=
+TryExec=
+Type=
+OnlyShowIn=
+NotShowIn=
+Hidden=
+AutostartCondition=
+X-KDE-autostart-condition=
+X-GNOME-Autostart-Phase=
+X-GNOME-HiddenUnderSystemd=
diff --git a/units/user/meson.build b/units/user/meson.build
index cb8f630b8c..33732e7d59 100644
--- a/units/user/meson.build
+++ b/units/user/meson.build
@@ -20,6 +20,10 @@ units = [
'timers.target',
]
+if conf.get('ENABLE_XDG_AUTOSTART') == 1
+ units += [ 'xdg-desktop-autostart.target', ]
+endif
+
foreach file : units
install_data(file,
install_dir : userunitdir)
diff --git a/units/user/xdg-desktop-autostart.target b/units/user/xdg-desktop-autostart.target
new file mode 100644
index 0000000000..22df5a35d3
--- /dev/null
+++ b/units/user/xdg-desktop-autostart.target
@@ -0,0 +1,14 @@
+# SPDX-License-Identifier: LGPL-2.1+
+#
+# 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.
+
+[Unit]
+Description=Startup of XDG autostart applications
+Documentation=man:systemd.special(7)
+RefuseManualStart=yes
+StopWhenUnneeded=yes