]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/xdg-autostart-generator/xdg-autostart-service.c
tree-wide: replace strv_split_full() with strv_split_extract() everywhere
[thirdparty/systemd.git] / src / xdg-autostart-generator / xdg-autostart-service.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <stdio.h>
5 #include <unistd.h>
6
7 #include "xdg-autostart-service.h"
8
9 #include "conf-parser.h"
10 #include "escape.h"
11 #include "unit-name.h"
12 #include "path-util.h"
13 #include "fd-util.h"
14 #include "generator.h"
15 #include "log.h"
16 #include "specifier.h"
17 #include "string-util.h"
18 #include "nulstr-util.h"
19 #include "strv.h"
20
21 XdgAutostartService* xdg_autostart_service_free(XdgAutostartService *s) {
22 if (!s)
23 return NULL;
24
25 free(s->name);
26 free(s->path);
27 free(s->description);
28
29 free(s->type);
30 free(s->exec_string);
31
32 strv_free(s->only_show_in);
33 strv_free(s->not_show_in);
34
35 free(s->try_exec);
36 free(s->autostart_condition);
37 free(s->kde_autostart_condition);
38
39 free(s->gnome_autostart_phase);
40
41 return mfree(s);
42 }
43
44 char *xdg_autostart_service_translate_name(const char *name) {
45 _cleanup_free_ char *c = NULL, *escaped = NULL;
46 char *res;
47
48 c = strdup(name);
49 if (!c)
50 return NULL;
51
52 res = endswith(c, ".desktop");
53 if (res)
54 *res = '\0';
55
56 escaped = unit_name_escape(c);
57 if (!escaped)
58 return NULL;
59
60 return strjoin("app-", escaped, "-autostart.service");
61 }
62
63 static int xdg_config_parse_bool(
64 const char *unit,
65 const char *filename,
66 unsigned line,
67 const char *section,
68 unsigned section_line,
69 const char *lvalue,
70 int ltype,
71 const char *rvalue,
72 void *data,
73 void *userdata) {
74
75 bool *b = data;
76
77 assert(filename);
78 assert(lvalue);
79 assert(rvalue);
80 assert(data);
81
82 if (streq(rvalue, "true"))
83 *b = true;
84 else if (streq(rvalue, "false"))
85 *b = false;
86 else
87 return log_syntax(unit, LOG_ERR, filename, line, SYNTHETIC_ERRNO(EINVAL), "Invalid value for boolean: %s", rvalue);
88
89 return 0;
90 }
91
92 /* Unescapes the string in-place, returns non-zero status on error. */
93 static int xdg_unescape_string(
94 const char *unit,
95 const char *filename,
96 int line,
97 char *str) {
98
99 char *in;
100 char *out;
101
102 assert(str);
103
104 in = out = str;
105
106 for (; *in; in++, out++) {
107 if (*in == '\\') {
108 /* Move forward, and ensure it is a valid escape. */
109 in++;
110
111 switch (*in) {
112 case 's':
113 *out = ' ';
114 break;
115 case 'n':
116 *out = '\n';
117 break;
118 case 't':
119 *out = '\t';
120 break;
121 case 'r':
122 *out = '\r';
123 break;
124 case '\\':
125 *out = '\\';
126 break;
127 case ';':
128 /* Technically only permitted for strv. */
129 *out = ';';
130 break;
131 default:
132 return log_syntax(unit, LOG_ERR, filename, line, SYNTHETIC_ERRNO(EINVAL), "Undefined escape sequence \\%c.", *in);
133 }
134
135 continue;
136 }
137
138 *out = *in;
139 }
140 *out = '\0';
141
142 return 0;
143 }
144
145 /* Note: We do not bother with unescaping the strings, hence the _raw postfix. */
146 static int xdg_config_parse_string(
147 const char *unit,
148 const char *filename,
149 unsigned line,
150 const char *section,
151 unsigned section_line,
152 const char *lvalue,
153 int ltype,
154 const char *rvalue,
155 void *data,
156 void *userdata) {
157
158 _cleanup_free_ char *res = NULL;
159 char **out = data;
160 int r;
161
162 assert(filename);
163 assert(lvalue);
164 assert(rvalue);
165 assert(data);
166
167 /* XDG does not allow duplicate definitions. */
168 if (*out) {
169 log_syntax(unit, LOG_ERR, filename, line, 0, "Key %s was defined multiple times, ignoring.", lvalue);
170 return 0;
171 }
172
173 res = strdup(rvalue);
174 if (!res)
175 return log_oom();
176
177 r = xdg_unescape_string(unit, filename, line, res);
178 if (r < 0)
179 return r;
180
181 *out = TAKE_PTR(res);
182 return 0;
183 }
184
185 static int strv_strndup_unescape_and_push(
186 const char *unit,
187 const char *filename,
188 unsigned line,
189 char ***sv,
190 size_t *n_allocated,
191 size_t *n,
192 const char *start,
193 const char *end) {
194
195 if (end == start)
196 return 0;
197
198 _cleanup_free_ char *copy = NULL;
199 int r;
200
201 copy = strndup(start, end - start);
202 if (!copy)
203 return log_oom();
204
205 r = xdg_unescape_string(unit, filename, line, copy);
206 if (r < 0)
207 return r;
208
209 if (!greedy_realloc((void**) sv, n_allocated, *n + 2, sizeof(char*))) /* One extra for NULL */
210 return log_oom();
211
212 (*sv)[*n] = TAKE_PTR(copy);
213 (*sv)[*n + 1] = NULL;
214 (*n)++;
215
216 return 0;
217 }
218
219 static int xdg_config_parse_strv(
220 const char *unit,
221 const char *filename,
222 unsigned line,
223 const char *section,
224 unsigned section_line,
225 const char *lvalue,
226 int ltype,
227 const char *rvalue,
228 void *data,
229 void *userdata) {
230
231 char ***ret_sv = data;
232 int r;
233
234 assert(filename);
235 assert(lvalue);
236 assert(rvalue);
237 assert(data);
238
239 /* XDG does not allow duplicate definitions. */
240 if (*ret_sv) {
241 log_syntax(unit, LOG_ERR, filename, line, 0, "Key %s was already defined, ignoring.", lvalue);
242 return 0;
243 }
244
245 size_t n = 0, n_allocated = 0;
246 _cleanup_strv_free_ char **sv = NULL;
247
248 if (!GREEDY_REALLOC0(sv, n_allocated, 1))
249 return log_oom();
250
251 /* We cannot use strv_split because it does not handle escaping correctly. */
252 const char *start = rvalue, *end;
253
254 for (end = start; *end; end++) {
255 if (*end == '\\') {
256 /* Move forward, and ensure it is a valid escape. */
257 end++;
258 if (!strchr("sntr\\;", *end)) {
259 log_syntax(unit, LOG_ERR, filename, line, 0, "Undefined escape sequence \\%c.", *end);
260 return 0;
261 }
262 continue;
263 }
264
265 if (*end == ';') {
266 r = strv_strndup_unescape_and_push(unit, filename, line,
267 &sv, &n_allocated, &n,
268 start, end);
269 if (r < 0)
270 return r;
271
272 start = end + 1;
273 }
274 }
275
276 /* Handle the trailing entry after the last separator */
277 r = strv_strndup_unescape_and_push(unit, filename, line,
278 &sv, &n_allocated, &n,
279 start, end);
280 if (r < 0)
281 return r;
282
283 *ret_sv = TAKE_PTR(sv);
284 return 0;
285 }
286
287 static int xdg_config_item_table_lookup(
288 const void *table,
289 const char *section,
290 const char *lvalue,
291 ConfigParserCallback *func,
292 int *ltype,
293 void **data,
294 void *userdata) {
295
296 assert(lvalue);
297
298 /* Ignore any keys with [] as those are translations. */
299 if (strchr(lvalue, '[')) {
300 *func = NULL;
301 *ltype = 0;
302 *data = NULL;
303 return 1;
304 }
305
306 return config_item_table_lookup(table, section, lvalue, func, ltype, data, userdata);
307 }
308
309 XdgAutostartService *xdg_autostart_service_parse_desktop(const char *path) {
310 _cleanup_(xdg_autostart_service_freep) XdgAutostartService *service = NULL;
311 int r;
312
313 service = new0(XdgAutostartService, 1);
314 if (!service)
315 return NULL;
316
317 service->path = strdup(path);
318 if (!service->path)
319 return NULL;
320
321 const ConfigTableItem items[] = {
322 { "Desktop Entry", "Name", xdg_config_parse_string, 0, &service->description},
323 { "Desktop Entry", "Exec", xdg_config_parse_string, 0, &service->exec_string},
324 { "Desktop Entry", "TryExec", xdg_config_parse_string, 0, &service->try_exec},
325 { "Desktop Entry", "Type", xdg_config_parse_string, 0, &service->type},
326 { "Desktop Entry", "OnlyShowIn", xdg_config_parse_strv, 0, &service->only_show_in},
327 { "Desktop Entry", "NotShowIn", xdg_config_parse_strv, 0, &service->not_show_in},
328 { "Desktop Entry", "Hidden", xdg_config_parse_bool, 0, &service->hidden},
329 { "Desktop Entry", "AutostartCondition", xdg_config_parse_string, 0, &service->autostart_condition},
330 { "Desktop Entry", "X-KDE-autostart-condition", xdg_config_parse_string, 0, &service->kde_autostart_condition},
331 { "Desktop Entry", "X-GNOME-Autostart-Phase", xdg_config_parse_string, 0, &service->gnome_autostart_phase},
332 { "Desktop Entry", "X-systemd-skip", xdg_config_parse_bool, 0, &service->systemd_skip},
333
334 /* Common entries that we do not use currently. */
335 { "Desktop Entry", "Categories", NULL, 0, NULL},
336 { "Desktop Entry", "Comment", NULL, 0, NULL},
337 { "Desktop Entry", "Encoding", NULL, 0, NULL},
338 { "Desktop Entry", "GenericName", NULL, 0, NULL},
339 { "Desktop Entry", "Icon", NULL, 0, NULL},
340 { "Desktop Entry", "Keywords", NULL, 0, NULL},
341 { "Desktop Entry", "NoDisplay", NULL, 0, NULL},
342 { "Desktop Entry", "StartupNotify", NULL, 0, NULL},
343 { "Desktop Entry", "Terminal", NULL, 0, NULL},
344 { "Desktop Entry", "Version", NULL, 0, NULL},
345 {}
346 };
347
348 r = config_parse(NULL, service->path, NULL,
349 "Desktop Entry\0",
350 xdg_config_item_table_lookup, items,
351 CONFIG_PARSE_WARN, service,
352 NULL);
353 /* If parsing failed, only hide the file so it will still mask others. */
354 if (r < 0) {
355 log_warning_errno(r, "Failed to parse %s, ignoring it", service->path);
356 service->hidden = true;
357 }
358
359 return TAKE_PTR(service);
360 }
361
362 int xdg_autostart_format_exec_start(
363 const char *exec,
364 char **ret_exec_start) {
365
366 _cleanup_strv_free_ char **exec_split = NULL;
367 char *res;
368 size_t n, i;
369 bool first_arg;
370 int r;
371
372 /*
373 * Unfortunately, there is a mismatch between systemd's idea of $PATH
374 * and XDGs. i.e. we need to ensure that we have an absolute path to
375 * support cases where $PATH has been modified from the default set.
376 *
377 * Note that this is only needed for development environments though;
378 * so while it is important, this should have no effect in production
379 * environments.
380 *
381 * To be compliant with the XDG specification, we also need to strip
382 * certain parameters and such. Doing so properly makes parsing the
383 * command line unavoidable.
384 *
385 * NOTE: Technically, XDG only specifies " as quotes, while this also
386 * accepts '.
387 */
388 r = strv_split_extract(&exec_split, exec, NULL, EXTRACT_UNQUOTE | EXTRACT_RELAX);
389 if (r < 0)
390 return r;
391
392 if (strv_isempty(exec_split))
393 return log_warning_errno(SYNTHETIC_ERRNO(EINVAL), "Exec line is empty");
394
395 first_arg = true;
396 for (i = n = 0; exec_split[i]; i++) {
397 _cleanup_free_ char *c = NULL, *raw = NULL, *p = NULL, *escaped = NULL, *quoted = NULL;
398
399 r = cunescape(exec_split[i], 0, &c);
400 if (r < 0)
401 return log_debug_errno(r, "Failed to unescape '%s': %m", exec_split[i]);
402
403 if (first_arg) {
404 _cleanup_free_ char *executable = NULL;
405
406 /* This is the executable, find it in $PATH */
407 first_arg = false;
408 r = find_binary(c, &executable);
409 if (r < 0)
410 return log_info_errno(r, "Exec binary '%s' does not exist: %m", c);
411
412 escaped = cescape(executable);
413 if (!escaped)
414 return log_oom();
415
416 free(exec_split[n]);
417 exec_split[n++] = TAKE_PTR(escaped);
418 continue;
419 }
420
421 /*
422 * Remove any standardised XDG fields; we assume they never appear as
423 * part of another argument as that just does not make any sense as
424 * they can be empty (GLib will e.g. turn "%f" into an empty argument).
425 * Other implementations may handle this differently.
426 */
427 if (STR_IN_SET(c,
428 "%f", "%F",
429 "%u", "%U",
430 "%d", "%D",
431 "%n", "%N",
432 "%i", /* Location of icon, could be implemented. */
433 "%c", /* Translated application name, could be implemented. */
434 "%k", /* Location of desktop file, could be implemented. */
435 "%v",
436 "%m"
437 ))
438 continue;
439
440 /*
441 * %% -> % and then % -> %% means that we correctly quote any %
442 * and also quote any left over (and invalid) % specifier from
443 * the desktop file.
444 */
445 raw = strreplace(c, "%%", "%");
446 if (!raw)
447 return log_oom();
448 p = strreplace(raw, "%", "%%");
449 if (!p)
450 return log_oom();
451 escaped = cescape(p);
452 if (!escaped)
453 return log_oom();
454
455 quoted = strjoin("\"", escaped, "\"");
456 if (!quoted)
457 return log_oom();
458
459 free(exec_split[n]);
460 exec_split[n++] = TAKE_PTR(quoted);
461 }
462 for (; exec_split[n]; n++)
463 exec_split[n] = mfree(exec_split[n]);
464
465 res = strv_join(exec_split, " ");
466 if (!res)
467 return log_oom();
468
469 *ret_exec_start = res;
470 return 0;
471 }
472
473 static int xdg_autostart_generate_desktop_condition(
474 FILE *f,
475 const char *test_binary,
476 const char *condition) {
477
478 int r;
479
480 /* Generate an ExecCondition for GNOME autostart condition */
481 if (!isempty(condition)) {
482 _cleanup_free_ char *gnome_autostart_condition_path = NULL, *e_autostart_condition = NULL;
483
484 r = find_binary(test_binary, &gnome_autostart_condition_path);
485 if (r < 0) {
486 log_full_errno(r == -ENOENT ? LOG_INFO : LOG_WARNING, r,
487 "%s not found: %m", test_binary);
488 fprintf(f, "# ExecCondition using %s skipped due to missing binary.\n", test_binary);
489 return r;
490 }
491
492 e_autostart_condition = cescape(condition);
493 if (!e_autostart_condition)
494 return log_oom();
495
496 fprintf(f,
497 "ExecCondition=%s --condition \"%s\"\n",
498 gnome_autostart_condition_path,
499 e_autostart_condition);
500 }
501
502 return 0;
503 }
504
505 int xdg_autostart_service_generate_unit(
506 XdgAutostartService *service,
507 const char *dest) {
508
509 _cleanup_free_ char *path_escaped = NULL, *exec_start = NULL, *unit = NULL;
510 _cleanup_fclose_ FILE *f = NULL;
511 int r;
512
513 assert(service);
514
515 /* Nothing to do for hidden services. */
516 if (service->hidden) {
517 log_info("Not generating service for XDG autostart %s, it is hidden.", service->name);
518 return 0;
519 }
520
521 if (service->systemd_skip) {
522 log_info("Not generating service for XDG autostart %s, should be skipped by generator.", service->name);
523 return 0;
524 }
525
526 /* Nothing to do if type is not Application. */
527 if (!streq_ptr(service->type, "Application")) {
528 log_info("Not generating service for XDG autostart %s, only Type=Application is supported.", service->name);
529 return 0;
530 }
531
532 if (!service->exec_string) {
533 log_warning("Not generating service for XDG autostart %s, it is has no Exec= line.", service->name);
534 return 0;
535 }
536
537 /*
538 * The TryExec key cannot be checked properly from the systemd unit,
539 * it is trivial to check using find_binary though.
540 */
541 if (service->try_exec) {
542 r = find_binary(service->try_exec, NULL);
543 if (r < 0) {
544 log_full_errno(r == -ENOENT ? LOG_INFO : LOG_WARNING, r,
545 "Not generating service for XDG autostart %s, could not find TryExec= binary %s: %m",
546 service->name, service->try_exec);
547 return 0;
548 }
549 }
550
551 r = xdg_autostart_format_exec_start(service->exec_string, &exec_start);
552 if (r < 0) {
553 log_warning_errno(r,
554 "Not generating service for XDG autostart %s, error parsing Exec= line: %m",
555 service->name);
556 return 0;
557 }
558
559 if (service->gnome_autostart_phase) {
560 /* There is no explicit value for the "Application" phase. */
561 log_info("Not generating service for XDG autostart %s, startup phases are not supported.",
562 service->name);
563 return 0;
564 }
565
566 path_escaped = specifier_escape(service->path);
567 if (!path_escaped)
568 return log_oom();
569
570 unit = path_join(dest, service->name);
571 if (!unit)
572 return log_oom();
573
574 f = fopen(unit, "wxe");
575 if (!f)
576 return log_error_errno(errno, "Failed to create unit file %s: %m", unit);
577
578 fprintf(f,
579 "# Automatically generated by systemd-xdg-autostart-generator\n\n"
580 "[Unit]\n"
581 "Documentation=man:systemd-xdg-autostart-generator(8)\n"
582 "SourcePath=%s\n"
583 "PartOf=graphical-session.target\n\n",
584 path_escaped);
585
586 if (service->description) {
587 _cleanup_free_ char *t = NULL;
588
589 t = specifier_escape(service->description);
590 if (!t)
591 return log_oom();
592
593 fprintf(f, "Description=%s\n", t);
594 }
595
596 /* Only start after the session is ready. */
597 fprintf(f,
598 "After=graphical-session.target\n");
599
600 fprintf(f,
601 "\n[Service]\n"
602 "Type=simple\n"
603 "ExecStart=:%s\n"
604 "Restart=no\n"
605 "TimeoutSec=5s\n"
606 "Slice=app.slice\n",
607 exec_start);
608
609 /* Generate an ExecCondition to check $XDG_CURRENT_DESKTOP */
610 if (!strv_isempty(service->only_show_in) || !strv_isempty(service->not_show_in)) {
611 _cleanup_free_ char *only_show_in = NULL, *not_show_in = NULL, *e_only_show_in = NULL, *e_not_show_in = NULL;
612
613 only_show_in = strv_join(service->only_show_in, ":");
614 not_show_in = strv_join(service->not_show_in, ":");
615 if (!only_show_in || !not_show_in)
616 return log_oom();
617
618 e_only_show_in = cescape(only_show_in);
619 e_not_show_in = cescape(not_show_in);
620 if (!e_only_show_in || !e_not_show_in)
621 return log_oom();
622
623 /* Just assume the values are reasonably sane */
624 fprintf(f,
625 "ExecCondition=" ROOTLIBEXECDIR "/systemd-xdg-autostart-condition \"%s\" \"%s\"\n",
626 e_only_show_in,
627 e_not_show_in);
628 }
629
630 r = xdg_autostart_generate_desktop_condition(f,
631 "gnome-systemd-autostart-condition",
632 service->autostart_condition);
633 if (r < 0)
634 return r;
635
636 r = xdg_autostart_generate_desktop_condition(f,
637 "kde-systemd-start-condition",
638 service->kde_autostart_condition);
639 if (r < 0)
640 return r;
641
642 (void) generator_add_symlink(dest, "xdg-desktop-autostart.target", "wants", service->name);
643
644 return 0;
645 }